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