1c2bd2044b915b1d94600df7c3336bf659271333
[openssl.git] / util / perl / TLSProxy / Message.pm
1 # Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
2 #
3 # Licensed under the OpenSSL license (the "License").  You may not use
4 # this file except in compliance with the License.  You can obtain a copy
5 # in the file LICENSE in the source distribution or at
6 # https://www.openssl.org/source/license.html
7
8 use strict;
9
10 package TLSProxy::Message;
11
12 use constant TLS_MESSAGE_HEADER_LENGTH => 4;
13
14 #Message types
15 use constant {
16     MT_HELLO_REQUEST => 0,
17     MT_CLIENT_HELLO => 1,
18     MT_SERVER_HELLO => 2,
19     MT_NEW_SESSION_TICKET => 4,
20     MT_HELLO_RETRY_REQUEST => 6,
21     MT_ENCRYPTED_EXTENSIONS => 8,
22     MT_CERTIFICATE => 11,
23     MT_SERVER_KEY_EXCHANGE => 12,
24     MT_CERTIFICATE_REQUEST => 13,
25     MT_SERVER_HELLO_DONE => 14,
26     MT_CERTIFICATE_VERIFY => 15,
27     MT_CLIENT_KEY_EXCHANGE => 16,
28     MT_FINISHED => 20,
29     MT_CERTIFICATE_STATUS => 22,
30     MT_NEXT_PROTO => 67
31 };
32
33 #Alert levels
34 use constant {
35     AL_LEVEL_WARN => 1,
36     AL_LEVEL_FATAL => 2
37 };
38
39 #Alert descriptions
40 use constant {
41     AL_DESC_CLOSE_NOTIFY => 0,
42     AL_DESC_UNEXPECTED_MESSAGE => 10,
43     AL_DESC_NO_RENEGOTIATION => 100
44 };
45
46 my %message_type = (
47     MT_HELLO_REQUEST, "HelloRequest",
48     MT_CLIENT_HELLO, "ClientHello",
49     MT_SERVER_HELLO, "ServerHello",
50     MT_NEW_SESSION_TICKET, "NewSessionTicket",
51     MT_HELLO_RETRY_REQUEST, "HelloRetryRequest",
52     MT_ENCRYPTED_EXTENSIONS, "EncryptedExtensions",
53     MT_CERTIFICATE, "Certificate",
54     MT_SERVER_KEY_EXCHANGE, "ServerKeyExchange",
55     MT_CERTIFICATE_REQUEST, "CertificateRequest",
56     MT_SERVER_HELLO_DONE, "ServerHelloDone",
57     MT_CERTIFICATE_VERIFY, "CertificateVerify",
58     MT_CLIENT_KEY_EXCHANGE, "ClientKeyExchange",
59     MT_FINISHED, "Finished",
60     MT_CERTIFICATE_STATUS, "CertificateStatus",
61     MT_NEXT_PROTO, "NextProto"
62 );
63
64 use constant {
65     EXT_SERVER_NAME => 0,
66     EXT_MAX_FRAGMENT_LENGTH => 1,
67     EXT_STATUS_REQUEST => 5,
68     EXT_SUPPORTED_GROUPS => 10,
69     EXT_EC_POINT_FORMATS => 11,
70     EXT_SRP => 12,
71     EXT_SIG_ALGS => 13,
72     EXT_USE_SRTP => 14,
73     EXT_ALPN => 16,
74     EXT_SCT => 18,
75     EXT_PADDING => 21,
76     EXT_ENCRYPT_THEN_MAC => 22,
77     EXT_EXTENDED_MASTER_SECRET => 23,
78     EXT_SESSION_TICKET => 35,
79     EXT_KEY_SHARE => 40,
80     EXT_PSK => 41,
81     EXT_SUPPORTED_VERSIONS => 43,
82     EXT_COOKIE => 44,
83     EXT_PSK_KEX_MODES => 45,
84     EXT_RENEGOTIATE => 65281,
85     EXT_NPN => 13172,
86     # This extension is an unofficial extension only ever written by OpenSSL
87     # (i.e. not read), and even then only when enabled. We use it to test
88     # handling of duplicate extensions.
89     EXT_DUPLICATE_EXTENSION => 0xfde8,
90     EXT_UNKNOWN => 0xfffe,
91     #Unknown extension that should appear last
92     EXT_FORCE_LAST => 0xffff
93 };
94
95 # SignatureScheme of TLS 1.3, from
96 # https://tools.ietf.org/html/draft-ietf-tls-tls13-20#appendix-B.3.1.3
97 # TODO(TLS1.3) update link to IANA registry after publication
98 # We have to manually grab the SHA224 equivalents from the old registry
99 use constant {
100     SIG_ALG_RSA_PKCS1_SHA256 => 0x0401,
101     SIG_ALG_RSA_PKCS1_SHA384 => 0x0501,
102     SIG_ALG_RSA_PKCS1_SHA512 => 0x0601,
103     SIG_ALG_ECDSA_SECP256R1_SHA256 => 0x0403,
104     SIG_ALG_ECDSA_SECP384R1_SHA384 => 0x0503,
105     SIG_ALG_ECDSA_SECP521R1_SHA512 => 0x0603,
106     SIG_ALG_RSA_PSS_SHA256 => 0x0804,
107     SIG_ALG_RSA_PSS_SHA384 => 0x0805,
108     SIG_ALG_RSA_PSS_SHA512 => 0x0806,
109     SIG_ALG_ED25519 => 0x0807,
110     SIG_ALG_ED448 => 0x0808,
111     SIG_ALG_RSA_PKCS1_SHA1 => 0x0201,
112     SIG_ALG_ECDSA_SHA1 => 0x0203,
113     SIG_ALG_DSA_SHA1 => 0x0202,
114     SIG_ALG_DSA_SHA256 => 0x0402,
115     SIG_ALG_DSA_SHA384 => 0x0502,
116     SIG_ALG_DSA_SHA512 => 0x0602,
117     OSSL_SIG_ALG_RSA_PKCS1_SHA224 => 0x0301,
118     OSSL_SIG_ALG_DSA_SHA224 => 0x0302,
119     OSSL_SIG_ALG_ECDSA_SHA224 => 0x0303
120 };
121
122 use constant {
123     CIPHER_DHE_RSA_AES_128_SHA => 0x0033,
124     CIPHER_ADH_AES_128_SHA => 0x0034,
125     CIPHER_TLS13_AES_128_GCM_SHA256 => 0x1301,
126     CIPHER_TLS13_AES_256_GCM_SHA384 => 0x1302
127 };
128
129 my $payload = "";
130 my $messlen = -1;
131 my $mt;
132 my $startoffset = -1;
133 my $server = 0;
134 my $success = 0;
135 my $end = 0;
136 my @message_rec_list = ();
137 my @message_frag_lens = ();
138 my $ciphersuite = 0;
139 my $successondata = 0;
140
141 sub clear
142 {
143     $payload = "";
144     $messlen = -1;
145     $startoffset = -1;
146     $server = 0;
147     $success = 0;
148     $end = 0;
149     $successondata = 0;
150     @message_rec_list = ();
151     @message_frag_lens = ();
152 }
153
154 #Class method to extract messages from a record
155 sub get_messages
156 {
157     my $class = shift;
158     my $serverin = shift;
159     my $record = shift;
160     my @messages = ();
161     my $message;
162
163     @message_frag_lens = ();
164
165     if ($serverin != $server && length($payload) != 0) {
166         die "Changed peer, but we still have fragment data\n";
167     }
168     $server = $serverin;
169
170     if ($record->content_type == TLSProxy::Record::RT_CCS) {
171         if ($payload ne "") {
172             #We can't handle this yet
173             die "CCS received before message data complete\n";
174         }
175         if ($server) {
176             TLSProxy::Record->server_encrypting(1);
177         } else {
178             TLSProxy::Record->client_encrypting(1);
179         }
180     } elsif ($record->content_type == TLSProxy::Record::RT_HANDSHAKE) {
181         if ($record->len == 0 || $record->len_real == 0) {
182             print "  Message truncated\n";
183         } else {
184             my $recoffset = 0;
185
186             if (length $payload > 0) {
187                 #We are continuing processing a message started in a previous
188                 #record. Add this record to the list associated with this
189                 #message
190                 push @message_rec_list, $record;
191
192                 if ($messlen <= length($payload)) {
193                     #Shouldn't happen
194                     die "Internal error: invalid messlen: ".$messlen
195                         ." payload length:".length($payload)."\n";
196                 }
197                 if (length($payload) + $record->decrypt_len >= $messlen) {
198                     #We can complete the message with this record
199                     $recoffset = $messlen - length($payload);
200                     $payload .= substr($record->decrypt_data, 0, $recoffset);
201                     push @message_frag_lens, $recoffset;
202                     $message = create_message($server, $mt, $payload,
203                                               $startoffset);
204                     push @messages, $message;
205
206                     $payload = "";
207                 } else {
208                     #This is just part of the total message
209                     $payload .= $record->decrypt_data;
210                     $recoffset = $record->decrypt_len;
211                     push @message_frag_lens, $record->decrypt_len;
212                 }
213                 print "  Partial message data read: ".$recoffset." bytes\n";
214             }
215
216             while ($record->decrypt_len > $recoffset) {
217                 #We are at the start of a new message
218                 if ($record->decrypt_len - $recoffset < 4) {
219                     #Whilst technically probably valid we can't cope with this
220                     die "End of record in the middle of a message header\n";
221                 }
222                 @message_rec_list = ($record);
223                 my $lenhi;
224                 my $lenlo;
225                 ($mt, $lenhi, $lenlo) = unpack('CnC',
226                                                substr($record->decrypt_data,
227                                                       $recoffset));
228                 $messlen = ($lenhi << 8) | $lenlo;
229                 print "  Message type: $message_type{$mt}\n";
230                 print "  Message Length: $messlen\n";
231                 $startoffset = $recoffset;
232                 $recoffset += 4;
233                 $payload = "";
234                 
235                 if ($recoffset <= $record->decrypt_len) {
236                     #Some payload data is present in this record
237                     if ($record->decrypt_len - $recoffset >= $messlen) {
238                         #We can complete the message with this record
239                         $payload .= substr($record->decrypt_data, $recoffset,
240                                            $messlen);
241                         $recoffset += $messlen;
242                         push @message_frag_lens, $messlen;
243                         $message = create_message($server, $mt, $payload,
244                                                   $startoffset);
245                         push @messages, $message;
246
247                         $payload = "";
248                     } else {
249                         #This is just part of the total message
250                         $payload .= substr($record->decrypt_data, $recoffset,
251                                            $record->decrypt_len - $recoffset);
252                         $recoffset = $record->decrypt_len;
253                         push @message_frag_lens, $recoffset;
254                     }
255                 }
256             }
257         }
258     } elsif ($record->content_type == TLSProxy::Record::RT_APPLICATION_DATA) {
259         print "  [ENCRYPTED APPLICATION DATA]\n";
260         print "  [".$record->decrypt_data."]\n";
261
262         if ($successondata) {
263             $success = 1;
264             $end = 1;
265         }
266     } elsif ($record->content_type == TLSProxy::Record::RT_ALERT) {
267         my ($alertlev, $alertdesc) = unpack('CC', $record->decrypt_data);
268         #A CloseNotify from the client indicates we have finished successfully
269         #(we assume)
270         if (!$end && !$server && $alertlev == AL_LEVEL_WARN
271             && $alertdesc == AL_DESC_CLOSE_NOTIFY) {
272             $success = 1;
273         }
274         #All alerts end the test
275         $end = 1;
276     }
277
278     return @messages;
279 }
280
281 #Function to work out which sub-class we need to create and then
282 #construct it
283 sub create_message
284 {
285     my ($server, $mt, $data, $startoffset) = @_;
286     my $message;
287
288     #We only support ClientHello in this version...needs to be extended for
289     #others
290     if ($mt == MT_CLIENT_HELLO) {
291         $message = TLSProxy::ClientHello->new(
292             $server,
293             $data,
294             [@message_rec_list],
295             $startoffset,
296             [@message_frag_lens]
297         );
298         $message->parse();
299     } elsif ($mt == MT_HELLO_RETRY_REQUEST) {
300         $message = TLSProxy::HelloRetryRequest->new(
301             $server,
302             $data,
303             [@message_rec_list],
304             $startoffset,
305             [@message_frag_lens]
306         );
307         $message->parse();
308     } elsif ($mt == MT_SERVER_HELLO) {
309         $message = TLSProxy::ServerHello->new(
310             $server,
311             $data,
312             [@message_rec_list],
313             $startoffset,
314             [@message_frag_lens]
315         );
316         $message->parse();
317     } elsif ($mt == MT_ENCRYPTED_EXTENSIONS) {
318         $message = TLSProxy::EncryptedExtensions->new(
319             $server,
320             $data,
321             [@message_rec_list],
322             $startoffset,
323             [@message_frag_lens]
324         );
325         $message->parse();
326     } elsif ($mt == MT_CERTIFICATE) {
327         $message = TLSProxy::Certificate->new(
328             $server,
329             $data,
330             [@message_rec_list],
331             $startoffset,
332             [@message_frag_lens]
333         );
334         $message->parse();
335     } elsif ($mt == MT_CERTIFICATE_VERIFY) {
336         $message = TLSProxy::CertificateVerify->new(
337             $server,
338             $data,
339             [@message_rec_list],
340             $startoffset,
341             [@message_frag_lens]
342         );
343         $message->parse();
344     } elsif ($mt == MT_SERVER_KEY_EXCHANGE) {
345         $message = TLSProxy::ServerKeyExchange->new(
346             $server,
347             $data,
348             [@message_rec_list],
349             $startoffset,
350             [@message_frag_lens]
351         );
352         $message->parse();
353     } elsif ($mt == MT_NEW_SESSION_TICKET) {
354         $message = TLSProxy::NewSessionTicket->new(
355             $server,
356             $data,
357             [@message_rec_list],
358             $startoffset,
359             [@message_frag_lens]
360         );
361         $message->parse();
362     } else {
363         #Unknown message type
364         $message = TLSProxy::Message->new(
365             $server,
366             $mt,
367             $data,
368             [@message_rec_list],
369             $startoffset,
370             [@message_frag_lens]
371         );
372     }
373
374     return $message;
375 }
376
377 sub end
378 {
379     my $class = shift;
380     return $end;
381 }
382 sub success
383 {
384     my $class = shift;
385     return $success;
386 }
387 sub fail
388 {
389     my $class = shift;
390     return !$success && $end;
391 }
392 sub new
393 {
394     my $class = shift;
395     my ($server,
396         $mt,
397         $data,
398         $records,
399         $startoffset,
400         $message_frag_lens) = @_;
401     
402     my $self = {
403         server => $server,
404         data => $data,
405         records => $records,
406         mt => $mt,
407         startoffset => $startoffset,
408         message_frag_lens => $message_frag_lens
409     };
410
411     return bless $self, $class;
412 }
413
414 sub ciphersuite
415 {
416     my $class = shift;
417     if (@_) {
418       $ciphersuite = shift;
419     }
420     return $ciphersuite;
421 }
422
423 #Update all the underlying records with the modified data from this message
424 #Note: Only supports re-encrypting for TLSv1.3
425 sub repack
426 {
427     my $self = shift;
428     my $msgdata;
429
430     my $numrecs = $#{$self->records};
431
432     $self->set_message_contents();
433
434     my $lenhi;
435     my $lenlo;
436
437     $lenlo = length($self->data) & 0xff;
438     $lenhi = length($self->data) >> 8;
439     $msgdata = pack('CnC', $self->mt, $lenhi, $lenlo).$self->data;
440
441     if ($numrecs == 0) {
442         #The message is fully contained within one record
443         my ($rec) = @{$self->records};
444         my $recdata = $rec->decrypt_data;
445
446         my $old_length;
447
448         # We use empty message_frag_lens to indicates that pre-repacking,
449         # the message wasn't present. The first fragment length doesn't include
450         # the TLS header, so we need to check and compute the right length.
451         if (@{$self->message_frag_lens}) {
452             $old_length = ${$self->message_frag_lens}[0] +
453               TLS_MESSAGE_HEADER_LENGTH;
454         } else {
455             $old_length = 0;
456         }
457
458         my $prefix = substr($recdata, 0, $self->startoffset);
459         my $suffix = substr($recdata, $self->startoffset + $old_length);
460
461         $rec->decrypt_data($prefix.($msgdata).($suffix));
462         # TODO(openssl-team): don't keep explicit lengths.
463         # (If a length override is ever needed to construct invalid packets,
464         #  use an explicit override field instead.)
465         $rec->decrypt_len(length($rec->decrypt_data));
466         $rec->len($rec->len + length($msgdata) - $old_length);
467         # Only support re-encryption for TLSv1.3.
468         if (TLSProxy::Proxy->is_tls13() && $rec->encrypted()) {
469             #Add content type (1 byte) and 16 tag bytes
470             $rec->data($rec->decrypt_data
471                 .pack("C", TLSProxy::Record::RT_HANDSHAKE).("\0"x16));
472         } else {
473             $rec->data($rec->decrypt_data);
474         }
475
476         #Update the fragment len in case we changed it above
477         ${$self->message_frag_lens}[0] = length($msgdata)
478                                          - TLS_MESSAGE_HEADER_LENGTH;
479         return;
480     }
481
482     #Note we don't currently support changing a fragmented message length
483     my $recctr = 0;
484     my $datadone = 0;
485     foreach my $rec (@{$self->records}) {
486         my $recdata = $rec->decrypt_data;
487         if ($recctr == 0) {
488             #This is the first record
489             my $remainlen = length($recdata) - $self->startoffset;
490             $rec->data(substr($recdata, 0, $self->startoffset)
491                        .substr(($msgdata), 0, $remainlen));
492             $datadone += $remainlen;
493         } elsif ($recctr + 1 == $numrecs) {
494             #This is the last record
495             $rec->data(substr($msgdata, $datadone));
496         } else {
497             #This is a middle record
498             $rec->data(substr($msgdata, $datadone, length($rec->data)));
499             $datadone += length($rec->data);
500         }
501         $recctr++;
502     }
503 }
504
505 #To be overridden by sub-classes
506 sub set_message_contents
507 {
508 }
509
510 #Read only accessors
511 sub server
512 {
513     my $self = shift;
514     return $self->{server};
515 }
516
517 #Read/write accessors
518 sub mt
519 {
520     my $self = shift;
521     if (@_) {
522       $self->{mt} = shift;
523     }
524     return $self->{mt};
525 }
526 sub data
527 {
528     my $self = shift;
529     if (@_) {
530       $self->{data} = shift;
531     }
532     return $self->{data};
533 }
534 sub records
535 {
536     my $self = shift;
537     if (@_) {
538       $self->{records} = shift;
539     }
540     return $self->{records};
541 }
542 sub startoffset
543 {
544     my $self = shift;
545     if (@_) {
546       $self->{startoffset} = shift;
547     }
548     return $self->{startoffset};
549 }
550 sub message_frag_lens
551 {
552     my $self = shift;
553     if (@_) {
554       $self->{message_frag_lens} = shift;
555     }
556     return $self->{message_frag_lens};
557 }
558 sub encoded_length
559 {
560     my $self = shift;
561     return TLS_MESSAGE_HEADER_LENGTH + length($self->data);
562 }
563 sub successondata
564 {
565     my $class = shift;
566     if (@_) {
567         $successondata = shift;
568     }
569     return $successondata;
570 }
571 1;