Removes SCT_LIST_set_source and SCT_LIST_set0_logs
[openssl.git] / util / TLSProxy / Message.pm
1 # Written by Matt Caswell for the OpenSSL project.
2 # ====================================================================
3 # Copyright (c) 1998-2015 The OpenSSL Project.  All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions
7 # are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright
10 #    notice, this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright
13 #    notice, this list of conditions and the following disclaimer in
14 #    the documentation and/or other materials provided with the
15 #    distribution.
16 #
17 # 3. All advertising materials mentioning features or use of this
18 #    software must display the following acknowledgment:
19 #    "This product includes software developed by the OpenSSL Project
20 #    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
21 #
22 # 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
23 #    endorse or promote products derived from this software without
24 #    prior written permission. For written permission, please contact
25 #    openssl-core@openssl.org.
26 #
27 # 5. Products derived from this software may not be called "OpenSSL"
28 #    nor may "OpenSSL" appear in their names without prior written
29 #    permission of the OpenSSL Project.
30 #
31 # 6. Redistributions of any form whatsoever must retain the following
32 #    acknowledgment:
33 #    "This product includes software developed by the OpenSSL Project
34 #    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
35 #
36 # THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
37 # EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
39 # PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
40 # ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
42 # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44 # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
45 # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
47 # OF THE POSSIBILITY OF SUCH DAMAGE.
48 # ====================================================================
49 #
50 # This product includes cryptographic software written by Eric Young
51 # (eay@cryptsoft.com).  This product includes software written by Tim
52 # Hudson (tjh@cryptsoft.com).
53
54 use strict;
55
56 package TLSProxy::Message;
57
58 use constant TLS_MESSAGE_HEADER_LENGTH => 4;
59
60 #Message types
61 use constant {
62     MT_HELLO_REQUEST => 0,
63     MT_CLIENT_HELLO => 1,
64     MT_SERVER_HELLO => 2,
65     MT_NEW_SESSION_TICKET => 4,
66     MT_CERTIFICATE => 11,
67     MT_SERVER_KEY_EXCHANGE => 12,
68     MT_CERTIFICATE_REQUEST => 13,
69     MT_SERVER_HELLO_DONE => 14,
70     MT_CERTIFICATE_VERIFY => 15,
71     MT_CLIENT_KEY_EXCHANGE => 16,
72     MT_FINISHED => 20,
73     MT_CERTIFICATE_STATUS => 22,
74     MT_NEXT_PROTO => 67
75 };
76
77 #Alert levels
78 use constant {
79     AL_LEVEL_WARN => 1,
80     AL_LEVEL_FATAL => 2
81 };
82
83 #Alert descriptions
84 use constant {
85     AL_DESC_CLOSE_NOTIFY => 0
86 };
87
88 my %message_type = (
89     MT_HELLO_REQUEST, "HelloRequest",
90     MT_CLIENT_HELLO, "ClientHello",
91     MT_SERVER_HELLO, "ServerHello",
92     MT_NEW_SESSION_TICKET, "NewSessionTicket",
93     MT_CERTIFICATE, "Certificate",
94     MT_SERVER_KEY_EXCHANGE, "ServerKeyExchange",
95     MT_CERTIFICATE_REQUEST, "CertificateRequest",
96     MT_SERVER_HELLO_DONE, "ServerHelloDone",
97     MT_CERTIFICATE_VERIFY, "CertificateVerify",
98     MT_CLIENT_KEY_EXCHANGE, "ClientKeyExchange",
99     MT_FINISHED, "Finished",
100     MT_CERTIFICATE_STATUS, "CertificateStatus",
101     MT_NEXT_PROTO, "NextProto"
102 );
103
104 use constant {
105     EXT_STATUS_REQUEST => 5,
106     EXT_ENCRYPT_THEN_MAC => 22,
107     EXT_EXTENDED_MASTER_SECRET => 23,
108     EXT_SESSION_TICKET => 35,
109     # This extension does not exist and isn't recognised by OpenSSL.
110     # We use it to test handling of duplicate extensions.
111     EXT_DUPLICATE_EXTENSION => 1234
112 };
113
114 my $payload = "";
115 my $messlen = -1;
116 my $mt;
117 my $startoffset = -1;
118 my $server = 0;
119 my $success = 0;
120 my $end = 0;
121 my @message_rec_list = ();
122 my @message_frag_lens = ();
123 my $ciphersuite = 0;
124
125 sub clear
126 {
127     $payload = "";
128     $messlen = -1;
129     $startoffset = -1;
130     $server = 0;
131     $success = 0;
132     $end = 0;
133     @message_rec_list = ();
134     @message_frag_lens = ();
135 }
136
137 #Class method to extract messages from a record
138 sub get_messages
139 {
140     my $class = shift;
141     my $serverin = shift;
142     my $record = shift;
143     my @messages = ();
144     my $message;
145
146     @message_frag_lens = ();
147
148     if ($serverin != $server && length($payload) != 0) {
149         die "Changed peer, but we still have fragment data\n";
150     }
151     $server = $serverin;
152
153     if ($record->content_type == TLSProxy::Record::RT_CCS) {
154         if ($payload ne "") {
155             #We can't handle this yet
156             die "CCS received before message data complete\n";
157         }
158         if ($server) {
159             TLSProxy::Record->server_ccs_seen(1);
160         } else {
161             TLSProxy::Record->client_ccs_seen(1);
162         }
163     } elsif ($record->content_type == TLSProxy::Record::RT_HANDSHAKE) {
164         if ($record->len == 0 || $record->len_real == 0) {
165             print "  Message truncated\n";
166         } else {
167             my $recoffset = 0;
168
169             if (length $payload > 0) {
170                 #We are continuing processing a message started in a previous
171                 #record. Add this record to the list associated with this
172                 #message
173                 push @message_rec_list, $record;
174
175                 if ($messlen <= length($payload)) {
176                     #Shouldn't happen
177                     die "Internal error: invalid messlen: ".$messlen
178                         ." payload length:".length($payload)."\n";
179                 }
180                 if (length($payload) + $record->decrypt_len >= $messlen) {
181                     #We can complete the message with this record
182                     $recoffset = $messlen - length($payload);
183                     $payload .= substr($record->decrypt_data, 0, $recoffset);
184                     push @message_frag_lens, $recoffset;
185                     $message = create_message($server, $mt, $payload,
186                                               $startoffset);
187                     push @messages, $message;
188
189                     $payload = "";
190                 } else {
191                     #This is just part of the total message
192                     $payload .= $record->decrypt_data;
193                     $recoffset = $record->decrypt_len;
194                     push @message_frag_lens, $record->decrypt_len;
195                 }
196                 print "  Partial message data read: ".$recoffset." bytes\n";
197             }
198
199             while ($record->decrypt_len > $recoffset) {
200                 #We are at the start of a new message
201                 if ($record->decrypt_len - $recoffset < 4) {
202                     #Whilst technically probably valid we can't cope with this
203                     die "End of record in the middle of a message header\n";
204                 }
205                 @message_rec_list = ($record);
206                 my $lenhi;
207                 my $lenlo;
208                 ($mt, $lenhi, $lenlo) = unpack('CnC',
209                                                substr($record->decrypt_data,
210                                                       $recoffset));
211                 $messlen = ($lenhi << 8) | $lenlo;
212                 print "  Message type: $message_type{$mt}\n";
213                 print "  Message Length: $messlen\n";
214                 $startoffset = $recoffset;
215                 $recoffset += 4;
216                 $payload = "";
217                 
218                 if ($recoffset < $record->decrypt_len) {
219                     #Some payload data is present in this record
220                     if ($record->decrypt_len - $recoffset >= $messlen) {
221                         #We can complete the message with this record
222                         $payload .= substr($record->decrypt_data, $recoffset,
223                                            $messlen);
224                         $recoffset += $messlen;
225                         push @message_frag_lens, $messlen;
226                         $message = create_message($server, $mt, $payload,
227                                                   $startoffset);
228                         push @messages, $message;
229
230                         $payload = "";
231                     } else {
232                         #This is just part of the total message
233                         $payload .= substr($record->decrypt_data, $recoffset,
234                                            $record->decrypt_len - $recoffset);
235                         $recoffset = $record->decrypt_len;
236                         push @message_frag_lens, $recoffset;
237                     }
238                 }
239             }
240         }
241     } elsif ($record->content_type == TLSProxy::Record::RT_APPLICATION_DATA) {
242         print "  [ENCRYPTED APPLICATION DATA]\n";
243         print "  [".$record->decrypt_data."]\n";
244     } elsif ($record->content_type == TLSProxy::Record::RT_ALERT) {
245         my ($alertlev, $alertdesc) = unpack('CC', $record->decrypt_data);
246         #All alerts end the test
247         $end = 1;
248         #A CloseNotify from the client indicates we have finished successfully
249         #(we assume)
250         if (!$server && $alertlev == AL_LEVEL_WARN
251             && $alertdesc == AL_DESC_CLOSE_NOTIFY) {
252             $success = 1;
253         }
254     }
255
256     return @messages;
257 }
258
259 #Function to work out which sub-class we need to create and then
260 #construct it
261 sub create_message
262 {
263     my ($server, $mt, $data, $startoffset) = @_;
264     my $message;
265
266     #We only support ClientHello in this version...needs to be extended for
267     #others
268     if ($mt == MT_CLIENT_HELLO) {
269         $message = TLSProxy::ClientHello->new(
270             $server,
271             $data,
272             [@message_rec_list],
273             $startoffset,
274             [@message_frag_lens]
275         );
276         $message->parse();
277     } elsif ($mt == MT_SERVER_HELLO) {
278         $message = TLSProxy::ServerHello->new(
279             $server,
280             $data,
281             [@message_rec_list],
282             $startoffset,
283             [@message_frag_lens]
284         );
285         $message->parse();
286     } elsif ($mt == MT_SERVER_KEY_EXCHANGE) {
287         $message = TLSProxy::ServerKeyExchange->new(
288             $server,
289             $data,
290             [@message_rec_list],
291             $startoffset,
292             [@message_frag_lens]
293         );
294         $message->parse();
295     } elsif ($mt == MT_NEW_SESSION_TICKET) {
296         $message = TLSProxy::NewSessionTicket->new(
297             $server,
298             $data,
299             [@message_rec_list],
300             $startoffset,
301             [@message_frag_lens]
302         );
303         $message->parse();
304     } else {
305         #Unknown message type
306         $message = TLSProxy::Message->new(
307             $server,
308             $mt,
309             $data,
310             [@message_rec_list],
311             $startoffset,
312             [@message_frag_lens]
313         );
314     }
315
316     return $message;
317 }
318
319 sub end
320 {
321     my $class = shift;
322     return $end;
323 }
324 sub success
325 {
326     my $class = shift;
327     return $success;
328 }
329 sub fail
330 {
331     my $class = shift;
332     return !$success && $end;
333 }
334 sub new
335 {
336     my $class = shift;
337     my ($server,
338         $mt,
339         $data,
340         $records,
341         $startoffset,
342         $message_frag_lens) = @_;
343     
344     my $self = {
345         server => $server,
346         data => $data,
347         records => $records,
348         mt => $mt,
349         startoffset => $startoffset,
350         message_frag_lens => $message_frag_lens
351     };
352
353     return bless $self, $class;
354 }
355
356 sub ciphersuite
357 {
358     my $class = shift;
359     if (@_) {
360       $ciphersuite = shift;
361     }
362     return $ciphersuite;
363 }
364
365 #Update all the underlying records with the modified data from this message
366 #Note: Does not currently support re-encrypting
367 sub repack
368 {
369     my $self = shift;
370     my $msgdata;
371
372     my $numrecs = $#{$self->records};
373
374     $self->set_message_contents();
375
376     my $lenhi;
377     my $lenlo;
378
379     $lenlo = length($self->data) & 0xff;
380     $lenhi = length($self->data) >> 8;
381     $msgdata = pack('CnC', $self->mt, $lenhi, $lenlo).$self->data;
382
383     if ($numrecs == 0) {
384         #The message is fully contained within one record
385         my ($rec) = @{$self->records};
386         my $recdata = $rec->decrypt_data;
387
388         my $old_length;
389
390         # We use empty message_frag_lens to indicates that pre-repacking,
391         # the message wasn't present. The first fragment length doesn't include
392         # the TLS header, so we need to check and compute the right length.
393         if (@{$self->message_frag_lens}) {
394             $old_length = ${$self->message_frag_lens}[0] +
395               TLS_MESSAGE_HEADER_LENGTH;
396         } else {
397             $old_length = 0;
398         }
399
400         my $prefix = substr($recdata, 0, $self->startoffset);
401         my $suffix = substr($recdata, $self->startoffset + $old_length);
402
403         $rec->decrypt_data($prefix.($msgdata).($suffix));
404         # TODO(openssl-team): don't keep explicit lengths.
405         # (If a length override is ever needed to construct invalid packets,
406         #  use an explicit override field instead.)
407         $rec->decrypt_len(length($rec->decrypt_data));
408         $rec->len($rec->len + length($msgdata) - $old_length);
409         # Don't support re-encryption.
410         $rec->data($rec->decrypt_data);
411
412         #Update the fragment len in case we changed it above
413         ${$self->message_frag_lens}[0] = length($msgdata)
414                                          - TLS_MESSAGE_HEADER_LENGTH;
415         return;
416     }
417
418     #Note we don't currently support changing a fragmented message length
419     my $recctr = 0;
420     my $datadone = 0;
421     foreach my $rec (@{$self->records}) {
422         my $recdata = $rec->decrypt_data;
423         if ($recctr == 0) {
424             #This is the first record
425             my $remainlen = length($recdata) - $self->startoffset;
426             $rec->data(substr($recdata, 0, $self->startoffset)
427                        .substr(($msgdata), 0, $remainlen));
428             $datadone += $remainlen;
429         } elsif ($recctr + 1 == $numrecs) {
430             #This is the last record
431             $rec->data(substr($msgdata, $datadone));
432         } else {
433             #This is a middle record
434             $rec->data(substr($msgdata, $datadone, length($rec->data)));
435             $datadone += length($rec->data);
436         }
437         $recctr++;
438     }
439 }
440
441 #To be overridden by sub-classes
442 sub set_message_contents
443 {
444 }
445
446 #Read only accessors
447 sub server
448 {
449     my $self = shift;
450     return $self->{server};
451 }
452
453 #Read/write accessors
454 sub mt
455 {
456     my $self = shift;
457     if (@_) {
458       $self->{mt} = shift;
459     }
460     return $self->{mt};
461 }
462 sub data
463 {
464     my $self = shift;
465     if (@_) {
466       $self->{data} = shift;
467     }
468     return $self->{data};
469 }
470 sub records
471 {
472     my $self = shift;
473     if (@_) {
474       $self->{records} = shift;
475     }
476     return $self->{records};
477 }
478 sub startoffset
479 {
480     my $self = shift;
481     if (@_) {
482       $self->{startoffset} = shift;
483     }
484     return $self->{startoffset};
485 }
486 sub message_frag_lens
487 {
488     my $self = shift;
489     if (@_) {
490       $self->{message_frag_lens} = shift;
491     }
492     return $self->{message_frag_lens};
493 }
494 sub encoded_length
495 {
496     my $self = shift;
497     return TLS_MESSAGE_HEADER_LENGTH + length($self->data);
498 }
499
500 1;