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