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