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 *)(void *)((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 \ Debug function that prints a string (and a newline) on stderr.
85 extern int fprintf(void *, const char *, ...);
86 fprintf(stderr, "%s\n", &t0_datablock[T0_POPi()]);
89 \ Debug function that prints a string and an integer value (followed
90 \ by a newline) on stderr.
91 cc: DBG2 ( addr x -- ) {
93 extern int fprintf(void *, const char *, ...);
94 int32_t x = T0_POPi();
95 fprintf(stderr, "%s: %ld (0x%08lX)\n",
96 &t0_datablock[T0_POPi()], (long)x, (unsigned long)(uint32_t)x);
99 \ Mark the context as failed with a specific error code. This also
100 \ returns control to the caller.
101 cc: fail ( err -- ! ) {
102 br_ssl_engine_fail(ENG, (int)T0_POPi());
106 \ Read a byte from the context (address is offset in context).
107 cc: get8 ( addr -- val ) {
108 size_t addr = (size_t)T0_POP();
109 T0_PUSH(*((unsigned char *)ENG + addr));
112 \ Read a 16-bit word from the context (address is offset in context).
113 cc: get16 ( addr -- val ) {
114 size_t addr = (size_t)T0_POP();
115 T0_PUSH(*(uint16_t *)(void *)((unsigned char *)ENG + addr));
118 \ Read a 32-bit word from the context (address is offset in context).
119 cc: get32 ( addr -- val ) {
120 size_t addr = (size_t)T0_POP();
121 T0_PUSH(*(uint32_t *)(void *)((unsigned char *)ENG + addr));
124 \ Set a byte in the context (address is offset in context).
125 cc: set8 ( val addr -- ) {
126 size_t addr = (size_t)T0_POP();
127 *((unsigned char *)ENG + addr) = (unsigned char)T0_POP();
130 \ Set a 16-bit word in the context (address is offset in context).
131 cc: set16 ( val addr -- ) {
132 size_t addr = (size_t)T0_POP();
133 *(uint16_t *)(void *)((unsigned char *)ENG + addr) = (uint16_t)T0_POP();
136 \ Set a 32-bit word in the context (address is offset in context).
137 cc: set32 ( val addr -- ) {
138 size_t addr = (size_t)T0_POP();
139 *(uint32_t *)(void *)((unsigned char *)ENG + addr) = (uint32_t)T0_POP();
142 \ Define a word that evaluates as an address of a field within the
143 \ engine context. The field name (C identifier) must follow in the
144 \ source. For field 'foo', the defined word is 'addr-foo'.
147 "addr-" field + 0 1 define-word
148 0 8191 "offsetof(br_ssl_engine_context, " field + ")" + make-CX
149 postpone literal postpone ; ;
151 addr-eng: max_frag_len
152 addr-eng: log_max_frag_len
153 addr-eng: peer_log_max_frag_len
154 addr-eng: shutdown_recv
155 addr-eng: record_type_in
156 addr-eng: record_type_out
158 addr-eng: version_out
159 addr-eng: application_data
160 addr-eng: version_min
161 addr-eng: version_max
164 addr-eng: server_name
165 addr-eng: client_random
166 addr-eng: server_random
167 addr-eng: ecdhe_curve
168 addr-eng: ecdhe_point
169 addr-eng: ecdhe_point_len
171 addr-eng: saved_finished
176 addr-eng: close_received
177 addr-eng: protocol_names_num
178 addr-eng: selected_protocol
180 \ Similar to 'addr-eng:', for fields in the 'session' substructure.
181 : addr-session-field:
183 "addr-" field + 0 1 define-word
184 0 8191 "offsetof(br_ssl_engine_context, session) + offsetof(br_ssl_session_parameters, " field + ")" + make-CX
185 postpone literal postpone ; ;
187 addr-session-field: session_id
188 addr-session-field: session_id_len
189 addr-session-field: version
190 addr-session-field: cipher_suite
191 addr-session-field: master_secret
193 \ Check a server flag by index.
194 : flag? ( index -- bool )
195 addr-flags get32 swap >> 1 and neg ;
197 \ Define a word that evaluates to an error constant. This assumes that
198 \ all relevant error codes are in the 0..63 range.
202 0 63 "BR_" name + make-CX postpone literal postpone ; ;
207 err: ERR_UNSUPPORTED_VERSION
213 err: ERR_UNKNOWN_TYPE
217 err: ERR_BAD_HANDSHAKE
218 err: ERR_OVERSIZED_ID
219 err: ERR_BAD_CIPHER_SUITE
220 err: ERR_BAD_COMPRESSION
222 err: ERR_BAD_SECRENEG
223 err: ERR_EXTRA_EXTENSION
225 err: ERR_BAD_HELLO_DONE
226 err: ERR_LIMIT_EXCEEDED
227 err: ERR_BAD_FINISHED
228 err: ERR_RESUME_MISMATCH
229 err: ERR_INVALID_ALGORITHM
230 err: ERR_BAD_SIGNATURE
231 err: ERR_WRONG_KEY_USAGE
232 err: ERR_NO_CLIENT_AUTH
234 \ Get supported curves (bit mask).
235 cc: supported-curves ( -- x ) {
236 uint32_t x = ENG->iec == NULL ? 0 : ENG->iec->supported_curves;
240 \ Get supported hash functions (bit mask and number).
241 \ Note: this (on purpose) skips MD5.
242 cc: supported-hash-functions ( -- x num ) {
248 for (i = br_sha1_ID; i <= br_sha512_ID; i ++) {
249 if (br_multihash_getimpl(&ENG->mhash, i)) {
258 \ Test support for RSA signatures.
259 cc: supports-rsa-sign? ( -- bool ) {
260 T0_PUSHi(-(ENG->irsavrfy != 0));
263 \ Test support for ECDSA signatures.
264 cc: supports-ecdsa? ( -- bool ) {
265 T0_PUSHi(-(ENG->iecdsa != 0));
268 \ (Re)initialise the multihasher.
269 cc: multihash-init ( -- ) {
270 br_multihash_init(&ENG->mhash);
273 \ Flush the current record: if some payload data has been accumulated,
274 \ close the record and schedule it for sending. If there is no such data,
275 \ this function does nothing.
276 cc: flush-record ( -- ) {
277 br_ssl_engine_flush_record(ENG);
280 \ Yield control to the caller.
281 \ When the control is returned to us, react to the new context. Returned
282 \ value is a bitwise combination of the following:
283 \ 0x01 handshake data is available
284 \ 0x02 change-cipher-spec data is available
285 \ 0x04 some data other than handshake or change-cipher-spec is available
286 \ 0x08 output buffer is ready for a new outgoing record
287 \ 0x10 renegotiation is requested and not to be ignored
288 \ Flags 0x01, 0x02 and 0x04 are mutually exclusive.
289 : wait-co ( -- state )
292 addr-action get8 dup if
294 1 of 0 do-close endof
295 2 of addr-application_data get8 1 = if
302 addr-close_received get8 ifnot
304 addr-record_type_in get8 case
309 \ Alert -- if close_notify received, trigger
310 \ the closure sequence.
311 21 of process-alerts if -1 do-close then endof
316 \ Not CCS, Alert or Handshake.
321 can-output? if 0x08 or then ;
323 \ Send an alert message. This shall be called only when there is room for
324 \ an outgoing record.
325 : send-alert ( level alert -- )
326 21 addr-record_type_out set8
327 swap write8-native drop write8-native drop
330 \ Send an alert message of level "warning". This shall be called only when
331 \ there is room for an outgoing record.
332 : send-warning ( alert -- )
335 \ Fail by sending a fatal alert.
336 : fail-alert ( alert -- ! )
339 begin can-output? not while wait-co drop repeat
341 begin can-output? not while wait-co drop repeat
344 \ Perform the close operation:
345 \ -- Prevent new application data from the caller.
346 \ -- Incoming data is discarded (except alerts).
347 \ -- Outgoing data is flushed.
348 \ -- A close_notify alert is sent.
349 \ -- If 'cnr' is zero, then incoming data is discarded until a close_notify
351 \ -- At the end, the context is terminated.
353 \ cnr shall be either 0 or -1.
354 : do-close ( cnr -- ! )
355 \ 'cnr' is set to non-zero when a close_notify is received from
359 \ Get out of application data state. If we were accepting
360 \ application data (flag is 1), and we still expect a close_notify
361 \ from the peer (cnr is 0), then we should set the flag to 2.
362 \ In all other cases, flag should be set to 0.
363 addr-application_data get8 cnr not and 1 << addr-application_data set8
365 \ Flush existing payload if any.
368 \ Wait for room to send the close_notify. Since individual records
369 \ can always hold at least 512 bytes, we know that when there is
370 \ room, then there is room for a complete close_notify (two bytes).
371 begin can-output? not while cnr wait-for-close >cnr repeat
373 \ Write the close_notify and flush it.
374 \ 21 addr-record_type_out set8
375 \ 1 write8-native 0 write8-native 2drop
379 \ Loop until our record has been sent (we know it's gone when
380 \ writing is again possible) and a close_notify has been received.
383 dup can-output? and if ERR_OK fail then
387 \ Yield control to the engine, with a possible flush. If 'cnr' is 0,
388 \ then input is analysed: all input is discarded, until a close_notify
390 : wait-for-close ( cnr -- cnr )
394 addr-record_type_in get8 21 = if
396 \ If we received a close_notify then we
397 \ no longer accept incoming application
399 0 addr-application_data set8
406 \ Test whether there is some accumulated payload that still needs to be
408 cc: payload-to-send? ( -- bool ) {
409 T0_PUSHi(-br_ssl_engine_has_pld_to_send(ENG));
412 \ Test whether there is some available input data.
413 cc: has-input? ( -- bool ) {
414 T0_PUSHi(-(ENG->hlen_in != 0));
417 \ Test whether some payload bytes may be written.
418 cc: can-output? ( -- bool ) {
419 T0_PUSHi(-(ENG->hlen_out > 0));
422 \ Discard current input entirely.
423 cc: discard-input ( -- ) {
427 \ Low-level read for one byte. If there is no available byte right
428 \ away, then -1 is returned. Otherwise, the byte value is returned.
429 \ If the current record type is "handshake" then the read byte is also
430 \ injected in the multi-hasher.
431 cc: read8-native ( -- x ) {
432 if (ENG->hlen_in > 0) {
435 x = *ENG->hbuf_in ++;
436 if (ENG->record_type_in == BR_SSL_HANDSHAKE) {
437 br_multihash_update(&ENG->mhash, &x, 1);
446 \ Low-level read for several bytes. On entry, this expects an address
447 \ (offset in the engine context) and a length; these values designate
448 \ where the chunk should go. Upon exit, the new address and length
449 \ are pushed; that output length contains how many bytes could not be
450 \ read. If there is no available byte for reading, the address and
451 \ length are unchanged.
452 \ If the current record type is "handshake" then the read bytes are
453 \ injected in the multi-hasher.
454 cc: read-chunk-native ( addr len -- addr len ) {
455 size_t clen = ENG->hlen_in;
461 if ((size_t)len < clen) {
464 memcpy((unsigned char *)ENG + addr, ENG->hbuf_in, clen);
465 if (ENG->record_type_in == BR_SSL_HANDSHAKE) {
466 br_multihash_update(&ENG->mhash, ENG->hbuf_in, clen);
468 T0_PUSH(addr + (uint32_t)clen);
469 T0_PUSH(len - (uint32_t)clen);
470 ENG->hbuf_in += clen;
471 ENG->hlen_in -= clen;
475 \ Process available alert bytes. If a fatal alert is received, then the
476 \ context is terminated; otherwise, this returns either true (-1) if a
477 \ close_notify was received, false (0) otherwise.
478 : process-alerts ( -- bool )
480 begin has-input? while read8-native process-alert-byte or repeat
481 dup if 1 addr-shutdown_recv set8 then ;
483 \ Process an alert byte. Returned value is non-zero if this is a close_notify,
485 : process-alert-byte ( x -- bool )
488 \ 'alert' field is 0, so this byte shall be a level.
489 \ Levels shall be 1 (warning) or 2 (fatal); we convert
490 \ all other values to "fatal".
491 dup 1 <> if drop 2 then
496 \ close_notify has value 0.
497 \ no_renegotiation has value 100, and we treat it
499 dup 100 = if 256 + fail then
502 \ Fatal alert implies context termination.
506 \ In general we only deal with handshake data here. Alerts are processed
507 \ in specific code right when they are received, and ChangeCipherSpec has
508 \ its own handling code. So we need to check that the data is "handshake"
509 \ only when returning from a coroutine call.
511 \ Yield control to the engine. Alerts are processed; if incoming data is
512 \ neither handshake or alert, then an error is triggered.
513 : wait-for-handshake ( -- )
514 wait-co 0x07 and 0x01 > if ERR_UNEXPECTED fail then ;
516 \ Flush outgoing data (if any), then wait for the output buffer to be
517 \ clear; when this is done, set the output record type to the specified
519 : wait-rectype-out ( rectype -- )
523 can-output? if rectype addr-record_type_out set8 ret then
527 \ Read one byte of handshake data. Block until that byte is available.
528 \ This does not check any length.
531 read8-native dup 0< ifnot ret then
532 drop wait-for-handshake
535 \ Test whether there are some more bytes in the current record. These
536 \ bytes have not necessarily been received yet (processing of unencrypted
537 \ records may begin before all bytes are received).
538 cc: more-incoming-bytes? ( -- bool ) {
539 T0_PUSHi(ENG->hlen_in != 0 || !br_ssl_engine_recvrec_finished(ENG));
542 \ For reading functions, the TOS is supposed to contain the number of bytes
543 \ that can still be read (from encapsulating structure header), and it is
546 : check-len ( lim len -- lim )
547 - dup 0< if ERR_BAD_PARAM fail then ;
549 \ Read one byte of handshake data. This pushes an integer in the 0..255 range.
550 : read8 ( lim -- lim x )
551 1 check-len read8-nc ;
553 \ Read a 16-bit value (in the 0..65535 range)
554 : read16 ( lim -- lim n )
555 2 check-len read8-nc 8 << read8-nc + ;
557 \ Read a 24-bit value (in the 0..16777215 range)
558 : read24 ( lim -- lim n )
559 3 check-len read8-nc 8 << read8-nc + 8 << read8-nc + ;
561 \ Read some bytes. The "address" is an offset within the context
563 : read-blob ( lim addr len -- lim )
569 dup 0 = if 2drop ret then
573 \ Read some bytes and drop them.
574 : skip-blob ( lim len -- lim )
575 swap over check-len swap
576 begin dup while read8-nc drop 1- repeat
579 \ Read a 16-bit length, then skip exactly that many bytes.
580 : read-ignore-16 ( lim -- lim )
583 \ Open a substructure: the inner structure length is checked against,
584 \ and substracted, from the output structure current limit.
585 : open-elt ( lim len -- lim-outer lim-inner )
587 - dup 0< if ERR_BAD_PARAM fail then
590 \ Close the current structure. This checks that the limit is 0.
591 : close-elt ( lim -- )
592 if ERR_BAD_PARAM fail then ;
594 \ Write one byte of handshake data.
597 dup write8-native if drop ret then
601 \ Low-level write for one byte. On exit, it pushes either -1 (byte was
602 \ written) or 0 (no room in output buffer).
603 cc: write8-native ( x -- bool ) {
606 x = (unsigned char)T0_POP();
607 if (ENG->hlen_out > 0) {
608 if (ENG->record_type_out == BR_SSL_HANDSHAKE) {
609 br_multihash_update(&ENG->mhash, &x, 1);
611 *ENG->hbuf_out ++ = x;
619 \ Write a 16-bit value.
621 dup 8 u>> write8 write8 ;
623 \ Write a 24-bit value.
625 dup 16 u>> write8 write16 ;
627 \ Write some bytes. The "address" is an offset within the context
629 : write-blob ( addr len -- )
632 dup 0 = if 2drop ret then
636 cc: write-blob-chunk ( addr len -- addr len ) {
637 size_t clen = ENG->hlen_out;
643 if ((size_t)len < clen) {
646 memcpy(ENG->hbuf_out, (unsigned char *)ENG + addr, clen);
647 if (ENG->record_type_out == BR_SSL_HANDSHAKE) {
648 br_multihash_update(&ENG->mhash, ENG->hbuf_out, clen);
650 T0_PUSH(addr + (uint32_t)clen);
651 T0_PUSH(len - (uint32_t)clen);
652 ENG->hbuf_out += clen;
653 ENG->hlen_out -= clen;
657 \ Write a blob with the length as header (over one byte)
658 : write-blob-head8 ( addr len -- )
659 dup write8 write-blob ;
661 \ Write a blob with the length as header (over two bytes)
662 : write-blob-head16 ( addr len -- )
663 dup write16 write-blob ;
665 \ Perform a byte-to-byte comparison between two blobs. Each blob is
666 \ provided as an "address" (offset in the context structure); the
667 \ length is common. Returned value is true (-1) if the two blobs are
668 \ equal, false (0) otherwise.
669 cc: memcmp ( addr1 addr2 len -- bool ) {
670 size_t len = (size_t)T0_POP();
671 void *addr2 = (unsigned char *)ENG + (size_t)T0_POP();
672 void *addr1 = (unsigned char *)ENG + (size_t)T0_POP();
673 int x = memcmp(addr1, addr2, len);
674 T0_PUSH((uint32_t)-(x == 0));
677 \ Copy bytes between two areas, whose addresses are provided as
678 \ offsets in the context structure.
679 cc: memcpy ( dst src len -- ) {
680 size_t len = (size_t)T0_POP();
681 void *src = (unsigned char *)ENG + (size_t)T0_POP();
682 void *dst = (unsigned char *)ENG + (size_t)T0_POP();
683 memcpy(dst, src, len);
686 \ Get string length (zero-terminated). The string address is provided as
687 \ an offset relative to the context start. Returned length does not include
689 cc: strlen ( str -- len ) {
690 void *str = (unsigned char *)ENG + (size_t)T0_POP();
691 T0_PUSH((uint32_t)strlen(str));
694 \ Fill a buffer with zeros. The buffer address is an offset in the context.
695 cc: bzero ( addr len -- ) {
696 size_t len = (size_t)T0_POP();
697 void *addr = (unsigned char *)ENG + (size_t)T0_POP();
698 memset(addr, 0, len);
701 \ Scan the list of supported cipher suites for a given value. If found,
702 \ then the list index at which it was found is returned; otherwise, -1
704 : scan-suite ( suite -- index )
706 addr-suites_num get8 { num }
708 begin dup num < while
709 dup 1 << addr-suites_buf + get16 suite = if ret then
714 \ =======================================================================
716 \ Generate random bytes into buffer (address is offset in context).
717 cc: mkrand ( addr len -- ) {
718 size_t len = (size_t)T0_POP();
719 void *addr = (unsigned char *)ENG + (size_t)T0_POP();
720 br_hmac_drbg_generate(&ENG->rng, addr, len);
723 \ Read a handshake message header: type and length. These are returned
724 \ in reverse order (type is TOS, length is below it).
725 : read-handshake-header-core ( -- lim type )
726 read8-nc 3 read24 swap drop swap ;
728 \ Read a handshake message header: type and length. If the header is for
729 \ a HelloRequest message, then it is discarded and a new header is read
730 \ (repeatedly if necessary).
731 : read-handshake-header ( -- lim type )
733 read-handshake-header-core dup 0= while
734 drop if ERR_BAD_HANDSHAKE fail then
737 \ =======================================================================
739 \ Cipher suite processing.
741 \ Unfortunately, cipher suite identifiers are attributed mostly arbitrary,
742 \ so we have to map the cipher suite numbers we support into aggregate
743 \ words that encode the information we need. Table below is organized
744 \ as a sequence of pairs of 16-bit words, the first being the cipher suite
745 \ identifier, the second encoding the algorithm elements. The suites are
746 \ ordered by increasing cipher suite ID, so that fast lookups may be
747 \ performed with a binary search (not implemented for the moment, since it
748 \ does not appear to matter much in practice).
750 \ Algorithm elements are encoded over 4 bits each, in the following order
751 \ (most significant to least significant):
753 \ -- Server key type:
754 \ 0 RSA (RSA key exchange)
755 \ 1 ECDHE-RSA (ECDHE key exchange, RSA signature)
756 \ 2 ECDHE-ECDSA (ECDHE key exchange, ECDSA signature)
757 \ 3 ECDH-RSA (ECDH key exchange, certificate is RSA-signed)
758 \ 4 ECDH-ECDSA (ECDH key exchange, certificate is ECDSA-signed)
759 \ -- Encryption algorithm:
765 \ 5 ChaCha20/Poly1305
767 \ 0 none (for suites with AEAD encryption)
771 \ -- PRF for TLS-1.2:
775 \ WARNING: if adding a new cipher suite that does not use SHA-256 for the
776 \ PRF (with TLS 1.2), be sure to check the suites_sha384[] array defined
777 \ in ssl/ssl_keyexport.c
779 data: cipher-suite-def
781 hexb| 000A 0024 | \ TLS_RSA_WITH_3DES_EDE_CBC_SHA
782 hexb| 002F 0124 | \ TLS_RSA_WITH_AES_128_CBC_SHA
783 hexb| 0035 0224 | \ TLS_RSA_WITH_AES_256_CBC_SHA
784 hexb| 003C 0144 | \ TLS_RSA_WITH_AES_128_CBC_SHA256
785 hexb| 003D 0244 | \ TLS_RSA_WITH_AES_256_CBC_SHA256
787 hexb| 009C 0304 | \ TLS_RSA_WITH_AES_128_GCM_SHA256
788 hexb| 009D 0405 | \ TLS_RSA_WITH_AES_256_GCM_SHA384
790 hexb| C003 4024 | \ TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
791 hexb| C004 4124 | \ TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
792 hexb| C005 4224 | \ TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
793 hexb| C008 2024 | \ TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
794 hexb| C009 2124 | \ TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
795 hexb| C00A 2224 | \ TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
796 hexb| C00D 3024 | \ TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
797 hexb| C00E 3124 | \ TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
798 hexb| C00F 3224 | \ TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
799 hexb| C012 1024 | \ TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
800 hexb| C013 1124 | \ TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
801 hexb| C014 1224 | \ TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
803 hexb| C023 2144 | \ TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
804 hexb| C024 2255 | \ TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
805 hexb| C025 4144 | \ TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
806 hexb| C026 4255 | \ TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
807 hexb| C027 1144 | \ TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
808 hexb| C028 1255 | \ TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
809 hexb| C029 3144 | \ TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
810 hexb| C02A 3255 | \ TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
811 hexb| C02B 2304 | \ TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
812 hexb| C02C 2405 | \ TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
813 hexb| C02D 4304 | \ TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
814 hexb| C02E 4405 | \ TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
815 hexb| C02F 1304 | \ TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
816 hexb| C030 1405 | \ TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
817 hexb| C031 3304 | \ TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
818 hexb| C032 3405 | \ TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
820 hexb| CCA8 1504 | \ TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
821 hexb| CCA9 2504 | \ TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
823 hexb| 0000 | \ List terminator.
825 \ Convert cipher suite identifier to element words. This returns 0 if
826 \ the cipher suite is not known.
827 : cipher-suite-to-elements ( suite -- elts )
831 dup 2+ swap data-get16
832 dup ifnot 2drop 0 ret then
833 id = if data-get16 ret then
837 \ Check that a given cipher suite is supported. Note that this also
838 \ returns true (-1) for the TLS_FALLBACK_SCSV pseudo-ciphersuite.
839 : suite-supported? ( suite -- bool )
840 dup 0x5600 = if drop -1 ret then
841 cipher-suite-to-elements 0<> ;
843 \ Get expected key type for cipher suite. The key type is one of
844 \ BR_KEYTYPE_RSA or BR_KEYTYPE_EC, combined with either BR_KEYTYPE_KEYX
845 \ (RSA encryption or static ECDH) or BR_KEYTYPE_SIGN (RSA or ECDSA
846 \ signature, for ECDHE cipher suites).
847 : expected-key-type ( suite -- key-type )
848 cipher-suite-to-elements 12 >>
850 0 of CX 0 63 { BR_KEYTYPE_RSA | BR_KEYTYPE_KEYX } endof
851 1 of CX 0 63 { BR_KEYTYPE_RSA | BR_KEYTYPE_SIGN } endof
852 2 of CX 0 63 { BR_KEYTYPE_EC | BR_KEYTYPE_SIGN } endof
853 3 of CX 0 63 { BR_KEYTYPE_EC | BR_KEYTYPE_KEYX } endof
854 4 of CX 0 63 { BR_KEYTYPE_EC | BR_KEYTYPE_KEYX } endof
858 \ Test whether the cipher suite uses RSA key exchange.
859 : use-rsa-keyx? ( suite -- bool )
860 cipher-suite-to-elements 12 >> 0= ;
862 \ Test whether the cipher suite uses ECDHE key exchange, signed with RSA.
863 : use-rsa-ecdhe? ( suite -- bool )
864 cipher-suite-to-elements 12 >> 1 = ;
866 \ Test whether the cipher suite uses ECDHE key exchange, signed with ECDSA.
867 : use-ecdsa-ecdhe? ( suite -- bool )
868 cipher-suite-to-elements 12 >> 2 = ;
870 \ Test whether the cipher suite uses ECDHE key exchange (with RSA or ECDSA).
871 : use-ecdhe? ( suite -- bool )
872 cipher-suite-to-elements 12 >> dup 0> swap 3 < and ;
874 \ Test whether the cipher suite uses ECDH (static) key exchange.
875 : use-ecdh? ( suite -- bool )
876 cipher-suite-to-elements 12 >> 2 > ;
878 \ Get identifier for the PRF (TLS 1.2).
879 : prf-id ( suite -- id )
880 cipher-suite-to-elements 15 and ;
882 \ Test whether a cipher suite is only for TLS-1.2. Cipher suites that
883 \ can be used with TLS-1.0 or 1.1 use HMAC/SHA-1. RFC do not formally
884 \ forbid using a CBC-based TLS-1.2 cipher suite, e.g. based on HMAC/SHA-256,
885 \ with older protocol versions; however, servers should not do that, since
886 \ it may confuse clients. Since the server code does not try such games,
887 \ for consistency, the client should reject it as well (normal servers
888 \ don't do that, so any attempt is a sign of foul play).
889 : use-tls12? ( suite -- bool )
890 cipher-suite-to-elements 0xF0 and 0x20 <> ;
892 \ Switch to negotiated security parameters for input or output.
893 : switch-encryption ( is-client for-input -- )
895 addr-cipher_suite get16 cipher-suite-to-elements { elts }
903 \ cipher type and key length
904 elts 8 >> 15 and case
963 cc: switch-cbc-out ( is_client prf_id mac_id aes cipher_key_len -- ) {
964 int is_client, prf_id, mac_id, aes;
965 unsigned cipher_key_len;
967 cipher_key_len = T0_POP();
971 is_client = T0_POP();
972 br_ssl_engine_switch_cbc_out(ENG, is_client, prf_id, mac_id,
973 aes ? ENG->iaes_cbcenc : ENG->ides_cbcenc, cipher_key_len);
976 cc: switch-cbc-in ( is_client prf_id mac_id aes cipher_key_len -- ) {
977 int is_client, prf_id, mac_id, aes;
978 unsigned cipher_key_len;
980 cipher_key_len = T0_POP();
984 is_client = T0_POP();
985 br_ssl_engine_switch_cbc_in(ENG, is_client, prf_id, mac_id,
986 aes ? ENG->iaes_cbcdec : ENG->ides_cbcdec, cipher_key_len);
989 cc: switch-aesgcm-out ( is_client prf_id cipher_key_len -- ) {
990 int is_client, prf_id;
991 unsigned cipher_key_len;
993 cipher_key_len = T0_POP();
995 is_client = T0_POP();
996 br_ssl_engine_switch_gcm_out(ENG, is_client, prf_id,
997 ENG->iaes_ctr, cipher_key_len);
1000 cc: switch-aesgcm-in ( is_client prf_id cipher_key_len -- ) {
1001 int is_client, prf_id;
1002 unsigned cipher_key_len;
1004 cipher_key_len = T0_POP();
1006 is_client = T0_POP();
1007 br_ssl_engine_switch_gcm_in(ENG, is_client, prf_id,
1008 ENG->iaes_ctr, cipher_key_len);
1011 cc: switch-chapol-out ( is_client prf_id -- ) {
1012 int is_client, prf_id;
1015 is_client = T0_POP();
1016 br_ssl_engine_switch_chapol_out(ENG, is_client, prf_id);
1019 cc: switch-chapol-in ( is_client prf_id -- ) {
1020 int is_client, prf_id;
1023 is_client = T0_POP();
1024 br_ssl_engine_switch_chapol_in(ENG, is_client, prf_id);
1027 \ Write Finished message.
1028 : write-Finished ( from_client -- )
1030 20 write8 12 write24 addr-pad 12 write-blob ;
1032 \ Read Finished message.
1033 : read-Finished ( from_client -- )
1035 read-handshake-header 20 <> if ERR_UNEXPECTED fail then
1036 addr-pad 12 + 12 read-blob
1038 addr-pad dup 12 + 12 memcmp ifnot ERR_BAD_FINISHED fail then ;
1040 \ Compute the "Finished" contents (either the value to send, or the
1041 \ expected value). The 12-byte string is written in the pad. The
1042 \ "from_client" value is non-zero for the Finished sent by the client.
1043 \ The computed value is also saved in the relevant buffer for handling
1044 \ secure renegotiation.
1045 : compute-Finished ( from_client -- )
1046 dup addr-saved_finished swap ifnot 12 + then swap
1047 addr-cipher_suite get16 prf-id compute-Finished-inner
1048 addr-pad 12 memcpy ;
1050 cc: compute-Finished-inner ( from_client prf_id -- ) {
1051 int prf_id = T0_POP();
1052 int from_client = T0_POPi();
1053 unsigned char tmp[48];
1054 br_tls_prf_seed_chunk seed;
1056 br_tls_prf_impl prf = br_ssl_engine_get_PRF(ENG, prf_id);
1058 if (ENG->session.version >= BR_TLS12) {
1059 seed.len = br_multihash_out(&ENG->mhash, prf_id, tmp);
1061 br_multihash_out(&ENG->mhash, br_md5_ID, tmp);
1062 br_multihash_out(&ENG->mhash, br_sha1_ID, tmp + 16);
1065 prf(ENG->pad, 12, ENG->session.master_secret,
1066 sizeof ENG->session.master_secret,
1067 from_client ? "client finished" : "server finished",
1071 \ Receive ChangeCipherSpec and Finished from the peer.
1072 : read-CCS-Finished ( is-client -- )
1074 addr-record_type_in get8 20 <> if ERR_UNEXPECTED fail then
1077 wait-co 0x07 and dup 0x02 <> while
1078 if ERR_UNEXPECTED fail then
1082 read8-nc 1 <> more-incoming-bytes? or if ERR_BAD_CCS fail then
1083 dup 1 switch-encryption
1085 \ Read and verify Finished from peer.
1088 \ Send ChangeCipherSpec and Finished to the peer.
1089 : write-CCS-Finished ( is-client -- )
1090 \ Flush and wait for output buffer to be clear, so that we may
1091 \ write our ChangeCipherSpec. We must switch immediately after
1092 \ triggering the flush.
1096 dup 0 switch-encryption
1101 \ Read and parse a list of supported signature algorithms (with hash
1102 \ functions). The resulting bit field is returned.
1103 : read-list-sign-algos ( lim -- lim value )
1107 read8 { hash } read8 { sign }
1109 \ If hash is 0x08 then this is a "new algorithm" identifier,
1110 \ and we set the corresponding bit if it is in the 0..15
1111 \ range. Otherwise, we keep the value only if the signature
1112 \ is either 1 (RSA) or 3 (ECDSA), and the hash is one of the
1113 \ SHA-* functions (2 to 6). Note that we reject MD5.
1116 1 sign 16 + << hashes or >hashes
1119 hash 2 >= hash 6 <= and
1120 sign 1 = sign 3 = or
1122 hashes 1 sign 1- 2 << hash + << or >hashes
1129 \ =======================================================================
1131 \ Compute total chain length. This includes the individual certificate
1132 \ headers, but not the total chain header. This also sets the cert_cur,
1133 \ cert_len and chain_len context fields.
1134 cc: total-chain-length ( -- len ) {
1139 for (u = 0; u < ENG->chain_len; u ++) {
1140 total += 3 + (uint32_t)ENG->chain[u].data_len;
1145 \ Get length for current certificate in the chain; if the chain end was
1146 \ reached, then this returns -1.
1147 cc: begin-cert ( -- len ) {
1148 if (ENG->chain_len == 0) {
1151 ENG->cert_cur = ENG->chain->data;
1152 ENG->cert_len = ENG->chain->data_len;
1155 T0_PUSH(ENG->cert_len);
1159 \ Copy a chunk of certificate data into the pad. Returned value is the
1160 \ chunk length, or 0 if the certificate end is reached.
1161 cc: copy-cert-chunk ( -- len ) {
1164 clen = ENG->cert_len;
1165 if (clen > sizeof ENG->pad) {
1166 clen = sizeof ENG->pad;
1168 memcpy(ENG->pad, ENG->cert_cur, clen);
1169 ENG->cert_cur += clen;
1170 ENG->cert_len -= clen;
1174 \ Write a Certificate message. Total chain length (excluding the 3-byte
1175 \ header) is returned; it is 0 if the chain is empty.
1176 : write-Certificate ( -- total_chain_len )
1178 total-chain-length dup
1179 dup 3 + write24 write24
1182 dup 0< if drop ret then write24
1183 begin copy-cert-chunk dup while
1184 addr-pad swap write-blob
1189 cc: x509-start-chain ( by_client -- ) {
1190 const br_x509_class *xc;
1194 xc = *(ENG->x509ctx);
1195 xc->start_chain(ENG->x509ctx, bc ? ENG->server_name : NULL);
1198 cc: x509-start-cert ( length -- ) {
1199 const br_x509_class *xc;
1201 xc = *(ENG->x509ctx);
1202 xc->start_cert(ENG->x509ctx, T0_POP());
1205 cc: x509-append ( length -- ) {
1206 const br_x509_class *xc;
1209 xc = *(ENG->x509ctx);
1211 xc->append(ENG->x509ctx, ENG->pad, len);
1214 cc: x509-end-cert ( -- ) {
1215 const br_x509_class *xc;
1217 xc = *(ENG->x509ctx);
1218 xc->end_cert(ENG->x509ctx);
1221 cc: x509-end-chain ( -- err ) {
1222 const br_x509_class *xc;
1224 xc = *(ENG->x509ctx);
1225 T0_PUSH(xc->end_chain(ENG->x509ctx));
1228 cc: get-key-type-usages ( -- key-type-usages ) {
1229 const br_x509_class *xc;
1230 const br_x509_pkey *pk;
1233 xc = *(ENG->x509ctx);
1234 pk = xc->get_pkey(ENG->x509ctx, &usages);
1238 T0_PUSH(pk->key_type | usages);
1242 \ Read a Certificate message.
1243 \ Parameter: non-zero if this is a read by the client of a certificate
1244 \ sent by the server; zero otherwise.
1247 \ - Valid: combination of key type and allowed key usages.
1248 \ - Invalid: negative (-x for error code x)
1249 : read-Certificate ( by_client -- key-type-usages )
1250 \ Get header, and check message type.
1251 read-handshake-header 11 = ifnot ERR_UNEXPECTED fail then
1253 \ If the chain is empty, do some special processing.
1255 read24 if ERR_BAD_PARAM fail then
1259 \ Start processing the chain through the X.509 engine.
1260 swap x509-start-chain
1262 \ Total chain length is a 24-bit integer.
1269 \ We read the certificate by chunks through the pad, so
1270 \ as to use the existing reading function (read-blob)
1271 \ that also ensures proper hashing.
1274 dup 256 > if 256 else dup then { len }
1275 addr-pad len read-blob
1282 \ We must close the chain AND the handshake message.
1286 \ Chain processing is finished; get the error code.
1288 dup if neg ret then drop
1290 \ Return key type and usages.
1291 get-key-type-usages ;
1293 \ =======================================================================
1295 \ Copy a specific protocol name from the list to the pad. The byte
1296 \ length is returned.
1297 cc: copy-protocol-name ( idx -- len ) {
1298 size_t idx = T0_POP();
1299 size_t len = strlen(ENG->protocol_names[idx]);
1300 memcpy(ENG->pad, ENG->protocol_names[idx], len);
1304 \ Compare name in pad with the configured list of protocol names.
1305 \ If a match is found, then the index is returned; otherwise, -1
1307 cc: test-protocol-name ( len -- n ) {
1308 size_t len = T0_POP();
1311 for (u = 0; u < ENG->protocol_names_num; u ++) {
1314 name = ENG->protocol_names[u];
1315 if (len == strlen(name) && memcmp(ENG->pad, name, len) == 0) {