6376219d151b91626830e68f225ca4d5689ce8b2
[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     } else {
286         #Unknown message type
287         $message = TLSProxy::Message->new(
288             $server,
289             $mt,
290             $data,
291             [@message_rec_list],
292             $startoffset,
293             [@message_frag_lens]
294         );
295     }
296
297     return $message;
298 }
299
300 sub end
301 {
302     my $class = shift;
303     return $end;
304 }
305 sub success
306 {
307     my $class = shift;
308     return $success;
309 }
310 sub fail
311 {
312     my $class = shift;
313     return !$success && $end;
314 }
315 sub new
316 {
317     my $class = shift;
318     my ($server,
319         $mt,
320         $data,
321         $records,
322         $startoffset,
323         $message_frag_lens) = @_;
324     
325     my $self = {
326         server => $server,
327         data => $data,
328         records => $records,
329         mt => $mt,
330         startoffset => $startoffset,
331         message_frag_lens => $message_frag_lens
332     };
333
334     return bless $self, $class;
335 }
336
337 sub ciphersuite
338 {
339     my $class = shift;
340     if (@_) {
341       $ciphersuite = shift;
342     }
343     return $ciphersuite;
344 }
345
346 #Update all the underlying records with the modified data from this message
347 #Note: Does not currently support re-encrypting
348 sub repack
349 {
350     my $self = shift;
351     my $msgdata;
352
353     my $numrecs = $#{$self->records};
354
355     $self->set_message_contents();
356
357     my $lenhi;
358     my $lenlo;
359
360     $lenlo = length($self->data) & 0xff;
361     $lenhi = length($self->data) >> 8;
362     $msgdata = pack('CnC', $self->mt, $lenhi, $lenlo).$self->data;
363
364
365     if ($numrecs == 0) {
366         #The message is fully contained within one record
367         my ($rec) = @{$self->records};
368         my $recdata = $rec->decrypt_data;
369
370         if (length($msgdata) != ${$self->message_frag_lens}[0]
371                                 + TLS_MESSAGE_HEADER_LENGTH) {
372             #Message length has changed! Better adjust the record length
373             my $diff = length($msgdata) - ${$self->message_frag_lens}[0]
374                                         - TLS_MESSAGE_HEADER_LENGTH;
375             $rec->len($rec->len + $diff);
376         }
377
378         $rec->data(substr($recdata, 0, $self->startoffset)
379                    .($msgdata)
380                    .substr($recdata, ${$self->message_frag_lens}[0]
381                                      + TLS_MESSAGE_HEADER_LENGTH));
382
383         #Update the fragment len in case we changed it above
384         ${$self->message_frag_lens}[0] = length($msgdata)
385                                          - TLS_MESSAGE_HEADER_LENGTH;
386         return;
387     }
388
389     #Note we don't currently support changing a fragmented message length
390     my $recctr = 0;
391     my $datadone = 0;
392     foreach my $rec (@{$self->records}) {
393         my $recdata = $rec->decrypt_data;
394         if ($recctr == 0) {
395             #This is the first record
396             my $remainlen = length($recdata) - $self->startoffset;
397             $rec->data(substr($recdata, 0, $self->startoffset)
398                        .substr(($msgdata), 0, $remainlen));
399             $datadone += $remainlen;
400         } elsif ($recctr + 1 == $numrecs) {
401             #This is the last record
402             $rec->data(substr($msgdata, $datadone));
403         } else {
404             #This is a middle record
405             $rec->data(substr($msgdata, $datadone, length($rec->data)));
406             $datadone += length($rec->data);
407         }
408         $recctr++;
409     }
410 }
411
412 #To be overridden by sub-classes
413 sub set_message_contents
414 {
415 }
416
417 #Read only accessors
418 sub server
419 {
420     my $self = shift;
421     return $self->{server};
422 }
423
424 #Read/write accessors
425 sub mt
426 {
427     my $self = shift;
428     if (@_) {
429       $self->{mt} = shift;
430     }
431     return $self->{mt};
432 }
433 sub data
434 {
435     my $self = shift;
436     if (@_) {
437       $self->{data} = shift;
438     }
439     return $self->{data};
440 }
441 sub records
442 {
443     my $self = shift;
444     if (@_) {
445       $self->{records} = shift;
446     }
447     return $self->{records};
448 }
449 sub startoffset
450 {
451     my $self = shift;
452     if (@_) {
453       $self->{startoffset} = shift;
454     }
455     return $self->{startoffset};
456 }
457 sub message_frag_lens
458 {
459     my $self = shift;
460     if (@_) {
461       $self->{message_frag_lens} = shift;
462     }
463     return $self->{message_frag_lens};
464 }
465
466 1;