tinydtls: remove certificate_list length field for raw public keys
[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 #define DTLS_EC_SUBJECTPUBLICKEY_SIZE (2 * DTLS_EC_KEY_SIZE + sizeof(cert_asn1_header))
2069
2070 static int
2071 dtls_send_certificate_ecdsa(dtls_context_t *ctx, dtls_peer_t *peer,
2072                             const dtls_ecc_key_t *key)
2073 {
2074   uint8 buf[DTLS_CE_LENGTH];
2075   uint8 *p;
2076
2077   /* Certificate 
2078    *
2079    * Start message construction at beginning of buffer. */
2080   p = buf;
2081
2082   /* length of this certificate */
2083   dtls_int_to_uint24(p, DTLS_EC_SUBJECTPUBLICKEY_SIZE);
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) != DTLS_EC_SUBJECTPUBLICKEY_SIZE) {
3003     dtls_alert("expect length of %d bytes for certificate\n",
3004                DTLS_EC_SUBJECTPUBLICKEY_SIZE);
3005     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3006   }
3007   data += sizeof(uint24);
3008
3009   if (memcmp(data, cert_asn1_header, sizeof(cert_asn1_header))) {
3010     dtls_alert("got an unexpected Subject public key format\n");
3011     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3012   }
3013   data += sizeof(cert_asn1_header);
3014
3015   memcpy(config->keyx.ecc.other_pub_x, data,
3016          sizeof(config->keyx.ecc.other_pub_x));
3017   data += sizeof(config->keyx.ecc.other_pub_x);
3018
3019   memcpy(config->keyx.ecc.other_pub_y, data,
3020          sizeof(config->keyx.ecc.other_pub_y));
3021   data += sizeof(config->keyx.ecc.other_pub_y);
3022
3023   err = CALL(ctx, verify_ecdsa_key, &peer->session,
3024              config->keyx.ecc.other_pub_x,
3025              config->keyx.ecc.other_pub_y,
3026              sizeof(config->keyx.ecc.other_pub_x));
3027   if (err < 0) {
3028     dtls_warn("The certificate was not accepted\n");
3029     return err;
3030   }
3031
3032   return 0;
3033 }
3034
3035 static int
3036 check_server_key_exchange_ecdsa(dtls_context_t *ctx,
3037                                 dtls_peer_t *peer,
3038                                 uint8 *data, size_t data_length)
3039 {
3040   dtls_handshake_parameters_t *config = peer->handshake_params;
3041   int ret;
3042   unsigned char *result_r;
3043   unsigned char *result_s;
3044   unsigned char *key_params;
3045
3046   update_hs_hash(peer, data, data_length);
3047
3048   assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
3049
3050   data += DTLS_HS_LENGTH;
3051
3052   if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_LENGTH) {
3053     dtls_alert("the packet length does not match the expected\n");
3054     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3055   }
3056   key_params = data;
3057
3058   if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
3059     dtls_alert("Only named curves supported\n");
3060     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3061   }
3062   data += sizeof(uint8);
3063   data_length -= sizeof(uint8);
3064
3065   if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
3066     dtls_alert("secp256r1 supported\n");
3067     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3068   }
3069   data += sizeof(uint16);
3070   data_length -= sizeof(uint16);
3071
3072   if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
3073     dtls_alert("expected 65 bytes long public point\n");
3074     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3075   }
3076   data += sizeof(uint8);
3077   data_length -= sizeof(uint8);
3078
3079   if (dtls_uint8_to_int(data) != 4) {
3080     dtls_alert("expected uncompressed public point\n");
3081     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3082   }
3083   data += sizeof(uint8);
3084   data_length -= sizeof(uint8);
3085
3086   memcpy(config->keyx.ecc.other_eph_pub_x, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3087   data += sizeof(config->keyx.ecc.other_eph_pub_y);
3088   data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3089
3090   memcpy(config->keyx.ecc.other_eph_pub_y, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3091   data += sizeof(config->keyx.ecc.other_eph_pub_y);
3092   data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3093
3094   ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
3095   if (ret < 0) {
3096     return ret;
3097   }
3098   data += ret;
3099   data_length -= ret;
3100
3101   ret = dtls_ecdsa_verify_sig(config->keyx.ecc.other_pub_x, config->keyx.ecc.other_pub_y,
3102                             sizeof(config->keyx.ecc.other_pub_x),
3103                             config->tmp.random.client, DTLS_RANDOM_LENGTH,
3104                             config->tmp.random.server, DTLS_RANDOM_LENGTH,
3105                             key_params,
3106                             1 + 2 + 1 + 1 + (2 * DTLS_EC_KEY_SIZE),
3107                             result_r, result_s);
3108
3109   if (ret < 0) {
3110     dtls_alert("wrong signature\n");
3111     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3112   }
3113   return 0;
3114 }
3115
3116 static int
3117 check_server_key_exchange_ecdh(dtls_context_t *ctx,
3118                                 dtls_peer_t *peer,
3119                                 uint8 *data, size_t data_length)
3120 {
3121   dtls_handshake_parameters_t *config = peer->handshake_params;
3122
3123   update_hs_hash(peer, data, data_length);
3124
3125   assert(is_tls_ecdh_anon_with_aes_128_cbc_sha_256(config->cipher));
3126
3127   data += DTLS_HS_LENGTH;
3128
3129   if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_ECDH_ANON_LENGTH) {
3130     dtls_alert("the packet length does not match the expected\n");
3131     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3132   }
3133
3134   if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
3135     dtls_alert("Only named curves supported\n");
3136     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3137   }
3138   data += sizeof(uint8);
3139   data_length -= sizeof(uint8);
3140
3141   if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
3142     dtls_alert("secp256r1 supported\n");
3143     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3144   }
3145   data += sizeof(uint16);
3146   data_length -= sizeof(uint16);
3147
3148   if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
3149     dtls_alert("expected 65 bytes long public point\n");
3150     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3151   }
3152   data += sizeof(uint8);
3153   data_length -= sizeof(uint8);
3154
3155   if (dtls_uint8_to_int(data) != 4) {
3156     dtls_alert("expected uncompressed public point\n");
3157     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3158   }
3159   data += sizeof(uint8);
3160   data_length -= sizeof(uint8);
3161
3162   memcpy(config->keyx.ecc.other_eph_pub_x, data, sizeof(config->keyx.ecc.other_eph_pub_x));
3163   data += sizeof(config->keyx.ecc.other_eph_pub_x);
3164   data_length -= sizeof(config->keyx.ecc.other_eph_pub_x);
3165
3166   memcpy(config->keyx.ecc.other_eph_pub_y, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3167   data += sizeof(config->keyx.ecc.other_eph_pub_y);
3168   data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3169
3170   return 0;
3171 }
3172 #endif /* DTLS_ECC */
3173 #if defined(DTLS_PSK) && defined(DTLS_ECC)
3174 check_server_key_exchange_ecdhe_psk(dtls_context_t *ctx,
3175                               dtls_peer_t *peer,
3176                               uint8 *data, size_t data_length)
3177 {
3178   dtls_handshake_parameters_t *config = peer->handshake_params;
3179   uint16_t psk_len = 0;
3180
3181   /* ServerKeyExchange
3182     * Please see Session 2, RFC 5489.
3183
3184          struct {
3185           select (KeyExchangeAlgorithm) {
3186               //other cases for rsa, diffie_hellman, etc.
3187               case ec_diffie_hellman_psk:  // NEW
3188                   opaque psk_identity_hint<0..2^16-1>;
3189                   ServerECDHParams params;
3190           };
3191       } ServerKeyExchange; */
3192
3193   update_hs_hash(peer, data, data_length);
3194
3195   assert(is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(config->cipher));
3196
3197   data += DTLS_HS_LENGTH;
3198
3199   psk_len = dtls_uint16_to_int(data);
3200   data += sizeof(uint16);
3201
3202   if (psk_len != data_length - DTLS_HS_LENGTH - DTLS_SKEXEC_ECDH_ANON_LENGTH - sizeof(uint16)) {
3203     dtls_warn("the length of the server identity hint is worng\n");
3204     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3205   }
3206
3207   if (psk_len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
3208     dtls_warn("please use a smaller server identity hint\n");
3209     return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3210   }
3211
3212   // store the psk_identity_hint in config->keyx.psk for later use
3213   config->keyx.psk.id_length = psk_len;
3214   memcpy(config->keyx.psk.identity, data, psk_len);
3215
3216   data += psk_len;
3217   data_length -= psk_len;
3218
3219   if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_ECDH_ANON_LENGTH) {
3220     dtls_alert("the packet length does not match the expected\n");
3221     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3222   }
3223
3224   if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
3225     dtls_alert("Only named curves supported\n");
3226     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3227   }
3228   data += sizeof(uint8);
3229   data_length -= sizeof(uint8);
3230
3231   if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
3232     dtls_alert("secp256r1 supported\n");
3233     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3234   }
3235   data += sizeof(uint16);
3236   data_length -= sizeof(uint16);
3237
3238   if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
3239     dtls_alert("expected 65 bytes long public point\n");
3240     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3241   }
3242   data += sizeof(uint8);
3243   data_length -= sizeof(uint8);
3244
3245   if (dtls_uint8_to_int(data) != 4) {
3246     dtls_alert("expected uncompressed public point\n");
3247     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3248   }
3249   data += sizeof(uint8);
3250   data_length -= sizeof(uint8);
3251
3252   memcpy(config->keyx.ecc.other_eph_pub_x, data, sizeof(config->keyx.ecc.other_eph_pub_x));
3253   data += sizeof(config->keyx.ecc.other_eph_pub_x);
3254   data_length -= sizeof(config->keyx.ecc.other_eph_pub_x);
3255
3256   memcpy(config->keyx.ecc.other_eph_pub_y, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3257   data += sizeof(config->keyx.ecc.other_eph_pub_y);
3258   data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3259
3260   return 0;
3261 }
3262 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
3263
3264 #ifdef DTLS_PSK
3265 static int
3266 check_server_key_exchange_psk(dtls_context_t *ctx,
3267                               dtls_peer_t *peer,
3268                               uint8 *data, size_t data_length)
3269 {
3270   dtls_handshake_parameters_t *config = peer->handshake_params;
3271   uint16_t len;
3272
3273   update_hs_hash(peer, data, data_length);
3274
3275   assert(is_tls_psk_with_aes_128_ccm_8(config->cipher));
3276
3277   data += DTLS_HS_LENGTH;
3278
3279   if (data_length < DTLS_HS_LENGTH + DTLS_SKEXECPSK_LENGTH_MIN) {
3280     dtls_alert("the packet length does not match the expected\n");
3281     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3282   }
3283
3284   len = dtls_uint16_to_int(data);
3285   data += sizeof(uint16);
3286
3287   if (len != data_length - DTLS_HS_LENGTH - sizeof(uint16)) {
3288     dtls_warn("the length of the server identity hint is worng\n");
3289     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3290   }
3291
3292   if (len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
3293     dtls_warn("please use a smaller server identity hint\n");
3294     return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3295   }
3296
3297   /* store the psk_identity_hint in config->keyx.psk for later use */
3298   config->keyx.psk.id_length = len;
3299   memcpy(config->keyx.psk.identity, data, len);
3300   return 0;
3301 }
3302 #endif /* DTLS_PSK */
3303
3304 static int
3305 check_certificate_request(dtls_context_t *ctx, 
3306                           dtls_peer_t *peer,
3307                           uint8 *data, size_t data_length)
3308 {
3309   unsigned int i;
3310   int auth_alg;
3311   int sig_alg;
3312   int hash_alg;
3313
3314   update_hs_hash(peer, data, data_length);
3315
3316   assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher));
3317
3318   data += DTLS_HS_LENGTH;
3319
3320   if (data_length < DTLS_HS_LENGTH + 5) {
3321     dtls_alert("the packet length does not match the expected\n");
3322     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3323   }
3324
3325   i = dtls_uint8_to_int(data);
3326   data += sizeof(uint8);
3327   if (i + 1 > data_length) {
3328     dtls_alert("the cerfificate types are too long\n");
3329     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3330   }
3331
3332   auth_alg = 0;
3333   for (; i > 0 ; i -= sizeof(uint8)) {
3334     if (dtls_uint8_to_int(data) == TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN
3335         && auth_alg == 0)
3336       auth_alg = dtls_uint8_to_int(data);
3337     data += sizeof(uint8);
3338   }
3339
3340   if (auth_alg != TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN) {
3341     dtls_alert("the request authentication algorithm is not supproted\n");
3342     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3343   }
3344
3345   i = dtls_uint16_to_int(data);
3346   data += sizeof(uint16);
3347   if (i + 1 > data_length) {
3348     dtls_alert("the signature and hash algorithm list is too long\n");
3349     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3350   }
3351
3352   hash_alg = 0;
3353   sig_alg = 0;
3354   for (; i > 0 ; i -= sizeof(uint16)) {
3355     int current_hash_alg;
3356     int current_sig_alg;
3357
3358     current_hash_alg = dtls_uint8_to_int(data);
3359     data += sizeof(uint8);
3360     current_sig_alg = dtls_uint8_to_int(data);
3361     data += sizeof(uint8);
3362
3363     if (current_hash_alg == TLS_EXT_SIG_HASH_ALGO_SHA256 && hash_alg == 0 && 
3364         current_sig_alg == TLS_EXT_SIG_HASH_ALGO_ECDSA && sig_alg == 0) {
3365       hash_alg = current_hash_alg;
3366       sig_alg = current_sig_alg;
3367     }
3368   }
3369
3370   if (hash_alg != TLS_EXT_SIG_HASH_ALGO_SHA256 ||
3371       sig_alg != TLS_EXT_SIG_HASH_ALGO_ECDSA) {
3372     dtls_alert("no supported hash and signature algorithem\n");
3373     return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3374   }
3375
3376   /* common names are ignored */
3377
3378   peer->handshake_params->do_client_auth = 1;
3379   return 0;
3380 }
3381
3382 static int
3383 check_server_hellodone(dtls_context_t *ctx, 
3384                       dtls_peer_t *peer,
3385                       uint8 *data, size_t data_length)
3386 {
3387   int res;
3388 #ifdef DTLS_ECC
3389   const dtls_ecc_key_t *ecdsa_key;
3390 #endif /* DTLS_ECC */
3391
3392   dtls_handshake_parameters_t *handshake = peer->handshake_params;
3393
3394   /* calculate master key, send CCS */
3395
3396   update_hs_hash(peer, data, data_length);
3397
3398 #ifdef DTLS_ECC
3399   if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && handshake->do_client_auth) {
3400
3401     res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
3402     if (res < 0) {
3403       dtls_crit("no ecdsa certificate to send in certificate\n");
3404       return res;
3405     }
3406
3407     res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
3408
3409     if (res < 0) {
3410       dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
3411       return res;
3412     }
3413   }
3414 #endif /* DTLS_ECC */
3415
3416   /* send ClientKeyExchange */
3417   res = dtls_send_client_key_exchange(ctx, peer);
3418
3419   if (res < 0) {
3420     dtls_debug("cannot send KeyExchange message\n");
3421     return res;
3422   }
3423
3424 #ifdef DTLS_ECC
3425   if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && handshake->do_client_auth) {
3426
3427     res = dtls_send_certificate_verify_ecdh(ctx, peer, ecdsa_key);
3428
3429     if (res < 0) {
3430       dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
3431       return res;
3432     }
3433   }
3434 #endif /* DTLS_ECC */
3435
3436   res = calculate_key_block(ctx, handshake, peer,
3437                             &peer->session, peer->role);
3438   if (res < 0) {
3439     return res;
3440   }
3441
3442   res = dtls_send_ccs(ctx, peer);
3443   if (res < 0) {
3444     dtls_debug("cannot send CCS message\n");
3445     return res;
3446   }
3447
3448   /* and switch cipher suite */
3449   dtls_security_params_switch(peer);
3450
3451   /* Client Finished */
3452   return dtls_send_finished(ctx, peer, PRF_LABEL(client), PRF_LABEL_SIZE(client));
3453 }
3454
3455 static int
3456 decrypt_verify(dtls_peer_t *peer, uint8 *packet, size_t length,
3457                uint8 **cleartext)
3458 {
3459   dtls_record_header_t *header = DTLS_RECORD_HEADER(packet);
3460   dtls_security_parameters_t *security = dtls_security_params_epoch(peer, dtls_get_epoch(header));
3461   int clen;
3462   
3463   *cleartext = (uint8 *)packet + sizeof(dtls_record_header_t);
3464   clen = length - sizeof(dtls_record_header_t);
3465
3466   if (!security) {
3467     dtls_alert("No security context for epoch: %i\n", dtls_get_epoch(header));
3468     return -1;
3469   }
3470
3471   if (security->cipher == TLS_NULL_WITH_NULL_NULL) {
3472     /* no cipher suite selected */
3473     return clen;
3474   } else if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(security->cipher) ||
3475              is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(security->cipher)) {
3476
3477     unsigned char nonce[DTLS_CBC_IV_LENGTH];
3478
3479     if (clen < (DTLS_CBC_IV_LENGTH + DTLS_HMAC_DIGEST_SIZE))            /* need at least IV and MAC */
3480       return -1;
3481
3482     memcpy(nonce, *cleartext , DTLS_CBC_IV_LENGTH);
3483     clen -= DTLS_CBC_IV_LENGTH;
3484     *cleartext += DTLS_CBC_IV_LENGTH ;
3485
3486     clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
3487                        dtls_kb_remote_write_key(security, peer->role),
3488                        dtls_kb_key_size(security, peer->role),
3489                        NULL, 0,
3490                        security->cipher);
3491
3492   } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
3493     /** 
3494      * length of additional_data for the AEAD cipher which consists of
3495      * seq_num(2+6) + type(1) + version(2) + length(2)
3496      */
3497 #define A_DATA_LEN 13
3498     unsigned char nonce[DTLS_CCM_BLOCKSIZE];
3499     unsigned char A_DATA[A_DATA_LEN];
3500
3501     if (clen < 16)              /* need at least IV and MAC */
3502       return -1;
3503
3504     memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
3505     memcpy(nonce, dtls_kb_remote_iv(security, peer->role),
3506         dtls_kb_iv_size(security, peer->role));
3507
3508     /* read epoch and seq_num from message */
3509     memcpy(nonce + dtls_kb_iv_size(security, peer->role), *cleartext, 8);
3510     *cleartext += 8;
3511     clen -= 8;
3512
3513     dtls_debug_dump("nonce", nonce, DTLS_CCM_BLOCKSIZE);
3514     dtls_debug_dump("key", dtls_kb_remote_write_key(security, peer->role),
3515                     dtls_kb_key_size(security, peer->role));
3516     dtls_debug_dump("ciphertext", *cleartext, clen);
3517
3518     /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
3519      * 
3520      * additional_data = seq_num + TLSCompressed.type +
3521      *                   TLSCompressed.version + TLSCompressed.length;
3522      */
3523     memcpy(A_DATA, &DTLS_RECORD_HEADER(packet)->epoch, 8); /* epoch and seq_num */
3524     memcpy(A_DATA + 8,  &DTLS_RECORD_HEADER(packet)->content_type, 3); /* type and version */
3525     dtls_int_to_uint16(A_DATA + 11, clen - 8); /* length without nonce_explicit */
3526
3527     clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
3528                        dtls_kb_remote_write_key(security, peer->role),
3529                        dtls_kb_key_size(security, peer->role),
3530                        A_DATA, A_DATA_LEN,
3531                        security->cipher);
3532   }
3533
3534   if (clen < 0)
3535     dtls_warn("decryption failed\n");
3536   else {
3537 #ifndef NDEBUG
3538     dtls_debug("decrypt_verify(): found %i bytes cleartext\n", clen);
3539 #endif
3540     dtls_security_params_free_other(peer);
3541     dtls_debug_dump("cleartext", *cleartext, clen);
3542   }
3543
3544   return clen;
3545 }
3546
3547 static int
3548 dtls_send_hello_request(dtls_context_t *ctx, dtls_peer_t *peer)
3549 {
3550   return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
3551                                       DTLS_HT_HELLO_REQUEST,
3552                                       NULL, 0, 0);
3553 }
3554
3555 int
3556 dtls_renegotiate(dtls_context_t *ctx, const session_t *dst)
3557 {
3558   dtls_peer_t *peer = NULL;
3559   int err;
3560
3561   peer = dtls_get_peer(ctx, dst);
3562
3563   if (!peer) {
3564     return -1;
3565   }
3566   if (peer->state != DTLS_STATE_CONNECTED)
3567     return -1;
3568
3569   peer->handshake_params = dtls_handshake_new();
3570   if (!peer->handshake_params)
3571     return -1;
3572
3573   peer->handshake_params->hs_state.mseq_r = 0;
3574   peer->handshake_params->hs_state.mseq_s = 0;
3575
3576   if (peer->role == DTLS_CLIENT) {
3577     /* send ClientHello with empty Cookie */
3578     err = dtls_send_client_hello(ctx, peer, NULL, 0);
3579     if (err < 0)
3580       dtls_warn("cannot send ClientHello\n");
3581     else
3582       peer->state = DTLS_STATE_CLIENTHELLO;
3583     return err;
3584   } else if (peer->role == DTLS_SERVER) {
3585     return dtls_send_hello_request(ctx, peer);
3586   }
3587
3588   return -1;
3589 }
3590
3591 static int
3592 handle_handshake_msg(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
3593                  const dtls_peer_type role, const dtls_state_t state,
3594                  uint8 *data, size_t data_length) {
3595
3596   int err = 0;
3597
3598   /* This will clear the retransmission buffer if we get an expected
3599    * handshake message. We have to make sure that no handshake message
3600    * should get expected when we still should retransmit something, when
3601    * we do everything accordingly to the DTLS 1.2 standard this should
3602    * not be a problem. */
3603   if (peer) {
3604     dtls_stop_retransmission(ctx, peer);
3605   }
3606
3607   /* The following switch construct handles the given message with
3608    * respect to the current internal state for this peer. In case of
3609    * error, it is left with return 0. */
3610
3611   dtls_debug("handle handshake packet of type: %s (%i)\n",
3612              dtls_handshake_type_to_name(data[0]), data[0]);
3613   switch (data[0]) {
3614
3615   /************************************************************************
3616    * Client states
3617    ************************************************************************/
3618   case DTLS_HT_HELLO_VERIFY_REQUEST:
3619
3620     if (state != DTLS_STATE_CLIENTHELLO) {
3621       return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3622     }
3623
3624     err = check_server_hello_verify_request(ctx, peer, data, data_length);
3625     if (err < 0) {
3626       dtls_warn("error in check_server_hello_verify_request err: %i\n", err);
3627       return err;
3628     }
3629
3630     break;
3631   case DTLS_HT_SERVER_HELLO:
3632
3633     if (state != DTLS_STATE_CLIENTHELLO) {
3634       return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3635     }
3636
3637     err = check_server_hello(ctx, peer, data, data_length);
3638     if (err < 0) {
3639       dtls_warn("error in check_server_hello err: %i\n", err);
3640       return err;
3641     }
3642     if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher))
3643       peer->state = DTLS_STATE_WAIT_SERVERCERTIFICATE; //ecdsa
3644     else if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(peer->handshake_params->cipher) ||
3645         is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(peer->handshake_params->cipher))
3646         peer->state = DTLS_STATE_WAIT_SERVERKEYEXCHANGE; //ecdh
3647     else
3648       peer->state = DTLS_STATE_WAIT_SERVERHELLODONE; //psk
3649     /* update_hs_hash(peer, data, data_length); */
3650
3651     break;
3652
3653 #ifdef DTLS_ECC
3654   case DTLS_HT_CERTIFICATE:
3655
3656     if ((role == DTLS_CLIENT && state != DTLS_STATE_WAIT_SERVERCERTIFICATE) ||
3657         (role == DTLS_SERVER && state != DTLS_STATE_WAIT_CLIENTCERTIFICATE)) {
3658       return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3659     }
3660     err = check_server_certificate(ctx, peer, data, data_length);
3661     if (err < 0) {
3662       dtls_warn("error in check_server_certificate err: %i\n", err);
3663       return err;
3664     }
3665     if (role == DTLS_CLIENT) {
3666       peer->state = DTLS_STATE_WAIT_SERVERKEYEXCHANGE;
3667     } else if (role == DTLS_SERVER){
3668       peer->state = DTLS_STATE_WAIT_CLIENTKEYEXCHANGE;
3669     }
3670     /* update_hs_hash(peer, data, data_length); */
3671
3672     break;
3673 #endif /* DTLS_ECC */
3674
3675   case DTLS_HT_SERVER_KEY_EXCHANGE:
3676
3677 #ifdef DTLS_ECC
3678     if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
3679       if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3680         return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3681       }
3682       err = check_server_key_exchange_ecdsa(ctx, peer, data, data_length);
3683     }
3684
3685     if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(peer->handshake_params->cipher)) {
3686       if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3687         return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3688       }
3689       err = check_server_key_exchange_ecdh(ctx, peer, data, data_length);
3690     }
3691 #endif /* DTLS_ECC */
3692
3693 #if defined(DTLS_PSK) && defined(DTLS_ECC)
3694     if (is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(peer->handshake_params->cipher)) {
3695         if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3696           return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3697         }
3698       err = check_server_key_exchange_ecdhe_psk(ctx, peer, data, data_length);
3699     }
3700 #endif defined(DTLS_PSK) && defined(DTLS_ECC)
3701
3702 #ifdef DTLS_PSK
3703     if (is_tls_psk_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
3704       if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3705         return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3706       }
3707       err = check_server_key_exchange_psk(ctx, peer, data, data_length);
3708     }
3709 #endif /* DTLS_PSK */
3710
3711     if (err < 0) {
3712       dtls_warn("error in check_server_key_exchange err: %i\n", err);
3713       return err;
3714     }
3715     peer->state = DTLS_STATE_WAIT_SERVERHELLODONE;
3716     /* update_hs_hash(peer, data, data_length); */
3717
3718     break;
3719
3720   case DTLS_HT_SERVER_HELLO_DONE:
3721
3722     if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3723       return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3724     }
3725
3726     err = check_server_hellodone(ctx, peer, data, data_length);
3727     if (err < 0) {
3728       dtls_warn("error in check_server_hellodone err: %i\n", err);
3729       return err;
3730     }
3731     peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
3732     /* update_hs_hash(peer, data, data_length); */
3733
3734     break;
3735
3736   case DTLS_HT_CERTIFICATE_REQUEST:
3737
3738     if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3739       return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3740     }
3741
3742     err = check_certificate_request(ctx, peer, data, data_length);
3743     if (err < 0) {
3744       dtls_warn("error in check_certificate_request err: %i\n", err);
3745       return err;
3746     }
3747
3748     break;
3749
3750   case DTLS_HT_FINISHED:
3751     /* expect a Finished message from server */
3752
3753     if (state != DTLS_STATE_WAIT_FINISHED) {
3754       return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3755     }
3756
3757     err = check_finished(ctx, peer, data, data_length);
3758     if (err < 0) {
3759       dtls_warn("error in check_finished err: %i\n", err);
3760       return err;
3761     }
3762     if (role == DTLS_SERVER) {
3763       /* send ServerFinished */
3764       update_hs_hash(peer, data, data_length);
3765
3766       /* send change cipher spec message and switch to new configuration */
3767       err = dtls_send_ccs(ctx, peer);
3768       if (err < 0) {
3769         dtls_warn("cannot send CCS message\n");
3770         return err;
3771       }
3772
3773       dtls_security_params_switch(peer);
3774
3775       err = dtls_send_finished(ctx, peer, PRF_LABEL(server), PRF_LABEL_SIZE(server));
3776       if (err < 0) {
3777         dtls_warn("sending server Finished failed\n");
3778         return err;
3779       }
3780     }
3781     dtls_handshake_free(peer->handshake_params);
3782     peer->handshake_params = NULL;
3783     dtls_debug("Handshake complete\n");
3784     check_stack();
3785     peer->state = DTLS_STATE_CONNECTED;
3786
3787     /* return here to not increase the message receive counter */
3788     return err;
3789
3790   /************************************************************************
3791    * Server states
3792    ************************************************************************/
3793
3794   case DTLS_HT_CLIENT_KEY_EXCHANGE:
3795     /* handle ClientHello, update msg and msglen and goto next if not finished */
3796
3797     if (state != DTLS_STATE_WAIT_CLIENTKEYEXCHANGE) {
3798       return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3799     }
3800
3801     err = check_client_keyexchange(ctx, peer->handshake_params, data, data_length);
3802     if (err < 0) {
3803       dtls_warn("error in check_client_keyexchange err: %i\n", err);
3804       return err;
3805     }
3806     update_hs_hash(peer, data, data_length);
3807
3808     if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
3809         is_ecdsa_client_auth_supported(ctx))
3810       peer->state = DTLS_STATE_WAIT_CERTIFICATEVERIFY; //ecdsa
3811     else
3812       peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC; //psk || ecdh_anon
3813     break;
3814
3815 #ifdef DTLS_ECC
3816   case DTLS_HT_CERTIFICATE_VERIFY:
3817
3818     if (state != DTLS_STATE_WAIT_CERTIFICATEVERIFY) {
3819       return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3820     }
3821
3822     err = check_client_certificate_verify(ctx, peer, data, data_length);
3823     if (err < 0) {
3824       dtls_warn("error in check_client_certificate_verify err: %i\n", err);
3825       return err;
3826     }
3827
3828     update_hs_hash(peer, data, data_length);
3829     peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
3830     break;
3831 #endif /* DTLS_ECC */
3832
3833   case DTLS_HT_CLIENT_HELLO:
3834
3835     if ((peer && state != DTLS_STATE_CONNECTED && state != DTLS_STATE_WAIT_CLIENTHELLO) ||
3836         (!peer && state != DTLS_STATE_WAIT_CLIENTHELLO)) {
3837       return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3838     }
3839
3840     /* When no DTLS state exists for this peer, we only allow a
3841        Client Hello message with
3842
3843        a) a valid cookie, or
3844        b) no cookie.
3845
3846        Anything else will be rejected. Fragementation is not allowed
3847        here as it would require peer state as well.
3848     */
3849     err = dtls_verify_peer(ctx, peer, session, state, data, data_length);
3850     if (err < 0) {
3851       dtls_warn("error in dtls_verify_peer err: %i\n", err);
3852       return err;
3853     }
3854
3855     if (err > 0) {
3856       dtls_debug("server hello verify was sent\n");
3857       break;
3858     }
3859
3860     /* At this point, we have a good relationship with this peer. This
3861      * state is left for re-negotiation of key material. */
3862      /* As per RFC 6347 - section 4.2.8 if this is an attempt to
3863       * rehandshake, we can delete the existing key material
3864       * as the client has demonstrated reachibility by completing
3865       * the cookie exchange */
3866     if (peer && state == DTLS_STATE_WAIT_CLIENTHELLO) {
3867        dtls_debug("removing the peer\n");
3868 #ifndef WITH_CONTIKI
3869        HASH_DEL_PEER(ctx->peers, peer);
3870 #else  /* WITH_CONTIKI */
3871        list_remove(ctx->peers, peer);
3872 #endif /* WITH_CONTIKI */
3873
3874        dtls_free_peer(peer);
3875        peer = NULL;
3876     }
3877     if (!peer) {
3878       dtls_debug("creating new peer\n");
3879       dtls_security_parameters_t *security;
3880
3881       /* msg contains a Client Hello with a valid cookie, so we can
3882        * safely create the server state machine and continue with
3883        * the handshake. */
3884       peer = dtls_new_peer(session);
3885       if (!peer) {
3886         dtls_alert("cannot create peer\n");
3887         return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3888       }
3889       peer->role = DTLS_SERVER;
3890
3891       /* Initialize record sequence number to 1 for new peers. The first
3892        * record with sequence number 0 is a stateless Hello Verify Request.
3893        */
3894       security = dtls_security_params(peer);
3895       security->rseq = 1;
3896       dtls_add_peer(ctx, peer);
3897     }
3898     if (peer && !peer->handshake_params) {
3899       dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
3900
3901       peer->handshake_params = dtls_handshake_new();
3902       if (!peer->handshake_params)
3903         return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3904
3905       LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
3906       peer->handshake_params->hs_state.mseq_r = dtls_uint16_to_int(hs_header->message_seq);
3907       peer->handshake_params->hs_state.mseq_s = 1;
3908     }
3909
3910     clear_hs_hash(peer);
3911
3912     /* First negotiation step: check for PSK
3913      *
3914      * Note that we already have checked that msg is a Handshake
3915      * message containing a ClientHello. dtls_get_cipher() therefore
3916      * does not check again.
3917      */
3918     err = dtls_update_parameters(ctx, peer, data, data_length);
3919     if (err < 0) {
3920       dtls_warn("error updating security parameters\n");
3921       return err;
3922     }
3923
3924     /* update finish MAC */
3925     update_hs_hash(peer, data, data_length);
3926
3927     err = dtls_send_server_hello_msgs(ctx, peer);
3928     if (err < 0) {
3929       return err;
3930     }
3931     if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
3932         is_ecdsa_client_auth_supported(ctx))
3933       peer->state = DTLS_STATE_WAIT_CLIENTCERTIFICATE; //ecdhe
3934     else
3935       peer->state = DTLS_STATE_WAIT_CLIENTKEYEXCHANGE; //psk, ecdh_anon
3936
3937     /* after sending the ServerHelloDone, we expect the
3938      * ClientKeyExchange (possibly containing the PSK id),
3939      * followed by a ChangeCipherSpec and an encrypted Finished.
3940      */
3941
3942     break;
3943
3944   case DTLS_HT_HELLO_REQUEST:
3945
3946     if (state != DTLS_STATE_CONNECTED) {
3947       /* we should just ignore such packets when in handshake */
3948       return 0;
3949     }
3950
3951     if (peer && !peer->handshake_params) {
3952       peer->handshake_params = dtls_handshake_new();
3953       if (!peer->handshake_params)
3954         return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3955
3956       LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
3957       peer->handshake_params->hs_state.mseq_r = 0;
3958       peer->handshake_params->hs_state.mseq_s = 0;
3959     }
3960
3961     /* send ClientHello with empty Cookie */
3962     err = dtls_send_client_hello(ctx, peer, NULL, 0);
3963     if (err < 0) {
3964       dtls_warn("cannot send ClientHello\n");
3965       return err;
3966     }
3967     peer->state = DTLS_STATE_CLIENTHELLO;
3968     break;
3969
3970   default:
3971     dtls_crit("unhandled message %d\n", data[0]);
3972     return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3973   }
3974
3975   if (peer && peer->handshake_params && err >= 0) {
3976     peer->handshake_params->hs_state.mseq_r++;
3977   }
3978
3979   return err;
3980 }
3981       
3982 static int
3983 handle_handshake(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
3984                  const dtls_peer_type role, const dtls_state_t state,
3985                  uint8 *data, size_t data_length)
3986 {
3987   dtls_handshake_header_t *hs_header;
3988   int res;
3989
3990   if (data_length < DTLS_HS_LENGTH) {
3991     dtls_warn("handshake message too short\n");
3992     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3993   }
3994   hs_header = DTLS_HANDSHAKE_HEADER(data);
3995
3996   dtls_debug("received handshake packet of type: %s (%i)\n",
3997              dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
3998
3999   if (!peer || !peer->handshake_params) {
4000     /* This is the initial ClientHello */
4001     if (hs_header->msg_type != DTLS_HT_CLIENT_HELLO && !peer) {
4002       dtls_warn("If there is no peer only ClientHello is allowed\n");
4003       return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
4004     }
4005
4006     /* This is a ClientHello or Hello Request send when doing TLS renegotiation */
4007     if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
4008         hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
4009       return handle_handshake_msg(ctx, peer, session, role, state, data,
4010                                   data_length);
4011     } else {
4012       dtls_warn("ignore unexpected handshake message\n");
4013       return 0;
4014     }
4015   }
4016
4017   if (dtls_uint16_to_int(hs_header->message_seq) < peer->handshake_params->hs_state.mseq_r) {
4018     dtls_warn("The message sequence number is too small, expected %i, got: %i\n",
4019               peer->handshake_params->hs_state.mseq_r, dtls_uint16_to_int(hs_header->message_seq));
4020     return 0;
4021   } else if (dtls_uint16_to_int(hs_header->message_seq) > peer->handshake_params->hs_state.mseq_r) {
4022     /* A packet in between is missing, buffer this packet. */
4023     netq_t *n;
4024
4025     /* TODO: only add packet that are not too new. */
4026     if (data_length > DTLS_MAX_BUF) {
4027       dtls_warn("the packet is too big to buffer for reoder\n");
4028       return 0;
4029     }
4030
4031     netq_t *node = netq_head(peer->handshake_params->reorder_queue);
4032     while (node) {
4033       dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
4034       if (dtls_uint16_to_int(node_header->message_seq) == dtls_uint16_to_int(hs_header->message_seq)) {
4035         dtls_warn("a packet with this sequence number is already stored\n");
4036         return 0;
4037       }
4038       node = netq_next(node);
4039     }
4040
4041     n = netq_node_new(data_length);
4042     if (!n) {
4043       dtls_warn("no space in reoder buffer\n");
4044       return 0;
4045     }
4046
4047     n->peer = peer;
4048     n->length = data_length;
4049     memcpy(n->data, data, data_length);
4050
4051     if (!netq_insert_node(peer->handshake_params->reorder_queue, n)) {
4052       dtls_warn("cannot add packet to reoder buffer\n");
4053       netq_node_free(n);
4054     }
4055     dtls_info("Added packet for reordering\n");
4056     return 0;
4057   } else if (dtls_uint16_to_int(hs_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
4058     /* Found the expected packet, use this and all the buffered packet */
4059     int next = 1;
4060
4061     res = handle_handshake_msg(ctx, peer, session, role, state, data, data_length);
4062     if (res < 0)
4063       return res;
4064
4065     /* We do not know in which order the packet are in the list just search the list for every packet. */
4066     while (next && peer->handshake_params) {
4067       next = 0;
4068       netq_t *node = netq_head(peer->handshake_params->reorder_queue);
4069       while (node) {
4070         dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
4071
4072         if (dtls_uint16_to_int(node_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
4073           netq_remove(peer->handshake_params->reorder_queue, node);
4074           next = 1;
4075           res = handle_handshake_msg(ctx, peer, session, role, peer->state, node->data, node->length);
4076           if (res < 0) {
4077             return res;
4078           }
4079
4080           break;
4081         } else {
4082           node = netq_next(node);
4083         }
4084       }
4085     }
4086     return res;
4087   }
4088   assert(0);
4089   return 0;
4090 }
4091
4092 static int
4093 handle_ccs(dtls_context_t *ctx, dtls_peer_t *peer, 
4094            uint8 *record_header, uint8 *data, size_t data_length)
4095 {
4096   int err;
4097   dtls_handshake_parameters_t *handshake = peer->handshake_params;
4098
4099   /* A CCS message is handled after a KeyExchange message was
4100    * received from the client. When security parameters have been
4101    * updated successfully and a ChangeCipherSpec message was sent
4102    * by ourself, the security context is switched and the record
4103    * sequence number is reset. */
4104   
4105   if (!peer || peer->state != DTLS_STATE_WAIT_CHANGECIPHERSPEC) {
4106     dtls_warn("expected ChangeCipherSpec during handshake\n");
4107     return 0;
4108   }
4109
4110   if (data_length < 1 || data[0] != 1)
4111     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
4112
4113   /* Just change the cipher when we are on the same epoch */
4114   if (peer->role == DTLS_SERVER) {
4115     err = calculate_key_block(ctx, handshake, peer,
4116                               &peer->session, peer->role);
4117     if (err < 0) {
4118       return err;
4119     }
4120   }
4121   
4122   peer->state = DTLS_STATE_WAIT_FINISHED;
4123
4124   return 0;
4125 }  
4126
4127 /** 
4128  * Handles incoming Alert messages. This function returns \c 1 if the
4129  * connection should be closed and the peer is to be invalidated.
4130  */
4131 static int
4132 handle_alert(dtls_context_t *ctx, dtls_peer_t *peer, 
4133              uint8 *record_header, uint8 *data, size_t data_length) {
4134   int free_peer = 0;            /* indicates whether to free peer */
4135
4136   if (data_length < 2)
4137     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
4138
4139   dtls_info("** Alert: level %d, description %d\n", data[0], data[1]);
4140
4141   if (!peer) {
4142     dtls_warn("got an alert for an unknown peer, we probably already removed it, ignore it\n");
4143     return 0;
4144   }
4145
4146   /* The peer object is invalidated for FATAL alerts and close
4147    * notifies. This is done in two steps.: First, remove the object
4148    * from our list of peers. After that, the event handler callback is
4149    * invoked with the still existing peer object. Finally, the storage
4150    * used by peer is released.
4151    */
4152   if (data[0] == DTLS_ALERT_LEVEL_FATAL || data[1] == DTLS_ALERT_CLOSE_NOTIFY) {
4153     dtls_alert("%d invalidate peer\n", data[1]);
4154     
4155 #ifndef WITH_CONTIKI
4156     HASH_DEL_PEER(ctx->peers, peer);
4157 #else /* WITH_CONTIKI */
4158     list_remove(ctx->peers, peer);
4159
4160 #ifndef NDEBUG
4161     PRINTF("removed peer [");
4162     PRINT6ADDR(&peer->session.addr);
4163     PRINTF("]:%d\n", uip_ntohs(peer->session.port));
4164 #endif
4165 #endif /* WITH_CONTIKI */
4166
4167     free_peer = 1;
4168
4169   }
4170
4171   (void)CALL(ctx, event, &peer->session, 
4172              (dtls_alert_level_t)data[0], (unsigned short)data[1]);
4173   switch (data[1]) {
4174   case DTLS_ALERT_CLOSE_NOTIFY:
4175     /* If state is DTLS_STATE_CLOSING, we have already sent a
4176      * close_notify so, do not send that again. */
4177     if (peer->state != DTLS_STATE_CLOSING) {
4178       peer->state = DTLS_STATE_CLOSING;
4179       dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_CLOSE_NOTIFY);
4180     } else
4181       peer->state = DTLS_STATE_CLOSED;
4182     break;
4183   default:
4184     ;
4185   }
4186   
4187   if (free_peer) {
4188     dtls_stop_retransmission(ctx, peer);
4189     dtls_destroy_peer(ctx, peer, 0);
4190   }
4191
4192   return free_peer;
4193 }
4194
4195 static int dtls_alert_send_from_err(dtls_context_t *ctx, dtls_peer_t *peer,
4196                                     session_t *session, int err)
4197 {
4198   int level;
4199   int desc;
4200
4201   if (err < -(1 << 8) && err > -(3 << 8)) {
4202     level = ((-err) & 0xff00) >> 8;
4203     desc = (-err) & 0xff;
4204     if (!peer) {
4205       peer = dtls_get_peer(ctx, session);
4206     }
4207     if (peer) {
4208       peer->state = DTLS_STATE_CLOSING;
4209       return dtls_send_alert(ctx, peer, level, desc);
4210     }
4211   } else if (err == -1) {
4212     if (!peer) {
4213       peer = dtls_get_peer(ctx, session);
4214     }
4215     if (peer) {
4216       peer->state = DTLS_STATE_CLOSING;
4217       return dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_INTERNAL_ERROR);
4218     }
4219   }
4220   return -1;
4221 }
4222
4223 /** 
4224  * Handles incoming data as DTLS message from given peer.
4225  */
4226 int
4227 dtls_handle_message(dtls_context_t *ctx, 
4228                     session_t *session,
4229                     uint8 *msg, int msglen) {
4230   dtls_peer_t *peer = NULL;
4231   unsigned int rlen;            /* record length */
4232   uint8 *data;                  /* (decrypted) payload */
4233   int data_length;              /* length of decrypted payload 
4234                                    (without MAC and padding) */
4235   int err;
4236
4237   /* check if we have DTLS state for addr/port/ifindex */
4238   peer = dtls_get_peer(ctx, session);
4239
4240   if (!peer) {
4241     dtls_debug("dtls_handle_message: PEER NOT FOUND\n");
4242     dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "peer addr", session);
4243   } else {
4244     dtls_debug("dtls_handle_message: FOUND PEER\n");
4245   }
4246
4247   while ((rlen = is_record(msg,msglen))) {
4248     dtls_peer_type role;
4249     dtls_state_t state;
4250
4251     dtls_debug("got packet %d (%d bytes)\n", msg[0], rlen);
4252     if (peer) {
4253       data_length = decrypt_verify(peer, msg, rlen, &data);
4254       if (data_length < 0) {
4255         if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
4256           data = msg + DTLS_RH_LENGTH;
4257           data_length = rlen - DTLS_RH_LENGTH;
4258           state = DTLS_STATE_WAIT_CLIENTHELLO;
4259           role = DTLS_SERVER;       
4260         } else {
4261           int err =  dtls_alert_fatal_create(DTLS_ALERT_DECRYPT_ERROR);
4262           dtls_info("decrypt_verify() failed\n");
4263           if (peer->state < DTLS_STATE_CONNECTED) {
4264             dtls_alert_send_from_err(ctx, peer, &peer->session, err);
4265             peer->state = DTLS_STATE_CLOSED;
4266             /* dtls_stop_retransmission(ctx, peer); */
4267             dtls_destroy_peer(ctx, peer, 1);
4268           }
4269           return err;
4270         }
4271       } else {
4272         role = peer->role;
4273         state = peer->state;
4274       }
4275     } else {
4276       /* is_record() ensures that msg contains at least a record header */
4277       data = msg + DTLS_RH_LENGTH;
4278       data_length = rlen - DTLS_RH_LENGTH;
4279       state = DTLS_STATE_WAIT_CLIENTHELLO;
4280       role = DTLS_SERVER;
4281     }
4282
4283     dtls_debug_hexdump("receive header", msg, sizeof(dtls_record_header_t));
4284     dtls_debug_hexdump("receive unencrypted", data, data_length);
4285
4286     /* Handle received record according to the first byte of the
4287      * message, i.e. the subprotocol. We currently do not support
4288      * combining multiple fragments of one type into a single
4289      * record. */
4290
4291     switch (msg[0]) {
4292
4293     case DTLS_CT_CHANGE_CIPHER_SPEC:
4294       if (peer) {
4295         dtls_stop_retransmission(ctx, peer);
4296       }
4297       err = handle_ccs(ctx, peer, msg, data, data_length);
4298       if (err < 0) {
4299         dtls_warn("error while handling ChangeCipherSpec message\n");
4300         dtls_alert_send_from_err(ctx, peer, session, err);
4301
4302         /* invalidate peer */
4303         dtls_destroy_peer(ctx, peer, 1);
4304         peer = NULL;
4305
4306         return err;
4307       }
4308       break;
4309
4310     case DTLS_CT_ALERT:
4311       if (peer) {
4312         dtls_stop_retransmission(ctx, peer);
4313       }
4314       err = handle_alert(ctx, peer, msg, data, data_length);
4315       if (err < 0 || err == 1) {
4316          dtls_warn("received alert, peer has been invalidated\n");
4317          /* handle alert has invalidated peer */
4318          peer = NULL;
4319          return err < 0 ?err:-1;
4320       }
4321       break;
4322
4323     case DTLS_CT_HANDSHAKE:
4324       /* Handshake messages other than Finish must use the current
4325        * epoch, Finish has epoch + 1. */
4326
4327       if (peer) {
4328         uint16_t expected_epoch = dtls_security_params(peer)->epoch;
4329         uint16_t msg_epoch = 
4330           dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
4331
4332         /* The new security parameters must be used for all messages
4333          * that are sent after the ChangeCipherSpec message. This
4334          * means that the client's Finished message uses epoch + 1
4335          * while the server is still in the old epoch.
4336          */
4337         if (role == DTLS_SERVER && state == DTLS_STATE_WAIT_FINISHED) {
4338           expected_epoch++;
4339         }
4340
4341         if (expected_epoch != msg_epoch) {
4342           if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
4343             state = DTLS_STATE_WAIT_CLIENTHELLO;
4344             role = DTLS_SERVER;
4345           } else {
4346             dtls_warn("Wrong epoch, expected %i, got: %i\n",
4347                     expected_epoch, msg_epoch);
4348             break;
4349           }
4350         }
4351       }
4352
4353       err = handle_handshake(ctx, peer, session, role, state, data, data_length);
4354       if (err < 0) {
4355         dtls_warn("error while handling handshake packet\n");
4356         dtls_alert_send_from_err(ctx, peer, session, err);
4357         return err;
4358       }
4359       if (peer && peer->state == DTLS_STATE_CONNECTED) {
4360         /* stop retransmissions */
4361         dtls_stop_retransmission(ctx, peer);
4362         CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECTED);
4363       }
4364       break;
4365
4366     case DTLS_CT_APPLICATION_DATA:
4367       dtls_info("** application data:\n");
4368       if (!peer) {
4369         dtls_warn("no peer available, send an alert\n");
4370         // TODO: should we send a alert here?
4371         return -1;
4372       }
4373       dtls_stop_retransmission(ctx, peer);
4374       CALL(ctx, read, &peer->session, data, data_length);
4375       break;
4376     default:
4377       dtls_info("dropped unknown message of type %d\n",msg[0]);
4378     }
4379
4380     /* advance msg by length of ciphertext */
4381     msg += rlen;
4382     msglen -= rlen;
4383   }
4384
4385   return 0;
4386 }
4387
4388 dtls_context_t *
4389 dtls_new_context(void *app_data) {
4390   dtls_context_t *c;
4391   dtls_tick_t now;
4392 #ifndef WITH_CONTIKI
4393   FILE *urandom = fopen("/dev/urandom", "r");
4394   unsigned char buf[sizeof(unsigned long)];
4395 #endif /* WITH_CONTIKI */
4396
4397   dtls_ticks(&now);
4398 #ifdef WITH_CONTIKI
4399   /* FIXME: need something better to init PRNG here */
4400   dtls_prng_init(now);
4401 #else /* WITH_CONTIKI */
4402   if (!urandom) {
4403     dtls_emerg("cannot initialize PRNG\n");
4404     return NULL;
4405   }
4406
4407   if (fread(buf, 1, sizeof(buf), urandom) != sizeof(buf)) {
4408     dtls_emerg("cannot initialize PRNG\n");
4409     return NULL;
4410   }
4411
4412   fclose(urandom);
4413   dtls_prng_init((unsigned long)*buf);
4414 #endif /* WITH_CONTIKI */
4415
4416   c = malloc_context();
4417   if (!c)
4418     goto error;
4419
4420   memset(c, 0, sizeof(dtls_context_t));
4421   c->app = app_data;
4422   
4423   LIST_STRUCT_INIT(c, sendqueue);
4424
4425 #ifdef WITH_CONTIKI
4426   LIST_STRUCT_INIT(c, peers);
4427   /* LIST_STRUCT_INIT(c, key_store); */
4428   
4429   process_start(&dtls_retransmit_process, (char *)c);
4430   PROCESS_CONTEXT_BEGIN(&dtls_retransmit_process);
4431   /* the retransmit timer must be initialized to some large value */
4432   etimer_set(&c->retransmit_timer, 0xFFFF);
4433   PROCESS_CONTEXT_END(&coap_retransmit_process);
4434 #endif /* WITH_CONTIKI */
4435
4436   if (dtls_prng(c->cookie_secret, DTLS_COOKIE_SECRET_LENGTH))
4437     c->cookie_secret_age = now;
4438   else 
4439     goto error;
4440   
4441   return c;
4442
4443  error:
4444   dtls_alert("cannot create DTLS context\n");
4445   if (c)
4446     dtls_free_context(c);
4447   return NULL;
4448 }
4449
4450 void
4451 dtls_free_context(dtls_context_t *ctx) {
4452   dtls_peer_t *p;
4453
4454   if (!ctx) {
4455     return;
4456   }
4457
4458 #ifndef WITH_CONTIKI
4459   dtls_peer_t *tmp;
4460
4461   if (ctx->peers) {
4462     HASH_ITER(hh, ctx->peers, p, tmp) {
4463       dtls_destroy_peer(ctx, p, 1);
4464     }
4465   }
4466 #else /* WITH_CONTIKI */
4467   for (p = list_head(ctx->peers); p; p = list_item_next(p))
4468     dtls_destroy_peer(ctx, p, 1);
4469 #endif /* WITH_CONTIKI */
4470
4471   free_context(ctx);
4472 }
4473
4474 int
4475 dtls_connect_peer(dtls_context_t *ctx, dtls_peer_t *peer) {
4476   int res;
4477
4478   assert(peer);
4479   if (!peer)
4480     return -1;
4481
4482   /* check if the same peer is already in our list */
4483   if (peer == dtls_get_peer(ctx, &peer->session)) {
4484     dtls_debug("found peer, try to re-connect\n");
4485     return dtls_renegotiate(ctx, &peer->session);
4486   }
4487     
4488   /* set local peer role to client, remote is server */
4489   peer->role = DTLS_CLIENT;
4490
4491   dtls_add_peer(ctx, peer);
4492
4493   /* send ClientHello with empty Cookie */
4494   peer->handshake_params = dtls_handshake_new();
4495       if (!peer->handshake_params)
4496         return -1;
4497
4498   peer->handshake_params->hs_state.mseq_r = 0;
4499   peer->handshake_params->hs_state.mseq_s = 0;
4500   LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
4501   res = dtls_send_client_hello(ctx, peer, NULL, 0);
4502   if (res < 0)
4503     dtls_warn("cannot send ClientHello\n");
4504   else 
4505     peer->state = DTLS_STATE_CLIENTHELLO;
4506
4507   return res;
4508 }
4509
4510 int
4511 dtls_connect(dtls_context_t *ctx, const session_t *dst) {
4512   dtls_peer_t *peer;
4513   int res;
4514
4515   peer = dtls_get_peer(ctx, dst);
4516   
4517   if (!peer)
4518     peer = dtls_new_peer(dst);
4519
4520   if (!peer) {
4521     dtls_crit("cannot create new peer\n");
4522     return -1;
4523   }
4524
4525   res = dtls_connect_peer(ctx, peer);
4526
4527   /* Invoke event callback to indicate connection attempt or
4528    * re-negotiation. */
4529   if (res > 0) {
4530     CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECT);
4531   } else if (res == 0) {
4532     CALL(ctx, event, &peer->session, 0, DTLS_EVENT_RENEGOTIATE);
4533   }
4534   
4535   return res;
4536 }
4537
4538 static void
4539 dtls_retransmit(dtls_context_t *context, netq_t *node) {
4540   if (!context || !node)
4541     return;
4542
4543   /* re-initialize timeout when maximum number of retransmissions are not reached yet */
4544   if (node->retransmit_cnt < DTLS_DEFAULT_MAX_RETRANSMIT) {
4545       unsigned char sendbuf[DTLS_MAX_BUF];
4546       size_t len = sizeof(sendbuf);
4547       int err;
4548       unsigned char *data = node->data;
4549       size_t length = node->length;
4550       dtls_tick_t now;
4551       dtls_security_parameters_t *security = dtls_security_params_epoch(node->peer, node->epoch);
4552
4553       dtls_ticks(&now);
4554       node->retransmit_cnt++;
4555       node->t = now + (node->timeout << node->retransmit_cnt);
4556       netq_insert_node(context->sendqueue, node);
4557       
4558       if (node->type == DTLS_CT_HANDSHAKE) {
4559         dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
4560
4561         dtls_debug("** retransmit handshake packet of type: %s (%i)\n",
4562                    dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
4563       } else {
4564         dtls_debug("** retransmit packet\n");
4565       }
4566       
4567       err = dtls_prepare_record(node->peer, security, node->type, &data, &length,
4568                                 1, sendbuf, &len);
4569       if (err < 0) {
4570         dtls_warn("can not retransmit packet, err: %i\n", err);
4571         return;
4572       }
4573       dtls_debug_hexdump("retransmit header", sendbuf,
4574                          sizeof(dtls_record_header_t));
4575       dtls_debug_hexdump("retransmit unencrypted", node->data, node->length);
4576
4577       (void)CALL(context, write, &node->peer->session, sendbuf, len);
4578       return;
4579   }
4580
4581   /* no more retransmissions, remove node from system */
4582   
4583   dtls_debug("** removed transaction\n");
4584
4585   /* And finally delete the node */
4586   netq_node_free(node);
4587 }
4588
4589 static void
4590 dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer) {
4591   netq_t *node;
4592   node = list_head(context->sendqueue); 
4593
4594   while (node) {
4595     if (dtls_session_equals(&node->peer->session, &peer->session)) {
4596       netq_t *tmp = node;
4597       node = list_item_next(node);
4598       list_remove(context->sendqueue, tmp);
4599       netq_node_free(tmp);
4600     } else
4601       node = list_item_next(node);    
4602   }
4603 }
4604
4605 void
4606 dtls_check_retransmit(dtls_context_t *context, clock_time_t *next) {
4607   dtls_tick_t now;
4608   netq_t *node = netq_head(context->sendqueue);
4609
4610   dtls_ticks(&now);
4611   while (node && node->t <= now) {
4612     netq_pop_first(context->sendqueue);
4613     dtls_retransmit(context, node);
4614     node = netq_head(context->sendqueue);
4615   }
4616
4617   if (next && node)
4618     *next = node->t;
4619 }
4620
4621 size_t
4622 dtls_prf_with_current_keyblock(dtls_context_t *ctx, session_t *session,
4623                                const uint8_t* label, const uint32_t labellen,
4624                                const uint8_t* random1, const uint32_t random1len,
4625                                const uint8_t* random2, const uint32_t random2len,
4626                                uint8_t* buf, const uint32_t buflen) {
4627   dtls_peer_t *peer = NULL;
4628   dtls_security_parameters_t *security = NULL;
4629   size_t keysize = 0;
4630
4631   if(!ctx || !session || !label || !buf || labellen == 0 || buflen == 0) {
4632     dtls_warn("dtls_prf_with_current_keyblock(): invalid parameter\n");
4633     return 0;
4634   }
4635
4636   peer = dtls_get_peer(ctx, session);
4637   if (!peer) {
4638     dtls_warn("dtls_prf_with_current_keyblock(): cannot find peer\n");
4639     return 0;
4640   }
4641
4642   security = dtls_security_params(peer);
4643   if (!security) {
4644     dtls_crit("dtls_prf_with_current_keyblock(): peer has empty security parameters\n");
4645     return 0;
4646   }
4647
4648   /* note that keysize should never be zero as bad things will happen */
4649   keysize = dtls_kb_size(security, peer->role);
4650   assert(keysize > 0);
4651
4652   return dtls_prf(security->key_block, keysize,
4653                   label, labellen,
4654                   random1, random1len,
4655                   random2, random2len,
4656                   buf, buflen);
4657 }
4658
4659 #ifdef WITH_CONTIKI
4660 /*---------------------------------------------------------------------------*/
4661 /* message retransmission */
4662 /*---------------------------------------------------------------------------*/
4663 PROCESS_THREAD(dtls_retransmit_process, ev, data)
4664 {
4665   clock_time_t now;
4666   netq_t *node;
4667
4668   PROCESS_BEGIN();
4669
4670   dtls_debug("Started DTLS retransmit process\r\n");
4671
4672   while(1) {
4673     PROCESS_YIELD();
4674     if (ev == PROCESS_EVENT_TIMER) {
4675       if (etimer_expired(&the_dtls_context.retransmit_timer)) {
4676         
4677         node = list_head(the_dtls_context.sendqueue);
4678         
4679         now = clock_time();
4680         if (node && node->t <= now) {
4681           dtls_retransmit(&the_dtls_context, list_pop(the_dtls_context.sendqueue));
4682           node = list_head(the_dtls_context.sendqueue);
4683         }
4684
4685         /* need to set timer to some value even if no nextpdu is available */
4686         if (node) {
4687           etimer_set(&the_dtls_context.retransmit_timer, 
4688                      node->t <= now ? 1 : node->t - now);
4689         } else {
4690           etimer_set(&the_dtls_context.retransmit_timer, 0xFFFF);
4691         }
4692       } 
4693     }
4694   }
4695   
4696   PROCESS_END();
4697 }
4698 #endif /* WITH_CONTIKI */