1 ! Copyright (C) 2007, 2008, Slava Pestov, Elie CHAFTARI.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors alien alien.c-types alien.data alien.enums
4 alien.strings assocs byte-arrays classes.struct combinators
5 combinators.short-circuit destructors io io.backend io.binary
6 io.buffers io.encodings.latin1 io.encodings.string
7 io.encodings.utf8 io.files io.pathnames io.ports io.sockets
8 io.sockets.secure io.timeouts kernel libc math math.functions
9 math.order math.parser namespaces openssl openssl.libcrypto
10 openssl.libssl random sequences sets splitting unicode ;
11 SLOT: alpn-supported-protocols
12 IN: io.sockets.secure.openssl
14 GENERIC: ssl-method ( symbol -- method )
15 M: TLSv1 ssl-method drop TLSv1_method ;
16 M: TLSv1.1 ssl-method drop TLSv1_1_method ;
17 M: TLSv1.2 ssl-method drop TLSv1_2_method ;
19 MEMO: make-cipher-list ( -- string )
21 "ECDHE-ECDSA-AES256-GCM-SHA384"
22 "ECDHE-ECDSA-AES256-SHA384"
23 "ECDHE-ECDSA-AES128-GCM-SHA256"
24 "ECDHE-ECDSA-AES128-SHA256"
25 "ECDHE-RSA-AES256-GCM-SHA384"
26 "ECDHE-RSA-AES256-SHA384"
27 "ECDHE-RSA-AES128-GCM-SHA256"
28 "ECDHE-RSA-AES128-SHA256"
29 "ECDHE-ECDSA-AES256-CCM8"
30 "ECDHE-ECDSA-AES256-CCM"
31 "ECDHE-ECDSA-AES128-CCM8"
32 "ECDHE-ECDSA-AES128-CCM"
33 "ECDHE-ECDSA-CAMELLIA256-SHA384"
34 "ECDHE-RSA-CAMELLIA256-SHA384"
35 "ECDHE-ECDSA-CAMELLIA128-SHA256"
36 "ECDHE-RSA-CAMELLIA128-SHA256"
37 "ECDHE-RSA-CHACHA20-POLY1305"
38 "ECDHE-ECDSA-CHACHA20-POLY1305"
39 "ECDHE-PSK-CHACHA20-POLY1305"
49 TUPLE: openssl-context < secure-context aliens sessions ;
53 : bn-bytes-needed ( num -- bytes-required )
54 log2 1 + 8 / ceiling ;
58 : number>bn ( num -- bn )
59 dup bn-bytes-needed >be
63 : disable-old-tls ( ctx -- )
65 SSL_OP_NO_TLSv1 SSL_OP_NO_TLSv1_1 bitor
66 SSL_CTX_set_options ssl-error ;
68 : set-session-cache ( ctx -- )
70 [ SSL_SESS_CACHE_BOTH SSL_CTX_set_session_cache_mode ssl-error ]
71 [ 32 random-bits >hex dup length SSL_CTX_set_session_id_context ssl-error ]
74 ERROR: file-expected path ;
76 : ensure-exists ( path -- path )
77 dup exists? [ file-expected ] unless ; inline
79 : ssl-file-path ( path -- path' )
80 absolute-path ensure-exists ;
82 : load-certificate-chain ( ctx -- )
83 dup config>> key-file>> [
84 [ handle>> ] [ config>> key-file>> ssl-file-path ] bi
85 SSL_CTX_use_certificate_chain_file
89 : password-callback ( -- alien )
90 int { void* int bool void* } cdecl
91 [| buf size rwflag password! |
92 password [ B{ 0 } password! ] unless
94 password strlen :> len
95 buf password len 1 + size min memcpy
99 : default-pasword ( ctx -- alien )
100 [ config>> password>> latin1 malloc-string ] [ aliens>> ] bi
101 [ push ] [ drop ] 2bi ;
103 : set-default-password ( ctx -- )
104 dup config>> password>> [
105 [ handle>> password-callback SSL_CTX_set_default_passwd_cb ]
107 [ handle>> ] [ default-pasword ] bi
108 SSL_CTX_set_default_passwd_cb_userdata
112 : use-private-key-file ( ctx -- )
113 dup config>> key-file>> [
115 [ config>> key-file>> ssl-file-path ] bi
116 SSL_FILETYPE_PEM SSL_CTX_use_PrivateKey_file
120 : load-verify-locations ( ctx -- )
121 dup config>> [ ca-file>> ] [ ca-path>> ] bi or [
125 [ ca-file>> dup [ ssl-file-path ] when ]
126 [ ca-path>> dup [ ssl-file-path ] when ] bi
128 SSL_CTX_load_verify_locations
129 ] [ handle>> SSL_CTX_set_default_verify_paths ] if ssl-error ;
131 : set-verify-depth ( ctx -- )
132 dup config>> verify-depth>> [
133 [ handle>> ] [ config>> verify-depth>> ] bi
134 SSL_CTX_set_verify_depth
137 TUPLE: bio < disposable handle ;
139 : <bio> ( handle -- bio ) bio new-disposable swap >>handle ;
141 M: bio dispose* handle>> BIO_free ssl-error ;
143 : <file-bio> ( path -- bio )
144 normalize-path "r" BIO_new_file dup ssl-error <bio> ;
146 : load-dh-params ( ctx -- )
147 dup config>> dh-file>> [
148 [ handle>> ] [ config>> dh-file>> ] bi <file-bio> &dispose
149 handle>> f f f PEM_read_bio_DHparams dup ssl-error
150 SSL_CTX_set_tmp_dh ssl-error
153 ! Attempt to set ecdh. If it fails, ignore...?
154 : set-ecdh-params ( ctx -- )
155 handle>> SSL_CTRL_SET_ECDH_AUTO 1 f SSL_CTX_ctrl drop ;
157 : <openssl-context> ( config ctx -- context )
158 openssl-context new-disposable
162 H{ } clone >>sessions ;
164 M: openssl <secure-context>
167 dup method>> ssl-method SSL_CTX_new
168 dup ssl-error <openssl-context> |dispose
170 [ set-session-cache ]
171 [ load-certificate-chain ]
172 [ set-default-password ]
173 [ use-private-key-file ]
174 [ load-verify-locations ]
182 M: openssl-context dispose*
184 [ aliens>> [ &free drop ] each ]
185 [ sessions>> values [ SSL_SESSION_free ] each ]
186 [ handle>> SSL_CTX_free ]
190 TUPLE: ssl-handle < disposable file handle connected ;
192 SYMBOL: default-secure-context
194 : current-secure-context ( -- ctx )
196 default-secure-context [
197 <secure-config> <secure-context>
201 : get-session ( addrspec -- session/f )
202 current-secure-context sessions>> at ;
204 : save-session ( session addrspec -- )
205 current-secure-context sessions>> set-at ;
207 : set-secure-cipher-list-only ( ssl -- ssl )
208 dup handle>> make-cipher-list SSL_set_cipher_list ssl-error ;
210 : <ssl-handle> ( fd -- ssl )
212 ssl-handle new-disposable |dispose
213 current-secure-context handle>> SSL_new
214 dup ssl-error >>handle
216 set-secure-cipher-list-only
221 : alpn_select_cb_func ( -- alien )
222 [| ssl out outlen in inlen arg |
223 ! if alpn-protocols is empty return err noack
225 ! current-secure-context relies on secure-context
226 ! variable being set. if this is not set in a callback,
227 ! we need some other way of accessing it (probably
228 ! passing it as arg to SSL_CTX_set_alpn_select_cb, but
229 ! need to make sure that stays defined as long as the
230 ! callback can be called)
231 current-secure-context config>> alpn-supported-protocols>>
232 [ SSL_TLSEXT_ERR_NOACK ]
234 ! convert alpn-protocols from list of strings to
235 ! c-string in wire format and length.
236 ! see https://www.openssl.org/docs/manmaster/man3/SSL_set_alpn_protos.html
237 [ utf8 encode dup length prefix ] map
239 in inlen SSL_select_next_proto
240 ! the function returns OPENSSL_NPN_NO_OVERLAP when no
241 ! match is found, otherwise OPENSSL_NPN_NEGOTIATED
242 OPENSSL_NPN_NEGOTIATED =
243 [ ! DOUBLECHECK: The value in out is already copied
244 ! from the original, so we can just leave it and
245 ! return... otherwise this detail needs to be ironed
246 ! out, probably by finding the entry in in that out
247 ! is identical to. (out needs to point directly into
248 ! in, or a buffer that will outlive the tls
251 [ SSL_TLSEXT_ERR_ALERT_FATAL ] if
253 ] SSL_CTX_alpn_select_cb_func ;
255 : get_alpn_selected_wrapper ( ssl* -- alpn_string/f )
256 { c-string int } [ SSL_get0_alpn_selected ] with-out-parameters
257 drop ! how do we unbox the c-string?
258 ! also, the string is not null-terminated, is that problematic?
263 :: <ssl-socket> ( winsock hostname -- ssl )
264 winsock socket-handle BIO_NOCLOSE BIO_new_socket dup ssl-error :> bio
265 winsock <ssl-handle> :> handle
266 handle handle>> :> native-handle
267 current-secure-context config>> alpn-supported-protocols>>
268 [ drop native-handle ctx>> alpn_select_cb_func f SSL_CTX_set_alpn_select_cb ]
272 native-handle swap SSL_set_tlsext_host_name ssl-error
274 native-handle bio bio SSL_set_bio
277 : ssl-error-syscall ( ssl-handle -- event/f )
281 errno { [ ECONNRESET = ] [ EPIPE = ] } 1||
282 [ premature-close ] [ throw-errno ] if f
284 ! https://stackoverflow.com/questions/13686398/ssl-read-failing-with-ssl-error-syscall-error
289 : check-ssl-error ( ssl-handle ret -- event/f )
290 [ drop ] [ [ handle>> ] dip SSL_get_error ] 2bi
292 { SSL_ERROR_NONE [ drop f ] }
293 { SSL_ERROR_WANT_READ [ drop +input+ ] }
294 { SSL_ERROR_WANT_WRITE [ drop +output+ ] }
295 { SSL_ERROR_SYSCALL [ ssl-error-syscall ] }
296 { SSL_ERROR_SSL [ drop (ssl-error) ] }
297 { SSL_ERROR_ZERO_RETURN [ drop f ] }
298 { SSL_ERROR_WANT_ACCEPT [ drop +input+ ] }
302 : do-ssl-accept-once ( ssl-handle -- event/f )
303 dup handle>> SSL_accept check-ssl-error ;
305 : do-ssl-accept ( ssl-handle -- )
306 dup do-ssl-accept-once
307 [ [ dup file>> ] dip wait-for-fd do-ssl-accept ] [ drop ] if* ;
309 : maybe-handshake ( ssl-handle -- )
310 dup connected>> [ drop ] [
311 [ [ do-ssl-accept ] with-timeout ]
312 [ t swap connected<< ] bi
316 : do-ssl-read ( buffer ssl-handle -- event/f )
317 2dup handle>> swap [ buffer-end ] [ buffer-capacity ] bi SSL_read
318 [ check-ssl-error ] keep swap [ 2nip ] [ swap buffer+ f ] if* ;
321 dup maybe-handshake [ buffer>> ] dip do-ssl-read ;
324 : do-ssl-write ( buffer ssl-handle -- event/f )
325 2dup handle>> swap [ buffer@ ] [ buffer-length ] bi SSL_write
326 [ check-ssl-error ] keep swap [ 2nip ] [ swap buffer-consume f ] if* ;
329 dup maybe-handshake [ buffer>> ] dip do-ssl-write ;
332 : do-ssl-connect-once ( ssl-handle -- event/f )
333 dup handle>> SSL_connect check-ssl-error ;
335 : do-ssl-connect ( ssl-handle -- )
336 dup do-ssl-connect-once
337 [ dupd wait-for-fd do-ssl-connect ] [ drop ] if* ;
339 : resume-session ( ssl-handle ssl-session -- )
340 [ [ handle>> ] dip SSL_set_session ssl-error ]
341 [ drop do-ssl-connect ]
344 : begin-session ( ssl-handle addrspec -- )
345 [ drop do-ssl-connect ]
346 [ [ handle>> SSL_get1_session ] dip save-session ]
349 : secure-connection ( client-out addrspec -- )
354 [ resume-session ] [ begin-session ] ?if
356 ] [ drop t >>connected drop ] 2bi ;
358 M: ssl-handle timeout
359 drop secure-socket-timeout get ;
361 M: ssl-handle cancel-operation
362 file>> cancel-operation ;
364 M: ssl-handle dispose*
366 ! Free file>> after SSL_free
367 [ file>> &dispose drop ]
368 [ handle>> SSL_free ] bi
371 : check-verify-result ( ssl-handle -- )
372 SSL_get_verify_result X509_V_ERROR number>enum dup X509_V_ERR_OK =
373 [ drop ] [ certificate-verify-error ] if ;
375 : x509name>string ( x509name -- string )
376 NID_commonName 256 <byte-array>
377 [ 256 X509_NAME_get_text_by_NID ] keep
378 swap -1 = [ drop f ] [ latin1 alien>string ] if ;
380 : subject-name ( certificate -- host )
381 X509_get_subject_name x509name>string ;
383 : issuer-name ( certificate -- issuer )
384 X509_get_issuer_name x509name>string ;
386 : sk-value ( stack v -- obj )
387 ssl-new-api? get-global [ OPENSSL_sk_value ] [ sk_value ] if ;
389 : sk-num ( stack -- num )
390 ssl-new-api? get-global [ OPENSSL_sk_num ] [ sk_num ] if ;
392 : name-stack>sequence ( name-stack -- seq )
394 sk-value GENERAL_NAME_st memory>struct
397 : alternative-dns-names ( certificate -- dns-names )
398 NID_subject_alt_name f f X509_get_ext_d2i
399 [ name-stack>sequence ] [ f ] if*
400 [ type>> GEN_DNS = ] filter
401 [ d>> dNSName>> data>> utf8 alien>string ] map ;
403 ! *.foo.com matches: foo.com, www.foo.com, a.foo.com
404 ! *.bar.foo.com matches: bar.foo.com, www.bar.foo.com, b.bar.foo.com
405 : subject-names-match? ( name pattern -- ? )
410 [ [ [ CHAR: . = ] count ] bi@ - 1 <= ]
416 : check-subject-name ( host ssl-handle -- )
417 SSL_get_peer_certificate [
418 [ alternative-dns-names ]
419 [ subject-name ] bi suffix members
420 2dup [ subject-names-match? ] with any?
421 [ 2drop ] [ subject-name-verify-error ] if
422 ] [ certificate-missing-error ] if* ;
424 M: openssl check-certificate
425 current-secure-context config>> verify>> [
427 [ nip check-verify-result ]
428 [ check-subject-name ]
432 : check-buffer ( port -- port )
433 dup buffer>> buffer-empty? [ upgrade-buffers-full ] unless ;
435 : input/output-ports ( -- input output )
436 input-stream output-stream
437 [ get underlying-port check-buffer ] bi@
438 2dup [ handle>> ] bi@ eq? [ upgrade-on-non-socket ] unless ;
440 : make-input/output-secure ( input output -- )
441 dup handle>> non-ssl-socket? [ upgrade-on-non-socket ] unless
442 [ f <ssl-socket> ] change-handle
443 handle>> >>handle drop ;
445 : (send-secure-handshake) ( output -- )
446 remote-address get [ upgrade-on-non-socket ] unless*
449 M: openssl send-secure-handshake
451 [ make-input/output-secure ] keep
452 [ (send-secure-handshake) ] keep
453 remote-address get dup inet? [
454 host>> swap handle>> check-certificate
457 M: openssl accept-secure-handshake
459 make-input/output-secure ;
461 openssl secure-socket-backend set-global