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