forked from simonrob/email-oauth2-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemailproxy.py
2254 lines (1915 loc) · 122 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/POP/SMTP proxy that intercepts authenticate and login commands, transparently replacing them with OAuth
2.0 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) 2022 Simon Robinson'
__license__ = 'Apache 2.0'
__version__ = '2022-08-22' # ISO 8601 (YYYY-MM-DD)
import argparse
import base64
import binascii
import configparser
import datetime
import enum
import errno
import io
import json
import logging
import logging.handlers
import os
import pathlib
import plistlib
import queue
import re
import signal
import socket
import ssl
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import warnings
import wsgiref.simple_server
import wsgiref.util
import zlib
# asyncore is essential, but has been deprecated and will be removed in python 3.12 (see PEP 594)
# pyasyncore is our workaround, so suppress this warning until the proxy is rewritten in, e.g., asyncio
with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
import asyncore
# for encrypting/decrypting the locally-stored credentials
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
# for macOS-specific unified logging
if sys.platform == 'darwin':
# pyoslog *is* present; see youtrack.jetbrains.com/issue/PY-11963 (same for others with this suppressed inspection)
# noinspection PyPackageRequirements
import pyoslog
# by default the proxy is a GUI application with a menu bar/taskbar icon, but it is also useful in 'headless' contexts
# where not having to install GUI-only requirements can be helpful - see the proxy's readme and requirements-no-gui.txt
if not os.environ.get('EMAIL_OAUTH2_PROXY_REQUIREMENTS_NO_GUI', None):
import pkg_resources # from setuptools - used to check package versions and choose compatible methods
import pystray # the menu bar/taskbar GUI
import timeago # the last authenticated activity hint
from PIL import Image, ImageDraw, ImageFont # draw the menu bar icon from the TTF font stored in APP_ICON
# noinspection PyPackageRequirements
import webview # the popup authentication window (in default and `--external-auth` modes only)
# for macOS-specific functionality
if sys.platform == 'darwin':
# noinspection PyPackageRequirements
import AppKit # retina icon, menu update on click, native notifications and receiving system events
import PyObjCTools # SIGTERM handling (only needed when in GUI mode; `signal` is sufficient otherwise)
import SystemConfiguration # network availability monitoring
else:
# dummy implementations to allow use regardless of whether pystray or AppKit are available
# noinspection PyPep8Naming
class pystray:
class Icon:
pass
class AppKit:
class NSObject:
pass
APP_NAME = 'Email OAuth 2.0 Proxy'
APP_SHORT_NAME = 'emailproxy'
APP_PACKAGE = 'ac.robinson.email-oauth2-proxy'
# noinspection SpellCheckingInspection
APP_ICON = b'''eNp1Uc9rE0EUfjM7u1nyq0m72aQxpnbTbFq0TbJNNkGkNpVKb2mxtgjWsqRJU+jaQHOoeMlVeoiCHqQXrwX/gEK9efGgNy+C4MWbHjxER
DCJb3dTUdQH733zvW/ezHszQADAAy3gIFO+kdbW3lXWAUgRs2sV02igdoL8MfLctrHf6PeBAXBe5OL27r2acry6hPprdLleNbbiXfkUtRfoeh0T4gaju
O6gT9TN5gEWo5GHGNjuXsVAPET+yuKmcdAAETaRR5BfuGuYVRCs/fQjBqGxt98En80/WzpYvaN3tPsvN4eufAWPc/r707dvLPyg/PiCcMSAq1n9AgXHs
MbeedvZz+zMH0YGZ99x7v9LxwyzpuBBpA8oTg9tB8kn0IiIHQLPwT9tuba4BfNQhervPZzdMGBWp1a9hJHYyHBeS2Y2r+I/2LF/9Ku3Q7tXZ9ogJKEEN
+EWbODRqpoaFwRXUJbDvK4Xghlek+WQ5KfKDM3N0dlshiQEQVHzuYJeKMxRVMNhWRISClYmc6qaUPxUitNZTdfz2QyfcmXIOK8xoOZKt7ViUkRqYXekW
J6Sp0urC5fCken5STr0KDoUlyhjVd4nxSUvq3tCftEn8r2ro+mxUDIaCMQmQrGZGHmi53tAT3rPGH1e3qF0p9w7LtcohwuyvnRxWZ8sZUej6WvlhXSk1
7k+POJ1iR73N/+w2xN0f4+GJcHtfqoWzgfi6cuZscC54lSq3SbN1tmzC4MXtcwN/zOC78r9BIfNc3M=''' # TTF ('e') -> zlib -> base64
CENSOR_MESSAGE = b'[[ Credentials removed from proxy log ]]' # replaces actual credentials; must be a byte-type string
CONFIG_FILE_PATH = '%s/%s.config' % (os.path.dirname(os.path.realpath(__file__)), APP_SHORT_NAME)
CONFIG_SERVER_MATCHER = re.compile(r'^(?P<type>(IMAP|POP|SMTP))-(?P<port>\d+)$')
MAX_CONNECTIONS = 0 # maximum concurrent IMAP/POP/SMTP connections; 0 = no limit; limit is per server
# maximum number of bytes to read from the socket at a time (limit is per socket)
RECEIVE_BUFFER_SIZE = 65536
# IMAP/POP/SMTP require \r\n as a line terminator (we use lines only pre-authentication; afterwards just pass through)
LINE_TERMINATOR = b'\r\n'
LINE_TERMINATOR_LENGTH = len(LINE_TERMINATOR)
# 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_TAG_PATTERN = r"[!#$&',-\[\]-z|}~]+" # https://ietf.org/rfc/rfc9051.html#name-formal-syntax
IMAP_AUTHENTICATION_REQUEST_MATCHER = re.compile(
r'^(?P<tag>%s) (?P<command>(LOGIN|AUTHENTICATE)) (?P<flags>.*)$' % IMAP_TAG_PATTERN, flags=re.IGNORECASE)
IMAP_CAPABILITY_MATCHER = re.compile(r'^(\* |\* OK \[)CAPABILITY .*$', flags=re.IGNORECASE) # note: '* ' and '* OK ['
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><head><script type="text/javascript">function copyLink(targetLink){
var copySource=document.createElement('textarea');copySource.value=targetLink;copySource.style.position='absolute';
copySource.style.left='-9999px';document.body.appendChild(copySource);copySource.select();
document.execCommand('copy');document.body.removeChild(copySource);
document.getElementById('copy').innerText='✔'}</script><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></head><body>
<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>
<a id="copy" onclick="copyLink('%s')" style="margin-left:0.5em;margin-top:0.1em;font-weight:bold;font-size:150%%;
text-decoration:none;cursor:pointer;float:right" title="Copy link">⧉</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 at the bottom of this page 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.''' + (
' If you are using Windows, submitting can take a few seconds.' if sys.platform == 'win32' else '') + '''</p>
<p style="margin-top:2em">According to your proxy configuration file, the expected 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);
document.auth.submit.value='Submitting...'; document.auth.submit.disabled=true; 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;width:65%%"><input type="submit"
id="submit" value="Submit"></div></form></body></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
_HANDLER = None
_DATE_FORMAT = '%Y-%m-%d %H:%M:%S:'
_SYSLOG_MESSAGE_FORMAT = '%s: %%(message)s' % APP_NAME
_MACOS_USE_SYSLOG = not pyoslog.is_supported() if sys.platform == 'darwin' else False
@staticmethod
def initialise():
Log._LOGGER = logging.getLogger(APP_NAME)
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'))
elif sys.platform == 'darwin':
if Log._MACOS_USE_SYSLOG: # syslog prior to 10.12
handler = logging.handlers.SysLogHandler(address='/var/run/syslog')
handler.setFormatter(logging.Formatter(Log._SYSLOG_MESSAGE_FORMAT))
else: # unified logging in 10.12+
handler = pyoslog.Handler()
handler.setSubsystem(APP_PACKAGE)
else:
if os.path.exists('/dev/log'):
handler = logging.handlers.SysLogHandler(address='/dev/log')
handler.setFormatter(logging.Formatter(Log._SYSLOG_MESSAGE_FORMAT))
else:
handler = logging.StreamHandler()
Log._HANDLER = handler
Log._LOGGER.addHandler(Log._HANDLER)
Log.set_level(logging.INFO)
@staticmethod
def get_level():
return Log._LOGGER.getEffectiveLevel()
@staticmethod
def set_level(level):
# set both handler and logger level as we just want a direct mapping input->output
Log._HANDLER.setLevel(level)
Log._LOGGER.setLevel(level)
@staticmethod
def _log(level_method, level, *args):
message = ' '.join(map(str, args))
if Log.get_level() <= level:
print(datetime.datetime.now().strftime(Log._DATE_FORMAT), message)
if len(message) > 2048 and (sys.platform not in ['win32', 'darwin'] or Log._MACOS_USE_SYSLOG):
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._SYSLOG_MESSAGE_FORMAT) - len(truncation_message)] + truncation_message
# note: need LOG_ALERT (i.e., warning) or higher to show in syslog on macOS
severity = Log._LOGGER.warning if Log._MACOS_USE_SYSLOG else level_method
severity(message)
@staticmethod
def debug(*args):
Log._log(Log._LOGGER.debug, logging.DEBUG, *args)
@staticmethod
def info(*args):
Log._log(Log._LOGGER.info, logging.INFO, *args)
@staticmethod
def error(*args):
Log._log(Log._LOGGER.error, logging.ERROR, *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
_GLOBALS = None
_SERVERS = []
_ACCOUNTS = []
@staticmethod
def _load():
AppConfig.unload()
AppConfig._PARSER = configparser.ConfigParser()
AppConfig._PARSER.read(CONFIG_FILE_PATH)
config_sections = AppConfig._PARSER.sections()
if APP_SHORT_NAME in config_sections:
AppConfig._GLOBALS = AppConfig._PARSER[APP_SHORT_NAME]
else:
AppConfig._GLOBALS = configparser.SectionProxy(AppConfig._PARSER, APP_SHORT_NAME)
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._GLOBALS = None
AppConfig._SERVERS = []
AppConfig._ACCOUNTS = []
@staticmethod
def reload():
AppConfig.unload()
return AppConfig.get()
@staticmethod
def globals():
AppConfig.get() # make sure config is loaded
return AppConfig._GLOBALS
@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.error('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)
redirect_listen_address = config.get(username, 'redirect_listen_address', fallback=None)
client_id = config.get(username, 'client_id', fallback=None)
client_secret = config.get(username, 'client_secret', fallback=None)
# note that we don't require client_secret here because it can be optional for Office 365 configurations
if not (permission_url and token_url and oauth2_scope and redirect_uri and client_id):
Log.error('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))
# while not technically forbidden (RFC 6749, A.1 and A.2), it is highly unlikely the example value is valid
example_client_value = '*** your client'
example_client_status = [example_client_value in i for i in [client_id, client_secret] if i]
if any(example_client_status):
if all(example_client_status) or example_client_value in client_id:
Log.info('Warning: client configuration for account', username, 'seems to contain example values -',
'if authentication fails, please double-check these values are correct')
elif example_client_value in client_secret:
Log.info('Warning: client secret for account', username, 'seems to contain the example value - if you',
'are using an Office 365 setup that does not need a secret, please delete this line entirely;',
'otherwise, if authentication fails, please double-check this value is correct')
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, username)
# note: get_oauth2_authorisation_code is a blocking call
success, authorisation_code = OAuth2Helper.get_oauth2_authorisation_code(permission_url, redirect_uri,
redirect_listen_address,
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']))
if 'refresh_token' in response:
config.set(username, 'refresh_token',
OAuth2Helper.encrypt(cryptographer, response['refresh_token']))
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 remove our cached version and re-authenticate - this can
# be disabled by a configuration setting, but note that we always remove credentials on 400 Bad Request
if e.args == (400, APP_PACKAGE) or AppConfig.globals().getboolean('delete_account_token_on_password_error',
fallback=True):
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()
else:
recurse_retries = False # no need to recurse if we are just trying the same credentials again
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)
else:
Log.error('Invalid password to decrypt', username, 'credentials - aborting login:', Log.error_string(e))
return False, '%s: Login failed - the password for account %s is incorrect' % (APP_NAME, username)
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: URLError(OSError(50, 'Network is down'))) rather than e.g., bad requests
Log.info('Caught exception while requesting OAuth 2.0 credentials:', Log.error_string(e))
return False, '%s: Login failed for account %s - please check your internet connection and retry' % (
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 start_redirection_receiver_server(token_request):
"""Starts a local WSGI web server at token_request['redirect_uri'] to receive OAuth responses"""
wsgi_address = token_request['redirect_listen_address'] if token_request['redirect_listen_address'] else \
token_request['redirect_uri']
parsed_uri = urllib.parse.urlparse(wsgi_address)
parsed_port = 80 if parsed_uri.port is None else parsed_uri.port
Log.debug('Local server auth mode (%s:%d): starting server to listen for authentication response' % (
parsed_uri.hostname, parsed_port))
class LoggingWSGIRequestHandler(wsgiref.simple_server.WSGIRequestHandler):
def log_message(self, format_string, *args):
Log.debug('Local server auth mode (%s:%d): received authentication response' % (
parsed_uri.hostname, parsed_port), *args)
class RedirectionReceiverWSGIApplication:
def __call__(self, environ, start_response):
start_response('200 OK', [('Content-type', 'text/html; charset=utf-8')])
token_request['response_url'] = wsgiref.util.request_uri(environ)
return [('<html><head><title>%s authentication complete (%s)</title><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></head><body><p>%s successfully authenticated account %s.</p><p>You can close this '
'window.</p></body></html>' % ((APP_NAME, token_request['username']) * 2)).encode('utf-8')]
try:
wsgiref.simple_server.WSGIServer.allow_reuse_address = False
redirection_server = wsgiref.simple_server.make_server(str(parsed_uri.hostname), parsed_port,
RedirectionReceiverWSGIApplication(),
handler_class=LoggingWSGIRequestHandler)
token_request['local_server_auth_wsgi'] = redirection_server
Log.info('Please visit the following URL to authenticate account %s: %s' %
(token_request['username'], token_request['permission_url']))
redirection_server.handle_request()
redirection_server.server_close()
Log.debug('Local server auth mode (%s:%d): closing local server and returning response' % (
parsed_uri.hostname, parsed_port), token_request['response_url'])
del token_request['local_server_auth']
del token_request['local_server_auth_wsgi']
RESPONSE_QUEUE.put(token_request)
except socket.error as e:
Log.error('Local server auth mode (%s:%d): unable to start local server. Please check that the %s for '
'account %s is unique across accounts, specifies a port number, and is not already in use. See '
'the documentation in the proxy\'s sample configuration file for further detail' % (
parsed_uri.hostname, parsed_port,
'redirect_listen_address' if token_request['redirect_listen_address'] else 'redirect_uri',
token_request['username']), Log.error_string(e))
@staticmethod
def construct_oauth2_permission_url(permission_url, redirect_uri, client_id, scope, username):
"""Constructs and returns the URL to request permission for this client to access the given scope, hinting
the username where possible (note that delegated accounts without direct login enabled will need to select the
'Sign in with another account' option)"""
params = {'client_id': client_id, 'redirect_uri': redirect_uri, 'scope': scope, 'response_type': 'code',
'access_type': 'offline', 'login_hint': username}
param_pairs = []
for param in params:
param_pairs.append('%s=%s' % (param, OAuth2Helper.oauth2_url_escape(params[param])))
return '%s?%s' % (permission_url, '&'.join(param_pairs))
@staticmethod
def get_oauth2_authorisation_code(permission_url, redirect_uri, redirect_listen_address, 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, 'redirect_listen_address': redirect_listen_address,
'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
if 'local_server_auth_wsgi' in token_request:
token_request['local_server_auth_wsgi'].server_close()
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
# to improve no-GUI mode we also support the use of a local server to receive the OAuth redirection
# (note: not enabled by default because no-GUI mode is typically unattended, but useful in some cases)
if 'local_server_auth' in data:
threading.Thread(target=OAuth2Helper.start_redirection_receiver_server, args=(data,),
name='EmailOAuth2Proxy-auth-%s' % data['username'], daemon=True).start()
else:
if 'response_url' in data 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'}
if not client_secret:
del params['client_secret'] # client secret can be optional for O365, but we don't want a None entry
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:
Log.debug('Error requesting access token - received invalid response:', json.loads(e.read()))
raise e
@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'}
if not client_secret:
del params['client_secret'] # client secret can be optional for O365, but we don't want a None entry
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:
Log.debug('Error refreshing access token - received invalid response:', json.loads(e.read()))
if e.code == 400: # 400 Bad Request typically means re-authentication is required (refresh token expired)
raise InvalidToken(e.code, APP_PACKAGE)
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 shouldn'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:
# formal syntax: https://tools.ietf.org/html/rfc4616#section-2
_, 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/POP/SMTP client interaction (note that there
is some protocol-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.receive_buffer = b''
self.proxy_type = proxy_type
self.connection_info = connection_info
self.server_connection = server_connection
self.local_address = proxy_parent.local_address
self.server_address = server_connection.server_address
self.proxy_parent = proxy_parent
self.custom_configuration = custom_configuration
self.censor_next_log = False # try to avoid logging credentials
self.authenticated = False
self.ssl_handshake_completed = not (
custom_configuration['local_certificate_path'] and custom_configuration['local_key_path'])
def info_string(self):
if Log.get_level() == logging.DEBUG:
return '%s (%s:%d; %s:%d->%s:%d%s)' % (
self.proxy_type, self.local_address[0], self.local_address[1], self.connection_info[0],
self.connection_info[1], self.server_address[0], self.server_address[1],
'; %s' % self.server_connection.authenticated_username if
self.server_connection and self.server_connection.authenticated_username else '')
else:
return '%s (%s:%d)' % (self.proxy_type, self.local_address[0], self.local_address[1])
def ssl_handshake(self):
try:
# noinspection PyUnresolvedReferences
self.socket.do_handshake()
except (ssl.SSLWantReadError, ssl.SSLWantWriteError): # only relevant when using local certificates
return
else:
Log.debug(self.info_string(), '[ SSL/TLS handshake complete ]')
self.ssl_handshake_completed = True
def readable(self):
return super().readable() and self.ssl_handshake_completed
def writable(self):
return super().writable() and self.ssl_handshake_completed
def handle_read(self):
if not self.ssl_handshake_completed:
self.ssl_handshake()
return
byte_data = self.recv(RECEIVE_BUFFER_SIZE)
if not byte_data:
return
# client is established after server; this state should not happen unless already closing
if not self.server_connection:
Log.debug(self.info_string(), '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
if self.authenticated:
Log.debug(self.info_string(), '-->', byte_data)
OAuth2ClientConnection.process_data(self, byte_data)
# if not authenticated, buffer incoming data and process line-by-line (slightly more involved than the server
# connection because we censor commands that contain passwords or authentication tokens)
else:
self.receive_buffer += byte_data
complete_lines = []
while True:
terminator_index = self.receive_buffer.find(LINE_TERMINATOR)
if terminator_index != -1:
split_position = terminator_index + LINE_TERMINATOR_LENGTH
complete_lines.append(self.receive_buffer[:split_position])
self.receive_buffer = self.receive_buffer[split_position:]
else:
break
for line in complete_lines:
# try to remove credentials from logged data - both inline (via regex) and as separate requests
if self.censor_next_log:
log_data = CENSOR_MESSAGE
self.censor_next_log = False
else:
# IMAP LOGIN command with inline username/password, POP PASS and IMAP/POP/SMTP AUTH(ENTICATE)
tag_pattern = IMAP_TAG_PATTERN.encode('utf-8')
log_data = re.sub(b'(%s) (LOGIN) (.*)\r\n' % tag_pattern, b'\\1 \\2 %s\r\n' % CENSOR_MESSAGE,
line, flags=re.IGNORECASE)
log_data = re.sub(b'(PASS) (.*)\r\n', b'\\1 %s\r\n' % CENSOR_MESSAGE, log_data, flags=re.IGNORECASE)
log_data = re.sub(b'(%s)?( ?)(AUTH)(ENTICATE)? (PLAIN|LOGIN) (.*)\r\n' % tag_pattern,
b'\\1\\2\\3\\4 \\5 %s\r\n' % CENSOR_MESSAGE, log_data, flags=re.IGNORECASE)
Log.debug(self.info_string(), '-->', log_data)
self.process_data(line)
def process_data(self, byte_data, censor_server_log=False):
try:
self.server_connection.send(byte_data, censor_log=censor_server_log) # default = send everything to server
except AttributeError as e:
Log.info(self.info_string(), 'Caught client exception; server connection closed before data could be sent:',
Log.error_string(e))
self.close()
def send(self, byte_data):
while not self.ssl_handshake_completed:
self.ssl_handshake()
Log.debug(self.info_string(), '<--', byte_data)
super().send(byte_data)
def log_info(self, message, message_type='info'):
# override to redirect error messages to our own log
if message_type not in self.ignore_log_types:
Log.info(self.info_string(), 'Caught asyncore info message (client) -', message_type, ':', message)
def handle_close(self):
Log.debug(self.info_string(), '--> [ 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 (note: space after response code is mandatory)
else:
# we don't support any other methods - let the server handle this
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), censor_server_log=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 POPOAuth2ClientConnection(OAuth2ClientConnection):
"""The client side of the connection - watch for AUTH, USER and PASS commands and replace with OAuth 2.0"""
class STATE(enum.Enum):
PENDING = 1
CAPA_AWAITING_RESPONSE = 2
AUTH_PLAIN_AWAITING_CREDENTIALS = 3
USER_AWAITING_PASS = 4
XOAUTH2_AWAITING_CONFIRMATION = 5
XOAUTH2_CREDENTIALS_SENT = 6
def __init__(self, connection, socket_map, connection_info, server_connection, proxy_parent, custom_configuration):
super().__init__('POP', connection, socket_map, connection_info, server_connection, proxy_parent,
custom_configuration)
self.connection_state = self.STATE.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()
if self.connection_state is self.STATE.PENDING:
if str_data_lower == 'capa':
self.server_connection.capa = []
self.connection_state = self.STATE.CAPA_AWAITING_RESPONSE
super().process_data(byte_data)
elif str_data_lower == 'auth': # a bare 'auth' command is another way to request capabilities
self.send(b'+OK\r\nPLAIN\r\n.\r\n') # no need to actually send to the server - we know what we support
elif str_data_lower.startswith('auth plain'):
if len(str_data) > 11: # 11 = len('AUTH PLAIN ') - 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.connection_state = self.STATE.AUTH_PLAIN_AWAITING_CREDENTIALS
self.censor_next_log = True
self.send(b'+ \r\n') # request details
elif str_data_lower.startswith('user'):
self.server_connection.username = str_data[5:] # 5 = len('USER ')
self.connection_state = self.STATE.USER_AWAITING_PASS
self.send(b'+OK\r\n') # request password
else:
super().process_data(byte_data) # some other command that we don't handle - pass directly to server
elif self.connection_state is self.STATE.AUTH_PLAIN_AWAITING_CREDENTIALS:
if str_data == '*': # request cancelled by the client - reset state (must be a negative response)
self.connection_state = self.STATE.PENDING
self.send(b'-ERR\r\n')
else:
self.server_connection.username, self.server_connection.password = OAuth2Helper.decode_credentials(
str_data)
self.send_authentication_request()
elif self.connection_state is self.STATE.USER_AWAITING_PASS:
if str_data_lower.startswith('pass'):
self.server_connection.password = str_data[5:] # 5 = len('PASS ')
self.send_authentication_request()
else:
# the only valid input here is PASS (above) or QUIT
self.send(b'+OK Bye\r\n')
self.close()
else:
super().process_data(byte_data) # some other command that we don't handle - pass directly to server
def send_authentication_request(self):
self.connection_state = self.STATE.XOAUTH2_AWAITING_CONFIRMATION
super().process_data(b'AUTH XOAUTH2\r\n')
class SMTPOAuth2ClientConnection(OAuth2ClientConnection):
"""The client side of the connection - intercept AUTH PLAIN and AUTH LOGIN commands and replace with OAuth 2.0"""
class STATE(enum.Enum):
PENDING = 1
EHLO_AWAITING_RESPONSE = 2
AUTH_PLAIN_AWAITING_CREDENTIALS = 3
AUTH_LOGIN_AWAITING_USERNAME = 4
AUTH_LOGIN_AWAITING_PASSWORD = 5
XOAUTH2_AWAITING_CONFIRMATION = 6
XOAUTH2_CREDENTIALS_SENT = 7
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.connection_state = self.STATE.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 correct capabilities and replay after STARTTLS if needed (in server connection class)
if self.connection_state is self.STATE.PENDING:
if str_data_lower.startswith('ehlo') or str_data_lower.startswith('helo'):
self.connection_state = self.STATE.EHLO_AWAITING_RESPONSE
self.server_connection.ehlo = byte_data # save the command so we can replay later if needed (STARTTLS)
super().process_data(byte_data) # don't just go to STARTTLS - most servers require EHLO first
# intercept AUTH PLAIN and AUTH LOGIN to replace with AUTH XOAUTH2
elif str_data_lower.startswith('auth plain'):
if len(str_data) > 11: # 11 = len('AUTH PLAIN ') - 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.connection_state = self.STATE.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 str_data_lower.startswith('auth login'):
if len(str_data) > 11: # 11 = len('AUTH LOGIN ') - this method can have the username either inline...
self.decode_username_and_request_password(str_data[11:])
else: # ...or requested separately
self.connection_state = self.STATE.AUTH_LOGIN_AWAITING_USERNAME
self.send(b'334 %s\r\n' % base64.b64encode(b'Username:'))
else:
super().process_data(byte_data) # some other command that we don't handle - pass directly to server
elif self.connection_state is self.STATE.AUTH_PLAIN_AWAITING_CREDENTIALS:
self.server_connection.username, self.server_connection.password = OAuth2Helper.decode_credentials(
str_data)
self.send_authentication_request()
elif self.connection_state is self.STATE.AUTH_LOGIN_AWAITING_USERNAME:
self.decode_username_and_request_password(str_data)
elif self.connection_state is self.STATE.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 decode_username_and_request_password(self, encoded_username):
try:
self.server_connection.username = base64.b64decode(encoded_username).decode('utf-8')
except binascii.Error:
self.server_connection.username = ''
self.connection_state = self.STATE.AUTH_LOGIN_AWAITING_PASSWORD
self.censor_next_log = True
self.send(b'334 %s\r\n' % base64.b64encode(b'Password:'))
def send_authentication_request(self):
self.connection_state = self.STATE.XOAUTH2_AWAITING_CONFIRMATION
super().process_data(b'AUTH XOAUTH2\r\n')