Repository navigation
Expand file tree
/
Copy pathsmtp.py
More file actions
1551 lines (1397 loc) · 61.4 KB
/
Copy pathsmtp.py
File metadata and controls
1551 lines (1397 loc) · 61.4 KB
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
# Copyright 2014-2021 The aiosmtpd Developers
# SPDX-License-Identifier: Apache-2.0
import asyncio
import asyncio.sslproto as sslproto
import binascii
import collections
import enum
import inspect
import logging
import re
import socket
import ssl
from base64 import b64decode, b64encode
from email._header_value_parser import get_addr_spec, get_angle_addr
from email.errors import HeaderParseError
from typing import (
Any,
AnyStr,
Awaitable,
Callable,
Dict,
Iterable,
List,
MutableMapping,
NamedTuple,
Optional,
Protocol,
Sequence,
Tuple,
TypeVar,
Union,
)
from warnings import warn
import attr
from public import public
from aiosmtpd import __version__, _get_or_new_eventloop
from aiosmtpd.proxy_protocol import ProxyData, get_proxy
# region #### Custom Data Types #######################################################
class _Missing(enum.Enum):
MISSING = object()
class _AuthMechAttr(NamedTuple):
method: "AuthMechanismType"
is_builtin: bool
class _DataState(enum.Enum):
NOMINAL = enum.auto()
TOO_LONG = enum.auto()
TOO_MUCH = enum.auto()
AuthCallbackType = Callable[[str, bytes, bytes], bool]
AuthenticatorType = Callable[["SMTP", "Session", "Envelope", str, Any], "AuthResult"]
AuthMechanismType = Callable[["SMTP", List[str]], Awaitable[Any]]
_TriStateType = Union[None, _Missing, bytes]
RT = TypeVar("RT") # "ReturnType"
DecoratorType = Callable[[Callable[..., RT]], Callable[..., RT]]
# IPv4, IPv6, UNIX socket, not set
PeerType = Union[tuple[str, int], tuple[str, int, int, int], str, None]
# endregion
# region #### Constant & Constant-likes ###############################################
__all__ = [
"AuthCallbackType",
"AuthMechanismType",
"MISSING",
"__version__",
] # Will be added to by @public
__ident__ = 'Python SMTP {}'.format(__version__)
log = logging.getLogger('mail.log')
BOGUS_LIMIT = 5
CALL_LIMIT_DEFAULT = 20
DATA_SIZE_DEFAULT = 2**25 # Where does this number come from, I wonder...
EMPTY_BARR = bytearray()
EMPTYBYTES = b''
MISSING = _Missing.MISSING
VALID_AUTHMECH = re.compile(r"[A-Z0-9_-]+\Z")
# https://tools.ietf.org/html/rfc3207.html#page-3
ALLOWED_BEFORE_STARTTLS = {"NOOP", "EHLO", "STARTTLS", "QUIT"}
# Auth hiding regexes
CLIENT_AUTH_B = re.compile(
# Matches "AUTH" <mechanism> <whitespace_but_not_\r_nor_\n>
br"(?P<authm>\s*AUTH\s+\S+[^\S\r\n]+)"
# Param to AUTH <mechanism>. We only need to sanitize if param is given, which
# for some mechanisms contain sensitive info. If no param is given, then we
# can skip (match fails)
br"(\S+)"
# Optional bCRLF at end. Why optional? Because we also want to sanitize the
# stripped line. If no bCRLF, then this group will be b""
br"(?P<crlf>(?:\r\n)?)", re.IGNORECASE
)
"""Regex that matches 'AUTH <mech> <param>' commend"""
# endregion
@attr.s
class AuthResult:
"""
Contains the result of authentication, to be returned to the smtp_AUTH method.
All initialization arguments _must_ be keyworded!
"""
success: bool = attr.ib(kw_only=True)
"""Indicates authentication is successful or not"""
handled: bool = attr.ib(kw_only=True, default=True)
"""
True means everything (including sending of status code) has been handled by the
AUTH handler and smtp_AUTH should not do anything else.
Applicable only if success == False.
"""
message: Optional[str] = attr.ib(kw_only=True, default=None)
"""
Optional message for additional handling by smtp_AUTH.
Applicable only if handled == False.
"""
auth_data: Optional[Any] = attr.ib(kw_only=True, default=None, repr=lambda x: "...")
"""
Optional free-form authentication data. For the built-in mechanisms, it is usually
an instance of LoginPassword. Other implementations are free to use any data
structure here.
"""
@public
class LoginPassword(NamedTuple):
login: bytes
password: bytes
def __str__(self) -> str:
return f"LoginPassword(login='{self.login.decode()}', password=...)"
def __repr__(self) -> str:
return str(self)
@public
class Session:
def __init__(self, loop: asyncio.AbstractEventLoop):
self.peer: PeerType = None
self.ssl: Optional[dict[str, Any]] = None
self.host_name: Optional[str] = None
self.extended_smtp = False
self.loop = loop
self.proxy_data: Optional[ProxyData] = None
"""Data from PROXY Protocol handshake"""
self._login_data = None
self.auth_data = None
"""
New system *optional* authentication data;
can contain anything returned by the authenticator callback.
Can even be None; check `authenticated` attribute to determine
if AUTH successful or not.
"""
self.authenticated: Optional[bool] = None
@property
def login_data(self) -> Any:
"""Legacy login_data, usually containing the username"""
log.warning(
"Session.login_data is deprecated and will be removed in version 2.0"
)
return self._login_data
@login_data.setter
def login_data(self, value: Any) -> None:
log.warning(
"Session.login_data is deprecated and will be removed in version 2.0"
)
self._login_data = value
@public
class Envelope:
def __init__(self) -> None:
self.mail_from: Optional[str] = None
self.mail_options: List[str] = []
self.smtp_utf8 = False
self.content: Union[None, bytes, str] = None
self.original_content: Optional[bytes] = None
self.rcpt_tos: List[str] = []
self.rcpt_options: List[str] = []
# This is here to enable debugging output when the -E option is given to the
# unit test suite. In that case, this function is mocked to set the debug
# level on the loop (as if PYTHONASYNCIODEBUG=1 were set).
def make_loop() -> asyncio.AbstractEventLoop:
return _get_or_new_eventloop()
@public
def syntax(
text: str, extended: Optional[str] = None, when: Optional[str] = None
) -> DecoratorType:
"""
A @decorator that provides helptext for (E)SMTP HELP.
Applies for smtp_* methods only!
:param text: Help text for (E)SMTP HELP
:param extended: Additional text for ESMTP HELP (appended to text)
:param when: The name of the attribute of SMTP class to check; if the value
of the attribute is false-y then HELP will not be available for the command
"""
def decorator(f: Callable[..., RT]) -> Callable[..., RT]:
f.__smtp_syntax__ = text # type: ignore[attr-defined]
f.__smtp_syntax_extended__ = extended # type: ignore[attr-defined]
f.__smtp_syntax_when__ = when # type: ignore[attr-defined]
return f
return decorator
@public
def auth_mechanism(actual_name: str) -> DecoratorType:
"""
A @decorator to explicitly specifies the name of the AUTH mechanism implemented by
the function/method this decorates
:param actual_name: Name of AUTH mechanism. Must consists of [A-Z0-9_-] only.
Will be converted to uppercase
"""
def decorator(f: Callable[..., RT]) -> Callable[..., RT]:
f.__auth_mechanism_name__ = actual_name # type: ignore[attr-defined]
return f
actual_name = actual_name.upper()
if not VALID_AUTHMECH.match(actual_name):
raise ValueError(f"Invalid AUTH mechanism name: {actual_name}")
return decorator
def login_always_fail(
mechanism: str, login: bytes, password: bytes
) -> bool:
return False
def is_int(o: Any) -> bool:
return isinstance(o, int)
# This could be an inline expression but is a separate function
# for easier mocking in tests
def len_contents(lst: list[bytes]) -> int:
return sum(len(b) for b in lst)
@public
class TLSSetupException(Exception):
pass
@public
def sanitize(text: bytes) -> bytes:
m = CLIENT_AUTH_B.match(text)
if m:
return m.group("authm") + b"********" + m.group("crlf")
return text
@public
def sanitized_log(func: Callable[..., None], msg: AnyStr, *args, **kwargs) -> None:
"""
Sanitize args before passing to a logging function.
"""
sanitized_args = [
sanitize(a) if isinstance(a, bytes) else a
for a in args
]
func(msg, *sanitized_args, **kwargs)
@public
class SMTP(asyncio.StreamReaderProtocol):
"""
`Documentation can be found here
<https://aiosmtpd.readthedocs.io/en/latest/smtp.html>`_
"""
command_size_limit = 512
command_size_limits: Dict[str, int] = collections.defaultdict(
lambda: SMTP.command_size_limit)
line_length_limit = 1001
"""Maximum line length according to RFC 5321 s 4.5.3.1.6"""
# The number comes from this calculation:
# (RFC 5322 s 2.1.1 + RFC 6532 s 3.4) 998 octets + CRLF = 1000 octets
# (RFC 5321 s 4.5.3.1.6) 1000 octets + "transparent dot" = 1001 octets
local_part_limit: int = 0
"""
Maximum local part length. (RFC 5321 § 4.5.3.1.1 specifies 64, but lenient)
If 0 or Falsey, local part length is unlimited.
"""
AuthLoginUsernameChallenge = "User Name\x00"
AuthLoginPasswordChallenge = "Password\x00"
def __init__(
self,
handler: Any,
*,
data_size_limit: Optional[int] = DATA_SIZE_DEFAULT,
enable_SMTPUTF8: bool = False,
decode_data: bool = False,
hostname: Optional[str] = None,
ident: Optional[str] = None,
tls_context: Optional[ssl.SSLContext] = None,
require_starttls: bool = False,
timeout: float = 300,
auth_required: bool = False,
auth_require_tls: bool = True,
auth_exclude_mechanism: Optional[Iterable[str]] = None,
auth_callback: Optional[AuthCallbackType] = None,
command_call_limit: Union[int, Dict[str, int], None] = None,
authenticator: Optional[AuthenticatorType] = None,
proxy_protocol_timeout: Optional[Union[int, float]] = None,
loop: Optional[asyncio.AbstractEventLoop] = None
):
self.__ident__ = ident or __ident__
self.loop = loop if loop else make_loop()
super().__init__(
asyncio.StreamReader(loop=self.loop, limit=self.line_length_limit),
client_connected_cb=self._cb_client_connected,
loop=self.loop)
self.event_handler = handler
assert data_size_limit is None or isinstance(data_size_limit, int)
self.data_size_limit = data_size_limit
self.enable_SMTPUTF8 = enable_SMTPUTF8
self._decode_data = decode_data
self.command_size_limits.clear()
if hostname:
self.hostname = hostname
else:
self.hostname = socket.getfqdn()
self.tls_context = tls_context
if tls_context:
if (tls_context.verify_mode
not in {ssl.CERT_NONE, ssl.CERT_OPTIONAL}): # noqa: DUO122
log.warning("tls_context.verify_mode not in {CERT_NONE, "
"CERT_OPTIONAL}; this might cause client "
"connection problems")
elif tls_context.check_hostname:
log.warning("tls_context.check_hostname == True; "
"this might cause client connection problems")
self.require_starttls = tls_context and require_starttls
self._timeout_duration = timeout
self._timeout_handle: Optional[asyncio.TimerHandle] = None
self._tls_handshake_okay = True
self._tls_protocol: Optional[sslproto.SSLProtocol] = None
self._original_transport: Optional[asyncio.BaseTransport] = None
self.session: Optional[Session] = None
self.envelope: Optional[Envelope] = None
self.transport: Optional[asyncio.BaseTransport] = None
self._handler_coroutine: Optional[asyncio.Task[None]] = None
if not auth_require_tls and auth_required:
warn("Requiring AUTH while not requiring TLS "
"can lead to security vulnerabilities!")
log.warning("auth_required == True but auth_require_tls == False")
self._auth_require_tls = auth_require_tls
if proxy_protocol_timeout is not None:
if proxy_protocol_timeout <= 0:
raise ValueError("proxy_protocol_timeout must be > 0")
elif proxy_protocol_timeout < 3.0:
log.warning("proxy_protocol_timeout < 3.0")
self._proxy_timeout = proxy_protocol_timeout
self._authenticator: Optional[AuthenticatorType]
self._auth_callback: Optional[AuthCallbackType]
if authenticator is not None:
self._authenticator = authenticator
self._auth_callback = None
else:
self._auth_callback = auth_callback or login_always_fail
self._authenticator = None
self._auth_required = auth_required
# Get hooks & methods to significantly speedup getattr's
self._auth_methods: Dict[str, _AuthMechAttr] = {
getattr(
mfunc, "__auth_mechanism_name__",
mname.replace("auth_", "").replace("__", "-")
): _AuthMechAttr(mfunc, obj is self)
for obj in (self, handler)
for mname, mfunc in inspect.getmembers(obj)
if mname.startswith("auth_")
}
for m in (auth_exclude_mechanism or []):
self._auth_methods.pop(m, None)
log.info(
"Available AUTH mechanisms: "
+ " ".join(
m + "(builtin)" if impl.is_builtin else m
for m, impl in sorted(self._auth_methods.items())
)
)
self._handle_hooks: Dict[str, Callable] = {
m.replace("handle_", ""): getattr(handler, m)
for m in dir(handler)
if m.startswith("handle_")
}
# When we've deprecated the 4-arg form of handle_EHLO,
# we can -- and should -- remove this whole code block
ehlo_hook = self._handle_hooks.get("EHLO")
if ehlo_hook is None:
self._ehlo_hook_ver = None
else:
ehlo_hook_params = inspect.signature(ehlo_hook).parameters
if len(ehlo_hook_params) == 4:
self._ehlo_hook_ver = "old"
warn("Use the 5-argument handle_EHLO() hook instead of "
"the 4-argument handle_EHLO() hook; "
"support for the 4-argument handle_EHLO() hook will be "
"removed in version 2.0",
DeprecationWarning)
elif len(ehlo_hook_params) == 5:
self._ehlo_hook_ver = "new"
else:
raise RuntimeError("Unsupported EHLO Hook")
self._smtp_methods: Dict[str, Any] = {
m.replace("smtp_", ""): getattr(self, m)
for m in dir(self)
if m.startswith("smtp_")
}
self._call_limit_default: int
if command_call_limit is None:
self._enforce_call_limit = False
else:
self._enforce_call_limit = True
if isinstance(command_call_limit, int):
self._call_limit_base = {}
self._call_limit_default = command_call_limit
elif isinstance(command_call_limit, dict):
if not all(map(is_int, command_call_limit.values())):
raise TypeError("All command_call_limit values must be int")
self._call_limit_base = command_call_limit
self._call_limit_default = command_call_limit.get(
"*", CALL_LIMIT_DEFAULT
)
else:
raise TypeError("command_call_limit must be int or Dict[str, int]")
def _create_session(self) -> Session:
return Session(self.loop)
def _create_envelope(self) -> Envelope:
return Envelope()
async def _call_handler_hook(self, command: str, *args) -> Any:
hook = self._handle_hooks.get(command)
if hook is None:
return MISSING
status = await hook(self, self.session, self.envelope, *args)
return status
@property
def max_command_size_limit(self) -> int:
try:
return max(self.command_size_limits.values())
except ValueError:
return self.command_size_limit
def __del__(self): # pragma: nocover
# This is nocover-ed because the contents *totally* does NOT affect function-
# ality, and in addition this comes directly from StreamReaderProtocol.__del__()
# but with a getattr()+check addition to stop the annoying (but harmless)
# "exception ignored" messages caused by AttributeError when self._closed is
# missing (which seems to happen randomly).
closed = getattr(self, "_closed", None)
if closed is None:
return
if closed.done() and not closed.cancelled():
closed.exception()
def connection_made(self, transport: asyncio.BaseTransport) -> None:
# Reset state due to rfc3207 part 4.2.
self._set_rset_state()
self.session = self._create_session()
self.session.peer = transport.get_extra_info('peername')
self._reset_timeout()
seen_starttls = (self._original_transport is not None)
if self.transport is not None and seen_starttls:
# It is STARTTLS connection over normal connection.
self._reader._transport = transport # type: ignore[attr-defined]
self._writer._transport = transport # type: ignore[attr-defined]
self.transport = transport
# Discard any leftover unencrypted data
# See https://tools.ietf.org/html/rfc3207#page-7
self._reader._buffer.clear() # type: ignore[attr-defined]
# Do SSL certificate checking as rfc3207 part 4.1 says. Why is
# _extra a protected attribute?
assert self._tls_protocol is not None
self.session.ssl = self._tls_protocol._extra
hook = self._handle_hooks.get("STARTTLS")
if hook is None:
self._tls_handshake_okay = True
else:
self._tls_handshake_okay = hook(
self, self.session, self.envelope)
else:
super().connection_made(transport)
self.transport = transport
log.info('Peer: %r', self.session.peer)
# Process the client's requests.
self._handler_coroutine = self.loop.create_task(
self._handle_client())
def connection_lost(self, error: Optional[Exception]) -> None:
assert self.session is not None
log.info('%r connection lost', self.session.peer)
assert self._timeout_handle is not None
self._timeout_handle.cancel()
# If STARTTLS was issued, then our transport is the SSL protocol
# transport, and we need to close the original transport explicitly,
# otherwise an unexpected eof_received() will be called *after* the
# connection_lost(). At that point the stream reader will already be
# destroyed and we'll get a traceback in super().eof_received() below.
if self._original_transport is not None:
self._original_transport.close()
super().connection_lost(error)
assert self._handler_coroutine is not None
self._handler_coroutine.cancel()
self.transport = None
def eof_received(self) -> Optional[bool]:
assert self.session is not None
log.info('%r EOF received', self.session.peer)
assert self._handler_coroutine is not None
self._handler_coroutine.cancel()
if self.session.ssl is not None:
# If STARTTLS was issued, return False, because True has no effect
# on an SSL transport and raises a warning. Our superclass has no
# way of knowing we switched to SSL so it might return True.
return False
return super().eof_received()
def _reset_timeout(self, duration: Optional[float] = None) -> None:
if self._timeout_handle is not None:
self._timeout_handle.cancel()
self._timeout_handle = self.loop.call_later(
duration or self._timeout_duration, self._timeout_cb
)
def _timeout_cb(self):
assert self.session is not None
log.info('%r connection timeout', self.session.peer)
# Calling close() on the transport will trigger connection_lost(),
# which gracefully closes the SSL transport if required and cleans
# up state.
assert self.transport is not None
self.transport.close()
def _cb_client_connected(
self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
):
# This is redundant since we subclass StreamReaderProtocol, but I like
# the shorter names.
self._reader = reader
self._writer = writer
def _set_post_data_state(self):
"""Reset state variables to their post-DATA state."""
self.envelope = self._create_envelope()
def _set_rset_state(self):
"""Reset all state variables except the greeting."""
self._set_post_data_state()
async def push(self, status: AnyStr):
if isinstance(status, str):
response = bytes(
status, 'utf-8' if self.enable_SMTPUTF8 else 'ascii')
else:
response = status
assert isinstance(response, bytes)
self._writer.write(response + b"\r\n")
assert self.session is not None
log.debug("%r << %r", self.session.peer, response)
await self._writer.drain()
async def handle_exception(self, error: Exception) -> str:
if hasattr(self.event_handler, 'handle_exception'):
status = await self.event_handler.handle_exception(error)
return status
else:
assert self.session is not None
log.exception('%r SMTP session exception', self.session.peer)
status = '500 Error: ({}) {}'.format(
error.__class__.__name__, str(error))
return status
async def _handle_client(self) -> None:
assert self.session is not None
log.info('%r handling connection', self.session.peer)
if self._proxy_timeout is not None:
self._reset_timeout(self._proxy_timeout)
log.debug("%r waiting PROXY handshake", self.session.peer)
self.session.proxy_data = await get_proxy(self._reader)
if self.session.proxy_data:
log.info("%r valid PROXY handshake", self.session.peer)
status = await self._call_handler_hook("PROXY", self.session.proxy_data)
log.debug("%r handle_PROXY returned %r", self.session.peer, status)
else:
log.warning("%r invalid PROXY handshake", self.session.peer)
status = False
if status is MISSING or not status:
log.info("%r rejected by handle_PROXY", self.session.peer)
assert self.transport is not None
self.transport.close()
return
self._reset_timeout()
await self.push('220 {} {}'.format(self.hostname, self.__ident__))
if self._enforce_call_limit:
call_limit: MutableMapping[str, int] = collections.defaultdict(
lambda: self._call_limit_default,
self._call_limit_base
)
else:
# Not used, but this silences code inspection tools
call_limit = {}
bogus_budget = BOGUS_LIMIT
while self.transport is not None: # pragma: nobranch
try:
try:
line: bytes = await self._reader.readuntil()
except asyncio.LimitOverrunError as error:
# Line too long. Read until end of line before sending 500.
await self._reader.read(error.consumed)
while True:
try:
await self._reader.readuntil()
break
except asyncio.LimitOverrunError as e:
# Line is even longer...
await self._reader.read(e.consumed)
continue
# Now that we have read a full line from the client,
# send error response and read the next command line.
await self.push('500 Command line too long')
continue
sanitized_log(log.debug, '_handle_client readline: %r', line)
# XXX this rstrip may not completely preserve old behavior.
line = line.rstrip(b'\r\n')
sanitized_log(log.info, '%r >> %r', self.session.peer, line)
if not line:
await self.push('500 Error: bad syntax')
continue
command_bytes, _, arg_bytes = line.partition(b" ")
# Decode to string only the command name part, which must be
# ASCII as per RFC. If there is an argument, it is decoded to
# UTF-8/surrogateescape so that non-UTF-8 data can be
# re-encoded back to the original bytes when the SMTP command
# is handled.
try:
command = command_bytes.upper().decode(encoding='ascii')
except UnicodeDecodeError:
await self.push('500 Error: bad syntax')
continue
if not arg_bytes:
arg: Optional[str] = None
else:
arg_bytes = arg_bytes.strip()
# Remote SMTP servers can send us UTF-8 content despite
# whether they've declared to do so or not. Some old
# servers can send 8-bit data. Use surrogateescape so
# that the fidelity of the decoding is preserved, and the
# original bytes can be retrieved.
if self.enable_SMTPUTF8:
arg = str(
arg_bytes, encoding='utf-8', errors='surrogateescape')
else:
try:
arg = str(arg_bytes, encoding='ascii', errors='strict')
except UnicodeDecodeError:
# This happens if enable_SMTPUTF8 is false, meaning
# that the server explicitly does not want to
# accept non-ASCII, but the client ignores that and
# sends non-ASCII anyway.
await self.push('500 Error: strict ASCII mode')
# Should we await self.handle_exception()?
continue
max_sz = (
self.command_size_limits[command]
if self.session.extended_smtp
else self.command_size_limit
)
if len(line) > max_sz:
await self.push('500 Command line too long')
continue
if not self._tls_handshake_okay and command != 'QUIT':
await self.push(
'554 Command refused due to lack of security')
continue
if (self.require_starttls
and not self._tls_protocol
and command not in ALLOWED_BEFORE_STARTTLS):
# RFC3207 part 4
await self.push('530 Must issue a STARTTLS command first')
continue
if self._enforce_call_limit:
budget = call_limit[command]
if budget < 1:
log.warning(
"%r over limit for %s", self.session.peer, command
)
await self.push(
f"421 4.7.0 {command} sent too many times"
)
self.transport.close()
continue
call_limit[command] = budget - 1
method = self._smtp_methods.get(command)
if method is None:
log.warning("%r unrecognised: %s", self.session.peer, command)
bogus_budget -= 1
if bogus_budget < 1:
log.warning("%r too many bogus commands", self.session.peer)
await self.push(
"502 5.5.1 Too many unrecognized commands, goodbye."
)
self.transport.close()
continue
await self.push(
f'500 Error: command "{command}" not recognized'
)
continue
# Received a valid command, reset the timer.
self._reset_timeout()
await method(arg)
except asyncio.CancelledError:
# The connection got reset during the DATA command.
# XXX If handler method raises ConnectionResetError, we should
# verify that it was actually self._reader that was reset.
log.info('%r Connection lost during _handle_client()',
self.session.peer)
self._writer.close()
raise
except ConnectionResetError:
log.info('%r Connection lost during _handle_client()',
self.session.peer)
self._writer.close()
raise
except Exception as error:
status = None
try:
status = await self.handle_exception(error)
except Exception as inner_error:
try:
log.exception('%r Exception in handle_exception()',
self.session.peer)
status = '500 Error: ({}) {}'.format(
inner_error.__class__.__name__, str(inner_error))
except Exception:
status = '500 Error: Cannot describe error'
finally:
if isinstance(error, TLSSetupException):
# This code branch is inside None check for self.transport
# so there shouldn't be a None self.transport but pytype
# still complains, so silence that error.
self.transport.close() # pytype: disable=attribute-error
self.connection_lost(error)
else:
# The value of status is being set with ex-except and it
# shouldn't be None, but pytype isn't able to infer that
# so ignore the error related to wrong argument types.
await self.push(status) # pytype: disable=wrong-arg-types
async def check_helo_needed(self, helo: str = "HELO") -> bool:
"""
Check if HELO/EHLO is needed.
:param helo: The actual string of HELO/EHLO
:return: True if HELO/EHLO is needed
"""
assert self.session is not None
if not self.session.host_name:
await self.push(f'503 Error: send {helo} first')
return True
return False
async def check_auth_needed(self, caller_method: str) -> bool:
"""
Check if AUTH is needed.
:param caller_method: The SMTP method needing a check (for logging)
:return: True if AUTH is needed
"""
assert self.session is not None
if self._auth_required and not self.session.authenticated:
log.info(f'{caller_method}: Authentication required')
await self.push('530 5.7.0 Authentication required')
return True
return False
# SMTP and ESMTP commands
@syntax('HELO hostname')
async def smtp_HELO(self, hostname: str):
if not hostname:
await self.push('501 Syntax: HELO hostname')
return
self._set_rset_state()
assert self.session is not None
self.session.extended_smtp = False
status = await self._call_handler_hook('HELO', hostname)
if status is MISSING:
self.session.host_name = hostname
status = '250 {}'.format(self.hostname)
await self.push(status)
@syntax('EHLO hostname')
async def smtp_EHLO(self, hostname: str):
if not hostname:
await self.push('501 Syntax: EHLO hostname')
return
response = ['250-' + self.hostname, ]
self._set_rset_state()
assert self.session is not None
self.session.extended_smtp = True
if self.data_size_limit:
response.append(f'250-SIZE {self.data_size_limit}')
self.command_size_limits['MAIL'] += 26
if not self._decode_data:
response.append('250-8BITMIME')
if self.enable_SMTPUTF8:
response.append('250-SMTPUTF8')
self.command_size_limits['MAIL'] += 10
if self.tls_context and not self._tls_protocol:
response.append('250-STARTTLS')
if not self._auth_require_tls or self._tls_protocol:
response.append(
"250-AUTH " + " ".join(sorted(self._auth_methods.keys()))
)
if hasattr(self, 'ehlo_hook'):
warn('Use handler.handle_EHLO() instead of .ehlo_hook()',
DeprecationWarning)
await self.ehlo_hook()
if self._ehlo_hook_ver is None:
self.session.host_name = hostname
response.append('250 HELP')
elif self._ehlo_hook_ver == "old":
# Old behavior: Send all responses first...
for r in response:
await self.push(r)
# ... then send the response from the hook.
response = [await self._call_handler_hook("EHLO", hostname)]
# (The hook might internally send its own responses.)
elif self._ehlo_hook_ver == "new": # pragma: nobranch
# New behavior: hand over list of responses so far to the hook, and
# REPLACE existing list of responses with what the hook returns.
# We will handle the push()ing
response.append('250 HELP')
response = await self._call_handler_hook("EHLO", hostname, response)
for r in response:
await self.push(r)
@syntax('NOOP [ignored]')
async def smtp_NOOP(self, arg: str):
status = await self._call_handler_hook('NOOP', arg)
await self.push('250 OK' if status is MISSING else status)
@syntax('QUIT')
async def smtp_QUIT(self, arg: str):
if arg:
await self.push('501 Syntax: QUIT')
else:
status = await self._call_handler_hook('QUIT')
await self.push('221 Bye' if status is MISSING else status)
assert self._handler_coroutine is not None
self._handler_coroutine.cancel()
assert self.transport is not None
self.transport.close()
@syntax('STARTTLS', when='tls_context')
async def smtp_STARTTLS(self, arg: str):
if arg:
await self.push('501 Syntax: STARTTLS')
return
if not self.tls_context:
await self.push('454 TLS not available')
return
await self.push('220 Ready to start TLS')
# Create a waiter Future to wait for SSL handshake to complete
waiter = self.loop.create_future()
# Create SSL layer.
# noinspection PyTypeChecker
self._tls_protocol = sslproto.SSLProtocol(
self.loop,
self,
self.tls_context,
waiter,
server_side=True)
# Reconfigure transport layer. Keep a reference to the original
# transport so that we can close it explicitly when the connection is
# lost.
self._original_transport = self.transport
assert self._original_transport is not None
self._original_transport.set_protocol(self._tls_protocol)
# Reconfigure the protocol layer. Why is the app transport a protected
# property, if it MUST be used externally?
self.transport = self._tls_protocol._app_transport
self._tls_protocol.connection_made(self._original_transport)
# wait until handshake complete
try:
await waiter
except asyncio.CancelledError:
raise
except Exception as error:
raise TLSSetupException() from error
@syntax("AUTH <mechanism>")
async def smtp_AUTH(self, arg: str) -> None:
if await self.check_helo_needed("EHLO"):
return
assert self.session is not None
if not self.session.extended_smtp:
await self.push("500 Error: command 'AUTH' not recognized")
return
elif self._auth_require_tls and not self._tls_protocol:
await self.push("538 5.7.11 Encryption required for requested "
"authentication mechanism")
return
elif self.session.authenticated:
await self.push('503 Already authenticated')
return
elif not arg:
await self.push('501 Not enough value')
return
args = arg.split()
if len(args) > 2:
await self.push('501 Too many values')
return
mechanism = args[0]
if mechanism not in self._auth_methods:
await self.push('504 5.5.4 Unrecognized authentication type')
return
CODE_SUCCESS = "235 2.7.0 Authentication successful"
CODE_INVALID = "535 5.7.8 Authentication credentials invalid"
status = await self._call_handler_hook('AUTH', args)
if status is MISSING:
auth_method = self._auth_methods[mechanism]
log.debug(
"Using %s auth_ hook for %r",
"builtin" if auth_method.is_builtin else "handler",
mechanism
)
# Pass 'self' to method so external methods can leverage this
# class's helper methods such as push()
auth_result = await auth_method.method(self, args)
log.debug("auth_%s returned %r", mechanism, auth_result)
# New system using `authenticator` and AuthResult
if isinstance(auth_result, AuthResult):
if auth_result.success:
self.session.authenticated = True
_auth_data = auth_result.auth_data
self.session.auth_data = _auth_data
# Custom mechanisms might not implement the "login" attribute, and