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