Fixed scheduling error (jumping back to failed engine, could lead to segfault).
[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 *generator, *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 generator = 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 memcpy(point, generator, glen);
290 if (!ctx->eng.iec->mul(point, glen, key, olen, curve)) {
291 return -BR_ERR_INVALID_ALGORITHM;
292 }
293 memcpy(ctx->eng.pad, point, glen);
294 return (int)glen;
295 }
296
297 /*
298 * Perform full static ECDH. This occurs only in the context of client
299 * authentication with certificates: the server uses an EC public key,
300 * the cipher suite is of type ECDH (not ECDHE), the server requested a
301 * client certificate and accepts static ECDH, the client has a
302 * certificate with an EC public key in the same curve, and accepts
303 * static ECDH as well.
304 *
305 * Returned value is 0 on success, -1 on error.
306 */
307 static int
308 make_pms_static_ecdh(br_ssl_client_context *ctx, int prf_id)
309 {
310 unsigned char point[133];
311 size_t point_len;
312 const br_x509_class **xc;
313 const br_x509_pkey *pk;
314
315 xc = ctx->eng.x509ctx;
316 pk = (*xc)->get_pkey(xc, NULL);
317 point_len = pk->key.ec.qlen;
318 if (point_len > sizeof point) {
319 return -1;
320 }
321 memcpy(point, pk->key.ec.q, point_len);
322 if (!(*ctx->client_auth_vtable)->do_keyx(
323 ctx->client_auth_vtable, point, point_len))
324 {
325 return -1;
326 }
327 br_ssl_engine_compute_master(&ctx->eng,
328 prf_id, point + 1, point_len >> 1);
329 return 0;
330 }
331
332 /*
333 * Compute the client-side signature. This is invoked only when a
334 * signature-based client authentication was selected. The computed
335 * signature is in the pad; its length (in bytes) is returned. On
336 * error, 0 is returned.
337 */
338 static size_t
339 make_client_sign(br_ssl_client_context *ctx)
340 {
341 size_t hv_len;
342
343 /*
344 * Compute hash of handshake messages so far. This "cannot" fail
345 * because the list of supported hash functions provided to the
346 * client certificate handler was trimmed to include only the
347 * hash functions that the multi-hasher supports.
348 */
349 if (ctx->hash_id) {
350 hv_len = br_multihash_out(&ctx->eng.mhash,
351 ctx->hash_id, ctx->eng.pad);
352 } else {
353 br_multihash_out(&ctx->eng.mhash,
354 br_md5_ID, ctx->eng.pad);
355 br_multihash_out(&ctx->eng.mhash,
356 br_sha1_ID, ctx->eng.pad + 16);
357 hv_len = 36;
358 }
359 return (*ctx->client_auth_vtable)->do_sign(
360 ctx->client_auth_vtable, ctx->hash_id, hv_len,
361 ctx->eng.pad, sizeof ctx->eng.pad);
362 }
363
364 }
365
366 \ =======================================================================
367
368 : addr-ctx:
369 next-word { field }
370 "addr-" field + 0 1 define-word
371 0 8191 "offsetof(br_ssl_client_context, " field + ")" + make-CX
372 postpone literal postpone ; ;
373
374 addr-ctx: min_clienthello_len
375 addr-ctx: hashes
376 addr-ctx: auth_type
377 addr-ctx: hash_id
378
379 \ Length of the Secure Renegotiation extension. This is 5 for the
380 \ first handshake, 17 for a renegotiation (if the server supports the
381 \ extension), or 0 if we know that the server does not support the
382 \ extension.
383 : ext-reneg-length ( -- n )
384 addr-reneg get8 dup if 1 - 17 * else drop 5 then ;
385
386 \ Length of SNI extension.
387 : ext-sni-length ( -- len )
388 addr-server_name strlen dup if 9 + then ;
389
390 \ Length of Maximum Fragment Length extension.
391 : ext-frag-length ( -- len )
392 addr-log_max_frag_len get8 14 = if 0 else 5 then ;
393
394 \ Length of Signatures extension.
395 : ext-signatures-length ( -- len )
396 supported-hash-functions { x } drop
397 0
398 supports-rsa-sign? if x + then
399 supports-ecdsa? if x + then
400 dup if 1 << 6 + then ;
401
402 \ Write supported hash functions ( sign -- )
403 : write-hashes
404 { sign }
405 supported-hash-functions drop
406 \ We advertise hash functions in the following preference order:
407 \ SHA-256 SHA-224 SHA-384 SHA-512 SHA-1
408 \ Rationale:
409 \ -- SHA-256 and SHA-224 are more efficient on 32-bit architectures
410 \ -- SHA-1 is less than ideally collision-resistant
411 dup 0x10 and if 4 write8 sign write8 then
412 dup 0x08 and if 3 write8 sign write8 then
413 dup 0x20 and if 5 write8 sign write8 then
414 dup 0x40 and if 6 write8 sign write8 then
415 0x04 and if 2 write8 sign write8 then ;
416
417 \ Length of Supported Curves extension.
418 : ext-supported-curves-length ( -- len )
419 supported-curves dup if
420 0 { x }
421 begin dup while
422 dup 1 and x + >x
423 1 >>
424 repeat
425 drop x 1 << 6 +
426 then ;
427
428 \ Length of Supported Point Formats extension.
429 : ext-point-format-length ( -- len )
430 supported-curves if 6 else 0 then ;
431
432 \ Write handshake message: ClientHello
433 : write-ClientHello ( -- )
434 { ; total-ext-length }
435
436 \ Compute length for extensions (without the general two-byte header).
437 \ This does not take padding extension into account.
438 ext-reneg-length ext-sni-length + ext-frag-length +
439 ext-signatures-length +
440 ext-supported-curves-length + ext-point-format-length +
441 >total-ext-length
442
443 \ ClientHello type
444 1 write8
445
446 \ Compute and write length
447 39 addr-session_id_len get8 + addr-suites_num get8 1 << +
448 total-ext-length if 2+ total-ext-length + then
449 \ Compute padding (if requested).
450 addr-min_clienthello_len get16 over - dup 0> if
451 \ We well add a Pad ClientHello extension, which has its
452 \ own header (4 bytes) and might be the only extension
453 \ (2 extra bytes for the extension list header).
454 total-ext-length ifnot swap 2+ swap 2- then
455 \ Account for the extension header.
456 4 - dup 0< if drop 0 then
457 \ Adjust total extension length.
458 dup 4 + total-ext-length + >total-ext-length
459 \ Adjust ClientHello length.
460 swap 4 + over + swap
461 else
462 drop
463 -1
464 then
465 { ext-padding-amount }
466 write24
467
468 \ Protocol version
469 addr-version_max get16 write16
470
471 \ Client random
472 addr-client_random 4 bzero
473 addr-client_random 4 + 28 mkrand
474 addr-client_random 32 write-blob
475
476 \ Session ID
477 addr-session_id addr-session_id_len get8 write-blob-head8
478
479 \ Supported cipher suites. We also check here that we indeed
480 \ support all these suites.
481 addr-suites_num get8 dup 1 << write16
482 addr-suites_buf swap
483 begin
484 dup while 1-
485 over get16
486 dup suite-supported? ifnot ERR_BAD_CIPHER_SUITE fail then
487 write16
488 swap 2+ swap
489 repeat
490 2drop
491
492 \ Compression methods (only "null" compression)
493 1 write8 0 write8
494
495 \ Extensions
496 total-ext-length if
497 total-ext-length write16
498 ext-reneg-length if
499 0xFF01 write16 \ extension type (0xFF01)
500 addr-saved_finished
501 ext-reneg-length 4 - dup write16 \ extension length
502 1- write-blob-head8 \ verify data
503 then
504 ext-sni-length if
505 0x0000 write16 \ extension type (0)
506 addr-server_name
507 ext-sni-length 4 - dup write16 \ extension length
508 2 - dup write16 \ ServerNameList length
509 0 write8 \ name type: host_name
510 3 - write-blob-head16 \ the name itself
511 then
512 ext-frag-length if
513 0x0001 write16 \ extension type (1)
514 0x0001 write16 \ extension length
515 addr-log_max_frag_len get8 8 - write8
516 then
517 ext-signatures-length if
518 0x000D write16 \ extension type (13)
519 ext-signatures-length 4 - dup write16 \ extension length
520 2 - write16 \ list length
521 supports-ecdsa? if 3 write-hashes then
522 supports-rsa-sign? if 1 write-hashes then
523 then
524 \ TODO: add an API to specify preference order for curves.
525 \ Right now we use increasing id order, which makes P-256
526 \ the preferred curve.
527 ext-supported-curves-length dup if
528 0x000A write16 \ extension type (10)
529 4 - dup write16 \ extension length
530 2- write16 \ list length
531 supported-curves 0
532 begin dup 32 < while
533 dup2 >> 1 and if dup write16 then
534 1+
535 repeat
536 2drop
537 else
538 drop
539 then
540 ext-point-format-length if
541 0x000B write16 \ extension type (11)
542 0x0002 write16 \ extension length
543 0x0100 write16 \ value: 1 format: uncompressed
544 then
545 ext-padding-amount 0< ifnot
546 0x0015 write16 \ extension value (21)
547 ext-padding-amount
548 dup write16 \ extension length
549 begin dup while
550 1- 0 write8 repeat \ value (only zeros)
551 drop
552 then
553 then
554 ;
555
556 \ =======================================================================
557
558 \ Parse server SNI extension. If present, then it should be empty.
559 : read-server-sni ( lim -- lim )
560 read16 if ERR_BAD_SNI fail then ;
561
562 \ Parse server Max Fragment Length extension. If present, then it should
563 \ advertise the same length as the client. Note that whether the server
564 \ sends it or not changes nothing for us: we won't send any record larger
565 \ than the advertised value anyway, and we will accept incoming records
566 \ up to our input buffer length.
567 : read-server-frag ( lim -- lim )
568 read16 1 = ifnot ERR_BAD_FRAGLEN fail then
569 read8 8 + addr-log_max_frag_len get8 = ifnot ERR_BAD_FRAGLEN fail then ;
570
571 \ Parse server Secure Renegotiation extension. This is called only if
572 \ the client sent that extension, so we only have two cases to
573 \ distinguish: first handshake, and renegotiation; in the latter case,
574 \ we know that the server supports the extension, otherwise the client
575 \ would not have sent it.
576 : read-server-reneg ( lim -- lim )
577 read16
578 addr-reneg get8 ifnot
579 \ "reneg" is 0, so this is a first handshake. The server's
580 \ extension MUST be empty. We also learn that the server
581 \ supports the extension.
582 1 = ifnot ERR_BAD_SECRENEG fail then
583 read8 0 = ifnot ERR_BAD_SECRENEG fail then
584 2 addr-reneg set8
585 else
586 \ "reneg" is non-zero, and we sent an extension, so it must
587 \ be 2 and this is a renegotiation. We must verify that
588 \ the extension contents have length exactly 24 bytes and
589 \ match the saved client and server "Finished".
590 25 = ifnot ERR_BAD_SECRENEG fail then
591 read8 24 = ifnot ERR_BAD_SECRENEG fail then
592 addr-pad 24 read-blob
593 addr-saved_finished addr-pad 24 memcmp ifnot
594 ERR_BAD_SECRENEG fail
595 then
596 then ;
597
598 \ Save a value in a 16-bit field, or check it in case of session resumption.
599 : check-resume ( val addr resume -- )
600 if get16 = ifnot ERR_RESUME_MISMATCH fail then else set16 then ;
601
602 cc: DEBUG-BLOB ( addr len -- ) {
603 extern int printf(const char *fmt, ...);
604
605 size_t len = T0_POP();
606 unsigned char *buf = (unsigned char *)CTX + T0_POP();
607 size_t u;
608
609 printf("BLOB:");
610 for (u = 0; u < len; u ++) {
611 if (u % 16 == 0) {
612 printf("\n ");
613 }
614 printf(" %02x", buf[u]);
615 }
616 printf("\n");
617 }
618
619 \ Parse incoming ServerHello. Returned value is true (-1) on session
620 \ resumption.
621 : read-ServerHello ( -- bool )
622 \ Get header, and check message type.
623 read-handshake-header 2 = ifnot ERR_UNEXPECTED fail then
624
625 \ Get protocol version.
626 read16 { version }
627 version addr-version_min get16 < version addr-version_max get16 > or if
628 ERR_UNSUPPORTED_VERSION fail
629 then
630
631 \ Enforce chosen version for subsequent records in both directions.
632 version addr-version_in get16 <> if ERR_BAD_VERSION fail then
633 version addr-version_out set16
634
635 \ Server random.
636 addr-server_random 32 read-blob
637
638 \ The "session resumption" flag.
639 0 { resume }
640
641 \ Session ID.
642 read8 { idlen }
643 idlen 32 > if ERR_OVERSIZED_ID fail then
644 addr-pad idlen read-blob
645 idlen addr-session_id_len get8 = idlen 0 > and if
646 addr-session_id addr-pad idlen memcmp if
647 \ Server session ID is non-empty and matches what
648 \ we sent, so this is a session resumption.
649 -1 >resume
650 then
651 then
652 addr-session_id addr-pad idlen memcpy
653 idlen addr-session_id_len set8
654
655 \ Record version.
656 version addr-version resume check-resume
657
658 \ Cipher suite. We check that it is part of the list of cipher
659 \ suites that we advertised.
660 \ read16 { suite ; found }
661 \ 0 >found
662 \ addr-suites_buf dup addr-suites_num get8 1 << +
663 \ begin dup2 < while
664 \ 2 - dup get16
665 \ suite = found or >found
666 \ repeat
667 \ 2drop found ifnot ERR_BAD_CIPHER_SUITE fail then
668 read16
669 dup scan-suite 0< if ERR_BAD_CIPHER_SUITE fail then
670 addr-cipher_suite resume check-resume
671
672 \ Compression method. Should be 0 (no compression).
673 read8 if ERR_BAD_COMPRESSION fail then
674
675 \ Parse extensions (if any). If there is no extension, then the
676 \ read limit (on the TOS) should be 0 at that point.
677 dup if
678 \ Length of extension list.
679 \ message size.
680 read16 open-elt
681
682 \ Enumerate extensions. For each of them, check that we
683 \ sent an extension of that type, and did not see it
684 \ yet; and then process it.
685 ext-sni-length { ok-sni }
686 ext-reneg-length { ok-reneg }
687 ext-frag-length { ok-frag }
688 ext-signatures-length { ok-signatures }
689 ext-supported-curves-length { ok-curves }
690 ext-point-format-length { ok-points }
691 begin dup while
692 read16
693 case
694 \ Server Name Indication. The server may
695 \ send such an extension if it uses the SNI
696 \ from the client, but that "response
697 \ extension" is supposed to be empty.
698 0x0000 of
699 ok-sni ifnot
700 ERR_EXTRA_EXTENSION fail
701 then
702 0 >ok-sni
703 read-server-sni
704 endof
705
706 \ Max Frag Length. The contents shall be
707 \ a single byte whose value matches the one
708 \ sent by the client.
709 0x0001 of
710 ok-frag ifnot
711 ERR_EXTRA_EXTENSION fail
712 then
713 0 >ok-frag
714 read-server-frag
715 endof
716
717 \ Secure Renegotiation.
718 0xFF01 of
719 ok-reneg ifnot
720 ERR_EXTRA_EXTENSION fail
721 then
722 0 >ok-reneg
723 read-server-reneg
724 endof
725
726 \ Signature Algorithms.
727 \ Normally, the server should never send this
728 \ extension (so says RFC 5246 #7.4.1.4.1),
729 \ but some existing servers do.
730 0x000D of
731 ok-signatures ifnot
732 ERR_EXTRA_EXTENSION fail
733 then
734 0 >ok-signatures
735 read-ignore-16
736 endof
737
738 \ Supported Curves.
739 0x000A of
740 ok-curves ifnot
741 ERR_EXTRA_EXTENSION fail
742 then
743 0 >ok-curves
744 read-ignore-16
745 endof
746
747 \ Supported Point Formats.
748 0x000B of
749 ok-points ifnot
750 ERR_EXTRA_EXTENSION fail
751 then
752 0 >ok-points
753 read-ignore-16
754 endof
755
756 ERR_EXTRA_EXTENSION fail
757 endcase
758 repeat
759
760 \ If we sent a secure renegotiation extension but did not
761 \ receive a response, then the server does not support
762 \ secure renegotiation. This is a hard failure if this
763 \ is a renegotiation.
764 ok-reneg if
765 ok-reneg 5 > if ERR_BAD_SECRENEG fail then
766 1 addr-reneg set8
767 then
768 close-elt
769 then
770 close-elt
771 resume
772 ;
773
774 cc: set-server-curve ( -- ) {
775 const br_x509_class *xc;
776 const br_x509_pkey *pk;
777
778 xc = *(ENG->x509ctx);
779 pk = xc->get_pkey(ENG->x509ctx, NULL);
780 CTX->server_curve =
781 (pk->key_type == BR_KEYTYPE_EC) ? pk->key.ec.curve : 0;
782 }
783
784 \ Read Certificate message from server.
785 : read-Certificate-from-server ( -- )
786 addr-cipher_suite get16 expected-key-type
787 -1 read-Certificate
788 dup 0< if neg fail then
789 dup ifnot ERR_UNEXPECTED fail then
790 over and <> if ERR_WRONG_KEY_USAGE fail then
791
792 \ Set server curve (used for static ECDH).
793 set-server-curve ;
794
795 \ Verify signature on ECDHE point sent by the server.
796 \ 'hash' is the hash function to use (1 to 6, or 0 for RSA with MD5+SHA-1)
797 \ 'use-rsa' is 0 for ECDSA, -1 for for RSA
798 \ 'sig-len' is the signature length (in bytes)
799 \ The signature itself is in the pad.
800 cc: verify-SKE-sig ( hash use-rsa sig-len -- err ) {
801 size_t sig_len = T0_POP();
802 int use_rsa = T0_POPi();
803 int hash = T0_POPi();
804
805 T0_PUSH(verify_SKE_sig(CTX, hash, use_rsa, sig_len));
806 }
807
808 \ Parse ServerKeyExchange
809 : read-ServerKeyExchange ( -- )
810 \ Get header, and check message type.
811 read-handshake-header 12 = ifnot ERR_UNEXPECTED fail then
812
813 \ We expect a named curve, and we must support it.
814 read8 3 = ifnot ERR_INVALID_ALGORITHM fail then
815 read16 dup addr-ecdhe_curve set8
816 dup 32 >= if ERR_INVALID_ALGORITHM fail then
817 supported-curves swap >> 1 and ifnot ERR_INVALID_ALGORITHM fail then
818
819 \ Read the server point.
820 read8
821 dup 133 > if ERR_INVALID_ALGORITHM fail then
822 dup addr-ecdhe_point_len set8
823 addr-ecdhe_point swap read-blob
824
825 \ If using TLS-1.2+, then the hash function and signature algorithm
826 \ are explicitly provided; the signature algorithm must match what
827 \ the cipher suite specifies. With TLS-1.0 and 1.1, the signature
828 \ algorithm is inferred from the cipher suite, and the hash is
829 \ either MD5+SHA-1 (for RSA signatures) or SHA-1 (for ECDSA).
830 addr-version get16 0x0303 >= { tls1.2+ }
831 addr-cipher_suite get16 use-rsa-ecdhe? { use-rsa }
832 2 { hash }
833 tls1.2+ if
834 \ Read hash function; accept only the SHA-* identifiers
835 \ (from SHA-1 to SHA-512, no MD5 here).
836 read8
837 dup dup 2 < swap 6 > or if ERR_INVALID_ALGORITHM fail then
838 >hash
839 read8
840 \ Get expected signature algorithm and compare with what
841 \ the server just sent. Expected value is 1 for RSA, 3
842 \ for ECDSA. Note that 'use-rsa' evaluates to -1 for RSA,
843 \ 0 for ECDSA.
844 use-rsa 1 << 3 + = ifnot ERR_INVALID_ALGORITHM fail then
845 else
846 \ For MD5+SHA-1, we set 'hash' to 0.
847 use-rsa if 0 >hash then
848 then
849
850 \ Read signature into the pad.
851 read16 dup { sig-len }
852
853 dup 512 > if ERR_LIMIT_EXCEEDED fail then
854 addr-pad swap read-blob
855
856 \ Verify signature.
857 hash use-rsa sig-len verify-SKE-sig
858 dup if fail then drop
859
860 close-elt ;
861
862 \ Client certificate: start processing of anchor names.
863 cc: anchor-dn-start-name-list ( -- ) {
864 if (CTX->client_auth_vtable != NULL) {
865 (*CTX->client_auth_vtable)->start_name_list(
866 CTX->client_auth_vtable);
867 }
868 }
869
870 \ Client certificate: start a new anchor DN (length is 16-bit).
871 cc: anchor-dn-start-name ( length -- ) {
872 size_t len;
873
874 len = T0_POP();
875 if (CTX->client_auth_vtable != NULL) {
876 (*CTX->client_auth_vtable)->start_name(
877 CTX->client_auth_vtable, len);
878 }
879 }
880
881 \ Client certificate: push some data for current anchor DN.
882 cc: anchor-dn-append-name ( length -- ) {
883 size_t len;
884
885 len = T0_POP();
886 if (CTX->client_auth_vtable != NULL) {
887 (*CTX->client_auth_vtable)->append_name(
888 CTX->client_auth_vtable, ENG->pad, len);
889 }
890 }
891
892 \ Client certificate: end current anchor DN.
893 cc: anchor-dn-end-name ( -- ) {
894 if (CTX->client_auth_vtable != NULL) {
895 (*CTX->client_auth_vtable)->end_name(
896 CTX->client_auth_vtable);
897 }
898 }
899
900 \ Client certificate: end list of anchor DN.
901 cc: anchor-dn-end-name-list ( -- ) {
902 if (CTX->client_auth_vtable != NULL) {
903 (*CTX->client_auth_vtable)->end_name_list(
904 CTX->client_auth_vtable);
905 }
906 }
907
908 \ Client certificate: obtain the client certificate chain.
909 cc: get-client-chain ( auth_types -- ) {
910 uint32_t auth_types;
911
912 auth_types = T0_POP();
913 if (CTX->client_auth_vtable != NULL) {
914 br_ssl_client_certificate ux;
915
916 (*CTX->client_auth_vtable)->choose(CTX->client_auth_vtable,
917 CTX, auth_types, &ux);
918 CTX->auth_type = (unsigned char)ux.auth_type;
919 CTX->hash_id = (unsigned char)ux.hash_id;
920 ENG->chain = ux.chain;
921 ENG->chain_len = ux.chain_len;
922 } else {
923 CTX->hash_id = 0;
924 ENG->chain_len = 0;
925 }
926 }
927
928 \ Parse CertificateRequest. Header has already been read.
929 : read-contents-CertificateRequest ( lim -- )
930 \ Read supported client authentification types. We keep only
931 \ RSA, ECDSA, and ECDH.
932 0 { auth_types }
933 read8 open-elt
934 begin dup while
935 read8 case
936 1 of 0x0000FF endof
937 64 of 0x00FF00 endof
938 65 of 0x010000 endof
939 66 of 0x020000 endof
940 0 swap
941 endcase
942 auth_types or >auth_types
943 repeat
944 close-elt
945
946 \ Full static ECDH is allowed only if the cipher suite is ECDH
947 \ (not ECDHE). It would be theoretically feasible to use static
948 \ ECDH on the client side with an ephemeral key pair from the
949 \ server, but RFC 4492 (section 3) forbids it because ECDHE suites
950 \ are supposed to provide forward secrecy, and static ECDH would
951 \ negate that property.
952 addr-cipher_suite get16 use-ecdh? ifnot
953 auth_types 0xFFFF and >auth_types
954 then
955
956 \ Note: if the cipher suite is ECDH, then the X.509 validation
957 \ engine was invoked with the BR_KEYTYPE_EC | BR_KEYTYPE_KEYX
958 \ combination, so the server's public key has already been
959 \ checked to be fit for a key exchange.
960
961 \ With TLS 1.2:
962 \ - rsa_fixed_ecdh and ecdsa_fixed_ecdh are synoymous.
963 \ - There is an explicit list of supported sign+hash.
964 \ With TLS 1.0,
965 addr-version get16 0x0303 >= if
966 \ With TLS 1.2:
967 \ - There is an explicit list of supported sign+hash.
968 \ - The ECDH flags must be adjusted for RSA/ECDSA
969 \ support.
970 read-list-sign-algos dup addr-hashes set16
971
972 \ Trim down the list depending on what hash functions
973 \ we support (since the hashing itself is done by the SSL
974 \ engine, not by the certificate handler).
975 supported-hash-functions drop dup 8 << or 0x030000 or and
976
977 auth_types and
978 auth_types 0x030000 and if
979 dup 0x0000FF and if 0x010000 or then
980 dup 0x00FF00 and if 0x020000 or then
981 then
982 >auth_types
983 else
984 \ TLS 1.0 or 1.1. The hash function is fixed for signatures
985 \ (MD5+SHA-1 for RSA, SHA-1 for ECDSA).
986 auth_types 0x030401 and >auth_types
987 then
988
989 \ Parse list of anchor DN.
990 anchor-dn-start-name-list
991 read16 open-elt
992 begin dup while
993 read16 open-elt
994 dup anchor-dn-start-name
995
996 \ We read the DN by chunks through the pad, so
997 \ as to use the existing reading function (read-blob)
998 \ that also ensures proper hashing.
999 begin
1000 dup while
1001 dup 256 > if 256 else dup then { len }
1002 addr-pad len read-blob
1003 len anchor-dn-append-name
1004 repeat
1005 close-elt
1006 anchor-dn-end-name
1007 repeat
1008 close-elt
1009 anchor-dn-end-name-list
1010
1011 \ We should have reached the message end.
1012 close-elt
1013
1014 \ Obtain the client chain.
1015 auth_types get-client-chain
1016 ;
1017
1018 \ (obsolete)
1019 \ Write an empty Certificate message.
1020 \ : write-empty-Certificate ( -- )
1021 \ 11 write8 3 write24 0 write24 ;
1022
1023 cc: do-rsa-encrypt ( prf_id -- nlen ) {
1024 int x;
1025
1026 x = make_pms_rsa(CTX, T0_POP());
1027 if (x < 0) {
1028 br_ssl_engine_fail(ENG, -x);
1029 T0_CO();
1030 } else {
1031 T0_PUSH(x);
1032 }
1033 }
1034
1035 cc: do-ecdh ( echde prf_id -- ulen ) {
1036 unsigned prf_id = T0_POP();
1037 unsigned ecdhe = T0_POP();
1038 int x;
1039
1040 x = make_pms_ecdh(CTX, ecdhe, prf_id);
1041 if (x < 0) {
1042 br_ssl_engine_fail(ENG, -x);
1043 T0_CO();
1044 } else {
1045 T0_PUSH(x);
1046 }
1047 }
1048
1049 cc: do-static-ecdh ( prf-id -- ) {
1050 unsigned prf_id = T0_POP();
1051
1052 if (make_pms_static_ecdh(CTX, prf_id) < 0) {
1053 br_ssl_engine_fail(ENG, BR_ERR_INVALID_ALGORITHM);
1054 T0_CO();
1055 }
1056 }
1057
1058 cc: do-client-sign ( -- sig_len ) {
1059 size_t sig_len;
1060
1061 sig_len = make_client_sign(CTX);
1062 if (sig_len == 0) {
1063 br_ssl_engine_fail(ENG, BR_ERR_INVALID_ALGORITHM);
1064 T0_CO();
1065 }
1066 T0_PUSH(sig_len);
1067 }
1068
1069 \ Write ClientKeyExchange.
1070 : write-ClientKeyExchange ( -- )
1071 16 write8
1072 addr-cipher_suite get16
1073 dup use-rsa-keyx? if
1074 prf-id do-rsa-encrypt
1075 dup 2+ write24
1076 dup write16
1077 addr-pad swap write-blob
1078 else
1079 dup use-ecdhe? swap prf-id do-ecdh
1080 dup 1+ write24
1081 dup write8
1082 addr-pad swap write-blob
1083 then ;
1084
1085 \ Write CertificateVerify. This is invoked only if a client certificate
1086 \ was requested and sent, and the authentication is not full static ECDH.
1087 : write-CertificateVerify ( -- )
1088 do-client-sign
1089 15 write8 dup
1090 addr-version get16 0x0303 >= if
1091 4 + write24
1092 addr-hash_id get8 write8
1093 addr-auth_type get8 write8
1094 else
1095 2+ write24
1096 then
1097 dup write16 addr-pad swap write-blob ;
1098
1099 \ =======================================================================
1100
1101 \ Perform a handshake.
1102 : do-handshake ( -- )
1103 0 addr-application_data set8
1104 22 addr-record_type_out set8
1105 multihash-init
1106
1107 write-ClientHello
1108 flush-record
1109 read-ServerHello
1110
1111 if
1112 \ Session resumption.
1113 -1 read-CCS-Finished
1114 -1 write-CCS-Finished
1115
1116 else
1117
1118 \ Not a session resumption.
1119
1120 \ Read certificate; then check key type and usages against
1121 \ cipher suite.
1122 read-Certificate-from-server
1123
1124 \ Depending on cipher suite, we may now expect a
1125 \ ServerKeyExchange.
1126 addr-cipher_suite get16 expected-key-type
1127 CX 0 63 { BR_KEYTYPE_SIGN } and if
1128 read-ServerKeyExchange
1129 then
1130
1131 \ Get next header.
1132 read-handshake-header
1133
1134 \ If this is a CertificateRequest, parse it, then read
1135 \ next header.
1136 dup 13 = if
1137 drop read-contents-CertificateRequest
1138 read-handshake-header
1139 -1
1140 else
1141 0
1142 then
1143 { seen-CR }
1144
1145 \ At that point, we should have a ServerHelloDone,
1146 \ whose length must be 0.
1147 14 = ifnot ERR_UNEXPECTED fail then
1148 if ERR_BAD_HELLO_DONE fail then
1149
1150 \ There should not be more bytes in the record at that point.
1151 more-incoming-bytes? if ERR_UNEXPECTED fail then
1152
1153 seen-CR if
1154 \ If the server requested a client certificate, then
1155 \ we must write a Certificate message (it may be
1156 \ empty).
1157 write-Certificate
1158
1159 \ If using static ECDH, then the ClientKeyExchange
1160 \ is empty, and there is no CertificateVerify.
1161 \ Otherwise, there is a ClientKeyExchange; there
1162 \ will then be a CertificateVerify if a client chain
1163 \ was indeed sent.
1164 addr-hash_id get8 0xFF = if
1165 drop
1166 16 write8 0 write24
1167 addr-cipher_suite get16 prf-id do-static-ecdh
1168 else
1169 write-ClientKeyExchange
1170 if write-CertificateVerify then
1171 then
1172 else
1173 write-ClientKeyExchange
1174 then
1175
1176 -1 write-CCS-Finished
1177 -1 read-CCS-Finished
1178 then
1179
1180 \ Now we should be invoked only in case of renegotiation.
1181 1 addr-application_data set8
1182 23 addr-record_type_out set8 ;
1183
1184 \ Read a HelloRequest message.
1185 : read-HelloRequest ( -- )
1186 \ A HelloRequest has length 0 and type 0.
1187 read-handshake-header-core
1188 if ERR_UNEXPECTED fail then
1189 if ERR_BAD_HANDSHAKE fail then ;
1190
1191 \ Entry point.
1192 : main ( -- ! )
1193 \ Perform initial handshake.
1194 do-handshake
1195
1196 begin
1197 \ Wait for further invocation. At that point, we should
1198 \ get either an explicit call for renegotiation, or
1199 \ an incoming HelloRequest handshake message.
1200 wait-co
1201 dup 0x07 and case
1202 0x00 of
1203 0x10 and if
1204 do-handshake
1205 then
1206 endof
1207 0x01 of
1208 drop
1209 0 addr-application_data set8
1210 read-HelloRequest
1211 \ Reject renegotiations if the peer does not
1212 \ support secure renegotiation, or if the
1213 \ "no renegotiation" flag is set.
1214 addr-reneg get8 1 = 1 flag? or if
1215 flush-record
1216 begin can-output? not while
1217 wait-co drop
1218 repeat
1219 100 send-warning
1220 else
1221 do-handshake
1222 then
1223 endof
1224 ERR_UNEXPECTED fail
1225 endcase
1226 again
1227 ;