Imported Upstream version 1.1.1
[platform/upstream/iotivity.git] / extlibs / tinydtls / dtls.c
1 /* dtls -- a very basic DTLS implementation
2  *
3  * Copyright (C) 2011--2012,2014 Olaf Bergmann <bergmann@tzi.org>
4  * Copyright (C) 2013 Hauke Mehrtens <hauke@hauke-m.de>
5  *
6  * Permission is hereby granted, free of charge, to any person
7  * obtaining a copy of this software and associated documentation
8  * files (the "Software"), to deal in the Software without
9  * restriction, including without limitation the rights to use, copy,
10  * modify, merge, publish, distribute, sublicense, and/or sell copies
11  * of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be
15  * included in all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
21  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
22  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24  * SOFTWARE.
25  */
26
27 #include "tinydtls.h"
28 #include "dtls_config.h"
29 #include "dtls_time.h"
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #ifdef HAVE_ASSERT_H
34 #include <assert.h>
35 #endif
36 #ifndef WITH_CONTIKI
37 #include <stdlib.h>
38 #include "uthash.h"
39 #endif /* WITH_CONTIKI */
40
41 #include "debug.h"
42 #include "numeric.h"
43 #include "netq.h"
44 #include "dtls.h"
45
46 #include "alert.h"
47 #include "session.h"
48 #include "prng.h"
49
50 #ifdef WITH_SHA256
51 #  include "sha2/sha2.h"
52 #endif
53
54 #define dtls_set_version(H,V) dtls_int_to_uint16((H)->version, (V))
55 #define dtls_set_content_type(H,V) ((H)->content_type = (V) & 0xff)
56 #define dtls_set_length(H,V)  ((H)->length = (V))
57
58 #define dtls_get_content_type(H) ((H)->content_type & 0xff)
59 #define dtls_get_version(H) dtls_uint16_to_int((H)->version)
60 #define dtls_get_epoch(H) dtls_uint16_to_int((H)->epoch)
61 #define dtls_get_sequence_number(H) dtls_uint48_to_ulong((H)->sequence_number)
62 #define dtls_get_fragment_length(H) dtls_uint24_to_int((H)->fragment_length)
63
64 #ifndef WITH_CONTIKI
65 #define HASH_FIND_PEER(head,sess,out)           \
66   HASH_FIND(hh,head,sess,sizeof(session_t),out)
67 #define HASH_ADD_PEER(head,sess,add)            \
68   HASH_ADD(hh,head,sess,sizeof(session_t),add)
69 #define HASH_DEL_PEER(head,delptr)              \
70   HASH_DELETE(hh,head,delptr)
71 #endif /* WITH_CONTIKI */
72
73 #define DTLS_RH_LENGTH sizeof(dtls_record_header_t)
74 #define DTLS_HS_LENGTH sizeof(dtls_handshake_header_t)
75 #define DTLS_CH_LENGTH sizeof(dtls_client_hello_t) /* no variable length fields! */
76 #define DTLS_COOKIE_LENGTH_MAX 32
77 #define DTLS_CH_LENGTH_MAX sizeof(dtls_client_hello_t) + DTLS_COOKIE_LENGTH_MAX + 12 + 26
78 #define DTLS_HV_LENGTH sizeof(dtls_hello_verify_t)
79 #define DTLS_SH_LENGTH (2 + DTLS_RANDOM_LENGTH + 1 + 2 + 1)
80 #define DTLS_CE_LENGTH (3 + 3 + 27 + DTLS_EC_KEY_SIZE + DTLS_EC_KEY_SIZE)
81 #define DTLS_SKEXEC_LENGTH (1 + 2 + 1 + 1 + DTLS_EC_KEY_SIZE + DTLS_EC_KEY_SIZE + 1 + 1 + 2 + 70)
82 #define DTLS_SKEXEC_ECDH_ANON_LENGTH (1 + 2 + 1 + 1 + DTLS_EC_KEY_SIZE + DTLS_EC_KEY_SIZE)
83 #define DTLS_SKEXECPSK_LENGTH_MIN 2
84 #define DTLS_SKEXECPSK_LENGTH_MAX 2 + DTLS_PSK_MAX_CLIENT_IDENTITY_LEN
85 #define DTLS_CKXPSK_LENGTH_MIN 2
86 #define DTLS_CKXEC_LENGTH (1 + 1 + DTLS_EC_KEY_SIZE + DTLS_EC_KEY_SIZE)
87 #define DTLS_CV_LENGTH (1 + 1 + 2 + 1 + 1 + 1 + 1 + DTLS_EC_KEY_SIZE + 1 + 1 + DTLS_EC_KEY_SIZE)
88 #define DTLS_FIN_LENGTH 12
89
90 #define HS_HDR_LENGTH  DTLS_RH_LENGTH + DTLS_HS_LENGTH
91 #define HV_HDR_LENGTH  HS_HDR_LENGTH + DTLS_HV_LENGTH
92
93 #define HIGH(V) (((V) >> 8) & 0xff)
94 #define LOW(V)  ((V) & 0xff)
95
96 #define DTLS_RECORD_HEADER(M) ((dtls_record_header_t *)(M))
97 #define DTLS_HANDSHAKE_HEADER(M) ((dtls_handshake_header_t *)(M))
98
99 #define HANDSHAKE(M) ((dtls_handshake_header_t *)((M) + DTLS_RH_LENGTH))
100 #define CLIENTHELLO(M) ((dtls_client_hello_t *)((M) + HS_HDR_LENGTH))
101
102 /* The length check here should work because dtls_*_to_int() works on
103  * unsigned char. Otherwise, broken messages could cause severe
104  * trouble. Note that this macro jumps out of the current program flow
105  * when the message is too short. Beware!
106  */
107 #define SKIP_VAR_FIELD(P,L,T) {                                         \
108     if (L < dtls_ ## T ## _to_int(P) + sizeof(T))                       \
109       goto error;                                                       \
110     L -= dtls_ ## T ## _to_int(P) + sizeof(T);                          \
111     P += dtls_ ## T ## _to_int(P) + sizeof(T);                          \
112   }
113
114 /* some constants for the PRF */
115 #define PRF_LABEL(Label) prf_label_##Label
116 #define PRF_LABEL_SIZE(Label) (sizeof(PRF_LABEL(Label)) - 1)
117
118 static const unsigned char prf_label_master[] = "master secret";
119 static const unsigned char prf_label_key[] = "key expansion";
120 static const unsigned char prf_label_client[] = "client";
121 static const unsigned char prf_label_server[] = "server";
122 static const unsigned char prf_label_finished[] = " finished";
123
124 /* first part of Raw public key, the is the start of the Subject Public Key */
125 static const unsigned char cert_asn1_header[] = {
126   0x30, 0x59, /* SEQUENCE, length 89 bytes */
127     0x30, 0x13, /* SEQUENCE, length 19 bytes */
128       0x06, 0x07, /* OBJECT IDENTIFIER ecPublicKey (1 2 840 10045 2 1) */
129         0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01,
130       0x06, 0x08, /* OBJECT IDENTIFIER prime256v1 (1 2 840 10045 3 1 7) */
131         0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07,
132       0x03, 0x42, 0x00, /* BIT STRING, length 66 bytes, 0 bits unused */
133          0x04 /* uncompressed, followed by the r und s values of the public key */
134 };
135
136 #ifdef WITH_CONTIKI
137 PROCESS(dtls_retransmit_process, "DTLS retransmit process");
138
139 static dtls_context_t the_dtls_context;
140
141 static inline dtls_context_t *
142 malloc_context() {
143   return &the_dtls_context;
144 }
145
146 static inline void
147 free_context(dtls_context_t *context) {
148 }
149
150 #else /* WITH_CONTIKI */
151
152 static inline dtls_context_t *
153 malloc_context() {
154   return (dtls_context_t *)malloc(sizeof(dtls_context_t));
155 }
156
157 static inline void
158 free_context(dtls_context_t *context) {
159   free(context);
160 }
161 #endif
162
163 void
164 dtls_init() {
165   dtls_clock_init();
166   crypto_init();
167   netq_init();
168   peer_init();
169 }
170
171  void
172  dtls_enables_anon_ecdh(dtls_context_t* ctx, dtls_cipher_enable_t is_enable)
173 {
174     if(ctx)
175     {
176         ctx->is_anon_ecdh_eabled = is_enable;
177     }
178 }
179
180 void
181 dtls_select_cipher(dtls_context_t* ctx, const dtls_cipher_t cipher)
182 {
183     if(ctx)
184     {
185         ctx->selected_cipher = cipher;
186     }
187 }
188
189 /* Calls cb_alert() with given arguments if defined, otherwise an
190  * error message is logged and the result is -1. This is just an
191  * internal helper.
192  */
193 #define CALL(Context, which, ...)                                       \
194   ((Context)->h && (Context)->h->which                                  \
195    ? (Context)->h->which((Context), ##__VA_ARGS__)                      \
196    : -1)
197
198 static int
199 dtls_send_multi(dtls_context_t *ctx, dtls_peer_t *peer,
200                 dtls_security_parameters_t *security , session_t *session,
201                 unsigned char type, uint8 *buf_array[],
202                 size_t buf_len_array[], size_t buf_array_len);
203
204 /** 
205  * Sends the fragment of length \p buflen given in \p buf to the
206  * specified \p peer. The data will be MAC-protected and encrypted
207  * according to the selected cipher and split into one or more DTLS
208  * records of the specified \p type. This function returns the number
209  * of bytes that were sent, or \c -1 if an error occurred.
210  *
211  * \param ctx    The DTLS context to use.
212  * \param peer   The remote peer.
213  * \param type   The content type of the record. 
214  * \param buf    The data to send.
215  * \param buflen The actual length of \p buf.
216  * \return Less than zero on error, the number of bytes written otherwise.
217  */
218 static int
219 dtls_send(dtls_context_t *ctx, dtls_peer_t *peer, unsigned char type,
220           uint8 *buf, size_t buflen) {
221   return dtls_send_multi(ctx, peer, dtls_security_params(peer), &peer->session,
222                          type, &buf, &buflen, 1);
223 }
224
225 /**
226  * Stops ongoing retransmissions of handshake messages for @p peer.
227  */
228 static void dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer);
229
230 /**
231  * Starts retransmissions of handshake messages for @p peer.
232  */
233 static void dtls_start_retransmission(dtls_context_t *context, dtls_peer_t *peer);
234
235 /**
236  * Clears retransmissions of handshake messages for @p peer.
237  */
238 static void dtls_clear_retransmission(dtls_context_t *context, dtls_peer_t *peer);
239
240 dtls_peer_t *
241 dtls_get_peer(const dtls_context_t *ctx, const session_t *session) {
242   dtls_peer_t *p = NULL;
243
244 #ifndef WITH_CONTIKI
245   HASH_FIND_PEER(ctx->peers, session, p);
246 #else /* WITH_CONTIKI */
247   for (p = list_head(ctx->peers); p; p = list_item_next(p))
248     if (dtls_session_equals(&p->session, session))
249       return p;
250 #endif /* WITH_CONTIKI */
251   
252   return p;
253 }
254
255 static void
256 dtls_add_peer(dtls_context_t *ctx, dtls_peer_t *peer) {
257 #ifndef WITH_CONTIKI
258   HASH_ADD_PEER(ctx->peers, session, peer);
259 #else /* WITH_CONTIKI */
260   list_add(ctx->peers, peer);
261 #endif /* WITH_CONTIKI */
262 }
263
264 int
265 dtls_write(struct dtls_context_t *ctx, 
266            session_t *dst, uint8 *buf, size_t len) {
267   
268   dtls_peer_t *peer = dtls_get_peer(ctx, dst);
269
270   /* Check if peer connection already exists */
271   if (!peer) { /* no ==> create one */
272     int res;
273
274     /* dtls_connect() returns a value greater than zero if a new
275      * connection attempt is made, 0 for session reuse. */
276     res = dtls_connect(ctx, dst);
277
278     return (res >= 0) ? 0 : res;
279   } else { /* a session exists, check if it is in state connected */
280     
281     if (peer->state != DTLS_STATE_CONNECTED) {
282       return 0;
283     } else {
284       return dtls_send(ctx, peer, DTLS_CT_APPLICATION_DATA, buf, len);
285     }
286   }
287 }
288
289 static int
290 dtls_get_cookie(uint8 *msg, size_t msglen, uint8 **cookie) {
291   /* To access the cookie, we have to determine the session id's
292    * length and skip the whole thing. */
293   if (msglen < DTLS_HS_LENGTH + DTLS_CH_LENGTH + sizeof(uint8))
294     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
295
296   if (dtls_uint16_to_int(msg + DTLS_HS_LENGTH) != DTLS_VERSION)
297     return dtls_alert_fatal_create(DTLS_ALERT_PROTOCOL_VERSION);
298
299   msglen -= DTLS_HS_LENGTH + DTLS_CH_LENGTH;
300   msg += DTLS_HS_LENGTH + DTLS_CH_LENGTH;
301
302   SKIP_VAR_FIELD(msg, msglen, uint8); /* skip session id */
303
304   if (msglen < (*msg & 0xff) + sizeof(uint8))
305     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
306   
307   *cookie = msg + sizeof(uint8);
308   return dtls_uint8_to_int(msg);
309
310  error:
311   return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
312 }
313
314 static int
315 dtls_create_cookie(dtls_context_t *ctx, 
316                    session_t *session,
317                    uint8 *msg, size_t msglen,
318                    uint8 *cookie, int *clen) {
319   unsigned char buf[DTLS_HMAC_MAX];
320   size_t len, e;
321
322   /* create cookie with HMAC-SHA256 over:
323    * - SECRET
324    * - session parameters (only IP address?)
325    * - client version 
326    * - random gmt and bytes
327    * - session id
328    * - cipher_suites 
329    * - compression method
330    */
331
332   /* We use our own buffer as hmac_context instead of a dynamic buffer
333    * created by dtls_hmac_new() to separate storage space for cookie
334    * creation from storage that is used in real sessions. Note that
335    * the buffer size must fit with the default hash algorithm (see
336    * implementation of dtls_hmac_context_new()). */
337
338   dtls_hmac_context_t hmac_context;
339   dtls_hmac_init(&hmac_context, ctx->cookie_secret, DTLS_COOKIE_SECRET_LENGTH);
340
341   dtls_hmac_update(&hmac_context, 
342                    (unsigned char *)&session->addr, session->size);
343
344   /* feed in the beginning of the Client Hello up to and including the
345      session id */
346   e = sizeof(dtls_client_hello_t);
347   e += (*(msg + DTLS_HS_LENGTH + e) & 0xff) + sizeof(uint8);
348   if (e + DTLS_HS_LENGTH > msglen)
349     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
350
351   dtls_hmac_update(&hmac_context, msg + DTLS_HS_LENGTH, e);
352   
353   /* skip cookie bytes and length byte */
354   e += *(uint8 *)(msg + DTLS_HS_LENGTH + e) & 0xff;
355   e += sizeof(uint8);
356   if (e + DTLS_HS_LENGTH > msglen)
357     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
358
359   dtls_hmac_update(&hmac_context, 
360                    msg + DTLS_HS_LENGTH + e,
361                    dtls_get_fragment_length(DTLS_HANDSHAKE_HEADER(msg)) - e);
362
363   len = dtls_hmac_finalize(&hmac_context, buf);
364
365   if (len < *clen) {
366     memset(cookie + len, 0, *clen - len);
367     *clen = len;
368   }
369   
370   memcpy(cookie, buf, *clen);
371   return 0;
372 }
373
374 #ifdef DTLS_CHECK_CONTENTTYPE
375 /* used to check if a received datagram contains a DTLS message */
376 static char const content_types[] = { 
377   DTLS_CT_CHANGE_CIPHER_SPEC,
378   DTLS_CT_ALERT,
379   DTLS_CT_HANDSHAKE,
380   DTLS_CT_APPLICATION_DATA,
381   0                             /* end marker */
382 };
383 #endif
384
385 /**
386  * Checks if \p msg points to a valid DTLS record. If
387  * 
388  */
389 static unsigned int
390 is_record(uint8 *msg, size_t msglen) {
391   unsigned int rlen = 0;
392
393   if (msglen >= DTLS_RH_LENGTH  /* FIXME allow empty records? */
394 #ifdef DTLS_CHECK_CONTENTTYPE
395       && strchr(content_types, msg[0])
396 #endif
397       && msg[1] == HIGH(DTLS_VERSION)
398       && msg[2] == LOW(DTLS_VERSION)) 
399     {
400       rlen = DTLS_RH_LENGTH + 
401         dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->length);
402       
403       /* we do not accept wrong length field in record header */
404       if (rlen > msglen)        
405         rlen = 0;
406   } 
407   
408   return rlen;
409 }
410
411 /**
412  * Initializes \p buf as record header. The caller must ensure that \p
413  * buf is capable of holding at least \c sizeof(dtls_record_header_t)
414  * bytes. Increments sequence number counter of \p security.
415  * \return pointer to the next byte after the written header.
416  * The length will be set to 0 and has to be changed before sending.
417  */ 
418 static inline uint8 *
419 dtls_set_record_header(uint8 type, dtls_security_parameters_t *security,
420                        uint8 *buf) {
421   
422   dtls_int_to_uint8(buf, type);
423   buf += sizeof(uint8);
424
425   dtls_int_to_uint16(buf, DTLS_VERSION);
426   buf += sizeof(uint16);
427
428   if (security) {
429     dtls_int_to_uint16(buf, security->epoch);
430     buf += sizeof(uint16);
431
432     dtls_int_to_uint48(buf, security->rseq);
433     buf += sizeof(uint48);
434
435     /* increment record sequence counter by 1 */
436     security->rseq++;
437   } else {
438     memset(buf, 0, sizeof(uint16) + sizeof(uint48));
439     buf += sizeof(uint16) + sizeof(uint48);
440   }
441
442   memset(buf, 0, sizeof(uint16));
443   return buf + sizeof(uint16);
444 }
445
446 /**
447  * Initializes \p buf as handshake header. The caller must ensure that \p
448  * buf is capable of holding at least \c sizeof(dtls_handshake_header_t)
449  * bytes. Increments message sequence number counter of \p peer.
450  * \return pointer to the next byte after \p buf
451  */ 
452 static inline uint8 *
453 dtls_set_handshake_header(uint8 type, dtls_peer_t *peer, 
454                           int length, 
455                           int frag_offset, int frag_length, 
456                           uint8 *buf) {
457   
458   dtls_int_to_uint8(buf, type);
459   buf += sizeof(uint8);
460
461   dtls_int_to_uint24(buf, length);
462   buf += sizeof(uint24);
463
464   if (peer && peer->handshake_params) {
465     /* and copy the result to buf */
466     dtls_int_to_uint16(buf, peer->handshake_params->hs_state.mseq_s);
467
468     /* increment handshake message sequence counter by 1 */
469     peer->handshake_params->hs_state.mseq_s++;
470   } else {
471     memset(buf, 0, sizeof(uint16));    
472   }
473   buf += sizeof(uint16);
474   
475   dtls_int_to_uint24(buf, frag_offset);
476   buf += sizeof(uint24);
477
478   dtls_int_to_uint24(buf, frag_length);
479   buf += sizeof(uint24);
480   
481   return buf;
482 }
483
484 /** only one compression method is currently defined */
485 static uint8 compression_methods[] = {
486   TLS_COMPRESSION_NULL
487 };
488
489 /** returns true if the cipher matches TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
490 static inline int is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(dtls_cipher_t cipher)
491 {
492 #if defined(DTLS_ECC) || defined(DTLS_X509)
493   return cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
494 #else
495   return 0;
496 #endif /* DTLS_ECC */
497 }
498
499 /** returns true if the cipher matches TLS_PSK_WITH_AES_128_CCM_8 */
500 static inline int is_tls_psk_with_aes_128_ccm_8(dtls_cipher_t cipher)
501 {
502 #ifdef DTLS_PSK
503   return cipher == TLS_PSK_WITH_AES_128_CCM_8;
504 #else
505   return 0;
506 #endif /* DTLS_PSK */
507 }
508
509 /** returns true if the cipher matches TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 */
510 static inline int is_tls_ecdh_anon_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
511 {
512 #ifdef DTLS_ECC
513     return cipher == TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256;
514 #else
515     return 0;
516 #endif
517 }
518
519 /** returns true if the cipher matches TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 */
520 static inline int is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
521 {
522 #if defined(DTLS_ECC) && defined(DTLS_PSK)
523   return cipher == TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256;
524 #else
525   return 0;
526 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
527 }
528
529
530
531 /** returns true if the application is configured for psk */
532 static inline int is_psk_supported(dtls_context_t *ctx)
533 {
534 #ifdef DTLS_PSK
535   return ctx && ctx->h && ctx->h->get_psk_info;
536 #else
537   return 0;
538 #endif /* DTLS_PSK */
539 }
540
541 /** returns true if the application is configured for ecdhe_ecdsa */
542 static inline int is_ecdsa_supported(dtls_context_t *ctx, int is_client)
543 {
544 #ifdef DTLS_ECC
545   return ctx && ctx->h && ((!is_client && ctx->h->get_ecdsa_key) ||
546                            (is_client && ctx->h->verify_ecdsa_key));
547 #else
548   return 0;
549 #endif /* DTLS_ECC */
550 }
551
552 /** returns true if the application is configured for x509 */
553 static inline int is_x509_supported(dtls_context_t *ctx, int is_client)
554 {
555 #ifdef DTLS_X509
556   return ctx && ctx->h && ((!is_client && ctx->h->get_x509_cert) ||
557                (is_client && ctx->h->verify_x509_cert));
558 #else
559   return 0;
560 #endif /* DTLS_X509 */
561 }
562
563 /** Returns true if the application is configured for ecdhe_ecdsa with
564   * client authentication */
565 static inline int is_ecdsa_client_auth_supported(dtls_context_t *ctx)
566 {
567 #ifdef DTLS_ECC
568   return ctx && ctx->h && ctx->h->get_ecdsa_key && ctx->h->verify_ecdsa_key;
569 #else
570   return 0;
571 #endif /* DTLS_ECC */
572 }
573
574 /** Returns true if the application is configured for x509 with
575   * client authentication */
576 static inline int is_x509_client_auth_supported(dtls_context_t *ctx)
577 {
578 #ifdef DTLS_X509
579   return ctx && ctx->h && ctx->h->get_x509_cert && ctx->h->verify_x509_cert;
580 #else
581   return 0;
582 #endif /* DTLS_X509 */
583 }
584
585 /** returns true if ecdh_anon_with_aes_128_cbc_sha is supported */
586 static inline int is_ecdh_anon_supported(dtls_context_t *ctx)
587 {
588 #ifdef DTLS_ECC
589     return ctx &&  (ctx->is_anon_ecdh_eabled == DTLS_CIPHER_ENABLE);
590 #else
591     return 0;
592 #endif
593 }
594
595 /** returns true if ecdhe_psk_with_aes_128_cbc_sha_256 is supported */
596 static inline int is_ecdhe_psk_supported(dtls_context_t *ctx)
597 {
598 #if defined(DTLS_ECC) && defined(DTLS_PSK)
599     return is_psk_supported(ctx);
600 #else
601     return 0;
602 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
603 }
604
605
606 /**
607  * Returns @c 1 if @p code is a cipher suite other than @c
608  * TLS_NULL_WITH_NULL_NULL that we recognize.
609  *
610  * @param ctx   The current DTLS context
611  * @param code The cipher suite identifier to check
612  * @param is_client 1 for a dtls client, 0 for server
613  * @return @c 1 iff @p code is recognized,
614  */ 
615 static int
616 known_cipher(dtls_context_t *ctx, dtls_cipher_t code, int is_client) {
617   int psk;
618   int ecdsa;
619   int ecdh_anon;
620   int ecdhe_psk;
621   int x509;
622
623   psk = is_psk_supported(ctx);
624   ecdsa = is_ecdsa_supported(ctx, is_client);
625   ecdh_anon = is_ecdh_anon_supported(ctx);
626   ecdhe_psk = is_ecdhe_psk_supported(ctx);
627   x509 = is_x509_supported(ctx, is_client);
628
629   return (psk && is_tls_psk_with_aes_128_ccm_8(code)) ||
630          (ecdsa && is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(code)) ||
631          (ecdh_anon && is_tls_ecdh_anon_with_aes_128_cbc_sha_256(code)) ||
632          (ecdhe_psk && is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(code)) ||
633      (x509 && is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(code));
634 }
635
636 /**
637  * This method detects if we already have a established DTLS session with
638  * peer and the peer is attempting to perform a fresh handshake by sending
639  * messages with epoch = 0. This is to handle situations mentioned in
640  * RFC 6347 - section 4.2.8.
641  *
642  * @param msg  The packet received from Client
643  * @param msglen Packet length
644  * @param peer peer who is the sender for this packet
645  * @return @c 1 if this is a rehandshake attempt by
646  * client
647  */
648 static int
649 hs_attempt_with_existing_peer(uint8_t *msg, size_t msglen,
650     dtls_peer_t *peer)
651 {
652     if ((peer) && (peer->state == DTLS_STATE_CONNECTED)) {
653       if (msg[0] == DTLS_CT_HANDSHAKE) {
654         uint16_t msg_epoch = dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
655         if (msg_epoch == 0) {
656           dtls_handshake_header_t * hs_header = DTLS_HANDSHAKE_HEADER(msg + DTLS_RH_LENGTH);
657           if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
658               hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
659             return 1;
660           }
661         }
662       }
663     }
664     return 0;
665 }
666
667 /** Dump out the cipher keys and IVs used for the symetric cipher. */
668 static void dtls_debug_keyblock(dtls_security_parameters_t *config)
669 {
670   dtls_debug("key_block (%d bytes):\n", dtls_kb_size(config, peer->role));
671   dtls_debug_dump("  client_MAC_secret",
672                   dtls_kb_client_mac_secret(config, peer->role),
673                   dtls_kb_mac_secret_size(config->cipher));
674
675   dtls_debug_dump("  server_MAC_secret",
676                   dtls_kb_server_mac_secret(config, peer->role),
677                   dtls_kb_mac_secret_size(config->cipher));
678
679   dtls_debug_dump("  client_write_key",
680                   dtls_kb_client_write_key(config, peer->role),
681                   dtls_kb_key_size(config, peer->role));
682
683   dtls_debug_dump("  server_write_key",
684                   dtls_kb_server_write_key(config, peer->role),
685                   dtls_kb_key_size(config, peer->role));
686
687   dtls_debug_dump("  client_IV",
688                   dtls_kb_client_iv(config, peer->role),
689                   dtls_kb_iv_size(config->cipher));
690
691   dtls_debug_dump("  server_IV",
692                   dtls_kb_server_iv(config, peer->role),
693                   dtls_kb_iv_size(config->cipher));
694 }
695
696 /** returns the name of the goven handshake type number.
697   * see IANA for a full list of types:
698   * https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-7
699   */
700 static char *dtls_handshake_type_to_name(int type)
701 {
702   switch (type) {
703   case DTLS_HT_HELLO_REQUEST:
704     return "hello_request";
705   case DTLS_HT_CLIENT_HELLO:
706     return "client_hello";
707   case DTLS_HT_SERVER_HELLO:
708     return "server_hello";
709   case DTLS_HT_HELLO_VERIFY_REQUEST:
710     return "hello_verify_request";
711   case DTLS_HT_CERTIFICATE:
712     return "certificate";
713   case DTLS_HT_SERVER_KEY_EXCHANGE:
714     return "server_key_exchange";
715   case DTLS_HT_CERTIFICATE_REQUEST:
716     return "certificate_request";
717   case DTLS_HT_SERVER_HELLO_DONE:
718     return "server_hello_done";
719   case DTLS_HT_CERTIFICATE_VERIFY:
720     return "certificate_verify";
721   case DTLS_HT_CLIENT_KEY_EXCHANGE:
722     return "client_key_exchange";
723   case DTLS_HT_FINISHED:
724     return "finished";
725   default:
726     return "unknown";
727   }
728 }
729
730 /**
731  * Calculate the pre master secret and after that calculate the master-secret.
732  */
733 static int
734 calculate_key_block(dtls_context_t *ctx, 
735                     dtls_handshake_parameters_t *handshake,
736                     dtls_peer_t *peer,
737                     session_t *session,
738                     dtls_peer_type role) {
739 #if defined(DTLS_PSK) && defined(DTLS_ECC)
740   unsigned char pre_master_secret[MAX_KEYBLOCK_LENGTH + uECC_BYTES];
741 #else
742   unsigned char pre_master_secret[MAX_KEYBLOCK_LENGTH];
743 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
744   int pre_master_len = 0;
745   dtls_security_parameters_t *security = dtls_security_params_next(peer);
746   uint8 master_secret[DTLS_MASTER_SECRET_LENGTH];
747
748   if (!security) {
749     return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
750   }
751
752   switch (handshake->cipher) {
753 #ifdef DTLS_PSK
754   case TLS_PSK_WITH_AES_128_CCM_8: {
755     unsigned char psk[DTLS_PSK_MAX_KEY_LEN];
756     int len;
757
758     len = CALL(ctx, get_psk_info, session, DTLS_PSK_KEY,
759                handshake->keyx.psk.identity,
760                handshake->keyx.psk.id_length,
761                psk, DTLS_PSK_MAX_KEY_LEN);
762     if (len < 0) {
763       dtls_crit("no psk key for session available\n");
764       return len;
765     }
766   /* Temporarily use the key_block storage space for the pre master secret. */
767     pre_master_len = dtls_psk_pre_master_secret(psk, len,
768                                                 pre_master_secret,
769                                                 MAX_KEYBLOCK_LENGTH);
770
771     dtls_debug_hexdump("psk", psk, len);
772
773     memset(psk, 0, DTLS_PSK_MAX_KEY_LEN);
774     if (pre_master_len < 0) {
775       dtls_crit("the psk was too long, for the pre master secret\n");
776       return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
777     }
778
779     break;
780   }
781 #endif /* DTLS_PSK */
782 #if defined(DTLS_ECC) || defined(DTLS_X509)
783   case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
784   case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256: {
785     pre_master_len = dtls_ecdh_pre_master_secret(handshake->keyx.ecc.own_eph_priv,
786                                                  handshake->keyx.ecc.other_eph_pub_x,
787                                                  handshake->keyx.ecc.other_eph_pub_y,
788                                                  sizeof(handshake->keyx.ecc.own_eph_priv),
789                                                  pre_master_secret,
790                                                  MAX_KEYBLOCK_LENGTH);
791     if (pre_master_len < 0) {
792       dtls_crit("the curve was too long, for the pre master secret\n");
793       return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
794     }
795     break;
796   }
797 #endif /* DTLS_ECC */
798 #if defined(DTLS_PSK) && defined(DTLS_ECC)
799     case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256: {
800       unsigned char psk[DTLS_PSK_MAX_KEY_LEN];
801       int psklen;
802
803       psklen = CALL(ctx, get_psk_info, session, DTLS_PSK_KEY,
804              handshake->keyx.psk.identity,
805              handshake->keyx.psk.id_length,
806              psk, DTLS_PSK_MAX_KEY_LEN);
807       if (psklen < 0) {
808         dtls_crit("no psk key for session available\n");
809         return psklen;
810       }
811
812       pre_master_len = dtls_ecdhe_psk_pre_master_secret(psk, psklen,
813                            handshake->keyx.ecc.own_eph_priv,
814                            handshake->keyx.ecc.other_eph_pub_x,
815                            handshake->keyx.ecc.other_eph_pub_y,
816                            sizeof(handshake->keyx.ecc.own_eph_priv),
817                            pre_master_secret,
818                            MAX_KEYBLOCK_LENGTH + uECC_BYTES);
819
820       if (pre_master_len < 0) {
821         dtls_crit("the curve was too long, for the pre master secret\n");
822         return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
823       }
824       break;
825     }
826 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC)  */
827   default:
828     dtls_crit("calculate_key_block: unknown cipher\n");
829     return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
830   }
831
832   dtls_debug_dump("client_random", handshake->tmp.random.client, DTLS_RANDOM_LENGTH);
833   dtls_debug_dump("server_random", handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
834   dtls_debug_dump("pre_master_secret", pre_master_secret, pre_master_len);
835
836   dtls_prf(pre_master_secret, pre_master_len,
837            PRF_LABEL(master), PRF_LABEL_SIZE(master),
838            handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
839            handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
840            master_secret,
841            DTLS_MASTER_SECRET_LENGTH);
842
843   dtls_debug_dump("master_secret", master_secret, DTLS_MASTER_SECRET_LENGTH);
844
845   /* create key_block from master_secret
846    * key_block = PRF(master_secret,
847                     "key expansion" + tmp.random.server + tmp.random.client) */
848   security->cipher = handshake->cipher;
849   security->compression = handshake->compression;
850   security->rseq = 0;
851
852   dtls_prf(master_secret,
853            DTLS_MASTER_SECRET_LENGTH,
854            PRF_LABEL(key), PRF_LABEL_SIZE(key),
855            handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
856            handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
857            security->key_block,
858            dtls_kb_size(security, role));
859
860   memcpy(handshake->tmp.master_secret, master_secret, DTLS_MASTER_SECRET_LENGTH);
861   dtls_debug_keyblock(security);
862
863
864   return 0;
865 }
866
867 /* TODO: add a generic method which iterates over a list and searches for a specific key */
868 static int verify_ext_eliptic_curves(uint8 *data, size_t data_length) {
869   int i, curve_name;
870
871   /* length of curve list */
872   i = dtls_uint16_to_int(data);
873   data += sizeof(uint16);
874   if (i + sizeof(uint16) != data_length) {
875     dtls_warn("the list of the supported elliptic curves should be tls extension length - 2\n");
876     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
877   }
878
879   for (i = data_length - sizeof(uint16); i > 0; i -= sizeof(uint16)) {
880     /* check if this curve is supported */
881     curve_name = dtls_uint16_to_int(data);
882     data += sizeof(uint16);
883
884     if (curve_name == TLS_EXT_ELLIPTIC_CURVES_SECP256R1)
885       return 0;
886   }
887
888   dtls_warn("no supported elliptic curve found\n");
889   return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
890 }
891
892 static int verify_ext_cert_type(uint8 *data, size_t data_length) {
893   int i, cert_type;
894
895   /* length of cert type list */
896   i = dtls_uint8_to_int(data);
897   data += sizeof(uint8);
898   if (i + sizeof(uint8) != data_length) {
899     dtls_warn("the list of the supported certificate types should be tls extension length - 1\n");
900     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
901   }
902
903   for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
904     /* check if this cert type is supported */
905     cert_type = dtls_uint8_to_int(data);
906     data += sizeof(uint8);
907
908
909     if (cert_type == TLS_CERT_TYPE_RAW_PUBLIC_KEY)
910         return 0;
911 #ifdef DTLS_X509
912     if (cert_type == TLS_CERT_TYPE_X509)
913         return 0;
914 #endif
915   }
916
917   dtls_warn("no supported certificate type found\n");
918   return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
919 }
920
921 static int verify_ext_ec_point_formats(uint8 *data, size_t data_length) {
922   int i, cert_type;
923
924   /* length of ec_point_formats list */
925   i = dtls_uint8_to_int(data);
926   data += sizeof(uint8);
927   if (i + sizeof(uint8) != data_length) {
928     dtls_warn("the list of the supported ec_point_formats should be tls extension length - 1\n");
929     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
930   }
931
932   for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
933     /* check if this ec_point_format is supported */
934     cert_type = dtls_uint8_to_int(data);
935     data += sizeof(uint8);
936
937     if (cert_type == TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED)
938       return 0;
939   }
940
941   dtls_warn("no supported ec_point_format found\n");
942   return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
943 }
944
945 /*
946  * Check for some TLS Extensions used by the ECDHE_ECDSA cipher.
947  */
948 static int
949 dtls_check_tls_extension(dtls_peer_t *peer,
950                          uint8 *data, size_t data_length, int client_hello)
951 {
952   uint16_t i, j;
953   int ext_elliptic_curve = 0;
954   int ext_client_cert_type = 0;
955   int ext_server_cert_type = 0;
956   int ext_ec_point_formats = 0;
957   dtls_handshake_parameters_t *handshake = peer->handshake_params;
958
959   if (data_length < sizeof(uint16)) { 
960     /* no tls extensions specified */
961     if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher)) {
962       goto error;
963     }
964     return 0;
965   }
966
967   /* get the length of the tls extension list */
968   j = dtls_uint16_to_int(data);
969   data += sizeof(uint16);
970   data_length -= sizeof(uint16);
971
972   if (data_length < j)
973     goto error;
974
975   /* check for TLS extensions needed for this cipher */
976   while (data_length) {
977     if (data_length < sizeof(uint16) * 2)
978       goto error;
979
980     /* get the tls extension type */
981     i = dtls_uint16_to_int(data);
982     data += sizeof(uint16);
983     data_length -= sizeof(uint16);
984
985     /* get the length of the tls extension */
986     j = dtls_uint16_to_int(data);
987     data += sizeof(uint16);
988     data_length -= sizeof(uint16);
989
990     if (data_length < j)
991       goto error;
992
993     switch (i) {
994       case TLS_EXT_ELLIPTIC_CURVES:
995         ext_elliptic_curve = 1;
996         if (verify_ext_eliptic_curves(data, j))
997           goto error;
998         break;
999       case TLS_EXT_CLIENT_CERTIFICATE_TYPE:
1000         ext_client_cert_type = 1;
1001         if (client_hello) {
1002           if (verify_ext_cert_type(data, j))
1003             goto error;
1004         } else {
1005 #ifndef DTLS_X509
1006           if (dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY)
1007 #else
1008           if ((dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY) &&
1009               (dtls_uint8_to_int(data) != TLS_CERT_TYPE_X509))
1010 #endif
1011             goto error;
1012         }
1013         break;
1014       case TLS_EXT_SERVER_CERTIFICATE_TYPE:
1015         ext_server_cert_type = 1;
1016         if (client_hello) {
1017           if (verify_ext_cert_type(data, j))
1018             goto error;
1019         } else {
1020 #ifndef DTLS_X509
1021           if (dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY)
1022 #else
1023           if ((dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY) &&
1024               (dtls_uint8_to_int(data) != TLS_CERT_TYPE_X509))
1025 #endif
1026             goto error;
1027         }
1028         break;
1029       case TLS_EXT_EC_POINT_FORMATS:
1030         ext_ec_point_formats = 1;
1031         if (verify_ext_ec_point_formats(data, j))
1032           goto error;
1033         break;
1034       case TLS_EXT_ENCRYPT_THEN_MAC:
1035         /* As only AEAD cipher suites are currently available, this
1036          * extension can be skipped. 
1037          */
1038         dtls_info("skipped encrypt-then-mac extension\n");
1039         break;
1040       default:
1041         dtls_warn("unsupported tls extension: %i\n", i);
1042         break;
1043     }
1044     data += j;
1045     data_length -= j;
1046   }
1047   if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && client_hello) {
1048     if (!ext_elliptic_curve || !ext_client_cert_type || !ext_server_cert_type
1049         || !ext_ec_point_formats) {
1050       dtls_warn("not all required tls extensions found in client hello\n");
1051       goto error;
1052     }
1053   } else if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && !client_hello) {
1054     if (!ext_client_cert_type || !ext_server_cert_type) {
1055       dtls_warn("not all required tls extensions found in server hello\n");
1056       goto error;
1057     }
1058   }
1059   return 0;
1060
1061 error:
1062   if (client_hello && peer->state == DTLS_STATE_CONNECTED) {
1063     return dtls_alert_create(DTLS_ALERT_LEVEL_WARNING, DTLS_ALERT_NO_RENEGOTIATION);
1064   } else {
1065     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1066   }
1067 }
1068
1069 /**
1070  * Parses the ClientHello from the client and updates the internal handshake
1071  * parameters with the new data for the given \p peer. When the ClientHello
1072  * handshake message in \p data does not contain a cipher suite or
1073  * compression method, it is copied from the the current security parameters.
1074  *
1075  * \param ctx   The current DTLS context.
1076  * \param peer  The remote peer whose security parameters are about to change.
1077  * \param data  The handshake message with a ClientHello. 
1078  * \param data_length The actual size of \p data.
1079  * \return \c -Something if an error occurred, \c 0 on success.
1080  */
1081 static int
1082 dtls_update_parameters(dtls_context_t *ctx, 
1083                        dtls_peer_t *peer,
1084                        uint8 *data, size_t data_length) {
1085   int i, j;
1086   int ok;
1087   dtls_handshake_parameters_t *config = peer->handshake_params;
1088   dtls_security_parameters_t *security = dtls_security_params(peer);
1089
1090   assert(config);
1091   assert(data_length > DTLS_HS_LENGTH + DTLS_CH_LENGTH);
1092
1093   /* skip the handshake header and client version information */
1094   data += DTLS_HS_LENGTH + sizeof(uint16);
1095   data_length -= DTLS_HS_LENGTH + sizeof(uint16);
1096
1097   /* store client random in config */
1098   memcpy(config->tmp.random.client, data, DTLS_RANDOM_LENGTH);
1099   data += DTLS_RANDOM_LENGTH;
1100   data_length -= DTLS_RANDOM_LENGTH;
1101
1102   /* Caution: SKIP_VAR_FIELD may jump to error: */
1103   SKIP_VAR_FIELD(data, data_length, uint8);     /* skip session id */
1104   SKIP_VAR_FIELD(data, data_length, uint8);     /* skip cookie */
1105
1106   i = dtls_uint16_to_int(data);
1107   if (data_length < i + sizeof(uint16)) {
1108     /* Looks like we do not have a cipher nor compression. This is ok
1109      * for renegotiation, but not for the initial handshake. */
1110
1111     if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL)
1112       goto error;
1113
1114     config->cipher = security->cipher;
1115     config->compression = security->compression;
1116
1117     return 0;
1118   }
1119
1120   data += sizeof(uint16);
1121   data_length -= sizeof(uint16) + i;
1122
1123   ok = 0;
1124   while (i && !ok) {
1125     config->cipher = dtls_uint16_to_int(data);
1126     ok = known_cipher(ctx, config->cipher, 0);
1127     i -= sizeof(uint16);
1128     data += sizeof(uint16);
1129   }
1130
1131   /* skip remaining ciphers */
1132   data += i;
1133
1134   if (!ok) {
1135     /* reset config cipher to a well-defined value */
1136     config->cipher = TLS_NULL_WITH_NULL_NULL;
1137     dtls_warn("No matching cipher found\n");
1138     goto error;
1139   }
1140
1141   if (data_length < sizeof(uint8)) { 
1142     /* no compression specified, take the current compression method */
1143     if (security)
1144       config->compression = security->compression;
1145     else
1146       config->compression = TLS_COMPRESSION_NULL;
1147     return 0;
1148   }
1149
1150   i = dtls_uint8_to_int(data);
1151   if (data_length < i + sizeof(uint8))
1152     goto error;
1153
1154   data += sizeof(uint8);
1155   data_length -= sizeof(uint8) + i;
1156
1157   ok = 0;
1158   while (i && !ok) {
1159     for (j = 0; j < sizeof(compression_methods) / sizeof(uint8); ++j)
1160       if (dtls_uint8_to_int(data) == compression_methods[j]) {
1161         config->compression = compression_methods[j];
1162         ok = 1;
1163       }
1164     i -= sizeof(uint8);
1165     data += sizeof(uint8);    
1166   }
1167
1168   if (!ok) {
1169     /* reset config cipher to a well-defined value */
1170     goto error;
1171   }
1172   
1173   return dtls_check_tls_extension(peer, data, data_length, 1);
1174 error:
1175   if (peer->state == DTLS_STATE_CONNECTED) {
1176     return dtls_alert_create(DTLS_ALERT_LEVEL_WARNING, DTLS_ALERT_NO_RENEGOTIATION);
1177   } else {
1178     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1179   }
1180 }
1181
1182 /**
1183  * Parse the ClientKeyExchange and update the internal handshake state with
1184  * the new data.
1185  */
1186 static inline int
1187 check_client_keyexchange(dtls_context_t *ctx, 
1188                          dtls_handshake_parameters_t *handshake,
1189                          uint8 *data, size_t length) {
1190
1191 #if defined(DTLS_ECC) || defined(DTLS_X509)
1192   if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) ||
1193        is_tls_ecdh_anon_with_aes_128_cbc_sha_256(handshake->cipher) ) {
1194
1195     if (length < DTLS_HS_LENGTH + DTLS_CKXEC_LENGTH) {
1196       dtls_debug("The client key exchange is too short\n");
1197       return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1198     }
1199     data += DTLS_HS_LENGTH;
1200
1201     if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
1202       dtls_alert("expected 65 bytes long public point\n");
1203       return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1204     }
1205     data += sizeof(uint8);
1206
1207     if (dtls_uint8_to_int(data) != 4) {
1208       dtls_alert("expected uncompressed public point\n");
1209       return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1210     }
1211     data += sizeof(uint8);
1212
1213     memcpy(handshake->keyx.ecc.other_eph_pub_x, data,
1214            sizeof(handshake->keyx.ecc.other_eph_pub_x));
1215     data += sizeof(handshake->keyx.ecc.other_eph_pub_x);
1216
1217     memcpy(handshake->keyx.ecc.other_eph_pub_y, data,
1218            sizeof(handshake->keyx.ecc.other_eph_pub_y));
1219     data += sizeof(handshake->keyx.ecc.other_eph_pub_y);
1220   }
1221 #endif /* DTLS_ECC */
1222 #if defined(DTLS_PSK) && defined(DTLS_ECC)
1223   if (is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(handshake->cipher)) {
1224     int id_length;
1225
1226     if (length < DTLS_HS_LENGTH + DTLS_CKXEC_LENGTH) {
1227       dtls_debug("The client key exchange is too short\n");
1228       return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1229     }
1230     data += DTLS_HS_LENGTH;
1231
1232     //PSK hint
1233     id_length = dtls_uint16_to_int(data);
1234     data += sizeof(uint16);
1235
1236     if (DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN + DTLS_CKXEC_LENGTH + id_length != length) {
1237       dtls_debug("The identity has a wrong length\n");
1238       return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1239     }
1240
1241     if (id_length > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
1242       dtls_warn("please use a smaller client identity\n");
1243       return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1244     }
1245
1246     handshake->keyx.psk.id_length = id_length;
1247     memcpy(handshake->keyx.psk.identity, data, id_length);
1248     data += id_length;
1249
1250     //ECDH public
1251     if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
1252       dtls_alert("expected 65 bytes long public point\n");
1253       return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1254     }
1255     data += sizeof(uint8);
1256
1257     if (dtls_uint8_to_int(data) != 4) {
1258       dtls_alert("expected uncompressed public point\n");
1259       return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1260     }
1261     data += sizeof(uint8);
1262
1263     memcpy(handshake->keyx.ecc.other_eph_pub_x, data,
1264        sizeof(handshake->keyx.ecc.other_eph_pub_x));
1265     data += sizeof(handshake->keyx.ecc.other_eph_pub_x);
1266
1267     memcpy(handshake->keyx.ecc.other_eph_pub_y, data,
1268        sizeof(handshake->keyx.ecc.other_eph_pub_y));
1269     data += sizeof(handshake->keyx.ecc.other_eph_pub_y);
1270   }
1271 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
1272 #ifdef DTLS_PSK
1273   if (is_tls_psk_with_aes_128_ccm_8(handshake->cipher)) {
1274     int id_length;
1275
1276     if (length < DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN) {
1277       dtls_debug("The client key exchange is too short\n");
1278       return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1279     }
1280     data += DTLS_HS_LENGTH;
1281
1282     id_length = dtls_uint16_to_int(data);
1283     data += sizeof(uint16);
1284
1285     if (DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN + id_length != length) {
1286       dtls_debug("The identity has a wrong length\n");
1287       return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1288     }
1289
1290     if (id_length > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
1291       dtls_warn("please use a smaller client identity\n");
1292       return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1293     }
1294
1295     handshake->keyx.psk.id_length = id_length;
1296     memcpy(handshake->keyx.psk.identity, data, id_length);
1297   }
1298 #endif /* DTLS_PSK */
1299   return 0;
1300 }
1301
1302 static inline void
1303 update_hs_hash(dtls_peer_t *peer, uint8 *data, size_t length) {
1304   dtls_debug_dump("add MAC data", data, length);
1305   dtls_hash_update(&peer->handshake_params->hs_state.hs_hash, data, length);
1306 }
1307
1308 static void
1309 copy_hs_hash(dtls_peer_t *peer, dtls_hash_ctx *hs_hash) {
1310   memcpy(hs_hash, &peer->handshake_params->hs_state.hs_hash,
1311          sizeof(peer->handshake_params->hs_state.hs_hash));
1312 }
1313
1314 static inline size_t
1315 finalize_hs_hash(dtls_peer_t *peer, uint8 *buf) {
1316   return dtls_hash_finalize(buf, &peer->handshake_params->hs_state.hs_hash);
1317 }
1318
1319 static inline void
1320 clear_hs_hash(dtls_peer_t *peer) {
1321   assert(peer);
1322   dtls_debug("clear MAC\n");
1323   dtls_hash_init(&peer->handshake_params->hs_state.hs_hash);
1324 }
1325
1326 /** 
1327  * Checks if \p record + \p data contain a Finished message with valid
1328  * verify_data. 
1329  *
1330  * \param ctx    The current DTLS context.
1331  * \param peer   The remote peer of the security association.
1332  * \param data   The cleartext payload of the message.
1333  * \param data_length Actual length of \p data.
1334  * \return \c 0 if the Finished message is valid, \c negative number otherwise.
1335  */
1336 static int
1337 check_finished(dtls_context_t *ctx, dtls_peer_t *peer,
1338                uint8 *data, size_t data_length) {
1339   size_t digest_length, label_size;
1340   const unsigned char *label;
1341   unsigned char buf[DTLS_HMAC_MAX];
1342
1343   if (data_length < DTLS_HS_LENGTH + DTLS_FIN_LENGTH)
1344     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1345
1346   /* Use a union here to ensure that sufficient stack space is
1347    * reserved. As statebuf and verify_data are not used at the same
1348    * time, we can re-use the storage safely.
1349    */
1350   union {
1351     unsigned char statebuf[DTLS_HASH_CTX_SIZE];
1352     unsigned char verify_data[DTLS_FIN_LENGTH];
1353   } b;
1354
1355   /* temporarily store hash status for roll-back after finalize */
1356   memcpy(b.statebuf, &peer->handshake_params->hs_state.hs_hash, DTLS_HASH_CTX_SIZE);
1357
1358   digest_length = finalize_hs_hash(peer, buf);
1359   /* clear_hash(); */
1360
1361   /* restore hash status */
1362   memcpy(&peer->handshake_params->hs_state.hs_hash, b.statebuf, DTLS_HASH_CTX_SIZE);
1363
1364   if (peer->role == DTLS_CLIENT) {
1365     label = PRF_LABEL(server);
1366     label_size = PRF_LABEL_SIZE(server);
1367   } else { /* server */
1368     label = PRF_LABEL(client);
1369     label_size = PRF_LABEL_SIZE(client);
1370   }
1371
1372   dtls_prf(peer->handshake_params->tmp.master_secret,
1373            DTLS_MASTER_SECRET_LENGTH,
1374            label, label_size,
1375            PRF_LABEL(finished), PRF_LABEL_SIZE(finished),
1376            buf, digest_length,
1377            b.verify_data, sizeof(b.verify_data));
1378
1379   dtls_debug_dump("d:", data + DTLS_HS_LENGTH, sizeof(b.verify_data));
1380   dtls_debug_dump("v:", b.verify_data, sizeof(b.verify_data));
1381
1382   /* compare verify data and create DTLS alert code when they differ */
1383   return equals(data + DTLS_HS_LENGTH, b.verify_data, sizeof(b.verify_data))
1384     ? 0
1385     : dtls_alert_create(DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
1386 }
1387
1388 /**
1389  * Prepares the payload given in \p data for sending with
1390  * dtls_send(). The \p data is encrypted and compressed according to
1391  * the current security parameters of \p peer.  The result of this
1392  * operation is put into \p sendbuf with a prepended record header of
1393  * type \p type ready for sending. As some cipher suites add a MAC
1394  * before encryption, \p data must be large enough to hold this data
1395  * as well (usually \c dtls_kb_digest_size(CURRENT_CONFIG(peer)).
1396  *
1397  * \param peer    The remote peer the packet will be sent to.
1398  * \param security  The encryption paramater used to encrypt
1399  * \param type    The content type of this record.
1400  * \param data_array Array with payloads in correct order.
1401  * \param data_len_array sizes of the payloads in correct order.
1402  * \param data_array_len The number of payloads given.
1403  * \param sendbuf The output buffer where the encrypted record
1404  *                will be placed.
1405  * \param rlen    This parameter must be initialized with the 
1406  *                maximum size of \p sendbuf and will be updated
1407  *                to hold the actual size of the stored packet
1408  *                on success. On error, the value of \p rlen is
1409  *                undefined. 
1410  * \return Less than zero on error, or greater than zero success.
1411  */
1412 static int
1413 dtls_prepare_record(dtls_peer_t *peer, dtls_security_parameters_t *security,
1414                     unsigned char type,
1415                     uint8 *data_array[], size_t data_len_array[],
1416                     size_t data_array_len,
1417                     uint8 *sendbuf, size_t *rlen) {
1418   uint8 *p, *start;
1419   int res;
1420   unsigned int i;
1421   
1422   if (*rlen < DTLS_RH_LENGTH) {
1423     dtls_alert("The sendbuf (%zu bytes) is too small\n", *rlen);
1424     return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1425   }
1426
1427   p = dtls_set_record_header(type, security, sendbuf);
1428   start = p;
1429
1430   if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL) {
1431     /* no cipher suite */
1432
1433     res = 0;
1434     for (i = 0; i < data_array_len; i++) {
1435       /* check the minimum that we need for packets that are not encrypted */
1436       if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1437         dtls_debug("dtls_prepare_record: send buffer too small\n");
1438         return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1439       }
1440
1441       memcpy(p, data_array[i], data_len_array[i]);
1442       p += data_len_array[i];
1443       res += data_len_array[i];
1444     }
1445   } else if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(security->cipher) ||
1446              is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(security->cipher)) {
1447
1448     unsigned char nonce[DTLS_CBC_IV_LENGTH];
1449
1450     /** Add IV into body of packet in case of AES CBC mode according to RFC 5246, Section 6.2.3.2
1451      *
1452      *    opaque IV[SecurityParameters.record_iv_length];
1453      *    block-ciphered struct {
1454      *        opaque content[TLSCompressed.length];
1455      *        opaque MAC[SecurityParameters.mac_length];
1456      *        uint8 padding[GenericBlockCipher.padding_length];
1457      *        uint8 padding_length;
1458      * };
1459      *
1460      */
1461
1462     res = 0;
1463     dtls_prng(nonce, DTLS_CBC_IV_LENGTH);
1464     memcpy(p , nonce, DTLS_CBC_IV_LENGTH);
1465     p += DTLS_CBC_IV_LENGTH;
1466     res += DTLS_CBC_IV_LENGTH;
1467
1468     for (i = 0; i < data_array_len; i++) {
1469         /* check the minimum that we need for packets that are not encrypted */
1470         if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1471             dtls_debug("dtls_prepare_record: send buffer too small\n");
1472             return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1473         }
1474
1475         memcpy(p, data_array[i], data_len_array[i]);
1476         p += data_len_array[i];
1477         res += data_len_array[i];
1478      }
1479
1480      res = dtls_encrypt(start + DTLS_CBC_IV_LENGTH, res - DTLS_CBC_IV_LENGTH,
1481                start + DTLS_CBC_IV_LENGTH, nonce,
1482                dtls_kb_local_write_key(security, peer->role),
1483                dtls_kb_key_size(security, peer->role),
1484                dtls_kb_local_mac_secret(security, peer->role),
1485                dtls_kb_mac_secret_size(security->cipher),
1486                NULL, 0,
1487                security->cipher);
1488      if (res < 0)
1489        return res;
1490
1491      res += DTLS_CBC_IV_LENGTH;
1492
1493   } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */   
1494     /** 
1495      * length of additional_data for the AEAD cipher which consists of
1496      * seq_num(2+6) + type(1) + version(2) + length(2)
1497      */
1498 #define A_DATA_LEN 13
1499     unsigned char nonce[DTLS_CCM_BLOCKSIZE];
1500     unsigned char A_DATA[A_DATA_LEN];
1501
1502     if (is_tls_psk_with_aes_128_ccm_8(security->cipher)) {
1503       dtls_debug("dtls_prepare_record(): encrypt using TLS_PSK_WITH_AES_128_CCM_8\n");
1504     } else if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(security->cipher)) {
1505       dtls_debug("dtls_prepare_record(): encrypt using TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8\n");
1506     } else {
1507       dtls_debug("dtls_prepare_record(): encrypt using unknown cipher\n");
1508     }
1509
1510     /* set nonce       
1511        from RFC 6655:
1512         The "nonce" input to the AEAD algorithm is exactly that of [RFC5288]:
1513         the "nonce" SHALL be 12 bytes long and is constructed as follows:
1514         (this is an example of a "partially explicit" nonce; see Section
1515         3.2.1 in [RFC5116]).
1516
1517                        struct {
1518              opaque salt[4];
1519              opaque nonce_explicit[8];
1520                        } CCMNonce;
1521
1522          [...]
1523
1524          In DTLS, the 64-bit seq_num is the 16-bit epoch concatenated with the
1525          48-bit seq_num.
1526
1527          When the nonce_explicit is equal to the sequence number, the CCMNonce
1528          will have the structure of the CCMNonceExample given below.
1529
1530                     struct {
1531                      uint32 client_write_IV; // low order 32-bits
1532                      uint64 seq_num;         // TLS sequence number
1533                     } CCMClientNonce.
1534
1535
1536                     struct {
1537                      uint32 server_write_IV; // low order 32-bits
1538                      uint64 seq_num; // TLS sequence number
1539                     } CCMServerNonce.
1540
1541
1542                     struct {
1543                      case client:
1544                        CCMClientNonce;
1545                      case server:
1546                        CCMServerNonce:
1547                     } CCMNonceExample;
1548     */
1549
1550     memcpy(p, &DTLS_RECORD_HEADER(sendbuf)->epoch, 8);
1551     p += 8;
1552     res = 8;
1553
1554     for (i = 0; i < data_array_len; i++) {
1555       /* check the minimum that we need for packets that are not encrypted */
1556       if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1557         dtls_debug("dtls_prepare_record: send buffer too small\n");
1558         return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1559       }
1560
1561       memcpy(p, data_array[i], data_len_array[i]);
1562       p += data_len_array[i];
1563       res += data_len_array[i];
1564     }
1565
1566     memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
1567     memcpy(nonce, dtls_kb_local_iv(security, peer->role),
1568         dtls_kb_iv_size(security->cipher));
1569     memcpy(nonce + dtls_kb_iv_size(security->cipher), start, 8); /* epoch + seq_num */
1570
1571     dtls_debug_dump("nonce:", nonce, DTLS_CCM_BLOCKSIZE);
1572     dtls_debug_dump("key:", dtls_kb_local_write_key(security, peer->role),
1573                     dtls_kb_key_size(security, peer->role));
1574     
1575     /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
1576      * 
1577      * additional_data = seq_num + TLSCompressed.type +
1578      *                   TLSCompressed.version + TLSCompressed.length;
1579      */
1580     memcpy(A_DATA, &DTLS_RECORD_HEADER(sendbuf)->epoch, 8); /* epoch and seq_num */
1581     memcpy(A_DATA + 8,  &DTLS_RECORD_HEADER(sendbuf)->content_type, 3); /* type and version */
1582     dtls_int_to_uint16(A_DATA + 11, res - 8); /* length */
1583
1584     res = dtls_encrypt(start + 8, res - 8, start + 8, nonce,
1585                dtls_kb_local_write_key(security, peer->role),
1586                dtls_kb_key_size(security, peer->role),
1587                dtls_kb_local_mac_secret(security, peer->role),
1588                dtls_kb_mac_secret_size(security->cipher),
1589                A_DATA, A_DATA_LEN,
1590                security->cipher);
1591
1592     if (res < 0)
1593       return res;
1594
1595     res += 8; /* increment res by size of nonce_explicit */
1596     dtls_debug_dump("message:", start, res);
1597   }
1598
1599   /* fix length of fragment in sendbuf */
1600   dtls_int_to_uint16(sendbuf + 11, res);
1601   
1602   *rlen = DTLS_RH_LENGTH + res;
1603   return 0;
1604 }
1605
1606 static int
1607 dtls_send_handshake_msg_hash(dtls_context_t *ctx,
1608                              dtls_peer_t *peer,
1609                              session_t *session,
1610                              uint8 header_type,
1611                              uint8 *data, size_t data_length,
1612                              int add_hash)
1613 {
1614   uint8 buf[DTLS_HS_LENGTH];
1615   uint8 *data_array[2];
1616   size_t data_len_array[2];
1617   int i = 0;
1618   dtls_security_parameters_t *security = peer ? dtls_security_params(peer) : NULL;
1619
1620   dtls_set_handshake_header(header_type, peer, data_length, 0,
1621                             data_length, buf);
1622
1623   if (add_hash) {
1624     update_hs_hash(peer, buf, sizeof(buf));
1625   }
1626   data_array[i] = buf;
1627   data_len_array[i] = sizeof(buf);
1628   i++;
1629
1630   if (data != NULL) {
1631     if (add_hash) {
1632       update_hs_hash(peer, data, data_length);
1633     }
1634     data_array[i] = data;
1635     data_len_array[i] = data_length;
1636     i++;
1637   }
1638   dtls_debug("send handshake packet of type: %s (%i)\n",
1639              dtls_handshake_type_to_name(header_type), header_type);
1640   return dtls_send_multi(ctx, peer, security, session, DTLS_CT_HANDSHAKE,
1641                          data_array, data_len_array, i);
1642 }
1643
1644 static int
1645 dtls_send_handshake_msg(dtls_context_t *ctx,
1646                         dtls_peer_t *peer,
1647                         uint8 header_type,
1648                         uint8 *data, size_t data_length)
1649 {
1650   return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
1651                                       header_type, data, data_length, 1);
1652 }
1653
1654 /** 
1655  * Returns true if the message @p Data is a handshake message that
1656  * must be included in the calculation of verify_data in the Finished
1657  * message.
1658  * 
1659  * @param Type The message type. Only handshake messages but the initial 
1660  * Client Hello and Hello Verify Request are included in the hash,
1661  * @param Data The PDU to examine.
1662  * @param Length The length of @p Data.
1663  * 
1664  * @return @c 1 if @p Data must be included in hash, @c 0 otherwise.
1665  *
1666  * @hideinitializer
1667  */
1668 #define MUST_HASH(Type, Data, Length)                                   \
1669   ((Type) == DTLS_CT_HANDSHAKE &&                                       \
1670    ((Data) != NULL) && ((Length) > 0)  &&                               \
1671    ((Data)[0] != DTLS_HT_HELLO_VERIFY_REQUEST) &&                       \
1672    ((Data)[0] != DTLS_HT_CLIENT_HELLO ||                                \
1673     ((Length) >= HS_HDR_LENGTH &&                                       \
1674      (dtls_uint16_to_int(DTLS_RECORD_HEADER(Data)->epoch > 0) ||        \
1675       (dtls_uint16_to_int(HANDSHAKE(Data)->message_seq) > 0)))))
1676
1677 /**
1678  * Sends the data passed in @p buf as a DTLS record of type @p type to
1679  * the given peer. The data will be encrypted and compressed according
1680  * to the security parameters for @p peer.
1681  *
1682  * @param ctx    The DTLS context in effect.
1683  * @param peer   The remote party where the packet is sent.
1684  * @param type   The content type of this record.
1685  * @param buf    The data to send.
1686  * @param buflen The number of bytes to send from @p buf.
1687  * @return Less than zero in case of an error or the number of
1688  *   bytes that have been sent otherwise.
1689  */
1690 static int
1691 dtls_send_multi(dtls_context_t *ctx, dtls_peer_t *peer,
1692                 dtls_security_parameters_t *security , session_t *session,
1693                 unsigned char type, uint8 *buf_array[],
1694                 size_t buf_len_array[], size_t buf_array_len)
1695 {
1696   /* We cannot use ctx->sendbuf here as it is reserved for collecting
1697    * the input for this function, i.e. buf == ctx->sendbuf.
1698    *
1699    * TODO: check if we can use the receive buf here. This would mean
1700    * that we might not be able to handle multiple records stuffed in
1701    * one UDP datagram */
1702   unsigned char sendbuf[DTLS_MAX_BUF];
1703   size_t len = sizeof(sendbuf);
1704   int res;
1705   unsigned int i;
1706   size_t overall_len = 0;
1707
1708   res = dtls_prepare_record(peer, security, type, buf_array, buf_len_array, buf_array_len, sendbuf, &len);
1709
1710   if (res < 0)
1711     return res;
1712
1713   /* if (peer && MUST_HASH(peer, type, buf, buflen)) */
1714   /*   update_hs_hash(peer, buf, buflen); */
1715
1716   dtls_debug_hexdump("send header", sendbuf, sizeof(dtls_record_header_t));
1717   for (i = 0; i < buf_array_len; i++) {
1718     dtls_debug_hexdump("send unencrypted", buf_array[i], buf_len_array[i]);
1719     overall_len += buf_len_array[i];
1720   }
1721
1722   if ((type == DTLS_CT_HANDSHAKE && buf_array[0][0] != DTLS_HT_HELLO_VERIFY_REQUEST) ||
1723       type == DTLS_CT_CHANGE_CIPHER_SPEC) {
1724     /* copy handshake messages other than HelloVerify into retransmit buffer */
1725     netq_t *n = netq_node_new(overall_len);
1726     if (n) {
1727       dtls_tick_t now;
1728       dtls_ticks(&now);
1729       n->t = now + 2 * CLOCK_SECOND;
1730       n->retransmit_cnt = 0;
1731       n->timeout = 2 * CLOCK_SECOND;
1732       n->peer = peer;
1733       n->epoch = (security) ? security->epoch : 0;
1734       n->type = type;
1735       n->length = 0;
1736       for (i = 0; i < buf_array_len; i++) {
1737         memcpy(n->data + n->length, buf_array[i], buf_len_array[i]);
1738         n->length += buf_len_array[i];
1739       }
1740
1741       if (!netq_insert_node(ctx->sendqueue, n)) {
1742         dtls_warn("cannot add packet to retransmit buffer\n");
1743         netq_node_free(n);
1744 #ifdef WITH_CONTIKI
1745       } else {
1746         /* must set timer within the context of the retransmit process */
1747         PROCESS_CONTEXT_BEGIN(&dtls_retransmit_process);
1748         etimer_set(&ctx->retransmit_timer, n->timeout);
1749         PROCESS_CONTEXT_END(&dtls_retransmit_process);
1750 #else /* WITH_CONTIKI */
1751         dtls_debug("copied to sendqueue\n");
1752 #endif /* WITH_CONTIKI */
1753       }
1754     } else 
1755       dtls_warn("retransmit buffer full\n");
1756   }
1757
1758   /* FIXME: copy to peer's sendqueue (after fragmentation if
1759    * necessary) and initialize retransmit timer */
1760   res = CALL(ctx, write, session, sendbuf, len);
1761
1762   /* Guess number of bytes application data actually sent:
1763    * dtls_prepare_record() tells us in len the number of bytes to
1764    * send, res will contain the bytes actually sent. */
1765   return res <= 0 ? res : overall_len - (len - res);
1766 }
1767
1768 static inline int
1769 dtls_send_alert(dtls_context_t *ctx, dtls_peer_t *peer, dtls_alert_level_t level,
1770                 dtls_alert_t description) {
1771   uint8_t msg[] = { level, description };
1772
1773   dtls_send(ctx, peer, DTLS_CT_ALERT, msg, sizeof(msg));
1774   return 0;
1775 }
1776
1777 int 
1778 dtls_close(dtls_context_t *ctx, const session_t *remote) {
1779   int res = -1;
1780   dtls_peer_t *peer;
1781
1782   peer = dtls_get_peer(ctx, remote);
1783
1784   if (peer) {
1785     res = dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_CLOSE_NOTIFY);
1786     /* indicate tear down */
1787     peer->state = DTLS_STATE_CLOSING;
1788   }
1789   return res;
1790 }
1791
1792 static void dtls_destroy_peer(dtls_context_t *ctx, dtls_peer_t *peer, int unlink)
1793 {
1794   if (peer->state != DTLS_STATE_CLOSED && peer->state != DTLS_STATE_CLOSING)
1795     dtls_close(ctx, &peer->session);
1796   if (unlink) {
1797 #ifndef WITH_CONTIKI
1798     HASH_DEL_PEER(ctx->peers, peer);
1799 #else /* WITH_CONTIKI */
1800     list_remove(ctx->peers, peer);
1801 #endif /* WITH_CONTIKI */
1802
1803     dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "removed peer", &peer->session);
1804   }
1805   dtls_free_peer(peer);
1806 }
1807
1808 /**
1809  * Checks a received Client Hello message for a valid cookie. When the
1810  * Client Hello contains no cookie, the function fails and a Hello
1811  * Verify Request is sent to the peer (using the write callback function
1812  * registered with \p ctx). The return value is \c -1 on error, \c 0 when
1813  * undecided, and \c 1 if the Client Hello was good. 
1814  * 
1815  * \param ctx     The DTLS context.
1816  * \param peer    The remote party we are talking to, if any.
1817  * \param session Transport address of the remote peer.
1818  * \param state   Current state of the connection.
1819  * \param msg     The received datagram.
1820  * \param msglen  Length of \p msg.
1821  * \return \c 1 if msg is a Client Hello with a valid cookie, \c 0 or
1822  * \c -1 otherwise.
1823  */
1824 static int
1825 dtls_verify_peer(dtls_context_t *ctx, 
1826                  dtls_peer_t *peer, 
1827                  session_t *session,
1828                  const dtls_state_t state,
1829                  uint8 *data, size_t data_length)
1830 {
1831   uint8 buf[DTLS_HV_LENGTH + DTLS_COOKIE_LENGTH];
1832   uint8 *p = buf;
1833   int len = DTLS_COOKIE_LENGTH;
1834   uint8 *cookie = NULL;
1835   int err;
1836 #undef mycookie
1837 #define mycookie (buf + DTLS_HV_LENGTH)
1838
1839   /* Store cookie where we can reuse it for the HelloVerify request. */
1840   err = dtls_create_cookie(ctx, session, data, data_length, mycookie, &len);
1841   if (err < 0)
1842     return err;
1843
1844   dtls_debug_dump("create cookie", mycookie, len);
1845
1846   assert(len == DTLS_COOKIE_LENGTH);
1847     
1848   /* Perform cookie check. */
1849   len = dtls_get_cookie(data, data_length, &cookie);
1850   if (len < 0) {
1851     dtls_warn("error while fetching the cookie, err: %i\n", err);
1852     return err;
1853   }
1854
1855   dtls_debug_dump("compare with cookie", cookie, len);
1856
1857   /* check if cookies match */
1858   if (len == DTLS_COOKIE_LENGTH && memcmp(cookie, mycookie, len) == 0) {
1859     dtls_debug("found matching cookie\n");
1860     return 0;
1861   }
1862
1863   if (len > 0) {
1864     dtls_debug_dump("invalid cookie", cookie, len);
1865   } else {
1866     dtls_debug("cookie len is 0!\n");
1867   }
1868
1869   /* ClientHello did not contain any valid cookie, hence we send a
1870    * HelloVerify request. */
1871
1872   dtls_int_to_uint16(p, DTLS_VERSION);
1873   p += sizeof(uint16);
1874
1875   dtls_int_to_uint8(p, DTLS_COOKIE_LENGTH);
1876   p += sizeof(uint8);
1877
1878   assert(p == mycookie);
1879
1880   p += DTLS_COOKIE_LENGTH;
1881
1882   /* TODO use the same record sequence number as in the ClientHello,
1883      see 4.2.1. Denial-of-Service Countermeasures */
1884   err = dtls_send_handshake_msg_hash(ctx,
1885                      state == DTLS_STATE_CONNECTED ? peer : NULL,
1886                      session,
1887                      DTLS_HT_HELLO_VERIFY_REQUEST,
1888                      buf, p - buf, 0);
1889   if (err < 0) {
1890     dtls_warn("cannot send HelloVerify request\n");
1891   }
1892   return err; /* HelloVerify is sent, now we cannot do anything but wait */
1893
1894 #undef mycookie
1895 }
1896
1897 #if defined(DTLS_ECC) || defined(DTLS_X509)
1898 static int
1899 dtls_check_ecdsa_signature_elem(uint8 *data, size_t data_length,
1900                                 unsigned char **result_r,
1901                                 unsigned char **result_s)
1902 {
1903   int i;
1904   uint8 *data_orig = data;
1905
1906   if (dtls_uint8_to_int(data) != TLS_EXT_SIG_HASH_ALGO_SHA256) {
1907     dtls_alert("only sha256 is supported in certificate verify\n");
1908     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1909   }
1910   data += sizeof(uint8);
1911   data_length -= sizeof(uint8);
1912
1913   if (dtls_uint8_to_int(data) != TLS_EXT_SIG_HASH_ALGO_ECDSA) {
1914     dtls_alert("only ecdsa signature is supported in client verify\n");
1915     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1916   }
1917   data += sizeof(uint8);
1918   data_length -= sizeof(uint8);
1919
1920   if (data_length < dtls_uint16_to_int(data)) {
1921     dtls_alert("signature length wrong\n");
1922     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1923   }
1924   data += sizeof(uint16);
1925   data_length -= sizeof(uint16);
1926
1927   if (dtls_uint8_to_int(data) != 0x30) {
1928     dtls_alert("wrong ASN.1 struct, expected SEQUENCE\n");
1929     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1930   }
1931   data += sizeof(uint8);
1932   data_length -= sizeof(uint8);
1933
1934   if (data_length < dtls_uint8_to_int(data)) {
1935     dtls_alert("signature length wrong\n");
1936     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1937   }
1938   data += sizeof(uint8);
1939   data_length -= sizeof(uint8);
1940
1941   if (dtls_uint8_to_int(data) != 0x02) {
1942     dtls_alert("wrong ASN.1 struct, expected Integer\n");
1943     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1944   }
1945   data += sizeof(uint8);
1946   data_length -= sizeof(uint8);
1947
1948   i = dtls_uint8_to_int(data);
1949   data += sizeof(uint8);
1950   data_length -= sizeof(uint8);
1951
1952   /* Sometimes these values have a leeding 0 byte */
1953   *result_r = data + i - DTLS_EC_KEY_SIZE;
1954
1955   data += i;
1956   data_length -= i;
1957
1958   if (dtls_uint8_to_int(data) != 0x02) {
1959     dtls_alert("wrong ASN.1 struct, expected Integer\n");
1960     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1961   }
1962   data += sizeof(uint8);
1963   data_length -= sizeof(uint8);
1964
1965   i = dtls_uint8_to_int(data);
1966   data += sizeof(uint8);
1967   data_length -= sizeof(uint8);
1968
1969   /* Sometimes these values have a leeding 0 byte */
1970   *result_s = data + i - DTLS_EC_KEY_SIZE;
1971
1972   data += i;
1973   data_length -= i;
1974
1975   return data - data_orig;
1976 }
1977
1978 static int
1979 check_client_certificate_verify(dtls_context_t *ctx, 
1980                                 dtls_peer_t *peer,
1981                                 uint8 *data, size_t data_length)
1982 {
1983   dtls_handshake_parameters_t *config = peer->handshake_params;
1984   int ret;
1985   unsigned char *result_r;
1986   unsigned char *result_s;
1987   dtls_hash_ctx hs_hash;
1988   unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
1989
1990   assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
1991
1992   data += DTLS_HS_LENGTH;
1993
1994   if (data_length < DTLS_HS_LENGTH + DTLS_CV_LENGTH) {
1995     dtls_alert("the packet length does not match the expected\n");
1996     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1997   }
1998
1999   ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
2000   if (ret < 0) {
2001     return ret;
2002   }
2003   data += ret;
2004   data_length -= ret;
2005
2006   copy_hs_hash(peer, &hs_hash);
2007
2008   dtls_hash_finalize(sha256hash, &hs_hash);
2009
2010   ret = dtls_ecdsa_verify_sig_hash(config->keyx.ecc.other_pub_x, config->keyx.ecc.other_pub_y,
2011                                    sizeof(config->keyx.ecc.other_pub_x),
2012                                    sha256hash, sizeof(sha256hash),
2013                                    result_r, result_s);
2014
2015   if (ret <= 0) {
2016     dtls_alert("wrong signature err: %i\n", ret);
2017     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2018   }
2019   return 0;
2020 }
2021 #endif /* DTLS_ECC */
2022
2023 static int
2024 dtls_send_server_hello(dtls_context_t *ctx, dtls_peer_t *peer)
2025 {
2026   /* Ensure that the largest message to create fits in our source
2027    * buffer. (The size of the destination buffer is checked by the
2028    * encoding function, so we do not need to guess.) */
2029   uint8 buf[DTLS_SH_LENGTH + 2 + 5 + 5 + 8 + 6];
2030   uint8 *p;
2031   int ecdsa;
2032   uint8 extension_size;
2033   dtls_handshake_parameters_t *handshake = peer->handshake_params;
2034   dtls_tick_t now;
2035
2036   ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher);
2037
2038   extension_size = (ecdsa) ? 2 + 5 + 5 + 6 : 0;
2039
2040   /* Handshake header */
2041   p = buf;
2042
2043   /* ServerHello */
2044   dtls_int_to_uint16(p, DTLS_VERSION);
2045   p += sizeof(uint16);
2046
2047   /* Set server random: First 4 bytes are the server's Unix timestamp,
2048    * followed by 28 bytes of generate random data. */
2049   dtls_ticks(&now);
2050   dtls_int_to_uint32(handshake->tmp.random.server, now / CLOCK_SECOND);
2051   dtls_prng(handshake->tmp.random.server + 4, 28);
2052
2053   memcpy(p, handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
2054   p += DTLS_RANDOM_LENGTH;
2055
2056   *p++ = 0;                     /* no session id */
2057
2058   if (handshake->cipher != TLS_NULL_WITH_NULL_NULL) {
2059     /* selected cipher suite */
2060     dtls_int_to_uint16(p, handshake->cipher);
2061     p += sizeof(uint16);
2062
2063     /* selected compression method */
2064     *p++ = compression_methods[handshake->compression];
2065   }
2066
2067   if (extension_size) {
2068     /* length of the extensions */
2069     dtls_int_to_uint16(p, extension_size - 2);
2070     p += sizeof(uint16);
2071   }
2072
2073   if (ecdsa) {
2074     /* client certificate type extension */
2075     dtls_int_to_uint16(p, TLS_EXT_CLIENT_CERTIFICATE_TYPE);
2076     p += sizeof(uint16);
2077
2078     /* length of this extension type */
2079     dtls_int_to_uint16(p, 1);
2080     p += sizeof(uint16);
2081 #ifdef DTLS_X509
2082     if (CALL(ctx, is_x509_active) == 0)
2083       dtls_int_to_uint8(p, TLS_CERT_TYPE_X509);
2084     else
2085 #endif /* DTLS_X509 */
2086       dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2087
2088     p += sizeof(uint8);
2089
2090     /* client certificate type extension */
2091     dtls_int_to_uint16(p, TLS_EXT_SERVER_CERTIFICATE_TYPE);
2092     p += sizeof(uint16);
2093
2094     /* length of this extension type */
2095     dtls_int_to_uint16(p, 1);
2096     p += sizeof(uint16);
2097
2098 #ifdef DTLS_X509
2099     if (CALL(ctx, is_x509_active) == 0)
2100       dtls_int_to_uint8(p, TLS_CERT_TYPE_X509);
2101     else
2102 #endif /* DTLS_X509 */
2103       dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2104
2105     p += sizeof(uint8);
2106
2107     /* ec_point_formats */
2108     dtls_int_to_uint16(p, TLS_EXT_EC_POINT_FORMATS);
2109     p += sizeof(uint16);
2110
2111     /* length of this extension type */
2112     dtls_int_to_uint16(p, 2);
2113     p += sizeof(uint16);
2114
2115     /* number of supported formats */
2116     dtls_int_to_uint8(p, 1);
2117     p += sizeof(uint8);
2118
2119     dtls_int_to_uint8(p, TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED);
2120     p += sizeof(uint8);
2121   }
2122
2123   assert(p - buf <= sizeof(buf));
2124
2125   /* TODO use the same record sequence number as in the ClientHello,
2126      see 4.2.1. Denial-of-Service Countermeasures */
2127   return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_HELLO,
2128                                  buf, p - buf);
2129 }
2130
2131 #ifdef DTLS_ECC
2132 #define DTLS_EC_SUBJECTPUBLICKEY_SIZE (2 * DTLS_EC_KEY_SIZE + sizeof(cert_asn1_header))
2133
2134 static int
2135 dtls_send_certificate_ecdsa(dtls_context_t *ctx, dtls_peer_t *peer,
2136                             const dtls_ecc_key_t *key)
2137 {
2138   uint8 buf[DTLS_CE_LENGTH];
2139   uint8 *p;
2140
2141   /* Certificate
2142    *
2143    * Start message construction at beginning of buffer. */
2144   p = buf;
2145
2146   /* length of this certificate */
2147   dtls_int_to_uint24(p, DTLS_EC_SUBJECTPUBLICKEY_SIZE);
2148   p += sizeof(uint24);
2149
2150   memcpy(p, &cert_asn1_header, sizeof(cert_asn1_header));
2151   p += sizeof(cert_asn1_header);
2152
2153   memcpy(p, key->pub_key_x, DTLS_EC_KEY_SIZE);
2154   p += DTLS_EC_KEY_SIZE;
2155
2156   memcpy(p, key->pub_key_y, DTLS_EC_KEY_SIZE);
2157   p += DTLS_EC_KEY_SIZE;
2158
2159   assert(p - buf <= sizeof(buf));
2160
2161   return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE,
2162                                  buf, p - buf);
2163 }
2164 #endif /* DTLS_ECC */
2165
2166 #ifdef DTLS_X509
2167 static int
2168 dtls_send_certificate_x509(dtls_context_t *ctx, dtls_peer_t *peer)
2169 {
2170   uint8 buf[DTLS_MAX_CERT_SIZE];
2171   uint8 *p;
2172   int ret;
2173   unsigned char *cert;
2174   size_t cert_size;
2175
2176   dtls_info("\n dtls_send_certificate_ecdsa\n");
2177   ret = CALL(ctx, get_x509_cert, &peer->session,
2178           (const unsigned char **)&cert, &cert_size);
2179
2180   if (ret < 0) {
2181     dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2182     return ret;
2183   }
2184
2185   /* Certificate
2186    *
2187    * Start message construction at beginning of buffer. */
2188   p = buf;
2189
2190   dtls_int_to_uint24(p, cert_size); /* certificates length */
2191   p += sizeof(uint24);
2192
2193   memcpy(p, cert, cert_size);
2194   p += cert_size;
2195
2196   assert(p - buf <= sizeof(buf));
2197
2198   return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE,
2199                                  buf, p - buf);
2200 }
2201 #endif /* DTLS_X509 */
2202
2203 #if defined(DTLS_X509) || defined(DTLS_ECC)
2204 static uint8 *
2205 dtls_add_ecdsa_signature_elem(uint8 *p, uint32_t *point_r, uint32_t *point_s)
2206 {
2207   int len_r;
2208   int len_s;
2209
2210 #define R_KEY_OFFSET (1 + 1 + 2 + 1 + 1 + 1 + 1)
2211 #define S_KEY_OFFSET(len_s) (R_KEY_OFFSET + (len_s) + 1 + 1)
2212   /* store the pointer to the r component of the signature and make space */
2213   len_r = dtls_ec_key_from_uint32_asn1(point_r, DTLS_EC_KEY_SIZE, p + R_KEY_OFFSET);
2214   len_s = dtls_ec_key_from_uint32_asn1(point_s, DTLS_EC_KEY_SIZE, p + S_KEY_OFFSET(len_r));
2215
2216 #undef R_KEY_OFFSET
2217 #undef S_KEY_OFFSET
2218
2219   /* sha256 */
2220   dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_SHA256);
2221   p += sizeof(uint8);
2222
2223   /* ecdsa */
2224   dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_ECDSA);
2225   p += sizeof(uint8);
2226
2227   /* length of signature */
2228   dtls_int_to_uint16(p, len_r + len_s + 2 + 2 + 2);
2229   p += sizeof(uint16);
2230
2231   /* ASN.1 SEQUENCE */
2232   dtls_int_to_uint8(p, 0x30);
2233   p += sizeof(uint8);
2234
2235   dtls_int_to_uint8(p, len_r + len_s + 2 + 2);
2236   p += sizeof(uint8);
2237
2238   /* ASN.1 Integer r */
2239   dtls_int_to_uint8(p, 0x02);
2240   p += sizeof(uint8);
2241
2242   dtls_int_to_uint8(p, len_r);
2243   p += sizeof(uint8);
2244
2245   /* the pint r was added here */
2246   p += len_r;
2247
2248   /* ASN.1 Integer s */
2249   dtls_int_to_uint8(p, 0x02);
2250   p += sizeof(uint8);
2251
2252   dtls_int_to_uint8(p, len_s);
2253   p += sizeof(uint8);
2254
2255   /* the pint s was added here */
2256   p += len_s;
2257
2258   return p;
2259 }
2260
2261 static int
2262 dtls_send_server_key_exchange_ecdh(dtls_context_t *ctx, dtls_peer_t *peer,
2263                                    const dtls_ecc_key_t *key)
2264 {
2265   /* The ASN.1 Integer representation of an 32 byte unsigned int could be
2266    * 33 bytes long add space for that */
2267   uint8 buf[DTLS_SKEXEC_LENGTH + 2];
2268   uint8 *p;
2269   uint8 *key_params;
2270   uint8 *ephemeral_pub_x;
2271   uint8 *ephemeral_pub_y;
2272   uint32_t point_r[9];
2273   uint32_t point_s[9];
2274   int ecdsa;
2275   dtls_handshake_parameters_t *config = peer->handshake_params;
2276
2277   ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher);
2278   /* ServerKeyExchange
2279    *
2280    * Start message construction at beginning of buffer. */
2281   p = buf;
2282
2283   key_params = p;
2284   /* ECCurveType curve_type: named_curve */
2285   dtls_int_to_uint8(p, 3);
2286   p += sizeof(uint8);
2287
2288   /* NamedCurve namedcurve: secp256r1 */
2289   dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
2290   p += sizeof(uint16);
2291
2292   dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2293   p += sizeof(uint8);
2294
2295   /* This should be an uncompressed point, but I do not have access to the spec. */
2296   dtls_int_to_uint8(p, 4);
2297   p += sizeof(uint8);
2298
2299   /* store the pointer to the x component of the pub key and make space */
2300   ephemeral_pub_x = p;
2301   p += DTLS_EC_KEY_SIZE;
2302
2303   /* store the pointer to the y component of the pub key and make space */
2304   ephemeral_pub_y = p;
2305   p += DTLS_EC_KEY_SIZE;
2306
2307   dtls_ecdsa_generate_key(config->keyx.ecc.own_eph_priv,
2308               ephemeral_pub_x, ephemeral_pub_y,
2309               DTLS_EC_KEY_SIZE);
2310   if(ecdsa) {
2311       /* sign the ephemeral and its paramaters */
2312            dtls_ecdsa_create_sig(key->priv_key, DTLS_EC_KEY_SIZE,
2313                config->tmp.random.client, DTLS_RANDOM_LENGTH,
2314                config->tmp.random.server, DTLS_RANDOM_LENGTH,
2315                key_params, p - key_params,
2316                point_r, point_s);
2317
2318       p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
2319   }
2320
2321   assert(p - buf <= sizeof(buf));
2322
2323   return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
2324                                  buf, p - buf);
2325 }
2326 #endif /* defined(DTLS_X509) || defined(DTLS_ECC) */
2327
2328 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2329 static int dtls_send_server_key_exchange_ecdhe_psk(dtls_context_t *ctx, dtls_peer_t *peer,
2330                                   const unsigned char *psk_hint, size_t psk_hint_len)
2331 {
2332   /* The ASN.1 Integer representation of an 32 byte unsigned int could be
2333    * 33 bytes long add space for that */
2334   uint8 buf[DTLS_SKEXEC_LENGTH + DTLS_SKEXECPSK_LENGTH_MAX + 2];
2335   uint8 *p;
2336   uint8 *ephemeral_pub_x;
2337   uint8 *ephemeral_pub_y;
2338   dtls_handshake_parameters_t *config = peer->handshake_params;
2339
2340   /* ServerKeyExchange
2341     * Please see Session 2, RFC 5489.
2342
2343          struct {
2344           select (KeyExchangeAlgorithm) {
2345               //other cases for rsa, diffie_hellman, etc.
2346               case ec_diffie_hellman_psk:  // NEW
2347                   opaque psk_identity_hint<0..2^16-1>;
2348                   ServerECDHParams params;
2349           };
2350       } ServerKeyExchange; */
2351   p = buf;
2352
2353   assert(psk_hint_len <= DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2354   if (psk_hint_len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
2355     // should never happen
2356     dtls_warn("psk identity hint is too long\n");
2357     return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2358   }
2359
2360   // psk_identity_hint
2361   dtls_int_to_uint16(p, psk_hint_len);
2362   p += sizeof(uint16);
2363
2364   memcpy(p, psk_hint, psk_hint_len);
2365   p += psk_hint_len;
2366
2367   /* ServerECDHParams. */
2368   /* ECCurveType curve_type: named_curve */
2369   dtls_int_to_uint8(p, TLS_EC_CURVE_TYPE_NAMED_CURVE);
2370   p += sizeof(uint8);
2371
2372   /* NamedCurve namedcurve: secp256r1 */
2373   dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
2374   p += sizeof(uint16);
2375
2376   dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2377   p += sizeof(uint8);
2378
2379   /* This should be an uncompressed point, but I do not have access to the spec. */
2380   dtls_int_to_uint8(p, 4);
2381   p += sizeof(uint8);
2382
2383   /* store the pointer to the x component of the pub key and make space */
2384   ephemeral_pub_x = p;
2385   p += DTLS_EC_KEY_SIZE;
2386
2387   /* store the pointer to the y component of the pub key and make space */
2388   ephemeral_pub_y = p;
2389   p += DTLS_EC_KEY_SIZE;
2390
2391   dtls_ecdsa_generate_key(config->keyx.ecc.own_eph_priv,
2392               ephemeral_pub_x, ephemeral_pub_y,
2393               DTLS_EC_KEY_SIZE);
2394
2395   assert(p - buf <= sizeof(buf));
2396
2397   return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
2398                                  buf, p - buf);
2399 }
2400 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2401
2402 #ifdef DTLS_PSK
2403 static int
2404 dtls_send_server_key_exchange_psk(dtls_context_t *ctx, dtls_peer_t *peer,
2405                                   const unsigned char *psk_hint, size_t len)
2406 {
2407   uint8 buf[DTLS_SKEXECPSK_LENGTH_MAX];
2408   uint8 *p;
2409
2410   p = buf;
2411
2412   assert(len <= DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2413   if (len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
2414     /* should never happen */
2415     dtls_warn("psk identity hint is too long\n");
2416     return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2417   }
2418
2419   dtls_int_to_uint16(p, len);
2420   p += sizeof(uint16);
2421
2422   memcpy(p, psk_hint, len);
2423   p += len;
2424
2425   assert(p - buf <= sizeof(buf));
2426
2427   return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
2428                                  buf, p - buf);
2429 }
2430 #endif /* DTLS_PSK */
2431
2432 #if defined(DTLS_ECC) || defined(DTLS_X509)
2433 static int
2434 dtls_send_server_certificate_request(dtls_context_t *ctx, dtls_peer_t *peer)
2435 {
2436   uint8 buf[8];
2437   uint8 *p;
2438
2439   /* ServerHelloDone 
2440    *
2441    * Start message construction at beginning of buffer. */
2442   p = buf;
2443
2444   /* certificate_types */
2445   dtls_int_to_uint8(p, 1);
2446   p += sizeof(uint8);
2447
2448   /* ecdsa_sign */
2449   dtls_int_to_uint8(p, TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN);
2450   p += sizeof(uint8);
2451
2452   /* supported_signature_algorithms */
2453   dtls_int_to_uint16(p, 2);
2454   p += sizeof(uint16);
2455
2456   /* sha256 */
2457   dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_SHA256);
2458   p += sizeof(uint8);
2459
2460   /* ecdsa */
2461   dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_ECDSA);
2462   p += sizeof(uint8);
2463
2464   /* certificate_authoritiess */
2465   dtls_int_to_uint16(p, 0);
2466   p += sizeof(uint16);
2467
2468   assert(p - buf <= sizeof(buf));
2469
2470   return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE_REQUEST,
2471                                  buf, p - buf);
2472 }
2473 #endif /* DTLS_ECC */
2474
2475 static int
2476 dtls_send_server_hello_done(dtls_context_t *ctx, dtls_peer_t *peer)
2477 {
2478
2479   /* ServerHelloDone 
2480    *
2481    * Start message construction at beginning of buffer. */
2482
2483   return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_HELLO_DONE,
2484                                  NULL, 0);
2485 }
2486
2487 static int
2488 dtls_send_server_hello_msgs(dtls_context_t *ctx, dtls_peer_t *peer)
2489 {
2490   int res;
2491   int ecdsa;
2492   int ecdh_anon;
2493   int ecdhe_psk;
2494
2495   res = dtls_send_server_hello(ctx, peer);
2496
2497   if (res < 0) {
2498     dtls_debug("dtls_server_hello: cannot prepare ServerHello record\n");
2499     return res;
2500   }
2501
2502   ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher);
2503   ecdh_anon = is_tls_ecdh_anon_with_aes_128_cbc_sha_256(peer->handshake_params->cipher);
2504   ecdhe_psk = is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(peer->handshake_params->cipher);
2505
2506 #if defined(DTLS_ECC) || defined(DTLS_X509)
2507   if(ecdh_anon) {
2508       res = dtls_send_server_key_exchange_ecdh(ctx, peer, NULL);
2509
2510       if (res < 0) {
2511         dtls_debug("dtls_server_hello(with ECDH): cannot prepare Server Key Exchange record\n");
2512         return res;
2513       }
2514   }
2515   else if (ecdsa) {
2516     const dtls_ecc_key_t *ecdsa_key;
2517
2518 #ifdef DTLS_X509
2519     if (CALL(ctx, is_x509_active) == 0)
2520       res = CALL(ctx, get_x509_key, &peer->session, &ecdsa_key);
2521     else
2522 #endif /* DTLS_X509 */
2523       res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
2524
2525     if (res < 0) {
2526         dtls_debug("no ecdsa key to send\n");
2527       return res;
2528     }
2529
2530 #ifdef DTLS_X509
2531     if (CALL(ctx, is_x509_active) == 0)
2532       res = dtls_send_certificate_x509(ctx, peer);
2533     else
2534 #endif /* DTLS_X509 */
2535       res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
2536
2537     if (res < 0) {
2538       dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
2539       return res;
2540     }
2541
2542     res = dtls_send_server_key_exchange_ecdh(ctx, peer, ecdsa_key);
2543
2544     if (res < 0) {
2545       dtls_debug("dtls_server_hello: cannot prepare Server Key Exchange record\n");
2546       return res;
2547     }
2548
2549     if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
2550         (is_ecdsa_client_auth_supported(ctx) || (is_x509_client_auth_supported(ctx)))) {
2551       res = dtls_send_server_certificate_request(ctx, peer);
2552       if (res < 0) {
2553         dtls_debug("dtls_server_hello(with ECDSA): cannot prepare certificate Request record\n");
2554         return res;
2555       }
2556     }
2557   }
2558 #endif /* DTLS_ECC */
2559 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2560   else if(ecdhe_psk) {
2561     unsigned char psk_hint[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2562     int psk_len;
2563
2564     /* The identity hint is optional, therefore we ignore the result
2565      * and check psk only. */
2566     psk_len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_HINT,
2567                NULL, 0, psk_hint, DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2568
2569     if (psk_len < 0) {
2570       dtls_debug("dtls_server_hello: cannot create ServerKeyExchange\n");
2571       return psk_len;
2572     }
2573
2574     if (psk_len > 0) {
2575       res = dtls_send_server_key_exchange_ecdhe_psk(ctx, peer, psk_hint, (size_t)psk_len);
2576
2577       if (res < 0) {
2578         dtls_debug("dtls_server_hello(with ECDHE): cannot prepare Server Key Exchange record\n");
2579         return res;
2580       }
2581     }
2582   }
2583 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2584 #ifdef DTLS_PSK
2585   if (is_tls_psk_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
2586     unsigned char psk_hint[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2587     int len;
2588
2589     /* The identity hint is optional, therefore we ignore the result
2590      * and check psk only. */
2591     len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_HINT,
2592                NULL, 0, psk_hint, DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2593
2594     if (len < 0) {
2595       dtls_debug("dtls_server_hello: cannot create ServerKeyExchange\n");
2596       return len;
2597     }
2598
2599     if (len > 0) {
2600       res = dtls_send_server_key_exchange_psk(ctx, peer, psk_hint, (size_t)len);
2601
2602       if (res < 0) {
2603         dtls_debug("dtls_server_key_exchange_psk: cannot send server key exchange record\n");
2604         return res;
2605       }
2606     }
2607   }
2608 #endif /* DTLS_PSK */
2609
2610   res = dtls_send_server_hello_done(ctx, peer);
2611
2612   if (res < 0) {
2613     dtls_debug("dtls_server_hello: cannot prepare ServerHelloDone record\n");
2614     return res;
2615   }
2616   return 0;
2617 }
2618
2619 static inline int 
2620 dtls_send_ccs(dtls_context_t *ctx, dtls_peer_t *peer) {
2621   uint8 buf[1] = {1};
2622
2623   return dtls_send(ctx, peer, DTLS_CT_CHANGE_CIPHER_SPEC, buf, 1);
2624 }
2625
2626     
2627 static int
2628 dtls_send_client_key_exchange(dtls_context_t *ctx, dtls_peer_t *peer)
2629 {
2630 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2631   uint8 buf[DTLS_CKXEC_LENGTH + 2 + DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2632 #else
2633   uint8 buf[DTLS_CKXEC_LENGTH];
2634 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2635   uint8 client_id[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2636   uint8 *p;
2637   dtls_handshake_parameters_t *handshake = peer->handshake_params;
2638
2639   p = buf;
2640
2641   switch (handshake->cipher) {
2642 #ifdef DTLS_PSK
2643   case TLS_PSK_WITH_AES_128_CCM_8: {
2644     int len;
2645
2646     len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_IDENTITY,
2647                NULL, 0,
2648                client_id,
2649                sizeof(client_id));
2650     if (len < 0) {
2651       dtls_crit("no psk identity set in kx\n");
2652       return len;
2653     }
2654
2655     if (len + sizeof(uint16) > DTLS_CKXEC_LENGTH) {
2656       dtls_warn("the psk identity is too long\n");
2657       return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2658     }
2659
2660     dtls_int_to_uint16(p, len);
2661     p += sizeof(uint16);
2662
2663     memcpy(p, client_id, len);
2664     p += len;
2665
2666     break;
2667   }
2668 #endif /* DTLS_PSK */
2669 #if defined(DTLS_ECC) || defined(DTLS_X509)
2670   case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
2671   case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256: {
2672     uint8 *ephemeral_pub_x;
2673     uint8 *ephemeral_pub_y;
2674
2675     dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2676     p += sizeof(uint8);
2677
2678     /* This should be an uncompressed point, but I do not have access to the spec. */
2679     dtls_int_to_uint8(p, 4);
2680     p += sizeof(uint8);
2681
2682     ephemeral_pub_x = p;
2683     p += DTLS_EC_KEY_SIZE;
2684     ephemeral_pub_y = p;
2685     p += DTLS_EC_KEY_SIZE;
2686
2687     dtls_ecdsa_generate_key(peer->handshake_params->keyx.ecc.own_eph_priv,
2688                             ephemeral_pub_x, ephemeral_pub_y,
2689                             DTLS_EC_KEY_SIZE);
2690
2691     break;
2692   }
2693 #endif /* DTLS_ECC */
2694 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2695   case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256: {
2696       int psk_len;
2697       uint8 *ephemeral_pub_x;
2698       uint8 *ephemeral_pub_y;
2699
2700     /* Please see Session 2, RFC 5489.
2701          struct {
2702             select (KeyExchangeAlgorithm) {
2703                 // other cases for rsa, diffie_hellman, etc.
2704                 case ec_diffie_hellman_psk:
2705                     opaque psk_identity<0..2^16-1>;
2706                     ClientECDiffieHellmanPublic public;
2707             } exchange_keys;
2708         } ClientKeyExchange;
2709     */
2710
2711     psk_len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_IDENTITY,
2712                NULL, 0,
2713                client_id,
2714                sizeof(client_id));
2715     if (psk_len < 0) {
2716       dtls_crit("no psk identity set in kx\n");
2717       return psk_len;
2718     }
2719
2720     if (psk_len + sizeof(uint16) > DTLS_CKXEC_LENGTH) {
2721       dtls_warn("the psk identity is too long\n");
2722       return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2723     }
2724
2725     dtls_int_to_uint16(p, psk_len);
2726     p += sizeof(uint16);
2727
2728     memcpy(p, client_id, psk_len);
2729     p += psk_len;
2730
2731     dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2732     p += sizeof(uint8);
2733
2734     dtls_int_to_uint8(p, 4);
2735     p += sizeof(uint8);
2736
2737     ephemeral_pub_x = p;
2738     p += DTLS_EC_KEY_SIZE;
2739     ephemeral_pub_y = p;
2740     p += DTLS_EC_KEY_SIZE;
2741
2742     dtls_ecdsa_generate_key(peer->handshake_params->keyx.ecc.own_eph_priv,
2743                             ephemeral_pub_x, ephemeral_pub_y,
2744                             DTLS_EC_KEY_SIZE);
2745     break;
2746   }
2747 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2748   default:
2749     dtls_crit("cipher not supported\n");
2750     return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2751   }
2752
2753   assert(p - buf <= sizeof(buf));
2754
2755   return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CLIENT_KEY_EXCHANGE,
2756                                  buf, p - buf);
2757 }
2758
2759 #if defined(DTLS_ECC) || defined(DTLS_X509)
2760 static int
2761 dtls_send_certificate_verify_ecdh(dtls_context_t *ctx, dtls_peer_t *peer,
2762                                    const dtls_ecc_key_t *key)
2763 {
2764   /* The ASN.1 Integer representation of an 32 byte unsigned int could be
2765    * 33 bytes long add space for that */
2766   uint8 buf[DTLS_CV_LENGTH + 2];
2767   uint8 *p;
2768   uint32_t point_r[9];
2769   uint32_t point_s[9];
2770   dtls_hash_ctx hs_hash;
2771   unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
2772
2773   /* ServerKeyExchange 
2774    *
2775    * Start message construction at beginning of buffer. */
2776   p = buf;
2777
2778   copy_hs_hash(peer, &hs_hash);
2779
2780   dtls_hash_finalize(sha256hash, &hs_hash);
2781
2782   /* sign the ephemeral and its paramaters */
2783   dtls_ecdsa_create_sig_hash(key->priv_key, DTLS_EC_KEY_SIZE,
2784                              sha256hash, sizeof(sha256hash),
2785                              point_r, point_s);
2786
2787   p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
2788
2789   assert(p - buf <= sizeof(buf));
2790
2791   return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE_VERIFY,
2792                                  buf, p - buf);
2793 }
2794 #endif /* DTLS_ECC */
2795
2796 static int
2797 dtls_send_finished(dtls_context_t *ctx, dtls_peer_t *peer,
2798                    const unsigned char *label, size_t labellen)
2799 {
2800   int length;
2801   uint8 hash[DTLS_HMAC_MAX];
2802   uint8 buf[DTLS_FIN_LENGTH];
2803   dtls_hash_ctx hs_hash;
2804   uint8 *p = buf;
2805
2806   copy_hs_hash(peer, &hs_hash);
2807
2808   length = dtls_hash_finalize(hash, &hs_hash);
2809
2810   dtls_prf(peer->handshake_params->tmp.master_secret,
2811            DTLS_MASTER_SECRET_LENGTH,
2812            label, labellen,
2813            PRF_LABEL(finished), PRF_LABEL_SIZE(finished), 
2814            hash, length,
2815            p, DTLS_FIN_LENGTH);
2816
2817   dtls_debug_dump("server finished MAC", p, DTLS_FIN_LENGTH);
2818
2819   p += DTLS_FIN_LENGTH;
2820
2821   assert(p - buf <= sizeof(buf));
2822
2823   return dtls_send_handshake_msg(ctx, peer, DTLS_HT_FINISHED,
2824                                  buf, p - buf);
2825 }
2826
2827 static int
2828 dtls_send_client_hello(dtls_context_t *ctx, dtls_peer_t *peer,
2829                        uint8 cookie[], size_t cookie_length) {
2830   uint8 buf[DTLS_CH_LENGTH_MAX];
2831   uint8 *p = buf;
2832   uint8_t cipher_size = 0;
2833   uint8_t extension_size = 0;
2834   int psk = 0;
2835   int ecdsa = 0;
2836   int ecdh_anon = 0;
2837   int ecdhe_psk = 0;
2838   int x509 = 0;
2839   dtls_handshake_parameters_t *handshake = peer->handshake_params;
2840   dtls_tick_t now;
2841
2842   switch(ctx->selected_cipher)
2843   {
2844       case TLS_PSK_WITH_AES_128_CCM_8:
2845         psk = is_psk_supported(ctx);
2846         break;
2847       case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
2848         ecdsa = is_ecdsa_supported(ctx, 1);
2849         x509 = is_x509_supported(ctx, 1);
2850         break;
2851       case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256:
2852         ecdh_anon = is_ecdh_anon_supported(ctx);
2853         break;
2854       case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256:
2855         ecdhe_psk = is_ecdhe_psk_supported(ctx);
2856         break;
2857       default:
2858         psk = is_psk_supported(ctx);
2859         ecdsa = is_ecdsa_supported(ctx, 1);
2860         ecdh_anon = is_ecdh_anon_supported(ctx);
2861         ecdhe_psk = is_ecdhe_psk_supported(ctx);
2862         x509 = is_x509_supported(ctx, 1);
2863         break;
2864    }
2865
2866   cipher_size = 2 + ((ecdsa || x509) ? 2 : 0) + (psk ? 2 : 0) + (ecdh_anon ? 2 : 0) + (ecdhe_psk ? 2 : 0);
2867
2868   /* Is extension needed? */
2869   extension_size = (ecdsa || x509 || ecdhe_psk || ecdh_anon) ? 2 : 0;
2870   /* Supported EC and Supported Point Formats */
2871   extension_size += (ecdsa || x509 || ecdhe_psk | ecdh_anon) ? ( 8 + 6) : 0;
2872   /* Supported Client and Server Cert Types */
2873   extension_size += (ecdsa || x509) ? ( 6 + 6) : 0;
2874
2875   if (cipher_size == 0) {
2876     dtls_crit("no cipher callbacks implemented\n");
2877   }
2878
2879   dtls_int_to_uint16(p, DTLS_VERSION);
2880   p += sizeof(uint16);
2881
2882   if (cookie_length > DTLS_COOKIE_LENGTH_MAX) {
2883     dtls_warn("the cookie is too long\n");
2884     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2885   }
2886
2887   if (cookie_length == 0) {
2888     /* Set client random: First 4 bytes are the client's Unix timestamp,
2889      * followed by 28 bytes of generate random data. */
2890     dtls_ticks(&now);
2891     dtls_int_to_uint32(handshake->tmp.random.client, now / CLOCK_SECOND);
2892     dtls_prng(handshake->tmp.random.client + sizeof(uint32),
2893          DTLS_RANDOM_LENGTH - sizeof(uint32));
2894   }
2895   /* we must use the same Client Random as for the previous request */
2896   memcpy(p, handshake->tmp.random.client, DTLS_RANDOM_LENGTH);
2897   p += DTLS_RANDOM_LENGTH;
2898
2899   /* session id (length 0) */
2900   dtls_int_to_uint8(p, 0);
2901   p += sizeof(uint8);
2902
2903   /* cookie */
2904   dtls_int_to_uint8(p, cookie_length);
2905   p += sizeof(uint8);
2906   if (cookie_length != 0) {
2907     memcpy(p, cookie, cookie_length);
2908     p += cookie_length;
2909   }
2910
2911   /* add known cipher(s) */
2912   dtls_int_to_uint16(p, cipher_size - 2);
2913   p += sizeof(uint16);
2914
2915   if (ecdh_anon) {
2916     dtls_int_to_uint16(p, TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256);
2917     p += sizeof(uint16);
2918   }
2919   if (psk) {
2920     dtls_int_to_uint16(p, TLS_PSK_WITH_AES_128_CCM_8);
2921     p += sizeof(uint16);
2922   }
2923   if (ecdsa || x509) {
2924     dtls_int_to_uint16(p, TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
2925     p += sizeof(uint16);
2926   }
2927   if (ecdhe_psk) {
2928       dtls_int_to_uint16(p, TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);
2929       p += sizeof(uint16);
2930   }
2931
2932   /* compression method */
2933   dtls_int_to_uint8(p, 1);
2934   p += sizeof(uint8);
2935
2936   dtls_int_to_uint8(p, TLS_COMPRESSION_NULL);
2937   p += sizeof(uint8);
2938
2939   if (extension_size) {
2940     /* length of the extensions */
2941     dtls_int_to_uint16(p, extension_size - 2);
2942     p += sizeof(uint16);
2943   }
2944
2945   if (ecdsa || x509) {
2946     /* client certificate type extension */
2947     dtls_int_to_uint16(p, TLS_EXT_CLIENT_CERTIFICATE_TYPE);
2948     p += sizeof(uint16);
2949
2950     /* length of this extension type */
2951     dtls_int_to_uint16(p, 2);
2952     p += sizeof(uint16);
2953
2954     /* length of the list */
2955     dtls_int_to_uint8(p, 1);
2956     p += sizeof(uint8);
2957
2958 #ifdef DTLS_X509
2959     if (CALL(ctx, is_x509_active) == 0)
2960       dtls_int_to_uint8(p, TLS_CERT_TYPE_X509);
2961     else
2962 #endif /* DTLS_X509 */
2963       dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2964
2965     p += sizeof(uint8);
2966
2967     /* server certificate type extension */
2968     dtls_int_to_uint16(p, TLS_EXT_SERVER_CERTIFICATE_TYPE);
2969     p += sizeof(uint16);
2970
2971     /* length of this extension type */
2972     dtls_int_to_uint16(p, 2);
2973     p += sizeof(uint16);
2974
2975     /* length of the list */
2976     dtls_int_to_uint8(p, 1);
2977     p += sizeof(uint8);
2978
2979 #ifdef DTLS_X509
2980     if (CALL(ctx, is_x509_active) == 0)
2981       dtls_int_to_uint8(p, TLS_CERT_TYPE_X509);
2982     else
2983 #endif /* DTLS_X509 */
2984       dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2985
2986     p += sizeof(uint8);
2987   }
2988
2989   if (ecdsa || x509 || ecdhe_psk || ecdh_anon ) {
2990     /* elliptic_curves */
2991     dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES);
2992     p += sizeof(uint16);
2993
2994     /* length of this extension type */
2995     dtls_int_to_uint16(p, 4);
2996     p += sizeof(uint16);
2997
2998     /* length of the list */
2999     dtls_int_to_uint16(p, 2);
3000     p += sizeof(uint16);
3001
3002     dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
3003     p += sizeof(uint16);
3004
3005     /* ec_point_formats */
3006     dtls_int_to_uint16(p, TLS_EXT_EC_POINT_FORMATS);
3007     p += sizeof(uint16);
3008
3009     /* length of this extension type */
3010     dtls_int_to_uint16(p, 2);
3011     p += sizeof(uint16);
3012
3013     /* number of supported formats */
3014     dtls_int_to_uint8(p, 1);
3015     p += sizeof(uint8);
3016
3017     dtls_int_to_uint8(p, TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED);
3018     p += sizeof(uint8);
3019   }
3020
3021   assert(p - buf <= sizeof(buf));
3022
3023   if (cookie_length != 0)
3024     clear_hs_hash(peer);
3025
3026   return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
3027                                       DTLS_HT_CLIENT_HELLO,
3028                                       buf, p - buf, cookie_length != 0);
3029 }
3030
3031 static int
3032 check_server_hello(dtls_context_t *ctx, 
3033                       dtls_peer_t *peer,
3034                       uint8 *data, size_t data_length)
3035 {
3036   dtls_handshake_parameters_t *handshake = peer->handshake_params;
3037
3038   /* This function is called when we expect a ServerHello (i.e. we
3039    * have sent a ClientHello).  We might instead receive a HelloVerify
3040    * request containing a cookie. If so, we must repeat the
3041    * ClientHello with the given Cookie.
3042    */
3043   if (data_length < DTLS_HS_LENGTH + DTLS_HS_LENGTH)
3044     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3045
3046   update_hs_hash(peer, data, data_length);
3047
3048   /* FIXME: check data_length before accessing fields */
3049
3050   /* Get the server's random data and store selected cipher suite
3051    * and compression method (like dtls_update_parameters().
3052    * Then calculate master secret and wait for ServerHelloDone. When received,
3053    * send ClientKeyExchange (?) and ChangeCipherSpec + ClientFinished. */
3054     
3055   /* check server version */
3056   data += DTLS_HS_LENGTH;
3057   data_length -= DTLS_HS_LENGTH;
3058     
3059   if (dtls_uint16_to_int(data) != DTLS_VERSION) {
3060     dtls_alert("unknown DTLS version\n");
3061     return dtls_alert_fatal_create(DTLS_ALERT_PROTOCOL_VERSION);
3062   }
3063
3064   data += sizeof(uint16);             /* skip version field */
3065   data_length -= sizeof(uint16);
3066
3067   /* store server random data */
3068   memcpy(handshake->tmp.random.server, data, DTLS_RANDOM_LENGTH);
3069   /* skip server random */
3070   data += DTLS_RANDOM_LENGTH;
3071   data_length -= DTLS_RANDOM_LENGTH;
3072
3073   SKIP_VAR_FIELD(data, data_length, uint8); /* skip session id */
3074     
3075   /* Check cipher suite. As we offer all we have, it is sufficient
3076    * to check if the cipher suite selected by the server is in our
3077    * list of known cipher suites. Subsets are not supported. */
3078   handshake->cipher = dtls_uint16_to_int(data);
3079   if (!known_cipher(ctx, handshake->cipher, 1)) {
3080     dtls_alert("unsupported cipher 0x%02x 0x%02x\n",
3081              data[0], data[1]);
3082     return dtls_alert_fatal_create(DTLS_ALERT_INSUFFICIENT_SECURITY);
3083   }
3084   data += sizeof(uint16);
3085   data_length -= sizeof(uint16);
3086
3087   /* Check if NULL compression was selected. We do not know any other. */
3088   if (dtls_uint8_to_int(data) != TLS_COMPRESSION_NULL) {
3089     dtls_alert("unsupported compression method 0x%02x\n", data[0]);
3090     return dtls_alert_fatal_create(DTLS_ALERT_INSUFFICIENT_SECURITY);
3091   }
3092   data += sizeof(uint8);
3093   data_length -= sizeof(uint8);
3094
3095   return dtls_check_tls_extension(peer, data, data_length, 0);
3096
3097 error:
3098   return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3099 }
3100
3101 static int
3102 check_server_hello_verify_request(dtls_context_t *ctx,
3103                                   dtls_peer_t *peer,
3104                                   uint8 *data, size_t data_length)
3105 {
3106   dtls_hello_verify_t *hv;
3107   int res;
3108
3109   if (data_length < DTLS_HS_LENGTH + DTLS_HV_LENGTH)
3110     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3111
3112   hv = (dtls_hello_verify_t *)(data + DTLS_HS_LENGTH);
3113
3114   res = dtls_send_client_hello(ctx, peer, hv->cookie, hv->cookie_length);
3115
3116   if (res < 0)
3117     dtls_warn("cannot send ClientHello\n");
3118
3119   return res;
3120 }
3121
3122 #ifdef DTLS_ECC
3123
3124 static int
3125 check_peer_certificate(dtls_context_t *ctx,
3126                          dtls_peer_t *peer,
3127                          uint8 *data, size_t data_length)
3128 {
3129   int err;
3130   dtls_handshake_parameters_t *config = peer->handshake_params;
3131
3132   update_hs_hash(peer, data, data_length);
3133
3134   assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
3135
3136   data += DTLS_HS_LENGTH;
3137
3138   if (dtls_uint24_to_int(data) != DTLS_EC_SUBJECTPUBLICKEY_SIZE) {
3139     dtls_alert("expect length of %d bytes for certificate\n",
3140                DTLS_EC_SUBJECTPUBLICKEY_SIZE);
3141     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3142   }
3143   data += sizeof(uint24);
3144
3145   if (memcmp(data, cert_asn1_header, sizeof(cert_asn1_header))) {
3146     dtls_alert("got an unexpected Subject public key format\n");
3147     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3148   }
3149   data += sizeof(cert_asn1_header);
3150
3151   memcpy(config->keyx.ecc.other_pub_x, data,
3152          sizeof(config->keyx.ecc.other_pub_x));
3153   data += sizeof(config->keyx.ecc.other_pub_x);
3154
3155   memcpy(config->keyx.ecc.other_pub_y, data,
3156          sizeof(config->keyx.ecc.other_pub_y));
3157   data += sizeof(config->keyx.ecc.other_pub_y);
3158
3159   err = CALL(ctx, verify_ecdsa_key, &peer->session,
3160              config->keyx.ecc.other_pub_x,
3161              config->keyx.ecc.other_pub_y,
3162              sizeof(config->keyx.ecc.other_pub_x));
3163   if (err < 0) {
3164     dtls_warn("The certificate was not accepted\n");
3165     return err;
3166   }
3167
3168   return 0;
3169 }
3170 #endif /* DTLS_ECC */
3171
3172 #ifdef DTLS_X509
3173 static int
3174 check_peer_certificate_x509(dtls_context_t *ctx,
3175                          dtls_peer_t *peer,
3176                          uint8 *data, size_t data_length)
3177 {
3178   int ret;
3179   dtls_handshake_parameters_t *config = peer->handshake_params;
3180   int cert_length;
3181
3182   dtls_info("\n check_peer_certificate_x509\n");
3183   update_hs_hash(peer, data, data_length);
3184
3185   assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
3186
3187   data += DTLS_HS_LENGTH;
3188
3189   cert_length = dtls_uint24_to_int(data);
3190   data += sizeof(uint24);
3191
3192   ret = CALL(ctx, verify_x509_cert, &peer->session, data, cert_length,
3193           config->keyx.ecc.other_pub_x, sizeof(config->keyx.ecc.other_pub_x),
3194           config->keyx.ecc.other_pub_y, sizeof(config->keyx.ecc.other_pub_y));
3195   if (ret < 0) {
3196     dtls_warn("The certificate was not accepted\n");
3197     return ret;
3198   }
3199
3200   return 0;
3201 }
3202 #endif /* DTLS_X509 */
3203
3204 #if defined(DTLS_X509) || defined(DTLS_ECC)
3205 static int
3206 check_server_key_exchange_ecdsa(dtls_context_t *ctx,
3207                                 dtls_peer_t *peer,
3208                                 uint8 *data, size_t data_length)
3209 {
3210   dtls_handshake_parameters_t *config = peer->handshake_params;
3211   int ret;
3212   unsigned char *result_r;
3213   unsigned char *result_s;
3214   unsigned char *key_params;
3215
3216   update_hs_hash(peer, data, data_length);
3217
3218   assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
3219
3220   data += DTLS_HS_LENGTH;
3221
3222   if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_LENGTH) {
3223     dtls_alert("the packet length does not match the expected\n");
3224     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3225   }
3226   key_params = data;
3227
3228   if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
3229     dtls_alert("Only named curves supported\n");
3230     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3231   }
3232   data += sizeof(uint8);
3233   data_length -= sizeof(uint8);
3234
3235   if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
3236     dtls_alert("secp256r1 supported\n");
3237     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3238   }
3239   data += sizeof(uint16);
3240   data_length -= sizeof(uint16);
3241
3242   if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
3243     dtls_alert("expected 65 bytes long public point\n");
3244     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3245   }
3246   data += sizeof(uint8);
3247   data_length -= sizeof(uint8);
3248
3249   if (dtls_uint8_to_int(data) != 4) {
3250     dtls_alert("expected uncompressed public point\n");
3251     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3252   }
3253   data += sizeof(uint8);
3254   data_length -= sizeof(uint8);
3255
3256   memcpy(config->keyx.ecc.other_eph_pub_x, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3257   data += sizeof(config->keyx.ecc.other_eph_pub_y);
3258   data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3259
3260   memcpy(config->keyx.ecc.other_eph_pub_y, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3261   data += sizeof(config->keyx.ecc.other_eph_pub_y);
3262   data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3263
3264   ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
3265   if (ret < 0) {
3266     return ret;
3267   }
3268   data += ret;
3269   data_length -= ret;
3270
3271   ret = dtls_ecdsa_verify_sig(config->keyx.ecc.other_pub_x, config->keyx.ecc.other_pub_y,
3272                               sizeof(config->keyx.ecc.other_pub_x),
3273                               config->tmp.random.client, DTLS_RANDOM_LENGTH,
3274                               config->tmp.random.server, DTLS_RANDOM_LENGTH,
3275                               key_params,
3276                               1 + 2 + 1 + 1 + (2 * DTLS_EC_KEY_SIZE),
3277                               result_r, result_s);
3278
3279   if (ret <= 0) {
3280     dtls_alert("wrong signature\n");
3281     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3282   }
3283   return 0;
3284 }
3285
3286 static int
3287 check_server_key_exchange_ecdh(dtls_context_t *ctx,
3288                                 dtls_peer_t *peer,
3289                                 uint8 *data, size_t data_length)
3290 {
3291   dtls_handshake_parameters_t *config = peer->handshake_params;
3292
3293   update_hs_hash(peer, data, data_length);
3294
3295   assert(is_tls_ecdh_anon_with_aes_128_cbc_sha_256(config->cipher));
3296
3297   data += DTLS_HS_LENGTH;
3298
3299   if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_ECDH_ANON_LENGTH) {
3300     dtls_alert("the packet length does not match the expected\n");
3301     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3302   }
3303
3304   if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
3305     dtls_alert("Only named curves supported\n");
3306     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3307   }
3308   data += sizeof(uint8);
3309   data_length -= sizeof(uint8);
3310
3311   if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
3312     dtls_alert("secp256r1 supported\n");
3313     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3314   }
3315   data += sizeof(uint16);
3316   data_length -= sizeof(uint16);
3317
3318   if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
3319     dtls_alert("expected 65 bytes long public point\n");
3320     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3321   }
3322   data += sizeof(uint8);
3323   data_length -= sizeof(uint8);
3324
3325   if (dtls_uint8_to_int(data) != 4) {
3326     dtls_alert("expected uncompressed public point\n");
3327     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3328   }
3329   data += sizeof(uint8);
3330   data_length -= sizeof(uint8);
3331
3332   memcpy(config->keyx.ecc.other_eph_pub_x, data, sizeof(config->keyx.ecc.other_eph_pub_x));
3333   data += sizeof(config->keyx.ecc.other_eph_pub_x);
3334   data_length -= sizeof(config->keyx.ecc.other_eph_pub_x);
3335
3336   memcpy(config->keyx.ecc.other_eph_pub_y, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3337   data += sizeof(config->keyx.ecc.other_eph_pub_y);
3338   data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3339
3340   return 0;
3341 }
3342 #endif /* DTLS_ECC */
3343 #if defined(DTLS_PSK) && defined(DTLS_ECC)
3344 check_server_key_exchange_ecdhe_psk(dtls_context_t *ctx,
3345                               dtls_peer_t *peer,
3346                               uint8 *data, size_t data_length)
3347 {
3348   dtls_handshake_parameters_t *config = peer->handshake_params;
3349   uint16_t psk_len = 0;
3350
3351   /* ServerKeyExchange
3352     * Please see Session 2, RFC 5489.
3353
3354          struct {
3355           select (KeyExchangeAlgorithm) {
3356               //other cases for rsa, diffie_hellman, etc.
3357               case ec_diffie_hellman_psk:  // NEW
3358                   opaque psk_identity_hint<0..2^16-1>;
3359                   ServerECDHParams params;
3360           };
3361       } ServerKeyExchange; */
3362
3363   update_hs_hash(peer, data, data_length);
3364
3365   assert(is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(config->cipher));
3366
3367   data += DTLS_HS_LENGTH;
3368
3369   psk_len = dtls_uint16_to_int(data);
3370   data += sizeof(uint16);
3371
3372   if (psk_len != data_length - DTLS_HS_LENGTH - DTLS_SKEXEC_ECDH_ANON_LENGTH - sizeof(uint16)) {
3373     dtls_warn("the length of the server identity hint is worng\n");
3374     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3375   }
3376
3377   if (psk_len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
3378     dtls_warn("please use a smaller server identity hint\n");
3379     return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3380   }
3381
3382   // store the psk_identity_hint in config->keyx.psk for later use
3383   config->keyx.psk.id_length = psk_len;
3384   memcpy(config->keyx.psk.identity, data, psk_len);
3385
3386   data += psk_len;
3387   data_length -= psk_len;
3388
3389   if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_ECDH_ANON_LENGTH) {
3390     dtls_alert("the packet length does not match the expected\n");
3391     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3392   }
3393
3394   if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
3395     dtls_alert("Only named curves supported\n");
3396     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3397   }
3398   data += sizeof(uint8);
3399   data_length -= sizeof(uint8);
3400
3401   if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
3402     dtls_alert("secp256r1 supported\n");
3403     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3404   }
3405   data += sizeof(uint16);
3406   data_length -= sizeof(uint16);
3407
3408   if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
3409     dtls_alert("expected 65 bytes long public point\n");
3410     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3411   }
3412   data += sizeof(uint8);
3413   data_length -= sizeof(uint8);
3414
3415   if (dtls_uint8_to_int(data) != 4) {
3416     dtls_alert("expected uncompressed public point\n");
3417     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3418   }
3419   data += sizeof(uint8);
3420   data_length -= sizeof(uint8);
3421
3422   memcpy(config->keyx.ecc.other_eph_pub_x, data, sizeof(config->keyx.ecc.other_eph_pub_x));
3423   data += sizeof(config->keyx.ecc.other_eph_pub_x);
3424   data_length -= sizeof(config->keyx.ecc.other_eph_pub_x);
3425
3426   memcpy(config->keyx.ecc.other_eph_pub_y, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3427   data += sizeof(config->keyx.ecc.other_eph_pub_y);
3428   data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3429
3430   return 0;
3431 }
3432 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
3433
3434 #ifdef DTLS_PSK
3435 static int
3436 check_server_key_exchange_psk(dtls_context_t *ctx,
3437                               dtls_peer_t *peer,
3438                               uint8 *data, size_t data_length)
3439 {
3440   dtls_handshake_parameters_t *config = peer->handshake_params;
3441   uint16_t len;
3442
3443   update_hs_hash(peer, data, data_length);
3444
3445   assert(is_tls_psk_with_aes_128_ccm_8(config->cipher));
3446
3447   data += DTLS_HS_LENGTH;
3448
3449   if (data_length < DTLS_HS_LENGTH + DTLS_SKEXECPSK_LENGTH_MIN) {
3450     dtls_alert("the packet length does not match the expected\n");
3451     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3452   }
3453
3454   len = dtls_uint16_to_int(data);
3455   data += sizeof(uint16);
3456
3457   if (len != data_length - DTLS_HS_LENGTH - sizeof(uint16)) {
3458     dtls_warn("the length of the server identity hint is worng\n");
3459     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3460   }
3461
3462   if (len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
3463     dtls_warn("please use a smaller server identity hint\n");
3464     return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3465   }
3466
3467   /* store the psk_identity_hint in config->keyx.psk for later use */
3468   config->keyx.psk.id_length = len;
3469   memcpy(config->keyx.psk.identity, data, len);
3470   return 0;
3471 }
3472 #endif /* DTLS_PSK */
3473
3474 static int
3475 check_certificate_request(dtls_context_t *ctx, 
3476                           dtls_peer_t *peer,
3477                           uint8 *data, size_t data_length)
3478 {
3479   unsigned int i;
3480   int auth_alg;
3481   int sig_alg;
3482   int hash_alg;
3483
3484   update_hs_hash(peer, data, data_length);
3485
3486   assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher));
3487
3488   data += DTLS_HS_LENGTH;
3489
3490   if (data_length < DTLS_HS_LENGTH + 5) {
3491     dtls_alert("the packet length does not match the expected\n");
3492     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3493   }
3494
3495   i = dtls_uint8_to_int(data);
3496   data += sizeof(uint8);
3497   if (i + 1 > data_length) {
3498     dtls_alert("the cerfificate types are too long\n");
3499     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3500   }
3501
3502   auth_alg = 0;
3503   for (; i > 0 ; i -= sizeof(uint8)) {
3504     if (dtls_uint8_to_int(data) == TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN
3505         && auth_alg == 0)
3506       auth_alg = dtls_uint8_to_int(data);
3507     data += sizeof(uint8);
3508   }
3509
3510   if (auth_alg != TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN) {
3511     dtls_alert("the request authentication algorithm is not supproted\n");
3512     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3513   }
3514
3515   i = dtls_uint16_to_int(data);
3516   data += sizeof(uint16);
3517   if (i + 1 > data_length) {
3518     dtls_alert("the signature and hash algorithm list is too long\n");
3519     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3520   }
3521
3522   hash_alg = 0;
3523   sig_alg = 0;
3524   for (; i > 0 ; i -= sizeof(uint16)) {
3525     int current_hash_alg;
3526     int current_sig_alg;
3527
3528     current_hash_alg = dtls_uint8_to_int(data);
3529     data += sizeof(uint8);
3530     current_sig_alg = dtls_uint8_to_int(data);
3531     data += sizeof(uint8);
3532
3533     if (current_hash_alg == TLS_EXT_SIG_HASH_ALGO_SHA256 && hash_alg == 0 && 
3534         current_sig_alg == TLS_EXT_SIG_HASH_ALGO_ECDSA && sig_alg == 0) {
3535       hash_alg = current_hash_alg;
3536       sig_alg = current_sig_alg;
3537     }
3538   }
3539
3540   if (hash_alg != TLS_EXT_SIG_HASH_ALGO_SHA256 ||
3541       sig_alg != TLS_EXT_SIG_HASH_ALGO_ECDSA) {
3542     dtls_alert("no supported hash and signature algorithem\n");
3543     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3544   }
3545
3546   /* common names are ignored */
3547
3548   peer->handshake_params->do_client_auth = 1;
3549   return 0;
3550 }
3551
3552 static int
3553 check_server_hellodone(dtls_context_t *ctx,
3554                       dtls_peer_t *peer,
3555                       uint8 *data, size_t data_length)
3556 {
3557   int res = 0;
3558 #ifdef DTLS_ECC
3559   const dtls_ecc_key_t *ecdsa_key;
3560 #ifdef DTLS_X509
3561   unsigned char *cert;
3562   size_t cert_size;
3563 #endif /* DTLS_X509 */
3564 #endif /* DTLS_ECC */
3565
3566   dtls_handshake_parameters_t *handshake = peer->handshake_params;
3567
3568   /* calculate master key, send CCS */
3569
3570   update_hs_hash(peer, data, data_length);
3571
3572 #if defined(DTLS_ECC) || defined(DTLS_X509)
3573   if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && handshake->do_client_auth) {
3574 #ifdef DTLS_X509
3575     if (CALL(ctx, is_x509_active) == 0)
3576       res = CALL(ctx, get_x509_key, &peer->session, &ecdsa_key);
3577     else
3578 #endif /* DTLS_X509 */
3579       res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
3580     if (res < 0) {
3581       dtls_crit("no ecdsa key to use\n");
3582       return res;
3583     }
3584
3585 #ifdef DTLS_X509
3586     if (CALL(ctx, is_x509_active) == 0)
3587       res = dtls_send_certificate_x509(ctx, peer);
3588     else
3589 #endif /* DTLS_X509 */
3590       res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
3591
3592     if (res < 0) {
3593       dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
3594       return res;
3595     }
3596   }
3597 #endif /* DTLS_ECC */
3598
3599   /* send ClientKeyExchange */
3600   res = dtls_send_client_key_exchange(ctx, peer);
3601
3602   if (res < 0) {
3603     dtls_debug("cannot send KeyExchange message\n");
3604     return res;
3605   }
3606
3607 #ifdef DTLS_ECC
3608   if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && handshake->do_client_auth) {
3609     res = dtls_send_certificate_verify_ecdh(ctx, peer, ecdsa_key);
3610
3611     if (res < 0) {
3612       dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
3613       return res;
3614     }
3615   }
3616 #endif /* DTLS_ECC */
3617
3618   res = calculate_key_block(ctx, handshake, peer,
3619                             &peer->session, peer->role);
3620   if (res < 0) {
3621     return res;
3622   }
3623
3624   res = dtls_send_ccs(ctx, peer);
3625   if (res < 0) {
3626     dtls_debug("cannot send CCS message\n");
3627     return res;
3628   }
3629
3630   /* and switch cipher suite */
3631   dtls_security_params_switch(peer);
3632
3633   /* Client Finished */
3634   return dtls_send_finished(ctx, peer, PRF_LABEL(client), PRF_LABEL_SIZE(client));
3635 }
3636
3637 static int
3638 decrypt_verify(dtls_peer_t *peer, uint8 *packet, size_t length,
3639                uint8 **cleartext)
3640 {
3641   dtls_record_header_t *header = DTLS_RECORD_HEADER(packet);
3642   dtls_security_parameters_t *security = dtls_security_params_epoch(peer, dtls_get_epoch(header));
3643   int clen;
3644   
3645   *cleartext = (uint8 *)packet + sizeof(dtls_record_header_t);
3646   clen = length - sizeof(dtls_record_header_t);
3647
3648   if (!security) {
3649     dtls_alert("No security context for epoch: %i\n", dtls_get_epoch(header));
3650     return -1;
3651   }
3652
3653   if (security->cipher == TLS_NULL_WITH_NULL_NULL) {
3654     /* no cipher suite selected */
3655     return clen;
3656   } else if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(security->cipher) ||
3657              is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(security->cipher)) {
3658
3659     unsigned char nonce[DTLS_CBC_IV_LENGTH];
3660
3661     if (clen < (DTLS_CBC_IV_LENGTH + DTLS_HMAC_DIGEST_SIZE))            /* need at least IV and MAC */
3662       return -1;
3663
3664     memcpy(nonce, *cleartext , DTLS_CBC_IV_LENGTH);
3665     clen -= DTLS_CBC_IV_LENGTH;
3666     *cleartext += DTLS_CBC_IV_LENGTH ;
3667
3668     clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
3669                        dtls_kb_remote_write_key(security, peer->role),
3670                        dtls_kb_key_size(security, peer->role),
3671                        dtls_kb_remote_mac_secret(security, peer->role),
3672                        dtls_kb_mac_secret_size(security->cipher),
3673                        NULL, 0,
3674                        security->cipher);
3675
3676   } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
3677     /** 
3678      * length of additional_data for the AEAD cipher which consists of
3679      * seq_num(2+6) + type(1) + version(2) + length(2)
3680      */
3681 #define A_DATA_LEN 13
3682     unsigned char nonce[DTLS_CCM_BLOCKSIZE];
3683     unsigned char A_DATA[A_DATA_LEN];
3684
3685     if (clen < 16)              /* need at least IV and MAC */
3686       return -1;
3687
3688     memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
3689     memcpy(nonce, dtls_kb_remote_iv(security, peer->role),
3690         dtls_kb_iv_size(security->cipher));
3691
3692     /* read epoch and seq_num from message */
3693     memcpy(nonce + dtls_kb_iv_size(security->cipher), *cleartext, 8);
3694     *cleartext += 8;
3695     clen -= 8;
3696
3697     dtls_debug_dump("nonce", nonce, DTLS_CCM_BLOCKSIZE);
3698     dtls_debug_dump("key", dtls_kb_remote_write_key(security, peer->role),
3699                     dtls_kb_key_size(security, peer->role));
3700     dtls_debug_dump("ciphertext", *cleartext, clen);
3701
3702     /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
3703      * 
3704      * additional_data = seq_num + TLSCompressed.type +
3705      *                   TLSCompressed.version + TLSCompressed.length;
3706      */
3707     memcpy(A_DATA, &DTLS_RECORD_HEADER(packet)->epoch, 8); /* epoch and seq_num */
3708     memcpy(A_DATA + 8,  &DTLS_RECORD_HEADER(packet)->content_type, 3); /* type and version */
3709     dtls_int_to_uint16(A_DATA + 11, clen - 8); /* length without nonce_explicit */
3710
3711     clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
3712                        dtls_kb_remote_write_key(security, peer->role),
3713                        dtls_kb_key_size(security, peer->role),
3714                        dtls_kb_remote_mac_secret(security, peer->role),
3715                        dtls_kb_mac_secret_size(security->cipher),
3716                        A_DATA, A_DATA_LEN,
3717                        security->cipher);
3718   }
3719
3720   if (clen < 0)
3721     dtls_warn("decryption failed\n");
3722   else {
3723 #ifndef NDEBUG
3724     dtls_debug("decrypt_verify(): found %i bytes cleartext\n", clen);
3725 #endif
3726     dtls_security_params_free_other(peer);
3727     dtls_debug_dump("cleartext", *cleartext, clen);
3728   }
3729
3730   return clen;
3731 }
3732
3733 static int
3734 dtls_send_hello_request(dtls_context_t *ctx, dtls_peer_t *peer)
3735 {
3736   return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
3737                                       DTLS_HT_HELLO_REQUEST,
3738                                       NULL, 0, 0);
3739 }
3740
3741 int
3742 dtls_renegotiate(dtls_context_t *ctx, const session_t *dst)
3743 {
3744   dtls_peer_t *peer = NULL;
3745   int err;
3746
3747   peer = dtls_get_peer(ctx, dst);
3748
3749   if (!peer) {
3750     return -1;
3751   }
3752   if (peer->state != DTLS_STATE_CONNECTED)
3753     return -1;
3754
3755   peer->handshake_params = dtls_handshake_new();
3756   if (!peer->handshake_params)
3757     return -1;
3758
3759   peer->handshake_params->hs_state.mseq_r = 0;
3760   peer->handshake_params->hs_state.mseq_s = 0;
3761
3762   if (peer->role == DTLS_CLIENT) {
3763     /* send ClientHello with empty Cookie */
3764     err = dtls_send_client_hello(ctx, peer, NULL, 0);
3765     if (err < 0)
3766       dtls_warn("cannot send ClientHello\n");
3767     else
3768       peer->state = DTLS_STATE_CLIENTHELLO;
3769     return err;
3770   } else if (peer->role == DTLS_SERVER) {
3771     return dtls_send_hello_request(ctx, peer);
3772   }
3773
3774   return -1;
3775 }
3776
3777 static int
3778 handle_handshake_msg(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
3779                  const dtls_peer_type role, const dtls_state_t state,
3780                  uint8 *data, size_t data_length) {
3781
3782   int err = 0;
3783
3784   /* This will clear the retransmission buffer if we get an expected
3785    * handshake message. We have to make sure that no handshake message
3786    * should get expected when we still should retransmit something, when
3787    * we do everything accordingly to the DTLS 1.2 standard this should
3788    * not be a problem. */
3789   if (peer) {
3790     dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
3791     if (state == DTLS_STATE_WAIT_CHANGECIPHERSPEC && hs_header->msg_type ==  DTLS_HT_FINISHED) {
3792       return 0;
3793     }
3794     dtls_clear_retransmission(ctx, peer);
3795   }
3796
3797   /* The following switch construct handles the given message with
3798    * respect to the current internal state for this peer. In case of
3799    * error, it is left with return 0. */
3800
3801   dtls_debug("handle handshake packet of type: %s (%i)\n",
3802              dtls_handshake_type_to_name(data[0]), data[0]);
3803   switch (data[0]) {
3804
3805   /************************************************************************
3806    * Client states
3807    ************************************************************************/
3808   case DTLS_HT_HELLO_VERIFY_REQUEST:
3809
3810     if (state != DTLS_STATE_CLIENTHELLO) {
3811       return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3812     }
3813
3814     err = check_server_hello_verify_request(ctx, peer, data, data_length);
3815     if (err < 0) {
3816       dtls_warn("error in check_server_hello_verify_request err: %i\n", err);
3817       return err;
3818     }
3819
3820     break;
3821   case DTLS_HT_SERVER_HELLO:
3822
3823     if (state != DTLS_STATE_CLIENTHELLO) {
3824       return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3825     }
3826
3827     err = check_server_hello(ctx, peer, data, data_length);
3828     if (err < 0) {
3829       dtls_warn("error in check_server_hello err: %i\n", err);
3830       return err;
3831     }
3832     if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher))
3833       peer->state = DTLS_STATE_WAIT_SERVERCERTIFICATE; //ecdsa
3834     else if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(peer->handshake_params->cipher) ||
3835         is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(peer->handshake_params->cipher))
3836         peer->state = DTLS_STATE_WAIT_SERVERKEYEXCHANGE; //ecdh
3837     else
3838       peer->state = DTLS_STATE_WAIT_SERVERHELLODONE; //psk
3839     /* update_hs_hash(peer, data, data_length); */
3840
3841     break;
3842
3843 #if defined(DTLS_ECC) || defined(DTLS_X509)
3844   case DTLS_HT_CERTIFICATE:
3845
3846     if ((role == DTLS_CLIENT && state != DTLS_STATE_WAIT_SERVERCERTIFICATE) ||
3847         (role == DTLS_SERVER && state != DTLS_STATE_WAIT_CLIENTCERTIFICATE)) {
3848       return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3849     }
3850 #ifdef DTLS_X509
3851     if (CALL(ctx, is_x509_active) == 0)
3852       err = check_peer_certificate_x509(ctx, peer, data, data_length);
3853     else
3854 #endif /* DTLS_X509 */
3855       err = check_peer_certificate(ctx, peer, data, data_length);
3856     if (err < 0) {
3857       dtls_warn("error in check_peer_certificate err: %i\n", err);
3858       return err;
3859     }
3860     if (role == DTLS_CLIENT) {
3861       peer->state = DTLS_STATE_WAIT_SERVERKEYEXCHANGE;
3862     } else if (role == DTLS_SERVER){
3863       peer->state = DTLS_STATE_WAIT_CLIENTKEYEXCHANGE;
3864     }
3865     /* update_hs_hash(peer, data, data_length); */
3866
3867     break;
3868 #endif /* DTLS_ECC */
3869
3870   case DTLS_HT_SERVER_KEY_EXCHANGE:
3871
3872 #if defined(DTLS_ECC) || defined(DTLS_X509)
3873     if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
3874       if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3875         return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3876       }
3877       err = check_server_key_exchange_ecdsa(ctx, peer, data, data_length);
3878     }
3879
3880     if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(peer->handshake_params->cipher)) {
3881       if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3882         return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3883       }
3884       err = check_server_key_exchange_ecdh(ctx, peer, data, data_length);
3885     }
3886 #endif /* DTLS_ECC */
3887
3888 #if defined(DTLS_PSK) && defined(DTLS_ECC)
3889     if (is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(peer->handshake_params->cipher)) {
3890         if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3891           return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3892         }
3893       err = check_server_key_exchange_ecdhe_psk(ctx, peer, data, data_length);
3894     }
3895 #endif defined(DTLS_PSK) && defined(DTLS_ECC)
3896
3897 #ifdef DTLS_PSK
3898     if (is_tls_psk_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
3899       if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3900         return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3901       }
3902       err = check_server_key_exchange_psk(ctx, peer, data, data_length);
3903     }
3904 #endif /* DTLS_PSK */
3905
3906     if (err < 0) {
3907       dtls_warn("error in check_server_key_exchange err: %i\n", err);
3908       return err;
3909     }
3910     peer->state = DTLS_STATE_WAIT_SERVERHELLODONE;
3911     /* update_hs_hash(peer, data, data_length); */
3912
3913     break;
3914
3915   case DTLS_HT_SERVER_HELLO_DONE:
3916
3917     if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3918       return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3919     }
3920
3921     err = check_server_hellodone(ctx, peer, data, data_length);
3922     if (err < 0) {
3923       dtls_warn("error in check_server_hellodone err: %i\n", err);
3924       return err;
3925     }
3926     peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
3927     /* update_hs_hash(peer, data, data_length); */
3928
3929     break;
3930
3931   case DTLS_HT_CERTIFICATE_REQUEST:
3932
3933     if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3934       return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3935     }
3936
3937     err = check_certificate_request(ctx, peer, data, data_length);
3938     if (err < 0) {
3939       dtls_warn("error in check_certificate_request err: %i\n", err);
3940       return err;
3941     }
3942
3943     break;
3944
3945   case DTLS_HT_FINISHED:
3946     /* expect a Finished message from server */
3947
3948     if (state != DTLS_STATE_WAIT_FINISHED) {
3949       return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3950     }
3951
3952     err = check_finished(ctx, peer, data, data_length);
3953     if (err < 0) {
3954       dtls_warn("error in check_finished err: %i\n", err);
3955       return err;
3956     }
3957     if (role == DTLS_SERVER) {
3958       /* send ServerFinished */
3959       update_hs_hash(peer, data, data_length);
3960
3961       /* send change cipher spec message and switch to new configuration */
3962       err = dtls_send_ccs(ctx, peer);
3963       if (err < 0) {
3964         dtls_warn("cannot send CCS message\n");
3965         return err;
3966       }
3967
3968       dtls_security_params_switch(peer);
3969
3970       err = dtls_send_finished(ctx, peer, PRF_LABEL(server), PRF_LABEL_SIZE(server));
3971       if (err < 0) {
3972         dtls_warn("sending server Finished failed\n");
3973         return err;
3974       }
3975     }
3976     dtls_handshake_free(peer->handshake_params);
3977     peer->handshake_params = NULL;
3978     dtls_debug("Handshake complete\n");
3979     check_stack();
3980     peer->state = DTLS_STATE_CONNECTED;
3981
3982     /* return here to not increase the message receive counter */
3983     return err;
3984
3985   /************************************************************************
3986    * Server states
3987    ************************************************************************/
3988
3989   case DTLS_HT_CLIENT_KEY_EXCHANGE:
3990     /* handle ClientHello, update msg and msglen and goto next if not finished */
3991
3992     if (state != DTLS_STATE_WAIT_CLIENTKEYEXCHANGE) {
3993       return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3994     }
3995
3996     err = check_client_keyexchange(ctx, peer->handshake_params, data, data_length);
3997     if (err < 0) {
3998       dtls_warn("error in check_client_keyexchange err: %i\n", err);
3999       return err;
4000     }
4001     update_hs_hash(peer, data, data_length);
4002
4003     if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
4004             (is_ecdsa_client_auth_supported(ctx) || (is_x509_client_auth_supported(ctx))))
4005       peer->state = DTLS_STATE_WAIT_CERTIFICATEVERIFY; //ecdsa
4006     else
4007       peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC; //psk || ecdh_anon
4008     break;
4009
4010 #if defined(DTLS_ECC) || defined(DTLS_X509)
4011   case DTLS_HT_CERTIFICATE_VERIFY:
4012
4013     if (state != DTLS_STATE_WAIT_CERTIFICATEVERIFY) {
4014       return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
4015     }
4016
4017     err = check_client_certificate_verify(ctx, peer, data, data_length);
4018     if (err < 0) {
4019       dtls_warn("error in check_client_certificate_verify err: %i\n", err);
4020       return err;
4021     }
4022
4023     update_hs_hash(peer, data, data_length);
4024     peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
4025     break;
4026 #endif /* DTLS_ECC */
4027
4028   case DTLS_HT_CLIENT_HELLO:
4029
4030     if ((peer && state != DTLS_STATE_CONNECTED && state != DTLS_STATE_WAIT_CLIENTHELLO) ||
4031         (!peer && state != DTLS_STATE_WAIT_CLIENTHELLO)) {
4032       return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
4033     }
4034
4035     /* When no DTLS state exists for this peer, we only allow a
4036        Client Hello message with
4037
4038        a) a valid cookie, or
4039        b) no cookie.
4040
4041        Anything else will be rejected. Fragementation is not allowed
4042        here as it would require peer state as well.
4043     */
4044     err = dtls_verify_peer(ctx, peer, session, state, data, data_length);
4045     if (err < 0) {
4046       dtls_warn("error in dtls_verify_peer err: %i\n", err);
4047       return err;
4048     }
4049
4050     if (err > 0) {
4051       dtls_debug("server hello verify was sent\n");
4052       break;
4053     }
4054
4055     /* At this point, we have a good relationship with this peer. This
4056      * state is left for re-negotiation of key material. */
4057      /* As per RFC 6347 - section 4.2.8 if this is an attempt to
4058       * rehandshake, we can delete the existing key material
4059       * as the client has demonstrated reachibility by completing
4060       * the cookie exchange */
4061     if (peer && state == DTLS_STATE_WAIT_CLIENTHELLO) {
4062        dtls_debug("removing the peer\n");
4063 #ifndef WITH_CONTIKI
4064        HASH_DEL_PEER(ctx->peers, peer);
4065 #else  /* WITH_CONTIKI */
4066        list_remove(ctx->peers, peer);
4067 #endif /* WITH_CONTIKI */
4068
4069        dtls_free_peer(peer);
4070        peer = NULL;
4071     }
4072     if (!peer) {
4073       dtls_debug("creating new peer\n");
4074       dtls_security_parameters_t *security;
4075
4076       /* msg contains a Client Hello with a valid cookie, so we can
4077        * safely create the server state machine and continue with
4078        * the handshake. */
4079       peer = dtls_new_peer(session);
4080       if (!peer) {
4081         dtls_alert("cannot create peer\n");
4082         return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
4083       }
4084       peer->role = DTLS_SERVER;
4085
4086       /* Initialize record sequence number to 1 for new peers. The first
4087        * record with sequence number 0 is a stateless Hello Verify Request.
4088        */
4089       security = dtls_security_params(peer);
4090       security->rseq = 1;
4091       dtls_add_peer(ctx, peer);
4092     }
4093     if (peer && !peer->handshake_params) {
4094       dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
4095
4096       peer->handshake_params = dtls_handshake_new();
4097       if (!peer->handshake_params)
4098         return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
4099
4100       LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
4101       peer->handshake_params->hs_state.mseq_r = dtls_uint16_to_int(hs_header->message_seq);
4102       peer->handshake_params->hs_state.mseq_s = 1;
4103     }
4104
4105     clear_hs_hash(peer);
4106
4107     /* First negotiation step: check for PSK
4108      *
4109      * Note that we already have checked that msg is a Handshake
4110      * message containing a ClientHello. dtls_get_cipher() therefore
4111      * does not check again.
4112      */
4113     err = dtls_update_parameters(ctx, peer, data, data_length);
4114     if (err < 0) {
4115       dtls_warn("error updating security parameters\n");
4116       return err;
4117     }
4118
4119     /* update finish MAC */
4120     update_hs_hash(peer, data, data_length);
4121
4122     err = dtls_send_server_hello_msgs(ctx, peer);
4123     if (err < 0) {
4124       return err;
4125     }
4126     if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
4127             (is_ecdsa_client_auth_supported(ctx) || (is_x509_client_auth_supported(ctx))))
4128       peer->state = DTLS_STATE_WAIT_CLIENTCERTIFICATE; //ecdhe
4129     else
4130       peer->state = DTLS_STATE_WAIT_CLIENTKEYEXCHANGE; //psk, ecdh_anon
4131
4132     /* after sending the ServerHelloDone, we expect the
4133      * ClientKeyExchange (possibly containing the PSK id),
4134      * followed by a ChangeCipherSpec and an encrypted Finished.
4135      */
4136
4137     break;
4138
4139   case DTLS_HT_HELLO_REQUEST:
4140
4141     if (state != DTLS_STATE_CONNECTED) {
4142       /* we should just ignore such packets when in handshake */
4143       return 0;
4144     }
4145
4146     if (peer && !peer->handshake_params) {
4147       peer->handshake_params = dtls_handshake_new();
4148       if (!peer->handshake_params)
4149         return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
4150
4151       LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
4152       peer->handshake_params->hs_state.mseq_r = 0;
4153       peer->handshake_params->hs_state.mseq_s = 0;
4154     }
4155
4156     /* send ClientHello with empty Cookie */
4157     err = dtls_send_client_hello(ctx, peer, NULL, 0);
4158     if (err < 0) {
4159       dtls_warn("cannot send ClientHello\n");
4160       return err;
4161     }
4162     peer->state = DTLS_STATE_CLIENTHELLO;
4163     break;
4164
4165   default:
4166     dtls_crit("unhandled message %d\n", data[0]);
4167     return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
4168   }
4169
4170   if (peer && peer->handshake_params && err >= 0) {
4171     peer->handshake_params->hs_state.mseq_r++;
4172   }
4173
4174   return err;
4175 }
4176       
4177 static int
4178 handle_handshake(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
4179                  const dtls_peer_type role, const dtls_state_t state,
4180                  uint8 *data, size_t data_length)
4181 {
4182   dtls_handshake_header_t *hs_header;
4183   int res;
4184
4185   if (data_length < DTLS_HS_LENGTH) {
4186     dtls_warn("handshake message too short\n");
4187     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
4188   }
4189   hs_header = DTLS_HANDSHAKE_HEADER(data);
4190
4191   dtls_debug("received handshake packet of type: %s (%i)\n",
4192              dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
4193
4194   if (!peer || !peer->handshake_params) {
4195     /* This is the initial ClientHello */
4196     if (hs_header->msg_type != DTLS_HT_CLIENT_HELLO && !peer) {
4197       dtls_warn("If there is no peer only ClientHello is allowed\n");
4198       return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
4199     }
4200
4201     /* This is a ClientHello or Hello Request send when doing TLS renegotiation */
4202     if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
4203         hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
4204       return handle_handshake_msg(ctx, peer, session, role, state, data,
4205                                   data_length);
4206     } else {
4207       dtls_warn("ignore unexpected handshake message\n");
4208       return 0;
4209     }
4210   }
4211   /* This is a ClientHello send when doing retransmission */
4212   if (peer && hs_header->msg_type == DTLS_HT_CLIENT_HELLO &&
4213               dtls_uint16_to_int(hs_header->message_seq) == 0) {
4214      res = dtls_verify_peer(ctx, peer, session, state, data, data_length);
4215      if (res < 0) {
4216        dtls_warn("error in dtls_verify_peer err: %i\n", res);
4217      }
4218      if (res > 0) {
4219        dtls_debug("server hello verify was sent\n");
4220      }
4221      return res;
4222   }
4223
4224   if (dtls_uint16_to_int(hs_header->message_seq) < peer->handshake_params->hs_state.mseq_r) {
4225     dtls_warn("The message sequence number is too small, expected %i, got: %i\n",
4226               peer->handshake_params->hs_state.mseq_r, dtls_uint16_to_int(hs_header->message_seq));
4227     return 0;
4228   } else if (dtls_uint16_to_int(hs_header->message_seq) > peer->handshake_params->hs_state.mseq_r) {
4229     /* A packet in between is missing, buffer this packet. */
4230     netq_t *n;
4231
4232     /* TODO: only add packet that are not too new. */
4233     if (data_length > DTLS_MAX_BUF) {
4234       dtls_warn("the packet is too big to buffer for reoder\n");
4235       return 0;
4236     }
4237
4238     netq_t *node = netq_head(peer->handshake_params->reorder_queue);
4239     while (node) {
4240       dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
4241       if (dtls_uint16_to_int(node_header->message_seq) == dtls_uint16_to_int(hs_header->message_seq)) {
4242         dtls_warn("a packet with this sequence number is already stored\n");
4243         return 0;
4244       }
4245       node = netq_next(node);
4246     }
4247
4248     n = netq_node_new(data_length);
4249     if (!n) {
4250       dtls_warn("no space in reoder buffer\n");
4251       return 0;
4252     }
4253
4254     n->peer = peer;
4255     n->length = data_length;
4256     memcpy(n->data, data, data_length);
4257
4258     if (!netq_insert_node(peer->handshake_params->reorder_queue, n)) {
4259       dtls_warn("cannot add packet to reoder buffer\n");
4260       netq_node_free(n);
4261     }
4262     dtls_info("Added packet for reordering\n");
4263     return 0;
4264   } else if (dtls_uint16_to_int(hs_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
4265     /* Found the expected packet, use this and all the buffered packet */
4266     int next = 1;
4267
4268     res = handle_handshake_msg(ctx, peer, session, role, state, data, data_length);
4269     if (res < 0)
4270       return res;
4271
4272     /* We do not know in which order the packet are in the list just search the list for every packet. */
4273     while (next && peer->handshake_params) {
4274       next = 0;
4275       netq_t *node = netq_head(peer->handshake_params->reorder_queue);
4276       while (node) {
4277         dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
4278
4279         if (dtls_uint16_to_int(node_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
4280           netq_remove(peer->handshake_params->reorder_queue, node);
4281           next = 1;
4282           res = handle_handshake_msg(ctx, peer, session, role, peer->state, node->data, node->length);
4283           if (res < 0) {
4284             return res;
4285           }
4286
4287           break;
4288         } else {
4289           node = netq_next(node);
4290         }
4291       }
4292     }
4293     return res;
4294   }
4295   assert(0);
4296   return 0;
4297 }
4298
4299 static int
4300 handle_ccs(dtls_context_t *ctx, dtls_peer_t *peer, 
4301            uint8 *record_header, uint8 *data, size_t data_length)
4302 {
4303   int err;
4304
4305   /* A CCS message is handled after a KeyExchange message was
4306    * received from the client. When security parameters have been
4307    * updated successfully and a ChangeCipherSpec message was sent
4308    * by ourself, the security context is switched and the record
4309    * sequence number is reset. */
4310   
4311   if (!peer || peer->state != DTLS_STATE_WAIT_CHANGECIPHERSPEC) {
4312     dtls_warn("expected ChangeCipherSpec during handshake\n");
4313     return 0;
4314   }
4315
4316   if (data_length < 1 || data[0] != 1)
4317     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
4318
4319   dtls_handshake_parameters_t *handshake = peer->handshake_params;
4320   /* Just change the cipher when we are on the same epoch */
4321   if (peer->role == DTLS_SERVER) {
4322     err = calculate_key_block(ctx, handshake, peer,
4323                               &peer->session, peer->role);
4324     if (err < 0) {
4325       return err;
4326     }
4327   }
4328   
4329   peer->state = DTLS_STATE_WAIT_FINISHED;
4330
4331   return 0;
4332 }  
4333
4334 /** 
4335  * Handles incoming Alert messages. This function returns \c 1 if the
4336  * connection should be closed and the peer is to be invalidated.
4337  */
4338 static int
4339 handle_alert(dtls_context_t *ctx, dtls_peer_t *peer, 
4340              uint8 *record_header, uint8 *data, size_t data_length) {
4341   int free_peer = 0;            /* indicates whether to free peer */
4342
4343   if (data_length < 2)
4344     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
4345
4346   dtls_info("** Alert: level %d, description %d\n", data[0], data[1]);
4347
4348   if (!peer) {
4349     dtls_warn("got an alert for an unknown peer, we probably already removed it, ignore it\n");
4350     return 0;
4351   }
4352
4353   /* The peer object is invalidated for FATAL alerts and close
4354    * notifies. This is done in two steps.: First, remove the object
4355    * from our list of peers. After that, the event handler callback is
4356    * invoked with the still existing peer object. Finally, the storage
4357    * used by peer is released.
4358    */
4359   if (data[0] == DTLS_ALERT_LEVEL_FATAL || data[1] == DTLS_ALERT_CLOSE_NOTIFY) {
4360     dtls_alert("%d invalidate peer\n", data[1]);
4361     
4362 #ifndef WITH_CONTIKI
4363     HASH_DEL_PEER(ctx->peers, peer);
4364 #else /* WITH_CONTIKI */
4365     list_remove(ctx->peers, peer);
4366
4367 #ifndef NDEBUG
4368     PRINTF("removed peer [");
4369     PRINT6ADDR(&peer->session.addr);
4370     PRINTF("]:%d\n", uip_ntohs(peer->session.port));
4371 #endif
4372 #endif /* WITH_CONTIKI */
4373
4374     free_peer = 1;
4375
4376   }
4377
4378   (void)CALL(ctx, event, &peer->session, 
4379              (dtls_alert_level_t)data[0], (unsigned short)data[1]);
4380   switch (data[1]) {
4381   case DTLS_ALERT_CLOSE_NOTIFY:
4382     /* If state is DTLS_STATE_CLOSING, we have already sent a
4383      * close_notify so, do not send that again. */
4384     if (peer->state != DTLS_STATE_CLOSING) {
4385       peer->state = DTLS_STATE_CLOSING;
4386       dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_CLOSE_NOTIFY);
4387     } else
4388       peer->state = DTLS_STATE_CLOSED;
4389     break;
4390   default:
4391     ;
4392   }
4393   
4394   if (free_peer) {
4395     dtls_clear_retransmission(ctx, peer);
4396     dtls_destroy_peer(ctx, peer, 0);
4397   }
4398
4399   return free_peer;
4400 }
4401
4402 static int dtls_alert_send_from_err(dtls_context_t *ctx, dtls_peer_t *peer,
4403                                     session_t *session, int err)
4404 {
4405   int level;
4406   int desc;
4407
4408   if (err < -(1 << 8) && err > -(3 << 8)) {
4409     level = ((-err) & 0xff00) >> 8;
4410     desc = (-err) & 0xff;
4411     if (!peer) {
4412       peer = dtls_get_peer(ctx, session);
4413     }
4414     if (peer) {
4415       peer->state = DTLS_STATE_CLOSING;
4416       return dtls_send_alert(ctx, peer, level, desc);
4417     }
4418   } else if (err == -1) {
4419     if (!peer) {
4420       peer = dtls_get_peer(ctx, session);
4421     }
4422     if (peer) {
4423       peer->state = DTLS_STATE_CLOSING;
4424       return dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_INTERNAL_ERROR);
4425     }
4426   }
4427   return -1;
4428 }
4429
4430 /** 
4431  * Handles incoming data as DTLS message from given peer.
4432  */
4433 int
4434 dtls_handle_message(dtls_context_t *ctx, 
4435                     session_t *session,
4436                     uint8 *msg, int msglen) {
4437   dtls_peer_t *peer = NULL;
4438   unsigned int rlen;            /* record length */
4439   uint8 *data;                  /* (decrypted) payload */
4440   int data_length;              /* length of decrypted payload 
4441                                    (without MAC and padding) */
4442   int err;
4443
4444   /* check if we have DTLS state for addr/port/ifindex */
4445   peer = dtls_get_peer(ctx, session);
4446
4447   if (!peer) {
4448     dtls_debug("dtls_handle_message: PEER NOT FOUND\n");
4449     dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "peer addr", session);
4450   } else {
4451     dtls_debug("dtls_handle_message: FOUND PEER\n");
4452   }
4453
4454   while ((rlen = is_record(msg,msglen))) {
4455     dtls_peer_type role;
4456     dtls_state_t state;
4457
4458     dtls_debug("got packet %d (%d bytes)\n", msg[0], rlen);
4459     if (peer) {
4460       data_length = decrypt_verify(peer, msg, rlen, &data);
4461       if (data_length < 0) {
4462         if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
4463           data = msg + DTLS_RH_LENGTH;
4464           data_length = rlen - DTLS_RH_LENGTH;
4465           state = DTLS_STATE_WAIT_CLIENTHELLO;
4466           role = DTLS_SERVER;
4467         } else {
4468           if (DTLS_CT_HANDSHAKE == msg[0] && DTLS_STATE_WAIT_FINISHED == peer->state) {
4469             int err =  dtls_alert_fatal_create(DTLS_ALERT_DECRYPT_ERROR);
4470             dtls_info("decrypt_verify() failed\n");
4471
4472             dtls_alert_send_from_err(ctx, peer, &peer->session, err);
4473
4474             (void)CALL(ctx, event, &peer->session,
4475                     DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
4476             peer->state = DTLS_STATE_CLOSED;
4477                   /* dtls_clear_retransmission(ctx, peer); */
4478             dtls_destroy_peer(ctx, peer, 1);
4479             return err;
4480           } else {
4481             data = msg + DTLS_RH_LENGTH;
4482             data_length = rlen - DTLS_RH_LENGTH;
4483             role = peer->role;
4484             state = peer->state;
4485           }
4486         }
4487       } else {
4488         role = peer->role;
4489         state = peer->state;
4490       }
4491     } else {
4492       /* is_record() ensures that msg contains at least a record header */
4493       data = msg + DTLS_RH_LENGTH;
4494       data_length = rlen - DTLS_RH_LENGTH;
4495       state = DTLS_STATE_WAIT_CLIENTHELLO;
4496       role = DTLS_SERVER;
4497     }
4498
4499     dtls_debug_hexdump("receive header", msg, sizeof(dtls_record_header_t));
4500     dtls_debug_hexdump("receive unencrypted", data, data_length);
4501
4502     /* Handle received record according to the first byte of the
4503      * message, i.e. the subprotocol. We currently do not support
4504      * combining multiple fragments of one type into a single
4505      * record. */
4506
4507     switch (msg[0]) {
4508
4509     case DTLS_CT_CHANGE_CIPHER_SPEC:
4510       err = handle_ccs(ctx, peer, msg, data, data_length);
4511       if (err < 0) {
4512         dtls_warn("error while handling ChangeCipherSpec message\n");
4513         dtls_alert_send_from_err(ctx, peer, session, err);
4514         if (peer) {
4515           (void)CALL(ctx, event, &peer->session,
4516                 DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
4517
4518           /* invalidate peer */
4519           dtls_clear_retransmission(ctx, peer);
4520           dtls_destroy_peer(ctx, peer, 1);
4521           peer = NULL;
4522         }
4523         return err;
4524       }
4525       break;
4526
4527     case DTLS_CT_ALERT:
4528       if (peer) {
4529         dtls_clear_retransmission(ctx, peer);
4530       }
4531       err = handle_alert(ctx, peer, msg, data, data_length);
4532       if (err < 0 || err == 1) {
4533          dtls_warn("received alert, peer has been invalidated\n");
4534          /* handle alert has invalidated peer */
4535          peer = NULL;
4536          return err < 0 ?err:-1;
4537       }
4538       break;
4539
4540     case DTLS_CT_HANDSHAKE:
4541
4542       /* Handshake messages other than Finish must use the current
4543        * epoch, Finish has epoch + 1. */
4544
4545       if (peer) {
4546
4547               /* Handle the client's last flight retransmission when the server's
4548                * Finished message is lost. This avoids deadlock. */
4549         if (DTLS_SERVER == role && DTLS_STATE_CONNECTED == state) {
4550           dtls_start_retransmission(ctx, peer);
4551           break;
4552         }
4553         uint16_t expected_epoch = dtls_security_params(peer)->epoch;
4554         uint16_t msg_epoch = 
4555           dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
4556
4557         /* The new security parameters must be used for all messages
4558          * that are sent after the ChangeCipherSpec message. This
4559          * means that the client's Finished message uses epoch + 1
4560          * while the server is still in the old epoch.
4561          */
4562         if (role == DTLS_SERVER && state == DTLS_STATE_WAIT_FINISHED) {
4563           expected_epoch++;
4564         }
4565
4566         if (expected_epoch != msg_epoch) {
4567           if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
4568             state = DTLS_STATE_WAIT_CLIENTHELLO;
4569             role = DTLS_SERVER;
4570           } else {
4571             dtls_warn("Wrong epoch, expected %i, got: %i\n",
4572                     expected_epoch, msg_epoch);
4573             break;
4574           }
4575         }
4576       }
4577
4578       err = handle_handshake(ctx, peer, session, role, state, data, data_length);
4579       if (err < 0) {
4580         dtls_warn("error while handling handshake packet\n");
4581         dtls_alert_send_from_err(ctx, peer, session, err);
4582
4583       if (peer) {
4584         (void)CALL(ctx, event, &peer->session,
4585               DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
4586         dtls_destroy_peer(ctx, peer, 1);
4587       }
4588
4589         return err;
4590       }
4591       if (peer && peer->state == DTLS_STATE_CONNECTED) {
4592         /* stop retransmissions */
4593         dtls_stop_retransmission(ctx, peer);
4594         CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECTED);
4595       }
4596       break;
4597
4598     case DTLS_CT_APPLICATION_DATA:
4599       dtls_info("** application data:\n");
4600       if (!peer) {
4601         dtls_warn("no peer available, send an alert\n");
4602         // TODO: should we send a alert here?
4603         return -1;
4604       }
4605       dtls_clear_retransmission(ctx, peer);
4606       CALL(ctx, read, &peer->session, data, data_length);
4607       break;
4608     default:
4609       dtls_info("dropped unknown message of type %d\n",msg[0]);
4610     }
4611
4612     /* advance msg by length of ciphertext */
4613     msg += rlen;
4614     msglen -= rlen;
4615   }
4616
4617   return 0;
4618 }
4619
4620 dtls_context_t *
4621 dtls_new_context(void *app_data) {
4622   dtls_context_t *c;
4623   dtls_tick_t now;
4624 #ifndef WITH_CONTIKI
4625   FILE *urandom = fopen("/dev/urandom", "r");
4626   unsigned char buf[sizeof(unsigned long)];
4627 #endif /* WITH_CONTIKI */
4628
4629   dtls_ticks(&now);
4630 #ifdef WITH_CONTIKI
4631   /* FIXME: need something better to init PRNG here */
4632   dtls_prng_init(now);
4633 #else /* WITH_CONTIKI */
4634   if (!urandom) {
4635     dtls_emerg("cannot initialize PRNG\n");
4636     return NULL;
4637   }
4638
4639   if (fread(buf, 1, sizeof(buf), urandom) != sizeof(buf)) {
4640     dtls_emerg("cannot initialize PRNG\n");
4641     fclose(urandom);
4642     return NULL;
4643   }
4644
4645   fclose(urandom);
4646   dtls_prng_init((unsigned long)*buf);
4647 #endif /* WITH_CONTIKI */
4648
4649   c = malloc_context();
4650   if (!c)
4651     goto error;
4652
4653   memset(c, 0, sizeof(dtls_context_t));
4654   c->app = app_data;
4655   
4656   LIST_STRUCT_INIT(c, sendqueue);
4657
4658 #ifdef WITH_CONTIKI
4659   LIST_STRUCT_INIT(c, peers);
4660   /* LIST_STRUCT_INIT(c, key_store); */
4661   
4662   process_start(&dtls_retransmit_process, (char *)c);
4663   PROCESS_CONTEXT_BEGIN(&dtls_retransmit_process);
4664   /* the retransmit timer must be initialized to some large value */
4665   etimer_set(&c->retransmit_timer, 0xFFFF);
4666   PROCESS_CONTEXT_END(&coap_retransmit_process);
4667 #endif /* WITH_CONTIKI */
4668
4669   if (dtls_prng(c->cookie_secret, DTLS_COOKIE_SECRET_LENGTH))
4670     c->cookie_secret_age = now;
4671   else 
4672     goto error;
4673   
4674   return c;
4675
4676  error:
4677   dtls_alert("cannot create DTLS context\n");
4678   if (c)
4679     dtls_free_context(c);
4680   return NULL;
4681 }
4682
4683 void
4684 dtls_free_context(dtls_context_t *ctx) {
4685   dtls_peer_t *p;
4686
4687   if (!ctx) {
4688     return;
4689   }
4690
4691 #ifndef WITH_CONTIKI
4692   dtls_peer_t *tmp;
4693
4694   if (ctx->peers) {
4695     HASH_ITER(hh, ctx->peers, p, tmp) {
4696       dtls_destroy_peer(ctx, p, 1);
4697     }
4698   }
4699 #else /* WITH_CONTIKI */
4700   for (p = list_head(ctx->peers); p; p = list_item_next(p))
4701     dtls_destroy_peer(ctx, p, 1);
4702 #endif /* WITH_CONTIKI */
4703
4704   free_context(ctx);
4705 }
4706
4707 int
4708 dtls_connect_peer(dtls_context_t *ctx, dtls_peer_t *peer) {
4709   int res;
4710
4711   assert(peer);
4712   if (!peer)
4713     return -1;
4714
4715   /* check if the same peer is already in our list */
4716   if (peer == dtls_get_peer(ctx, &peer->session)) {
4717     dtls_debug("found peer, try to re-connect\n");
4718     return dtls_renegotiate(ctx, &peer->session);
4719   }
4720     
4721   /* set local peer role to client, remote is server */
4722   peer->role = DTLS_CLIENT;
4723
4724   dtls_add_peer(ctx, peer);
4725
4726   /* send ClientHello with empty Cookie */
4727   peer->handshake_params = dtls_handshake_new();
4728       if (!peer->handshake_params)
4729         return -1;
4730
4731   peer->handshake_params->hs_state.mseq_r = 0;
4732   peer->handshake_params->hs_state.mseq_s = 0;
4733   LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
4734   res = dtls_send_client_hello(ctx, peer, NULL, 0);
4735   if (res < 0)
4736     dtls_warn("cannot send ClientHello\n");
4737   else
4738     peer->state = DTLS_STATE_CLIENTHELLO;
4739
4740   return res;
4741 }
4742
4743 int
4744 dtls_connect(dtls_context_t *ctx, const session_t *dst) {
4745   dtls_peer_t *peer;
4746   int res;
4747
4748   peer = dtls_get_peer(ctx, dst);
4749   
4750   if (!peer)
4751     peer = dtls_new_peer(dst);
4752
4753   if (!peer) {
4754     dtls_crit("cannot create new peer\n");
4755     return -1;
4756   }
4757
4758   res = dtls_connect_peer(ctx, peer);
4759
4760   /* Invoke event callback to indicate connection attempt or
4761    * re-negotiation. */
4762   if (res > 0) {
4763     CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECT);
4764   } else if (res == 0) {
4765     CALL(ctx, event, &peer->session, 0, DTLS_EVENT_RENEGOTIATE);
4766   }
4767   
4768   return res;
4769 }
4770
4771 static void
4772 dtls_retransmit(dtls_context_t *context, netq_t *node) {
4773   if (!context || !node)
4774     return;
4775
4776   /* re-initialize timeout when maximum number of retransmissions are not reached yet */
4777   if (node->retransmit_cnt < DTLS_DEFAULT_MAX_RETRANSMIT) {
4778       unsigned char sendbuf[DTLS_MAX_BUF];
4779       size_t len = sizeof(sendbuf);
4780       int err;
4781       unsigned char *data = node->data;
4782       size_t length = node->length;
4783       dtls_tick_t now;
4784       dtls_security_parameters_t *security = dtls_security_params_epoch(node->peer, node->epoch);
4785
4786       dtls_ticks(&now);
4787       node->retransmit_cnt++;
4788       if (node->t == 1) {
4789         node->t = 0;
4790       } else {
4791         node->t = now + (node->timeout << node->retransmit_cnt);
4792       }
4793       netq_insert_node(context->sendqueue, node);
4794       
4795       if (node->type == DTLS_CT_HANDSHAKE) {
4796         dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
4797
4798         dtls_debug("** retransmit handshake packet of type: %s (%i)\n",
4799                    dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
4800       } else {
4801         dtls_debug("** retransmit packet\n");
4802       }
4803       
4804       err = dtls_prepare_record(node->peer, security, node->type, &data, &length,
4805                                 1, sendbuf, &len);
4806       if (err < 0) {
4807         dtls_warn("can not retransmit packet, err: %i\n", err);
4808         return;
4809       }
4810       dtls_debug_hexdump("retransmit header", sendbuf,
4811                          sizeof(dtls_record_header_t));
4812       dtls_debug_hexdump("retransmit unencrypted", node->data, node->length);
4813
4814       (void)CALL(context, write, &node->peer->session, sendbuf, len);
4815       return;
4816   }
4817
4818   /* no more retransmissions, remove node from system */
4819   
4820   dtls_debug("** removed transaction\n");
4821
4822   /* And finally delete the node */
4823   netq_node_free(node);
4824 }
4825
4826 static void
4827 dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer) {
4828   netq_t *node;
4829   node = list_head(context->sendqueue); 
4830
4831   while (node) {
4832     if (dtls_session_equals(&node->peer->session, &peer->session)) {
4833       node->t = 0;
4834     }
4835     node = list_item_next(node);
4836   }
4837 }
4838
4839 static void
4840 dtls_start_retransmission(dtls_context_t *context, dtls_peer_t *peer) {
4841   netq_t *node;
4842   node = list_head(context->sendqueue);
4843
4844   while (node) {
4845     if (dtls_session_equals(&node->peer->session, &peer->session)) {
4846       node->retransmit_cnt = 0;
4847       node->t = 1;
4848     }
4849     node = list_item_next(node);
4850   }
4851 }
4852
4853 static void
4854 dtls_clear_retransmission(dtls_context_t *context, dtls_peer_t *peer) {
4855   netq_t *node;
4856   node = list_head(context->sendqueue);
4857
4858   while (node) {
4859     if (dtls_session_equals(&node->peer->session, &peer->session)) {
4860       netq_t *tmp = node;
4861       node = list_item_next(node);
4862       list_remove(context->sendqueue, tmp);
4863       netq_node_free(tmp);
4864     } else {
4865       node = list_item_next(node);
4866     }
4867   }
4868 }
4869
4870 void
4871 dtls_check_retransmit(dtls_context_t *context, clock_time_t *next) {
4872   dtls_tick_t now;
4873   netq_t *node = netq_head(context->sendqueue);
4874
4875   dtls_ticks(&now);
4876
4877   while (node) {
4878     if (node->t && node->t <= now){
4879       netq_pop_first(context->sendqueue);
4880       dtls_retransmit(context, node);
4881       node = netq_head(context->sendqueue);
4882     } else {
4883       node = list_item_next(node);
4884     }
4885   }
4886 }
4887
4888 size_t
4889 dtls_prf_with_current_keyblock(dtls_context_t *ctx, session_t *session,
4890                                const uint8_t* label, const uint32_t labellen,
4891                                const uint8_t* random1, const uint32_t random1len,
4892                                const uint8_t* random2, const uint32_t random2len,
4893                                uint8_t* buf, const uint32_t buflen) {
4894   dtls_peer_t *peer = NULL;
4895   dtls_security_parameters_t *security = NULL;
4896   size_t keysize = 0;
4897
4898   if(!ctx || !session || !label || !buf || labellen == 0 || buflen == 0) {
4899     dtls_warn("dtls_prf_with_current_keyblock(): invalid parameter\n");
4900     return 0;
4901   }
4902
4903   peer = dtls_get_peer(ctx, session);
4904   if (!peer) {
4905     dtls_warn("dtls_prf_with_current_keyblock(): cannot find peer\n");
4906     return 0;
4907   }
4908
4909   security = dtls_security_params(peer);
4910   if (!security) {
4911     dtls_crit("dtls_prf_with_current_keyblock(): peer has empty security parameters\n");
4912     return 0;
4913   }
4914
4915   /* note that keysize should never be zero as bad things will happen */
4916   keysize = dtls_kb_size(security, peer->role);
4917   assert(keysize > 0);
4918
4919   return dtls_prf(security->key_block, keysize,
4920                   label, labellen,
4921                   random1, random1len,
4922                   random2, random2len,
4923                   buf, buflen);
4924 }
4925
4926 #ifdef WITH_CONTIKI
4927 /*---------------------------------------------------------------------------*/
4928 /* message retransmission */
4929 /*---------------------------------------------------------------------------*/
4930 PROCESS_THREAD(dtls_retransmit_process, ev, data)
4931 {
4932   clock_time_t now;
4933   netq_t *node;
4934
4935   PROCESS_BEGIN();
4936
4937   dtls_debug("Started DTLS retransmit process\r\n");
4938
4939   while(1) {
4940     PROCESS_YIELD();
4941     if (ev == PROCESS_EVENT_TIMER) {
4942       if (etimer_expired(&the_dtls_context.retransmit_timer)) {
4943         
4944         node = list_head(the_dtls_context.sendqueue);
4945         
4946         now = clock_time();
4947         if (node && node->t <= now) {
4948           dtls_retransmit(&the_dtls_context, list_pop(the_dtls_context.sendqueue));
4949           node = list_head(the_dtls_context.sendqueue);
4950         }
4951
4952         /* need to set timer to some value even if no nextpdu is available */
4953         if (node) {
4954           etimer_set(&the_dtls_context.retransmit_timer, 
4955                      node->t <= now ? 1 : node->t - now);
4956         } else {
4957           etimer_set(&the_dtls_context.retransmit_timer, 0xFFFF);
4958         }
4959       } 
4960     }
4961   }
4962   
4963   PROCESS_END();
4964 }
4965 #endif /* WITH_CONTIKI */