summaryrefslogtreecommitdiff
path: root/lib/ssl/doc/src/using_ssl.xml
blob: 148c7d8dfca182f097e6e10a7b487b1bc9d65d9e (plain)
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
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">

<chapter>
  <header>
    <copyright>
      <year>2003</year><year>2022</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      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.
    
    </legalnotice>

    <title>Using SSL application API</title>
    <prepared></prepared>
    <responsible></responsible>
    <docno></docno>
    <approved></approved>
    <checked></checked>
    <date></date>
    <rev></rev>
    <file>using_ssl.xml</file>
  </header>
  <p>To see relevant version information for ssl, call
  <seemfa marker="ssl:ssl#versions/0"><c>ssl:versions/0</c></seemfa>
  .</p>
    
  <p>To see all supported cipher suites, call <seemfa
  marker="ssl:ssl#cipher_suites/2"><c>ssl:cipher_suites(all,
  'tlsv1.3')</c> </seemfa>.  The available cipher suites for a
  connection depend on the TLS version and pre TLS-1.3 also on the
  certificate. To see the default cipher suite list change <c>all</c>
  to <c>default</c>.  Note that TLS 1.3 and previous versions do not
  have any cipher suites in common, for listing cipher suites for a
  specific version use <seemfa
  marker="ssl:ssl#cipher_suites/2"><c>ssl:cipher_suites(exclusive,
  'tlsv1.3')</c> </seemfa>.  Specific cipher suites that you want your
  connection to use can also be specified. Default is to use the
  strongest available.</p>


  <p>The following sections shows small examples of how to set up
  client/server connections using the Erlang shell. The returned
  value of the <c>sslsocket</c> is abbreviated with <c>[...]</c> as
  it can be fairly large and is opaque to the user except for the
  purpose of pattern matching.</p>


  <note><p>Note that client certificate verification is optional for the server and needs additional conguration
  on both sides to work. The Certificate and keys, in the examples, are provided using the <seetype marker="ssl:ssl#certs_keys">certs_keys</seetype> option
  introduced in OTP-25.
  </p>
  </note>

  <section>
    <title>Basic Client</title>
    <code type="erl"> 1 > ssl:start(), ssl:connect("google.com", 443, [{verify, verify_peer},
    {cacerts, public_key:cacerts_get()}]).
   {ok,{sslsocket, [...]}}</code>
  </section>

  <section>
    <title>Basic Connection</title>

    <p><em>Step 1:</em> Start the server side:</p>
    <code type="erl">1 server> ssl:start().
ok</code>

     <p><em>Step 2:</em> with alternative certificates,
    in this example the EDDSA certificate will be preferred if TLS-1.3
    is negotiated and the RSA certificate will always be used for TLS-1.2
    as it does not support the EDDSA algorithm: </p>
      <code type="erl">2 server> {ok, ListenSocket} =
ssl:listen(9999, [{certs_keys, [#{certfile => "eddsacert.pem",
                                  keyfile => "eddsakey.pem"},
			        #{certfile => "rsacert.pem",
                                  keyfile => "rsakey.pem",
			          password => "foobar"}
			       ]},{reuseaddr, true}]).
{ok,{sslsocket, [...]}}</code>

      
      <p><em>Step 3:</em> Do a transport accept on the TLS listen socket:</p>
      <code type="erl">3 server> {ok, TLSTransportSocket} = ssl:transport_accept(ListenSocket).
{ok,{sslsocket, [...]}}</code>


<note><p> ssl:transport_accept/1 and ssl:handshake/2 are separate functions so that
the handshake part can be called in a new erlang process dedicated to handling the
connection</p>
</note>

      <p><em>Step 4:</em> Start the client side: </p>
      <code type="erl">1 client> ssl:start().
ok</code>
      <p> Be sure to configure trusted certificates to use for server certificate verification.</p>
      <code type="erl">2 client> {ok, Socket} = ssl:connect("localhost", 9999,
      [{verify, verify_peer},
      {cacertfile, "cacerts.pem"}, {active, once}], infinity).
{ok,{sslsocket, [...]}}</code>
      
      <p><em>Step 5:</em> Do the TLS handshake:</p>
      <code type="erl">4 server> {ok, Socket} = ssl:handshake(TLSTransportSocket).
{ok,{sslsocket, [...]}}</code>

