This repository has been archived by the owner on May 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 70
/
bankapi
executable file
·466 lines (372 loc) · 15.5 KB
/
bankapi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import json
import psycopg2
import psycopg2.extras
import re
import httplib
import pprint
import socket
import getopt
import subprocess
import os
pg_connect_str = "dbname=bankapi"
pg_conn = None
pgp_keyserver = "keys.gnupg.net"
verbose = False
def bail(error=None, help=False):
global pgp_keyserver
if error is not None:
print "Error: %s" % (error.rstrip())
if error is None or help == True:
print "Usage: %s [-d dbname] <command> <args>" % (sys.argv[0])
print ""
print "Commands:"
print " send frombank tobank messagetype [ filename ... ]"
print " list"
print " read messageid"
print " add keyid"
print ""
print "Arguments:"
print " -v Be more verbose about what is being done"
print " -d dbname Name of database to use locally (default: bankapi)"
print " -k server Use this keyserver instead of the default when adding a bank"
print " (default: %s)" % (pgp_keyserver)
sys.exit(1)
def debug(s):
global verbose
if verbose == True:
print " + " + s
def process_commandline(command, argv):
if command == 'send':
# We need at least one sender, once receiver, one filetype
if len(argv) < 3:
bail(error='Insufficient arguments')
frombank = argv.pop(0)
tobank = argv.pop(0)
messagetype = argv.pop(0)
if len(argv):
files = argv
else:
files = ['-']
for filename in files:
send_file(frombank, tobank, messagetype, filename)
elif command == 'list':
list_messages()
elif command == 'read':
if len(argv) != 1:
bail()
read_message(argv[0])
elif command == 'add':
if len(argv) != 1:
bail()
add_bank_key(argv[0])
else:
bail('Invalid command "%s"' % (command), help=True)
def send_file(from_bank, to_bank, messagetype, filename):
global pg_conn
fh = None
if filename == '-':
fh = sys.stdin
filename = '<stdin>'
else:
try:
fh = open(filename, 'r')
except IOError as e:
bail(error='Could not open file %s: %s' % (filename, e))
messagetext = None
try:
messagetext = fh.read()
except IOError as e:
bail(error='Failed to read from file %s: %s' % (filename, e))
if messagetext is None or len(messagetext) == 0:
bail(error='No message text in file %s' % (filename))
cur = pg_conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
messagehub_host, messagehub_port, messagehub_proto, messagehub_path = None, None, None, None
try:
cur.execute("SELECT Protocol, Host, Port, Path FROM Get_Bank(%s)",
[to_bank]);
sqldata = cur.fetchone()
messagehub_proto = sqldata['protocol']
messagehub_host = sqldata['host']
messagehub_port = sqldata['port']
messagehub_path = sqldata['path']
pg_conn.commit()
except (psycopg2.InternalError, psycopg2.ProgrammingError) as e:
pg_conn.rollback()
bail(error=e.pgerror)
client = None
if messagehub_proto == 'https':
client = httplib.HTTPSConnection(messagehub_host, messagehub_port)
else:
client = httplib.HTTPConnection(messagehub_host, messagehub_port)
messagehub_str = url_str(messagehub_proto, messagehub_host, messagehub_port, messagehub_path)
print "Sending message %s -> %s using %s ... " % (from_bank, to_bank, messagehub_str),
cur = pg_conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
messageid = None
ciphertext = None
try:
cur.execute("""SELECT CipherText FROM Get_Message(Create_Message(
_PlainText := %s,
_MessageType := %s,
_FromBankID := %s,
_ToBankID := %s
))""",
[messagetext, messagetype, from_bank, to_bank]);
sqldata = cur.fetchone()
ciphertext = sqldata['ciphertext']
pg_conn.commit()
except (psycopg2.InternalError, psycopg2.ProgrammingError) as e:
pg_conn.rollback()
bail(error=e.pgerror)
response = None
request = ciphertext
headers = {
"Content-Type": "text/plain"
}
try:
client.request('POST', messagehub_path, request, headers)
response = client.getresponse()
except (socket.gaierror, socket.error) as e:
bail(error="Could not connect to %s: %s" % (messagehub_str, str(e)))
print " %s %s" % (response.status, response.reason)
debug('Ciphertext sent: %s' % (ciphertext))
if response.status == 200:
response_body = response.read()
debug('Peer responded with: %s' % (response_body))
try:
print " Saving delivery recieipt"
cur.execute("""SELECT FileID, FromBankID, ToBankID FROM Decode_Delivery_Receipt(
_DeliveryReceipt := %s
)""",
[response_body])
sqldata = cur.fetchone()
print " Message delivered to %s (from %s) %s" % (sqldata['tobankid'], sqldata['frombankid'], sqldata['fileid'])
pg_conn.commit()
except (psycopg2.InternalError, psycopg2.ProgrammingError) as e:
pg_conn.rollback()
bail(error="Failed to save delivery receipt: error=%s, code=%s" % (e.pgerror, e.pgcode))
else:
bail(error="Failure")
def list_messages():
global pg_conn
try:
cur = pg_conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute("SELECT DateStamp, MessageID, MessageType, FromBankID, ToBankID FROM List_Messages()")
print "{datestamp:19} {messageid:10} {messagetype:30.30}{frombankid:17.17}{tobankid:17.17}".format(datestamp='Date', messageid='ID', messagetype='Type', frombankid='From bank', tobankid='To bank')
for sqldata in cur:
print "{datestamp:%Y-%m-%d %H:%M:%S} {messageid:10} {messagetype:30.30}{frombankid:17.17}{tobankid:17.17}".format(**dict(sqldata))
print " %s messages" % (cur.rowcount)
pg_conn.commit()
except (psycopg2.InternalError, psycopg2.ProgrammingError) as e:
pg_conn.rollback()
bail(error=e.pgerror)
def read_message(messageid):
global pg_conn
try:
cur = pg_conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute("SELECT PlainText FROM Read_Message(%s)",
[messageid])
sqldata = cur.fetchone()
print sqldata['plaintext'],
pg_conn.commit()
except (psycopg2.InternalError, psycopg2.ProgrammingError) as e:
pg_conn.rollback()
if e.pgcode == 'P0002':
bail('No such message')
elif e.pgcode == 'P0003':
bail('Message ID amibgous')
bail(error="Read failed with error %s, code %s" % (e.pgerror, e.pgcode))
def gpg_list_key_data(keyid, desc, secret=None):
try:
fhnull = open(os.devnull, 'w')
if secret is not None:
key_list = subprocess.check_output(['/usr/bin/gpg', '--with-fingerprint', '--with-colons', '--list-secret-keys', keyid], stderr=fhnull)
else:
key_list = subprocess.check_output(['/usr/bin/gpg', '--with-fingerprint', '--with-colons', '--list-keys', keyid], stderr=fhnull)
except subprocess.CalledProcessError:
return None
key_lines = key_list.split('\n')
data = {}
for line in key_lines:
fields = line.split(':')
if fields[0] == 'pub' or fields[0] == 'sec':
try:
keyid = fields[4]
bankid = fields[9][:(fields[9].index(' '))]
data_str = unescape_gpg_comment(fields[9][(fields[9].index('(') + 1):(fields[9].rindex(')'))])
except ValueError as e:
bail(error="Failed to parse description in %s key (%s)" % (fields[0], fields[9]))
try:
commentdata = json.loads(data_str)
except ValueError as e:
bail(error="Invalid JSON description in %s key (%s): %s" % (fields[0], data_str, str(e)))
data[fields[0]] = {
"keyid": keyid,
"bankid": bankid,
"comment": commentdata
}
elif fields[0] == 'fpr':
data[fields[0]] = fields[9]
elif fields[0] == 'sub':
data[fields[0]] = {
"keyid": fields[4]
}
return data
def gpg_export_key_data(keyid, desc, secret=None):
try:
fhnull = open(os.devnull, 'w')
if secret is not None:
key = subprocess.check_output(['/usr/bin/gpg', '--armor', '--export-secret-keys', keyid], stderr=fhnull)
else:
key = subprocess.check_output(['/usr/bin/gpg', '--armor', '--export', keyid], stderr=fhnull)
return key
except subprocess.CalledProcessErrror:
bail(error="Could not export %s key %s" % (desc, keyid))
def fpr_str(fpr):
return ' '.join([fpr[i:i+4] for i in range(0, len(fpr), 4)])
def add_bank_key(bankid):
global pgp_keyserver
global pg_conn
try:
cur = pg_conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute('SELECT 1 AS hasbank FROM Banks WHERE BankID = %s', [bankid])
sqldata = cur.fetchone()
pg_conn.commit()
if cur.rowcount > 0:
bail(error='Bank %s already exists' % (bankid))
except (psycopg2.InternalError, psycopg2.ProgrammingError) as e:
pg_conn.rollback()
bail(error="Querying configured banks failes with error %s, code %s" % (e.pgerror, e.pgcode))
use_keyid = None
has_searched = False
while use_keyid is None:
key_list = None
try:
fhnull = open(os.devnull, 'w')
key_list = subprocess.check_output(['/usr/bin/gpg', '--list-keys', bankid], stderr=fhnull)
except subprocess.CalledProcessError:
pass
search_keyserver = True
if key_list is not None:
print "There are local keys matching search for %s:" % (bankid)
print ""
print key_list
if has_searched:
print "Enter key id of key to use, blank to abort:"
else:
print "Enter key id of key to use, blank to search keyserver:"
use_keyid = sys.stdin.readline().rstrip()
if use_keyid == '':
use_keyid = None
if use_keyid is not None:
search_keyserver = False
if use_keyid is None and has_searched:
break
if search_keyserver:
has_searched = True
subprocess.call(['/usr/bin/gpg', '--keyserver', pgp_keyserver, '--search-keys',bankid])
if use_keyid is None:
bail(error='No key for import')
pubkey = gpg_list_key_data(use_keyid, "Public key")
if pubkey is None:
bail(error='Could not find public key information for bank %s' % (bankid))
if pubkey.get('pub') is None:
bail(error='Found public key for %s, however failed to extract information from gpg regarding the key' % (bankid))
if (pubkey['pub']['comment'].get('protocol') is None or
pubkey['pub']['comment'].get('host') is None or
pubkey['pub']['comment'].get('port') is None or
pubkey['pub']['comment'].get('path') is None):
bail(error="Found public key for %s (key %s) and it privides a valid JSON in the comment, but does not provide values for protocol, host, port and path" % (bankid, pubkey['pub']['keyid']))
print "Found publickey %s for %s with fingerprint %s" % (use_keyid, bankid, fpr_str(pubkey['fpr']))
print ""
print "Use this key (y/N)? ",
if sys.stdin.readline().rstrip() != 'y':
bail(error='Aborting')
pubkey_armor = gpg_export_key_data(pubkey['pub']['keyid'], "Public key for %s" % (bankid))
print " - Registering bank %s with pubkey %s, subkey %s using %s" % (bankid, pubkey['pub']['keyid'], pubkey['sub']['keyid'], url_str(pubkey['pub']['comment']['protocol'],
pubkey['pub']['comment']['host'], pubkey['pub']['comment']['port'], pubkey['pub']['comment']['path']))
seckey_armor = None
seckey = gpg_list_key_data(use_keyid, "Secret key", secret=True)
if seckey is not None:
if seckey.get('sec') is None:
bail(error='Found secret key for %s (key %s), however failed to extract information from gpg regarding the key')
if pubkey['fpr'] != seckey['fpr']:
bail(error='Found secret key for %s (key %s), however the fingerprint for this key does not match the fingerprint for the public key (%s != %s)' % (fpr_str(pubkey['fpr']), fpr_str(seckey['fpr'])))
seckey_armor = gpg_export_key_data(seckey['sec']['keyid'], "Secret key for %s" % (bankid), True)
print " - Found matching secret key for bank %s, adding it" % (bankid)
try:
cur = pg_conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute("""SELECT Register_Bank(
_BankID := %s,
_Protocol := %s,
_Host := %s,
_Port := %s,
_Path := %s)""",
[bankid, pubkey['pub']['comment']['protocol'], pubkey['pub']['comment']['host'], pubkey['pub']['comment']['port'], pubkey['pub']['comment']['path']])
sqldata = cur.fetchone()
cur = pg_conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute("""SELECT Register_Public_Keyring(
_BankID := %s,
_PublicKeyring := %s)""",
[bankid, pubkey_armor])
sqldata = cur.fetchone()
if seckey_armor is not None:
cur = pg_conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute("""SELECT Register_Secret_Keyring(
_BankID := %s,
_SecretKeyring := %s)""",
[bankid, seckey_armor])
sqldata = cur.fetchone()
pg_conn.commit()
except (psycopg2.InternalError, psycopg2.ProgrammingError) as e:
pg_conn.rollback()
bail(error="Register bank failed with error %s, code %s" % (e.pgerror, e.pgcode))
def url_str(protocol, host, port, path=None):
expected_port = 80
if protocol == 'https':
expected_port = 443
url = "%s://%s" % (protocol, host)
if port != expected_port:
url = url + ':%i' % (port)
if path is not None:
url = url + path
return url
def unescape_gpg_comment(comment):
if comment is None:
return None
n_comment = ''
ndx = comment.find('\\x')
while ndx > -1:
hexstr = None
if ndx > 0:
n_comment = n_comment + comment[:ndx]
hexstr = comment[(ndx+2):(ndx+4)]
comment = comment[(ndx+4):]
n_comment = n_comment + chr(int(hexstr, 16))
ndx = comment.find('\\x')
return n_comment + comment
if len(sys.argv) < 2:
bail(error='No command given', help=True)
command = sys.argv.pop(1)
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:?hv')
for o, a in opts:
if o == '-d':
pg_connect_str = "dbname=%s" % (a)
elif o == '-v':
verbose = True
elif o == '-h' or o == '-?':
bail()
else:
bail(error="Bad argument %s" % (o), help=True)
except getopt.GetoptError as e:
bail(error=str(e))
try:
debug('Connecting to database using %s" % (pg_connect_str)')
pg_conn = psycopg2.connect(pg_connect_str)
except psycopg2.OperationalError as e:
bail(error='Failed to connect to database: %s' % (e))
process_commandline(command, args)
sys.exit(0)