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