New basic implementation of Curve25519 (generic i15 code, experimental).
[BearSSL] / src / ssl / ssl_hs_client.t0
1 \ Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
2 \
3 \ Permission is hereby granted, free of charge, to any person obtaining
4 \ a copy of this software and associated documentation files (the
5 \ "Software"), to deal in the Software without restriction, including
6 \ without limitation the rights to use, copy, modify, merge, publish,
7 \ distribute, sublicense, and/or sell copies of the Software, and to
8 \ permit persons to whom the Software is furnished to do so, subject to
9 \ the following conditions:
10 \
11 \ The above copyright notice and this permission notice shall be
12 \ included in all copies or substantial portions of the Software.
13 \
14 \ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 \ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 \ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 \ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
18 \ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
19 \ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 \ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 \ SOFTWARE.
22
23 \ ----------------------------------------------------------------------
24 \ Handshake processing code, for the client.
25 \ The common T0 code (ssl_hs_common.t0) shall be read first.
26
27 preamble {
28
29 /*
30 * This macro evaluates to a pointer to the client context, under that
31 * specific name. It must be noted that since the engine context is the
32 * first field of the br_ssl_client_context structure ('eng'), then
33 * pointers values of both types are interchangeable, modulo an
34 * appropriate cast. This also means that "adresses" computed as offsets
35 * within the structure work for both kinds of context.
36 */
37 #define CTX ((br_ssl_client_context *)ENG)
38
39 /*
40 * Generate the pre-master secret for RSA key exchange, and encrypt it
41 * with the server's public key. Returned value is either the encrypted
42 * data length (in bytes), or -x on error, with 'x' being an error code.
43 *
44 * This code assumes that the public key has been already verified (it
45 * was properly obtained by the X.509 engine, and it has the right type,
46 * i.e. it is of type RSA and suitable for encryption).
47 */
48 static int
49 make_pms_rsa(br_ssl_client_context *ctx, int prf_id)
50 {
51 const br_x509_class **xc;
52 const br_x509_pkey *pk;
53 const unsigned char *n;
54 unsigned char *pms;
55 size_t nlen, u;
56
57 xc = ctx->eng.x509ctx;
58 pk = (*xc)->get_pkey(xc, NULL);
59
60 /*
61 * Compute actual RSA key length, in case there are leading zeros.
62 */
63 n = pk->key.rsa.n;
64 nlen = pk->key.rsa.nlen;
65 while (nlen > 0 && *n == 0) {
66 n ++;
67 nlen --;
68 }
69
70 /*
71 * We need at least 59 bytes (48 bytes for pre-master secret, and
72 * 11 bytes for the PKCS#1 type 2 padding). Note that the X.509
73 * minimal engine normally blocks RSA keys shorter than 128 bytes,
74 * so this is mostly for public keys provided explicitly by the
75 * caller.
76 */
77 if (nlen < 59) {
78 return -BR_ERR_X509_WEAK_PUBLIC_KEY;
79 }
80 if (nlen > sizeof ctx->eng.pad) {
81 return -BR_ERR_LIMIT_EXCEEDED;
82 }
83
84 /*
85 * Make PMS.
86 */
87 pms = ctx->eng.pad + nlen - 48;
88 br_enc16be(pms, ctx->eng.version_max);
89 br_hmac_drbg_generate(&ctx->eng.rng, pms + 2, 46);
90 br_ssl_engine_compute_master(&ctx->eng, prf_id, pms, 48);
91
92 /*
93 * Apply PKCS#1 type 2 padding.
94 */
95 ctx->eng.pad[0] = 0x00;
96 ctx->eng.pad[1] = 0x02;
97 ctx->eng.pad[nlen - 49] = 0x00;
98 br_hmac_drbg_generate(&ctx->eng.rng, ctx->eng.pad + 2, nlen - 51);
99 for (u = 2; u < nlen - 49; u ++) {
100 while (ctx->eng.pad[u] == 0) {
101 br_hmac_drbg_generate(&ctx->eng.rng,
102 &ctx->eng.pad[u], 1);
103 }
104 }
105
106 /*
107 * Compute RSA encryption.
108 */
109 if (!ctx->irsapub(ctx->eng.pad, nlen, &pk->key.rsa)) {
110 return -BR_ERR_LIMIT_EXCEEDED;
111 }
112 return (int)nlen;
113 }
114
115 /*
116 * OID for hash functions in RSA signatures.
117 */
118 static const unsigned char HASH_OID_SHA1[] = {
119 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A
120 };
121
122 static const unsigned char HASH_OID_SHA224[] = {
123 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04
124 };
125
126 static const unsigned char HASH_OID_SHA256[] = {
127 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01
128 };
129
130 static const unsigned char HASH_OID_SHA384[] = {
131 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02
132 };
133
134 static const unsigned char HASH_OID_SHA512[] = {
135 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03
136 };
137
138 static const unsigned char *HASH_OID[] = {
139 HASH_OID_SHA1,
140 HASH_OID_SHA224,
141 HASH_OID_SHA256,
142 HASH_OID_SHA384,
143 HASH_OID_SHA512
144 };
145
146 /*
147 * Check the RSA signature on the ServerKeyExchange message.
148 *
149 * hash hash function ID (2 to 6), or 0 for MD5+SHA-1 (with RSA only)
150 * use_rsa non-zero for RSA signature, zero for ECDSA
151 * sig_len signature length (in bytes); signature value is in the pad
152 *
153 * Returned value is 0 on success, or an error code.
154 */
155 static int
156 verify_SKE_sig(br_ssl_client_context *ctx,
157 int hash, int use_rsa, size_t sig_len)
158 {
159 const br_x509_class **xc;
160 const br_x509_pkey *pk;
161 br_multihash_context mhc;
162 unsigned char hv[64], head[4];
163 size_t hv_len;
164
165 xc = ctx->eng.x509ctx;
166 pk = (*xc)->get_pkey(xc, NULL);
167 br_multihash_zero(&mhc);
168 br_multihash_copyimpl(&mhc, &ctx->eng.mhash);
169 br_multihash_init(&mhc);
170 br_multihash_update(&mhc,
171 ctx->eng.client_random, sizeof ctx->eng.client_random);
172 br_multihash_update(&mhc,
173 ctx->eng.server_random, sizeof ctx->eng.server_random);
174 head[0] = 3;
175 head[1] = 0;
176 head[2] = ctx->eng.ecdhe_curve;
177 head[3] = ctx->eng.ecdhe_point_len;
178 br_multihash_update(&mhc, head, sizeof head);
179 br_multihash_update(&mhc,
180 ctx->eng.ecdhe_point, ctx->eng.ecdhe_point_len);
181 if (hash) {
182 hv_len = br_multihash_out(&mhc, hash, hv);
183 if (hv_len == 0) {
184 return BR_ERR_INVALID_ALGORITHM;
185 }
186 } else {
187 if (!br_multihash_out(&mhc, br_md5_ID, hv)
188 || !br_multihash_out(&mhc, br_sha1_ID, hv + 16))
189 {
190 return BR_ERR_INVALID_ALGORITHM;
191 }
192 hv_len = 36;
193 }
194 if (use_rsa) {
195 unsigned char tmp[64];
196 const unsigned char *hash_oid;
197
198 if (hash) {
199 hash_oid = HASH_OID[hash - 2];
200 } else {
201 hash_oid = NULL;
202 }
203 if (!ctx->eng.irsavrfy(ctx->eng.pad, sig_len,
204 hash_oid, hv_len, &pk->key.rsa, tmp)
205 || memcmp(tmp, hv, hv_len) != 0)
206 {
207 return BR_ERR_BAD_SIGNATURE;
208 }
209 } else {
210 if (!ctx->eng.iecdsa(ctx->eng.iec, hv, hv_len, &pk->key.ec,
211 ctx->eng.pad, sig_len))
212 {
213 return BR_ERR_BAD_SIGNATURE;
214 }
215 }
216 return 0;
217 }
218
219 /*
220 * Perform client-side ECDH (or ECDHE). The point that should be sent to
221 * the server is written in the pad; returned value is either the point
222 * length (in bytes), or -x on error, with 'x' being an error code.
223 *
224 * The point _from_ the server is taken from ecdhe_point[] if 'ecdhe'
225 * is non-zero, or from the X.509 engine context if 'ecdhe' is zero
226 * (for static ECDH).
227 */
228 static int
229 make_pms_ecdh(br_ssl_client_context *ctx, unsigned ecdhe, int prf_id)
230 {
231 int curve;
232 unsigned char key[66], point[133];
233 const unsigned char *order, *point_src;
234 size_t glen, olen, point_len;
235 unsigned char mask;
236
237 if (ecdhe) {
238 curve = ctx->eng.ecdhe_curve;
239 point_src = ctx->eng.ecdhe_point;
240 point_len = ctx->eng.ecdhe_point_len;
241 } else {
242 const br_x509_class **xc;
243 const br_x509_pkey *pk;
244
245 xc = ctx->eng.x509ctx;
246 pk = (*xc)->get_pkey(xc, NULL);
247 curve = pk->key.ec.curve;
248 point_src = pk->key.ec.q;
249 point_len = pk->key.ec.qlen;
250 }
251 if ((ctx->eng.iec->supported_curves & ((uint32_t)1 << curve)) == 0) {
252 return -BR_ERR_INVALID_ALGORITHM;
253 }
254
255 /*
256 * We need to generate our key, as a non-zero random value which
257 * is lower than the curve order, in a "large enough" range. We
258 * force top bit to 0 and bottom bit to 1, which guarantees that
259 * the value is in the proper range.
260 */
261 order = ctx->eng.iec->order(curve, &olen);
262 mask = 0xFF;
263 while (mask >= order[0]) {
264 mask >>= 1;
265 }
266 br_hmac_drbg_generate(&ctx->eng.rng, key, olen);
267 key[0] &= mask;
268 key[olen - 1] |= 0x01;
269
270 /*
271 * Compute the common ECDH point, whose X coordinate is the
272 * pre-master secret.
273 */
274 ctx->eng.iec->generator(curve, &glen);
275 if (glen != point_len) {
276 return -BR_ERR_INVALID_ALGORITHM;
277 }
278
279 memcpy(point, point_src, glen);
280 if (!ctx->eng.iec->mul(point, glen, key, olen, curve)) {
281 return -BR_ERR_INVALID_ALGORITHM;
282 }
283
284 /*
285 * The pre-master secret is the X coordinate.
286 */
287 br_ssl_engine_compute_master(&ctx->eng, prf_id, point + 1, glen >> 1);
288
289 ctx->eng.iec->mulgen(point, key, olen, curve);
290 memcpy(ctx->eng.pad, point, glen);
291 return (int)glen;
292 }
293
294 /*
295 * Perform full static ECDH. This occurs only in the context of client
296 * authentication with certificates: the server uses an EC public key,
297 * the cipher suite is of type ECDH (not ECDHE), the server requested a
298 * client certificate and accepts static ECDH, the client has a
299 * certificate with an EC public key in the same curve, and accepts
300 * static ECDH as well.
301 *
302 * Returned value is 0 on success, -1 on error.
303 */
304 static int
305 make_pms_static_ecdh(br_ssl_client_context *ctx, int prf_id)
306 {
307 unsigned char point[133];
308 size_t point_len;
309 const br_x509_class **xc;
310 const br_x509_pkey *pk;
311
312 xc = ctx->eng.x509ctx;
313 pk = (*xc)->get_pkey(xc, NULL);
314 point_len = pk->key.ec.qlen;
315 if (point_len > sizeof point) {
316 return -1;
317 }
318 memcpy(point, pk->key.ec.q, point_len);
319 if (!(*ctx->client_auth_vtable)->do_keyx(
320 ctx->client_auth_vtable, point, point_len))
321 {
322 return -1;
323 }
324 br_ssl_engine_compute_master(&ctx->eng,
325 prf_id, point + 1, point_len >> 1);
326 return 0;
327 }
328
329 /*
330 * Compute the client-side signature. This is invoked only when a
331 * signature-based client authentication was selected. The computed
332 * signature is in the pad; its length (in bytes) is returned. On
333 * error, 0 is returned.
334 */
335 static size_t
336 make_client_sign(br_ssl_client_context *ctx)
337 {
338 size_t hv_len;
339
340 /*
341 * Compute hash of handshake messages so far. This "cannot" fail
342 * because the list of supported hash functions provided to the
343 * client certificate handler was trimmed to include only the
344 * hash functions that the multi-hasher supports.
345 */
346 if (ctx->hash_id) {
347 hv_len = br_multihash_out(&ctx->eng.mhash,
348 ctx->hash_id, ctx->eng.pad);
349 } else {
350 br_multihash_out(&ctx->eng.mhash,
351 br_md5_ID, ctx->eng.pad);
352 br_multihash_out(&ctx->eng.mhash,
353 br_sha1_ID, ctx->eng.pad + 16);
354 hv_len = 36;
355 }
356 return (*ctx->client_auth_vtable)->do_sign(
357 ctx->client_auth_vtable, ctx->hash_id, hv_len,
358 ctx->eng.pad, sizeof ctx->eng.pad);
359 }
360
361 }
362
363 \ =======================================================================
364
365 : addr-ctx:
366 next-word { field }
367 "addr-" field + 0 1 define-word
368 0 8191 "offsetof(br_ssl_client_context, " field + ")" + make-CX
369 postpone literal postpone ; ;
370
371 addr-ctx: min_clienthello_len
372 addr-ctx: hashes
373 addr-ctx: auth_type
374 addr-ctx: hash_id
375
376 \ Length of the Secure Renegotiation extension. This is 5 for the
377 \ first handshake, 17 for a renegotiation (if the server supports the
378 \ extension), or 0 if we know that the server does not support the
379 \ extension.
380 : ext-reneg-length ( -- n )
381 addr-reneg get8 dup if 1 - 17 * else drop 5 then ;
382
383 \ Length of SNI extension.
384 : ext-sni-length ( -- len )
385 addr-server_name strlen dup if 9 + then ;
386
387 \ Length of Maximum Fragment Length extension.
388 : ext-frag-length ( -- len )
389 addr-log_max_frag_len get8 14 = if 0 else 5 then ;
390
391 \ Length of Signatures extension.
392 : ext-signatures-length ( -- len )
393 supported-hash-functions { x } drop
394 0
395 supports-rsa-sign? if x + then
396 supports-ecdsa? if x + then
397 dup if 1 << 6 + then ;
398
399 \ Write supported hash functions ( sign -- )
400 : write-hashes
401 { sign }
402 supported-hash-functions drop
403 \ We advertise hash functions in the following preference order:
404 \ SHA-256 SHA-224 SHA-384 SHA-512 SHA-1
405 \ Rationale:
406 \ -- SHA-256 and SHA-224 are more efficient on 32-bit architectures
407 \ -- SHA-1 is less than ideally collision-resistant
408 dup 0x10 and if 4 write8 sign write8 then
409 dup 0x08 and if 3 write8 sign write8 then
410 dup 0x20 and if 5 write8 sign write8 then
411 dup 0x40 and if 6 write8 sign write8 then
412 0x04 and if 2 write8 sign write8 then ;
413
414 \ Length of Supported Curves extension.
415 : ext-supported-curves-length ( -- len )
416 supported-curves dup if
417 0 { x }
418 begin dup while
419 dup 1 and x + >x
420 1 >>
421 repeat
422 drop x 1 << 6 +
423 then ;
424
425 \ Length of Supported Point Formats extension.
426 : ext-point-format-length ( -- len )
427 supported-curves if 6 else 0 then ;
428
429 \ Length of ALPN extension.
430 cc: ext-ALPN-length ( -- len ) {
431 size_t u, len;
432
433 if (ENG->protocol_names_num == 0) {
434 T0_PUSH(0);
435 T0_RET();
436 }
437 len = 6;
438 for (u = 0; u < ENG->protocol_names_num; u ++) {
439 len += 1 + strlen(ENG->protocol_names[u]);
440 }
441 T0_PUSH(len);
442 }
443
444 \ Write handshake message: ClientHello
445 : write-ClientHello ( -- )
446 { ; total-ext-length }
447
448 \ Compute length for extensions (without the general two-byte header).
449 \ This does not take padding extension into account.
450 ext-reneg-length ext-sni-length + ext-frag-length +
451 ext-signatures-length +
452 ext-supported-curves-length + ext-point-format-length +
453 ext-ALPN-length +
454 >total-ext-length
455
456 \ ClientHello type
457 1 write8
458
459 \ Compute and write length
460 39 addr-session_id_len get8 + addr-suites_num get8 1 << +
461 total-ext-length if 2+ total-ext-length + then
462 \ Compute padding (if requested).
463 addr-min_clienthello_len get16 over - dup 0> if
464 \ We well add a Pad ClientHello extension, which has its
465 \ own header (4 bytes) and might be the only extension
466 \ (2 extra bytes for the extension list header).
467 total-ext-length ifnot swap 2+ swap 2- then
468 \ Account for the extension header.
469 4 - dup 0< if drop 0 then
470 \ Adjust total extension length.
471 dup 4 + total-ext-length + >total-ext-length
472 \ Adjust ClientHello length.
473 swap 4 + over + swap
474 else
475 drop
476 -1
477 then
478 { ext-padding-amount }
479 write24
480
481 \ Protocol version
482 addr-version_max get16 write16
483
484 \ Client random
485 addr-client_random 4 bzero
486 addr-client_random 4 + 28 mkrand
487 addr-client_random 32 write-blob
488
489 \ Session ID
490 addr-session_id addr-session_id_len get8 write-blob-head8
491
492 \ Supported cipher suites. We also check here that we indeed
493 \ support all these suites.
494 addr-suites_num get8 dup 1 << write16
495 addr-suites_buf swap
496 begin
497 dup while 1-
498 over get16
499 dup suite-supported? ifnot ERR_BAD_CIPHER_SUITE fail then
500 write16
501 swap 2+ swap
502 repeat
503 2drop
504
505 \ Compression methods (only "null" compression)
506 1 write8 0 write8
507
508 \ Extensions
509 total-ext-length if
510 total-ext-length write16
511 ext-reneg-length if
512 0xFF01 write16 \ extension type (0xFF01)
513 addr-saved_finished
514 ext-reneg-length 4 - dup write16 \ extension length
515 1- write-blob-head8 \ verify data
516 then
517 ext-sni-length if
518 0x0000 write16 \ extension type (0)
519 addr-server_name
520 ext-sni-length 4 - dup write16 \ extension length
521 2 - dup write16 \ ServerNameList length
522 0 write8 \ name type: host_name
523 3 - write-blob-head16 \ the name itself
524 then
525 ext-frag-length if
526 0x0001 write16 \ extension type (1)
527 0x0001 write16 \ extension length
528 addr-log_max_frag_len get8 8 - write8
529 then
530 ext-signatures-length if
531 0x000D write16 \ extension type (13)
532 ext-signatures-length 4 - dup write16 \ extension length
533 2 - write16 \ list length
534 supports-ecdsa? if 3 write-hashes then
535 supports-rsa-sign? if 1 write-hashes then
536 then
537 \ TODO: add an API to specify preference order for curves.
538 \ Right now we use increasing id order, which makes P-256
539 \ the preferred curve.
540 ext-supported-curves-length dup if
541 0x000A write16 \ extension type (10)
542 4 - dup write16 \ extension length
543 2- write16 \ list length
544 supported-curves 0
545 begin dup 32 < while
546 dup2 >> 1 and if dup write16 then
547 1+
548 repeat
549 2drop
550 else
551 drop
552 then
553 ext-point-format-length if
554 0x000B write16 \ extension type (11)
555 0x0002 write16 \ extension length
556 0x0100 write16 \ value: 1 format: uncompressed
557 then
558 ext-ALPN-length dup if
559 0x0010 write16 \ extension type (16)
560 4 - dup write16 \ extension length
561 2- write16 \ list length
562 addr-protocol_names_num get16 0
563 begin
564 dup2 > while
565 dup copy-protocol-name
566 dup write8 addr-pad swap write-blob
567 1+
568 repeat
569 2drop
570 else
571 drop
572 then
573 ext-padding-amount 0< ifnot
574 0x0015 write16 \ extension value (21)
575 ext-padding-amount
576 dup write16 \ extension length
577 begin dup while
578 1- 0 write8 repeat \ value (only zeros)
579 drop
580 then
581 then
582 ;
583
584 \ =======================================================================
585
586 \ Parse server SNI extension. If present, then it should be empty.
587 : read-server-sni ( lim -- lim )
588 read16 if ERR_BAD_SNI fail then ;
589
590 \ Parse server Max Fragment Length extension. If present, then it should
591 \ advertise the same length as the client. Note that whether the server
592 \ sends it or not changes nothing for us: we won't send any record larger
593 \ than the advertised value anyway, and we will accept incoming records
594 \ up to our input buffer length.
595 : read-server-frag ( lim -- lim )
596 read16 1 = ifnot ERR_BAD_FRAGLEN fail then
597 read8 8 + addr-log_max_frag_len get8 = ifnot ERR_BAD_FRAGLEN fail then ;
598
599 \ Parse server Secure Renegotiation extension. This is called only if
600 \ the client sent that extension, so we only have two cases to
601 \ distinguish: first handshake, and renegotiation; in the latter case,
602 \ we know that the server supports the extension, otherwise the client
603 \ would not have sent it.
604 : read-server-reneg ( lim -- lim )
605 read16
606 addr-reneg get8 ifnot
607 \ "reneg" is 0, so this is a first handshake. The server's
608 \ extension MUST be empty. We also learn that the server
609 \ supports the extension.
610 1 = ifnot ERR_BAD_SECRENEG fail then
611 read8 0 = ifnot ERR_BAD_SECRENEG fail then
612 2 addr-reneg set8
613 else
614 \ "reneg" is non-zero, and we sent an extension, so it must
615 \ be 2 and this is a renegotiation. We must verify that
616 \ the extension contents have length exactly 24 bytes and
617 \ match the saved client and server "Finished".
618 25 = ifnot ERR_BAD_SECRENEG fail then
619 read8 24 = ifnot ERR_BAD_SECRENEG fail then
620 addr-pad 24 read-blob
621 addr-saved_finished addr-pad 24 memcmp ifnot
622 ERR_BAD_SECRENEG fail
623 then
624 then ;
625
626 \ Read the ALPN extension from the server. It must contain a single name,
627 \ and that name must match one of our names.
628 : read-ALPN-from-server ( lim -- lim )
629 \ Extension contents length.
630 read16 open-elt
631 \ Length of list of names.
632 read16 open-elt
633 \ There should be a single name.
634 read8 addr-pad swap dup { len } read-blob
635 close-elt
636 close-elt
637 len test-protocol-name dup 0< if
638 3 flag? if ERR_UNEXPECTED fail then
639 drop
640 else
641 1+ addr-selected_protocol set16
642 then ;
643
644 \ Save a value in a 16-bit field, or check it in case of session resumption.
645 : check-resume ( val addr resume -- )
646 if get16 = ifnot ERR_RESUME_MISMATCH fail then else set16 then ;
647
648 cc: DEBUG-BLOB ( addr len -- ) {
649 extern int printf(const char *fmt, ...);
650
651 size_t len = T0_POP();
652 unsigned char *buf = (unsigned char *)CTX + T0_POP();
653 size_t u;
654
655 printf("BLOB:");
656 for (u = 0; u < len; u ++) {
657 if (u % 16 == 0) {
658 printf("\n ");
659 }
660 printf(" %02x", buf[u]);
661 }
662 printf("\n");
663 }
664
665 \ Parse incoming ServerHello. Returned value is true (-1) on session
666 \ resumption.
667 : read-ServerHello ( -- bool )
668 \ Get header, and check message type.
669 read-handshake-header 2 = ifnot ERR_UNEXPECTED fail then
670
671 \ Get protocol version.
672 read16 { version }
673 version addr-version_min get16 < version addr-version_max get16 > or if
674 ERR_UNSUPPORTED_VERSION fail
675 then
676
677 \ Enforce chosen version for subsequent records in both directions.
678 version addr-version_in get16 <> if ERR_BAD_VERSION fail then
679 version addr-version_out set16
680
681 \ Server random.
682 addr-server_random 32 read-blob
683
684 \ The "session resumption" flag.
685 0 { resume }
686
687 \ Session ID.
688 read8 { idlen }
689 idlen 32 > if ERR_OVERSIZED_ID fail then
690 addr-pad idlen read-blob
691 idlen addr-session_id_len get8 = idlen 0 > and if
692 addr-session_id addr-pad idlen memcmp if
693 \ Server session ID is non-empty and matches what
694 \ we sent, so this is a session resumption.
695 -1 >resume
696 then
697 then
698 addr-session_id addr-pad idlen memcpy
699 idlen addr-session_id_len set8
700
701 \ Record version.
702 version addr-version resume check-resume
703
704 \ Cipher suite. We check that it is part of the list of cipher
705 \ suites that we advertised.
706 \ read16 { suite ; found }
707 \ 0 >found
708 \ addr-suites_buf dup addr-suites_num get8 1 << +
709 \ begin dup2 < while
710 \ 2 - dup get16
711 \ suite = found or >found
712 \ repeat
713 \ 2drop found ifnot ERR_BAD_CIPHER_SUITE fail then
714 read16
715 dup scan-suite 0< if ERR_BAD_CIPHER_SUITE fail then
716 addr-cipher_suite resume check-resume
717
718 \ Compression method. Should be 0 (no compression).
719 read8 if ERR_BAD_COMPRESSION fail then
720
721 \ Parse extensions (if any). If there is no extension, then the
722 \ read limit (on the TOS) should be 0 at that point.
723 dup if
724 \ Length of extension list.
725 \ message size.
726 read16 open-elt
727
728 \ Enumerate extensions. For each of them, check that we
729 \ sent an extension of that type, and did not see it
730 \ yet; and then process it.
731 ext-sni-length { ok-sni }
732 ext-reneg-length { ok-reneg }
733 ext-frag-length { ok-frag }
734 ext-signatures-length { ok-signatures }
735 ext-supported-curves-length { ok-curves }
736 ext-point-format-length { ok-points }
737 ext-ALPN-length { ok-ALPN }
738 begin dup while
739 read16
740 case
741 \ Server Name Indication. The server may
742 \ send such an extension if it uses the SNI
743 \ from the client, but that "response
744 \ extension" is supposed to be empty.
745 0x0000 of
746 ok-sni ifnot
747 ERR_EXTRA_EXTENSION fail
748 then
749 0 >ok-sni
750 read-server-sni
751 endof
752
753 \ Max Frag Length. The contents shall be
754 \ a single byte whose value matches the one
755 \ sent by the client.
756 0x0001 of
757 ok-frag ifnot
758 ERR_EXTRA_EXTENSION fail
759 then
760 0 >ok-frag
761 read-server-frag
762 endof
763
764 \ Secure Renegotiation.
765 0xFF01 of
766 ok-reneg ifnot
767 ERR_EXTRA_EXTENSION fail
768 then
769 0 >ok-reneg
770 read-server-reneg
771 endof
772
773 \ Signature Algorithms.
774 \ Normally, the server should never send this
775 \ extension (so says RFC 5246 #7.4.1.4.1),
776 \ but some existing servers do.
777 0x000D of
778 ok-signatures ifnot
779 ERR_EXTRA_EXTENSION fail
780 then
781 0 >ok-signatures
782 read-ignore-16
783 endof
784
785 \ Supported Curves.
786 0x000A of
787 ok-curves ifnot
788 ERR_EXTRA_EXTENSION fail
789 then
790 0 >ok-curves
791 read-ignore-16
792 endof
793
794 \ Supported Point Formats.
795 0x000B of
796 ok-points ifnot
797 ERR_EXTRA_EXTENSION fail
798 then
799 0 >ok-points
800 read-ignore-16
801 endof
802
803 \ ALPN.
804 0x0010 of
805 ok-ALPN ifnot
806 ERR_EXTRA_EXTENSION fail
807 then
808 0 >ok-ALPN
809 read-ALPN-from-server
810 endof
811
812 ERR_EXTRA_EXTENSION fail
813 endcase
814 repeat
815
816 \ If we sent a secure renegotiation extension but did not
817 \ receive a response, then the server does not support
818 \ secure renegotiation. This is a hard failure if this
819 \ is a renegotiation.
820 ok-reneg if
821 ok-reneg 5 > if ERR_BAD_SECRENEG fail then
822 1 addr-reneg set8
823 then
824 close-elt
825 then
826 close-elt
827 resume
828 ;
829
830 cc: set-server-curve ( -- ) {
831 const br_x509_class *xc;
832 const br_x509_pkey *pk;
833
834 xc = *(ENG->x509ctx);
835 pk = xc->get_pkey(ENG->x509ctx, NULL);
836 CTX->server_curve =
837 (pk->key_type == BR_KEYTYPE_EC) ? pk->key.ec.curve : 0;
838 }
839
840 \ Read Certificate message from server.
841 : read-Certificate-from-server ( -- )
842 addr-cipher_suite get16 expected-key-type
843 -1 read-Certificate
844 dup 0< if neg fail then
845 dup ifnot ERR_UNEXPECTED fail then
846 over and <> if ERR_WRONG_KEY_USAGE fail then
847
848 \ Set server curve (used for static ECDH).
849 set-server-curve ;
850
851 \ Verify signature on ECDHE point sent by the server.
852 \ 'hash' is the hash function to use (1 to 6, or 0 for RSA with MD5+SHA-1)
853 \ 'use-rsa' is 0 for ECDSA, -1 for for RSA
854 \ 'sig-len' is the signature length (in bytes)
855 \ The signature itself is in the pad.
856 cc: verify-SKE-sig ( hash use-rsa sig-len -- err ) {
857 size_t sig_len = T0_POP();
858 int use_rsa = T0_POPi();
859 int hash = T0_POPi();
860
861 T0_PUSH(verify_SKE_sig(CTX, hash, use_rsa, sig_len));
862 }
863
864 \ Parse ServerKeyExchange
865 : read-ServerKeyExchange ( -- )
866 \ Get header, and check message type.
867 read-handshake-header 12 = ifnot ERR_UNEXPECTED fail then
868
869 \ We expect a named curve, and we must support it.
870 read8 3 = ifnot ERR_INVALID_ALGORITHM fail then
871 read16 dup addr-ecdhe_curve set8
872 dup 32 >= if ERR_INVALID_ALGORITHM fail then
873 supported-curves swap >> 1 and ifnot ERR_INVALID_ALGORITHM fail then
874
875 \ Read the server point.
876 read8
877 dup 133 > if ERR_INVALID_ALGORITHM fail then
878 dup addr-ecdhe_point_len set8
879 addr-ecdhe_point swap read-blob
880
881 \ If using TLS-1.2+, then the hash function and signature algorithm
882 \ are explicitly provided; the signature algorithm must match what
883 \ the cipher suite specifies. With TLS-1.0 and 1.1, the signature
884 \ algorithm is inferred from the cipher suite, and the hash is
885 \ either MD5+SHA-1 (for RSA signatures) or SHA-1 (for ECDSA).
886 addr-version get16 0x0303 >= { tls1.2+ }
887 addr-cipher_suite get16 use-rsa-ecdhe? { use-rsa }
888 2 { hash }
889 tls1.2+ if
890 \ Read hash function; accept only the SHA-* identifiers
891 \ (from SHA-1 to SHA-512, no MD5 here).
892 read8
893 dup dup 2 < swap 6 > or if ERR_INVALID_ALGORITHM fail then
894 >hash
895 read8
896 \ Get expected signature algorithm and compare with what
897 \ the server just sent. Expected value is 1 for RSA, 3
898 \ for ECDSA. Note that 'use-rsa' evaluates to -1 for RSA,
899 \ 0 for ECDSA.
900 use-rsa 1 << 3 + = ifnot ERR_INVALID_ALGORITHM fail then
901 else
902 \ For MD5+SHA-1, we set 'hash' to 0.
903 use-rsa if 0 >hash then
904 then
905
906 \ Read signature into the pad.
907 read16 dup { sig-len }
908
909 dup 512 > if ERR_LIMIT_EXCEEDED fail then
910 addr-pad swap read-blob
911
912 \ Verify signature.
913 hash use-rsa sig-len verify-SKE-sig
914 dup if fail then drop
915
916 close-elt ;
917
918 \ Client certificate: start processing of anchor names.
919 cc: anchor-dn-start-name-list ( -- ) {
920 if (CTX->client_auth_vtable != NULL) {
921 (*CTX->client_auth_vtable)->start_name_list(
922 CTX->client_auth_vtable);
923 }
924 }
925
926 \ Client certificate: start a new anchor DN (length is 16-bit).
927 cc: anchor-dn-start-name ( length -- ) {
928 size_t len;
929
930 len = T0_POP();
931 if (CTX->client_auth_vtable != NULL) {
932 (*CTX->client_auth_vtable)->start_name(
933 CTX->client_auth_vtable, len);
934 }
935 }
936
937 \ Client certificate: push some data for current anchor DN.
938 cc: anchor-dn-append-name ( length -- ) {
939 size_t len;
940
941 len = T0_POP();
942 if (CTX->client_auth_vtable != NULL) {
943 (*CTX->client_auth_vtable)->append_name(
944 CTX->client_auth_vtable, ENG->pad, len);
945 }
946 }
947
948 \ Client certificate: end current anchor DN.
949 cc: anchor-dn-end-name ( -- ) {
950 if (CTX->client_auth_vtable != NULL) {
951 (*CTX->client_auth_vtable)->end_name(
952 CTX->client_auth_vtable);
953 }
954 }
955
956 \ Client certificate: end list of anchor DN.
957 cc: anchor-dn-end-name-list ( -- ) {
958 if (CTX->client_auth_vtable != NULL) {
959 (*CTX->client_auth_vtable)->end_name_list(
960 CTX->client_auth_vtable);
961 }
962 }
963
964 \ Client certificate: obtain the client certificate chain.
965 cc: get-client-chain ( auth_types -- ) {
966 uint32_t auth_types;
967
968 auth_types = T0_POP();
969 if (CTX->client_auth_vtable != NULL) {
970 br_ssl_client_certificate ux;
971
972 (*CTX->client_auth_vtable)->choose(CTX->client_auth_vtable,
973 CTX, auth_types, &ux);
974 CTX->auth_type = (unsigned char)ux.auth_type;
975 CTX->hash_id = (unsigned char)ux.hash_id;
976 ENG->chain = ux.chain;
977 ENG->chain_len = ux.chain_len;
978 } else {
979 CTX->hash_id = 0;
980 ENG->chain_len = 0;
981 }
982 }
983
984 \ Parse CertificateRequest. Header has already been read.
985 : read-contents-CertificateRequest ( lim -- )
986 \ Read supported client authentification types. We keep only
987 \ RSA, ECDSA, and ECDH.
988 0 { auth_types }
989 read8 open-elt
990 begin dup while
991 read8 case
992 1 of 0x0000FF endof
993 64 of 0x00FF00 endof
994 65 of 0x010000 endof
995 66 of 0x020000 endof
996 0 swap
997 endcase
998 auth_types or >auth_types
999 repeat
1000 close-elt
1001
1002 \ Full static ECDH is allowed only if the cipher suite is ECDH
1003 \ (not ECDHE). It would be theoretically feasible to use static
1004 \ ECDH on the client side with an ephemeral key pair from the
1005 \ server, but RFC 4492 (section 3) forbids it because ECDHE suites
1006 \ are supposed to provide forward secrecy, and static ECDH would
1007 \ negate that property.
1008 addr-cipher_suite get16 use-ecdh? ifnot
1009 auth_types 0xFFFF and >auth_types
1010 then
1011
1012 \ Note: if the cipher suite is ECDH, then the X.509 validation
1013 \ engine was invoked with the BR_KEYTYPE_EC | BR_KEYTYPE_KEYX
1014 \ combination, so the server's public key has already been
1015 \ checked to be fit for a key exchange.
1016
1017 \ With TLS 1.2:
1018 \ - rsa_fixed_ecdh and ecdsa_fixed_ecdh are synoymous.
1019 \ - There is an explicit list of supported sign+hash.
1020 \ With TLS 1.0,
1021 addr-version get16 0x0303 >= if
1022 \ With TLS 1.2:
1023 \ - There is an explicit list of supported sign+hash.
1024 \ - The ECDH flags must be adjusted for RSA/ECDSA
1025 \ support.
1026 read-list-sign-algos dup addr-hashes set32
1027
1028 \ Trim down the list depending on what hash functions
1029 \ we support (since the hashing itself is done by the SSL
1030 \ engine, not by the certificate handler).
1031 supported-hash-functions drop dup 8 << or 0x030000 or and
1032
1033 auth_types and
1034 auth_types 0x030000 and if
1035 dup 0x0000FF and if 0x010000 or then
1036 dup 0x00FF00 and if 0x020000 or then
1037 then
1038 >auth_types
1039 else
1040 \ TLS 1.0 or 1.1. The hash function is fixed for signatures
1041 \ (MD5+SHA-1 for RSA, SHA-1 for ECDSA).
1042 auth_types 0x030401 and >auth_types
1043 then
1044
1045 \ Parse list of anchor DN.
1046 anchor-dn-start-name-list
1047 read16 open-elt
1048 begin dup while
1049 read16 open-elt
1050 dup anchor-dn-start-name
1051
1052 \ We read the DN by chunks through the pad, so
1053 \ as to use the existing reading function (read-blob)
1054 \ that also ensures proper hashing.
1055 begin
1056 dup while
1057 dup 256 > if 256 else dup then { len }
1058 addr-pad len read-blob
1059 len anchor-dn-append-name
1060 repeat
1061 close-elt
1062 anchor-dn-end-name
1063 repeat
1064 close-elt
1065 anchor-dn-end-name-list
1066
1067 \ We should have reached the message end.
1068 close-elt
1069
1070 \ Obtain the client chain.
1071 auth_types get-client-chain
1072 ;
1073
1074 \ (obsolete)
1075 \ Write an empty Certificate message.
1076 \ : write-empty-Certificate ( -- )
1077 \ 11 write8 3 write24 0 write24 ;
1078
1079 cc: do-rsa-encrypt ( prf_id -- nlen ) {
1080 int x;
1081
1082 x = make_pms_rsa(CTX, T0_POP());
1083 if (x < 0) {
1084 br_ssl_engine_fail(ENG, -x);
1085 T0_CO();
1086 } else {
1087 T0_PUSH(x);
1088 }
1089 }
1090
1091 cc: do-ecdh ( echde prf_id -- ulen ) {
1092 unsigned prf_id = T0_POP();
1093 unsigned ecdhe = T0_POP();
1094 int x;
1095
1096 x = make_pms_ecdh(CTX, ecdhe, prf_id);
1097 if (x < 0) {
1098 br_ssl_engine_fail(ENG, -x);
1099 T0_CO();
1100 } else {
1101 T0_PUSH(x);
1102 }
1103 }
1104
1105 cc: do-static-ecdh ( prf-id -- ) {
1106 unsigned prf_id = T0_POP();
1107
1108 if (make_pms_static_ecdh(CTX, prf_id) < 0) {
1109 br_ssl_engine_fail(ENG, BR_ERR_INVALID_ALGORITHM);
1110 T0_CO();
1111 }
1112 }
1113
1114 cc: do-client-sign ( -- sig_len ) {
1115 size_t sig_len;
1116
1117 sig_len = make_client_sign(CTX);
1118 if (sig_len == 0) {
1119 br_ssl_engine_fail(ENG, BR_ERR_INVALID_ALGORITHM);
1120 T0_CO();
1121 }
1122 T0_PUSH(sig_len);
1123 }
1124
1125 \ Write ClientKeyExchange.
1126 : write-ClientKeyExchange ( -- )
1127 16 write8
1128 addr-cipher_suite get16
1129 dup use-rsa-keyx? if
1130 prf-id do-rsa-encrypt
1131 dup 2+ write24
1132 dup write16
1133 addr-pad swap write-blob
1134 else
1135 dup use-ecdhe? swap prf-id do-ecdh
1136 dup 1+ write24
1137 dup write8
1138 addr-pad swap write-blob
1139 then ;
1140
1141 \ Write CertificateVerify. This is invoked only if a client certificate
1142 \ was requested and sent, and the authentication is not full static ECDH.
1143 : write-CertificateVerify ( -- )
1144 do-client-sign
1145 15 write8 dup
1146 addr-version get16 0x0303 >= if
1147 4 + write24
1148 addr-hash_id get8 write8
1149 addr-auth_type get8 write8
1150 else
1151 2+ write24
1152 then
1153 dup write16 addr-pad swap write-blob ;
1154
1155 \ =======================================================================
1156
1157 \ Perform a handshake.
1158 : do-handshake ( -- )
1159 0 addr-application_data set8
1160 22 addr-record_type_out set8
1161 0 addr-selected_protocol set16
1162 multihash-init
1163
1164 write-ClientHello
1165 flush-record
1166 read-ServerHello
1167
1168 if
1169 \ Session resumption.
1170 -1 read-CCS-Finished
1171 -1 write-CCS-Finished
1172
1173 else
1174
1175 \ Not a session resumption.
1176
1177 \ Read certificate; then check key type and usages against
1178 \ cipher suite.
1179 read-Certificate-from-server
1180
1181 \ Depending on cipher suite, we may now expect a
1182 \ ServerKeyExchange.
1183 addr-cipher_suite get16 expected-key-type
1184 CX 0 63 { BR_KEYTYPE_SIGN } and if
1185 read-ServerKeyExchange
1186 then
1187
1188 \ Get next header.
1189 read-handshake-header
1190
1191 \ If this is a CertificateRequest, parse it, then read
1192 \ next header.
1193 dup 13 = if
1194 drop read-contents-CertificateRequest
1195 read-handshake-header
1196 -1
1197 else
1198 0
1199 then
1200 { seen-CR }
1201
1202 \ At that point, we should have a ServerHelloDone,
1203 \ whose length must be 0.
1204 14 = ifnot ERR_UNEXPECTED fail then
1205 if ERR_BAD_HELLO_DONE fail then
1206
1207 \ There should not be more bytes in the record at that point.
1208 more-incoming-bytes? if ERR_UNEXPECTED fail then
1209
1210 seen-CR if
1211 \ If the server requested a client certificate, then
1212 \ we must write a Certificate message (it may be
1213 \ empty).
1214 write-Certificate
1215
1216 \ If using static ECDH, then the ClientKeyExchange
1217 \ is empty, and there is no CertificateVerify.
1218 \ Otherwise, there is a ClientKeyExchange; there
1219 \ will then be a CertificateVerify if a client chain
1220 \ was indeed sent.
1221 addr-hash_id get8 0xFF = if
1222 drop
1223 16 write8 0 write24
1224 addr-cipher_suite get16 prf-id do-static-ecdh
1225 else
1226 write-ClientKeyExchange
1227 if write-CertificateVerify then
1228 then
1229 else
1230 write-ClientKeyExchange
1231 then
1232
1233 -1 write-CCS-Finished
1234 -1 read-CCS-Finished
1235 then
1236
1237 \ Now we should be invoked only in case of renegotiation.
1238 1 addr-application_data set8
1239 23 addr-record_type_out set8 ;
1240
1241 \ Read a HelloRequest message.
1242 : read-HelloRequest ( -- )
1243 \ A HelloRequest has length 0 and type 0.
1244 read-handshake-header-core
1245 if ERR_UNEXPECTED fail then
1246 if ERR_BAD_HANDSHAKE fail then ;
1247
1248 \ Entry point.
1249 : main ( -- ! )
1250 \ Perform initial handshake.
1251 do-handshake
1252
1253 begin
1254 \ Wait for further invocation. At that point, we should
1255 \ get either an explicit call for renegotiation, or
1256 \ an incoming HelloRequest handshake message.
1257 wait-co
1258 dup 0x07 and case
1259 0x00 of
1260 0x10 and if
1261 do-handshake
1262 then
1263 endof
1264 0x01 of
1265 drop
1266 0 addr-application_data set8
1267 read-HelloRequest
1268 \ Reject renegotiations if the peer does not
1269 \ support secure renegotiation, or if the
1270 \ "no renegotiation" flag is set.
1271 addr-reneg get8 1 = 1 flag? or if
1272 flush-record
1273 begin can-output? not while
1274 wait-co drop
1275 repeat
1276 100 send-warning
1277 else
1278 do-handshake
1279 then
1280 endof
1281 ERR_UNEXPECTED fail
1282 endcase
1283 again
1284 ;