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