tls: add Server Key Exchange message
[siplcs.git] / src / core / sipe-tls.c
blob90888e77f5864beab3f447eb122c7500bb187aa5
1 /**
2 * @file sipe-tls.c
4 * pidgin-sipe
6 * Copyright (C) 2011-2015 SIPE Project <http://sipe.sourceforge.net/>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 * TLS Protocol Version 1.0/1.1/1.2 - Handshake Messages
26 * TLS-DSK uses the handshake messages during authentication and session key
27 * exchange. This module *ONLY* implements this part of the TLS specification!
29 * Specification references:
31 * - RFC2246: http://www.ietf.org/rfc/rfc2246.txt
32 * - RFC3546: http://www.ietf.org/rfc/rfc3546.txt
33 * - RFC4346: http://www.ietf.org/rfc/rfc4346.txt
36 #include <stdlib.h>
37 #include <string.h>
38 #include <stdarg.h>
40 #include <glib.h>
42 #include "sipe-common.h"
43 #include "sipe-backend.h"
44 #include "sipe-cert-crypto.h"
45 #include "sipe-crypt.h"
46 #include "sipe-digest.h"
47 #include "sipe-svc.h"
48 #include "sipe-tls.h"
51 * Private part of TLS state tracking
53 enum tls_handshake_state {
54 TLS_HANDSHAKE_STATE_START,
55 TLS_HANDSHAKE_STATE_SERVER_HELLO,
56 TLS_HANDSHAKE_STATE_FINISHED,
57 TLS_HANDSHAKE_STATE_COMPLETED,
58 TLS_HANDSHAKE_STATE_FAILED
61 struct tls_internal_state {
62 struct sipe_tls_state common;
63 gpointer certificate;
64 enum tls_handshake_state state;
65 guchar *msg_current;
66 gsize msg_remainder;
67 GHashTable *data;
68 GString *debug;
69 guint cipher_type;
70 gpointer md5_context;
71 gpointer sha1_context;
72 gpointer server_certificate;
73 struct sipe_tls_random client_random;
74 struct sipe_tls_random server_random;
75 struct sipe_tls_random pre_master_secret;
76 gsize mac_length;
77 gsize key_length;
78 guchar *master_secret;
79 guchar *key_block;
80 guchar *tls_dsk_key_block;
81 const guchar *client_write_mac_secret;
82 const guchar *server_write_mac_secret;
83 const guchar *client_write_secret;
84 const guchar *server_write_secret;
85 void (*mac_func)(const guchar *key, gsize key_length,
86 const guchar *data, gsize data_length,
87 guchar *digest);
88 gpointer cipher_context;
89 guint64 sequence_number;
90 gboolean encrypted;
94 * TLS messages & layout descriptors
97 /* constants */
98 #define TLS_VECTOR_MAX8 255 /* 2^8 - 1 */
99 #define TLS_VECTOR_MAX16 65535 /* 2^16 - 1 */
100 #define TLS_VECTOR_MAX24 16777215 /* 2^24 - 1 */
102 #define TLS_PROTOCOL_VERSION_1_0 0x0301
103 #define TLS_PROTOCOL_VERSION_1_1 0x0302
104 #define TLS_PROTOCOL_VERSION_1_2 0x0303
106 /* CipherSuites */
107 #define TLS_RSA_EXPORT_WITH_RC4_40_MD5 0x0003
108 #define TLS_RSA_WITH_RC4_128_MD5 0x0004
109 #define TLS_RSA_WITH_RC4_128_SHA 0x0005
110 #define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA 0xC014
112 /* CompressionMethods */
113 #define TLS_COMP_METHOD_NULL 0
115 /* various array lengths */
116 #define TLS_ARRAY_RANDOM_LENGTH 32
117 #define TLS_ARRAY_MASTER_SECRET_LENGTH 48
118 #define TLS_ARRAY_VERIFY_LENGTH 12
120 #define TLS_RECORD_HEADER_LENGTH 5
121 #define TLS_RECORD_OFFSET_TYPE 0
122 #define TLS_RECORD_TYPE_CHANGE_CIPHER_SPEC 20
123 #define TLS_RECORD_TYPE_HANDSHAKE 22
124 #define TLS_RECORD_OFFSET_VERSION 1
125 #define TLS_RECORD_OFFSET_LENGTH 3
127 #define TLS_HANDSHAKE_HEADER_LENGTH 4
128 #define TLS_HANDSHAKE_OFFSET_TYPE 0
129 #define TLS_HANDSHAKE_TYPE_CLIENT_HELLO 1
130 #define TLS_HANDSHAKE_TYPE_SERVER_HELLO 2
131 #define TLS_HANDSHAKE_TYPE_CERTIFICATE 11
132 #define TLS_HANDSHAKE_TYPE_SERVER_KEY_EXCHANGE 12
133 #define TLS_HANDSHAKE_TYPE_CERTIFICATE_REQ 13
134 #define TLS_HANDSHAKE_TYPE_SERVER_HELLO_DONE 14
135 #define TLS_HANDSHAKE_TYPE_CERTIFICATE_VERIFY 15
136 #define TLS_HANDSHAKE_TYPE_CLIENT_KEY_EXCHANGE 16
137 #define TLS_HANDSHAKE_TYPE_FINISHED 20
138 #define TLS_HANDSHAKE_OFFSET_LENGTH 1
140 struct layout_descriptor;
141 typedef gboolean parse_func(struct tls_internal_state *state,
142 const struct layout_descriptor *desc);
144 /* Defines the strictest alignment requirement */
145 struct tls_compile_integer;
146 typedef void compile_func(struct tls_internal_state *state,
147 const struct layout_descriptor *desc,
148 const struct tls_compile_integer *data);
150 struct layout_descriptor {
151 const gchar *label;
152 parse_func *parser;
153 compile_func *compiler;
154 gsize min; /* 0 for fixed/array */
155 gsize max;
156 gsize offset;
159 #define TLS_LAYOUT_DESCRIPTOR_END { NULL, NULL, NULL, 0, 0, 0 }
160 #define TLS_LAYOUT_IS_VALID(desc) (desc->label)
162 struct msg_descriptor {
163 const struct msg_descriptor *next;
164 const gchar *description;
165 const struct layout_descriptor *layouts;
166 guint type;
169 /* parsed data */
170 struct tls_parsed_integer {
171 guint value;
174 struct tls_parsed_array {
175 gsize length; /* bytes */
176 const guchar data[0];
179 /* compile data */
180 struct tls_compile_integer {
181 gsize value;
184 struct tls_compile_array {
185 gsize elements; /* unused */
186 guchar placeholder[];
189 struct tls_compile_random {
190 gsize elements; /* unused */
191 guchar random[TLS_ARRAY_RANDOM_LENGTH];
194 struct tls_compile_verify {
195 gsize elements; /* unused */
196 guchar verify[TLS_ARRAY_VERIFY_LENGTH];
199 struct tls_compile_vector {
200 gsize elements; /* VECTOR */
201 guint placeholder[];
204 struct tls_compile_sessionid {
205 gsize elements; /* VECTOR */
208 struct tls_compile_cipher {
209 gsize elements; /* VECTOR */
210 guint suites[4];
213 struct tls_compile_compression {
214 gsize elements; /* VECTOR */
215 guint methods[1];
218 /* compiled message */
219 struct tls_compiled_message {
220 gsize size;
221 guchar data[];
225 * Random byte buffers
227 void sipe_tls_fill_random(struct sipe_tls_random *random,
228 guint bits)
230 guint bytes = ((bits + 15) / 16) * 2;
231 guint16 *p = g_malloc(bytes);
233 SIPE_DEBUG_INFO("sipe_tls_fill_random: %d bits -> %d bytes",
234 bits, bytes);
236 random->buffer = (guint8*) p;
237 random->length = bytes;
239 for (bytes /= 2; bytes; bytes--)
240 *p++ = rand() & 0xFFFF;
243 void sipe_tls_free_random(struct sipe_tls_random *random)
245 g_free(random->buffer);
249 * TLS message debugging
251 static void debug_hex(struct tls_internal_state *state,
252 gsize alternative_length)
254 GString *str = state->debug;
255 const guchar *bytes;
256 gsize length;
257 gint count;
259 if (!str) return;
261 bytes = state->msg_current;
262 length = alternative_length ? alternative_length : state->msg_remainder;
263 count = -1;
265 while (length-- > 0) {
266 if (++count == 0) {
267 /* do nothing */;
268 } else if ((count % 16) == 0) {
269 g_string_append(str, "\n");
270 } else if ((count % 8) == 0) {
271 g_string_append(str, " ");
273 g_string_append_printf(str, " %02X", *bytes++);
275 g_string_append(str, "\n");
278 #define debug_print(state, string) \
279 if (state->debug) g_string_append(state->debug, string)
280 #define debug_printf(state, format, ...) \
281 if (state->debug) g_string_append_printf(state->debug, format, __VA_ARGS__)
283 /* Analyzer only needs the debugging functions */
284 #ifndef _SIPE_COMPILING_ANALYZER
286 static void debug_secrets(struct tls_internal_state *state,
287 const gchar *label,
288 const guchar *secret,
289 gsize secret_length)
291 if (state->debug && secret) {
292 g_string_append_printf(state->debug, "%s (%3" G_GSIZE_FORMAT ") = ",
293 label, secret_length);
294 while (secret_length--)
295 g_string_append_printf(state->debug, "%02X", *secret++);
296 SIPE_DEBUG_INFO_NOFORMAT(state->debug->str);
297 g_string_truncate(state->debug, 0);
302 * TLS Pseudorandom Function (PRF) - RFC2246, Section 5
304 static guchar *sipe_tls_p_md5(const guchar *secret,
305 gsize secret_length,
306 const guchar *seed,
307 gsize seed_length,
308 gsize output_length)
310 guchar *output = NULL;
313 * output_length == 0 -> illegal
314 * output_length == 1..16 -> iterations = 1
315 * output_length == 17..32 -> iterations = 2
317 if (secret && seed && (output_length > 0)) {
318 guint iterations = (output_length + SIPE_DIGEST_HMAC_MD5_LENGTH - 1) / SIPE_DIGEST_HMAC_MD5_LENGTH;
319 guchar *concat = g_malloc(SIPE_DIGEST_HMAC_MD5_LENGTH + seed_length);
320 guchar A[SIPE_DIGEST_HMAC_MD5_LENGTH];
321 guchar *p;
323 SIPE_DEBUG_INFO("p_md5: secret %" G_GSIZE_FORMAT " bytes, seed %" G_GSIZE_FORMAT " bytes",
324 secret_length, seed_length);
325 SIPE_DEBUG_INFO("p_md5: output %" G_GSIZE_FORMAT " bytes -> %d iterations",
326 output_length, iterations);
328 /* A(1) = HMAC_MD5(secret, A(0)), A(0) = seed */
329 sipe_digest_hmac_md5(secret, secret_length,
330 seed, seed_length,
333 /* Each iteration adds SIPE_DIGEST_HMAC_MD5_LENGTH bytes */
334 p = output = g_malloc(iterations * SIPE_DIGEST_HMAC_MD5_LENGTH);
336 while (iterations-- > 0) {
337 /* P_MD5(i) = HMAC_MD5(secret, A(i) + seed), i = 1, 2, ... */
338 guchar P[SIPE_DIGEST_HMAC_MD5_LENGTH];
339 memcpy(concat, A, SIPE_DIGEST_HMAC_MD5_LENGTH);
340 memcpy(concat + SIPE_DIGEST_HMAC_MD5_LENGTH, seed, seed_length);
341 sipe_digest_hmac_md5(secret, secret_length,
342 concat, SIPE_DIGEST_HMAC_MD5_LENGTH + seed_length,
344 memcpy(p, P, SIPE_DIGEST_HMAC_MD5_LENGTH);
345 p += SIPE_DIGEST_HMAC_MD5_LENGTH;
347 /* A(i+1) = HMAC_MD5(secret, A(i)) */
348 sipe_digest_hmac_md5(secret, secret_length,
349 A, SIPE_DIGEST_HMAC_MD5_LENGTH,
352 g_free(concat);
355 return(output);
358 guchar *sipe_tls_p_sha1(const guchar *secret,
359 gsize secret_length,
360 const guchar *seed,
361 gsize seed_length,
362 gsize output_length)
364 guchar *output = NULL;
367 * output_length == 0 -> illegal
368 * output_length == 1..20 -> iterations = 1
369 * output_length == 21..40 -> iterations = 2
371 if (secret && seed && (output_length > 0)) {
372 guint iterations = (output_length + SIPE_DIGEST_HMAC_SHA1_LENGTH - 1) / SIPE_DIGEST_HMAC_SHA1_LENGTH;
373 guchar *concat = g_malloc(SIPE_DIGEST_HMAC_SHA1_LENGTH + seed_length);
374 guchar A[SIPE_DIGEST_HMAC_SHA1_LENGTH];
375 guchar *p;
377 SIPE_DEBUG_INFO("p_sha1: secret %" G_GSIZE_FORMAT " bytes, seed %" G_GSIZE_FORMAT " bytes",
378 secret_length, seed_length);
379 SIPE_DEBUG_INFO("p_sha1: output %" G_GSIZE_FORMAT " bytes -> %d iterations",
380 output_length, iterations);
382 /* A(1) = HMAC_SHA1(secret, A(0)), A(0) = seed */
383 sipe_digest_hmac_sha1(secret, secret_length,
384 seed, seed_length,
387 /* Each iteration adds SIPE_DIGEST_HMAC_SHA1_LENGTH bytes */
388 p = output = g_malloc(iterations * SIPE_DIGEST_HMAC_SHA1_LENGTH);
390 while (iterations-- > 0) {
391 /* P_SHA1(i) = HMAC_SHA1(secret, A(i) + seed), i = 1, 2, ... */
392 guchar P[SIPE_DIGEST_HMAC_SHA1_LENGTH];
393 memcpy(concat, A, SIPE_DIGEST_HMAC_SHA1_LENGTH);
394 memcpy(concat + SIPE_DIGEST_HMAC_SHA1_LENGTH, seed, seed_length);
395 sipe_digest_hmac_sha1(secret, secret_length,
396 concat, SIPE_DIGEST_HMAC_SHA1_LENGTH + seed_length,
398 memcpy(p, P, SIPE_DIGEST_HMAC_SHA1_LENGTH);
399 p += SIPE_DIGEST_HMAC_SHA1_LENGTH;
401 /* A(i+1) = HMAC_SHA1(secret, A(i)) */
402 sipe_digest_hmac_sha1(secret, secret_length,
403 A, SIPE_DIGEST_HMAC_SHA1_LENGTH,
406 g_free(concat);
409 return(output);
412 static guchar *sipe_tls_prf(SIPE_UNUSED_PARAMETER struct tls_internal_state *state,
413 const guchar *secret,
414 gsize secret_length,
415 const guchar *label,
416 gsize label_length,
417 const guchar *seed,
418 gsize seed_length,
419 gsize output_length)
421 gsize half = (secret_length + 1) / 2;
422 gsize newseed_length = label_length + seed_length;
423 /* secret: used as S1; secret2: last half of original secret (S2) */
424 guchar *secret2 = g_memdup(secret + secret_length - half, half);
425 guchar *newseed = g_malloc(newseed_length);
426 guchar *md5, *dest;
427 guchar *sha1, *src;
428 gsize count;
430 /* make Coverity happy - lengths could be 0 */
431 if (!secret2 || !newseed) {
432 g_free(secret2);
433 g_free(newseed);
434 return(NULL);
438 * PRF(secret, label, seed) = P_MD5(S1, label + seed) XOR
439 * P_SHA-1(S2, label + seed);
441 memcpy(newseed, label, label_length);
442 memcpy(newseed + label_length, seed, seed_length);
443 #undef __SIPE_TLS_CRYPTO_DEBUG
444 #ifdef __SIPE_TLS_CRYPTO_DEBUG
445 debug_secrets(state, "sipe_tls_prf: secret ",
446 secret, secret_length);
447 debug_secrets(state, "sipe_tls_prf: combined seed ",
448 newseed, newseed_length);
449 SIPE_DEBUG_INFO("total seed length %" G_GSIZE_FORMAT,
450 newseed_length);
451 debug_secrets(state, "sipe_tls_prf: S1 ",
452 secret, half);
453 debug_secrets(state, "sipe_tls_prf: S2 ",
454 secret2, half);
455 #endif
456 md5 = sipe_tls_p_md5(secret, half, newseed, newseed_length, output_length);
457 sha1 = sipe_tls_p_sha1(secret2, half, newseed, newseed_length, output_length);
458 #ifdef __SIPE_TLS_CRYPTO_DEBUG
459 debug_secrets(state, "sipe_tls_prf: P_md5() ",
460 md5, output_length);
461 debug_secrets(state, "sipe_tls_prf: P_sha1() ",
462 sha1, output_length);
463 #endif
464 for (dest = md5, src = sha1, count = output_length;
465 count > 0;
466 count--)
467 *dest++ ^= *src++;
469 g_free(sha1);
470 g_free(newseed);
471 g_free(secret2);
473 #ifdef __SIPE_TLS_CRYPTO_DEBUG
474 debug_secrets(state, "sipe_tls_prf: PRF() ",
475 md5, output_length);
476 #endif
478 return(md5);
481 #endif /* !_SIPE_COMPILING_ANALYZER */
484 * TLS data parsers
486 * Low-level data conversion routines
488 * - host alignment agnostic, i.e. can fetch a word from uneven address
489 * - TLS -> host endianess conversion
490 * - no length check, caller has to do it
491 * - don't modify state
493 static guint lowlevel_integer_to_host(const guchar *bytes,
494 gsize length)
496 guint sum = 0;
497 while (length--) sum = (sum << 8) + *bytes++;
498 return(sum);
502 * Generic data type parser routines
504 static gboolean msg_remainder_check(struct tls_internal_state *state,
505 const gchar *label,
506 gsize length)
508 if (length > state->msg_remainder) {
509 SIPE_DEBUG_ERROR("msg_remainder_check: '%s' expected %" G_GSIZE_FORMAT " bytes, remaining %" G_GSIZE_FORMAT,
510 label, length, state->msg_remainder);
511 return(FALSE);
513 return(TRUE);
516 static gboolean parse_integer_quiet(struct tls_internal_state *state,
517 const gchar *label,
518 gsize length,
519 guint *result)
521 if (!msg_remainder_check(state, label, length)) return(FALSE);
522 *result = lowlevel_integer_to_host(state->msg_current, length);
523 state->msg_current += length;
524 state->msg_remainder -= length;
525 return(TRUE);
528 static gboolean parse_integer(struct tls_internal_state *state,
529 const struct layout_descriptor *desc)
531 guint value;
532 if (!parse_integer_quiet(state, desc->label, desc->max, &value))
533 return(FALSE);
534 debug_printf(state, "%s/INTEGER%" G_GSIZE_FORMAT " = %d\n",
535 desc->label, desc->max, value);
536 if (state->data) {
537 struct tls_parsed_integer *save = g_new0(struct tls_parsed_integer, 1);
538 save->value = value;
539 g_hash_table_insert(state->data, (gpointer) desc->label, save);
541 return(TRUE);
544 static gboolean parse_array(struct tls_internal_state *state,
545 const struct layout_descriptor *desc)
547 if (!msg_remainder_check(state, desc->label, desc->max))
548 return(FALSE);
549 debug_printf(state, "%s/ARRAY[%" G_GSIZE_FORMAT "]\n",
550 desc->label, desc->max);
551 #ifdef _SIPE_COMPILING_ANALYZER
552 if (desc->max)
553 debug_hex(state, desc->max);
554 #endif
555 if (state->data) {
556 struct tls_parsed_array *save = g_malloc0(sizeof(struct tls_parsed_array) +
557 desc->max);
558 save->length = desc->max;
559 memcpy((guchar *)save->data, state->msg_current, desc->max);
560 g_hash_table_insert(state->data, (gpointer) desc->label, save);
563 state->msg_current += desc->max;
564 state->msg_remainder -= desc->max;
565 return(TRUE);
568 static gboolean parse_vector(struct tls_internal_state *state,
569 const struct layout_descriptor *desc)
571 guint length;
572 if (!parse_integer_quiet(state, desc->label,
573 (desc->max > TLS_VECTOR_MAX16) ? 3 :
574 (desc->max > TLS_VECTOR_MAX8) ? 2 : 1,
575 &length))
576 return(FALSE);
577 if (length < desc->min) {
578 SIPE_DEBUG_ERROR("parse_vector: '%s' too short %d, expected %" G_GSIZE_FORMAT,
579 desc->label, length, desc->min);
580 return(FALSE);
582 debug_printf(state, "%s/VECTOR<%d>\n", desc->label, length);
583 #ifdef _SIPE_COMPILING_ANALYZER
584 if (length)
585 debug_hex(state, length);
586 #endif
587 if (state->data) {
588 struct tls_parsed_array *save = g_malloc0(sizeof(struct tls_parsed_array) +
589 length);
590 save->length = length;
591 memcpy((guchar *)save->data, state->msg_current, length);
592 g_hash_table_insert(state->data, (gpointer) desc->label, save);
594 state->msg_current += length;
595 state->msg_remainder -= length;
596 return(TRUE);
600 * Specific data type parser routines
603 /* TBD... */
606 * TLS data compilers
608 * Low-level data conversion routines
610 * - host alignment agnostic, i.e. can fetch a word from uneven address
611 * - host -> TLS host endianess conversion
612 * - don't modify state
614 static void lowlevel_integer_to_tls(guchar *bytes,
615 gsize length,
616 guint value)
618 while (length--) {
619 bytes[length] = value & 0xFF;
620 value >>= 8;
625 * Generic data type compiler routines
627 static void compile_integer(struct tls_internal_state *state,
628 const struct layout_descriptor *desc,
629 const struct tls_compile_integer *data)
631 lowlevel_integer_to_tls(state->msg_current, desc->max, data->value);
632 state->msg_current += desc->max;
635 static void compile_array(struct tls_internal_state *state,
636 const struct layout_descriptor *desc,
637 const struct tls_compile_integer *data)
639 const struct tls_compile_array *array = (struct tls_compile_array *) data;
640 memcpy(state->msg_current, array->placeholder, desc->max);
641 state->msg_current += desc->max;
644 static void compile_vector(struct tls_internal_state *state,
645 const struct layout_descriptor *desc,
646 const struct tls_compile_integer *data)
648 const struct tls_compile_vector *vector = (struct tls_compile_vector *) data;
649 gsize length = vector->elements;
650 gsize length_field = (desc->max > TLS_VECTOR_MAX16) ? 3 :
651 (desc->max > TLS_VECTOR_MAX8) ? 2 : 1;
653 lowlevel_integer_to_tls(state->msg_current, length_field, length);
654 state->msg_current += length_field;
655 memcpy(state->msg_current, vector->placeholder, length);
656 state->msg_current += length;
659 static void compile_vector_int2(struct tls_internal_state *state,
660 const struct layout_descriptor *desc,
661 const struct tls_compile_integer *data)
663 const struct tls_compile_vector *vector = (struct tls_compile_vector *) data;
664 gsize elements = vector->elements;
665 gsize length = elements * sizeof(guint16);
666 gsize length_field = (desc->max > TLS_VECTOR_MAX16) ? 3 :
667 (desc->max > TLS_VECTOR_MAX8) ? 2 : 1;
668 const guint *p = vector->placeholder;
670 lowlevel_integer_to_tls(state->msg_current, length_field, length);
671 state->msg_current += length_field;
672 while (elements--) {
673 lowlevel_integer_to_tls(state->msg_current, sizeof(guint16), *p++);
674 state->msg_current += sizeof(guint16);
679 * Specific data type compiler routines
682 /* TBD... */
685 * TLS handshake message layout descriptors
687 struct ClientHello_host {
688 struct tls_compile_integer protocol_version;
689 struct tls_compile_random random;
690 struct tls_compile_sessionid sessionid;
691 struct tls_compile_cipher cipher;
692 struct tls_compile_compression compression;
694 #define CLIENTHELLO_OFFSET(a) offsetof(struct ClientHello_host, a)
696 static const struct layout_descriptor ClientHello_l[] = {
697 { "Client Protocol Version", parse_integer, compile_integer, 0, 2, CLIENTHELLO_OFFSET(protocol_version) },
698 { "Random", parse_array, compile_array, 0, TLS_ARRAY_RANDOM_LENGTH, CLIENTHELLO_OFFSET(random) },
699 { "SessionID", parse_vector, compile_vector, 0, 32, CLIENTHELLO_OFFSET(sessionid) },
700 { "CipherSuite", parse_vector, compile_vector_int2, 2, TLS_VECTOR_MAX16, CLIENTHELLO_OFFSET(cipher)},
701 { "CompressionMethod", parse_vector, compile_vector, 1, TLS_VECTOR_MAX8, CLIENTHELLO_OFFSET(compression) },
702 TLS_LAYOUT_DESCRIPTOR_END
704 static const struct msg_descriptor ClientHello_m = {
705 NULL, "Client Hello", ClientHello_l, TLS_HANDSHAKE_TYPE_CLIENT_HELLO
708 static const struct layout_descriptor ServerHello_l[] = {
709 { "Server Protocol Version", parse_integer, NULL, 0, 2, 0 },
710 { "Random", parse_array, NULL, 0, TLS_ARRAY_RANDOM_LENGTH, 0 },
711 { "SessionID", parse_vector, NULL, 0, 32, 0 },
712 { "CipherSuite", parse_integer, NULL, 0, 2, 0 },
713 { "CompressionMethod", parse_integer, NULL, 0, 1, 0 },
714 TLS_LAYOUT_DESCRIPTOR_END
716 static const struct msg_descriptor ServerHello_m = {
717 &ClientHello_m, "Server Hello", ServerHello_l, TLS_HANDSHAKE_TYPE_SERVER_HELLO
720 struct Certificate_host {
721 struct tls_compile_vector certificate;
723 #define CERTIFICATE_OFFSET(a) offsetof(struct Certificate_host, a)
725 static const struct layout_descriptor Certificate_l[] = {
726 { "Certificate", parse_vector, compile_vector, 0, TLS_VECTOR_MAX24, CERTIFICATE_OFFSET(certificate) },
727 TLS_LAYOUT_DESCRIPTOR_END
729 static const struct msg_descriptor Certificate_m = {
730 &ServerHello_m, "Certificate", Certificate_l, TLS_HANDSHAKE_TYPE_CERTIFICATE
733 /* we only support ECDHE */
734 static const struct layout_descriptor ServerKeyExchange_l[] = {
735 { "EC Curve Type", parse_integer, NULL, 0, 1, 0 },
736 TLS_LAYOUT_DESCRIPTOR_END
738 static const struct msg_descriptor ServerKeyExchange_m = {
739 &Certificate_m, "Server Key Exchange", ServerKeyExchange_l, TLS_HANDSHAKE_TYPE_SERVER_KEY_EXCHANGE
742 static const struct layout_descriptor CertificateRequest_l[] = {
743 { "CertificateType", parse_vector, NULL, 1, TLS_VECTOR_MAX8, 0 },
744 { "DistinguishedName", parse_vector, NULL, 0, TLS_VECTOR_MAX16, 0 },
745 TLS_LAYOUT_DESCRIPTOR_END
747 static const struct msg_descriptor CertificateRequest_m = {
748 &ServerKeyExchange_m, "Certificate Request", CertificateRequest_l, TLS_HANDSHAKE_TYPE_CERTIFICATE_REQ
751 static const struct layout_descriptor ServerHelloDone_l[] = {
752 TLS_LAYOUT_DESCRIPTOR_END
754 static const struct msg_descriptor ServerHelloDone_m = {
755 &CertificateRequest_m, "Server Hello Done", ServerHelloDone_l, TLS_HANDSHAKE_TYPE_SERVER_HELLO_DONE
758 struct ClientKeyExchange_host {
759 struct tls_compile_vector secret;
761 #define CLIENTKEYEXCHANGE_OFFSET(a) offsetof(struct ClientKeyExchange_host, a)
763 static const struct layout_descriptor ClientKeyExchange_l[] = {
764 { "Exchange Keys", parse_vector, compile_vector, 0, TLS_VECTOR_MAX16, CLIENTKEYEXCHANGE_OFFSET(secret) },
765 TLS_LAYOUT_DESCRIPTOR_END
767 static const struct msg_descriptor ClientKeyExchange_m = {
768 &ServerHelloDone_m, "Client Key Exchange", ClientKeyExchange_l, TLS_HANDSHAKE_TYPE_CLIENT_KEY_EXCHANGE
771 struct CertificateVerify_host {
772 struct tls_compile_vector signature;
774 #define CERTIFICATEVERIFY_OFFSET(a) offsetof(struct CertificateVerify_host, a)
776 static const struct layout_descriptor CertificateVerify_l[] = {
777 { "Signature", parse_vector, compile_vector, 0, TLS_VECTOR_MAX16, CERTIFICATEVERIFY_OFFSET(signature) },
778 TLS_LAYOUT_DESCRIPTOR_END
780 static const struct msg_descriptor CertificateVerify_m = {
781 &ClientKeyExchange_m, "Certificate Verify", CertificateVerify_l, TLS_HANDSHAKE_TYPE_CERTIFICATE_VERIFY
784 struct Finished_host {
785 struct tls_compile_verify verify;
787 #define FINISHED_OFFSET(a) offsetof(struct Finished_host, a)
789 static const struct layout_descriptor Finished_l[] = {
790 { "Verify Data", parse_array, compile_array, 0, TLS_ARRAY_VERIFY_LENGTH, FINISHED_OFFSET(verify) },
791 TLS_LAYOUT_DESCRIPTOR_END
793 static const struct msg_descriptor Finished_m = {
794 &CertificateVerify_m, "Finished", Finished_l, TLS_HANDSHAKE_TYPE_FINISHED
797 #define HANDSHAKE_MSG_DESCRIPTORS &Finished_m
800 * TLS message parsers
802 static gboolean handshake_parse(struct tls_internal_state *state)
804 const guchar *bytes = state->msg_current;
805 gsize length = state->msg_remainder;
806 gboolean success = FALSE;
808 while (length > 0) {
809 const struct msg_descriptor *desc;
810 gsize msg_length;
811 guint msg_type;
813 /* header check */
814 if (length < TLS_HANDSHAKE_HEADER_LENGTH) {
815 debug_print(state, "CORRUPTED HANDSHAKE HEADER");
816 break;
819 /* msg length check */
820 msg_length = lowlevel_integer_to_host(bytes + TLS_HANDSHAKE_OFFSET_LENGTH,
822 if (msg_length > length) {
823 debug_print(state, "HANDSHAKE MESSAGE TOO LONG");
824 break;
827 /* msg type */
828 msg_type = bytes[TLS_HANDSHAKE_OFFSET_TYPE];
829 for (desc = HANDSHAKE_MSG_DESCRIPTORS;
830 desc;
831 desc = desc->next)
832 if (msg_type == desc->type)
833 break;
835 debug_printf(state, "TLS handshake (%" G_GSIZE_FORMAT " bytes) (%d)",
836 msg_length, msg_type);
838 state->msg_current = (guchar *) bytes + TLS_HANDSHAKE_HEADER_LENGTH;
839 state->msg_remainder = msg_length;
841 if (desc && desc->layouts) {
842 const struct layout_descriptor *ldesc = desc->layouts;
844 debug_printf(state, "%s\n", desc->description);
845 while (TLS_LAYOUT_IS_VALID(ldesc)) {
846 success = ldesc->parser(state, ldesc);
847 if (!success)
848 break;
849 ldesc++;
851 if (!success)
852 break;
853 } else {
854 debug_print(state, "ignored\n");
855 debug_hex(state, 0);
858 /* next message */
859 bytes += TLS_HANDSHAKE_HEADER_LENGTH + msg_length;
860 length -= TLS_HANDSHAKE_HEADER_LENGTH + msg_length;
861 if (length > 0) {
862 debug_print(state, "------\n");
863 } else {
864 success = TRUE;
868 return(success);
871 static void free_parse_data(struct tls_internal_state *state)
873 if (state->data) {
874 g_hash_table_destroy(state->data);
875 state->data = NULL;
879 static gboolean tls_record_parse(struct tls_internal_state *state,
880 gboolean incoming)
882 const guchar *bytes = incoming ? state->common.in_buffer : state->common.out_buffer;
883 gsize length = incoming ? state->common.in_length : state->common.out_length;
884 guint version;
885 const gchar *version_str;
886 gsize record_length;
887 gboolean success = TRUE;
889 /* reject empty incoming messages */
890 if (incoming && (length == 0)) {
891 SIPE_DEBUG_ERROR_NOFORMAT("tls_record_parse: empty TLS message received");
892 return(FALSE);
895 #ifndef _SIPE_COMPILING_ANALYZER
896 debug_printf(state, "TLS MESSAGE %s\n", incoming ? "INCOMING" : "OUTGOING");
897 #endif
899 /* Collect parser data for incoming messages */
900 if (incoming)
901 state->data = g_hash_table_new_full(g_str_hash, g_str_equal,
902 NULL, g_free);
904 while (success && (length > 0)) {
906 /* truncated header check */
907 if (length < TLS_RECORD_HEADER_LENGTH) {
908 SIPE_DEBUG_ERROR("tls_record_parse: too short TLS record header (%" G_GSIZE_FORMAT " bytes)",
909 length);
910 success = FALSE;
911 break;
914 /* protocol version check */
915 version = lowlevel_integer_to_host(bytes + TLS_RECORD_OFFSET_VERSION, 2);
916 if (version < TLS_PROTOCOL_VERSION_1_0) {
917 SIPE_DEBUG_ERROR_NOFORMAT("tls_record_parse: SSL1/2/3 not supported");
918 success = FALSE;
919 break;
921 switch (version) {
922 case TLS_PROTOCOL_VERSION_1_0:
923 version_str = "1.0 (RFC2246)";
924 break;
925 case TLS_PROTOCOL_VERSION_1_1:
926 version_str = "1.1 (RFC4346)";
927 break;
928 case TLS_PROTOCOL_VERSION_1_2:
929 version_str = "1.2 (RFC5246)";
930 break;
931 default:
932 version_str = "<future protocol version>";
933 break;
936 /* record length check */
937 record_length = TLS_RECORD_HEADER_LENGTH +
938 lowlevel_integer_to_host(bytes + TLS_RECORD_OFFSET_LENGTH, 2);
939 if (record_length > length) {
940 SIPE_DEBUG_ERROR_NOFORMAT("tls_record_parse: record too long");
941 success = FALSE;
942 break;
945 /* TLS record header OK */
946 debug_printf(state, "TLS %s record (%" G_GSIZE_FORMAT " bytes)\n",
947 version_str, record_length);
948 state->msg_current = (guchar *) bytes + TLS_RECORD_HEADER_LENGTH;
949 state->msg_remainder = record_length - TLS_RECORD_HEADER_LENGTH;
951 /* Analyzer only needs the debugging functions */
952 #ifndef _SIPE_COMPILING_ANALYZER
953 /* Add incoming message contents to digest contexts */
954 if (incoming) {
955 sipe_digest_md5_update(state->md5_context,
956 state->msg_current,
957 state->msg_remainder);
958 sipe_digest_sha1_update(state->sha1_context,
959 state->msg_current,
960 state->msg_remainder);
962 #endif /* !_SIPE_COMPILING_ANALYZER */
964 switch (bytes[TLS_RECORD_OFFSET_TYPE]) {
965 case TLS_RECORD_TYPE_CHANGE_CIPHER_SPEC:
966 debug_print(state, "Change Cipher Spec\n");
967 if (incoming) state->encrypted = TRUE;
968 break;
970 case TLS_RECORD_TYPE_HANDSHAKE:
971 if (incoming && state->encrypted) {
972 debug_print(state, "Encrypted handshake message\n");
973 debug_hex(state, 0);
974 } else {
975 success = handshake_parse(state);
977 break;
979 default:
980 debug_print(state, "Unsupported TLS message\n");
981 debug_hex(state, 0);
982 break;
985 /* next fragment */
986 bytes += record_length;
987 length -= record_length;
990 if (!success)
991 free_parse_data(state);
993 if (state->debug) {
994 SIPE_DEBUG_INFO_NOFORMAT(state->debug->str);
995 g_string_truncate(state->debug, 0);
998 return(success);
1001 /* Analyzer only needs the debugging functions */
1002 #ifndef _SIPE_COMPILING_ANALYZER
1005 * TLS message compiler
1007 static void compile_tls_record(struct tls_internal_state *state,
1008 ...)
1010 gsize total_size = 0;
1011 guchar *current;
1012 va_list ap;
1014 /* calculate message size */
1015 va_start(ap, state);
1016 while (1) {
1017 const struct tls_compiled_message *msg = va_arg(ap, struct tls_compiled_message *);
1018 if (!msg) break;
1019 total_size += msg->size;
1021 va_end(ap);
1023 SIPE_DEBUG_INFO("compile_tls_record: total size %" G_GSIZE_FORMAT,
1024 total_size);
1026 state->common.out_buffer = current = g_malloc(total_size + TLS_RECORD_HEADER_LENGTH);
1027 state->common.out_length = total_size + TLS_RECORD_HEADER_LENGTH;
1029 /* add TLS record header */
1030 current[TLS_RECORD_OFFSET_TYPE] = TLS_RECORD_TYPE_HANDSHAKE;
1031 lowlevel_integer_to_tls(current + TLS_RECORD_OFFSET_VERSION, 2,
1032 TLS_PROTOCOL_VERSION_1_0);
1033 lowlevel_integer_to_tls(current + TLS_RECORD_OFFSET_LENGTH, 2,
1034 total_size);
1035 current += TLS_RECORD_HEADER_LENGTH;
1037 /* copy messages */
1038 va_start(ap, state);
1039 while (1) {
1040 const struct tls_compiled_message *msg = va_arg(ap, struct tls_compiled_message *);
1041 if (!msg) break;
1043 memcpy(current, msg->data, msg->size);
1044 current += msg->size;
1046 va_end(ap);
1049 static void compile_encrypted_tls_record(struct tls_internal_state *state,
1050 const struct tls_compiled_message *msg)
1052 guchar *plaintext;
1053 gsize plaintext_length;
1054 guchar *mac;
1055 gsize mac_length;
1056 guchar *message;
1057 guchar *encrypted;
1058 gsize encrypted_length;
1060 /* Create plaintext TLS record */
1061 compile_tls_record(state, msg, NULL);
1062 plaintext = state->common.out_buffer;
1063 plaintext_length = state->common.out_length;
1064 if (plaintext_length == 0) /* make Coverity happy */
1065 return;
1067 /* Prepare encryption buffer */
1068 encrypted_length = plaintext_length + state->mac_length;
1069 SIPE_DEBUG_INFO("compile_encrypted_tls_record: total size %" G_GSIZE_FORMAT,
1070 encrypted_length - TLS_RECORD_HEADER_LENGTH);
1071 message = g_malloc(encrypted_length);
1072 memcpy(message, plaintext, plaintext_length);
1073 lowlevel_integer_to_tls(message + TLS_RECORD_OFFSET_LENGTH, 2,
1074 encrypted_length - TLS_RECORD_HEADER_LENGTH);
1077 * Calculate MAC
1079 * HMAC_hash(client_write_mac_secret,
1080 * sequence_number + type + version + length + fragment)
1081 * \--- == original TLS record ---/
1083 mac_length = sizeof(guint64) + plaintext_length;
1084 mac = g_malloc(mac_length);
1085 lowlevel_integer_to_tls(mac,
1086 sizeof(guint64),
1087 state->sequence_number++);
1088 memcpy(mac + sizeof(guint64), plaintext, plaintext_length);
1089 g_free(plaintext);
1090 state->mac_func(state->client_write_mac_secret,
1091 state->mac_length,
1092 mac,
1093 mac_length,
1094 message + plaintext_length);
1095 g_free(mac);
1097 /* Encrypt message + MAC */
1098 encrypted = g_malloc(encrypted_length);
1099 memcpy(encrypted, message, TLS_RECORD_HEADER_LENGTH);
1100 sipe_crypt_tls_stream(state->cipher_context,
1101 message + TLS_RECORD_HEADER_LENGTH,
1102 encrypted_length - TLS_RECORD_HEADER_LENGTH,
1103 encrypted + TLS_RECORD_HEADER_LENGTH);
1104 g_free(message);
1106 /* swap buffers */
1107 state->common.out_buffer = encrypted;
1108 state->common.out_length = encrypted_length;
1111 static struct tls_compiled_message *compile_handshake_msg(struct tls_internal_state *state,
1112 const struct msg_descriptor *desc,
1113 gpointer data,
1114 gsize size)
1117 * Estimate the size of the compiled message
1119 * The data structures in the host format have zero or more padding
1120 * bytes added by the compiler to ensure correct element alignments.
1121 * So the sizeof() of the data structure is always equal or greater
1122 * than the space needed for the compiled data. By adding the space
1123 * required for the headers we arrive at a safe estimate
1125 * Therefore we don't need space checks in the compiler functions
1127 gsize total_size = sizeof(struct tls_compiled_message) +
1128 size + TLS_HANDSHAKE_HEADER_LENGTH;
1129 struct tls_compiled_message *msg = g_malloc(total_size);
1130 guchar *handshake = msg->data;
1131 const struct layout_descriptor *ldesc = desc->layouts;
1132 gsize length;
1134 SIPE_DEBUG_INFO("compile_handshake_msg: buffer size %" G_GSIZE_FORMAT,
1135 total_size);
1137 /* add TLS handshake header */
1138 handshake[TLS_HANDSHAKE_OFFSET_TYPE] = desc->type;
1139 state->msg_current = handshake + TLS_HANDSHAKE_HEADER_LENGTH;
1141 while (TLS_LAYOUT_IS_VALID(ldesc)) {
1143 * Avoid "cast increases required alignment" errors
1145 * (void *) tells the compiler that we know what we're
1146 * doing, i.e. we know that the calculated address
1147 * points to correctly aligned data.
1149 ldesc->compiler(state, ldesc,
1150 (void *) ((guchar *) data + ldesc->offset));
1151 ldesc++;
1154 length = state->msg_current - handshake - TLS_HANDSHAKE_HEADER_LENGTH;
1155 lowlevel_integer_to_tls(handshake + TLS_HANDSHAKE_OFFSET_LENGTH,
1156 3, length);
1157 SIPE_DEBUG_INFO("compile_handshake_msg: (%d)%s, size %" G_GSIZE_FORMAT,
1158 desc->type, desc->description, length);
1160 msg->size = length + TLS_HANDSHAKE_HEADER_LENGTH;
1162 /* update digest contexts */
1163 sipe_digest_md5_update(state->md5_context, handshake, msg->size);
1164 sipe_digest_sha1_update(state->sha1_context, handshake, msg->size);
1166 return(msg);
1170 * Specific TLS data verficiation & message compilers
1172 static struct tls_compiled_message *tls_client_certificate(struct tls_internal_state *state)
1174 struct Certificate_host *certificate;
1175 gsize certificate_length = sipe_cert_crypto_raw_length(state->certificate);
1176 struct tls_compiled_message *msg;
1178 /* setup our response */
1179 /* Client Certificate is VECTOR_MAX24 of VECTOR_MAX24s */
1180 certificate = g_malloc0(sizeof(struct Certificate_host) + 3 +
1181 certificate_length);
1182 certificate->certificate.elements = certificate_length + 3;
1183 lowlevel_integer_to_tls((guchar *) certificate->certificate.placeholder, 3,
1184 certificate_length);
1185 memcpy((guchar *) certificate->certificate.placeholder + 3,
1186 sipe_cert_crypto_raw(state->certificate),
1187 certificate_length);
1189 msg = compile_handshake_msg(state, &Certificate_m, certificate,
1190 sizeof(struct Certificate_host) + certificate_length + 3);
1191 g_free(certificate);
1193 return(msg);
1196 static gboolean check_cipher_suite(struct tls_internal_state *state)
1198 struct tls_parsed_integer *cipher_suite = g_hash_table_lookup(state->data,
1199 "CipherSuite");
1200 const gchar *label = NULL;
1202 if (!cipher_suite) {
1203 SIPE_DEBUG_ERROR_NOFORMAT("check_cipher_suite: server didn't specify the cipher suite");
1204 return(FALSE);
1207 switch (cipher_suite->value) {
1208 case TLS_RSA_EXPORT_WITH_RC4_40_MD5:
1209 state->mac_length = SIPE_DIGEST_HMAC_MD5_LENGTH;
1210 state->key_length = 40 / 8;
1211 state->mac_func = sipe_digest_hmac_md5;
1212 label = "MD5";
1213 state->common.algorithm = SIPE_TLS_DIGEST_ALGORITHM_MD5;
1214 state->cipher_type = SIPE_CRYPT_STREAM_RC4;
1215 break;
1217 case TLS_RSA_WITH_RC4_128_MD5:
1218 state->mac_length = SIPE_DIGEST_HMAC_MD5_LENGTH;
1219 state->key_length = 128 / 8;
1220 state->mac_func = sipe_digest_hmac_md5;
1221 label = "MD5";
1222 state->common.algorithm = SIPE_TLS_DIGEST_ALGORITHM_MD5;
1223 state->cipher_type = SIPE_CRYPT_STREAM_RC4;
1224 break;
1226 case TLS_RSA_WITH_RC4_128_SHA:
1227 state->mac_length = SIPE_DIGEST_HMAC_SHA1_LENGTH;
1228 state->key_length = 128 / 8;
1229 state->mac_func = sipe_digest_hmac_sha1;
1230 label = "SHA-1";
1231 state->common.algorithm = SIPE_TLS_DIGEST_ALGORITHM_SHA1;
1232 state->cipher_type = SIPE_CRYPT_STREAM_RC4;
1233 break;
1235 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
1236 state->mac_length = SIPE_DIGEST_HMAC_SHA1_LENGTH;
1237 state->key_length = 256 / 8;
1238 state->mac_func = sipe_digest_hmac_sha1;
1239 label = "SHA-1";
1240 state->common.algorithm = SIPE_TLS_DIGEST_ALGORITHM_SHA1;
1241 state->cipher_type = SIPE_CRYPT_STREAM_AES_CBC;
1242 break;
1244 default:
1245 SIPE_DEBUG_ERROR("check_cipher_suite: unsupported cipher suite %d",
1246 cipher_suite->value);
1247 break;
1250 if (label)
1251 SIPE_DEBUG_INFO("check_cipher_suite: KEY(stream cipher RC4) %" G_GSIZE_FORMAT ", MAC(%s) %" G_GSIZE_FORMAT,
1252 state->key_length, label, state->mac_length);
1254 return(label != NULL);
1257 static void tls_calculate_secrets(struct tls_internal_state *state)
1259 gsize length = 2 * (state->mac_length + state->key_length);
1260 guchar *random;
1262 /* Generate pre-master secret */
1263 sipe_tls_fill_random(&state->pre_master_secret,
1264 TLS_ARRAY_MASTER_SECRET_LENGTH * 8); /* bits */
1265 lowlevel_integer_to_tls(state->pre_master_secret.buffer, 2,
1266 TLS_PROTOCOL_VERSION_1_0);
1267 debug_secrets(state, "tls_calculate_secrets: pre-master secret",
1268 state->pre_master_secret.buffer,
1269 state->pre_master_secret.length);
1272 * Calculate master secret
1274 * master_secret = PRF(pre_master_secret,
1275 * "master secret",
1276 * ClientHello.random + ServerHello.random)
1278 random = g_malloc(TLS_ARRAY_RANDOM_LENGTH * 2);
1279 memcpy(random,
1280 state->client_random.buffer,
1281 TLS_ARRAY_RANDOM_LENGTH);
1282 memcpy(random + TLS_ARRAY_RANDOM_LENGTH,
1283 state->server_random.buffer,
1284 TLS_ARRAY_RANDOM_LENGTH);
1285 state->master_secret = sipe_tls_prf(state,
1286 state->pre_master_secret.buffer,
1287 state->pre_master_secret.length,
1288 (guchar *) "master secret",
1290 random,
1291 TLS_ARRAY_RANDOM_LENGTH * 2,
1292 TLS_ARRAY_MASTER_SECRET_LENGTH);
1293 debug_secrets(state, "tls_calculate_secrets: master secret ",
1294 state->master_secret,
1295 TLS_ARRAY_MASTER_SECRET_LENGTH);
1298 * Calculate session key material
1300 * key_block = PRF(master_secret,
1301 * "key expansion",
1302 * ServerHello.random + ClientHello.random)
1304 SIPE_DEBUG_INFO("tls_calculate_secrets: key_block length %" G_GSIZE_FORMAT,
1305 length);
1306 memcpy(random,
1307 state->server_random.buffer,
1308 TLS_ARRAY_RANDOM_LENGTH);
1309 memcpy(random + TLS_ARRAY_RANDOM_LENGTH,
1310 state->client_random.buffer,
1311 TLS_ARRAY_RANDOM_LENGTH);
1312 state->key_block = sipe_tls_prf(state,
1313 state->master_secret,
1314 TLS_ARRAY_MASTER_SECRET_LENGTH,
1315 (guchar *) "key expansion",
1317 random,
1318 TLS_ARRAY_RANDOM_LENGTH * 2,
1319 length);
1320 g_free(random);
1321 debug_secrets(state, "tls_calculate_secrets: key block ",
1322 state->key_block, length);
1324 /* partition key block */
1325 state->client_write_mac_secret = state->key_block;
1326 state->server_write_mac_secret = state->key_block + state->mac_length;
1327 state->client_write_secret = state->key_block + 2 * state->mac_length;
1328 state->server_write_secret = state->key_block + 2 * state->mac_length + state->key_length;
1330 /* initialize cipher context */
1331 state->cipher_context = sipe_crypt_tls_start(state->cipher_type,
1332 state->client_write_secret,
1333 state->key_length);
1336 #if 0 /* NOT NEEDED? */
1337 /* signing */
1338 static guchar *tls_pkcs1_private_padding(SIPE_UNUSED_PARAMETER struct tls_internal_state *state,
1339 const guchar *data,
1340 gsize data_length,
1341 gsize buffer_length)
1343 gsize pad_length;
1344 guchar *pad_buffer;
1346 if (data_length + 3 > buffer_length) ||
1347 (buffer_length == 0)) /* this is dead code, but makes Coverity happy */)
1348 return(NULL);
1350 pad_length = buffer_length - data_length - 3;
1351 pad_buffer = g_malloc(buffer_length);
1353 /* PKCS1 private key block padding */
1354 pad_buffer[0] = 0; /* +1 */
1355 pad_buffer[1] = 1; /* +2 */
1356 memset(pad_buffer + 2, 0xFF, pad_length);
1357 pad_buffer[2 + pad_length] = 0; /* +3 */
1358 memcpy(pad_buffer + 3 + pad_length, data, data_length);
1360 #ifdef __SIPE_TLS_CRYPTO_DEBUG
1361 debug_secrets(state, "tls_pkcs1_private_padding: ",
1362 pad_buffer, buffer_length);
1363 #endif
1365 return(pad_buffer);
1367 #endif
1369 /* encryption */
1370 static guchar *tls_pkcs1_public_padding(SIPE_UNUSED_PARAMETER struct tls_internal_state *state,
1371 const guchar *data,
1372 gsize data_length,
1373 gsize buffer_length)
1375 gsize pad_length, random_count;
1376 guchar *pad_buffer, *random;
1378 if ((data_length + 3 > buffer_length) ||
1379 (buffer_length == 0)) /* this is dead code, but makes Coverity happy */
1380 return(NULL);
1382 pad_length = buffer_length - data_length - 3;
1383 pad_buffer = g_malloc(buffer_length);
1385 /* PKCS1 public key block padding */
1386 pad_buffer[0] = 0; /* +1 */
1387 pad_buffer[1] = 2; /* +2 */
1388 for (random = pad_buffer + 2, random_count = pad_length;
1389 random_count > 0;
1390 random_count--) {
1391 guchar byte;
1392 /* non-zero random byte */
1393 while ((byte = rand() & 0xFF) == 0);
1394 *random++ = byte;
1396 pad_buffer[2 + pad_length] = 0; /* +3 */
1397 memcpy(pad_buffer + 3 + pad_length, data, data_length);
1399 #ifdef __SIPE_TLS_CRYPTO_DEBUG
1400 debug_secrets(state, "tls_pkcs1_private_padding: ",
1401 pad_buffer, buffer_length);
1402 #endif
1404 return(pad_buffer);
1407 static struct tls_compiled_message *tls_client_key_exchange(struct tls_internal_state *state)
1409 struct tls_parsed_array *server_random;
1410 struct tls_parsed_array *server_certificate;
1411 struct ClientKeyExchange_host *exchange;
1412 gsize server_certificate_length;
1413 guchar *padded;
1414 struct tls_compiled_message *msg;
1416 /* check for required data fields */
1417 if (!check_cipher_suite(state))
1418 return(NULL);
1419 server_random = g_hash_table_lookup(state->data, "Random");
1420 if (!server_random) {
1421 SIPE_DEBUG_ERROR_NOFORMAT("tls_client_key_exchange: no server random");
1422 return(NULL);
1424 server_certificate = g_hash_table_lookup(state->data, "Certificate");
1425 /* Server Certificate is VECTOR_MAX24 of VECTOR_MAX24s */
1426 if (!server_certificate || (server_certificate->length < 3)) {
1427 SIPE_DEBUG_ERROR_NOFORMAT("tls_client_key_exchange: no server certificate");
1428 return(FALSE);
1430 SIPE_DEBUG_INFO("tls_client_key_exchange: server certificate list %" G_GSIZE_FORMAT" bytes",
1431 server_certificate->length);
1432 /* first certificate is the server certificate */
1433 server_certificate_length = lowlevel_integer_to_host(server_certificate->data,
1435 SIPE_DEBUG_INFO("tls_client_key_exchange: server certificate %" G_GSIZE_FORMAT" bytes",
1436 server_certificate_length);
1437 if ((server_certificate_length + 3) > server_certificate->length) {
1438 SIPE_DEBUG_ERROR_NOFORMAT("tls_client_key_exchange: truncated server certificate");
1440 state->server_certificate = sipe_cert_crypto_import(server_certificate->data + 3,
1441 server_certificate_length);
1442 if (!state->server_certificate) {
1443 SIPE_DEBUG_ERROR_NOFORMAT("tls_client_key_exchange: corrupted server certificate");
1444 return(FALSE);
1446 /* server public key modulus length */
1447 server_certificate_length = sipe_cert_crypto_modulus_length(state->server_certificate);
1448 if (server_certificate_length < TLS_ARRAY_MASTER_SECRET_LENGTH) {
1449 SIPE_DEBUG_ERROR("tls_client_key_exchange: server public key strength too low (%" G_GSIZE_FORMAT ")",
1450 server_certificate_length);
1451 return(FALSE);
1453 SIPE_DEBUG_INFO("tls_client_key_exchange: server public key strength = %" G_GSIZE_FORMAT,
1454 server_certificate_length);
1456 /* found all the required fields */
1457 state->server_random.length = server_random->length;
1458 state->server_random.buffer = g_memdup(server_random->data,
1459 server_random->length);
1460 tls_calculate_secrets(state);
1462 /* ClientKeyExchange */
1463 padded = tls_pkcs1_public_padding(state,
1464 state->pre_master_secret.buffer,
1465 state->pre_master_secret.length,
1466 server_certificate_length);
1467 if (!padded) {
1468 SIPE_DEBUG_ERROR_NOFORMAT("tls_client_key_exchange: padding of pre-master secret failed");
1469 return(NULL);
1471 exchange = g_malloc0(sizeof(struct ClientKeyExchange_host) +
1472 server_certificate_length);
1473 exchange->secret.elements = server_certificate_length;
1474 if (!sipe_crypt_rsa_encrypt(sipe_cert_crypto_public_key(state->server_certificate),
1475 server_certificate_length,
1476 padded,
1477 (guchar *) exchange->secret.placeholder)) {
1478 SIPE_DEBUG_ERROR_NOFORMAT("tls_client_key_exchange: encryption of pre-master secret failed");
1479 g_free(exchange);
1480 g_free(padded);
1481 return(NULL);
1483 g_free(padded);
1485 #ifdef __SIPE_TLS_CRYPTO_DEBUG
1486 debug_secrets(state, "tls_client_key_exchange: secret (encr) ",
1487 (guchar *) exchange->secret.placeholder,
1488 server_certificate_length);
1489 #endif
1491 msg = compile_handshake_msg(state, &ClientKeyExchange_m, exchange,
1492 sizeof(struct ClientKeyExchange_host) + server_certificate_length);
1493 g_free(exchange);
1495 return(msg);
1498 static struct tls_compiled_message *tls_certificate_verify(struct tls_internal_state *state)
1500 struct CertificateVerify_host *verify;
1501 struct tls_compiled_message *msg;
1502 guchar *digests = g_malloc(SIPE_DIGEST_MD5_LENGTH + SIPE_DIGEST_SHA1_LENGTH);
1503 guchar *signature;
1504 gsize length;
1506 /* calculate digests */
1507 sipe_digest_md5_end(state->md5_context, digests);
1508 sipe_digest_sha1_end(state->sha1_context, digests + SIPE_DIGEST_MD5_LENGTH);
1510 /* sign digests */
1511 signature = sipe_crypt_rsa_sign(sipe_cert_crypto_private_key(state->certificate),
1512 digests,
1513 SIPE_DIGEST_MD5_LENGTH + SIPE_DIGEST_SHA1_LENGTH,
1514 &length);
1515 g_free(digests);
1516 if (!signature) {
1517 SIPE_DEBUG_ERROR_NOFORMAT("tls_certificate_verify: signing of handshake digests failed");
1518 return(NULL);
1521 /* CertificateVerify */
1522 verify = g_malloc0(sizeof(struct CertificateVerify_host) +
1523 length);
1524 verify->signature.elements = length;
1525 memcpy(verify->signature.placeholder, signature, length);
1526 g_free(signature);
1528 msg = compile_handshake_msg(state, &CertificateVerify_m, verify,
1529 sizeof(struct CertificateVerify_host) + length);
1530 g_free(verify);
1532 return(msg);
1535 static struct tls_compiled_message *tls_client_finished(struct tls_internal_state *state)
1537 guchar *digests = g_malloc(SIPE_DIGEST_MD5_LENGTH + SIPE_DIGEST_SHA1_LENGTH);
1538 guchar *verify;
1539 struct tls_compiled_message *cmsg;
1540 struct Finished_host msg;
1542 /* calculate digests */
1543 sipe_digest_md5_end(state->md5_context, digests);
1544 sipe_digest_sha1_end(state->sha1_context, digests + SIPE_DIGEST_MD5_LENGTH);
1547 * verify_data = PRF(master_secret, "client finished",
1548 * MD5(handshake_messages) +
1549 * SHA-1(handshake_messages)) [0..11];
1551 verify = sipe_tls_prf(state,
1552 state->master_secret,
1553 TLS_ARRAY_MASTER_SECRET_LENGTH,
1554 (guchar *) "client finished",
1556 digests,
1557 SIPE_DIGEST_MD5_LENGTH + SIPE_DIGEST_SHA1_LENGTH,
1558 TLS_ARRAY_VERIFY_LENGTH);
1559 g_free(digests);
1560 memcpy(msg.verify.verify, verify, TLS_ARRAY_VERIFY_LENGTH);
1561 g_free(verify);
1563 cmsg = compile_handshake_msg(state, &Finished_m, &msg, sizeof(msg));
1565 return(cmsg);
1569 * TLS state handling
1572 static gboolean tls_client_hello(struct tls_internal_state *state)
1574 guint32 now = time(NULL);
1575 guint32 now_N = GUINT32_TO_BE(now);
1576 struct ClientHello_host msg = {
1577 { TLS_PROTOCOL_VERSION_1_0 },
1578 { 0, { 0 } },
1579 { 0 /* empty SessionID */ },
1580 { 4,
1582 TLS_RSA_WITH_RC4_128_MD5,
1583 TLS_RSA_WITH_RC4_128_SHA,
1584 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
1585 TLS_RSA_EXPORT_WITH_RC4_40_MD5
1588 { 1,
1590 TLS_COMP_METHOD_NULL
1594 struct tls_compiled_message *cmsg;
1596 /* First 4 bytes of client_random is the current timestamp */
1597 sipe_tls_fill_random(&state->client_random,
1598 TLS_ARRAY_RANDOM_LENGTH * 8); /* -> bits */
1599 memcpy(state->client_random.buffer, &now_N, sizeof(now_N));
1600 memcpy(msg.random.random, state->client_random.buffer,
1601 TLS_ARRAY_RANDOM_LENGTH);
1603 cmsg = compile_handshake_msg(state, &ClientHello_m, &msg, sizeof(msg));
1604 compile_tls_record(state, cmsg, NULL);
1605 g_free(cmsg);
1607 if (sipe_backend_debug_enabled())
1608 state->debug = g_string_new("");
1610 state->state = TLS_HANDSHAKE_STATE_SERVER_HELLO;
1611 return(tls_record_parse(state, FALSE));
1614 static gboolean tls_server_hello(struct tls_internal_state *state)
1616 struct tls_compiled_message *certificate = NULL;
1617 struct tls_compiled_message *exchange = NULL;
1618 struct tls_compiled_message *verify = NULL;
1619 struct tls_compiled_message *finished = NULL;
1620 gboolean success = FALSE;
1622 if (!tls_record_parse(state, TRUE))
1623 return(FALSE);
1625 if (((certificate = tls_client_certificate(state)) != NULL) &&
1626 ((exchange = tls_client_key_exchange(state)) != NULL) &&
1627 ((verify = tls_certificate_verify(state)) != NULL) &&
1628 ((finished = tls_client_finished(state)) != NULL)) {
1630 /* Part 1 */
1631 compile_tls_record(state, certificate, exchange, verify, NULL);
1633 success = tls_record_parse(state, FALSE);
1634 if (success) {
1635 guchar *part1 = state->common.out_buffer;
1636 gsize part1_length = state->common.out_length;
1637 guchar *part3;
1638 gsize part3_length;
1639 guchar *merged;
1640 gsize length;
1641 /* ChangeCipherSpec is always the same */
1642 static const guchar part2[] = {
1643 TLS_RECORD_TYPE_CHANGE_CIPHER_SPEC,
1644 (TLS_PROTOCOL_VERSION_1_0 >> 8) & 0xFF,
1645 TLS_PROTOCOL_VERSION_1_0 & 0xFF,
1646 0x00, 0x01, /* length: 1 byte */
1647 0x01 /* change_cipher_spec(1) */
1650 state->common.out_buffer = NULL;
1652 /* Part 3 - this is the first encrypted record */
1653 compile_encrypted_tls_record(state, finished);
1654 part3 = state->common.out_buffer;
1655 part3_length = state->common.out_length;
1657 /* merge TLS records */
1658 length = part1_length + sizeof(part2) + part3_length;
1659 merged = g_malloc(length);
1661 memcpy(merged, part1, part1_length);
1662 memcpy(merged + part1_length, part2, sizeof(part2));
1663 memcpy(merged + part1_length + sizeof(part2), part3, part3_length);
1664 g_free(part3);
1665 g_free(part1);
1667 /* replace output buffer with merged message */
1668 state->common.out_buffer = merged;
1669 state->common.out_length = length;
1671 state->state = TLS_HANDSHAKE_STATE_FINISHED;
1675 g_free(finished);
1676 g_free(verify);
1677 g_free(exchange);
1678 g_free(certificate);
1679 free_parse_data(state);
1681 return(success);
1684 static gboolean tls_finished(struct tls_internal_state *state)
1686 guchar *random;
1688 if (!tls_record_parse(state, TRUE))
1689 return(FALSE);
1691 /* we don't need the data */
1692 free_parse_data(state);
1695 * Calculate session keys [MS-SIPAE section 3.2.5.1]
1697 * key_material = PRF (master_secret,
1698 * "client EAP encryption",
1699 * ClientHello.random + ServerHello.random)[128]
1700 * = 4 x 32 Bytes
1702 * client key = key_material[3rd 32 Bytes]
1703 * server key = key_material[4th 32 Bytes]
1705 random = g_malloc(TLS_ARRAY_RANDOM_LENGTH * 2);
1706 memcpy(random,
1707 state->client_random.buffer,
1708 TLS_ARRAY_RANDOM_LENGTH);
1709 memcpy(random + TLS_ARRAY_RANDOM_LENGTH,
1710 state->server_random.buffer,
1711 TLS_ARRAY_RANDOM_LENGTH);
1712 state->tls_dsk_key_block = sipe_tls_prf(state,
1713 state->master_secret,
1714 TLS_ARRAY_MASTER_SECRET_LENGTH,
1715 (guchar *) "client EAP encryption",
1717 random,
1718 TLS_ARRAY_RANDOM_LENGTH * 2,
1719 4 * 32);
1720 g_free(random);
1722 #ifdef __SIPE_TLS_CRYPTO_DEBUG
1723 debug_secrets(state, "tls_finished: TLS-DSK key block ",
1724 state->tls_dsk_key_block, 4 * 32);
1725 #endif
1727 state->common.client_key = state->tls_dsk_key_block + 2 * 32;
1728 state->common.server_key = state->tls_dsk_key_block + 3 * 32;
1729 state->common.key_length = 32;
1731 debug_secrets(state, "tls_finished: TLS-DSK client key ",
1732 state->common.client_key,
1733 state->common.key_length);
1734 debug_secrets(state, "tls_finished: TLS-DSK server key ",
1735 state->common.server_key,
1736 state->common.key_length);
1738 state->common.out_buffer = NULL;
1739 state->common.out_length = 0;
1740 state->state = TLS_HANDSHAKE_STATE_COMPLETED;
1742 return(TRUE);
1746 * TLS public API
1749 struct sipe_tls_state *sipe_tls_start(gpointer certificate)
1751 struct tls_internal_state *state;
1753 if (!certificate)
1754 return(NULL);
1756 state = g_new0(struct tls_internal_state, 1);
1757 state->certificate = certificate;
1758 state->state = TLS_HANDSHAKE_STATE_START;
1759 state->md5_context = sipe_digest_md5_start();
1760 state->sha1_context = sipe_digest_sha1_start();
1761 state->common.algorithm = SIPE_TLS_DIGEST_ALGORITHM_NONE;
1763 return((struct sipe_tls_state *) state);
1766 gboolean sipe_tls_next(struct sipe_tls_state *state)
1768 /* Avoid "cast increases required alignment" errors */
1769 struct tls_internal_state *internal = (void *) state;
1770 gboolean success = FALSE;
1772 if (!state)
1773 return(FALSE);
1775 state->out_buffer = NULL;
1777 switch (internal->state) {
1778 case TLS_HANDSHAKE_STATE_START:
1779 success = tls_client_hello(internal);
1780 break;
1782 case TLS_HANDSHAKE_STATE_SERVER_HELLO:
1783 success = tls_server_hello(internal);
1784 break;
1786 case TLS_HANDSHAKE_STATE_FINISHED:
1787 success = tls_finished(internal);
1788 break;
1790 case TLS_HANDSHAKE_STATE_COMPLETED:
1791 case TLS_HANDSHAKE_STATE_FAILED:
1792 /* This should not happen */
1793 SIPE_DEBUG_ERROR_NOFORMAT("sipe_tls_next: called in incorrect state!");
1794 break;
1797 if (!success) {
1798 internal->state = TLS_HANDSHAKE_STATE_FAILED;
1801 return(success);
1804 guint sipe_tls_expires(struct sipe_tls_state *state)
1806 /* Avoid "cast increases required alignment" errors */
1807 struct tls_internal_state *internal = (void *) state;
1809 if (!state)
1810 return(0);
1812 return(sipe_cert_crypto_expires(internal->certificate));
1815 void sipe_tls_free(struct sipe_tls_state *state)
1817 if (state) {
1818 /* Avoid "cast increases required alignment" errors */
1819 struct tls_internal_state *internal = (void *) state;
1821 free_parse_data(internal);
1822 if (internal->debug)
1823 g_string_free(internal->debug, TRUE);
1824 g_free(internal->tls_dsk_key_block);
1825 g_free(internal->key_block);
1826 g_free(internal->master_secret);
1827 sipe_tls_free_random(&internal->pre_master_secret);
1828 sipe_tls_free_random(&internal->client_random);
1829 sipe_tls_free_random(&internal->server_random);
1830 if (internal->cipher_context)
1831 sipe_crypt_tls_destroy(internal->cipher_context);
1832 if (internal->md5_context)
1833 sipe_digest_md5_destroy(internal->md5_context);
1834 if (internal->sha1_context)
1835 sipe_digest_sha1_destroy(internal->sha1_context);
1836 sipe_cert_crypto_destroy(internal->server_certificate);
1837 g_free(state->out_buffer);
1838 g_free(state);
1842 #endif /* !_SIPE_COMPILING_ANALYZER */
1845 Local Variables:
1846 mode: c
1847 c-file-style: "bsd"
1848 indent-tabs-mode: t
1849 tab-width: 8
1850 End: