Empty session ticket: add a test
[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 my $payload = "";
105 my $messlen = -1;
106 my $mt;
107 my $startoffset = -1;
108 my $server = 0;
109 my $success = 0;
110 my $end = 0;
111 my @message_rec_list = ();
112 my @message_frag_lens = ();
113 my $ciphersuite = 0;
114
115 sub clear
116 {
117     $payload = "";
118     $messlen = -1;
119     $startoffset = -1;
120     $server = 0;
121     $success = 0;
122     $end = 0;
123     @message_rec_list = ();
124     @message_frag_lens = ();
125 }
126
127 #Class method to extract messages from a record
128 sub get_messages
129 {
130     my $class = shift;
131     my $serverin = shift;
132     my $record = shift;
133     my @messages = ();
134     my $message;
135
136     @message_frag_lens = ();
137
138     if ($serverin != $server && length($payload) != 0) {
139         die "Changed peer, but we still have fragment data\n";
140     }
141     $server = $serverin;
142
143     if ($record->content_type == TLSProxy::Record::RT_CCS) {
144         if ($payload ne "") {
145             #We can't handle this yet
146             die "CCS received before message data complete\n";
147         }
148         if ($server) {
149             TLSProxy::Record->server_ccs_seen(1);
150         } else {
151             TLSProxy::Record->client_ccs_seen(1);
152         }
153     } elsif ($record->content_type == TLSProxy::Record::RT_HANDSHAKE) {
154         if ($record->len == 0 || $record->len_real == 0) {
155             print "  Message truncated\n";
156         } else {
157             my $recoffset = 0;
158
159             if (length $payload > 0) {
160                 #We are continuing processing a message started in a previous
161                 #record. Add this record to the list associated with this
162                 #message
163                 push @message_rec_list, $record;
164
165                 if ($messlen <= length($payload)) {
166                     #Shouldn't happen
167                     die "Internal error: invalid messlen: ".$messlen
168                         ." payload length:".length($payload)."\n";
169                 }
170                 if (length($payload) + $record->decrypt_len >= $messlen) {
171                     #We can complete the message with this record
172                     $recoffset = $messlen - length($payload);
173                     $payload .= substr($record->decrypt_data, 0, $recoffset);
174                     push @message_frag_lens, $recoffset;
175                     $message = create_message($server, $mt, $payload,
176                                               $startoffset);
177                     push @messages, $message;
178
179                     $payload = "";
180                 } else {
181                     #This is just part of the total message
182                     $payload .= $record->decrypt_data;
183                     $recoffset = $record->decrypt_len;
184                     push @message_frag_lens, $record->decrypt_len;
185                 }
186                 print "  Partial message data read: ".$recoffset." bytes\n";
187             }
188
189             while ($record->decrypt_len > $recoffset) {
190                 #We are at the start of a new message
191                 if ($record->decrypt_len - $recoffset < 4) {
192                     #Whilst technically probably valid we can't cope with this
193                     die "End of record in the middle of a message header\n";
194                 }
195                 @message_rec_list = ($record);
196                 my $lenhi;
197                 my $lenlo;
198                 ($mt, $lenhi, $lenlo) = unpack('CnC',
199                                                substr($record->decrypt_data,
200                                                       $recoffset));
201                 $messlen = ($lenhi << 8) | $lenlo;
202                 print "  Message type: $message_type{$mt}\n";
203                 print "  Message Length: $messlen\n";
204                 $startoffset = $recoffset;
205                 $recoffset += 4;
206                 $payload = "";
207                 
208                 if ($recoffset < $record->decrypt_len) {
209                     #Some payload data is present in this record
210                     if ($record->decrypt_len - $recoffset >= $messlen) {
211                         #We can complete the message with this record
212                         $payload .= substr($record->decrypt_data, $recoffset,
213                                            $messlen);
214                         $recoffset += $messlen;
215                         push @message_frag_lens, $messlen;
216                         $message = create_message($server, $mt, $payload,
217                                                   $startoffset);
218                         push @messages, $message;
219
220                         $payload = "";
221                     } else {
222                         #This is just part of the total message
223                         $payload .= substr($record->decrypt_data, $recoffset,
224                                            $record->decrypt_len - $recoffset);
225                         $recoffset = $record->decrypt_len;
226                         push @message_frag_lens, $recoffset;
227                     }
228                 }
229             }
230         }
231     } elsif ($record->content_type == TLSProxy::Record::RT_APPLICATION_DATA) {
232         print "  [ENCRYPTED APPLICATION DATA]\n";
233         print "  [".$record->decrypt_data."]\n";
234     } elsif ($record->content_type == TLSProxy::Record::RT_ALERT) {
235         my ($alertlev, $alertdesc) = unpack('CC', $record->decrypt_data);
236         #All alerts end the test
237         $end = 1;
238         #A CloseNotify from the client indicates we have finished successfully
239         #(we assume)
240         if (!$server && $alertlev == AL_LEVEL_WARN
241             && $alertdesc == AL_DESC_CLOSE_NOTIFY) {
242             $success = 1;
243         }
244     }
245
246     return @messages;
247 }
248
249 #Function to work out which sub-class we need to create and then
250 #construct it
251 sub create_message
252 {
253     my ($server, $mt, $data, $startoffset) = @_;
254     my $message;
255
256     #We only support ClientHello in this version...needs to be extended for
257     #others
258     if ($mt == MT_CLIENT_HELLO) {
259         $message = TLSProxy::ClientHello->new(
260             $server,
261             $data,
262             [@message_rec_list],
263             $startoffset,
264             [@message_frag_lens]
265         );
266         $message->parse();
267     } elsif ($mt == MT_SERVER_HELLO) {
268         $message = TLSProxy::ServerHello->new(
269             $server,
270             $data,
271             [@message_rec_list],
272             $startoffset,
273             [@message_frag_lens]
274         );
275         $message->parse();
276     } elsif ($mt == MT_SERVER_KEY_EXCHANGE) {
277         $message = TLSProxy::ServerKeyExchange->new(
278             $server,
279             $data,
280             [@message_rec_list],
281             $startoffset,
282             [@message_frag_lens]
283         );
284         $message->parse();
285     } elsif ($mt == MT_NEW_SESSION_TICKET) {
286         $message = TLSProxy::NewSessionTicket->new(
287             $server,
288             $data,
289             [@message_rec_list],
290             $startoffset,
291             [@message_frag_lens]
292         );
293         $message->parse();
294     } else {
295         #Unknown message type
296         $message = TLSProxy::Message->new(
297             $server,
298             $mt,
299             $data,
300             [@message_rec_list],
301             $startoffset,
302             [@message_frag_lens]
303         );
304     }
305
306     return $message;
307 }
308
309 sub end
310 {
311     my $class = shift;
312     return $end;
313 }
314 sub success
315 {
316     my $class = shift;
317     return $success;
318 }
319 sub fail
320 {
321     my $class = shift;
322     return !$success && $end;
323 }
324 sub new
325 {
326     my $class = shift;
327     my ($server,
328         $mt,
329         $data,
330         $records,
331         $startoffset,
332         $message_frag_lens) = @_;
333     
334     my $self = {
335         server => $server,
336         data => $data,
337         records => $records,
338         mt => $mt,
339         startoffset => $startoffset,
340         message_frag_lens => $message_frag_lens
341     };
342
343     return bless $self, $class;
344 }
345
346 sub ciphersuite
347 {
348     my $class = shift;
349     if (@_) {
350       $ciphersuite = shift;
351     }
352     return $ciphersuite;
353 }
354
355 #Update all the underlying records with the modified data from this message
356 #Note: Does not currently support re-encrypting
357 sub repack
358 {
359     my $self = shift;
360     my $msgdata;
361
362     my $numrecs = $#{$self->records};
363
364     $self->set_message_contents();
365
366     my $lenhi;
367     my $lenlo;
368
369     $lenlo = length($self->data) & 0xff;
370     $lenhi = length($self->data) >> 8;
371     $msgdata = pack('CnC', $self->mt, $lenhi, $lenlo).$self->data;
372
373
374     if ($numrecs == 0) {
375         #The message is fully contained within one record
376         my ($rec) = @{$self->records};
377         my $recdata = $rec->decrypt_data;
378
379         if (length($msgdata) != ${$self->message_frag_lens}[0]
380                                 + TLS_MESSAGE_HEADER_LENGTH) {
381             #Message length has changed! Better adjust the record length
382             my $diff = length($msgdata) - ${$self->message_frag_lens}[0]
383                                         - TLS_MESSAGE_HEADER_LENGTH;
384             $rec->len($rec->len + $diff);
385         }
386
387         $rec->data(substr($recdata, 0, $self->startoffset)
388                    .($msgdata)
389                    .substr($recdata, ${$self->message_frag_lens}[0]
390                                      + TLS_MESSAGE_HEADER_LENGTH));
391
392         #Update the fragment len in case we changed it above
393         ${$self->message_frag_lens}[0] = length($msgdata)
394                                          - TLS_MESSAGE_HEADER_LENGTH;
395         return;
396     }
397
398     #Note we don't currently support changing a fragmented message length
399     my $recctr = 0;
400     my $datadone = 0;
401     foreach my $rec (@{$self->records}) {
402         my $recdata = $rec->decrypt_data;
403         if ($recctr == 0) {
404             #This is the first record
405             my $remainlen = length($recdata) - $self->startoffset;
406             $rec->data(substr($recdata, 0, $self->startoffset)
407                        .substr(($msgdata), 0, $remainlen));
408             $datadone += $remainlen;
409         } elsif ($recctr + 1 == $numrecs) {
410             #This is the last record
411             $rec->data(substr($msgdata, $datadone));
412         } else {
413             #This is a middle record
414             $rec->data(substr($msgdata, $datadone, length($rec->data)));
415             $datadone += length($rec->data);
416         }
417         $recctr++;
418     }
419 }
420
421 #To be overridden by sub-classes
422 sub set_message_contents
423 {
424 }
425
426 #Read only accessors
427 sub server
428 {
429     my $self = shift;
430     return $self->{server};
431 }
432
433 #Read/write accessors
434 sub mt
435 {
436     my $self = shift;
437     if (@_) {
438       $self->{mt} = shift;
439     }
440     return $self->{mt};
441 }
442 sub data
443 {
444     my $self = shift;
445     if (@_) {
446       $self->{data} = shift;
447     }
448     return $self->{data};
449 }
450 sub records
451 {
452     my $self = shift;
453     if (@_) {
454       $self->{records} = shift;
455     }
456     return $self->{records};
457 }
458 sub startoffset
459 {
460     my $self = shift;
461     if (@_) {
462       $self->{startoffset} = shift;
463     }
464     return $self->{startoffset};
465 }
466 sub message_frag_lens
467 {
468     my $self = shift;
469     if (@_) {
470       $self->{message_frag_lens} = shift;
471     }
472     return $self->{message_frag_lens};
473 }
474
475 1;