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