Merge branch 'security-summit' into 'master'
[platform/upstream/iotivity.git] / extlibs / tinydtls / dtls.h
1 /* dtls -- a very basic DTLS implementation
2  *
3  * Copyright (C) 2011--2013 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 /**
28  * @file dtls.h
29  * @brief High level DTLS API and visible structures. 
30  */
31
32 #ifndef _DTLS_DTLS_H_
33 #define _DTLS_DTLS_H_
34
35 #include <stdint.h>
36
37 #include "t_list.h"
38 #include "state.h"
39 #include "peer.h"
40
41 #ifndef WITH_CONTIKI
42 #include "uthash.h"
43 #include "t_list.h"
44 #endif /* WITH_CONTIKI */
45
46 #include "alert.h"
47 #include "crypto.h"
48 #include "hmac.h"
49
50 #include "global.h"
51 #include "dtls_time.h"
52
53 #ifndef DTLSv12
54 #define DTLS_VERSION 0xfeff     /* DTLS v1.1 */
55 #else
56 #define DTLS_VERSION 0xfefd     /* DTLS v1.2 */
57 #endif
58
59 #ifdef DTLS_X509
60 #define DTLS_MAX_CERT_SIZE       1400
61 #endif
62
63 typedef enum dtls_credentials_type_t {
64   DTLS_PSK_HINT, DTLS_PSK_IDENTITY, DTLS_PSK_KEY
65 } dtls_credentials_type_t;
66
67 typedef struct dtls_ecc_key_t {
68   dtls_ecdh_curve curve;
69   const unsigned char *priv_key;        /** < private key as bytes > */
70   const unsigned char *pub_key_x;       /** < x part of the public key for the given private key > */
71   const unsigned char *pub_key_y;       /** < y part of the public key for the given private key > */
72 } dtls_ecc_key_t;
73
74 /** Length of the secret that is used for generating Hello Verify cookies. */
75 #define DTLS_COOKIE_SECRET_LENGTH 12
76
77 struct dtls_context_t;
78
79 /**
80  * This structure contains callback functions used by tinydtls to
81  * communicate with the application. At least the write function must
82  * be provided. It is called by the DTLS state machine to send packets
83  * over the network. The read function is invoked to deliver decrypted
84  * and verfified application data. The third callback is an event
85  * handler function that is called when alert messages are encountered
86  * or events generated by the library have occured.
87  */ 
88 typedef struct {
89   /** 
90    * Called from dtls_handle_message() to send DTLS packets over the
91    * network. The callback function must use the network interface
92    * denoted by session->ifindex to send the data.
93    *
94    * @param ctx  The current DTLS context.
95    * @param session The session object, including the address of the
96    *              remote peer where the data shall be sent.
97    * @param buf  The data to send.
98    * @param len  The actual length of @p buf.
99    * @return The callback function must return the number of bytes 
100    *         that were sent, or a value less than zero to indicate an 
101    *         error.
102    */
103   int (*write)(struct dtls_context_t *ctx, 
104                session_t *session, uint8 *buf, size_t len);
105
106   /** 
107    * Called from dtls_handle_message() deliver application data that was 
108    * received on the given session. The data is delivered only after
109    * decryption and verification have succeeded. 
110    *
111    * @param ctx  The current DTLS context.
112    * @param session The session object, including the address of the
113    *              data's origin. 
114    * @param buf  The received data packet.
115    * @param len  The actual length of @p buf.
116    * @return ignored
117    */
118   int (*read)(struct dtls_context_t *ctx, 
119                session_t *session, uint8 *buf, size_t len);
120
121   /**
122    * The event handler is called when a message from the alert
123    * protocol is received or the state of the DTLS session changes.
124    *
125    * @param ctx     The current dtls context.
126    * @param session The session object that was affected.
127    * @param level   The alert level or @c 0 when an event ocurred that 
128    *                is not an alert. 
129    * @param code    Values less than @c 256 indicate alerts, while
130    *                @c 256 or greater indicate internal DTLS session changes.
131    * @return ignored
132    */
133   int (*event)(struct dtls_context_t *ctx, session_t *session, 
134                 dtls_alert_level_t level, unsigned short code);
135
136 #ifdef DTLS_PSK
137   /**
138    * Called during handshake to get information related to the
139    * psk key exchange. The type of information requested is
140    * indicated by @p type which will be one of DTLS_PSK_HINT,
141    * DTLS_PSK_IDENTITY, or DTLS_PSK_KEY. The called function
142    * must store the requested item in the buffer @p result of
143    * size @p result_length. On success, the function must return
144    * the actual number of bytes written to @p result, of a
145    * value less than zero on error. The parameter @p desc may
146    * contain additional request information (e.g. the psk_identity
147    * for which a key is requested when @p type == @c DTLS_PSK_KEY.
148    *
149    * @param ctx     The current dtls context.
150    * @param session The session where the key will be used.
151    * @param type    The type of the requested information.
152    * @param desc    Additional request information
153    * @param desc_len The actual length of desc.
154    * @param result  Must be filled with the requested information.
155    * @param result_length  Maximum size of @p result.
156    * @return The number of bytes written to @p result or a value
157    *         less than zero on error.
158    */
159   int (*get_psk_info)(struct dtls_context_t *ctx,
160                       const session_t *session,
161                       dtls_credentials_type_t type,
162                       const unsigned char *desc, size_t desc_len,
163                       unsigned char *result, size_t result_length);
164
165 #endif /* DTLS_PSK */
166
167 #ifdef DTLS_ECC
168   /**
169    * Called during handshake to get the server's or client's ecdsa
170    * key used to authenticate this server or client in this 
171    * session. If found, the key must be stored in @p result and 
172    * the return value must be @c 0. If not found, @p result is 
173    * undefined and the return value must be less than zero.
174    *
175    * If ECDSA should not be supported, set this pointer to NULL.
176    *
177    * Implement this if you want to provide your own certificate to 
178    * the other peer. This is mandatory for a server providing ECDSA
179    * support and optional for a client. A client doing DTLS client
180    * authentication has to implementing this callback.
181    *
182    * @param ctx     The current dtls context.
183    * @param session The session where the key will be used.
184    * @param result  Must be set to the key object to used for the given
185    *                session.
186    * @return @c 0 if result is set, or less than zero on error.
187    */
188   int (*get_ecdsa_key)(struct dtls_context_t *ctx,
189                        const session_t *session,
190                        const dtls_ecc_key_t **result);
191
192
193   /**
194    * Called during handshake to check the peer's pubic key in this
195    * session. If the public key matches the session and should be
196    * considerated valid the return value must be @c 0. If not valid,
197    * the return value must be less than zero.
198    *
199    * If ECDSA should not be supported, set this pointer to NULL.
200    *
201    * Implement this if you want to verify the other peers public key.
202    * This is mandatory for a DTLS client doing based ECDSA
203    * authentication. A server implementing this will request the
204    * client to do DTLS client authentication.
205    *
206    * @param ctx          The current dtls context.
207    * @param session      The session where the key will be used.
208    * @param other_pub_x  x component of the public key.
209    * @param other_pub_y  y component of the public key.
210    * @return @c 0 if public key matches, or less than zero on error.
211    * error codes:
212    *   return dtls_alert_fatal_create(DTLS_ALERT_BAD_CERTIFICATE);
213    *   return dtls_alert_fatal_create(DTLS_ALERT_UNSUPPORTED_CERTIFICATE);
214    *   return dtls_alert_fatal_create(DTLS_ALERT_CERTIFICATE_REVOKED);
215    *   return dtls_alert_fatal_create(DTLS_ALERT_CERTIFICATE_EXPIRED);
216    *   return dtls_alert_fatal_create(DTLS_ALERT_CERTIFICATE_UNKNOWN);
217    *   return dtls_alert_fatal_create(DTLS_ALERT_UNKNOWN_CA);
218    */
219   int (*verify_ecdsa_key)(struct dtls_context_t *ctx,
220                           const session_t *session,
221                           const unsigned char *other_pub_x,
222                           const unsigned char *other_pub_y,
223                           size_t key_size);
224 #endif /* DTLS_ECC */
225 #ifdef DTLS_X509
226   /**
227    * Called during handshake to get the server's or client's ecdsa
228    * key used to authenticate this server or client in this
229    * session. If found, the key must be stored in @p result and
230    * the return value must be @c 0. If not found, @p result is
231    * undefined and the return value must be less than zero.
232    *
233    * If ECDSA should not be supported, set this pointer to NULL.
234    *
235    * Implement this if you want to provide your own certificate to
236    * the other peer. This is mandatory for a server providing X.509
237    * support and optional for a client. A client doing DTLS client
238    * authentication has to implementing this callback.
239    *
240    * @param ctx     The current dtls context.
241    * @param session The session where the key will be used.
242    * @param result  Must be set to the key object to used for the given
243    *                session.
244    * @return @c 0 if result is set, or less than zero on error.
245    */
246   int (*get_x509_key)(struct dtls_context_t *ctx,
247                const session_t *session,
248                const dtls_ecc_key_t **result);
249   /**
250    * Called during handshake to get the server's or client's
251    * certificate used to authenticate this server or client in this
252    * session. If found, the certificate must be stored in @p cert and
253    * the return value must be @c 0. If not found, @p cert is
254    * undefined and the return value must be less than zero.
255    *
256    * If X.509 should not be supported, set this pointer to NULL.
257    *
258    * Implement this if you want to provide your own certificate to
259    * the other peer. This is mandatory for a server providing X.509
260    * support and optional for a client. A client doing DTLS client
261    * authentication has to implementing this callback.
262    *
263    * @param ctx       The current dtls context.
264    * @param session   The session where the certificate will be used.
265    * @param cert      Must be set to the certificate object to used for
266    *                  the given session.
267    * @param cert_size Size of certificate in bytes.
268    * @return @c 0 if result is set, or less than zero on error.
269    */
270   int (*get_x509_cert)(struct dtls_context_t *ctx,
271                         const session_t *session,
272                         const unsigned char **cert,
273                         size_t *cert_size);
274
275   /**
276    * Called during handshake to check the peer's certificate in this
277    * session. If the certificate matches the session and is valid the
278    * return value must be @c 0. If not valid, the return value must be
279    * less than zero.
280    *
281    * If X.509 should not be supported, set this pointer to NULL.
282    *
283    * Implement this if you want to verify the other peers certificate.
284    * This is mandatory for a DTLS client doing based X.509
285    * authentication. A server implementing this will request the
286    * client to do DTLS client authentication.
287    *
288    * @param ctx       The current dtls context.
289    * @param session   The session where the key will be used.
290    * @param cert      Peer's certificate to check.
291    * @param cert_size Size of certificate in bytes.
292    * @param x         Allocated memory to store peer's public key part x.
293    * @param x_size    Size of allocated memory to store peer's public key part x.
294    * @param y         Allocated memory to store peer's public key part y.
295    * @param y_size    Size of allocated memory to store peer's public key part y.
296    * @return @c 0 if public key matches, or less than zero on error.
297    * error codes:
298    *   return dtls_alert_fatal_create(DTLS_ALERT_BAD_CERTIFICATE);
299    *   return dtls_alert_fatal_create(DTLS_ALERT_UNSUPPORTED_CERTIFICATE);
300    *   return dtls_alert_fatal_create(DTLS_ALERT_CERTIFICATE_REVOKED);
301    *   return dtls_alert_fatal_create(DTLS_ALERT_CERTIFICATE_EXPIRED);
302    *   return dtls_alert_fatal_create(DTLS_ALERT_CERTIFICATE_UNKNOWN);
303    *   return dtls_alert_fatal_create(DTLS_ALERT_UNKNOWN_CA);
304    */
305   int (*verify_x509_cert)(struct dtls_context_t *ctx,
306                            const session_t *session,
307                            const unsigned char *cert,
308                            size_t cert_size,
309                unsigned char *x,
310                            size_t x_size,
311                unsigned char *y,
312                            size_t y_size);
313
314   /**
315    * Called during handshake to check if certificate format should be X.509
316    *
317    * If X.509 should not be supported, set this pointer to NULL.
318    *
319    * @param ctx       The current dtls context.
320    * @return @c 0 if certificate format should be X.509, or less than zero on error.
321    */
322   int (*is_x509_active)(struct dtls_context_t *ctx);
323 #endif /* DTLS_X509 */
324 } dtls_handler_t;
325
326 /** Holds global information of the DTLS engine. */
327 typedef struct dtls_context_t {
328   unsigned char cookie_secret[DTLS_COOKIE_SECRET_LENGTH];
329   clock_time_t cookie_secret_age; /**< the time the secret has been generated */
330
331 #ifndef WITH_CONTIKI
332   dtls_peer_t *peers;           /**< peer hash map */
333 #else /* WITH_CONTIKI */
334   LIST_STRUCT(peers);
335
336   struct etimer retransmit_timer; /**< fires when the next packet must be sent */
337 #endif /* WITH_CONTIKI */
338
339   LIST_STRUCT(sendqueue);       /**< the packets to send */
340
341   void *app;                    /**< application-specific data */
342
343   dtls_handler_t *h;            /**< callback handlers */
344
345   dtls_cipher_enable_t is_anon_ecdh_eabled;    /**< enable/disable the TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 */
346
347   dtls_cipher_t selected_cipher; /**< selected ciper suite for handshake */
348
349   unsigned char readbuf[DTLS_MAX_BUF];
350 } dtls_context_t;
351
352 /** 
353  * This function initializes the tinyDTLS memory management and must
354  * be called first.
355  */
356 void dtls_init();
357
358 /** 
359  * Creates a new context object. The storage allocated for the new
360  * object must be released with dtls_free_context(). */
361 dtls_context_t *dtls_new_context(void *app_data);
362
363 /** Releases any storage that has been allocated for \p ctx. */
364 void dtls_free_context(dtls_context_t *ctx);
365
366 #define dtls_set_app_data(CTX,DATA) ((CTX)->app = (DATA))
367 #define dtls_get_app_data(CTX) ((CTX)->app)
368
369 /** Sets the callback handler object for @p ctx to @p h. */
370 static inline void dtls_set_handler(dtls_context_t *ctx, dtls_handler_t *h) {
371   ctx->h = h;
372 }
373
374  /**
375   * @brief Enabling the TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256
376   *
377   * @param ctx              The DTLS context to use.
378   * @param is_enable    DTLS_CIPHER_ENABLE(1) or DTLS_CIPHER_DISABLE(0)
379   */
380 void dtls_enables_anon_ecdh(dtls_context_t* ctx, dtls_cipher_enable_t is_enable);
381
382 /**
383  * @brief Select the cipher suite for handshake
384  *
385  * @param ctx              The DTLS context to use.
386  * @param cipher         TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 (0xC018)
387  *                                  TLS_PSK_WITH_AES_128_CCM_8 (0xX0A8)
388  *                                  TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 (0xC0AE)
389  */
390 void dtls_select_cipher(dtls_context_t* ctx, const dtls_cipher_t cipher);
391
392 /**
393  * Establishes a DTLS channel with the specified remote peer @p dst.
394  * This function returns @c 0 if that channel already exists, a value
395  * greater than zero when a new ClientHello message was sent, and
396  * a value less than zero on error.
397  *
398  * @param ctx    The DTLS context to use.
399  * @param dst    The remote party to connect to.
400  * @return A value less than zero on error, greater or equal otherwise.
401  */
402 int dtls_connect(dtls_context_t *ctx, const session_t *dst);
403
404 /**
405  * Establishes a DTLS channel with the specified remote peer.
406  * This function returns @c 0 if that channel already exists, a value
407  * greater than zero when a new ClientHello message was sent, and
408  * a value less than zero on error.
409  *
410  * @param ctx    The DTLS context to use.
411  * @param peer   The peer object that describes the session.
412  * @return A value less than zero on error, greater or equal otherwise.
413  */
414 int dtls_connect_peer(dtls_context_t *ctx, dtls_peer_t *peer);
415
416 /**
417  * Closes the DTLS connection associated with @p remote. This function
418  * returns zero on success, and a value less than zero on error.
419  */
420 int dtls_close(dtls_context_t *ctx, const session_t *remote);
421
422 int dtls_renegotiate(dtls_context_t *ctx, const session_t *dst);
423
424 /** 
425  * Writes the application data given in @p buf to the peer specified
426  * by @p session. 
427  * 
428  * @param ctx      The DTLS context to use.
429  * @param session  The remote transport address and local interface.
430  * @param buf      The data to write.
431  * @param len      The actual length of @p data.
432  * 
433  * @return The number of bytes written or @c -1 on error.
434  */
435 int dtls_write(struct dtls_context_t *ctx, session_t *session, 
436                uint8 *buf, size_t len);
437
438 /**
439  * Checks sendqueue of given DTLS context object for any outstanding
440  * packets to be transmitted. 
441  *
442  * @param context The DTLS context object to use.
443  * @param next    If not NULL, @p next is filled with the timestamp
444  *  of the next scheduled retransmission, or @c 0 when no packets are
445  *  waiting.
446  */
447 void dtls_check_retransmit(dtls_context_t *context, clock_time_t *next);
448
449 #define DTLS_COOKIE_LENGTH 16
450
451 #define DTLS_CT_CHANGE_CIPHER_SPEC 20
452 #define DTLS_CT_ALERT              21
453 #define DTLS_CT_HANDSHAKE          22
454 #define DTLS_CT_APPLICATION_DATA   23
455
456 /** Generic header structure of the DTLS record layer. */
457 typedef struct __attribute__((__packed__)) {
458   uint8 content_type;           /**< content type of the included message */
459   uint16 version;               /**< Protocol version */
460   uint16 epoch;                 /**< counter for cipher state changes */
461   uint48 sequence_number;       /**< sequence number */
462   uint16 length;                /**< length of the following fragment */
463   /* fragment */
464 } dtls_record_header_t;
465
466 /* Handshake types */
467
468 #define DTLS_HT_HELLO_REQUEST        0
469 #define DTLS_HT_CLIENT_HELLO         1
470 #define DTLS_HT_SERVER_HELLO         2
471 #define DTLS_HT_HELLO_VERIFY_REQUEST 3
472 #define DTLS_HT_CERTIFICATE         11
473 #define DTLS_HT_SERVER_KEY_EXCHANGE 12
474 #define DTLS_HT_CERTIFICATE_REQUEST 13
475 #define DTLS_HT_SERVER_HELLO_DONE   14
476 #define DTLS_HT_CERTIFICATE_VERIFY  15
477 #define DTLS_HT_CLIENT_KEY_EXCHANGE 16
478 #define DTLS_HT_FINISHED            20
479
480 /** Header structure for the DTLS handshake protocol. */
481 typedef struct __attribute__((__packed__)) {
482   uint8 msg_type; /**< Type of handshake message  (one of DTLS_HT_) */
483   uint24 length;  /**< length of this message */
484   uint16 message_seq;   /**< Message sequence number */
485   uint24 fragment_offset;       /**< Fragment offset. */
486   uint24 fragment_length;       /**< Fragment length. */
487   /* body */
488 } dtls_handshake_header_t;
489
490 /** Structure of the Client Hello message. */
491 typedef struct __attribute__((__packed__)) {
492   uint16 version;         /**< Client version */
493   uint32 gmt_random;      /**< GMT time of the random byte creation */
494   unsigned char random[28];     /**< Client random bytes */
495   /* session id (up to 32 bytes) */
496   /* cookie (up to 32 bytes) */
497   /* cipher suite (2 to 2^16 -1 bytes) */
498   /* compression method */
499 } dtls_client_hello_t;
500
501 /** Structure of the Hello Verify Request. */
502 typedef struct __attribute__((__packed__)) {
503   uint16 version;               /**< Server version */
504   uint8 cookie_length;  /**< Length of the included cookie */
505   uint8 cookie[];               /**< up to 32 bytes making up the cookie */
506 } dtls_hello_verify_t;  
507
508 #if 0
509 /** 
510  * Checks a received DTLS record for consistency and eventually decrypt,
511  * verify, decompress and reassemble the contained fragment for 
512  * delivery to high-lever clients. 
513  * 
514  * \param state The DTLS record state for the current session. 
515  * \param 
516  */
517 int dtls_record_read(dtls_state_t *state, uint8 *msg, int msglen);
518 #endif
519
520 /** 
521  * Handles incoming data as DTLS message from given peer.
522  *
523  * @param ctx     The dtls context to use.
524  * @param session The current session
525  * @param msg     The received data
526  * @param msglen  The actual length of @p msg.
527  * @return A value less than zero on error, zero on success.
528  */
529 int dtls_handle_message(dtls_context_t *ctx, session_t *session,
530                         uint8 *msg, int msglen);
531
532 /**
533  * Check if @p session is associated with a peer object in @p context.
534  * This function returns a pointer to the peer if found, NULL otherwise.
535  *
536  * @param context  The DTLS context to search.
537  * @param session  The remote address and local interface
538  * @return A pointer to the peer associated with @p session or NULL if
539  *  none exists.
540  */
541 dtls_peer_t *dtls_get_peer(const dtls_context_t *context,
542                            const session_t *session);
543
544 /**
545 * Invokes the DTLS PRF using the current key block for @p session as
546 * key and @p label + @p random1 + @p random2 as its input. This function
547 * writes upto @p buflen bytes into the given output buffer @p buf.
548 *
549 * @param ctx The dtls context to use.
550 * @param session The session whose key shall be used.
551 * @param label A PRF label.
552 * @param labellen Actual length of @p label.
553 * @param random1 Random seed.
554 * @param random1len Actual length of @p random1 (may be zero).
555 * @param random2 Random seed.
556 * @param random2len Actual length of @p random2 (may be zero).
557 * @param buf Output buffer for generated random data.
558 * @param buflen Maximum size of @p buf.
559 *
560 * @return The actual number of bytes written to @p buf or @c 0 on error.
561 */
562 size_t dtls_prf_with_current_keyblock(dtls_context_t *ctx, session_t *session,
563                                       const uint8_t* label, const uint32_t labellen,
564                                       const uint8_t* random1, const uint32_t random1len,
565                                       const uint8_t* random2, const uint32_t random2len,
566                                       uint8_t* buf, const uint32_t buflen);
567
568
569 #endif /* _DTLS_DTLS_H_ */
570
571 /**
572  * @mainpage 
573  *
574  * @author Olaf Bergmann, TZI Uni Bremen
575  *
576  * This library provides a very simple datagram server with DTLS
577  * support. It is designed to support session multiplexing in
578  * single-threaded applications and thus targets specifically on
579  * embedded systems.
580  *
581  * @section license License
582  *
583  * This software is under the <a 
584  * href="http://www.opensource.org/licenses/mit-license.php">MIT License</a>.
585  * 
586  * @subsection uthash UTHash
587  *
588  * This library uses <a href="http://uthash.sourceforge.net/">uthash</a> to manage
589  * its peers (not used for Contiki). @b uthash uses the <b>BSD revised license</b>, see
590  * <a href="http://uthash.sourceforge.net/license.html">http://uthash.sourceforge.net/license.html</a>.
591  *
592  * @subsection sha256 Aaron D. Gifford's SHA256 Implementation
593  *
594  * tinyDTLS provides HMAC-SHA256 with BSD-licensed code from Aaron D. Gifford, 
595  * see <a href="http://www.aarongifford.com/">www.aarongifford.com</a>.
596  *
597  * @subsection aes Rijndael Implementation From OpenBSD
598  *
599  * The AES implementation is taken from rijndael.{c,h} contained in the crypto 
600  * sub-system of the OpenBSD operating system. It is copyright by Vincent Rijmen, *
601  * Antoon Bosselaers and Paulo Barreto. See <a 
602  * href="http://www.openbsd.org/cgi-bin/cvsweb/src/sys/crypto/rijndael.c">rijndael.c</a> 
603  * for License info.
604  *
605  * @section download Getting the Files
606  *
607  * You can get the sources either from the <a 
608  * href="http://sourceforge.net/projects/tinydtls/files">downloads</a> section or 
609  * through git from the <a 
610  * href="http://sourceforge.net/projects/tinydtls/develop">project develop page</a>.
611  *
612  * @section config Configuration
613  *
614  * Use @c configure to set up everything for a successful build. For Contiki, use the
615  * option @c --with-contiki.
616  *
617  * @section build Building
618  *
619  * After configuration, just type 
620  * @code
621 make
622  * @endcode
623  * optionally followed by
624  * @code
625 make install
626  * @endcode
627  * The Contiki version is integrated with the Contiki build system, hence you do not
628  * need to invoke @c make explicitely. Just add @c tinydtls to the variable @c APPS
629  * in your @c Makefile.
630  *
631  * @addtogroup dtls_usage DTLS Usage
632  *
633  * @section dtls_server_example DTLS Server Example
634  *
635  * This section shows how to use the DTLS library functions to setup a 
636  * simple secure UDP echo server. The application is responsible for the
637  * entire network communication and thus will look like a usual UDP
638  * server with socket creation and binding and a typical select-loop as
639  * shown below. The minimum configuration required for DTLS is the 
640  * creation of the dtls_context_t using dtls_new_context(), and a callback
641  * for sending data. Received packets are read by the application and
642  * passed to dtls_handle_message() as shown in @ref dtls_read_cb. 
643  * For any useful communication to happen, read and write call backs 
644  * and a key management function should be registered as well. 
645  * 
646  * @code 
647  dtls_context_t *the_context = NULL;
648  int fd, result;
649
650  static dtls_handler_t cb = {
651    .write = send_to_peer,
652    .read  = read_from_peer,
653    .event = NULL,
654    .get_psk_key = get_psk_key
655  };
656
657  fd = socket(...);
658  if (fd < 0 || bind(fd, ...) < 0)
659    exit(-1);
660
661  the_context = dtls_new_context(&fd);
662  dtls_set_handler(the_context, &cb);
663
664  while (1) {
665    ...initialize fd_set rfds and timeout ...
666    result = select(fd+1, &rfds, NULL, 0, NULL);
667     
668    if (FD_ISSET(fd, &rfds))
669      dtls_handle_read(the_context);
670  }
671
672  dtls_free_context(the_context);
673  * @endcode
674  * 
675  * @subsection dtls_read_cb The Read Callback
676  *
677  * The DTLS library expects received raw data to be passed to
678  * dtls_handle_message(). The application is responsible for
679  * filling a session_t structure with the address data of the
680  * remote peer as illustrated by the following example:
681  * 
682  * @code
683 int dtls_handle_read(struct dtls_context_t *ctx) {
684   int *fd;
685   session_t session;
686   static uint8 buf[DTLS_MAX_BUF];
687   int len;
688
689   fd = dtls_get_app_data(ctx);
690
691   assert(fd);
692
693   session.size = sizeof(session.addr);
694   len = recvfrom(*fd, buf, sizeof(buf), 0, &session.addr.sa, &session.size);
695   
696   return len < 0 ? len : dtls_handle_message(ctx, &session, buf, len);
697 }    
698  * @endcode 
699  * 
700  * Once a new DTLS session was established and DTLS ApplicationData has been
701  * received, the DTLS server invokes the read callback with the MAC-verified 
702  * cleartext data as its argument. A read callback for a simple echo server
703  * could look like this:
704  * @code
705 int read_from_peer(struct dtls_context_t *ctx, session_t *session, uint8 *data, size_t len) {
706   return dtls_write(ctx, session, data, len);
707 }
708  * @endcode 
709  * 
710  * @subsection dtls_send_cb The Send Callback
711  * 
712  * The callback function send_to_peer() is called whenever data must be
713  * sent over the network. Here, the sendto() system call is used to
714  * transmit data within the given session. The socket descriptor required
715  * by sendto() has been registered as application data when the DTLS context
716  * was created with dtls_new_context().
717  * Note that it is on the application to buffer the data when it cannot be
718  * sent at the time this callback is invoked. The following example thus
719  * is incomplete as it would have to deal with EAGAIN somehow.
720  * @code
721 int send_to_peer(struct dtls_context_t *ctx, session_t *session, uint8 *data, size_t len) {
722   int fd = *(int *)dtls_get_app_data(ctx);
723   return sendto(fd, data, len, MSG_DONTWAIT, &session->addr.sa, session->size);
724 }
725  * @endcode
726  * 
727  * @subsection dtls_get_psk_info The Key Storage
728  *
729  * When a new DTLS session is created, the library must ask the application
730  * for keying material. To do so, it invokes the registered call-back function
731  * get_psk_info() with the current context and session information as parameter.
732  * When the call-back function is invoked with the parameter @p type set to 
733  * @c DTLS_PSK_IDENTITY, the result parameter @p result must be filled with
734  * the psk_identity_hint in case of a server, or the actual psk_identity in 
735  * case of a client. When @p type is @c DTLS_PSK_KEY, the result parameter
736  * must be filled with a key for the given identity @p id. The function must
737  * return the number of bytes written to @p result which must not exceed
738  * @p result_length.
739  * In case of an error, the function must return a negative value that 
740  * corresponds to a valid error code defined in alert.h.
741  * 
742  * @code
743 int get_psk_info(struct dtls_context_t *ctx UNUSED_PARAM,
744             const session_t *session UNUSED_PARAM,
745             dtls_credentials_type_t type,
746             const unsigned char *id, size_t id_len,
747             unsigned char *result, size_t result_length) {
748
749   switch (type) {
750   case DTLS_PSK_IDENTITY:
751     if (result_length < psk_id_length) {
752       dtls_warn("cannot set psk_identity -- buffer too small\n");
753       return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
754     }
755
756     memcpy(result, psk_id, psk_id_length);
757     return psk_id_length;
758   case DTLS_PSK_KEY:
759     if (id_len != psk_id_length || memcmp(psk_id, id, id_len) != 0) {
760       dtls_warn("PSK for unknown id requested, exiting\n");
761       return dtls_alert_fatal_create(DTLS_ALERT_ILLEGAL_PARAMETER);
762     } else if (result_length < psk_key_length) {
763       dtls_warn("cannot set psk -- buffer too small\n");
764       return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
765     }
766
767     memcpy(result, psk_key, psk_key_length);
768     return psk_key_length;
769   default:
770     dtls_warn("unsupported request type: %d\n", type);
771   }
772
773   return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
774 }
775  * @endcode
776  * 
777  * @subsection dtls_events The Event Notifier
778  *
779  * Applications that want to be notified whenever the status of a DTLS session
780  * has changed can register an event handling function with the field @c event
781  * in the dtls_handler_t structure (see \ref dtls_server_example). The call-back
782  * function is called for alert messages and internal state changes. For alert
783  * messages, the argument @p level will be set to a value greater than zero, and
784  * @p code will indicate the notification code. For internal events, @p level
785  * is @c 0, and @p code a value greater than @c 255. 
786  *
787  * Internal events are DTLS_EVENT_CONNECTED, @c DTLS_EVENT_CONNECT, and
788  * @c DTLS_EVENT_RENEGOTIATE.
789  *
790  * @code
791 int handle_event(struct dtls_context_t *ctx, session_t *session, 
792                  dtls_alert_level_t level, unsigned short code) {
793   ... do something with event ...
794   return 0;
795 }
796  * @endcode
797  *
798  * @section dtls_client_example DTLS Client Example
799  *
800  * A DTLS client is constructed like a server but needs to actively setup
801  * a new session by calling dtls_connect() at some point. As this function
802  * usually returns before the new DTLS channel is established, the application
803  * must register an event handler and wait for @c DTLS_EVENT_CONNECT before
804  * it can send data over the DTLS channel.
805  *
806  */
807
808 /**
809  * @addtogroup contiki Contiki
810  *
811  * To use tinyDTLS as Contiki application, place the source code in the directory 
812  * @c apps/tinydtls in the Contiki source tree and invoke configure with the option
813  * @c --with-contiki. This will define WITH_CONTIKI in tinydtls.h and include 
814  * @c Makefile.contiki in the main Makefile. To cross-compile for another platform
815  * you will need to set your host and build system accordingly. For example,
816  * when configuring for ARM, you would invoke
817  * @code
818 ./configure --with-contiki --build=x86_64-linux-gnu --host=arm-none-eabi 
819  * @endcode
820  * on an x86_64 linux host.
821  *
822  * Then, create a Contiki project with @c APPS += tinydtls in its Makefile. A sample
823  * server could look like this (with read_from_peer() and get_psk_key() as shown above).
824  *
825  * @code
826 #include "contiki.h"
827
828 #include "tinydtls.h"
829 #include "dtls.h"
830
831 #define UIP_IP_BUF   ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
832 #define UIP_UDP_BUF  ((struct uip_udp_hdr *)&uip_buf[UIP_LLIPH_LEN])
833
834 int send_to_peer(struct dtls_context_t *, session_t *, uint8 *, size_t);
835
836 static struct uip_udp_conn *server_conn;
837 static dtls_context_t *dtls_context;
838
839 static dtls_handler_t cb = {
840   .write = send_to_peer,
841   .read  = read_from_peer,
842   .event = NULL,
843   .get_psk_key = get_psk_key
844 };
845
846 PROCESS(server_process, "DTLS server process");
847 AUTOSTART_PROCESSES(&server_process);
848
849 PROCESS_THREAD(server_process, ev, data)
850 {
851   PROCESS_BEGIN();
852
853   dtls_init();
854
855   server_conn = udp_new(NULL, 0, NULL);
856   udp_bind(server_conn, UIP_HTONS(5684));
857
858   dtls_context = dtls_new_context(server_conn);
859   if (!dtls_context) {
860     dtls_emerg("cannot create context\n");
861     PROCESS_EXIT();
862   }
863
864   dtls_set_handler(dtls_context, &cb);
865
866   while(1) {
867     PROCESS_WAIT_EVENT();
868     if(ev == tcpip_event && uip_newdata()) {
869       session_t session;
870
871       uip_ipaddr_copy(&session.addr, &UIP_IP_BUF->srcipaddr);
872       session.port = UIP_UDP_BUF->srcport;
873       session.size = sizeof(session.addr) + sizeof(session.port);
874     
875       dtls_handle_message(ctx, &session, uip_appdata, uip_datalen());
876     }
877   }
878
879   PROCESS_END();
880 }
881
882 int send_to_peer(struct dtls_context_t *ctx, session_t *session, uint8 *data, size_t len) {
883   struct uip_udp_conn *conn = (struct uip_udp_conn *)dtls_get_app_data(ctx);
884
885   uip_ipaddr_copy(&conn->ripaddr, &session->addr);
886   conn->rport = session->port;
887
888   uip_udp_packet_send(conn, data, len);
889
890   memset(&conn->ripaddr, 0, sizeof(server_conn->ripaddr));
891   memset(&conn->rport, 0, sizeof(conn->rport));
892
893   return len;
894 }
895  * @endcode
896  */