Copyright consolidation; .pm and Configure
[openssl.git] / util / 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_CERTIFICATE => 11,
21     MT_SERVER_KEY_EXCHANGE => 12,
22     MT_CERTIFICATE_REQUEST => 13,
23     MT_SERVER_HELLO_DONE => 14,
24     MT_CERTIFICATE_VERIFY => 15,
25     MT_CLIENT_KEY_EXCHANGE => 16,
26     MT_FINISHED => 20,
27     MT_CERTIFICATE_STATUS => 22,
28     MT_NEXT_PROTO => 67
29 };
30
31 #Alert levels
32 use constant {
33     AL_LEVEL_WARN => 1,
34     AL_LEVEL_FATAL => 2
35 };
36
37 #Alert descriptions
38 use constant {
39     AL_DESC_CLOSE_NOTIFY => 0
40 };
41
42 my %message_type = (
43     MT_HELLO_REQUEST, "HelloRequest",
44     MT_CLIENT_HELLO, "ClientHello",
45     MT_SERVER_HELLO, "ServerHello",
46     MT_NEW_SESSION_TICKET, "NewSessionTicket",
47     MT_CERTIFICATE, "Certificate",
48     MT_SERVER_KEY_EXCHANGE, "ServerKeyExchange",
49     MT_CERTIFICATE_REQUEST, "CertificateRequest",
50     MT_SERVER_HELLO_DONE, "ServerHelloDone",
51     MT_CERTIFICATE_VERIFY, "CertificateVerify",
52     MT_CLIENT_KEY_EXCHANGE, "ClientKeyExchange",
53     MT_FINISHED, "Finished",
54     MT_CERTIFICATE_STATUS, "CertificateStatus",
55     MT_NEXT_PROTO, "NextProto"
56 );
57
58 use constant {
59     EXT_STATUS_REQUEST => 5,
60     EXT_ENCRYPT_THEN_MAC => 22,
61     EXT_EXTENDED_MASTER_SECRET => 23,
62     EXT_SESSION_TICKET => 35,
63     # This extension does not exist and isn't recognised by OpenSSL.
64     # We use it to test handling of duplicate extensions.
65     EXT_DUPLICATE_EXTENSION => 1234
66 };
67
68 my $payload = "";
69 my $messlen = -1;
70 my $mt;
71 my $startoffset = -1;
72 my $server = 0;
73 my $success = 0;
74 my $end = 0;
75 my @message_rec_list = ();
76 my @message_frag_lens = ();
77 my $ciphersuite = 0;
78
79 sub clear
80 {
81     $payload = "";
82     $messlen = -1;
83     $startoffset = -1;
84     $server = 0;
85     $success = 0;
86     $end = 0;
87     @message_rec_list = ();
88     @message_frag_lens = ();
89 }
90
91 #Class method to extract messages from a record
92 sub get_messages
93 {
94     my $class = shift;
95     my $serverin = shift;
96     my $record = shift;
97     my @messages = ();
98     my $message;
99
100     @message_frag_lens = ();
101
102     if ($serverin != $server && length($payload) != 0) {
103         die "Changed peer, but we still have fragment data\n";
104     }
105     $server = $serverin;
106
107     if ($record->content_type == TLSProxy::Record::RT_CCS) {
108         if ($payload ne "") {
109             #We can't handle this yet
110             die "CCS received before message data complete\n";
111         }
112         if ($server) {
113             TLSProxy::Record->server_ccs_seen(1);
114         } else {
115             TLSProxy::Record->client_ccs_seen(1);
116         }
117     } elsif ($record->content_type == TLSProxy::Record::RT_HANDSHAKE) {
118         if ($record->len == 0 || $record->len_real == 0) {
119             print "  Message truncated\n";
120         } else {
121             my $recoffset = 0;
122
123             if (length $payload > 0) {
124                 #We are continuing processing a message started in a previous
125                 #record. Add this record to the list associated with this
126                 #message
127                 push @message_rec_list, $record;
128
129                 if ($messlen <= length($payload)) {
130                     #Shouldn't happen
131                     die "Internal error: invalid messlen: ".$messlen
132                         ." payload length:".length($payload)."\n";
133                 }
134                 if (length($payload) + $record->decrypt_len >= $messlen) {
135                     #We can complete the message with this record
136                     $recoffset = $messlen - length($payload);
137                     $payload .= substr($record->decrypt_data, 0, $recoffset);
138                     push @message_frag_lens, $recoffset;
139                     $message = create_message($server, $mt, $payload,
140                                               $startoffset);
141                     push @messages, $message;
142
143                     $payload = "";
144                 } else {
145                     #This is just part of the total message
146                     $payload .= $record->decrypt_data;
147                     $recoffset = $record->decrypt_len;
148                     push @message_frag_lens, $record->decrypt_len;
149                 }
150                 print "  Partial message data read: ".$recoffset." bytes\n";
151             }
152
153             while ($record->decrypt_len > $recoffset) {
154                 #We are at the start of a new message
155                 if ($record->decrypt_len - $recoffset < 4) {
156                     #Whilst technically probably valid we can't cope with this
157                     die "End of record in the middle of a message header\n";
158                 }
159                 @message_rec_list = ($record);
160                 my $lenhi;
161                 my $lenlo;
162                 ($mt, $lenhi, $lenlo) = unpack('CnC',
163                                                substr($record->decrypt_data,
164                                                       $recoffset));
165                 $messlen = ($lenhi << 8) | $lenlo;
166                 print "  Message type: $message_type{$mt}\n";
167                 print "  Message Length: $messlen\n";
168                 $startoffset = $recoffset;
169                 $recoffset += 4;
170                 $payload = "";
171                 
172                 if ($recoffset < $record->decrypt_len) {
173                     #Some payload data is present in this record
174                     if ($record->decrypt_len - $recoffset >= $messlen) {
175                         #We can complete the message with this record
176                         $payload .= substr($record->decrypt_data, $recoffset,
177                                            $messlen);
178                         $recoffset += $messlen;
179                         push @message_frag_lens, $messlen;
180                         $message = create_message($server, $mt, $payload,
181                                                   $startoffset);
182                         push @messages, $message;
183
184                         $payload = "";
185                     } else {
186                         #This is just part of the total message
187                         $payload .= substr($record->decrypt_data, $recoffset,
188                                            $record->decrypt_len - $recoffset);
189                         $recoffset = $record->decrypt_len;
190                         push @message_frag_lens, $recoffset;
191                     }
192                 }
193             }
194         }
195     } elsif ($record->content_type == TLSProxy::Record::RT_APPLICATION_DATA) {
196         print "  [ENCRYPTED APPLICATION DATA]\n";
197         print "  [".$record->decrypt_data."]\n";
198     } elsif ($record->content_type == TLSProxy::Record::RT_ALERT) {
199         my ($alertlev, $alertdesc) = unpack('CC', $record->decrypt_data);
200         #All alerts end the test
201         $end = 1;
202         #A CloseNotify from the client indicates we have finished successfully
203         #(we assume)
204         if (!$server && $alertlev == AL_LEVEL_WARN
205             && $alertdesc == AL_DESC_CLOSE_NOTIFY) {
206             $success = 1;
207         }
208     }
209
210     return @messages;
211 }
212
213 #Function to work out which sub-class we need to create and then
214 #construct it
215 sub create_message
216 {
217     my ($server, $mt, $data, $startoffset) = @_;
218     my $message;
219
220     #We only support ClientHello in this version...needs to be extended for
221     #others
222     if ($mt == MT_CLIENT_HELLO) {
223         $message = TLSProxy::ClientHello->new(
224             $server,
225             $data,
226             [@message_rec_list],
227             $startoffset,
228             [@message_frag_lens]
229         );
230         $message->parse();
231     } elsif ($mt == MT_SERVER_HELLO) {
232         $message = TLSProxy::ServerHello->new(
233             $server,
234             $data,
235             [@message_rec_list],
236             $startoffset,
237             [@message_frag_lens]
238         );
239         $message->parse();
240     } elsif ($mt == MT_SERVER_KEY_EXCHANGE) {
241         $message = TLSProxy::ServerKeyExchange->new(
242             $server,
243             $data,
244             [@message_rec_list],
245             $startoffset,
246             [@message_frag_lens]
247         );
248         $message->parse();
249     } elsif ($mt == MT_NEW_SESSION_TICKET) {
250         $message = TLSProxy::NewSessionTicket->new(
251             $server,
252             $data,
253             [@message_rec_list],
254             $startoffset,
255             [@message_frag_lens]
256         );
257         $message->parse();
258     } else {
259         #Unknown message type
260         $message = TLSProxy::Message->new(
261             $server,
262             $mt,
263             $data,
264             [@message_rec_list],
265             $startoffset,
266             [@message_frag_lens]
267         );
268     }
269
270     return $message;
271 }
272
273 sub end
274 {
275     my $class = shift;
276     return $end;
277 }
278 sub success
279 {
280     my $class = shift;
281     return $success;
282 }
283 sub fail
284 {
285     my $class = shift;
286     return !$success && $end;
287 }
288 sub new
289 {
290     my $class = shift;
291     my ($server,
292         $mt,
293         $data,
294         $records,
295         $startoffset,
296         $message_frag_lens) = @_;
297     
298     my $self = {
299         server => $server,
300         data => $data,
301         records => $records,
302         mt => $mt,
303         startoffset => $startoffset,
304         message_frag_lens => $message_frag_lens
305     };
306
307     return bless $self, $class;
308 }
309
310 sub ciphersuite
311 {
312     my $class = shift;
313     if (@_) {
314       $ciphersuite = shift;
315     }
316     return $ciphersuite;
317 }
318
319 #Update all the underlying records with the modified data from this message
320 #Note: Does not currently support re-encrypting
321 sub repack
322 {
323     my $self = shift;
324     my $msgdata;
325
326     my $numrecs = $#{$self->records};
327
328     $self->set_message_contents();
329
330     my $lenhi;
331     my $lenlo;
332
333     $lenlo = length($self->data) & 0xff;
334     $lenhi = length($self->data) >> 8;
335     $msgdata = pack('CnC', $self->mt, $lenhi, $lenlo).$self->data;
336
337     if ($numrecs == 0) {
338         #The message is fully contained within one record
339         my ($rec) = @{$self->records};
340         my $recdata = $rec->decrypt_data;
341
342         my $old_length;
343
344         # We use empty message_frag_lens to indicates that pre-repacking,
345         # the message wasn't present. The first fragment length doesn't include
346         # the TLS header, so we need to check and compute the right length.
347         if (@{$self->message_frag_lens}) {
348             $old_length = ${$self->message_frag_lens}[0] +
349               TLS_MESSAGE_HEADER_LENGTH;
350         } else {
351             $old_length = 0;
352         }
353
354         my $prefix = substr($recdata, 0, $self->startoffset);
355         my $suffix = substr($recdata, $self->startoffset + $old_length);
356
357         $rec->decrypt_data($prefix.($msgdata).($suffix));
358         # TODO(openssl-team): don't keep explicit lengths.
359         # (If a length override is ever needed to construct invalid packets,
360         #  use an explicit override field instead.)
361         $rec->decrypt_len(length($rec->decrypt_data));
362         $rec->len($rec->len + length($msgdata) - $old_length);
363         # Don't support re-encryption.
364         $rec->data($rec->decrypt_data);
365
366         #Update the fragment len in case we changed it above
367         ${$self->message_frag_lens}[0] = length($msgdata)
368                                          - TLS_MESSAGE_HEADER_LENGTH;
369         return;
370     }
371
372     #Note we don't currently support changing a fragmented message length
373     my $recctr = 0;
374     my $datadone = 0;
375     foreach my $rec (@{$self->records}) {
376         my $recdata = $rec->decrypt_data;
377         if ($recctr == 0) {
378             #This is the first record
379             my $remainlen = length($recdata) - $self->startoffset;
380             $rec->data(substr($recdata, 0, $self->startoffset)
381                        .substr(($msgdata), 0, $remainlen));
382             $datadone += $remainlen;
383         } elsif ($recctr + 1 == $numrecs) {
384             #This is the last record
385             $rec->data(substr($msgdata, $datadone));
386         } else {
387             #This is a middle record
388             $rec->data(substr($msgdata, $datadone, length($rec->data)));
389             $datadone += length($rec->data);
390         }
391         $recctr++;
392     }
393 }
394
395 #To be overridden by sub-classes
396 sub set_message_contents
397 {
398 }
399
400 #Read only accessors
401 sub server
402 {
403     my $self = shift;
404     return $self->{server};
405 }
406
407 #Read/write accessors
408 sub mt
409 {
410     my $self = shift;
411     if (@_) {
412       $self->{mt} = shift;
413     }
414     return $self->{mt};
415 }
416 sub data
417 {
418     my $self = shift;
419     if (@_) {
420       $self->{data} = shift;
421     }
422     return $self->{data};
423 }
424 sub records
425 {
426     my $self = shift;
427     if (@_) {
428       $self->{records} = shift;
429     }
430     return $self->{records};
431 }
432 sub startoffset
433 {
434     my $self = shift;
435     if (@_) {
436       $self->{startoffset} = shift;
437     }
438     return $self->{startoffset};
439 }
440 sub message_frag_lens
441 {
442     my $self = shift;
443     if (@_) {
444       $self->{message_frag_lens} = shift;
445     }
446     return $self->{message_frag_lens};
447 }
448 sub encoded_length
449 {
450     my $self = shift;
451     return TLS_MESSAGE_HEADER_LENGTH + length($self->data);
452 }
453
454 1;