Remove a spurious TLSProxy byte in TLSv1.3
[openssl.git] / util / perl / TLSProxy / Message.pm
1 # Copyright 2016-2018 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_ENCRYPTED_EXTENSIONS => 8,
21     MT_CERTIFICATE => 11,
22     MT_SERVER_KEY_EXCHANGE => 12,
23     MT_CERTIFICATE_REQUEST => 13,
24     MT_SERVER_HELLO_DONE => 14,
25     MT_CERTIFICATE_VERIFY => 15,
26     MT_CLIENT_KEY_EXCHANGE => 16,
27     MT_FINISHED => 20,
28     MT_CERTIFICATE_STATUS => 22,
29     MT_NEXT_PROTO => 67
30 };
31
32 #Alert levels
33 use constant {
34     AL_LEVEL_WARN => 1,
35     AL_LEVEL_FATAL => 2
36 };
37
38 #Alert descriptions
39 use constant {
40     AL_DESC_CLOSE_NOTIFY => 0,
41     AL_DESC_UNEXPECTED_MESSAGE => 10,
42     AL_DESC_NO_RENEGOTIATION => 100
43 };
44
45 my %message_type = (
46     MT_HELLO_REQUEST, "HelloRequest",
47     MT_CLIENT_HELLO, "ClientHello",
48     MT_SERVER_HELLO, "ServerHello",
49     MT_NEW_SESSION_TICKET, "NewSessionTicket",
50     MT_ENCRYPTED_EXTENSIONS, "EncryptedExtensions",
51     MT_CERTIFICATE, "Certificate",
52     MT_SERVER_KEY_EXCHANGE, "ServerKeyExchange",
53     MT_CERTIFICATE_REQUEST, "CertificateRequest",
54     MT_SERVER_HELLO_DONE, "ServerHelloDone",
55     MT_CERTIFICATE_VERIFY, "CertificateVerify",
56     MT_CLIENT_KEY_EXCHANGE, "ClientKeyExchange",
57     MT_FINISHED, "Finished",
58     MT_CERTIFICATE_STATUS, "CertificateStatus",
59     MT_NEXT_PROTO, "NextProto"
60 );
61
62 use constant {
63     EXT_SERVER_NAME => 0,
64     EXT_MAX_FRAGMENT_LENGTH => 1,
65     EXT_STATUS_REQUEST => 5,
66     EXT_SUPPORTED_GROUPS => 10,
67     EXT_EC_POINT_FORMATS => 11,
68     EXT_SRP => 12,
69     EXT_SIG_ALGS => 13,
70     EXT_USE_SRTP => 14,
71     EXT_ALPN => 16,
72     EXT_SCT => 18,
73     EXT_PADDING => 21,
74     EXT_ENCRYPT_THEN_MAC => 22,
75     EXT_EXTENDED_MASTER_SECRET => 23,
76     EXT_SESSION_TICKET => 35,
77     EXT_KEY_SHARE => 51,
78     EXT_PSK => 41,
79     EXT_SUPPORTED_VERSIONS => 43,
80     EXT_COOKIE => 44,
81     EXT_PSK_KEX_MODES => 45,
82     EXT_POST_HANDSHAKE_AUTH => 49,
83     EXT_SIG_ALGS_CERT => 50,
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 (!TLSProxy::Proxy->is_tls13()) {
176             if ($server) {
177                 TLSProxy::Record->server_encrypting(1);
178             } else {
179                 TLSProxy::Record->client_encrypting(1);
180             }
181         }
182     } elsif ($record->content_type == TLSProxy::Record::RT_HANDSHAKE) {
183         if ($record->len == 0 || $record->len_real == 0) {
184             print "  Message truncated\n";
185         } else {
186             my $recoffset = 0;
187
188             if (length $payload > 0) {
189                 #We are continuing processing a message started in a previous
190                 #record. Add this record to the list associated with this
191                 #message
192                 push @message_rec_list, $record;
193
194                 if ($messlen <= length($payload)) {
195                     #Shouldn't happen
196                     die "Internal error: invalid messlen: ".$messlen
197                         ." payload length:".length($payload)."\n";
198                 }
199                 if (length($payload) + $record->decrypt_len >= $messlen) {
200                     #We can complete the message with this record
201                     $recoffset = $messlen - length($payload);
202                     $payload .= substr($record->decrypt_data, 0, $recoffset);
203                     push @message_frag_lens, $recoffset;
204                     $message = create_message($server, $mt, $payload,
205                                               $startoffset);
206                     push @messages, $message;
207
208                     $payload = "";
209                 } else {
210                     #This is just part of the total message
211                     $payload .= $record->decrypt_data;
212                     $recoffset = $record->decrypt_len;
213                     push @message_frag_lens, $record->decrypt_len;
214                 }
215                 print "  Partial message data read: ".$recoffset." bytes\n";
216             }
217
218             while ($record->decrypt_len > $recoffset) {
219                 #We are at the start of a new message
220                 if ($record->decrypt_len - $recoffset < 4) {
221                     #Whilst technically probably valid we can't cope with this
222                     die "End of record in the middle of a message header\n";
223                 }
224                 @message_rec_list = ($record);
225                 my $lenhi;
226                 my $lenlo;
227                 ($mt, $lenhi, $lenlo) = unpack('CnC',
228                                                substr($record->decrypt_data,
229                                                       $recoffset));
230                 $messlen = ($lenhi << 8) | $lenlo;
231                 print "  Message type: $message_type{$mt}\n";
232                 print "  Message Length: $messlen\n";
233                 $startoffset = $recoffset;
234                 $recoffset += 4;
235                 $payload = "";
236                 
237                 if ($recoffset <= $record->decrypt_len) {
238                     #Some payload data is present in this record
239                     if ($record->decrypt_len - $recoffset >= $messlen) {
240                         #We can complete the message with this record
241                         $payload .= substr($record->decrypt_data, $recoffset,
242                                            $messlen);
243                         $recoffset += $messlen;
244                         push @message_frag_lens, $messlen;
245                         $message = create_message($server, $mt, $payload,
246                                                   $startoffset);
247                         push @messages, $message;
248
249                         $payload = "";
250                     } else {
251                         #This is just part of the total message
252                         $payload .= substr($record->decrypt_data, $recoffset,
253                                            $record->decrypt_len - $recoffset);
254                         $recoffset = $record->decrypt_len;
255                         push @message_frag_lens, $recoffset;
256                     }
257                 }
258             }
259         }
260     } elsif ($record->content_type == TLSProxy::Record::RT_APPLICATION_DATA) {
261         print "  [ENCRYPTED APPLICATION DATA]\n";
262         print "  [".$record->decrypt_data."]\n";
263
264         if ($successondata) {
265             $success = 1;
266             $end = 1;
267         }
268     } elsif ($record->content_type == TLSProxy::Record::RT_ALERT) {
269         my ($alertlev, $alertdesc) = unpack('CC', $record->decrypt_data);
270         #A CloseNotify from the client indicates we have finished successfully
271         #(we assume)
272         if (!$end && !$server && $alertlev == AL_LEVEL_WARN
273             && $alertdesc == AL_DESC_CLOSE_NOTIFY) {
274             $success = 1;
275         }
276         #All alerts end the test
277         $end = 1;
278     }
279
280     return @messages;
281 }
282
283 #Function to work out which sub-class we need to create and then
284 #construct it
285 sub create_message
286 {
287     my ($server, $mt, $data, $startoffset) = @_;
288     my $message;
289
290     #We only support ClientHello in this version...needs to be extended for
291     #others
292     if ($mt == MT_CLIENT_HELLO) {
293         $message = TLSProxy::ClientHello->new(
294             $server,
295             $data,
296             [@message_rec_list],
297             $startoffset,
298             [@message_frag_lens]
299         );
300         $message->parse();
301     } elsif ($mt == MT_SERVER_HELLO) {
302         $message = TLSProxy::ServerHello->new(
303             $server,
304             $data,
305             [@message_rec_list],
306             $startoffset,
307             [@message_frag_lens]
308         );
309         $message->parse();
310     } elsif ($mt == MT_ENCRYPTED_EXTENSIONS) {
311         $message = TLSProxy::EncryptedExtensions->new(
312             $server,
313             $data,
314             [@message_rec_list],
315             $startoffset,
316             [@message_frag_lens]
317         );
318         $message->parse();
319     } elsif ($mt == MT_CERTIFICATE) {
320         $message = TLSProxy::Certificate->new(
321             $server,
322             $data,
323             [@message_rec_list],
324             $startoffset,
325             [@message_frag_lens]
326         );
327         $message->parse();
328     } elsif ($mt == MT_CERTIFICATE_VERIFY) {
329         $message = TLSProxy::CertificateVerify->new(
330             $server,
331             $data,
332             [@message_rec_list],
333             $startoffset,
334             [@message_frag_lens]
335         );
336         $message->parse();
337     } elsif ($mt == MT_SERVER_KEY_EXCHANGE) {
338         $message = TLSProxy::ServerKeyExchange->new(
339             $server,
340             $data,
341             [@message_rec_list],
342             $startoffset,
343             [@message_frag_lens]
344         );
345         $message->parse();
346     } elsif ($mt == MT_NEW_SESSION_TICKET) {
347         $message = TLSProxy::NewSessionTicket->new(
348             $server,
349             $data,
350             [@message_rec_list],
351             $startoffset,
352             [@message_frag_lens]
353         );
354         $message->parse();
355     } else {
356         #Unknown message type
357         $message = TLSProxy::Message->new(
358             $server,
359             $mt,
360             $data,
361             [@message_rec_list],
362             $startoffset,
363             [@message_frag_lens]
364         );
365     }
366
367     return $message;
368 }
369
370 sub end
371 {
372     my $class = shift;
373     return $end;
374 }
375 sub success
376 {
377     my $class = shift;
378     return $success;
379 }
380 sub fail
381 {
382     my $class = shift;
383     return !$success && $end;
384 }
385 sub new
386 {
387     my $class = shift;
388     my ($server,
389         $mt,
390         $data,
391         $records,
392         $startoffset,
393         $message_frag_lens) = @_;
394     
395     my $self = {
396         server => $server,
397         data => $data,
398         records => $records,
399         mt => $mt,
400         startoffset => $startoffset,
401         message_frag_lens => $message_frag_lens
402     };
403
404     return bless $self, $class;
405 }
406
407 sub ciphersuite
408 {
409     my $class = shift;
410     if (@_) {
411       $ciphersuite = shift;
412     }
413     return $ciphersuite;
414 }
415
416 #Update all the underlying records with the modified data from this message
417 #Note: Only supports re-encrypting for TLSv1.3
418 sub repack
419 {
420     my $self = shift;
421     my $msgdata;
422
423     my $numrecs = $#{$self->records};
424
425     $self->set_message_contents();
426
427     my $lenhi;
428     my $lenlo;
429
430     $lenlo = length($self->data) & 0xff;
431     $lenhi = length($self->data) >> 8;
432     $msgdata = pack('CnC', $self->mt, $lenhi, $lenlo).$self->data;
433
434     if ($numrecs == 0) {
435         #The message is fully contained within one record
436         my ($rec) = @{$self->records};
437         my $recdata = $rec->decrypt_data;
438
439         my $old_length;
440
441         # We use empty message_frag_lens to indicates that pre-repacking,
442         # the message wasn't present. The first fragment length doesn't include
443         # the TLS header, so we need to check and compute the right length.
444         if (@{$self->message_frag_lens}) {
445             $old_length = ${$self->message_frag_lens}[0] +
446               TLS_MESSAGE_HEADER_LENGTH;
447         } else {
448             $old_length = 0;
449         }
450
451         my $prefix = substr($recdata, 0, $self->startoffset);
452         my $suffix = substr($recdata, $self->startoffset + $old_length);
453
454         $rec->decrypt_data($prefix.($msgdata).($suffix));
455         # TODO(openssl-team): don't keep explicit lengths.
456         # (If a length override is ever needed to construct invalid packets,
457         #  use an explicit override field instead.)
458         $rec->decrypt_len(length($rec->decrypt_data));
459         $rec->len($rec->len + length($msgdata) - $old_length);
460         # Only support re-encryption for TLSv1.3.
461         if (TLSProxy::Proxy->is_tls13() && $rec->encrypted()) {
462             #Add content type (1 byte) and 16 tag bytes
463             $rec->data($rec->decrypt_data
464                 .pack("C", TLSProxy::Record::RT_HANDSHAKE).("\0"x16));
465         } else {
466             $rec->data($rec->decrypt_data);
467         }
468
469         #Update the fragment len in case we changed it above
470         ${$self->message_frag_lens}[0] = length($msgdata)
471                                          - TLS_MESSAGE_HEADER_LENGTH;
472         return;
473     }
474
475     #Note we don't currently support changing a fragmented message length
476     my $recctr = 0;
477     my $datadone = 0;
478     foreach my $rec (@{$self->records}) {
479         my $recdata = $rec->decrypt_data;
480         if ($recctr == 0) {
481             #This is the first record
482             my $remainlen = length($recdata) - $self->startoffset;
483             $rec->data(substr($recdata, 0, $self->startoffset)
484                        .substr(($msgdata), 0, $remainlen));
485             $datadone += $remainlen;
486         } elsif ($recctr + 1 == $numrecs) {
487             #This is the last record
488             $rec->data(substr($msgdata, $datadone));
489         } else {
490             #This is a middle record
491             $rec->data(substr($msgdata, $datadone, length($rec->data)));
492             $datadone += length($rec->data);
493         }
494         $recctr++;
495     }
496 }
497
498 #To be overridden by sub-classes
499 sub set_message_contents
500 {
501 }
502
503 #Read only accessors
504 sub server
505 {
506     my $self = shift;
507     return $self->{server};
508 }
509
510 #Read/write accessors
511 sub mt
512 {
513     my $self = shift;
514     if (@_) {
515       $self->{mt} = shift;
516     }
517     return $self->{mt};
518 }
519 sub data
520 {
521     my $self = shift;
522     if (@_) {
523       $self->{data} = shift;
524     }
525     return $self->{data};
526 }
527 sub records
528 {
529     my $self = shift;
530     if (@_) {
531       $self->{records} = shift;
532     }
533     return $self->{records};
534 }
535 sub startoffset
536 {
537     my $self = shift;
538     if (@_) {
539       $self->{startoffset} = shift;
540     }
541     return $self->{startoffset};
542 }
543 sub message_frag_lens
544 {
545     my $self = shift;
546     if (@_) {
547       $self->{message_frag_lens} = shift;
548     }
549     return $self->{message_frag_lens};
550 }
551 sub encoded_length
552 {
553     my $self = shift;
554     return TLS_MESSAGE_HEADER_LENGTH + length($self->data);
555 }
556 sub successondata
557 {
558     my $class = shift;
559     if (@_) {
560         $successondata = shift;
561     }
562     return $successondata;
563 }
564 1;