1 /********************************************************************************
\r
2 Copyright (c) 2016-2018, Eduard Suica
\r
5 Redistribution and use in source and binary forms, with or without modification,
\r
6 are permitted provided that the following conditions are met:
\r
8 1. Redistributions of source code must retain the above copyright notice, this
\r
9 list of conditions and the following disclaimer.
\r
11 2. Redistributions in binary form must reproduce the above copyright notice, this
\r
12 list of conditions and the following disclaimer in the documentation and/or other
\r
13 materials provided with the distribution.
\r
15 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
\r
16 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
\r
17 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
\r
18 IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
\r
19 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
\r
20 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
\r
21 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
\r
22 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
\r
23 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
\r
24 POSSIBILITY OF SUCH DAMAGE.
\r
25 ********************************************************************************/
\r
35 #include <windows.h>
\r
36 #include <wincrypt.h>
\r
37 #define strcasecmp stricmp
\r
39 // hton* and ntoh* functions
\r
40 #include <arpa/inet.h>
\r
44 #ifdef TLS_AMALGAMATION
\r
45 #include "libtomcrypt.c"
\r
47 #include <tomcrypt.h>
\r
50 #if (CRYPT <= 0x0117)
\r
51 #define LTC_PKCS_1_EMSA LTC_LTC_PKCS_1_EMSA
\r
52 #define LTC_PKCS_1_V1_5 LTC_LTC_PKCS_1_V1_5
\r
56 #include <sys/types.h>
\r
57 #include <sys/socket.h>
\r
58 #include <netinet/tcp.h>
\r
61 // using ChaCha20 implementation by D. J. Bernstein
\r
65 #ifndef TLS_FORWARD_SECRECY
\r
66 #undef TLS_ECDSA_SUPPORTED
\r
69 #ifndef TLS_ECDSA_SUPPORTED
\r
70 // disable client ECDSA if not supported
\r
71 #undef TLS_CLIENT_ECDSA
\r
74 #define TLS_DH_DEFAULT_P "87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C022E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251CCACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D2276E11715F693877FAD7EF09CADB094AE91E1A1597"
\r
75 #define TLS_DH_DEFAULT_G "3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2DDF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148D47954515E2327CFEF98C582664B4C0F6CC41659"
\r
76 #define __TLS_DHE_KEY_SIZE 2048
\r
78 // you should never use weak DH groups (1024 bits)
\r
79 // but if you have old devices (like grandstream ip phones)
\r
80 // that can't handle 2048bit DHE, uncomment next lines
\r
81 // and define TLS_WEAK_DH_LEGACY_DEVICES
\r
82 // #ifdef TLS_WEAK_DH_LEGACY_DEVICES
\r
83 // #define TLS_DH_DEFAULT_P "B10B8F96A080E01DDE92DE5EAE5D54EC52C99FBCFB06A3C69A6A9DCA52D23B616073E28675A23D189838EF1E2EE652C013ECB4AEA906112324975C3CD49B83BFACCBDD7D90C4BD7098488E9C219A73724EFFD6FAE5644738FAA31A4FF55BCCC0A151AF5F0DC8B4BD45BF37DF365C1A65E68CFDA76D4DA708DF1FB2BC2E4A4371"
\r
84 // #define TLS_DH_DEFAULT_G "A4D1CBD5C3FD34126765A442EFB99905F8104DD258AC507FD6406CFF14266D31266FEA1E5C41564B777E690F5504F213160217B4B01B886A5E91547F9E2749F4D7FBD7D3B9A92EE1909D0D2263F80A76A6A24C087A091F531DBF0A0169B6A28AD662A4D18E73AFA32D779D5918D08BC8858F4DCEF97C2A24855E6EEB22B3B2E5"
\r
85 // #define __TLS_DHE_KEY_SIZE 1024
\r
89 #define TLS_MALLOC(size) malloc(size)
\r
92 #define TLS_REALLOC(ptr, size) realloc(ptr, size)
\r
95 #define TLS_FREE(ptr) if (ptr) free(ptr)
\r
99 #define DEBUG_PRINT(...) fprintf(stderr, __VA_ARGS__)
\r
100 #define DEBUG_DUMP_HEX(buf, len) {int i; for (i = 0; i < len; i++) { DEBUG_PRINT("%02X ", (unsigned int)(buf)[i]); } }
\r
101 #define DEBUG_INDEX(fields) print_index(fields)
\r
102 #define DEBUG_DUMP(buf, length) fwrite(buf, 1, length, stderr);
\r
103 #define DEBUG_DUMP_HEX_LABEL(title, buf, len) {fprintf(stderr, "%s (%i): ", title, (int)len); DEBUG_DUMP_HEX(buf, len); fprintf(stderr, "\n");}
\r
105 #define DEBUG_PRINT(...) { }
\r
106 #define DEBUG_DUMP_HEX(buf, len) { }
\r
107 #define DEBUG_INDEX(fields) { }
\r
108 #define DEBUG_DUMP(buf, length) { }
\r
109 #define DEBUG_DUMP_HEX_LABEL(title, buf, len) { }
\r
113 #define htonll(x) ((1==htonl(1)) ? (x) : ((uint64_t)htonl((x) & 0xFFFFFFFF) << 32) | htonl((x) >> 32))
\r
117 #define ntohll(x) ((1==ntohl(1)) ? (x) : ((uint64_t)ntohl((x) & 0xFFFFFFFF) << 32) | ntohl((x) >> 32))
\r
120 #define TLS_CHANGE_CIPHER 0x14
\r
121 #define TLS_ALERT 0x15
\r
122 #define TLS_HANDSHAKE 0x16
\r
123 #define TLS_APPLICATION_DATA 0x17
\r
125 #define TLS_SERIALIZED_OBJECT 0xFE
\r
127 #define __TLS_CLIENT_HELLO_MINSIZE 41
\r
128 #define __TLS_CLIENT_RANDOM_SIZE 32
\r
129 #define __TLS_SERVER_RANDOM_SIZE 32
\r
130 #define __TLS_MAX_SESSION_ID 32
\r
131 #define __TLS_SHA256_MAC_SIZE 32
\r
132 #define __TLS_SHA1_MAC_SIZE 20
\r
133 #define __TLS_SHA384_MAC_SIZE 48
\r
134 #define __TLS_MAX_MAC_SIZE __TLS_SHA384_MAC_SIZE
\r
135 #define __TLS_MAX_KEY_EXPANSION_SIZE 192 // 160
\r
136 // 512bits (sha256) = 64 bytes
\r
137 #define __TLS_MAX_HASH_LEN 64
\r
138 #define __TLS_AES_IV_LENGTH 16
\r
139 #define __TLS_AES_BLOCK_SIZE 16
\r
140 #define __TLS_AES_GCM_IV_LENGTH 4
\r
141 #define __TLS_GCM_TAG_LEN 16
\r
142 #define __TLS_MAX_TAG_LEN 16
\r
143 #define __TLS_MIN_FINISHED_OPAQUE_LEN 12
\r
145 #define __TLS_BLOB_INCREMENT 0xFFF
\r
146 #define __TLS_ASN1_MAXLEVEL 0xFF
\r
148 #define __DTLS_COOKIE_SIZE 32
\r
150 #define __TLS_MAX_SHA_SIZE 48
\r
151 #define __TLS_V11_HASH_SIZE 36 // 16(md5) + 20(sha1)
\r
152 #define __TLS_MAX_HASH_SIZE __TLS_MAX_SHA_SIZE
\r
153 #define __TLS_MAX_RSA_KEY 2048 // 16kbits
\r
155 #define __TLS_MAX_TLS_APP_SIZE 0x4000
\r
156 // max 1 second sleep
\r
157 #define __TLS_MAX_ERROR_SLEEP_uS 1000000
\r
158 // max 5 seconds context sleep
\r
159 #define __TLS_MAX_ERROR_IDLE_S 5
\r
161 #define VERSION_SUPPORTED(version, err) if ((version != TLS_V12) && (version != TLS_V11) && (version != TLS_V10) && (version != DTLS_V12) && (version != DTLS_V10)) { if ((version == SSL_V30) && (context->connection_status == 0)) { version = TLS_V12; } else { DEBUG_PRINT("UNSUPPORTED TLS VERSION %x\n", (int)version); return err;} }
\r
162 #define CHECK_SIZE(size, buf_size, err) if (((int)size > (int)buf_size) || ((int)buf_size < 0)) return err;
\r
163 #define TLS_IMPORT_CHECK_SIZE(buf_pos, size, buf_size) if (((int)size > (int)buf_size - buf_pos) || ((int)buf_pos > (int)buf_size)) { DEBUG_PRINT("IMPORT ELEMENT SIZE ERROR\n"); tls_destroy_context(context); return NULL; }
\r
164 #define CHECK_HANDSHAKE_STATE(context, n, limit) { if (context->hs_messages[n] >= limit) { DEBUG_PRINT("* UNEXPECTED MESSAGE (%i)\n", (int)n); payload_res = TLS_UNEXPECTED_MESSAGE; break; } context->hs_messages[n]++; }
\r
166 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
167 #define __TLS_CHACHA20_IV_LENGTH 12
\r
169 // ChaCha20 implementation by D. J. Bernstein
\r
172 #define CHACHA_MINKEYLEN 16
\r
173 #define CHACHA_NONCELEN 8
\r
174 #define CHACHA_NONCELEN_96 12
\r
175 #define CHACHA_CTRLEN 8
\r
176 #define CHACHA_CTRLEN_96 4
\r
177 #define CHACHA_STATELEN (CHACHA_NONCELEN+CHACHA_CTRLEN)
\r
178 #define CHACHA_BLOCKLEN 64
\r
180 #define POLY1305_MAX_AAD 32
\r
181 #define POLY1305_KEYLEN 32
\r
182 #define POLY1305_TAGLEN 16
\r
184 #define u_int unsigned int
\r
185 #define uint8_t unsigned char
\r
186 #define u_char unsigned char
\r
188 #define NULL (void *)0
\r
191 #if (CRYPT >= 0x0117) && (0)
\r
192 // to do: use ltc chacha/poly1305 implementation (working on big-endian machines)
\r
193 #define chacha_ctx chacha20poly1305_state
\r
194 #define poly1305_context poly1305_state
\r
196 #define __private_tls_poly1305_init(ctx, key, len) poly1305_init(ctx, key, len)
\r
197 #define __private_tls_poly1305_update(ctx, in, len) poly1305_process(ctx, in, len)
\r
198 #define __private_tls_poly1305_finish(ctx, mac) poly1305_done(ctx, mac, 16)
\r
200 struct chacha_ctx {
\r
202 uint8_t ks[CHACHA_BLOCKLEN];
\r
206 static inline void chacha_keysetup(struct chacha_ctx *x, const u_char *k, u_int kbits);
\r
207 static inline void chacha_ivsetup(struct chacha_ctx *x, const u_char *iv, const u_char *ctr);
\r
208 static inline void chacha_ivsetup_96bitnonce(struct chacha_ctx *x, const u_char *iv, const u_char *ctr);
\r
209 static inline void chacha_encrypt_bytes(struct chacha_ctx *x, const u_char *m, u_char *c, u_int bytes);
\r
210 static inline int poly1305_generate_key(unsigned char *key256, unsigned char *nonce, unsigned int noncelen, unsigned char *poly_key, unsigned int counter);
\r
212 #define poly1305_block_size 16
\r
213 #define poly1305_context poly1305_state_internal_t
\r
215 //========== ChaCha20 from D. J. Bernstein ========= //
\r
216 // Source available at https://cr.yp.to/chacha.html //
\r
218 typedef unsigned char u8;
\r
219 typedef unsigned int u32;
\r
221 typedef struct chacha_ctx chacha_ctx;
\r
223 #define U8C(v) (v##U)
\r
224 #define U32C(v) (v##U)
\r
226 #define U8V(v) ((u8)(v) & U8C(0xFF))
\r
227 #define U32V(v) ((u32)(v) & U32C(0xFFFFFFFF))
\r
229 #define ROTL32(v, n) \
\r
230 (U32V((v) << (n)) | ((v) >> (32 - (n))))
\r
232 #define __private_tls_U8TO32_LITTLE(p) \
\r
233 (((u32)((p)[0])) | \
\r
234 ((u32)((p)[1]) << 8) | \
\r
235 ((u32)((p)[2]) << 16) | \
\r
236 ((u32)((p)[3]) << 24))
\r
238 #define __private_tls_U32TO8_LITTLE(p, v) \
\r
240 (p)[0] = U8V((v)); \
\r
241 (p)[1] = U8V((v) >> 8); \
\r
242 (p)[2] = U8V((v) >> 16); \
\r
243 (p)[3] = U8V((v) >> 24); \
\r
246 #define ROTATE(v,c) (ROTL32(v,c))
\r
247 #define XOR(v,w) ((v) ^ (w))
\r
248 #define PLUS(v,w) (U32V((v) + (w)))
\r
249 #define PLUSONE(v) (PLUS((v),1))
\r
251 #define QUARTERROUND(a,b,c,d) \
\r
252 a = PLUS(a,b); d = ROTATE(XOR(d,a),16); \
\r
253 c = PLUS(c,d); b = ROTATE(XOR(b,c),12); \
\r
254 a = PLUS(a,b); d = ROTATE(XOR(d,a), 8); \
\r
255 c = PLUS(c,d); b = ROTATE(XOR(b,c), 7);
\r
257 static const char sigma[] = "expand 32-byte k";
\r
258 static const char tau[] = "expand 16-byte k";
\r
260 static inline void chacha_keysetup(chacha_ctx *x, const u8 *k, u32 kbits) {
\r
261 const char *constants;
\r
263 x->input[4] = __private_tls_U8TO32_LITTLE(k + 0);
\r
264 x->input[5] = __private_tls_U8TO32_LITTLE(k + 4);
\r
265 x->input[6] = __private_tls_U8TO32_LITTLE(k + 8);
\r
266 x->input[7] = __private_tls_U8TO32_LITTLE(k + 12);
\r
267 if (kbits == 256) { /* recommended */
\r
270 } else { /* kbits == 128 */
\r
273 x->input[8] = __private_tls_U8TO32_LITTLE(k + 0);
\r
274 x->input[9] = __private_tls_U8TO32_LITTLE(k + 4);
\r
275 x->input[10] = __private_tls_U8TO32_LITTLE(k + 8);
\r
276 x->input[11] = __private_tls_U8TO32_LITTLE(k + 12);
\r
277 x->input[0] = __private_tls_U8TO32_LITTLE(constants + 0);
\r
278 x->input[1] = __private_tls_U8TO32_LITTLE(constants + 4);
\r
279 x->input[2] = __private_tls_U8TO32_LITTLE(constants + 8);
\r
280 x->input[3] = __private_tls_U8TO32_LITTLE(constants + 12);
\r
283 static inline void chacha_key(chacha_ctx *x, u8 *k) {
\r
284 __private_tls_U32TO8_LITTLE(k, x->input[4]);
\r
285 __private_tls_U32TO8_LITTLE(k + 4, x->input[5]);
\r
286 __private_tls_U32TO8_LITTLE(k + 8, x->input[6]);
\r
287 __private_tls_U32TO8_LITTLE(k + 12, x->input[7]);
\r
289 __private_tls_U32TO8_LITTLE(k + 16, x->input[8]);
\r
290 __private_tls_U32TO8_LITTLE(k + 20, x->input[9]);
\r
291 __private_tls_U32TO8_LITTLE(k + 24, x->input[10]);
\r
292 __private_tls_U32TO8_LITTLE(k + 28, x->input[11]);
\r
295 static inline void chacha_nonce(chacha_ctx *x, u8 *nonce) {
\r
296 __private_tls_U32TO8_LITTLE(nonce + 0, x->input[13]);
\r
297 __private_tls_U32TO8_LITTLE(nonce + 4, x->input[14]);
\r
298 __private_tls_U32TO8_LITTLE(nonce + 8, x->input[15]);
\r
301 static inline void chacha_ivsetup(chacha_ctx *x, const u8 *iv, const u8 *counter) {
\r
302 x->input[12] = counter == NULL ? 0 : __private_tls_U8TO32_LITTLE(counter + 0);
\r
303 x->input[13] = counter == NULL ? 0 : __private_tls_U8TO32_LITTLE(counter + 4);
\r
305 x->input[14] = __private_tls_U8TO32_LITTLE(iv + 0);
\r
306 x->input[15] = __private_tls_U8TO32_LITTLE(iv + 4);
\r
310 static inline void chacha_ivsetup_96bitnonce(chacha_ctx *x, const u8 *iv, const u8 *counter) {
\r
311 x->input[12] = counter == NULL ? 0 : __private_tls_U8TO32_LITTLE(counter + 0);
\r
313 x->input[13] = __private_tls_U8TO32_LITTLE(iv + 0);
\r
314 x->input[14] = __private_tls_U8TO32_LITTLE(iv + 4);
\r
315 x->input[15] = __private_tls_U8TO32_LITTLE(iv + 8);
\r
319 static inline void chacha_ivupdate(chacha_ctx *x, const u8 *iv, const u8 *aad, const u8 *counter) {
\r
320 x->input[12] = counter == NULL ? 0 : __private_tls_U8TO32_LITTLE(counter + 0);
\r
321 x->input[13] = __private_tls_U8TO32_LITTLE(iv + 0);
\r
322 x->input[14] = __private_tls_U8TO32_LITTLE(iv + 4) ^ __private_tls_U8TO32_LITTLE(aad);
\r
323 x->input[15] = __private_tls_U8TO32_LITTLE(iv + 8) ^ __private_tls_U8TO32_LITTLE(aad + 4);
\r
326 static inline void chacha_encrypt_bytes(chacha_ctx *x, const u8 *m, u8 *c, u32 bytes) {
\r
327 u32 x0, x1, x2, x3, x4, x5, x6, x7;
\r
328 u32 x8, x9, x10, x11, x12, x13, x14, x15;
\r
329 u32 j0, j1, j2, j3, j4, j5, j6, j7;
\r
330 u32 j8, j9, j10, j11, j12, j13, j14, j15;
\r
331 u8 *ctarget = NULL;
\r
348 j10 = x->input[10];
\r
349 j11 = x->input[11];
\r
350 j12 = x->input[12];
\r
351 j13 = x->input[13];
\r
352 j14 = x->input[14];
\r
353 j15 = x->input[15];
\r
357 for (i = 0; i < bytes; ++i)
\r
379 for (i = 20; i > 0; i -= 2) {
\r
380 QUARTERROUND(x0, x4, x8, x12)
\r
381 QUARTERROUND(x1, x5, x9, x13)
\r
382 QUARTERROUND(x2, x6, x10, x14)
\r
383 QUARTERROUND(x3, x7, x11, x15)
\r
384 QUARTERROUND(x0, x5, x10, x15)
\r
385 QUARTERROUND(x1, x6, x11, x12)
\r
386 QUARTERROUND(x2, x7, x8, x13)
\r
387 QUARTERROUND(x3, x4, x9, x14)
\r
399 x10 = PLUS(x10, j10);
\r
400 x11 = PLUS(x11, j11);
\r
401 x12 = PLUS(x12, j12);
\r
402 x13 = PLUS(x13, j13);
\r
403 x14 = PLUS(x14, j14);
\r
404 x15 = PLUS(x15, j15);
\r
407 __private_tls_U32TO8_LITTLE(x->ks + 0, x0);
\r
408 __private_tls_U32TO8_LITTLE(x->ks + 4, x1);
\r
409 __private_tls_U32TO8_LITTLE(x->ks + 8, x2);
\r
410 __private_tls_U32TO8_LITTLE(x->ks + 12, x3);
\r
411 __private_tls_U32TO8_LITTLE(x->ks + 16, x4);
\r
412 __private_tls_U32TO8_LITTLE(x->ks + 20, x5);
\r
413 __private_tls_U32TO8_LITTLE(x->ks + 24, x6);
\r
414 __private_tls_U32TO8_LITTLE(x->ks + 28, x7);
\r
415 __private_tls_U32TO8_LITTLE(x->ks + 32, x8);
\r
416 __private_tls_U32TO8_LITTLE(x->ks + 36, x9);
\r
417 __private_tls_U32TO8_LITTLE(x->ks + 40, x10);
\r
418 __private_tls_U32TO8_LITTLE(x->ks + 44, x11);
\r
419 __private_tls_U32TO8_LITTLE(x->ks + 48, x12);
\r
420 __private_tls_U32TO8_LITTLE(x->ks + 52, x13);
\r
421 __private_tls_U32TO8_LITTLE(x->ks + 56, x14);
\r
422 __private_tls_U32TO8_LITTLE(x->ks + 60, x15);
\r
425 x0 = XOR(x0, __private_tls_U8TO32_LITTLE(m + 0));
\r
426 x1 = XOR(x1, __private_tls_U8TO32_LITTLE(m + 4));
\r
427 x2 = XOR(x2, __private_tls_U8TO32_LITTLE(m + 8));
\r
428 x3 = XOR(x3, __private_tls_U8TO32_LITTLE(m + 12));
\r
429 x4 = XOR(x4, __private_tls_U8TO32_LITTLE(m + 16));
\r
430 x5 = XOR(x5, __private_tls_U8TO32_LITTLE(m + 20));
\r
431 x6 = XOR(x6, __private_tls_U8TO32_LITTLE(m + 24));
\r
432 x7 = XOR(x7, __private_tls_U8TO32_LITTLE(m + 28));
\r
433 x8 = XOR(x8, __private_tls_U8TO32_LITTLE(m + 32));
\r
434 x9 = XOR(x9, __private_tls_U8TO32_LITTLE(m + 36));
\r
435 x10 = XOR(x10, __private_tls_U8TO32_LITTLE(m + 40));
\r
436 x11 = XOR(x11, __private_tls_U8TO32_LITTLE(m + 44));
\r
437 x12 = XOR(x12, __private_tls_U8TO32_LITTLE(m + 48));
\r
438 x13 = XOR(x13, __private_tls_U8TO32_LITTLE(m + 52));
\r
439 x14 = XOR(x14, __private_tls_U8TO32_LITTLE(m + 56));
\r
440 x15 = XOR(x15, __private_tls_U8TO32_LITTLE(m + 60));
\r
442 j12 = PLUSONE(j12);
\r
444 j13 = PLUSONE(j13);
\r
446 * Stopping at 2^70 bytes per nonce is the user's
\r
451 __private_tls_U32TO8_LITTLE(c + 0, x0);
\r
452 __private_tls_U32TO8_LITTLE(c + 4, x1);
\r
453 __private_tls_U32TO8_LITTLE(c + 8, x2);
\r
454 __private_tls_U32TO8_LITTLE(c + 12, x3);
\r
455 __private_tls_U32TO8_LITTLE(c + 16, x4);
\r
456 __private_tls_U32TO8_LITTLE(c + 20, x5);
\r
457 __private_tls_U32TO8_LITTLE(c + 24, x6);
\r
458 __private_tls_U32TO8_LITTLE(c + 28, x7);
\r
459 __private_tls_U32TO8_LITTLE(c + 32, x8);
\r
460 __private_tls_U32TO8_LITTLE(c + 36, x9);
\r
461 __private_tls_U32TO8_LITTLE(c + 40, x10);
\r
462 __private_tls_U32TO8_LITTLE(c + 44, x11);
\r
463 __private_tls_U32TO8_LITTLE(c + 48, x12);
\r
464 __private_tls_U32TO8_LITTLE(c + 52, x13);
\r
465 __private_tls_U32TO8_LITTLE(c + 56, x14);
\r
466 __private_tls_U32TO8_LITTLE(c + 60, x15);
\r
470 for (i = 0; i < bytes; ++i)
\r
473 x->input[12] = j12;
\r
474 x->input[13] = j13;
\r
475 x->unused = 64 - bytes;
\r
484 static inline void chacha20_block(chacha_ctx *x, unsigned char *c, int len) {
\r
487 unsigned int state[16];
\r
488 for (i = 0; i < 16; i++)
\r
489 state[i] = x->input[i];
\r
490 for (i = 20; i > 0; i -= 2) {
\r
491 QUARTERROUND(state[0], state[4], state[8], state[12])
\r
492 QUARTERROUND(state[1], state[5], state[9], state[13])
\r
493 QUARTERROUND(state[2], state[6], state[10], state[14])
\r
494 QUARTERROUND(state[3], state[7], state[11], state[15])
\r
495 QUARTERROUND(state[0], state[5], state[10], state[15])
\r
496 QUARTERROUND(state[1], state[6], state[11], state[12])
\r
497 QUARTERROUND(state[2], state[7], state[8], state[13])
\r
498 QUARTERROUND(state[3], state[4], state[9], state[14])
\r
501 for (i = 0; i < 16; i++)
\r
502 x->input[i] = PLUS(x->input[i], state[i]);
\r
504 for (i = 0; i < len; i += 4) {
\r
505 __private_tls_U32TO8_LITTLE(c + i, x->input[i/4]);
\r
509 static inline int poly1305_generate_key(unsigned char *key256, unsigned char *nonce, unsigned int noncelen, unsigned char *poly_key, unsigned int counter) {
\r
510 struct chacha_ctx ctx;
\r
512 memset(&ctx, 0, sizeof(ctx));
\r
513 chacha_keysetup(&ctx, key256, 256);
\r
514 switch (noncelen) {
\r
517 chacha_ivsetup(&ctx, nonce, (unsigned char *)&ctr);
\r
520 chacha_ivsetup_96bitnonce(&ctx, nonce, (unsigned char *)&counter);
\r
525 chacha20_block(&ctx, poly_key, POLY1305_KEYLEN);
\r
529 /* 17 + sizeof(size_t) + 14*sizeof(unsigned long) */
\r
530 typedef struct poly1305_state_internal_t {
\r
531 unsigned long r[5];
\r
532 unsigned long h[5];
\r
533 unsigned long pad[4];
\r
535 unsigned char buffer[poly1305_block_size];
\r
536 unsigned char final;
\r
537 } poly1305_state_internal_t;
\r
539 /* interpret four 8 bit unsigned integers as a 32 bit unsigned integer in little endian */
\r
540 static unsigned long __private_tls_U8TO32(const unsigned char *p) {
\r
542 (((unsigned long)(p[0] & 0xff) ) |
\r
543 ((unsigned long)(p[1] & 0xff) << 8) |
\r
544 ((unsigned long)(p[2] & 0xff) << 16) |
\r
545 ((unsigned long)(p[3] & 0xff) << 24));
\r
548 /* store a 32 bit unsigned integer as four 8 bit unsigned integers in little endian */
\r
549 static void __private_tls_U32TO8(unsigned char *p, unsigned long v) {
\r
550 p[0] = (v ) & 0xff;
\r
551 p[1] = (v >> 8) & 0xff;
\r
552 p[2] = (v >> 16) & 0xff;
\r
553 p[3] = (v >> 24) & 0xff;
\r
556 void __private_tls_poly1305_init(poly1305_context *ctx, const unsigned char key[32]) {
\r
557 poly1305_state_internal_t *st = (poly1305_state_internal_t *)ctx;
\r
559 /* r &= 0xffffffc0ffffffc0ffffffc0fffffff */
\r
560 st->r[0] = (__private_tls_U8TO32(&key[ 0]) ) & 0x3ffffff;
\r
561 st->r[1] = (__private_tls_U8TO32(&key[ 3]) >> 2) & 0x3ffff03;
\r
562 st->r[2] = (__private_tls_U8TO32(&key[ 6]) >> 4) & 0x3ffc0ff;
\r
563 st->r[3] = (__private_tls_U8TO32(&key[ 9]) >> 6) & 0x3f03fff;
\r
564 st->r[4] = (__private_tls_U8TO32(&key[12]) >> 8) & 0x00fffff;
\r
573 /* save pad for later */
\r
574 st->pad[0] = __private_tls_U8TO32(&key[16]);
\r
575 st->pad[1] = __private_tls_U8TO32(&key[20]);
\r
576 st->pad[2] = __private_tls_U8TO32(&key[24]);
\r
577 st->pad[3] = __private_tls_U8TO32(&key[28]);
\r
583 static void __private_tls_poly1305_blocks(poly1305_state_internal_t *st, const unsigned char *m, size_t bytes) {
\r
584 const unsigned long hibit = (st->final) ? 0 : (1UL << 24); /* 1 << 128 */
\r
585 unsigned long r0,r1,r2,r3,r4;
\r
586 unsigned long s1,s2,s3,s4;
\r
587 unsigned long h0,h1,h2,h3,h4;
\r
588 unsigned long long d0,d1,d2,d3,d4;
\r
608 while (bytes >= poly1305_block_size) {
\r
610 h0 += (__private_tls_U8TO32(m+ 0) ) & 0x3ffffff;
\r
611 h1 += (__private_tls_U8TO32(m+ 3) >> 2) & 0x3ffffff;
\r
612 h2 += (__private_tls_U8TO32(m+ 6) >> 4) & 0x3ffffff;
\r
613 h3 += (__private_tls_U8TO32(m+ 9) >> 6) & 0x3ffffff;
\r
614 h4 += (__private_tls_U8TO32(m+12) >> 8) | hibit;
\r
617 d0 = ((unsigned long long)h0 * r0) + ((unsigned long long)h1 * s4) + ((unsigned long long)h2 * s3) + ((unsigned long long)h3 * s2) + ((unsigned long long)h4 * s1);
\r
618 d1 = ((unsigned long long)h0 * r1) + ((unsigned long long)h1 * r0) + ((unsigned long long)h2 * s4) + ((unsigned long long)h3 * s3) + ((unsigned long long)h4 * s2);
\r
619 d2 = ((unsigned long long)h0 * r2) + ((unsigned long long)h1 * r1) + ((unsigned long long)h2 * r0) + ((unsigned long long)h3 * s4) + ((unsigned long long)h4 * s3);
\r
620 d3 = ((unsigned long long)h0 * r3) + ((unsigned long long)h1 * r2) + ((unsigned long long)h2 * r1) + ((unsigned long long)h3 * r0) + ((unsigned long long)h4 * s4);
\r
621 d4 = ((unsigned long long)h0 * r4) + ((unsigned long long)h1 * r3) + ((unsigned long long)h2 * r2) + ((unsigned long long)h3 * r1) + ((unsigned long long)h4 * r0);
\r
623 /* (partial) h %= p */
\r
624 c = (unsigned long)(d0 >> 26); h0 = (unsigned long)d0 & 0x3ffffff;
\r
625 d1 += c; c = (unsigned long)(d1 >> 26); h1 = (unsigned long)d1 & 0x3ffffff;
\r
626 d2 += c; c = (unsigned long)(d2 >> 26); h2 = (unsigned long)d2 & 0x3ffffff;
\r
627 d3 += c; c = (unsigned long)(d3 >> 26); h3 = (unsigned long)d3 & 0x3ffffff;
\r
628 d4 += c; c = (unsigned long)(d4 >> 26); h4 = (unsigned long)d4 & 0x3ffffff;
\r
629 h0 += c * 5; c = (h0 >> 26); h0 = h0 & 0x3ffffff;
\r
632 m += poly1305_block_size;
\r
633 bytes -= poly1305_block_size;
\r
643 void __private_tls_poly1305_finish(poly1305_context *ctx, unsigned char mac[16]) {
\r
644 poly1305_state_internal_t *st = (poly1305_state_internal_t *)ctx;
\r
645 unsigned long h0,h1,h2,h3,h4,c;
\r
646 unsigned long g0,g1,g2,g3,g4;
\r
647 unsigned long long f;
\r
648 unsigned long mask;
\r
650 /* process the remaining block */
\r
651 if (st->leftover) {
\r
652 size_t i = st->leftover;
\r
653 st->buffer[i++] = 1;
\r
654 for (; i < poly1305_block_size; i++)
\r
657 __private_tls_poly1305_blocks(st, st->buffer, poly1305_block_size);
\r
660 /* fully carry h */
\r
667 c = h1 >> 26; h1 = h1 & 0x3ffffff;
\r
668 h2 += c; c = h2 >> 26; h2 = h2 & 0x3ffffff;
\r
669 h3 += c; c = h3 >> 26; h3 = h3 & 0x3ffffff;
\r
670 h4 += c; c = h4 >> 26; h4 = h4 & 0x3ffffff;
\r
671 h0 += c * 5; c = h0 >> 26; h0 = h0 & 0x3ffffff;
\r
674 /* compute h + -p */
\r
675 g0 = h0 + 5; c = g0 >> 26; g0 &= 0x3ffffff;
\r
676 g1 = h1 + c; c = g1 >> 26; g1 &= 0x3ffffff;
\r
677 g2 = h2 + c; c = g2 >> 26; g2 &= 0x3ffffff;
\r
678 g3 = h3 + c; c = g3 >> 26; g3 &= 0x3ffffff;
\r
679 g4 = h4 + c - (1UL << 26);
\r
681 /* select h if h < p, or h + -p if h >= p */
\r
682 mask = (g4 >> ((sizeof(unsigned long) * 8) - 1)) - 1;
\r
689 h0 = (h0 & mask) | g0;
\r
690 h1 = (h1 & mask) | g1;
\r
691 h2 = (h2 & mask) | g2;
\r
692 h3 = (h3 & mask) | g3;
\r
693 h4 = (h4 & mask) | g4;
\r
695 /* h = h % (2^128) */
\r
696 h0 = ((h0 ) | (h1 << 26)) & 0xffffffff;
\r
697 h1 = ((h1 >> 6) | (h2 << 20)) & 0xffffffff;
\r
698 h2 = ((h2 >> 12) | (h3 << 14)) & 0xffffffff;
\r
699 h3 = ((h3 >> 18) | (h4 << 8)) & 0xffffffff;
\r
701 /* mac = (h + pad) % (2^128) */
\r
702 f = (unsigned long long)h0 + st->pad[0] ; h0 = (unsigned long)f;
\r
703 f = (unsigned long long)h1 + st->pad[1] + (f >> 32); h1 = (unsigned long)f;
\r
704 f = (unsigned long long)h2 + st->pad[2] + (f >> 32); h2 = (unsigned long)f;
\r
705 f = (unsigned long long)h3 + st->pad[3] + (f >> 32); h3 = (unsigned long)f;
\r
707 __private_tls_U32TO8(mac + 0, h0);
\r
708 __private_tls_U32TO8(mac + 4, h1);
\r
709 __private_tls_U32TO8(mac + 8, h2);
\r
710 __private_tls_U32TO8(mac + 12, h3);
\r
712 /* zero out the state */
\r
729 void __private_tls_poly1305_update(poly1305_context *ctx, const unsigned char *m, size_t bytes) {
\r
730 poly1305_state_internal_t *st = (poly1305_state_internal_t *)ctx;
\r
732 /* handle leftover */
\r
733 if (st->leftover) {
\r
734 size_t want = (poly1305_block_size - st->leftover);
\r
737 for (i = 0; i < want; i++)
\r
738 st->buffer[st->leftover + i] = m[i];
\r
741 st->leftover += want;
\r
742 if (st->leftover < poly1305_block_size)
\r
744 __private_tls_poly1305_blocks(st, st->buffer, poly1305_block_size);
\r
748 /* process full blocks */
\r
749 if (bytes >= poly1305_block_size) {
\r
750 size_t want = (bytes & ~(poly1305_block_size - 1));
\r
751 __private_tls_poly1305_blocks(st, m, want);
\r
756 /* store leftover */
\r
758 for (i = 0; i < bytes; i++)
\r
759 st->buffer[st->leftover + i] = m[i];
\r
760 st->leftover += bytes;
\r
764 int poly1305_verify(const unsigned char mac1[16], const unsigned char mac2[16]) {
\r
766 unsigned int dif = 0;
\r
767 for (i = 0; i < 16; i++)
\r
768 dif |= (mac1[i] ^ mac2[i]);
\r
769 dif = (dif - 1) >> ((sizeof(unsigned int) * 8) - 1);
\r
773 void chacha20_poly1305_key(struct chacha_ctx *ctx, unsigned char *poly1305_key) {
\r
774 unsigned char key[32];
\r
775 unsigned char nonce[12];
\r
776 chacha_key(ctx, key);
\r
777 chacha_nonce(ctx, nonce);
\r
778 poly1305_generate_key(key, nonce, sizeof(nonce), poly1305_key, 0);
\r
781 int chacha20_poly1305_aead(struct chacha_ctx *ctx, unsigned char *pt, unsigned int len, unsigned char *aad, unsigned int aad_len, unsigned char *poly_key, unsigned char *out) {
\r
782 static unsigned char zeropad[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
\r
783 if (aad_len > POLY1305_MAX_AAD)
\r
786 unsigned int counter = 1;
\r
787 chacha_ivsetup_96bitnonce(ctx, NULL, (unsigned char *)&counter);
\r
788 chacha_encrypt_bytes(ctx, pt, out, len);
\r
790 poly1305_context aead_ctx;
\r
791 __private_tls_poly1305_init(&aead_ctx, poly_key);
\r
792 __private_tls_poly1305_update(&aead_ctx, aad, aad_len);
\r
793 int rem = aad_len % 16;
\r
795 __private_tls_poly1305_update(&aead_ctx, zeropad, 16 - rem);
\r
796 __private_tls_poly1305_update(&aead_ctx, out, len);
\r
799 __private_tls_poly1305_update(&aead_ctx, zeropad, 16 - rem);
\r
801 unsigned char trail[16];
\r
802 __private_tls_U32TO8(&trail[0], aad_len);
\r
803 *(int *)&trail[4] = 0;
\r
804 __private_tls_U32TO8(&trail[8], len);
\r
805 *(int *)&trail[12] = 0;
\r
807 __private_tls_poly1305_update(&aead_ctx, trail, 16);
\r
808 __private_tls_poly1305_finish(&aead_ctx, out + len);
\r
810 return len + POLY1305_TAGLEN;
\r
822 KEA_ec_diffie_hellman
\r
823 } KeyExchangeAlgorithm;
\r
830 rsa_ephemeral_dh_RESERVED = 5,
\r
831 dss_ephemeral_dh_RESERVED = 6,
\r
832 fortezza_dms_RESERVED = 20,
\r
834 rsa_fixed_ecdh = 65,
\r
835 ecdsa_fixed_ecdh = 66
\r
836 } TLSClientCertificateType;
\r
847 } TLSHashAlgorithm;
\r
854 } TLSSignatureAlgorithm;
\r
856 struct __private_OID_chain {
\r
858 unsigned char *oid;
\r
861 struct TLSCertificate {
\r
862 unsigned short version;
\r
863 unsigned int algorithm;
\r
864 unsigned int key_algorithm;
\r
865 unsigned int ec_algorithm;
\r
866 unsigned char *exponent;
\r
867 unsigned int exponent_len;
\r
869 unsigned int pk_len;
\r
870 unsigned char *priv;
\r
871 unsigned int priv_len;
\r
872 unsigned char *issuer_country;
\r
873 unsigned char *issuer_state;
\r
874 unsigned char *issuer_location;
\r
875 unsigned char *issuer_entity;
\r
876 unsigned char *issuer_subject;
\r
877 unsigned char *not_before;
\r
878 unsigned char *not_after;
\r
879 unsigned char *country;
\r
880 unsigned char *state;
\r
881 unsigned char *location;
\r
882 unsigned char *entity;
\r
883 unsigned char *subject;
\r
884 unsigned char **san;
\r
885 unsigned short san_length;
\r
886 unsigned char *ocsp;
\r
887 unsigned char *serial_number;
\r
888 unsigned int serial_len;
\r
889 unsigned char *sign_key;
\r
890 unsigned int sign_len;
\r
891 unsigned char *fingerprint;
\r
892 unsigned char *der_bytes;
\r
893 unsigned int der_len;
\r
894 unsigned char *bytes;
\r
900 symmetric_CBC aes_local;
\r
901 gcm_state aes_gcm_local;
\r
902 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
903 chacha_ctx chacha_local;
\r
907 symmetric_CBC aes_remote;
\r
908 gcm_state aes_gcm_remote;
\r
909 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
910 chacha_ctx chacha_remote;
\r
914 unsigned char local_mac[__TLS_MAX_MAC_SIZE];
\r
915 unsigned char local_aead_iv[__TLS_AES_GCM_IV_LENGTH];
\r
916 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
917 unsigned char local_nonce[__TLS_CHACHA20_IV_LENGTH];
\r
921 unsigned char remote_aead_iv[__TLS_AES_GCM_IV_LENGTH];
\r
922 unsigned char remote_mac[__TLS_MAX_MAC_SIZE];
\r
923 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
924 unsigned char remote_nonce[__TLS_CHACHA20_IV_LENGTH];
\r
927 unsigned char created;
\r
932 #ifdef TLS_LEGACY_SUPPORT
\r
935 unsigned char created;
\r
938 #ifdef TLS_FORWARD_SECRECY
\r
939 #define mp_init(a) ltc_mp.init(a)
\r
940 #define mp_init_multi ltc_init_multi
\r
941 #define mp_clear(a) ltc_mp.deinit(a)
\r
942 #define mp_clear_multi ltc_deinit_multi
\r
943 #define mp_count_bits(a) ltc_mp.count_bits(a)
\r
944 #define mp_read_radix(a, b, c) ltc_mp.read_radix(a, b, c)
\r
945 #define mp_unsigned_bin_size(a) ltc_mp.unsigned_size(a)
\r
946 #define mp_to_unsigned_bin(a, b) ltc_mp.unsigned_write(a, b)
\r
947 #define mp_read_unsigned_bin(a, b, c) ltc_mp.unsigned_read(a, b, c)
\r
948 #define mp_exptmod(a, b, c, d) ltc_mp.exptmod(a, b, c, d)
\r
949 #define mp_add(a, b, c) ltc_mp.add(a, b, c)
\r
950 #define mp_mul(a, b, c) ltc_mp.mul(a, b, c)
\r
951 #define mp_cmp(a, b) ltc_mp.compare(a, b)
\r
952 #define mp_cmp_d(a, b) ltc_mp.compare_d(a, b)
\r
953 #define mp_sqr(a, b) ltc_mp.sqr(a, b)
\r
954 #define mp_mod(a, b, c) ltc_mp.mpdiv(a, b, NULL, c)
\r
955 #define mp_sub(a, b, c) ltc_mp.sub(a, b, c)
\r
956 #define mp_set(a, b) ltc_mp.set_int(a, b)
\r
965 struct ECCCurveParameters {
\r
975 ltc_ecc_set_type dp;
\r
978 static struct ECCCurveParameters secp192r1 = {
\r
982 "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", // P
\r
983 "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", // A
\r
984 "64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1", // B
\r
985 "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012", // Gx
\r
986 "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811", // Gy
\r
987 "FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831" // order (n)
\r
991 static struct ECCCurveParameters secp224r1 = {
\r
995 "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001", // P
\r
996 "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE", // A
\r
997 "B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4", // B
\r
998 "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21", // Gx
\r
999 "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34", // Gy
\r
1000 "FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D" // order (n)
\r
1003 static struct ECCCurveParameters secp224k1 = {
\r
1007 "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFE56D", // P
\r
1008 "00000000000000000000000000000000000000000000000000000000", // A
\r
1009 "00000000000000000000000000000000000000000000000000000005", // B
\r
1010 "A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C", // Gx
\r
1011 "7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5", // Gy
\r
1012 "0000000000000000000000000001DCE8D2EC6184CAF0A971769FB1F7" // order (n)
\r
1015 static struct ECCCurveParameters secp256r1 = {
\r
1019 "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", // P
\r
1020 "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", // A
\r
1021 "5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B", // B
\r
1022 "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296", // Gx
\r
1023 "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5", // Gy
\r
1024 "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551" // order (n)
\r
1027 static struct ECCCurveParameters secp256k1 = {
\r
1031 "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", // P
\r
1032 "0000000000000000000000000000000000000000000000000000000000000000", // A
\r
1033 "0000000000000000000000000000000000000000000000000000000000000007", // B
\r
1034 "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", // Gx
\r
1035 "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", // Gy
\r
1036 "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141" // order (n)
\r
1039 static struct ECCCurveParameters secp384r1 = {
\r
1043 "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF", // P
\r
1044 "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC", // A
\r
1045 "B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF", // B
\r
1046 "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7", // Gx
\r
1047 "3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F", // Gy
\r
1048 "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973" // order (n)
\r
1051 static struct ECCCurveParameters secp521r1 = {
\r
1055 "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", // P
\r
1056 "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", // A
\r
1057 "0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", // B
\r
1058 "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66", // Gx
\r
1059 "011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650", // Gy
\r
1060 "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409" // order (n)
\r
1063 static struct ECCCurveParameters * const default_curve = &secp256r1;
\r
1065 void init_curve(struct ECCCurveParameters *curve) {
\r
1066 curve->dp.size = curve->size;
\r
1067 curve->dp.name = (char *)curve->name;
\r
1068 curve->dp.B = (char *)curve->B;
\r
1069 curve->dp.prime = (char *)curve->P;
\r
1070 curve->dp.Gx = (char *)curve->Gx;
\r
1071 curve->dp.Gy = (char *)curve->Gy;
\r
1072 curve->dp.order = (char *)curve->order;
\r
1075 void init_curves() {
\r
1076 init_curve(&secp192r1);
\r
1077 init_curve(&secp224r1);
\r
1078 init_curve(&secp224k1);
\r
1079 init_curve(&secp256r1);
\r
1080 init_curve(&secp256k1);
\r
1081 init_curve(&secp384r1);
\r
1082 init_curve(&secp521r1);
\r
1086 struct TLSContext {
\r
1087 unsigned char remote_random[__TLS_CLIENT_RANDOM_SIZE];
\r
1088 unsigned char local_random[__TLS_SERVER_RANDOM_SIZE];
\r
1089 unsigned char session[__TLS_MAX_SESSION_ID];
\r
1090 unsigned char session_size;
\r
1091 unsigned short cipher;
\r
1092 unsigned short version;
\r
1093 unsigned char is_server;
\r
1094 struct TLSCertificate **certificates;
\r
1095 struct TLSCertificate *private_key;
\r
1096 #ifdef TLS_ECDSA_SUPPORTED
\r
1097 struct TLSCertificate *ec_private_key;
\r
1099 #ifdef TLS_FORWARD_SECRECY
\r
1102 char *default_dhe_p;
\r
1103 char *default_dhe_g;
\r
1104 const struct ECCCurveParameters *curve;
\r
1106 struct TLSCertificate **client_certificates;
\r
1107 unsigned int certificates_count;
\r
1108 unsigned int client_certificates_count;
\r
1109 unsigned char *master_key;
\r
1110 unsigned int master_key_len;
\r
1111 unsigned char *premaster_key;
\r
1112 unsigned int premaster_key_len;
\r
1113 unsigned char cipher_spec_set;
\r
1115 TLSHash *handshake_hash;
\r
1117 unsigned char *message_buffer;
\r
1118 unsigned int message_buffer_len;
\r
1119 uint64_t remote_sequence_number;
\r
1120 uint64_t local_sequence_number;
\r
1122 unsigned char connection_status;
\r
1123 unsigned char critical_error;
\r
1124 unsigned char error_code;
\r
1126 unsigned char *tls_buffer;
\r
1127 unsigned int tls_buffer_len;
\r
1129 unsigned char *application_buffer;
\r
1130 unsigned int application_buffer_len;
\r
1131 unsigned char is_child;
\r
1132 unsigned char exportable;
\r
1133 unsigned char *exportable_keys;
\r
1134 unsigned char exportable_size;
\r
1136 unsigned char request_client_certificate;
\r
1137 unsigned char dtls;
\r
1138 unsigned short dtls_epoch_local;
\r
1139 unsigned short dtls_epoch_remote;
\r
1140 unsigned char *dtls_cookie;
\r
1141 unsigned char dtls_cookie_len;
\r
1142 unsigned char dtls_seq;
\r
1143 unsigned char *cached_handshake;
\r
1144 unsigned int cached_handshake_len;
\r
1145 unsigned char client_verified;
\r
1146 // handshake messages flags
\r
1147 unsigned char hs_messages[11];
\r
1149 struct TLSCertificate **root_certificates;
\r
1150 unsigned int root_count;
\r
1151 #ifdef TLS_ACCEPT_SECURE_RENEGOTIATION
\r
1152 unsigned char *verify_data;
\r
1153 unsigned char verify_len;
\r
1156 unsigned char alpn_count;
\r
1157 char *negotiated_alpn;
\r
1158 unsigned int sleep_until;
\r
1161 struct TLSPacket {
\r
1162 unsigned char *buf;
\r
1164 unsigned int size;
\r
1165 unsigned char broken;
\r
1166 struct TLSContext *context;
\r
1169 #ifdef SSL_COMPATIBLE_INTERFACE
\r
1171 typedef int (*SOCKET_RECV_CALLBACK)(int socket, void *buffer, size_t length, int flags);
\r
1172 typedef int (*SOCKET_SEND_CALLBACK)(int socket, const void *buffer, size_t length, int flags);
\r
1175 #include <winsock2.h>
\r
1177 #include <sys/socket.h>
\r
1181 static const unsigned int version_id[] = {1, 1, 1, 0};
\r
1182 static const unsigned int pk_id[] = {1, 1, 7, 0};
\r
1183 static const unsigned int serial_id[] = {1, 1, 2, 1, 0};
\r
1184 static const unsigned int issurer_id[] = {1, 1, 4, 0};
\r
1185 static const unsigned int owner_id[] = {1, 1, 6, 0};
\r
1186 static const unsigned int validity_id[] = {1, 1, 5, 0};
\r
1187 static const unsigned int algorithm_id[] = {1, 1, 3, 0};
\r
1188 static const unsigned int sign_id[] = {1, 3, 2, 1, 0};
\r
1189 static const unsigned int priv_id[] = {1, 4, 0};
\r
1190 static const unsigned int priv_der_id[] = {1, 3, 1, 0};
\r
1191 static const unsigned int ecc_priv_id[] = {1, 2, 0};
\r
1193 static const unsigned char country_oid[] = {0x55, 0x04, 0x06, 0x00};
\r
1194 static const unsigned char state_oid[] = {0x55, 0x04, 0x08, 0x00};
\r
1195 static const unsigned char location_oid[] = {0x55, 0x04, 0x07, 0x00};
\r
1196 static const unsigned char entity_oid[] = {0x55, 0x04, 0x0A, 0x00};
\r
1197 static const unsigned char subject_oid[] = {0x55, 0x04, 0x03, 0x00};
\r
1198 static const unsigned char san_oid[] = {0x55, 0x1D, 0x11, 0x00};
\r
1199 static const unsigned char ocsp_oid[] = {0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x01, 0x00};
\r
1201 static const unsigned char TLS_RSA_SIGN_RSA_OID[] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x00};
\r
1202 static const unsigned char TLS_RSA_SIGN_MD5_OID[] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x04, 0x00};
\r
1203 static const unsigned char TLS_RSA_SIGN_SHA1_OID[] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x05, 0x00};
\r
1204 static const unsigned char TLS_RSA_SIGN_SHA256_OID[] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x00};
\r
1205 static const unsigned char TLS_RSA_SIGN_SHA384_OID[] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0C, 0x00};
\r
1206 static const unsigned char TLS_RSA_SIGN_SHA512_OID[] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0D, 0x00};
\r
1208 // static const unsigned char TLS_ECDSA_SIGN_SHA1_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x01, 0x05, 0x00, 0x00};
\r
1209 // static const unsigned char TLS_ECDSA_SIGN_SHA224_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x01, 0x05, 0x00, 0x00};
\r
1210 // static const unsigned char TLS_ECDSA_SIGN_SHA256_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02, 0x05, 0x00, 0x00};
\r
1211 // static const unsigned char TLS_ECDSA_SIGN_SHA384_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x03, 0x05, 0x00, 0x00};
\r
1212 // static const unsigned char TLS_ECDSA_SIGN_SHA512_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x04, 0x05, 0x00, 0x00};
\r
1214 static const unsigned char TLS_EC_PUBLIC_KEY_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01, 0x00};
\r
1216 static const unsigned char TLS_EC_prime192v1_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x01, 0x00};
\r
1217 static const unsigned char TLS_EC_prime192v2_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x02, 0x00};
\r
1218 static const unsigned char TLS_EC_prime192v3_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x03, 0x00};
\r
1219 static const unsigned char TLS_EC_prime239v1_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x04, 0x00};
\r
1220 static const unsigned char TLS_EC_prime239v2_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x05, 0x00};
\r
1221 static const unsigned char TLS_EC_prime239v3_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x06, 0x00};
\r
1222 static const unsigned char TLS_EC_prime256v1_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07, 0x00};
\r
1224 #define TLS_EC_secp256r1_OID TLS_EC_prime256v1_OID
\r
1225 static const unsigned char TLS_EC_secp224r1_OID[] = {0x2B, 0x81, 0x04, 0x00, 0x21, 0x00};
\r
1226 static const unsigned char TLS_EC_secp384r1_OID[] = {0x2B, 0x81, 0x04, 0x00, 0x22, 0x00};
\r
1227 static const unsigned char TLS_EC_secp521r1_OID[] = {0x2B, 0x81, 0x04, 0x00, 0x23, 0x00};
\r
1229 struct TLSCertificate *asn1_parse(struct TLSContext *context, const unsigned char *buffer, int size, int client_cert);
\r
1230 int __private_tls_update_hash(struct TLSContext *context, const unsigned char *in, unsigned int len);
\r
1231 struct TLSPacket *tls_build_finished(struct TLSContext *context);
\r
1232 unsigned int __private_tls_hmac_message(unsigned char local, struct TLSContext *context, const unsigned char *buf, int buf_len, const unsigned char *buf2, int buf_len2, unsigned char *out, unsigned int outlen, uint64_t remote_sequence_number);
\r
1233 int tls_random(unsigned char *key, int len);
\r
1234 void tls_destroy_packet(struct TLSPacket *packet);
\r
1235 struct TLSPacket *tls_build_hello(struct TLSContext *context);
\r
1236 struct TLSPacket *tls_build_certificate(struct TLSContext *context);
\r
1237 struct TLSPacket *tls_build_done(struct TLSContext *context);
\r
1238 struct TLSPacket *tls_build_alert(struct TLSContext *context, char critical, unsigned char code);
\r
1239 struct TLSPacket *tls_build_change_cipher_spec(struct TLSContext *context);
\r
1240 struct TLSPacket *tls_build_verify_request(struct TLSContext *context);
\r
1241 int __private_tls_crypto_create(struct TLSContext *context, int key_length, int iv_length, unsigned char *localkey, unsigned char *localiv, unsigned char *remotekey, unsigned char *remoteiv);
\r
1242 int __private_tls_get_hash(struct TLSContext *context, unsigned char *hout);
\r
1243 int __private_tls_build_random(struct TLSPacket *packet);
\r
1244 unsigned int __private_tls_mac_length(struct TLSContext *context);
\r
1245 void __private_dtls_handshake_data(struct TLSContext *context, struct TLSPacket *packet, unsigned int dataframe);
\r
1246 #ifdef TLS_FORWARD_SECRECY
\r
1247 void __private_tls_dhe_free(struct TLSContext *context);
\r
1248 void __private_tls_ecc_dhe_free(struct TLSContext *context);
\r
1249 void __private_tls_dh_clear_key(DHKey *key);
\r
1252 static unsigned char dependecies_loaded = 0;
\r
1254 // static unsigned char TLS_DSA_SIGN_SHA1_OID[] = {0x2A, 0x86, 0x52, 0xCE, 0x38, 0x04, 0x03, 0x00};
\r
1257 static const char cd64[] = "|$$$}rstuvwxyz{$$$$$$$>?@ABCDEFGHIJKLMNOPQRSTUVW$$$$$$XYZ[\\]^_`abcdefghijklmnopq";
\r
1259 void __private_b64_decodeblock(unsigned char in[4], unsigned char out[3]) {
\r
1260 out[0] = (unsigned char )(in[0] << 2 | in[1] >> 4);
\r
1261 out[1] = (unsigned char )(in[1] << 4 | in[2] >> 2);
\r
1262 out[2] = (unsigned char )(((in[2] << 6) & 0xc0) | in[3]);
\r
1265 int __private_b64_decode(const char *in_buffer, int in_buffer_size, unsigned char *out_buffer) {
\r
1266 unsigned char in[4], out[3], v;
\r
1269 const char *ptr = in_buffer;
\r
1270 char *out_ptr = (char *)out_buffer;
\r
1272 while (ptr <= in_buffer + in_buffer_size) {
\r
1273 for (len = 0, i = 0; i < 4 && (ptr <= in_buffer + in_buffer_size); i++) {
\r
1275 while ((ptr <= in_buffer + in_buffer_size) && v == 0) {
\r
1276 v = (unsigned char)ptr[0];
\r
1278 v = (unsigned char)((v < 43 || v > 122) ? 0 : cd64[v - 43]);
\r
1280 v = (unsigned char)((v == '$') ? 0 : v - 61);
\r
1282 if (ptr <= in_buffer + in_buffer_size) {
\r
1285 in[i] = (unsigned char)(v - 1);
\r
1291 __private_b64_decodeblock(in, out);
\r
1292 for (i = 0; i < len - 1; i++) {
\r
1293 out_ptr[0] = out[i];
\r
1298 return (int)((intptr_t)out_ptr - (intptr_t)out_buffer);
\r
1302 if (dependecies_loaded)
\r
1304 DEBUG_PRINT("Initializing dependencies\n");
\r
1305 dependecies_loaded = 1;
\r
1307 ltc_mp = ltm_desc;
\r
1310 ltc_mp = tfm_desc;
\r
1313 ltc_mp = gmp_desc;
\r
1317 register_prng(&sprng_desc);
\r
1318 register_hash(&sha256_desc);
\r
1319 register_hash(&sha1_desc);
\r
1320 register_hash(&sha384_desc);
\r
1321 register_hash(&sha512_desc);
\r
1322 register_hash(&md5_desc);
\r
1323 register_cipher(&aes_desc);
\r
1324 #ifdef TLS_FORWARD_SECRECY
\r
1329 #ifdef TLS_FORWARD_SECRECY
\r
1330 int __private_tls_dh_shared_secret(DHKey *private_key, DHKey *public_key, unsigned char *out, unsigned long *outlen) {
\r
1335 if ((!private_key) || (!public_key) || (!out) || (!outlen))
\r
1336 return TLS_GENERIC_ERROR;
\r
1338 /* compute y^x mod p */
\r
1339 if ((err = mp_init(&tmp)) != CRYPT_OK)
\r
1342 if ((err = mp_exptmod(public_key->y, private_key->x, private_key->p, tmp)) != CRYPT_OK) {
\r
1347 x = (unsigned long)mp_unsigned_bin_size(tmp);
\r
1348 if (*outlen < x) {
\r
1349 err = CRYPT_BUFFER_OVERFLOW;
\r
1354 if ((err = mp_to_unsigned_bin(tmp, out)) != CRYPT_OK) {
\r
1363 unsigned char *__private_tls_decrypt_dhe(struct TLSContext *context, const unsigned char *buffer, unsigned int len, unsigned int *size, int clear_key) {
\r
1365 if ((!len) || (!context) || (!context->dhe)) {
\r
1366 DEBUG_PRINT("No private DHE key set\n");
\r
1370 unsigned char *out = (unsigned char *)TLS_MALLOC(len);
\r
1371 unsigned long out_size = len;
\r
1374 if (mp_init(&Yc)) {
\r
1375 DEBUG_PRINT("ERROR CREATING Yc\n");
\r
1378 if (mp_read_unsigned_bin(Yc, (unsigned char *)buffer, len)) {
\r
1379 DEBUG_PRINT("ERROR LOADING DHE Yc\n");
\r
1384 memset(&client_key, 0, sizeof(DHKey));
\r
1386 client_key.p = context->dhe->p;
\r
1387 client_key.g = context->dhe->g;
\r
1388 client_key.y = Yc;
\r
1389 int err = __private_tls_dh_shared_secret(context->dhe, &client_key, out, &out_size);
\r
1390 // don't delete p and g
\r
1391 client_key.p = NULL;
\r
1392 client_key.g = NULL;
\r
1393 __private_tls_dh_clear_key(&client_key);
\r
1394 // not needing the dhe key anymore
\r
1396 __private_tls_dhe_free(context);
\r
1398 DEBUG_PRINT("DHE DECRYPT ERROR %i\n", err);
\r
1402 DEBUG_PRINT("OUT_SIZE: %lu\n", out_size);
\r
1403 DEBUG_DUMP_HEX_LABEL("DHE", out, out_size);
\r
1404 *size = (unsigned int)out_size;
\r
1408 unsigned char *__private_tls_decrypt_ecc_dhe(struct TLSContext *context, const unsigned char *buffer, unsigned int len, unsigned int *size, int clear_key) {
\r
1410 if ((!len) || (!context) || (!context->ecc_dhe)) {
\r
1411 DEBUG_PRINT("No private ECC DHE key set\n");
\r
1415 const struct ECCCurveParameters *curve;
\r
1416 if (context->curve)
\r
1417 curve = context->curve;
\r
1419 curve = default_curve;
\r
1421 ltc_ecc_set_type *dp = (ltc_ecc_set_type *)&curve->dp;
\r
1423 ecc_key client_key;
\r
1424 memset(&client_key, 0, sizeof(client_key));
\r
1425 if (ecc_ansi_x963_import_ex(buffer, len, &client_key, dp)) {
\r
1426 DEBUG_PRINT("Error importing ECC DHE key\n");
\r
1429 unsigned char *out = (unsigned char *)TLS_MALLOC(len);
\r
1430 unsigned long out_size = len;
\r
1432 int err = ecc_shared_secret(context->ecc_dhe, &client_key, out, &out_size);
\r
1433 ecc_free(&client_key);
\r
1435 __private_tls_ecc_dhe_free(context);
\r
1437 DEBUG_PRINT("ECC DHE DECRYPT ERROR %i\n", err);
\r
1441 DEBUG_PRINT("OUT_SIZE: %lu\n", out_size);
\r
1442 DEBUG_DUMP_HEX_LABEL("ECC DHE", out, out_size);
\r
1443 *size = (unsigned int)out_size;
\r
1448 unsigned char *__private_tls_decrypt_rsa(struct TLSContext *context, const unsigned char *buffer, unsigned int len, unsigned int *size) {
\r
1450 if ((!len) || (!context) || (!context->private_key) || (!context->private_key->der_bytes) || (!context->private_key->der_len)) {
\r
1451 DEBUG_PRINT("No private key set\n");
\r
1457 err = rsa_import(context->private_key->der_bytes, context->private_key->der_len, &key);
\r
1460 DEBUG_PRINT("Error importing RSA key (code: %i)\n", err);
\r
1463 unsigned char *out = (unsigned char *)TLS_MALLOC(len);
\r
1464 unsigned long out_size = len;
\r
1465 int hash_idx = find_hash("sha256");
\r
1467 err = rsa_decrypt_key_ex(buffer, len, out, &out_size, (unsigned char *)"Concept", 7, hash_idx, LTC_PKCS_1_V1_5, &res, &key);
\r
1469 if ((err) || (!out_size)) {
\r
1470 DEBUG_PRINT("RSA DECRYPT ERROR\n");
\r
1474 *size = (unsigned int)out_size;
\r
1478 unsigned char *__private_tls_encrypt_rsa(struct TLSContext *context, const unsigned char *buffer, unsigned int len, unsigned int *size) {
\r
1480 if ((!len) || (!context) || (!context->certificates) || (!context->certificates_count) || (!context->certificates[0]) ||
\r
1481 (!context->certificates[0]->der_bytes) || (!context->certificates[0]->der_len)) {
\r
1482 DEBUG_PRINT("No certificate set\n");
\r
1488 err = rsa_import(context->certificates[0]->der_bytes, context->certificates[0]->der_len, &key);
\r
1491 DEBUG_PRINT("Error importing RSA certificate (code: %i)\n", err);
\r
1494 unsigned long out_size = __TLS_MAX_RSA_KEY;
\r
1495 unsigned char *out = (unsigned char *)TLS_MALLOC(out_size);
\r
1496 int hash_idx = find_hash("sha256");
\r
1497 int prng_idx = find_prng("sprng");
\r
1498 err = rsa_encrypt_key_ex(buffer, len, out, &out_size, (unsigned char *)"Concept", 7, NULL, prng_idx, hash_idx, LTC_PKCS_1_V1_5, &key);
\r
1500 if ((err) || (!out_size)) {
\r
1504 *size = (unsigned int)out_size;
\r
1508 #ifdef TLS_LEGACY_SUPPORT
\r
1509 int __private_rsa_verify_hash_md5sha1(const unsigned char *sig, unsigned long siglen, unsigned char *hash, unsigned long hashlen, int *stat, rsa_key *key) {
\r
1510 unsigned long modulus_bitlen, modulus_bytelen, x;
\r
1512 unsigned char *tmpbuf = NULL;
\r
1514 if ((hash == NULL) || (sig == NULL) || (stat == NULL) || (key == NULL) || (!siglen) || (!hashlen))
\r
1515 return TLS_GENERIC_ERROR;
\r
1519 modulus_bitlen = mp_count_bits((key->N));
\r
1521 modulus_bytelen = mp_unsigned_bin_size((key->N));
\r
1522 if (modulus_bytelen != siglen)
\r
1523 return TLS_GENERIC_ERROR;
\r
1525 tmpbuf = (unsigned char *)TLS_MALLOC(siglen);
\r
1527 return TLS_GENERIC_ERROR;
\r
1530 if ((err = ltc_mp.rsa_me(sig, siglen, tmpbuf, &x, PK_PUBLIC, key)) != CRYPT_OK) {
\r
1535 if (x != siglen) {
\r
1537 return CRYPT_INVALID_PACKET;
\r
1539 unsigned long out_len = siglen;
\r
1540 unsigned char *out = (unsigned char *)TLS_MALLOC(siglen);
\r
1543 return TLS_GENERIC_ERROR;
\r
1547 err = pkcs_1_v1_5_decode(tmpbuf, x, LTC_PKCS_1_EMSA, modulus_bitlen, out, &out_len, &decoded);
\r
1549 if (out_len == hashlen) {
\r
1550 if (!memcmp(out, hash, hashlen))
\r
1561 int __private_tls_verify_rsa(struct TLSContext *context, unsigned int hash_type, const unsigned char *buffer, unsigned int len, const unsigned char *message, unsigned int message_len) {
\r
1566 if (context->is_server) {
\r
1567 if ((!len) || (!context) || (!context->client_certificates) || (!context->client_certificates_count) || (!context->client_certificates[0]) ||
\r
1568 (!context->client_certificates[0]->der_bytes) || (!context->client_certificates[0]->der_len)) {
\r
1569 DEBUG_PRINT("No client certificate set\n");
\r
1570 return TLS_GENERIC_ERROR;
\r
1572 err = rsa_import(context->client_certificates[0]->der_bytes, context->client_certificates[0]->der_len, &key);
\r
1574 if ((!len) || (!context) || (!context->certificates) || (!context->certificates_count) || (!context->certificates[0]) ||
\r
1575 (!context->certificates[0]->der_bytes) || (!context->certificates[0]->der_len)) {
\r
1576 DEBUG_PRINT("No server certificate set\n");
\r
1577 return TLS_GENERIC_ERROR;
\r
1579 err = rsa_import(context->certificates[0]->der_bytes, context->certificates[0]->der_len, &key);
\r
1582 DEBUG_PRINT("Error importing RSA certificate (code: %i)\n", err);
\r
1583 return TLS_GENERIC_ERROR;
\r
1585 int hash_idx = -1;
\r
1586 unsigned char hash[__TLS_MAX_HASH_LEN];
\r
1587 unsigned int hash_len = 0;
\r
1589 switch (hash_type) {
\r
1591 hash_idx = find_hash("md5");
\r
1592 err = md5_init(&state);
\r
1594 err = md5_process(&state, message, message_len);
\r
1596 err = md5_done(&state, hash);
\r
1601 hash_idx = find_hash("sha1");
\r
1602 err = sha1_init(&state);
\r
1604 err = sha1_process(&state, message, message_len);
\r
1606 err = sha1_done(&state, hash);
\r
1611 hash_idx = find_hash("sha256");
\r
1612 err = sha256_init(&state);
\r
1614 err = sha256_process(&state, message, message_len);
\r
1616 err = sha256_done(&state, hash);
\r
1621 hash_idx = find_hash("sha384");
\r
1622 err = sha384_init(&state);
\r
1624 err = sha384_process(&state, message, message_len);
\r
1626 err = sha384_done(&state, hash);
\r
1631 hash_idx = find_hash("sha512");
\r
1632 err = sha512_init(&state);
\r
1634 err = sha512_process(&state, message, message_len);
\r
1636 err = sha512_done(&state, hash);
\r
1640 #ifdef TLS_LEGACY_SUPPORT
\r
1642 hash_idx = find_hash("md5");
\r
1643 err = md5_init(&state);
\r
1645 err = md5_process(&state, message, message_len);
\r
1647 err = md5_done(&state, hash);
\r
1649 hash_idx = find_hash("sha1");
\r
1650 err = sha1_init(&state);
\r
1652 err = sha1_process(&state, message, message_len);
\r
1654 err = sha1_done(&state, hash + 16);
\r
1657 err = sha1_init(&state);
\r
1659 err = sha1_process(&state, message, message_len);
\r
1661 err = sha1_done(&state, hash + 16);
\r
1667 if ((hash_idx < 0) || (err)) {
\r
1668 DEBUG_PRINT("Unsupported hash type: %i\n", hash_type);
\r
1669 return TLS_GENERIC_ERROR;
\r
1672 #ifdef TLS_LEGACY_SUPPORT
\r
1673 if (hash_type == __md5_sha1)
\r
1674 err = __private_rsa_verify_hash_md5sha1(buffer, len, hash, hash_len, &rsa_stat, &key);
\r
1677 err = rsa_verify_hash_ex(buffer, len, hash, hash_len, LTC_PKCS_1_V1_5, hash_idx, 0, &rsa_stat, &key);
\r
1684 #ifdef TLS_LEGACY_SUPPORT
\r
1685 int __private_rsa_sign_hash_md5sha1(const unsigned char *in, unsigned long inlen, unsigned char *out, unsigned long *outlen, prng_state *prng, int prng_idx, unsigned long saltlen, rsa_key *key) {
\r
1686 unsigned long modulus_bitlen, modulus_bytelen, x;
\r
1689 if ((in == NULL) || (out == NULL) || (outlen == NULL) || (key == NULL))
\r
1690 return TLS_GENERIC_ERROR;
\r
1692 modulus_bitlen = mp_count_bits((key->N));
\r
1694 modulus_bytelen = mp_unsigned_bin_size((key->N));
\r
1695 if (modulus_bytelen > *outlen) {
\r
1696 *outlen = modulus_bytelen;
\r
1697 return CRYPT_BUFFER_OVERFLOW;
\r
1699 x = modulus_bytelen;
\r
1700 err = pkcs_1_v1_5_encode(in, inlen, LTC_PKCS_1_EMSA, modulus_bitlen, NULL, 0, out, &x);
\r
1701 if (err != CRYPT_OK)
\r
1704 return ltc_mp.rsa_me(out, x, out, outlen, PK_PRIVATE, key);
\r
1708 int __private_tls_sign_rsa(struct TLSContext *context, unsigned int hash_type, const unsigned char *message, unsigned int message_len, unsigned char *out, unsigned long *outlen) {
\r
1709 if ((!outlen) || (!context) || (!out) || (!outlen) || (!context->private_key) || (!context->private_key->der_bytes) || (!context->private_key->der_len)) {
\r
1710 DEBUG_PRINT("No private key set\n");
\r
1711 return TLS_GENERIC_ERROR;
\r
1716 err = rsa_import(context->private_key->der_bytes, context->private_key->der_len, &key);
\r
1719 DEBUG_PRINT("Error importing RSA certificate (code: %i)\n", err);
\r
1720 return TLS_GENERIC_ERROR;
\r
1722 int hash_idx = -1;
\r
1723 unsigned char hash[__TLS_MAX_HASH_LEN];
\r
1724 unsigned int hash_len = 0;
\r
1726 switch (hash_type) {
\r
1728 hash_idx = find_hash("md5");
\r
1729 err = md5_init(&state);
\r
1731 err = md5_process(&state, message, message_len);
\r
1733 err = md5_done(&state, hash);
\r
1738 hash_idx = find_hash("sha1");
\r
1739 err = sha1_init(&state);
\r
1741 err = sha1_process(&state, message, message_len);
\r
1743 err = sha1_done(&state, hash);
\r
1748 hash_idx = find_hash("sha256");
\r
1749 err = sha256_init(&state);
\r
1751 err = sha256_process(&state, message, message_len);
\r
1753 err = sha256_done(&state, hash);
\r
1758 hash_idx = find_hash("sha384");
\r
1759 err = sha384_init(&state);
\r
1761 err = sha384_process(&state, message, message_len);
\r
1763 err = sha384_done(&state, hash);
\r
1768 hash_idx = find_hash("sha512");
\r
1769 err = sha512_init(&state);
\r
1771 err = sha512_process(&state, message, message_len);
\r
1773 err = sha512_done(&state, hash);
\r
1778 hash_idx = find_hash("md5");
\r
1779 err = md5_init(&state);
\r
1781 err = md5_process(&state, message, message_len);
\r
1783 err = md5_done(&state, hash);
\r
1785 hash_idx = find_hash("sha1");
\r
1786 err = sha1_init(&state);
\r
1788 err = sha1_process(&state, message, message_len);
\r
1790 err = sha1_done(&state, hash + 16);
\r
1793 err = sha1_init(&state);
\r
1795 err = sha1_process(&state, message, message_len);
\r
1797 err = sha1_done(&state, hash + 16);
\r
1802 #ifdef TLS_LEGACY_SUPPORT
\r
1803 if (hash_type == __md5_sha1) {
\r
1805 DEBUG_PRINT("Unsupported hash type: %i\n", hash_type);
\r
1806 return TLS_GENERIC_ERROR;
\r
1808 err = __private_rsa_sign_hash_md5sha1(hash, hash_len, out, outlen, NULL, find_prng("sprng"), 0, &key);
\r
1812 if ((hash_idx < 0) || (err)) {
\r
1813 DEBUG_PRINT("Unsupported hash type: %i\n", hash_type);
\r
1814 return TLS_GENERIC_ERROR;
\r
1816 err = rsa_sign_hash_ex(hash, hash_len, out, outlen, LTC_PKCS_1_V1_5, NULL, find_prng("sprng"), hash_idx, 0, &key);
\r
1825 #ifdef TLS_ECDSA_SUPPORTED
\r
1826 static int __private_tls_is_point(ecc_key *key) {
\r
1827 void *prime, *b, *t1, *t2;
\r
1830 if ((err = mp_init_multi(&prime, &b, &t1, &t2, NULL)) != CRYPT_OK) {
\r
1834 /* load prime and b */
\r
1835 if ((err = mp_read_radix(prime, key->dp->prime, 16)) != CRYPT_OK) {
\r
1838 if ((err = mp_read_radix(b, key->dp->B, 16)) != CRYPT_OK) {
\r
1843 if ((err = mp_sqr(key->pubkey.y, t1)) != CRYPT_OK) {
\r
1848 if ((err = mp_sqr(key->pubkey.x, t2)) != CRYPT_OK) {
\r
1851 if ((err = mp_mod(t2, prime, t2)) != CRYPT_OK) {
\r
1854 if ((err = mp_mul(key->pubkey.x, t2, t2)) != CRYPT_OK) {
\r
1858 /* compute y^2 - x^3 */
\r
1859 if ((err = mp_sub(t1, t2, t1)) != CRYPT_OK) {
\r
1863 /* compute y^2 - x^3 + 3x */
\r
1864 if ((err = mp_add(t1, key->pubkey.x, t1)) != CRYPT_OK) {
\r
1867 if ((err = mp_add(t1, key->pubkey.x, t1)) != CRYPT_OK) {
\r
1870 if ((err = mp_add(t1, key->pubkey.x, t1)) != CRYPT_OK) {
\r
1873 if ((err = mp_mod(t1, prime, t1)) != CRYPT_OK) {
\r
1876 while (mp_cmp_d(t1, 0) == LTC_MP_LT) {
\r
1877 if ((err = mp_add(t1, prime, t1)) != CRYPT_OK) {
\r
1881 while (mp_cmp(t1, prime) != LTC_MP_LT) {
\r
1882 if ((err = mp_sub(t1, prime, t1)) != CRYPT_OK) {
\r
1887 /* compare to b */
\r
1888 if (mp_cmp(t1, b) != LTC_MP_EQ) {
\r
1889 err = CRYPT_INVALID_PACKET;
\r
1895 mp_clear_multi(prime, b, t1, t2, NULL);
\r
1899 int __private_tls_ecc_import_key(const unsigned char *private_key, int private_len, const unsigned char *public_key, int public_len, ecc_key *key, const ltc_ecc_set_type *dp) {
\r
1902 if ((!key) || (!ltc_mp.name))
\r
1905 key->type = PK_PRIVATE;
\r
1907 if (mp_init_multi(&key->pubkey.x, &key->pubkey.y, &key->pubkey.z, &key->k, NULL) != CRYPT_OK)
\r
1910 if ((public_len) && (!public_key[0])) {
\r
1914 if ((err = mp_read_unsigned_bin(key->pubkey.x, (unsigned char *)public_key + 1, (public_len - 1) >> 1)) != CRYPT_OK) {
\r
1915 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z, key->k, NULL);
\r
1919 if ((err = mp_read_unsigned_bin(key->pubkey.y, (unsigned char *)public_key + 1 + ((public_len - 1) >> 1), (public_len - 1) >> 1)) != CRYPT_OK) {
\r
1920 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z, key->k, NULL);
\r
1924 if ((err = mp_read_unsigned_bin(key->k, (unsigned char *)private_key, private_len)) != CRYPT_OK) {
\r
1925 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z, key->k, NULL);
\r
1933 if ((err = mp_set(key->pubkey.z, 1)) != CRYPT_OK) {
\r
1934 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z, key->k, NULL);
\r
1938 /* is it a point on the curve? */
\r
1939 if ((err = __private_tls_is_point(key)) != CRYPT_OK) {
\r
1940 DEBUG_PRINT("KEY IS NOT ON CURVE\n");
\r
1941 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z, key->k, NULL);
\r
1949 int __private_tls_sign_ecdsa(struct TLSContext *context, unsigned int hash_type, const unsigned char *message, unsigned int message_len, unsigned char *out, unsigned long *outlen) {
\r
1950 if ((!outlen) || (!context) || (!out) || (!outlen) || (!context->ec_private_key) ||
\r
1951 (!context->ec_private_key->priv) || (!context->ec_private_key->priv_len) || (!context->ec_private_key->pk) || (!context->ec_private_key->pk_len)) {
\r
1952 DEBUG_PRINT("No private ECDSA key set\n");
\r
1953 return TLS_GENERIC_ERROR;
\r
1956 const struct ECCCurveParameters *curve = NULL;
\r
1958 switch (context->ec_private_key->ec_algorithm) {
\r
1960 curve = &secp192r1;
\r
1963 curve = &secp224k1;
\r
1966 curve = &secp224r1;
\r
1969 curve = &secp256k1;
\r
1972 curve = &secp256r1;
\r
1975 curve = &secp384r1;
\r
1978 curve = &secp521r1;
\r
1981 DEBUG_PRINT("UNSUPPORTED CURVE\n");
\r
1982 return TLS_GENERIC_ERROR;
\r
1986 return TLS_GENERIC_ERROR;
\r
1992 ltc_ecc_set_type *dp = (ltc_ecc_set_type *)&curve->dp;
\r
1994 // broken ... fix this
\r
1995 err = __private_tls_ecc_import_key(context->ec_private_key->priv, context->ec_private_key->priv_len, context->ec_private_key->pk, context->ec_private_key->pk_len, &key, dp);
\r
1997 DEBUG_PRINT("Error importing ECC certificate (code: %i)\n", (int)err);
\r
1998 return TLS_GENERIC_ERROR;
\r
2000 int hash_idx = -1;
\r
2001 unsigned char hash[__TLS_MAX_HASH_LEN];
\r
2002 unsigned int hash_len = 0;
\r
2004 switch (hash_type) {
\r
2006 hash_idx = find_hash("md5");
\r
2007 err = md5_init(&state);
\r
2009 err = md5_process(&state, message, message_len);
\r
2011 err = md5_done(&state, hash);
\r
2016 hash_idx = find_hash("sha1");
\r
2017 err = sha1_init(&state);
\r
2019 err = sha1_process(&state, message, message_len);
\r
2021 err = sha1_done(&state, hash);
\r
2026 hash_idx = find_hash("sha256");
\r
2027 err = sha256_init(&state);
\r
2029 err = sha256_process(&state, message, message_len);
\r
2031 err = sha256_done(&state, hash);
\r
2036 hash_idx = find_hash("sha384");
\r
2037 err = sha384_init(&state);
\r
2039 err = sha384_process(&state, message, message_len);
\r
2041 err = sha384_done(&state, hash);
\r
2046 hash_idx = find_hash("sha512");
\r
2047 err = sha512_init(&state);
\r
2049 err = sha512_process(&state, message, message_len);
\r
2051 err = sha512_done(&state, hash);
\r
2056 hash_idx = find_hash("md5");
\r
2057 err = md5_init(&state);
\r
2059 err = md5_process(&state, message, message_len);
\r
2061 err = md5_done(&state, hash);
\r
2063 hash_idx = find_hash("sha1");
\r
2064 err = sha1_init(&state);
\r
2066 err = sha1_process(&state, message, message_len);
\r
2068 err = sha1_done(&state, hash + 16);
\r
2071 err = sha1_init(&state);
\r
2073 err = sha1_process(&state, message, message_len);
\r
2075 err = sha1_done(&state, hash + 16);
\r
2081 if ((hash_idx < 0) || (err)) {
\r
2082 DEBUG_PRINT("Unsupported hash type: %i\n", hash_type);
\r
2083 return TLS_GENERIC_ERROR;
\r
2085 // "Let z be the Ln leftmost bits of e, where Ln is the bit length of the group order n."
\r
2086 if (hash_len > curve->size)
\r
2087 hash_len = curve->size;
\r
2088 err = ecc_sign_hash(hash, hash_len, out, outlen, NULL, find_prng("sprng"), &key);
\r
2089 DEBUG_DUMP_HEX_LABEL("ECC SIGNATURE", out, *outlen);
\r
2097 #ifdef TLS_CLIENT_ECDSA
\r
2098 int __private_tls_ecc_import_pk(const unsigned char *public_key, int public_len, ecc_key *key, const ltc_ecc_set_type *dp) {
\r
2101 if ((!key) || (!ltc_mp.name))
\r
2104 key->type = PK_PUBLIC;
\r
2106 if (mp_init_multi(&key->pubkey.x, &key->pubkey.y, &key->pubkey.z, &key->k, NULL) != CRYPT_OK)
\r
2109 if ((public_len) && (!public_key[0])) {
\r
2113 if ((err = mp_read_unsigned_bin(key->pubkey.x, (unsigned char *)public_key + 1, (public_len - 1) >> 1)) != CRYPT_OK) {
\r
2114 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z, key->k, NULL);
\r
2118 if ((err = mp_read_unsigned_bin(key->pubkey.y, (unsigned char *)public_key + 1 + ((public_len - 1) >> 1), (public_len - 1) >> 1)) != CRYPT_OK) {
\r
2119 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z, key->k, NULL);
\r
2128 if ((err = mp_set(key->pubkey.z, 1)) != CRYPT_OK) {
\r
2129 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z, key->k, NULL);
\r
2133 /* is it a point on the curve? */
\r
2134 if ((err = __private_tls_is_point(key)) != CRYPT_OK) {
\r
2135 DEBUG_PRINT("KEY IS NOT ON CURVE\n");
\r
2136 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z, key->k, NULL);
\r
2144 int __private_tls_verify_ecdsa(struct TLSContext *context, unsigned int hash_type, const unsigned char *buffer, unsigned int len, const unsigned char *message, unsigned int message_len) {
\r
2149 if (context->is_server) {
\r
2150 if ((!len) || (!context) || (!context->client_certificates) || (!context->client_certificates_count) || (!context->client_certificates[0]) ||
\r
2151 (!context->client_certificates[0]->pk) || (!context->client_certificates[0]->pk_len) || (!context->curve)) {
\r
2152 DEBUG_PRINT("No client certificate set\n");
\r
2153 return TLS_GENERIC_ERROR;
\r
2155 err = __private_tls_ecc_import_pk(context->client_certificates[0]->pk, context->client_certificates[0]->pk_len, &key, (ltc_ecc_set_type *)&context->curve->dp);
\r
2157 if ((!len) || (!context) || (!context->certificates) || (!context->certificates_count) || (!context->certificates[0]) ||
\r
2158 (!context->certificates[0]->pk) || (!context->certificates[0]->pk_len) || (!context->curve)) {
\r
2159 DEBUG_PRINT("No server certificate set\n");
\r
2160 return TLS_GENERIC_ERROR;
\r
2162 err = __private_tls_ecc_import_pk(context->certificates[0]->pk, context->certificates[0]->pk_len, &key, (ltc_ecc_set_type *)&context->curve->dp);
\r
2165 DEBUG_PRINT("Error importing ECC certificate (code: %i)", err);
\r
2166 return TLS_GENERIC_ERROR;
\r
2168 int hash_idx = -1;
\r
2169 unsigned char hash[__TLS_MAX_HASH_LEN];
\r
2170 unsigned int hash_len = 0;
\r
2172 switch (hash_type) {
\r
2174 hash_idx = find_hash("md5");
\r
2175 err = md5_init(&state);
\r
2177 err = md5_process(&state, message, message_len);
\r
2179 err = md5_done(&state, hash);
\r
2184 hash_idx = find_hash("sha1");
\r
2185 err = sha1_init(&state);
\r
2187 err = sha1_process(&state, message, message_len);
\r
2189 err = sha1_done(&state, hash);
\r
2194 hash_idx = find_hash("sha256");
\r
2195 err = sha256_init(&state);
\r
2197 err = sha256_process(&state, message, message_len);
\r
2199 err = sha256_done(&state, hash);
\r
2204 hash_idx = find_hash("sha384");
\r
2205 err = sha384_init(&state);
\r
2207 err = sha384_process(&state, message, message_len);
\r
2209 err = sha384_done(&state, hash);
\r
2214 hash_idx = find_hash("sha512");
\r
2215 err = sha512_init(&state);
\r
2217 err = sha512_process(&state, message, message_len);
\r
2219 err = sha512_done(&state, hash);
\r
2223 #ifdef TLS_LEGACY_SUPPORT
\r
2225 hash_idx = find_hash("md5");
\r
2226 err = md5_init(&state);
\r
2228 err = md5_process(&state, message, message_len);
\r
2230 err = md5_done(&state, hash);
\r
2232 hash_idx = find_hash("sha1");
\r
2233 err = sha1_init(&state);
\r
2235 err = sha1_process(&state, message, message_len);
\r
2237 err = sha1_done(&state, hash + 16);
\r
2240 err = sha1_init(&state);
\r
2242 err = sha1_process(&state, message, message_len);
\r
2244 err = sha1_done(&state, hash + 16);
\r
2250 if ((hash_idx < 0) || (err)) {
\r
2251 DEBUG_PRINT("Unsupported hash type: %i\n", hash_type);
\r
2252 return TLS_GENERIC_ERROR;
\r
2255 err = ecc_verify_hash(buffer, len, hash, hash_len, &ecc_stat, &key);
\r
2265 unsigned int __private_tls_random_int(int limit) {
\r
2266 unsigned int res = 0;
\r
2267 tls_random((unsigned char *)&res, sizeof(int));
\r
2273 void __private_tls_sleep(unsigned int microseconds) {
\r
2275 Sleep(microseconds/1000);
\r
2277 struct timespec ts;
\r
2279 ts.tv_sec = (unsigned int) (microseconds / 1000000);
\r
2280 ts.tv_nsec = (unsigned int) (microseconds % 1000000) * 1000ul;
\r
2282 nanosleep(&ts, NULL);
\r
2286 void __private_random_sleep(struct TLSContext *context, int max_microseconds) {
\r
2288 context->sleep_until = time(NULL) + __private_tls_random_int(max_microseconds/1000000 * __TLS_MAX_ERROR_IDLE_S);
\r
2290 __private_tls_sleep(__private_tls_random_int(max_microseconds));
\r
2293 void __private_tls_prf_helper(int hash_idx, unsigned long dlen, unsigned char *output, unsigned int outlen, const unsigned char *secret, const unsigned int secret_len,
\r
2294 const unsigned char *label, unsigned int label_len, unsigned char *seed, unsigned int seed_len,
\r
2295 unsigned char *seed_b, unsigned int seed_b_len) {
\r
2296 unsigned char digest_out0[__TLS_MAX_HASH_LEN];
\r
2297 unsigned char digest_out1[__TLS_MAX_HASH_LEN];
\r
2301 hmac_init(&hmac, hash_idx, secret, secret_len);
\r
2302 hmac_process(&hmac, label, label_len);
\r
2304 hmac_process(&hmac, seed, seed_len);
\r
2305 if ((seed_b) && (seed_b_len))
\r
2306 hmac_process(&hmac, seed_b, seed_b_len);
\r
2307 hmac_done(&hmac, digest_out0, &dlen);
\r
2310 hmac_init(&hmac, hash_idx, secret, secret_len);
\r
2311 hmac_process(&hmac, digest_out0, dlen);
\r
2312 hmac_process(&hmac, label, label_len);
\r
2313 hmac_process(&hmac, seed, seed_len);
\r
2314 if ((seed_b) && (seed_b_len))
\r
2315 hmac_process(&hmac, seed_b, seed_b_len);
\r
2316 hmac_done(&hmac, digest_out1, &dlen);
\r
2318 unsigned int copylen = outlen;
\r
2319 if (copylen > dlen)
\r
2322 for (i = 0; i < copylen; i++) {
\r
2323 output[idx++] ^= digest_out1[i];
\r
2330 hmac_init(&hmac, hash_idx, secret, secret_len);
\r
2331 hmac_process(&hmac, digest_out0, dlen);
\r
2332 hmac_done(&hmac, digest_out0, &dlen);
\r
2336 void __private_tls_prf(struct TLSContext *context,
\r
2337 unsigned char *output, unsigned int outlen, const unsigned char *secret, const unsigned int secret_len,
\r
2338 const unsigned char *label, unsigned int label_len, unsigned char *seed, unsigned int seed_len,
\r
2339 unsigned char *seed_b, unsigned int seed_b_len) {
\r
2340 if ((!secret) || (!secret_len)) {
\r
2341 DEBUG_PRINT("NULL SECRET\n");
\r
2344 if ((context->version != TLS_V12) && (context->version != DTLS_V12)) {
\r
2345 int md5_hash_idx = find_hash("md5");
\r
2346 int sha1_hash_idx = find_hash("sha1");
\r
2347 int half_secret = (secret_len + 1) / 2;
\r
2349 memset(output, 0, outlen);
\r
2350 __private_tls_prf_helper(md5_hash_idx, 16, output, outlen, secret, half_secret, label, label_len, seed, seed_len, seed_b, seed_b_len);
\r
2351 __private_tls_prf_helper(sha1_hash_idx, 20, output, outlen, secret + (secret_len - half_secret), secret_len - half_secret, label, label_len, seed, seed_len, seed_b, seed_b_len);
\r
2354 unsigned char digest_out0[__TLS_MAX_HASH_LEN];
\r
2355 unsigned char digest_out1[__TLS_MAX_HASH_LEN];
\r
2356 unsigned long dlen = 32;
\r
2358 unsigned int mac_length = __private_tls_mac_length(context);
\r
2359 if (mac_length == __TLS_SHA384_MAC_SIZE) {
\r
2360 hash_idx = find_hash("sha384");
\r
2361 dlen = mac_length;
\r
2363 hash_idx = find_hash("sha256");
\r
2367 hmac_init(&hmac, hash_idx, secret, secret_len);
\r
2368 hmac_process(&hmac, label, label_len);
\r
2370 hmac_process(&hmac, seed, seed_len);
\r
2371 if ((seed_b) && (seed_b_len))
\r
2372 hmac_process(&hmac, seed_b, seed_b_len);
\r
2373 hmac_done(&hmac, digest_out0, &dlen);
\r
2376 hmac_init(&hmac, hash_idx, secret, secret_len);
\r
2377 hmac_process(&hmac, digest_out0, dlen);
\r
2378 hmac_process(&hmac, label, label_len);
\r
2379 hmac_process(&hmac, seed, seed_len);
\r
2380 if ((seed_b) && (seed_b_len))
\r
2381 hmac_process(&hmac, seed_b, seed_b_len);
\r
2382 hmac_done(&hmac, digest_out1, &dlen);
\r
2384 unsigned int copylen = outlen;
\r
2385 if (copylen > dlen)
\r
2386 copylen = (unsigned int)dlen;
\r
2388 for (i = 0; i < copylen; i++) {
\r
2389 output[idx++] = digest_out1[i];
\r
2396 hmac_init(&hmac, hash_idx, secret, secret_len);
\r
2397 hmac_process(&hmac, digest_out0, dlen);
\r
2398 hmac_done(&hmac, digest_out0, &dlen);
\r
2403 int __private_tls_key_length(struct TLSContext *context) {
\r
2404 switch (context->cipher) {
\r
2405 case TLS_RSA_WITH_AES_128_CBC_SHA:
\r
2406 case TLS_RSA_WITH_AES_128_CBC_SHA256:
\r
2407 case TLS_RSA_WITH_AES_128_GCM_SHA256:
\r
2408 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
\r
2409 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
\r
2410 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
\r
2411 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
\r
2412 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
\r
2413 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
\r
2414 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
\r
2415 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
\r
2416 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
\r
2418 case TLS_RSA_WITH_AES_256_CBC_SHA:
\r
2419 case TLS_RSA_WITH_AES_256_CBC_SHA256:
\r
2420 case TLS_RSA_WITH_AES_256_GCM_SHA384:
\r
2421 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
\r
2422 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
\r
2423 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
\r
2424 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
\r
2425 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
\r
2426 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
\r
2427 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
\r
2428 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
\r
2429 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
\r
2430 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
\r
2431 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
\r
2437 int __private_tls_is_aead(struct TLSContext *context) {
\r
2438 switch (context->cipher) {
\r
2439 case TLS_RSA_WITH_AES_128_GCM_SHA256:
\r
2440 case TLS_RSA_WITH_AES_256_GCM_SHA384:
\r
2441 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
\r
2442 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
\r
2443 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
\r
2444 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
\r
2445 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
\r
2446 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
\r
2448 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
\r
2449 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
\r
2450 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
\r
2458 unsigned int __private_tls_mac_length(struct TLSContext *context) {
\r
2459 switch (context->cipher) {
\r
2460 case TLS_RSA_WITH_AES_128_CBC_SHA:
\r
2461 case TLS_RSA_WITH_AES_256_CBC_SHA:
\r
2462 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
\r
2463 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
\r
2464 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
\r
2465 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
\r
2466 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
\r
2467 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
\r
2468 return __TLS_SHA1_MAC_SIZE;
\r
2469 case TLS_RSA_WITH_AES_128_CBC_SHA256:
\r
2470 case TLS_RSA_WITH_AES_256_CBC_SHA256:
\r
2471 case TLS_RSA_WITH_AES_128_GCM_SHA256:
\r
2472 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
\r
2473 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
\r
2474 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
\r
2475 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
\r
2476 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
\r
2477 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
\r
2478 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
\r
2479 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
\r
2480 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
\r
2481 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
\r
2482 return __TLS_SHA256_MAC_SIZE;
\r
2483 case TLS_RSA_WITH_AES_256_GCM_SHA384:
\r
2484 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
\r
2485 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
\r
2486 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
\r
2487 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
\r
2488 return __TLS_SHA384_MAC_SIZE;
\r
2493 int __private_tls_expand_key(struct TLSContext *context) {
\r
2494 unsigned char key[__TLS_MAX_KEY_EXPANSION_SIZE];
\r
2496 if ((!context->master_key) || (!context->master_key_len))
\r
2499 int key_length = __private_tls_key_length(context);
\r
2500 int mac_length = __private_tls_mac_length(context);
\r
2502 if ((!key_length) || (!mac_length)) {
\r
2503 DEBUG_PRINT("KEY EXPANSION FAILED, KEY LENGTH: %i, MAC LENGTH: %i\n", key_length, mac_length);
\r
2507 if (context->is_server)
\r
2508 __private_tls_prf(context, key, sizeof(key), context->master_key, context->master_key_len, (unsigned char *)"key expansion", 13, context->local_random, __TLS_SERVER_RANDOM_SIZE, context->remote_random, __TLS_CLIENT_RANDOM_SIZE);
\r
2510 __private_tls_prf(context, key, sizeof(key), context->master_key, context->master_key_len, (unsigned char *)"key expansion", 13, context->remote_random, __TLS_SERVER_RANDOM_SIZE, context->local_random, __TLS_CLIENT_RANDOM_SIZE);
\r
2512 DEBUG_DUMP_HEX_LABEL("LOCAL RANDOM ", context->local_random, __TLS_SERVER_RANDOM_SIZE);
\r
2513 DEBUG_DUMP_HEX_LABEL("REMOTE RANDOM", context->remote_random, __TLS_CLIENT_RANDOM_SIZE);
\r
2514 DEBUG_PRINT("\n=========== EXPANSION ===========\n");
\r
2515 DEBUG_DUMP_HEX(key, __TLS_MAX_KEY_EXPANSION_SIZE);
\r
2516 DEBUG_PRINT("\n");
\r
2518 unsigned char *clientkey = NULL;
\r
2519 unsigned char *serverkey = NULL;
\r
2520 unsigned char *clientiv = NULL;
\r
2521 unsigned char *serveriv = NULL;
\r
2522 int iv_length = __TLS_AES_IV_LENGTH;
\r
2525 int is_aead = __private_tls_is_aead(context);
\r
2526 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
2527 if (is_aead == 2) {
\r
2528 iv_length = __TLS_CHACHA20_IV_LENGTH;
\r
2532 iv_length = __TLS_AES_GCM_IV_LENGTH;
\r
2534 if (context->is_server) {
\r
2535 memcpy(context->crypto.ctx_remote_mac.remote_mac, &key[pos], mac_length);
\r
2536 pos += mac_length;
\r
2537 memcpy(context->crypto.ctx_local_mac.local_mac, &key[pos], mac_length);
\r
2538 pos += mac_length;
\r
2540 memcpy(context->crypto.ctx_local_mac.local_mac, &key[pos], mac_length);
\r
2541 pos += mac_length;
\r
2542 memcpy(context->crypto.ctx_remote_mac.remote_mac, &key[pos], mac_length);
\r
2543 pos += mac_length;
\r
2547 clientkey = &key[pos];
\r
2548 pos += key_length;
\r
2549 serverkey = &key[pos];
\r
2550 pos += key_length;
\r
2551 clientiv = &key[pos];
\r
2553 serveriv = &key[pos];
\r
2556 DEBUG_PRINT("EXPANSION %i/%i\n", (int)pos, (int)__TLS_MAX_KEY_EXPANSION_SIZE);
\r
2557 DEBUG_DUMP_HEX_LABEL("CLIENT KEY", clientkey, key_length)
\r
2558 DEBUG_DUMP_HEX_LABEL("CLIENT IV", clientiv, iv_length)
\r
2559 DEBUG_DUMP_HEX_LABEL("CLIENT MAC KEY", context->is_server ? context->crypto.ctx_remote_mac.remote_mac : context->crypto.ctx_local_mac.local_mac, mac_length)
\r
2560 DEBUG_DUMP_HEX_LABEL("SERVER KEY", serverkey, key_length)
\r
2561 DEBUG_DUMP_HEX_LABEL("SERVER IV", serveriv, iv_length)
\r
2562 DEBUG_DUMP_HEX_LABEL("SERVER MAC KEY", context->is_server ? context->crypto.ctx_local_mac.local_mac : context->crypto.ctx_remote_mac.remote_mac, mac_length)
\r
2564 if (context->is_server) {
\r
2565 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
2566 if (is_aead == 2) {
\r
2567 memcpy(context->crypto.ctx_remote_mac.remote_nonce, clientiv, iv_length);
\r
2568 memcpy(context->crypto.ctx_local_mac.local_nonce, serveriv, iv_length);
\r
2572 memcpy(context->crypto.ctx_remote_mac.remote_aead_iv, clientiv, iv_length);
\r
2573 memcpy(context->crypto.ctx_local_mac.local_aead_iv, serveriv, iv_length);
\r
2575 if (__private_tls_crypto_create(context, key_length, iv_length, serverkey, serveriv, clientkey, clientiv))
\r
2578 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
2579 if (is_aead == 2) {
\r
2580 memcpy(context->crypto.ctx_local_mac.local_nonce, clientiv, iv_length);
\r
2581 memcpy(context->crypto.ctx_remote_mac.remote_nonce, serveriv, iv_length);
\r
2585 memcpy(context->crypto.ctx_local_mac.local_aead_iv, clientiv, iv_length);
\r
2586 memcpy(context->crypto.ctx_remote_mac.remote_aead_iv, serveriv, iv_length);
\r
2588 if (__private_tls_crypto_create(context, key_length, iv_length, clientkey, clientiv, serverkey, serveriv))
\r
2592 if (context->exportable) {
\r
2593 TLS_FREE(context->exportable_keys);
\r
2594 context->exportable_keys = (unsigned char *)TLS_MALLOC(key_length * 2);
\r
2595 if (context->exportable_keys) {
\r
2596 if (context->is_server) {
\r
2597 memcpy(context->exportable_keys, serverkey, key_length);
\r
2598 memcpy(context->exportable_keys + key_length, clientkey, key_length);
\r
2600 memcpy(context->exportable_keys, clientkey, key_length);
\r
2601 memcpy(context->exportable_keys + key_length, serverkey, key_length);
\r
2603 context->exportable_size = key_length * 2;
\r
2607 // extract client_mac_key(mac_key_length)
\r
2608 // extract server_mac_key(mac_key_length)
\r
2609 // extract client_key(enc_key_length)
\r
2610 // extract server_key(enc_key_length)
\r
2611 // extract client_iv(fixed_iv_lengh)
\r
2612 // extract server_iv(fixed_iv_length)
\r
2616 int __private_tls_compute_key(struct TLSContext *context, unsigned int key_len) {
\r
2617 if ((!context) || (!context->premaster_key) || (!context->premaster_key_len) || (key_len < 48)) {
\r
2618 DEBUG_PRINT("CANNOT COMPUTE MASTER SECRET\n");
\r
2622 unsigned char master_secret_label[] = "master secret";
\r
2623 #ifdef __TLS_CHECK_PREMASTER_KEY
\r
2624 if (!tls_cipher_is_ephemeral(context)) {
\r
2625 unsigned short version = ntohs(*(unsigned short *)context->premaster_key);
\r
2626 // this check is not true for DHE/ECDHE ciphers
\r
2627 if (context->version > version) {
\r
2628 DEBUG_PRINT("Mismatch protocol version 0x(%x)\n", version);
\r
2633 TLS_FREE(context->master_key);
\r
2634 context->master_key_len = 0;
\r
2635 context->master_key = NULL;
\r
2636 if ((context->version == TLS_V12) || (context->version == TLS_V11) || (context->version == TLS_V10) || (context->version == DTLS_V12) || (context->version == DTLS_V10)) {
\r
2637 context->master_key = (unsigned char *)TLS_MALLOC(key_len);
\r
2638 if (!context->master_key)
\r
2640 context->master_key_len = key_len;
\r
2641 if (context->is_server) {
\r
2642 __private_tls_prf(context,
\r
2643 context->master_key, context->master_key_len,
\r
2644 context->premaster_key, context->premaster_key_len,
\r
2645 master_secret_label, 13,
\r
2646 context->remote_random, __TLS_CLIENT_RANDOM_SIZE,
\r
2647 context->local_random, __TLS_SERVER_RANDOM_SIZE
\r
2650 __private_tls_prf(context,
\r
2651 context->master_key, context->master_key_len,
\r
2652 context->premaster_key, context->premaster_key_len,
\r
2653 master_secret_label, 13,
\r
2654 context->local_random, __TLS_CLIENT_RANDOM_SIZE,
\r
2655 context->remote_random, __TLS_SERVER_RANDOM_SIZE
\r
2658 TLS_FREE(context->premaster_key);
\r
2659 context->premaster_key = NULL;
\r
2660 context->premaster_key_len = 0;
\r
2661 DEBUG_PRINT("\n=========== Master key ===========\n");
\r
2662 DEBUG_DUMP_HEX(context->master_key, context->master_key_len);
\r
2663 DEBUG_PRINT("\n");
\r
2664 __private_tls_expand_key(context);
\r
2670 unsigned char *tls_pem_decode(const unsigned char *data_in, unsigned int input_length, int cert_index, unsigned int *output_len) {
\r
2673 int alloc_len = input_length / 4 * 3;
\r
2674 unsigned char *output = (unsigned char *)TLS_MALLOC(alloc_len);
\r
2677 unsigned int start_at = 0;
\r
2678 unsigned int idx = 0;
\r
2679 for (i = 0; i < input_length; i++) {
\r
2680 if ((data_in[i] == '\n') || (data_in[i] == '\r'))
\r
2683 if (data_in[i] != '-') {
\r
2684 // read entire line
\r
2685 while ((i < input_length) && (data_in[i] != '\n'))
\r
2690 if (data_in[i] == '-') {
\r
2691 unsigned int end_idx = i;
\r
2692 //read until end of line
\r
2693 while ((i < input_length) && (data_in[i] != '\n'))
\r
2696 if (cert_index > 0) {
\r
2700 idx = __private_b64_decode((const char *)&data_in[start_at], end_idx - start_at, output);
\r
2707 *output_len = idx;
\r
2715 int __is_oid(const unsigned char *oid, const unsigned char *compare_to, int compare_to_len) {
\r
2717 while ((oid[i]) && (i < compare_to_len)) {
\r
2718 if (oid[i] != compare_to[i])
\r
2726 int __is_oid2(const unsigned char *oid, const unsigned char *compare_to, int compare_to_len, int oid_len) {
\r
2728 if (oid_len < compare_to_len)
\r
2729 compare_to_len = oid_len;
\r
2730 while (i < compare_to_len) {
\r
2731 if (oid[i] != compare_to[i])
\r
2739 struct TLSCertificate *tls_create_certificate() {
\r
2740 struct TLSCertificate *cert = (struct TLSCertificate *)TLS_MALLOC(sizeof(struct TLSCertificate));
\r
2742 memset(cert, 0, sizeof(struct TLSCertificate));
\r
2746 int tls_certificate_valid_subject_name(const unsigned char *cert_subject, const char *subject) {
\r
2747 // no subjects ...
\r
2748 if (((!cert_subject) || (!cert_subject[0])) && ((!subject) || (!subject[0])))
\r
2751 if ((!subject) || (!subject[0]))
\r
2752 return bad_certificate;
\r
2754 if ((!cert_subject) || (!cert_subject[0]))
\r
2755 return bad_certificate;
\r
2758 if (!strcmp((const char *)cert_subject, subject))
\r
2761 const char *wildcard = strchr((const char *)cert_subject, '*');
\r
2763 // 6.4.3 (1) The client SHOULD NOT attempt to match a presented identifier in
\r
2764 // which the wildcard character comprises a label other than the left-most label
\r
2765 if (!wildcard[1]) {
\r
2768 // subject is [something*] .. invalid
\r
2769 return bad_certificate;
\r
2772 const char *match = strstr(subject, wildcard);
\r
2773 if ((!match) && (wildcard[0] == '.')) {
\r
2774 // check *.domain.com agains domain.com
\r
2776 if (!strcasecmp(subject, wildcard))
\r
2780 unsigned long offset = (unsigned long)match - (unsigned long)subject;
\r
2782 // check for foo.*.domain.com against *.domain.com (invalid)
\r
2783 if (memchr(subject, '.', offset))
\r
2784 return bad_certificate;
\r
2786 // check if exact match
\r
2787 if (!strcasecmp(match, wildcard))
\r
2792 return bad_certificate;
\r
2795 int tls_certificate_valid_subject(struct TLSCertificate *cert, const char *subject) {
\r
2798 return certificate_unknown;
\r
2799 int err = tls_certificate_valid_subject_name(cert->subject, subject);
\r
2800 if ((err) && (cert->san)) {
\r
2801 for (i = 0; i < cert->san_length; i++) {
\r
2802 err = tls_certificate_valid_subject_name(cert->san[i], subject);
\r
2810 int tls_certificate_is_valid(struct TLSCertificate *cert) {
\r
2812 return certificate_unknown;
\r
2813 if (!cert->not_before)
\r
2814 return certificate_unknown;
\r
2815 if (!cert->not_after)
\r
2816 return certificate_unknown;
\r
2817 //20160224182300Z//
\r
2818 char current_time[16];
\r
2819 time_t t = time(NULL);
\r
2820 struct tm *utct = gmtime(&t);
\r
2822 current_time[0] = 0;
\r
2823 snprintf(current_time, sizeof(current_time), "%04d%02d%02d%02d%02d%02dZ", 1900 + utct->tm_year, utct->tm_mon + 1, utct->tm_mday, utct->tm_hour, utct->tm_min, utct->tm_sec);
\r
2824 if (strcasecmp((char *)cert->not_before, current_time) > 0) {
\r
2825 DEBUG_PRINT("Certificate is not yer valid, now: %s (validity: %s - %s)\n", current_time, cert->not_before, cert->not_after);
\r
2826 return certificate_expired;
\r
2828 if (strcasecmp((char *)cert->not_after, current_time) < 0) {
\r
2829 DEBUG_PRINT("Expired certificate, now: %s (validity: %s - %s)\n", current_time, cert->not_before, cert->not_after);
\r
2830 return certificate_expired;
\r
2832 DEBUG_PRINT("Valid certificate, now: %s (validity: %s - %s)\n", current_time, cert->not_before, cert->not_after);
\r
2837 void tls_certificate_set_copy(unsigned char **member, const unsigned char *val, int len) {
\r
2840 TLS_FREE(*member);
\r
2842 *member = (unsigned char *)TLS_MALLOC(len + 1);
\r
2844 memcpy(*member, val, len);
\r
2845 (*member)[len] = 0;
\r
2851 void tls_certificate_set_copy_date(unsigned char **member, const unsigned char *val, int len) {
\r
2854 TLS_FREE(*member);
\r
2856 *member = (unsigned char *)TLS_MALLOC(len + 3);
\r
2858 if (val[0] == '9') {
\r
2865 memcpy(*member + 2, val, len);
\r
2866 (*member)[len] = 0;
\r
2872 void tls_certificate_set_key(struct TLSCertificate *cert, const unsigned char *val, int len) {
\r
2873 if ((!val[0]) && (len % 2)) {
\r
2877 tls_certificate_set_copy(&cert->pk, val, len);
\r
2879 cert->pk_len = len;
\r
2882 void tls_certificate_set_priv(struct TLSCertificate *cert, const unsigned char *val, int len) {
\r
2883 tls_certificate_set_copy(&cert->priv, val, len);
\r
2885 cert->priv_len = len;
\r
2888 void tls_certificate_set_sign_key(struct TLSCertificate *cert, const unsigned char *val, int len) {
\r
2889 if ((!val[0]) && (len % 2)) {
\r
2893 tls_certificate_set_copy(&cert->sign_key, val, len);
\r
2894 if (cert->sign_key)
\r
2895 cert->sign_len = len;
\r
2898 char *tls_certificate_to_string(struct TLSCertificate *cert, char *buffer, int len) {
\r
2903 if (cert->version) {
\r
2904 int res = snprintf(buffer, len, "X.509v%i certificate\n Issued by: [%s]%s (%s)\n Issued to: [%s]%s (%s, %s)\n Subject: %s\n Validity: %s - %s\n OCSP: %s\n Serial number: ",
\r
2905 (int)cert->version,
\r
2906 cert->issuer_country, cert->issuer_entity, cert->issuer_subject,
\r
2907 cert->country, cert->entity, cert->state, cert->location,
\r
2909 cert->not_before, cert->not_after,
\r
2913 for (i = 0; i < cert->serial_len; i++)
\r
2914 res += snprintf(buffer + res, len - res, "%02x", (int)cert->serial_number[i]);
\r
2916 if ((cert->san) && (cert->san_length)) {
\r
2917 res += snprintf(buffer + res, len - res, "\n Alternative subjects: ");
\r
2918 for (i = 0; i < cert->san_length; i++) {
\r
2920 res += snprintf(buffer + res, len - res, ", %s", cert->san[i]);
\r
2922 res += snprintf(buffer + res, len - res, "%s", cert->san[i]);
\r
2925 res += snprintf(buffer + res, len - res, "\n Key (%i bits, ", cert->pk_len * 8);
\r
2927 switch (cert->key_algorithm) {
\r
2928 case TLS_RSA_SIGN_RSA:
\r
2929 res += snprintf(buffer + res, len - res, "RSA_SIGN_RSA");
\r
2931 case TLS_RSA_SIGN_MD5:
\r
2932 res += snprintf(buffer + res, len - res, "RSA_SIGN_MD5");
\r
2934 case TLS_RSA_SIGN_SHA1:
\r
2935 res += snprintf(buffer + res, len - res, "RSA_SIGN_SHA1");
\r
2937 case TLS_RSA_SIGN_SHA256:
\r
2938 res += snprintf(buffer + res, len - res, "RSA_SIGN_SHA256");
\r
2940 case TLS_RSA_SIGN_SHA384:
\r
2941 res += snprintf(buffer + res, len - res, "RSA_SIGN_SHA384");
\r
2943 case TLS_RSA_SIGN_SHA512:
\r
2944 res += snprintf(buffer + res, len - res, "RSA_SIGN_SHA512");
\r
2946 case TLS_EC_PUBLIC_KEY:
\r
2947 res += snprintf(buffer + res, len - res, "EC_PUBLIC_KEY");
\r
2950 res += snprintf(buffer + res, len - res, "not supported (%i)", (int)cert->key_algorithm);
\r
2953 if ((res > 0) && (cert->ec_algorithm)) {
\r
2954 switch (cert->ec_algorithm) {
\r
2955 case TLS_EC_prime192v1:
\r
2956 res += snprintf(buffer + res, len - res, " prime192v1");
\r
2958 case TLS_EC_prime192v2:
\r
2959 res += snprintf(buffer + res, len - res, " prime192v2");
\r
2961 case TLS_EC_prime192v3:
\r
2962 res += snprintf(buffer + res, len - res, " prime192v3");
\r
2964 case TLS_EC_prime239v2:
\r
2965 res += snprintf(buffer + res, len - res, " prime239v2");
\r
2967 case TLS_EC_secp256r1:
\r
2968 res += snprintf(buffer + res, len - res, " EC_secp256r1");
\r
2970 case TLS_EC_secp224r1:
\r
2971 res += snprintf(buffer + res, len - res, " EC_secp224r1");
\r
2973 case TLS_EC_secp384r1:
\r
2974 res += snprintf(buffer + res, len - res, " EC_secp384r1");
\r
2976 case TLS_EC_secp521r1:
\r
2977 res += snprintf(buffer + res, len - res, " EC_secp521r1");
\r
2980 res += snprintf(buffer + res, len - res, " unknown(%i)", (int)cert->ec_algorithm);
\r
2983 res += snprintf(buffer + res, len - res, "):\n");
\r
2985 for (i = 0; i < cert->pk_len; i++)
\r
2986 res += snprintf(buffer + res, len - res, "%02x", (int)cert->pk[i]);
\r
2987 res += snprintf(buffer + res, len - res, "\n Signature (%i bits, ", cert->sign_len * 8);
\r
2988 switch (cert->algorithm) {
\r
2989 case TLS_RSA_SIGN_RSA:
\r
2990 res += snprintf(buffer + res, len - res, "RSA_SIGN_RSA):\n");
\r
2992 case TLS_RSA_SIGN_MD5:
\r
2993 res += snprintf(buffer + res, len - res, "RSA_SIGN_MD5):\n");
\r
2995 case TLS_RSA_SIGN_SHA1:
\r
2996 res += snprintf(buffer + res, len - res, "RSA_SIGN_SHA1):\n");
\r
2998 case TLS_RSA_SIGN_SHA256:
\r
2999 res += snprintf(buffer + res, len - res, "RSA_SIGN_SHA256):\n");
\r
3001 case TLS_RSA_SIGN_SHA384:
\r
3002 res += snprintf(buffer + res, len - res, "RSA_SIGN_SHA384):\n");
\r
3004 case TLS_RSA_SIGN_SHA512:
\r
3005 res += snprintf(buffer + res, len - res, "RSA_SIGN_SHA512):\n");
\r
3007 case TLS_EC_PUBLIC_KEY:
\r
3008 res += snprintf(buffer + res, len - res, "EC_PUBLIC_KEY):\n");
\r
3011 res += snprintf(buffer + res, len - res, "not supported):\n");
\r
3014 for (i = 0; i < cert->sign_len; i++)
\r
3015 res += snprintf(buffer + res, len - res, "%02x", (int)cert->sign_key[i]);
\r
3018 if ((cert->priv) && (cert->priv_len)) {
\r
3019 int res = snprintf(buffer, len, "X.509 private key\n");
\r
3020 res += snprintf(buffer + res, len - res, " Private Key: ");
\r
3022 for (i = 0; i < cert->priv_len; i++)
\r
3023 res += snprintf(buffer + res, len - res, "%02x", (int)cert->priv[i]);
\r
3026 snprintf(buffer, len, "Empty ASN1 file");
\r
3030 void tls_certificate_set_exponent(struct TLSCertificate *cert, const unsigned char *val, int len) {
\r
3031 tls_certificate_set_copy(&cert->exponent, val, len);
\r
3032 if (cert->exponent)
\r
3033 cert->exponent_len = len;
\r
3036 void tls_certificate_set_serial(struct TLSCertificate *cert, const unsigned char *val, int len) {
\r
3037 tls_certificate_set_copy(&cert->serial_number, val, len);
\r
3038 if (cert->serial_number)
\r
3039 cert->serial_len = len;
\r
3042 void tls_certificate_set_algorithm(unsigned int *algorithm, const unsigned char *val, int len) {
\r
3043 if ((len == 7) && (__is_oid(val, TLS_EC_PUBLIC_KEY_OID, 7))) {
\r
3044 *algorithm = TLS_EC_PUBLIC_KEY;
\r
3048 if (__is_oid(val, TLS_EC_prime192v1_OID, len)) {
\r
3049 *algorithm = TLS_EC_prime192v1;
\r
3052 if (__is_oid(val, TLS_EC_prime192v2_OID, len)) {
\r
3053 *algorithm = TLS_EC_prime192v2;
\r
3056 if (__is_oid(val, TLS_EC_prime192v3_OID, len)) {
\r
3057 *algorithm = TLS_EC_prime192v3;
\r
3060 if (__is_oid(val, TLS_EC_prime239v1_OID, len)) {
\r
3061 *algorithm = TLS_EC_prime239v1;
\r
3064 if (__is_oid(val, TLS_EC_prime239v2_OID, len)) {
\r
3065 *algorithm = TLS_EC_prime239v2;
\r
3068 if (__is_oid(val, TLS_EC_prime239v3_OID, len)) {
\r
3069 *algorithm = TLS_EC_prime239v3;
\r
3072 if (__is_oid(val, TLS_EC_prime256v1_OID, len)) {
\r
3073 *algorithm = TLS_EC_prime256v1;
\r
3078 if (__is_oid2(val, TLS_EC_secp224r1_OID, len, sizeof(TLS_EC_secp224r1_OID) - 1)) {
\r
3079 *algorithm = TLS_EC_secp224r1;
\r
3082 if (__is_oid2(val, TLS_EC_secp384r1_OID, len, sizeof(TLS_EC_secp384r1_OID) - 1)) {
\r
3083 *algorithm = TLS_EC_secp384r1;
\r
3086 if (__is_oid2(val, TLS_EC_secp521r1_OID, len, sizeof(TLS_EC_secp521r1_OID) - 1)) {
\r
3087 *algorithm = TLS_EC_secp521r1;
\r
3094 if (__is_oid(val, TLS_RSA_SIGN_SHA256_OID, 9)) {
\r
3095 *algorithm = TLS_RSA_SIGN_SHA256;
\r
3099 if (__is_oid(val, TLS_RSA_SIGN_RSA_OID, 9)) {
\r
3100 *algorithm = TLS_RSA_SIGN_RSA;
\r
3104 if (__is_oid(val, TLS_RSA_SIGN_SHA1_OID, 9)) {
\r
3105 *algorithm = TLS_RSA_SIGN_SHA1;
\r
3109 if (__is_oid(val, TLS_RSA_SIGN_SHA512_OID, 9)) {
\r
3110 *algorithm = TLS_RSA_SIGN_SHA512;
\r
3114 if (__is_oid(val, TLS_RSA_SIGN_SHA384_OID, 9)) {
\r
3115 *algorithm = TLS_RSA_SIGN_SHA384;
\r
3119 if (__is_oid(val, TLS_RSA_SIGN_MD5_OID, 9)) {
\r
3120 *algorithm = TLS_RSA_SIGN_MD5;
\r
3125 void tls_destroy_certificate(struct TLSCertificate *cert) {
\r
3128 TLS_FREE(cert->exponent);
\r
3129 TLS_FREE(cert->pk);
\r
3130 TLS_FREE(cert->issuer_country);
\r
3131 TLS_FREE(cert->issuer_state);
\r
3132 TLS_FREE(cert->issuer_location);
\r
3133 TLS_FREE(cert->issuer_entity);
\r
3134 TLS_FREE(cert->issuer_subject);
\r
3135 TLS_FREE(cert->country);
\r
3136 TLS_FREE(cert->state);
\r
3137 TLS_FREE(cert->location);
\r
3138 TLS_FREE(cert->subject);
\r
3139 for (i = 0; i < cert->san_length; i++) {
\r
3140 TLS_FREE(cert->san[i]);
\r
3142 TLS_FREE(cert->san);
\r
3143 TLS_FREE(cert->ocsp);
\r
3144 TLS_FREE(cert->serial_number);
\r
3145 TLS_FREE(cert->entity);
\r
3146 TLS_FREE(cert->not_before);
\r
3147 TLS_FREE(cert->not_after);
\r
3148 TLS_FREE(cert->sign_key);
\r
3149 TLS_FREE(cert->priv);
\r
3150 TLS_FREE(cert->der_bytes);
\r
3151 TLS_FREE(cert->bytes);
\r
3152 TLS_FREE(cert->fingerprint);
\r
3157 struct TLSPacket *tls_create_packet(struct TLSContext *context, unsigned char type, unsigned short version, int payload_size_hint) {
\r
3158 struct TLSPacket *packet = (struct TLSPacket *)TLS_MALLOC(sizeof(struct TLSPacket));
\r
3161 packet->broken = 0;
\r
3162 if (payload_size_hint > 0)
\r
3163 packet->size = payload_size_hint + 10;
\r
3165 packet->size = __TLS_BLOB_INCREMENT;
\r
3166 packet->buf = (unsigned char *)TLS_MALLOC(packet->size);
\r
3167 packet->context = context;
\r
3168 if (!packet->buf) {
\r
3172 if ((context) && (context->dtls))
\r
3176 packet->buf[0] = type;
\r
3177 *(unsigned short *)&packet->buf[1] = htons(version);
\r
3181 void tls_destroy_packet(struct TLSPacket *packet) {
\r
3184 TLS_FREE(packet->buf);
\r
3189 int __private_tls_crypto_create(struct TLSContext *context, int key_length, int iv_length, unsigned char *localkey, unsigned char *localiv, unsigned char *remotekey, unsigned char *remoteiv) {
\r
3190 if (context->crypto.created) {
\r
3191 if (context->crypto.created == 1) {
\r
3192 cbc_done(&context->crypto.ctx_remote.aes_remote);
\r
3193 cbc_done(&context->crypto.ctx_local.aes_local);
\r
3195 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
3196 if (context->crypto.created == 2) {
\r
3198 unsigned char dummy_buffer[32];
\r
3199 unsigned long tag_len = 0;
\r
3200 gcm_done(&context->crypto.ctx_remote.aes_gcm_remote, dummy_buffer, &tag_len);
\r
3201 gcm_done(&context->crypto.ctx_local.aes_gcm_local, dummy_buffer, &tag_len);
\r
3202 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
3206 context->crypto.created = 0;
\r
3209 int is_aead = __private_tls_is_aead(context);
\r
3210 int cipherID = find_cipher("aes");
\r
3211 DEBUG_PRINT("Using cipher ID: %x\n", (int)context->cipher);
\r
3212 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
3213 if (is_aead == 2) {
\r
3214 unsigned int counter = 1;
\r
3216 chacha_keysetup(&context->crypto.ctx_local.chacha_local, localkey, key_length * 8);
\r
3217 chacha_ivsetup_96bitnonce(&context->crypto.ctx_local.chacha_local, localiv, (unsigned char *)&counter);
\r
3219 chacha_keysetup(&context->crypto.ctx_remote.chacha_remote, remotekey, key_length * 8);
\r
3220 chacha_ivsetup_96bitnonce(&context->crypto.ctx_remote.chacha_remote, remoteiv, (unsigned char *)&counter);
\r
3222 context->crypto.created = 3;
\r
3226 int res1 = gcm_init(&context->crypto.ctx_local.aes_gcm_local, cipherID, localkey, key_length);
\r
3227 int res2 = gcm_init(&context->crypto.ctx_remote.aes_gcm_remote, cipherID, remotekey, key_length);
\r
3229 if ((res1) || (res2))
\r
3230 return TLS_GENERIC_ERROR;
\r
3231 context->crypto.created = 2;
\r
3233 int res1 = cbc_start(cipherID, localiv, localkey, key_length, 0, &context->crypto.ctx_local.aes_local);
\r
3234 int res2 = cbc_start(cipherID, remoteiv, remotekey, key_length, 0, &context->crypto.ctx_remote.aes_remote);
\r
3236 if ((res1) || (res2))
\r
3237 return TLS_GENERIC_ERROR;
\r
3238 context->crypto.created = 1;
\r
3243 int __private_tls_crypto_encrypt(struct TLSContext *context, unsigned char *buf, unsigned char *ct, unsigned int len) {
\r
3244 if (context->crypto.created == 1)
\r
3245 return cbc_encrypt(buf, ct, len, &context->crypto.ctx_local.aes_local);
\r
3247 memset(ct, 0, len);
\r
3248 return TLS_GENERIC_ERROR;
\r
3251 int __private_tls_crypto_decrypt(struct TLSContext *context, unsigned char *buf, unsigned char *pt, unsigned int len) {
\r
3252 if (context->crypto.created == 1)
\r
3253 return cbc_decrypt(buf, pt, len, &context->crypto.ctx_remote.aes_remote);
\r
3255 memset(pt, 0, len);
\r
3256 return TLS_GENERIC_ERROR;
\r
3259 void __private_tls_crypto_done(struct TLSContext *context) {
\r
3260 unsigned char dummy_buffer[32];
\r
3261 unsigned long tag_len = 0;
\r
3262 switch (context->crypto.created) {
\r
3264 cbc_done(&context->crypto.ctx_remote.aes_remote);
\r
3265 cbc_done(&context->crypto.ctx_local.aes_local);
\r
3268 gcm_done(&context->crypto.ctx_remote.aes_gcm_remote, dummy_buffer, &tag_len);
\r
3269 gcm_done(&context->crypto.ctx_local.aes_gcm_local, dummy_buffer, &tag_len);
\r
3272 context->crypto.created = 0;
\r
3275 void tls_packet_update(struct TLSPacket *packet) {
\r
3276 if ((packet) && (!packet->broken)) {
\r
3277 unsigned int header_size = 5;
\r
3278 if ((packet->context) && (packet->context->dtls)) {
\r
3280 *(unsigned short *)&packet->buf[3] = htons(packet->context->dtls_epoch_local);
\r
3281 uint64_t sequence_number = packet->context->local_sequence_number;
\r
3282 packet->buf[5] = sequence_number / 0x10000000000LL;
\r
3283 sequence_number %= 0x10000000000LL;
\r
3284 packet->buf[6] = sequence_number / 0x100000000LL;
\r
3285 sequence_number %= 0x100000000LL;
\r
3286 packet->buf[7] = sequence_number / 0x1000000;
\r
3287 sequence_number %= 0x1000000;
\r
3288 packet->buf[8] = sequence_number / 0x10000;
\r
3289 sequence_number %= 0x10000;
\r
3290 packet->buf[9] = sequence_number / 0x100;
\r
3291 sequence_number %= 0x100;
\r
3292 packet->buf[10] = sequence_number;
\r
3294 *(unsigned short *)&packet->buf[11] = htons(packet->len - header_size);
\r
3296 *(unsigned short *)&packet->buf[3] = htons(packet->len - header_size);
\r
3297 if (packet->context) {
\r
3298 if (packet->buf[0] != TLS_CHANGE_CIPHER) {
\r
3299 if ((packet->buf[0] == TLS_HANDSHAKE) && (packet->len > header_size)) {
\r
3300 unsigned char handshake_type = packet->buf[header_size];
\r
3301 if ((handshake_type != 0x00) && (handshake_type != 0x03))
\r
3302 __private_tls_update_hash(packet->context, packet->buf + header_size, packet->len - header_size);
\r
3305 if ((packet->context->cipher_spec_set) && (packet->context->crypto.created)) {
\r
3306 int block_size = __TLS_AES_BLOCK_SIZE;
\r
3308 unsigned int length = 0;
\r
3309 unsigned char padding = 0;
\r
3310 unsigned int pt_length = packet->len - header_size;
\r
3312 if (packet->context->crypto.created == 1) {
\r
3313 mac_size = __private_tls_mac_length(packet->context);
\r
3314 #ifdef TLS_LEGACY_SUPPORT
\r
3315 if (packet->context->version == TLS_V10)
\r
3316 length = packet->len - header_size + mac_size;
\r
3319 length = packet->len - header_size + __TLS_AES_IV_LENGTH + mac_size;
\r
3320 padding = block_size - length % block_size;
\r
3321 length += padding;
\r
3322 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
3324 if (packet->context->crypto.created == 3) {
\r
3325 mac_size = POLY1305_TAGLEN;
\r
3326 length = packet->len - header_size + mac_size;
\r
3329 mac_size = __TLS_GCM_TAG_LEN;
\r
3330 length = packet->len - header_size + 8 + mac_size;
\r
3334 if (packet->context->crypto.created == 1) {
\r
3335 unsigned char *buf = (unsigned char *)TLS_MALLOC(length);
\r
3337 unsigned char *ct = (unsigned char *)TLS_MALLOC(length + header_size);
\r
3339 unsigned int buf_pos = 0;
\r
3340 memcpy(ct, packet->buf, header_size - 2);
\r
3341 *(unsigned short *)&ct[header_size - 2] = htons(length);
\r
3342 #ifdef TLS_LEGACY_SUPPORT
\r
3343 if (packet->context->version != TLS_V10)
\r
3346 tls_random(buf, __TLS_AES_IV_LENGTH);
\r
3347 buf_pos += __TLS_AES_IV_LENGTH;
\r
3350 memcpy(buf + buf_pos, packet->buf + header_size, packet->len - header_size);
\r
3351 buf_pos += packet->len - header_size;
\r
3352 if (packet->context->dtls) {
\r
3353 unsigned char temp_buf[5];
\r
3354 memcpy(temp_buf, packet->buf, 3);
\r
3355 *(unsigned short *)&temp_buf[3] = *(unsigned short *)&packet->buf[header_size - 2];
\r
3356 uint64_t dtls_sequence_number = ntohll(*(uint64_t *)&packet->buf[3]);
\r
3357 __private_tls_hmac_message(1, packet->context, temp_buf, 5, packet->buf + header_size, packet->len - header_size, buf + buf_pos, mac_size, dtls_sequence_number);
\r
3359 __private_tls_hmac_message(1, packet->context, packet->buf, packet->len, NULL, 0, buf + buf_pos, mac_size, 0);
\r
3360 buf_pos += mac_size;
\r
3362 memset(buf + buf_pos, padding - 1, padding);
\r
3363 buf_pos += padding;
\r
3365 //DEBUG_DUMP_HEX_LABEL("PT BUFFER", buf, length);
\r
3366 __private_tls_crypto_encrypt(packet->context, buf, ct + header_size, length);
\r
3367 TLS_FREE(packet->buf);
\r
3369 packet->len = length + header_size;
\r
3370 packet->size = packet->len;
\r
3372 // invalidate packet
\r
3373 memset(packet->buf, 0, packet->len);
\r
3377 // invalidate packet
\r
3378 memset(packet->buf, 0, packet->len);
\r
3381 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
3382 if (packet->context->crypto.created >= 2) {
\r
3384 if (packet->context->crypto.created == 2) {
\r
3386 int ct_size = length + header_size + 12 + __TLS_MAX_TAG_LEN;
\r
3387 unsigned char *ct = (unsigned char *)TLS_MALLOC(ct_size);
\r
3389 memset(ct, 0, ct_size);
\r
3391 // sequence number (8 bytes)
\r
3392 // content type (1 byte)
\r
3393 // version (2 bytes)
\r
3394 // length (2 bytes)
\r
3395 unsigned char aad[13];
\r
3396 if (packet->context->dtls)
\r
3397 *((uint64_t *)aad) = *(uint64_t *)&packet->buf[3];
\r
3399 *((uint64_t *)aad) = htonll(packet->context->local_sequence_number);
\r
3400 aad[8] = packet->buf[0];
\r
3401 aad[9] = packet->buf[1];
\r
3402 aad[10] = packet->buf[2];
\r
3403 *((unsigned short *)&aad[11]) = htons(packet->len - header_size);
\r
3405 int ct_pos = header_size;
\r
3406 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
3407 if (packet->context->crypto.created == 3) {
\r
3408 unsigned int counter = 1;
\r
3409 unsigned char poly1305_key[POLY1305_KEYLEN];
\r
3410 chacha_ivupdate(&packet->context->crypto.ctx_local.chacha_local, packet->context->crypto.ctx_local_mac.local_aead_iv, aad, (u8 *)&counter);
\r
3411 chacha20_poly1305_key(&packet->context->crypto.ctx_local.chacha_local, poly1305_key);
\r
3412 ct_pos += chacha20_poly1305_aead(&packet->context->crypto.ctx_local.chacha_local, packet->buf + header_size, pt_length, aad, sizeof(aad), poly1305_key, ct + ct_pos);
\r
3415 unsigned char iv[12];
\r
3416 memcpy(iv, packet->context->crypto.ctx_local_mac.local_aead_iv, __TLS_AES_GCM_IV_LENGTH);
\r
3417 tls_random(iv + __TLS_AES_GCM_IV_LENGTH, 8);
\r
3418 memcpy(ct + ct_pos, iv + __TLS_AES_GCM_IV_LENGTH, 8);
\r
3421 gcm_reset(&packet->context->crypto.ctx_local.aes_gcm_local);
\r
3422 gcm_add_iv(&packet->context->crypto.ctx_local.aes_gcm_local, iv, 12);
\r
3423 gcm_add_aad(&packet->context->crypto.ctx_local.aes_gcm_local, aad, sizeof(aad));
\r
3425 gcm_process(&packet->context->crypto.ctx_local.aes_gcm_local, packet->buf + header_size, pt_length, ct + ct_pos, GCM_ENCRYPT);
\r
3426 ct_pos += pt_length;
\r
3428 unsigned long taglen = __TLS_GCM_TAG_LEN;
\r
3429 gcm_done(&packet->context->crypto.ctx_local.aes_gcm_local, ct + ct_pos, &taglen);
\r
3431 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
3435 memcpy(ct, packet->buf, header_size - 2);
\r
3436 *(unsigned short *)&ct[header_size - 2] = htons(ct_pos - header_size);
\r
3437 TLS_FREE(packet->buf);
\r
3439 packet->len = ct_pos;
\r
3440 packet->size = ct_pos;
\r
3442 // invalidate packet
\r
3443 memset(packet->buf, 0, packet->len);
\r
3446 // invalidate packet (never reached)
\r
3447 memset(packet->buf, 0, packet->len);
\r
3451 packet->context->dtls_epoch_local++;
\r
3452 packet->context->local_sequence_number++;
\r
3457 int tls_packet_append(struct TLSPacket *packet, const unsigned char *buf, unsigned int len) {
\r
3458 if ((!packet) || (packet->broken))
\r
3464 unsigned int new_len = packet->len + len;
\r
3466 if (new_len > packet->size) {
\r
3467 packet->size = (new_len / __TLS_BLOB_INCREMENT + 1) * __TLS_BLOB_INCREMENT;
\r
3468 packet->buf = (unsigned char *)TLS_REALLOC(packet->buf, packet->size);
\r
3469 if (!packet->buf) {
\r
3472 packet->broken = 1;
\r
3476 memcpy(packet->buf + packet->len, buf, len);
\r
3477 packet->len = new_len;
\r
3481 int tls_packet_uint8(struct TLSPacket *packet, unsigned char i) {
\r
3482 return tls_packet_append(packet, &i, 1);
\r
3485 int tls_packet_uint16(struct TLSPacket *packet, unsigned short i) {
\r
3486 unsigned short ni = htons(i);
\r
3487 return tls_packet_append(packet, (unsigned char *)&ni, 2);
\r
3490 int tls_packet_uint32(struct TLSPacket *packet, unsigned int i) {
\r
3491 unsigned int ni = htonl(i);
\r
3492 return tls_packet_append(packet, (unsigned char *)&ni, 4);
\r
3495 int tls_packet_uint24(struct TLSPacket *packet, unsigned int i) {
\r
3496 unsigned char buf[3];
\r
3497 buf[0] = i / 0x10000;
\r
3499 buf[1] = i / 0x100;
\r
3503 return tls_packet_append(packet, buf, 3);
\r
3506 int tls_random(unsigned char *key, int len) {
\r
3508 for (int i = 0; i < len; i++) {
\r
3509 unsigned int v = arc4random() % 0x100;
\r
3515 HCRYPTPROV hProvider = 0;
\r
3516 if (CryptAcquireContext(&hProvider, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
\r
3517 if (CryptGenRandom(hProvider, len, (BYTE *)key)) {
\r
3518 CryptReleaseContext(hProvider, 0);
\r
3521 CryptReleaseContext(hProvider, 0);
\r
3524 FILE *fp = fopen("/dev/urandom", "r");
\r
3526 int key_len = fread(key, 1, len, fp);
\r
3528 if (key_len == len)
\r
3536 TLSHash *__private_tls_ensure_hash(struct TLSContext *context) {
\r
3537 TLSHash *hash = context->handshake_hash;
\r
3539 hash = (TLSHash *)TLS_MALLOC(sizeof(TLSHash));
\r
3541 memset(hash, 0, sizeof(TLSHash));
\r
3542 context->handshake_hash = hash;
\r
3547 void __private_tls_destroy_hash(struct TLSContext *context) {
\r
3549 TLS_FREE(context->handshake_hash);
\r
3550 context->handshake_hash = NULL;
\r
3554 void __private_tls_create_hash(struct TLSContext *context) {
\r
3558 TLSHash *hash = __private_tls_ensure_hash(context);
\r
3559 if ((context->version == TLS_V12) || (context->version == DTLS_V12)) {
\r
3560 int hash_size = __private_tls_mac_length(context);
\r
3561 if (hash->created) {
\r
3562 unsigned char temp[__TLS_MAX_SHA_SIZE];
\r
3563 if (hash_size == __TLS_SHA384_MAC_SIZE)
\r
3564 sha384_done(&hash->hash, temp);
\r
3566 sha256_done(&hash->hash, temp);
\r
3568 if (hash_size == __TLS_SHA384_MAC_SIZE)
\r
3569 sha384_init(&hash->hash);
\r
3571 sha256_init(&hash->hash);
\r
3572 hash->created = 1;
\r
3574 #ifdef TLS_LEGACY_SUPPORT
\r
3576 if (hash->created) {
\r
3577 unsigned char temp[__TLS_V11_HASH_SIZE];
\r
3578 md5_done(&hash->hash, temp);
\r
3579 sha1_done(&hash->hash2, temp);
\r
3581 md5_init(&hash->hash);
\r
3582 sha1_init(&hash->hash2);
\r
3583 hash->created = 1;
\r
3588 int __private_tls_update_hash(struct TLSContext *context, const unsigned char *in, unsigned int len) {
\r
3591 TLSHash *hash = __private_tls_ensure_hash(context);
\r
3592 if ((context->version == TLS_V12) || (context->version == DTLS_V12)) {
\r
3593 if (!hash->created) {
\r
3594 __private_tls_create_hash(context);
\r
3595 #ifdef TLS_LEGACY_SUPPORT
\r
3596 // cache first hello in case of protocol downgrade
\r
3597 if ((!context->is_server) && (!context->cached_handshake) && (!context->request_client_certificate) && (len)) {
\r
3598 context->cached_handshake = (unsigned char *)TLS_MALLOC(len);
\r
3599 if (context->cached_handshake) {
\r
3600 memcpy(context->cached_handshake, in, len);
\r
3601 context->cached_handshake_len = len;
\r
3606 int hash_size = __private_tls_mac_length(context);
\r
3607 if (hash_size == __TLS_SHA384_MAC_SIZE) {
\r
3608 sha384_process(&hash->hash, in, len);
\r
3610 sha256_process(&hash->hash, in, len);
\r
3611 hash_size = __TLS_SHA256_MAC_SIZE;
\r
3614 #ifdef TLS_LEGACY_SUPPORT
\r
3615 if (!hash->created)
\r
3616 __private_tls_create_hash(context);
\r
3617 md5_process(&hash->hash, in, len);
\r
3618 sha1_process(&hash->hash2, in, len);
\r
3621 if ((context->request_client_certificate) && (len)) {
\r
3622 // cache all messages for verification
\r
3623 int new_len = context->cached_handshake_len + len;
\r
3624 context->cached_handshake = (unsigned char *)TLS_REALLOC(context->cached_handshake, new_len);
\r
3625 if (context->cached_handshake) {
\r
3626 memcpy(context->cached_handshake + context->cached_handshake_len, in, len);
\r
3627 context->cached_handshake_len = new_len;
\r
3629 context->cached_handshake_len = 0;
\r
3634 #ifdef TLS_LEGACY_SUPPORT
\r
3635 int __private_tls_change_hash_type(struct TLSContext *context) {
\r
3638 TLSHash *hash = __private_tls_ensure_hash(context);
\r
3639 if ((hash) && (hash->created) && (context->cached_handshake) && (context->cached_handshake_len)) {
\r
3640 __private_tls_destroy_hash(context);
\r
3641 int res = __private_tls_update_hash(context, context->cached_handshake, context->cached_handshake_len);
\r
3642 TLS_FREE(context->cached_handshake);
\r
3643 context->cached_handshake = NULL;
\r
3644 context->cached_handshake_len = 0;
\r
3651 int __private_tls_done_hash(struct TLSContext *context, unsigned char *hout) {
\r
3655 TLSHash *hash = __private_tls_ensure_hash(context);
\r
3656 if (!hash->created)
\r
3659 int hash_size = 0;
\r
3660 if ((context->version == TLS_V12) || (context->version == DTLS_V12)) {
\r
3661 unsigned char temp[__TLS_MAX_SHA_SIZE];
\r
3664 //__TLS_HASH_DONE(&hash->hash, hout);
\r
3665 hash_size = __private_tls_mac_length(context);
\r
3666 if (hash_size == __TLS_SHA384_MAC_SIZE)
\r
3667 sha384_done(&hash->hash, hout);
\r
3669 sha256_done(&hash->hash, hout);
\r
3670 hash_size = __TLS_SHA256_MAC_SIZE;
\r
3673 #ifdef TLS_LEGACY_SUPPORT
\r
3675 unsigned char temp[__TLS_V11_HASH_SIZE];
\r
3678 md5_done(&hash->hash, hout);
\r
3679 sha1_done(&hash->hash2, hout + 16);
\r
3680 hash_size = __TLS_V11_HASH_SIZE;
\r
3683 hash->created = 0;
\r
3684 if (context->cached_handshake) {
\r
3685 // not needed anymore
\r
3686 TLS_FREE(context->cached_handshake);
\r
3687 context->cached_handshake = NULL;
\r
3688 context->cached_handshake_len = 0;
\r
3693 int __private_tls_get_hash(struct TLSContext *context, unsigned char *hout) {
\r
3697 TLSHash *hash = __private_tls_ensure_hash(context);
\r
3698 if (!hash->created)
\r
3701 int hash_size = 0;
\r
3702 if ((context->version == TLS_V12) || (context->version == DTLS_V12)) {
\r
3703 hash_size = __private_tls_mac_length(context);
\r
3705 memcpy(&prec, &hash->hash, sizeof(hash_state));
\r
3706 if (hash_size == __TLS_SHA384_MAC_SIZE)
\r
3707 sha384_done(&hash->hash, hout);
\r
3709 hash_size = __TLS_SHA256_MAC_SIZE;
\r
3710 sha256_done(&hash->hash, hout);
\r
3712 memcpy(&hash->hash, &prec, sizeof(hash_state));
\r
3714 #ifdef TLS_LEGACY_SUPPORT
\r
3718 memcpy(&prec, &hash->hash, sizeof(hash_state));
\r
3719 md5_done(&hash->hash, hout);
\r
3720 memcpy(&hash->hash, &prec, sizeof(hash_state));
\r
3722 memcpy(&prec, &hash->hash2, sizeof(hash_state));
\r
3723 sha1_done(&hash->hash2, hout + 16);
\r
3724 memcpy(&hash->hash2, &prec, sizeof(hash_state));
\r
3726 hash_size = __TLS_V11_HASH_SIZE;
\r
3732 int __private_tls_write_packet(struct TLSPacket *packet) {
\r
3735 struct TLSContext *context = packet->context;
\r
3739 if (context->tls_buffer) {
\r
3740 int len = context->tls_buffer_len + packet->len;
\r
3741 context->tls_buffer = (unsigned char *)TLS_REALLOC(context->tls_buffer, len);
\r
3742 if (!context->tls_buffer) {
\r
3743 context->tls_buffer_len = 0;
\r
3746 memcpy(context->tls_buffer + context->tls_buffer_len, packet->buf, packet->len);
\r
3747 context->tls_buffer_len = len;
\r
3748 int written = packet->len;
\r
3749 tls_destroy_packet(packet);
\r
3752 context->tls_buffer_len = packet->len;
\r
3753 context->tls_buffer = packet->buf;
\r
3754 packet->buf = NULL;
\r
3757 tls_destroy_packet(packet);
\r
3758 return context->tls_buffer_len;
\r
3761 int __private_tls_write_app_data(struct TLSContext *context, const unsigned char *buf, unsigned int buf_len) {
\r
3764 if ((!buf) || (!buf_len))
\r
3767 int len = context->application_buffer_len + buf_len;
\r
3768 context->application_buffer = (unsigned char *)TLS_REALLOC(context->application_buffer, len);
\r
3769 if (!context->application_buffer) {
\r
3770 context->application_buffer_len = 0;
\r
3773 memcpy(context->application_buffer + context->application_buffer_len, buf, buf_len);
\r
3774 context->application_buffer_len = len;
\r
3778 const unsigned char *tls_get_write_buffer(struct TLSContext *context, unsigned int *outlen) {
\r
3785 // check if any error
\r
3786 if (context->sleep_until) {
\r
3787 if (context->sleep_until < time(NULL)) {
\r
3791 context->sleep_until = 0;
\r
3793 *outlen = context->tls_buffer_len;
\r
3794 return context->tls_buffer;
\r
3797 const unsigned char *tls_get_message(struct TLSContext *context, unsigned int *outlen, int offset) {
\r
3800 if ((!context) || (!context->tls_buffer)) {
\r
3805 if (offset >= context->tls_buffer_len) {
\r
3809 // check if any error
\r
3810 if (context->sleep_until) {
\r
3811 if (context->sleep_until < time(NULL)) {
\r
3815 context->sleep_until = 0;
\r
3817 unsigned char *tls_buffer = &context->tls_buffer[offset];
\r
3818 unsigned int tls_buffer_len = context->tls_buffer_len - offset;
\r
3820 if (context->dtls) {
\r
3821 if (tls_buffer_len < 13) {
\r
3826 len = ntohs(*(unsigned short *)&tls_buffer[11]) + 13;
\r
3828 if (tls_buffer_len < 5) {
\r
3832 len = ntohs(*(unsigned short *)&tls_buffer[3]) + 5;
\r
3834 if (len > tls_buffer_len) {
\r
3840 return tls_buffer;
\r
3843 void tls_buffer_clear(struct TLSContext *context) {
\r
3844 if ((context) && (context->tls_buffer)) {
\r
3845 TLS_FREE(context->tls_buffer);
\r
3846 context->tls_buffer = NULL;
\r
3847 context->tls_buffer_len = 0;
\r
3851 int tls_established(struct TLSContext *context) {
\r
3853 if (context->critical_error)
\r
3856 if (context->connection_status == 0xFF)
\r
3862 void tls_read_clear(struct TLSContext *context) {
\r
3863 if ((context) && (context->application_buffer)) {
\r
3864 TLS_FREE(context->application_buffer);
\r
3865 context->application_buffer = NULL;
\r
3866 context->application_buffer_len = 0;
\r
3870 int tls_read(struct TLSContext *context, unsigned char *buf, unsigned int size) {
\r
3873 if ((context->application_buffer) && (context->application_buffer_len)) {
\r
3874 if (context->application_buffer_len < size)
\r
3875 size = context->application_buffer_len;
\r
3877 memcpy(buf, context->application_buffer, size);
\r
3878 if (context->application_buffer_len == size) {
\r
3879 TLS_FREE(context->application_buffer);
\r
3880 context->application_buffer = NULL;
\r
3881 context->application_buffer_len = 0;
\r
3884 context->application_buffer_len -= size;
\r
3885 memmove(context->application_buffer, context->application_buffer + size, context->application_buffer_len);
\r
3891 struct TLSContext *tls_create_context(unsigned char is_server, unsigned short version) {
\r
3892 struct TLSContext *context = (struct TLSContext *)TLS_MALLOC(sizeof(struct TLSContext));
\r
3894 memset(context, 0, sizeof(struct TLSContext));
\r
3895 context->is_server = is_server;
\r
3896 if ((version == DTLS_V12) || (version == DTLS_V10))
\r
3897 context->dtls = 1;
\r
3898 context->version = version;
\r
3903 #ifdef TLS_FORWARD_SECRECY
\r
3904 const struct ECCCurveParameters *tls_set_curve(struct TLSContext *context, const struct ECCCurveParameters *curve) {
\r
3905 if (!context->is_server)
\r
3907 const struct ECCCurveParameters *old_curve = context->curve;
\r
3908 context->curve = curve;
\r
3913 struct TLSContext *tls_accept(struct TLSContext *context) {
\r
3914 if ((!context) || (!context->is_server))
\r
3917 struct TLSContext *child = (struct TLSContext *)TLS_MALLOC(sizeof(struct TLSContext));
\r
3919 memset(child, 0, sizeof(struct TLSContext));
\r
3920 child->is_server = 1;
\r
3921 child->is_child = 1;
\r
3922 child->dtls = context->dtls;
\r
3923 child->version = context->version;
\r
3924 child->certificates = context->certificates;
\r
3925 child->certificates_count = context->certificates_count;
\r
3926 child->private_key = context->private_key;
\r
3927 #ifdef TLS_ECDSA_SUPPORTED
\r
3928 child->ec_private_key = context->ec_private_key;
\r
3930 child->exportable = context->exportable;
\r
3931 child->root_certificates = context->root_certificates;
\r
3932 child->root_count = context->root_count;
\r
3933 #ifdef TLS_FORWARD_SECRECY
\r
3934 child->default_dhe_p = context->default_dhe_p;
\r
3935 child->default_dhe_g = context->default_dhe_g;
\r
3936 child->curve = context->curve;
\r
3938 child->alpn = context->alpn;
\r
3939 child->alpn_count = context->alpn_count;
\r
3944 #ifdef TLS_FORWARD_SECRECY
\r
3945 void __private_tls_dhe_free(struct TLSContext *context) {
\r
3946 if (context->dhe) {
\r
3947 __private_tls_dh_clear_key(context->dhe);
\r
3948 TLS_FREE(context->dhe);
\r
3949 context->dhe = NULL;
\r
3953 void __private_tls_dhe_create(struct TLSContext *context) {
\r
3954 __private_tls_dhe_free(context);
\r
3955 context->dhe = (DHKey *)TLS_MALLOC(sizeof(DHKey));
\r
3957 memset(context->dhe, 0, sizeof(DHKey));
\r
3960 void __private_tls_ecc_dhe_free(struct TLSContext *context) {
\r
3961 if (context->ecc_dhe) {
\r
3962 ecc_free(context->ecc_dhe);
\r
3963 TLS_FREE(context->ecc_dhe);
\r
3964 context->ecc_dhe = NULL;
\r
3968 void __private_tls_ecc_dhe_create(struct TLSContext *context) {
\r
3969 __private_tls_ecc_dhe_free(context);
\r
3970 context->ecc_dhe = (ecc_key *)TLS_MALLOC(sizeof(ecc_key));
\r
3971 memset(context->ecc_dhe, 0, sizeof(ecc_key));
\r
3974 int tls_set_default_dhe_pg(struct TLSContext *context, const char *p_hex_str, const char *g_hex_str) {
\r
3975 if ((!context) || (context->is_child) || (!context->is_server) || (!p_hex_str) || (!g_hex_str))
\r
3978 TLS_FREE(context->default_dhe_p);
\r
3979 TLS_FREE(context->default_dhe_g);
\r
3981 context->default_dhe_p = NULL;
\r
3982 context->default_dhe_g = NULL;
\r
3984 int p_len = strlen(p_hex_str);
\r
3985 int g_len = strlen(g_hex_str);
\r
3986 if ((p_len <= 0) || (g_len <= 0))
\r
3988 context->default_dhe_p = (char *)TLS_MALLOC(p_len + 1);
\r
3989 if (!context->default_dhe_p)
\r
3991 context->default_dhe_g = (char *)TLS_MALLOC(g_len + 1);
\r
3992 if (!context->default_dhe_g)
\r
3995 memcpy(context->default_dhe_p, p_hex_str, p_len);
\r
3996 context->default_dhe_p[p_len] = 0;
\r
3998 memcpy(context->default_dhe_g, g_hex_str, g_len);
\r
3999 context->default_dhe_g[g_len] = 0;
\r
4004 const char *tls_alpn(struct TLSContext *context) {
\r
4007 return context->negotiated_alpn;
\r
4010 int tls_add_alpn(struct TLSContext *context, const char *alpn) {
\r
4011 if ((!context) || (!alpn) || (!alpn[0]) || ((context->is_server) && (context->is_child)))
\r
4012 return TLS_GENERIC_ERROR;
\r
4013 int len = strlen(alpn);
\r
4014 if (tls_alpn_contains(context, alpn, len))
\r
4016 context->alpn = (char **)TLS_REALLOC(context->alpn, (context->alpn_count + 1) * sizeof(char *));
\r
4017 if (!context->alpn) {
\r
4018 context->alpn_count = 0;
\r
4019 return TLS_NO_MEMORY;
\r
4021 char *alpn_ref = (char *)TLS_MALLOC(len+1);
\r
4022 context->alpn[context->alpn_count] = alpn_ref;
\r
4024 memcpy(alpn_ref, alpn, len);
\r
4025 alpn_ref[len] = 0;
\r
4026 context->alpn_count++;
\r
4028 return TLS_NO_MEMORY;
\r
4032 int tls_alpn_contains(struct TLSContext *context, const char *alpn, unsigned char alpn_size) {
\r
4033 if ((!context) || (!alpn) || (!alpn_size))
\r
4036 if (context->alpn) {
\r
4038 for (i = 0; i < context->alpn_count; i++) {
\r
4039 const char *alpn_local = context->alpn[i];
\r
4041 int len = strlen(alpn_local);
\r
4042 if (alpn_size == len) {
\r
4043 if (!memcmp(alpn_local, alpn, alpn_size))
\r
4052 void tls_destroy_context(struct TLSContext *context) {
\r
4056 if (!context->is_child) {
\r
4057 if (context->certificates) {
\r
4058 for (i = 0; i < context->certificates_count; i++)
\r
4059 tls_destroy_certificate(context->certificates[i]);
\r
4061 if (context->root_certificates) {
\r
4062 for (i = 0; i < context->root_count; i++)
\r
4063 tls_destroy_certificate(context->root_certificates[i]);
\r
4065 if (context->private_key)
\r
4066 tls_destroy_certificate(context->private_key);
\r
4067 #ifdef TLS_ECDSA_SUPPORTED
\r
4068 if (context->ec_private_key)
\r
4069 tls_destroy_certificate(context->ec_private_key);
\r
4071 TLS_FREE(context->certificates);
\r
4072 #ifdef TLS_FORWARD_SECRECY
\r
4073 TLS_FREE(context->default_dhe_p);
\r
4074 TLS_FREE(context->default_dhe_g);
\r
4076 if (context->alpn) {
\r
4077 for (i = 0; i < context->alpn_count; i++)
\r
4078 TLS_FREE(context->alpn[i]);
\r
4079 TLS_FREE(context->alpn);
\r
4082 if (context->client_certificates) {
\r
4083 for (i = 0; i < context->client_certificates_count; i++)
\r
4084 tls_destroy_certificate(context->client_certificates[i]);
\r
4085 TLS_FREE(context->client_certificates);
\r
4087 context->client_certificates = NULL;
\r
4088 TLS_FREE(context->master_key);
\r
4089 TLS_FREE(context->premaster_key);
\r
4090 if (context->crypto.created)
\r
4091 __private_tls_crypto_done(context);
\r
4092 TLS_FREE(context->message_buffer);
\r
4093 __private_tls_done_hash(context, NULL);
\r
4094 __private_tls_destroy_hash(context);
\r
4095 TLS_FREE(context->tls_buffer);
\r
4096 TLS_FREE(context->application_buffer);
\r
4097 // zero out the keys before free
\r
4098 if ((context->exportable_keys) && (context->exportable_size))
\r
4099 memset(context->exportable_keys, 0, context->exportable_size);
\r
4100 TLS_FREE(context->exportable_keys);
\r
4101 TLS_FREE(context->sni);
\r
4102 TLS_FREE(context->dtls_cookie);
\r
4103 TLS_FREE(context->cached_handshake);
\r
4104 #ifdef TLS_FORWARD_SECRECY
\r
4105 __private_tls_dhe_free(context);
\r
4106 __private_tls_ecc_dhe_free(context);
\r
4108 #ifdef TLS_ACCEPT_SECURE_RENEGOTIATION
\r
4109 TLS_FREE(context->verify_data);
\r
4111 TLS_FREE(context->negotiated_alpn);
\r
4112 TLS_FREE(context);
\r
4115 #ifdef TLS_ACCEPT_SECURE_RENEGOTIATION
\r
4116 void __private_tls_reset_context(struct TLSContext *context) {
\r
4120 if (!context->is_child) {
\r
4121 if (context->certificates) {
\r
4122 for (i = 0; i < context->certificates_count; i++)
\r
4123 tls_destroy_certificate(context->certificates[i]);
\r
4125 context->certificates = NULL;
\r
4126 if (context->private_key) {
\r
4127 tls_destroy_certificate(context->private_key);
\r
4128 context->private_key = NULL;
\r
4130 #ifdef TLS_ECDSA_SUPPORTED
\r
4131 if (context->ec_private_key) {
\r
4132 tls_destroy_certificate(context->ec_private_key);
\r
4133 context->ec_private_key = NULL;
\r
4136 TLS_FREE(context->certificates);
\r
4137 context->certificates = NULL;
\r
4138 #ifdef TLS_FORWARD_SECRECY
\r
4139 TLS_FREE(context->default_dhe_p);
\r
4140 TLS_FREE(context->default_dhe_g);
\r
4141 context->default_dhe_p = NULL;
\r
4142 context->default_dhe_g = NULL;
\r
4145 if (context->client_certificates) {
\r
4146 for (i = 0; i < context->client_certificates_count; i++)
\r
4147 tls_destroy_certificate(context->client_certificates[i]);
\r
4148 TLS_FREE(context->client_certificates);
\r
4150 context->client_certificates = NULL;
\r
4151 TLS_FREE(context->master_key);
\r
4152 context->master_key = NULL;
\r
4153 TLS_FREE(context->premaster_key);
\r
4154 context->premaster_key = NULL;
\r
4155 if (context->crypto.created)
\r
4156 __private_tls_crypto_done(context);
\r
4157 __private_tls_done_hash(context, NULL);
\r
4158 __private_tls_destroy_hash(context);
\r
4159 TLS_FREE(context->application_buffer);
\r
4160 context->application_buffer = NULL;
\r
4161 // zero out the keys before free
\r
4162 if ((context->exportable_keys) && (context->exportable_size))
\r
4163 memset(context->exportable_keys, 0, context->exportable_size);
\r
4164 TLS_FREE(context->exportable_keys);
\r
4165 context->exportable_keys = NULL;
\r
4166 TLS_FREE(context->sni);
\r
4167 context->sni = NULL;
\r
4168 TLS_FREE(context->dtls_cookie);
\r
4169 context->dtls_cookie = NULL;
\r
4170 TLS_FREE(context->cached_handshake);
\r
4171 context->cached_handshake = NULL;
\r
4172 context->connection_status = 0;
\r
4173 #ifdef TLS_FORWARD_SECRECY
\r
4174 __private_tls_dhe_free(context);
\r
4175 __private_tls_ecc_dhe_free(context);
\r
4180 int tls_cipher_supported(struct TLSContext *context, unsigned short cipher) {
\r
4184 #ifdef TLS_FORWARD_SECRECY
\r
4185 #ifdef TLS_ECDSA_SUPPORTED
\r
4186 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
\r
4187 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
\r
4188 #ifdef TLS_CLIENT_ECDSA
\r
4189 if ((context) && (((context->certificates) && (context->certificates_count) && (context->ec_private_key)) || (!context->is_server)))
\r
4191 if ((context) && (context->certificates) && (context->certificates_count) && (context->ec_private_key))
\r
4195 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
\r
4196 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
\r
4197 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
\r
4198 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
\r
4199 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
4200 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
\r
4202 if ((context->version == TLS_V12) || (context->version == DTLS_V12)) {
\r
4203 #ifdef TLS_CLIENT_ECDSA
\r
4204 if ((context) && (((context->certificates) && (context->certificates_count) && (context->ec_private_key)) || (!context->is_server)))
\r
4206 if ((context) && (context->certificates) && (context->certificates_count) && (context->ec_private_key))
\r
4212 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
\r
4213 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
\r
4214 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
\r
4215 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
\r
4217 case TLS_RSA_WITH_AES_128_CBC_SHA:
\r
4218 case TLS_RSA_WITH_AES_256_CBC_SHA:
\r
4220 #ifdef TLS_FORWARD_SECRECY
\r
4221 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
\r
4222 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
\r
4223 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
\r
4224 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
\r
4225 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
\r
4226 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
\r
4227 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
\r
4228 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
4229 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
\r
4230 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
\r
4233 case TLS_RSA_WITH_AES_128_GCM_SHA256:
\r
4234 case TLS_RSA_WITH_AES_128_CBC_SHA256:
\r
4235 case TLS_RSA_WITH_AES_256_CBC_SHA256:
\r
4236 case TLS_RSA_WITH_AES_256_GCM_SHA384:
\r
4237 if ((context->version == TLS_V12) || (context->version == DTLS_V12))
\r
4244 int tls_cipher_is_fs(struct TLSContext *context, unsigned short cipher) {
\r
4248 #ifdef TLS_ECDSA_SUPPORTED
\r
4249 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
\r
4250 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
\r
4251 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
4252 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
\r
4254 if ((context) && (context->certificates) && (context->certificates_count) && (context->ec_private_key))
\r
4257 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
\r
4258 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
\r
4259 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
\r
4260 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
\r
4261 if ((context->version == TLS_V12) || (context->version == DTLS_V12)) {
\r
4262 if ((context) && (context->certificates) && (context->certificates_count) && (context->ec_private_key))
\r
4267 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
\r
4268 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
\r
4269 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
\r
4270 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
\r
4272 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
\r
4273 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
\r
4274 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
\r
4275 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
\r
4276 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
\r
4277 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
\r
4278 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
\r
4279 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
4280 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
\r
4281 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
\r
4283 if ((context->version == TLS_V12) || (context->version == DTLS_V12))
\r
4291 int __private_tls_prefer_ktls(struct TLSContext *context, unsigned short cipher) {
\r
4292 if ((context->version != TLS_V12) && (context->version != DTLS_V12))
\r
4296 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
\r
4297 if ((context->version == TLS_V12) || (context->version == DTLS_V12)) {
\r
4298 if ((context) && (context->certificates) && (context->certificates_count) && (context->ec_private_key))
\r
4302 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
\r
4303 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
\r
4310 int tls_choose_cipher(struct TLSContext *context, const unsigned char *buf, int buf_len, int *scsv_set) {
\r
4316 int selected_cipher = TLS_NO_COMMON_CIPHER;
\r
4317 #ifdef TLS_FORWARD_SECRECY
\r
4319 for (i = 0; i < buf_len; i+=2) {
\r
4320 unsigned short cipher = ntohs(*(unsigned short *)&buf[i]);
\r
4321 if (__private_tls_prefer_ktls(context, cipher)) {
\r
4322 selected_cipher = cipher;
\r
4327 if (selected_cipher == TLS_NO_COMMON_CIPHER) {
\r
4328 for (i = 0; i < buf_len; i+=2) {
\r
4329 unsigned short cipher = ntohs(*(unsigned short *)&buf[i]);
\r
4330 if (tls_cipher_is_fs(context, cipher)) {
\r
4331 selected_cipher = cipher;
\r
4337 for (i = 0; i < buf_len; i+=2) {
\r
4338 unsigned short cipher = ntohs(*(unsigned short *)&buf[i]);
\r
4339 if (cipher == TLS_FALLBACK_SCSV) {
\r
4342 if (selected_cipher != TLS_NO_COMMON_CIPHER)
\r
4345 #ifndef TLS_ROBOT_MITIGATION
\r
4347 if ((selected_cipher == TLS_NO_COMMON_CIPHER) && (tls_cipher_supported(context, cipher)))
\r
4348 selected_cipher = cipher;
\r
4351 return selected_cipher;
\r
4354 int tls_cipher_is_ephemeral(struct TLSContext *context) {
\r
4356 switch (context->cipher) {
\r
4357 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
\r
4358 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
\r
4359 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
\r
4360 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
\r
4361 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
\r
4362 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
\r
4363 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
\r
4365 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
\r
4366 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
\r
4367 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
\r
4368 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
\r
4369 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
\r
4370 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
\r
4371 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
\r
4372 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
\r
4373 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
\r
4374 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
\r
4375 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
\r
4376 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
\r
4377 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
\r
4384 const char *tls_cipher_name(struct TLSContext *context) {
\r
4386 switch (context->cipher) {
\r
4387 case TLS_RSA_WITH_AES_128_CBC_SHA:
\r
4388 return "RSA-AES128CBC-SHA";
\r
4389 case TLS_RSA_WITH_AES_256_CBC_SHA:
\r
4390 return "RSA-AES256CBC-SHA";
\r
4391 case TLS_RSA_WITH_AES_128_CBC_SHA256:
\r
4392 return "RSA-AES128CBC-SHA256";
\r
4393 case TLS_RSA_WITH_AES_256_CBC_SHA256:
\r
4394 return "RSA-AES256CBC-SHA256";
\r
4395 case TLS_RSA_WITH_AES_128_GCM_SHA256:
\r
4396 return "RSA-AES128GCM-SHA256";
\r
4397 case TLS_RSA_WITH_AES_256_GCM_SHA384:
\r
4398 return "RSA-AES256GCM-SHA384";
\r
4399 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
\r
4400 return "DHE-RSA-AES128CBC-SHA";
\r
4401 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
\r
4402 return "DHE-RSA-AES256CBC-SHA";
\r
4403 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
\r
4404 return "DHE-RSA-AES128CBC-SHA256";
\r
4405 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
\r
4406 return "DHE-RSA-AES256CBC-SHA256";
\r
4407 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
\r
4408 return "DHE-RSA-AES128GCM-SHA256";
\r
4409 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
\r
4410 return "DHE-RSA-AES256GCM-SHA384";
\r
4411 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
\r
4412 return "ECDHE-RSA-AES128CBC-SHA";
\r
4413 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
\r
4414 return "ECDHE-RSA-AES256CBC-SHA";
\r
4415 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
\r
4416 return "ECDHE-RSA-AES128CBC-SHA256";
\r
4417 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
\r
4418 return "ECDHE-RSA-AES128GCM-SHA256";
\r
4419 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
\r
4420 return "ECDHE-RSA-AES256GCM-SHA384";
\r
4421 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
\r
4422 return "ECDHE-ECDSA-AES128CBC-SHA";
\r
4423 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
\r
4424 return "ECDHE-ECDSA-AES256CBC-SHA";
\r
4425 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
\r
4426 return "ECDHE-ECDSA-AES128CBC-SHA256";
\r
4427 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
\r
4428 return "ECDHE-ECDSA-AES256CBC-SHA384";
\r
4429 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
\r
4430 return "ECDHE-ECDSA-AES128GCM-SHA256";
\r
4431 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
\r
4432 return "ECDHE-ECDSA-AES256GCM-SHA384";
\r
4433 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
\r
4434 return "ECDHE-RSA-CHACHA20-POLY1305-SHA256";
\r
4435 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
\r
4436 return "ECDHE-ECDSA-CHACHA20-POLY1305-SHA256";
\r
4437 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
\r
4438 return "ECDHE-DHE-CHACHA20-POLY1305-SHA256";
\r
4444 #ifdef TLS_FORWARD_SECRECY
\r
4445 int __private_tls_dh_export_pqY(unsigned char *pbuf, unsigned long *plen, unsigned char *gbuf, unsigned long *glen, unsigned char *Ybuf, unsigned long *Ylen, DHKey *key) {
\r
4446 unsigned long len;
\r
4449 if ((pbuf == NULL) || (plen == NULL) || (gbuf == NULL) || (glen == NULL) || (Ybuf == NULL) || (Ylen == NULL) || (key == NULL))
\r
4450 return TLS_GENERIC_ERROR;
\r
4452 len = mp_unsigned_bin_size(key->y);
\r
4454 return TLS_GENERIC_ERROR;
\r
4456 if ((err = mp_to_unsigned_bin(key->y, Ybuf)) != CRYPT_OK)
\r
4461 len = mp_unsigned_bin_size(key->p);
\r
4463 return TLS_GENERIC_ERROR;
\r
4465 if ((err = mp_to_unsigned_bin(key->p, pbuf)) != CRYPT_OK)
\r
4470 len = mp_unsigned_bin_size(key->g);
\r
4472 return TLS_GENERIC_ERROR;
\r
4474 if ((err = mp_to_unsigned_bin(key->g, gbuf)) != CRYPT_OK)
\r
4482 void __private_tls_dh_clear_key(DHKey *key) {
\r
4483 mp_clear_multi(key->g, key->p, key->x, key->y, NULL);
\r
4490 int __private_tls_dh_make_key(int keysize, DHKey *key, const char *pbuf, const char *gbuf, int pbuf_len, int gbuf_len) {
\r
4491 unsigned char *buf;
\r
4494 return TLS_GENERIC_ERROR;
\r
4496 static prng_state prng;
\r
4497 int wprng = find_prng("sprng");
\r
4498 if ((err = prng_is_valid(wprng)) != CRYPT_OK)
\r
4501 buf = (unsigned char *)TLS_MALLOC(keysize);
\r
4503 return TLS_NO_MEMORY;
\r
4505 if (rng_make_prng(keysize, wprng, &prng, NULL) != CRYPT_OK) {
\r
4507 return TLS_GENERIC_ERROR;
\r
4510 if (prng_descriptor[wprng].read(buf, keysize, &prng) != (unsigned long)keysize) {
\r
4512 return TLS_GENERIC_ERROR;
\r
4515 if ((err = mp_init_multi(&key->g, &key->p, &key->x, &key->y, NULL)) != CRYPT_OK) {
\r
4518 return TLS_GENERIC_ERROR;
\r
4521 if (gbuf_len <= 0) {
\r
4522 if ((err = mp_read_radix(key->g, gbuf, 16)) != CRYPT_OK) {
\r
4524 __private_tls_dh_clear_key(key);
\r
4525 return TLS_GENERIC_ERROR;
\r
4528 if ((err = mp_read_unsigned_bin(key->g, (unsigned char *)gbuf, gbuf_len)) != CRYPT_OK) {
\r
4530 __private_tls_dh_clear_key(key);
\r
4531 return TLS_GENERIC_ERROR;
\r
4535 if (pbuf_len <= 0) {
\r
4536 if ((err = mp_read_radix(key->p, pbuf, 16)) != CRYPT_OK) {
\r
4538 __private_tls_dh_clear_key(key);
\r
4539 return TLS_GENERIC_ERROR;
\r
4542 if ((err = mp_read_unsigned_bin(key->p, (unsigned char *)pbuf, pbuf_len)) != CRYPT_OK) {
\r
4544 __private_tls_dh_clear_key(key);
\r
4545 return TLS_GENERIC_ERROR;
\r
4549 if ((err = mp_read_unsigned_bin(key->x, buf, keysize)) != CRYPT_OK) {
\r
4551 __private_tls_dh_clear_key(key);
\r
4552 return TLS_GENERIC_ERROR;
\r
4555 if ((err = mp_exptmod(key->g, key->x, key->p, key->y)) != CRYPT_OK) {
\r
4557 __private_tls_dh_clear_key(key);
\r
4558 return TLS_GENERIC_ERROR;
\r
4566 int tls_is_ecdsa(struct TLSContext *context) {
\r
4569 switch (context->cipher) {
\r
4570 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
\r
4571 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
\r
4572 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
\r
4573 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
\r
4574 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
\r
4575 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
\r
4576 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
4577 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
\r
4584 struct TLSPacket *tls_build_client_key_exchange(struct TLSContext *context) {
\r
4585 if (context->is_server) {
\r
4586 DEBUG_PRINT("CANNOT BUILD CLIENT KEY EXCHANGE MESSAGE FOR SERVERS\n");
\r
4590 struct TLSPacket *packet = tls_create_packet(context, TLS_HANDSHAKE, context->version, 0);
\r
4591 tls_packet_uint8(packet, 0x10);
\r
4592 #ifdef TLS_FORWARD_SECRECY
\r
4593 int ephemeral = tls_cipher_is_ephemeral(context);
\r
4594 if ((ephemeral) && (context->premaster_key) && (context->premaster_key_len)) {
\r
4595 if (ephemeral == 1) {
\r
4596 unsigned char dh_Ys[0xFFF];
\r
4597 unsigned char dh_p[0xFFF];
\r
4598 unsigned char dh_g[0xFFF];
\r
4599 unsigned long dh_p_len = sizeof(dh_p);
\r
4600 unsigned long dh_g_len = sizeof(dh_g);
\r
4601 unsigned long dh_Ys_len = sizeof(dh_Ys);
\r
4603 if (__private_tls_dh_export_pqY(dh_p, &dh_p_len, dh_g, &dh_g_len, dh_Ys, &dh_Ys_len, context->dhe)) {
\r
4604 DEBUG_PRINT("ERROR EXPORTING DHE KEY %p\n", context->dhe);
\r
4606 __private_tls_dhe_free(context);
\r
4609 __private_tls_dhe_free(context);
\r
4610 DEBUG_DUMP_HEX_LABEL("Yc", dh_Ys, dh_Ys_len);
\r
4611 tls_packet_uint24(packet, dh_Ys_len + 2);
\r
4612 if (context->dtls)
\r
4613 __private_dtls_handshake_data(context, packet, dh_Ys_len + 2);
\r
4614 tls_packet_uint16(packet, dh_Ys_len);
\r
4615 tls_packet_append(packet, dh_Ys, dh_Ys_len);
\r
4617 if (context->ecc_dhe) {
\r
4618 unsigned char out[__TLS_MAX_RSA_KEY];
\r
4619 unsigned long out_len = __TLS_MAX_RSA_KEY;
\r
4621 if (ecc_ansi_x963_export(context->ecc_dhe, out, &out_len)) {
\r
4622 DEBUG_PRINT("Error exporting ECC key\n");
\r
4626 __private_tls_ecc_dhe_free(context);
\r
4627 tls_packet_uint24(packet, out_len + 1);
\r
4628 if (context->dtls) {
\r
4629 __private_dtls_handshake_data(context, packet, out_len + 1);
\r
4630 context->dtls_seq++;
\r
4632 tls_packet_uint8(packet, out_len);
\r
4633 tls_packet_append(packet, out, out_len);
\r
4635 __private_tls_compute_key(context, 48);
\r
4638 __private_tls_build_random(packet);
\r
4639 context->connection_status = 2;
\r
4640 tls_packet_update(packet);
\r
4644 void __private_dtls_handshake_data(struct TLSContext *context, struct TLSPacket *packet, unsigned int framelength) {
\r
4646 tls_packet_uint16(packet, context->dtls_seq);
\r
4647 // fragment offset
\r
4648 tls_packet_uint24(packet, 0);
\r
4649 // fragment length
\r
4650 tls_packet_uint24(packet, framelength);
\r
4653 void __private_dtls_handshake_copyframesize(struct TLSContext *context, struct TLSPacket *packet) {
\r
4654 packet->buf[22] = packet->buf[14];
\r
4655 packet->buf[23] = packet->buf[15];
\r
4656 packet->buf[24] = packet->buf[16];
\r
4659 struct TLSPacket *tls_build_server_key_exchange(struct TLSContext *context, int method) {
\r
4660 if (!context->is_server) {
\r
4661 DEBUG_PRINT("CANNOT BUILD SERVER KEY EXCHANGE MESSAGE FOR CLIENTS\n");
\r
4665 struct TLSPacket *packet = tls_create_packet(context, TLS_HANDSHAKE, context->version, 0);
\r
4666 tls_packet_uint8(packet, 0x0C);
\r
4667 unsigned char dummy[3];
\r
4668 tls_packet_append(packet, dummy, 3);
\r
4669 if (context->dtls)
\r
4670 __private_dtls_handshake_data(context, packet, 0);
\r
4671 int start_len = packet->len;
\r
4672 #ifdef TLS_FORWARD_SECRECY
\r
4673 if (method == KEA_dhe_rsa) {
\r
4675 __private_tls_dhe_create(context);
\r
4677 const char *default_dhe_p = context->default_dhe_p;
\r
4678 const char *default_dhe_g = context->default_dhe_g;
\r
4680 if ((!default_dhe_p) || (!default_dhe_g)) {
\r
4681 default_dhe_p = TLS_DH_DEFAULT_P;
\r
4682 default_dhe_g = TLS_DH_DEFAULT_G;
\r
4683 key_size = __TLS_DHE_KEY_SIZE / 8;
\r
4685 if (default_dhe_p)
\r
4686 key_size = strlen(default_dhe_p);
\r
4688 key_size = strlen(default_dhe_g);
\r
4690 if (__private_tls_dh_make_key(key_size, context->dhe, default_dhe_p, default_dhe_g, 0, 0)) {
\r
4691 DEBUG_PRINT("ERROR CREATING DHE KEY\n");
\r
4693 TLS_FREE(context->dhe);
\r
4694 context->dhe = NULL;
\r
4698 unsigned char dh_Ys[0xFFF];
\r
4699 unsigned char dh_p[0xFFF];
\r
4700 unsigned char dh_g[0xFFF];
\r
4701 unsigned long dh_p_len = sizeof(dh_p);
\r
4702 unsigned long dh_g_len = sizeof(dh_g);
\r
4703 unsigned long dh_Ys_len = sizeof(dh_Ys);
\r
4705 if (__private_tls_dh_export_pqY(dh_p, &dh_p_len, dh_g, &dh_g_len, dh_Ys, &dh_Ys_len, context->dhe)) {
\r
4706 DEBUG_PRINT("ERROR EXPORTING DHE KEY\n");
\r
4711 DEBUG_PRINT("LEN: %lu (%lu, %lu)\n", dh_Ys_len, dh_p_len, dh_g_len);
\r
4712 DEBUG_DUMP_HEX_LABEL("DHE PK", dh_Ys, dh_Ys_len);
\r
4713 DEBUG_DUMP_HEX_LABEL("DHE P", dh_p, dh_p_len);
\r
4714 DEBUG_DUMP_HEX_LABEL("DHE G", dh_g, dh_g_len);
\r
4716 tls_packet_uint16(packet, dh_p_len);
\r
4717 tls_packet_append(packet, dh_p, dh_p_len);
\r
4719 tls_packet_uint16(packet, dh_g_len);
\r
4720 tls_packet_append(packet, dh_g, dh_g_len);
\r
4722 tls_packet_uint16(packet, dh_Ys_len);
\r
4723 tls_packet_append(packet, dh_Ys, dh_Ys_len);
\r
4728 if (method == KEA_ec_diffie_hellman) {
\r
4729 // 3 = named curve
\r
4730 if (!context->curve)
\r
4731 context->curve = default_curve;
\r
4732 tls_packet_uint8(packet, 3);
\r
4733 tls_packet_uint16(packet, context->curve->iana);
\r
4735 __private_tls_ecc_dhe_create(context);
\r
4737 ltc_ecc_set_type *dp = (ltc_ecc_set_type *)&context->curve->dp;
\r
4739 if (ecc_make_key_ex(NULL, find_prng("sprng"), context->ecc_dhe, dp)) {
\r
4740 TLS_FREE(context->ecc_dhe);
\r
4741 context->ecc_dhe = NULL;
\r
4742 DEBUG_PRINT("Error generatic ECC key\n");
\r
4746 unsigned char out[__TLS_MAX_RSA_KEY];
\r
4747 unsigned long out_len = __TLS_MAX_RSA_KEY;
\r
4748 if (ecc_ansi_x963_export(context->ecc_dhe, out, &out_len)) {
\r
4749 DEBUG_PRINT("Error exporting ECC key\n");
\r
4753 tls_packet_uint8(packet, out_len);
\r
4754 tls_packet_append(packet, out, out_len);
\r
4759 DEBUG_PRINT("Unsupported ephemeral method: %i\n", method);
\r
4764 unsigned int params_len = packet->len - start_len;
\r
4765 unsigned int message_len = params_len + __TLS_CLIENT_RANDOM_SIZE + __TLS_SERVER_RANDOM_SIZE;
\r
4766 unsigned char *message = (unsigned char *)TLS_MALLOC(message_len);
\r
4768 unsigned char out[__TLS_MAX_RSA_KEY];
\r
4769 unsigned long out_len = __TLS_MAX_RSA_KEY;
\r
4771 int hash_algorithm;
\r
4772 if ((context->version != TLS_V12) && (context->version != DTLS_V12)) {
\r
4773 hash_algorithm = __md5_sha1;
\r
4775 if ((context->version == TLS_V12) || (context->version == DTLS_V12))
\r
4776 hash_algorithm = sha256;
\r
4778 hash_algorithm = sha1;
\r
4780 #ifdef TLS_ECDSA_SUPPORTED
\r
4781 if (tls_is_ecdsa(context)) {
\r
4782 if ((context->version == TLS_V12) || (context->version == DTLS_V12))
\r
4783 hash_algorithm = sha512;
\r
4784 tls_packet_uint8(packet, hash_algorithm);
\r
4785 tls_packet_uint8(packet, ecdsa);
\r
4789 tls_packet_uint8(packet, hash_algorithm);
\r
4790 tls_packet_uint8(packet, rsa_sign);
\r
4794 memcpy(message, context->remote_random, __TLS_CLIENT_RANDOM_SIZE);
\r
4795 memcpy(message + __TLS_CLIENT_RANDOM_SIZE, context->local_random, __TLS_SERVER_RANDOM_SIZE);
\r
4796 memcpy(message + __TLS_CLIENT_RANDOM_SIZE + __TLS_SERVER_RANDOM_SIZE, packet->buf + start_len, params_len);
\r
4797 #ifdef TLS_ECDSA_SUPPORTED
\r
4798 if (tls_is_ecdsa(context)) {
\r
4799 if (__private_tls_sign_ecdsa(context, hash_algorithm, message, message_len, out, &out_len) == 1) {
\r
4800 DEBUG_PRINT("Signing OK! (ECDSA, length %lu)\n", out_len);
\r
4801 tls_packet_uint16(packet, out_len);
\r
4802 tls_packet_append(packet, out, out_len);
\r
4806 if (__private_tls_sign_rsa(context, hash_algorithm, message, message_len, out, &out_len) == 1) {
\r
4807 DEBUG_PRINT("Signing OK! (length %lu)\n", out_len);
\r
4808 tls_packet_uint16(packet, out_len);
\r
4809 tls_packet_append(packet, out, out_len);
\r
4811 TLS_FREE(message);
\r
4813 if ((!packet->broken) && (packet->buf)) {
\r
4814 int remaining = packet->len - start_len;
\r
4815 int payload_pos = 6;
\r
4816 if (context->dtls)
\r
4818 packet->buf[payload_pos] = remaining / 0x10000;
\r
4819 remaining %= 0x10000;
\r
4820 packet->buf[payload_pos + 1] = remaining / 0x100;
\r
4821 remaining %= 0x100;
\r
4822 packet->buf[payload_pos + 2] = remaining;
\r
4823 if (context->dtls) {
\r
4824 __private_dtls_handshake_copyframesize(context, packet);
\r
4825 context->dtls_seq++;
\r
4828 tls_packet_update(packet);
\r
4832 void __private_tls_set_session_id(struct TLSContext *context) {
\r
4833 if (tls_random(context->session, __TLS_MAX_SESSION_ID))
\r
4834 context->session_size = __TLS_MAX_SESSION_ID;
\r
4836 context->session_size = 0;
\r
4839 struct TLSPacket *tls_build_hello(struct TLSContext *context) {
\r
4840 if (!tls_random(context->local_random, __TLS_SERVER_RANDOM_SIZE))
\r
4843 unsigned short packet_version = context->version;
\r
4844 unsigned short version = context->version;
\r
4845 struct TLSPacket *packet = tls_create_packet(context, TLS_HANDSHAKE, packet_version, 0);
\r
4848 if (context->is_server)
\r
4849 tls_packet_uint8(packet, 0x02);
\r
4851 tls_packet_uint8(packet, 0x01);
\r
4852 unsigned char dummy[3];
\r
4853 tls_packet_append(packet, dummy, 3);
\r
4855 if (context->dtls)
\r
4856 __private_dtls_handshake_data(context, packet, 0);
\r
4858 int start_len = packet->len;
\r
4859 tls_packet_uint16(packet, version);
\r
4860 if (context->is_server)
\r
4861 tls_packet_append(packet, context->local_random, __TLS_SERVER_RANDOM_SIZE);
\r
4863 tls_packet_append(packet, context->local_random, __TLS_CLIENT_RANDOM_SIZE);
\r
4865 #ifdef IGNORE_SESSION_ID
\r
4867 tls_packet_uint8(packet, 0);
\r
4869 __private_tls_set_session_id(context);
\r
4871 tls_packet_uint8(packet, context->session_size);
\r
4872 if (context->session_size)
\r
4873 tls_packet_append(packet, context->session, context->session_size);
\r
4876 int extension_len = 0;
\r
4878 int alpn_negotiated_len = 0;
\r
4880 if ((context->is_server) && (context->negotiated_alpn)) {
\r
4881 alpn_negotiated_len = strlen(context->negotiated_alpn);
\r
4882 alpn_len = alpn_negotiated_len + 1;
\r
4883 extension_len += alpn_len + 6;
\r
4885 if ((!context->is_server) && (context->alpn_count)) {
\r
4886 for (i = 0; i < context->alpn_count;i++) {
\r
4887 if (context->alpn[i]) {
\r
4888 int len = strlen(context->alpn[i]);
\r
4890 alpn_len += len + 1;
\r
4894 extension_len += alpn_len + 6;
\r
4898 if (context->is_server) {
\r
4899 // fallback ... this should never happen
\r
4900 if (!context->cipher)
\r
4901 context->cipher = TLS_DHE_RSA_WITH_AES_128_CBC_SHA;
\r
4903 tls_packet_uint16(packet, context->cipher);
\r
4905 tls_packet_uint8(packet, 0);
\r
4906 #ifndef STRICT_TLS
\r
4907 if ((context->version == TLS_V12) || (context->version == DTLS_V12)) {
\r
4908 // extensions size
\r
4909 tls_packet_uint16(packet, 5 + extension_len);
\r
4910 // secure renegotation
\r
4911 // advertise it, but refuse renegotiation
\r
4912 tls_packet_uint16(packet, 0xff01);
\r
4913 #ifdef TLS_ACCEPT_SECURE_RENEGOTIATION
\r
4914 // a little defensive
\r
4915 if ((context->verify_len) && (!context->verify_data))
\r
4916 context->verify_len = 0;
\r
4917 tls_packet_uint16(packet, context->verify_len + 1);
\r
4918 tls_packet_uint8(packet, context->verify_len);
\r
4919 if (context->verify_len)
\r
4920 tls_packet_append(packet, (unsigned char *)context->verify_data, context->verify_len);
\r
4922 tls_packet_uint16(packet, 1);
\r
4923 tls_packet_uint8(packet, 0);
\r
4926 tls_packet_uint16(packet, 0x10);
\r
4927 tls_packet_uint16(packet, alpn_len + 2);
\r
4928 tls_packet_uint16(packet, alpn_len);
\r
4930 tls_packet_uint8(packet, alpn_negotiated_len);
\r
4931 tls_packet_append(packet, (unsigned char *)context->negotiated_alpn, alpn_negotiated_len);
\r
4936 if (context->dtls) {
\r
4937 tls_packet_uint8(packet, context->dtls_cookie_len);
\r
4938 if (context->dtls_cookie_len)
\r
4939 tls_packet_append(packet, context->dtls_cookie, context->dtls_cookie_len);
\r
4942 #ifndef STRICT_TLS
\r
4943 if ((context->version == TLS_V12) || (context->version == DTLS_V12)) {
\r
4945 #ifdef TLS_FORWARD_SECRECY
\r
4946 #ifdef TLS_CLIENT_ECDHE
\r
4947 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
4948 #ifdef TLS_CLIENT_ECDSA
\r
4949 tls_packet_uint16(packet, TLS_CIPHERS_SIZE(16, 5));
\r
4950 #ifdef TLS_PREFER_CHACHA20
\r
4951 tls_packet_uint16(packet, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256);
\r
4953 tls_packet_uint16(packet, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256);
\r
4954 #ifndef TLS_PREFER_CHACHA20
\r
4955 tls_packet_uint16(packet, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256);
\r
4957 tls_packet_uint16(packet, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256);
\r
4958 tls_packet_uint16(packet, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA);
\r
4959 tls_packet_uint16(packet, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA);
\r
4961 // sizeof ciphers (16 ciphers * 2 bytes)
\r
4962 tls_packet_uint16(packet, TLS_CIPHERS_SIZE(11, 5));
\r
4965 #ifdef TLS_CLIENT_ECDSA
\r
4966 tls_packet_uint16(packet, TLS_CIPHERS_SIZE(13, 5));
\r
4967 tls_packet_uint16(packet, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256);
\r
4968 tls_packet_uint16(packet, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256);
\r
4969 tls_packet_uint16(packet, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA);
\r
4970 tls_packet_uint16(packet, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA);
\r
4972 // sizeof ciphers (14 ciphers * 2 bytes)
\r
4973 tls_packet_uint16(packet, TLS_CIPHERS_SIZE(9, 5));
\r
4976 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
4977 #ifdef TLS_PREFER_CHACHA20
\r
4978 tls_packet_uint16(packet, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256);
\r
4981 tls_packet_uint16(packet, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256);
\r
4982 tls_packet_uint16(packet, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA);
\r
4983 tls_packet_uint16(packet, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA);
\r
4984 tls_packet_uint16(packet, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256);
\r
4985 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
4986 #ifndef TLS_PREFER_CHACHA20
\r
4987 tls_packet_uint16(packet, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256);
\r
4991 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
4992 // sizeof ciphers (11 ciphers * 2 bytes)
\r
4993 tls_packet_uint16(packet, TLS_CIPHERS_SIZE(6, 5));
\r
4995 // sizeof ciphers (10 ciphers * 2 bytes)
\r
4996 tls_packet_uint16(packet, TLS_CIPHERS_SIZE(5, 5));
\r
4999 // not yet supported, because the first message sent (this one)
\r
5000 // is already hashed by the client with sha256 (sha384 not yet supported client-side)
\r
5001 // but is fully suported server-side
\r
5002 // tls_packet_uint16(packet, TLS_DHE_RSA_WITH_AES_256_GCM_SHA384);
\r
5003 tls_packet_uint16(packet, TLS_DHE_RSA_WITH_AES_128_GCM_SHA256);
\r
5004 tls_packet_uint16(packet, TLS_DHE_RSA_WITH_AES_256_CBC_SHA256);
\r
5005 tls_packet_uint16(packet, TLS_DHE_RSA_WITH_AES_128_CBC_SHA256);
\r
5006 tls_packet_uint16(packet, TLS_DHE_RSA_WITH_AES_256_CBC_SHA);
\r
5007 tls_packet_uint16(packet, TLS_DHE_RSA_WITH_AES_128_CBC_SHA);
\r
5008 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
5009 tls_packet_uint16(packet, TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256);
\r
5012 tls_packet_uint16(packet, TLS_CIPHERS_SIZE(0, 5));
\r
5014 // tls_packet_uint16(packet, TLS_RSA_WITH_AES_256_GCM_SHA384);
\r
5015 #ifndef TLS_ROBOT_MITIGATION
\r
5016 tls_packet_uint16(packet, TLS_RSA_WITH_AES_128_GCM_SHA256);
\r
5017 tls_packet_uint16(packet, TLS_RSA_WITH_AES_256_CBC_SHA256);
\r
5018 tls_packet_uint16(packet, TLS_RSA_WITH_AES_128_CBC_SHA256);
\r
5019 tls_packet_uint16(packet, TLS_RSA_WITH_AES_256_CBC_SHA);
\r
5020 tls_packet_uint16(packet, TLS_RSA_WITH_AES_128_CBC_SHA);
\r
5022 #ifndef STRICT_TLS
\r
5024 #ifdef TLS_FORWARD_SECRECY
\r
5025 #ifdef TLS_CLIENT_ECDHE
\r
5026 tls_packet_uint16(packet, TLS_CIPHERS_SIZE(5, 2));
\r
5027 tls_packet_uint16(packet, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA);
\r
5028 tls_packet_uint16(packet, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA);
\r
5030 tls_packet_uint16(packet, TLS_CIPHERS_SIZE(3, 2));
\r
5032 tls_packet_uint16(packet, TLS_DHE_RSA_WITH_AES_256_CBC_SHA);
\r
5033 tls_packet_uint16(packet, TLS_DHE_RSA_WITH_AES_256_CBC_SHA);
\r
5034 tls_packet_uint16(packet, TLS_DHE_RSA_WITH_AES_128_CBC_SHA);
\r
5036 tls_packet_uint16(packet, TLS_CIPHERS_SIZE(0, 2));
\r
5038 #ifndef TLS_ROBOT_MITIGATION
\r
5039 tls_packet_uint16(packet, TLS_RSA_WITH_AES_256_CBC_SHA);
\r
5040 tls_packet_uint16(packet, TLS_RSA_WITH_AES_128_CBC_SHA);
\r
5045 tls_packet_uint8(packet, 1);
\r
5047 tls_packet_uint8(packet, 0);
\r
5048 if ((context->version == TLS_V12) || (context->version == DTLS_V12)) {
\r
5051 sni_len = strlen(context->sni);
\r
5053 #ifdef TLS_CLIENT_ECDHE
\r
5054 extension_len += 12;
\r
5057 extension_len += sni_len + 9;
\r
5059 tls_packet_uint16(packet, extension_len);
\r
5063 tls_packet_uint16(packet, 0x00);
\r
5064 // sni extension len
\r
5065 tls_packet_uint16(packet, sni_len + 5);
\r
5067 tls_packet_uint16(packet, sni_len + 3);
\r
5069 tls_packet_uint8(packet, 0);
\r
5071 tls_packet_uint16(packet, sni_len);
\r
5072 tls_packet_append(packet, (unsigned char *)context->sni, sni_len);
\r
5074 #ifdef TLS_FORWARD_SECRECY
\r
5075 #ifdef TLS_CLIENT_ECDHE
\r
5076 // supported groups
\r
5077 tls_packet_uint16(packet, 0x0A);
\r
5078 tls_packet_uint16(packet, 8);
\r
5079 // 3 curves x 2 bytes
\r
5080 tls_packet_uint16(packet, 6);
\r
5081 tls_packet_uint16(packet, secp256r1.iana);
\r
5082 tls_packet_uint16(packet, secp384r1.iana);
\r
5083 tls_packet_uint16(packet, secp224r1.iana);
\r
5087 tls_packet_uint16(packet, 0x10);
\r
5088 tls_packet_uint16(packet, alpn_len + 2);
\r
5089 tls_packet_uint16(packet, alpn_len);
\r
5091 for (i = 0; i < context->alpn_count;i++) {
\r
5092 if (context->alpn[i]) {
\r
5093 int len = strlen(context->alpn[i]);
\r
5095 tls_packet_uint8(packet, len);
\r
5096 tls_packet_append(packet, (unsigned char *)context->alpn[i], len);
\r
5104 if ((!packet->broken) && (packet->buf)) {
\r
5105 int remaining = packet->len - start_len;
\r
5106 int payload_pos = 6;
\r
5107 if (context->dtls)
\r
5109 packet->buf[payload_pos] = remaining / 0x10000;
\r
5110 remaining %= 0x10000;
\r
5111 packet->buf[payload_pos + 1] = remaining / 0x100;
\r
5112 remaining %= 0x100;
\r
5113 packet->buf[payload_pos + 2] = remaining;
\r
5114 if (context->dtls) {
\r
5115 __private_dtls_handshake_copyframesize(context, packet);
\r
5116 context->dtls_seq++;
\r
5119 tls_packet_update(packet);
\r
5124 struct TLSPacket *tls_certificate_request(struct TLSContext *context) {
\r
5125 if ((!context) || (!context->is_server))
\r
5128 unsigned short packet_version = context->version;
\r
5129 struct TLSPacket *packet = tls_create_packet(context, TLS_HANDSHAKE, packet_version, 0);
\r
5131 // certificate request
\r
5132 tls_packet_uint8(packet, 0x0D);
\r
5133 unsigned char dummy[3];
\r
5134 tls_packet_append(packet, dummy, 3);
\r
5135 if (context->dtls)
\r
5136 __private_dtls_handshake_data(context, packet, 0);
\r
5137 int start_len = packet->len;
\r
5138 tls_packet_uint8(packet, 1);
\r
5139 tls_packet_uint8(packet, rsa_sign);
\r
5140 if ((context->version == TLS_V12) || (context->version == DTLS_V12)) {
\r
5141 // 10 pairs or 2 bytes
\r
5142 tls_packet_uint16(packet, 10);
\r
5143 tls_packet_uint8(packet, sha256);
\r
5144 tls_packet_uint8(packet, rsa);
\r
5145 tls_packet_uint8(packet, sha1);
\r
5146 tls_packet_uint8(packet, rsa);
\r
5147 tls_packet_uint8(packet, sha384);
\r
5148 tls_packet_uint8(packet, rsa);
\r
5149 tls_packet_uint8(packet, sha512);
\r
5150 tls_packet_uint8(packet, rsa);
\r
5151 tls_packet_uint8(packet, md5);
\r
5152 tls_packet_uint8(packet, rsa);
\r
5154 // no DistinguishedName yet
\r
5155 tls_packet_uint16(packet, 0);
\r
5156 if ((!packet->broken) && (packet->buf)) {
\r
5157 int remaining = packet->len - start_len;
\r
5158 int payload_pos = 6;
\r
5159 if (context->dtls)
\r
5161 packet->buf[payload_pos] = remaining / 0x10000;
\r
5162 remaining %= 0x10000;
\r
5163 packet->buf[payload_pos + 1] = remaining / 0x100;
\r
5164 remaining %= 0x100;
\r
5165 packet->buf[payload_pos + 2] = remaining;
\r
5167 if (context->dtls) {
\r
5168 __private_dtls_handshake_copyframesize(context, packet);
\r
5169 context->dtls_seq++;
\r
5172 tls_packet_update(packet);
\r
5177 struct TLSPacket *tls_build_verify_request(struct TLSContext *context) {
\r
5178 if ((!context->is_server) || (!context->dtls))
\r
5181 if ((!context->dtls_cookie) || (!context->dtls_cookie_len)) {
\r
5182 context->dtls_cookie = (unsigned char *)TLS_MALLOC(__DTLS_COOKIE_SIZE);
\r
5183 if (!context->dtls_cookie)
\r
5186 if (!tls_random(context->dtls_cookie, __DTLS_COOKIE_SIZE)) {
\r
5187 TLS_FREE(context->dtls_cookie);
\r
5188 context->dtls_cookie = NULL;
\r
5191 context->dtls_cookie_len = __DTLS_COOKIE_SIZE;
\r
5194 unsigned short packet_version = context->version;
\r
5195 struct TLSPacket *packet = tls_create_packet(context, TLS_HANDSHAKE, packet_version, 0);
\r
5198 tls_packet_uint8(packet, 0x03);
\r
5200 tls_packet_uint24(packet, context->dtls_cookie_len + 3);
\r
5201 // 16-bit message_sequence
\r
5202 tls_packet_uint16(packet, 0);
\r
5203 // 24-bit fragment_offset
\r
5204 tls_packet_uint24(packet, 0);
\r
5205 // 24-bit fragment_offset
\r
5206 tls_packet_uint24(packet, context->dtls_cookie_len + 3);
\r
5208 tls_packet_uint16(packet, context->version);
\r
5209 tls_packet_uint8(packet, context->dtls_cookie_len);
\r
5210 tls_packet_append(packet, context->dtls_cookie, context->dtls_cookie_len);
\r
5211 tls_packet_update(packet);
\r
5216 int __private_dtls_check_packet(const unsigned char *buf, int buf_len) {
\r
5217 CHECK_SIZE(11, buf_len, TLS_NEED_MORE_DATA)
\r
5219 unsigned int bytes_to_follow = buf[0] * 0x10000 + buf[1] * 0x100 + buf[2];
\r
5220 // not used: unsigned short message_seq = ntohs(*(unsigned short *)&buf[3]);
\r
5221 unsigned int fragment_offset = buf[5] * 0x10000 + buf[6] * 0x100 + buf[7];
\r
5222 unsigned int fragment_length = buf[8] * 0x10000 + buf[9] * 0x100 + buf[10];
\r
5224 if ((fragment_offset) || (fragment_length != bytes_to_follow)) {
\r
5225 DEBUG_PRINT("FRAGMENTED PACKETS NOT SUPPORTED\n");
\r
5226 return TLS_FEATURE_NOT_SUPPORTED;
\r
5228 return bytes_to_follow;
\r
5231 void __private_dtls_reset(struct TLSContext *context) {
\r
5232 context->dtls_epoch_local = 0;
\r
5233 context->dtls_epoch_remote = 0;
\r
5234 context->dtls_seq = 0;
\r
5235 __private_tls_destroy_hash(context);
\r
5236 context->connection_status = 0;
\r
5239 int tls_parse_verify_request(struct TLSContext *context, const unsigned char *buf, int buf_len, unsigned int *write_packets) {
\r
5240 *write_packets = 0;
\r
5241 if ((context->connection_status != 0) || (!context->dtls)) {
\r
5242 DEBUG_PRINT("UNEXPECTED VERIFY REQUEST MESSAGE\n");
\r
5243 return TLS_UNEXPECTED_MESSAGE;
\r
5246 int bytes_to_follow = __private_dtls_check_packet(buf, buf_len);
\r
5247 if (bytes_to_follow < 0)
\r
5248 return bytes_to_follow;
\r
5250 CHECK_SIZE(bytes_to_follow, buf_len - res, TLS_NEED_MORE_DATA)
\r
5251 // not used: unsigned short version = ntohs(*(unsigned short *)&buf[res]);
\r
5253 unsigned char len = buf[res];
\r
5255 TLS_FREE(context->dtls_cookie);
\r
5256 context->dtls_cookie_len = 0;
\r
5258 CHECK_SIZE(len, buf_len - res, TLS_NEED_MORE_DATA)
\r
5259 context->dtls_cookie = (unsigned char *)TLS_MALLOC(len);
\r
5260 if (!context->dtls_cookie)
\r
5261 return TLS_NO_MEMORY;
\r
5262 context->dtls_cookie_len = len;
\r
5263 memcpy(context->dtls_cookie, &buf[res], len);
\r
5265 *write_packets = 4;
\r
5269 __private_dtls_reset(context);
\r
5273 void __private_dtls_reset_cookie(struct TLSContext *context) {
\r
5274 TLS_FREE(context->dtls_cookie);
\r
5275 context->dtls_cookie = NULL;
\r
5276 context->dtls_cookie_len = 0;
\r
5279 int tls_parse_hello(struct TLSContext *context, const unsigned char *buf, int buf_len, unsigned int *write_packets, unsigned int *dtls_verified) {
\r
5280 *write_packets = 0;
\r
5281 *dtls_verified = 0;
\r
5282 if (context->connection_status != 0) {
\r
5283 // ignore multiple hello on dtls
\r
5284 if (context->dtls) {
\r
5285 DEBUG_PRINT("RETRANSMITTED HELLO MESSAGE RECEIVED\n");
\r
5288 DEBUG_PRINT("UNEXPECTED HELLO MESSAGE\n");
\r
5289 return TLS_UNEXPECTED_MESSAGE;
\r
5293 int downgraded = 0;
\r
5294 int hello_min_size = context->dtls ? __TLS_CLIENT_HELLO_MINSIZE + 8 : __TLS_CLIENT_HELLO_MINSIZE;
\r
5295 CHECK_SIZE(hello_min_size, buf_len, TLS_NEED_MORE_DATA)
\r
5297 unsigned int bytes_to_follow = buf[0] * 0x10000 + buf[1] * 0x100 + buf[2];
\r
5299 if (context->dtls) {
\r
5300 int dtls_check = __private_dtls_check_packet(buf, buf_len);
\r
5301 if (dtls_check < 0)
\r
5302 return dtls_check;
\r
5303 // 16 bit message seq + 24 bit fragment offset + 24 bit fragment length
\r
5306 CHECK_SIZE(bytes_to_follow, buf_len - res, TLS_NEED_MORE_DATA)
\r
5308 CHECK_SIZE(2, buf_len - res, TLS_NEED_MORE_DATA)
\r
5309 unsigned short version = ntohs(*(unsigned short *)&buf[res]);
\r
5312 VERSION_SUPPORTED(version, TLS_NOT_SAFE)
\r
5313 DEBUG_PRINT("VERSION REQUIRED BY REMOTE %x, VERSION NOW %x\n", (int)version, (int)context->version);
\r
5314 #ifdef TLS_LEGACY_SUPPORT
\r
5315 // when no legacy support, don't downgrade
\r
5316 #ifndef TLS_FORCE_LOCAL_VERSION
\r
5318 if (context->dtls) {
\r
5319 // for dlts, newer version has lower id (1.0 = FEFF, 1.2 = FEFD)
\r
5320 if (context->version < version)
\r
5323 if (context->version > version)
\r
5327 context->version = version;
\r
5328 if (!context->is_server)
\r
5329 __private_tls_change_hash_type(context);
\r
5333 memcpy(context->remote_random, &buf[res], __TLS_CLIENT_RANDOM_SIZE);
\r
5334 res += __TLS_CLIENT_RANDOM_SIZE;
\r
5336 unsigned char session_len = buf[res++];
\r
5337 CHECK_SIZE(session_len, buf_len - res, TLS_NEED_MORE_DATA)
\r
5338 if ((session_len) && (session_len <= __TLS_MAX_SESSION_ID)) {
\r
5339 memcpy(context->session, &buf[res], session_len);
\r
5340 context->session_size = session_len;
\r
5342 context->session_size = 0;
\r
5344 res += session_len;
\r
5346 if (context->is_server) {
\r
5347 if (context->dtls) {
\r
5348 CHECK_SIZE(1, buf_len - res, TLS_NEED_MORE_DATA)
\r
5349 unsigned char tls_cookie_len = buf[res++];
\r
5350 if (tls_cookie_len) {
\r
5351 CHECK_SIZE(tls_cookie_len, buf_len - res, TLS_NEED_MORE_DATA)
\r
5352 if ((context->dtls_cookie_len != tls_cookie_len) || (!context->dtls_cookie)) {
\r
5353 *dtls_verified = 2;
\r
5354 __private_dtls_reset_cookie(context);
\r
5355 DEBUG_PRINT("INVALID DTLS COOKIE\n");
\r
5356 return TLS_BROKEN_PACKET;
\r
5358 if (memcmp(context->dtls_cookie, &buf[res], tls_cookie_len)) {
\r
5359 *dtls_verified = 3;
\r
5360 __private_dtls_reset_cookie(context);
\r
5361 DEBUG_PRINT("MISMATCH DTLS COOKIE\n");
\r
5362 return TLS_BROKEN_PACKET;
\r
5364 __private_dtls_reset_cookie(context);
\r
5365 context->dtls_seq++;
\r
5366 *dtls_verified = 1;
\r
5367 res += tls_cookie_len;
\r
5369 *write_packets = 2;
\r
5373 CHECK_SIZE(2, buf_len - res, TLS_NEED_MORE_DATA)
\r
5374 unsigned short cipher_len = ntohs(*(unsigned short *)&buf[res]);
\r
5376 CHECK_SIZE(cipher_len, buf_len - res, TLS_NEED_MORE_DATA)
\r
5377 // faster than cipher_len % 2
\r
5378 if (cipher_len & 1)
\r
5379 return TLS_BROKEN_PACKET;
\r
5382 int cipher = tls_choose_cipher(context, &buf[res], cipher_len, &scsv_set);
\r
5384 DEBUG_PRINT("NO COMMON CIPHERS\n");
\r
5387 if ((downgraded) && (scsv_set)) {
\r
5388 DEBUG_PRINT("NO DOWNGRADE (SCSV SET)\n");
\r
5389 __private_tls_write_packet(tls_build_alert(context, 1, inappropriate_fallback));
\r
5390 context->critical_error = 1;
\r
5391 return TLS_NOT_SAFE;
\r
5393 context->cipher = cipher;
\r
5394 res += cipher_len;
\r
5396 CHECK_SIZE(1, buf_len - res, TLS_NEED_MORE_DATA)
\r
5397 unsigned char compression_list_size = buf[res++];
\r
5398 CHECK_SIZE(compression_list_size, buf_len - res, TLS_NEED_MORE_DATA)
\r
5400 // no compression support
\r
5401 res += compression_list_size;
\r
5403 CHECK_SIZE(2, buf_len - res, TLS_NEED_MORE_DATA)
\r
5404 unsigned short cipher = ntohs(*(unsigned short *)&buf[res]);
\r
5406 context->cipher = cipher;
\r
5407 if (!tls_cipher_supported(context, cipher)) {
\r
5408 context->cipher = 0;
\r
5409 DEBUG_PRINT("NO CIPHER SUPPORTED\n");
\r
5410 return TLS_NO_COMMON_CIPHER;
\r
5412 DEBUG_PRINT("CIPHER: %s\n", tls_cipher_name(context));
\r
5413 CHECK_SIZE(1, buf_len - res, TLS_NEED_MORE_DATA)
\r
5414 unsigned char compression = buf[res++];
\r
5415 if (compression != 0) {
\r
5416 DEBUG_PRINT("COMPRESSION NOT SUPPORTED\n");
\r
5417 return TLS_COMPRESSION_NOT_SUPPORTED;
\r
5422 if (context->is_server)
\r
5423 *write_packets = 2;
\r
5424 context->connection_status = 1;
\r
5431 // ignore extensions for now
\r
5432 while (buf_len - res >= 4) {
\r
5433 // have extensions
\r
5434 unsigned short extension_type = ntohs(*(unsigned short *)&buf[res]);
\r
5436 unsigned short extension_len = ntohs(*(unsigned short *)&buf[res]);
\r
5438 DEBUG_PRINT("Extension: 0x0%x (%i), len: %i\n", (int)extension_type, (int)extension_type, (int)extension_len);
\r
5439 if (extension_len) {
\r
5441 CHECK_SIZE(extension_len, buf_len - res, TLS_NEED_MORE_DATA)
\r
5442 if (extension_type == 0x00) {
\r
5443 // unsigned short sni_len = ntohs(*(unsigned short *)&buf[res]);
\r
5444 // unsigned char sni_type = buf[res + 2];
\r
5445 unsigned short sni_host_len = ntohs(*(unsigned short *)&buf[res + 3]);
\r
5446 CHECK_SIZE(sni_host_len, buf_len - res - 5, TLS_NEED_MORE_DATA)
\r
5447 if (sni_host_len) {
\r
5448 TLS_FREE(context->sni);
\r
5449 context->sni = (char *)TLS_MALLOC(sni_host_len + 1);
\r
5450 if (context->sni) {
\r
5451 memcpy(context->sni, &buf[res + 5], sni_host_len);
\r
5452 context->sni[sni_host_len] = 0;
\r
5453 DEBUG_PRINT("SNI HOST INDICATOR: [%s]\n", context->sni);
\r
5457 #ifdef TLS_FORWARD_SECRECY
\r
5458 if (extension_type == 0x0A) {
\r
5459 // supported groups
\r
5460 if (buf_len - res > 2) {
\r
5461 unsigned short group_len = ntohs(*(unsigned short *)&buf[res]);
\r
5462 if (buf_len - res >= group_len + 2) {
\r
5463 DEBUG_DUMP_HEX_LABEL("SUPPORTED GROUPS", &buf[res + 2], group_len);
\r
5466 for (i = 0; i < group_len; i += 2) {
\r
5467 unsigned short iana_n = ntohs(*(unsigned short *)&buf[res + 2 + i]);
\r
5470 context->curve = &secp256r1;
\r
5474 context->curve = &secp384r1;
\r
5477 // do not use it anymore
\r
5479 // context->curve = &secp521r1;
\r
5484 DEBUG_PRINT("SELECTED CURVE %s\n", context->curve->name);
\r
5492 if ((extension_type == 0x10) && (context->alpn) && (context->alpn_count)) {
\r
5493 if (buf_len - res > 2) {
\r
5494 unsigned short alpn_len = ntohs(*(unsigned short *)&buf[res]);
\r
5495 if ((alpn_len) && (alpn_len <= extension_len - 2)) {
\r
5496 unsigned char *alpn = (unsigned char *)&buf[res + 2];
\r
5498 while (alpn_pos < alpn_len) {
\r
5499 unsigned char alpn_size = alpn[alpn_pos++];
\r
5500 if (alpn_size + alpn_pos >= extension_len)
\r
5502 if ((alpn_size) && (tls_alpn_contains(context, (char *)&alpn[alpn_pos], alpn_size))) {
\r
5503 TLS_FREE(context->negotiated_alpn);
\r
5504 context->negotiated_alpn = (char *)TLS_MALLOC(alpn_size + 1);
\r
5505 if (context->negotiated_alpn) {
\r
5506 memcpy(context->negotiated_alpn, &alpn[alpn_pos], alpn_size);
\r
5507 context->negotiated_alpn[alpn_size] = 0;
\r
5508 DEBUG_PRINT("NEGOTIATED ALPN: %s\n", context->negotiated_alpn);
\r
5512 alpn_pos += alpn_size;
\r
5513 // ServerHello contains just one alpn
\r
5514 if (!context->is_server)
\r
5520 if (extension_type == 0x0D) {
\r
5521 // supported signatures
\r
5522 DEBUG_DUMP_HEX_LABEL("SUPPORTED SIGNATURES", &buf[res], extension_len);
\r
5524 if (extension_type == 0x0B) {
\r
5525 // supported point formats
\r
5526 DEBUG_DUMP_HEX_LABEL("SUPPORTED POINT FORMATS", &buf[res], extension_len);
\r
5528 res += extension_len;
\r
5531 if (buf_len != res)
\r
5532 return TLS_NEED_MORE_DATA;
\r
5536 int tls_parse_certificate(struct TLSContext *context, const unsigned char *buf, int buf_len, int is_client) {
\r
5538 CHECK_SIZE(3, buf_len, TLS_NEED_MORE_DATA)
\r
5539 unsigned int size_of_all_certificates = buf[0] * 0x10000 + buf[1] * 0x100 + buf[2];
\r
5541 if (size_of_all_certificates <= 4)
\r
5542 return 3 + size_of_all_certificates;
\r
5545 if (context->dtls) {
\r
5546 int dtls_check = __private_dtls_check_packet(buf, buf_len);
\r
5547 if (dtls_check < 0)
\r
5548 return dtls_check;
\r
5552 CHECK_SIZE(size_of_all_certificates, buf_len - res, TLS_NEED_MORE_DATA);
\r
5553 int size = size_of_all_certificates;
\r
5556 int valid_certificate = 0;
\r
5557 while (size > 0) {
\r
5559 CHECK_SIZE(3, buf_len - res, TLS_NEED_MORE_DATA);
\r
5560 unsigned int certificate_size = buf[res] * 0x10000 + buf[res + 1] * 0x100 + buf[res + 2];
\r
5562 CHECK_SIZE(certificate_size, buf_len - res, TLS_NEED_MORE_DATA)
\r
5564 int certificates_in_chain = 0;
\r
5566 unsigned int remaining = certificate_size;
\r
5568 if (remaining <= 3)
\r
5570 certificates_in_chain++;
\r
5571 unsigned int certificate_size2 = buf[res2] * 0x10000 + buf[res2 + 1] * 0x100 + buf[res2 + 2];
\r
5574 if (certificate_size2 > remaining) {
\r
5575 DEBUG_PRINT("Invalid certificate size (%i from %i bytes remaining)\n", certificate_size2, remaining);
\r
5578 remaining -= certificate_size2;
\r
5580 struct TLSCertificate *cert = asn1_parse(context, &buf[res2], certificate_size2, is_client);
\r
5582 if (certificate_size2) {
\r
5583 cert->bytes = (unsigned char *)TLS_MALLOC(certificate_size2);
\r
5584 if (cert->bytes) {
\r
5585 cert->len = certificate_size2;
\r
5586 memcpy(cert->bytes, &buf[res2], certificate_size2);
\r
5589 // valid certificate
\r
5591 valid_certificate = 1;
\r
5592 context->client_certificates = (struct TLSCertificate **)TLS_REALLOC(context->client_certificates, (context->client_certificates_count + 1) * sizeof(struct TLSCertificate));
\r
5593 context->client_certificates[context->client_certificates_count] = cert;
\r
5594 context->client_certificates_count++;
\r
5596 context->certificates = (struct TLSCertificate **)TLS_REALLOC(context->certificates, (context->certificates_count + 1) * sizeof(struct TLSCertificate));
\r
5597 context->certificates[context->certificates_count] = cert;
\r
5598 context->certificates_count++;
\r
5599 if ((cert->pk) || (cert->priv))
\r
5600 valid_certificate = 1;
\r
5602 if (!context->is_server)
\r
5603 valid_certificate = 1;
\r
5606 res2 += certificate_size2;
\r
5607 } while (remaining > 0);
\r
5609 DEBUG_PRINT("Extra %i bytes after certificate\n", remaining);
\r
5610 size -= certificate_size + 3;
\r
5611 res += certificate_size;
\r
5613 if (!valid_certificate)
\r
5614 return TLS_UNSUPPORTED_CERTIFICATE;
\r
5615 if (res != buf_len) {
\r
5616 DEBUG_PRINT("Warning: %i bytes read from %i byte buffer\n", (int)res, (int)buf_len);
\r
5621 int __private_tls_parse_dh(struct TLSContext *context, const unsigned char *buf, int buf_len, const unsigned char **out, int *out_size) {
\r
5625 CHECK_SIZE(2, buf_len, TLS_NEED_MORE_DATA)
\r
5626 unsigned short size = ntohs(*(unsigned short *)buf);
\r
5628 CHECK_SIZE(size, buf_len - res, TLS_NEED_MORE_DATA)
\r
5629 DEBUG_DUMP_HEX(&buf[res], size);
\r
5636 int __private_tls_parse_random(struct TLSContext *context, const unsigned char *buf, int buf_len) {
\r
5638 int ephemeral = tls_cipher_is_ephemeral(context);
\r
5639 unsigned short size;
\r
5640 if (ephemeral == 2) {
\r
5641 CHECK_SIZE(1, buf_len, TLS_NEED_MORE_DATA)
\r
5645 CHECK_SIZE(2, buf_len, TLS_NEED_MORE_DATA)
\r
5646 size = ntohs(*(unsigned short *)buf);
\r
5650 CHECK_SIZE(size, buf_len - res, TLS_NEED_MORE_DATA)
\r
5651 unsigned int out_len = 0;
\r
5652 unsigned char *random = NULL;
\r
5653 switch (ephemeral) {
\r
5654 #ifdef TLS_FORWARD_SECRECY
\r
5656 random = __private_tls_decrypt_dhe(context, &buf[res], size, &out_len, 1);
\r
5659 random = __private_tls_decrypt_ecc_dhe(context, &buf[res], size, &out_len, 1);
\r
5663 random = __private_tls_decrypt_rsa(context, &buf[res], size, &out_len);
\r
5666 if ((random) && (out_len > 2)) {
\r
5667 // *(unsigned short *)&random[0] = htons(context->version);
\r
5668 DEBUG_DUMP_HEX_LABEL("PRE MASTER KEY", random, out_len);
\r
5669 TLS_FREE(context->premaster_key);
\r
5670 context->premaster_key = random;
\r
5671 context->premaster_key_len = out_len;
\r
5672 __private_tls_compute_key(context, 48);
\r
5681 int __private_tls_build_random(struct TLSPacket *packet) {
\r
5683 unsigned char rand_bytes[48];
\r
5685 if (!tls_random(rand_bytes, bytes))
\r
5686 return TLS_GENERIC_ERROR;
\r
5688 // max supported version
\r
5689 if (packet->context->is_server)
\r
5690 *(unsigned short *)&rand_bytes[0] = htons(packet->context->version);
\r
5692 if (packet->context->dtls)
\r
5693 *(unsigned short *)&rand_bytes[0] = htons(DTLS_V12);
\r
5695 *(unsigned short *)&rand_bytes[0] = htons(TLS_V12);
\r
5696 //DEBUG_DUMP_HEX_LABEL("PREMASTER KEY", rand_bytes, bytes);
\r
5698 TLS_FREE(packet->context->premaster_key);
\r
5699 packet->context->premaster_key = (unsigned char *)TLS_MALLOC(bytes);
\r
5700 if (!packet->context->premaster_key)
\r
5701 return TLS_NO_MEMORY;
\r
5703 packet->context->premaster_key_len = bytes;
\r
5704 memcpy(packet->context->premaster_key, rand_bytes, packet->context->premaster_key_len);
\r
5706 unsigned int out_len;
\r
5707 unsigned char *random = __private_tls_encrypt_rsa(packet->context, packet->context->premaster_key, packet->context->premaster_key_len, &out_len);
\r
5709 __private_tls_compute_key(packet->context, bytes);
\r
5710 if ((random) && (out_len > 2)) {
\r
5711 tls_packet_uint24(packet, out_len + 2);
\r
5712 if (packet->context->dtls)
\r
5713 __private_dtls_handshake_data(packet->context, packet, out_len + 2);
\r
5714 tls_packet_uint16(packet, out_len);
\r
5715 tls_packet_append(packet, random, out_len);
\r
5717 res = TLS_GENERIC_ERROR;
\r
5722 return out_len + 2;
\r
5725 const unsigned char *__private_tls_parse_signature(struct TLSContext *context, const unsigned char *buf, int buf_len, int *hash_algorithm, int *sign_algorithm, int *sig_size, int *offset) {
\r
5727 CHECK_SIZE(2, buf_len, NULL)
\r
5728 *hash_algorithm = __md5_sha1;
\r
5729 *sign_algorithm = rsa_sign;
\r
5731 if ((context->version == TLS_V12) || (context->version == DTLS_V12)) {
\r
5732 *hash_algorithm = buf[res];
\r
5734 *sign_algorithm = buf[res];
\r
5737 unsigned short size = ntohs(*(unsigned short *)&buf[res]);
\r
5739 CHECK_SIZE(size, buf_len - res, NULL)
\r
5740 DEBUG_DUMP_HEX(&buf[res], size);
\r
5742 *offset = res + size;
\r
5746 int tls_parse_server_key_exchange(struct TLSContext *context, const unsigned char *buf, int buf_len) {
\r
5749 CHECK_SIZE(3, buf_len, TLS_NEED_MORE_DATA)
\r
5750 unsigned int size = buf[0] * 0x10000 + buf[1] * 0x100 + buf[2];
\r
5752 if (context->dtls) {
\r
5753 int dtls_check = __private_dtls_check_packet(buf, buf_len);
\r
5754 if (dtls_check < 0)
\r
5755 return dtls_check;
\r
5758 const unsigned char *packet_ref = buf + res;
\r
5759 CHECK_SIZE(size, buf_len - res, TLS_NEED_MORE_DATA);
\r
5764 unsigned char has_ds_params = 0;
\r
5765 unsigned int key_size = 0;
\r
5766 #ifdef TLS_FORWARD_SECRECY
\r
5767 const struct ECCCurveParameters *curve = NULL;
\r
5768 const unsigned char *pk_key = NULL;
\r
5769 int ephemeral = tls_cipher_is_ephemeral(context);
\r
5771 if (ephemeral == 1) {
\r
5772 has_ds_params = 1;
\r
5774 if (buf[res++] != 3) {
\r
5776 // any other method is not supported
\r
5779 CHECK_SIZE(3, buf_len - res, TLS_NEED_MORE_DATA);
\r
5780 int iana_n = ntohs(*(unsigned short *)&buf[res]);
\r
5782 key_size = buf[res];
\r
5784 CHECK_SIZE(key_size, buf_len - res, TLS_NEED_MORE_DATA);
\r
5785 DEBUG_PRINT("IANA CURVE NUMBER: %i\n", iana_n);
\r
5788 curve = &secp192r1;
\r
5791 curve = &secp224k1;
\r
5794 curve = &secp224r1;
\r
5797 curve = &secp256k1;
\r
5800 curve = &secp256r1;
\r
5803 curve = &secp384r1;
\r
5806 curve = &secp521r1;
\r
5809 DEBUG_PRINT("UNSUPPORTED CURVE\n");
\r
5810 return TLS_GENERIC_ERROR;
\r
5812 pk_key = &buf[res];
\r
5814 context->curve = curve;
\r
5818 const unsigned char *dh_p = NULL;
\r
5820 const unsigned char *dh_g = NULL;
\r
5822 const unsigned char *dh_Ys = NULL;
\r
5823 int dh_Ys_len = 0;
\r
5824 if (has_ds_params) {
\r
5825 DEBUG_PRINT(" dh_p: ");
\r
5826 dh_res = __private_tls_parse_dh(context, &buf[res], buf_len - res, &dh_p, &dh_p_len);
\r
5828 return TLS_BROKEN_PACKET;
\r
5830 DEBUG_PRINT("\n");
\r
5832 DEBUG_PRINT(" dh_q: ");
\r
5833 dh_res = __private_tls_parse_dh(context, &buf[res], buf_len - res, &dh_g, &dh_g_len);
\r
5835 return TLS_BROKEN_PACKET;
\r
5837 DEBUG_PRINT("\n");
\r
5839 DEBUG_PRINT(" dh_Ys: ");
\r
5840 dh_res = __private_tls_parse_dh(context, &buf[res], buf_len - res, &dh_Ys, &dh_Ys_len);
\r
5842 return TLS_BROKEN_PACKET;
\r
5844 DEBUG_PRINT("\n");
\r
5847 int hash_algorithm;
\r
5848 int sign_algorithm;
\r
5849 int packet_size = res - 3;
\r
5850 if (context->dtls)
\r
5853 DEBUG_PRINT(" SIGNATURE (%i/%i/%i): ", packet_size, dh_res, key_size);
\r
5854 const unsigned char *signature = __private_tls_parse_signature(context, &buf[res], buf_len - res, &hash_algorithm, &sign_algorithm, &sign_size, &offset);
\r
5855 DEBUG_PRINT("\n");
\r
5856 if ((sign_size <= 0) || (!signature))
\r
5857 return TLS_BROKEN_PACKET;
\r
5859 // check signature
\r
5860 unsigned int message_len = packet_size + __TLS_CLIENT_RANDOM_SIZE + __TLS_SERVER_RANDOM_SIZE;
\r
5861 unsigned char *message = (unsigned char *)TLS_MALLOC(message_len);
\r
5863 memcpy(message, context->local_random, __TLS_CLIENT_RANDOM_SIZE);
\r
5864 memcpy(message + __TLS_CLIENT_RANDOM_SIZE, context->remote_random, __TLS_SERVER_RANDOM_SIZE);
\r
5865 memcpy(message + __TLS_CLIENT_RANDOM_SIZE + __TLS_SERVER_RANDOM_SIZE, packet_ref, packet_size);
\r
5866 #ifdef TLS_CLIENT_ECDSA
\r
5867 if (tls_is_ecdsa(context)) {
\r
5868 if (__private_tls_verify_ecdsa(context, hash_algorithm, signature, sign_size, message, message_len) != 1) {
\r
5869 DEBUG_PRINT("ECC Server signature FAILED!\n");
\r
5870 TLS_FREE(message);
\r
5871 return TLS_BROKEN_PACKET;
\r
5876 if (__private_tls_verify_rsa(context, hash_algorithm, signature, sign_size, message, message_len) != 1) {
\r
5877 DEBUG_PRINT("Server signature FAILED!\n");
\r
5878 TLS_FREE(message);
\r
5879 return TLS_BROKEN_PACKET;
\r
5882 TLS_FREE(message);
\r
5885 if (buf_len - res) {
\r
5886 DEBUG_PRINT("EXTRA %i BYTES AT THE END OF MESSAGE\n", buf_len - res);
\r
5887 DEBUG_DUMP_HEX(&buf[res], buf_len - res);
\r
5888 DEBUG_PRINT("\n");
\r
5890 #ifdef TLS_FORWARD_SECRECY
\r
5891 if (ephemeral == 1) {
\r
5892 __private_tls_dhe_create(context);
\r
5893 DEBUG_DUMP_HEX_LABEL("DHP", dh_p, dh_p_len);
\r
5894 DEBUG_DUMP_HEX_LABEL("DHG", dh_g, dh_g_len);
\r
5895 int dhe_key_size = dh_p_len;
\r
5896 if (dh_g_len > dh_p_len)
\r
5897 dhe_key_size = dh_g_len;
\r
5898 if (__private_tls_dh_make_key(dhe_key_size, context->dhe, (const char *)dh_p, (const char *)dh_g, dh_p_len, dh_g_len)) {
\r
5899 DEBUG_PRINT("ERROR CREATING DHE KEY\n");
\r
5900 TLS_FREE(context->dhe);
\r
5901 context->dhe = NULL;
\r
5902 return TLS_GENERIC_ERROR;
\r
5905 unsigned int dh_key_size = 0;
\r
5906 unsigned char *key = __private_tls_decrypt_dhe(context, dh_Ys, dh_Ys_len, &dh_key_size, 0);
\r
5907 DEBUG_DUMP_HEX_LABEL("DH COMMON SECRET", key, dh_key_size);
\r
5908 if ((key) && (dh_key_size)) {
\r
5909 TLS_FREE(context->premaster_key);
\r
5910 context->premaster_key = key;
\r
5911 context->premaster_key_len = dh_key_size;
\r
5914 if ((ephemeral == 2) && (curve) && (pk_key) && (key_size)) {
\r
5916 __private_tls_ecc_dhe_create(context);
\r
5918 ltc_ecc_set_type *dp = (ltc_ecc_set_type *)&curve->dp;
\r
5919 if (ecc_make_key_ex(NULL, find_prng("sprng"), context->ecc_dhe, dp)) {
\r
5920 TLS_FREE(context->ecc_dhe);
\r
5921 context->ecc_dhe = NULL;
\r
5922 DEBUG_PRINT("Error generatic ECC key\n");
\r
5923 return TLS_GENERIC_ERROR;
\r
5926 TLS_FREE(context->premaster_key);
\r
5927 context->premaster_key_len = 0;
\r
5929 unsigned int out_len = 0;
\r
5930 context->premaster_key = __private_tls_decrypt_ecc_dhe(context, pk_key, key_size, &out_len, 0);
\r
5931 if (context->premaster_key)
\r
5932 context->premaster_key_len = out_len;
\r
5938 int tls_parse_client_key_exchange(struct TLSContext *context, const unsigned char *buf, int buf_len) {
\r
5939 if (context->connection_status != 1) {
\r
5940 DEBUG_PRINT("UNEXPECTED CLIENT KEY EXCHANGE MESSAGE (connections status: %i)\n", (int)context->connection_status);
\r
5941 return TLS_UNEXPECTED_MESSAGE;
\r
5946 CHECK_SIZE(3, buf_len, TLS_NEED_MORE_DATA)
\r
5948 unsigned int size = buf[0] * 0x10000 + buf[1] * 0x100 + buf[2];
\r
5950 if (context->dtls) {
\r
5951 int dtls_check = __private_dtls_check_packet(buf, buf_len);
\r
5952 if (dtls_check < 0)
\r
5953 return dtls_check;
\r
5957 CHECK_SIZE(size, buf_len - res, TLS_NEED_MORE_DATA);
\r
5962 dh_res = __private_tls_parse_random(context, &buf[res], size);
\r
5963 if (dh_res <= 0) {
\r
5964 DEBUG_PRINT("broken key\n");
\r
5965 return TLS_BROKEN_PACKET;
\r
5967 DEBUG_PRINT("\n");
\r
5970 context->connection_status = 2;
\r
5974 int tls_parse_server_hello_done(struct TLSContext *context, const unsigned char *buf, int buf_len) {
\r
5976 CHECK_SIZE(3, buf_len, TLS_NEED_MORE_DATA)
\r
5978 unsigned int size = buf[0] * 0x10000 + buf[1] * 0x100 + buf[2];
\r
5980 if (context->dtls) {
\r
5981 int dtls_check = __private_dtls_check_packet(buf, buf_len);
\r
5982 if (dtls_check < 0)
\r
5983 return dtls_check;
\r
5987 CHECK_SIZE(size, buf_len - res, TLS_NEED_MORE_DATA);
\r
5993 int tls_parse_finished(struct TLSContext *context, const unsigned char *buf, int buf_len, unsigned int *write_packets) {
\r
5994 if ((context->connection_status < 2) || (context->connection_status == 0xFF)) {
\r
5995 DEBUG_PRINT("UNEXPECTED HELLO MESSAGE\n");
\r
5996 return TLS_UNEXPECTED_MESSAGE;
\r
6000 *write_packets = 0;
\r
6001 CHECK_SIZE(3, buf_len, TLS_NEED_MORE_DATA)
\r
6003 unsigned int size = buf[0] * 0x10000 + buf[1] * 0x100 + buf[2];
\r
6005 if (context->dtls) {
\r
6006 int dtls_check = __private_dtls_check_packet(buf, buf_len);
\r
6007 if (dtls_check < 0)
\r
6008 return dtls_check;
\r
6012 if (size < __TLS_MIN_FINISHED_OPAQUE_LEN) {
\r
6013 DEBUG_PRINT("Invalid finished pachet size: %i\n", size);
\r
6014 return TLS_BROKEN_PACKET;
\r
6017 CHECK_SIZE(size, buf_len - res, TLS_NEED_MORE_DATA);
\r
6020 unsigned char *out = (unsigned char *)TLS_MALLOC(size);
\r
6022 DEBUG_PRINT("Error in TLS_MALLOC (%i bytes)\n", (int)size);
\r
6023 return TLS_NO_MEMORY;
\r
6026 unsigned char hash[__TLS_MAX_SHA_SIZE];
\r
6027 unsigned int hash_len = __private_tls_get_hash(context, hash);
\r
6028 // server verifies client's message
\r
6029 if (context->is_server)
\r
6030 __private_tls_prf(context, out, size, context->master_key, context->master_key_len, (unsigned char *)"client finished", 15, hash, hash_len, NULL, 0);
\r
6032 __private_tls_prf(context, out, size, context->master_key, context->master_key_len, (unsigned char *)"server finished", 15, hash, hash_len, NULL, 0);
\r
6034 //unsigned char hash2[__TLS_HASH_SIZE];
\r
6035 //hash_len = __private_tls_get_hash(context, hash2);
\r
6036 //int x = memcmp(hash, hash2, __TLS_HASH_SIZE);
\r
6037 //DEBUG_PRINT("MEMCMP RESULT: %i\n", x);
\r
6038 if (memcmp(out, &buf[res], size)) {
\r
6040 DEBUG_PRINT("Finished validation error (sequence number, local: %i, remote: %i)\n", (int)context->local_sequence_number, (int)context->remote_sequence_number);
\r
6041 DEBUG_DUMP_HEX_LABEL("FINISHED OPAQUE", &buf[res], size);
\r
6042 DEBUG_DUMP_HEX_LABEL("VERIFY", out, size);
\r
6043 return TLS_NOT_VERIFIED;
\r
6046 if (context->is_server)
\r
6047 *write_packets = 3;
\r
6049 context->connection_status = 0xFF;
\r
6050 #ifdef TLS_ACCEPT_SECURE_RENEGOTIATION
\r
6052 if (context->is_server) {
\r
6053 TLS_FREE(context->verify_data);
\r
6054 context->verify_data = (unsigned char *)TLS_MALLOC(size);
\r
6055 if (context->verify_data) {
\r
6056 memcpy(context->verify_data, out, size);
\r
6057 context->verify_len = size;
\r
6060 // concatenate client verify and server verify
\r
6061 context->verify_data = (unsigned char *)TLS_REALLOC(context->verify_data, size);
\r
6062 if (context->verify_data) {
\r
6063 memcpy(context->verify_data + context->verify_len, out, size);
\r
6064 context->verify_len += size;
\r
6066 context->verify_len = 0;
\r
6074 int tls_parse_verify(struct TLSContext *context, const unsigned char *buf, int buf_len) {
\r
6075 CHECK_SIZE(7, buf_len, TLS_BAD_CERTIFICATE)
\r
6076 unsigned int bytes_to_follow = buf[0] * 0x10000 + buf[1] * 0x100 + buf[2];
\r
6077 CHECK_SIZE(bytes_to_follow, buf_len - 3, TLS_BAD_CERTIFICATE)
\r
6080 if ((context->version == TLS_V12) || (context->version == DTLS_V12)) {
\r
6081 unsigned int hash = buf[3];
\r
6082 unsigned int algorithm = buf[4];
\r
6083 if (algorithm != rsa)
\r
6084 return TLS_UNSUPPORTED_CERTIFICATE;
\r
6085 unsigned short size = ntohs(*(unsigned short *)&buf[5]);
\r
6086 CHECK_SIZE(size, bytes_to_follow - 4, TLS_BAD_CERTIFICATE)
\r
6087 DEBUG_PRINT("ALGORITHM %i/%i (%i)\n", hash, algorithm, (int)size);
\r
6088 DEBUG_DUMP_HEX_LABEL("VERIFY", &buf[7], bytes_to_follow - 7);
\r
6090 res = __private_tls_verify_rsa(context, hash, &buf[7], size, context->cached_handshake, context->cached_handshake_len);
\r
6092 #ifdef TLS_LEGACY_SUPPORT
\r
6093 unsigned short size = ntohs(*(unsigned short *)&buf[3]);
\r
6094 CHECK_SIZE(size, bytes_to_follow - 2, TLS_BAD_CERTIFICATE)
\r
6095 res = __private_tls_verify_rsa(context, md5, &buf[5], size, context->cached_handshake, context->cached_handshake_len);
\r
6098 if (context->cached_handshake) {
\r
6099 // not needed anymore
\r
6100 TLS_FREE(context->cached_handshake);
\r
6101 context->cached_handshake = NULL;
\r
6102 context->cached_handshake_len = 0;
\r
6105 DEBUG_PRINT("Signature OK\n");
\r
6106 context->client_verified = 1;
\r
6108 DEBUG_PRINT("Signature FAILED\n");
\r
6109 context->client_verified = 0;
\r
6114 int tls_parse_payload(struct TLSContext *context, const unsigned char *buf, int buf_len, tls_validation_function certificate_verify) {
\r
6115 int orig_len = buf_len;
\r
6116 if (context->connection_status == 0xFF) {
\r
6117 #ifndef TLS_ACCEPT_SECURE_RENEGOTIATION
\r
6118 // renegotiation disabled (emit warning alert)
\r
6119 __private_tls_write_packet(tls_build_alert(context, 0, no_renegotiation));
\r
6124 while ((buf_len >= 4) && (!context->critical_error)) {
\r
6125 int payload_res = 0;
\r
6126 unsigned char update_hash = 1;
\r
6127 CHECK_SIZE(1, buf_len, TLS_NEED_MORE_DATA)
\r
6128 unsigned char type = buf[0];
\r
6129 unsigned int write_packets = 0;
\r
6130 unsigned int dtls_cookie_verified = 0;
\r
6131 int certificate_verify_alert = no_error;
\r
6132 unsigned int payload_size = buf[1] * 0x10000 + buf[2] * 0x100 + buf[3] + 3;
\r
6133 if (context->dtls)
\r
6134 payload_size += 8;
\r
6135 CHECK_SIZE(payload_size + 1, buf_len, TLS_NEED_MORE_DATA)
\r
6139 CHECK_HANDSHAKE_STATE(context, 0, 1);
\r
6140 DEBUG_PRINT(" => HELLO REQUEST (RENEGOTIATION?)\n");
\r
6141 if (context->dtls)
\r
6142 context->dtls_seq = 0;
\r
6143 if (context->is_server)
\r
6144 payload_res = TLS_UNEXPECTED_MESSAGE;
\r
6146 if (context->connection_status == 0xFF) {
\r
6148 #ifdef TLS_ACCEPT_SECURE_RENEGOTIATION
\r
6149 if (context->critical_error)
\r
6150 payload_res = TLS_UNEXPECTED_MESSAGE;
\r
6152 __private_tls_reset_context(context);
\r
6153 __private_tls_write_packet(tls_build_hello(context));
\r
6157 payload_res = TLS_NO_RENEGOTIATION;
\r
6160 payload_res = TLS_UNEXPECTED_MESSAGE;
\r
6166 CHECK_HANDSHAKE_STATE(context, 1, (context->dtls ? 2 : 1));
\r
6167 DEBUG_PRINT(" => CLIENT HELLO\n");
\r
6168 if (context->is_server) {
\r
6169 payload_res = tls_parse_hello(context, buf + 1, payload_size, &write_packets, &dtls_cookie_verified);
\r
6170 DEBUG_PRINT(" => DTLS COOKIE VERIFIED: %i (%i)\n", dtls_cookie_verified, payload_res);
\r
6171 if ((context->dtls) && (payload_res > 0) && (!dtls_cookie_verified) && (context->connection_status == 1)) {
\r
6172 // wait client hello
\r
6173 context->connection_status = 0;
\r
6177 payload_res = TLS_UNEXPECTED_MESSAGE;
\r
6181 CHECK_HANDSHAKE_STATE(context, 2, 1);
\r
6182 DEBUG_PRINT(" => SERVER HELLO\n");
\r
6183 if (context->is_server)
\r
6184 payload_res = TLS_UNEXPECTED_MESSAGE;
\r
6186 payload_res = tls_parse_hello(context, buf + 1, payload_size, &write_packets, &dtls_cookie_verified);
\r
6188 // hello verify request
\r
6190 DEBUG_PRINT(" => VERIFY REQUEST\n");
\r
6191 CHECK_HANDSHAKE_STATE(context, 3, 1);
\r
6192 if ((context->dtls) && (!context->is_server)) {
\r
6193 payload_res = tls_parse_verify_request(context, buf + 1, payload_size, &write_packets);
\r
6196 payload_res = TLS_UNEXPECTED_MESSAGE;
\r
6200 CHECK_HANDSHAKE_STATE(context, 4, 1);
\r
6201 DEBUG_PRINT(" => CERTIFICATE\n");
\r
6202 if (context->connection_status == 1) {
\r
6203 if (context->is_server) {
\r
6204 // client certificate
\r
6205 payload_res = tls_parse_certificate(context, buf + 1, payload_size, 1);
\r
6206 if ((certificate_verify) && (context->client_certificates_count))
\r
6207 certificate_verify_alert = certificate_verify(context, context->client_certificates, context->client_certificates_count);
\r
6208 // empty certificates are permitted for client
\r
6209 if (payload_res <= 0)
\r
6212 payload_res = tls_parse_certificate(context, buf + 1, payload_size, 0);
\r
6213 if ((certificate_verify) && (context->certificates_count))
\r
6214 certificate_verify_alert = certificate_verify(context, context->certificates, context->certificates_count);
\r
6217 payload_res = TLS_UNEXPECTED_MESSAGE;
\r
6219 // server key exchange
\r
6221 CHECK_HANDSHAKE_STATE(context, 5, 1);
\r
6222 DEBUG_PRINT(" => SERVER KEY EXCHANGE\n");
\r
6223 if (context->is_server)
\r
6224 payload_res = TLS_UNEXPECTED_MESSAGE;
\r
6226 payload_res = tls_parse_server_key_exchange(context, buf + 1, payload_size);
\r
6228 // certificate request
\r
6230 CHECK_HANDSHAKE_STATE(context, 6, 1);
\r
6231 // server to client
\r
6232 if (context->is_server)
\r
6233 payload_res = TLS_UNEXPECTED_MESSAGE;
\r
6235 context->client_verified = 2;
\r
6236 DEBUG_PRINT(" => CERTIFICATE REQUEST\n");
\r
6238 // server hello done
\r
6240 CHECK_HANDSHAKE_STATE(context, 7, 1);
\r
6241 DEBUG_PRINT(" => SERVER HELLO DONE\n");
\r
6242 if (context->is_server) {
\r
6243 payload_res = TLS_UNEXPECTED_MESSAGE;
\r
6245 payload_res = tls_parse_server_hello_done(context, buf + 1, payload_size);
\r
6246 if (payload_res > 0)
\r
6247 write_packets = 1;
\r
6250 // certificate verify
\r
6252 CHECK_HANDSHAKE_STATE(context, 8, 1);
\r
6253 DEBUG_PRINT(" => CERTIFICATE VERIFY\n");
\r
6254 if (context->connection_status == 2)
\r
6255 payload_res = tls_parse_verify(context, buf + 1, payload_size);
\r
6257 payload_res = TLS_UNEXPECTED_MESSAGE;
\r
6259 // client key exchange
\r
6261 CHECK_HANDSHAKE_STATE(context, 9, 1);
\r
6262 DEBUG_PRINT(" => CLIENT KEY EXCHANGE\n");
\r
6263 if (context->is_server)
\r
6264 payload_res = tls_parse_client_key_exchange(context, buf + 1, payload_size);
\r
6266 payload_res = TLS_UNEXPECTED_MESSAGE;
\r
6270 if (context->cached_handshake) {
\r
6271 TLS_FREE(context->cached_handshake);
\r
6272 context->cached_handshake = NULL;
\r
6273 context->cached_handshake_len = 0;
\r
6275 CHECK_HANDSHAKE_STATE(context, 10, 1);
\r
6276 DEBUG_PRINT(" => FINISHED\n");
\r
6277 payload_res = tls_parse_finished(context, buf + 1, payload_size, &write_packets);
\r
6278 if (payload_res > 0)
\r
6279 memset(context->hs_messages, 0, sizeof(context->hs_messages));
\r
6282 DEBUG_PRINT(" => NOT UNDERSTOOD PAYLOAD TYPE: %x\n", (int)type);
\r
6283 return TLS_NOT_UNDERSTOOD;
\r
6285 if ((type != 0x00) && (update_hash))
\r
6286 __private_tls_update_hash(context, buf, payload_size + 1);
\r
6288 if (certificate_verify_alert != no_error) {
\r
6289 __private_tls_write_packet(tls_build_alert(context, 1, certificate_verify_alert));
\r
6290 context->critical_error = 1;
\r
6293 if (payload_res < 0) {
\r
6294 switch (payload_res) {
\r
6295 case TLS_UNEXPECTED_MESSAGE:
\r
6296 __private_tls_write_packet(tls_build_alert(context, 1, unexpected_message));
\r
6298 case TLS_COMPRESSION_NOT_SUPPORTED:
\r
6299 __private_tls_write_packet(tls_build_alert(context, 1, decompression_failure));
\r
6301 case TLS_BROKEN_PACKET:
\r
6302 __private_tls_write_packet(tls_build_alert(context, 1, decode_error));
\r
6304 case TLS_NO_MEMORY:
\r
6305 __private_tls_write_packet(tls_build_alert(context, 1, internal_error));
\r
6307 case TLS_NOT_VERIFIED:
\r
6308 __private_tls_write_packet(tls_build_alert(context, 1, bad_record_mac));
\r
6310 case TLS_BAD_CERTIFICATE:
\r
6311 if (context->is_server) {
\r
6312 // bad client certificate, continue
\r
6313 __private_tls_write_packet(tls_build_alert(context, 0, bad_certificate));
\r
6316 __private_tls_write_packet(tls_build_alert(context, 1, bad_certificate));
\r
6318 case TLS_UNSUPPORTED_CERTIFICATE:
\r
6319 __private_tls_write_packet(tls_build_alert(context, 1, unsupported_certificate));
\r
6321 case TLS_NO_COMMON_CIPHER:
\r
6322 __private_tls_write_packet(tls_build_alert(context, 1, insufficient_security));
\r
6324 case TLS_NOT_UNDERSTOOD:
\r
6325 __private_tls_write_packet(tls_build_alert(context, 1, internal_error));
\r
6327 case TLS_NO_RENEGOTIATION:
\r
6328 __private_tls_write_packet(tls_build_alert(context, 0, no_renegotiation));
\r
6332 if (payload_res < 0)
\r
6333 return payload_res;
\r
6335 if (certificate_verify_alert != no_error)
\r
6336 payload_res = TLS_BAD_CERTIFICATE;
\r
6338 // except renegotiation
\r
6339 switch (write_packets) {
\r
6341 if (context->client_verified == 2) {
\r
6342 DEBUG_PRINT("<= Building CERTIFICATE \n");
\r
6343 __private_tls_write_packet(tls_build_certificate(context));
\r
6344 context->client_verified = 0;
\r
6346 // client handshake
\r
6347 DEBUG_PRINT("<= Building KEY EXCHANGE\n");
\r
6348 __private_tls_write_packet(tls_build_client_key_exchange(context));
\r
6349 DEBUG_PRINT("<= Building CHANGE CIPHER SPEC\n");
\r
6350 __private_tls_write_packet(tls_build_change_cipher_spec(context));
\r
6351 context->cipher_spec_set = 1;
\r
6352 context->local_sequence_number = 0;
\r
6353 DEBUG_PRINT("<= Building CLIENT FINISHED\n");
\r
6354 __private_tls_write_packet(tls_build_finished(context));
\r
6355 context->cipher_spec_set = 0;
\r
6358 // server handshake
\r
6359 if ((context->dtls) && (dtls_cookie_verified == 0)) {
\r
6360 __private_tls_write_packet(tls_build_verify_request(context));
\r
6361 __private_dtls_reset(context);
\r
6363 DEBUG_PRINT("<= SENDING SERVER HELLO\n");
\r
6364 __private_tls_write_packet(tls_build_hello(context));
\r
6365 DEBUG_PRINT("<= SENDING CERTIFICATE\n");
\r
6366 __private_tls_write_packet(tls_build_certificate(context));
\r
6367 int ephemeral_cipher = tls_cipher_is_ephemeral(context);
\r
6368 if (ephemeral_cipher) {
\r
6369 DEBUG_PRINT("<= SENDING EPHEMERAL DH KEY\n");
\r
6370 __private_tls_write_packet(tls_build_server_key_exchange(context, ephemeral_cipher == 1 ? KEA_dhe_rsa : KEA_ec_diffie_hellman));
\r
6372 if (context->request_client_certificate) {
\r
6373 DEBUG_PRINT("<= SENDING CERTIFICATE REQUEST\n");
\r
6374 __private_tls_write_packet(tls_certificate_request(context));
\r
6376 DEBUG_PRINT("<= SENDING DONE\n");
\r
6377 __private_tls_write_packet(tls_build_done(context));
\r
6382 __private_tls_write_packet(tls_build_change_cipher_spec(context));
\r
6383 __private_tls_write_packet(tls_build_finished(context));
\r
6384 context->connection_status = 0xFF;
\r
6388 context->dtls_seq = 1;
\r
6389 __private_tls_write_packet(tls_build_hello(context));
\r
6393 buf += payload_size;
\r
6394 buf_len -= payload_size;
\r
6399 unsigned int __private_tls_hmac_message(unsigned char local, struct TLSContext *context, const unsigned char *buf, int buf_len, const unsigned char *buf2, int buf_len2, unsigned char *out, unsigned int outlen, uint64_t remote_sequence_number) {
\r
6401 int mac_size = outlen;
\r
6403 if (mac_size == __TLS_SHA1_MAC_SIZE)
\r
6404 hash_idx = find_hash("sha1");
\r
6406 if (mac_size == __TLS_SHA384_MAC_SIZE)
\r
6407 hash_idx = find_hash("sha384");
\r
6409 hash_idx = find_hash("sha256");
\r
6411 if (hmac_init(&hash, hash_idx, local ? context->crypto.ctx_local_mac.local_mac : context->crypto.ctx_remote_mac.remote_mac, mac_size))
\r
6414 uint64_t squence_number;
\r
6415 if (context->dtls)
\r
6416 squence_number = htonll(remote_sequence_number);
\r
6419 squence_number = htonll(context->local_sequence_number);
\r
6421 squence_number = htonll(context->remote_sequence_number);
\r
6423 if (hmac_process(&hash, (unsigned char *)&squence_number, sizeof(uint64_t)))
\r
6426 if (hmac_process(&hash, buf, buf_len))
\r
6428 if ((buf2) && (buf_len2)) {
\r
6429 if (hmac_process(&hash, buf2, buf_len2))
\r
6432 unsigned long ref_outlen = outlen;
\r
6433 if (hmac_done(&hash, out, &ref_outlen))
\r
6436 return (unsigned int)ref_outlen;
\r
6439 int tls_parse_message(struct TLSContext *context, unsigned char *buf, int buf_len, tls_validation_function certificate_verify) {
\r
6441 if (context->dtls)
\r
6443 int header_size = res;
\r
6444 int payload_res = 0;
\r
6446 CHECK_SIZE(res, buf_len, TLS_NEED_MORE_DATA)
\r
6448 unsigned char type = *buf;
\r
6452 unsigned short version = ntohs(*(unsigned short *)&buf[buf_pos]);
\r
6455 uint64_t dtls_sequence_number = 0;
\r
6456 if (context->dtls) {
\r
6457 CHECK_SIZE(buf_pos + 8, buf_len, TLS_NEED_MORE_DATA)
\r
6458 dtls_sequence_number = ntohll(*(uint64_t *)&buf[buf_pos]);
\r
6462 VERSION_SUPPORTED(version, TLS_NOT_SAFE)
\r
6463 unsigned short length;
\r
6464 length = ntohs(*(unsigned short *)&buf[buf_pos]);
\r
6467 unsigned char *pt = NULL;
\r
6468 const unsigned char *ptr = buf + buf_pos;
\r
6470 CHECK_SIZE(buf_pos + length, buf_len, TLS_NEED_MORE_DATA)
\r
6471 DEBUG_PRINT("Message type: %0x, length: %i\n", (int)type, (int)length);
\r
6472 if (context->cipher_spec_set) {
\r
6473 DEBUG_DUMP_HEX_LABEL("encrypted", &buf[header_size], length);
\r
6474 if (!context->crypto.created) {
\r
6475 DEBUG_PRINT("Encryption context not created\n");
\r
6476 __private_random_sleep(context, __TLS_MAX_ERROR_SLEEP_uS);
\r
6477 return TLS_BROKEN_PACKET;
\r
6479 pt = (unsigned char *)TLS_MALLOC(length);
\r
6481 DEBUG_PRINT("Error in TLS_MALLOC (%i bytes)\n", (int)length);
\r
6482 __private_random_sleep(context, __TLS_MAX_ERROR_SLEEP_uS);
\r
6483 return TLS_NO_MEMORY;
\r
6485 unsigned char aad[16];
\r
6486 if (context->crypto.created == 2) {
\r
6487 int pt_length = length - 8 - __TLS_GCM_TAG_LEN;
\r
6488 if (pt_length < 0) {
\r
6489 DEBUG_PRINT("Invalid packet length");
\r
6491 __private_random_sleep(context, __TLS_MAX_ERROR_SLEEP_uS);
\r
6492 return TLS_BROKEN_PACKET;
\r
6494 // build aad and iv
\r
6495 if (context->dtls)
\r
6496 *((uint64_t *)aad) = htonll(dtls_sequence_number);
\r
6498 *((uint64_t *)aad) = htonll(context->remote_sequence_number);
\r
6499 unsigned char iv[12];
\r
6500 memcpy(iv, context->crypto.ctx_remote_mac.remote_aead_iv, 4);
\r
6501 memcpy(iv + 4, buf + header_size, 8);
\r
6502 gcm_reset(&context->crypto.ctx_remote.aes_gcm_remote);
\r
6503 int res0 = gcm_add_iv(&context->crypto.ctx_remote.aes_gcm_remote, iv, 12);
\r
6505 DEBUG_DUMP_HEX_LABEL("aad iv", iv, 12);
\r
6510 *((unsigned short *)&aad[11]) = htons(pt_length);
\r
6511 int res1 = gcm_add_aad(&context->crypto.ctx_remote.aes_gcm_remote, aad, 13);
\r
6512 memset(pt, 0, length);
\r
6513 DEBUG_PRINT("PT SIZE: %i\n", pt_length);
\r
6514 int res2 = gcm_process(&context->crypto.ctx_remote.aes_gcm_remote, pt, pt_length, buf + header_size + 8, GCM_DECRYPT);
\r
6515 unsigned char tag[32];
\r
6516 unsigned long taglen = 32;
\r
6517 int res3 = gcm_done(&context->crypto.ctx_remote.aes_gcm_remote, tag, &taglen);
\r
6518 if ((res0) || (res1) || (res2) || (res3) || (taglen != __TLS_GCM_TAG_LEN)) {
\r
6519 DEBUG_PRINT("ERROR: gcm_add_iv: %i, gcm_add_aad: %i, gcm_process: %i, gcm_done: %i\n", res0, res1, res2, res3);
\r
6520 __private_random_sleep(context, __TLS_MAX_ERROR_SLEEP_uS);
\r
6521 return TLS_BROKEN_PACKET;
\r
6523 DEBUG_DUMP_HEX_LABEL("decrypted", pt, pt_length);
\r
6524 DEBUG_DUMP_HEX_LABEL("tag", tag, taglen);
\r
6526 if (memcmp(buf + header_size + 8 + pt_length, tag, taglen)) {
\r
6527 DEBUG_PRINT("INTEGRITY CHECK FAILED (msg length %i)\n", pt_length);
\r
6528 DEBUG_DUMP_HEX_LABEL("TAG RECEIVED", buf + header_size + 8 + pt_length, taglen);
\r
6529 DEBUG_DUMP_HEX_LABEL("TAG COMPUTED", tag, taglen);
\r
6531 __private_random_sleep(context, __TLS_MAX_ERROR_SLEEP_uS);
\r
6532 __private_tls_write_packet(tls_build_alert(context, 1, bad_record_mac));
\r
6533 return TLS_INTEGRITY_FAILED;
\r
6536 length = pt_length;
\r
6537 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
6539 if (context->crypto.created == 3) {
\r
6540 int pt_length = length - POLY1305_TAGLEN;
\r
6541 unsigned int counter = 1;
\r
6542 unsigned char poly1305_key[POLY1305_KEYLEN];
\r
6543 unsigned char trail[16];
\r
6544 unsigned char mac_tag[POLY1305_TAGLEN];
\r
6546 if (pt_length < 0) {
\r
6547 DEBUG_PRINT("Invalid packet length");
\r
6549 __private_random_sleep(context, __TLS_MAX_ERROR_SLEEP_uS);
\r
6550 return TLS_BROKEN_PACKET;
\r
6552 if (context->dtls)
\r
6553 *((uint64_t *)aad) = htonll(dtls_sequence_number);
\r
6555 *((uint64_t *)aad) = htonll(context->remote_sequence_number);
\r
6559 *((unsigned short *)&aad[11]) = htons(pt_length);
\r
6564 chacha_ivupdate(&context->crypto.ctx_remote.chacha_remote, context->crypto.ctx_remote_mac.remote_aead_iv, aad, (unsigned char *)&counter);
\r
6566 chacha_encrypt_bytes(&context->crypto.ctx_remote.chacha_remote, buf + header_size, pt, pt_length);
\r
6567 DEBUG_DUMP_HEX_LABEL("decrypted", pt, pt_length);
\r
6569 length = pt_length;
\r
6571 chacha20_poly1305_key(&context->crypto.ctx_remote.chacha_remote, poly1305_key);
\r
6572 poly1305_context ctx;
\r
6573 __private_tls_poly1305_init(&ctx, poly1305_key);
\r
6574 __private_tls_poly1305_update(&ctx, aad, 16);
\r
6575 __private_tls_poly1305_update(&ctx, buf + header_size, pt_length);
\r
6576 int rem = pt_length % 16;
\r
6578 static unsigned char zeropad[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
\r
6579 __private_tls_poly1305_update(&ctx, zeropad, 16 - rem);
\r
6582 __private_tls_U32TO8(&trail[0], 13);
\r
6583 *(int *)&trail[4] = 0;
\r
6584 __private_tls_U32TO8(&trail[8], pt_length);
\r
6585 *(int *)&trail[12] = 0;
\r
6587 __private_tls_poly1305_update(&ctx, trail, 16);
\r
6588 __private_tls_poly1305_finish(&ctx, mac_tag);
\r
6589 if (memcmp(mac_tag, buf + header_size + pt_length, POLY1305_TAGLEN)) {
\r
6590 DEBUG_PRINT("INTEGRITY CHECK FAILED (msg length %i)\n", length);
\r
6591 DEBUG_DUMP_HEX_LABEL("POLY1305 TAG RECEIVED", buf + header_size + pt_length, POLY1305_TAGLEN);
\r
6592 DEBUG_DUMP_HEX_LABEL("POLY1305 TAG COMPUTED", mac_tag, POLY1305_TAGLEN);
\r
6595 // silently ignore packet for DTLS
\r
6596 if (context->dtls)
\r
6597 return header_size + length;
\r
6599 __private_random_sleep(context, __TLS_MAX_ERROR_SLEEP_uS);
\r
6600 __private_tls_write_packet(tls_build_alert(context, 1, bad_record_mac));
\r
6601 return TLS_INTEGRITY_FAILED;
\r
6605 int err = __private_tls_crypto_decrypt(context, buf + header_size, pt, length);
\r
6608 DEBUG_PRINT("Decryption error %i\n", (int)err);
\r
6609 __private_random_sleep(context, __TLS_MAX_ERROR_SLEEP_uS);
\r
6610 return TLS_BROKEN_PACKET;
\r
6612 unsigned char padding_byte = pt[length - 1];
\r
6613 unsigned char padding = padding_byte + 1;
\r
6616 int padding_index = length - padding;
\r
6617 if (padding_index > 0) {
\r
6619 int limit = length - 1;
\r
6620 for (i = length - padding; i < limit; i++) {
\r
6621 if (pt[i] != padding_byte) {
\r
6623 DEBUG_PRINT("BROKEN PACKET (POODLE ?)\n");
\r
6624 __private_random_sleep(context, __TLS_MAX_ERROR_SLEEP_uS);
\r
6625 __private_tls_write_packet(tls_build_alert(context, 1, decrypt_error));
\r
6626 return TLS_BROKEN_PACKET;
\r
6631 unsigned int decrypted_length = length;
\r
6632 if (padding < decrypted_length)
\r
6633 decrypted_length -= padding;
\r
6635 DEBUG_DUMP_HEX_LABEL("decrypted", pt, decrypted_length);
\r
6637 #ifdef TLS_LEGACY_SUPPORT
\r
6638 if ((context->version != TLS_V10) && (decrypted_length > __TLS_AES_IV_LENGTH)) {
\r
6639 decrypted_length -= __TLS_AES_IV_LENGTH;
\r
6640 ptr += __TLS_AES_IV_LENGTH;
\r
6643 if (decrypted_length > __TLS_AES_IV_LENGTH) {
\r
6644 decrypted_length -= __TLS_AES_IV_LENGTH;
\r
6645 ptr += __TLS_AES_IV_LENGTH;
\r
6648 length = decrypted_length;
\r
6650 unsigned int mac_size = __private_tls_mac_length(context);
\r
6651 if ((length < mac_size) || (!mac_size)) {
\r
6653 DEBUG_PRINT("BROKEN PACKET\n");
\r
6654 __private_random_sleep(context, __TLS_MAX_ERROR_SLEEP_uS);
\r
6655 __private_tls_write_packet(tls_build_alert(context, 1, decrypt_error));
\r
6656 return TLS_BROKEN_PACKET;
\r
6659 length -= mac_size;
\r
6661 const unsigned char *message_hmac = &ptr[length];
\r
6662 unsigned char hmac_out[__TLS_MAX_MAC_SIZE];
\r
6663 unsigned char temp_buf[5];
\r
6664 memcpy(temp_buf, buf, 3);
\r
6665 *(unsigned short *)&temp_buf[3] = htons(length);
\r
6666 unsigned int hmac_out_len = __private_tls_hmac_message(0, context, temp_buf, 5, ptr, length, hmac_out, mac_size, dtls_sequence_number);
\r
6667 if ((hmac_out_len != mac_size) || (memcmp(message_hmac, hmac_out, mac_size))) {
\r
6668 DEBUG_PRINT("INTEGRITY CHECK FAILED (msg length %i)\n", length);
\r
6669 DEBUG_DUMP_HEX_LABEL("HMAC RECEIVED", message_hmac, mac_size);
\r
6670 DEBUG_DUMP_HEX_LABEL("HMAC COMPUTED", hmac_out, hmac_out_len);
\r
6673 // silently ignore packet for DTLS
\r
6674 if (context->dtls)
\r
6675 return header_size + length;
\r
6677 __private_random_sleep(context, __TLS_MAX_ERROR_SLEEP_uS);
\r
6678 __private_tls_write_packet(tls_build_alert(context, 1, bad_record_mac));
\r
6680 return TLS_INTEGRITY_FAILED;
\r
6684 context->remote_sequence_number++;
\r
6687 // application data
\r
6688 case TLS_APPLICATION_DATA:
\r
6689 if (context->connection_status != 0xFF) {
\r
6690 DEBUG_PRINT("UNEXPECTED APPLICATION DATA MESSAGE\n");
\r
6691 payload_res = TLS_UNEXPECTED_MESSAGE;
\r
6692 __private_tls_write_packet(tls_build_alert(context, 1, unexpected_message));
\r
6694 DEBUG_PRINT("APPLICATION DATA MESSAGE (TLS VERSION: %x):\n", (int)context->version);
\r
6695 DEBUG_DUMP(ptr, length);
\r
6696 DEBUG_PRINT("\n");
\r
6697 __private_tls_write_app_data(context, ptr, length);
\r
6701 case TLS_HANDSHAKE:
\r
6702 DEBUG_PRINT("HANDSHAKE MESSAGE\n");
\r
6703 payload_res = tls_parse_payload(context, ptr, length, certificate_verify);
\r
6705 // change cipher spec
\r
6706 case TLS_CHANGE_CIPHER:
\r
6707 context->dtls_epoch_remote++;
\r
6708 if (context->connection_status != 2) {
\r
6709 DEBUG_PRINT("UNEXPECTED CHANGE CIPHER SPEC MESSAGE (%i)\n", context->connection_status);
\r
6710 __private_tls_write_packet(tls_build_alert(context, 1, unexpected_message));
\r
6711 payload_res = TLS_UNEXPECTED_MESSAGE;
\r
6713 DEBUG_PRINT("CHANGE CIPHER SPEC MESSAGE\n");
\r
6714 context->cipher_spec_set = 1;
\r
6715 // reset sequence numbers
\r
6716 context->remote_sequence_number = 0;
\r
6721 DEBUG_PRINT("ALERT MESSAGE\n");
\r
6722 if (length >= 2) {
\r
6723 DEBUG_DUMP_HEX(ptr, length);
\r
6724 int level = ptr[0];
\r
6725 int code = ptr[1];
\r
6726 if (level == TLS_ALERT_CRITICAL) {
\r
6727 context->critical_error = 1;
\r
6728 res = TLS_ERROR_ALERT;
\r
6730 context->error_code = code;
\r
6734 DEBUG_PRINT("NOT UNDERSTOOD MESSAGE TYPE: %x\n", (int)type);
\r
6735 return TLS_NOT_UNDERSTOOD;
\r
6739 if (payload_res < 0)
\r
6740 return payload_res;
\r
6743 return header_size + length;
\r
6748 unsigned int asn1_get_len(const unsigned char *buffer, int buf_len, unsigned int *octets) {
\r
6754 unsigned char size = buffer[0];
\r
6756 if (size & 0x80) {
\r
6757 *octets = size & 0x7F;
\r
6758 if ((int)*octets > buf_len - 1)
\r
6761 unsigned int ref_octets = *octets;
\r
6764 if ((int)*octets > buf_len -1)
\r
6766 unsigned int long_size = 0;
\r
6767 unsigned int coef = 1;
\r
6769 for (i = ref_octets; i > 0; i--) {
\r
6770 long_size += buffer[i] * coef;
\r
6780 void print_index(const unsigned int *fields) {
\r
6782 while (fields[i]) {
\r
6785 DEBUG_PRINT("%i", fields[i]);
\r
6794 int __is_field(const unsigned int *fields, const unsigned int *prefix) {
\r
6796 while (prefix[i]) {
\r
6797 if (fields[i] != prefix[i])
\r
6804 int __private_tls_hash_len(int algorithm) {
\r
6805 switch (algorithm) {
\r
6806 case TLS_RSA_SIGN_MD5:
\r
6808 case TLS_RSA_SIGN_SHA1:
\r
6810 case TLS_RSA_SIGN_SHA256:
\r
6812 case TLS_RSA_SIGN_SHA384:
\r
6814 case TLS_RSA_SIGN_SHA512:
\r
6820 unsigned char *__private_tls_compute_hash(int algorithm, const unsigned char *message, unsigned int message_len) {
\r
6821 unsigned char *hash = NULL;
\r
6822 if ((!message) || (!message_len))
\r
6826 switch (algorithm) {
\r
6827 case TLS_RSA_SIGN_MD5:
\r
6828 DEBUG_PRINT("SIGN MD5\n");
\r
6829 hash = (unsigned char *)TLS_MALLOC(16);
\r
6833 err = md5_init(&state);
\r
6835 err = md5_process(&state, message, message_len);
\r
6837 err = md5_done(&state, hash);
\r
6840 case TLS_RSA_SIGN_SHA1:
\r
6841 DEBUG_PRINT("SIGN SHA1\n");
\r
6842 hash = (unsigned char *)TLS_MALLOC(20);
\r
6846 err = sha1_init(&state);
\r
6848 err = sha1_process(&state, message, message_len);
\r
6850 err = sha1_done(&state, hash);
\r
6853 case TLS_RSA_SIGN_SHA256:
\r
6854 DEBUG_PRINT("SIGN SHA256\n");
\r
6855 hash = (unsigned char *)TLS_MALLOC(32);
\r
6859 err = sha256_init(&state);
\r
6861 err = sha256_process(&state, message, message_len);
\r
6863 err = sha256_done(&state, hash);
\r
6866 case TLS_RSA_SIGN_SHA384:
\r
6867 DEBUG_PRINT("SIGN SHA384\n");
\r
6868 hash = (unsigned char *)TLS_MALLOC(48);
\r
6872 err = sha384_init(&state);
\r
6874 err = sha384_process(&state, message, message_len);
\r
6876 err = sha384_done(&state, hash);
\r
6879 case TLS_RSA_SIGN_SHA512:
\r
6880 DEBUG_PRINT("SIGN SHA512\n");
\r
6881 hash = (unsigned char *)TLS_MALLOC(64);
\r
6885 err = sha512_init(&state);
\r
6887 err = sha512_process(&state, message, message_len);
\r
6889 err = sha512_done(&state, hash);
\r
6893 DEBUG_PRINT("UNKNOWN SIGNATURE ALGORITHM\n");
\r
6898 int tls_certificate_verify_signature(struct TLSCertificate *cert, struct TLSCertificate *parent) {
\r
6899 if ((!cert) || (!parent) || (!cert->sign_key) || (!cert->fingerprint) || (!cert->sign_len) || (!parent->der_bytes) || (!parent->der_len)) {
\r
6900 DEBUG_PRINT("CANNOT VERIFY SIGNATURE");
\r
6904 int hash_len = __private_tls_hash_len(cert->algorithm);
\r
6905 if (hash_len <= 0)
\r
6908 int hash_index = -1;
\r
6909 switch (cert->algorithm) {
\r
6910 case TLS_RSA_SIGN_MD5:
\r
6911 hash_index = find_hash("md5");
\r
6913 case TLS_RSA_SIGN_SHA1:
\r
6914 hash_index = find_hash("sha1");
\r
6916 case TLS_RSA_SIGN_SHA256:
\r
6917 hash_index = find_hash("sha256");
\r
6919 case TLS_RSA_SIGN_SHA384:
\r
6920 hash_index = find_hash("sha384");
\r
6922 case TLS_RSA_SIGN_SHA512:
\r
6923 hash_index = find_hash("sha512");
\r
6926 DEBUG_PRINT("UNKNOWN SIGNATURE ALGORITHM\n");
\r
6931 int err = rsa_import(parent->der_bytes, parent->der_len, &key);
\r
6933 DEBUG_PRINT("Error importing RSA certificate (code: %i)\n", err);
\r
6934 DEBUG_DUMP_HEX_LABEL("CERTIFICATE", parent->der_bytes, parent->der_len);
\r
6938 unsigned char *signature = cert->sign_key;
\r
6939 int signature_len = cert->sign_len;
\r
6940 if (!signature[0]) {
\r
6944 err = rsa_verify_hash_ex(signature, signature_len, cert->fingerprint, hash_len, LTC_PKCS_1_V1_5, hash_index, 0, &rsa_stat, &key);
\r
6947 DEBUG_PRINT("HASH VERIFY ERROR %i\n", err);
\r
6950 DEBUG_PRINT("CERTIFICATE VALIDATION: %i\n", rsa_stat);
\r
6954 int tls_certificate_chain_is_valid(struct TLSCertificate **certificates, int len) {
\r
6955 if ((!certificates) || (!len))
\r
6956 return bad_certificate;
\r
6961 // expired certificate or not yet valid ?
\r
6962 if (tls_certificate_is_valid(certificates[0]))
\r
6963 return bad_certificate;
\r
6966 for (i = 0; i < len; i++) {
\r
6967 // certificate in chain is expired ?
\r
6968 if (tls_certificate_is_valid(certificates[i+1]))
\r
6969 return bad_certificate;
\r
6970 if (!tls_certificate_verify_signature(certificates[i], certificates[i+1]))
\r
6971 return bad_certificate;
\r
6976 int tls_certificate_chain_is_valid_root(struct TLSContext *context, struct TLSCertificate **certificates, int len) {
\r
6977 if ((!certificates) || (!len) || (!context->root_certificates) || (!context->root_count))
\r
6978 return bad_certificate;
\r
6981 for (i = 0; i < len; i++) {
\r
6982 for (j = 0; j < context->root_count; j++) {
\r
6983 // check if root certificate expired
\r
6984 if (tls_certificate_is_valid(context->root_certificates[j]))
\r
6986 // if any root validates any certificate in the chain, then is root validated
\r
6987 if (tls_certificate_verify_signature(certificates[i], context->root_certificates[j]))
\r
6991 return bad_certificate;
\r
6994 int __private_is_oid(struct __private_OID_chain *ref_chain, const unsigned char *looked_oid, int looked_oid_len) {
\r
6995 while (ref_chain) {
\r
6996 if (ref_chain->oid) {
\r
6997 if (__is_oid2(ref_chain->oid, looked_oid, 16, looked_oid_len))
\r
7000 ref_chain = (struct __private_OID_chain *)ref_chain->top;
\r
7005 int __private_asn1_parse(struct TLSContext *context, struct TLSCertificate *cert, const unsigned char *buffer, int size, int level, unsigned int *fields, unsigned char *has_key, int client_cert, unsigned char *top_oid, struct __private_OID_chain *chain) {
\r
7006 struct __private_OID_chain local_chain;
\r
7007 local_chain.top = chain;
\r
7011 unsigned char oid[16];
\r
7012 memset(oid, 0, 16);
\r
7013 local_chain.oid = oid;
\r
7016 unsigned char local_has_key = 0;
\r
7017 const unsigned char *cert_data = NULL;
\r
7018 unsigned int cert_len = 0;
\r
7019 while (pos < size) {
\r
7020 unsigned int start_pos = pos;
\r
7021 CHECK_SIZE(2, size - pos, TLS_NEED_MORE_DATA)
\r
7022 unsigned char first = buffer[pos++];
\r
7023 unsigned char type = first & 0x1F;
\r
7024 unsigned char constructed = first & 0x20;
\r
7025 unsigned char element_class = first >> 6;
\r
7026 unsigned int octets = 0;
\r
7027 unsigned int temp;
\r
7029 if (level <= __TLS_ASN1_MAXLEVEL)
\r
7030 fields[level - 1] = idx;
\r
7031 unsigned int length = asn1_get_len((unsigned char *)&buffer[pos], size - pos, &octets);
\r
7032 if ((octets > 4) || (octets > size - pos)) {
\r
7033 DEBUG_PRINT("CANNOT READ CERTIFICATE\n");
\r
7037 CHECK_SIZE(length, size - pos, TLS_NEED_MORE_DATA)
\r
7038 //DEBUG_PRINT("FIRST: %x => %x (%i)\n", (int)first, (int)type, length);
\r
7040 //DEBUG_PRINT("%2i: ", level);
\r
7042 DEBUG_INDEX(fields);
\r
7044 for (i1 = 1; i1 < level; i1++)
\r
7048 if ((length) && (constructed)) {
\r
7051 DEBUG_PRINT("CONSTRUCTED BITSTREAM\n");
\r
7054 DEBUG_PRINT("SEQUENCE\n");
\r
7055 if ((level == 2) && (idx == 1)) {
\r
7056 cert_len = length + (pos - start_pos);
\r
7057 cert_data = &buffer[start_pos];
\r
7059 // private key on server or public key on client
\r
7060 if ((!cert->version) && (__is_field(fields, priv_der_id))) {
\r
7061 TLS_FREE(cert->der_bytes);
\r
7062 temp = length + (pos - start_pos);
\r
7063 cert->der_bytes = (unsigned char *)TLS_MALLOC(temp);
\r
7064 if (cert->der_bytes) {
\r
7065 memcpy(cert->der_bytes, &buffer[start_pos], temp);
\r
7066 cert->der_len = temp;
\r
7068 cert->der_len = 0;
\r
7072 DEBUG_PRINT("EMBEDDED PDV\n");
\r
7075 if (element_class == 0x02) {
\r
7076 DEBUG_PRINT("CONTEXT-SPECIFIC\n");
\r
7080 DEBUG_PRINT("CONSTRUCT TYPE %02X\n", (int)type);
\r
7082 local_has_key = 0;
\r
7083 __private_asn1_parse(context, cert, &buffer[pos], length, level + 1, fields, &local_has_key, client_cert, top_oid, &local_chain);
\r
7084 if ((((local_has_key) && (context) && ((!context->is_server) || (client_cert))) || (!context)) && (__is_field(fields, pk_id))) {
\r
7085 TLS_FREE(cert->der_bytes);
\r
7086 temp = length + (pos - start_pos);
\r
7087 cert->der_bytes = (unsigned char *)TLS_MALLOC(temp);
\r
7088 if (cert->der_bytes) {
\r
7089 memcpy(cert->der_bytes, &buffer[start_pos], temp);
\r
7090 cert->der_len = temp;
\r
7092 cert->der_len = 0;
\r
7098 DEBUG_PRINT("END OF CONTENT\n");
\r
7103 temp = buffer[pos];
\r
7104 DEBUG_PRINT("BOOLEAN: %i\n", temp);
\r
7108 if (__is_field(fields, pk_id)) {
\r
7113 tls_certificate_set_key(cert, &buffer[pos], length);
\r
7116 tls_certificate_set_exponent(cert, &buffer[pos], length);
\r
7118 if (__is_field(fields, serial_id))
\r
7119 tls_certificate_set_serial(cert, &buffer[pos], length);
\r
7120 if (__is_field(fields, version_id)) {
\r
7122 cert->version = buffer[pos];
\r
7123 #ifdef TLS_X509_V1_SUPPORT
\r
7125 cert->version = 0;
\r
7130 unsigned int fields_temp[3];
\r
7131 fields_temp[0] = fields[level - 2];
\r
7132 fields_temp[1] = fields[level - 1];
\r
7133 fields_temp[2] = 0;
\r
7134 if (__is_field(fields_temp, priv_id))
\r
7135 tls_certificate_set_priv(cert, &buffer[pos], length);
\r
7137 DEBUG_PRINT("INTEGER(%i): ", length);
\r
7138 DEBUG_DUMP_HEX(&buffer[pos], length);
\r
7139 if ((chain) && (length > 2)) {
\r
7140 if (__private_is_oid(chain, san_oid, sizeof(san_oid) - 1)) {
\r
7141 cert->san = (unsigned char **)TLS_REALLOC(cert->san, sizeof(unsigned char *) * (cert->san_length + 1));
\r
7143 cert->san[cert->san_length] = NULL;
\r
7144 tls_certificate_set_copy(&cert->san[cert->san_length], &buffer[pos], length);
\r
7145 DEBUG_PRINT(" => SUBJECT ALTERNATIVE NAME: %s", cert->san[cert->san_length ]);
\r
7146 cert->san_length++;
\r
7148 cert->san_length = 0;
\r
7151 DEBUG_PRINT("\n");
\r
7154 if (__is_field(fields, pk_id)) {
\r
7159 DEBUG_PRINT("BITSTREAM(%i): ", length);
\r
7160 DEBUG_DUMP_HEX(&buffer[pos], length);
\r
7161 DEBUG_PRINT("\n");
\r
7162 if (__is_field(fields, sign_id)) {
\r
7163 tls_certificate_set_sign_key(cert, &buffer[pos], length);
\r
7165 if ((cert->ec_algorithm) && (__is_field(fields, pk_id))) {
\r
7166 tls_certificate_set_key(cert, &buffer[pos], length);
\r
7168 if ((buffer[pos] == 0x00) && (length > 256))
\r
7169 __private_asn1_parse(context, cert, &buffer[pos]+1, length - 1, level + 1, fields, &local_has_key, client_cert, top_oid, &local_chain);
\r
7171 __private_asn1_parse(context, cert, &buffer[pos], length, level + 1, fields, &local_has_key, client_cert, top_oid, &local_chain);
\r
7172 #ifdef TLS_FORWARD_SECRECY
\r
7173 #ifdef TLS_ECDSA_SUPPORTED
\r
7175 if (__is_oid2(top_oid, TLS_EC_prime256v1_OID, sizeof(oid), sizeof(TLS_EC_prime256v1) - 1)) {
\r
7176 cert->ec_algorithm = secp256r1.iana;
\r
7178 if (__is_oid2(top_oid, TLS_EC_secp224r1_OID, sizeof(oid), sizeof(TLS_EC_secp224r1_OID) - 1)) {
\r
7179 cert->ec_algorithm = secp224r1.iana;
\r
7181 if (__is_oid2(top_oid, TLS_EC_secp384r1_OID, sizeof(oid), sizeof(TLS_EC_secp384r1_OID) - 1)) {
\r
7182 cert->ec_algorithm = secp384r1.iana;
\r
7184 if (__is_oid2(top_oid, TLS_EC_secp521r1_OID, sizeof(oid), sizeof(TLS_EC_secp521r1_OID) - 1)) {
\r
7185 cert->ec_algorithm = secp521r1.iana;
\r
7187 if ((cert->ec_algorithm) && (!cert->pk))
\r
7188 tls_certificate_set_key(cert, &buffer[pos], length);
\r
7195 if ((top_oid) && (__is_field(fields, ecc_priv_id)) && (!cert->priv)) {
\r
7196 DEBUG_PRINT("BINARY STRING(%i): ", length);
\r
7197 DEBUG_DUMP_HEX(&buffer[pos], length);
\r
7198 DEBUG_PRINT("\n");
\r
7199 tls_certificate_set_priv(cert, &buffer[pos], length);
\r
7201 __private_asn1_parse(context, cert, &buffer[pos], length, level + 1, fields, &local_has_key, client_cert, top_oid, &local_chain);
\r
7204 DEBUG_PRINT("NULL\n");
\r
7207 // object identifier
\r
7208 if (__is_field(fields, pk_id)) {
\r
7209 #ifdef TLS_ECDSA_SUPPORTED
\r
7210 if ((length == 8) || (length == 5))
\r
7211 tls_certificate_set_algorithm(&cert->ec_algorithm, &buffer[pos], length);
\r
7214 tls_certificate_set_algorithm(&cert->key_algorithm, &buffer[pos], length);
\r
7216 if (__is_field(fields, algorithm_id))
\r
7217 tls_certificate_set_algorithm(&cert->algorithm, &buffer[pos], length);
\r
7219 DEBUG_PRINT("OBJECT IDENTIFIER(%i): ", length);
\r
7220 DEBUG_DUMP_HEX(&buffer[pos], length);
\r
7221 DEBUG_PRINT("\n");
\r
7222 // check previous oid
\r
7223 if (__is_oid2(oid, ocsp_oid, 16, sizeof(ocsp_oid) - 1))
\r
7224 tls_certificate_set_copy(&cert->ocsp, &buffer[pos], length);
\r
7227 memcpy(oid, &buffer[pos], length);
\r
7229 memcpy(oid, &buffer[pos], 16);
\r
7231 memcpy(top_oid, oid, 16);
\r
7234 DEBUG_PRINT("REAL NUMBER(%i): ", length);
\r
7235 DEBUG_DUMP_HEX(&buffer[pos], length);
\r
7236 DEBUG_PRINT("\n");
\r
7240 DEBUG_PRINT("UTC TIME: [");
\r
7241 DEBUG_DUMP(&buffer[pos], length);
\r
7242 DEBUG_PRINT("]\n");
\r
7244 if (__is_field(fields, validity_id)) {
\r
7246 tls_certificate_set_copy_date(&cert->not_before, &buffer[pos], length);
\r
7248 tls_certificate_set_copy_date(&cert->not_after, &buffer[pos], length);
\r
7252 // generalized time
\r
7253 DEBUG_PRINT("GENERALIZED TIME: [");
\r
7254 DEBUG_DUMP(&buffer[pos], length);
\r
7255 DEBUG_PRINT("]\n");
\r
7258 // printable string
\r
7269 if (__is_field(fields, issurer_id)) {
\r
7270 if (__is_oid(oid, country_oid, 3))
\r
7271 tls_certificate_set_copy(&cert->issuer_country, &buffer[pos], length);
\r
7273 if (__is_oid(oid, state_oid, 3))
\r
7274 tls_certificate_set_copy(&cert->issuer_state, &buffer[pos], length);
\r
7276 if (__is_oid(oid, location_oid, 3))
\r
7277 tls_certificate_set_copy(&cert->issuer_location, &buffer[pos], length);
\r
7279 if (__is_oid(oid, entity_oid, 3))
\r
7280 tls_certificate_set_copy(&cert->issuer_entity, &buffer[pos], length);
\r
7282 if (__is_oid(oid, subject_oid, 3))
\r
7283 tls_certificate_set_copy(&cert->issuer_subject, &buffer[pos], length);
\r
7285 if (__is_field(fields, owner_id)) {
\r
7286 if (__is_oid(oid, country_oid, 3))
\r
7287 tls_certificate_set_copy(&cert->country, &buffer[pos], length);
\r
7289 if (__is_oid(oid, state_oid, 3))
\r
7290 tls_certificate_set_copy(&cert->state, &buffer[pos], length);
\r
7292 if (__is_oid(oid, location_oid, 3))
\r
7293 tls_certificate_set_copy(&cert->location, &buffer[pos], length);
\r
7295 if (__is_oid(oid, entity_oid, 3))
\r
7296 tls_certificate_set_copy(&cert->entity, &buffer[pos], length);
\r
7298 if (__is_oid(oid, subject_oid, 3))
\r
7299 tls_certificate_set_copy(&cert->subject, &buffer[pos], length);
\r
7301 DEBUG_PRINT("STR: [");
\r
7302 DEBUG_DUMP(&buffer[pos], length);
\r
7303 DEBUG_PRINT("]\n");
\r
7306 DEBUG_PRINT("EMPTY SEQUENCE\n");
\r
7309 DEBUG_PRINT("ENUMERATED(%i): ", length);
\r
7310 DEBUG_DUMP_HEX(&buffer[pos], length);
\r
7311 DEBUG_PRINT("\n");
\r
7314 DEBUG_PRINT("========> NOT SUPPORTED %x\n", (int)type);
\r
7315 // not supported / needed
\r
7321 if ((level == 2) && (cert->sign_key) && (cert->sign_len) && (cert_len) && (cert_data)) {
\r
7322 TLS_FREE(cert->fingerprint);
\r
7323 cert->fingerprint = __private_tls_compute_hash(cert->algorithm, cert_data, cert_len);
\r
7325 if (cert->fingerprint) {
\r
7326 DEBUG_DUMP_HEX_LABEL("FINGERPRINT", cert->fingerprint, __private_tls_hash_len(cert->algorithm));
\r
7333 struct TLSCertificate *asn1_parse(struct TLSContext *context, const unsigned char *buffer, int size, int client_cert) {
\r
7334 unsigned int fields[__TLS_ASN1_MAXLEVEL];
\r
7335 memset(fields, 0, sizeof(int) * __TLS_ASN1_MAXLEVEL);
\r
7336 struct TLSCertificate *cert = tls_create_certificate();
\r
7338 if (client_cert < 0) {
\r
7341 unsigned char top_oid[16];
\r
7342 memset(top_oid, 0, sizeof(top_oid));
\r
7343 __private_asn1_parse(context, cert, buffer, size, 1, fields, NULL, client_cert, top_oid, NULL);
\r
7345 __private_asn1_parse(context, cert, buffer, size, 1, fields, NULL, client_cert, NULL, NULL);
\r
7350 int tls_load_certificates(struct TLSContext *context, const unsigned char *pem_buffer, int pem_size) {
\r
7352 return TLS_GENERIC_ERROR;
\r
7357 unsigned char *data = tls_pem_decode(pem_buffer, pem_size, idx++, &len);
\r
7358 if ((!data) || (!len))
\r
7360 struct TLSCertificate *cert = asn1_parse(context, data, len, 0);
\r
7362 if ((cert->version == 2)
\r
7363 #ifdef TLS_X509_V1_SUPPORT
\r
7364 || (cert->version == 0)
\r
7367 TLS_FREE(cert->der_bytes);
\r
7368 cert->der_bytes = data;
\r
7369 cert->der_len = len;
\r
7372 DEBUG_PRINT("WARNING - parse error (private key encountered in certificate)\n");
\r
7373 TLS_FREE(cert->priv);
\r
7374 cert->priv = NULL;
\r
7375 cert->priv_len = 0;
\r
7377 context->certificates = (struct TLSCertificate **)TLS_REALLOC(context->certificates, (context->certificates_count + 1) * sizeof(struct TLSCertificate));
\r
7378 context->certificates[context->certificates_count] = cert;
\r
7379 context->certificates_count++;
\r
7380 DEBUG_PRINT("Loaded certificate: %i\n", (int)context->certificates_count);
\r
7382 DEBUG_PRINT("WARNING - certificate version error (v%i)\n", (int)cert->version);
\r
7383 tls_destroy_certificate(cert);
\r
7388 return context->certificates_count;
\r
7391 int tls_load_private_key(struct TLSContext *context, const unsigned char *pem_buffer, int pem_size) {
\r
7393 return TLS_GENERIC_ERROR;
\r
7398 unsigned char *data = tls_pem_decode(pem_buffer, pem_size, idx++, &len);
\r
7399 if ((!data) || (!len))
\r
7401 struct TLSCertificate *cert = asn1_parse(context, data, len, -1);
\r
7403 if (!cert->der_len) {
\r
7404 TLS_FREE(cert->der_bytes);
\r
7405 cert->der_bytes = data;
\r
7406 cert->der_len = len;
\r
7409 if ((cert) && (cert->priv) && (cert->priv_len)) {
\r
7410 #ifdef TLS_ECDSA_SUPPORTED
\r
7411 if (cert->ec_algorithm) {
\r
7412 DEBUG_PRINT("Loaded ECC private key\n");
\r
7413 if (context->ec_private_key)
\r
7414 tls_destroy_certificate(context->ec_private_key);
\r
7415 context->ec_private_key = cert;
\r
7420 DEBUG_PRINT("Loaded private key\n");
\r
7421 if (context->private_key)
\r
7422 tls_destroy_certificate(context->private_key);
\r
7423 context->private_key = cert;
\r
7427 tls_destroy_certificate(cert);
\r
7434 int tls_clear_certificates(struct TLSContext *context) {
\r
7436 if ((!context) || (!context->is_server) || (context->is_child))
\r
7437 return TLS_GENERIC_ERROR;
\r
7439 if (context->root_certificates) {
\r
7440 for (i = 0; i < context->root_count; i++)
\r
7441 tls_destroy_certificate(context->root_certificates[i]);
\r
7443 context->root_certificates = NULL;
\r
7444 context->root_count = 0;
\r
7445 if (context->private_key)
\r
7446 tls_destroy_certificate(context->private_key);
\r
7447 context->private_key = NULL;
\r
7448 #ifdef TLS_ECDSA_SUPPORTED
\r
7449 if (context->ec_private_key)
\r
7450 tls_destroy_certificate(context->ec_private_key);
\r
7451 context->ec_private_key = NULL;
\r
7453 TLS_FREE(context->certificates);
\r
7454 context->certificates = NULL;
\r
7455 context->certificates_count = 0;
\r
7459 struct TLSPacket *tls_build_certificate(struct TLSContext *context) {
\r
7461 unsigned int all_certificate_size = 0;
\r
7462 int certificates_count;
\r
7463 struct TLSCertificate **certificates;
\r
7464 if (context->is_server) {
\r
7465 certificates_count = context->certificates_count;
\r
7466 certificates = context->certificates;
\r
7468 certificates_count = context->client_certificates_count;
\r
7469 certificates = context->client_certificates;
\r
7472 #ifdef TLS_ECDSA_SUPPORTED
\r
7473 int is_ecdsa = tls_is_ecdsa(context);
\r
7475 for (i = 0; i < certificates_count; i++) {
\r
7476 struct TLSCertificate *cert = certificates[i];
\r
7477 if ((cert) && (cert->der_len) && (cert->ec_algorithm))
\r
7478 all_certificate_size += cert->der_len + 3;
\r
7481 for (i = 0; i < certificates_count; i++) {
\r
7482 struct TLSCertificate *cert = certificates[i];
\r
7483 if ((cert) && (cert->der_len) && (!cert->ec_algorithm))
\r
7484 all_certificate_size += cert->der_len + 3;
\r
7488 for (i = 0; i < certificates_count; i++) {
\r
7489 struct TLSCertificate *cert = certificates[i];
\r
7490 if ((cert) && (cert->der_len))
\r
7491 all_certificate_size += cert->der_len + 3;
\r
7494 if (!all_certificate_size) {
\r
7495 DEBUG_PRINT("NO CERTIFICATE SET\n");
\r
7498 struct TLSPacket *packet = tls_create_packet(context, TLS_HANDSHAKE, context->version, 0);
\r
7499 tls_packet_uint8(packet, 0x0B);
\r
7500 if (all_certificate_size) {
\r
7501 tls_packet_uint24(packet, all_certificate_size + 3);
\r
7503 if (context->dtls)
\r
7504 __private_dtls_handshake_data(context, packet, all_certificate_size + 3);
\r
7506 tls_packet_uint24(packet, all_certificate_size);
\r
7507 for (i = 0; i < certificates_count; i++) {
\r
7508 struct TLSCertificate *cert = certificates[i];
\r
7509 if ((cert) && (cert->der_len)) {
\r
7510 #ifdef TLS_ECDSA_SUPPORTED
\r
7511 // is RSA certificate ?
\r
7512 if ((is_ecdsa) && (!cert->ec_algorithm))
\r
7514 // is ECC certificate ?
\r
7515 if ((!is_ecdsa) && (cert->ec_algorithm))
\r
7518 // 2 times -> one certificate
\r
7519 tls_packet_uint24(packet, cert->der_len);
\r
7520 tls_packet_append(packet, cert->der_bytes, cert->der_len);
\r
7524 tls_packet_uint24(packet, all_certificate_size);
\r
7525 if (context->dtls)
\r
7526 __private_dtls_handshake_data(context, packet, all_certificate_size);
\r
7528 tls_packet_update(packet);
\r
7529 if (context->dtls)
\r
7530 context->dtls_seq++;
\r
7534 struct TLSPacket *tls_build_finished(struct TLSContext *context) {
\r
7535 struct TLSPacket *packet = tls_create_packet(context, TLS_HANDSHAKE, context->version, __TLS_MIN_FINISHED_OPAQUE_LEN + 64);
\r
7536 tls_packet_uint8(packet, 0x14);
\r
7537 tls_packet_uint24(packet, __TLS_MIN_FINISHED_OPAQUE_LEN);
\r
7538 if (context->dtls)
\r
7539 __private_dtls_handshake_data(context, packet, __TLS_MIN_FINISHED_OPAQUE_LEN);
\r
7541 unsigned char hash[__TLS_MAX_HASH_SIZE];
\r
7542 unsigned char out[__TLS_MIN_FINISHED_OPAQUE_LEN];
\r
7543 unsigned int hash_len;
\r
7545 // server verifies client's message
\r
7546 if (context->is_server) {
\r
7547 hash_len = __private_tls_done_hash(context, hash);
\r
7548 __private_tls_prf(context, out, __TLS_MIN_FINISHED_OPAQUE_LEN, context->master_key, context->master_key_len, (unsigned char *)"server finished", 15, hash, hash_len, NULL, 0);
\r
7549 __private_tls_destroy_hash(context);
\r
7551 hash_len = __private_tls_get_hash(context, hash);
\r
7552 __private_tls_prf(context, out, __TLS_MIN_FINISHED_OPAQUE_LEN, context->master_key, context->master_key_len, (unsigned char *)"client finished", 15, hash, hash_len, NULL, 0);
\r
7554 tls_packet_append(packet, out, __TLS_MIN_FINISHED_OPAQUE_LEN);
\r
7555 tls_packet_update(packet);
\r
7556 DEBUG_DUMP_HEX_LABEL("VERIFY DATA", out, __TLS_MIN_FINISHED_OPAQUE_LEN);
\r
7557 #ifdef TLS_ACCEPT_SECURE_RENEGOTIATION
\r
7558 if (context->is_server) {
\r
7559 // concatenate client verify and server verify
\r
7560 context->verify_data = (unsigned char *)TLS_REALLOC(context->verify_data, __TLS_MIN_FINISHED_OPAQUE_LEN);
\r
7561 if (context->verify_data) {
\r
7562 memcpy(context->verify_data + context->verify_len, out, __TLS_MIN_FINISHED_OPAQUE_LEN);
\r
7563 context->verify_len += __TLS_MIN_FINISHED_OPAQUE_LEN;
\r
7565 context->verify_len = 0;
\r
7567 TLS_FREE(context->verify_data);
\r
7568 context->verify_data = (unsigned char *)TLS_MALLOC(__TLS_MIN_FINISHED_OPAQUE_LEN);
\r
7569 if (context->verify_data) {
\r
7570 memcpy(context->verify_data, out, __TLS_MIN_FINISHED_OPAQUE_LEN);
\r
7571 context->verify_len = __TLS_MIN_FINISHED_OPAQUE_LEN;
\r
7578 struct TLSPacket *tls_build_change_cipher_spec(struct TLSContext *context) {
\r
7579 struct TLSPacket *packet = tls_create_packet(context, TLS_CHANGE_CIPHER, context->version, 64);
\r
7580 tls_packet_uint8(packet, 1);
\r
7581 tls_packet_update(packet);
\r
7582 context->local_sequence_number = 0;
\r
7586 struct TLSPacket *tls_build_done(struct TLSContext *context) {
\r
7587 struct TLSPacket *packet = tls_create_packet(context, TLS_HANDSHAKE, context->version, 0);
\r
7588 tls_packet_uint8(packet, 0x0E);
\r
7589 tls_packet_uint24(packet, 0);
\r
7590 if (context->dtls) {
\r
7591 __private_dtls_handshake_data(context, packet, 0);
\r
7592 context->dtls_seq++;
\r
7594 tls_packet_update(packet);
\r
7598 struct TLSPacket *tls_build_message(struct TLSContext *context, const unsigned char *data, unsigned int len) {
\r
7599 if ((!data) || (!len))
\r
7601 struct TLSPacket *packet = tls_create_packet(context, TLS_APPLICATION_DATA, context->version, len);
\r
7602 tls_packet_append(packet, data, len);
\r
7603 tls_packet_update(packet);
\r
7607 int tls_client_connect(struct TLSContext *context) {
\r
7608 if ((context->is_server) || (context->critical_error))
\r
7609 return TLS_UNEXPECTED_MESSAGE;
\r
7611 return __private_tls_write_packet(tls_build_hello(context));
\r
7614 int tls_write(struct TLSContext *context, const unsigned char *data, unsigned int len) {
\r
7616 return TLS_GENERIC_ERROR;
\r
7617 if (context->connection_status != 0xFF)
\r
7618 return TLS_UNEXPECTED_MESSAGE;
\r
7619 if (len > __TLS_MAX_TLS_APP_SIZE)
\r
7620 len = __TLS_MAX_TLS_APP_SIZE;
\r
7621 int actually_written = __private_tls_write_packet(tls_build_message(context, data, len));
\r
7622 if (actually_written <= 0)
\r
7623 return actually_written;
\r
7627 struct TLSPacket *tls_build_alert(struct TLSContext *context, char critical, unsigned char code) {
\r
7628 struct TLSPacket *packet = tls_create_packet(context, TLS_ALERT, context->version, 0);
\r
7629 tls_packet_uint8(packet, critical ? TLS_ALERT_CRITICAL : TLS_ALERT_WARNING);
\r
7631 context->critical_error = 1;
\r
7632 tls_packet_uint8(packet, code);
\r
7633 tls_packet_update(packet);
\r
7637 int __private_tls_read_from_file(const char *fname, void *buf, int max_len) {
\r
7638 FILE *f = fopen(fname, "rb");
\r
7640 int size = fread(buf, 1, max_len, f);
\r
7647 int tls_consume_stream(struct TLSContext *context, const unsigned char *buf, int buf_len, tls_validation_function certificate_verify) {
\r
7649 return TLS_GENERIC_ERROR;
\r
7651 if (context->critical_error)
\r
7652 return TLS_BROKEN_CONNECTION;
\r
7654 if (buf_len <= 0) {
\r
7655 DEBUG_PRINT("tls_consume_stream called with buf_len %i\n", buf_len);
\r
7660 DEBUG_PRINT("tls_consume_stream called NULL buffer\n");
\r
7661 context->critical_error = 1;
\r
7662 return TLS_NO_MEMORY;
\r
7665 unsigned int orig_len = context->message_buffer_len;
\r
7666 context->message_buffer_len += buf_len;
\r
7667 context->message_buffer = (unsigned char *)TLS_REALLOC(context->message_buffer, context->message_buffer_len);
\r
7668 if (!context->message_buffer) {
\r
7669 context->message_buffer_len = 0;
\r
7670 return TLS_NO_MEMORY;
\r
7672 memcpy(context->message_buffer + orig_len, buf, buf_len);
\r
7673 unsigned int index = 0;
\r
7674 unsigned int tls_buffer_len = context->message_buffer_len;
\r
7677 int tls_header_size;
\r
7678 int tls_size_offset;
\r
7680 if (context->dtls) {
\r
7681 tls_size_offset = 11;
\r
7682 tls_header_size = 13;
\r
7684 tls_size_offset = 3;
\r
7685 tls_header_size = 5;
\r
7687 while (tls_buffer_len >= 5) {
\r
7688 unsigned int length = ntohs(*(unsigned short *)&context->message_buffer[index + tls_size_offset]) + tls_header_size;
\r
7689 if (length > tls_buffer_len) {
\r
7690 DEBUG_PRINT("NEED DATA: %i/%i\n", length, tls_buffer_len);
\r
7693 int consumed = tls_parse_message(context, &context->message_buffer[index], length, certificate_verify);
\r
7694 DEBUG_PRINT("Consumed %i bytes\n", consumed);
\r
7695 if (consumed < 0) {
\r
7696 if (!context->critical_error)
\r
7697 context->critical_error = 1;
\r
7698 err_flag = consumed;
\r
7702 tls_buffer_len -= length;
\r
7703 if (context->critical_error) {
\r
7704 err_flag = TLS_BROKEN_CONNECTION;
\r
7709 DEBUG_PRINT("ERROR IN CONSUME: %i\n", err_flag);
\r
7710 context->message_buffer_len = 0;
\r
7711 TLS_FREE(context->message_buffer);
\r
7712 context->message_buffer = NULL;
\r
7716 context->message_buffer_len -= index;
\r
7717 if (context->message_buffer_len) {
\r
7718 // no realloc here
\r
7719 memmove(context->message_buffer, context->message_buffer + index, context->message_buffer_len);
\r
7721 TLS_FREE(context->message_buffer);
\r
7722 context->message_buffer = NULL;
\r
7728 void tls_close_notify(struct TLSContext *context) {
\r
7729 if ((!context) || (context->critical_error))
\r
7731 context->critical_error = 1;
\r
7732 DEBUG_PRINT("CLOSE\n");
\r
7733 __private_tls_write_packet(tls_build_alert(context, 0, close_notify));
\r
7736 void tls_alert(struct TLSContext *context, unsigned char critical, int code) {
\r
7739 if ((!context->critical_error) && (critical))
\r
7740 context->critical_error = 1;
\r
7741 DEBUG_PRINT("ALERT\n");
\r
7742 __private_tls_write_packet(tls_build_alert(context, critical, code));
\r
7745 int tls_pending(struct TLSContext *context) {
\r
7746 if (!context->message_buffer)
\r
7748 return context->message_buffer_len;
\r
7751 void tls_make_exportable(struct TLSContext *context, unsigned char exportable_flag) {
\r
7752 context->exportable = exportable_flag;
\r
7753 if (!exportable_flag) {
\r
7754 // zero the memory
\r
7755 if ((context->exportable_keys) && (context->exportable_size))
\r
7756 memset(context->exportable_keys, 0, context->exportable_size);
\r
7757 // free the memory, if alocated
\r
7758 TLS_FREE(context->exportable_keys);
\r
7759 context->exportable_size = 0;
\r
7763 int tls_export_context(struct TLSContext *context, unsigned char *buffer, unsigned int buf_len, unsigned char small_version) {
\r
7764 // only negotiated AND exportable connections may be exported
\r
7765 if ((!context) || (context->critical_error) || (context->connection_status != 0xFF) || (!context->exportable) || (!context->exportable_keys) || (!context->exportable_size) || (!context->crypto.created)) {
\r
7766 DEBUG_PRINT("CANNOT EXPORT CONTEXT %i\n", (int)context->connection_status);
\r
7770 struct TLSPacket *packet = tls_create_packet(NULL, TLS_SERIALIZED_OBJECT, context->version, 0);
\r
7771 // export buffer version
\r
7772 tls_packet_uint8(packet, 0x01);
\r
7773 tls_packet_uint8(packet, context->connection_status);
\r
7774 tls_packet_uint16(packet, context->cipher);
\r
7775 if (context->is_child)
\r
7776 tls_packet_uint8(packet, 2);
\r
7778 tls_packet_uint8(packet, context->is_server);
\r
7780 if (context->crypto.created == 2) {
\r
7782 tls_packet_uint8(packet, __TLS_AES_GCM_IV_LENGTH);
\r
7783 tls_packet_append(packet, context->crypto.ctx_local_mac.local_aead_iv, __TLS_AES_GCM_IV_LENGTH);
\r
7784 tls_packet_append(packet, context->crypto.ctx_remote_mac.remote_aead_iv, __TLS_AES_GCM_IV_LENGTH);
\r
7785 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
7787 if (context->crypto.created == 3) {
\r
7789 tls_packet_uint8(packet, __TLS_CHACHA20_IV_LENGTH);
\r
7790 tls_packet_append(packet, context->crypto.ctx_local_mac.local_nonce, __TLS_CHACHA20_IV_LENGTH);
\r
7791 tls_packet_append(packet, context->crypto.ctx_remote_mac.remote_nonce, __TLS_CHACHA20_IV_LENGTH);
\r
7794 unsigned char iv[__TLS_AES_IV_LENGTH];
\r
7795 unsigned long len = __TLS_AES_IV_LENGTH;
\r
7797 memset(iv, 0, __TLS_AES_IV_LENGTH);
\r
7798 cbc_getiv(iv, &len, &context->crypto.ctx_local.aes_local);
\r
7799 tls_packet_uint8(packet, __TLS_AES_IV_LENGTH);
\r
7800 tls_packet_append(packet, iv, len);
\r
7802 memset(iv, 0, __TLS_AES_IV_LENGTH);
\r
7803 cbc_getiv(iv, &len, &context->crypto.ctx_remote.aes_remote);
\r
7804 tls_packet_append(packet, iv, __TLS_AES_IV_LENGTH);
\r
7807 tls_packet_uint8(packet, context->exportable_size);
\r
7808 tls_packet_append(packet, context->exportable_keys, context->exportable_size);
\r
7810 if (context->crypto.created == 2) {
\r
7811 tls_packet_uint8(packet, 0);
\r
7812 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
7814 if (context->crypto.created == 3) {
\r
7816 tls_packet_uint8(packet, 0);
\r
7818 for (i = 0; i < 16; i++)
\r
7819 tls_packet_uint32(packet, context->crypto.ctx_local.chacha_local.input[i]);
\r
7820 for (i = 0; i < 16; i++)
\r
7821 tls_packet_uint32(packet, context->crypto.ctx_remote.chacha_remote.input[i]);
\r
7822 tls_packet_append(packet, context->crypto.ctx_local.chacha_local.ks, CHACHA_BLOCKLEN);
\r
7823 tls_packet_append(packet, context->crypto.ctx_remote.chacha_remote.ks, CHACHA_BLOCKLEN);
\r
7826 unsigned char mac_length = (unsigned char)__private_tls_mac_length(context);
\r
7827 tls_packet_uint8(packet, mac_length);
\r
7828 tls_packet_append(packet, context->crypto.ctx_local_mac.local_mac, mac_length);
\r
7829 tls_packet_append(packet, context->crypto.ctx_remote_mac.remote_mac, mac_length);
\r
7832 if (small_version) {
\r
7833 tls_packet_uint16(packet, 0);
\r
7835 tls_packet_uint16(packet, context->master_key_len);
\r
7836 tls_packet_append(packet, context->master_key, context->master_key_len);
\r
7839 uint64_t sequence_number = htonll(context->local_sequence_number);
\r
7840 tls_packet_append(packet, (unsigned char *)&sequence_number, sizeof(uint64_t));
\r
7841 sequence_number = htonll(context->remote_sequence_number);
\r
7842 tls_packet_append(packet, (unsigned char *)&sequence_number, sizeof(uint64_t));
\r
7844 tls_packet_uint32(packet, context->tls_buffer_len);
\r
7845 tls_packet_append(packet, context->tls_buffer, context->tls_buffer_len);
\r
7847 tls_packet_uint32(packet, context->message_buffer_len);
\r
7848 tls_packet_append(packet, context->message_buffer, context->message_buffer_len);
\r
7850 tls_packet_uint32(packet, context->application_buffer_len);
\r
7851 tls_packet_append(packet, context->application_buffer, context->application_buffer_len);
\r
7852 tls_packet_uint8(packet, context->dtls);
\r
7853 if (context->dtls) {
\r
7854 tls_packet_uint16(packet, context->dtls_epoch_local);
\r
7855 tls_packet_uint16(packet, context->dtls_epoch_remote);
\r
7857 tls_packet_update(packet);
\r
7858 unsigned int size = packet->len;
\r
7859 if ((buffer) && (buf_len)) {
\r
7860 if (size > buf_len) {
\r
7861 tls_destroy_packet(packet);
\r
7862 DEBUG_PRINT("EXPORT BUFFER TO SMALL\n");
\r
7863 return (int)buf_len - (int)size;
\r
7865 memcpy(buffer, packet->buf, size);
\r
7867 tls_destroy_packet(packet);
\r
7871 struct TLSContext *tls_import_context(const unsigned char *buffer, unsigned int buf_len) {
\r
7872 if ((!buffer) || (buf_len < 64) || (buffer[0] != TLS_SERIALIZED_OBJECT) || (buffer[5] != 0x01)) {
\r
7873 DEBUG_PRINT("CANNOT IMPORT CONTEXT BUFFER\n");
\r
7876 // create a context object
\r
7877 struct TLSContext *context = tls_create_context(0, TLS_V12);
\r
7879 unsigned char temp[0xFF];
\r
7880 context->version = ntohs(*(unsigned short *)&buffer[1]);
\r
7881 unsigned short length = ntohs(*(unsigned short *)&buffer[3]);
\r
7882 if (length != buf_len - 5) {
\r
7883 DEBUG_PRINT("INVALID IMPORT BUFFER SIZE\n");
\r
7884 tls_destroy_context(context);
\r
7887 context->connection_status = buffer[6];
\r
7888 context->cipher = ntohs(*(unsigned short *)&buffer[7]);
\r
7889 unsigned char server = buffer[9];
\r
7890 if (server == 2) {
\r
7891 context->is_server = 1;
\r
7892 context->is_child = 1;
\r
7894 context->is_server = server;
\r
7896 unsigned char local_iv[__TLS_AES_IV_LENGTH];
\r
7897 unsigned char remote_iv[__TLS_AES_IV_LENGTH];
\r
7898 unsigned char iv_len = buffer[10];
\r
7899 if (iv_len > __TLS_AES_IV_LENGTH) {
\r
7900 DEBUG_PRINT("INVALID IV LENGTH\n");
\r
7901 tls_destroy_context(context);
\r
7905 // get the initialization vectors
\r
7907 memcpy(local_iv, &buffer[buf_pos], iv_len);
\r
7908 buf_pos += iv_len;
\r
7909 memcpy(remote_iv, &buffer[buf_pos], iv_len);
\r
7910 buf_pos += iv_len;
\r
7912 unsigned char key_lengths = buffer[buf_pos++];
\r
7913 TLS_IMPORT_CHECK_SIZE(buf_pos, key_lengths, buf_len)
\r
7914 memcpy(temp, &buffer[buf_pos], key_lengths);
\r
7915 buf_pos += key_lengths;
\r
7916 #ifdef TLS_REEXPORTABLE
\r
7917 context->exportable = 1;
\r
7918 context->exportable_keys = (unsigned char *)TLS_MALLOC(key_lengths);
\r
7919 memcpy(context->exportable_keys, temp, key_lengths);
\r
7920 context->exportable_size = key_lengths;
\r
7922 context->exportable = 0;
\r
7924 int is_aead = __private_tls_is_aead(context);
\r
7925 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
7926 if (is_aead == 2) {
\r
7928 if (iv_len > __TLS_CHACHA20_IV_LENGTH)
\r
7929 iv_len = __TLS_CHACHA20_IV_LENGTH;
\r
7930 memcpy(context->crypto.ctx_local_mac.local_nonce, local_iv, iv_len);
\r
7931 memcpy(context->crypto.ctx_remote_mac.remote_nonce, remote_iv, iv_len);
\r
7935 if (iv_len > __TLS_AES_GCM_IV_LENGTH)
\r
7936 iv_len = __TLS_AES_GCM_IV_LENGTH;
\r
7937 memcpy(context->crypto.ctx_local_mac.local_aead_iv, local_iv, iv_len);
\r
7938 memcpy(context->crypto.ctx_remote_mac.remote_aead_iv, remote_iv, iv_len);
\r
7940 if (context->is_server) {
\r
7941 if (__private_tls_crypto_create(context, key_lengths / 2, iv_len, temp, local_iv, temp + key_lengths / 2, remote_iv)) {
\r
7942 DEBUG_PRINT("ERROR CREATING KEY CONTEXT\n");
\r
7943 tls_destroy_context(context);
\r
7947 if (__private_tls_crypto_create(context, key_lengths / 2, iv_len, temp + key_lengths / 2, remote_iv, temp, local_iv)) {
\r
7948 DEBUG_PRINT("ERROR CREATING KEY CONTEXT (CLIENT)\n");
\r
7949 tls_destroy_context(context);
\r
7953 memset(temp, 0, sizeof(temp));
\r
7955 unsigned char mac_length = buffer[buf_pos++];
\r
7956 if (mac_length > __TLS_MAX_MAC_SIZE) {
\r
7957 DEBUG_PRINT("INVALID MAC SIZE\n");
\r
7958 tls_destroy_context(context);
\r
7963 TLS_IMPORT_CHECK_SIZE(buf_pos, mac_length, buf_len)
\r
7964 memcpy(context->crypto.ctx_local_mac.local_mac, &buffer[buf_pos], mac_length);
\r
7965 buf_pos += mac_length;
\r
7967 TLS_IMPORT_CHECK_SIZE(buf_pos, mac_length, buf_len)
\r
7968 memcpy(context->crypto.ctx_remote_mac.remote_mac, &buffer[buf_pos], mac_length);
\r
7969 buf_pos += mac_length;
\r
7971 #ifdef TLS_WITH_CHACHA20_POLY1305
\r
7972 if (is_aead == 2) {
\r
7975 TLS_IMPORT_CHECK_SIZE(buf_pos, 128 + CHACHA_BLOCKLEN * 2, buf_len)
\r
7976 for (i = 0; i < 16; i++) {
\r
7977 context->crypto.ctx_local.chacha_local.input[i] = ntohl(*(unsigned int *)&buffer[buf_pos]);
\r
7978 buf_pos += sizeof(unsigned int);
\r
7980 for (i = 0; i < 16; i++) {
\r
7981 context->crypto.ctx_remote.chacha_remote.input[i] = ntohl(*(unsigned int *)&buffer[buf_pos]);
\r
7982 buf_pos += sizeof(unsigned int);
\r
7984 memcpy(context->crypto.ctx_local.chacha_local.ks, &buffer[buf_pos], CHACHA_BLOCKLEN);
\r
7985 buf_pos += CHACHA_BLOCKLEN;
\r
7986 memcpy(context->crypto.ctx_remote.chacha_remote.ks, &buffer[buf_pos], CHACHA_BLOCKLEN);
\r
7987 buf_pos += CHACHA_BLOCKLEN;
\r
7991 TLS_IMPORT_CHECK_SIZE(buf_pos, 2, buf_len)
\r
7992 unsigned short master_key_len = ntohs(*(unsigned short *)&buffer[buf_pos]);
\r
7994 if (master_key_len) {
\r
7995 TLS_IMPORT_CHECK_SIZE(buf_pos, master_key_len, buf_len)
\r
7996 context->master_key = (unsigned char *)TLS_MALLOC(master_key_len);
\r
7997 if (context->master_key) {
\r
7998 memcpy(context->master_key, &buffer[buf_pos], master_key_len);
\r
7999 context->master_key_len = master_key_len;
\r
8001 buf_pos += master_key_len;
\r
8004 TLS_IMPORT_CHECK_SIZE(buf_pos, 16, buf_len)
\r
8006 context->local_sequence_number = ntohll(*(uint64_t *)&buffer[buf_pos]);
\r
8008 context->remote_sequence_number = ntohll(*(uint64_t *)&buffer[buf_pos]);
\r
8011 TLS_IMPORT_CHECK_SIZE(buf_pos, 4, buf_len)
\r
8012 unsigned int tls_buffer_len = ntohl(*(unsigned int *)&buffer[buf_pos]);
\r
8014 TLS_IMPORT_CHECK_SIZE(buf_pos, tls_buffer_len, buf_len)
\r
8015 if (tls_buffer_len) {
\r
8016 context->tls_buffer = (unsigned char *)TLS_MALLOC(tls_buffer_len);
\r
8017 if (context->tls_buffer) {
\r
8018 memcpy(context->tls_buffer, &buffer[buf_pos], tls_buffer_len);
\r
8019 context->tls_buffer_len = tls_buffer_len;
\r
8021 buf_pos += tls_buffer_len;
\r
8024 TLS_IMPORT_CHECK_SIZE(buf_pos, 4, buf_len)
\r
8025 unsigned int message_buffer_len = ntohl(*(unsigned int *)&buffer[buf_pos]);
\r
8027 TLS_IMPORT_CHECK_SIZE(buf_pos, message_buffer_len, buf_len)
\r
8028 if (message_buffer_len) {
\r
8029 context->message_buffer = (unsigned char *)TLS_MALLOC(message_buffer_len);
\r
8030 if (context->message_buffer) {
\r
8031 memcpy(context->message_buffer, &buffer[buf_pos], message_buffer_len);
\r
8032 context->message_buffer_len = message_buffer_len;
\r
8034 buf_pos += message_buffer_len;
\r
8037 TLS_IMPORT_CHECK_SIZE(buf_pos, 4, buf_len)
\r
8038 unsigned int application_buffer_len = ntohl(*(unsigned int *)&buffer[buf_pos]);
\r
8040 context->cipher_spec_set = 1;
\r
8041 TLS_IMPORT_CHECK_SIZE(buf_pos, application_buffer_len, buf_len)
\r
8042 if (application_buffer_len) {
\r
8043 context->application_buffer = (unsigned char *)TLS_MALLOC(application_buffer_len);
\r
8044 if (context->application_buffer) {
\r
8045 memcpy(context->application_buffer, &buffer[buf_pos], application_buffer_len);
\r
8046 context->application_buffer_len = application_buffer_len;
\r
8048 buf_pos += application_buffer_len;
\r
8050 TLS_IMPORT_CHECK_SIZE(buf_pos, 1, buf_len)
\r
8051 context->dtls = buffer[buf_pos];
\r
8053 if (context->dtls) {
\r
8054 TLS_IMPORT_CHECK_SIZE(buf_pos, 4, buf_len)
\r
8055 context->dtls_epoch_local = ntohs(*(unsigned short *)&buffer[buf_pos]);
\r
8057 context->dtls_epoch_remote = ntohs(*(unsigned short *)&buffer[buf_pos]);
\r
8063 int tls_is_broken(struct TLSContext *context) {
\r
8064 if ((!context) || (context->critical_error))
\r
8069 int tls_request_client_certificate(struct TLSContext *context) {
\r
8070 if ((!context) || (!context->is_server))
\r
8073 context->request_client_certificate = 1;
\r
8077 int tls_client_verified(struct TLSContext *context) {
\r
8078 if ((!context) || (context->critical_error))
\r
8081 return (context->client_verified == 1);
\r
8084 const char *tls_sni(struct TLSContext *context) {
\r
8087 return context->sni;
\r
8090 int tls_sni_set(struct TLSContext *context, const char *sni) {
\r
8091 if ((!context) || (context->is_server) || (context->critical_error) || (context->connection_status != 0))
\r
8093 TLS_FREE(context->sni);
\r
8094 context->sni = NULL;
\r
8096 int len = strlen(sni);
\r
8098 context->sni = (char *)TLS_MALLOC(len + 1);
\r
8099 if (context->sni) {
\r
8100 context->sni[len] = 0;
\r
8101 memcpy(context->sni, sni, len);
\r
8109 int tls_load_root_certificates(struct TLSContext *context, const unsigned char *pem_buffer, int pem_size) {
\r
8111 return TLS_GENERIC_ERROR;
\r
8117 unsigned char *data = tls_pem_decode(pem_buffer, pem_size, idx++, &len);
\r
8118 if ((!data) || (!len))
\r
8120 struct TLSCertificate *cert = asn1_parse(NULL, data, len, 0);
\r
8122 if (cert->version == 2) {
\r
8124 DEBUG_PRINT("WARNING - parse error (private key encountered in certificate)\n");
\r
8125 TLS_FREE(cert->priv);
\r
8126 cert->priv = NULL;
\r
8127 cert->priv_len = 0;
\r
8129 context->root_certificates = (struct TLSCertificate **)TLS_REALLOC(context->root_certificates, (context->root_count + 1) * sizeof(struct TLSCertificate));
\r
8130 if (!context->root_certificates) {
\r
8131 context->root_count = 0;
\r
8132 return TLS_GENERIC_ERROR;
\r
8134 context->root_certificates[context->root_count] = cert;
\r
8135 context->root_count++;
\r
8136 DEBUG_PRINT("Loaded certificate: %i\n", (int)context->root_count);
\r
8138 DEBUG_PRINT("WARNING - certificate version error (v%i)\n", (int)cert->version);
\r
8139 tls_destroy_certificate(cert);
\r
8144 return context->root_count;
\r
8147 int tls_default_verify(struct TLSContext *context, struct TLSCertificate **certificate_chain, int len) {
\r
8151 if (certificate_chain) {
\r
8152 for (i = 0; i < len; i++) {
\r
8153 struct TLSCertificate *certificate = certificate_chain[i];
\r
8154 // check validity date
\r
8155 err = tls_certificate_is_valid(certificate);
\r
8160 // check if chain is valid
\r
8161 err = tls_certificate_chain_is_valid(certificate_chain, len);
\r
8165 // check certificate subject
\r
8166 if ((!context->is_server) && (context->sni) && (len > 0) && (certificate_chain)) {
\r
8167 err = tls_certificate_valid_subject(certificate_chain[0], context->sni);
\r
8172 err = tls_certificate_chain_is_valid_root(context, certificate_chain, len);
\r
8176 DEBUG_PRINT("Certificate OK\n");
\r
8180 int tls_unmake_ktls(struct TLSContext *context, int socket) {
\r
8182 struct tls12_crypto_info_aes_gcm_128 crypto_info;
\r
8183 socklen_t crypt_info_size = sizeof(crypto_info);
\r
8184 if (getsockopt(socket, SOL_TLS, TLS_TX, &crypto_info, &crypt_info_size)) {
\r
8185 DEBUG_PRINT("ERROR IN getsockopt\n");
\r
8186 return TLS_GENERIC_ERROR;
\r
8188 memcpy(crypto_info.rec_seq, &context->local_sequence_number, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE);
\r
8189 context->local_sequence_number = ntohll(context->local_sequence_number);
\r
8191 crypt_info_size = sizeof(crypto_info);
\r
8192 if (getsockopt(socket, SOL_TLS, TLS_RX, &crypto_info, &crypt_info_size)) {
\r
8193 DEBUG_PRINT("ERROR IN getsockopt\n");
\r
8194 return TLS_GENERIC_ERROR;
\r
8196 memcpy(crypto_info.rec_seq, &context->remote_sequence_number, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE);
\r
8197 context->remote_sequence_number = ntohll(context->remote_sequence_number);
\r
8201 DEBUG_PRINT("TLSe COMPILED WITHOUT kTLS SUPPORT\n");
\r
8202 return TLS_FEATURE_NOT_SUPPORTED;
\r
8205 int tls_make_ktls(struct TLSContext *context, int socket) {
\r
8206 if ((!context) || (context->critical_error) || (context->connection_status != 0xFF) || (!context->crypto.created)) {
\r
8207 DEBUG_PRINT("CANNOT SWITCH TO kTLS\n");
\r
8208 return TLS_GENERIC_ERROR;
\r
8210 if ((!context->exportable) || (!context->exportable_keys)) {
\r
8211 DEBUG_PRINT("KEY MUST BE EXPORTABLE TO BE ABLE TO USE kTLS\n");
\r
8212 return TLS_GENERIC_ERROR;
\r
8214 if ((context->version != TLS_V12) && (context->version != DTLS_V12)) {
\r
8215 DEBUG_PRINT("kTLS IS SUPPORTED ONLY FOR TLS 1.2 AND DTLS 1.2\n");
\r
8216 return TLS_FEATURE_NOT_SUPPORTED;
\r
8218 switch (context->cipher) {
\r
8219 case TLS_RSA_WITH_AES_128_GCM_SHA256:
\r
8220 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
\r
8221 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
\r
8222 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
\r
8225 DEBUG_PRINT("CIPHER UNSUPPORTED: kTLS SUPPORTS ONLY AES 128 GCM CIPHERS\n");
\r
8226 return TLS_FEATURE_NOT_SUPPORTED;
\r
8229 if (context->exportable_size < TLS_CIPHER_AES_GCM_128_KEY_SIZE * 2) {
\r
8230 DEBUG_PRINT("INVALID KEY SIZE\n");
\r
8231 return TLS_GENERIC_ERROR;
\r
8233 struct tls12_crypto_info_aes_gcm_128 crypto_info;
\r
8235 crypto_info.info.version = TLS_1_2_VERSION;
\r
8236 crypto_info.info.cipher_type = TLS_CIPHER_AES_GCM_128;
\r
8238 uint64_t local_sequence_number = htonll(context->local_sequence_number);
\r
8239 memcpy(crypto_info.iv, &local_sequence_number, TLS_CIPHER_AES_GCM_128_IV_SIZE);
\r
8240 memcpy(crypto_info.rec_seq, &local_sequence_number, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE);
\r
8241 memcpy(crypto_info.key, context->exportable_keys, TLS_CIPHER_AES_GCM_128_KEY_SIZE);
\r
8242 memcpy(crypto_info.salt, context->crypto.ctx_local_mac.local_aead_iv, TLS_CIPHER_AES_GCM_128_SALT_SIZE);
\r
8244 setsockopt(socket, SOL_TCP, TCP_ULP, "tls", sizeof("tls"));
\r
8247 // kernel 4.17 adds TLS_RX support
\r
8248 struct tls12_crypto_info_aes_gcm_128 crypto_info_read;
\r
8250 crypto_info_read.info.version = TLS_1_2_VERSION;
\r
8251 crypto_info_read.info.cipher_type = TLS_CIPHER_AES_GCM_128;
\r
8253 uint64_t remote_sequence_number = htonll(context->remote_sequence_number);
\r
8254 memcpy(crypto_info_read.iv, &remote_sequence_number, TLS_CIPHER_AES_GCM_128_IV_SIZE);
\r
8255 memcpy(crypto_info_read.rec_seq, &remote_sequence_number, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE);
\r
8256 memcpy(crypto_info_read.key, context->exportable_keys + TLS_CIPHER_AES_GCM_128_KEY_SIZE, TLS_CIPHER_AES_GCM_128_KEY_SIZE);
\r
8257 memcpy(crypto_info_read.salt, context->crypto.ctx_remote_mac.remote_aead_iv, TLS_CIPHER_AES_GCM_128_SALT_SIZE);
\r
8259 int err = setsockopt(socket, SOL_TLS, TLS_RX, &crypto_info_read, sizeof(crypto_info_read));
\r
8263 return setsockopt(socket, SOL_TLS, TLS_TX, &crypto_info, sizeof(crypto_info));
\r
8265 DEBUG_PRINT("TLSe COMPILED WITHOUT kTLS SUPPORT\n");
\r
8266 return TLS_FEATURE_NOT_SUPPORTED;
\r
8271 void tls_print_certificate(const char *fname) {
\r
8272 unsigned char buf[0xFFFF];
\r
8273 char out_buf[0xFFFF];
\r
8274 int size = __private_tls_read_from_file(fname, buf, 0xFFFF);
\r
8279 unsigned char *data;
\r
8280 if (buf[0] == '-') {
\r
8281 data = tls_pem_decode(buf, size, idx++, &len);
\r
8286 if ((!data) || (!len))
\r
8288 struct TLSCertificate *cert = asn1_parse(NULL, data, len, -1);
\r
8292 fprintf(stderr, "%s", tls_certificate_to_string(cert, out_buf, 0xFFFF));
\r
8293 tls_destroy_certificate(cert);
\r
8302 #ifdef SSL_COMPATIBLE_INTERFACE
\r
8304 int SSL_library_init() {
\r
8309 void SSL_load_error_strings() {
\r
8313 void OpenSSL_add_all_algorithms() {
\r
8317 void OpenSSL_add_all_ciphers() {
\r
8321 void OpenSSL_add_all_digests() {
\r
8325 void EVP_cleanup() {
\r
8329 int __tls_ssl_private_send_pending(int client_sock, struct TLSContext *context) {
\r
8330 unsigned int out_buffer_len = 0;
\r
8331 const unsigned char *out_buffer = tls_get_write_buffer(context, &out_buffer_len);
\r
8332 unsigned int out_buffer_index = 0;
\r
8334 SOCKET_SEND_CALLBACK write_cb = NULL;
\r
8335 SSLUserData *ssl_data = (SSLUserData *)context->user_data;
\r
8337 write_cb = (SOCKET_SEND_CALLBACK)ssl_data->send;
\r
8338 while ((out_buffer) && (out_buffer_len > 0)) {
\r
8341 res = write_cb(client_sock, (char *)&out_buffer[out_buffer_index], out_buffer_len, 0);
\r
8343 res = send(client_sock, (char *)&out_buffer[out_buffer_index], out_buffer_len, 0);
\r
8348 out_buffer_len -= res;
\r
8349 out_buffer_index += res;
\r
8352 tls_buffer_clear(context);
\r
8356 struct TLSContext *SSL_new(struct TLSContext *context) {
\r
8357 return tls_accept(context);
\r
8360 int SSLv3_server_method() {
\r
8364 int SSLv3_client_method() {
\r
8368 int SSL_CTX_use_certificate_file(struct TLSContext *context, const char *filename, int dummy) {
\r
8370 unsigned char buf[0xFFFF];
\r
8371 int size = __private_tls_read_from_file(filename, buf, sizeof(buf));
\r
8373 return tls_load_certificates(context, buf, size);
\r
8377 int SSL_CTX_use_PrivateKey_file(struct TLSContext *context, const char *filename, int dummy) {
\r
8378 unsigned char buf[0xFFFF];
\r
8379 int size = __private_tls_read_from_file(filename, buf, sizeof(buf));
\r
8381 return tls_load_private_key(context, buf, size);
\r
8386 int SSL_CTX_check_private_key(struct TLSContext *context) {
\r
8387 if ((!context) || (((!context->private_key) || (!context->private_key->der_bytes) || (!context->private_key->der_len))
\r
8388 #ifdef TLS_ECDSA_SUPPORTED
\r
8389 && ((!context->ec_private_key) || (!context->ec_private_key->der_bytes) || (!context->ec_private_key->der_len))
\r
8396 struct TLSContext *SSL_CTX_new(int method) {
\r
8397 return tls_create_context(method, TLS_V12);
\r
8400 void SSL_free(struct TLSContext *context) {
\r
8402 TLS_FREE(context->user_data);
\r
8403 tls_destroy_context(context);
\r
8407 void SSL_CTX_free(struct TLSContext *context) {
\r
8408 SSL_free(context);
\r
8411 int SSL_get_error(struct TLSContext *context, int ret) {
\r
8413 return TLS_GENERIC_ERROR;
\r
8414 return context->critical_error;
\r
8417 int SSL_set_fd(struct TLSContext *context, int socket) {
\r
8419 return TLS_GENERIC_ERROR;
\r
8420 SSLUserData *ssl_data = (SSLUserData *)context->user_data;
\r
8422 ssl_data = (SSLUserData *)TLS_MALLOC(sizeof(SSLUserData));
\r
8424 return TLS_NO_MEMORY;
\r
8425 memset(ssl_data, 0, sizeof(SSLUserData));
\r
8426 context->user_data = ssl_data;
\r
8428 ssl_data->fd = socket;
\r
8432 void *SSL_set_userdata(struct TLSContext *context, void *data) {
\r
8435 SSLUserData *ssl_data = (SSLUserData *)context->user_data;
\r
8437 ssl_data = (SSLUserData *)TLS_MALLOC(sizeof(SSLUserData));
\r
8440 memset(ssl_data, 0, sizeof(SSLUserData));
\r
8441 context->user_data = ssl_data;
\r
8443 void *old_data = ssl_data->user_data;
\r
8444 ssl_data->user_data = data;
\r
8448 void *SSL_userdata(struct TLSContext *context) {
\r
8451 SSLUserData *ssl_data = (SSLUserData *)context->user_data;
\r
8455 return ssl_data->user_data;
\r
8458 int SSL_CTX_root_ca(struct TLSContext *context, const char *pem_filename) {
\r
8460 return TLS_GENERIC_ERROR;
\r
8462 int count = TLS_GENERIC_ERROR;
\r
8463 FILE *f = fopen(pem_filename, "rb");
\r
8465 fseek(f, 0, SEEK_END);
\r
8466 long size = ftell(f);
\r
8467 fseek(f, 0, SEEK_SET);
\r
8469 unsigned char *buf = (unsigned char *)TLS_MALLOC(size + 1);
\r
8472 if (fread(buf, 1, size, f) == size) {
\r
8473 count = tls_load_root_certificates(context, buf, size);
\r
8475 SSLUserData *ssl_data = (SSLUserData *)context->user_data;
\r
8477 ssl_data = (SSLUserData *)TLS_MALLOC(sizeof(SSLUserData));
\r
8479 return TLS_NO_MEMORY;
\r
8480 memset(ssl_data, 0, sizeof(SSLUserData));
\r
8481 context->user_data = ssl_data;
\r
8483 if (!ssl_data->certificate_verify)
\r
8484 ssl_data->certificate_verify = tls_default_verify;
\r
8494 void SSL_CTX_set_verify(struct TLSContext *context, int mode, tls_validation_function verify_callback) {
\r
8497 SSLUserData *ssl_data = (SSLUserData *)context->user_data;
\r
8499 ssl_data = (SSLUserData *)TLS_MALLOC(sizeof(SSLUserData));
\r
8502 memset(ssl_data, 0, sizeof(SSLUserData));
\r
8503 context->user_data = ssl_data;
\r
8505 if (mode == SSL_VERIFY_NONE)
\r
8506 ssl_data->certificate_verify = NULL;
\r
8508 ssl_data->certificate_verify = verify_callback;
\r
8511 int __private_tls_safe_read(struct TLSContext *context, void *buffer, int buf_size) {
\r
8512 SSLUserData *ssl_data = (SSLUserData *)context->user_data;
\r
8513 if ((!ssl_data) || (ssl_data->fd <= 0))
\r
8514 return TLS_GENERIC_ERROR;
\r
8516 SOCKET_RECV_CALLBACK read_cb = (SOCKET_RECV_CALLBACK)ssl_data->recv;
\r
8518 return read_cb(ssl_data->fd, (char *)buffer, buf_size, 0);
\r
8519 return recv(ssl_data->fd, (char *)buffer, buf_size, 0);
\r
8522 int SSL_accept(struct TLSContext *context) {
\r
8524 return TLS_GENERIC_ERROR;
\r
8525 SSLUserData *ssl_data = (SSLUserData *)context->user_data;
\r
8526 if ((!ssl_data) || (ssl_data->fd <= 0))
\r
8527 return TLS_GENERIC_ERROR;
\r
8528 if (tls_established(context))
\r
8530 unsigned char client_message[0xFFFF];
\r
8532 int read_size = 0;
\r
8533 while ((read_size = __private_tls_safe_read(context, (char *)client_message, sizeof(client_message))) > 0) {
\r
8534 if (tls_consume_stream(context, client_message, read_size, ssl_data->certificate_verify) >= 0) {
\r
8535 int res = __tls_ssl_private_send_pending(ssl_data->fd, context);
\r
8539 if (tls_established(context))
\r
8542 if (read_size <= 0)
\r
8543 return TLS_BROKEN_CONNECTION;
\r
8547 int SSL_connect(struct TLSContext *context) {
\r
8549 return TLS_GENERIC_ERROR;
\r
8550 SSLUserData *ssl_data = (SSLUserData *)context->user_data;
\r
8551 if ((!ssl_data) || (ssl_data->fd <= 0) || (context->critical_error))
\r
8552 return TLS_GENERIC_ERROR;
\r
8553 int res = tls_client_connect(context);
\r
8556 res = __tls_ssl_private_send_pending(ssl_data->fd, context);
\r
8561 unsigned char client_message[0xFFFF];
\r
8563 while ((read_size = __private_tls_safe_read(context, (char *)client_message, sizeof(client_message))) > 0) {
\r
8564 if (tls_consume_stream(context, client_message, read_size, ssl_data->certificate_verify) >= 0) {
\r
8565 res = __tls_ssl_private_send_pending(ssl_data->fd, context);
\r
8569 if (tls_established(context))
\r
8571 if (context->critical_error)
\r
8572 return TLS_GENERIC_ERROR;
\r
8577 int SSL_shutdown(struct TLSContext *context) {
\r
8579 return TLS_GENERIC_ERROR;
\r
8580 SSLUserData *ssl_data = (SSLUserData *)context->user_data;
\r
8581 if ((!ssl_data) || (ssl_data->fd <= 0))
\r
8582 return TLS_GENERIC_ERROR;
\r
8584 tls_close_notify(context);
\r
8588 int SSL_write(struct TLSContext *context, const void *buf, unsigned int len) {
\r
8590 return TLS_GENERIC_ERROR;
\r
8591 SSLUserData *ssl_data = (SSLUserData *)context->user_data;
\r
8592 if ((!ssl_data) || (ssl_data->fd <= 0))
\r
8593 return TLS_GENERIC_ERROR;
\r
8595 int written_size = tls_write(context, (const unsigned char *)buf, len);
\r
8596 if (written_size > 0) {
\r
8597 int res = __tls_ssl_private_send_pending(ssl_data->fd, context);
\r
8601 return written_size;
\r
8604 int SSL_read(struct TLSContext *context, void *buf, unsigned int len) {
\r
8606 return TLS_GENERIC_ERROR;
\r
8608 if (context->application_buffer_len)
\r
8609 return tls_read(context, (unsigned char *)buf, len);
\r
8611 SSLUserData *ssl_data = (SSLUserData *)context->user_data;
\r
8612 if ((!ssl_data) || (ssl_data->fd <= 0) || (context->critical_error))
\r
8613 return TLS_GENERIC_ERROR;
\r
8614 if (tls_established(context) != 1)
\r
8615 return TLS_GENERIC_ERROR;
\r
8617 if (!context->application_buffer_len) {
\r
8618 unsigned char client_message[0xFFFF];
\r
8621 while ((read_size = __private_tls_safe_read(context, (char *)client_message, sizeof(client_message))) > 0) {
\r
8622 if (tls_consume_stream(context, client_message, read_size, ssl_data->certificate_verify) > 0) {
\r
8623 __tls_ssl_private_send_pending(ssl_data->fd, context);
\r
8626 if ((context->critical_error) && (!context->application_buffer_len)) {
\r
8627 return TLS_GENERIC_ERROR;
\r
8630 if ((read_size <= 0) && (!context->application_buffer_len))
\r
8634 return tls_read(context, (unsigned char *)buf, len);
\r
8637 int SSL_pending(struct TLSContext *context) {
\r
8639 return TLS_GENERIC_ERROR;
\r
8640 return context->application_buffer_len;
\r
8643 int SSL_set_io(struct TLSContext *context, void *recv_cb, void *send_cb) {
\r
8645 return TLS_GENERIC_ERROR;
\r
8646 SSLUserData *ssl_data = (SSLUserData *)context->user_data;
\r
8648 ssl_data = (SSLUserData *)TLS_MALLOC(sizeof(SSLUserData));
\r
8650 return TLS_NO_MEMORY;
\r
8651 memset(ssl_data, 0, sizeof(SSLUserData));
\r
8652 context->user_data = ssl_data;
\r
8654 ssl_data->recv = recv_cb;
\r
8655 ssl_data->send = send_cb;
\r
8658 #endif // SSL_COMPATIBLE_INTERFACE
\r
8663 struct SRTPContext {
\r
8664 symmetric_CTR aes;
\r
8665 unsigned int salt[4];
\r
8666 unsigned char mac[__TLS_SHA1_MAC_SIZE];
\r
8667 unsigned int tag_size;
\r
8669 unsigned short seq;
\r
8671 unsigned char mode;
\r
8672 unsigned char auth_mode;
\r
8675 struct SRTPContext *srtp_init(unsigned char mode, unsigned char auth_mode) {
\r
8676 struct SRTPContext *context = NULL;
\r
8687 switch (auth_mode) {
\r
8688 case SRTP_AUTH_NULL:
\r
8690 case SRTP_AUTH_HMAC_SHA1:
\r
8695 context = (struct SRTPContext *)TLS_MALLOC(sizeof(struct SRTPContext));
\r
8697 memset(context, 0, sizeof(struct SRTPContext));
\r
8698 context->mode = mode;
\r
8699 context->auth_mode = auth_mode;
\r
8704 static int __private_tls_srtp_key_derive(const void *key, int keylen, const void *salt, unsigned char label, void *out, int outlen) {
\r
8705 unsigned char iv[16];
\r
8706 memcpy(iv, salt, 14);
\r
8707 iv[14] = iv[15] = 0;
\r
8708 void *in = TLS_MALLOC(outlen);
\r
8710 return TLS_GENERIC_ERROR;
\r
8711 memset(in, 0, outlen);
\r
8715 symmetric_CTR aes;
\r
8717 if (ctr_start(find_cipher("aes"), iv, (const unsigned char *)key, keylen, 0, CTR_COUNTER_BIG_ENDIAN, &aes))
\r
8718 return TLS_GENERIC_ERROR;
\r
8720 ctr_encrypt((unsigned char *)in, (unsigned char *)out, outlen, &aes);
\r
8726 int srtp_key(struct SRTPContext *context, const void *key, int keylen, const void *salt, int saltlen, int tag_bits) {
\r
8728 return TLS_GENERIC_ERROR;
\r
8729 if (context->mode == SRTP_AES_CM) {
\r
8730 if ((saltlen < 14) || (keylen < 16))
\r
8731 return TLS_GENERIC_ERROR;
\r
8733 unsigned char key_buf[16];
\r
8734 unsigned char iv[16];
\r
8736 memset(iv, 0, sizeof(iv));
\r
8738 if (__private_tls_srtp_key_derive(key, keylen, salt, 0, key_buf, sizeof(key_buf)))
\r
8739 return TLS_GENERIC_ERROR;
\r
8741 DEBUG_DUMP_HEX_LABEL("KEY", key_buf, 16)
\r
8743 if (__private_tls_srtp_key_derive(key, keylen, salt, 1, context->mac, 20))
\r
8744 return TLS_GENERIC_ERROR;
\r
8746 DEBUG_DUMP_HEX_LABEL("AUTH", context->mac, 20)
\r
8748 memset(context->salt, 0, sizeof(context->salt));
\r
8749 if (__private_tls_srtp_key_derive(key, keylen, salt, 2, context->salt, 14))
\r
8750 return TLS_GENERIC_ERROR;
\r
8752 DEBUG_DUMP_HEX_LABEL("SALT", ((unsigned char *)context->salt), 14)
\r
8754 if (ctr_start(find_cipher("aes"), iv, key_buf, sizeof(key_buf), 0, CTR_COUNTER_BIG_ENDIAN, &context->aes))
\r
8755 return TLS_GENERIC_ERROR;
\r
8757 if (context->auth_mode)
\r
8758 context->tag_size = tag_bits / 8;
\r
8762 int srtp_inline(struct SRTPContext *context, const char *b64, int tag_bits) {
\r
8763 char out_buffer[1024];
\r
8766 return TLS_GENERIC_ERROR;
\r
8768 int len = strlen(b64);
\r
8769 if (len >= sizeof(out_buffer))
\r
8770 len = sizeof(out_buffer);
\r
8771 int size = __private_b64_decode(b64, len, (unsigned char *)out_buffer);
\r
8773 return TLS_GENERIC_ERROR;
\r
8774 switch (context->mode) {
\r
8777 return TLS_BROKEN_PACKET;
\r
8778 return srtp_key(context, out_buffer, 16, out_buffer + 16, 14, tag_bits);
\r
8780 return TLS_GENERIC_ERROR;
\r
8783 int srtp_encrypt(struct SRTPContext *context, const unsigned char *pt_header, int pt_len, const unsigned char *payload, unsigned int payload_len, unsigned char *out, int *out_buffer_len) {
\r
8784 if ((!context) || (!out) || (!out_buffer_len) || (*out_buffer_len < payload_len))
\r
8785 return TLS_GENERIC_ERROR;
\r
8787 int out_len = payload_len;
\r
8789 unsigned short seq = 0;
\r
8790 unsigned int roc = context->roc;
\r
8791 unsigned int ssrc = 0;
\r
8793 if ((pt_header) && (pt_len >= 12)) {
\r
8794 seq = ntohs(*((unsigned short *)&pt_header[2]));
\r
8795 ssrc = ntohl(*((unsigned long *)&pt_header[8]));
\r
8798 if (seq < context->seq)
\r
8801 unsigned int roc_be = htonl(roc);
\r
8802 if (context->mode) {
\r
8803 if (*out_buffer_len < out_len)
\r
8804 return TLS_NO_MEMORY;
\r
8806 unsigned int counter[4];
\r
8807 counter[0] = context->salt[0];
\r
8808 counter[1] = context->salt[1] ^ htonl (ssrc);
\r
8809 counter[2] = context->salt[2] ^ roc_be;
\r
8810 counter[3] = context->salt[3] ^ htonl (seq << 16);
\r
8811 ctr_setiv((unsigned char *)&counter, 16, &context->aes);
\r
8812 if (ctr_encrypt(payload, out, payload_len, &context->aes))
\r
8813 return TLS_GENERIC_ERROR;
\r
8815 memcpy(out, payload, payload_len);
\r
8818 *out_buffer_len = out_len;
\r
8820 if (context->auth_mode == SRTP_AUTH_HMAC_SHA1) {
\r
8821 unsigned char digest_out[__TLS_SHA1_MAC_SIZE];
\r
8822 unsigned long dlen = __TLS_SHA1_MAC_SIZE;
\r
8824 int err = hmac_init(&hmac, find_hash("sha1"), context->mac, 20);
\r
8827 err = hmac_process(&hmac, pt_header, pt_len);
\r
8829 err = hmac_process(&hmac, out, payload_len);
\r
8830 err = hmac_process(&hmac, (unsigned char *)&roc_be, 4);
\r
8832 err = hmac_done(&hmac, digest_out, &dlen);
\r
8835 return TLS_GENERIC_ERROR;
\r
8836 if (dlen > context->tag_size)
\r
8837 dlen = context->tag_size;
\r
8839 *out_buffer_len += dlen;
\r
8840 memcpy(out + out_len, digest_out, dlen);
\r
8842 context->roc = roc;
\r
8843 context->seq = seq;
\r
8847 int srtp_decrypt(struct SRTPContext *context, const unsigned char *pt_header, int pt_len, const unsigned char *payload, unsigned int payload_len, unsigned char *out, int *out_buffer_len) {
\r
8848 if ((!context) || (!out) || (!out_buffer_len) || (*out_buffer_len < payload_len) || (payload_len < context->tag_size) || (!pt_header) || (pt_len < 12))
\r
8849 return TLS_GENERIC_ERROR;
\r
8851 int out_len = payload_len;
\r
8853 unsigned short seq = ntohs(*((unsigned short *)&pt_header[2]));
\r
8854 unsigned int roc = context->roc;
\r
8855 unsigned int ssrc = ntohl(*((unsigned long *)&pt_header[8]));
\r
8857 if (seq < context->seq)
\r
8860 unsigned int roc_be = htonl(roc);
\r
8861 if (context->mode) {
\r
8862 unsigned int counter[4];
\r
8863 counter[0] = context->salt[0];
\r
8864 counter[1] = context->salt[1] ^ htonl (ssrc);
\r
8865 counter[2] = context->salt[2] ^ roc_be;
\r
8866 counter[3] = context->salt[3] ^ htonl (seq << 16);
\r
8867 ctr_setiv((unsigned char *)&counter, 16, &context->aes);
\r
8869 if (ctr_decrypt(payload, out, payload_len - context->tag_size, &context->aes))
\r
8870 return TLS_GENERIC_ERROR;
\r
8872 if (context->auth_mode == SRTP_AUTH_HMAC_SHA1) {
\r
8873 unsigned char digest_out[__TLS_SHA1_MAC_SIZE];
\r
8874 unsigned long dlen = __TLS_SHA1_MAC_SIZE;
\r
8876 int err = hmac_init(&hmac, find_hash("sha1"), context->mac, 20);
\r
8879 err = hmac_process(&hmac, pt_header, pt_len);
\r
8881 err = hmac_process(&hmac, payload, payload_len - context->tag_size);
\r
8882 err = hmac_process(&hmac, (unsigned char *)&roc_be, 4);
\r
8884 err = hmac_done(&hmac, digest_out, &dlen);
\r
8887 return TLS_GENERIC_ERROR;
\r
8888 if (dlen > context->tag_size)
\r
8889 dlen = context->tag_size;
\r
8891 if (memcmp(digest_out, payload + payload_len - context->tag_size, dlen))
\r
8892 return TLS_INTEGRITY_FAILED;
\r
8895 memcpy(out, payload, payload_len - context->tag_size);
\r
8897 context->seq = seq;
\r
8898 context->roc = roc;
\r
8899 *out_buffer_len = payload_len - context->tag_size;
\r
8903 void srtp_destroy(struct SRTPContext *context) {
\r
8905 if (context->mode)
\r
8906 ctr_done(&context->aes);
\r
8907 TLS_FREE(context);
\r
8911 #endif // TLS_SRTP
\r