<note><p> A real server should use ssl:handshake/2 that has a timeout
to avoid DoS attacks. In the example the timeout defaults to infinty.</p>
</note>

      <p><em>Step 6:</em> Send a message over TLS:</p>
      <code type="erl">5 server> ssl:send(Socket, "foo").
ok</code>
      
      <p><em>Step 7:</em> Flush the shell message queue to see that the message
      sent on the server side is recived by the client side:</p>
      <code type="erl">3 client> flush().
Shell got {ssl,{sslsocket,[...]},"foo"}
ok</code>
  </section>


  <section>
  <title>Upgrade Example - TLS only</title>

  <p>Upgrading a a TCP/IP connection to a TLS connections is mostly
  used when there is a desire have unencrypted communication first and
  then later secure the communication channel by using TLS. Note that
  the client and server need to agree to do the upgrade in the
  protocol doing the communication. This is concept is often
  referenced as <c>STARTLS</c> and used in many protocols such as
  <c>SMTP</c>, <c>FTPS</c> and <c>HTTPS</c> via a proxy.
  </p>

  <warning><p>Maximum security recommendations are however moving away from such solutions.</p></warning>
      
  <p>To upgrade to a TLS connection:</p>

  <p><em>Step 1:</em> Start the server side:</p>
  <code type="erl">1 server> ssl:start().
  ok</code>

  <p><em>Step 2:</em> Create a normal TCP listen socket and ensure
  <c>active</c> is set to <c>false</c> and not set to any active mode
  otherwise TLS handshake messages can be delivered to the
  wrong process.
  </p>
  <code type="erl">2 server> {ok, ListenSocket} = gen_tcp:listen(9999, [{reuseaddr, true},
  {active, false}]).
  {ok, #Port&lt;0.475&gt;}</code>

  <p><em>Step 3:</em> Accept client connection:</p>
  <code type="erl">3 server> {ok, Socket} = gen_tcp:accept(ListenSocket).
  {ok, #Port&lt;0.476&gt;}</code>

  <p><em>Step 4:</em> Start the client side:</p>
  <code type="erl">1 client> ssl:start().
  ok</code>

  <code type="erl">2 client> {ok, Socket} = gen_tcp:connect("localhost", 9999,  [], infinity).</code>

  <p><em>Step 5:</em> Do the TLS handshake:</p>
  <code type="erl">4 server> {ok, TLSSocket} = ssl:handshake(Socket, [{verify, verify_peer},
  {fail_if_no_peer_cert, true},
  {cacertfile, "cacerts.pem"},
  {certs_keys, [#{certfile => "cert.pem", keyfile => "key.pem"}]}]).
  {ok,{sslsocket,[...]}}</code>
      
  <p><em>Step 6:</em> Upgrade to a TLS connection. The client and
  server must agree upon the upgrade. The server must be prepared to be a TLS server before the client
  can do a successful connect.</p>

  <code type="erl">3 client>{ok, TLSSocket} = ssl:connect(Socket, [{verify, verify_peer},
  {cacertfile, "cacerts.pem"},
  {certs_keys, [#{certfile => "cert.pem", keyfile => "key.pem"}]}], infinity).
{ok,{sslsocket,[...]}}</code>

      <p><em>Step 7:</em> Send a message over TLS:</p>
      <code type="erl">4 client> ssl:send(TLSSocket, "foo").
      ok</code>
      
      <p><em>Step 8:</em> Set <c>active once</c> on the TLS socket:</p>
      <code type="erl">5 server> ssl:setopts(TLSSocket, [{active, once}]).
      ok</code>
      
      <p><em>Step 9:</em> Flush the shell message queue to see that
      the message sent on the client side is recived by the server side:</p>

      <code type="erl">5 server> flush().
      Shell got {ssl,{sslsocket,[...]},"foo"}
      ok</code>
</section>

  <section>
    <title>Customizing cipher suites</title>

    <p>Fetch default cipher suite list for a TLS/DTLS version. Change default
    to all to get all possible cipher suites.</p>

    <code type="erl">1>  Default = ssl:cipher_suites(default, 'tlsv1.2').
    [#{cipher => aes_256_gcm,key_exchange => ecdhe_ecdsa,
    mac => aead,prf => sha384}, ....]
</code>

    <p>In OTP 20 it is desirable to remove all cipher suites
    that uses rsa key exchange (removed from default in 21) </p>
    <code type="erl">2> NoRSA =
    ssl:filter_cipher_suites(Default,
                            [{key_exchange, fun(rsa) -> false;
			                        (_) -> true
			                    end}]).
    [...]
    </code>

    <p> Pick just a few suites </p>
    <code type="erl"> 3> Suites =
    ssl:filter_cipher_suites(Default,
                            [{key_exchange, fun(ecdh_ecdsa) -> true;
			                        (_) -> false
			                    end},
                             {cipher, fun(aes_128_cbc) -> true;
			                  (_) ->false
			              end}]).
    [#{cipher => aes_128_cbc,key_exchange => ecdh_ecdsa,
     mac => sha256,prf => sha256},
     #{cipher => aes_128_cbc,key_exchange => ecdh_ecdsa,mac => sha,
     prf => default_prf}]
    </code>
    
    <p> Make some particular suites the most preferred, or least
    preferred by changing prepend to append.</p>
    <code type="erl"> 4>ssl:prepend_cipher_suites(Suites, Default).
  [#{cipher => aes_128_cbc,key_exchange => ecdh_ecdsa,
     mac => sha256,prf => sha256},
   #{cipher => aes_128_cbc,key_exchange => ecdh_ecdsa,mac => sha,
     prf => default_prf},
   #{cipher => aes_256_cbc,key_exchange => ecdhe_ecdsa,
     mac => sha384,prf => sha384}, ...]
    </code>
  </section>      

  <section>
    <title>Using an Engine Stored Key</title>
    
    <p>Erlang ssl application is able to use private keys provided
    by OpenSSL engines using the following mechanism:</p>
    
    <code type="erl">1> ssl:start().
ok</code>

    <p>Load a crypto engine, should be done once per engine used. For example
    dynamically load the engine called <c>MyEngine</c>:
    </p>
    <code type="erl">2> {ok, EngineRef} =
crypto:engine_load(&lt;&lt;"dynamic">>,
[{&lt;&lt;"SO_PATH">>, "/tmp/user/engines/MyEngine"},&lt;&lt;"LOAD">>],
[]).
{ok,#Ref&lt;0.2399045421.3028942852.173962>}
    </code>
    
    <p>Create a map with the engine information and the algorithm used by the engine:</p>
    <code type="erl">3> PrivKey =
 #{algorithm => rsa,
   engine => EngineRef,
   key_id => "id of the private key in Engine"}.
    </code>
    <p>Use the map in the ssl key option:</p>
    <code type="erl">4> {ok, SSLSocket} =
ssl:connect("localhost", 9999,
            [{cacertfile, "cacerts.pem"},
	    {certs_keys, [#{certfile => "cert.pem", key => PrivKey}]}
	    ], infinity).
    </code>

    <p>See also <seeguide marker="crypto:engine_load#engine_load"> crypto documentation</seeguide> </p>
    
  </section>

  <section>
    <title>Session Reuse pre TLS 1.3</title>

    <p>Clients can request to reuse a session established by a
    previous full handshake between that client and server by sending
    the id of the session in the initial handshake message. The server
    may or may not agree to reuse it. If agreed the server will send
    back the id and if not it will send a new id. The ssl application
    has several options for handling session reuse.</p>

    <p>On the client side the ssl application will save session data
    to try to automate session reuse on behalf of the client processes
    on the Erlang node. Note that only verified sessions will be saved
    for security reasons, that is session resumption relies on the
    certificate validation to have been run in the original
    handshake. To minimize memory consumption only unique sessions
    will be saved unless the special <c>save</c> value is specified
    for the following option <c> {reuse_sessions, boolean() |
    save}</c> in which case a full handshake will be performed and
    that specific session will have been saved before the handshake
    returns. The session id and even an opaque binary containing the
    session data can be retrieved using
    <c>ssl:connection_information/1</c> function. A saved session
    (guaranteed by the save option) can be explicitly reused using
    <c>{reuse_session, SessionId}</c>. Also it is possible for the
    client to reuse a session that is not saved by the ssl application
    using <c>{reuse_session, {SessionId, SessionData}}</c>.</p>

    <note><p>When using explicit session reuse, it is up to the client
    to make sure that the session being reused is for the correct
    server and has been verified.</p></note>

    <p>Here follows a client side example,
    divide into several steps for readability.
    </p>

    <p>Step 1 - Automated Session Reuse</p>

    <code type="erl">
1> ssl:start().
ok

2&gt; {ok, C1} = ssl:connect("localhost", 9999, [{verify, verify_peer},
					      {versions, ['tlsv1.2']},
					      {cacertfile, "cacerts.pem"}]).
{ok,{sslsocket,{gen_tcp,#Port&lt;0.7&gt;,tls_connection,undefined}, ...}}

3&gt; ssl:connection_information(C1, [session_id]).
{ok,[{session_id,&lt;&lt;95,32,43,22,35,63,249,22,26,36,106,
                   152,49,52,124,56,130,192,137,161,
                   146,145,164,232,...&gt;&gt;}]}

%% Reuse session if possible, note that if C2 is really fast the session
%% data might not be available for reuse.
4&gt; {ok, C2} = ssl:connect("localhost", 9999, [{verify, verify_peer},
					      {versions, ['tlsv1.2']},
					      {cacertfile, "cacerts.pem"},
					      {reuse_sessions, true}]).
{ok,{sslsocket,{gen_tcp,#Port&lt;0.8&gt;,tls_connection,undefined}, ...]}}

%% C2 got same session ID as client one, session was automatically reused.
5&gt; ssl:connection_information(C2, [session_id]).
{ok,[{session_id,&lt;&lt;95,32,43,22,35,63,249,22,26,36,106,
                   152,49,52,124,56,130,192,137,161,
                   146,145,164,232,...&gt;&gt;}]}

</code>

<p>Step 2- Using <c>save</c> Option </p>

<code type="erl">
%% We want save this particular session for
%% reuse although it has the same basis as C1
6&gt; {ok, C3} = ssl:connect("localhost", 9999, [{verify, verify_peer},
					      {versions, ['tlsv1.2']},
					      {cacertfile, "cacerts.pem"},
					      {reuse_sessions, save}]).
{ok,{sslsocket,{gen_tcp,#Port&lt;0.9&gt;,tls_connection,undefined}, ...]}}

%% A full handshake is performed and we get a new session ID
7&gt; {ok, [{session_id, ID}]} = ssl:connection_information(C3, [session_id]).
{ok,[{session_id,&lt;&lt;91,84,27,151,183,39,84,90,143,141,
                   121,190,66,192,10,1,27,192,33,95,78,
                   8,34,180,...&gt;&gt;}]}

%% Use automatic session reuse
8&gt; {ok, C4} = ssl:connect("localhost", 9999, [{verify, verify_peer},
					      {versions, ['tlsv1.2']},
					      {cacertfile, "cacerts.pem"},
					      {reuse_sessions, true}]).
{ok,{sslsocket,{gen_tcp,#Port&lt;0.10&gt;,tls_connection,
                        undefined}, ...]}}

%% The "saved" one happened to be selected, but this is not a guarantee
9&gt; ssl:connection_information(C4, [session_id]).
{ok,[{session_id,&lt;&lt;91,84,27,151,183,39,84,90,143,141,
                   121,190,66,192,10,1,27,192,33,95,78,
                   8,34,180,...&gt;&gt;}]}

%% Make sure to reuse the "saved" session
10&gt; {ok, C5} = ssl:connect("localhost", 9999, [{verify, verify_peer},
					       {versions, ['tlsv1.2']},
					       {cacertfile, "cacerts.pem"},
					       {reuse_session, ID}]).
{ok,{sslsocket,{gen_tcp,#Port&lt;0.11&gt;,tls_connection,
                        undefined}, ...]}}

11&gt; ssl:connection_information(C5, [session_id]).
{ok,[{session_id,&lt;&lt;91,84,27,151,183,39,84,90,143,141,
                   121,190,66,192,10,1,27,192,33,95,78,
                   8,34,180,...&gt;&gt;}]}
</code>

<p>Step 3 - Explicit Session Reuse </p>

<code type="erl">
%% Perform a full handshake and the session will not be saved for reuse
12&gt; {ok, C9} =
ssl:connect("localhost", 9999, [{verify, verify_peer},
				{versions, ['tlsv1.2']},
		                {cacertfile, "cacerts.pem"},
                                {reuse_sessions, false},
	                        {server_name_indication, disable}]).
{ok,{sslsocket,{gen_tcp,#Port&lt;0.14&gt;,tls_connection, ...}}

%% Fetch session ID and data for C9 connection
12&gt; {ok, [{session_id, ID1}, {session_data, SessData}]} =
	ssl:connection_information(C9, [session_id, session_data]).
{ok,[{session_id,&lt;&lt;9,233,4,54,170,88,170,180,17,96,202,
                   85,85,99,119,47,9,68,195,50,120,52,
                   130,239,...&gt;&gt;},
     {session_data,&lt;&lt;131,104,13,100,0,7,115,101,115,115,105,
                     111,110,109,0,0,0,32,9,233,4,54,170,...&gt;&gt;}]}

%% Explicitly reuse the session from C9
13&gt; {ok, C10} = ssl:connect("localhost", 9999, [{verify, verify_peer},
						{versions, ['tlsv1.2']},
						{cacertfile, "cacerts.pem"},
						{reuse_session, {ID1, SessData}}]).
{ok,{sslsocket,{gen_tcp,#Port&lt;0.15&gt;,tls_connection,
                        undefined}, ...}}

14&gt; ssl:connection_information(C10, [session_id]).
{ok,[{session_id,&lt;&lt;9,233,4,54,170,88,170,180,17,96,202,
                   85,85,99,119,47,9,68,195,50,120,52,
                   130,239,...&gt;&gt;}]}

</code>

<p>Step 4 - Not Possible to Reuse Explicit Session by ID Only</p>

<code type="erl">
%% Try to reuse the session from C9 using only the id
15&gt; {ok, E} = ssl:connect("localhost", 9999, [{verify, verify_peer},
				              {versions, ['tlsv1.2']},
				              {cacertfile, "cacerts.pem"},
					      {reuse_session, ID1}]).
{ok,{sslsocket,{gen_tcp,#Port&lt;0.18&gt;,tls_connection,
                        undefined}, ...}}

%% This will fail (as it is not saved for reuse)
%% and a full handshake will be performed, we get a new id.
16&gt;  ssl:connection_information(E, [session_id]).
{ok,[{session_id,&lt;&lt;87,46,43,126,175,68,160,153,37,29,
                   196,240,65,160,254,88,65,224,18,63,
                   18,17,174,39,...&gt;&gt;}]}
</code>

    <p>On the server side the the <c>{reuse_sessions, boolean()}</c> option
      determines if the server will save session data and allow session
      reuse or not. This can be further customized by the option
      <c>{reuse_session, fun()}</c> that may introduce a local policy for
      session reuse.
    </p>

  </section>

  <section>
    <title>Session Tickets and Session Resumption in TLS 1.3</title>

    <p>
    TLS 1.3 introduces a new secure way of resuming sessions by using session tickets.
    A session ticket is an opaque data structure that is sent in the pre_shared_key extension of
    a ClientHello, when a client attempts to resume a session with keying material from a
    previous successful handshake.</p>
    <p>Session tickets can be stateful or stateless. A stateful session ticket is a database reference
    (session ticket store) and used with stateful servers, while a stateless ticket
    is a self-encrypted and self-authenticated data structure with cryptographic keying material and
    state data, enabling session resumption with stateless servers.</p>
    <p>The choice between stateful or stateless depends on the server requirements as the session tickets
    are opaque for the clients. Generally, stateful tickets are smaller and the server can guarantee
    that tickets are only used once. Stateless tickets contain additional data, require less storage
    on the server side, but they offer different guarantees against anti-replay. See also
    <seeguide marker="ssl:using_ssl#anti-replay-protection-in-tls-1.3">
    Anti-Replay Protection in TLS 1.3</seeguide>
    </p>
    <p>Session tickets are sent by servers on newly established TLS connections.
    The number of tickets sent and their lifetime are configurable by application variables. See also
    <seeapp marker="ssl:ssl_app#configuration"> SSL's configuration</seeapp>.</p>
    <p>Session tickets are protected by application traffic keys, and in stateless
    tickets, the opaque data structure itself is self-encrypted.</p>

    <p>An example with automatic and manual session resumption:</p>

    <code type="erl">
      {ok, _} = application:ensure_all_started(ssl).
      LOpts = [{certs_keys, [#{certfile => "cert.pem",
                               keyfile => "key.pem"}]},
               {versions, ['tlsv1.2','tlsv1.3']},
               {session_tickets, stateless}].
      {ok, LSock} = ssl:listen(8001, LOpts).
      {ok, CSock} = ssl:transport_accept(LSock).
    </code>

    <p><em>Step 2 (client):</em> Start the client and connect to server:</p>
    <code type="erl">
      {ok, _} = application:ensure_all_started(ssl).
      COpts = [{cacertfile, "cert.pem"},
               {versions, ['tlsv1.2','tlsv1.3']},
               {log_level, debug},
               {session_tickets, auto}].
      ssl:connect("localhost", 8001, COpts).
    </code>

    <p><em>Step 3 (server):</em> Start the TLS handshake:</p>
    <code type="erl">
      ssl:handshake(CSock).
    </code>

    <p>A connection is established using a full handshake.
    Below is a summary of the exchanged messages:</p>
    <code type="erl">
      <![CDATA[>>>]]> TLS 1.3 Handshake, ClientHello ...
      <![CDATA[<<<]]> TLS 1.3 Handshake, ServerHello ...
      <![CDATA[<<<]]> Handshake, EncryptedExtensions ...
      <![CDATA[<<<]]> Handshake, Certificate ...
      <![CDATA[<<<]]> Handshake, CertificateVerify ...
      <![CDATA[<<<]]> Handshake, Finished ...
      <![CDATA[>>>]]> Handshake, Finished ...
      <![CDATA[<<<]]> Post-Handshake, NewSessionTicket ...
    </code>

    <p>At this point the client has stored the received session
    tickets and ready to use them when establishing new connections to
    the same server.</p>

    <p><em>Step 4 (server):</em> Accept a new connection on the server:</p>
    <code type="erl">
      {ok, CSock2} = ssl:transport_accept(LSock).
    </code>

    <p><em>Step 5 (client):</em> Make a new connection:</p>
    <code type="erl">
      ssl:connect("localhost", 8001, COpts).
    </code>

    <p><em>Step 6 (server):</em> Start the handshake:</p>
    <code type="erl">
      ssl:handshake(CSock2).
    </code>

    <p>The second connection is a session resumption using keying material
    from the previous handshake:</p>
    <code type="erl">
      <![CDATA[>>>]]> TLS 1.3 Handshake, ClientHello ...
      <![CDATA[<<<]]> TLS 1.3 Handshake, ServerHello ...
      <![CDATA[<<<]]> Handshake, EncryptedExtensions ...
      <![CDATA[<<<]]> Handshake, Finished ...
      <![CDATA[>>>]]> Handshake, Finished ...
      <![CDATA[<<<]]> Post-Handshake, NewSessionTicket ...
    </code>

    <p>Manual handling of session tickets is also supported. In manual mode, it is the
    responsibility of the client to handle received session tickets.</p>

    <p><em>Step 7 (server):</em> Accept a new connection on the server:</p>
    <code type="erl">
      {ok, CSock3} = ssl:transport_accept(LSock).
    </code>

    <p><em>Step 8 (client):</em> Make a new connection to server:</p>
    <code type="erl">
      {ok, _} = application:ensure_all_started(ssl).
      COpts2 = [{cacertfile, "cacerts.pem"},
                {versions, ['tlsv1.2','tlsv1.3']},
                {log_level, debug},
                {session_tickets, manual}].
      ssl:connect("localhost", 8001, COpts).
    </code>

    <p><em>Step 9 (server):</em> Start the handshake:</p>
    <code type="erl">
      ssl:handshake(CSock3).
    </code>

    <p>After the handshake is performed, the user process receivess
    messages with the tickets sent by the server.</p>

    <p><em>Step 10 (client):</em> Receive a new session ticket:</p>
    <code type="erl">
      Ticket = receive {ssl, session_ticket, {_, TicketData}} -> TicketData end.
    </code>

    <p><em>Step 11 (server):</em> Accept a new connection on the server:</p>
    <code type="erl">
      {ok, CSock4} = ssl:transport_accept(LSock).
    </code>

    <p><em>Step 12 (client):</em> Initiate a new connection to the server with the session ticket
    received in Step 10:</p>
    <code type="erl">
      {ok, _} = application:ensure_all_started(ssl).
      COpts2 = [{cacertfile, "cert.pem"},
                {versions, ['tlsv1.2','tlsv1.3']},
                {log_level, debug},
                {session_tickets, manual},
                {use_ticket, [Ticket]}].
      ssl:connect("localhost", 8001, COpts).
    </code>

    <p><em>Step 13 (server):</em> Start the handshake:</p>
    <code type="erl">
      ssl:handshake(CSock3).
    </code>
</section>


  <section>
    <title>Early Data in TLS 1.3</title>
    <p>TLS 1.3 allows clients to send data on the first flight if the endpoints have
    a shared crypographic secret (pre-shared key). This means that clients can send
    early data if they have a valid session ticket received in a previous
    successful handshake. For more information about session resumption see
    <seeguide marker="ssl:using_ssl#session-tickets-and-session-resumption-in-tls-1.3">
    Session Tickets and Session Resumption in TLS 1.3</seeguide>.
    </p>
    <p>The security properties of Early Data are weaker than other kinds of TLS data.
    This data is not forward secret, and it is vulnerable to replay attacks. For available
    mitigation strategies see
    <seeguide marker="ssl:using_ssl#anti-replay-protection-in-tls-1.3">
    Anti-Replay Protection in TLS 1.3</seeguide>.</p>
    <p>In normal operation, clients will not know which, if any, of the available mitigation
    strategies servers actually implement, and hence must only send early data which
    they deem safe to be replayed. For example, idempotent HTTP operations, such as HEAD and
    GET, can usually be regarded as safe but even they can be exploited by a large number of
    replays causing resource limit exhaustion and other similar problems.</p>
    <p>An example of sending early data with automatic and manual session ticket handling:</p>
    <warning>
    <p>The Early Data feature is experimental in this version of OTP.
    </p>
    </warning>

    <p><em>Server (with NSS key logging)</em></p>
    <code type="none">
    early_data_server() ->
        application:load(ssl),
        {ok, _} = application:ensure_all_started(ssl),
        Port = 11029,
        LOpts = [{certs_keys, [#{certfile => "cert.pem", keyfile => "key.pem"}]},
        {reuseaddr, true},
        {versions, ['tlsv1.2','tlsv1.3']},
        {session_tickets, stateless},
        {early_data, enabled},
        {keep_secrets, true} %% Enable NSS key log (debug option)
        ],
        {ok, LSock} = ssl:listen(Port, LOpts),
        %% Accept first connection
        {ok, CSock0} = ssl:transport_accept(LSock),
        {ok, _} = ssl:handshake(CSock0),
        %% Accept second connection
        {ok, CSock1} = ssl:transport_accept(LSock),
        {ok, Sock} = ssl:handshake(CSock1),
        Sock.
    </code>
    <p><em>Exporting the secrets (optional)</em></p>
    <code type="none">
    {ok, [{keylog, KeylogItems}]} = ssl:connection_information(Sock, [keylog]).
    file:write_file("key.log", [[KeylogItem,$\n] || KeylogItem &lt;- KeylogItems]).
    </code>
    <p><em>Client (automatic ticket handling):</em></p>
    <code type="erl">
    early_data_auto() -&gt;
        %% First handshake 1-RTT - get session tickets
	application:load(ssl),
	{ok, _} = application:ensure_all_started(ssl),
	Port = 11029,
	Data = &lt;&lt;"HEAD / HTTP/1.1\r\nHost: \r\nConnection: close\r\n"&gt;&gt;,
	COpts0 = [{cacertfile, "cacerts.pem"},
	          {versions, ['tlsv1.2', 'tlsv1.3']},
	          {session_tickets, auto}],
        {ok, Sock0} = ssl:connect("localhost", Port, COpts0),

        %% Wait for session tickets
	timer:sleep(500),
	%% Close socket if server cannot handle multiple
        %% connections e.g. openssl s_server
	ssl:close(Sock0),

        %% Second handshake 0-RTT
	COpts1 = [{cacertfile,  "cacerts.pem"},
	          {versions, ['tlsv1.2', 'tlsv1.3']},
		  {session_tickets, auto},
		  {early_data, Data}],
        {ok, Sock} = ssl:connect("localhost", Port, COpts1),
	Sock.
    </code>
    <p><em>Client (manual ticket handling):</em></p>
    <code type="erl">
    early_data_manual() -&gt;
        %% First handshake 1-RTT - get session tickets
	application:load(ssl),
	{ok, _} = application:ensure_all_started(ssl),
	Port = 11029,
	Data = &lt;&lt;"HEAD / HTTP/1.1\r\nHost: \r\nConnection: close\r\n"&gt;&gt;,
	COpts0 = [{cacertfile, "cacerts.pem"},
	          {versions, ['tlsv1.2', 'tlsv1.3']},
	          {session_tickets, manual}],
        {ok, Sock0} = ssl:connect("localhost", Port, COpts0),

        %% Wait for session tickets
	Ticket =
	    receive
	        {ssl, session_ticket, Ticket0} ->
		    Ticket0
            end,

       %% Close socket if server cannot handle multiple connections
       %% e.g. openssl s_server
       ssl:close(Sock0),

       %% Second handshake 0-RTT
       COpts1 = [{cacertfile, "cacerts.pem"},
                 {versions, ['tlsv1.2', 'tlsv1.3']},
		 {session_tickets, manual},
		 {use_ticket, [Ticket]},
		 {early_data, Data}],
       {ok, Sock} = ssl:connect("localhost", Port, COpts1),
       Sock.
    </code>
  </section>

  <section>
    <title>Anti-Replay Protection in TLS 1.3</title>

    <p>The TLS 1.3 protocol does not provide inherent protection for replay of 0-RTT data but
    describes mechanisms that SHOULD be implemented by compliant server implementations.
    The implementation of TLS 1.3 in the SSL application employs all standard methods
    to prevent potential threats.
    </p>
    <p><em>Single-use tickets</em></p>
    <p>This mechanism is available with stateful session tickets. Session tickets can
    only be used once, subsequent use of the same ticket results in a full handshake.
    Stateful servers enforce this rule by maintaining a database of outstanding valid
    tickets.</p>

    <p><em>Client Hello Recording</em></p>
    <p>This mechanism is available with stateless session tickets. The server records
    a unique value derived from the ClientHello (PSK binder) in a given time window. The
    ticket's age is verified by using both the "obsfuscated_ticket_age" and an additional
    timestamp encrypted in the ticket data. As the used datastore allows false positives,
    apparent replays will be answered by doing a full 1-RTT handshake.</p>

    <p><em>Freshness Checks</em></p>
    <p>This mechanism is available with the stateless session tickets. As the ticket data
    has an embedded timestamp, the server can determine if a ClientHello was sent reasonably
    recently and accept the 0-RTT handshake, otherwise if falls back to a full 1-RTT
    handshake. This mechanism is tightly coupled with the previous one, it prevents storing an
    unlimited number of ClientHellos.</p>

    <p>The current implementation uses a pair of Bloom filters to implement the last two mechanisms.
    Bloom filters are fast, memory-efficient, probabilistic data structures that can tell
    if an element may be in a set or if it is definitely not in the set.</p>

    <p>If the option <seetype marker="ssl:ssl#anti_replay">anti_replay</seetype>
    is defined in the server, a pair of Bloom filters (<em>current</em> and
    <em>old</em>) are used to record incoming ClientHello messages (it is the unique
    binder value that is actually stored).
    The <em>current</em> Bloom filter is used for <c>WindowSize</c> seconds to store new
    elements. At the end of the time window the Bloom filters are rotated
    (the <em>current</em> Bloom filter becomes the <em>old</em> and an empty Bloom filter
    is set as <em>current</em>.
    </p>

    <p>The Anti-Replay protection feature in stateless servers executes in the following steps
    when a new ClientHello is received:</p>
    <list type="bulleted">
      <item><p>Reported ticket age (obfuscated ticket age) shall be
      less than ticket lifetime.</p></item>
      <item><p>Actual ticket age shall be less than the ticket lifetime (stateless session
      tickets contain the servers timestamp when the ticket was issued).</p></item>
      <item><p>ClientHello created with the ticket shall be sent relatively recently (freshness checks).</p></item>
      <item><p>If all above checks passed both <em>current</em> and <em>old</em> Bloom filters
      are checked to detect if binder was already seen. Being a probabilistic data structure,
      false positives can occur and they trigger a full handshake.</p></item>
      <item><p>If the binder is not seen, the binder is validated. If the binder is valid,
      the server proceeds with the 0-RTT handshake.</p></item>
    </list>

  </section>

  <section>
    <title>Using DTLS</title>

 <p> Using DTLS has basically the same API as TLS. You need to add the option {protocol, dtls} to the connect and listen functions. For example</p>

 <code type="erl"> client> {ok, Socket} = ssl:connect("localhost", 9999, [{protocol, dtls},
{verify, verify_peer},{cacertfile, "cacerts.pem"}], infinity).
{ok,{sslsocket, [...]}}</code> 
 </section>
 </chapter>