1%
2%% %CopyrightBegin%
3%%
4%% Copyright Ericsson AB 2007-2019. All Rights Reserved.
5%%
6%% Licensed under the Apache License, Version 2.0 (the "License");
7%% you may not use this file except in compliance with the License.
8%% You may obtain a copy of the License at
9%%
10%%     http://www.apache.org/licenses/LICENSE-2.0
11%%
12%% Unless required by applicable law or agreed to in writing, software
13%% distributed under the License is distributed on an "AS IS" BASIS,
14%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15%% See the License for the specific language governing permissions and
16%% limitations under the License.
17%%
18%% %CopyrightEnd%
19%%
20
21%%
22%%----------------------------------------------------------------------
23%% Purpose: Help functions for handling the SSL ciphers
24%%
25%%----------------------------------------------------------------------
26
27-module(ssl_cipher).
28
29-include("ssl_internal.hrl").
30-include("ssl_record.hrl").
31-include("ssl_cipher.hrl").
32-include("ssl_handshake.hrl").
33-include("ssl_alert.hrl").
34-include("tls_handshake_1_3.hrl").
35-include_lib("public_key/include/public_key.hrl").
36
37-export([security_parameters/2,
38         security_parameters/3,
39         security_parameters_1_3/2,
40	 cipher_init/3,
41         nonce_seed/2,
42         decipher/6,
43         cipher/5,
44         aead_encrypt/6,
45         aead_decrypt/6,
46	 suites/1,
47         all_suites/1,
48         crypto_support_filters/0,
49	 anonymous_suites/1,
50         filter/3,
51         filter_suites/1,
52         filter_suites/2,
53	 hash_algorithm/1,
54         sign_algorithm/1,
55         is_acceptable_hash/2,
56         is_fallback/1,
57	 random_bytes/1,
58         calc_mac_hash/4,
59         calc_mac_hash/6,
60         is_stream_ciphersuite/1,
61         is_supported_sign/2,
62         signature_scheme/1,
63         signature_schemes_1_2/1,
64         scheme_to_components/1,
65         hash_size/1,
66         effective_key_bits/1,
67         key_material/1,
68         signature_algorithm_to_scheme/1,
69         bulk_cipher_algorithm/1]).
70
71%% RFC 8446 TLS 1.3
72-export([generate_client_shares/1,
73         generate_server_share/1,
74         add_zero_padding/2,
75         encrypt_ticket/3,
76         decrypt_ticket/3,
77         encrypt_data/4,
78         decrypt_data/4]).
79
80-compile(inline).
81
82-type cipher_enum()        :: integer().
83
84-export_type([cipher_enum/0]).
85
86%%--------------------------------------------------------------------
87-spec security_parameters(ssl_cipher_format:cipher_suite(), #security_parameters{}) ->
88				 #security_parameters{}.
89%% Only security_parameters/2 should call security_parameters/3 with undefined as
90%% first argument.
91%%--------------------------------------------------------------------
92
93security_parameters(?TLS_NULL_WITH_NULL_NULL = CipherSuite, SecParams) ->
94    security_parameters(undefined, CipherSuite, SecParams).
95
96%%--------------------------------------------------------------------
97-spec security_parameters(ssl_record:ssl_version() | undefined,
98                          ssl_cipher_format:cipher_suite(), #security_parameters{}) ->
99				 #security_parameters{}.
100%%
101%% Description: Returns a security parameters record where the
102%% cipher values has been updated according to <CipherSuite>
103%%-------------------------------------------------------------------
104security_parameters(Version, CipherSuite, SecParams) ->
105    #{cipher := Cipher, mac := Hash,
106      prf := PrfHashAlg} = ssl_cipher_format:suite_bin_to_map(CipherSuite),
107    SecParams#security_parameters{
108      cipher_suite = CipherSuite,
109      bulk_cipher_algorithm = bulk_cipher_algorithm(Cipher),
110      cipher_type = type(Cipher),
111      key_size = effective_key_bits(Cipher),
112      expanded_key_material_length = expanded_key_material(Cipher),
113      key_material_length = key_material(Cipher),
114      iv_size = iv_size(Cipher),
115      mac_algorithm = mac_algorithm(Hash),
116      prf_algorithm = prf_algorithm(PrfHashAlg, Version),
117      hash_size = hash_size(Hash)}.
118
119security_parameters_1_3(SecParams, CipherSuite) ->
120     #{cipher := Cipher, prf := PrfHashAlg} =
121        ssl_cipher_format:suite_bin_to_map(CipherSuite),
122    SecParams#security_parameters{
123      cipher_suite = CipherSuite,
124      bulk_cipher_algorithm = bulk_cipher_algorithm(Cipher),
125      prf_algorithm = PrfHashAlg,  %% HKDF hash algorithm
126      cipher_type = ?AEAD}.
127
128%%--------------------------------------------------------------------
129-spec cipher_init(cipher_enum(), binary(), binary()) -> #cipher_state{}.
130%%
131%% Description: Initializes the #cipher_state according to BCA
132%%-------------------------------------------------------------------
133cipher_init(?RC4, IV, Key) ->
134    State = {stream_init,rc4,Key,IV},
135    #cipher_state{iv = IV, key = Key, state = State};
136cipher_init(Type, IV, Key) when Type == ?AES_GCM;
137                                Type == ?AES_CCM ->
138    <<Nonce:64>> = random_bytes(8),
139    #cipher_state{iv = IV, key = Key, nonce = Nonce, tag_len = 16};
140cipher_init(?AES_CCM_8, IV, Key) ->
141    <<Nonce:64>> = random_bytes(8),
142    #cipher_state{iv = IV, key = Key, nonce = Nonce, tag_len = 8};
143cipher_init(?CHACHA20_POLY1305, IV, Key) ->
144    #cipher_state{iv = IV, key = Key, tag_len = 16};
145cipher_init(_BCA, IV, Key) ->
146    %% Initialize random IV cache, not used for aead ciphers
147    #cipher_state{iv = IV, key = Key, state = <<>>}.
148
149nonce_seed(Seed, CipherState) ->
150    CipherState#cipher_state{nonce = Seed}.
151
152%%--------------------------------------------------------------------
153-spec cipher(cipher_enum(), #cipher_state{}, binary(), iodata(), ssl_record:ssl_version()) ->
154		    {binary(), #cipher_state{}}.
155%%
156%% Description: Encrypts the data and the MAC using cipher described
157%% by cipher_enum() and updating the cipher state
158%% Used for "MAC then Cipher" suites where first an HMAC of the
159%% data is calculated and the data plus the HMAC is encrypted.
160%%-------------------------------------------------------------------
161cipher(?NULL, CipherState, <<>>, Fragment, _Version) ->
162    {iolist_to_binary(Fragment), CipherState};
163cipher(CipherEnum, CipherState = #cipher_state{state = {stream_init,rc4,Key,_IV}}, Mac, Fragment, Version) ->
164    State = crypto:crypto_init(rc4, Key, true),
165    cipher(CipherEnum,  CipherState#cipher_state{state = State}, Mac, Fragment, Version);
166cipher(?RC4, CipherState = #cipher_state{state = State}, Mac, Fragment, _Version) ->
167    GenStreamCipherList = [Fragment, Mac],
168    T = crypto:crypto_update(State, GenStreamCipherList),
169    {iolist_to_binary(T), CipherState};
170cipher(?DES, CipherState, Mac, Fragment, Version) ->
171    block_cipher(fun(Key, IV, T) ->
172			 crypto:crypto_one_time(des_cbc, Key, IV, T, true)
173		 end, block_size(des_cbc), CipherState, Mac, Fragment, Version);
174cipher(?'3DES', CipherState, Mac, Fragment, Version) ->
175    block_cipher(fun(Key, IV, T) ->
176			 crypto:crypto_one_time(des_ede3_cbc, Key, IV, T, true)
177		 end, block_size(des_ede3_cbc), CipherState, Mac, Fragment, Version);
178cipher(?AES_CBC, CipherState, Mac, Fragment, Version) ->
179    block_cipher(fun(Key, IV, T) when byte_size(Key) =:= 16 ->
180			 crypto:crypto_one_time(aes_128_cbc, Key, IV, T, true);
181		    (Key, IV, T) when byte_size(Key) =:= 32 ->
182			 crypto:crypto_one_time(aes_256_cbc, Key, IV, T, true)
183		 end, block_size(aes_128_cbc), CipherState, Mac, Fragment, Version).
184
185aead_encrypt(Type, Key, Nonce, Fragment, AdditionalData, TagLen) ->
186    crypto:crypto_one_time_aead(aead_type(Type,size(Key)), Key, Nonce, Fragment, AdditionalData, TagLen, true).
187
188aead_decrypt(Type, Key, Nonce, CipherText, CipherTag, AdditionalData) ->
189    crypto:crypto_one_time_aead(aead_type(Type,size(Key)), Key, Nonce, CipherText, AdditionalData, CipherTag, false).
190
191aead_type(?AES_GCM, 16) ->
192    aes_128_gcm;
193aead_type(?AES_GCM, 24) ->
194    aes_192_gcm;
195aead_type(?AES_GCM, 32) ->
196    aes_256_gcm;
197aead_type(?AES_CCM, 16) ->
198    aes_128_ccm;
199aead_type(?AES_CCM, 24) ->
200    aes_192_ccm;
201aead_type(?AES_CCM, 32) ->
202    aes_256_ccm;
203aead_type(?AES_CCM_8, 16) ->
204    aes_128_ccm;
205aead_type(?AES_CCM_8, 24) ->
206    aes_192_ccm;
207aead_type(?AES_CCM_8, 32) ->
208    aes_256_ccm;
209aead_type(?CHACHA20_POLY1305, _) ->
210    chacha20_poly1305.
211
212build_cipher_block(BlockSz, Mac, Fragment) ->
213    TotSz = byte_size(Mac) + erlang:iolist_size(Fragment) + 1,
214    [Fragment, Mac, padding_with_len(TotSz, BlockSz)].
215
216block_cipher(Fun, BlockSz, #cipher_state{key=Key, iv=IV} = CS0,
217	     Mac, Fragment, {3, N})
218  when N == 0; N == 1 ->
219    L = build_cipher_block(BlockSz, Mac, Fragment),
220    T = Fun(Key, IV, L),
221    NextIV = next_iv(T, IV),
222    {T, CS0#cipher_state{iv=NextIV}};
223
224block_cipher(Fun, BlockSz, #cipher_state{key=Key, iv=IV, state = IV_Cache0} = CS0,
225	     Mac, Fragment, {3, N})
226  when N == 2; N == 3; N == 4 ->
227    IV_Size = byte_size(IV),
228    <<NextIV:IV_Size/binary, IV_Cache/binary>> =
229        case IV_Cache0 of
230            <<>> ->
231                random_bytes(IV_Size bsl 5); % 32 IVs
232            _ ->
233                IV_Cache0
234        end,
235    L0 = build_cipher_block(BlockSz, Mac, Fragment),
236    L = [NextIV|L0],
237    T = Fun(Key, IV, L),
238    {T, CS0#cipher_state{iv=NextIV, state = IV_Cache}}.
239
240%%--------------------------------------------------------------------
241-spec decipher(cipher_enum(), integer(), #cipher_state{}, binary(),
242	       ssl_record:ssl_version(), boolean()) ->
243		      {binary(), binary(), #cipher_state{}} | #alert{}.
244%%
245%% Description: Decrypts the data and the MAC using cipher described
246%% by cipher_enum() and updating the cipher state.
247%% Used for "MAC then Cipher" suites where first the data is decrypted
248%% and the an HMAC of the decrypted data is checked
249%%-------------------------------------------------------------------
250decipher(?NULL, _HashSz, CipherState, Fragment, _, _) ->
251    {Fragment, <<>>, CipherState};
252decipher(CipherEnum, HashSz, CipherState = #cipher_state{state = {stream_init,rc4,Key,_IV}},
253         Fragment, Version, PaddingCheck) ->
254    State = crypto:crypto_init(rc4, Key, false),
255    decipher(CipherEnum, HashSz, CipherState#cipher_state{state = State}, Fragment, Version, PaddingCheck);
256decipher(?RC4, HashSz, CipherState = #cipher_state{state = State}, Fragment, _, _) ->
257    try crypto:crypto_update(State, Fragment) of
258	Text ->
259	    GSC = generic_stream_cipher_from_bin(Text, HashSz),
260	    #generic_stream_cipher{content = Content, mac = Mac} = GSC,
261	    {Content, Mac, CipherState}
262    catch
263	_:_ ->
264	    %% This is a DECRYPTION_FAILED but
265	    %% "differentiating between bad_record_mac and decryption_failed
266	    %% alerts may permit certain attacks against CBC mode as used in
267	    %% TLS [CBCATT].  It is preferable to uniformly use the
268	    %% bad_record_mac alert to hide the specific type of the error."
269            ?ALERT_REC(?FATAL, ?BAD_RECORD_MAC, decryption_failed)
270    end;
271
272decipher(?DES, HashSz, CipherState, Fragment, Version, PaddingCheck) ->
273    block_decipher(fun(Key, IV, T) ->
274                           crypto:crypto_one_time(des_cbc, Key, IV, T, false)
275		   end, CipherState, HashSz, Fragment, Version, PaddingCheck);
276decipher(?'3DES', HashSz, CipherState, Fragment, Version, PaddingCheck) ->
277    block_decipher(fun(Key, IV, T) ->
278                           crypto:crypto_one_time(des_ede3_cbc, Key, IV, T, false)
279		   end, CipherState, HashSz, Fragment, Version, PaddingCheck);
280decipher(?AES_CBC, HashSz, CipherState, Fragment, Version, PaddingCheck) ->
281    block_decipher(fun(Key, IV, T) when byte_size(Key) =:= 16 ->
282                           crypto:crypto_one_time(aes_128_cbc, Key, IV, T, false);
283		      (Key, IV, T) when byte_size(Key) =:= 32 ->
284                           crypto:crypto_one_time(aes_256_cbc, Key, IV, T, false)
285		   end, CipherState, HashSz, Fragment, Version, PaddingCheck).
286
287block_decipher(Fun, #cipher_state{key=Key, iv=IV} = CipherState0,
288	       HashSz, Fragment, Version, PaddingCheck) ->
289    try
290	Text = Fun(Key, IV, Fragment),
291	NextIV = next_iv(Fragment, IV),
292	GBC = generic_block_cipher_from_bin(Version, Text, NextIV, HashSz),
293	Content = GBC#generic_block_cipher.content,
294	Mac = GBC#generic_block_cipher.mac,
295	CipherState1 = CipherState0#cipher_state{iv=GBC#generic_block_cipher.next_iv},
296	case is_correct_padding(GBC, Version, PaddingCheck) of
297	    true ->
298		{Content, Mac, CipherState1};
299	    false ->
300		%% decryption failed or invalid padding,
301		%% intentionally break Content to make
302		%% sure a packet with invalid padding
303		%% but otherwise correct data will fail
304		%% the MAC test later
305		{<<16#F0, Content/binary>>, Mac, CipherState1}
306	end
307    catch
308	_:_ ->
309	    %% This is a DECRYPTION_FAILED but
310	    %% "differentiating between bad_record_mac and decryption_failed
311	    %% alerts may permit certain attacks against CBC mode as used in
312	    %% TLS [CBCATT].  It is preferable to uniformly use the
313	    %% bad_record_mac alert to hide the specific type of the error."
314            ?ALERT_REC(?FATAL, ?BAD_RECORD_MAC, decryption_failed)
315    end.
316
317%%--------------------------------------------------------------------
318-spec suites(ssl_record:ssl_version()) -> [ssl_cipher_format:cipher_suite()].
319%%
320%% Description: Returns a list of supported cipher suites.
321%%--------------------------------------------------------------------
322suites({3, Minor}) ->
323    tls_v1:suites(Minor);
324suites({_, Minor}) ->
325    dtls_v1:suites(Minor).
326all_suites({3, 4} = Version) ->
327    suites(Version)
328	++ tls_v1:psk_suites({3,3})
329	++ tls_v1:srp_suites({3,3})
330        ++ tls_v1:rsa_suites({3,3})
331        ++ tls_v1:des_suites({3,3})
332        ++ tls_v1:rc4_suites({3,3});
333all_suites({3, _} = Version) ->
334    suites(Version)
335	++ tls_v1:psk_suites(Version)
336	++ tls_v1:srp_suites(Version)
337        ++ tls_v1:rsa_suites(Version)
338        ++ tls_v1:des_suites(Version)
339        ++ tls_v1:rc4_suites(Version);
340all_suites(Version) ->
341    dtls_v1:all_suites(Version).
342
343%%--------------------------------------------------------------------
344-spec anonymous_suites(ssl_record:ssl_version() | integer()) ->
345                              [ssl_cipher_format:cipher_suite()].
346%%
347%% Description: Returns a list of the anonymous cipher suites, only supported
348%% if explicitly set by user. Intended only for testing.
349%%--------------------------------------------------------------------
350anonymous_suites({3, N}) ->
351    anonymous_suites(N);
352anonymous_suites({254, _} = Version) ->
353    dtls_v1:anonymous_suites(Version);
354
355anonymous_suites(1 = N) ->
356    tls_v1:exclusive_anonymous_suites(N);
357anonymous_suites(4 = N) ->
358    tls_v1:exclusive_anonymous_suites(N);
359anonymous_suites(N) when N > 1->
360    tls_v1:exclusive_anonymous_suites(N) ++ anonymous_suites(N-1).
361
362%%--------------------------------------------------------------------
363-spec filter(undefined | binary(), [ssl_cipher_format:cipher_suite()],
364             ssl_record:ssl_version()) -> [ssl_cipher_format:cipher_suite()].
365%%
366%% Description: Select the cipher suites that can be used together with the
367%% supplied certificate. (Server side functionality)
368%%-------------------------------------------------------------------
369filter(undefined, Ciphers, _) ->
370    Ciphers;
371filter(DerCert, Ciphers0, Version) ->
372    OtpCert = public_key:pkix_decode_cert(DerCert, otp),
373    SigAlg = OtpCert#'OTPCertificate'.signatureAlgorithm,
374    PubKeyInfo = OtpCert#'OTPCertificate'.tbsCertificate#'OTPTBSCertificate'.subjectPublicKeyInfo,
375    PubKeyAlg = PubKeyInfo#'OTPSubjectPublicKeyInfo'.algorithm,
376    Type =  case ssl_certificate:public_key_type(PubKeyAlg#'PublicKeyAlgorithm'.algorithm) of
377                rsa_pss_pss ->
378                    rsa;
379                Other ->
380                    Other
381            end,
382    Ciphers = filter_suites_pubkey(Type, Ciphers0, Version, OtpCert),
383    SigAlgo = SigAlg#'SignatureAlgorithm'.algorithm,
384    Sign = ssl_certificate:public_key_type(SigAlgo),
385    filter_suites_signature(Sign, Ciphers, Version).
386
387%%--------------------------------------------------------------------
388-spec filter_suites([ssl:erl_cipher_suite()] | [ssl_cipher_format:cipher_suite()], map()) ->
389                           [ssl:erl_cipher_suite()] |  [ssl_cipher_format:cipher_suite()].
390%%
391%% Description: Filter suites using supplied filter funs
392%%-------------------------------------------------------------------
393filter_suites(Suites, Filters) ->
394    ApplyFilters = fun(Suite) ->
395                           filter_suite(Suite, Filters)
396                   end,
397    lists:filter(ApplyFilters, Suites).
398
399filter_suite(#{key_exchange := KeyExchange,
400               cipher := Cipher,
401               mac := Hash,
402               prf := Prf},
403             #{key_exchange_filters := KeyFilters,
404               cipher_filters := CipherFilters,
405               mac_filters := HashFilters,
406               prf_filters := PrfFilters}) ->
407    all_filters(KeyExchange, KeyFilters) andalso
408        all_filters(Cipher, CipherFilters) andalso
409        all_filters(Hash, HashFilters) andalso
410        all_filters(Prf, PrfFilters);
411filter_suite(Suite, Filters) ->
412    filter_suite(ssl_cipher_format:suite_bin_to_map(Suite), Filters).
413
414%%--------------------------------------------------------------------
415-spec filter_suites([ssl:erl_cipher_suite()] | [ssl_cipher_format:cipher_suite()]) ->
416                           [ssl:erl_cipher_suite()] | [ssl_cipher_format:cipher_suite()].
417%%
418%% Description: Filter suites for algorithms supported by crypto.
419%%-------------------------------------------------------------------
420filter_suites(Suites) ->
421    Filters = crypto_support_filters(),
422    filter_suites(Suites, Filters).
423
424all_filters(_, []) ->
425    true;
426all_filters(Value, [Filter| Rest]) ->
427    case Filter(Value) of
428        true ->
429            all_filters(Value, Rest);
430        false ->
431            false
432    end.
433crypto_support_filters() ->
434    Algos = crypto:supports(),
435    Hashs =  proplists:get_value(hashs, Algos),
436    #{key_exchange_filters =>
437          [fun(KeyExchange) ->
438                  is_acceptable_keyexchange(KeyExchange,
439                                            proplists:get_value(public_keys, Algos))
440           end],
441      cipher_filters =>
442          [fun(Cipher) ->
443                  is_acceptable_cipher(Cipher,
444                                       proplists:get_value(ciphers, Algos))
445           end],
446      mac_filters =>
447          [fun(Hash) ->
448                  is_acceptable_hash(Hash, Hashs)
449          end],
450      prf_filters =>
451          [fun(Prf) ->
452                  is_acceptable_prf(Prf,
453                                    proplists:get_value(hashs, Algos))
454          end]}.
455
456is_acceptable_keyexchange(KeyExchange, _Algos) when KeyExchange == psk;
457                                                    KeyExchange == null;
458                                                    KeyExchange == any ->
459    true;
460is_acceptable_keyexchange(KeyExchange, Algos) when KeyExchange == dh_anon;
461                                                   KeyExchange == dhe_psk ->
462    proplists:get_bool(dh, Algos);
463is_acceptable_keyexchange(dhe_dss, Algos) ->
464    proplists:get_bool(dh, Algos) andalso
465        proplists:get_bool(dss, Algos);
466is_acceptable_keyexchange(dhe_rsa, Algos) ->
467    proplists:get_bool(dh, Algos) andalso
468        proplists:get_bool(rsa, Algos);
469is_acceptable_keyexchange(KeyExchange, Algos) when KeyExchange == ecdh_anon;
470                                                   KeyExchange == ecdhe_psk ->
471    proplists:get_bool(ecdh, Algos);
472is_acceptable_keyexchange(KeyExchange, Algos) when KeyExchange == ecdh_ecdsa;
473                                                   KeyExchange == ecdhe_ecdsa ->
474    proplists:get_bool(ecdh, Algos) andalso
475        proplists:get_bool(ecdsa, Algos);
476is_acceptable_keyexchange(KeyExchange, Algos) when KeyExchange == ecdh_rsa;
477                                                   KeyExchange == ecdhe_rsa ->
478    proplists:get_bool(ecdh, Algos) andalso
479        proplists:get_bool(rsa, Algos);
480is_acceptable_keyexchange(KeyExchange, Algos) when KeyExchange == rsa;
481                                                   KeyExchange == rsa_psk ->
482    proplists:get_bool(rsa, Algos);
483is_acceptable_keyexchange(srp_anon, Algos) ->
484    proplists:get_bool(srp, Algos);
485is_acceptable_keyexchange(srp_dss, Algos) ->
486    proplists:get_bool(srp, Algos) andalso
487        proplists:get_bool(dss, Algos);
488is_acceptable_keyexchange(srp_rsa, Algos) ->
489    proplists:get_bool(srp, Algos) andalso
490        proplists:get_bool(rsa, Algos);
491is_acceptable_keyexchange(_KeyExchange, _Algos) ->
492    false.
493
494is_acceptable_cipher(null, _Algos) ->
495    true;
496is_acceptable_cipher(rc4_128, Algos) ->
497    proplists:get_bool(rc4, Algos);
498is_acceptable_cipher('3des_ede_cbc', Algos) ->
499    proplists:get_bool(des_ede3_cbc, Algos);
500is_acceptable_cipher(aes_128_ccm_8, Algos) ->
501    proplists:get_bool(aes_128_ccm, Algos);
502is_acceptable_cipher(aes_256_ccm_8, Algos) ->
503    proplists:get_bool(aes_256_ccm, Algos);
504is_acceptable_cipher(Cipher, Algos) ->
505    proplists:get_bool(Cipher, Algos).
506
507is_acceptable_hash(null, _Algos) ->
508    true;
509is_acceptable_hash(aead, _Algos) ->
510    true;
511is_acceptable_hash(Hash, Algos) ->
512    proplists:get_bool(Hash, Algos).
513
514is_acceptable_prf(default_prf, _) ->
515    true;
516is_acceptable_prf(Prf, Algos) ->
517    proplists:get_bool(Prf, Algos).
518
519is_fallback(CipherSuites)->
520    lists:member(?TLS_FALLBACK_SCSV, CipherSuites).
521
522
523%%--------------------------------------------------------------------
524-spec random_bytes(integer()) -> binary().
525
526%%
527%% Description: Generates cryptographically secure random sequence
528%%--------------------------------------------------------------------
529random_bytes(N) ->
530    crypto:strong_rand_bytes(N).
531
532calc_mac_hash(Type, Version,
533	      PlainFragment, #{sequence_number := SeqNo,
534			       mac_secret := MacSecret,
535			       security_parameters :=
536				   #security_parameters{mac_algorithm = MacAlgorithm}}) ->
537    calc_mac_hash(Type, Version, PlainFragment, MacAlgorithm, MacSecret, SeqNo).
538%%
539calc_mac_hash(Type, Version, PlainFragment, MacAlgorithm, MacSecret, SeqNo) ->
540    Length = erlang:iolist_size(PlainFragment),
541    mac_hash(Version, MacAlgorithm, MacSecret, SeqNo, Type, Length, PlainFragment).
542
543is_stream_ciphersuite(#{cipher := rc4_128}) ->
544    true;
545is_stream_ciphersuite(_) ->
546    false.
547
548-spec  hash_size(atom()) -> integer().
549hash_size(null) ->
550    0;
551%% The AEAD MAC hash size is not used in the context
552%% of calculating the master secret. See RFC 5246 Section 6.2.3.3.
553hash_size(aead) ->
554    0;
555hash_size(md5) ->
556    16;
557hash_size(sha) ->
558    20;
559%% Uncomment when adding cipher suite that needs it
560%hash_size(sha224) ->
561%    28;
562hash_size(sha256) ->
563    32;
564hash_size(sha384) ->
565    48;
566hash_size(sha512) ->
567    64.
568
569is_supported_sign({Hash, rsa} = SignAlgo, HashSigns) -> %% PRE TLS-1.3
570    lists:member(SignAlgo, HashSigns) orelse
571        lists:member({Hash, rsa_pss_rsae}, HashSigns);
572is_supported_sign(rsa_pkcs1_sha256 = SignAlgo, HashSigns) -> %% TLS-1.3 leagcy
573    lists:member(SignAlgo, HashSigns) orelse
574        lists:member(rsa_pss_rsae_sha256, HashSigns);
575is_supported_sign(rsa_pkcs1_sha384 = SignAlgo, HashSigns) -> %% TLS-1.3 leagcy
576    lists:member(SignAlgo, HashSigns) orelse
577        lists:member(rsa_pss_rsae_sha384, HashSigns);
578is_supported_sign(rsa_pkcs1_sha512 = SignAlgo, HashSigns) -> %% TLS-1.3 leagcy
579    lists:member(SignAlgo, HashSigns) orelse
580        lists:member(rsa_pss_rsae_sha512, HashSigns);
581is_supported_sign(SignAlgo, HashSigns) -> %% PRE TLS-1.3 SignAlgo::tuple() TLS-1.3 SignAlgo::atom()
582    lists:member(SignAlgo, HashSigns).
583
584signature_scheme(rsa_pkcs1_sha256) -> ?RSA_PKCS1_SHA256;
585signature_scheme(rsa_pkcs1_sha384) -> ?RSA_PKCS1_SHA384;
586signature_scheme(rsa_pkcs1_sha512) -> ?RSA_PKCS1_SHA512;
587signature_scheme(ecdsa_secp256r1_sha256) -> ?ECDSA_SECP256R1_SHA256;
588signature_scheme(ecdsa_secp384r1_sha384) -> ?ECDSA_SECP384R1_SHA384;
589signature_scheme(ecdsa_secp521r1_sha512) -> ?ECDSA_SECP521R1_SHA512;
590signature_scheme(rsa_pss_rsae_sha256) -> ?RSA_PSS_RSAE_SHA256;
591signature_scheme(rsa_pss_rsae_sha384) -> ?RSA_PSS_RSAE_SHA384;
592signature_scheme(rsa_pss_rsae_sha512) -> ?RSA_PSS_RSAE_SHA512;
593signature_scheme(eddsa_ed25519) -> ?ED25519;
594signature_scheme(eddsa_ed448) -> ?ED448;
595signature_scheme(rsa_pss_pss_sha256) -> ?RSA_PSS_PSS_SHA256;
596signature_scheme(rsa_pss_pss_sha384) -> ?RSA_PSS_PSS_SHA384;
597signature_scheme(rsa_pss_pss_sha512) -> ?RSA_PSS_PSS_SHA512;
598signature_scheme(rsa_pkcs1_sha1) -> ?RSA_PKCS1_SHA1;
599signature_scheme(ecdsa_sha1) -> ?ECDSA_SHA1;
600%% New algorithms on legacy format
601signature_scheme({sha512, rsa_pss_pss}) ->
602    ?RSA_PSS_PSS_SHA512;
603signature_scheme({sha384, rsa_pss_pss}) ->
604    ?RSA_PSS_PSS_SHA384;
605signature_scheme({sha256, rsa_pss_pss}) ->
606    ?RSA_PSS_PSS_SHA256;
607signature_scheme({sha512, rsa_pss_rsae}) ->
608    ?RSA_PSS_RSAE_SHA512;
609signature_scheme({sha384, rsa_pss_rsae}) ->
610    ?RSA_PSS_RSAE_SHA384;
611signature_scheme({sha256, rsa_pss_rsae}) ->
612    ?RSA_PSS_RSAE_SHA256;
613%% Handling legacy signature algorithms
614signature_scheme({Hash0, Sign0}) ->
615    Hash = hash_algorithm(Hash0),
616    Sign = sign_algorithm(Sign0),
617    <<?UINT16(SigAlg)>> = <<?BYTE(Hash),?BYTE(Sign)>>,
618    SigAlg;
619signature_scheme(?RSA_PKCS1_SHA256) -> rsa_pkcs1_sha256;
620signature_scheme(?RSA_PKCS1_SHA384) -> rsa_pkcs1_sha384;
621signature_scheme(?RSA_PKCS1_SHA512) -> rsa_pkcs1_sha512;
622signature_scheme(?ECDSA_SECP256R1_SHA256) -> ecdsa_secp256r1_sha256;
623signature_scheme(?ECDSA_SECP384R1_SHA384) -> ecdsa_secp384r1_sha384;
624signature_scheme(?ECDSA_SECP521R1_SHA512) -> ecdsa_secp521r1_sha512;
625signature_scheme(?RSA_PSS_RSAE_SHA256) -> rsa_pss_rsae_sha256;
626signature_scheme(?RSA_PSS_RSAE_SHA384) -> rsa_pss_rsae_sha384;
627signature_scheme(?RSA_PSS_RSAE_SHA512) -> rsa_pss_rsae_sha512;
628signature_scheme(?ED25519) -> eddsa_ed25519;
629signature_scheme(?ED448) -> eddsa_ed448;
630signature_scheme(?RSA_PSS_PSS_SHA256) -> rsa_pss_pss_sha256;
631signature_scheme(?RSA_PSS_PSS_SHA384) -> rsa_pss_pss_sha384;
632signature_scheme(?RSA_PSS_PSS_SHA512) -> rsa_pss_pss_sha512;
633signature_scheme(?RSA_PKCS1_SHA1) -> rsa_pkcs1_sha1;
634signature_scheme(?ECDSA_SHA1) -> ecdsa_sha1;
635%% Handling legacy signature algorithms for logging purposes. These algorithms
636%% cannot be used in TLS 1.3 handshakes.
637signature_scheme(SignAlgo) when is_integer(SignAlgo) ->
638    <<?BYTE(Hash),?BYTE(Sign)>> = <<?UINT16(SignAlgo)>>,
639    try
640        {ssl_cipher:hash_algorithm(Hash), ssl_cipher:sign_algorithm(Sign)}
641    catch
642        _:_ ->
643            unassigned
644    end;
645signature_scheme(_) -> unassigned.
646
647signature_schemes_1_2(SigAlgs) ->
648    lists:foldl(fun(Alg, Acc) when is_atom(Alg) ->
649                        case scheme_to_components(Alg) of
650                            {Hash, Sign = rsa_pss_pss,_} ->
651                                [{Hash, Sign} | Acc];
652                            {Hash, Sign = rsa_pss_rsae,_} ->
653                                [{Hash, Sign} | Acc];
654                            {_, _, _} ->
655                                Acc
656                        end;
657                   (Alg, Acc) ->
658                        [Alg| Acc]
659                end, [], SigAlgs).
660
661%% TODO: reserved code points?
662
663scheme_to_components(rsa_pkcs1_sha256) -> {sha256, rsa_pkcs1, undefined};
664scheme_to_components(rsa_pkcs1_sha384) -> {sha384, rsa_pkcs1, undefined};
665scheme_to_components(rsa_pkcs1_sha512) -> {sha512, rsa_pkcs1, undefined};
666scheme_to_components(ecdsa_secp256r1_sha256) -> {sha256, ecdsa, secp256r1};
667scheme_to_components(ecdsa_secp384r1_sha384) -> {sha384, ecdsa, secp384r1};
668scheme_to_components(ecdsa_secp521r1_sha512) -> {sha512, ecdsa, secp521r1};
669scheme_to_components(rsa_pss_rsae_sha256) -> {sha256, rsa_pss_rsae, undefined};
670scheme_to_components(rsa_pss_rsae_sha384) -> {sha384, rsa_pss_rsae, undefined};
671scheme_to_components(rsa_pss_rsae_sha512) -> {sha512, rsa_pss_rsae, undefined};
672scheme_to_components(eddsa_ed25519) -> {none, eddsa, ed25519};
673scheme_to_components(eddsa_ed448) -> {none, eddsa, ed448};
674scheme_to_components(rsa_pss_pss_sha256) -> {sha256, rsa_pss_pss, undefined};
675scheme_to_components(rsa_pss_pss_sha384) -> {sha384, rsa_pss_pss, undefined};
676scheme_to_components(rsa_pss_pss_sha512) -> {sha512, rsa_pss_pss, undefined};
677scheme_to_components(rsa_pkcs1_sha1) -> {sha1, rsa_pkcs1, undefined};
678scheme_to_components(ecdsa_sha1) -> {sha1, ecdsa, undefined};
679%% Handling legacy signature algorithms
680scheme_to_components({Hash,Sign}) -> {Hash, Sign, undefined}.
681
682%%--------------------------------------------------------------------
683%%% Internal functions
684%%--------------------------------------------------------------------
685mac_hash({_,_}, ?NULL, _MacSecret, _SeqNo, _Type,
686	 _Length, _Fragment) ->
687    <<>>;
688mac_hash({3, N} = Version, MacAlg, MacSecret, SeqNo, Type, Length, Fragment)
689  when N =:= 1; N =:= 2; N =:= 3; N =:= 4 ->
690    tls_v1:mac_hash(MacAlg, MacSecret, SeqNo, Type, Version,
691		      Length, Fragment).
692
693bulk_cipher_algorithm(null) ->
694    ?NULL;
695bulk_cipher_algorithm(rc4_128) ->
696    ?RC4;
697bulk_cipher_algorithm(des_cbc) ->
698    ?DES;
699bulk_cipher_algorithm('3des_ede_cbc') ->
700    ?'3DES';
701bulk_cipher_algorithm(Cipher) when Cipher == aes_128_cbc;
702				   Cipher == aes_256_cbc ->
703    ?AES_CBC;
704bulk_cipher_algorithm(Cipher) when Cipher == aes_128_gcm;
705				   Cipher == aes_256_gcm ->
706    ?AES_GCM;
707bulk_cipher_algorithm(Cipher) when Cipher == aes_128_ccm;
708				   Cipher == aes_256_ccm ->
709    ?AES_CCM;
710bulk_cipher_algorithm(Cipher) when Cipher == aes_128_ccm_8;
711				   Cipher == aes_256_ccm_8 ->
712    ?AES_CCM_8;
713bulk_cipher_algorithm(chacha20_poly1305) ->
714    ?CHACHA20_POLY1305.
715
716type(Cipher) when Cipher == null;
717		  Cipher == rc4_128 ->
718    ?STREAM;
719
720type(Cipher) when Cipher == des_cbc;
721		  Cipher == '3des_ede_cbc';
722		  Cipher == aes_128_cbc;
723		  Cipher == aes_256_cbc ->
724    ?BLOCK;
725type(Cipher) when Cipher == aes_128_gcm;
726		  Cipher == aes_256_gcm;
727                  Cipher == aes_128_ccm;
728		  Cipher == aes_256_ccm;
729                  Cipher == aes_128_ccm_8;
730		  Cipher == aes_256_ccm_8;
731		  Cipher == chacha20_poly1305 ->
732    ?AEAD.
733
734key_material(null) ->
735    0;
736key_material(rc4_128) ->
737    16;
738key_material(des_cbc) ->
739    8;
740key_material('3des_ede_cbc') ->
741    24;
742key_material(aes_128_cbc) ->
743    16;
744key_material(aes_256_cbc) ->
745    32;
746key_material(aes_128_gcm) ->
747    16;
748key_material(aes_128_ccm) ->
749    16;
750key_material(aes_128_ccm_8) ->
751    16;
752key_material(aes_256_gcm) ->
753    32;
754key_material(aes_256_ccm_8) ->
755    32;
756key_material(aes_256_ccm) ->
757    32;
758key_material(chacha20_poly1305) ->
759    32.
760
761expanded_key_material(null) ->
762    0;
763expanded_key_material(rc4_128) ->
764    16;
765expanded_key_material(Cipher) when Cipher == des_cbc ->
766    8;
767expanded_key_material('3des_ede_cbc') ->
768    24;
769expanded_key_material(Cipher) when Cipher == aes_128_cbc;
770				   Cipher == aes_256_cbc;
771				   Cipher == aes_128_gcm;
772				   Cipher == aes_256_gcm;
773                                   Cipher == aes_128_ccm;
774				   Cipher == aes_256_ccm;
775                                   Cipher == aes_128_ccm_8;
776				   Cipher == aes_256_ccm_8;
777				   Cipher == chacha20_poly1305 ->
778    unknown.
779
780effective_key_bits(null) ->
781    0;
782effective_key_bits(des_cbc) ->
783    56;
784effective_key_bits(Cipher) when Cipher == rc4_128;
785				Cipher == aes_128_cbc;
786				Cipher == aes_128_gcm;
787                                Cipher == aes_128_ccm;
788                                Cipher == aes_128_ccm_8 ->
789    128;
790effective_key_bits('3des_ede_cbc') ->
791    168;
792effective_key_bits(Cipher) when Cipher == aes_256_cbc;
793				Cipher == aes_256_gcm;
794				Cipher == aes_256_ccm;
795                                Cipher == aes_256_ccm_8;
796				Cipher == chacha20_poly1305 ->
797    256.
798
799iv_size(Cipher) when Cipher == null;
800		     Cipher == rc4_128 ->
801    0;
802iv_size(Cipher) when Cipher == aes_128_gcm;
803		     Cipher == aes_256_gcm;
804                     Cipher == aes_128_ccm;
805		     Cipher == aes_256_ccm;
806                     Cipher == aes_128_ccm_8;
807		     Cipher == aes_256_ccm_8 ->
808    4;
809iv_size(chacha20_poly1305) ->
810    12;
811iv_size(Cipher) ->
812    block_size(Cipher).
813
814block_size(Cipher) when Cipher == des_cbc;
815			Cipher == des_ede3_cbc;
816			Cipher == '3des_ede_cbc' ->
817    8;
818block_size(Cipher) when Cipher == aes_128_cbc;
819			Cipher == aes_256_cbc;
820			Cipher == aes_128_gcm;
821			Cipher == aes_256_gcm;
822                        Cipher == aes_128_ccm;
823			Cipher == aes_256_ccm;
824                        Cipher == aes_128_ccm_8;
825			Cipher == aes_256_ccm_8;
826			Cipher == chacha20_poly1305 ->
827    16.
828
829prf_algorithm(default_prf, {3, N}) when N >= 3 ->
830    ?SHA256;
831prf_algorithm(default_prf, {3, _}) ->
832    ?MD5SHA;
833prf_algorithm(Algo, _) ->
834    hash_algorithm(Algo).
835
836mac_algorithm(aead) ->
837    aead;
838mac_algorithm(Algo) ->
839    hash_algorithm(Algo).
840
841hash_algorithm(null)   -> ?NULL;
842hash_algorithm(md5)    -> ?MD5;
843hash_algorithm(sha)   -> ?SHA; %% Only sha always refers to "SHA-1"
844hash_algorithm(sha224) -> ?SHA224;
845hash_algorithm(sha256) -> ?SHA256;
846hash_algorithm(sha384) -> ?SHA384;
847hash_algorithm(sha512) -> ?SHA512;
848hash_algorithm(?NULL) -> null;
849hash_algorithm(?MD5) -> md5;
850hash_algorithm(?SHA) -> sha;
851hash_algorithm(?SHA224) -> sha224;
852hash_algorithm(?SHA256) -> sha256;
853hash_algorithm(?SHA384) -> sha384;
854hash_algorithm(?SHA512) -> sha512;
855hash_algorithm(Other)  when is_integer(Other) andalso ((Other >= 7) and (Other =< 223)) -> unassigned;
856hash_algorithm(Other)  when is_integer(Other) andalso ((Other >= 224) and (Other =< 255)) -> Other.
857
858sign_algorithm(anon)  -> ?ANON;
859sign_algorithm(rsa)   -> ?RSA;
860sign_algorithm(dsa)   -> ?DSA;
861sign_algorithm(ecdsa) -> ?ECDSA;
862sign_algorithm(?ANON) -> anon;
863sign_algorithm(?RSA) -> rsa;
864sign_algorithm(?DSA) -> dsa;
865sign_algorithm(?ECDSA) -> ecdsa;
866sign_algorithm(Other) when is_integer(Other) andalso ((Other >= 4) and (Other =< 223)) -> unassigned;
867sign_algorithm(Other) when is_integer(Other) andalso ((Other >= 224) and (Other =< 255)) -> Other.
868
869
870signature_algorithm_to_scheme(#'SignatureAlgorithm'{algorithm = ?'id-RSASSA-PSS',
871                                                    parameters =  #'RSASSA-PSS-params'{
872                                                                     maskGenAlgorithm =
873                                                                         #'MaskGenAlgorithm'{algorithm = ?'id-mgf1',
874                                                                                             parameters = HashAlgo}}}) ->
875    #'HashAlgorithm'{algorithm = HashOid} = HashAlgo,
876    case public_key:pkix_hash_type(HashOid) of
877        sha256 ->
878            rsa_pss_pss_sha256;
879        sha384 ->
880            rsa_pss_pss_sha384;
881        sha512 ->
882            rsa_pss_pss_sha512
883    end;
884signature_algorithm_to_scheme(#'SignatureAlgorithm'{algorithm = ?sha256WithRSAEncryption}) ->
885    rsa_pkcs1_sha256;
886signature_algorithm_to_scheme(#'SignatureAlgorithm'{algorithm = ?sha384WithRSAEncryption}) ->
887    rsa_pkcs1_sha384;
888signature_algorithm_to_scheme(#'SignatureAlgorithm'{algorithm = ?sha512WithRSAEncryption}) ->
889    rsa_pkcs1_sha512;
890signature_algorithm_to_scheme(#'SignatureAlgorithm'{algorithm = ?'ecdsa-with-SHA256'}) ->
891    ecdsa_secp256r1_sha256;
892signature_algorithm_to_scheme(#'SignatureAlgorithm'{algorithm = ?'ecdsa-with-SHA384'}) ->
893    ecdsa_secp384r1_sha384;
894signature_algorithm_to_scheme(#'SignatureAlgorithm'{algorithm = ?'ecdsa-with-SHA512'}) ->
895    ecdsa_secp521r1_sha512;
896signature_algorithm_to_scheme(#'SignatureAlgorithm'{algorithm = ?'sha-1WithRSAEncryption'}) ->
897    rsa_pkcs1_sha1;
898signature_algorithm_to_scheme(#'SignatureAlgorithm'{algorithm = ?sha1WithRSAEncryption}) ->
899    rsa_pkcs1_sha1;
900signature_algorithm_to_scheme(#'SignatureAlgorithm'{algorithm = ?'ecdsa-with-SHA1'}) ->
901    ecdsa_sha1;
902signature_algorithm_to_scheme(#'SignatureAlgorithm'{algorithm = ?'id-Ed25519'}) ->
903    eddsa_ed25519;
904signature_algorithm_to_scheme(#'SignatureAlgorithm'{algorithm = ?'id-Ed448'}) ->
905    eddsa_ed448;
906signature_algorithm_to_scheme(#'SignatureAlgorithm'{algorithm = ?'rsaEncryption',
907                                                    parameters = ?NULL}) ->
908    rsa_pkcs1_sha1;
909signature_algorithm_to_scheme(#'SignatureAlgorithm'{algorithm = ?'rsaEncryption'}) ->
910    rsa_pss_rsae;
911signature_algorithm_to_scheme(#'SignatureAlgorithm'{algorithm = ?'id-RSASSA-PSS'}) ->
912    rsa_pss_pss.
913
914%% RFC 5246: 6.2.3.2.  CBC Block Cipher
915%%
916%%   Implementation note: Canvel et al. [CBCTIME] have demonstrated a
917%%   timing attack on CBC padding based on the time required to compute
918%%   the MAC.  In order to defend against this attack, implementations
919%%   MUST ensure that record processing time is essentially the same
920%%   whether or not the padding is correct.  In general, the best way to
921%%   do this is to compute the MAC even if the padding is incorrect, and
922%%   only then reject the packet.  For instance, if the pad appears to be
923%%   incorrect, the implementation might assume a zero-length pad and then
924%%   compute the MAC.  This leaves a small timing channel, since MAC
925%%   performance depends to some extent on the size of the data fragment,
926%%   but it is not believed to be large enough to be exploitable, due to
927%%   the large block size of existing MACs and the small size of the
928%%   timing signal.
929%%
930%% implementation note:
931%%   We return the original (possibly invalid) PadLength in any case.
932%%   An invalid PadLength will be caught by is_correct_padding/2
933%%
934generic_block_cipher_from_bin({3, N}, T, IV, HashSize)
935  when N == 0; N == 1 ->
936    Sz1 = byte_size(T) - 1,
937    <<_:Sz1/binary, ?BYTE(PadLength0)>> = T,
938    PadLength = if
939		    PadLength0 >= Sz1 -> 0;
940		    true -> PadLength0
941		end,
942    CompressedLength = byte_size(T) - PadLength - 1 - HashSize,
943    <<Content:CompressedLength/binary, Mac:HashSize/binary,
944     Padding:PadLength/binary, ?BYTE(PadLength0)>> = T,
945    #generic_block_cipher{content=Content, mac=Mac,
946			  padding=Padding, padding_length=PadLength0,
947			  next_iv = IV};
948
949generic_block_cipher_from_bin({3, N}, T, IV, HashSize)
950  when N == 2; N == 3; N == 4 ->
951    Sz1 = byte_size(T) - 1,
952    <<_:Sz1/binary, ?BYTE(PadLength)>> = T,
953    IVLength = byte_size(IV),
954    CompressedLength = byte_size(T) - IVLength - PadLength - 1 - HashSize,
955    <<NextIV:IVLength/binary, Content:CompressedLength/binary, Mac:HashSize/binary,
956      Padding:PadLength/binary, ?BYTE(PadLength)>> = T,
957    #generic_block_cipher{content=Content, mac=Mac,
958			  padding=Padding, padding_length=PadLength,
959			  next_iv = NextIV}.
960
961generic_stream_cipher_from_bin(T, HashSz) ->
962    Sz = byte_size(T),
963    CompressedLength = Sz - HashSz,
964    <<Content:CompressedLength/binary, Mac:HashSz/binary>> = T,
965    #generic_stream_cipher{content=Content,
966			   mac=Mac}.
967
968is_correct_padding(#generic_block_cipher{padding_length = Len,
969					 padding = Padding}, {3, 0}, _) ->
970    Len == byte_size(Padding); %% Only length check is done in SSL 3.0 spec
971%% For interoperability reasons it is possible to disable
972%% the padding check when using TLS 1.0, as it is not strictly required
973%% in the spec (only recommended), howerver this makes TLS 1.0 vunrable to the Poodle attack
974%% so by default this clause will not match
975is_correct_padding(GenBlockCipher, {3, 1}, false) ->
976    is_correct_padding(GenBlockCipher, {3, 0}, false);
977%% Padding must be checked in TLS 1.1 and after
978is_correct_padding(#generic_block_cipher{padding_length = Len,
979					 padding = Padding}, _, _) ->
980    (Len == byte_size(Padding)) andalso (padding(Len) == Padding).
981
982padding(PadLen) ->
983    case PadLen of
984        0 -> <<>>;
985        1 -> <<1>>;
986        2 -> <<2,2>>;
987        3 -> <<3,3,3>>;
988        4 -> <<4,4,4,4>>;
989        5 -> <<5,5,5,5,5>>;
990        6 -> <<6,6,6,6,6,6>>;
991        7 -> <<7,7,7,7,7,7,7>>;
992        8 -> <<8,8,8,8,8,8,8,8>>;
993        9 -> <<9,9,9,9,9,9,9,9,9>>;
994        10 -> <<10,10,10,10,10,10,10,10,10,10>>;
995        11 -> <<11,11,11,11,11,11,11,11,11,11,11>>;
996        12 -> <<12,12,12,12,12,12,12,12,12,12,12,12>>;
997        13 -> <<13,13,13,13,13,13,13,13,13,13,13,13,13>>;
998        14 -> <<14,14,14,14,14,14,14,14,14,14,14,14,14,14>>;
999        15 -> <<15,15,15,15,15,15,15,15,15,15,15,15,15,15,15>>;
1000        _ ->
1001            binary:copy(<<PadLen>>, PadLen)
1002    end.
1003
1004padding_with_len(TextLen, BlockSize) ->
1005    case BlockSize - (TextLen rem BlockSize) of
1006        0 -> <<0>>;
1007        1 -> <<1,1>>;
1008        2 -> <<2,2,2>>;
1009        3 -> <<3,3,3,3>>;
1010        4 -> <<4,4,4,4,4>>;
1011        5 -> <<5,5,5,5,5,5>>;
1012        6 -> <<6,6,6,6,6,6,6>>;
1013        7 -> <<7,7,7,7,7,7,7,7>>;
1014        8 -> <<8,8,8,8,8,8,8,8,8>>;
1015        9 -> <<9,9,9,9,9,9,9,9,9,9>>;
1016        10 -> <<10,10,10,10,10,10,10,10,10,10,10>>;
1017        11 -> <<11,11,11,11,11,11,11,11,11,11,11,11>>;
1018        12 -> <<12,12,12,12,12,12,12,12,12,12,12,12,12>>;
1019        13 -> <<13,13,13,13,13,13,13,13,13,13,13,13,13,13>>;
1020        14 -> <<14,14,14,14,14,14,14,14,14,14,14,14,14,14,14>>;
1021        15 -> <<15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15>>;
1022        PadLen ->
1023            binary:copy(<<PadLen>>, PadLen + 1)
1024    end.
1025
1026next_iv(Bin, IV) ->
1027    BinSz = byte_size(Bin),
1028    IVSz = byte_size(IV),
1029    FirstPart = BinSz - IVSz,
1030    <<_:FirstPart/binary, NextIV:IVSz/binary>> = Bin,
1031    NextIV.
1032
1033filter_suites_pubkey(rsa, CiphersSuites0, _Version, OtpCert) ->
1034    KeyUses = key_uses(OtpCert),
1035    NotECDSAKeyed = (CiphersSuites0 -- ec_keyed_suites(CiphersSuites0))
1036        -- dss_keyed_suites(CiphersSuites0),
1037    CiphersSuites = filter_keyuse_suites(keyEncipherment, KeyUses,
1038                                         NotECDSAKeyed,
1039                                         rsa_suites_encipher(CiphersSuites0)),
1040    filter_keyuse_suites(digitalSignature, KeyUses, CiphersSuites,
1041                         rsa_ecdhe_dhe_suites(CiphersSuites));
1042filter_suites_pubkey(dsa, Ciphers, _, OtpCert) ->
1043    KeyUses = key_uses(OtpCert),
1044    NotECRSAKeyed =  (Ciphers -- rsa_keyed_suites(Ciphers)) -- ec_keyed_suites(Ciphers),
1045    filter_keyuse_suites(digitalSignature, KeyUses, NotECRSAKeyed,
1046                         dss_dhe_suites(Ciphers));
1047filter_suites_pubkey(ecdsa, Ciphers, _, OtpCert) ->
1048    Uses = key_uses(OtpCert),
1049    NotRSADSAKeyed = (Ciphers -- rsa_keyed_suites(Ciphers)) -- dss_keyed_suites(Ciphers),
1050    CiphersSuites = filter_keyuse_suites(digitalSignature, Uses, NotRSADSAKeyed,
1051                                   ec_ecdhe_suites(Ciphers)),
1052    filter_keyuse_suites(keyAgreement, Uses, CiphersSuites, ec_ecdh_suites(Ciphers)).
1053
1054filter_suites_signature(_, Ciphers, {3, N}) when N >= 3 ->
1055     Ciphers;
1056filter_suites_signature(rsa, Ciphers, Version) ->
1057    (Ciphers -- ecdsa_signed_suites(Ciphers, Version)) -- dsa_signed_suites(Ciphers, Version);
1058filter_suites_signature(dsa, Ciphers, Version) ->
1059    (Ciphers -- ecdsa_signed_suites(Ciphers, Version)) -- rsa_signed_suites(Ciphers, Version);
1060filter_suites_signature(ecdsa, Ciphers, Version) ->
1061    (Ciphers -- rsa_signed_suites(Ciphers, Version)) -- dsa_signed_suites(Ciphers, Version).
1062
1063
1064%% From RFC 5246 - Section  7.4.2.  Server Certificate
1065%% If the client provided a "signature_algorithms" extension, then all
1066%% certificates provided by the server MUST be signed by a
1067%% hash/signature algorithm pair that appears in that extension.  Note
1068%% that this implies that a certificate containing a key for one
1069%% signature algorithm MAY be signed using a different signature
1070%% algorithm (for instance, an RSA key signed with a DSA key).  This is
1071%% a departure from TLS 1.1, which required that the algorithms be the
1072%% same.
1073%% Note that this also implies that the DH_DSS, DH_RSA,
1074%% ECDH_ECDSA, and ECDH_RSA key exchange algorithms do not restrict the
1075%% algorithm used to sign the certificate.  Fixed DH certificates MAY be
1076%% signed with any hash/signature algorithm pair appearing in the
1077%% extension.  The names DH_DSS, DH_RSA, ECDH_ECDSA, and ECDH_RSA are
1078%% historical.
1079%% Note: DH_DSS and DH_RSA is not supported
1080rsa_signed({3,N}) when N >= 3 ->
1081    fun(rsa) -> true;
1082       (dhe_rsa) -> true;
1083       (ecdhe_rsa) -> true;
1084       (rsa_psk) -> true;
1085       (srp_rsa) -> true;
1086       (_) -> false
1087    end;
1088rsa_signed(_) ->
1089    fun(rsa) -> true;
1090       (dhe_rsa) -> true;
1091       (ecdhe_rsa) -> true;
1092       (ecdh_rsa) -> true;
1093       (rsa_psk) -> true;
1094       (srp_rsa) -> true;
1095       (_) -> false
1096    end.
1097%% Cert should be signed by RSA
1098rsa_signed_suites(Ciphers, Version) ->
1099    filter_suites(Ciphers, #{key_exchange_filters => [rsa_signed(Version)],
1100                             cipher_filters => [],
1101                             mac_filters => [],
1102                             prf_filters => []}).
1103ecdsa_signed({3,N}) when N >= 3 ->
1104    fun(ecdhe_ecdsa) -> true;
1105       (_) -> false
1106    end;
1107ecdsa_signed(_) ->
1108    fun(ecdhe_ecdsa) -> true;
1109       (ecdh_ecdsa) -> true;
1110       (_) -> false
1111    end.
1112
1113%% Cert should be signed by ECDSA
1114ecdsa_signed_suites(Ciphers, Version) ->
1115    filter_suites(Ciphers, #{key_exchange_filters => [ecdsa_signed(Version)],
1116                             cipher_filters => [],
1117                             mac_filters => [],
1118                             prf_filters => []}).
1119
1120rsa_keyed(dhe_rsa) ->
1121    true;
1122rsa_keyed(ecdhe_rsa) ->
1123    true;
1124rsa_keyed(rsa) ->
1125    true;
1126rsa_keyed(rsa_psk) ->
1127    true;
1128rsa_keyed(srp_rsa) ->
1129    true;
1130rsa_keyed(_) ->
1131    false.
1132
1133%% Certs key is an RSA key
1134rsa_keyed_suites(Ciphers) ->
1135   filter_suites(Ciphers, #{key_exchange_filters => [fun(Kex) -> rsa_keyed(Kex) end],
1136                             cipher_filters => [],
1137                             mac_filters => [],
1138                             prf_filters => []}).
1139
1140%% RSA Certs key can be used for encipherment
1141rsa_suites_encipher(Ciphers) ->
1142    filter_suites(Ciphers, #{key_exchange_filters => [fun(rsa) -> true;
1143                                                         (rsa_psk) -> true;
1144                                                         (_) -> false
1145                                                      end],
1146                             cipher_filters => [],
1147                             mac_filters => [],
1148                             prf_filters => []}).
1149
1150dss_keyed(dhe_dss) ->
1151    true;
1152dss_keyed(spr_dss) ->
1153    true;
1154dss_keyed(_) ->
1155    false.
1156
1157%% Cert should be have DSS key (DSA)
1158dss_keyed_suites(Ciphers) ->
1159    filter_suites(Ciphers, #{key_exchange_filters => [fun(Kex) -> dss_keyed(Kex) end],
1160                             cipher_filters => [],
1161                             mac_filters => [],
1162                             prf_filters => []}).
1163
1164%% Cert should be signed by DSS (DSA)
1165dsa_signed_suites(Ciphers, Version) ->
1166    filter_suites(Ciphers, #{key_exchange_filters => [dsa_signed(Version)],
1167                             cipher_filters => [],
1168                             mac_filters => [],
1169                             prf_filters => []}).
1170dsa_signed(_) ->
1171    fun(dhe_dss) -> true;
1172       (_) -> false
1173    end.
1174
1175dss_dhe_suites(Ciphers) ->
1176    filter_suites(Ciphers, #{key_exchange_filters => [fun(dhe_dss) -> true;
1177                                                         (_) -> false
1178                                                      end],
1179                             cipher_filters => [],
1180                             mac_filters => [],
1181                             prf_filters => []}).
1182
1183ec_keyed(ecdh_ecdsa) ->
1184    true;
1185ec_keyed(ecdh_rsa) ->
1186    true;
1187ec_keyed(ecdhe_ecdsa) ->
1188    true;
1189ec_keyed(_) ->
1190    false.
1191
1192%% Certs key is an ECC key
1193ec_keyed_suites(Ciphers) ->
1194    filter_suites(Ciphers, #{key_exchange_filters => [fun(Kex) -> ec_keyed(Kex) end],
1195                             cipher_filters => [],
1196                             mac_filters => [],
1197                             prf_filters => []}).
1198
1199%% EC Certs key usage keyAgreement
1200ec_ecdh_suites(Ciphers)->
1201    filter_suites(Ciphers, #{key_exchange_filters => [fun(ecdh_ecdsa) -> true;
1202                                                         (_) -> false
1203                                                      end],
1204                             cipher_filters => [],
1205                             mac_filters => [],
1206                             prf_filters => []}).
1207
1208%% EC Certs key usage digitalSignature
1209ec_ecdhe_suites(Ciphers) ->
1210    filter_suites(Ciphers, #{key_exchange_filters => [fun(ecdhe_ecdsa) -> true;
1211                                                         (ecdhe_rsa) -> true;
1212                                                         (_) -> false
1213                                                      end],
1214                             cipher_filters => [],
1215                             mac_filters => [],
1216                             prf_filters => []}).
1217%% RSA Certs key usage digitalSignature
1218rsa_ecdhe_dhe_suites(Ciphers) ->
1219    filter_suites(Ciphers, #{key_exchange_filters => [fun(dhe_rsa) -> true;
1220                                                         (ecdhe_rsa) -> true;
1221                                                         (_) -> false
1222                                                      end],
1223                             cipher_filters => [],
1224                             mac_filters => [],
1225                             prf_filters => []}).
1226
1227key_uses(OtpCert) ->
1228    TBSCert = OtpCert#'OTPCertificate'.tbsCertificate,
1229    TBSExtensions = TBSCert#'OTPTBSCertificate'.extensions,
1230    Extensions = ssl_certificate:extensions_list(TBSExtensions),
1231    case ssl_certificate:select_extension(?'id-ce-keyUsage', Extensions) of
1232	undefined ->
1233	    [];
1234	#'Extension'{extnValue = KeyUses} ->
1235            KeyUses
1236    end.
1237
1238%% If no key-usage extension is defined all key-usages are allowed
1239filter_keyuse_suites(_, [], CiphersSuites, _) ->
1240    CiphersSuites;
1241filter_keyuse_suites(Use, KeyUse, CipherSuits, Suites) ->
1242    case ssl_certificate:is_valid_key_usage(KeyUse, Use) of
1243	true ->
1244	    CipherSuits;
1245	false ->
1246	    CipherSuits -- Suites
1247    end.
1248
1249generate_server_share(Group) ->
1250    Key = generate_key_exchange(Group),
1251    #key_share_server_hello{
1252       server_share = #key_share_entry{
1253                         group = Group,
1254                         key_exchange = Key
1255                        }}.
1256
1257generate_client_shares([]) ->
1258    #key_share_client_hello{client_shares = []};
1259generate_client_shares(Groups) ->
1260    generate_client_shares(Groups, []).
1261%%
1262generate_client_shares([], Acc) ->
1263    #key_share_client_hello{client_shares = lists:reverse(Acc)};
1264generate_client_shares([Group|Groups], Acc) ->
1265    Key = generate_key_exchange(Group),
1266    KeyShareEntry = #key_share_entry{
1267                       group = Group,
1268                       key_exchange = Key
1269                      },
1270    generate_client_shares(Groups, [KeyShareEntry|Acc]).
1271
1272
1273generate_key_exchange(secp256r1) ->
1274    public_key:generate_key({namedCurve, secp256r1});
1275generate_key_exchange(secp384r1) ->
1276    public_key:generate_key({namedCurve, secp384r1});
1277generate_key_exchange(secp521r1) ->
1278    public_key:generate_key({namedCurve, secp521r1});
1279generate_key_exchange(x25519) ->
1280    crypto:generate_key(ecdh, x25519);
1281generate_key_exchange(x448) ->
1282    crypto:generate_key(ecdh, x448);
1283generate_key_exchange(FFDHE) ->
1284    public_key:generate_key(ssl_dh_groups:dh_params(FFDHE)).
1285
1286
1287%% TODO: Move this functionality to crypto!
1288%% 7.4.1.  Finite Field Diffie-Hellman
1289%%
1290%%    For finite field groups, a conventional Diffie-Hellman [DH76]
1291%%    computation is performed.  The negotiated key (Z) is converted to a
1292%%    byte string by encoding in big-endian form and left-padded with zeros
1293%%    up to the size of the prime.  This byte string is used as the shared
1294%%    secret in the key schedule as specified above.
1295add_zero_padding(Bin, PrimeSize)
1296  when byte_size (Bin) =:= PrimeSize ->
1297    Bin;
1298add_zero_padding(Bin, PrimeSize) ->
1299    add_zero_padding(<<0, Bin/binary>>, PrimeSize).
1300
1301
1302%% Functions for handling self-encrypted session tickets (TLS 1.3).
1303%%
1304encrypt_ticket(#stateless_ticket{
1305                  hash = Hash,
1306                  pre_shared_key = PSK,
1307                  ticket_age_add = TicketAgeAdd,
1308                  lifetime = Lifetime,
1309                  timestamp = Timestamp
1310                 }, Shard, IV) ->
1311    Plaintext = <<(ssl_cipher:hash_algorithm(Hash)):8,PSK/binary,
1312                   ?UINT64(TicketAgeAdd),?UINT32(Lifetime),?UINT32(Timestamp)>>,
1313    encrypt_ticket_data(Plaintext, Shard, IV).
1314
1315
1316decrypt_ticket(CipherFragment, Shard, IV) ->
1317    case decrypt_ticket_data(CipherFragment, Shard, IV) of
1318        error ->
1319            error;
1320        Plaintext ->
1321            <<?BYTE(HKDF),T/binary>> = Plaintext,
1322            Hash = hash_algorithm(HKDF),
1323            HashSize = hash_size(Hash),
1324            <<PSK:HashSize/binary,?UINT64(TicketAgeAdd),?UINT32(Lifetime),?UINT32(Timestamp),_/binary>> = T,
1325            #stateless_ticket{
1326               hash = Hash,
1327               pre_shared_key = PSK,
1328               ticket_age_add = TicketAgeAdd,
1329               lifetime = Lifetime,
1330               timestamp = Timestamp
1331              }
1332    end.
1333
1334
1335encrypt_ticket_data(Plaintext, Shard, IV) ->
1336    AAD = additional_data(<<"ticket">>, erlang:iolist_size(Plaintext) + 16), %% TagLen = 16
1337    {OTP, Key} = make_otp_key(Shard),
1338    {Content, CipherTag} = crypto:crypto_one_time_aead(aes_256_gcm, Key, IV, Plaintext, AAD, 16, true),
1339    <<Content/binary,CipherTag/binary,OTP/binary>>.
1340
1341
1342decrypt_ticket_data(CipherFragment, Shard, IV) ->
1343    Size = byte_size(Shard),
1344    AAD = additional_data(<<"ticket">>, erlang:iolist_size(CipherFragment) - Size),
1345    Len = byte_size(CipherFragment) - Size - 16,
1346    case CipherFragment of
1347        <<Encrypted:Len/binary,CipherTag:16/binary,OTP:Size/binary>> ->
1348            Key = crypto:exor(OTP, Shard),
1349            crypto:crypto_one_time_aead(aes_256_gcm, Key, IV,
1350                                        Encrypted, AAD, CipherTag,
1351                                        false);
1352        _ ->
1353            error
1354    end.
1355
1356encrypt_data(ADTag, Plaintext, Shard, IV) ->
1357    AAD = additional_data(ADTag, erlang:iolist_size(Plaintext) + 16), %% TagLen = 16
1358    {OTP, Key} = make_otp_key(Shard),
1359    {Content, CipherTag} = crypto:crypto_one_time_aead(aes_256_gcm, Key, IV, Plaintext, AAD, 16, true),
1360    <<Content/binary,CipherTag/binary,OTP/binary>>.
1361
1362decrypt_data(ADTag, CipherFragment, Shard, IV) ->
1363    Size = byte_size(Shard),
1364    AAD = additional_data(ADTag, erlang:iolist_size(CipherFragment) - Size),
1365    Len = byte_size(CipherFragment) - Size - 16,
1366    <<Encrypted:Len/binary,CipherTag:16/binary,OTP:Size/binary>> = CipherFragment,
1367    Key = crypto:exor(OTP, Shard),
1368    crypto:crypto_one_time_aead(aes_256_gcm, Key, IV, Encrypted, AAD, CipherTag, false).
1369
1370additional_data(Tag, Length) ->
1371    <<Tag/binary,?UINT16(Length)>>.
1372
1373make_otp_key(Shard) ->
1374    Size = byte_size(Shard),
1375    OTP = crypto:strong_rand_bytes(Size),
1376    Key = crypto:exor(OTP, Shard),
1377    {OTP, Key}.
1378