-
Notifications
You must be signed in to change notification settings - Fork 10
/
bitmessage-gateway.py
executable file
·923 lines (701 loc) · 27.6 KB
/
bitmessage-gateway.py
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
#!/usr/bin/python
## imports
import os
import re
import time
import datetime
import argparse
import logging
import sys
import threading
import signal
import xmlrpclib
import json
import smtplib
import base64
import email
import urllib
import urllib2
import gnupg
import html2text
from BeautifulSoup import BeautifulSoup
from email.parser import Parser
from email.header import decode_header
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from cStringIO import StringIO
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from email import Charset
from email.generator import Generator
## globals
## system configuration details
config = {
'domain_name' : 'godark.ca',
'mail_folder' : '/home/bitmessage/MailDir/new/',
'log_filename' : '/var/log/bitmessage-gateway.log',
'process_interval' : 10,
'receiving_address_label' : 'goDark Generic Receive Address',
'sending_address_label' : 'goDark Generic Sender Address',
'registration_address_label' : 'goDark Registration Address',
'deregistration_address_label' : 'goDark Deregistration Address',
'broadcast_address_bitmesage' : 'BM-2cWtQgHwgDbohgi1wVQsjLJy8TdgEwqA63',
'bug_report_address_bitmessage' : 'BM-2cVFZippLaTJeH9n5WuKSXCGYs6onwNmr8',
'bug_report_address_email' : '[email protected]',
'debug' : True,
'respond_to_invalid' : True
}
## API connection information
api = {
'conn' : '',
'username' : 'bmapi',
'password' : '',
'host' : '127.0.0.1',
'port' : '8442'
}
## list of usernames to explicitly ban
banned_usernames = {
'bitmessage' : True,
'register' : True,
'admin' : True,
'administrator' : True,
'mailer' : True,
'mailer-daemon' : True,
'postmaster' : True,
'adm' : True,
'mail' : True,
'news': True,
'operator' : True,
'ftp' : True,
'root' : True,
'dovecot' : True,
'exim' : True,
'post' : True,
'mailnull' : True,
'system' : True,
'manager' : True,
'abuse' : True,
'newsadm' : True,
'newsadmin' : True,
'webmaster' : True,
'security' : True,
'hostmaster' : True,
'info' : True,
'marketing' : True,
'sales' : True,
'support' : True,
'bug' : True,
'bugs' : True,
'register' : True,
'deregister' : True,
'registration' : True,
'deregistration' : True
}
## supported PGP keyservers
key_servers = {
'sks-keyservers' : {
'url' : 'https://hkps.pool.sks-keyservers.net',
'begin' : '/pks/lookup?search=',
'end' : '&op=index&exact=on',
},
'mit': {
'url' : 'https://pgp.mit.edu',
'begin' : '/pks/lookup?search=',
'end' : '&op=index&exact=on'
},
'ubuntu': {
'url' : 'http://keyserver.ubuntu.com',
'begin' : '/pks/lookup?search=',
'end' : '&op=index&exact=on'
},
}
## GPG key cache
gpg = gnupg.GPG(gnupghome='/home/bitmessage/GPG-Keys')
## setup logging
if config['debug']:
logging.basicConfig(filename=config['log_filename'],level=logging.DEBUG, format='%(asctime)s %(levelname)s: %(message)s')
else:
logging.basicConfig(filename=config['log_filename'],level=logging.INFO, format='%(asctime)s %(levelname)s: %(message)s')
## address book and address list placeholders
address_list = {}
addressbook = {}
# create PGP key for user
def create_pgp_key(email):
## generate key
time_start = time.time()
input_data = gpg.gen_key_input(name_email=email, name_real=email, name_comment='Generated by GoDark.ca', key_type="RSA", key_length=2048)
key = gpg.gen_key(input_data)
time_stop = time.time()
time_total = int(time_stop - time_start)
logging.debug('Generated PGP key for ' + email + ' in ' + str(time_total) + ' seconds')
## upload key
keyid = check_pgp_key(email, True)
for server in key_servers:
server_url = key_servers[server]['url'].split("/")[2]
result = gpg.send_keys(server_url, keyid)
logging.debug('Uploading PGP key to ' + server_url + ' : ' + str(result))
## lookup PGP key by email
def find_pgp_key(email):
for server in key_servers:
## try to grab key
try:
soup = BeautifulSoup(urllib2.urlopen(key_servers[server]['url'] + key_servers[server]['begin'] + urllib.quote(email) + key_servers[server]['end']).read())
## extract key result
key_url = ''
for item in soup(text=re.compile(r'pub ')):
key_url = key_servers[server]['url'] + item.parent('a')[0].get('href')
break
## if no result, continue seaching
if not key_url:
continue
## find key value by following href url
key = ''
key_soup = BeautifulSoup(urllib2.urlopen(key_url))
key = key_soup.find('pre').getText()
## if no key is found (error), continue
if not key:
continue
else:
print server
print key
#import_gpg_key(key)
#return True
## if there is an error
except urllib2.URLError, e:
## no key available, so return
if e == 'HTTP Error 404: Not found':
continue
## something went wrong!
else:
logging.error('PGP keyfinder encountered an error when contacting the ' + server + ' keyserver: ' + str(e))
return False
## check if we have a GPG key in our keyring
def check_pgp_key(email, keyid=False):
global gpg
for key in gpg.list_keys():
if key['uids'][0].split('<')[1][:-1] == email:
if keyid:
return key['keyid']
else:
return key['fingerprint']
return False
## add GPG locally
def import_gpg_key(key):
global gpg
import_result = gpg.import_keys(key)
logging.info('Imported GPG key')
## encrypt text
## Note: you must patch /usr/share/pyshared/gnupg.py to enable --trust-model always
# def encrypt_file(self, file, recipients, sign=None,
# [...]
# else:
# args = ['--encrypt']
# if not _is_sequence(recipients):
# recipients = (recipients,)
# for recipient in recipients:
# args.extend(['--recipient', shell_quote(recipient)])
# args.extend(['--trust-model', 'always']) <---- ADD THIS!
def encrypt_text(text, fingerprint):
global gpg
return str(gpg.encrypt(text, fingerprint))
## connect to Bitmessage API
def api_connect(module):
global api
## connect to API
api['conn'] = xmlrpclib.ServerProxy('http://' + api['username'] + ':' + api['password'] + '@' + api['host'] + ':' + api['port'] + '/')
## check if API is responding
try:
response = api['conn'].add(2,2)
logging.info(module + " module loaded Bitmessage API and started")
## load addresses and addressbook
global address_list, addressbook
address_list = get_address_list()
addressbook = get_addressbook()
return True
except:
logging.error('Could not connect to Bitmessage API ')
return False
## find inbound address list for sending bitmessages from external email addresses
def get_address_list():
global api
bm_addresses = json.loads(api['conn'].listAddresses())['addresses']
address_list = {}
for address in bm_addresses:
address_list[address['label']] = address['address']
return address_list
## find destonation addressbook for sending bitmessages
def get_addressbook():
global api
bm_addressbook = json.loads(api['conn'].listAddressBookEntries())['addresses']
addressbook = {}
for address in bm_addressbook:
addressbook[base64.b64decode(address['label'])] = address['address']
return addressbook
## check if a bitmessage address has already registered a username
def is_address_registered(address):
global addressbook
for label in addressbook:
if addressbook[label] == address:
return True
return False
## find username from address
def find_username(address):
global addressbook
for label in addressbook:
if addressbook[label] == address:
return label
return False
## check if username is banned
def is_banned_username(username):
global banned_usernames
if username in banned_usernames:
return True
else:
return False
## find mapping for generated bitmessage ID to internet-bound email address
def find_internet_mapping(address):
global address_list
for email,bound_add in address_list.iteritems():
if bound_add == address:
return email
return False
## read email from file
def read_email(k):
global config
try:
f = open(config['mail_folder'] + k, 'r')
message = f.read()
return message
except IOError:
logging.error('Could not read email: ' + config['mail_folder'] + k)
return
## delete email from file
def delete_email(k):
global config
try:
os.remove(config['mail_folder'] + k)
except OSError:
logging.error('Could not delete email: ' + config['mail_folder'] + k)
## generate a bitmessage address for an incoming email adress
def generate_sender_address(email):
global api
## generate random address
time_start = time.time()
address = api['conn'].createRandomAddress(base64.b64encode(email))
time_stop = time.time()
time_total = int(time_stop - time_start)
logging.info('Generated sender address for ' + email + ' in ' + str(time_total) + ' seconds')
return address
## send bitmessage
def send_bitmessage(bm_to_address, bm_from_address, bm_subject, bm_body, from_email, to_email):
global api, config
## send message
while True:
try:
ackData = api['conn'].sendMessage(bm_to_address, bm_from_address, bm_subject, bm_body, 2)
except:
logging.warn('Could not send bitmessage via API. Retrying...')
continue
break
## log result
if config['debug']:
logging.info('Sent bitmessage from ' + from_email + ' to ' + to_email + ' : QUEUED FOR DELIVERY , API response: ' + ackData)
else:
logging.info('Sent bitmessage from ' + from_email + ' to ' + to_email + ' : QUEUED FOR DELIVERY')
## check for new bitmessages
def get_bitmessages():
global api
while True:
try:
messages = json.loads(api['conn'].getAllInboxMessages())['inboxMessages']
except:
logging.warn('Could not read inbox messages via API. Retrying...')
continue
break
return messages
## delete bitmessage
def delete_bitmessage(msgid):
global api, debug
result = api['conn'].trashMessage(msgid)
if config['debug']:
logging.debug('Deleted bitmessage, API response: ' + result)
else:
logging.info('Deleted bitmessage')
## send outbound email
def send_email(receiver, sender, subject, body, bm_id):
## open connection
server = smtplib.SMTP('localhost')
server.set_debuglevel(0)
## build message
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject
## generate a signing key if we dont have one
if not check_pgp_key(sender, True):
create_pgp_key(sender)
## sign message
user_keyid = check_pgp_key(sender, True)
if user_keyid:
signed_text = gpg.sign(body, keyid=user_keyid)
if signed_text:
body = str(signed_text)
else:
logging.error('Found the user\'s keyid, but could not sign message from ' + sender)
else:
logging.error('Could not find user\'s keyid: ' + sender)
## search for recipient PGP key
if find_pgp_key(receiver):
fingerprint = check_pgp_key(receiver)
## if the key was imported fine, encrypt the message
if fingerprint:
## only encrypt if the operation was successful
enc_body = encrypt_text(body, fingerprint)
if enc_body:
body = enc_body
## delete PGP key for privacy reasons
result = gpg.delete_keys(fingerprint)
logging.debug('Purging PGP key: ' + str(result))
## encode as needed
body = MIMEText(body, 'plain')
## attach body with correct encoding
msg.attach(body)
text = msg.as_string()
## send message
status = server.sendmail(sender, receiver, text)
server.close()
## check for errors
for address in status:
logging.error('Could not send email from ' + sender + ' to ' + receiver + ' : ' + status[address])
if not status:
logging.info('Sent email from ' + sender + ' to ' + receiver)
## delete bitmessage
delete_bitmessage(bm_id)
## list known addresses
def list_addresses():
global address_list, addressbook
## print all addresses
print "\n####################################\nInternal Address List\n####################################"
for tmp_email in address_list:
print tmp_email + "\t\t\t" + address_list[tmp_email]
print ''
print "\n####################################\nUser List\n####################################"
for tmp_email in addressbook:
print tmp_email + "\t\t\t" + addressbook[tmp_email]
print ""
## add email @godark.ca with bitmessage address
def add_new_user(address, email):
global api, config
if config['debug']:
logging.debug('Registered new user, API response: ' + api['conn'].addAddressBookEntry(address, base64.b64encode(email)))
else:
api['conn'].addAddressBookEntry(address, base64.b64encode(email))
logging.info('Registered new user ' + email)
## send out registration confirmation
def send_registration_verification(bm_to_address, bm_from_address, email):
global api, config, address_list
## build message
subject = base64.b64encode('Registration Request Accepted')
body = 'Thank you for your registration request for ' + email + '. Your account is now set up and ready to use!\r\n\r\n'
body = body + '*** Sending Emails ***\r\n'
body = body + 'To send anonymous emails to the Internet, send a bitmessage to ' + address_list[config['receiving_address_label']] + ' with the destination email address in the subject line.\r\n\r\n'
body = body + '*** Deregistering Your Account ***\r\n'
body = body + 'To deregister, simply send a message from this address to ' + address_list[config['deregistration_address_label']] + '.\r\n\r\n'
body = body + '*** ' + config['domain_name'] + ' Addresses to Trust (Add to Address Book) ***\r\n'
body = body + 'Registration Address: ' + address_list[config['registration_address_label']] + '\r\n'
body = body + 'Deregistration Address: ' + address_list[config['deregistration_address_label']] + '\r\n'
body = body + 'Outbound Messages Address: ' + address_list[config['receiving_address_label']] + '\r\n'
body = body + 'Inbound Messages Address: ' + address_list[config['sending_address_label']] + '\r\n\r\n'
body = body + '*** Mailing List Subscription ***\r\n'
body = body + 'To join our internal mailing list (notices, updates, bug fixes, etc.), please subscribe to ' + config['broadcast_address_bitmesage'] + '\r\n\r\n'
body = body + '*** Stuck Messages ***\r\n'
body = body + 'If you have sent a message to this service and Bitmessage does not show the message status as \'Acknowledged\' after 10 minutes, please send it again.\r\n\r\n'
body = body + '*** Reporting Bugs ***\r\n'
body = body + 'This service is still in Beta! Please send any comments/bug reports to ' + config['bug_report_address_email'] + ' or send us a bitmessage at ' + config['bug_report_address_bitmessage'] + '.\r\n\r\n'
body = base64.b64encode(body)
## send message
send_bitmessage(bm_to_address, bm_from_address, subject, body, 'register@' + config['domain_name'], email)
## send out deregistration confirmation
def send_deregistration_verification(bm_to_address, bm_from_address, email):
global api, config
## build message
subject = base64.b64encode('Deregistration Request Processed')
body = base64.b64encode('Thank you for your deregistration request for ' + email + '. Your account has now been removed. Bon vogage!')
## send message
send_bitmessage(bm_to_address, bm_from_address, subject, body, 'deregister@' + config['domain_name'], email)
## send registration request response for bad requests
def send_registration_response(badFormat, badUsername, bm_to_address, bm_from_address, email):
global api, config
## build message
subject = base64.b64encode('Registration Request Denied')
if badFormat:
logging.warn('Received invalid registration request from ' + bm_to_address + ' for ' + email + ' (Invalid Username)')
body = base64.b64encode('Your registration request for username ' + email + ' was dened because the submitted username format is invalid.\r\n\r\nPlease register an alpha-numeric only username with a length of 4-20 characters. We will add the ' + config['domain_name'] + ' suffix automatically!')
else:
logging.warn('Received invalid registration request from ' + bm_to_address + ' for ' + email + ' (Username In Use)')
body = base64.b64encode('Your registration request for username ' + email + ' was dened because the username is reserved, already in use, or you have already registered an address!')
## send message
if config['respond_to_invalid']:
send_bitmessage(bm_to_address, bm_from_address, subject, body, '[email protected]', 'Denied Registration Request')
## delete address
def delete_address(address):
global api, config
## try to delete and don't worry about if it actually goes through
api['conn'].deleteAddressBookEntry(address)
api['conn'].deleteAddress(address)
if config['debug']:
logging.debug('Deleted bitmessage address, ' + address)
## check for new bitmessages to process
def check_messages():
global config, addressbook, address_list
## get all messages
all_messages = json.loads(api['conn'].getAllInboxMessages())['inboxMessages']
## if no messages
if not all_messages:
return
## loop through messages to find unread
for a_message in all_messages:
## if already read, delete and break
if a_message['read'] == 1:
delete_bitmessage(a_message['msgid'])
continue
## if the message is unread, load it by ID to trigger the read flag
message = json.loads(api['conn'].getInboxMessageByID(a_message['msgid'], True))['inboxMessage'][0]
## if a blank message was returned
if not message:
logging.error('API returned blank message when requesting a message by msgID')
delete_bitmessage(bm_id)
continue
## find message ID
bm_id = message['msgid']
## check if receive address is a DEregistration request
if message['toAddress'] == address_list[config['deregistration_address_label']]:
## check if address is registered
is_registered = is_address_registered(message['fromAddress'])
## if the sender is actually registered and wants to deregister
if is_registered:
## find username
deregistered_email = find_username(message['fromAddress'])
## process deregistration
logging.info('Processed deregistration request for user ' + deregistered_email)
delete_address(message['fromAddress'])
addressbook.pop(deregistered_email, None)
## send deregistration confirmation email
send_deregistration_verification(message['fromAddress'], address_list[config['deregistration_address_label']], deregistered_email)
## bogus deregistration request
else:
logging.warn('Purged malicious deregistration bitmessage from ' + message['fromAddress'])
## check if receive address is a registration request
elif message['toAddress'] == address_list[config['registration_address_label']]:
## find requested username
proposed_registration_user = base64.b64decode(message['subject'])
#full_registration_user = registration_user + '@' + config['domain_name']
valid_one = re.match('^[\w]{4,20}$', proposed_registration_user) is not None
valid_two = re.match('^[\w]{4,20}@' + config['domain_name'] + '$', proposed_registration_user) is not None
## if username is valid check if it's available
if valid_one or valid_two:
# strip domain if they sent it during registration
if valid_one:
full_registration_user = proposed_registration_user.lower() + '@' + config['domain_name']
registration_user = proposed_registration_user.lower()
else:
full_registration_user = proposed_registration_user.lower()
registration_user = proposed_registration_user.split('@')[0].lower()
## check if address is already registered to a username or is banned
is_double_registered = is_address_registered(message['fromAddress'])
is_banned = is_banned_username(registration_user)
## if username is available and not banned and not double registered
if not full_registration_user in addressbook and not is_banned and not is_double_registered:
logging.info('Received registration request for username ' + full_registration_user)
add_new_user(message['fromAddress'], full_registration_user)
addressbook[full_registration_user] = message['fromAddress']
send_registration_verification(message['fromAddress'], address_list[config['registration_address_label']], full_registration_user)
## username already taken
else:
send_registration_response(False, True, message['fromAddress'], address_list[config['registration_address_label']], full_registration_user)
## if bad username format
else:
send_registration_response(True, False, message['fromAddress'], address_list[config['registration_address_label']], proposed_registration_user)
## if sent to the generic receiver or sender address
else:
## find message id
bm_id = message['msgid']
## if user is not registered, purge
is_registered = is_address_registered(message['fromAddress'])
if not is_registered:
logging.warn('Purged bitmessage from non-registered user ' + message['fromAddress'])
delete_bitmessage(bm_id)
continue
## if user is registered, find their username @ domain
else:
bm_sender = find_username(message['fromAddress'])
## find outbound email address
bm_receiver = re.findall(r'[\w\.-]+@[\w\.-]+\.[\w]+', base64.b64decode(message['subject']))
if len(bm_receiver) > 0:
bm_receiver = bm_receiver[0]
## if there is no receiver mapping or the generic address didnt get a valid outbound email, deny it
if not bm_receiver:
logging.warn('Received and purged bitmessage with unknown recipient (likely generic address and bad subject)')
delete_bitmessage(bm_id)
continue
## find message subject
bm_subject = base64.b64decode(message['subject'])
## handle removal of embedded BMG-FROM:: tag for replies
bm_subject = bm_subject.replace('BMG-FROM::' + bm_receiver + ' | ', '');
## remove email address from subject
if message['toAddress'] == address_list[config['receiving_address_label']]:
bm_subject = bm_subject.replace(bm_receiver, '')
## get message contents
bm_body = base64.b64decode(message['message'])
## send message and delete bitmessage, bitches
send_email(bm_receiver, bm_sender, bm_subject, bm_body, bm_id)
## remove message
delete_bitmessage(bm_id)
## check for new mail to process
def check_emails():
global config, address_list, addressbook
## find new messages in folders
dir = os.listdir(config['mail_folder'])
## no new mail
if not dir:
return
## iterate through new messages
for k in dir:
## read email from file
msg_raw = read_email(k)
if not msg_raw:
logging.error('Could not open email file: ' + k)
continue
## extract header
msg_headers = Parser().parsestr(msg_raw)
## check if email was valid
if not msg_headers:
logging.error('Malformed email detected and purged')
delete_email(k)
continue
## find email source and dest addresses
msg_sender = msg_headers["From"]
## failed delivery email
if msg_sender == '<>':
msg_sender = config['sending_address_label']
else:
msg_sender = re.findall(r'[\w\.-]+@[\w\.-]+.[\w]+', msg_sender)[0]
## find email details
msg_recipient = re.findall(r'[\w\.-]+@[\w\.-]+.[\w]+', msg_headers["To"])[0]
## check if we have valid sender and recipient details
if not msg_sender or not msg_recipient:
logging.warn('Malformed email detected and purged')
delete_email(k)
continue
## check if we have a recipient address for the receiving email
if not msg_recipient in addressbook:
## look for X-Original-To instead
msg_recipient = re.findall(r'[\w\.-]+@[\w\.-]+.[\w]+', msg_headers["X-Original-To"])[0]
## no valid recipient
if not msg_recipient in addressbook:
logging.warn('Purged email destined for unknown user ' + msg_recipient + ' from ' + msg_sender)
logging.debug(msg_headers)
delete_email(k)
continue
## set bitmessage destination address
bm_to_address = addressbook[msg_recipient]
## set from address
bm_from_address = address_list[config['sending_address_label']]
## find message subject
msg_subject = decode_header(msg_headers['subject'])[0]
if(msg_subject[1]):
msg_subject = unicode(msg_subject[0], msg_subject[1])
else:
msg_subject = msg_subject[0]
## find message body contents in plaintext
msg_tmp = email.message_from_string(msg_raw)
msg_body = ''
for part in msg_tmp.walk():
if part and part.get_content_type() == 'text/plain':
part_str = part.get_payload(decode=1)
if part.get_content_charset():
msg_body = msg_body + part_str.decode(part.get_content_charset())
else:
msg_body = msg_body + part_str
## if there's no plaintext content, convert the html
if not msg_body:
for part in msg_tmp.walk():
if part and part.get_content_type() == 'text/html':
part_str = part.get_payload(decode=1)
if part.get_content_charset():
msg_body = msg_body + part_str.decode(part.get_content_charset())
else:
msg_body = msg_body + part_str
#msg_body = msg_body + html2text.html2text(unicode(part.get_payload(), part.get_content_charset()))
## if there's no plaintext or html, check if it's encrypted
if not msg_body:
for part in msg_tmp.walk():
## look for encrypted attachment containing text
if part and part.get_content_type() == 'application/octet-stream':
part_str = part.get_payload(decode=1)
## if we see the pgp header, decrypt
if 'BEGIN PGP MESSAGE' in part_str:
decrypted_data = gpg.decrypt(part_str)
## decrypt failed
if not decrypted_data:
logging.error("Decryption of email destined for " + msg_recipient + " failed")
continue
## convert to email message format
decrypted_data = email.message_from_string(decrypted_data.data)
## extract decrypted data
for decrypted_part in decrypted_data.walk():
if decrypted_part and decrypted_part.get_content_type() == 'text/plain':
decrypted_str = decrypted_part.get_payload(decode=1)
if decrypted_part.get_content_charset():
msg_body = msg_body + decrypted_str.decode(decrypted_part.get_content_charset())
else:
msg_body = msg_body + decrypted_str
## unknown attachment
else:
logging.debug("Received application/octet-stream type in inbound email, but did not see encryption header")
## print message status and set correct subject
## if bounced email
if msg_sender == config['sending_address_label']:
logging.info('Received bounced email... forwarding to ' + msg_recipient)
bm_subject = base64.b64encode('postmaster@' + config['domain_name'])
## if normal email
else:
logging.info('Received inbound email request from ' + msg_sender + ' to ' + msg_recipient)
bm_subject = base64.b64encode('BMG-FROM::' + msg_sender + ' | ' + msg_subject.encode('utf-8'))
## send message to bitmessage address
bm_body = base64.b64encode(msg_body.encode('utf-8'))
send_bitmessage(bm_to_address, bm_from_address, bm_subject, bm_body, msg_sender, msg_recipient)
## remove email file
delete_email(k)
## main
parser = argparse.ArgumentParser(description='An email <-> bitmessage gateway.')
parser.add_argument('-l','--list', help='List known internal and external addresses',required=False, action='store_true')
parser.add_argument('-d','--delete', help='Delete an address',required=False, default=False)
parser.add_argument('-a','--add', help='Generate a new bitmessage address with given label',required=False, default=False)
args = parser.parse_args()
## call correct function
if args.list == True:
if api_connect('Address lister') == False:
sys.exit()
list_addresses()
elif args.delete:
if api_connect('Address deleter') == False:
sys.exit()
delete_address(args.delete)
elif args.add:
if api_connect('Address adder') == False:
sys.exit()
generate_sender_address(args.add)
else:
if api_connect('Main') == False:
sys.exit()
## run managers in threads
while True:
email_thread = threading.Thread(target=check_emails)
message_thread = threading.Thread(target=check_messages)
email_thread.start()
message_thread.start()
email_thread.join()
message_thread.join()
time.sleep(config['process_interval'])