a7475af0e1a2eb2621354313625546365797de3c
[BearSSL] / src / ssl / ssl_hs_server.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 server.
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 server context, under that
31 * specific name. It must be noted that since the engine context is the
32 * first field of the br_ssl_server_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_server_context *)ENG)
38
39 /*
40 * Decrypt the pre-master secret (RSA key exchange).
41 */
42 static void
43 do_rsa_decrypt(br_ssl_server_context *ctx, int prf_id,
44 unsigned char *epms, size_t len)
45 {
46 uint32_t x;
47 unsigned char rpms[48];
48
49 /*
50 * Decrypt the PMS.
51 */
52 x = (*ctx->policy_vtable)->do_keyx(ctx->policy_vtable, epms, len);
53
54 /*
55 * Set the first two bytes to the maximum supported client
56 * protocol version. These bytes are used for version rollback
57 * detection; forceing the two bytes will make the master secret
58 * wrong if the bytes are not correct. This process is
59 * recommended by RFC 5246 (section 7.4.7.1).
60 */
61 br_enc16be(epms, ctx->client_max_version);
62
63 /*
64 * Make a random PMS and copy it above the decrypted value if the
65 * decryption failed. Note that we use a constant-time conditional
66 * copy.
67 */
68 br_hmac_drbg_generate(&ctx->eng.rng, rpms, sizeof rpms);
69 br_ccopy(x ^ 1, epms, rpms, sizeof rpms);
70
71 /*
72 * Compute master secret.
73 */
74 br_ssl_engine_compute_master(&ctx->eng, prf_id, epms, 48);
75
76 /*
77 * Clear the pre-master secret from RAM: it is normally a buffer
78 * in the context, hence potentially long-lived.
79 */
80 memset(epms, 0, len);
81 }
82
83 /*
84 * Common part for ECDH and ECDHE.
85 */
86 static void
87 ecdh_common(br_ssl_server_context *ctx, int prf_id,
88 unsigned char *cpoint, size_t cpoint_len, uint32_t ctl)
89 {
90 unsigned char rpms[80];
91 size_t pms_len;
92
93 /*
94 * The point length is supposed to be 1+2*Xlen, where Xlen is
95 * the length (in bytes) of the X coordinate, i.e. the pre-master
96 * secret. If the provided point is too large, then it is
97 * obviously incorrect (i.e. everybody can see that it is
98 * incorrect), so leaking that fact is not a problem.
99 */
100 pms_len = cpoint_len >> 1;
101 if (pms_len > sizeof rpms) {
102 pms_len = sizeof rpms;
103 ctl = 0;
104 }
105
106 /*
107 * Make a random PMS and copy it above the decrypted value if the
108 * decryption failed. Note that we use a constant-time conditional
109 * copy.
110 */
111 br_hmac_drbg_generate(&ctx->eng.rng, rpms, pms_len);
112 br_ccopy(ctl ^ 1, cpoint + 1, rpms, pms_len);
113
114 /*
115 * Compute master secret.
116 */
117 br_ssl_engine_compute_master(&ctx->eng, prf_id, cpoint + 1, pms_len);
118
119 /*
120 * Clear the pre-master secret from RAM: it is normally a buffer
121 * in the context, hence potentially long-lived.
122 */
123 memset(cpoint, 0, cpoint_len);
124 }
125
126 /*
127 * Do the ECDH key exchange (not ECDHE).
128 */
129 static void
130 do_ecdh(br_ssl_server_context *ctx, int prf_id,
131 unsigned char *cpoint, size_t cpoint_len)
132 {
133 uint32_t x;
134
135 /*
136 * Finalise the key exchange.
137 */
138 x = (*ctx->policy_vtable)->do_keyx(ctx->policy_vtable,
139 cpoint, cpoint_len);
140 ecdh_common(ctx, prf_id, cpoint, cpoint_len, x);
141 }
142
143 /*
144 * Do the full static ECDH key exchange. When this function is called,
145 * it has already been verified that the cipher suite uses ECDH (not ECDHE),
146 * and the client's public key (from its certificate) has type EC and is
147 * apt for key exchange.
148 */
149 static void
150 do_static_ecdh(br_ssl_server_context *ctx, int prf_id)
151 {
152 unsigned char cpoint[133];
153 size_t cpoint_len;
154 const br_x509_class **xc;
155 const br_x509_pkey *pk;
156
157 xc = ctx->eng.x509ctx;
158 pk = (*xc)->get_pkey(xc, NULL);
159 cpoint_len = pk->key.ec.qlen;
160 if (cpoint_len > sizeof cpoint) {
161 /*
162 * If the point is larger than our buffer then we need to
163 * restrict it. Length 2 is not a valid point length, so
164 * the ECDH will fail.
165 */
166 cpoint_len = 2;
167 }
168 memcpy(cpoint, pk->key.ec.q, cpoint_len);
169 do_ecdh(ctx, prf_id, cpoint, cpoint_len);
170 }
171
172 static size_t
173 hash_data(br_ssl_server_context *ctx,
174 void *dst, int hash_id, const void *src, size_t len)
175 {
176 const br_hash_class *hf;
177 br_hash_compat_context hc;
178
179 if (hash_id == 0) {
180 unsigned char tmp[36];
181
182 hf = br_multihash_getimpl(&ctx->eng.mhash, br_md5_ID);
183 if (hf == NULL) {
184 return 0;
185 }
186 hf->init(&hc.vtable);
187 hf->update(&hc.vtable, src, len);
188 hf->out(&hc.vtable, tmp);
189 hf = br_multihash_getimpl(&ctx->eng.mhash, br_sha1_ID);
190 if (hf == NULL) {
191 return 0;
192 }
193 hf->init(&hc.vtable);
194 hf->update(&hc.vtable, src, len);
195 hf->out(&hc.vtable, tmp + 16);
196 memcpy(dst, tmp, 36);
197 return 36;
198 } else {
199 hf = br_multihash_getimpl(&ctx->eng.mhash, hash_id);
200 if (hf == NULL) {
201 return 0;
202 }
203 hf->init(&hc.vtable);
204 hf->update(&hc.vtable, src, len);
205 hf->out(&hc.vtable, dst);
206 return (hf->desc >> BR_HASHDESC_OUT_OFF) & BR_HASHDESC_OUT_MASK;
207 }
208 }
209
210 /*
211 * Do the ECDHE key exchange (part 1: generation of transient key, and
212 * computing of the point to send to the client). Returned value is the
213 * signature length (in bytes), or -x on error (with x being an error
214 * code). The encoded point is written in the ecdhe_point[] context buffer
215 * (length in ecdhe_point_len).
216 */
217 static int
218 do_ecdhe_part1(br_ssl_server_context *ctx, int curve)
219 {
220 unsigned algo_id;
221 unsigned mask;
222 const unsigned char *order;
223 size_t olen, glen;
224 size_t hv_len, sig_len;
225
226 if (!((ctx->eng.iec->supported_curves >> curve) & 1)) {
227 return -BR_ERR_INVALID_ALGORITHM;
228 }
229 ctx->eng.ecdhe_curve = curve;
230
231 /*
232 * Generate our private key. We need a non-zero random value
233 * which is lower than the curve order, in a "large enough"
234 * range. We force the top bit to 0 and bottom bit to 1, which
235 * does the trick. Note that contrary to what happens in ECDSA,
236 * this is not a problem if we do not cover the full range of
237 * possible values.
238 */
239 order = ctx->eng.iec->order(curve, &olen);
240 mask = 0xFF;
241 while (mask >= order[0]) {
242 mask >>= 1;
243 }
244 br_hmac_drbg_generate(&ctx->eng.rng, ctx->ecdhe_key, olen);
245 ctx->ecdhe_key[0] &= mask;
246 ctx->ecdhe_key[olen - 1] |= 0x01;
247 ctx->ecdhe_key_len = olen;
248
249 /*
250 * Compute our ECDH point.
251 */
252 glen = ctx->eng.iec->mulgen(ctx->eng.ecdhe_point,
253 ctx->ecdhe_key, olen, curve);
254 ctx->eng.ecdhe_point_len = glen;
255
256 /*
257 * Assemble the message to be signed, and possibly hash it.
258 */
259 memcpy(ctx->eng.pad, ctx->eng.client_random, 32);
260 memcpy(ctx->eng.pad + 32, ctx->eng.server_random, 32);
261 ctx->eng.pad[64 + 0] = 0x03;
262 ctx->eng.pad[64 + 1] = 0x00;
263 ctx->eng.pad[64 + 2] = curve;
264 ctx->eng.pad[64 + 3] = ctx->eng.ecdhe_point_len;
265 memcpy(ctx->eng.pad + 64 + 4,
266 ctx->eng.ecdhe_point, ctx->eng.ecdhe_point_len);
267 hv_len = 64 + 4 + ctx->eng.ecdhe_point_len;
268 algo_id = ctx->sign_hash_id;
269 if (algo_id >= (unsigned)0xFF00) {
270 hv_len = hash_data(ctx, ctx->eng.pad, algo_id & 0xFF,
271 ctx->eng.pad, hv_len);
272 if (hv_len == 0) {
273 return -BR_ERR_INVALID_ALGORITHM;
274 }
275 }
276
277 sig_len = (*ctx->policy_vtable)->do_sign(ctx->policy_vtable,
278 algo_id, ctx->eng.pad, hv_len, sizeof ctx->eng.pad);
279 return sig_len ? (int)sig_len : -BR_ERR_INVALID_ALGORITHM;
280 }
281
282 /*
283 * Do the ECDHE key exchange (part 2: computation of the shared secret
284 * from the point sent by the client).
285 */
286 static void
287 do_ecdhe_part2(br_ssl_server_context *ctx, int prf_id,
288 unsigned char *cpoint, size_t cpoint_len)
289 {
290 int curve;
291 uint32_t x;
292
293 curve = ctx->eng.ecdhe_curve;
294
295 /*
296 * Finalise the key exchange.
297 */
298 x = ctx->eng.iec->mul(cpoint, cpoint_len,
299 ctx->ecdhe_key, ctx->ecdhe_key_len, curve);
300 ecdh_common(ctx, prf_id, cpoint, cpoint_len, x);
301
302 /*
303 * Clear the ECDHE private key. Forward Secrecy is achieved insofar
304 * as that key does not get stolen, so we'd better destroy it
305 * as soon as it ceases to be useful.
306 */
307 memset(ctx->ecdhe_key, 0, ctx->ecdhe_key_len);
308 }
309
310 /*
311 * Offset for hash value within the pad (when obtaining all hash values,
312 * in preparation for verification of the CertificateVerify message).
313 * Order is MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512; last value
314 * is used to get the total length.
315 */
316 static const unsigned char HASH_PAD_OFF[] = { 0, 16, 36, 64, 96, 144, 208 };
317
318 /*
319 * OID for hash functions in RSA signatures.
320 */
321 static const unsigned char HASH_OID_SHA1[] = {
322 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A
323 };
324
325 static const unsigned char HASH_OID_SHA224[] = {
326 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04
327 };
328
329 static const unsigned char HASH_OID_SHA256[] = {
330 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01
331 };
332
333 static const unsigned char HASH_OID_SHA384[] = {
334 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02
335 };
336
337 static const unsigned char HASH_OID_SHA512[] = {
338 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03
339 };
340
341 static const unsigned char *HASH_OID[] = {
342 HASH_OID_SHA1,
343 HASH_OID_SHA224,
344 HASH_OID_SHA256,
345 HASH_OID_SHA384,
346 HASH_OID_SHA512
347 };
348
349 /*
350 * Verify the signature in CertificateVerify. Returned value is 0 on
351 * success, or a non-zero error code. Lack of implementation of the
352 * designated signature algorithm is reported as a "bad signature"
353 * error (because it means that the peer did not honour our advertised
354 * set of supported signature algorithms).
355 */
356 static int
357 verify_CV_sig(br_ssl_server_context *ctx, size_t sig_len)
358 {
359 const br_x509_class **xc;
360 const br_x509_pkey *pk;
361 int id;
362
363 id = ctx->hash_CV_id;
364 xc = ctx->eng.x509ctx;
365 pk = (*xc)->get_pkey(xc, NULL);
366 if (pk->key_type == BR_KEYTYPE_RSA) {
367 unsigned char tmp[64];
368 const unsigned char *hash_oid;
369
370 if (id == 0) {
371 hash_oid = NULL;
372 } else {
373 hash_oid = HASH_OID[id - 2];
374 }
375 if (ctx->eng.irsavrfy == 0) {
376 return BR_ERR_BAD_SIGNATURE;
377 }
378 if (!ctx->eng.irsavrfy(ctx->eng.pad, sig_len,
379 hash_oid, ctx->hash_CV_len, &pk->key.rsa, tmp)
380 || memcmp(tmp, ctx->hash_CV, ctx->hash_CV_len) != 0)
381 {
382 return BR_ERR_BAD_SIGNATURE;
383 }
384 } else {
385 if (ctx->eng.iecdsa == 0) {
386 return BR_ERR_BAD_SIGNATURE;
387 }
388 if (!ctx->eng.iecdsa(ctx->eng.iec,
389 ctx->hash_CV, ctx->hash_CV_len,
390 &pk->key.ec, ctx->eng.pad, sig_len))
391 {
392 return BR_ERR_BAD_SIGNATURE;
393 }
394 }
395 return 0;
396 }
397
398 }
399
400 \ =======================================================================
401
402 : addr-ctx:
403 next-word { field }
404 "addr-" field + 0 1 define-word
405 0 8191 "offsetof(br_ssl_server_context, " field + ")" + make-CX
406 postpone literal postpone ; ;
407
408 addr-ctx: client_max_version
409 addr-ctx: client_suites
410 addr-ctx: client_suites_num
411 addr-ctx: hashes
412 addr-ctx: curves
413 addr-ctx: sign_hash_id
414
415 \ Get address and length of the client_suites[] buffer. Length is expressed
416 \ in bytes.
417 : addr-len-client_suites ( -- addr len )
418 addr-client_suites
419 CX 0 1023 { BR_MAX_CIPHER_SUITES * sizeof(br_suite_translated) } ;
420
421 \ Read the client SNI extension.
422 : read-client-sni ( lim -- lim )
423 \ Open extension value.
424 read16 open-elt
425
426 \ Open ServerNameList.
427 read16 open-elt
428
429 \ Find if there is a name of type 0 (host_name) with a length
430 \ that fits in our dedicated buffer.
431 begin dup while
432 read8 if
433 read-ignore-16
434 else
435 read16
436 dup 255 <= if
437 dup addr-server_name + 0 swap set8
438 addr-server_name swap read-blob
439 else
440 skip-blob
441 then
442 then
443 repeat
444
445 \ Close ServerNameList.
446 close-elt
447
448 \ Close extension value.
449 close-elt ;
450
451 \ Set the new maximum fragment length. BEWARE: this shall be called only
452 \ after reading the ClientHello and before writing the ServerHello.
453 cc: set-max-frag-len ( len -- ) {
454 size_t max_frag_len = T0_POP();
455
456 br_ssl_engine_new_max_frag_len(ENG, max_frag_len);
457
458 /*
459 * We must adjust our own output limit. Since we call this only
460 * after receiving a ClientHello and before beginning to send
461 * the ServerHello, the next output record should be empty at
462 * that point, so we can use max_frag_len as a limit.
463 */
464 if (ENG->hlen_out > max_frag_len) {
465 ENG->hlen_out = max_frag_len;
466 }
467 }
468
469 \ Read the client Max Frag Length extension.
470 : read-client-frag ( lim -- lim )
471 \ Extension value must have length exactly 1 byte.
472 read16 1 <> if ERR_BAD_FRAGLEN fail then
473 read8
474
475 \ The byte value must be 1, 2, 3 or 4.
476 dup dup 0= swap 5 >= or if ERR_BAD_FRAGLEN fail then
477
478 \ If our own maximum fragment length is greater, then we reduce
479 \ our length.
480 8 + dup addr-log_max_frag_len get8 < if
481 dup 1 swap << set-max-frag-len
482 dup addr-log_max_frag_len set8
483 addr-peer_log_max_frag_len set8
484 else
485 drop
486 then ;
487
488 \ Read the Secure Renegotiation extension from the client.
489 : read-client-reneg ( lim -- lim )
490 \ Get value length.
491 read16
492
493 \ The "reneg" value is one of:
494 \ 0 on first handshake, client support is unknown
495 \ 1 client does not support secure renegotiation
496 \ 2 client supports secure renegotiation
497 addr-reneg get8 case
498 0 of
499 \ First handshake, value length shall be 1.
500 1 = ifnot ERR_BAD_SECRENEG fail then
501 read8 if ERR_BAD_SECRENEG fail then
502 2 addr-reneg set8
503 endof
504 2 of
505 \ Renegotiation, value shall consist of 13 bytes
506 \ (header + copy of the saved client "Finished").
507 13 = ifnot ERR_BAD_SECRENEG fail then
508 read8 12 = ifnot ERR_BAD_SECRENEG fail then
509 addr-pad 12 read-blob
510 addr-saved_finished addr-pad 12 memcmp ifnot
511 ERR_BAD_SECRENEG fail
512 then
513 endof
514
515 \ If "reneg" is 1 then the client is not supposed to support
516 \ the extension, and it sends it nonetheless, which means
517 \ foul play.
518 ERR_BAD_SECRENEG fail
519 endcase ;
520
521 \ Read the Signature Algorithms extension.
522 : read-signatures ( lim -- lim )
523 \ Open extension value.
524 read16 open-elt
525
526 read-list-sign-algos addr-hashes set32
527
528 \ Close extension value.
529 close-elt ;
530
531 \ Read the Supported Curves extension.
532 : read-supported-curves ( lim -- lim )
533 \ Open extension value.
534 read16 open-elt
535
536 \ Open list of curve identifiers.
537 read16 open-elt
538
539 \ Get all supported curves.
540 0 addr-curves set32
541 begin dup while
542 read16 dup 32 < if
543 1 swap << addr-curves get32 or addr-curves set32
544 else
545 drop
546 then
547 repeat
548 close-elt
549 close-elt ;
550
551 \ Read the ALPN extension from client.
552 : read-ALPN-from-client ( lim -- lim )
553 \ If we do not have configured names, then we just ignore the
554 \ extension.
555 addr-protocol_names_num get16 ifnot read-ignore-16 ret then
556
557 \ Open extension value.
558 read16 open-elt
559
560 \ Open list of protocol names.
561 read16 open-elt
562
563 \ Get all names and test for their support. We keep the one with
564 \ the lowest index (because we apply server's preferences, as
565 \ recommended by RFC 7301, section 3.2. We set the 'found' variable
566 \ to -2 and use an unsigned comparison, making -2 a huge value.
567 -2 { found }
568 begin dup while
569 read8 dup { len } addr-pad swap read-blob
570 len test-protocol-name dup found u< if
571 >found
572 else
573 drop
574 then
575 repeat
576
577 \ End of extension.
578 close-elt
579 close-elt
580
581 \ Write back found name index (or not). If no match was found,
582 \ then we write -1 (0xFFFF) in the index value, not 0, so that
583 \ the caller knows that we tried to match, and failed.
584 found 1+ addr-selected_protocol set16 ;
585
586 \ Call policy handler to get cipher suite, hash function identifier and
587 \ certificate chain. Returned value is 0 (false) on failure.
588 cc: call-policy-handler ( -- bool ) {
589 int x;
590 br_ssl_server_choices choices;
591
592 x = (*CTX->policy_vtable)->choose(
593 CTX->policy_vtable, CTX, &choices);
594 ENG->session.cipher_suite = choices.cipher_suite;
595 CTX->sign_hash_id = choices.algo_id;
596 ENG->chain = choices.chain;
597 ENG->chain_len = choices.chain_len;
598 T0_PUSHi(-(x != 0));
599 }
600
601 \ Check for a remembered session.
602 cc: check-resume ( -- bool ) {
603 if (ENG->session.session_id_len == 32
604 && CTX->cache_vtable != NULL && (*CTX->cache_vtable)->load(
605 CTX->cache_vtable, CTX, &ENG->session))
606 {
607 T0_PUSHi(-1);
608 } else {
609 T0_PUSH(0);
610 }
611 }
612
613 \ Save the current session.
614 cc: save-session ( -- ) {
615 if (CTX->cache_vtable != NULL) {
616 (*CTX->cache_vtable)->save(
617 CTX->cache_vtable, CTX, &ENG->session);
618 }
619 }
620
621 \ Read ClientHello. If the session is resumed, then -1 is returned.
622 : read-ClientHello ( -- resume )
623 \ Get header, and check message type.
624 read-handshake-header 1 = ifnot ERR_UNEXPECTED fail then
625
626 \ Get maximum protocol version from client.
627 read16 dup { client-version-max } addr-client_max_version set16
628
629 \ Client random.
630 addr-client_random 32 read-blob
631
632 \ Client session ID.
633 read8 dup 32 > if ERR_OVERSIZED_ID fail then
634 dup addr-session_id_len set8
635 addr-session_id swap read-blob
636
637 \ Lookup session for resumption. We should do that here because
638 \ we need to verify that the remembered cipher suite is still
639 \ matched by this ClientHello.
640 check-resume { resume }
641
642 \ Cipher suites. We read all cipher suites from client, each time
643 \ matching against our own list. We accumulate suites in the
644 \ client_suites[] context buffer: we keep suites that are
645 \ supported by both the client and the server (so the list size
646 \ cannot exceed that of the server list), and we keep them in
647 \ either client or server preference order (depending on the
648 \ relevant flag).
649 \
650 \ We also need to identify the pseudo cipher suite for secure
651 \ renegotiation here.
652 read16 open-elt
653 0 { reneg-scsv }
654 0 { resume-suite }
655 addr-len-client_suites dup2 bzero
656 over + { css-off css-max }
657 begin
658 dup while
659 read16 dup { suite }
660
661 \ Check that when resuming a session, the requested
662 \ suite is still valid.
663 resume if
664 dup addr-cipher_suite get16 = if
665 -1 >resume-suite
666 then
667 then
668
669 \ Special handling for TLS_EMPTY_RENEGOTIATION_INFO_SCSV.
670 \ This fake cipher suite may occur only in the first
671 \ handshake.
672 dup 0x00FF = if
673 addr-reneg get8 if ERR_BAD_SECRENEG fail then
674 -1 >reneg-scsv
675 then
676
677 \ Special handling for TLS_FALLBACK_SCSV. If the client
678 \ maximum version is less than our own maximum version,
679 \ then this is an undue downgrade. We mark it by setting
680 \ the client max version to 0x10000.
681 dup 0x5600 = if
682 client-version-max addr-version_min get16 >=
683 client-version-max addr-version_max get16 < and if
684 -1 >client-version-max
685 then
686 then
687
688 \ Test whether the suite is supported by the server.
689 scan-suite dup 0< if
690 \ We do not support this cipher suite. Note
691 \ that this also covers the case of pseudo
692 \ cipher suites.
693 drop
694 else
695 \ If we use server order, then we place the
696 \ suite at the computed offset; otherwise, we
697 \ append it to the list at the current place.
698 0 flag? if
699 2 << addr-client_suites + suite swap set16
700 else
701 drop
702 \ We need to test for list length because
703 \ the client list may have duplicates,
704 \ that we do not filter. Duplicates are
705 \ invalid so this is not a problem if we
706 \ reject such clients.
707 css-off css-max >= if
708 ERR_BAD_HANDSHAKE fail
709 then
710 suite css-off set16
711 css-off 4 + >css-off
712 then
713 then
714 repeat
715 drop
716
717 \ Compression methods. We need method 0 (no compression).
718 0 { ok-compression }
719 read8 open-elt
720 begin dup while
721 read8 ifnot -1 >ok-compression then
722 repeat
723 close-elt
724
725 \ Set default values for parameters that may be affected by
726 \ extensions:
727 \ -- server name is empty
728 \ -- client is reputed to know RSA and ECDSA, both with SHA-1
729 \ -- the default elliptic curve is P-256 (secp256r1, id = 23)
730 0 addr-server_name set8
731 0x0404 addr-hashes set32
732 0x800000 addr-curves set32
733
734 \ Process extensions, if any.
735 dup if
736 read16 open-elt
737 begin dup while
738 read16 case
739 \ Server Name Indication.
740 0x0000 of
741 read-client-sni
742 endof
743 \ Max Frag Length.
744 0x0001 of
745 read-client-frag
746 endof
747 \ Secure Renegotiation.
748 0xFF01 of
749 read-client-reneg
750 endof
751 \ Signature Algorithms.
752 0x000D of
753 read-signatures
754 endof
755 \ Supported Curves.
756 0x000A of
757 read-supported-curves
758 endof
759 \ Supported Point Formats.
760 \ We only support "uncompressed", that all
761 \ implementations are supposed to support,
762 \ so we can simply ignore that extension.
763 \ 0x000B of
764 \ read-ignore-16
765 \ endof
766
767 \ ALPN
768 0x0010 of
769 read-ALPN-from-client
770 endof
771
772 \ Other extensions are ignored.
773 drop read-ignore-16 0
774 endcase
775 repeat
776 close-elt
777 then
778
779 \ Close message.
780 close-elt
781
782 \ Cancel session resumption if the cipher suite was not found.
783 resume resume-suite and >resume
784
785 \ Now check the received data. Since the client is expecting an
786 \ answer, we can send an appropriate fatal alert on any error.
787
788 \ Compute protocol version as the minimum of our maximum version,
789 \ and the maximum version sent by the client. If that is less than
790 \ 0x0300 (SSL-3.0), then fail. Otherwise, we may at least send an
791 \ alert with that version. We still reject versions lower than our
792 \ configured minimum.
793 \ As a special case, in case of undue downgrade, we send a specific
794 \ alert (see RFC 7507). Note that this case may happen only if
795 \ we would otherwise accept the client's version.
796 client-version-max 0< if
797 addr-client_max_version get16 addr-version_out set16
798 86 fail-alert
799 then
800 addr-version_max get16
801 dup client-version-max > if drop client-version-max then
802 dup 0x0300 < if ERR_BAD_VERSION fail then
803 client-version-max addr-version_min get16 < if
804 70 fail-alert
805 then
806 \ If resuming the session, then enforce the previously negotiated
807 \ version (if still possible).
808 resume if
809 addr-version get16 client-version-max <= if
810 drop addr-version get16
811 else
812 0 >resume
813 then
814 then
815 dup addr-version set16
816 dup addr-version_in set16
817 dup addr-version_out set16
818 0x0303 >= { can-tls12 }
819
820 \ If the client sent TLS_EMPTY_RENEGOTIATION_INFO_SCSV, then
821 \ we should mark the client as "supporting secure renegotiation".
822 reneg-scsv if 2 addr-reneg set8 then
823
824 \ Check compression.
825 ok-compression ifnot 40 fail-alert then
826
827 \ Filter hash function support by what the server also supports.
828 \ If no common hash function remains with RSA and/or ECDSA, then
829 \ the corresponding ECDHE suites are not possible.
830 supported-hash-functions drop 257 * 0xFFFF0000 or
831 addr-hashes get32 and dup addr-hashes set32
832 \ In 'can-ecdhe', bit 12 is set if ECDHE_RSA is possible, bit 13 is
833 \ set if ECDHE_ECDSA is possible.
834 dup 0xFF and 0<> neg
835 swap 8 >> 0<> 2 and or 12 << { can-ecdhe }
836
837 \ Filter supported curves. If there is no common curve between
838 \ client and us, then ECDHE suites cannot be used. Note that we
839 \ may still allow ECDH, depending on the EC key handler.
840 addr-curves get32 supported-curves and dup addr-curves set32
841 ifnot 0 >can-ecdhe then
842
843 \ If resuming a session, then the next steps are not necessary;
844 \ we won't invoke the policy handler.
845 resume if -1 ret then
846
847 \ We are not resuming, so a new session ID should be generated.
848 \ We don't check that the new ID is distinct from the one sent
849 \ by the client because probability of such an event is 2^(-256),
850 \ i.e. much (much) lower than that of an undetected transmission
851 \ error or hardware miscomputation, and with similar consequences
852 \ (handshake simply fails).
853 addr-session_id 32 mkrand
854 32 addr-session_id_len set8
855
856 \ Translate common cipher suites, then squeeze out holes: there
857 \ may be holes because of the way we fill the list when the
858 \ server preference order is enforced, and also in case some
859 \ suites are filtered out. In particular:
860 \ -- ECDHE suites are removed if there is no common hash function
861 \ (for the relevant signature algorithm) or no common curve.
862 \ -- TLS-1.2-only suites are removed if the negociated version is
863 \ TLS-1.1 or lower.
864 addr-client_suites dup >css-off
865 begin dup css-max < while
866 dup get16 dup cipher-suite-to-elements
867 dup 12 >> dup 1 = swap 2 = or if
868 dup can-ecdhe and ifnot
869 2drop 0 dup
870 then
871 then
872 can-tls12 ifnot
873 \ Suites compatible with TLS-1.0 and TLS-1.1 are
874 \ exactly the ones that use HMAC/SHA-1.
875 dup 0xF0 and 0x20 <> if
876 2drop 0 dup
877 then
878 then
879 dup if
880 css-off 2+ set16 css-off set16
881 css-off 4 + >css-off
882 else
883 2drop
884 then
885 4 +
886 repeat
887 drop
888 css-off addr-client_suites - 2 >>
889 dup ifnot
890 \ No common cipher suite: handshake failure.
891 40 fail-alert
892 then
893 addr-client_suites_num set8
894
895 \ Check ALPN.
896 addr-selected_protocol get16 0xFFFF = if
897 3 flag? if 120 fail-alert then
898 0 addr-selected_protocol set16
899 then
900
901 \ Call policy handler to obtain the cipher suite and other
902 \ parameters.
903 call-policy-handler ifnot 40 fail-alert then
904
905 \ We are not resuming a session.
906 0 ;
907
908 \ Write ServerHello.
909 : write-ServerHello ( initial -- )
910 { initial }
911 \ Compute ServerHello length.
912 2 write8 70
913
914 \ Compute length of Secure Renegotiation extension.
915 addr-reneg get8 2 = if
916 initial if 5 else 29 then
917 else
918 0
919 then
920 { ext-reneg-len }
921
922 \ Compute length of Max Fragment Length extension.
923 addr-peer_log_max_frag_len get8 if 5 else 0 then
924 { ext-max-frag-len }
925
926 \ Compute length of ALPN extension. This also copy the
927 \ selected protocol name into the pad.
928 addr-selected_protocol get16 dup if 1- copy-protocol-name 7 + then
929 { ext-ALPN-len }
930
931 \ Adjust ServerHello length to account for the extensions.
932 ext-reneg-len ext-max-frag-len + ext-ALPN-len + dup if 2 + then +
933 write24
934
935 \ Protocol version
936 addr-version get16 write16
937
938 \ Server random
939 addr-server_random 4 bzero
940 addr-server_random 4 + 28 mkrand
941 addr-server_random 32 write-blob
942
943 \ Session ID
944 \ TODO: if we have no session cache at all, we might send here
945 \ an empty session ID. This would save a bit of network
946 \ bandwidth.
947 32 write8
948 addr-session_id 32 write-blob
949
950 \ Cipher suite
951 addr-cipher_suite get16 write16
952
953 \ Compression method
954 0 write8
955
956 \ Extensions
957 ext-reneg-len ext-max-frag-len + ext-ALPN-len + dup if
958 write16
959 ext-reneg-len dup if
960 0xFF01 write16
961 4 - dup write16
962 1- addr-saved_finished swap write-blob-head8
963 else
964 drop
965 then
966 ext-max-frag-len if
967 0x0001 write16
968 1 write16 addr-peer_log_max_frag_len get8 8 - write8
969 then
970 ext-ALPN-len dup if
971 \ Note: the selected protocol name was previously
972 \ copied into the pad.
973 0x0010 write16
974 4 - dup write16
975 2- dup write16
976 1- addr-pad swap write-blob-head8
977 else
978 drop
979 then
980 else
981 drop
982 then ;
983
984 \ Do the first part of ECDHE. Returned value is the computed signature
985 \ length, or a negative error code on error.
986 cc: do-ecdhe-part1 ( curve -- len ) {
987 int curve = T0_POPi();
988 T0_PUSHi(do_ecdhe_part1(CTX, curve));
989 }
990
991 \ Write the Server Key Exchange message (if applicable).
992 : write-ServerKeyExchange ( -- )
993 addr-cipher_suite get16 use-ecdhe? ifnot ret then
994
995 \ We must select an appropriate curve among the curves that
996 \ are supported both by us and the peer. Right now we use
997 \ the one with the smallest ID, which in practice means P-256.
998 \ (TODO: add some option to make that behaviour configurable.)
999 \
1000 \ This loop always terminates because previous processing made
1001 \ sure that ECDHE suites are not selectable if there is no common
1002 \ curve.
1003 addr-curves get32 0
1004 begin dup2 >> 1 and 0= while 1+ repeat
1005 { curve-id } drop
1006
1007 \ Compute the signed curve point to send.
1008 curve-id do-ecdhe-part1 dup 0< if neg fail then { sig-len }
1009
1010 \ If using TLS-1.2+, then the hash function and signature
1011 \ algorithm are explicitly encoded in the message.
1012 addr-version get16 0x0303 >= { tls1.2+ }
1013
1014 12 write8
1015 sig-len addr-ecdhe_point_len get8 + tls1.2+ 2 and + 6 + write24
1016
1017 \ Curve parameters: named curve with 16-bit ID.
1018 3 write8 curve-id write16
1019
1020 \ Public point.
1021 addr-ecdhe_point addr-ecdhe_point_len get8 write-blob-head8
1022
1023 \ If TLS-1.2+, write hash and signature identifiers.
1024 tls1.2+ if
1025 \ sign_hash_id contains either a hash identifier,
1026 \ or the complete 16-bit value to write.
1027 addr-sign_hash_id get16
1028 dup 0xFF00 < if
1029 write16
1030 else
1031 0xFF and write8
1032 \ 'use-rsa-ecdhe?' returns -1 for RSA, 0 for
1033 \ ECDSA. The byte on the wire shall be 1 for RSA,
1034 \ 3 for ECDSA.
1035 addr-cipher_suite get16 use-rsa-ecdhe? 1 << 3 + write8
1036 then
1037 then
1038
1039 \ Signature.
1040 sig-len write16
1041 addr-pad sig-len write-blob ;
1042
1043 \ Get length of the list of anchor names to send to the client. The length
1044 \ includes the per-name 2-byte header, but _not_ the 2-byte header for
1045 \ the list itself. If no client certificate is requested, then this
1046 \ returns 0.
1047 cc: ta-names-total-length ( -- len ) {
1048 size_t u, len;
1049
1050 len = 0;
1051 if (CTX->ta_names != NULL) {
1052 for (u = 0; u < CTX->num_tas; u ++) {
1053 len += CTX->ta_names[u].len + 2;
1054 }
1055 } else if (CTX->tas != NULL) {
1056 for (u = 0; u < CTX->num_tas; u ++) {
1057 len += CTX->tas[u].dn.len + 2;
1058 }
1059 }
1060 T0_PUSH(len);
1061 }
1062
1063 \ Compute length and optionally write the contents of the list of
1064 \ supported client authentication methods.
1065 : write-list-auth ( do_write -- len )
1066 0
1067 addr-cipher_suite get16 use-ecdh? if
1068 2+ over if 65 write8 66 write8 then
1069 then
1070 supports-rsa-sign? if 1+ over if 1 write8 then then
1071 supports-ecdsa? if 1+ over if 64 write8 then then
1072 swap drop ;
1073
1074 : write-signhash-inner2 ( dow algo hashes len id -- dow algo hashes len )
1075 { id }
1076 over 1 id << and ifnot ret then
1077 2+
1078 3 pick if id write8 2 pick write8 then ;
1079
1080 : write-signhash-inner1 ( dow algo hashes -- dow len )
1081 0
1082 4 write-signhash-inner2
1083 5 write-signhash-inner2
1084 6 write-signhash-inner2
1085 3 write-signhash-inner2
1086 2 write-signhash-inner2
1087 -rot 2drop ;
1088
1089 \ Compute length and optionally write the contents of the list of
1090 \ supported sign+hash algorithms.
1091 : write-list-signhash ( do_write -- len )
1092 0 { len }
1093 \ If supporting neither RSA nor ECDSA in the engine, then we
1094 \ will do only static ECDH, and thus we claim support for
1095 \ everything (for the X.509 validator).
1096 supports-rsa-sign? supports-ecdsa? or ifnot
1097 1 0x7C write-signhash-inner1 >len
1098 3 0x7C write-signhash-inner1 len +
1099 swap drop ret
1100 then
1101 supports-rsa-sign? if
1102 1 supported-hash-functions drop
1103 write-signhash-inner1 >len
1104 then
1105 supports-ecdsa? if
1106 3 supported-hash-functions drop
1107 write-signhash-inner1 len + >len
1108 then
1109 drop len ;
1110
1111 \ Initialise index for sending the list of anchor DN.
1112 cc: begin-ta-name-list ( -- ) {
1113 CTX->cur_dn_index = 0;
1114 }
1115
1116 \ Switch to next DN in the list. Returned value is the DN length, or -1
1117 \ if the end of the list was reached.
1118 cc: begin-ta-name ( -- len ) {
1119 const br_x500_name *dn;
1120 if (CTX->cur_dn_index >= CTX->num_tas) {
1121 T0_PUSHi(-1);
1122 } else {
1123 if (CTX->ta_names == NULL) {
1124 dn = &CTX->tas[CTX->cur_dn_index].dn;
1125 } else {
1126 dn = &CTX->ta_names[CTX->cur_dn_index];
1127 }
1128 CTX->cur_dn_index ++;
1129 CTX->cur_dn = dn->data;
1130 CTX->cur_dn_len = dn->len;
1131 T0_PUSH(CTX->cur_dn_len);
1132 }
1133 }
1134
1135 \ Copy a chunk of the current DN into the pad. Returned value is the
1136 \ chunk length; this is 0 when the end of the current DN is reached.
1137 cc: copy-dn-chunk ( -- len ) {
1138 size_t clen;
1139
1140 clen = CTX->cur_dn_len;
1141 if (clen > sizeof ENG->pad) {
1142 clen = sizeof ENG->pad;
1143 }
1144 memcpy(ENG->pad, CTX->cur_dn, clen);
1145 CTX->cur_dn += clen;
1146 CTX->cur_dn_len -= clen;
1147 T0_PUSH(clen);
1148 }
1149
1150 \ Write a CertificateRequest message.
1151 : write-CertificateRequest ( -- )
1152 \ The list of client authentication types includes:
1153 \ rsa_sign (1)
1154 \ ecdsa_sign (64)
1155 \ rsa_fixed_ecdh (65)
1156 \ ecdsa_fixed_ecdh (66)
1157 \ rsa_sign and ecdsa_sign require, respectively, RSA and ECDSA
1158 \ support. Static ECDH requires that the cipher suite is ECDH.
1159 \ When we ask for static ECDH, we always send both rsa_fixed_ecdh
1160 \ and ecdsa_fixed_ecdh because what matters there is what the
1161 \ X.509 engine may support, and we do not control that.
1162 \
1163 \ With TLS 1.2, we must also send a list of supported signature
1164 \ and hash algorithms. That list is supposed to qualify both
1165 \ the engine itself, and the X.509 validator, which are separate
1166 \ in BearSSL. There again, we use the engine capabilities in that
1167 \ list, and resort to a generic all-support list if only
1168 \ static ECDH is accepted.
1169 \
1170 \ (In practice, client implementations tend to have at most one
1171 \ or two certificates, and send the chain regardless of what
1172 \ algorithms are used in it.)
1173
1174 0 write-list-auth
1175 addr-version get16 0x0303 >= if
1176 2+ 0 write-list-signhash +
1177 then
1178 ta-names-total-length + 3 +
1179
1180 \ Message header
1181 13 write8 write24
1182
1183 \ List of authentication methods
1184 0 write-list-auth write8 1 write-list-auth drop
1185
1186 \ For TLS 1.2+, list of sign+hash
1187 addr-version get16 0x0303 >= if
1188 0 write-list-signhash write16 1 write-list-signhash drop
1189 then
1190
1191 \ Trust anchor names
1192 ta-names-total-length write16
1193 begin-ta-name-list
1194 begin
1195 begin-ta-name
1196 dup 0< if drop ret then write16
1197 begin copy-dn-chunk dup while
1198 addr-pad swap write-blob
1199 repeat
1200 drop
1201 again ;
1202
1203 \ Write the Server Hello Done message.
1204 : write-ServerHelloDone ( -- )
1205 14 write8 0 write24 ;
1206
1207 \ Perform RSA decryption of the client-sent pre-master secret. The value
1208 \ is in the pad, and its length is provided as parameter.
1209 cc: do-rsa-decrypt ( len prf_id -- ) {
1210 int prf_id = T0_POPi();
1211 size_t len = T0_POP();
1212 do_rsa_decrypt(CTX, prf_id, ENG->pad, len);
1213 }
1214
1215 \ Perform ECDH (not ECDHE). The point from the client is in the pad, and
1216 \ its length is provided as parameter.
1217 cc: do-ecdh ( len prf_id -- ) {
1218 int prf_id = T0_POPi();
1219 size_t len = T0_POP();
1220 do_ecdh(CTX, prf_id, ENG->pad, len);
1221 }
1222
1223 \ Do the second part of ECDHE.
1224 cc: do-ecdhe-part2 ( len prf_id -- ) {
1225 int prf_id = T0_POPi();
1226 size_t len = T0_POP();
1227 do_ecdhe_part2(CTX, prf_id, ENG->pad, len);
1228 }
1229
1230 \ Perform static ECDH. The point from the client is the public key
1231 \ extracted from its certificate.
1232 cc: do-static-ecdh ( prf_id -- ) {
1233 do_static_ecdh(CTX, T0_POP());
1234 }
1235
1236 \ Read a ClientKeyExchange header.
1237 : read-ClientKeyExchange-header ( -- len )
1238 read-handshake-header 16 = ifnot ERR_UNEXPECTED fail then ;
1239
1240 \ Read the Client Key Exchange contents (non-empty case).
1241 : read-ClientKeyExchange-contents ( lim -- )
1242 \ What we should get depends on the cipher suite.
1243 addr-cipher_suite get16 use-rsa-keyx? if
1244 \ RSA key exchange: we expect a RSA-encrypted value.
1245 read16
1246 dup 512 > if ERR_LIMIT_EXCEEDED fail then
1247 dup { enc-rsa-len }
1248 addr-pad swap read-blob
1249 enc-rsa-len addr-cipher_suite get16 prf-id do-rsa-decrypt
1250 then
1251 addr-cipher_suite get16 dup use-ecdhe? swap use-ecdh? { ecdhe ecdh }
1252 ecdh ecdhe or if
1253 \ ECDH or ECDHE key exchange: we expect an EC point.
1254 read8 dup { ec-point-len }
1255 addr-pad swap read-blob
1256 ec-point-len addr-cipher_suite get16 prf-id
1257 ecdhe if do-ecdhe-part2 else do-ecdh then
1258 then
1259 close-elt ;
1260
1261 \ Read the Client Key Exchange (normal case).
1262 : read-ClientKeyExchange ( -- )
1263 read-ClientKeyExchange-header
1264 read-ClientKeyExchange-contents ;
1265
1266 \ Obtain all possible hash values for handshake messages so far. This
1267 \ is done because we need the hash value for the CertificateVerify
1268 \ _before_ knowing which hash function will actually be used, as this
1269 \ information is obtained from decoding the message header itself.
1270 \ All hash values are stored in the pad (208 bytes in total).
1271 cc: compute-hash-CV ( -- ) {
1272 int i;
1273
1274 for (i = 1; i <= 6; i ++) {
1275 br_multihash_out(&ENG->mhash, i,
1276 ENG->pad + HASH_PAD_OFF[i - 1]);
1277 }
1278 }
1279
1280 \ Copy the proper hash value from the pad into the dedicated buffer.
1281 \ Returned value is true (-1) on success, false (0) on error (error
1282 \ being an unimplemented hash function). The id has already been verified
1283 \ to be either 0 (for MD5+SHA-1) or one of the SHA-* functions.
1284 cc: copy-hash-CV ( hash_id -- bool ) {
1285 int id = T0_POP();
1286 size_t off, len;
1287
1288 if (id == 0) {
1289 off = 0;
1290 len = 36;
1291 } else {
1292 if (br_multihash_getimpl(&ENG->mhash, id) == 0) {
1293 T0_PUSH(0);
1294 T0_RET();
1295 }
1296 off = HASH_PAD_OFF[id - 1];
1297 len = HASH_PAD_OFF[id] - off;
1298 }
1299 memcpy(CTX->hash_CV, ENG->pad + off, len);
1300 CTX->hash_CV_len = len;
1301 CTX->hash_CV_id = id;
1302 T0_PUSHi(-1);
1303 }
1304
1305 \ Verify signature in CertificateVerify. Output is 0 on success, or a
1306 \ non-zero error code.
1307 cc: verify-CV-sig ( sig-len -- err ) {
1308 int err;
1309
1310 err = verify_CV_sig(CTX, T0_POP());
1311 T0_PUSHi(err);
1312 }
1313
1314 \ Process static ECDH.
1315 : process-static-ECDH ( ktu -- )
1316 \ Static ECDH is allowed only if the cipher suite uses ECDH, and
1317 \ the client's public key has type EC and allows key exchange.
1318 \ BR_KEYTYPE_KEYX is 0x10, and BR_KEYTYPE_EC is 2.
1319 0x1F and 0x12 = ifnot ERR_WRONG_KEY_USAGE fail then
1320 addr-cipher_suite get16
1321 dup use-ecdh? ifnot ERR_UNEXPECTED fail then
1322 prf-id
1323 do-static-ecdh ;
1324
1325 \ Read CertificateVerify header.
1326 : read-CertificateVerify-header ( -- lim )
1327 compute-hash-CV
1328 read-handshake-header 15 = ifnot ERR_UNEXPECTED fail then ;
1329
1330 \ Read CertificateVerify. The client key type + usage is expected on the
1331 \ stack.
1332 : read-CertificateVerify ( ktu -- )
1333 \ Check that the key allows for signatures.
1334 dup 0x20 and ifnot ERR_WRONG_KEY_USAGE fail then
1335 0x0F and { key-type }
1336
1337 \ Get header.
1338 read-CertificateVerify-header
1339
1340 \ With TLS 1.2+, there is an explicit hash + signature indication,
1341 \ which must be compatible with the key type.
1342 addr-version get16 0x0303 >= if
1343 \ Get hash function, then signature algorithm. The
1344 \ signature algorithm is 1 (RSA) or 3 (ECDSA) while our
1345 \ symbolic constants for key types are 1 (RSA) or 2 (EC).
1346 read16
1347 dup 0xFF and 1+ 1 >> key-type = ifnot
1348 ERR_BAD_SIGNATURE fail
1349 then
1350 8 >>
1351
1352 \ We support only SHA-1, SHA-224, SHA-256, SHA-384
1353 \ and SHA-512. We explicitly reject MD5.
1354 dup 2 < over 6 > or if ERR_INVALID_ALGORITHM fail then
1355 else
1356 \ With TLS 1.0 and 1.1, hash is MD5+SHA-1 (0) for RSA,
1357 \ SHA-1 (2) for ECDSA.
1358 key-type 0x01 = if 0 else 2 then
1359 then
1360 copy-hash-CV ifnot ERR_INVALID_ALGORITHM fail then
1361
1362 \ Read signature.
1363 read16 dup { sig-len }
1364 dup 512 > if ERR_LIMIT_EXCEEDED fail then
1365 addr-pad swap read-blob
1366 sig-len verify-CV-sig
1367 dup if fail then drop
1368
1369 close-elt ;
1370
1371 \ Send a HelloRequest.
1372 : send-HelloRequest ( -- )
1373 flush-record
1374 begin can-output? not while wait-co drop repeat
1375 22 addr-record_type_out set8
1376 0 write8 0 write24 flush-record
1377 23 addr-record_type_out set8 ;
1378
1379 \ Make a handshake.
1380 : do-handshake ( initial -- )
1381 0 addr-application_data set8
1382 22 addr-record_type_out set8
1383 0 addr-selected_protocol set16
1384 multihash-init
1385 read-ClientHello
1386 more-incoming-bytes? if ERR_UNEXPECTED fail then
1387 if
1388 \ Session resumption
1389 write-ServerHello
1390 0 write-CCS-Finished
1391 0 read-CCS-Finished
1392 else
1393 \ Not a session resumption
1394 write-ServerHello
1395 write-Certificate drop
1396 write-ServerKeyExchange
1397 ta-names-total-length if
1398 write-CertificateRequest
1399 then
1400 write-ServerHelloDone
1401 flush-record
1402
1403 \ If we sent a CertificateRequest then we expect a
1404 \ Certificate message.
1405 ta-names-total-length if
1406 \ Read client certificate.
1407 0 read-Certificate
1408
1409 choice
1410 dup 0< uf
1411 \ Client certificate validation failed.
1412 2 flag? ifnot neg fail then
1413 drop
1414 read-ClientKeyExchange
1415 read-CertificateVerify-header
1416 dup skip-blob drop
1417 enduf
1418 dup 0= uf
1419 \ Client sent no certificate at all.
1420 drop
1421 2 flag? ifnot
1422 ERR_NO_CLIENT_AUTH fail
1423 then
1424 read-ClientKeyExchange
1425 enduf
1426
1427 \ Client certificate was validated.
1428 read-ClientKeyExchange-header
1429 dup ifnot
1430 \ Empty ClientKeyExchange.
1431 drop
1432 process-static-ECDH
1433 else
1434 read-ClientKeyExchange-contents
1435 read-CertificateVerify
1436 then
1437 endchoice
1438 else
1439 \ No client certificate request, we just expect
1440 \ a non-empty ClientKeyExchange.
1441 read-ClientKeyExchange
1442 then
1443 0 read-CCS-Finished
1444 0 write-CCS-Finished
1445 save-session
1446 then
1447 1 addr-application_data set8
1448 23 addr-record_type_out set8 ;
1449
1450 \ Entry point.
1451 : main ( -- ! )
1452 \ Perform initial handshake.
1453 -1 do-handshake
1454
1455 begin
1456 \ Wait for further invocation. At that point, we should
1457 \ get either an explicit call for renegotiation, or
1458 \ an incoming ClientHello handshake message.
1459 wait-co
1460 dup 0x07 and case
1461 0x00 of
1462 0x10 and if
1463 \ The best we can do is ask for a
1464 \ renegotiation, then wait for it
1465 \ to happen.
1466 send-HelloRequest
1467 then
1468 endof
1469 0x01 of
1470 \ Reject renegotiations if the peer does not
1471 \ support secure renegotiation, or if the
1472 \ "no renegotiation" flag is set.
1473 drop
1474 addr-reneg get8 1 = 1 flag? or if
1475 flush-record
1476 begin can-output? not while
1477 wait-co drop
1478 repeat
1479 100 send-warning
1480 else
1481 0 do-handshake
1482 then
1483 endof
1484 ERR_UNEXPECTED fail
1485 endcase
1486 again
1487 ;