Add a test for mismatch between key OID and sig alg
[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_RSAE_SHA256 => 0x0804,
107     SIG_ALG_RSA_PSS_RSAE_SHA384 => 0x0805,
108     SIG_ALG_RSA_PSS_RSAE_SHA512 => 0x0806,
109     SIG_ALG_ED25519 => 0x0807,
110     SIG_ALG_ED448 => 0x0808,
111     SIG_ALG_RSA_PSS_PSS_SHA256 => 0x0809,
112     SIG_ALG_RSA_PSS_PSS_SHA384 => 0x080a,
113     SIG_ALG_RSA_PSS_PSS_SHA512 => 0x080b,
114     SIG_ALG_RSA_PKCS1_SHA1 => 0x0201,
115     SIG_ALG_ECDSA_SHA1 => 0x0203,
116     SIG_ALG_DSA_SHA1 => 0x0202,
117     SIG_ALG_DSA_SHA256 => 0x0402,
118     SIG_ALG_DSA_SHA384 => 0x0502,
119     SIG_ALG_DSA_SHA512 => 0x0602,
120     OSSL_SIG_ALG_RSA_PKCS1_SHA224 => 0x0301,
121     OSSL_SIG_ALG_DSA_SHA224 => 0x0302,
122     OSSL_SIG_ALG_ECDSA_SHA224 => 0x0303
123 };
124
125 use constant {
126     CIPHER_DHE_RSA_AES_128_SHA => 0x0033,
127     CIPHER_ADH_AES_128_SHA => 0x0034,
128     CIPHER_TLS13_AES_128_GCM_SHA256 => 0x1301,
129     CIPHER_TLS13_AES_256_GCM_SHA384 => 0x1302
130 };
131
132 my $payload = "";
133 my $messlen = -1;
134 my $mt;
135 my $startoffset = -1;
136 my $server = 0;
137 my $success = 0;
138 my $end = 0;
139 my @message_rec_list = ();
140 my @message_frag_lens = ();
141 my $ciphersuite = 0;
142 my $successondata = 0;
143
144 sub clear
145 {
146     $payload = "";
147     $messlen = -1;
148     $startoffset = -1;
149     $server = 0;
150     $success = 0;
151     $end = 0;
152     $successondata = 0;
153     @message_rec_list = ();
154     @message_frag_lens = ();
155 }
156
157 #Class method to extract messages from a record
158 sub get_messages
159 {
160     my $class = shift;
161     my $serverin = shift;
162     my $record = shift;
163     my @messages = ();
164     my $message;
165
166     @message_frag_lens = ();
167
168     if ($serverin != $server && length($payload) != 0) {
169         die "Changed peer, but we still have fragment data\n";
170     }
171     $server = $serverin;
172
173     if ($record->content_type == TLSProxy::Record::RT_CCS) {
174         if ($payload ne "") {
175             #We can't handle this yet
176             die "CCS received before message data complete\n";
177         }
178         if (!TLSProxy::Proxy->is_tls13()) {
179             if ($server) {
180                 TLSProxy::Record->server_encrypting(1);
181             } else {
182                 TLSProxy::Record->client_encrypting(1);
183             }
184         }
185     } elsif ($record->content_type == TLSProxy::Record::RT_HANDSHAKE) {
186         if ($record->len == 0 || $record->len_real == 0) {
187             print "  Message truncated\n";
188         } else {
189             my $recoffset = 0;
190
191             if (length $payload > 0) {
192                 #We are continuing processing a message started in a previous
193                 #record. Add this record to the list associated with this
194                 #message
195                 push @message_rec_list, $record;
196
197                 if ($messlen <= length($payload)) {
198                     #Shouldn't happen
199                     die "Internal error: invalid messlen: ".$messlen
200                         ." payload length:".length($payload)."\n";
201                 }
202                 if (length($payload) + $record->decrypt_len >= $messlen) {
203                     #We can complete the message with this record
204                     $recoffset = $messlen - length($payload);
205                     $payload .= substr($record->decrypt_data, 0, $recoffset);
206                     push @message_frag_lens, $recoffset;
207                     $message = create_message($server, $mt, $payload,
208                                               $startoffset);
209                     push @messages, $message;
210
211                     $payload = "";
212                 } else {
213                     #This is just part of the total message
214                     $payload .= $record->decrypt_data;
215                     $recoffset = $record->decrypt_len;
216                     push @message_frag_lens, $record->decrypt_len;
217                 }
218                 print "  Partial message data read: ".$recoffset." bytes\n";
219             }
220
221             while ($record->decrypt_len > $recoffset) {
222                 #We are at the start of a new message
223                 if ($record->decrypt_len - $recoffset < 4) {
224                     #Whilst technically probably valid we can't cope with this
225                     die "End of record in the middle of a message header\n";
226                 }
227                 @message_rec_list = ($record);
228                 my $lenhi;
229                 my $lenlo;
230                 ($mt, $lenhi, $lenlo) = unpack('CnC',
231                                                substr($record->decrypt_data,
232                                                       $recoffset));
233                 $messlen = ($lenhi << 8) | $lenlo;
234                 print "  Message type: $message_type{$mt}\n";
235                 print "  Message Length: $messlen\n";
236                 $startoffset = $recoffset;
237                 $recoffset += 4;
238                 $payload = "";
239                 
240                 if ($recoffset <= $record->decrypt_len) {
241                     #Some payload data is present in this record
242                     if ($record->decrypt_len - $recoffset >= $messlen) {
243                         #We can complete the message with this record
244                         $payload .= substr($record->decrypt_data, $recoffset,
245                                            $messlen);
246                         $recoffset += $messlen;
247                         push @message_frag_lens, $messlen;
248                         $message = create_message($server, $mt, $payload,
249                                                   $startoffset);
250                         push @messages, $message;
251
252                         $payload = "";
253                     } else {
254                         #This is just part of the total message
255                         $payload .= substr($record->decrypt_data, $recoffset,
256                                            $record->decrypt_len - $recoffset);
257                         $recoffset = $record->decrypt_len;
258                         push @message_frag_lens, $recoffset;
259                     }
260                 }
261             }
262         }
263     } elsif ($record->content_type == TLSProxy::Record::RT_APPLICATION_DATA) {
264         print "  [ENCRYPTED APPLICATION DATA]\n";
265         print "  [".$record->decrypt_data."]\n";
266
267         if ($successondata) {
268             $success = 1;
269             $end = 1;
270         }
271     } elsif ($record->content_type == TLSProxy::Record::RT_ALERT) {
272         my ($alertlev, $alertdesc) = unpack('CC', $record->decrypt_data);
273         print "  [$alertlev, $alertdesc]\n";
274         #A CloseNotify from the client indicates we have finished successfully
275         #(we assume)
276         if (!$end && !$server && $alertlev == AL_LEVEL_WARN
277             && $alertdesc == AL_DESC_CLOSE_NOTIFY) {
278             $success = 1;
279         }
280         #Fatal or close notify alerts end the test
281         if ($alertlev == AL_LEVEL_FATAL || $alertdesc == AL_DESC_CLOSE_NOTIFY) {
282             $end = 1;
283         }
284     }
285
286     return @messages;
287 }
288
289 #Function to work out which sub-class we need to create and then
290 #construct it
291 sub create_message
292 {
293     my ($server, $mt, $data, $startoffset) = @_;
294     my $message;
295
296     #We only support ClientHello in this version...needs to be extended for
297     #others
298     if ($mt == MT_CLIENT_HELLO) {
299         $message = TLSProxy::ClientHello->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;