forked from erlang/otp
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathssl.erl
More file actions
3936 lines (3327 loc) · 157 KB
/
Copy pathssl.erl
File metadata and controls
3936 lines (3327 loc) · 157 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%%
%% %CopyrightBegin%
%%
%% SPDX-License-Identifier: Apache-2.0
%%
%% Copyright Ericsson AB 1999-2026. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
%%
%%% Purpose : Main API module for the SSL application that implements TLS and DTLS
%%% SSL is a legacy name.
-module(ssl).
-moduledoc """
Interface functions for TLS (Transport Layer Security)
and DTLS (Datagram Transport Layer Security).
> #### Note {: .info }
The application's name is still SSL because the first versions of the
TLS protocol were named SSL (Secure Socket Layer). However, no version
of the old SSL protocol is supported by this application.
Example:
```erlang
1> ssl:start(), ssl:connect("google.com", 443, [{verify, verify_peer},
{cacerts, public_key:cacerts_get()}]).
{ok,{sslsocket, [...]}}
```
See [Examples](using_ssl.md) for detailed usage and more examples of
this API.
Special Erlang node configuration for the application can be found in
[SSL Application](ssl_app.md).
""".
-include_lib("public_key/include/public_key.hrl").
-include_lib("kernel/include/logger.hrl").
-include("ssl_internal.hrl").
-include("ssl_api.hrl").
-include("ssl_record.hrl").
-include("ssl_cipher.hrl").
-include("ssl_handshake.hrl").
-include("ssl_srp.hrl").
%% Needed to make documentation rendering happy
-ifndef(VSN).
-define(VSN,"unknown").
-endif.
%% Application handling
-export([start/0,
start/1,
stop/0,
clear_pem_cache/0]).
%% Socket handling
-export([connect/3,
connect/2,
connect/4,
listen/2,
transport_accept/1,
transport_accept/2,
handshake/1,
handshake/2,
handshake/3,
handshake_continue/2,
handshake_continue/3,
handshake_cancel/1,
controlling_process/2,
peername/1,
peercert/1,
sockname/1,
close/1,
close/2,
shutdown/2,
recv/2,
recv/3,
send/2,
getopts/2,
setopts/2,
getstat/1,
getstat/2
]).
%% SSL/TLS protocol handling
-export([cipher_suites/2,
cipher_suites/3,
filter_cipher_suites/2,
prepend_cipher_suites/2,
append_cipher_suites/2,
signature_algs/2,
eccs/0,
eccs/1,
versions/0,
groups/0,
groups/1,
format_error/1,
renegotiate/1,
update_keys/2,
export_key_materials/4,
export_key_materials/5,
prf/5,
negotiated_protocol/1,
connection_information/1,
connection_information/2]).
%% Misc
-export([tls_version/1,
suite_to_str/1,
suite_to_openssl_str/1,
str_to_suite/1]).
%% Tracing
-export([handle_trace/3]).
-deprecated([{prf,5,"Use export_key_materials/4 instead. "
"Note that in OTP 28 the 'testing' way of calling this function will no longer be supported."
}]).
-deprecated_type([{prf_random, 0,"Only used in deprecated function prf/5 and will no longer be needed."}]).
-removed({ssl_accept, '_',
"use ssl:handshake/1,2,3 instead"}).
-removed({cipher_suites, 0,
"use ssl:cipher_suites/2,3 instead"}).
-removed({cipher_suites, 1,
"use ssl:cipher_suites/2,3 instead"}).
-removed([{negotiated_next_protocol,1,
"use ssl:negotiated_protocol/1 instead"}]).
-removed([{connection_info,1,
"use ssl:connection_information/1,2 instead"}]).
-export_type([active_msgs/0,
cert_key_conf/0,
cipher/0,
cipher_filters/0,
ciphers/0,
connection_info/0,
connection_info_keys/0,
erl_cipher_suite/0,
error_alert/0,
group/0,
hash/0,
host/0,
kex_algo/0,
key/0,
named_curve/0,
old_cipher_suite/0,
prf_random/0,
protocol_extensions/0,
protocol_version/0,
reason/0,
session_id/0,
session_ticket/0,
sign_algo/0,
sign_scheme/0,
signature_algs/0,
socket/0,
socket_option/0,
srp_param_type/0,
sslsocket/0,
tls_alert/0,
tls_client_option/0,
tls_option/0,
tls_server_option/0,
client_option_cert/0,
server_option_cert/0,
common_option_tls13/0,
keylog_info/0
]).
%% -------------------------------------------------------------------------------------------------------
-doc(#{group => <<"Socket">>}).
-doc """
A socket that can be used to perform a so-called "START-TLS", which
means using an already connected socket previously used for plain TCP
traffic and upgrading it to use TLS.
Both sides needs to agree on the upgrade.
""".
-type socket() :: gen_tcp:socket() | socket:socket(). % exported
-doc(#{group => <<"Socket">>}).
-doc """
Options for the transport socket.
The default socket options are
`[{mode, list}, {packet, 0}, {header, 0}, {active, true}]`.
For valid options, see `m:inet`, `m:gen_tcp`, and `m:gen_udp`
in Kernel. Note that stream-oriented options such as `packet` are
only relevant for TLS and not DTLS.
""".
-type socket_option() :: gen_tcp:connect_option() | gen_tcp:listen_option() | gen_udp:option(). % exported
-doc(#{group => <<"Socket">>}).
-doc """
An opaque reference to the TLS/DTLS connection.
Note that despite being opaque, matching `sslsocket()` instances is allowed.
""".
-type sslsocket() :: any(). % exported
-doc(#{group => <<"Socket">>}).
-doc """
An option related to the TLS/DTLS protocol.
""".
-type tls_option() :: tls_client_option() | tls_server_option(). % exported
-doc(#{group => <<"Socket">>}).
-doc """
An option that can be supplied to a TLS client.
""".
-type tls_client_option() :: client_option() | common_option() | socket_option() | transport_option(). % exported
-doc(#{group => <<"Socket">>}).
-doc """
An option that can be supplied to a TLS server.
""".
-type tls_server_option() :: server_option() | common_option() | socket_option() | transport_option(). % exported
-doc(#{group => <<"Socket">>}).
-doc """
The type for the messages that are delivered to the owner of a
TLS/DTLS socket in active mode.
The `ssl_error` reason may convey a TLS protocol alert if such an event occurs
after the connection has been established. The most common case when this will
happen is on the client side when a TLS-1.3 server requests a client certificate
and the provided certificate is not accepted by the server, as it will be
verified after the server has sent its last handshake message.
The `ssl_passive` message is sent only when the socket is in `{active, N}` mode
and the counter has dropped to 0. It indicates that the socket has transitioned
to passive (`{active, false}`) mode.
""".
-type active_msgs() :: {ssl, sslsocket(), Data::binary() | list()} | {ssl_closed, sslsocket()} |
{ssl_error, sslsocket(), Alert::error_alert() | Reason::any()} | {ssl_passive, sslsocket()}. % exported
-doc(#{group => <<"Socket">>}).
-doc """
Transport option defines a callback module and message tags to handle the underlying transport socket.
Can be used to customize the transport layer. The tag
values should be the values used by the underlying transport in its active mode
messages.
Defaults to `{gen_tcp, tcp, tcp_closed, tcp_error, tcp_passive}` for TLS.
> #### Note {: .info }
For backward compatibility a tuple of size four will be converted to a
tuple of size five, where `PassiveTag` is the `DataTag` element with
`_passive` appended.
For TLS the callback module must implement a reliable transport
protocol, behave as `m:gen_tcp`, and have functions corresponding to
`inet:setopts/2`, `inet:getopts/2`, `inet:peername/1`, `inet:sockname/1`, and
`inet:port/1`. The callback `m:gen_tcp` is treated specially and calls `m:inet`
directly. For DTLS this feature is considered experimental.
""".
-type transport_option() :: {cb_info, {CallbackModule::atom(), DataTag::atom(),
ClosedTag::atom(), ErrTag::atom()}} |
{cb_info, {CallbackModule::atom(), DataTag::atom(),
ClosedTag::atom(), ErrTag::atom(), PassiveTag::atom()}}.
-doc(#{group => <<"Socket">>}).
-doc """
A name or address to a host.
""".
-type host() :: inet:hostname() | inet:ip_address(). % exported
-doc(#{group =>
<<"Socket">>}).
-doc """
Identifies a TLS session prior to TLS-1.3.
""".
-type session_id() :: binary(). % exported
-doc(#{group => <<"Socket">>}).
-doc """
TLS or DTLS protocol version.
""".
-type protocol_version() :: tls_version() | dtls_version(). % exported
-doc(#{group => <<"Socket">>}).
-doc """
TLS protocol version.
""".
-type tls_version() :: 'tlsv1.2' | 'tlsv1.3' | tls_legacy_version().
-doc(#{group => <<"Socket">>}).
-doc """
DTLS protocol version.
""".
-type dtls_version() :: 'dtlsv1.2' | dtls_legacy_version().
-doc(#{group => <<"Socket">>}).
-doc """
A TLS protocol version that are no longer supported by default for security reasons.
""".
-type tls_legacy_version() :: tlsv1 | 'tlsv1.1' .
-doc(#{group => <<"Socket">>}).
-doc """
A DTLS protocol version that are no longer supported by default for security reasons.
""".
-type dtls_legacy_version() :: 'dtlsv1'.
-doc(#{group => <<"Algorithms">>}).
-doc """
Cipher algorithms that can be used for payload encryption.
""".
-type cipher() :: aes_256_gcm
| aes_128_gcm
| aes_256_ccm
| aes_128_ccm
| chacha20_poly1305
| aes_256_ccm_8
| aes_128_ccm_8
| aes_128_cbc
| aes_256_cbc
| legacy_cipher(). % exported
-doc(#{group => <<"Algorithms Legacy">>}).
-doc """
Cipher algorithms that are no longer supported by default for security reasons.
""".
-type legacy_cipher() :: '3des_ede_cbc'
| des_cbc
| rc4_128.
-doc(#{group => <<"Algorithms">>}).
-doc """
Hash algorithms used together with signing and encryption functions.
""".
-type hash() :: sha2()
| legacy_hash(). % exported
-doc(#{group => <<"Algorithms">>}).
-doc """
SHA2 hash algorithms.
""".
-type sha2() :: sha512
| sha384
| sha256.
-doc(#{group => <<"Algorithms Legacy">>}).
-doc """
Hash algorithms that are no longer supported by default for security reasons.
""".
-type legacy_hash() :: sha224
| sha
| md5.
-doc(#{group => <<"Algorithms">>}).
-doc """
Signature algorithms.
""".
-type sign_algo() :: eddsa
| ecdsa
| rsa
| legacy_sign_algo(). % exported
-doc(#{group => <<"Algorithms Legacy">>}).
-doc """
Signature algorithms that are no longer supported by default for security reasons.
""".
-type legacy_sign_algo() :: dsa.
-doc(#{group => <<"Algorithms">>}).
-doc """
Signature schemes, defined by TLS-1.3, and replacing signature algorithms from TLS-1.2.
Explicitly list acceptable signature schemes in the preferred
order.
Overrides the algorithms supplied in
[`signature_algs`](`t:signature_algs/0`) option for certificates.
In addition to the `signature_algorithms` extension from TLS 1.2,
[TLS 1.3 (RFC 5246 Section 4.2.3)](http://www.ietf.org/rfc/rfc8446.txt#section-4.2.3)
adds the `signature_algorithms_cert` extension which enables having special
requirements on the signatures used in the certificates that differs from the
requirements on digital signatures as a whole. If this is not required this
extension is not needed.
The client will send a `signature_algorithms_cert` extension (in the
client hello message), if TLS version 1.2 (back-ported to TLS 1.2 in
24.1) or later is used, and the signature_algs_cert option is
explicitly specified. By default, only the
[signature_algs](`t:signature_algs/0`) extension is sent with the
exception of when signature_algs option is not explicitly specified,
in which case it will append the rsa_pkcs1_sha1 algorithm to the
default value of signature_algs and use it as value for
signature_algs_cert to allow certificates to have this signature but
still disallow sha1 use in the TLS protocol, since 27.0.1 and 26.2.5.2.
> #### Note {: .info }
>
> Note that supported signature schemes for TLS-1.2 are
[`legacy_sign_scheme()`](`t:legacy_sign_scheme/0`)
> and [`rsassa_pss_scheme()`](`t:rsassa_pss_scheme/0`).
""".
-type sign_scheme() :: eddsa_ed25519
| eddsa_ed448
| ecdsa_secp521r1_sha512
| ecdsa_secp384r1_sha384
| ecdsa_secp256r1_sha256
| ecdsa_brainpoolP512r1tls13_sha512
| ecdsa_brainpoolP384r1tls13_sha384
| ecdsa_brainpoolP256r1tls13_sha256
| post_quantum_schemes()
| rsassa_pss_scheme()
| legacy_sign_scheme() . % exported
-doc(#{group => <<"Algorithms">>}).
-doc """
Supported in TLS-1.3 and TLS-1.2.
""".
-type rsassa_pss_scheme() :: rsa_pss_rsae_sha512
| rsa_pss_rsae_sha384
| rsa_pss_rsae_sha256
| rsa_pss_pss_sha512
| rsa_pss_pss_sha384
| rsa_pss_pss_sha256.
-doc(#{group => <<"Algorithms">>}).
-doc """
Supported in TLS-1.3 only. ML-DSA since 28.1, SLH-DSA since 28.3.
""".
-type post_quantum_schemes() :: crypto:mldsa() | crypto:slh_dsa().
-doc(#{group => <<"Algorithms Legacy">>}).
-doc """
This is only used for certificate signatures if TLS-1.2 is negotiated,
meaning that the peer only supports TLS-1.2, but we also support
TLS-1.3.
""".
-type legacy_sign_scheme() :: rsa_pkcs1_sha512
| rsa_pkcs1_sha384
| rsa_pkcs1_sha256
| ecdsa_sha1
| rsa_pkcs1_sha1.
-doc(#{group => <<"Algorithms">>}).
-doc """
Cipher Suite Key Exchange Algorithm will be `any`
in TLS-1.3 as key exchange is no longer part of cipher suite
configuration in TLS-1.3.
""".
-type kex_algo() :: ecdhe_ecdsa
| ecdh_ecdsa
| ecdh_rsa
| rsa
| dhe_rsa
| dhe_dss
| srp_rsa
| srp_dss
| dhe_psk
| rsa_psk
| psk
| ecdh_anon
| dh_anon
| srp_anon
| any. %% TLS 1.3 (any of TLS-1.3 keyexchanges) , exported
-doc(#{group => <<"Algorithms">>}).
-doc """
Erlang cipher suite representation
> #### Warning {: .warning }
Enabling cipher suites using RSA as a key exchange algorithm is
strongly discouraged (only available prior to TLS-1.3). For some
configurations software preventions may exist, and can make them
usable if they work, but relying on them to work is risky. There
exists more reliable cipher suites that can be used instead.
""".
-type erl_cipher_suite() :: #{key_exchange := kex_algo(),
cipher := cipher(),
mac := hash() | aead,
prf := hash() | default_prf %% Old cipher suites, version dependent
}.
-doc(#{group => <<"Algorithms Legacy">>}).
-doc """
For backwards compatibility only; do not use.
""".
-type old_cipher_suite() :: {kex_algo(), cipher(), hash()} % Pre TLS 1.2
%% TLS 1.2, internally PRE TLS 1.2 will use default_prf
| {kex_algo(), cipher(), hash() | aead, hash()}.
-doc(#{group => <<"Algorithms">>}).
-doc """
Key exchange configuration prior to TLS-1.3.
""".
-type named_curve() :: x25519
| x448
| secp521r1
| brainpoolP512r1
| brainpoolP384r1
| secp384r1
| brainpoolP256r1
| secp256r1
| legacy_named_curve(). % exported
-doc(#{group => <<"Algorithms Legacy">>}).
-doc """
Key exchange configuration prior to TLS-1.3.
These curves have been deprecated by RFC 8422.
""".
-type legacy_named_curve() :: sect571r1
| sect571k1
| sect409k1
| sect409r1
| sect283k1
| sect283r1
| secp256k1
| sect239k1
| sect233k1
| sect233r1
| secp224k1
| secp224r1
| sect193r1
| sect193r2
| secp192k1
| secp192r1
| sect163k1
| sect163r1
| sect163r2
| secp160k1
| secp160r1
| secp160r2.
-doc(#{group => <<"Algorithms">>}).
-doc """
TLS-1.3 key exchange configuration.
""".
-type group() :: x25519
| x448
| secp256r1
| secp384r1
| secp521r1
| ffdhe2048
| ffdhe3072
| ffdhe4096
| ffdhe6144
| ffdhe8192. % exported
-doc(#{group => <<"Algorithms">>}).
-doc """
SRP cipher suite configuration prior to TLS-1.3.
""".
-type srp_param_type() :: srp_8192
| srp_6144
| srp_4096
| srp_3072
| srp_2048
| srp_1536
| srp_1024. % exported
-doc(#{group => <<"Socket">>}).
-doc """
If a TLS connection fails a TLS protocol ALERT will be sent/received.
An atom reflecting the raised alert, according to the TLS protocol, and a description string
with some further details will be returned.
""".
-type error_alert() :: {tls_alert, {tls_alert(), Description::string()}}. % exported
-doc(#{group => <<"Socket">>}).
-doc """
TLS Alert Protocol reasons.
""".
-type tls_alert() :: close_notify |
unexpected_message |
bad_record_mac |
record_overflow |
handshake_failure |
bad_certificate |
unsupported_certificate |
certificate_revoked |
certificate_expired |
certificate_unknown |
illegal_parameter |
unknown_ca |
access_denied |
decode_error |
decrypt_error |
export_restriction|
protocol_version |
insufficient_security |
internal_error |
inappropriate_fallback |
user_canceled |
no_renegotiation |
unsupported_extension |
certificate_unobtainable |
unrecognized_name |
bad_certificate_status_response |
bad_certificate_hash_value |
unknown_psk_identity |
no_application_protocol. % exported
-doc(#{group => <<"Socket">>}).
-doc """
Error reason for debug purposes.
Not to be matched.
""".
-type reason() :: term().
%% -------------------------------------------------------------------------------------------------------
-doc(#{group =>
<<"Client and Server Options">>}).
-doc """
Options common to both client and server side.
- **`{protocol, Protocol}`** - Choose TLS or DTLS protocol for the transport layer security.
Defaults to `tls`.
- **`{handshake, Completion}`** - Possibly pause handshake at hello stage.
Defaults to `full`. If `hello` is specified the handshake will pause
after the hello message, allowing the user to make decisions based
on hello extensions before continuing or aborting the handshake by
calling `handshake_continue/3` or `handshake_cancel/1`.
- **`{keep_secrets, KeepSecrets}`** - Configures a TLS connection for keylogging.
In order to be able retrieve all keylog information on a TLS connection, it must be
configured in advance.
> #### Warning {: .warning }
> The keylog information defeats the purpose of the protocol
> and enabling it makes the user responsible for the information
> not ending up compromising security, it is intended for debugging.
The `keep_secrets` functionality is disabled (`false`) by default.
If set to legacy value `true` keylog information can be retrieved from the connection
using connection_information/2.
Added in OTP 23.2.
> #### Note {: .info }
> Note that having to ask the connection has some drawbacks
> as for instance you can not get keylog information for
> failed connections, and other keylog items have
> to be retrieved in a polling manner and are not correctly
> formatted for key_updates.
Since OTP 27.3.1 you may instead of true provide a callback fun
providing keylog information for either just failing handshakes or
for entire connections, by setting `keep_secrets` option to
{keylog_hs, fun()} or {keylog, fun()}. The fun is of arity one and
will be called with keylog information
[`keylog_info()`](`t:keylog_info/0`) as an argument. `keylog_hs fun`
will only be called if the handshake fails, and is only relevant for
`TLS-1.3` that has encrypted messages before the first handshake is
complete.`keylog fun` will be called every time some secrets are
updated and provide keylog for that update that is during the
connection establishment and after that at `renegotiation` or `key
update` (depending on TLS protocol version). When a fun is used the
connection_information/2 can not be used to retrieve key log
information. For more information see [NSS
keylog](using_ssl.md#nss-keylog).
- **`{max_handshake_size, HandshakeSize}`** - Limit the acceptable handshake packet size.
Used to limit the size of valid TLS handshake packets to avoid DoS
attacks.
Integer (24 bits, unsigned). Defaults to `262144` since OTP 29.0
- **`{hibernate_after, HibernateTimeout}`** - Hibernate inactive connection processes.
When an integer-value is specified, the TLS/DTLS connection goes into hibernation
after the specified number of milliseconds of inactivity, thus reducing its
memory footprint. When not specified the process never goes into hibernation.
- **`{log_level, Level}`** - Specifies the log level for a TLS/DTLS connection.
Alerts are logged on `notice`
level, which is the default level. The level `debug` triggers verbose logging of
TLS/DTLS protocol messages. See also [SSL Application](ssl_app.md)
- **`{receiver|sender_spawn_opts, SpawnOpts}`** - Configure erlang spawn opts.
Configures spawn options of TLS sender and receiver processes.
Setting up garbage collection options can be helpful for trade-offs between CPU
usage and memory usage. See `erlang:spawn_opt/2`.
For connections using Erlang distribution, the default sender option
is `[...{priority, max}]`; this priority option cannot be changed. For all
connections, `...link` is added to receiver and cannot be changed.
""".
-type common_option() :: {protocol, tls | dtls} |
{handshake, hello | full} |
{ciphers, cipher_suites()} |
{signature_algs, signature_algs()} |
{signature_algs_cert, [sign_scheme()]} |
{keep_secrets,
KeepSecrets:: boolean() |
{keylog_hs, fun((Info::keylog_info()) -> any())} |
{keylog, fun((Info::keylog_info()) -> any())}} |
{max_handshake_size, HandshakeSize::pos_integer()} |
{versions, [protocol_version()]} |
{log_level, Level::logger:level() | none | all} |
{hibernate_after, HibernateTimeout::timeout()} |
{receiver_spawn_opts, SpawnOpts::[erlang:spawn_opt_option()]} |
{sender_spawn_opts, SpawnOpts::[erlang:spawn_opt_option()]}.
-doc(#{group =>
<<"Client and Server Options">>}).
-doc """
Common certificate related options to both client and server.
- **`{certs_keys, CertsKeys}`** - At least one certificate and key pair.
A list of a certificate (or possible a certificate and its chain)
and the associated key of the certificate that can be used to
authenticate the client or the server. The certificate key pair that
is considered best and matches negotiated parameters for the
connection will be selected.
The different signature algorithms are prioritized in the following
order: `mldsa`, `slhdsa`, `eddsa`, `ecdsa`, `rsa_pss_pss`, `rsa`, and `dsa`. If more
than one key is supplied for the same signature algorithm, they will
be prioritized by strength (except for _engine keys_; see the next
paragraph). This offers flexibility to, for instance, configure a
newer certificate that is expected to be used in most cases, and an
older but acceptable certificate that will only be used to
communicate with legacy systems. Note that there is a trade off
between the induced overhead and the flexibility; thus, alternatives
should be chosen for good reasons.
_Engine keys_ will be favored over other keys. As engine keys cannot
be inspected, supplying more than one engine key makes no sense.
When this option is specified it overrides all single certificate
and key options. For examples, see the [User's Guide](using_ssl.md).
> #### Note {: .info }
>
> `mldsa`, `slhdsa`, `eddsa` certificates are only supported by TLS-1.3 implementations that do not support `dsa`
> certificates. `rsa_pss_pss` (RSA certificates using Probabilistic Signature
> Scheme) are supported in TLS-1.2 and TLS-1.3, but some TLS-1.2 implementations
> do not support `rsa_pss_pss`.
- **`{depth, AllowedCertChainLen}`** - Limits the accepted number of certificates in the certificate chain.
Maximum number of non-self-issued intermediate certificates that can follow the
peer certificate in a valid certification path. So, if depth is 0 the PEER must
be signed by the trusted ROOT-CA directly; if 1 the path can be PEER, CA,
ROOT-CA; if 2 the path can be PEER, CA, CA, ROOT-CA, and so on. The default
value is 10. Used to mitigate DoS attack possibilities.
- **`{verify_fun, Verify}`** - Customize certificate path validation
The verification fun is to be defined as follows:
```erlang
fun(OtpCert :: #'OTPCertificate'{},
Event, InitialUserState :: term()) ->
{valid, UserState :: term()} |
{fail, Reason :: term()} | {unknown, UserState :: term()}.
fun(OtpCert :: #'OTPCertificate'{}, DerCert :: public_key:der_encoded(),
Event, InitialUserState :: term()) ->
{valid, UserState :: term()} |
{fail, Reason :: term()} | {unknown, UserState :: term()}.
Types:
Event = {bad_cert, Reason :: atom() |
{revoked, atom()}} |
{extension, #'Extension'{}} |
valid |
valid_peer
```
The verification fun is called during the X.509-path validation when
an error occurs or an extension unknown to the SSL application is
encountered. It is also called when a certificate is considered
valid by the path validation to allow access to each certificate in
the path to the user application. It differentiates between the peer
certificate and the CA certificates by using `valid_peer` or `valid`
as `Event` argument to the verification fun. See the [Public_Key
User's Guide](`e:public_key:public_key_records.md`) for definition
of `#'OTPCertificate'{}` and `#'Extension'{}`.
- If the verify callback fun returns `{fail, Reason}`, the verification process
is immediately stopped, an alert is sent to the peer, and the TLS/DTLS
handshake terminates.
- If the verify callback fun returns `{valid, UserState}`, the verification
process continues.
- If the verify callback fun always returns `{valid, UserState}`, the TLS/DTLS
handshake does not terminate regardless of verification failures, and the
connection is established.
- If called with an extension unknown to the user application, the fun is to
return `{unknown, UserState}`.
Note that if the fun returns `unknown` for an extension marked as critical,
validation will fail.
Default option `verify_fun` in `verify_peer mode`:
```erlang
{fun(_, _, {bad_cert, _} = Reason, _) ->
{fail, Reason};
(_, _, {extension, _}, UserState) ->
{unknown, UserState};
(_, _, valid, UserState) ->
{valid, UserState};
(_, _, valid_peer, UserState) ->
{valid, UserState}
end, []}
```
Default option `verify_fun` in mode `verify_none`:
```erlang
{fun(_, _, {bad_cert, _}, UserState) ->
{valid, UserState};
(_, _, {extension, #'Extension'{critical = true}}, UserState) ->
{valid, UserState};
(_, _, {extension, _}, UserState) ->
{unknown, UserState};
(_, _, valid, UserState) ->
{valid, UserState};
(_, _, valid_peer, UserState) ->
{valid, UserState}
end, []}
```
The possible path validation errors are given in the form `{bad_cert, Reason}`,
where `Reason` is:
- **`unknown_ca`**
No trusted CA was found in the trusted store. The trusted
CA is normally a so-called ROOT CA, which is a self-signed certificate. Trust
can be claimed for an intermediate CA (the trusted anchor does not have to be
self-signed according to X-509) by using option `partial_chain`.
- **`selfsigned_peer`**
The chain consisted only of one self-signed certificate.
- **{invalid_ext_keyusage, [public_key:oid()]} **
If the peer certificate specifies the extended keyusage extension and does
not include the purpose for either being a TLS server (id-kp-ServerAuth) or
TLS client (id-kp-ClientAuth) depending on the peers role.
- **{ca_invalid_ext_keyusage, [public_key:oid()]} **
If a CA certificate specifies the extended keyusage extension and does
not include the purpose for either being a TLS server
(id-kp-ServerAuth) or TLS client (id-kp-ClientAuth) depending
on the role of the peer chained with this CA, or the option allow_any_ca_purpose is set to `true`
but the special any-value (anyExtendedKeyUsage) is not included in the CA cert purposes.
- **`PKIX X-509-path validation error`**
For possible reasons, see `public_key:pkix_path_validation/3`.
- **`{cert_policy_opts, PolicyOpts}`** - Handle certificate policies.
Configure X.509 certificate policy handling for the certificate path validation process;
see [public_key:pkix_path_validation/3](`public_key:pkix_path_validation/3`) for
more details.
- **`{allow_any_ca_purpose, boolean()}`** - Handle certificate extended key usages extension
If a CA certificate has an extended key usage extension but it does not want to
restrict the usages of the key it can include a special `anyExtendedKeyUsage` purpose.
If this is option is set to `true` all key usage purposes is automatically
accepted for a CA that include that purpose, the options default to false.
- **`{crl_check, Check}`** - Handle certificate revocation lists.
Perform CRL (Certificate Revocation List) verification
[(public_key:pkix_crls_validate/3)](`public_key:pkix_crls_validate/3`) on all
the certificates during the path validation
[(public_key:pkix_path_validation/3) ](`public_key:pkix_path_validation/3`)of
the certificate chain. `Check` defaults to `false`.
The meaning of `Check` is as follows:
- **`false`**
No checks are performed.
- **`peer`**
Check is only performed on the peer certificate.
- **`best_effort`**
If certificate revocation status cannot be determined it will be accepted as valid.
The CA certificates specified for the connection will be used to construct the
certificate chain validating the CRLs.
The CRLs will be fetched from a local or external cache. See
`m:ssl_crl_cache_api`.
""".
-type common_option_cert() :: {certs_keys, CertsKeys::[cert_key_conf()]} |
{depth, AllowedCertChainLen::pos_integer()} |
{verify_fun, Verify::{Verifyfun :: fun(), InitialUserState :: any()}} |
{cert_policy_opts, PolicyOpts::[{policy_set, [public_key:oid()]} |
{explicit_policy, boolean()} |
{inhibit_policy_mapping, boolean()} |
{inhibit_any_policy, boolean()}]} |
{allow_any_ca_purpose, Allow::boolean()} |
{crl_check, Check::boolean() | peer | best_effort} |
{crl_cache, crl_cache_opts()} |
{partial_chain, anchor_fun()}.
-doc(#{group =>
<<"Client and Server Options">>}).
-doc """
Options common to client and server side prior to TLS-1.3.
- **`{eccs, NamedCurves}`** - Named Elliptic Curves
Elliptic curves that can be used in pre TLS-1.3 key exchange.
- **`{secure_renegotiate, SecureRenegotiate}`** - Inter-operate trade-off option
Specifies whether to reject renegotiation attempt that does not live
up to [RFC 5746](http://www.ietf.org/rfc/rfc5746.txt). By default,
`SecureRenegotiate` is `true`, meaning that secure renegotiation is
enforced. If `SecureRenegotiate` is `false` secure renegotiation
will still be used if possible, but it falls back to insecure
renegotiation if the peer does not support if [RFC
5746](http://www.ietf.org/rfc/rfc5746.txt).
- **`{user_lookup_fun, {LookupFun, UserState}}`** - PSK/SRP cipher suite option
The lookup fun is to be defined as follows:
```erlang
fun(psk, PSKIdentity :: binary(), UserState :: term()) ->
{ok, SharedSecret :: binary()} | error;
fun(srp, Username :: binary(), UserState :: term()) ->
{ok, {SRPParams :: srp_param_type(), Salt :: binary(),
DerivedKey :: binary()}} | error.
```
For Pre-Shared Key (PSK) cipher suites, the lookup fun is called by the client
and server to determine the shared secret. When called by the client,
`PSKIdentity` is the hint presented by the server or `undefined`. When
called by the server, `PSKIdentity` is the identity presented by the client.
For Secure Remote Password (SRP), the fun is only used by the server to obtain
parameters that it uses to generate its session keys. `DerivedKey` is to be
derived according to [RFC 2945](http://tools.ietf.org/html/rfc2945#section/3)
and [RFC 5054](http://tools.ietf.org/html/rfc5054#section-2.4):
`crypto:sha([Salt, crypto:sha([Username, <<$:>>, Password])])`
""".
-type common_option_pre_tls13() :: {eccs, NamedCurves::[named_curve()]} |
{secure_renegotiate, SecureRenegotiate::boolean()} |
{user_lookup_fun, {Lookupfun :: fun(), UserState :: any()}}.
-doc(#{group =>
<<"Client and Server Options">>}).
-doc """
Common options to both client and server for TLS-1.3.
- **`{supported_groups, Groups}`** - Key exchange option