• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1## This file is part of Scapy
2## Copyright (C) 2007, 2008, 2009 Arnaud Ebalard
3##               2015, 2016, 2017 Maxence Tury
4## This program is published under a GPLv2 license
5
6"""
7TLS client automaton. This makes for a primitive TLS stack.
8Obviously you need rights for network access.
9
10We support versions SSLv2 to TLS 1.2, along with many features.
11There is no session resumption mechanism for now.
12
13In order to run a client to tcp/50000 with one cipher suite of your choice:
14> from scapy.all import *
15> ch = TLSClientHello(ciphers=<int code of the cipher suite>)
16> t = TLSClientAutomaton(dport=50000, client_hello=ch)
17> t.run()
18"""
19
20from __future__ import print_function
21import socket
22
23from scapy.pton_ntop import inet_pton
24from scapy.utils import randstring
25from scapy.automaton import ATMT
26from scapy.layers.tls.automaton import _TLSAutomaton
27from scapy.layers.tls.basefields import _tls_version, _tls_version_options
28from scapy.layers.tls.session import tlsSession
29from scapy.layers.tls.extensions import (TLS_Ext_SupportedGroups,
30                                         TLS_Ext_SupportedVersions,
31                                         TLS_Ext_SignatureAlgorithms,
32                                         TLS_Ext_ServerName, ServerName)
33from scapy.layers.tls.handshake import *
34from scapy.layers.tls.handshake_sslv2 import *
35from scapy.layers.tls.keyexchange_tls13 import (TLS_Ext_KeyShare_CH,
36                                                KeyShareEntry)
37from scapy.layers.tls.record import (TLS, TLSAlert, TLSChangeCipherSpec,
38                                     TLSApplicationData)
39from scapy.modules import six
40
41
42class TLSClientAutomaton(_TLSAutomaton):
43    """
44    A simple TLS test client automaton. Try to overload some states or
45    conditions and see what happens on the other side.
46
47    Rather than with an interruption, the best way to stop this client is by
48    typing 'quit'. This won't be a message sent to the server.
49
50    _'mycert' and 'mykey' may be provided as filenames. They will be used in
51    the handshake, should the server ask for client authentication.
52    _'server_name' does not need to be set.
53    _'client_hello' may hold a TLSClientHello or SSLv2ClientHello to be sent
54    to the server. This is particularly useful for extensions tweaking.
55    _'version' is a quicker way to advertise a protocol version ("sslv2",
56    "tls1", "tls12", etc.) It may be overriden by the previous 'client_hello'.
57    _'data' is a list of raw data to be sent to the server once the handshake
58    has been completed. Both 'stop_server' and 'quit' will work this way.
59    """
60
61    def parse_args(self, server="127.0.0.1", dport=4433, server_name=None,
62                         mycert=None, mykey=None,
63                         client_hello=None, version=None,
64                         data=None,
65                         **kargs):
66
67        super(TLSClientAutomaton, self).parse_args(mycert=mycert,
68                                                   mykey=mykey,
69                                                   **kargs)
70        tmp = socket.getaddrinfo(server, dport)
71        self.remote_name = None
72        try:
73            if ':' in server:
74                inet_pton(socket.AF_INET6, server)
75            else:
76                inet_pton(socket.AF_INET, server)
77        except:
78            self.remote_name = socket.getfqdn(server)
79            if self.remote_name != server:
80                tmp = socket.getaddrinfo(self.remote_name, dport)
81
82        if server_name:
83            self.remote_name = server_name
84        self.remote_family = tmp[0][0]
85        self.remote_ip = tmp[0][4][0]
86        self.remote_port = dport
87        self.local_ip = None
88        self.local_port = None
89        self.socket = None
90
91        self.client_hello = client_hello
92        self.advertised_tls_version = None
93        if version:
94            v = _tls_version_options.get(version, None)
95            if not v:
96                self.vprint("Unrecognized TLS version option.")
97            else:
98                self.advertised_tls_version = v
99
100        self.linebreak = False
101        if isinstance(data, bytes):
102            self.data_to_send = [data]
103        elif isinstance(data, six.string_types):
104            self.data_to_send = [raw(data)]
105        elif isinstance(data, list):
106            self.data_to_send = list(raw(d) for d in reversed(data))
107        else:
108            self.data_to_send = []
109
110
111    def vprint_sessioninfo(self):
112        if self.verbose:
113            s = self.cur_session
114            v = _tls_version[s.tls_version]
115            self.vprint("Version       : %s" % v)
116            cs = s.wcs.ciphersuite.name
117            self.vprint("Cipher suite  : %s" % cs)
118            if s.tls_version >= 0x0304:
119                ms = s.tls13_master_secret
120            else:
121                ms = s.master_secret
122            self.vprint("Master secret : %s" % repr_hex(ms))
123            if s.server_certs:
124                self.vprint("Server certificate chain: %r" % s.server_certs)
125            self.vprint()
126
127
128    @ATMT.state(initial=True)
129    def INITIAL(self):
130        self.vprint("Starting TLS client automaton.")
131        raise self.INIT_TLS_SESSION()
132
133    @ATMT.state()
134    def INIT_TLS_SESSION(self):
135        self.cur_session = tlsSession(connection_end="client")
136        self.cur_session.client_certs = self.mycert
137        self.cur_session.client_key = self.mykey
138        v = self.advertised_tls_version
139        if v:
140            self.cur_session.advertised_tls_version = v
141        else:
142            default_version = self.cur_session.advertised_tls_version
143            self.advertised_tls_version = default_version
144        raise self.CONNECT()
145
146    @ATMT.state()
147    def CONNECT(self):
148        s = socket.socket(self.remote_family, socket.SOCK_STREAM)
149        self.vprint()
150        self.vprint("Trying to connect on %s:%d" % (self.remote_ip,
151                                                    self.remote_port))
152        s.connect((self.remote_ip, self.remote_port))
153        self.socket = s
154        self.local_ip, self.local_port = self.socket.getsockname()[:2]
155        self.vprint()
156        if self.cur_session.advertised_tls_version in [0x0200, 0x0002]:
157            raise self.SSLv2_PREPARE_CLIENTHELLO()
158        elif self.cur_session.advertised_tls_version >= 0x0304:
159            raise self.TLS13_START()
160        else:
161            raise self.PREPARE_CLIENTFLIGHT1()
162
163    ########################### TLS handshake #################################
164
165    @ATMT.state()
166    def PREPARE_CLIENTFLIGHT1(self):
167        self.add_record()
168
169    @ATMT.condition(PREPARE_CLIENTFLIGHT1)
170    def should_add_ClientHello(self):
171        self.add_msg(self.client_hello or TLSClientHello())
172        raise self.ADDED_CLIENTHELLO()
173
174    @ATMT.state()
175    def ADDED_CLIENTHELLO(self):
176        pass
177
178    @ATMT.condition(ADDED_CLIENTHELLO)
179    def should_send_ClientFlight1(self):
180        self.flush_records()
181        raise self.SENT_CLIENTFLIGHT1()
182
183    @ATMT.state()
184    def SENT_CLIENTFLIGHT1(self):
185        raise self.WAITING_SERVERFLIGHT1()
186
187    @ATMT.state()
188    def WAITING_SERVERFLIGHT1(self):
189        self.get_next_msg()
190        raise self.RECEIVED_SERVERFLIGHT1()
191
192    @ATMT.state()
193    def RECEIVED_SERVERFLIGHT1(self):
194        pass
195
196    @ATMT.condition(RECEIVED_SERVERFLIGHT1, prio=1)
197    def should_handle_ServerHello(self):
198        """
199        XXX We should check the ServerHello attributes for discrepancies with
200        our own ClientHello.
201        """
202        self.raise_on_packet(TLSServerHello,
203                             self.HANDLED_SERVERHELLO)
204
205    @ATMT.state()
206    def HANDLED_SERVERHELLO(self):
207        pass
208
209    @ATMT.condition(RECEIVED_SERVERFLIGHT1, prio=2)
210    def missing_ServerHello(self):
211        raise self.MISSING_SERVERHELLO()
212
213    @ATMT.state()
214    def MISSING_SERVERHELLO(self):
215        self.vprint("Missing TLS ServerHello message!")
216        raise self.CLOSE_NOTIFY()
217
218    @ATMT.condition(HANDLED_SERVERHELLO, prio=1)
219    def should_handle_ServerCertificate(self):
220        if not self.cur_session.prcs.key_exchange.anonymous:
221            self.raise_on_packet(TLSCertificate,
222                                 self.HANDLED_SERVERCERTIFICATE)
223        raise self.HANDLED_SERVERCERTIFICATE()
224
225    @ATMT.state()
226    def HANDLED_SERVERCERTIFICATE(self):
227        pass
228
229    @ATMT.condition(HANDLED_SERVERHELLO, prio=2)
230    def missing_ServerCertificate(self):
231        raise self.MISSING_SERVERCERTIFICATE()
232
233    @ATMT.state()
234    def MISSING_SERVERCERTIFICATE(self):
235        self.vprint("Missing TLS Certificate message!")
236        raise self.CLOSE_NOTIFY()
237
238    @ATMT.state()
239    def HANDLED_CERTIFICATEREQUEST(self):
240        self.vprint("Server asked for a certificate...")
241        if not self.mykey or not self.mycert:
242            self.vprint("No client certificate to send!")
243            self.vprint("Will try and send an empty Certificate message...")
244
245    @ATMT.condition(HANDLED_SERVERCERTIFICATE, prio=1)
246    def should_handle_ServerKeyExchange_from_ServerCertificate(self):
247        """
248        XXX We should check the ServerKeyExchange attributes for discrepancies
249        with our own ClientHello, along with the ServerHello and Certificate.
250        """
251        self.raise_on_packet(TLSServerKeyExchange,
252                             self.HANDLED_SERVERKEYEXCHANGE)
253
254    @ATMT.state(final=True)
255    def MISSING_SERVERKEYEXCHANGE(self):
256        pass
257
258    @ATMT.condition(HANDLED_SERVERCERTIFICATE, prio=2)
259    def missing_ServerKeyExchange(self):
260        if not self.cur_session.prcs.key_exchange.no_ske:
261            raise self.MISSING_SERVERKEYEXCHANGE()
262
263    @ATMT.state()
264    def HANDLED_SERVERKEYEXCHANGE(self):
265        pass
266
267    def should_handle_CertificateRequest(self):
268        """
269        XXX We should check the CertificateRequest attributes for discrepancies
270        with the cipher suite, etc.
271        """
272        self.raise_on_packet(TLSCertificateRequest,
273                             self.HANDLED_CERTIFICATEREQUEST)
274
275    @ATMT.condition(HANDLED_SERVERKEYEXCHANGE, prio=2)
276    def should_handle_CertificateRequest_from_ServerKeyExchange(self):
277        self.should_handle_CertificateRequest()
278
279    @ATMT.condition(HANDLED_SERVERCERTIFICATE, prio=3)
280    def should_handle_CertificateRequest_from_ServerCertificate(self):
281        self.should_handle_CertificateRequest()
282
283    def should_handle_ServerHelloDone(self):
284        self.raise_on_packet(TLSServerHelloDone,
285                             self.HANDLED_SERVERHELLODONE)
286
287    @ATMT.condition(HANDLED_SERVERKEYEXCHANGE, prio=1)
288    def should_handle_ServerHelloDone_from_ServerKeyExchange(self):
289        return self.should_handle_ServerHelloDone()
290
291    @ATMT.condition(HANDLED_CERTIFICATEREQUEST, prio=4)
292    def should_handle_ServerHelloDone_from_CertificateRequest(self):
293        return self.should_handle_ServerHelloDone()
294
295    @ATMT.condition(HANDLED_SERVERCERTIFICATE, prio=4)
296    def should_handle_ServerHelloDone_from_ServerCertificate(self):
297        return self.should_handle_ServerHelloDone()
298
299    @ATMT.state()
300    def HANDLED_SERVERHELLODONE(self):
301        raise self.PREPARE_CLIENTFLIGHT2()
302
303    @ATMT.state()
304    def PREPARE_CLIENTFLIGHT2(self):
305        self.add_record()
306
307    @ATMT.condition(PREPARE_CLIENTFLIGHT2, prio=1)
308    def should_add_ClientCertificate(self):
309        """
310        If the server sent a CertificateRequest, we send a Certificate message.
311        If no certificate is available, an empty Certificate message is sent:
312        - this is a SHOULD in RFC 4346 (Section 7.4.6)
313        - this is a MUST in RFC 5246 (Section 7.4.6)
314
315        XXX We may want to add a complete chain.
316        """
317        hs_msg = [type(m) for m in self.cur_session.handshake_messages_parsed]
318        if not TLSCertificateRequest in hs_msg:
319            return
320        certs = []
321        if self.mycert:
322            certs = [self.mycert]
323        self.add_msg(TLSCertificate(certs=certs))
324        raise self.ADDED_CLIENTCERTIFICATE()
325
326    @ATMT.state()
327    def ADDED_CLIENTCERTIFICATE(self):
328        pass
329
330    def should_add_ClientKeyExchange(self):
331        self.add_msg(TLSClientKeyExchange())
332        raise self.ADDED_CLIENTKEYEXCHANGE()
333
334    @ATMT.condition(PREPARE_CLIENTFLIGHT2, prio=2)
335    def should_add_ClientKeyExchange_from_ClientFlight2(self):
336        return self.should_add_ClientKeyExchange()
337
338    @ATMT.condition(ADDED_CLIENTCERTIFICATE)
339    def should_add_ClientKeyExchange_from_ClientCertificate(self):
340        return self.should_add_ClientKeyExchange()
341
342    @ATMT.state()
343    def ADDED_CLIENTKEYEXCHANGE(self):
344        pass
345
346    @ATMT.condition(ADDED_CLIENTKEYEXCHANGE, prio=1)
347    def should_add_ClientVerify(self):
348        """
349        XXX Section 7.4.7.1 of RFC 5246 states that the CertificateVerify
350        message is only sent following a client certificate that has signing
351        capability (i.e. not those containing fixed DH params).
352        We should verify that before adding the message. We should also handle
353        the case when the Certificate message was empty.
354        """
355        hs_msg = [type(m) for m in self.cur_session.handshake_messages_parsed]
356        if (not TLSCertificateRequest in hs_msg or
357            self.mycert is None or
358            self.mykey is None):
359            return
360        self.add_msg(TLSCertificateVerify())
361        raise self.ADDED_CERTIFICATEVERIFY()
362
363    @ATMT.state()
364    def ADDED_CERTIFICATEVERIFY(self):
365        pass
366
367    @ATMT.condition(ADDED_CERTIFICATEVERIFY)
368    def should_add_ChangeCipherSpec_from_CertificateVerify(self):
369        self.add_record()
370        self.add_msg(TLSChangeCipherSpec())
371        raise self.ADDED_CHANGECIPHERSPEC()
372
373    @ATMT.condition(ADDED_CLIENTKEYEXCHANGE, prio=2)
374    def should_add_ChangeCipherSpec_from_ClientKeyExchange(self):
375        self.add_record()
376        self.add_msg(TLSChangeCipherSpec())
377        raise self.ADDED_CHANGECIPHERSPEC()
378
379    @ATMT.state()
380    def ADDED_CHANGECIPHERSPEC(self):
381        pass
382
383    @ATMT.condition(ADDED_CHANGECIPHERSPEC)
384    def should_add_ClientFinished(self):
385        self.add_record()
386        self.add_msg(TLSFinished())
387        raise self.ADDED_CLIENTFINISHED()
388
389    @ATMT.state()
390    def ADDED_CLIENTFINISHED(self):
391        pass
392
393    @ATMT.condition(ADDED_CLIENTFINISHED)
394    def should_send_ClientFlight2(self):
395        self.flush_records()
396        raise self.SENT_CLIENTFLIGHT2()
397
398    @ATMT.state()
399    def SENT_CLIENTFLIGHT2(self):
400        raise self.WAITING_SERVERFLIGHT2()
401
402    @ATMT.state()
403    def WAITING_SERVERFLIGHT2(self):
404        self.get_next_msg()
405        raise self.RECEIVED_SERVERFLIGHT2()
406
407    @ATMT.state()
408    def RECEIVED_SERVERFLIGHT2(self):
409        pass
410
411    @ATMT.condition(RECEIVED_SERVERFLIGHT2)
412    def should_handle_ChangeCipherSpec(self):
413        self.raise_on_packet(TLSChangeCipherSpec,
414                             self.HANDLED_CHANGECIPHERSPEC)
415
416    @ATMT.state()
417    def HANDLED_CHANGECIPHERSPEC(self):
418        pass
419
420    @ATMT.condition(HANDLED_CHANGECIPHERSPEC)
421    def should_handle_Finished(self):
422        self.raise_on_packet(TLSFinished,
423                             self.HANDLED_SERVERFINISHED)
424
425    @ATMT.state()
426    def HANDLED_SERVERFINISHED(self):
427        self.vprint("TLS handshake completed!")
428        self.vprint_sessioninfo()
429        self.vprint("You may send data or use 'quit'.")
430
431    ####################### end of TLS handshake ##############################
432
433    @ATMT.condition(HANDLED_SERVERFINISHED)
434    def should_wait_ClientData(self):
435        raise self.WAIT_CLIENTDATA()
436
437    @ATMT.state()
438    def WAIT_CLIENTDATA(self):
439        pass
440
441    @ATMT.condition(WAIT_CLIENTDATA, prio=1)
442    def add_ClientData(self):
443        """
444        The user may type in:
445        GET / HTTP/1.1\r\nHost: testserver.com\r\n\r\n
446        Special characters are handled so that it becomes a valid HTTP request.
447        """
448        if not self.data_to_send:
449            data = six.moves.input().replace('\\r', '\r').replace('\\n', '\n').encode()
450        else:
451            data = self.data_to_send.pop()
452        if data == b"quit":
453            return
454        if self.linebreak:
455            data += b"\n"
456        self.add_record()
457        self.add_msg(TLSApplicationData(data=data))
458        raise self.ADDED_CLIENTDATA()
459
460    @ATMT.condition(WAIT_CLIENTDATA, prio=2)
461    def no_more_ClientData(self):
462        raise self.CLOSE_NOTIFY()
463
464    @ATMT.state()
465    def ADDED_CLIENTDATA(self):
466        pass
467
468    @ATMT.condition(ADDED_CLIENTDATA)
469    def should_send_ClientData(self):
470        self.flush_records()
471        raise self.SENT_CLIENTDATA()
472
473    @ATMT.state()
474    def SENT_CLIENTDATA(self):
475        raise self.WAITING_SERVERDATA()
476
477    @ATMT.state()
478    def WAITING_SERVERDATA(self):
479        self.get_next_msg(0.3, 1)
480        raise self.RECEIVED_SERVERDATA()
481
482    @ATMT.state()
483    def RECEIVED_SERVERDATA(self):
484        pass
485
486    @ATMT.condition(RECEIVED_SERVERDATA, prio=1)
487    def should_handle_ServerData(self):
488        if not self.buffer_in:
489            raise self.WAIT_CLIENTDATA()
490        p = self.buffer_in[0]
491        if isinstance(p, TLSApplicationData):
492            print("> Received: %r" % p.data)
493        elif isinstance(p, TLSAlert):
494            print("> Received: %r" % p)
495            raise self.CLOSE_NOTIFY()
496        else:
497            print("> Received: %r" % p)
498        self.buffer_in = self.buffer_in[1:]
499        raise self.HANDLED_SERVERDATA()
500
501    @ATMT.state()
502    def HANDLED_SERVERDATA(self):
503        raise self.WAIT_CLIENTDATA()
504
505    @ATMT.state()
506    def CLOSE_NOTIFY(self):
507        self.vprint()
508        self.vprint("Trying to send a TLSAlert to the server...")
509
510    @ATMT.condition(CLOSE_NOTIFY)
511    def close_session(self):
512        self.add_record()
513        self.add_msg(TLSAlert(level=1, descr=0))
514        try:
515            self.flush_records()
516        except:
517            self.vprint("Could not send termination Alert, maybe the server stopped?")
518        raise self.FINAL()
519
520    ########################## SSLv2 handshake ################################
521
522    @ATMT.state()
523    def SSLv2_PREPARE_CLIENTHELLO(self):
524        pass
525
526    @ATMT.condition(SSLv2_PREPARE_CLIENTHELLO)
527    def sslv2_should_add_ClientHello(self):
528        self.add_record(is_sslv2=True)
529        p = self.client_hello or SSLv2ClientHello(challenge=randstring(16))
530        self.add_msg(p)
531        raise self.SSLv2_ADDED_CLIENTHELLO()
532
533    @ATMT.state()
534    def SSLv2_ADDED_CLIENTHELLO(self):
535        pass
536
537    @ATMT.condition(SSLv2_ADDED_CLIENTHELLO)
538    def sslv2_should_send_ClientHello(self):
539        self.flush_records()
540        raise self.SSLv2_SENT_CLIENTHELLO()
541
542    @ATMT.state()
543    def SSLv2_SENT_CLIENTHELLO(self):
544        raise self.SSLv2_WAITING_SERVERHELLO()
545
546    @ATMT.state()
547    def SSLv2_WAITING_SERVERHELLO(self):
548        self.get_next_msg()
549        raise self.SSLv2_RECEIVED_SERVERHELLO()
550
551    @ATMT.state()
552    def SSLv2_RECEIVED_SERVERHELLO(self):
553        pass
554
555    @ATMT.condition(SSLv2_RECEIVED_SERVERHELLO, prio=1)
556    def sslv2_should_handle_ServerHello(self):
557        self.raise_on_packet(SSLv2ServerHello,
558                             self.SSLv2_HANDLED_SERVERHELLO)
559
560    @ATMT.state()
561    def SSLv2_HANDLED_SERVERHELLO(self):
562        pass
563
564    @ATMT.condition(SSLv2_RECEIVED_SERVERHELLO, prio=2)
565    def sslv2_missing_ServerHello(self):
566        raise self.SSLv2_MISSING_SERVERHELLO()
567
568    @ATMT.state()
569    def SSLv2_MISSING_SERVERHELLO(self):
570        self.vprint("Missing SSLv2 ServerHello message!")
571        raise self.SSLv2_CLOSE_NOTIFY()
572
573    @ATMT.condition(SSLv2_HANDLED_SERVERHELLO)
574    def sslv2_should_add_ClientMasterKey(self):
575        self.add_record(is_sslv2=True)
576        self.add_msg(SSLv2ClientMasterKey())
577        raise self.SSLv2_ADDED_CLIENTMASTERKEY()
578
579    @ATMT.state()
580    def SSLv2_ADDED_CLIENTMASTERKEY(self):
581        pass
582
583    @ATMT.condition(SSLv2_ADDED_CLIENTMASTERKEY)
584    def sslv2_should_send_ClientMasterKey(self):
585        self.flush_records()
586        raise self.SSLv2_SENT_CLIENTMASTERKEY()
587
588    @ATMT.state()
589    def SSLv2_SENT_CLIENTMASTERKEY(self):
590        raise self.SSLv2_WAITING_SERVERVERIFY()
591
592    @ATMT.state()
593    def SSLv2_WAITING_SERVERVERIFY(self):
594        # We give the server 0.5 second to send his ServerVerify.
595        # Else we assume that he's waiting for our ClientFinished.
596        self.get_next_msg(0.5, 0)
597        raise self.SSLv2_RECEIVED_SERVERVERIFY()
598
599    @ATMT.state()
600    def SSLv2_RECEIVED_SERVERVERIFY(self):
601        pass
602
603    @ATMT.condition(SSLv2_RECEIVED_SERVERVERIFY, prio=1)
604    def sslv2_should_handle_ServerVerify(self):
605        self.raise_on_packet(SSLv2ServerVerify,
606                             self.SSLv2_HANDLED_SERVERVERIFY,
607                             get_next_msg=False)
608
609    @ATMT.state()
610    def SSLv2_HANDLED_SERVERVERIFY(self):
611        pass
612
613    def sslv2_should_add_ClientFinished(self):
614        hs_msg = [type(m) for m in self.cur_session.handshake_messages_parsed]
615        if SSLv2ClientFinished in hs_msg:
616            return
617        self.add_record(is_sslv2=True)
618        self.add_msg(SSLv2ClientFinished())
619        raise self.SSLv2_ADDED_CLIENTFINISHED()
620
621    @ATMT.condition(SSLv2_HANDLED_SERVERVERIFY, prio=1)
622    def sslv2_should_add_ClientFinished_from_ServerVerify(self):
623        return self.sslv2_should_add_ClientFinished()
624
625    @ATMT.condition(SSLv2_HANDLED_SERVERVERIFY, prio=2)
626    def sslv2_should_wait_ServerFinished_from_ServerVerify(self):
627        raise self.SSLv2_WAITING_SERVERFINISHED()
628
629    @ATMT.condition(SSLv2_RECEIVED_SERVERVERIFY, prio=2)
630    def sslv2_should_add_ClientFinished_from_NoServerVerify(self):
631        return self.sslv2_should_add_ClientFinished()
632
633    @ATMT.condition(SSLv2_RECEIVED_SERVERVERIFY, prio=3)
634    def sslv2_missing_ServerVerify(self):
635        raise self.SSLv2_MISSING_SERVERVERIFY()
636
637    @ATMT.state(final=True)
638    def SSLv2_MISSING_SERVERVERIFY(self):
639        self.vprint("Missing SSLv2 ServerVerify message!")
640        raise self.SSLv2_CLOSE_NOTIFY()
641
642    @ATMT.state()
643    def SSLv2_ADDED_CLIENTFINISHED(self):
644        pass
645
646    @ATMT.condition(SSLv2_ADDED_CLIENTFINISHED)
647    def sslv2_should_send_ClientFinished(self):
648        self.flush_records()
649        raise self.SSLv2_SENT_CLIENTFINISHED()
650
651    @ATMT.state()
652    def SSLv2_SENT_CLIENTFINISHED(self):
653        hs_msg = [type(m) for m in self.cur_session.handshake_messages_parsed]
654        if SSLv2ServerVerify in hs_msg:
655            raise self.SSLv2_WAITING_SERVERFINISHED()
656        else:
657            self.get_next_msg()
658            raise self.SSLv2_RECEIVED_SERVERVERIFY()
659
660    @ATMT.state()
661    def SSLv2_WAITING_SERVERFINISHED(self):
662        self.get_next_msg()
663        raise self.SSLv2_RECEIVED_SERVERFINISHED()
664
665    @ATMT.state()
666    def SSLv2_RECEIVED_SERVERFINISHED(self):
667        pass
668
669    @ATMT.condition(SSLv2_RECEIVED_SERVERFINISHED, prio=1)
670    def sslv2_should_handle_ServerFinished(self):
671        self.raise_on_packet(SSLv2ServerFinished,
672                             self.SSLv2_HANDLED_SERVERFINISHED)
673
674    ####################### SSLv2 client authentication #######################
675
676    @ATMT.condition(SSLv2_RECEIVED_SERVERFINISHED, prio=2)
677    def sslv2_should_handle_RequestCertificate(self):
678        self.raise_on_packet(SSLv2RequestCertificate,
679                             self.SSLv2_HANDLED_REQUESTCERTIFICATE)
680
681    @ATMT.state()
682    def SSLv2_HANDLED_REQUESTCERTIFICATE(self):
683        self.vprint("Server asked for a certificate...")
684        if not self.mykey or not self.mycert:
685            self.vprint("No client certificate to send!")
686            raise self.SSLv2_CLOSE_NOTIFY()
687
688    @ATMT.condition(SSLv2_HANDLED_REQUESTCERTIFICATE)
689    def sslv2_should_add_ClientCertificate(self):
690        self.add_record(is_sslv2=True)
691        self.add_msg(SSLv2ClientCertificate(certdata=self.mycert))
692        raise self.SSLv2_ADDED_CLIENTCERTIFICATE()
693
694    @ATMT.state()
695    def SSLv2_ADDED_CLIENTCERTIFICATE(self):
696        pass
697
698    @ATMT.condition(SSLv2_ADDED_CLIENTCERTIFICATE)
699    def sslv2_should_send_ClientCertificate(self):
700        self.flush_records()
701        raise self.SSLv2_SENT_CLIENTCERTIFICATE()
702
703    @ATMT.state()
704    def SSLv2_SENT_CLIENTCERTIFICATE(self):
705        raise self.SSLv2_WAITING_SERVERFINISHED()
706
707    ################### end of SSLv2 client authentication ####################
708
709    @ATMT.state()
710    def SSLv2_HANDLED_SERVERFINISHED(self):
711        self.vprint("SSLv2 handshake completed!")
712        self.vprint_sessioninfo()
713        self.vprint("You may send data or use 'quit'.")
714
715    @ATMT.condition(SSLv2_RECEIVED_SERVERFINISHED, prio=3)
716    def sslv2_missing_ServerFinished(self):
717        raise self.SSLv2_MISSING_SERVERFINISHED()
718
719    @ATMT.state()
720    def SSLv2_MISSING_SERVERFINISHED(self):
721        self.vprint("Missing SSLv2 ServerFinished message!")
722        raise self.SSLv2_CLOSE_NOTIFY()
723
724    ######################## end of SSLv2 handshake ###########################
725
726    @ATMT.condition(SSLv2_HANDLED_SERVERFINISHED)
727    def sslv2_should_wait_ClientData(self):
728        raise self.SSLv2_WAITING_CLIENTDATA()
729
730    @ATMT.state()
731    def SSLv2_WAITING_CLIENTDATA(self):
732        pass
733
734    @ATMT.condition(SSLv2_WAITING_CLIENTDATA, prio=1)
735    def sslv2_add_ClientData(self):
736        if not self.data_to_send:
737            data = six.moves.input().replace('\\r', '\r').replace('\\n', '\n').encode()
738        else:
739            data = self.data_to_send.pop()
740            self.vprint("> Read from list: %s" % data)
741        if data == "quit":
742            return
743        if self.linebreak:
744            data += "\n"
745        self.add_record(is_sslv2=True)
746        self.add_msg(Raw(data))
747        raise self.SSLv2_ADDED_CLIENTDATA()
748
749    @ATMT.condition(SSLv2_WAITING_CLIENTDATA, prio=2)
750    def sslv2_no_more_ClientData(self):
751        raise self.SSLv2_CLOSE_NOTIFY()
752
753    @ATMT.state()
754    def SSLv2_ADDED_CLIENTDATA(self):
755        pass
756
757    @ATMT.condition(SSLv2_ADDED_CLIENTDATA)
758    def sslv2_should_send_ClientData(self):
759        self.flush_records()
760        raise self.SSLv2_SENT_CLIENTDATA()
761
762    @ATMT.state()
763    def SSLv2_SENT_CLIENTDATA(self):
764        raise self.SSLv2_WAITING_SERVERDATA()
765
766    @ATMT.state()
767    def SSLv2_WAITING_SERVERDATA(self):
768        self.get_next_msg(0.3, 1)
769        raise self.SSLv2_RECEIVED_SERVERDATA()
770
771    @ATMT.state()
772    def SSLv2_RECEIVED_SERVERDATA(self):
773        pass
774
775    @ATMT.condition(SSLv2_RECEIVED_SERVERDATA)
776    def sslv2_should_handle_ServerData(self):
777        if not self.buffer_in:
778            raise self.SSLv2_WAITING_CLIENTDATA()
779        p = self.buffer_in[0]
780        print("> Received: %r" % p.load)
781        if p.load.startswith(b"goodbye"):
782            raise self.SSLv2_CLOSE_NOTIFY()
783        self.buffer_in = self.buffer_in[1:]
784        raise self.SSLv2_HANDLED_SERVERDATA()
785
786    @ATMT.state()
787    def SSLv2_HANDLED_SERVERDATA(self):
788        raise self.SSLv2_WAITING_CLIENTDATA()
789
790    @ATMT.state()
791    def SSLv2_CLOSE_NOTIFY(self):
792        """
793        There is no proper way to end an SSLv2 session.
794        We try and send a 'goodbye' message as a substitute.
795        """
796        self.vprint()
797        self.vprint("Trying to send a 'goodbye' to the server...")
798
799    @ATMT.condition(SSLv2_CLOSE_NOTIFY)
800    def sslv2_close_session(self):
801        self.add_record()
802        self.add_msg(Raw('goodbye'))
803        try:
804            self.flush_records()
805        except:
806            self.vprint("Could not send our goodbye. The server probably stopped.")
807        self.socket.close()
808        raise self.FINAL()
809
810    ######################### TLS 1.3 handshake ###############################
811
812    @ATMT.state()
813    def TLS13_START(self):
814        pass
815
816    @ATMT.condition(TLS13_START)
817    def tls13_should_add_ClientHello(self):
818        # we have to use the legacy, plaintext TLS record here
819        self.add_record(is_tls13=False)
820        if self.client_hello:
821            p = self.client_hello
822        else:
823            # When trying to connect to a public TLS 1.3 server,
824            # you will most likely need to provide an SNI extension.
825           #sn = ServerName(servername="<put server name here>")
826            ext = [TLS_Ext_SupportedGroups(groups=["secp256r1"]),
827                  #TLS_Ext_ServerName(servernames=[sn]),
828                   TLS_Ext_KeyShare_CH(client_shares=[KeyShareEntry(group=23)]),
829                   TLS_Ext_SupportedVersions(versions=["TLS 1.3-d18"]),
830                   TLS_Ext_SignatureAlgorithms(sig_algs=["sha256+rsapss",
831                                                         "sha256+rsa"]) ]
832            p = TLSClientHello(ciphers=0x1301, ext=ext)
833        self.add_msg(p)
834        raise self.TLS13_ADDED_CLIENTHELLO()
835
836    @ATMT.state()
837    def TLS13_ADDED_CLIENTHELLO(self):
838        pass
839
840    @ATMT.condition(TLS13_ADDED_CLIENTHELLO)
841    def tls13_should_send_ClientHello(self):
842        self.flush_records()
843        raise self.TLS13_SENT_CLIENTHELLO()
844
845    @ATMT.state()
846    def TLS13_SENT_CLIENTHELLO(self):
847        raise self.TLS13_WAITING_SERVERHELLO()
848
849    @ATMT.state()
850    def TLS13_WAITING_SERVERHELLO(self):
851        self.get_next_msg()
852
853    @ATMT.condition(TLS13_WAITING_SERVERHELLO)
854    def tls13_should_handle_ServerHello(self):
855        self.raise_on_packet(TLS13ServerHello,
856                             self.TLS13_WAITING_ENCRYPTEDEXTENSIONS)
857
858    @ATMT.state()
859    def TLS13_WAITING_ENCRYPTEDEXTENSIONS(self):
860        self.get_next_msg()
861
862    @ATMT.condition(TLS13_WAITING_ENCRYPTEDEXTENSIONS)
863    def tls13_should_handle_EncryptedExtensions(self):
864        self.raise_on_packet(TLSEncryptedExtensions,
865                             self.TLS13_WAITING_CERTIFICATE)
866
867    @ATMT.state()
868    def TLS13_WAITING_CERTIFICATE(self):
869        self.get_next_msg()
870
871    @ATMT.condition(TLS13_WAITING_CERTIFICATE, prio=1)
872    def tls13_should_handle_Certificate(self):
873        self.raise_on_packet(TLS13Certificate,
874                             self.TLS13_WAITING_CERTIFICATEVERIFY)
875
876    @ATMT.condition(TLS13_WAITING_CERTIFICATE, prio=2)
877    def tls13_should_handle_CertificateRequest(self):
878        hs_msg = [type(m) for m in self.cur_session.handshake_messages_parsed]
879        if TLSCertificateRequest in hs_msg:
880            self.vprint("TLSCertificateRequest already received!")
881        self.raise_on_packet(TLSCertificateRequest,
882                             self.TLS13_WAITING_CERTIFICATE)
883
884    @ATMT.condition(TLS13_WAITING_CERTIFICATE, prio=3)
885    def tls13_should_handle_ServerFinished_from_EncryptedExtensions(self):
886        self.raise_on_packet(TLSFinished,
887                             self.TLS13_CONNECTED)
888
889    @ATMT.condition(TLS13_WAITING_CERTIFICATE, prio=4)
890    def tls13_missing_Certificate(self):
891        self.vprint("Missing TLS 1.3 message after EncryptedExtensions!")
892        raise self.FINAL()
893
894    @ATMT.state()
895    def TLS13_WAITING_CERTIFICATEVERIFY(self):
896        self.get_next_msg()
897
898    @ATMT.condition(TLS13_WAITING_CERTIFICATEVERIFY)
899    def tls13_should_handle_CertificateVerify(self):
900        self.raise_on_packet(TLSCertificateVerify,
901                             self.TLS13_WAITING_SERVERFINISHED)
902
903    @ATMT.state()
904    def TLS13_WAITING_SERVERFINISHED(self):
905        self.get_next_msg()
906
907    @ATMT.condition(TLS13_WAITING_SERVERFINISHED)
908    def tls13_should_handle_ServerFinished_from_CertificateVerify(self):
909        self.raise_on_packet(TLSFinished,
910                             self.TLS13_PREPARE_CLIENTFLIGHT2)
911
912    @ATMT.state()
913    def TLS13_PREPARE_CLIENTFLIGHT2(self):
914        self.add_record(is_tls13=True)
915        #raise self.FINAL()
916
917    @ATMT.condition(TLS13_PREPARE_CLIENTFLIGHT2)
918    def tls13_should_add_ClientFinished(self):
919        self.add_msg(TLSFinished())
920        raise self.TLS13_ADDED_CLIENTFINISHED()
921
922    @ATMT.state()
923    def TLS13_ADDED_CLIENTFINISHED(self):
924        pass
925
926    @ATMT.condition(TLS13_ADDED_CLIENTFINISHED)
927    def tls13_should_send_ClientFlight2(self):
928        self.flush_records()
929        raise self.TLS13_SENT_CLIENTFLIGHT2()
930
931    @ATMT.state()
932    def TLS13_SENT_CLIENTFLIGHT2(self):
933        raise self.HANDLED_SERVERFINISHED()
934
935    @ATMT.state(final=True)
936    def FINAL(self):
937        # We might call shutdown, but it may happen that the server
938        # did not wait for us to shutdown after answering our data query.
939        #self.socket.shutdown(1)
940        self.vprint("Closing client socket...")
941        self.socket.close()
942        self.vprint("Ending TLS client automaton.")
943
944