Imported Upstream version 1.0.0
[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    * considered 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
325 } dtls_handler_t;
326
327 /** Holds global information of the DTLS engine. */
328 typedef struct dtls_context_t {
329   unsigned char cookie_secret[DTLS_COOKIE_SECRET_LENGTH];
330   clock_time_t cookie_secret_age; /**< the time the secret has been generated */
331
332 #ifndef WITH_CONTIKI
333   dtls_peer_t *peers;           /**< peer hash map */
334 #else /* WITH_CONTIKI */
335   LIST_STRUCT(peers);
336
337   struct etimer retransmit_timer; /**< fires when the next packet must be sent */
338 #endif /* WITH_CONTIKI */
339
340   LIST_STRUCT(sendqueue);       /**< the packets to send */
341
342   void *app;                    /**< application-specific data */
343
344   dtls_handler_t *h;            /**< callback handlers */
345
346   dtls_cipher_enable_t is_anon_ecdh_eabled;    /**< enable/disable the TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 */
347
348   dtls_cipher_t selected_cipher; /**< selected ciper suite for handshake */
349
350   unsigned char readbuf[DTLS_MAX_BUF];
351 } dtls_context_t;
352
353 /** 
354  * This function initializes the tinyDTLS memory management and must
355  * be called first.
356  */
357 void dtls_init();
358
359 /** 
360  * Creates a new context object. The storage allocated for the new
361  * object must be released with dtls_free_context(). */
362 dtls_context_t *dtls_new_context(void *app_data);
363
364 /** Releases any storage that has been allocated for \p ctx. */
365 void dtls_free_context(dtls_context_t *ctx);
366
367 #define dtls_set_app_data(CTX,DATA) ((CTX)->app = (DATA))
368 #define dtls_get_app_data(CTX) ((CTX)->app)
369
370 /** Sets the callback handler object for @p ctx to @p h. */
371 static inline void dtls_set_handler(dtls_context_t *ctx, dtls_handler_t *h) {
372   ctx->h = h;
373 }
374
375  /**
376   * @brief Enabling the TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256
377   *
378   * @param ctx              The DTLS context to use.
379   * @param is_enable    DTLS_CIPHER_ENABLE(1) or DTLS_CIPHER_DISABLE(0)
380   */
381 void dtls_enables_anon_ecdh(dtls_context_t* ctx, dtls_cipher_enable_t is_enable);
382
383 /**
384  * @brief Select the cipher suite for handshake
385  *
386  * @param ctx              The DTLS context to use.
387  * @param cipher         TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 (0xC018)
388  *                                  TLS_PSK_WITH_AES_128_CCM_8 (0xX0A8)
389  *                                  TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 (0xC0AE)
390  */
391 void dtls_select_cipher(dtls_context_t* ctx, const dtls_cipher_t cipher);
392
393 /**
394  * Establishes a DTLS channel with the specified remote peer @p dst.
395  * This function returns @c 0 if that channel already exists, a value
396  * greater than zero when a new ClientHello message was sent, and
397  * a value less than zero on error.
398  *
399  * @param ctx    The DTLS context to use.
400  * @param dst    The remote party to connect to.
401  * @return A value less than zero on error, greater or equal otherwise.
402  */
403 int dtls_connect(dtls_context_t *ctx, const session_t *dst);
404
405 /**
406  * Establishes a DTLS channel with the specified remote peer.
407  * This function returns @c 0 if that channel already exists, a value
408  * greater than zero when a new ClientHello message was sent, and
409  * a value less than zero on error.
410  *
411  * @param ctx    The DTLS context to use.
412  * @param peer   The peer object that describes the session.
413  * @return A value less than zero on error, greater or equal otherwise.
414  */
415 int dtls_connect_peer(dtls_context_t *ctx, dtls_peer_t *peer);
416
417 /**
418  * Closes the DTLS connection associated with @p remote. This function
419  * returns zero on success, and a value less than zero on error.
420  */
421 int dtls_close(dtls_context_t *ctx, const session_t *remote);
422
423 int dtls_renegotiate(dtls_context_t *ctx, const session_t *dst);
424
425 /** 
426  * Writes the application data given in @p buf to the peer specified
427  * by @p session. 
428  * 
429  * @param ctx      The DTLS context to use.
430  * @param session  The remote transport address and local interface.
431  * @param buf      The data to write.
432  * @param len      The actual length of @p data.
433  * 
434  * @return The number of bytes written or @c -1 on error.
435  */
436 int dtls_write(struct dtls_context_t *ctx, session_t *session, 
437                uint8 *buf, size_t len);
438
439 /**
440  * Checks sendqueue of given DTLS context object for any outstanding
441  * packets to be transmitted. 
442  *
443  * @param context The DTLS context object to use.
444  * @param next    If not NULL, @p next is filled with the timestamp
445  *  of the next scheduled retransmission, or @c 0 when no packets are
446  *  waiting.
447  */
448 void dtls_check_retransmit(dtls_context_t *context, clock_time_t *next);
449
450 #define DTLS_COOKIE_LENGTH 16
451
452 #define DTLS_CT_CHANGE_CIPHER_SPEC 20
453 #define DTLS_CT_ALERT              21
454 #define DTLS_CT_HANDSHAKE          22
455 #define DTLS_CT_APPLICATION_DATA   23
456
457 /** Generic header structure of the DTLS record layer. */
458 typedef struct __attribute__((__packed__)) {
459   uint8 content_type;           /**< content type of the included message */
460   uint16 version;               /**< Protocol version */
461   uint16 epoch;                 /**< counter for cipher state changes */
462   uint48 sequence_number;       /**< sequence number */
463   uint16 length;                /**< length of the following fragment */
464   /* fragment */
465 } dtls_record_header_t;
466
467 /* Handshake types */
468
469 #define DTLS_HT_HELLO_REQUEST        0
470 #define DTLS_HT_CLIENT_HELLO         1
471 #define DTLS_HT_SERVER_HELLO         2
472 #define DTLS_HT_HELLO_VERIFY_REQUEST 3
473 #define DTLS_HT_CERTIFICATE         11
474 #define DTLS_HT_SERVER_KEY_EXCHANGE 12
475 #define DTLS_HT_CERTIFICATE_REQUEST 13
476 #define DTLS_HT_SERVER_HELLO_DONE   14
477 #define DTLS_HT_CERTIFICATE_VERIFY  15
478 #define DTLS_HT_CLIENT_KEY_EXCHANGE 16
479 #define DTLS_HT_FINISHED            20
480
481 /** Header structure for the DTLS handshake protocol. */
482 typedef struct __attribute__((__packed__)) {
483   uint8 msg_type; /**< Type of handshake message  (one of DTLS_HT_) */
484   uint24 length;  /**< length of this message */
485   uint16 message_seq;   /**< Message sequence number */
486   uint24 fragment_offset;       /**< Fragment offset. */
487   uint24 fragment_length;       /**< Fragment length. */
488   /* body */
489 } dtls_handshake_header_t;
490
491 /** Structure of the Client Hello message. */
492 typedef struct __attribute__((__packed__)) {
493   uint16 version;         /**< Client version */
494   uint32 gmt_random;      /**< GMT time of the random byte creation */
495   unsigned char random[28];     /**< Client random bytes */
496   /* session id (up to 32 bytes) */
497   /* cookie (up to 32 bytes) */
498   /* cipher suite (2 to 2^16 -1 bytes) */
499   /* compression method */
500 } dtls_client_hello_t;
501
502 /** Structure of the Hello Verify Request. */
503 typedef struct __attribute__((__packed__)) {
504   uint16 version;               /**< Server version */
505   uint8 cookie_length;  /**< Length of the included cookie */
506   uint8 cookie[];               /**< up to 32 bytes making up the cookie */
507 } dtls_hello_verify_t;  
508
509 #if 0
510 /** 
511  * Checks a received DTLS record for consistency and eventually decrypt,
512  * verify, decompress and reassemble the contained fragment for 
513  * delivery to high-lever clients. 
514  * 
515  * \param state The DTLS record state for the current session. 
516  * \param 
517  */
518 int dtls_record_read(dtls_state_t *state, uint8 *msg, int msglen);
519 #endif
520
521 /** 
522  * Handles incoming data as DTLS message from given peer.
523  *
524  * @param ctx     The dtls context to use.
525  * @param session The current session
526  * @param msg     The received data
527  * @param msglen  The actual length of @p msg.
528  * @return A value less than zero on error, zero on success.
529  */
530 int dtls_handle_message(dtls_context_t *ctx, session_t *session,
531                         uint8 *msg, int msglen);
532
533 /**
534  * Check if @p session is associated with a peer object in @p context.
535  * This function returns a pointer to the peer if found, NULL otherwise.
536  *
537  * @param context  The DTLS context to search.
538  * @param session  The remote address and local interface
539  * @return A pointer to the peer associated with @p session or NULL if
540  *  none exists.
541  */
542 dtls_peer_t *dtls_get_peer(const dtls_context_t *context,
543                            const session_t *session);
544
545 /**
546 * Invokes the DTLS PRF using the current key block for @p session as
547 * key and @p label + @p random1 + @p random2 as its input. This function
548 * writes upto @p buflen bytes into the given output buffer @p buf.
549 *
550 * @param ctx The dtls context to use.
551 * @param session The session whose key shall be used.
552 * @param label A PRF label.
553 * @param labellen Actual length of @p label.
554 * @param random1 Random seed.
555 * @param random1len Actual length of @p random1 (may be zero).
556 * @param random2 Random seed.
557 * @param random2len Actual length of @p random2 (may be zero).
558 * @param buf Output buffer for generated random data.
559 * @param buflen Maximum size of @p buf.
560 *
561 * @return The actual number of bytes written to @p buf or @c 0 on error.
562 */
563 size_t dtls_prf_with_current_keyblock(dtls_context_t *ctx, session_t *session,
564                                       const uint8_t* label, const uint32_t labellen,
565                                       const uint8_t* random1, const uint32_t random1len,
566                                       const uint8_t* random2, const uint32_t random2len,
567                                       uint8_t* buf, const uint32_t buflen);
568
569
570 #endif /* _DTLS_DTLS_H_ */
571
572 /**
573  * @mainpage 
574  *
575  * @author Olaf Bergmann, TZI Uni Bremen
576  *
577  * This library provides a very simple datagram server with DTLS
578  * support. It is designed to support session multiplexing in
579  * single-threaded applications and thus targets specifically on
580  * embedded systems.
581  *
582  * @section license License
583  *
584  * This software is under the <a 
585  * href="http://www.opensource.org/licenses/mit-license.php">MIT License</a>.
586  * 
587  * @subsection uthash UTHash
588  *
589  * This library uses <a href="http://uthash.sourceforge.net/">uthash</a> to manage
590  * its peers (not used for Contiki). @b uthash uses the <b>BSD revised license</b>, see
591  * <a href="http://uthash.sourceforge.net/license.html">http://uthash.sourceforge.net/license.html</a>.
592  *
593  * @subsection sha256 Aaron D. Gifford's SHA256 Implementation
594  *
595  * tinyDTLS provides HMAC-SHA256 with BSD-licensed code from Aaron D. Gifford, 
596  * see <a href="http://www.aarongifford.com/">www.aarongifford.com</a>.
597  *
598  * @subsection aes Rijndael Implementation From OpenBSD
599  *
600  * The AES implementation is taken from rijndael.{c,h} contained in the crypto 
601  * sub-system of the OpenBSD operating system. It is copyright by Vincent Rijmen, *
602  * Antoon Bosselaers and Paulo Barreto. See <a 
603  * href="http://www.openbsd.org/cgi-bin/cvsweb/src/sys/crypto/rijndael.c">rijndael.c</a> 
604  * for License info.
605  *
606  * @section download Getting the Files
607  *
608  * You can get the sources either from the <a 
609  * href="http://sourceforge.net/projects/tinydtls/files">downloads</a> section or 
610  * through git from the <a 
611  * href="http://sourceforge.net/projects/tinydtls/develop">project develop page</a>.
612  *
613  * @section config Configuration
614  *
615  * Use @c configure to set up everything for a successful build. For Contiki, use the
616  * option @c --with-contiki.
617  *
618  * @section build Building
619  *
620  * After configuration, just type 
621  * @code
622 make
623  * @endcode
624  * optionally followed by
625  * @code
626 make install
627  * @endcode
628  * The Contiki version is integrated with the Contiki build system, hence you do not
629  * need to invoke @c make explicitely. Just add @c tinydtls to the variable @c APPS
630  * in your @c Makefile.
631  *
632  * @addtogroup dtls_usage DTLS Usage
633  *
634  * @section dtls_server_example DTLS Server Example
635  *
636  * This section shows how to use the DTLS library functions to setup a 
637  * simple secure UDP echo server. The application is responsible for the
638  * entire network communication and thus will look like a usual UDP
639  * server with socket creation and binding and a typical select-loop as
640  * shown below. The minimum configuration required for DTLS is the 
641  * creation of the dtls_context_t using dtls_new_context(), and a callback
642  * for sending data. Received packets are read by the application and
643  * passed to dtls_handle_message() as shown in @ref dtls_read_cb. 
644  * For any useful communication to happen, read and write call backs 
645  * and a key management function should be registered as well. 
646  * 
647  * @code 
648  dtls_context_t *the_context = NULL;
649  int fd, result;
650
651  static dtls_handler_t cb = {
652    .write = send_to_peer,
653    .read  = read_from_peer,
654    .event = NULL,
655    .get_psk_key = get_psk_key
656  };
657
658  fd = socket(...);
659  if (fd < 0 || bind(fd, ...) < 0)
660    exit(-1);
661
662  the_context = dtls_new_context(&fd);
663  dtls_set_handler(the_context, &cb);
664
665  while (1) {
666    ...initialize fd_set rfds and timeout ...
667    result = select(fd+1, &rfds, NULL, 0, NULL);
668     
669    if (FD_ISSET(fd, &rfds))
670      dtls_handle_read(the_context);
671  }
672
673  dtls_free_context(the_context);
674  * @endcode
675  * 
676  * @subsection dtls_read_cb The Read Callback
677  *
678  * The DTLS library expects received raw data to be passed to
679  * dtls_handle_message(). The application is responsible for
680  * filling a session_t structure with the address data of the
681  * remote peer as illustrated by the following example:
682  * 
683  * @code
684 int dtls_handle_read(struct dtls_context_t *ctx) {
685   int *fd;
686   session_t session;
687   static uint8 buf[DTLS_MAX_BUF];
688   int len;
689
690   fd = dtls_get_app_data(ctx);
691
692   assert(fd);
693
694   session.size = sizeof(session.addr);
695   len = recvfrom(*fd, buf, sizeof(buf), 0, &session.addr.sa, &session.size);
696   
697   return len < 0 ? len : dtls_handle_message(ctx, &session, buf, len);
698 }    
699  * @endcode 
700  * 
701  * Once a new DTLS session was established and DTLS ApplicationData has been
702  * received, the DTLS server invokes the read callback with the MAC-verified 
703  * cleartext data as its argument. A read callback for a simple echo server
704  * could look like this:
705  * @code
706 int read_from_peer(struct dtls_context_t *ctx, session_t *session, uint8 *data, size_t len) {
707   return dtls_write(ctx, session, data, len);
708 }
709  * @endcode 
710  * 
711  * @subsection dtls_send_cb The Send Callback
712  * 
713  * The callback function send_to_peer() is called whenever data must be
714  * sent over the network. Here, the sendto() system call is used to
715  * transmit data within the given session. The socket descriptor required
716  * by sendto() has been registered as application data when the DTLS context
717  * was created with dtls_new_context().
718  * Note that it is on the application to buffer the data when it cannot be
719  * sent at the time this callback is invoked. The following example thus
720  * is incomplete as it would have to deal with EAGAIN somehow.
721  * @code
722 int send_to_peer(struct dtls_context_t *ctx, session_t *session, uint8 *data, size_t len) {
723   int fd = *(int *)dtls_get_app_data(ctx);
724   return sendto(fd, data, len, MSG_DONTWAIT, &session->addr.sa, session->size);
725 }
726  * @endcode
727  * 
728  * @subsection dtls_get_psk_info The Key Storage
729  *
730  * When a new DTLS session is created, the library must ask the application
731  * for keying material. To do so, it invokes the registered call-back function
732  * get_psk_info() with the current context and session information as parameter.
733  * When the call-back function is invoked with the parameter @p type set to 
734  * @c DTLS_PSK_IDENTITY, the result parameter @p result must be filled with
735  * the psk_identity_hint in case of a server, or the actual psk_identity in 
736  * case of a client. When @p type is @c DTLS_PSK_KEY, the result parameter
737  * must be filled with a key for the given identity @p id. The function must
738  * return the number of bytes written to @p result which must not exceed
739  * @p result_length.
740  * In case of an error, the function must return a negative value that 
741  * corresponds to a valid error code defined in alert.h.
742  * 
743  * @code
744 int get_psk_info(struct dtls_context_t *ctx UNUSED_PARAM,
745             const session_t *session UNUSED_PARAM,
746             dtls_credentials_type_t type,
747             const unsigned char *id, size_t id_len,
748             unsigned char *result, size_t result_length) {
749
750   switch (type) {
751   case DTLS_PSK_IDENTITY:
752     if (result_length < psk_id_length) {
753       dtls_warn("cannot set psk_identity -- buffer too small\n");
754       return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
755     }
756
757     memcpy(result, psk_id, psk_id_length);
758     return psk_id_length;
759   case DTLS_PSK_KEY:
760     if (id_len != psk_id_length || memcmp(psk_id, id, id_len) != 0) {
761       dtls_warn("PSK for unknown id requested, exiting\n");
762       return dtls_alert_fatal_create(DTLS_ALERT_ILLEGAL_PARAMETER);
763     } else if (result_length < psk_key_length) {
764       dtls_warn("cannot set psk -- buffer too small\n");
765       return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
766     }
767
768     memcpy(result, psk_key, psk_key_length);
769     return psk_key_length;
770   default:
771     dtls_warn("unsupported request type: %d\n", type);
772   }
773
774   return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
775 }
776  * @endcode
777  * 
778  * @subsection dtls_events The Event Notifier
779  *
780  * Applications that want to be notified whenever the status of a DTLS session
781  * has changed can register an event handling function with the field @c event
782  * in the dtls_handler_t structure (see \ref dtls_server_example). The call-back
783  * function is called for alert messages and internal state changes. For alert
784  * messages, the argument @p level will be set to a value greater than zero, and
785  * @p code will indicate the notification code. For internal events, @p level
786  * is @c 0, and @p code a value greater than @c 255. 
787  *
788  * Internal events are DTLS_EVENT_CONNECTED, @c DTLS_EVENT_CONNECT, and
789  * @c DTLS_EVENT_RENEGOTIATE.
790  *
791  * @code
792 int handle_event(struct dtls_context_t *ctx, session_t *session, 
793                  dtls_alert_level_t level, unsigned short code) {
794   ... do something with event ...
795   return 0;
796 }
797  * @endcode
798  *
799  * @section dtls_client_example DTLS Client Example
800  *
801  * A DTLS client is constructed like a server but needs to actively setup
802  * a new session by calling dtls_connect() at some point. As this function
803  * usually returns before the new DTLS channel is established, the application
804  * must register an event handler and wait for @c DTLS_EVENT_CONNECT before
805  * it can send data over the DTLS channel.
806  *
807  */
808
809 /**
810  * @addtogroup contiki Contiki
811  *
812  * To use tinyDTLS as Contiki application, place the source code in the directory 
813  * @c apps/tinydtls in the Contiki source tree and invoke configure with the option
814  * @c --with-contiki. This will define WITH_CONTIKI in tinydtls.h and include 
815  * @c Makefile.contiki in the main Makefile. To cross-compile for another platform
816  * you will need to set your host and build system accordingly. For example,
817  * when configuring for ARM, you would invoke
818  * @code
819 ./configure --with-contiki --build=x86_64-linux-gnu --host=arm-none-eabi 
820  * @endcode
821  * on an x86_64 linux host.
822  *
823  * Then, create a Contiki project with @c APPS += tinydtls in its Makefile. A sample
824  * server could look like this (with read_from_peer() and get_psk_key() as shown above).
825  *
826  * @code
827 #include "contiki.h"
828
829 #include "tinydtls.h"
830 #include "dtls.h"
831
832 #define UIP_IP_BUF   ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
833 #define UIP_UDP_BUF  ((struct uip_udp_hdr *)&uip_buf[UIP_LLIPH_LEN])
834
835 int send_to_peer(struct dtls_context_t *, session_t *, uint8 *, size_t);
836
837 static struct uip_udp_conn *server_conn;
838 static dtls_context_t *dtls_context;
839
840 static dtls_handler_t cb = {
841   .write = send_to_peer,
842   .read  = read_from_peer,
843   .event = NULL,
844   .get_psk_key = get_psk_key
845 };
846
847 PROCESS(server_process, "DTLS server process");
848 AUTOSTART_PROCESSES(&server_process);
849
850 PROCESS_THREAD(server_process, ev, data)
851 {
852   PROCESS_BEGIN();
853
854   dtls_init();
855
856   server_conn = udp_new(NULL, 0, NULL);
857   udp_bind(server_conn, UIP_HTONS(5684));
858
859   dtls_context = dtls_new_context(server_conn);
860   if (!dtls_context) {
861     dtls_emerg("cannot create context\n");
862     PROCESS_EXIT();
863   }
864
865   dtls_set_handler(dtls_context, &cb);
866
867   while(1) {
868     PROCESS_WAIT_EVENT();
869     if(ev == tcpip_event && uip_newdata()) {
870       session_t session;
871
872       uip_ipaddr_copy(&session.addr, &UIP_IP_BUF->srcipaddr);
873       session.port = UIP_UDP_BUF->srcport;
874       session.size = sizeof(session.addr) + sizeof(session.port);
875     
876       dtls_handle_message(ctx, &session, uip_appdata, uip_datalen());
877     }
878   }
879
880   PROCESS_END();
881 }
882
883 int send_to_peer(struct dtls_context_t *ctx, session_t *session, uint8 *data, size_t len) {
884   struct uip_udp_conn *conn = (struct uip_udp_conn *)dtls_get_app_data(ctx);
885
886   uip_ipaddr_copy(&conn->ripaddr, &session->addr);
887   conn->rport = session->port;
888
889   uip_udp_packet_send(conn, data, len);
890
891   memset(&conn->ripaddr, 0, sizeof(server_conn->ripaddr));
892   memset(&conn->rport, 0, sizeof(conn->rport));
893
894   return len;
895 }
896  * @endcode
897  */