1 \ Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
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:
11 \ The above copyright notice and this permission notice shall be
12 \ included in all copies or substantial portions of the Software.
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
23 \ ----------------------------------------------------------------------
24 \ Handshake processing code, for the client.
25 \ The common T0 code (ssl_hs_common.t0) shall be read first.
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.
37 #define CTX ((br_ssl_client_context *)ENG)
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.
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).
49 make_pms_rsa(br_ssl_client_context *ctx, int prf_id)
51 const br_x509_class **xc;
52 const br_x509_pkey *pk;
53 const unsigned char *n;
57 xc = ctx->eng.x509ctx;
58 pk = (*xc)->get_pkey(xc, NULL);
61 * Compute actual RSA key length, in case there are leading zeros.
64 nlen = pk->key.rsa.nlen;
65 while (nlen > 0 && *n == 0) {
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
78 return -BR_ERR_X509_WEAK_PUBLIC_KEY;
80 if (nlen > sizeof ctx->eng.pad) {
81 return -BR_ERR_LIMIT_EXCEEDED;
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);
93 * Apply PKCS#1 type 2 padding.
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);
107 * Compute RSA encryption.
109 if (!ctx->irsapub(ctx->eng.pad, nlen, &pk->key.rsa)) {
110 return -BR_ERR_LIMIT_EXCEEDED;
116 * OID for hash functions in RSA signatures.
118 static const unsigned char HASH_OID_SHA1[] = {
119 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A
122 static const unsigned char HASH_OID_SHA224[] = {
123 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04
126 static const unsigned char HASH_OID_SHA256[] = {
127 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01
130 static const unsigned char HASH_OID_SHA384[] = {
131 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02
134 static const unsigned char HASH_OID_SHA512[] = {
135 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03
138 static const unsigned char *HASH_OID[] = {
147 * Check the RSA signature on the ServerKeyExchange message.
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
153 * Returned value is 0 on success, or an error code.
156 verify_SKE_sig(br_ssl_client_context *ctx,
157 int hash, int use_rsa, size_t sig_len)
159 const br_x509_class **xc;
160 const br_x509_pkey *pk;
161 br_multihash_context mhc;
162 unsigned char hv[64], head[4];
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);
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);
182 hv_len = br_multihash_out(&mhc, hash, hv);
184 return BR_ERR_INVALID_ALGORITHM;
187 if (!br_multihash_out(&mhc, br_md5_ID, hv)
188 || !br_multihash_out(&mhc, br_sha1_ID, hv + 16))
190 return BR_ERR_INVALID_ALGORITHM;
195 unsigned char tmp[64];
196 const unsigned char *hash_oid;
199 hash_oid = HASH_OID[hash - 2];
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)
207 return BR_ERR_BAD_SIGNATURE;
210 if (!ctx->eng.iecdsa(ctx->eng.iec, hv, hv_len, &pk->key.ec,
211 ctx->eng.pad, sig_len))
213 return BR_ERR_BAD_SIGNATURE;
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.
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
229 make_pms_ecdh(br_ssl_client_context *ctx, unsigned ecdhe, int prf_id)
232 unsigned char key[66], point[133];
233 const unsigned char *generator, *order, *point_src;
234 size_t glen, olen, point_len;
238 curve = ctx->eng.ecdhe_curve;
239 point_src = ctx->eng.ecdhe_point;
240 point_len = ctx->eng.ecdhe_point_len;
242 const br_x509_class **xc;
243 const br_x509_pkey *pk;
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;
251 if ((ctx->eng.iec->supported_curves & ((uint32_t)1 << curve)) == 0) {
252 return -BR_ERR_INVALID_ALGORITHM;
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.
261 order = ctx->eng.iec->order(curve, &olen);
263 while (mask >= order[0]) {
266 br_hmac_drbg_generate(&ctx->eng.rng, key, olen);
268 key[olen - 1] |= 0x01;
271 * Compute the common ECDH point, whose X coordinate is the
274 generator = ctx->eng.iec->generator(curve, &glen);
275 if (glen != point_len) {
276 return -BR_ERR_INVALID_ALGORITHM;
279 memcpy(point, point_src, glen);
280 if (!ctx->eng.iec->mul(point, glen, key, olen, curve)) {
281 return -BR_ERR_INVALID_ALGORITHM;
285 * The pre-master secret is the X coordinate.
287 br_ssl_engine_compute_master(&ctx->eng, prf_id, point + 1, glen >> 1);
289 ctx->eng.iec->mulgen(point, key, olen, curve);
290 memcpy(ctx->eng.pad, point, glen);
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.
302 * Returned value is 0 on success, -1 on error.
305 make_pms_static_ecdh(br_ssl_client_context *ctx, int prf_id)
307 unsigned char point[133];
309 const br_x509_class **xc;
310 const br_x509_pkey *pk;
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) {
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))
324 br_ssl_engine_compute_master(&ctx->eng,
325 prf_id, point + 1, point_len >> 1);
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.
336 make_client_sign(br_ssl_client_context *ctx)
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.
347 hv_len = br_multihash_out(&ctx->eng.mhash,
348 ctx->hash_id, ctx->eng.pad);
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);
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);
363 \ =======================================================================
367 "addr-" field + 0 1 define-word
368 0 8191 "offsetof(br_ssl_client_context, " field + ")" + make-CX
369 postpone literal postpone ; ;
371 addr-ctx: min_clienthello_len
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
380 : ext-reneg-length ( -- n )
381 addr-reneg get8 dup if 1 - 17 * else drop 5 then ;
383 \ Length of SNI extension.
384 : ext-sni-length ( -- len )
385 addr-server_name strlen dup if 9 + then ;
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 ;
391 \ Length of Signatures extension.
392 : ext-signatures-length ( -- len )
393 supported-hash-functions { x } drop
395 supports-rsa-sign? if x + then
396 supports-ecdsa? if x + then
397 dup if 1 << 6 + then ;
399 \ Write supported hash functions ( 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
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 ;
414 \ Length of Supported Curves extension.
415 : ext-supported-curves-length ( -- len )
416 supported-curves dup if
425 \ Length of Supported Point Formats extension.
426 : ext-point-format-length ( -- len )
427 supported-curves if 6 else 0 then ;
429 \ Length of ALPN extension.
430 cc: ext-ALPN-length ( -- len ) {
433 if (ENG->protocol_names_num == 0) {
438 for (u = 0; u < ENG->protocol_names_num; u ++) {
439 len += 1 + strlen(ENG->protocol_names[u]);
444 \ Write handshake message: ClientHello
445 : write-ClientHello ( -- )
446 { ; total-ext-length }
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 +
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.
478 { ext-padding-amount }
482 addr-version_max get16 write16
485 addr-client_random 4 bzero
486 addr-client_random 4 + 28 mkrand
487 addr-client_random 32 write-blob
490 addr-session_id addr-session_id_len get8 write-blob-head8
492 \ Supported cipher suites. We also check here that we indeed
493 \ support all these suites.
494 addr-suites_num get8 dup 1 << write16
499 dup suite-supported? ifnot ERR_BAD_CIPHER_SUITE fail then
505 \ Compression methods (only "null" compression)
510 total-ext-length write16
512 0xFF01 write16 \ extension type (0xFF01)
514 ext-reneg-length 4 - dup write16 \ extension length
515 1- write-blob-head8 \ verify data
518 0x0000 write16 \ extension type (0)
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
526 0x0001 write16 \ extension type (1)
527 0x0001 write16 \ extension length
528 addr-log_max_frag_len get8 8 - write8
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
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
546 dup2 >> 1 and if dup write16 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
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
565 dup copy-protocol-name
566 dup write8 addr-pad swap write-blob
573 ext-padding-amount 0< ifnot
574 0x0015 write16 \ extension value (21)
576 dup write16 \ extension length
578 1- 0 write8 repeat \ value (only zeros)
584 \ =======================================================================
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 ;
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 ;
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 )
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
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
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.
631 \ Length of list of names.
633 \ There should be a single name.
634 read8 addr-pad swap dup { len } read-blob
637 len test-protocol-name dup 0< if
638 3 flag? if ERR_UNEXPECTED fail then
641 1+ addr-selected_protocol set16
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 ;
648 cc: DEBUG-BLOB ( addr len -- ) {
649 extern int printf(const char *fmt, ...);
651 size_t len = T0_POP();
652 unsigned char *buf = (unsigned char *)CTX + T0_POP();
656 for (u = 0; u < len; u ++) {
660 printf(" %02x", buf[u]);
665 \ Parse incoming ServerHello. Returned value is true (-1) on session
667 : read-ServerHello ( -- bool )
668 \ Get header, and check message type.
669 read-handshake-header 2 = ifnot ERR_UNEXPECTED fail then
671 \ Get protocol version.
673 version addr-version_min get16 < version addr-version_max get16 > or if
674 ERR_UNSUPPORTED_VERSION fail
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
682 addr-server_random 32 read-blob
684 \ The "session resumption" flag.
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.
698 addr-session_id addr-pad idlen memcpy
699 idlen addr-session_id_len set8
702 version addr-version resume check-resume
704 \ Cipher suite. We check that it is part of the list of cipher
705 \ suites that we advertised.
706 \ read16 { suite ; found }
708 \ addr-suites_buf dup addr-suites_num get8 1 << +
711 \ suite = found or >found
713 \ 2drop found ifnot ERR_BAD_CIPHER_SUITE fail then
715 dup scan-suite 0< if ERR_BAD_CIPHER_SUITE fail then
716 addr-cipher_suite resume check-resume
718 \ Compression method. Should be 0 (no compression).
719 read8 if ERR_BAD_COMPRESSION fail then
721 \ Parse extensions (if any). If there is no extension, then the
722 \ read limit (on the TOS) should be 0 at that point.
724 \ Length of extension list.
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 }
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.
747 ERR_EXTRA_EXTENSION fail
753 \ Max Frag Length. The contents shall be
754 \ a single byte whose value matches the one
755 \ sent by the client.
758 ERR_EXTRA_EXTENSION fail
764 \ Secure Renegotiation.
767 ERR_EXTRA_EXTENSION fail
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.
779 ERR_EXTRA_EXTENSION fail
788 ERR_EXTRA_EXTENSION fail
794 \ Supported Point Formats.
797 ERR_EXTRA_EXTENSION fail
806 ERR_EXTRA_EXTENSION fail
809 read-ALPN-from-server
812 ERR_EXTRA_EXTENSION fail
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.
821 ok-reneg 5 > if ERR_BAD_SECRENEG fail then
830 cc: set-server-curve ( -- ) {
831 const br_x509_class *xc;
832 const br_x509_pkey *pk;
834 xc = *(ENG->x509ctx);
835 pk = xc->get_pkey(ENG->x509ctx, NULL);
837 (pk->key_type == BR_KEYTYPE_EC) ? pk->key.ec.curve : 0;
840 \ Read Certificate message from server.
841 : read-Certificate-from-server ( -- )
842 addr-cipher_suite get16 expected-key-type
844 dup 0< if neg fail then
845 dup ifnot ERR_UNEXPECTED fail then
846 over and <> if ERR_WRONG_KEY_USAGE fail then
848 \ Set server curve (used for static ECDH).
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();
861 T0_PUSH(verify_SKE_sig(CTX, hash, use_rsa, sig_len));
864 \ Parse ServerKeyExchange
865 : read-ServerKeyExchange ( -- )
866 \ Get header, and check message type.
867 read-handshake-header 12 = ifnot ERR_UNEXPECTED fail then
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
875 \ Read the server point.
877 dup 133 > if ERR_INVALID_ALGORITHM fail then
878 dup addr-ecdhe_point_len set8
879 addr-ecdhe_point swap read-blob
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 }
890 \ Read hash function; accept only the SHA-* identifiers
891 \ (from SHA-1 to SHA-512, no MD5 here).
893 dup dup 2 < swap 6 > or if ERR_INVALID_ALGORITHM fail then
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,
900 use-rsa 1 << 3 + = ifnot ERR_INVALID_ALGORITHM fail then
902 \ For MD5+SHA-1, we set 'hash' to 0.
903 use-rsa if 0 >hash then
906 \ Read signature into the pad.
907 read16 dup { sig-len }
909 dup 512 > if ERR_LIMIT_EXCEEDED fail then
910 addr-pad swap read-blob
913 hash use-rsa sig-len verify-SKE-sig
914 dup if fail then drop
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);
926 \ Client certificate: start a new anchor DN (length is 16-bit).
927 cc: anchor-dn-start-name ( length -- ) {
931 if (CTX->client_auth_vtable != NULL) {
932 (*CTX->client_auth_vtable)->start_name(
933 CTX->client_auth_vtable, len);
937 \ Client certificate: push some data for current anchor DN.
938 cc: anchor-dn-append-name ( length -- ) {
942 if (CTX->client_auth_vtable != NULL) {
943 (*CTX->client_auth_vtable)->append_name(
944 CTX->client_auth_vtable, ENG->pad, len);
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);
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);
964 \ Client certificate: obtain the client certificate chain.
965 cc: get-client-chain ( auth_types -- ) {
968 auth_types = T0_POP();
969 if (CTX->client_auth_vtable != NULL) {
970 br_ssl_client_certificate ux;
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;
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.
998 auth_types or >auth_types
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
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.
1018 \ - rsa_fixed_ecdh and ecdsa_fixed_ecdh are synoymous.
1019 \ - There is an explicit list of supported sign+hash.
1021 addr-version get16 0x0303 >= if
1023 \ - There is an explicit list of supported sign+hash.
1024 \ - The ECDH flags must be adjusted for RSA/ECDSA
1026 read-list-sign-algos dup addr-hashes set16
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
1034 auth_types 0x030000 and if
1035 dup 0x0000FF and if 0x010000 or then
1036 dup 0x00FF00 and if 0x020000 or then
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
1045 \ Parse list of anchor DN.
1046 anchor-dn-start-name-list
1050 dup anchor-dn-start-name
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.
1057 dup 256 > if 256 else dup then { len }
1058 addr-pad len read-blob
1059 len anchor-dn-append-name
1065 anchor-dn-end-name-list
1067 \ We should have reached the message end.
1070 \ Obtain the client chain.
1071 auth_types get-client-chain
1075 \ Write an empty Certificate message.
1076 \ : write-empty-Certificate ( -- )
1077 \ 11 write8 3 write24 0 write24 ;
1079 cc: do-rsa-encrypt ( prf_id -- nlen ) {
1082 x = make_pms_rsa(CTX, T0_POP());
1084 br_ssl_engine_fail(ENG, -x);
1091 cc: do-ecdh ( echde prf_id -- ulen ) {
1092 unsigned prf_id = T0_POP();
1093 unsigned ecdhe = T0_POP();
1096 x = make_pms_ecdh(CTX, ecdhe, prf_id);
1098 br_ssl_engine_fail(ENG, -x);
1105 cc: do-static-ecdh ( prf-id -- ) {
1106 unsigned prf_id = T0_POP();
1108 if (make_pms_static_ecdh(CTX, prf_id) < 0) {
1109 br_ssl_engine_fail(ENG, BR_ERR_INVALID_ALGORITHM);
1114 cc: do-client-sign ( -- sig_len ) {
1117 sig_len = make_client_sign(CTX);
1119 br_ssl_engine_fail(ENG, BR_ERR_INVALID_ALGORITHM);
1125 \ Write ClientKeyExchange.
1126 : write-ClientKeyExchange ( -- )
1128 addr-cipher_suite get16
1129 dup use-rsa-keyx? if
1130 prf-id do-rsa-encrypt
1133 addr-pad swap write-blob
1135 dup use-ecdhe? swap prf-id do-ecdh
1138 addr-pad swap write-blob
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 ( -- )
1146 addr-version get16 0x0303 >= if
1148 addr-hash_id get8 write8
1149 addr-auth_type get8 write8
1153 dup write16 addr-pad swap write-blob ;
1155 \ =======================================================================
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
1169 \ Session resumption.
1170 -1 read-CCS-Finished
1171 -1 write-CCS-Finished
1175 \ Not a session resumption.
1177 \ Read certificate; then check key type and usages against
1179 read-Certificate-from-server
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
1189 read-handshake-header
1191 \ If this is a CertificateRequest, parse it, then read
1194 drop read-contents-CertificateRequest
1195 read-handshake-header
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
1207 \ There should not be more bytes in the record at that point.
1208 more-incoming-bytes? if ERR_UNEXPECTED fail then
1211 \ If the server requested a client certificate, then
1212 \ we must write a Certificate message (it may be
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
1221 addr-hash_id get8 0xFF = if
1224 addr-cipher_suite get16 prf-id do-static-ecdh
1226 write-ClientKeyExchange
1227 if write-CertificateVerify then
1230 write-ClientKeyExchange
1233 -1 write-CCS-Finished
1234 -1 read-CCS-Finished
1237 \ Now we should be invoked only in case of renegotiation.
1238 1 addr-application_data set8
1239 23 addr-record_type_out set8 ;
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 ;
1250 \ Perform initial handshake.
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.
1266 0 addr-application_data set8
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
1273 begin can-output? not while