Added support for TLS_FALLBACK_SCSV.
[BearSSL] / src / ssl / ssl_hs_common.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 \ This is the common T0 code for processing handshake messages (code that
25 \ is used by both client and server).
26
27 preamble {
28
29 #include <stddef.h>
30 #include <string.h>
31
32 #include "inner.h"
33
34 /*
35 * This macro evaluates to a pointer to the current engine context.
36 */
37 #define ENG ((br_ssl_engine_context *)((unsigned char *)t0ctx - offsetof(br_ssl_engine_context, cpu)))
38
39 }
40
41 \ IMPLEMENTATION NOTES
42 \ ====================
43 \
44 \ This code handles all records except application data records.
45 \ Application data is accepted (incoming records, outgoing payload data)
46 \ only when the application_data flag is set, which is done at the end
47 \ of the handshake; and it is cleared whenever a renegotiation or a
48 \ closure takes place.
49 \
50 \ Incoming alerts are processed on the fly; fatal alerts terminate the
51 \ context, while warnings are ignored, except for close_notify, which
52 \ triggers the closure procedure. That procedure never returns (it ends
53 \ with an 'ERR_OK fail' call). We can thus make this processing right
54 \ into the read functions.
55 \
56 \ Specific actions from the caller (closure or renegotiation) may happen
57 \ only when jumping back into the T0 code, i.e. just after a 'co' call.
58 \ Similarly, incoming record type may change only while the caller has
59 \ control, so we need to check that type only when returning from a 'co'.
60 \
61 \ The handshake processor needs to defer back to the caller ('co') only
62 \ in one of the following situations:
63 \
64 \ -- Some handshake data is expected.
65 \
66 \ -- The handshake is finished, and application data may flow. There may
67 \ be some incoming handshake data (HelloRequest from the server). This
68 \ is the only situation where a renegotiation call won't be ignored.
69 \
70 \ -- Some change-cipher-spec data is expected.
71 \
72 \ -- An alert record is expected. Other types of incoming records will be
73 \ skipped.
74 \
75 \ -- Waiting for the currently accumulated record to be sent and the
76 \ output buffer to become free again for another record.
77
78 \ Placeholder for handling not yet implemented functionalities.
79 : NYI ( -- ! )
80 "NOT YET IMPLEMENTED!" puts cr -1 fail ;
81
82 \ Mark the context as failed with a specific error code. This also
83 \ returns control to the caller.
84 cc: fail ( err -- ! ) {
85 br_ssl_engine_fail(ENG, (int)T0_POPi());
86 T0_CO();
87 }
88
89 \ Read a byte from the context (address is offset in context).
90 cc: get8 ( addr -- val ) {
91 size_t addr = (size_t)T0_POP();
92 T0_PUSH(*((unsigned char *)ENG + addr));
93 }
94
95 \ Read a 16-bit word from the context (address is offset in context).
96 cc: get16 ( addr -- val ) {
97 size_t addr = (size_t)T0_POP();
98 T0_PUSH(*(uint16_t *)((unsigned char *)ENG + addr));
99 }
100
101 \ Read a 32-bit word from the context (address is offset in context).
102 cc: get32 ( addr -- val ) {
103 size_t addr = (size_t)T0_POP();
104 T0_PUSH(*(uint32_t *)((unsigned char *)ENG + addr));
105 }
106
107 \ Set a byte in the context (address is offset in context).
108 cc: set8 ( val addr -- ) {
109 size_t addr = (size_t)T0_POP();
110 *((unsigned char *)ENG + addr) = (unsigned char)T0_POP();
111 }
112
113 \ Set a 16-bit word in the context (address is offset in context).
114 cc: set16 ( val addr -- ) {
115 size_t addr = (size_t)T0_POP();
116 *(uint16_t *)((unsigned char *)ENG + addr) = (uint16_t)T0_POP();
117 }
118
119 \ Set a 32-bit word in the context (address is offset in context).
120 cc: set32 ( val addr -- ) {
121 size_t addr = (size_t)T0_POP();
122 *(uint32_t *)((unsigned char *)ENG + addr) = (uint32_t)T0_POP();
123 }
124
125 \ Define a word that evaluates as an address of a field within the
126 \ engine context. The field name (C identifier) must follow in the
127 \ source. For field 'foo', the defined word is 'addr-foo'.
128 : addr-eng:
129 next-word { field }
130 "addr-" field + 0 1 define-word
131 0 8191 "offsetof(br_ssl_engine_context, " field + ")" + make-CX
132 postpone literal postpone ; ;
133
134 addr-eng: max_frag_len
135 addr-eng: log_max_frag_len
136 addr-eng: peer_log_max_frag_len
137 addr-eng: shutdown_recv
138 addr-eng: record_type_in
139 addr-eng: record_type_out
140 addr-eng: version_in
141 addr-eng: version_out
142 addr-eng: application_data
143 addr-eng: version_min
144 addr-eng: version_max
145 addr-eng: suites_buf
146 addr-eng: suites_num
147 addr-eng: server_name
148 \ addr-eng: version
149 \ addr-eng: cipher_suite
150 addr-eng: client_random
151 addr-eng: server_random
152 \ addr-eng: session_id_len
153 \ addr-eng: session_id
154 addr-eng: ecdhe_curve
155 addr-eng: ecdhe_point
156 addr-eng: ecdhe_point_len
157 addr-eng: reneg
158 addr-eng: saved_finished
159 addr-eng: pad
160 addr-eng: action
161 addr-eng: alert
162 addr-eng: close_received
163
164 \ Similar to 'addr-eng:', for fields in the 'session' substructure.
165 : addr-session-field:
166 next-word { field }
167 "addr-" field + 0 1 define-word
168 0 8191 "offsetof(br_ssl_engine_context, session) + offsetof(br_ssl_session_parameters, " field + ")" + make-CX
169 postpone literal postpone ; ;
170
171 addr-session-field: session_id
172 addr-session-field: session_id_len
173 addr-session-field: version
174 addr-session-field: cipher_suite
175 addr-session-field: master_secret
176
177 \ Define a word that evaluates to an error constant. This assumes that
178 \ all relevant error codes are in the 0..63 range.
179 : err:
180 next-word { name }
181 name 0 1 define-word
182 0 63 "BR_" name + make-CX postpone literal postpone ; ;
183
184 err: ERR_OK
185 err: ERR_BAD_PARAM
186 err: ERR_BAD_STATE
187 err: ERR_UNSUPPORTED_VERSION
188 err: ERR_BAD_VERSION
189 err: ERR_BAD_LENGTH
190 err: ERR_TOO_LARGE
191 err: ERR_BAD_MAC
192 err: ERR_NO_RANDOM
193 err: ERR_UNKNOWN_TYPE
194 err: ERR_UNEXPECTED
195 err: ERR_BAD_CCS
196 err: ERR_BAD_ALERT
197 err: ERR_BAD_HANDSHAKE
198 err: ERR_OVERSIZED_ID
199 err: ERR_BAD_CIPHER_SUITE
200 err: ERR_BAD_COMPRESSION
201 err: ERR_BAD_FRAGLEN
202 err: ERR_BAD_SECRENEG
203 err: ERR_EXTRA_EXTENSION
204 err: ERR_BAD_SNI
205 err: ERR_BAD_HELLO_DONE
206 err: ERR_LIMIT_EXCEEDED
207 err: ERR_BAD_FINISHED
208 err: ERR_RESUME_MISMATCH
209 err: ERR_INVALID_ALGORITHM
210
211 \ Get supported curves (bit mask).
212 cc: supported-curves ( -- x ) {
213 uint32_t x = ENG->iec == NULL ? 0 : ENG->iec->supported_curves;
214 T0_PUSH(x);
215 }
216
217 \ Get supported hash functions (bit mask and number).
218 cc: supported-hash-functions ( -- x num ) {
219 int i;
220 unsigned x, num;
221
222 x = 0;
223 num = 0;
224 for (i = br_sha1_ID; i <= br_sha512_ID; i ++) {
225 if (br_multihash_getimpl(&ENG->mhash, i)) {
226 x |= 1U << i;
227 num ++;
228 }
229 }
230 T0_PUSH(x);
231 T0_PUSH(num);
232 }
233
234 \ (Re)initialise the multihasher.
235 cc: multihash-init ( -- ) {
236 br_multihash_init(&ENG->mhash);
237 }
238
239 \ Flush the current record: if some payload data has been accumulated,
240 \ close the record and schedule it for sending. If there is no such data,
241 \ this function does nothing.
242 cc: flush-record ( -- ) {
243 br_ssl_engine_flush_record(ENG);
244 }
245
246 \ Yield control to the caller.
247 \ When the control is returned to us, react to the new context. Returned
248 \ value is a bitwise combination of the following:
249 \ 0x01 handshake data is available
250 \ 0x02 change-cipher-spec data is available
251 \ 0x04 some data other than handshake or change-cipher-spec is available
252 \ 0x08 output buffer is ready for a new outgoing record
253 \ 0x10 renegotiation is requested and not to be ignored
254 \ Flags 0x01, 0x02 and 0x04 are mutually exclusive.
255 : wait-co ( -- state )
256 co
257 0
258 addr-action get8 dup if
259 case
260 1 of 0 do-close endof
261 2 of addr-application_data get8 if 0x10 or then endof
262 endcase
263 else
264 drop
265 then
266 addr-close_received get8 ifnot
267 has-input? if
268 addr-record_type_in get8 case
269
270 \ ChangeCipherSpec
271 20 of 0x02 or endof
272
273 \ Alert -- if close_notify received, trigger
274 \ the closure sequence.
275 21 of process-alerts if -1 do-close then endof
276
277 \ Handshake
278 22 of 0x01 or endof
279
280 \ Not CCS, Alert or Handshake.
281 drop 0x04 or 0
282 endcase
283 then
284 then
285 can-output? if 0x08 or then ;
286
287 \ Send an alert message. This shall be called only when there is room for
288 \ an outgoing record.
289 : send-alert ( level alert -- )
290 21 addr-record_type_out set8
291 swap write8-native drop write8-native drop
292 flush-record ;
293
294 \ Send an alert message of level "warning". This shall be called only when
295 \ there is room for an outgoing record.
296 : send-warning ( alert -- )
297 1 swap send-alert ;
298
299 \ Fail by sending a fatal alert.
300 : fail-alert ( alert -- ! )
301 { alert }
302 flush-record
303 begin can-output? not while wait-co drop repeat
304 2 alert send-alert
305 begin can-output? not while wait-co drop repeat
306 alert 512 + fail ;
307
308 \ Perform the close operation:
309 \ -- Prevent new application data from the caller.
310 \ -- Incoming data is discarded (except alerts).
311 \ -- Outgoing data is flushed.
312 \ -- A close_notify alert is sent.
313 \ -- If 'cnr' is zero, then incoming data is discarded until a close_notify
314 \ is received.
315 \ -- At the end, the context is terminated.
316 : do-close ( cnr -- ! )
317 \ 'cnr' is set to non-zero when a close_notify is received from
318 \ the peer.
319 { cnr }
320
321 \ Get out of application data state.
322 0 addr-application_data set8
323
324 \ Flush existing payload if any.
325 flush-record
326
327 \ Wait for room to send the close_notify. Since individual records
328 \ can always hold at least 512 bytes, we know that when there is
329 \ room, then there is room for a complete close_notify (two bytes).
330 begin can-output? not while cnr wait-for-close >cnr repeat
331
332 \ Write the close_notify and flush it.
333 \ 21 addr-record_type_out set8
334 \ 1 write8-native 0 write8-native 2drop
335 \ flush-record
336 0 send-warning
337
338 \ Loop until our record has been sent (we know it's gone when
339 \ writing is again possible) and a close_notify has been received.
340 cnr
341 begin
342 dup can-output? and if ERR_OK fail then
343 wait-for-close
344 again ;
345
346 \ Yield control to the engine, with a possible flush. If 'cnr' is 0,
347 \ then input is analysed: all input is discarded, until a close_notify
348 \ is received.
349 : wait-for-close ( cnr -- cnr )
350 co
351 dup ifnot
352 has-input? if
353 addr-record_type_in get8 21 = if
354 drop process-alerts
355 else
356 discard-input
357 then
358 then
359 then ;
360
361 \ Test whether there is some accumulated payload that still needs to be
362 \ sent.
363 cc: payload-to-send? ( -- bool ) {
364 T0_PUSHi(-br_ssl_engine_has_pld_to_send(ENG));
365 }
366
367 \ Test whether there is some available input data.
368 cc: has-input? ( -- bool ) {
369 T0_PUSHi(-(ENG->hlen_in != 0));
370 }
371
372 \ Test whether some payload bytes may be written.
373 cc: can-output? ( -- bool ) {
374 T0_PUSHi(-(ENG->hlen_out > 0));
375 }
376
377 \ Discard current input entirely.
378 cc: discard-input ( -- ) {
379 ENG->hlen_in = 0;
380 }
381
382 \ Low-level read for one byte. If there is no available byte right
383 \ away, then -1 is returned. Otherwise, the byte value is returned.
384 \ If the current record type is "handshake" then the read byte is also
385 \ injected in the multi-hasher.
386 cc: read8-native ( -- x ) {
387 if (ENG->hlen_in > 0) {
388 unsigned char x;
389
390 x = *ENG->hbuf_in ++;
391 if (ENG->record_type_in == BR_SSL_HANDSHAKE) {
392 br_multihash_update(&ENG->mhash, &x, 1);
393 }
394 T0_PUSH(x);
395 ENG->hlen_in --;
396 } else {
397 T0_PUSHi(-1);
398 }
399 }
400
401 \ Low-level read for several bytes. On entry, this expects an address
402 \ (offset in the engine context) and a length; these values designate
403 \ where the chunk should go. Upon exit, the new address and length
404 \ are pushed; that output length contains how many bytes could not be
405 \ read. If there is no available byte for reading, the address and
406 \ length are unchanged.
407 \ If the current record type is "handshake" then the read bytes are
408 \ injected in the multi-hasher.
409 cc: read-chunk-native ( addr len -- addr len ) {
410 size_t clen = ENG->hlen_in;
411 if (clen > 0) {
412 uint32_t addr, len;
413
414 len = T0_POP();
415 addr = T0_POP();
416 if ((size_t)len < clen) {
417 clen = (size_t)len;
418 }
419 memcpy((unsigned char *)ENG + addr, ENG->hbuf_in, clen);
420 if (ENG->record_type_in == BR_SSL_HANDSHAKE) {
421 br_multihash_update(&ENG->mhash, ENG->hbuf_in, clen);
422 }
423 T0_PUSH(addr + (uint32_t)clen);
424 T0_PUSH(len - (uint32_t)clen);
425 ENG->hbuf_in += clen;
426 ENG->hlen_in -= clen;
427 }
428 }
429
430 \ Process available alert bytes. If a fatal alert is received, then the
431 \ context is terminated; otherwise, this returns either true (-1) if a
432 \ close_notify was received, false (0) otherwise.
433 : process-alerts ( -- bool )
434 0
435 begin has-input? while read8-native process-alert-byte or repeat
436 dup if 1 addr-shutdown_recv set8 then ;
437
438 \ Process an alert byte. Returned value is non-zero if this is a close_notify,
439 \ zero otherwise.
440 : process-alert-byte ( x -- bool )
441 addr-alert get8 case
442 0 of
443 \ 'alert' field is 0, so this byte shall be a level.
444 \ Levels shall be 1 (warning) or 2 (fatal); we convert
445 \ all other values to "fatal".
446 dup 1 <> if drop 2 then
447 addr-alert set8 0
448 endof
449 1 of
450 0 addr-alert set8
451 \ close_notify has value 0.
452 0= ret
453 endof
454 \ Fatal alert implies context termination.
455 drop 256 + fail
456 endcase ;
457
458 \ In general we only deal with handshake data here. Alerts are processed
459 \ in specific code right when they are received, and ChangeCipherSpec has
460 \ its own handling code. So we need to check that the data is "handshake"
461 \ only when returning from a coroutine call.
462
463 \ Yield control to the engine. Alerts are processed; if incoming data is
464 \ neither handshake or alert, then an error is triggered.
465 : wait-for-handshake ( -- )
466 wait-co 0x07 and 0x01 > if ERR_UNEXPECTED fail then ;
467
468 \ Flush outgoing data (if any), then wait for the output buffer to be
469 \ clear; when this is done, set the output record type to the specified
470 \ value.
471 : wait-rectype-out ( rectype -- )
472 { rectype }
473 flush-record
474 begin
475 can-output? if rectype addr-record_type_out set8 ret then
476 wait-co drop
477 again ;
478
479 \ Read one byte of handshake data. Block until that byte is available.
480 \ This does not check any length.
481 : read8-nc ( -- x )
482 begin
483 read8-native dup 0< ifnot ret then
484 drop wait-for-handshake
485 again ;
486
487 \ Test whether there are some more bytes in the current record. These
488 \ bytes have not necessarily been received yet (processing of unencrypted
489 \ records may begin before all bytes are received).
490 cc: more-incoming-bytes? ( -- bool ) {
491 T0_PUSHi(ENG->hlen_in != 0 || !br_ssl_engine_recvrec_finished(ENG));
492 }
493
494 \ For reading functions, the TOS is supposed to contain the number of bytes
495 \ that can still be read (from encapsulating structure header), and it is
496 \ updated.
497
498 : check-len ( lim len -- lim )
499 - dup 0< if ERR_BAD_PARAM fail then ;
500
501 \ Read one byte of handshake data. This pushes an integer in the 0..255 range.
502 : read8 ( lim -- lim x )
503 1 check-len read8-nc ;
504
505 \ Read a 16-bit value (in the 0..65535 range)
506 : read16 ( lim -- lim n )
507 2 check-len read8-nc 8 << read8-nc + ;
508
509 \ Read a 24-bit value (in the 0..16777215 range)
510 : read24 ( lim -- lim n )
511 3 check-len read8-nc 8 << read8-nc + 8 << read8-nc + ;
512
513 \ Read some bytes. The "address" is an offset within the context
514 \ structure.
515 : read-blob ( lim addr len -- lim )
516 { addr len }
517 len check-len
518 addr len
519 begin
520 read-chunk-native
521 dup 0 = if 2drop ret then
522 wait-for-handshake
523 again ;
524
525 \ Read some bytes and drop them.
526 : skip-blob ( lim len -- lim )
527 swap over check-len swap
528 begin dup while read8-nc drop 1- repeat
529 drop ;
530
531 \ Read a 16-bit length, then skip exactly that many bytes.
532 : read-ignore-16 ( lim -- lim )
533 read16 skip-blob ;
534
535 \ Open a substructure: the inner structure length is checked against,
536 \ and substracted, from the output structure current limit.
537 : open-elt ( lim len -- lim-outer lim-inner )
538 dup { len }
539 - dup 0< if ERR_BAD_PARAM fail then
540 len ;
541
542 \ Close the current structure. This checks that the limit is 0.
543 : close-elt ( lim -- )
544 if ERR_BAD_PARAM fail then ;
545
546 \ Write one byte of handshake data.
547 : write8 ( n -- )
548 begin
549 dup write8-native if drop ret then
550 wait-co drop
551 again ;
552
553 \ Low-level write for one byte. On exit, it pushes either -1 (byte was
554 \ written) or 0 (no room in output buffer).
555 cc: write8-native ( x -- bool ) {
556 unsigned char x;
557
558 x = (unsigned char)T0_POP();
559 if (ENG->hlen_out > 0) {
560 if (ENG->record_type_out == BR_SSL_HANDSHAKE) {
561 br_multihash_update(&ENG->mhash, &x, 1);
562 }
563 *ENG->hbuf_out ++ = x;
564 ENG->hlen_out --;
565 T0_PUSHi(-1);
566 } else {
567 T0_PUSHi(0);
568 }
569 }
570
571 \ Write a 16-bit value.
572 : write16 ( n -- )
573 dup 8 u>> write8 write8 ;
574
575 \ Write a 24-bit value.
576 : write24 ( n -- )
577 dup 16 u>> write8 write16 ;
578
579 \ Write some bytes. The "address" is an offset within the context
580 \ structure.
581 : write-blob ( addr len -- )
582 begin
583 write-blob-chunk
584 dup 0 = if 2drop ret then
585 wait-co drop
586 again ;
587
588 cc: write-blob-chunk ( addr len -- addr len ) {
589 size_t clen = ENG->hlen_out;
590 if (clen > 0) {
591 uint32_t addr, len;
592
593 len = T0_POP();
594 addr = T0_POP();
595 if ((size_t)len < clen) {
596 clen = (size_t)len;
597 }
598 memcpy(ENG->hbuf_out, (unsigned char *)ENG + addr, clen);
599 if (ENG->record_type_out == BR_SSL_HANDSHAKE) {
600 br_multihash_update(&ENG->mhash, ENG->hbuf_out, clen);
601 }
602 T0_PUSH(addr + (uint32_t)clen);
603 T0_PUSH(len - (uint32_t)clen);
604 ENG->hbuf_out += clen;
605 ENG->hlen_out -= clen;
606 }
607 }
608
609 \ Write a blob with the length as header (over one byte)
610 : write-blob-head8 ( addr len -- )
611 dup write8 write-blob ;
612
613 \ Write a blob with the length as header (over two bytes)
614 : write-blob-head16 ( addr len -- )
615 dup write16 write-blob ;
616
617 \ Perform a byte-to-byte comparison between two blobs. Each blob is
618 \ provided as an "address" (offset in the context structure); the
619 \ length is common. Returned value is true (-1) if the two blobs are
620 \ equal, false (0) otherwise.
621 cc: memcmp ( addr1 addr2 len -- bool ) {
622 size_t len = (size_t)T0_POP();
623 void *addr2 = (unsigned char *)ENG + (size_t)T0_POP();
624 void *addr1 = (unsigned char *)ENG + (size_t)T0_POP();
625 int x = memcmp(addr1, addr2, len);
626 T0_PUSH((uint32_t)-(x == 0));
627 }
628
629 \ Copy bytes between two areas, whose addresses are provided as
630 \ offsets in the context structure.
631 cc: memcpy ( dst src len -- ) {
632 size_t len = (size_t)T0_POP();
633 void *src = (unsigned char *)ENG + (size_t)T0_POP();
634 void *dst = (unsigned char *)ENG + (size_t)T0_POP();
635 memcpy(dst, src, len);
636 }
637
638 \ Get string length (zero-terminated). The string address is provided as
639 \ an offset relative to the context start. Returned length does not include
640 \ the terminated 0.
641 cc: strlen ( str -- len ) {
642 void *str = (unsigned char *)ENG + (size_t)T0_POP();
643 T0_PUSH((uint32_t)strlen(str));
644 }
645
646 \ Fill a buffer with zeros. The buffer address is an offset in the context.
647 cc: bzero ( addr len -- ) {
648 size_t len = (size_t)T0_POP();
649 void *addr = (unsigned char *)ENG + (size_t)T0_POP();
650 memset(addr, 0, len);
651 }
652
653 \ Scan the list of supported cipher suites for a given value. If found,
654 \ then the list index at which it was found is returned; otherwise, -1
655 \ is returned.
656 : scan-suite ( suite -- index )
657 { suite }
658 addr-suites_num get8 { num }
659 0
660 begin dup num < while
661 dup 1 << addr-suites_buf + get16 suite = if ret then
662 1+
663 repeat
664 drop -1 ;
665
666 \ =======================================================================
667
668 \ Generate random bytes into buffer (address is offset in context).
669 cc: mkrand ( addr len -- ) {
670 size_t len = (size_t)T0_POP();
671 void *addr = (unsigned char *)ENG + (size_t)T0_POP();
672 br_hmac_drbg_generate(&ENG->rng, addr, len);
673 }
674
675 \ Read a handshake message header: type and length. These are returned
676 \ in reverse order (type is TOS, length is below it).
677 : read-handshake-header-core ( -- lim type )
678 read8-nc 3 read24 swap drop swap ;
679
680 \ Read a handshake message header: type and length. If the header is for
681 \ a HelloRequest message, then it is discarded and a new header is read
682 \ (repeatedly if necessary).
683 : read-handshake-header ( -- lim type )
684 begin
685 read-handshake-header-core dup 0= while
686 drop if ERR_BAD_HANDSHAKE fail then
687 repeat ;
688
689 \ =======================================================================
690
691 \ Cipher suite processing.
692 \
693 \ Unfortunately, cipher suite identifiers are attributed mostly arbitrary,
694 \ so we have to map the cipher suite numbers we support into aggregate
695 \ words that encode the information we need. Table below is organized
696 \ as a sequence of pairs of 16-bit words, the first being the cipher suite
697 \ identifier, the second encoding the algorithm elements. The suites are
698 \ ordered by increasing cipher suite ID, so that fast lookups may be
699 \ performed with a binary search (not implemented for the moment, since it
700 \ does not appear to matter much in practice).
701 \
702 \ Algorithm elements are encoded over 4 bits each, in the following order
703 \ (most significant to least significant):
704 \
705 \ -- Server key type:
706 \ 0 RSA (RSA key exchange)
707 \ 1 ECDHE-RSA (ECDHE key exchange, RSA signature)
708 \ 2 ECDHE-ECDSA (ECDHE key exchange, ECDSA signature)
709 \ 3 ECDH-RSA (ECDH key exchange, certificate is RSA-signed)
710 \ 4 ECDH-ECDSA (ECDH key exchange, certificate is ECDSA-signed)
711 \ -- Encryption algorithm:
712 \ 0 3DES/CBC
713 \ 1 AES-128/CBC
714 \ 2 AES-256/CBC
715 \ 3 AES-128/GCM
716 \ 4 AES-256/GCM
717 \ 5 ChaCha20/Poly1305
718 \ -- MAC algorithm:
719 \ 0 none (for suites with AEAD encryption)
720 \ 2 HMAC/SHA-1
721 \ 4 HMAC/SHA-256
722 \ 5 HMAC/SHA-384
723 \ -- PRF for TLS-1.2:
724 \ 4 with SHA-256
725 \ 5 with SHA-384
726
727 data: cipher-suite-def
728
729 hexb| 000A 0024 | \ TLS_RSA_WITH_3DES_EDE_CBC_SHA
730 hexb| 002F 0124 | \ TLS_RSA_WITH_AES_128_CBC_SHA
731 hexb| 0035 0224 | \ TLS_RSA_WITH_AES_256_CBC_SHA
732 hexb| 003C 0144 | \ TLS_RSA_WITH_AES_128_CBC_SHA256
733 hexb| 003D 0244 | \ TLS_RSA_WITH_AES_256_CBC_SHA256
734
735 hexb| 009C 0304 | \ TLS_RSA_WITH_AES_128_GCM_SHA256
736 hexb| 009D 0405 | \ TLS_RSA_WITH_AES_256_GCM_SHA384
737
738 hexb| C003 4024 | \ TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
739 hexb| C004 4124 | \ TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
740 hexb| C005 4224 | \ TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
741 hexb| C008 2024 | \ TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
742 hexb| C009 2124 | \ TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
743 hexb| C00A 2224 | \ TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
744 hexb| C00D 3024 | \ TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
745 hexb| C00E 3124 | \ TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
746 hexb| C00F 3224 | \ TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
747 hexb| C012 1024 | \ TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
748 hexb| C013 1124 | \ TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
749 hexb| C014 1224 | \ TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
750
751 hexb| C023 2144 | \ TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
752 hexb| C024 2255 | \ TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
753 hexb| C025 4144 | \ TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
754 hexb| C026 4255 | \ TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
755 hexb| C027 1144 | \ TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
756 hexb| C028 1255 | \ TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
757 hexb| C029 3144 | \ TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
758 hexb| C02A 3255 | \ TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
759 hexb| C02B 2304 | \ TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
760 hexb| C02C 2405 | \ TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
761 hexb| C02D 4304 | \ TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
762 hexb| C02E 4405 | \ TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
763 hexb| C02F 1304 | \ TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
764 hexb| C030 1405 | \ TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
765 hexb| C031 3304 | \ TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
766 hexb| C032 3405 | \ TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
767
768 hexb| CCA8 1504 | \ TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
769 hexb| CCA9 2504 | \ TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
770
771 hexb| 0000 | \ List terminator.
772
773 \ Convert cipher suite identifier to element words. This returns 0 if
774 \ the cipher suite is not known.
775 : cipher-suite-to-elements ( suite -- elts )
776 { id }
777 cipher-suite-def
778 begin
779 dup 2+ swap data-get16
780 dup ifnot 2drop 0 ret then
781 id = if data-get16 ret then
782 2+
783 again ;
784
785 \ Check that a given cipher suite is supported. Note that this also
786 \ returns true (-1) for the TLS_FALLBACK_SCSV pseudo-ciphersuite.
787 : suite-supported? ( suite -- bool )
788 dup 0x5600 = if drop -1 ret then
789 cipher-suite-to-elements 0<> ;
790
791 \ Get expected key type for cipher suite. The key type is one of
792 \ BR_KEYTYPE_RSA or BR_KEYTYPE_EC, combined with either BR_KEYTYPE_KEYX
793 \ (RSA encryption or static ECDH) or BR_KEYTYPE_SIGN (RSA or ECDSA
794 \ signature, for ECDHE cipher suites).
795 : expected-key-type ( suite -- key-type )
796 cipher-suite-to-elements 12 >>
797 case
798 0 of CX 0 63 { BR_KEYTYPE_RSA | BR_KEYTYPE_KEYX } endof
799 1 of CX 0 63 { BR_KEYTYPE_RSA | BR_KEYTYPE_SIGN } endof
800 2 of CX 0 63 { BR_KEYTYPE_EC | BR_KEYTYPE_SIGN } endof
801 3 of CX 0 63 { BR_KEYTYPE_EC | BR_KEYTYPE_KEYX } endof
802 4 of CX 0 63 { BR_KEYTYPE_EC | BR_KEYTYPE_KEYX } endof
803 0 swap
804 endcase ;
805
806 \ Test whether the cipher suite uses RSA key exchange.
807 : use-rsa-keyx? ( suite -- bool )
808 cipher-suite-to-elements 12 >> 0= ;
809
810 \ Test whether the cipher suite uses ECDHE key exchange, signed with RSA.
811 : use-rsa-ecdhe? ( suite -- bool )
812 cipher-suite-to-elements 12 >> 1 = ;
813
814 \ Test whether the cipher suite uses ECDHE key exchange, signed with ECDSA.
815 : use-ecdsa-ecdhe? ( suite -- bool )
816 cipher-suite-to-elements 12 >> 2 = ;
817
818 \ Test whether the cipher suite uses ECDHE key exchange (with RSA or ECDSA).
819 : use-ecdhe? ( suite -- bool )
820 cipher-suite-to-elements 12 >> dup 0> swap 3 < and ;
821
822 \ Test whether the cipher suite uses ECDH (static) key exchange.
823 : use-ecdh? ( suite -- bool )
824 cipher-suite-to-elements 12 >> 2 > ;
825
826 \ Get identifier for the PRF (TLS 1.2).
827 : prf-id ( suite -- id )
828 cipher-suite-to-elements 15 and ;
829
830 \ Switch to negotiated security parameters for input or output.
831 : switch-encryption ( is-client for-input -- )
832 { for-input }
833 addr-cipher_suite get16 cipher-suite-to-elements { elts }
834
835 \ prf_id
836 elts 15 and
837
838 \ mac_id
839 elts 4 >> 15 and
840
841 \ cipher type and key length
842 elts 8 >> 15 and case
843 \ 3DES/CBC
844 0 of 0 24
845 for-input if
846 switch-cbc-in
847 else
848 switch-cbc-out
849 then
850 endof
851
852 \ AES-128/CBC
853 1 of 1 16
854 for-input if
855 switch-cbc-in
856 else
857 switch-cbc-out
858 then
859 endof
860
861 \ AES-256/CBC
862 2 of 1 32
863 for-input if
864 switch-cbc-in
865 else
866 switch-cbc-out
867 then
868 endof
869
870 \ AES-128/GCM
871 3 of drop 16
872 for-input if
873 switch-aesgcm-in
874 else
875 switch-aesgcm-out
876 then
877 endof
878
879 \ AES-256/GCM
880 4 of drop 32
881 for-input if
882 switch-aesgcm-in
883 else
884 switch-aesgcm-out
885 then
886 endof
887
888 \ ChaCha20/Poly1305
889 \ 5 of endof
890
891 ERR_BAD_PARAM fail
892 endcase
893 ;
894
895 cc: switch-cbc-out ( is_client prf_id mac_id aes cipher_key_len -- ) {
896 int is_client, prf_id, mac_id, aes;
897 unsigned cipher_key_len;
898
899 cipher_key_len = T0_POP();
900 aes = T0_POP();
901 mac_id = T0_POP();
902 prf_id = T0_POP();
903 is_client = T0_POP();
904 br_ssl_engine_switch_cbc_out(ENG, is_client, prf_id, mac_id,
905 aes ? ENG->iaes_cbcenc : ENG->ides_cbcenc, cipher_key_len);
906 }
907
908 cc: switch-cbc-in ( is_client prf_id mac_id aes cipher_key_len -- ) {
909 int is_client, prf_id, mac_id, aes;
910 unsigned cipher_key_len;
911
912 cipher_key_len = T0_POP();
913 aes = T0_POP();
914 mac_id = T0_POP();
915 prf_id = T0_POP();
916 is_client = T0_POP();
917 br_ssl_engine_switch_cbc_in(ENG, is_client, prf_id, mac_id,
918 aes ? ENG->iaes_cbcdec : ENG->ides_cbcdec, cipher_key_len);
919 }
920
921 cc: switch-aesgcm-out ( is_client prf_id cipher_key_len -- ) {
922 int is_client, prf_id;
923 unsigned cipher_key_len;
924
925 cipher_key_len = T0_POP();
926 prf_id = T0_POP();
927 is_client = T0_POP();
928 br_ssl_engine_switch_gcm_out(ENG, is_client, prf_id,
929 ENG->iaes_ctr, cipher_key_len);
930 }
931
932 cc: switch-aesgcm-in ( is_client prf_id cipher_key_len -- ) {
933 int is_client, prf_id;
934 unsigned cipher_key_len;
935
936 cipher_key_len = T0_POP();
937 prf_id = T0_POP();
938 is_client = T0_POP();
939 br_ssl_engine_switch_gcm_in(ENG, is_client, prf_id,
940 ENG->iaes_ctr, cipher_key_len);
941 }
942
943 \ Write Finished message.
944 : write-Finished ( from_client -- )
945 compute-Finished
946 20 write8 12 write24 addr-pad 12 write-blob ;
947
948 \ Read Finished message.
949 : read-Finished ( from_client -- )
950 compute-Finished
951 read-handshake-header 20 <> if ERR_UNEXPECTED fail then
952 addr-pad 12 + 12 read-blob
953 close-elt
954 addr-pad dup 12 + 12 memcmp ifnot ERR_BAD_FINISHED fail then ;
955
956 \ Compute the "Finished" contents (either the value to send, or the
957 \ expected value). The 12-byte string is written in the pad. The
958 \ "from_client" value is non-zero for the Finished sent by the client.
959 \ The computed value is also saved in the relevant buffer for handling
960 \ secure renegotiation.
961 : compute-Finished ( from_client -- )
962 dup addr-saved_finished swap ifnot 12 + then swap
963 addr-cipher_suite get16 prf-id compute-Finished-inner
964 addr-pad 12 memcpy ;
965
966 cc: compute-Finished-inner ( from_client prf_id -- ) {
967 int prf_id = T0_POP();
968 int from_client = T0_POPi();
969 unsigned char seed[48];
970 size_t seed_len;
971
972 br_tls_prf_impl prf = br_ssl_engine_get_PRF(ENG, prf_id);
973 if (ENG->session.version >= BR_TLS12) {
974 seed_len = br_multihash_out(&ENG->mhash, prf_id, seed);
975 } else {
976 br_multihash_out(&ENG->mhash, br_md5_ID, seed);
977 br_multihash_out(&ENG->mhash, br_sha1_ID, seed + 16);
978 seed_len = 36;
979 }
980 prf(ENG->pad, 12, ENG->session.master_secret,
981 sizeof ENG->session.master_secret,
982 from_client ? "client finished" : "server finished",
983 seed, seed_len);
984 }
985
986 \ Receive ChangeCipherSpec and Finished from the peer.
987 : read-CCS-Finished ( is-client -- )
988 has-input? if
989 addr-record_type_in get8 20 <> if ERR_UNEXPECTED fail then
990 else
991 begin
992 wait-co 0x07 and dup 0x02 <> while
993 if ERR_UNEXPECTED fail then
994 repeat
995 drop
996 then
997 read8-nc 1 <> more-incoming-bytes? or if ERR_BAD_CCS fail then
998 dup 1 switch-encryption
999
1000 \ Read and verify Finished from peer.
1001 not read-Finished ;
1002
1003 \ Send ChangeCipherSpec and Finished to the peer.
1004 : write-CCS-Finished ( is-client -- )
1005 \ Flush and wait for output buffer to be clear, so that we may
1006 \ write our ChangeCipherSpec. We must switch immediately after
1007 \ triggering the flush.
1008 20 wait-rectype-out
1009 1 write8
1010 flush-record
1011 dup 0 switch-encryption
1012 22 wait-rectype-out
1013 write-Finished
1014 flush-record ;