Added ChaCha20+Poly1305 support (stand-alone, cipher suites).
[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: client_random
149 addr-eng: server_random
150 addr-eng: ecdhe_curve
151 addr-eng: ecdhe_point
152 addr-eng: ecdhe_point_len
153 addr-eng: reneg
154 addr-eng: saved_finished
155 addr-eng: flags
156 addr-eng: pad
157 addr-eng: action
158 addr-eng: alert
159 addr-eng: close_received
160
161 \ Similar to 'addr-eng:', for fields in the 'session' substructure.
162 : addr-session-field:
163 next-word { field }
164 "addr-" field + 0 1 define-word
165 0 8191 "offsetof(br_ssl_engine_context, session) + offsetof(br_ssl_session_parameters, " field + ")" + make-CX
166 postpone literal postpone ; ;
167
168 addr-session-field: session_id
169 addr-session-field: session_id_len
170 addr-session-field: version
171 addr-session-field: cipher_suite
172 addr-session-field: master_secret
173
174 \ Check a server flag by index.
175 : flag? ( index -- bool )
176 addr-flags get32 swap >> 1 and neg ;
177
178 \ Define a word that evaluates to an error constant. This assumes that
179 \ all relevant error codes are in the 0..63 range.
180 : err:
181 next-word { name }
182 name 0 1 define-word
183 0 63 "BR_" name + make-CX postpone literal postpone ; ;
184
185 err: ERR_OK
186 err: ERR_BAD_PARAM
187 err: ERR_BAD_STATE
188 err: ERR_UNSUPPORTED_VERSION
189 err: ERR_BAD_VERSION
190 err: ERR_BAD_LENGTH
191 err: ERR_TOO_LARGE
192 err: ERR_BAD_MAC
193 err: ERR_NO_RANDOM
194 err: ERR_UNKNOWN_TYPE
195 err: ERR_UNEXPECTED
196 err: ERR_BAD_CCS
197 err: ERR_BAD_ALERT
198 err: ERR_BAD_HANDSHAKE
199 err: ERR_OVERSIZED_ID
200 err: ERR_BAD_CIPHER_SUITE
201 err: ERR_BAD_COMPRESSION
202 err: ERR_BAD_FRAGLEN
203 err: ERR_BAD_SECRENEG
204 err: ERR_EXTRA_EXTENSION
205 err: ERR_BAD_SNI
206 err: ERR_BAD_HELLO_DONE
207 err: ERR_LIMIT_EXCEEDED
208 err: ERR_BAD_FINISHED
209 err: ERR_RESUME_MISMATCH
210 err: ERR_INVALID_ALGORITHM
211 err: ERR_BAD_SIGNATURE
212 err: ERR_WRONG_KEY_USAGE
213 err: ERR_NO_CLIENT_AUTH
214
215 \ Get supported curves (bit mask).
216 cc: supported-curves ( -- x ) {
217 uint32_t x = ENG->iec == NULL ? 0 : ENG->iec->supported_curves;
218 T0_PUSH(x);
219 }
220
221 \ Get supported hash functions (bit mask and number).
222 \ Note: this (on purpose) skips MD5.
223 cc: supported-hash-functions ( -- x num ) {
224 int i;
225 unsigned x, num;
226
227 x = 0;
228 num = 0;
229 for (i = br_sha1_ID; i <= br_sha512_ID; i ++) {
230 if (br_multihash_getimpl(&ENG->mhash, i)) {
231 x |= 1U << i;
232 num ++;
233 }
234 }
235 T0_PUSH(x);
236 T0_PUSH(num);
237 }
238
239 \ Test support for RSA signatures.
240 cc: supports-rsa-sign? ( -- bool ) {
241 T0_PUSHi(-(ENG->irsavrfy != 0));
242 }
243
244 \ Test support for ECDSA signatures.
245 cc: supports-ecdsa? ( -- bool ) {
246 T0_PUSHi(-(ENG->iecdsa != 0));
247 }
248
249 \ (Re)initialise the multihasher.
250 cc: multihash-init ( -- ) {
251 br_multihash_init(&ENG->mhash);
252 }
253
254 \ Flush the current record: if some payload data has been accumulated,
255 \ close the record and schedule it for sending. If there is no such data,
256 \ this function does nothing.
257 cc: flush-record ( -- ) {
258 br_ssl_engine_flush_record(ENG);
259 }
260
261 \ Yield control to the caller.
262 \ When the control is returned to us, react to the new context. Returned
263 \ value is a bitwise combination of the following:
264 \ 0x01 handshake data is available
265 \ 0x02 change-cipher-spec data is available
266 \ 0x04 some data other than handshake or change-cipher-spec is available
267 \ 0x08 output buffer is ready for a new outgoing record
268 \ 0x10 renegotiation is requested and not to be ignored
269 \ Flags 0x01, 0x02 and 0x04 are mutually exclusive.
270 : wait-co ( -- state )
271 co
272 0
273 addr-action get8 dup if
274 case
275 1 of 0 do-close endof
276 2 of addr-application_data get8 if 0x10 or then endof
277 endcase
278 else
279 drop
280 then
281 addr-close_received get8 ifnot
282 has-input? if
283 addr-record_type_in get8 case
284
285 \ ChangeCipherSpec
286 20 of 0x02 or endof
287
288 \ Alert -- if close_notify received, trigger
289 \ the closure sequence.
290 21 of process-alerts if -1 do-close then endof
291
292 \ Handshake
293 22 of 0x01 or endof
294
295 \ Not CCS, Alert or Handshake.
296 drop 0x04 or 0
297 endcase
298 then
299 then
300 can-output? if 0x08 or then ;
301
302 \ Send an alert message. This shall be called only when there is room for
303 \ an outgoing record.
304 : send-alert ( level alert -- )
305 21 addr-record_type_out set8
306 swap write8-native drop write8-native drop
307 flush-record ;
308
309 \ Send an alert message of level "warning". This shall be called only when
310 \ there is room for an outgoing record.
311 : send-warning ( alert -- )
312 1 swap send-alert ;
313
314 \ Fail by sending a fatal alert.
315 : fail-alert ( alert -- ! )
316 { alert }
317 flush-record
318 begin can-output? not while wait-co drop repeat
319 2 alert send-alert
320 begin can-output? not while wait-co drop repeat
321 alert 512 + fail ;
322
323 \ Perform the close operation:
324 \ -- Prevent new application data from the caller.
325 \ -- Incoming data is discarded (except alerts).
326 \ -- Outgoing data is flushed.
327 \ -- A close_notify alert is sent.
328 \ -- If 'cnr' is zero, then incoming data is discarded until a close_notify
329 \ is received.
330 \ -- At the end, the context is terminated.
331 : do-close ( cnr -- ! )
332 \ 'cnr' is set to non-zero when a close_notify is received from
333 \ the peer.
334 { cnr }
335
336 \ Get out of application data state.
337 0 addr-application_data set8
338
339 \ Flush existing payload if any.
340 flush-record
341
342 \ Wait for room to send the close_notify. Since individual records
343 \ can always hold at least 512 bytes, we know that when there is
344 \ room, then there is room for a complete close_notify (two bytes).
345 begin can-output? not while cnr wait-for-close >cnr repeat
346
347 \ Write the close_notify and flush it.
348 \ 21 addr-record_type_out set8
349 \ 1 write8-native 0 write8-native 2drop
350 \ flush-record
351 0 send-warning
352
353 \ Loop until our record has been sent (we know it's gone when
354 \ writing is again possible) and a close_notify has been received.
355 cnr
356 begin
357 dup can-output? and if ERR_OK fail then
358 wait-for-close
359 again ;
360
361 \ Yield control to the engine, with a possible flush. If 'cnr' is 0,
362 \ then input is analysed: all input is discarded, until a close_notify
363 \ is received.
364 : wait-for-close ( cnr -- cnr )
365 co
366 dup ifnot
367 has-input? if
368 addr-record_type_in get8 21 = if
369 drop process-alerts
370 else
371 discard-input
372 then
373 then
374 then ;
375
376 \ Test whether there is some accumulated payload that still needs to be
377 \ sent.
378 cc: payload-to-send? ( -- bool ) {
379 T0_PUSHi(-br_ssl_engine_has_pld_to_send(ENG));
380 }
381
382 \ Test whether there is some available input data.
383 cc: has-input? ( -- bool ) {
384 T0_PUSHi(-(ENG->hlen_in != 0));
385 }
386
387 \ Test whether some payload bytes may be written.
388 cc: can-output? ( -- bool ) {
389 T0_PUSHi(-(ENG->hlen_out > 0));
390 }
391
392 \ Discard current input entirely.
393 cc: discard-input ( -- ) {
394 ENG->hlen_in = 0;
395 }
396
397 \ Low-level read for one byte. If there is no available byte right
398 \ away, then -1 is returned. Otherwise, the byte value is returned.
399 \ If the current record type is "handshake" then the read byte is also
400 \ injected in the multi-hasher.
401 cc: read8-native ( -- x ) {
402 if (ENG->hlen_in > 0) {
403 unsigned char x;
404
405 x = *ENG->hbuf_in ++;
406 if (ENG->record_type_in == BR_SSL_HANDSHAKE) {
407 br_multihash_update(&ENG->mhash, &x, 1);
408 }
409 T0_PUSH(x);
410 ENG->hlen_in --;
411 } else {
412 T0_PUSHi(-1);
413 }
414 }
415
416 \ Low-level read for several bytes. On entry, this expects an address
417 \ (offset in the engine context) and a length; these values designate
418 \ where the chunk should go. Upon exit, the new address and length
419 \ are pushed; that output length contains how many bytes could not be
420 \ read. If there is no available byte for reading, the address and
421 \ length are unchanged.
422 \ If the current record type is "handshake" then the read bytes are
423 \ injected in the multi-hasher.
424 cc: read-chunk-native ( addr len -- addr len ) {
425 size_t clen = ENG->hlen_in;
426 if (clen > 0) {
427 uint32_t addr, len;
428
429 len = T0_POP();
430 addr = T0_POP();
431 if ((size_t)len < clen) {
432 clen = (size_t)len;
433 }
434 memcpy((unsigned char *)ENG + addr, ENG->hbuf_in, clen);
435 if (ENG->record_type_in == BR_SSL_HANDSHAKE) {
436 br_multihash_update(&ENG->mhash, ENG->hbuf_in, clen);
437 }
438 T0_PUSH(addr + (uint32_t)clen);
439 T0_PUSH(len - (uint32_t)clen);
440 ENG->hbuf_in += clen;
441 ENG->hlen_in -= clen;
442 }
443 }
444
445 \ Process available alert bytes. If a fatal alert is received, then the
446 \ context is terminated; otherwise, this returns either true (-1) if a
447 \ close_notify was received, false (0) otherwise.
448 : process-alerts ( -- bool )
449 0
450 begin has-input? while read8-native process-alert-byte or repeat
451 dup if 1 addr-shutdown_recv set8 then ;
452
453 \ Process an alert byte. Returned value is non-zero if this is a close_notify,
454 \ zero otherwise.
455 : process-alert-byte ( x -- bool )
456 addr-alert get8 case
457 0 of
458 \ 'alert' field is 0, so this byte shall be a level.
459 \ Levels shall be 1 (warning) or 2 (fatal); we convert
460 \ all other values to "fatal".
461 dup 1 <> if drop 2 then
462 addr-alert set8 0
463 endof
464 1 of
465 0 addr-alert set8
466 \ close_notify has value 0.
467 \ no_renegotiation has value 100, and we treat it
468 \ as a fatal alert.
469 dup 100 = if 256 + fail then
470 0= ret
471 endof
472 \ Fatal alert implies context termination.
473 drop 256 + fail
474 endcase ;
475
476 \ In general we only deal with handshake data here. Alerts are processed
477 \ in specific code right when they are received, and ChangeCipherSpec has
478 \ its own handling code. So we need to check that the data is "handshake"
479 \ only when returning from a coroutine call.
480
481 \ Yield control to the engine. Alerts are processed; if incoming data is
482 \ neither handshake or alert, then an error is triggered.
483 : wait-for-handshake ( -- )
484 wait-co 0x07 and 0x01 > if ERR_UNEXPECTED fail then ;
485
486 \ Flush outgoing data (if any), then wait for the output buffer to be
487 \ clear; when this is done, set the output record type to the specified
488 \ value.
489 : wait-rectype-out ( rectype -- )
490 { rectype }
491 flush-record
492 begin
493 can-output? if rectype addr-record_type_out set8 ret then
494 wait-co drop
495 again ;
496
497 \ Read one byte of handshake data. Block until that byte is available.
498 \ This does not check any length.
499 : read8-nc ( -- x )
500 begin
501 read8-native dup 0< ifnot ret then
502 drop wait-for-handshake
503 again ;
504
505 \ Test whether there are some more bytes in the current record. These
506 \ bytes have not necessarily been received yet (processing of unencrypted
507 \ records may begin before all bytes are received).
508 cc: more-incoming-bytes? ( -- bool ) {
509 T0_PUSHi(ENG->hlen_in != 0 || !br_ssl_engine_recvrec_finished(ENG));
510 }
511
512 \ For reading functions, the TOS is supposed to contain the number of bytes
513 \ that can still be read (from encapsulating structure header), and it is
514 \ updated.
515
516 : check-len ( lim len -- lim )
517 - dup 0< if ERR_BAD_PARAM fail then ;
518
519 \ Read one byte of handshake data. This pushes an integer in the 0..255 range.
520 : read8 ( lim -- lim x )
521 1 check-len read8-nc ;
522
523 \ Read a 16-bit value (in the 0..65535 range)
524 : read16 ( lim -- lim n )
525 2 check-len read8-nc 8 << read8-nc + ;
526
527 \ Read a 24-bit value (in the 0..16777215 range)
528 : read24 ( lim -- lim n )
529 3 check-len read8-nc 8 << read8-nc + 8 << read8-nc + ;
530
531 \ Read some bytes. The "address" is an offset within the context
532 \ structure.
533 : read-blob ( lim addr len -- lim )
534 { addr len }
535 len check-len
536 addr len
537 begin
538 read-chunk-native
539 dup 0 = if 2drop ret then
540 wait-for-handshake
541 again ;
542
543 \ Read some bytes and drop them.
544 : skip-blob ( lim len -- lim )
545 swap over check-len swap
546 begin dup while read8-nc drop 1- repeat
547 drop ;
548
549 \ Read a 16-bit length, then skip exactly that many bytes.
550 : read-ignore-16 ( lim -- lim )
551 read16 skip-blob ;
552
553 \ Open a substructure: the inner structure length is checked against,
554 \ and substracted, from the output structure current limit.
555 : open-elt ( lim len -- lim-outer lim-inner )
556 dup { len }
557 - dup 0< if ERR_BAD_PARAM fail then
558 len ;
559
560 \ Close the current structure. This checks that the limit is 0.
561 : close-elt ( lim -- )
562 if ERR_BAD_PARAM fail then ;
563
564 \ Write one byte of handshake data.
565 : write8 ( n -- )
566 begin
567 dup write8-native if drop ret then
568 wait-co drop
569 again ;
570
571 \ Low-level write for one byte. On exit, it pushes either -1 (byte was
572 \ written) or 0 (no room in output buffer).
573 cc: write8-native ( x -- bool ) {
574 unsigned char x;
575
576 x = (unsigned char)T0_POP();
577 if (ENG->hlen_out > 0) {
578 if (ENG->record_type_out == BR_SSL_HANDSHAKE) {
579 br_multihash_update(&ENG->mhash, &x, 1);
580 }
581 *ENG->hbuf_out ++ = x;
582 ENG->hlen_out --;
583 T0_PUSHi(-1);
584 } else {
585 T0_PUSHi(0);
586 }
587 }
588
589 \ Write a 16-bit value.
590 : write16 ( n -- )
591 dup 8 u>> write8 write8 ;
592
593 \ Write a 24-bit value.
594 : write24 ( n -- )
595 dup 16 u>> write8 write16 ;
596
597 \ Write some bytes. The "address" is an offset within the context
598 \ structure.
599 : write-blob ( addr len -- )
600 begin
601 write-blob-chunk
602 dup 0 = if 2drop ret then
603 wait-co drop
604 again ;
605
606 cc: write-blob-chunk ( addr len -- addr len ) {
607 size_t clen = ENG->hlen_out;
608 if (clen > 0) {
609 uint32_t addr, len;
610
611 len = T0_POP();
612 addr = T0_POP();
613 if ((size_t)len < clen) {
614 clen = (size_t)len;
615 }
616 memcpy(ENG->hbuf_out, (unsigned char *)ENG + addr, clen);
617 if (ENG->record_type_out == BR_SSL_HANDSHAKE) {
618 br_multihash_update(&ENG->mhash, ENG->hbuf_out, clen);
619 }
620 T0_PUSH(addr + (uint32_t)clen);
621 T0_PUSH(len - (uint32_t)clen);
622 ENG->hbuf_out += clen;
623 ENG->hlen_out -= clen;
624 }
625 }
626
627 \ Write a blob with the length as header (over one byte)
628 : write-blob-head8 ( addr len -- )
629 dup write8 write-blob ;
630
631 \ Write a blob with the length as header (over two bytes)
632 : write-blob-head16 ( addr len -- )
633 dup write16 write-blob ;
634
635 \ Perform a byte-to-byte comparison between two blobs. Each blob is
636 \ provided as an "address" (offset in the context structure); the
637 \ length is common. Returned value is true (-1) if the two blobs are
638 \ equal, false (0) otherwise.
639 cc: memcmp ( addr1 addr2 len -- bool ) {
640 size_t len = (size_t)T0_POP();
641 void *addr2 = (unsigned char *)ENG + (size_t)T0_POP();
642 void *addr1 = (unsigned char *)ENG + (size_t)T0_POP();
643 int x = memcmp(addr1, addr2, len);
644 T0_PUSH((uint32_t)-(x == 0));
645 }
646
647 \ Copy bytes between two areas, whose addresses are provided as
648 \ offsets in the context structure.
649 cc: memcpy ( dst src len -- ) {
650 size_t len = (size_t)T0_POP();
651 void *src = (unsigned char *)ENG + (size_t)T0_POP();
652 void *dst = (unsigned char *)ENG + (size_t)T0_POP();
653 memcpy(dst, src, len);
654 }
655
656 \ Get string length (zero-terminated). The string address is provided as
657 \ an offset relative to the context start. Returned length does not include
658 \ the terminated 0.
659 cc: strlen ( str -- len ) {
660 void *str = (unsigned char *)ENG + (size_t)T0_POP();
661 T0_PUSH((uint32_t)strlen(str));
662 }
663
664 \ Fill a buffer with zeros. The buffer address is an offset in the context.
665 cc: bzero ( addr len -- ) {
666 size_t len = (size_t)T0_POP();
667 void *addr = (unsigned char *)ENG + (size_t)T0_POP();
668 memset(addr, 0, len);
669 }
670
671 \ Scan the list of supported cipher suites for a given value. If found,
672 \ then the list index at which it was found is returned; otherwise, -1
673 \ is returned.
674 : scan-suite ( suite -- index )
675 { suite }
676 addr-suites_num get8 { num }
677 0
678 begin dup num < while
679 dup 1 << addr-suites_buf + get16 suite = if ret then
680 1+
681 repeat
682 drop -1 ;
683
684 \ =======================================================================
685
686 \ Generate random bytes into buffer (address is offset in context).
687 cc: mkrand ( addr len -- ) {
688 size_t len = (size_t)T0_POP();
689 void *addr = (unsigned char *)ENG + (size_t)T0_POP();
690 br_hmac_drbg_generate(&ENG->rng, addr, len);
691 }
692
693 \ Read a handshake message header: type and length. These are returned
694 \ in reverse order (type is TOS, length is below it).
695 : read-handshake-header-core ( -- lim type )
696 read8-nc 3 read24 swap drop swap ;
697
698 \ Read a handshake message header: type and length. If the header is for
699 \ a HelloRequest message, then it is discarded and a new header is read
700 \ (repeatedly if necessary).
701 : read-handshake-header ( -- lim type )
702 begin
703 read-handshake-header-core dup 0= while
704 drop if ERR_BAD_HANDSHAKE fail then
705 repeat ;
706
707 \ =======================================================================
708
709 \ Cipher suite processing.
710 \
711 \ Unfortunately, cipher suite identifiers are attributed mostly arbitrary,
712 \ so we have to map the cipher suite numbers we support into aggregate
713 \ words that encode the information we need. Table below is organized
714 \ as a sequence of pairs of 16-bit words, the first being the cipher suite
715 \ identifier, the second encoding the algorithm elements. The suites are
716 \ ordered by increasing cipher suite ID, so that fast lookups may be
717 \ performed with a binary search (not implemented for the moment, since it
718 \ does not appear to matter much in practice).
719 \
720 \ Algorithm elements are encoded over 4 bits each, in the following order
721 \ (most significant to least significant):
722 \
723 \ -- Server key type:
724 \ 0 RSA (RSA key exchange)
725 \ 1 ECDHE-RSA (ECDHE key exchange, RSA signature)
726 \ 2 ECDHE-ECDSA (ECDHE key exchange, ECDSA signature)
727 \ 3 ECDH-RSA (ECDH key exchange, certificate is RSA-signed)
728 \ 4 ECDH-ECDSA (ECDH key exchange, certificate is ECDSA-signed)
729 \ -- Encryption algorithm:
730 \ 0 3DES/CBC
731 \ 1 AES-128/CBC
732 \ 2 AES-256/CBC
733 \ 3 AES-128/GCM
734 \ 4 AES-256/GCM
735 \ 5 ChaCha20/Poly1305
736 \ -- MAC algorithm:
737 \ 0 none (for suites with AEAD encryption)
738 \ 2 HMAC/SHA-1
739 \ 4 HMAC/SHA-256
740 \ 5 HMAC/SHA-384
741 \ -- PRF for TLS-1.2:
742 \ 4 with SHA-256
743 \ 5 with SHA-384
744
745 data: cipher-suite-def
746
747 hexb| 000A 0024 | \ TLS_RSA_WITH_3DES_EDE_CBC_SHA
748 hexb| 002F 0124 | \ TLS_RSA_WITH_AES_128_CBC_SHA
749 hexb| 0035 0224 | \ TLS_RSA_WITH_AES_256_CBC_SHA
750 hexb| 003C 0144 | \ TLS_RSA_WITH_AES_128_CBC_SHA256
751 hexb| 003D 0244 | \ TLS_RSA_WITH_AES_256_CBC_SHA256
752
753 hexb| 009C 0304 | \ TLS_RSA_WITH_AES_128_GCM_SHA256
754 hexb| 009D 0405 | \ TLS_RSA_WITH_AES_256_GCM_SHA384
755
756 hexb| C003 4024 | \ TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
757 hexb| C004 4124 | \ TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
758 hexb| C005 4224 | \ TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
759 hexb| C008 2024 | \ TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
760 hexb| C009 2124 | \ TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
761 hexb| C00A 2224 | \ TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
762 hexb| C00D 3024 | \ TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
763 hexb| C00E 3124 | \ TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
764 hexb| C00F 3224 | \ TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
765 hexb| C012 1024 | \ TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
766 hexb| C013 1124 | \ TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
767 hexb| C014 1224 | \ TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
768
769 hexb| C023 2144 | \ TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
770 hexb| C024 2255 | \ TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
771 hexb| C025 4144 | \ TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
772 hexb| C026 4255 | \ TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
773 hexb| C027 1144 | \ TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
774 hexb| C028 1255 | \ TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
775 hexb| C029 3144 | \ TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
776 hexb| C02A 3255 | \ TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
777 hexb| C02B 2304 | \ TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
778 hexb| C02C 2405 | \ TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
779 hexb| C02D 4304 | \ TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
780 hexb| C02E 4405 | \ TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
781 hexb| C02F 1304 | \ TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
782 hexb| C030 1405 | \ TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
783 hexb| C031 3304 | \ TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
784 hexb| C032 3405 | \ TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
785
786 hexb| CCA8 1504 | \ TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
787 hexb| CCA9 2504 | \ TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
788
789 hexb| 0000 | \ List terminator.
790
791 \ Convert cipher suite identifier to element words. This returns 0 if
792 \ the cipher suite is not known.
793 : cipher-suite-to-elements ( suite -- elts )
794 { id }
795 cipher-suite-def
796 begin
797 dup 2+ swap data-get16
798 dup ifnot 2drop 0 ret then
799 id = if data-get16 ret then
800 2+
801 again ;
802
803 \ Check that a given cipher suite is supported. Note that this also
804 \ returns true (-1) for the TLS_FALLBACK_SCSV pseudo-ciphersuite.
805 : suite-supported? ( suite -- bool )
806 dup 0x5600 = if drop -1 ret then
807 cipher-suite-to-elements 0<> ;
808
809 \ Get expected key type for cipher suite. The key type is one of
810 \ BR_KEYTYPE_RSA or BR_KEYTYPE_EC, combined with either BR_KEYTYPE_KEYX
811 \ (RSA encryption or static ECDH) or BR_KEYTYPE_SIGN (RSA or ECDSA
812 \ signature, for ECDHE cipher suites).
813 : expected-key-type ( suite -- key-type )
814 cipher-suite-to-elements 12 >>
815 case
816 0 of CX 0 63 { BR_KEYTYPE_RSA | BR_KEYTYPE_KEYX } endof
817 1 of CX 0 63 { BR_KEYTYPE_RSA | BR_KEYTYPE_SIGN } endof
818 2 of CX 0 63 { BR_KEYTYPE_EC | BR_KEYTYPE_SIGN } endof
819 3 of CX 0 63 { BR_KEYTYPE_EC | BR_KEYTYPE_KEYX } endof
820 4 of CX 0 63 { BR_KEYTYPE_EC | BR_KEYTYPE_KEYX } endof
821 0 swap
822 endcase ;
823
824 \ Test whether the cipher suite uses RSA key exchange.
825 : use-rsa-keyx? ( suite -- bool )
826 cipher-suite-to-elements 12 >> 0= ;
827
828 \ Test whether the cipher suite uses ECDHE key exchange, signed with RSA.
829 : use-rsa-ecdhe? ( suite -- bool )
830 cipher-suite-to-elements 12 >> 1 = ;
831
832 \ Test whether the cipher suite uses ECDHE key exchange, signed with ECDSA.
833 : use-ecdsa-ecdhe? ( suite -- bool )
834 cipher-suite-to-elements 12 >> 2 = ;
835
836 \ Test whether the cipher suite uses ECDHE key exchange (with RSA or ECDSA).
837 : use-ecdhe? ( suite -- bool )
838 cipher-suite-to-elements 12 >> dup 0> swap 3 < and ;
839
840 \ Test whether the cipher suite uses ECDH (static) key exchange.
841 : use-ecdh? ( suite -- bool )
842 cipher-suite-to-elements 12 >> 2 > ;
843
844 \ Get identifier for the PRF (TLS 1.2).
845 : prf-id ( suite -- id )
846 cipher-suite-to-elements 15 and ;
847
848 \ Switch to negotiated security parameters for input or output.
849 : switch-encryption ( is-client for-input -- )
850 { for-input }
851 addr-cipher_suite get16 cipher-suite-to-elements { elts }
852
853 \ prf_id
854 elts 15 and
855
856 \ mac_id
857 elts 4 >> 15 and
858
859 \ cipher type and key length
860 elts 8 >> 15 and case
861 \ 3DES/CBC
862 0 of 0 24
863 for-input if
864 switch-cbc-in
865 else
866 switch-cbc-out
867 then
868 endof
869
870 \ AES-128/CBC
871 1 of 1 16
872 for-input if
873 switch-cbc-in
874 else
875 switch-cbc-out
876 then
877 endof
878
879 \ AES-256/CBC
880 2 of 1 32
881 for-input if
882 switch-cbc-in
883 else
884 switch-cbc-out
885 then
886 endof
887
888 \ AES-128/GCM
889 3 of drop 16
890 for-input if
891 switch-aesgcm-in
892 else
893 switch-aesgcm-out
894 then
895 endof
896
897 \ AES-256/GCM
898 4 of drop 32
899 for-input if
900 switch-aesgcm-in
901 else
902 switch-aesgcm-out
903 then
904 endof
905
906 \ ChaCha20+Poly1305
907 5 of drop
908 for-input if
909 switch-chapol-in
910 else
911 switch-chapol-out
912 then
913 endof
914
915 ERR_BAD_PARAM fail
916 endcase
917 ;
918
919 cc: switch-cbc-out ( is_client prf_id mac_id aes cipher_key_len -- ) {
920 int is_client, prf_id, mac_id, aes;
921 unsigned cipher_key_len;
922
923 cipher_key_len = T0_POP();
924 aes = T0_POP();
925 mac_id = T0_POP();
926 prf_id = T0_POP();
927 is_client = T0_POP();
928 br_ssl_engine_switch_cbc_out(ENG, is_client, prf_id, mac_id,
929 aes ? ENG->iaes_cbcenc : ENG->ides_cbcenc, cipher_key_len);
930 }
931
932 cc: switch-cbc-in ( is_client prf_id mac_id aes cipher_key_len -- ) {
933 int is_client, prf_id, mac_id, aes;
934 unsigned cipher_key_len;
935
936 cipher_key_len = T0_POP();
937 aes = T0_POP();
938 mac_id = T0_POP();
939 prf_id = T0_POP();
940 is_client = T0_POP();
941 br_ssl_engine_switch_cbc_in(ENG, is_client, prf_id, mac_id,
942 aes ? ENG->iaes_cbcdec : ENG->ides_cbcdec, cipher_key_len);
943 }
944
945 cc: switch-aesgcm-out ( is_client prf_id cipher_key_len -- ) {
946 int is_client, prf_id;
947 unsigned cipher_key_len;
948
949 cipher_key_len = T0_POP();
950 prf_id = T0_POP();
951 is_client = T0_POP();
952 br_ssl_engine_switch_gcm_out(ENG, is_client, prf_id,
953 ENG->iaes_ctr, cipher_key_len);
954 }
955
956 cc: switch-aesgcm-in ( is_client prf_id cipher_key_len -- ) {
957 int is_client, prf_id;
958 unsigned cipher_key_len;
959
960 cipher_key_len = T0_POP();
961 prf_id = T0_POP();
962 is_client = T0_POP();
963 br_ssl_engine_switch_gcm_in(ENG, is_client, prf_id,
964 ENG->iaes_ctr, cipher_key_len);
965 }
966
967 cc: switch-chapol-out ( is_client prf_id -- ) {
968 int is_client, prf_id;
969
970 prf_id = T0_POP();
971 is_client = T0_POP();
972 br_ssl_engine_switch_chapol_out(ENG, is_client, prf_id);
973 }
974
975 cc: switch-chapol-in ( is_client prf_id -- ) {
976 int is_client, prf_id;
977
978 prf_id = T0_POP();
979 is_client = T0_POP();
980 br_ssl_engine_switch_chapol_in(ENG, is_client, prf_id);
981 }
982
983 \ Write Finished message.
984 : write-Finished ( from_client -- )
985 compute-Finished
986 20 write8 12 write24 addr-pad 12 write-blob ;
987
988 \ Read Finished message.
989 : read-Finished ( from_client -- )
990 compute-Finished
991 read-handshake-header 20 <> if ERR_UNEXPECTED fail then
992 addr-pad 12 + 12 read-blob
993 close-elt
994 addr-pad dup 12 + 12 memcmp ifnot ERR_BAD_FINISHED fail then ;
995
996 \ Compute the "Finished" contents (either the value to send, or the
997 \ expected value). The 12-byte string is written in the pad. The
998 \ "from_client" value is non-zero for the Finished sent by the client.
999 \ The computed value is also saved in the relevant buffer for handling
1000 \ secure renegotiation.
1001 : compute-Finished ( from_client -- )
1002 dup addr-saved_finished swap ifnot 12 + then swap
1003 addr-cipher_suite get16 prf-id compute-Finished-inner
1004 addr-pad 12 memcpy ;
1005
1006 cc: compute-Finished-inner ( from_client prf_id -- ) {
1007 int prf_id = T0_POP();
1008 int from_client = T0_POPi();
1009 unsigned char seed[48];
1010 size_t seed_len;
1011
1012 br_tls_prf_impl prf = br_ssl_engine_get_PRF(ENG, prf_id);
1013 if (ENG->session.version >= BR_TLS12) {
1014 seed_len = br_multihash_out(&ENG->mhash, prf_id, seed);
1015 } else {
1016 br_multihash_out(&ENG->mhash, br_md5_ID, seed);
1017 br_multihash_out(&ENG->mhash, br_sha1_ID, seed + 16);
1018 seed_len = 36;
1019 }
1020 prf(ENG->pad, 12, ENG->session.master_secret,
1021 sizeof ENG->session.master_secret,
1022 from_client ? "client finished" : "server finished",
1023 seed, seed_len);
1024 }
1025
1026 \ Receive ChangeCipherSpec and Finished from the peer.
1027 : read-CCS-Finished ( is-client -- )
1028 has-input? if
1029 addr-record_type_in get8 20 <> if ERR_UNEXPECTED fail then
1030 else
1031 begin
1032 wait-co 0x07 and dup 0x02 <> while
1033 if ERR_UNEXPECTED fail then
1034 repeat
1035 drop
1036 then
1037 read8-nc 1 <> more-incoming-bytes? or if ERR_BAD_CCS fail then
1038 dup 1 switch-encryption
1039
1040 \ Read and verify Finished from peer.
1041 not read-Finished ;
1042
1043 \ Send ChangeCipherSpec and Finished to the peer.
1044 : write-CCS-Finished ( is-client -- )
1045 \ Flush and wait for output buffer to be clear, so that we may
1046 \ write our ChangeCipherSpec. We must switch immediately after
1047 \ triggering the flush.
1048 20 wait-rectype-out
1049 1 write8
1050 flush-record
1051 dup 0 switch-encryption
1052 22 wait-rectype-out
1053 write-Finished
1054 flush-record ;
1055
1056 \ Read and parse a list of supported signature algorithms (with hash
1057 \ functions). The resulting bit field is returned.
1058 : read-list-sign-algos ( lim -- lim value )
1059 0 { hashes }
1060 read16 open-elt
1061 begin dup while
1062 read8 { hash } read8 { sign }
1063 \ We keep the value if the signature is either 1 (RSA)
1064 \ or 3 (ECDSA), and the hash is one of the SHA-* functions
1065 \ (2 to 6, from SHA-1 to SHA-512); we reject MD5.
1066 hash 2 >= hash 6 <= and
1067 sign 1 = sign 3 = or
1068 and if
1069 hashes 1 sign 1- 2 << hash + << or >hashes
1070 then
1071 repeat
1072 close-elt
1073 hashes ;
1074
1075 \ =======================================================================
1076
1077 \ Compute total chain length. This includes the individual certificate
1078 \ headers, but not the total chain header. This also sets the cert_cur,
1079 \ cert_len and chain_len context fields.
1080 cc: total-chain-length ( -- len ) {
1081 size_t u;
1082 uint32_t total;
1083
1084 total = 0;
1085 for (u = 0; u < ENG->chain_len; u ++) {
1086 total += 3 + (uint32_t)ENG->chain[u].data_len;
1087 }
1088 T0_PUSH(total);
1089 }
1090
1091 \ Get length for current certificate in the chain; if the chain end was
1092 \ reached, then this returns -1.
1093 cc: begin-cert ( -- len ) {
1094 if (ENG->chain_len == 0) {
1095 T0_PUSHi(-1);
1096 } else {
1097 ENG->cert_cur = ENG->chain->data;
1098 ENG->cert_len = ENG->chain->data_len;
1099 ENG->chain ++;
1100 ENG->chain_len --;
1101 T0_PUSH(ENG->cert_len);
1102 }
1103 }
1104
1105 \ Copy a chunk of certificate data into the pad. Returned value is the
1106 \ chunk length, or 0 if the certificate end is reached.
1107 cc: copy-cert-chunk ( -- len ) {
1108 size_t clen;
1109
1110 clen = ENG->cert_len;
1111 if (clen > sizeof ENG->pad) {
1112 clen = sizeof ENG->pad;
1113 }
1114 memcpy(ENG->pad, ENG->cert_cur, clen);
1115 ENG->cert_cur += clen;
1116 ENG->cert_len -= clen;
1117 T0_PUSH(clen);
1118 }
1119
1120 \ Write a Certificate message. Total chain length (excluding the 3-byte
1121 \ header) is returned; it is 0 if the chain is empty.
1122 : write-Certificate ( -- total_chain_len )
1123 11 write8
1124 total-chain-length dup
1125 dup 3 + write24 write24
1126 begin
1127 begin-cert
1128 dup 0< if drop ret then write24
1129 begin copy-cert-chunk dup while
1130 addr-pad swap write-blob
1131 repeat
1132 drop
1133 again ;
1134
1135 cc: x509-start-chain ( by_client -- ) {
1136 const br_x509_class *xc;
1137 uint32_t bc;
1138
1139 bc = T0_POP();
1140 xc = *(ENG->x509ctx);
1141 xc->start_chain(ENG->x509ctx, bc ? ENG->server_name : NULL);
1142 }
1143
1144 cc: x509-start-cert ( length -- ) {
1145 const br_x509_class *xc;
1146
1147 xc = *(ENG->x509ctx);
1148 xc->start_cert(ENG->x509ctx, T0_POP());
1149 }
1150
1151 cc: x509-append ( length -- ) {
1152 const br_x509_class *xc;
1153 size_t len;
1154
1155 xc = *(ENG->x509ctx);
1156 len = T0_POP();
1157 xc->append(ENG->x509ctx, ENG->pad, len);
1158 }
1159
1160 cc: x509-end-cert ( -- ) {
1161 const br_x509_class *xc;
1162
1163 xc = *(ENG->x509ctx);
1164 xc->end_cert(ENG->x509ctx);
1165 }
1166
1167 cc: x509-end-chain ( -- err ) {
1168 const br_x509_class *xc;
1169
1170 xc = *(ENG->x509ctx);
1171 T0_PUSH(xc->end_chain(ENG->x509ctx));
1172 }
1173
1174 cc: get-key-type-usages ( -- key-type-usages ) {
1175 const br_x509_class *xc;
1176 const br_x509_pkey *pk;
1177 unsigned usages;
1178
1179 xc = *(ENG->x509ctx);
1180 pk = xc->get_pkey(ENG->x509ctx, &usages);
1181 if (pk == NULL) {
1182 T0_PUSH(0);
1183 } else {
1184 T0_PUSH(pk->key_type | usages);
1185 }
1186 }
1187
1188 \ Read a Certificate message.
1189 \ Parameter: non-zero if this is a read by the client of a certificate
1190 \ sent by the server; zero otherwise.
1191 \ Returned value:
1192 \ - Empty: 0
1193 \ - Valid: combination of key type and allowed key usages.
1194 \ - Invalid: negative (-x for error code x)
1195 : read-Certificate ( by_client -- key-type-usages )
1196 \ Get header, and check message type.
1197 read-handshake-header 11 = ifnot ERR_UNEXPECTED fail then
1198
1199 \ If the chain is empty, do some special processing.
1200 dup 3 = if
1201 read24 if ERR_BAD_PARAM fail then
1202 swap drop ret
1203 then
1204
1205 \ Start processing the chain through the X.509 engine.
1206 swap x509-start-chain
1207
1208 \ Total chain length is a 24-bit integer.
1209 read24 open-elt
1210 begin
1211 dup while
1212 read24 open-elt
1213 dup x509-start-cert
1214
1215 \ We read the certificate by chunks through the pad, so
1216 \ as to use the existing reading function (read-blob)
1217 \ that also ensures proper hashing.
1218 begin
1219 dup while
1220 dup 256 > if 256 else dup then { len }
1221 addr-pad len read-blob
1222 len x509-append
1223 repeat
1224 close-elt
1225 x509-end-cert
1226 repeat
1227
1228 \ We must close the chain AND the handshake message.
1229 close-elt
1230 close-elt
1231
1232 \ Chain processing is finished; get the error code.
1233 x509-end-chain
1234 dup if neg ret then drop
1235
1236 \ Return key type and usages.
1237 get-key-type-usages ;