Imported Upstream version 1.0.1
[platform/upstream/iotivity.git] / extlibs / tinydtls / crypto.h
1 /* dtls -- a very basic DTLS implementation
2  *
3  * Copyright (C) 2011--2012 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 #ifndef _DTLS_CRYPTO_H_
28 #define _DTLS_CRYPTO_H_
29
30 #include <stdlib.h>             /* for rand() and srand() */
31 #include <stdint.h>
32
33 #include "t_list.h"
34
35 #include "aes/rijndael.h"
36
37 #include "global.h"
38 #include "state.h"
39 #include "numeric.h"
40 #include "hmac.h"
41 #include "ccm.h"
42 #include "ecc/ecc.h"
43
44 /* TLS_PSK_WITH_AES_128_CCM_8 */
45 #define DTLS_CCM_MAC_KEY_LENGTH        0       /* MAC Key length for AES-CCM cipher suites */
46 #define DTLS_CBC_MAC_KEY_LENGTH       32       /* MAC Key length for AES-CBC Cipher suites */
47 #define DTLS_KEY_LENGTH        16 /* AES-128 */
48 #define DTLS_BLK_LENGTH        16 /* AES-128 */
49 #define DTLS_MAC_LENGTH        DTLS_HMAC_DIGEST_SIZE
50 #define DTLS_CCM_IV_LENGTH     4  /* length of nonce_explicit */
51 #define DTLS_CBC_IV_LENGTH     16
52
53 /** 
54  * Maximum size of the generated keyblock. Note that MAX_KEYBLOCK_LENGTH must 
55  * be large enough to hold the pre_master_secret, i.e. twice the length of the 
56  * pre-shared key + 1.
57  */
58 #define CCM_KB_LENGTH  \
59     (2 * DTLS_KEY_LENGTH + 2 * DTLS_CCM_IV_LENGTH)
60
61 #define CBC_KB_LENGTH  \
62     (2 * DTLS_CBC_MAC_KEY_LENGTH + 2 * DTLS_KEY_LENGTH )
63
64 #define MAX_KEYBLOCK_LENGTH  \
65     ((CCM_KB_LENGTH) > (CBC_KB_LENGTH) ? (CCM_KB_LENGTH) : (CBC_KB_LENGTH) )
66
67 /** Length of DTLS master_secret */
68 #define DTLS_MASTER_SECRET_LENGTH 48
69 #define DTLS_RANDOM_LENGTH 32
70
71 typedef enum { AES128=0 
72 } dtls_crypto_alg;
73
74 typedef enum {
75   DTLS_ECDH_CURVE_SECP256R1
76 } dtls_ecdh_curve;
77
78 /** Crypto context for TLS_PSK_WITH_AES_128_CCM_8 cipher suite. */
79 typedef struct {
80   rijndael_ctx ctx;                    /**< AES-128 encryption context */
81 } aes128_t;
82
83 typedef struct dtls_cipher_context_t {
84   /** numeric identifier of this cipher suite in host byte order. */
85   aes128_t data;                /**< The crypto context */
86 } dtls_cipher_context_t;
87
88 typedef struct {
89   uint8 own_eph_priv[32];
90   uint8 other_eph_pub_x[32];
91   uint8 other_eph_pub_y[32];
92   uint8 other_pub_x[32];
93   uint8 other_pub_y[32];
94 } dtls_handshake_parameters_ecc_t;
95
96
97 /* This is the maximal supported length of the psk client identity and psk
98  * server identity hint */
99 #define DTLS_PSK_MAX_CLIENT_IDENTITY_LEN   32
100
101 /* This is the maximal supported length of the pre-shared key. */
102 #define DTLS_PSK_MAX_KEY_LEN 32
103
104 typedef struct {
105   uint16_t id_length;
106   unsigned char identity[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
107 } dtls_handshake_parameters_psk_t;
108
109 typedef struct {
110   dtls_compression_t compression;       /**< compression method */
111
112   dtls_cipher_t cipher;         /**< cipher type */
113   uint16_t epoch;            /**< counter for cipher state changes*/
114   uint64_t rseq;             /**< sequence number of last record sent */
115
116   /** 
117    * The key block generated from PRF applied to client and server
118    * random bytes. The actual size is given by the selected cipher and
119    * can be calculated using dtls_kb_size(). Use \c dtls_kb_ macros to
120    * access the components of the key block.
121    */
122   uint8 key_block[MAX_KEYBLOCK_LENGTH];
123 } dtls_security_parameters_t;
124
125 typedef struct {
126   union {
127     struct random_t {
128       uint8 client[DTLS_RANDOM_LENGTH]; /**< client random gmt and bytes */
129       uint8 server[DTLS_RANDOM_LENGTH]; /**< server random gmt and bytes */
130     } random;
131     /** the session's master secret */
132     uint8 master_secret[DTLS_MASTER_SECRET_LENGTH];
133   } tmp;
134   LIST_STRUCT(reorder_queue);   /**< the packets to reorder */
135   dtls_hs_state_t hs_state;  /**< handshake protocol status */
136
137   dtls_compression_t compression;               /**< compression method */
138   dtls_cipher_t cipher;         /**< cipher type */
139   unsigned int do_client_auth:1;
140
141 #if defined(DTLS_ECC) && defined(DTLS_PSK)
142   struct keyx_t {
143     dtls_handshake_parameters_ecc_t ecc;
144     dtls_handshake_parameters_psk_t psk;
145   } keyx;
146 #else /* DTLS_ECC && DTLS_PSK */
147   union {
148 #if defined(DTLS_ECC) || defined(DTLS_X509)
149     dtls_handshake_parameters_ecc_t ecc;
150 #endif /* DTLS_ECC */
151 #ifdef DTLS_PSK
152     dtls_handshake_parameters_psk_t psk;
153 #endif /* DTLS_PSK */
154   } keyx;
155 #endif /* DTLS_ECC && DTLS_PSK */
156 } dtls_handshake_parameters_t;
157
158 /* The following macros provide access to the components of the
159  * key_block in the security parameters. */
160
161 static inline int dtls_kb_mac_secret_size(dtls_cipher_t cipher)
162 {
163     switch(cipher)
164     {
165         case TLS_NULL_WITH_NULL_NULL:
166
167             return 0;
168             break;
169
170         case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256:
171         case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256:
172
173             return DTLS_CBC_MAC_KEY_LENGTH;
174             break;
175
176         case TLS_PSK_WITH_AES_128_CCM_8:
177         case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
178
179             return DTLS_CCM_MAC_KEY_LENGTH;
180             break;
181     }
182
183     return -1;
184 }
185
186
187 static inline int dtls_kb_iv_size(dtls_cipher_t cipher)
188 {
189     switch(cipher)
190     {
191         case TLS_NULL_WITH_NULL_NULL:
192         case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256:
193         case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256:
194
195             return 0;
196             break;
197
198         case TLS_PSK_WITH_AES_128_CCM_8:
199         case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
200
201             return DTLS_CCM_IV_LENGTH;
202             break;
203     }
204
205     return -1;
206 }
207
208
209
210
211 #define dtls_kb_client_mac_secret(Param, Role) ((Param)->key_block)
212 #define dtls_kb_server_mac_secret(Param, Role)                          \
213   (dtls_kb_client_mac_secret(Param, Role) + dtls_kb_mac_secret_size((Param)->cipher))
214 #define dtls_kb_remote_mac_secret(Param, Role)                          \
215   ((Role) == DTLS_SERVER                                                \
216    ? dtls_kb_client_mac_secret(Param, Role)                             \
217    : dtls_kb_server_mac_secret(Param, Role))
218 #define dtls_kb_local_mac_secret(Param, Role)                           \
219   ((Role) == DTLS_CLIENT                                                \
220    ? dtls_kb_client_mac_secret(Param, Role)                             \
221    : dtls_kb_server_mac_secret(Param, Role))
222 #define dtls_kb_client_write_key(Param, Role)                           \
223   (dtls_kb_server_mac_secret(Param, Role) + dtls_kb_mac_secret_size((Param)->cipher))
224 #define dtls_kb_server_write_key(Param, Role)                           \
225   (dtls_kb_client_write_key(Param, Role) + DTLS_KEY_LENGTH)
226 #define dtls_kb_remote_write_key(Param, Role)                           \
227   ((Role) == DTLS_SERVER                                                \
228    ? dtls_kb_client_write_key(Param, Role)                              \
229    : dtls_kb_server_write_key(Param, Role))
230 #define dtls_kb_local_write_key(Param, Role)                            \
231   ((Role) == DTLS_CLIENT                                                \
232    ? dtls_kb_client_write_key(Param, Role)                              \
233    : dtls_kb_server_write_key(Param, Role))
234 #define dtls_kb_key_size(Param, Role) DTLS_KEY_LENGTH
235 #define dtls_kb_client_iv(Param, Role)                                  \
236   (dtls_kb_server_write_key(Param, Role) + DTLS_KEY_LENGTH)
237 #define dtls_kb_server_iv(Param, Role)                                  \
238   (dtls_kb_client_iv(Param, Role) + dtls_kb_iv_size((Param)->cipher))
239 #define dtls_kb_remote_iv(Param, Role)                                  \
240   ((Role) == DTLS_SERVER                                                \
241    ? dtls_kb_client_iv(Param, Role)                                     \
242    : dtls_kb_server_iv(Param, Role))
243 #define dtls_kb_local_iv(Param, Role)                                   \
244   ((Role) == DTLS_CLIENT                                                \
245    ? dtls_kb_client_iv(Param, Role)                                     \
246    : dtls_kb_server_iv(Param, Role))
247
248 #define dtls_kb_size(Param, Role)                                       \
249   (2 * (dtls_kb_mac_secret_size((Param)->cipher) +                      \
250         dtls_kb_key_size(Param, Role) + dtls_kb_iv_size((Param)->cipher)))
251
252 /* just for consistency */
253 #define dtls_kb_digest_size(Param, Role) DTLS_MAC_LENGTH
254
255 /** 
256  * Expands the secret and key to a block of DTLS_HMAC_MAX 
257  * size according to the algorithm specified in section 5 of
258  * RFC 4346.
259  *
260  * \param h       Identifier of the hash function to use.
261  * \param key     The secret.
262  * \param keylen  Length of \p key.
263  * \param seed    The seed. 
264  * \param seedlen Length of \p seed.
265  * \param buf     Output buffer where the result is XORed into
266  *                The buffe must be capable to hold at least
267  *                \p buflen bytes.
268  * \return The actual number of bytes written to \p buf or 0
269  * on error.
270  */
271 size_t dtls_p_hash(dtls_hashfunc_t h, 
272                    const unsigned char *key, size_t keylen,
273                    const unsigned char *label, size_t labellen,
274                    const unsigned char *random1, size_t random1len,
275                    const unsigned char *random2, size_t random2len,
276                    unsigned char *buf, size_t buflen);
277
278 /**
279  * This function implements the TLS PRF for DTLS_VERSION. For version
280  * 1.0, the PRF is P_MD5 ^ P_SHA1 while version 1.2 uses
281  * P_SHA256. Currently, the actual PRF is selected at compile time.
282  */
283 size_t dtls_prf(const unsigned char *key, size_t keylen,
284                 const unsigned char *label, size_t labellen,
285                 const unsigned char *random1, size_t random1len,
286                 const unsigned char *random2, size_t random2len,
287                 unsigned char *buf, size_t buflen);
288
289 /**
290  * Calculates MAC for record + cleartext packet and places the result
291  * in \p buf. The given \p hmac_ctx must be initialized with the HMAC
292  * function to use and the proper secret. As the DTLS mac calculation
293  * requires data from the record header, \p record must point to a
294  * buffer of at least \c sizeof(dtls_record_header_t) bytes. Usually,
295  * the remaining packet will be encrypted, therefore, the cleartext
296  * is passed separately in \p packet.
297  * 
298  * \param hmac_ctx  The HMAC context to use for MAC calculation.
299  * \param record    The record header.
300  * \param packet    Cleartext payload to apply the MAC to.
301  * \param length    Size of \p packet.
302  * \param buf       A result buffer that is large enough to hold
303  *                  the generated digest.
304  */
305 void dtls_mac(dtls_hmac_context_t *hmac_ctx, 
306               const unsigned char *record,
307               const unsigned char *packet, size_t length,
308               unsigned char *buf);
309
310 /** 
311  * Encrypts the specified \p src of given \p length, writing the
312  * result to \p buf. The cipher implementation may add more data to
313  * the result buffer such as an initialization vector or padding
314  * (e.g. for block cipers in CBC mode). The caller therefore must
315  * ensure that \p buf provides sufficient storage to hold the result.
316  * Usually this means ( 2 + \p length / blocksize ) * blocksize.  The
317  * function returns a value less than zero on error or otherwise the
318  * number of bytes written.
319  *
320  * \param ctx    The cipher context to use.
321  * \param src    The data to encrypt.
322  * \param length The actual size of of \p src.
323  * \param buf    The result buffer. \p src and \p buf must not 
324  *               overlap.
325  * \param aad    additional data for AEAD ciphers
326  * \param aad_length actual size of @p aad
327  * \return The number of encrypted bytes on success, less than zero
328  *         otherwise. 
329  */
330 int dtls_encrypt(const unsigned char *src, size_t length,
331                  unsigned char *buf,
332                  unsigned char *nounce,
333                  unsigned char *write_key, size_t write_keylen,
334                  unsigned char *mac_key, size_t mac_keylen,
335                  const unsigned char *aad, size_t aad_length,
336                  const dtls_cipher_t cipher);
337
338 /** 
339  * Decrypts the given buffer \p src of given \p length, writing the
340  * result to \p buf. The function returns \c -1 in case of an error,
341  * or the number of bytes written. Note that for block ciphers, \p
342  * length must be a multiple of the cipher's block size. A return
343  * value between \c 0 and the actual length indicates that only \c n-1
344  * block have been processed. Unlike dtls_encrypt(), the source
345  * and destination of dtls_decrypt() may overlap. 
346  * 
347  * \param ctx     The cipher context to use.
348  * \param src     The buffer to decrypt.
349  * \param length  The length of the input buffer. 
350  * \param buf     The result buffer.
351  * \param aad     additional authentication data for AEAD ciphers
352  * \param aad_length actual size of @p aad
353  * \return Less than zero on error, the number of decrypted bytes 
354  *         otherwise.
355  */
356 int dtls_decrypt(const unsigned char *src, size_t length,
357                  unsigned char *buf,
358                  unsigned char *nounce,
359                  unsigned char *read_key, size_t read_keylen,
360                  unsigned char *mac_key, size_t mac_keylen,
361                  const unsigned char *a_data, size_t a_data_length,
362                  const dtls_cipher_t cipher);
363
364 /* helper functions */
365
366 /** 
367  * Generates pre_master_sercet from given PSK and fills the result
368  * according to the "plain PSK" case in section 2 of RFC 4279.
369  * Diffie-Hellman and RSA key exchange are currently not supported.
370  *
371  * @param key    The shared key.
372  * @param keylen Length of @p key in bytes.
373  * @param result The derived pre master secret.
374  * @return The actual length of @p result.
375  */
376 int dtls_psk_pre_master_secret(unsigned char *key, size_t keylen,
377                                unsigned char *result, size_t result_len);
378
379 #define DTLS_EC_KEY_SIZE 32
380
381 int dtls_ecdh_pre_master_secret(unsigned char *priv_key,
382                                 unsigned char *pub_key_x,
383                                 unsigned char *pub_key_y,
384                                 size_t key_size,
385                                 unsigned char *result,
386                                 size_t result_len);
387
388 void dtls_ecdsa_generate_key(unsigned char *priv_key,
389                              unsigned char *pub_key_x,
390                              unsigned char *pub_key_y,
391                              size_t key_size);
392
393 void dtls_ecdsa_create_sig_hash(const unsigned char *priv_key, size_t key_size,
394                                 const unsigned char *sign_hash, size_t sign_hash_size,
395                                 uint32_t point_r[9], uint32_t point_s[9]);
396
397 void dtls_ecdsa_create_sig(const unsigned char *priv_key, size_t key_size,
398                            const unsigned char *client_random, size_t client_random_size,
399                            const unsigned char *server_random, size_t server_random_size,
400                            const unsigned char *keyx_params, size_t keyx_params_size,
401                            uint32_t point_r[9], uint32_t point_s[9]);
402
403 int dtls_ecdsa_verify_sig_hash(const unsigned char *pub_key_x,
404                                const unsigned char *pub_key_y, size_t key_size,
405                                const unsigned char *sign_hash, size_t sign_hash_size,
406                                unsigned char *result_r, unsigned char *result_s);
407
408 int dtls_ecdsa_verify_sig(const unsigned char *pub_key_x,
409                           const unsigned char *pub_key_y, size_t key_size,
410                           const unsigned char *client_random, size_t client_random_size,
411                           const unsigned char *server_random, size_t server_random_size,
412                           const unsigned char *keyx_params, size_t keyx_params_size,
413                           unsigned char *result_r, unsigned char *result_s);
414
415 int dtls_ecdhe_psk_pre_master_secret(unsigned char *psk, size_t psklen,
416                                 unsigned char *ecc_priv_key,
417                                 unsigned char *ecc_pub_key_x,
418                                 unsigned char *ecc_pub_key_y,
419                                 size_t ecc_key_size,
420                                 unsigned char *result,
421                                 size_t result_len);
422
423 int dtls_ec_key_from_uint32_asn1(const uint32_t *key, size_t key_size,
424                                  unsigned char *buf);
425
426
427 dtls_handshake_parameters_t *dtls_handshake_new();
428
429 void dtls_handshake_free(dtls_handshake_parameters_t *handshake);
430
431 dtls_security_parameters_t *dtls_security_new();
432
433 void dtls_security_free(dtls_security_parameters_t *security);
434 void crypto_init();
435
436 #endif /* _DTLS_CRYPTO_H_ */
437