-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathssl.ex
More file actions
523 lines (430 loc) · 15.1 KB
/
ssl.ex
File metadata and controls
523 lines (430 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
# Version 2, December 2004
#
# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
# TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
#
# 0. You just DO WHAT THE FUCK YOU WANT TO.
defmodule Socket.SSL do
@moduledoc """
This module allows usage of SSL sockets and promotion of TCP sockets to SSL
sockets.
## Options
When creating a socket you can pass a series of options to use for it.
* `:cert` can either be an encoded certificate or `[path:
"path/to/certificate"]`
* `:key` can either be an encoded certificate, `[path: "path/to/key"]`, `[rsa:
"rsa encoded"]` or `[dsa: "dsa encoded"]` or `[ec: "ec encoded"]`
* `:authorities` can iehter be an encoded authorities or `[path:
"path/to/authorities"]`
* `:dh` can either be an encoded dh or `[path: "path/to/dh"]`
* `:verify` can either be `false` to disable peer certificate verification,
or a keyword list containing a `:function` and an optional `:data`
* `:password` the password to use to decrypt certificates
* `:renegotiation` if it's set to `:secure` renegotiation will be secured
* `:ciphers` is a list of ciphers to allow
* `:advertised_protocols` is a list of strings representing the advertised
protocols for NPN
* `:preferred_protocols` is a list of strings representing the preferred next
protocols for NPN
You can also pass TCP options.
## Smart garbage collection
Normally sockets in Erlang are closed when the controlling process exits,
with smart garbage collection the controlling process will be the
`Socket.Manager` and it will be closed when there are no more references to
it.
"""
use Socket.Helpers
require Record
@opaque t :: port
@doc """
Get the list of supported ciphers.
"""
@spec ciphers :: [:ssl.erl_cipher_suite]
def ciphers do
:ssl.cipher_suites
end
@doc """
Get the list of supported SSL/TLS versions.
"""
@spec versions :: [tuple]
def versions do
:ssl.versions
end
@doc """
Return a proper error string for the given code or nil if it can't be
converted.
"""
@spec error(term) :: String.t
def error(code) do
case :ssl.format_error(code) do
'Unexpected error:' ++ _ ->
nil
message ->
message |> to_string
end
end
@doc """
Connect to the given address and port tuple or SSL connect the given socket.
"""
@spec connect(Socket.t | { Socket.t, :inet.port_number }) :: { :ok, t } | { :error, term }
def connect({ address, port }) do
connect(address, port)
end
def connect(socket) do
connect(socket, [])
end
@doc """
Connect to the given address and port tuple or SSL connect the given socket,
raising if an error occurs.
"""
@spec connect!(Socket.t | { Socket.t, :inet.port_number }) :: t | no_return
defbang connect(socket_or_descriptor)
@doc """
Connect to the given address and port tuple with the given options or SSL
connect the given socket with the given options or connect to the given
address and port.
"""
@spec connect({ Socket.Address.t, :inet.port_number } | Socket.t | Socket.Address.t, Keyword.t | :inet.port_number) :: { :ok, t } | { :error, term }
def connect({ address, port }, options) when options |> is_list do
connect(address, port, options)
end
def connect(wrap, options) when options |> is_list do
wrap = unless wrap |> is_port do
wrap.to_port
else
wrap
end
timeout = options[:timeout] || :infinity
options = Keyword.delete(options, :timeout)
:ssl.connect(wrap, options, timeout)
end
def connect(address, port) when port |> is_integer do
connect(address, port, [])
end
@doc """
Connect to the given address and port tuple with the given options or SSL
connect the given socket with the given options or connect to the given
address and port, raising if an error occurs.
"""
@spec connect!({ Socket.Address.t, :inet.port_number } | Socket.t | Socket.Address.t, Keyword.t | :inet.port_number) :: t | no_return
defbang connect(descriptor, options)
@doc """
Connect to the given address and port with the given options.
"""
@spec connect(Socket.Address.t, :inet.port_number, Keyword.t) :: { :ok, t } | { :error, term }
def connect(address, port, options) do
address = if address |> is_binary do
String.to_charlist(address)
else
address
end
timeout = options[:timeout] || :infinity
options = Keyword.delete(options, :timeout)
:ssl.connect(address, port, arguments(options), timeout)
end
@doc """
Connect to the given address and port with the given options, raising if an
error occurs.
"""
@spec connect!(Socket.Address.t, :inet.port_number, Keyword.t) :: t | no_return
defbang connect(address, port, options)
@doc """
Create an SSL socket listening on an OS chosen port, use `local` to know the
port it was bound on.
"""
@spec listen :: { :ok, t } | { :error, term }
def listen do
listen(0, [])
end
@doc """
Create an SSL socket listening on an OS chosen port, use `local` to know the
port it was bound on, raising in case of error.
"""
@spec listen! :: t | no_return
defbang listen
@doc """
Create an SSL socket listening on an OS chosen port using the given options or
listening on the given port.
"""
@spec listen(:inet.port_number | Keyword.t) :: { :ok, t } | { :error, term }
def listen(port) when port |> is_integer do
listen(port, [])
end
def listen(options) do
listen(0, options)
end
@doc """
Create an SSL socket listening on an OS chosen port using the given options
or listening on the given port, raising in case of error.
"""
@spec listen!(:inet.port_number | Keyword.t) :: t | no_return
defbang listen(port_or_options)
@doc """
Create an SSL socket listening on the given port and using the given options.
"""
@spec listen(:inet.port_number, Keyword.t) :: { :ok, t } | { :error, term }
def listen(port, options) do
options = Keyword.put(options, :mode, :passive)
options = Keyword.put_new(options, :reuse, true)
:ssl.listen(port, arguments(options))
end
@doc """
Create an SSL socket listening on the given port and using the given options,
raising in case of error.
"""
@spec listen!(:inet.port_number, Keyword.t) :: t | no_return
defbang listen(port, options)
@doc """
Accept a connection from a listening SSL socket or start an SSL connection on
the given client socket.
"""
@spec accept(Socket.t | t) :: { :ok, t } | { :error, term }
def accept(self) do
accept(self, [])
end
@doc """
Accept a connection from a listening SSL socket or start an SSL connection on
the given client socket, raising if an error occurs.
"""
@spec accept!(Socket.t | t) :: t | no_return
defbang accept(socket)
@doc """
Accept a connection from a listening SSL socket with the given options or
start an SSL connection on the given client socket with the given options.
"""
@spec accept(Socket.t, Keyword.t) :: { :ok, t } | { :error, term }
def accept(socket, options) when socket |> Record.is_record(:sslsocket) do
timeout = options[:timeout] || :infinity
with { :ok, socket } <- socket |> :ssl.transport_accept(timeout),
:ok <- if(options[:mode] == :active, do: socket |> :ssl.setopts([{ :active, true }]), else: :ok),
:ok <- socket |> handshake(timeout: timeout)
do
{ :ok, socket }
else
{ :error, reason } ->
{ :error, reason }
end
end
def accept(wrap, options) when wrap |> is_port do
timeout = options[:timeout] || :infinity
options = Keyword.delete(options, :timeout)
:ssl.ssl_accept(wrap, arguments(options), timeout)
end
@doc """
Accept a connection from a listening SSL socket with the given options or
start an SSL connection on the given client socket with the given options,
raising if an error occurs.
"""
@spec accept!(Socket.t, t | Keyword.t) :: t | no_return
defbang accept(socket, options)
@doc """
Execute the handshake; useful if you want to delay the handshake to make it
in another process.
"""
@spec handshake(t) :: :ok | { :error, term }
@spec handshake(t, Keyword.t) :: :ok | { :error, term }
def handshake(socket, options \\ []) when socket |> Record.is_record(:sslsocket) do
timeout = options[:timeout] || :infinity
:ssl.ssl_accept(socket, timeout)
end
@doc """
Execute the handshake, raising if an error occurs; useful if you want to
delay the handshake to make it in another process.
"""
@spec handshake!(t) :: :ok | no_return
@spec handshake!(t, Keyword.t) :: :ok | no_return
defbang handshake(socket)
defbang handshake(socket, options)
@doc """
Set the process which will receive the messages.
"""
@spec process(t | port, pid) :: :ok | { :error, :closed | :not_owner | Error.t }
def process(socket, pid) when socket |> Record.is_record(:sslsocket) do
:ssl.controlling_process(socket, pid)
end
@doc """
Set the process which will receive the messages, raising if an error occurs.
"""
@spec process!(t | port, pid) :: :ok | no_return
def process!(socket, pid) do
case process(socket, pid) do
:ok ->
:ok
:closed ->
raise RuntimeError, message: "the socket is closed"
:not_owner ->
raise RuntimeError, message: "the current process isn't the owner"
code ->
raise Socket.Error, reason: code
end
end
@doc """
Set options of the socket.
"""
@spec options(t | :ssl.sslsocket, Keyword.t) :: :ok | { :error, Socket.Error.t }
def options(socket, options) when socket |> Record.is_record(:sslsocket) do
:ssl.setopts(socket, arguments(options))
end
@doc """
Set options of the socket, raising if an error occurs.
"""
@spec options!(t | Socket.SSL.t | port, Keyword.t) :: :ok | no_return
defbang options(socket, options)
@doc """
Convert SSL options to `:ssl.setopts` compatible arguments.
"""
@spec arguments(Keyword.t) :: list
def arguments(options) do
options = Enum.group_by(options, fn
{ :server_name, _ } -> true
{ :cert, _ } -> true
{ :key, _ } -> true
{ :authorities, _ } -> true
{ :sni, _ } -> true
{ :dh, _ } -> true
{ :verify, _ } -> true
{ :password, _ } -> true
{ :renegotiation, _ } -> true
{ :ciphers, _ } -> true
{ :depth, _ } -> true
{ :identity, _ } -> true
{ :versions, _ } -> true
{ :alert, _ } -> true
{ :ibernate, _ } -> true
{ :session, _ } -> true
{ :advertised_protocols, _ } -> true
{ :preferred_protocols, _ } -> true
_ -> false
end)
{ local, global } = {
Map.get(options, true, []),
Map.get(options, false, [])
}
Socket.TCP.arguments(global) ++ Enum.flat_map(local, fn
{ :server_name, false } ->
[{ :server_name_indication, :disable }]
{ :server_name, name } ->
[{ :server_name_indication, String.to_charlist(name) }]
{ :cert, [path: path] } ->
[{ :certfile, path }]
{ :cert, cert } ->
[{ :cert, cert }]
{ :key, [path: path] } ->
[{ :keyfile, path }]
{ :key, [rsa: key] } ->
[{ :key, { :RSAPrivateKey, key } }]
{ :key, [dsa: key] } ->
[{ :key, { :DSAPrivateKey, key } }]
{ :key, [ec: key] } ->
[{ :key, { :ECPrivateKey, key } }]
{ :key, key } ->
[{ :key, { :PrivateKeyInfo, key } }]
{ :authorities, [path: path] } ->
[{ :cacertfile, path }]
{ :authorities, ca } ->
[{ :cacerts, ca }]
{ :dh, [path: path] } ->
[{ :dhfile, path }]
{ :dh, dh } ->
[{ :dh, dh }]
{ :sni, sni } ->
Enum.flat_map(sni, fn
{ :hosts, hosts } ->
[{ :sni_hosts, Enum.map(hosts, fn { name, options } ->
{ String.to_charlist(name), arguments(options) }
end) }]
{ :function, fun } ->
[{ :sni_fun, fun }]
end)
{ :verify, false } ->
[{ :verify, :verify_none }]
{ :verify, [function: fun] } ->
[{ :verify, :verify_peer }, { :verify_fun, { fun, nil } }]
{ :verify, [function: fun, data: data] } ->
[{ :verify, :verify_peer }, { :verify_fun, { fun, data } }]
{ :identity, identity } ->
Enum.flat_map(identity, fn
{ :psk, value } ->
[{ :psk_identity, String.to_charlist(value) }]
{ :srp, { first, second } } ->
[{ :srp_identity, { String.to_charlist(first), String.to_charlist(second) } }]
end)
{ :password, password } ->
[{ :password, String.to_charlist(password) }]
{ :renegotiation, :secure } ->
[{ :secure_renegotiate, true }]
{ :ciphers, ciphers } ->
[{ :ciphers, ciphers }]
{ :depth, depth } ->
[{ :depth, depth }]
{ :versions, versions } ->
[{ :versions, versions }]
{ :alert, value } ->
[{ :log_alert, value }]
{ :hibernate, hibernate } ->
[{ :hibernate_after, hibernate }]
{ :session, session } ->
Enum.flat_map(session, fn
{ :reuse, true } ->
[{ :reuse_sessions, true }]
{ :reuse, false } ->
[{ :reuse_sessions, false }]
{ :reuse, fun } when fun |> is_function ->
[{ :reuse_session, fun }]
end)
{ :advertised_protocols, protocols } ->
[{ :next_protocols_advertised, protocols }]
{ :preferred_protocols, protocols } ->
[{ :client_preferred_next_protocols, protocols }]
end)
end
@doc """
Get information about the SSL connection.
"""
@spec info(t) :: { :ok, list } | { :error, term }
def info(socket) when socket |> Record.is_record(:sslsocket) do
:ssl.connection_information(socket)
end
@doc """
Get information about the SSL connection, raising if an error occurs.
"""
@spec info!(t) :: list | no_return
defbang info(socket)
@doc """
Get the certificate of the peer.
"""
@spec certificate(t) :: { :ok, String.t } | { :error, term }
def certificate(socket) when socket |> Record.is_record(:sslsocket) do
:ssl.peercert(socket)
end
@doc """
Get the certificate of the peer, raising if an error occurs.
"""
@spec certificate!(t) :: String.t | no_return
defbang certificate(socket)
@doc """
Get the negotiated protocol.
"""
@spec negotiated_protocol(t) :: String.t | nil
def negotiated_protocol(socket) when socket |> Record.is_record(:sslsocket) do
case :ssl.negotiated_protocol(socket) do
{ :ok, protocol } ->
protocol
{ :error, :protocol_not_negotiated } ->
nil
end
end
@doc """
Renegotiate the secure connection.
"""
@spec renegotiate(t) :: :ok | { :error, term }
def renegotiate(socket) when socket |> Record.is_record(:sslsocket) do
:ssl.renegotiate(socket)
end
@doc """
Renegotiate the secure connection, raising if an error occurs.
"""
@spec renegotiate!(t) :: :ok | no_return
defbang renegotiate(socket)
end