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