-
-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy pathemailproxy.py
1561 lines (1308 loc) · 79.1 KB
/
emailproxy.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
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""A simple IMAP/SMTP proxy that intercepts authenticate and login commands, transparently replacing them with OAuth 2.0
SASL authentication. Designed for apps/clients that don't support OAuth 2.0 but need to connect to modern servers."""
__author__ = 'Simon Robinson'
__copyright__ = 'Copyright (c) 2021 Simon Robinson'
__license__ = 'Apache 2.0'
__version__ = '2021-10-18' # ISO 8601
import argparse
import asyncore
import base64
import binascii
import configparser
import datetime
import enum
import json
import logging
import logging.handlers
import os
import pathlib
import plistlib
import queue
import socket
import ssl
import re
import subprocess
import sys
import threading
import time
import urllib.request
import urllib.parse
import urllib.error
import pystray
import timeago
import webview
# for drawing the menu bar icon
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
# for encrypting/decrypting the locally-stored credentials
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend
# for macOS-specific functionality: retina icon; updating menu on click
if sys.platform == 'darwin':
import AppKit
from AppKit import Foundation
APP_NAME = 'Email OAuth 2.0 Proxy'
APP_SHORT_NAME = 'emailproxy'
APP_PACKAGE = 'ac.robinson.email-oauth2-proxy'
VERBOSE = False # whether to print verbose logs (controlled via 'Debug mode' option in menu, or at startup here)
CENSOR_MESSAGE = b'[[ Credentials removed from proxy log ]]' # replaces credentials; must be a byte-type string
CONFIG_FILE_NAME = '%s.config' % APP_SHORT_NAME
CONFIG_FILE_PATH = '%s/%s' % (os.path.dirname(os.path.realpath(__file__)), CONFIG_FILE_NAME)
CONFIG_SERVER_MATCHER = re.compile(r'(?P<type>(IMAP|SMTP))-(?P<port>[\d]{4,5})')
MAX_CONNECTIONS = 0 # maximum concurrent IMAP/SMTP connections; 0 = no limit; limit is per server
# maximum number of bytes to read from the socket at once (limit is per socket) - note that we assume clients send one
# line at once (at least during the authentication phase), and we don't handle clients that flush the connection after
# each individual character (e.g., the inbuilt Windows telnet client)
RECEIVE_BUFFER_SIZE = 65536
# seconds to wait before cancelling authentication requests (i.e., the user has this long to log in) - note that the
# actual server timeout is often around 60 seconds, so the connection may be closed in the background and immediately
# disconnect after login completes; however, the login credentials will still be saved and used for future requests
AUTHENTICATION_TIMEOUT = 600
TOKEN_EXPIRY_MARGIN = 600 # seconds before its expiry to refresh the OAuth 2.0 token
IMAP_AUTHENTICATION_REQUEST_MATCHER = re.compile(r'(?P<tag>\w+) (?P<command>(LOGIN|AUTHENTICATE)) (?P<flags>.*)',
flags=re.IGNORECASE)
IMAP_AUTHENTICATION_RESPONSE_MATCHER = re.compile(r'(?P<tag>\w+) OK AUTHENTICATE.*', flags=re.IGNORECASE)
REQUEST_QUEUE = queue.Queue() # requests for authentication
RESPONSE_QUEUE = queue.Queue() # responses from client web view
WEBVIEW_QUEUE = queue.Queue() # authentication window events (macOS only)
QUEUE_SENTINEL = object() # object to send to signify queues should exit loops
PLIST_FILE_PATH = pathlib.Path('~/Library/LaunchAgents/%s.plist' % APP_PACKAGE).expanduser() # launchctl file location
CMD_FILE_PATH = pathlib.Path('~/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup/%s.cmd' %
APP_PACKAGE).expanduser() # Windows startup .cmd file location
AUTOSTART_FILE_PATH = pathlib.Path('~/.config/autostart/%s.desktop' % APP_PACKAGE).expanduser() # XDG Autostart file
EXTERNAL_AUTH_HTML = '''<html><style type="text/css">body{margin:20px auto;line-height:1.3;font-family:sans-serif;
font-size:16px;color:#444;padding:0 24px}</style>
<h3 style="margin:0.3em 0;">Login authorisation request for %s</h3>
<p style="margin-top:0">Click the following link to open your browser and approve the request:</p>
<p><a href="%s" target="_blank" style="word-wrap:break-word;word-break:break-all">%s</a></p>
<p style="margin-top:2em">After logging in and successfully authorising your account, paste and submit the
resulting URL from the browser's address bar using the box below to allow the %s script to transparently handle
login requests on your behalf in future.</p>
<p>Note that your browser may show a navigation error (e.g., <em>"localhost refused to connect"</em>) after
successfully logging in, but the final URL is the only important part, and as long as this begins with the correct
redirection URI and contains a valid authorisation code your email client's request will succeed.</p>
<p style="margin-top:2em">According to your %s configuration file, the expected final URL will be of the form:</p>
<p><pre>%s <em>[...]</em> code=<em><strong>[code]</strong> [...]</em></em></pre></p>
<form name="auth" onsubmit="window.location.assign(document.forms.auth.url.value); return false">
<div style="display:flex;flex-direction:row;margin-top:4em"><label for="url">Authorisation success URL:
</label><input type="text" name="url" id="url" style="flex:1;margin:0 5px"><input type="submit" value="Submit">
</div></form></html>'''
EXITING = False # used to check whether to restart failed threads - is set to True if the user has requested to exit
class Log:
"""Simple logging to syslog/Console.app on Linux/macOS and to a local file on Windows"""
_LOGGER = None
_DATE_FORMAT = '%Y-%m-%d %H:%M:%S:'
_DEFAULT_MESSAGE_FORMAT = '%s: %%(message)s' % APP_NAME
@staticmethod
def initialise():
Log._LOGGER = logging.getLogger(APP_NAME)
Log._LOGGER.setLevel(logging.INFO if sys.platform == 'darwin' else logging.DEBUG)
if sys.platform == 'win32':
handler = logging.FileHandler('%s/%s.log' % (os.path.dirname(os.path.realpath(__file__)), APP_SHORT_NAME))
handler.setFormatter(logging.Formatter('%(asctime)s: %(message)s'))
else:
handler = logging.handlers.SysLogHandler(
address='/var/run/syslog' if sys.platform == 'darwin' else '/dev/log')
handler.setFormatter(logging.Formatter(Log._DEFAULT_MESSAGE_FORMAT))
Log._LOGGER.addHandler(handler)
@staticmethod
def _log(level, *args):
message = ' '.join(map(str, args))
print(datetime.datetime.now().strftime(Log._DATE_FORMAT), message)
# note: need LOG_ALERT (i.e., warning) or higher to show in syslog on macOS
severity = Log._LOGGER.warning if sys.platform == 'darwin' else level
if len(message) > 2048:
truncation_message = ' [ NOTE: message over syslog length limit truncated to 2048 characters; run `%s' \
' --debug` in a terminal to see the full output ] ' % os.path.basename(__file__)
message = message[0:2048 - len(Log._DEFAULT_MESSAGE_FORMAT) - len(truncation_message)] + truncation_message
severity(message)
@staticmethod
def debug(*args):
if VERBOSE:
Log._log(Log._LOGGER.debug, *args)
@staticmethod
def info(*args):
Log._log(Log._LOGGER.info, *args)
@staticmethod
def error_string(error):
return getattr(error, 'message', repr(error))
class AppConfig:
"""Helper wrapper around ConfigParser to cache servers/accounts, and avoid writing to the file until necessary"""
_PARSER = None
_LOADED = False
_SERVERS = []
_ACCOUNTS = []
@staticmethod
def _load():
AppConfig.unload()
AppConfig._PARSER = configparser.ConfigParser()
AppConfig._PARSER.read(CONFIG_FILE_PATH)
config_sections = AppConfig._PARSER.sections()
AppConfig._SERVERS = [s for s in config_sections if CONFIG_SERVER_MATCHER.match(s)]
AppConfig._ACCOUNTS = [s for s in config_sections if '@' in s]
AppConfig._LOADED = True
@staticmethod
def get():
if not AppConfig._LOADED:
AppConfig._load()
return AppConfig._PARSER
@staticmethod
def unload():
AppConfig._PARSER = None
AppConfig._LOADED = False
AppConfig._SERVERS = []
AppConfig._ACCOUNTS = []
@staticmethod
def reload():
AppConfig.unload()
return AppConfig.get()
@staticmethod
def servers():
AppConfig.get() # make sure config is loaded
return AppConfig._SERVERS
@staticmethod
def accounts():
AppConfig.get() # make sure config is loaded
return AppConfig._ACCOUNTS
@staticmethod
def save():
if AppConfig._LOADED:
with open(CONFIG_FILE_PATH, 'w') as config_output:
AppConfig._PARSER.write(config_output)
class OAuth2Helper:
@staticmethod
def get_oauth2_credentials(username, password, connection_info, recurse_retries=True):
"""Using the given username (i.e., email address) and password, reads account details from AppConfig and
handles OAuth 2.0 token request and renewal, saving the updated details back to AppConfig (or removing them
if invalid). Returns either (True, '[OAuth2 string for authentication]') or (False, '[Error message]')"""
if username not in AppConfig.accounts():
Log.info('Proxy config file entry missing for account', username, '- aborting login')
return (False, '%s: No config file entry found for account %s - please add a new section with values '
'for permission_url, token_url, oauth2_scope, redirect_uri, client_id and '
'client_secret' % (APP_NAME, username))
config = AppConfig.get()
current_time = int(time.time())
permission_url = config.get(username, 'permission_url', fallback=None)
token_url = config.get(username, 'token_url', fallback=None)
oauth2_scope = config.get(username, 'oauth2_scope', fallback=None)
redirect_uri = config.get(username, 'redirect_uri', fallback=None)
client_id = config.get(username, 'client_id', fallback=None)
client_secret = config.get(username, 'client_secret', fallback=None)
if not (permission_url and token_url and oauth2_scope and redirect_uri and client_id and client_secret):
Log.info('Proxy config file entry incomplete for account', username, '- aborting login')
return (False, '%s: Incomplete config file entry found for account %s - please make sure all required '
'fields are added (permission_url, token_url, oauth2_scope, redirect_uri, client_id '
'and client_secret)' % (APP_NAME, username))
token_salt = config.get(username, 'token_salt', fallback=None)
access_token = config.get(username, 'access_token', fallback=None)
access_token_expiry = config.getint(username, 'access_token_expiry', fallback=current_time)
refresh_token = config.get(username, 'refresh_token', fallback=None)
# we hash locally-stored tokens with the given password
if not token_salt:
token_salt = base64.b64encode(os.urandom(16)).decode('utf-8')
# generate encrypter/decrypter based on password and random salt
key_derivation_function = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32,
salt=base64.b64decode(token_salt.encode('utf-8')), iterations=100000,
backend=default_backend())
key = base64.urlsafe_b64encode(key_derivation_function.derive(password.encode('utf-8')))
cryptographer = Fernet(key)
try:
if not refresh_token:
permission_url = OAuth2Helper.construct_oauth2_permission_url(permission_url, redirect_uri, client_id,
oauth2_scope)
# note: get_oauth2_authorisation_code is a blocking call
(success, authorisation_code) = OAuth2Helper.get_oauth2_authorisation_code(permission_url, redirect_uri,
username, connection_info)
if not success:
Log.info('Authentication request failed or expired for account', username, '- aborting login')
return False, '%s: Login failed - the authentication request expired or was cancelled for ' \
'account %s' % (APP_NAME, username)
response = OAuth2Helper.get_oauth2_authorisation_tokens(token_url, redirect_uri, client_id,
client_secret, authorisation_code)
access_token = response['access_token']
config.set(username, 'token_salt', token_salt)
config.set(username, 'access_token', OAuth2Helper.encrypt(cryptographer, access_token))
config.set(username, 'access_token_expiry', str(current_time + response['expires_in']))
config.set(username, 'refresh_token', OAuth2Helper.encrypt(cryptographer, response['refresh_token']))
AppConfig.save()
else:
if access_token_expiry - current_time < TOKEN_EXPIRY_MARGIN: # if expiring soon, refresh token
response = OAuth2Helper.refresh_oauth2_access_token(token_url, client_id, client_secret,
OAuth2Helper.decrypt(cryptographer,
refresh_token))
access_token = response['access_token']
config.set(username, 'access_token', OAuth2Helper.encrypt(cryptographer, access_token))
config.set(username, 'access_token_expiry', str(current_time + response['expires_in']))
AppConfig.save()
else:
access_token = OAuth2Helper.decrypt(cryptographer, access_token)
# send authentication command to server (response checked in ServerConnection) - note: we only support
# single-trip authentication (SASL) without actually checking the server's capabilities - improve?
oauth2_string = OAuth2Helper.construct_oauth2_string(username, access_token)
return True, oauth2_string
except InvalidToken as e:
# if invalid details are the reason for failure we need to remove our cached version and re-authenticate
config.remove_option(username, 'token_salt')
config.remove_option(username, 'access_token')
config.remove_option(username, 'access_token_expiry')
config.remove_option(username, 'refresh_token')
AppConfig.save()
if recurse_retries:
Log.info('Retrying login due to exception while requesting OAuth 2.0 credentials:', Log.error_string(e))
return OAuth2Helper.get_oauth2_credentials(username, password, connection_info, recurse_retries=False)
except Exception as e:
# note that we don't currently remove cached credentials here, as failures on the initial request are
# before caching happens, and the assumption is that refresh token request exceptions are temporal (e.g.,
# network errors) rather than e.g., bad requests
Log.info('Caught exception while requesting OAuth 2.0 credentials:', Log.error_string(e))
return False, '%s: Login failure - saved authentication data invalid for account %s' % (
APP_NAME, username)
@staticmethod
def encrypt(cryptographer, byte_input):
return cryptographer.encrypt(byte_input.encode('utf-8')).decode('utf-8')
@staticmethod
def decrypt(cryptographer, byte_input):
return cryptographer.decrypt(byte_input.encode('utf-8')).decode('utf-8')
@staticmethod
def oauth2_url_escape(text):
return urllib.parse.quote(text, safe='~-._') # see https://tools.ietf.org/html/rfc3986#section-2.3
@staticmethod
def oauth2_url_unescape(text):
return urllib.parse.unquote(text)
@staticmethod
def construct_oauth2_permission_url(permission_url, redirect_uri, client_id, scope):
"""Constructs and returns the URL to request permission for this client to access the given scope"""
params = {'client_id': client_id, 'redirect_uri': redirect_uri, 'scope': scope, 'response_type': 'code',
'access_type': 'offline'}
param_pairs = []
for param in sorted(iter(params.items()), key=lambda x: x[0]):
param_pairs.append('%s=%s' % (param[0], OAuth2Helper.oauth2_url_escape(param[1])))
return '%s?%s' % (permission_url, '&'.join(param_pairs))
@staticmethod
def get_oauth2_authorisation_code(permission_url, redirect_uri, username, connection_info):
"""Submit an authorisation request to the parent app and block until it is provided (or the request fails)"""
token_request = {'connection': connection_info, 'permission_url': permission_url,
'redirect_uri': redirect_uri, 'username': username, 'expired': False}
REQUEST_QUEUE.put(token_request)
wait_time = 0
while True:
try:
data = RESPONSE_QUEUE.get(block=True, timeout=1)
except queue.Empty:
wait_time += 1
if wait_time < AUTHENTICATION_TIMEOUT:
continue
else:
token_request['expired'] = True
REQUEST_QUEUE.put(token_request) # re-insert the request as expired so the parent app can remove it
return False, None
if data is QUEUE_SENTINEL: # app is closing
RESPONSE_QUEUE.put(QUEUE_SENTINEL) # make sure all watchers exit
return False, None
elif data['connection'] == connection_info: # found an authentication response meant for us
if data['response_url'] and 'code=' in data['response_url']:
authorisation_code = OAuth2Helper.oauth2_url_unescape(
data['response_url'].split('code=')[1].split('&')[0])
if authorisation_code:
return True, authorisation_code
return False, None
else: # not for this thread - put back into queue
RESPONSE_QUEUE.put(data)
time.sleep(1)
@staticmethod
def get_oauth2_authorisation_tokens(token_url, redirect_uri, client_id, client_secret, authorisation_code):
"""Requests OAuth 2.0 access and refresh tokens from token_url using the given client_id, client_secret,
authorisation_code and redirect_uri, returning a dict with 'access_token', 'expires_in', and 'refresh_token'
on success, or throwing an exception on failure (e.g., HTTP 400)"""
params = {'client_id': client_id, 'client_secret': client_secret, 'code': authorisation_code,
'redirect_uri': redirect_uri, 'grant_type': 'authorization_code'}
response = urllib.request.urlopen(token_url, urllib.parse.urlencode(params).encode('utf-8')).read()
return json.loads(response)
@staticmethod
def refresh_oauth2_access_token(token_url, client_id, client_secret, refresh_token):
"""Obtains a new access token from token_url using the given client_id, client_secret and refresh token,
returning a dict with 'access_token', 'expires_in', and 'refresh_token' on success; exception on failure"""
params = {'client_id': client_id, 'client_secret': client_secret, 'refresh_token': refresh_token,
'grant_type': 'refresh_token'}
try:
response = urllib.request.urlopen(token_url, urllib.parse.urlencode(params).encode('utf-8')).read()
return json.loads(response)
except urllib.error.HTTPError as e:
if e.code == 400: # 400 Bad Request typically means re-authentication is required (refresh token expired)
raise InvalidToken
raise e
@staticmethod
def construct_oauth2_string(username, access_token):
"""Constructs an OAuth 2.0 SASL authentication string from the given username and access token"""
return 'user=%s\1auth=Bearer %s\1\1' % (username, access_token)
@staticmethod
def encode_oauth2_string(input_string):
"""We use encode() from imaplib's _Authenticator, but it is a private class so we can't just import it. That
method's docstring is:
Invoke binascii.b2a_base64 iteratively with short even length buffers, strip the trailing line feed from
the result and append. 'Even' means a number that factors to both 6 and 8, so when it gets to the end of
the 8-bit input there's no partial 6-bit output."""
output_bytes = b''
if isinstance(input_string, str):
input_string = input_string.encode('utf-8')
while input_string:
if len(input_string) > 48:
t = input_string[:48]
input_string = input_string[48:]
else:
t = input_string
input_string = b''
e = binascii.b2a_base64(t)
if e:
output_bytes = output_bytes + e[:-1]
return output_bytes
@staticmethod
def strip_quotes(text):
"""Remove double quotes (i.e., " characters) around a string - used for IMAP LOGIN command"""
if text.startswith('"') and text.endswith('"'):
return text[1:-1].replace('\\"', '"') # also need to fix any escaped quotes within the string
return text
@staticmethod
def decode_credentials(str_data):
"""Decode credentials passed as a base64-encoded string: [some data we don't need]\x00username\x00password"""
try:
(_, bytes_username, bytes_password) = base64.b64decode(str_data).split(b'\x00')
return bytes_username.decode('utf-8'), bytes_password.decode('utf-8')
except (ValueError, binascii.Error):
# ValueError is from incorrect number of arguments; binascii.Error from incorrect encoding
return '', '' # no or invalid credentials provided
class OAuth2ClientConnection(asyncore.dispatcher_with_send):
"""The base client-side connection that is subclassed to handle IMAP/SMTP client interaction (note that there is
some IMAP-specific code in here, but it is not essential, and only used to avoid logging credentials)"""
def __init__(self, proxy_type, connection, socket_map, connection_info, server_connection, proxy_parent,
custom_configuration):
asyncore.dispatcher_with_send.__init__(self, connection, map=socket_map)
self.proxy_type = proxy_type
self.connection_info = connection_info
self.server_connection = server_connection
self.proxy_parent = proxy_parent
self.custom_configuration = custom_configuration
self.censor_next_log = False # try to avoid logging credentials
self.authenticated = False
def handle_connect(self):
pass
def handle_read(self):
# note: we don't handle clients that send one character at a time (e.g., inbuilt Windows telnet client)
byte_data = self.recv(RECEIVE_BUFFER_SIZE)
# client is established after server; this state should not happen unless already closing
if not self.server_connection:
if byte_data:
Log.debug(self.proxy_type, self.connection_info,
'Data received without server connection - ignoring and closing:', byte_data)
self.close()
return
# we have already authenticated - nothing to do; just pass data directly to server (slightly more involved
# than the server connection because we censor commands that contain passwords or authentication tokens)
if self.authenticated:
Log.debug(self.proxy_type, self.connection_info, '-->', byte_data)
OAuth2ClientConnection.process_data(self, byte_data)
else:
# try to remove credentials from logged data - both inline (via regex) and those as a separate request
if self.censor_next_log:
log_data = CENSOR_MESSAGE
self.censor_next_log = False
else:
# IMAP LOGIN command with username/password in plain text inline, and IMAP/SMTP AUTH(ENTICATE) command
log_data = re.sub(b'(\\w+) (LOGIN) (.*)\r\n', b'\\1 \\2 %s\r\n' % CENSOR_MESSAGE, byte_data,
flags=re.IGNORECASE)
log_data = re.sub(b'(\\w*)( ?)(AUTH)(ENTICATE)? (PLAIN) (.*)\r\n',
b'\\1\\2\\3\\4 \\5 %s\r\n' % CENSOR_MESSAGE, log_data, flags=re.IGNORECASE)
Log.debug(self.proxy_type, self.connection_info, '-->', log_data)
self.process_data(byte_data)
def process_data(self, byte_data, censor_server_log=False):
self.server_connection.send(byte_data, censor_server_log) # by default just send everything straight to server
def send(self, byte_data):
if not self.authenticated: # after authentication these are identical to server-side logs (in process_data)
Log.debug(self.proxy_type, self.connection_info, '<--', byte_data)
super().send(byte_data)
def handle_close(self):
Log.debug(self.proxy_type, self.connection_info, '--> [ Client disconnected ]')
self.close()
def close(self):
if self.server_connection:
self.server_connection.client_connection = None
self.server_connection.close()
self.server_connection = None
self.proxy_parent.remove_client(self)
super().close()
class IMAPOAuth2ClientConnection(OAuth2ClientConnection):
"""The client side of the connection - intercept LOGIN/AUTHENTICATE commands and replace with OAuth 2.0 SASL"""
def __init__(self, connection, socket_map, connection_info, server_connection, proxy_parent, custom_configuration):
super().__init__('IMAP', connection, socket_map, connection_info, server_connection, proxy_parent,
custom_configuration)
self.authentication_tag = None
self.authentication_command = None
self.awaiting_credentials = False
def process_data(self, byte_data, censor_server_log=False):
str_data = byte_data.decode('utf-8', 'replace').rstrip('\r\n')
# AUTHENTICATE PLAIN can be a two-stage request - handle credentials if they are separate from command
if self.awaiting_credentials:
self.awaiting_credentials = False
(username, password) = OAuth2Helper.decode_credentials(str_data)
self.authenticate_connection(username, password, 'authenticate')
else:
match = IMAP_AUTHENTICATION_REQUEST_MATCHER.match(str_data)
if not match: # probably an invalid command, but just let the server handle it
super().process_data(byte_data)
return
# we replace the standard LOGIN/AUTHENTICATE commands with OAuth 2.0 authentication
self.authentication_command = match.group('command').lower()
client_flags = match.group('flags')
if self.authentication_command == 'login':
split_flags = client_flags.split(' ')
if len(split_flags) > 1:
username = OAuth2Helper.strip_quotes(split_flags[0])
password = OAuth2Helper.strip_quotes(' '.join(split_flags[1:]))
self.authentication_tag = match.group('tag')
self.authenticate_connection(username, password)
else:
# wrong number of arguments - let the server handle the error
super().process_data(byte_data)
elif self.authentication_command == 'authenticate':
split_flags = client_flags.split(' ')
authentication_type = split_flags[0].lower()
if authentication_type == 'plain': # plain can be submitted as a single command or multiline
self.authentication_tag = match.group('tag')
if len(split_flags) > 1:
(username, password) = OAuth2Helper.decode_credentials(' '.join(split_flags[1:]))
self.authenticate_connection(username, password, 'authenticate')
else:
self.awaiting_credentials = True
self.censor_next_log = True
self.send(b'+ \r\n') # request credentials
else:
# we don't support any other methods - let the server handle the error
super().process_data(byte_data)
else:
# we haven't yet authenticated, but this is some other matched command - pass through
super().process_data(byte_data)
def authenticate_connection(self, username, password, command='login'):
(success, result) = OAuth2Helper.get_oauth2_credentials(username, password, self.connection_info)
if success:
# send authentication command to server (response checked in ServerConnection)
# note: we only support single-trip authentication (SASL) without checking server capabilities - improve?
super().process_data(b'%s AUTHENTICATE XOAUTH2 ' % self.authentication_tag.encode('utf-8'))
super().process_data(OAuth2Helper.encode_oauth2_string(result), True)
super().process_data(b'\r\n')
self.server_connection.authenticated_username = username
else:
error_message = '%s NO %s %s\r\n' % (self.authentication_tag, command.upper(), result)
self.send(error_message.encode('utf-8'))
self.send(b'* BYE Autologout; authentication failed\r\n')
self.close()
class SMTPOAuth2ClientConnection(OAuth2ClientConnection):
"""The client side of the connection - intercept AUTH LOGIN commands and replace with OAuth 2.0"""
class AUTH(enum.Enum):
PENDING = 1
PLAIN_AWAITING_CREDENTIALS = 2
LOGIN_AWAITING_USERNAME = 3
LOGIN_AWAITING_PASSWORD = 4
AUTH_CREDENTIALS_SENT = 5
def __init__(self, connection, socket_map, connection_info, server_connection, proxy_parent, custom_configuration):
super().__init__('SMTP', connection, socket_map, connection_info, server_connection, proxy_parent,
custom_configuration)
self.authentication_state = self.AUTH.PENDING
def process_data(self, byte_data, censor_server_log=False):
str_data = byte_data.decode('utf-8', 'replace').rstrip('\r\n')
str_data_lower = str_data.lower()
# intercept EHLO so we can add STARTTLS (in parent class)
if self.server_connection.ehlo is None and self.custom_configuration['starttls']:
if str_data_lower.startswith('ehlo') or str_data_lower.startswith('helo'):
self.server_connection.ehlo = str_data # save the command so we can replay later from the server side
super().process_data(byte_data)
return
# intercept AUTH PLAIN and AUTH LOGIN to replace with AUTH XOAUTH2
if self.authentication_state is self.AUTH.PENDING and str_data_lower.startswith('auth plain'):
if len(str_data) > 11: # 11 = len('AUTH PLAIN ') - this method can have the login details either inline...
(self.server_connection.username, self.server_connection.password) = OAuth2Helper.decode_credentials(
str_data[11:])
self.send_authentication_request()
else: # ...or requested separately
self.authentication_state = self.AUTH.PLAIN_AWAITING_CREDENTIALS
self.censor_next_log = True
self.send(b'334 \r\n') # request details (note: space after response code is mandatory)
elif self.authentication_state is self.AUTH.PLAIN_AWAITING_CREDENTIALS:
(self.server_connection.username, self.server_connection.password) = OAuth2Helper.decode_credentials(
str_data)
self.send_authentication_request()
elif self.authentication_state is self.AUTH.PENDING and str_data_lower.startswith('auth login'):
self.authentication_state = self.AUTH.LOGIN_AWAITING_USERNAME
self.send(b'334 %s\r\n' % base64.b64encode(b'Username:'))
elif self.authentication_state is self.AUTH.LOGIN_AWAITING_USERNAME:
try:
self.server_connection.username = base64.b64decode(str_data).decode('utf-8')
except binascii.Error:
self.server_connection.username = ''
self.authentication_state = self.AUTH.LOGIN_AWAITING_PASSWORD
self.censor_next_log = True
self.send(b'334 %s\r\n' % base64.b64encode(b'Password:'))
elif self.authentication_state is self.AUTH.LOGIN_AWAITING_PASSWORD:
try:
self.server_connection.password = base64.b64decode(str_data).decode('utf-8')
except binascii.Error:
self.server_connection.password = ''
self.send_authentication_request()
# some other command that we don't handle - pass directly to server
else:
super().process_data(byte_data)
def send_authentication_request(self):
self.authentication_state = self.AUTH.PENDING
self.server_connection.authentication_state = SMTPOAuth2ServerConnection.AUTH.STARTED
super().process_data(b'AUTH XOAUTH2\r\n')
class OAuth2ServerConnection(asyncore.dispatcher_with_send):
"""The base server-side connection, setting up STARTTLS if requested, subclassed for IMAP/SMTP server interaction"""
def __init__(self, proxy_type, socket_map, server_address, connection_info, proxy_parent, custom_configuration):
asyncore.dispatcher_with_send.__init__(self, map=socket_map) # note: establish connection later due to STARTTLS
self.proxy_type = proxy_type
self.connection_info = connection_info
self.client_connection = None
self.server_address = server_address
self.proxy_parent = proxy_parent
self.custom_configuration = custom_configuration
self.authenticated_username = None # used only for showing last activity in the menu
self.last_activity = 0
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect(self.server_address)
def handle_connect(self):
Log.debug(self.proxy_type, self.connection_info, '--> [ Client connected ]')
def create_socket(self, socket_family=socket.AF_INET, socket_type=socket.SOCK_STREAM):
new_socket = socket.socket(socket_family, socket_type)
new_socket.setblocking(True)
# connections can either be wrapped via the STARTTLS command, or SSL from the start
if self.custom_configuration['starttls']:
self.set_socket(new_socket)
else:
ssl_context = ssl.create_default_context()
self.set_socket(ssl_context.wrap_socket(new_socket, server_hostname=self.server_address[0]))
def handle_read(self):
# note: we don't handle servers that send one character at a time (no known instances, but see client side note)
byte_data = self.recv(RECEIVE_BUFFER_SIZE)
# data received before client is connected (or after client has disconnected) - ignore
if not self.client_connection:
if byte_data:
Log.debug(self.proxy_type, self.connection_info, 'Data received without client connection - ignoring:',
byte_data)
return
# we have already authenticated - nothing to do; just pass data directly to client, ignoring overridden method
if self.client_connection.authenticated:
OAuth2ServerConnection.process_data(self, byte_data)
# receiving data from the server while authenticated counts as activity (i.e., ignore pre-login negotiation)
if self.authenticated_username is not None:
activity_time = int(time.time())
if activity_time > self.last_activity:
config = AppConfig.get()
config.set(self.authenticated_username, 'last_activity', str(activity_time))
self.last_activity = activity_time
else:
Log.debug(self.proxy_type, self.connection_info, ' <--', byte_data) # command received before editing
self.process_data(byte_data)
def process_data(self, byte_data):
self.client_connection.send(byte_data) # by default we just send everything straight to the client
if self.client_connection.authenticated:
Log.debug(self.proxy_type, self.connection_info, '<--', byte_data) # command after any editing/interception
def send(self, byte_data, censor_log=False):
if not self.client_connection.authenticated: # after authentication these are identical to server-side logs
Log.debug(self.proxy_type, self.connection_info, ' -->', CENSOR_MESSAGE if censor_log else byte_data)
super().send(byte_data)
def handle_close(self):
Log.debug(self.proxy_type, self.connection_info, '<-- [ Server disconnected ]')
if self.client_connection:
self.client_connection.server_connection = None
self.client_connection.close()
self.client_connection = None
self.close()
class IMAPOAuth2ServerConnection(OAuth2ServerConnection):
"""The IMAP server side - watch for the OK AUTHENTICATE response, then ignore all subsequent data"""
# IMAP: https://tools.ietf.org/html/rfc3501
# IMAP SASL-IR: https://tools.ietf.org/html/rfc4959
def __init__(self, socket_map, server_address, connection_info, proxy_parent, custom_configuration):
super().__init__('IMAP', socket_map, server_address, connection_info, proxy_parent, custom_configuration)
def process_data(self, byte_data):
# note: there is no reason why IMAP STARTTLS (https://tools.ietf.org/html/rfc2595) couldn't be supported here
# as with SMTP, but it doesn't seem like any well-known servers support this, so left unimplemented for now
str_response = byte_data.decode('utf-8', 'replace').rstrip('\r\n')
if str_response.startswith('* CAPABILITY'):
# intercept CAPABILITY response and replace with what we can actually do
updated_response = re.sub(r'(AUTH=[\w]+ )+', 'AUTH=PLAIN ', str_response, flags=re.IGNORECASE)
byte_data = (b'%s\r\n' % updated_response.encode('utf-8'))
else:
# if authentication succeeds, remove our proxy from the client and ignore all further communication
match = IMAP_AUTHENTICATION_RESPONSE_MATCHER.match(str_response)
if match and match.group('tag') == self.client_connection.authentication_tag:
Log.info(self.proxy_type, self.connection_info,
'[ Successfully authenticated IMAP connection - removing proxy ]')
if self.client_connection.authentication_command == 'login':
byte_data = byte_data.replace(b'OK AUTHENTICATE', b'OK LOGIN') # make sure response is correct
self.client_connection.authenticated = True
super().process_data(byte_data)
class SMTPOAuth2ServerConnection(OAuth2ServerConnection):
"""The SMTP server side - setup STARTTLS, request any credentials, then watch for 235 and ignore subsequent data"""
# SMTP: https://tools.ietf.org/html/rfc2821
# SMTP STARTTLS: https://tools.ietf.org/html/rfc3207
# SMTP AUTH: https://tools.ietf.org/html/rfc4954
class STARTTLS(enum.Enum):
PENDING = 1
NEGOTIATING = 2
COMPLETE = 3
class AUTH(enum.Enum):
PENDING = 1
STARTED = 2
CREDENTIALS_SENT = 3
def __init__(self, socket_map, server_address, connection_info, proxy_parent, custom_configuration):
super().__init__('SMTP', socket_map, server_address, connection_info, proxy_parent, custom_configuration)
self.ehlo = None
if self.custom_configuration['starttls']:
self.starttls = self.STARTTLS.PENDING
else:
self.starttls = self.STARTTLS.COMPLETE
self.authentication_state = self.AUTH.PENDING
self.username = None
self.password = None
def process_data(self, byte_data):
# SMTP setup and authentication involves a little more back-and-forth than IMAP as the default is STARTTLS...
str_data = byte_data.decode('utf-8', 'replace').rstrip('\r\n')
# before we can do anything we need to intercept EHLO/HELO and add STARTTLS...
if self.ehlo is not None and self.starttls is not self.STARTTLS.COMPLETE:
if self.starttls is self.STARTTLS.PENDING:
self.send(b'STARTTLS\r\n')
self.starttls = self.STARTTLS.NEGOTIATING
elif self.starttls is self.STARTTLS.NEGOTIATING:
if str_data.startswith('220'):
ssl_context = ssl.create_default_context()
super().set_socket(ssl_context.wrap_socket(self.socket, server_hostname=self.server_address[0]))
self.starttls = self.STARTTLS.COMPLETE
Log.info(self.proxy_type, self.connection_info,
'[ Successfully negotiated SMTP STARTTLS connection - re-sending greeting ]')
self.send(b'%s\r\n' % self.ehlo.encode('utf-8')) # re-send original EHLO/HELO to server
else:
super().process_data(byte_data) # an error occurred - just send to the client and exit
self.client_connection.close()
# ...then, once we have the username and password we can respond to the '334 ' response with credentials
elif self.authentication_state is self.AUTH.STARTED and self.username is not None and self.password is not None:
if str_data.startswith('334'): # 334 = 'please send credentials' (note startswith; actually '334 ')
(success, result) = OAuth2Helper.get_oauth2_credentials(self.username, self.password,
self.connection_info)
if success:
self.authentication_state = self.AUTH.CREDENTIALS_SENT
self.send(OAuth2Helper.encode_oauth2_string(result), True)
self.send(b'\r\n')
self.authenticated_username = self.username
self.username = None
self.password = None
if not success:
# a local authentication error occurred - send details to the client and exit
super().process_data(
b'535 5.7.8 Authentication credentials invalid. %s\r\n' % result.encode('utf-8'))
self.client_connection.close()
return
else:
super().process_data(byte_data) # an error occurred - just send to the client and exit
self.client_connection.close()
elif self.authentication_state is self.AUTH.CREDENTIALS_SENT:
if str_data.startswith('235'):
Log.info(self.proxy_type, self.connection_info,
'[ Successfully authenticated SMTP connection - removing proxy ]')
self.client_connection.authenticated = True
super().process_data(byte_data)
else:
super().process_data(byte_data) # an error occurred - just send to the client and exit
self.client_connection.close()
else:
# intercept EHLO response AUTH capabilities and replace with what we can actually do
if str_data.startswith('250-'):
updated_response = re.sub(r'250-AUTH[\w ]+', '250-AUTH PLAIN LOGIN', str_data, flags=re.IGNORECASE)
super().process_data(b'%s\r\n' % updated_response.encode('utf-8'))
else:
super().process_data(byte_data) # a server->client interaction we don't handle; ignore
class OAuth2Proxy(asyncore.dispatcher):
"""Listen on SERVER_ADDRESS:SERVER_PORT, creating a ServerConnection + ClientConnection for each new connection"""
def __init__(self, proxy_type, local_address, server_address, custom_configuration):
asyncore.dispatcher.__init__(self)
self.proxy_type = proxy_type
self.local_address = local_address
self.server_address = server_address
self.custom_configuration = custom_configuration
self.client_connections = []
def info_string(self):
return '%s server at %s:%d proxying %s:%d' % (self.proxy_type, self.local_address[0], self.local_address[1],
self.server_address[0], self.server_address[1])
def handle_accepted(self, connection, address):
if MAX_CONNECTIONS <= 0 or len(self.client_connections) < MAX_CONNECTIONS:
try:
socket_map = {}
server_class = globals()['%sOAuth2ServerConnection' % self.proxy_type]
new_server_connection = server_class(socket_map, self.server_address, address, self,
self.custom_configuration)
client_class = globals()['%sOAuth2ClientConnection' % self.proxy_type]
new_client_connection = client_class(connection, socket_map, address, new_server_connection, self,
self.custom_configuration)
new_server_connection.client_connection = new_client_connection
self.client_connections.append(new_client_connection)
threading.Thread(target=self.run_server, args=(new_client_connection, socket_map, address),
name='EmailOAuth2Proxy-connection-%d' % address[1], daemon=True).start()
except ssl.SSLError:
error_text = '%s encountered an SSL error - is the server\'s starttls setting correct? Current ' \
'value: %s' % (self.info_string(), self.custom_configuration['starttls'])
Log.info(error_text)
connection.send(b'%s\r\n' % self.bye_message(error_text).encode('utf-8'))
connection.close()
else:
error_text = '%s rejecting new connection above MAX_CONNECTIONS limit of %d' % (
self.info_string(), MAX_CONNECTIONS)
Log.info(error_text)
connection.send(b'%s\r\n' % self.bye_message(error_text).encode('utf-8'))
connection.close()
@staticmethod
def run_server(client, socket_map, address):
try:
asyncore.loop(map=socket_map) # loop for a single connection thread
except Exception as e:
if not EXITING:
Log.info('Caught asyncore exception in', address, 'thread loop:', Log.error_string(e))
client.close()
def start(self):
Log.info('Starting %s' % self.info_string())
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind(self.local_address)
self.listen(1)
def remove_client(self, client):
if client in self.client_connections: # remove closed clients
self.client_connections.remove(client)
del client
def bye_message(self, error_text=None):
if self.proxy_type == 'IMAP':
return '* BYE %s' % ('Server shutting down' if error_text is None else error_text)
elif self.proxy_type == 'SMTP':
return '221 %s' % ('2.0.0 Service closing transmission channel' if error_text is None else error_text)
else:
return ''
def stop(self):
Log.info('Stopping %s' % self.info_string())
for connection in self.client_connections[:]: # iterate over a copy; remove (in close()) from original
connection.send(b'%s\r\n' % self.bye_message().encode('utf-8')) # try to exit gracefully
connection.close() # closes both client and server
self.close()
def restart(self):
self.stop()
self.start()
def handle_close(self):
# if we encounter an exception in asyncore, handle_close() is called; restart this server - typically one of:
# - (<class 'socket.gaierror'>:[Errno 8] nodename nor servname provided, or not known (asyncore.py|read)
# - (<class 'TimeoutError'>:[Errno 60] Operation timed out (asyncore.py|read)
# note - intentionally not overriding handle_error() so we see errors in the log rather than hiding them
Log.info('Unexpected close of proxy connection - restarting %s' % self.info_string())
try:
self.restart()
except Exception as e:
Log.info('Abandoning server restart of %s due to repeated exception: %s' % (self.info_string(),
Log.error_string(e)))
class AuthorisationWindow:
"""Used to dynamically add the missing get_title method to a pywebview window"""
# noinspection PyUnresolvedReferences
def get_title(self):
return self.title
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic,PyPep8Naming,PyUnusedLocal
class ProvisionalNavigationBrowserDelegate:
"""Used to dynamically give pywebview the ability to navigate to unresolved localhost URLs"""
# note: there is also webView_didFailProvisionalNavigation_withError_ as a broader alternative to these two
# callbacks, but using that means that window.get_current_url() returns None when the loaded handler is called
def webView_didStartProvisionalNavigation_(self, web_view, nav):
# called when a user action (i.e., clicking our external authorisation mode submit button) redirects locally
browser_view_instance = webview.platforms.cocoa.BrowserView.get_instance('webkit', web_view)
if browser_view_instance:
browser_view_instance.loaded.set()
def webView_didReceiveServerRedirectForProvisionalNavigation_(self, web_view, nav):
# called when the server initiates a local redirect
browser_view_instance = webview.platforms.cocoa.BrowserView.get_instance('webkit', web_view)
if browser_view_instance:
browser_view_instance.loaded.set()
# noinspection PyPackageRequirements,PyUnresolvedReferences,PyProtectedMember
class RetinaIcon(pystray.Icon):
"""Used to dynamically override the default pystray behaviour on macOS to support high-dpi ('retina') icons and
regeneration of the last activity time for each account every time the icon is clicked"""
if sys.platform == 'darwin':