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