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 \ This is the common T0 code for processing handshake messages (code that
25 \ is used by both client and server).
35 * This macro evaluates to a pointer to the current engine context.
37 #define ENG ((br_ssl_engine_context *)((unsigned char *)t0ctx - offsetof(br_ssl_engine_context, cpu)))
41 \ IMPLEMENTATION NOTES
42 \ ====================
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.
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.
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'.
61 \ The handshake processor needs to defer back to the caller ('co') only
62 \ in one of the following situations:
64 \ -- Some handshake data is expected.
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.
70 \ -- Some change-cipher-spec data is expected.
72 \ -- An alert record is expected. Other types of incoming records will be
75 \ -- Waiting for the currently accumulated record to be sent and the
76 \ output buffer to become free again for another record.
78 \ Placeholder for handling not yet implemented functionalities.
80 "NOT YET IMPLEMENTED!" puts cr -1 fail ;
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());
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));
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));
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));
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();
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();
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();
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'.
130 "addr-" field + 0 1 define-word
131 0 8191 "offsetof(br_ssl_engine_context, " field + ")" + make-CX
132 postpone literal postpone ; ;
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
141 addr-eng: version_out
142 addr-eng: application_data
143 addr-eng: version_min
144 addr-eng: version_max
147 addr-eng: server_name
148 addr-eng: client_random
149 addr-eng: server_random
150 addr-eng: ecdhe_curve
151 addr-eng: ecdhe_point
152 addr-eng: ecdhe_point_len
154 addr-eng: saved_finished
159 addr-eng: close_received
160 addr-eng: protocol_names_num
161 addr-eng: selected_protocol
163 \ Similar to 'addr-eng:', for fields in the 'session' substructure.
164 : addr-session-field:
166 "addr-" field + 0 1 define-word
167 0 8191 "offsetof(br_ssl_engine_context, session) + offsetof(br_ssl_session_parameters, " field + ")" + make-CX
168 postpone literal postpone ; ;
170 addr-session-field: session_id
171 addr-session-field: session_id_len
172 addr-session-field: version
173 addr-session-field: cipher_suite
174 addr-session-field: master_secret
176 \ Check a server flag by index.
177 : flag? ( index -- bool )
178 addr-flags get32 swap >> 1 and neg ;
180 \ Define a word that evaluates to an error constant. This assumes that
181 \ all relevant error codes are in the 0..63 range.
185 0 63 "BR_" name + make-CX postpone literal postpone ; ;
190 err: ERR_UNSUPPORTED_VERSION
196 err: ERR_UNKNOWN_TYPE
200 err: ERR_BAD_HANDSHAKE
201 err: ERR_OVERSIZED_ID
202 err: ERR_BAD_CIPHER_SUITE
203 err: ERR_BAD_COMPRESSION
205 err: ERR_BAD_SECRENEG
206 err: ERR_EXTRA_EXTENSION
208 err: ERR_BAD_HELLO_DONE
209 err: ERR_LIMIT_EXCEEDED
210 err: ERR_BAD_FINISHED
211 err: ERR_RESUME_MISMATCH
212 err: ERR_INVALID_ALGORITHM
213 err: ERR_BAD_SIGNATURE
214 err: ERR_WRONG_KEY_USAGE
215 err: ERR_NO_CLIENT_AUTH
217 \ Get supported curves (bit mask).
218 cc: supported-curves ( -- x ) {
219 uint32_t x = ENG->iec == NULL ? 0 : ENG->iec->supported_curves;
223 \ Get supported hash functions (bit mask and number).
224 \ Note: this (on purpose) skips MD5.
225 cc: supported-hash-functions ( -- x num ) {
231 for (i = br_sha1_ID; i <= br_sha512_ID; i ++) {
232 if (br_multihash_getimpl(&ENG->mhash, i)) {
241 \ Test support for RSA signatures.
242 cc: supports-rsa-sign? ( -- bool ) {
243 T0_PUSHi(-(ENG->irsavrfy != 0));
246 \ Test support for ECDSA signatures.
247 cc: supports-ecdsa? ( -- bool ) {
248 T0_PUSHi(-(ENG->iecdsa != 0));
251 \ (Re)initialise the multihasher.
252 cc: multihash-init ( -- ) {
253 br_multihash_init(&ENG->mhash);
256 \ Flush the current record: if some payload data has been accumulated,
257 \ close the record and schedule it for sending. If there is no such data,
258 \ this function does nothing.
259 cc: flush-record ( -- ) {
260 br_ssl_engine_flush_record(ENG);
263 \ Yield control to the caller.
264 \ When the control is returned to us, react to the new context. Returned
265 \ value is a bitwise combination of the following:
266 \ 0x01 handshake data is available
267 \ 0x02 change-cipher-spec data is available
268 \ 0x04 some data other than handshake or change-cipher-spec is available
269 \ 0x08 output buffer is ready for a new outgoing record
270 \ 0x10 renegotiation is requested and not to be ignored
271 \ Flags 0x01, 0x02 and 0x04 are mutually exclusive.
272 : wait-co ( -- state )
275 addr-action get8 dup if
277 1 of 0 do-close endof
278 2 of addr-application_data get8 if 0x10 or then endof
283 addr-close_received get8 ifnot
285 addr-record_type_in get8 case
290 \ Alert -- if close_notify received, trigger
291 \ the closure sequence.
292 21 of process-alerts if -1 do-close then endof
297 \ Not CCS, Alert or Handshake.
302 can-output? if 0x08 or then ;
304 \ Send an alert message. This shall be called only when there is room for
305 \ an outgoing record.
306 : send-alert ( level alert -- )
307 21 addr-record_type_out set8
308 swap write8-native drop write8-native drop
311 \ Send an alert message of level "warning". This shall be called only when
312 \ there is room for an outgoing record.
313 : send-warning ( alert -- )
316 \ Fail by sending a fatal alert.
317 : fail-alert ( alert -- ! )
320 begin can-output? not while wait-co drop repeat
322 begin can-output? not while wait-co drop repeat
325 \ Perform the close operation:
326 \ -- Prevent new application data from the caller.
327 \ -- Incoming data is discarded (except alerts).
328 \ -- Outgoing data is flushed.
329 \ -- A close_notify alert is sent.
330 \ -- If 'cnr' is zero, then incoming data is discarded until a close_notify
332 \ -- At the end, the context is terminated.
333 : do-close ( cnr -- ! )
334 \ 'cnr' is set to non-zero when a close_notify is received from
338 \ Get out of application data state.
339 0 addr-application_data set8
341 \ Flush existing payload if any.
344 \ Wait for room to send the close_notify. Since individual records
345 \ can always hold at least 512 bytes, we know that when there is
346 \ room, then there is room for a complete close_notify (two bytes).
347 begin can-output? not while cnr wait-for-close >cnr repeat
349 \ Write the close_notify and flush it.
350 \ 21 addr-record_type_out set8
351 \ 1 write8-native 0 write8-native 2drop
355 \ Loop until our record has been sent (we know it's gone when
356 \ writing is again possible) and a close_notify has been received.
359 dup can-output? and if ERR_OK fail then
363 \ Yield control to the engine, with a possible flush. If 'cnr' is 0,
364 \ then input is analysed: all input is discarded, until a close_notify
366 : wait-for-close ( cnr -- cnr )
370 addr-record_type_in get8 21 = if
378 \ Test whether there is some accumulated payload that still needs to be
380 cc: payload-to-send? ( -- bool ) {
381 T0_PUSHi(-br_ssl_engine_has_pld_to_send(ENG));
384 \ Test whether there is some available input data.
385 cc: has-input? ( -- bool ) {
386 T0_PUSHi(-(ENG->hlen_in != 0));
389 \ Test whether some payload bytes may be written.
390 cc: can-output? ( -- bool ) {
391 T0_PUSHi(-(ENG->hlen_out > 0));
394 \ Discard current input entirely.
395 cc: discard-input ( -- ) {
399 \ Low-level read for one byte. If there is no available byte right
400 \ away, then -1 is returned. Otherwise, the byte value is returned.
401 \ If the current record type is "handshake" then the read byte is also
402 \ injected in the multi-hasher.
403 cc: read8-native ( -- x ) {
404 if (ENG->hlen_in > 0) {
407 x = *ENG->hbuf_in ++;
408 if (ENG->record_type_in == BR_SSL_HANDSHAKE) {
409 br_multihash_update(&ENG->mhash, &x, 1);
418 \ Low-level read for several bytes. On entry, this expects an address
419 \ (offset in the engine context) and a length; these values designate
420 \ where the chunk should go. Upon exit, the new address and length
421 \ are pushed; that output length contains how many bytes could not be
422 \ read. If there is no available byte for reading, the address and
423 \ length are unchanged.
424 \ If the current record type is "handshake" then the read bytes are
425 \ injected in the multi-hasher.
426 cc: read-chunk-native ( addr len -- addr len ) {
427 size_t clen = ENG->hlen_in;
433 if ((size_t)len < clen) {
436 memcpy((unsigned char *)ENG + addr, ENG->hbuf_in, clen);
437 if (ENG->record_type_in == BR_SSL_HANDSHAKE) {
438 br_multihash_update(&ENG->mhash, ENG->hbuf_in, clen);
440 T0_PUSH(addr + (uint32_t)clen);
441 T0_PUSH(len - (uint32_t)clen);
442 ENG->hbuf_in += clen;
443 ENG->hlen_in -= clen;
447 \ Process available alert bytes. If a fatal alert is received, then the
448 \ context is terminated; otherwise, this returns either true (-1) if a
449 \ close_notify was received, false (0) otherwise.
450 : process-alerts ( -- bool )
452 begin has-input? while read8-native process-alert-byte or repeat
453 dup if 1 addr-shutdown_recv set8 then ;
455 \ Process an alert byte. Returned value is non-zero if this is a close_notify,
457 : process-alert-byte ( x -- bool )
460 \ 'alert' field is 0, so this byte shall be a level.
461 \ Levels shall be 1 (warning) or 2 (fatal); we convert
462 \ all other values to "fatal".
463 dup 1 <> if drop 2 then
468 \ close_notify has value 0.
469 \ no_renegotiation has value 100, and we treat it
471 dup 100 = if 256 + fail then
474 \ Fatal alert implies context termination.
478 \ In general we only deal with handshake data here. Alerts are processed
479 \ in specific code right when they are received, and ChangeCipherSpec has
480 \ its own handling code. So we need to check that the data is "handshake"
481 \ only when returning from a coroutine call.
483 \ Yield control to the engine. Alerts are processed; if incoming data is
484 \ neither handshake or alert, then an error is triggered.
485 : wait-for-handshake ( -- )
486 wait-co 0x07 and 0x01 > if ERR_UNEXPECTED fail then ;
488 \ Flush outgoing data (if any), then wait for the output buffer to be
489 \ clear; when this is done, set the output record type to the specified
491 : wait-rectype-out ( rectype -- )
495 can-output? if rectype addr-record_type_out set8 ret then
499 \ Read one byte of handshake data. Block until that byte is available.
500 \ This does not check any length.
503 read8-native dup 0< ifnot ret then
504 drop wait-for-handshake
507 \ Test whether there are some more bytes in the current record. These
508 \ bytes have not necessarily been received yet (processing of unencrypted
509 \ records may begin before all bytes are received).
510 cc: more-incoming-bytes? ( -- bool ) {
511 T0_PUSHi(ENG->hlen_in != 0 || !br_ssl_engine_recvrec_finished(ENG));
514 \ For reading functions, the TOS is supposed to contain the number of bytes
515 \ that can still be read (from encapsulating structure header), and it is
518 : check-len ( lim len -- lim )
519 - dup 0< if ERR_BAD_PARAM fail then ;
521 \ Read one byte of handshake data. This pushes an integer in the 0..255 range.
522 : read8 ( lim -- lim x )
523 1 check-len read8-nc ;
525 \ Read a 16-bit value (in the 0..65535 range)
526 : read16 ( lim -- lim n )
527 2 check-len read8-nc 8 << read8-nc + ;
529 \ Read a 24-bit value (in the 0..16777215 range)
530 : read24 ( lim -- lim n )
531 3 check-len read8-nc 8 << read8-nc + 8 << read8-nc + ;
533 \ Read some bytes. The "address" is an offset within the context
535 : read-blob ( lim addr len -- lim )
541 dup 0 = if 2drop ret then
545 \ Read some bytes and drop them.
546 : skip-blob ( lim len -- lim )
547 swap over check-len swap
548 begin dup while read8-nc drop 1- repeat
551 \ Read a 16-bit length, then skip exactly that many bytes.
552 : read-ignore-16 ( lim -- lim )
555 \ Open a substructure: the inner structure length is checked against,
556 \ and substracted, from the output structure current limit.
557 : open-elt ( lim len -- lim-outer lim-inner )
559 - dup 0< if ERR_BAD_PARAM fail then
562 \ Close the current structure. This checks that the limit is 0.
563 : close-elt ( lim -- )
564 if ERR_BAD_PARAM fail then ;
566 \ Write one byte of handshake data.
569 dup write8-native if drop ret then
573 \ Low-level write for one byte. On exit, it pushes either -1 (byte was
574 \ written) or 0 (no room in output buffer).
575 cc: write8-native ( x -- bool ) {
578 x = (unsigned char)T0_POP();
579 if (ENG->hlen_out > 0) {
580 if (ENG->record_type_out == BR_SSL_HANDSHAKE) {
581 br_multihash_update(&ENG->mhash, &x, 1);
583 *ENG->hbuf_out ++ = x;
591 \ Write a 16-bit value.
593 dup 8 u>> write8 write8 ;
595 \ Write a 24-bit value.
597 dup 16 u>> write8 write16 ;
599 \ Write some bytes. The "address" is an offset within the context
601 : write-blob ( addr len -- )
604 dup 0 = if 2drop ret then
608 cc: write-blob-chunk ( addr len -- addr len ) {
609 size_t clen = ENG->hlen_out;
615 if ((size_t)len < clen) {
618 memcpy(ENG->hbuf_out, (unsigned char *)ENG + addr, clen);
619 if (ENG->record_type_out == BR_SSL_HANDSHAKE) {
620 br_multihash_update(&ENG->mhash, ENG->hbuf_out, clen);
622 T0_PUSH(addr + (uint32_t)clen);
623 T0_PUSH(len - (uint32_t)clen);
624 ENG->hbuf_out += clen;
625 ENG->hlen_out -= clen;
629 \ Write a blob with the length as header (over one byte)
630 : write-blob-head8 ( addr len -- )
631 dup write8 write-blob ;
633 \ Write a blob with the length as header (over two bytes)
634 : write-blob-head16 ( addr len -- )
635 dup write16 write-blob ;
637 \ Perform a byte-to-byte comparison between two blobs. Each blob is
638 \ provided as an "address" (offset in the context structure); the
639 \ length is common. Returned value is true (-1) if the two blobs are
640 \ equal, false (0) otherwise.
641 cc: memcmp ( addr1 addr2 len -- bool ) {
642 size_t len = (size_t)T0_POP();
643 void *addr2 = (unsigned char *)ENG + (size_t)T0_POP();
644 void *addr1 = (unsigned char *)ENG + (size_t)T0_POP();
645 int x = memcmp(addr1, addr2, len);
646 T0_PUSH((uint32_t)-(x == 0));
649 \ Copy bytes between two areas, whose addresses are provided as
650 \ offsets in the context structure.
651 cc: memcpy ( dst src len -- ) {
652 size_t len = (size_t)T0_POP();
653 void *src = (unsigned char *)ENG + (size_t)T0_POP();
654 void *dst = (unsigned char *)ENG + (size_t)T0_POP();
655 memcpy(dst, src, len);
658 \ Get string length (zero-terminated). The string address is provided as
659 \ an offset relative to the context start. Returned length does not include
661 cc: strlen ( str -- len ) {
662 void *str = (unsigned char *)ENG + (size_t)T0_POP();
663 T0_PUSH((uint32_t)strlen(str));
666 \ Fill a buffer with zeros. The buffer address is an offset in the context.
667 cc: bzero ( addr len -- ) {
668 size_t len = (size_t)T0_POP();
669 void *addr = (unsigned char *)ENG + (size_t)T0_POP();
670 memset(addr, 0, len);
673 \ Scan the list of supported cipher suites for a given value. If found,
674 \ then the list index at which it was found is returned; otherwise, -1
676 : scan-suite ( suite -- index )
678 addr-suites_num get8 { num }
680 begin dup num < while
681 dup 1 << addr-suites_buf + get16 suite = if ret then
686 \ =======================================================================
688 \ Generate random bytes into buffer (address is offset in context).
689 cc: mkrand ( addr len -- ) {
690 size_t len = (size_t)T0_POP();
691 void *addr = (unsigned char *)ENG + (size_t)T0_POP();
692 br_hmac_drbg_generate(&ENG->rng, addr, len);
695 \ Read a handshake message header: type and length. These are returned
696 \ in reverse order (type is TOS, length is below it).
697 : read-handshake-header-core ( -- lim type )
698 read8-nc 3 read24 swap drop swap ;
700 \ Read a handshake message header: type and length. If the header is for
701 \ a HelloRequest message, then it is discarded and a new header is read
702 \ (repeatedly if necessary).
703 : read-handshake-header ( -- lim type )
705 read-handshake-header-core dup 0= while
706 drop if ERR_BAD_HANDSHAKE fail then
709 \ =======================================================================
711 \ Cipher suite processing.
713 \ Unfortunately, cipher suite identifiers are attributed mostly arbitrary,
714 \ so we have to map the cipher suite numbers we support into aggregate
715 \ words that encode the information we need. Table below is organized
716 \ as a sequence of pairs of 16-bit words, the first being the cipher suite
717 \ identifier, the second encoding the algorithm elements. The suites are
718 \ ordered by increasing cipher suite ID, so that fast lookups may be
719 \ performed with a binary search (not implemented for the moment, since it
720 \ does not appear to matter much in practice).
722 \ Algorithm elements are encoded over 4 bits each, in the following order
723 \ (most significant to least significant):
725 \ -- Server key type:
726 \ 0 RSA (RSA key exchange)
727 \ 1 ECDHE-RSA (ECDHE key exchange, RSA signature)
728 \ 2 ECDHE-ECDSA (ECDHE key exchange, ECDSA signature)
729 \ 3 ECDH-RSA (ECDH key exchange, certificate is RSA-signed)
730 \ 4 ECDH-ECDSA (ECDH key exchange, certificate is ECDSA-signed)
731 \ -- Encryption algorithm:
737 \ 5 ChaCha20/Poly1305
739 \ 0 none (for suites with AEAD encryption)
743 \ -- PRF for TLS-1.2:
747 data: cipher-suite-def
749 hexb| 000A 0024 | \ TLS_RSA_WITH_3DES_EDE_CBC_SHA
750 hexb| 002F 0124 | \ TLS_RSA_WITH_AES_128_CBC_SHA
751 hexb| 0035 0224 | \ TLS_RSA_WITH_AES_256_CBC_SHA
752 hexb| 003C 0144 | \ TLS_RSA_WITH_AES_128_CBC_SHA256
753 hexb| 003D 0244 | \ TLS_RSA_WITH_AES_256_CBC_SHA256
755 hexb| 009C 0304 | \ TLS_RSA_WITH_AES_128_GCM_SHA256
756 hexb| 009D 0405 | \ TLS_RSA_WITH_AES_256_GCM_SHA384
758 hexb| C003 4024 | \ TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
759 hexb| C004 4124 | \ TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
760 hexb| C005 4224 | \ TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
761 hexb| C008 2024 | \ TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
762 hexb| C009 2124 | \ TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
763 hexb| C00A 2224 | \ TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
764 hexb| C00D 3024 | \ TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
765 hexb| C00E 3124 | \ TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
766 hexb| C00F 3224 | \ TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
767 hexb| C012 1024 | \ TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
768 hexb| C013 1124 | \ TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
769 hexb| C014 1224 | \ TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
771 hexb| C023 2144 | \ TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
772 hexb| C024 2255 | \ TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
773 hexb| C025 4144 | \ TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
774 hexb| C026 4255 | \ TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
775 hexb| C027 1144 | \ TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
776 hexb| C028 1255 | \ TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
777 hexb| C029 3144 | \ TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
778 hexb| C02A 3255 | \ TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
779 hexb| C02B 2304 | \ TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
780 hexb| C02C 2405 | \ TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
781 hexb| C02D 4304 | \ TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
782 hexb| C02E 4405 | \ TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
783 hexb| C02F 1304 | \ TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
784 hexb| C030 1405 | \ TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
785 hexb| C031 3304 | \ TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
786 hexb| C032 3405 | \ TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
788 hexb| CCA8 1504 | \ TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
789 hexb| CCA9 2504 | \ TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
791 hexb| 0000 | \ List terminator.
793 \ Convert cipher suite identifier to element words. This returns 0 if
794 \ the cipher suite is not known.
795 : cipher-suite-to-elements ( suite -- elts )
799 dup 2+ swap data-get16
800 dup ifnot 2drop 0 ret then
801 id = if data-get16 ret then
805 \ Check that a given cipher suite is supported. Note that this also
806 \ returns true (-1) for the TLS_FALLBACK_SCSV pseudo-ciphersuite.
807 : suite-supported? ( suite -- bool )
808 dup 0x5600 = if drop -1 ret then
809 cipher-suite-to-elements 0<> ;
811 \ Get expected key type for cipher suite. The key type is one of
812 \ BR_KEYTYPE_RSA or BR_KEYTYPE_EC, combined with either BR_KEYTYPE_KEYX
813 \ (RSA encryption or static ECDH) or BR_KEYTYPE_SIGN (RSA or ECDSA
814 \ signature, for ECDHE cipher suites).
815 : expected-key-type ( suite -- key-type )
816 cipher-suite-to-elements 12 >>
818 0 of CX 0 63 { BR_KEYTYPE_RSA | BR_KEYTYPE_KEYX } endof
819 1 of CX 0 63 { BR_KEYTYPE_RSA | BR_KEYTYPE_SIGN } endof
820 2 of CX 0 63 { BR_KEYTYPE_EC | BR_KEYTYPE_SIGN } endof
821 3 of CX 0 63 { BR_KEYTYPE_EC | BR_KEYTYPE_KEYX } endof
822 4 of CX 0 63 { BR_KEYTYPE_EC | BR_KEYTYPE_KEYX } endof
826 \ Test whether the cipher suite uses RSA key exchange.
827 : use-rsa-keyx? ( suite -- bool )
828 cipher-suite-to-elements 12 >> 0= ;
830 \ Test whether the cipher suite uses ECDHE key exchange, signed with RSA.
831 : use-rsa-ecdhe? ( suite -- bool )
832 cipher-suite-to-elements 12 >> 1 = ;
834 \ Test whether the cipher suite uses ECDHE key exchange, signed with ECDSA.
835 : use-ecdsa-ecdhe? ( suite -- bool )
836 cipher-suite-to-elements 12 >> 2 = ;
838 \ Test whether the cipher suite uses ECDHE key exchange (with RSA or ECDSA).
839 : use-ecdhe? ( suite -- bool )
840 cipher-suite-to-elements 12 >> dup 0> swap 3 < and ;
842 \ Test whether the cipher suite uses ECDH (static) key exchange.
843 : use-ecdh? ( suite -- bool )
844 cipher-suite-to-elements 12 >> 2 > ;
846 \ Get identifier for the PRF (TLS 1.2).
847 : prf-id ( suite -- id )
848 cipher-suite-to-elements 15 and ;
850 \ Switch to negotiated security parameters for input or output.
851 : switch-encryption ( is-client for-input -- )
853 addr-cipher_suite get16 cipher-suite-to-elements { elts }
861 \ cipher type and key length
862 elts 8 >> 15 and case
921 cc: switch-cbc-out ( is_client prf_id mac_id aes cipher_key_len -- ) {
922 int is_client, prf_id, mac_id, aes;
923 unsigned cipher_key_len;
925 cipher_key_len = T0_POP();
929 is_client = T0_POP();
930 br_ssl_engine_switch_cbc_out(ENG, is_client, prf_id, mac_id,
931 aes ? ENG->iaes_cbcenc : ENG->ides_cbcenc, cipher_key_len);
934 cc: switch-cbc-in ( is_client prf_id mac_id aes cipher_key_len -- ) {
935 int is_client, prf_id, mac_id, aes;
936 unsigned cipher_key_len;
938 cipher_key_len = T0_POP();
942 is_client = T0_POP();
943 br_ssl_engine_switch_cbc_in(ENG, is_client, prf_id, mac_id,
944 aes ? ENG->iaes_cbcdec : ENG->ides_cbcdec, cipher_key_len);
947 cc: switch-aesgcm-out ( is_client prf_id cipher_key_len -- ) {
948 int is_client, prf_id;
949 unsigned cipher_key_len;
951 cipher_key_len = T0_POP();
953 is_client = T0_POP();
954 br_ssl_engine_switch_gcm_out(ENG, is_client, prf_id,
955 ENG->iaes_ctr, cipher_key_len);
958 cc: switch-aesgcm-in ( is_client prf_id cipher_key_len -- ) {
959 int is_client, prf_id;
960 unsigned cipher_key_len;
962 cipher_key_len = T0_POP();
964 is_client = T0_POP();
965 br_ssl_engine_switch_gcm_in(ENG, is_client, prf_id,
966 ENG->iaes_ctr, cipher_key_len);
969 cc: switch-chapol-out ( is_client prf_id -- ) {
970 int is_client, prf_id;
973 is_client = T0_POP();
974 br_ssl_engine_switch_chapol_out(ENG, is_client, prf_id);
977 cc: switch-chapol-in ( is_client prf_id -- ) {
978 int is_client, prf_id;
981 is_client = T0_POP();
982 br_ssl_engine_switch_chapol_in(ENG, is_client, prf_id);
985 \ Write Finished message.
986 : write-Finished ( from_client -- )
988 20 write8 12 write24 addr-pad 12 write-blob ;
990 \ Read Finished message.
991 : read-Finished ( from_client -- )
993 read-handshake-header 20 <> if ERR_UNEXPECTED fail then
994 addr-pad 12 + 12 read-blob
996 addr-pad dup 12 + 12 memcmp ifnot ERR_BAD_FINISHED fail then ;
998 \ Compute the "Finished" contents (either the value to send, or the
999 \ expected value). The 12-byte string is written in the pad. The
1000 \ "from_client" value is non-zero for the Finished sent by the client.
1001 \ The computed value is also saved in the relevant buffer for handling
1002 \ secure renegotiation.
1003 : compute-Finished ( from_client -- )
1004 dup addr-saved_finished swap ifnot 12 + then swap
1005 addr-cipher_suite get16 prf-id compute-Finished-inner
1006 addr-pad 12 memcpy ;
1008 cc: compute-Finished-inner ( from_client prf_id -- ) {
1009 int prf_id = T0_POP();
1010 int from_client = T0_POPi();
1011 unsigned char seed[48];
1014 br_tls_prf_impl prf = br_ssl_engine_get_PRF(ENG, prf_id);
1015 if (ENG->session.version >= BR_TLS12) {
1016 seed_len = br_multihash_out(&ENG->mhash, prf_id, seed);
1018 br_multihash_out(&ENG->mhash, br_md5_ID, seed);
1019 br_multihash_out(&ENG->mhash, br_sha1_ID, seed + 16);
1022 prf(ENG->pad, 12, ENG->session.master_secret,
1023 sizeof ENG->session.master_secret,
1024 from_client ? "client finished" : "server finished",
1028 \ Receive ChangeCipherSpec and Finished from the peer.
1029 : read-CCS-Finished ( is-client -- )
1031 addr-record_type_in get8 20 <> if ERR_UNEXPECTED fail then
1034 wait-co 0x07 and dup 0x02 <> while
1035 if ERR_UNEXPECTED fail then
1039 read8-nc 1 <> more-incoming-bytes? or if ERR_BAD_CCS fail then
1040 dup 1 switch-encryption
1042 \ Read and verify Finished from peer.
1045 \ Send ChangeCipherSpec and Finished to the peer.
1046 : write-CCS-Finished ( is-client -- )
1047 \ Flush and wait for output buffer to be clear, so that we may
1048 \ write our ChangeCipherSpec. We must switch immediately after
1049 \ triggering the flush.
1053 dup 0 switch-encryption
1058 \ Read and parse a list of supported signature algorithms (with hash
1059 \ functions). The resulting bit field is returned.
1060 : read-list-sign-algos ( lim -- lim value )
1064 read8 { hash } read8 { sign }
1065 \ We keep the value if the signature is either 1 (RSA)
1066 \ or 3 (ECDSA), and the hash is one of the SHA-* functions
1067 \ (2 to 6, from SHA-1 to SHA-512); we reject MD5.
1068 hash 2 >= hash 6 <= and
1069 sign 1 = sign 3 = or
1071 hashes 1 sign 1- 2 << hash + << or >hashes
1077 \ =======================================================================
1079 \ Compute total chain length. This includes the individual certificate
1080 \ headers, but not the total chain header. This also sets the cert_cur,
1081 \ cert_len and chain_len context fields.
1082 cc: total-chain-length ( -- len ) {
1087 for (u = 0; u < ENG->chain_len; u ++) {
1088 total += 3 + (uint32_t)ENG->chain[u].data_len;
1093 \ Get length for current certificate in the chain; if the chain end was
1094 \ reached, then this returns -1.
1095 cc: begin-cert ( -- len ) {
1096 if (ENG->chain_len == 0) {
1099 ENG->cert_cur = ENG->chain->data;
1100 ENG->cert_len = ENG->chain->data_len;
1103 T0_PUSH(ENG->cert_len);
1107 \ Copy a chunk of certificate data into the pad. Returned value is the
1108 \ chunk length, or 0 if the certificate end is reached.
1109 cc: copy-cert-chunk ( -- len ) {
1112 clen = ENG->cert_len;
1113 if (clen > sizeof ENG->pad) {
1114 clen = sizeof ENG->pad;
1116 memcpy(ENG->pad, ENG->cert_cur, clen);
1117 ENG->cert_cur += clen;
1118 ENG->cert_len -= clen;
1122 \ Write a Certificate message. Total chain length (excluding the 3-byte
1123 \ header) is returned; it is 0 if the chain is empty.
1124 : write-Certificate ( -- total_chain_len )
1126 total-chain-length dup
1127 dup 3 + write24 write24
1130 dup 0< if drop ret then write24
1131 begin copy-cert-chunk dup while
1132 addr-pad swap write-blob
1137 cc: x509-start-chain ( by_client -- ) {
1138 const br_x509_class *xc;
1142 xc = *(ENG->x509ctx);
1143 xc->start_chain(ENG->x509ctx, bc ? ENG->server_name : NULL);
1146 cc: x509-start-cert ( length -- ) {
1147 const br_x509_class *xc;
1149 xc = *(ENG->x509ctx);
1150 xc->start_cert(ENG->x509ctx, T0_POP());
1153 cc: x509-append ( length -- ) {
1154 const br_x509_class *xc;
1157 xc = *(ENG->x509ctx);
1159 xc->append(ENG->x509ctx, ENG->pad, len);
1162 cc: x509-end-cert ( -- ) {
1163 const br_x509_class *xc;
1165 xc = *(ENG->x509ctx);
1166 xc->end_cert(ENG->x509ctx);
1169 cc: x509-end-chain ( -- err ) {
1170 const br_x509_class *xc;
1172 xc = *(ENG->x509ctx);
1173 T0_PUSH(xc->end_chain(ENG->x509ctx));
1176 cc: get-key-type-usages ( -- key-type-usages ) {
1177 const br_x509_class *xc;
1178 const br_x509_pkey *pk;
1181 xc = *(ENG->x509ctx);
1182 pk = xc->get_pkey(ENG->x509ctx, &usages);
1186 T0_PUSH(pk->key_type | usages);
1190 \ Read a Certificate message.
1191 \ Parameter: non-zero if this is a read by the client of a certificate
1192 \ sent by the server; zero otherwise.
1195 \ - Valid: combination of key type and allowed key usages.
1196 \ - Invalid: negative (-x for error code x)
1197 : read-Certificate ( by_client -- key-type-usages )
1198 \ Get header, and check message type.
1199 read-handshake-header 11 = ifnot ERR_UNEXPECTED fail then
1201 \ If the chain is empty, do some special processing.
1203 read24 if ERR_BAD_PARAM fail then
1207 \ Start processing the chain through the X.509 engine.
1208 swap x509-start-chain
1210 \ Total chain length is a 24-bit integer.
1217 \ We read the certificate by chunks through the pad, so
1218 \ as to use the existing reading function (read-blob)
1219 \ that also ensures proper hashing.
1222 dup 256 > if 256 else dup then { len }
1223 addr-pad len read-blob
1230 \ We must close the chain AND the handshake message.
1234 \ Chain processing is finished; get the error code.
1236 dup if neg ret then drop
1238 \ Return key type and usages.
1239 get-key-type-usages ;
1241 \ =======================================================================
1243 \ Copy a specific protocol name from the list to the pad. The byte
1244 \ length is returned.
1245 cc: copy-protocol-name ( idx -- len ) {
1246 size_t idx = T0_POP();
1247 size_t len = strlen(ENG->protocol_names[idx]);
1248 memcpy(ENG->pad, ENG->protocol_names[idx], len);
1252 \ Compare name in pad with the configured list of protocol names.
1253 \ If a match is found, then the index is returned; otherwise, -1
1255 cc: test-protocol-name ( len -- n ) {
1256 size_t len = T0_POP();
1259 for (u = 0; u < ENG->protocol_names_num; u ++) {
1262 name = ENG->protocol_names[u];
1263 if (len == strlen(name) && memcmp(ENG->pad, name, len) == 0) {