ssl
Interface Functions for Secure Socket Layer
This module contains interface functions to the Secure Socket Layer.
SSL
- ssl requires the crypto and public_key applications.
- Supported SSL/TLS-versions are SSL-3.0, TLS-1.0, TLS-1.1 and TLS-1.2.
- For security reasons sslv2 is not supported.
- Ephemeral Diffie-Hellman cipher suites are supported but not Diffie Hellman Certificates cipher suites.
- Elliptic Curve cipher suites are supported if crypto supports it and named curves are used.
- Export cipher suites are not supported as the U.S. lifted its export restrictions in early 2000.
- IDEA cipher suites are not supported as they have become deprecated by the latest TLS spec so there is not any real motivation to implement them.
- CRL and policy certificate extensions are not supported yet. However CRL verification is supported by public_key, only not integrated in ssl yet.
- Support for 'Server Name Indication' extension client side (RFC 6066 section 3).
COMMON DATA TYPES
The following data types are used in the functions below:
boolean() = true | false
option() = socketoption() | ssloption() | transportoption()
socketoption() = proplists:property() - The default socket options are
[{mode,list},{packet, 0},{header, 0},{active, true}].
For valid options see inet(3) and gen_tcp(3).
ssloption() = {verify, verify_type()} |
{verify_fun, {fun(), term()}} |
{fail_if_no_peer_cert, boolean()}
{depth, integer()} |
{cert, der_encoded()}| {certfile, path()} |
{key, {'RSAPrivateKey'| 'DSAPrivateKey' | 'ECPrivateKey' |'PrivateKeyInfo', der_encoded()}} |
{keyfile, path()} | {password, string()} |
{cacerts, [der_encoded()]} | {cacertfile, path()} |
|{dh, der_encoded()} | {dhfile, path()} | {ciphers, ciphers()} |
{user_lookup_fun, {fun(), term()}}, {psk_identity, string()}, {srp_identity, {string(), string()}} |
{ssl_imp, ssl_imp()} | {reuse_sessions, boolean()} | {reuse_session, fun()}
{next_protocols_advertised, [binary()]} |
{client_preferred_next_protocols, {client | server, [binary()]} | {client | server, [binary()], binary()}} |
{log_alert, boolean()} | {server_name_indication, hostname() | disable}
transportoption() = {cb_info, {CallbackModule::atom(), DataTag::atom(), ClosedTag::atom(), ErrTag:atom()}}
- defaults to {gen_tcp, tcp, tcp_closed, tcp_error}. Can be used to customize
the transport layer. The callback module must implement a reliable transport
protocol and behave as gen_tcp and in addition have functions corresponding to
inet:setopts/2, inet:getopts/2, inet:peername/1, inet:sockname/1 and inet:port/1.
The callback gen_tcp is treated specially and will call inet directly.
CallbackModule =
atom()
DataTag =
atom() - tag used in socket data message.
ClosedTag = atom() - tag used in
socket close message.
verify_type() = verify_none | verify_peer
path() = string() - representing a file path.
der_encoded() = binary() -Asn1 DER encoded entity as an erlang binary.
host() = hostname() | ipaddress()
hostname() = string()
ip_address() = {N1,N2,N3,N4} % IPv4
| {K1,K2,K3,K4,K5,K6,K7,K8} % IPv6
sslsocket() - opaque to the user.
protocol() = sslv3 | tlsv1 | 'tlsv1.1' | 'tlsv1.2'
ciphers() = [ciphersuite()] | string() (according to old API)
ciphersuite() =
{key_exchange(), cipher(), hash()}
key_exchange() = rsa | dhe_dss | dhe_rsa | dh_anon
| psk | dhe_psk | rsa_psk | srp_anon | srp_dss | srp_rsa
| ecdh_anon | ecdh_ecdsa | ecdhe_ecdsa | ecdh_rsa | ecdhe_rsa
cipher() = rc4_128 | des_cbc | '3des_ede_cbc'
| aes_128_cbc | aes_256_cbc
hash() = md5 | sha
prf_random() = client_random | server_random
srp_param_type() = srp_1024 | srp_1536 | srp_2048 | srp_3072
| srp_4096 | srp_6144 | srp_8192
SSL OPTION DESCRIPTIONS - COMMON for SERVER and CLIENT
Options described here are options that are have the same meaning in the client and the server.
cipher_suites/0
can be used to find all ciphers that are
supported by default. cipher_suites(all)
may be called
to find all available cipher suites.
Pre-Shared Key (The verification fun should be defined as:
fun(OtpCert :: #'OTPCertificate'{}, Event :: {bad_cert, Reason :: atom()} |
{extension, #'Extension'{}}, InitialUserState :: term()) ->
{valid, UserState :: term()} | {valid_peer, UserState :: term()} |
{fail, Reason :: term()} | {unknown, UserState :: term()}.
The verify fun will be called during the X509-path validation when an error or an extension unknown to the ssl application is encountered. Additionally it will be called when a certificate is considered valid by the path validation to allow access to each certificate in the path to the user application. Note that it will differentiate between the peer certificate and CA certificates by using valid_peer or valid as the second argument to the verify fun. See the public_key User's Guide for definition of #'OTPCertificate'{} and #'Extension'{}.
If the verify callback fun returns {fail, Reason}, the verification process is immediately stopped and an alert is sent to the peer and the TLS/SSL handshake is terminated. If the verify callback fun returns {valid, UserState}, the verification process is continued. If the verify callback fun always returns {valid, UserState}, the TLS/SSL handshake will not be terminated with respect to verification failures and the connection will be established. If called with an extension unknown to the user application the return value {unknown, UserState} should be used.
The default verify_fun option in verify_peer mode:
{fun(_,{bad_cert, _} = Reason, _) ->
{fail, Reason};
(_,{extension, _}, UserState) ->
{unknown, UserState};
(_, valid, UserState) ->
{valid, UserState};
(_, valid_peer, UserState) ->
{valid, UserState}
end, []}
The default verify_fun option in verify_none mode:
{fun(_,{bad_cert, _}, UserState) ->
{valid, UserState};
(_,{extension, _}, UserState) ->
{unknown, UserState};
(_, valid, UserState) ->
{valid, UserState};
(_, valid_peer, UserState) ->
{valid, UserState}
end, []}
Possible path validation errors:
{bad_cert, cert_expired}, {bad_cert, invalid_issuer}, {bad_cert, invalid_signature}, {bad_cert, unknown_ca},{bad_cert, selfsigned_peer}, {bad_cert, name_not_permitted}, {bad_cert, missing_basic_constraint}, {bad_cert, invalid_key_usage}
protocol_version
. If the
environment option is not set it defaults to all versions supported by the SSL application. See also
ssl(6)
ssl_connection
will go into hibernation after the specified number of milliseconds
of inactivity, thus reducing its memory footprint. When
undefined
is specified (this is the default), the process
will never go into hibernation.
The lookup fun should be defined as:
fun(psk, PSKIdentity ::string(), UserState :: term()) ->
{ok, SharedSecret :: binary()} | error;
fun(srp, Username :: string(), UserState :: term()) ->
{ok, {SRPParams :: srp_param_type(), Salt :: binary(), DerivedKey :: binary()}} | error.
For Pre-Shared Key (PSK) cipher suites, the lookup fun will be called by the client and server to determine the shared secret. When called by the client, PSKIdentity will be set to the hint presented by the server or undefined. When called by the server, PSKIdentity is the identity presented by the client.
For Secure Remote Password (SRP), the fun will only be used by the server to obtain
parameters that it will use to generate its session keys. DerivedKey
should be
derived according to crypto:sha([Salt, crypto:sha([Username, <<$:>>, Password])])
SSL OPTION DESCRIPTIONS - CLIENT SIDE
Options described here are client specific or has a slightly different meaning in the client than in the server.
Indicates the client will try to perform Next Protocol Negotiation.
If precedence is server the negotiated protocol will be the first protocol that appears on the server advertised list that is also on the client preference list.
If precedence is client the negotiated protocol will be the first protocol that appears on the client preference list that is also on the server advertised list.
If the client does not support any of the server advertised protocols or the server does not advertise any protocols the client will fallback to the first protocol in its list or if a default is supplied it will fallback to that instead. If the server does not support Next Protocol Negotiation the connection will be aborted if no default protocol is supplied.
This option can be specified when upgrading a TCP socket to a TLS socket to use the TLS Server Name Indication extension.
When starting a TLS connection without upgrade the Server Name Indication extension will be sent if possible, this option may also be used to disable that behavior.
SSL OPTION DESCRIPTIONS - SERVER SIDE
Options described here are server specific or has a slightly different meaning in the server than in the client.
reuse_sessions
is set to true.
SuggestedSessionId is a binary(), PeerCert is a DER encoded
certificate, Compression is an enumeration integer
and CipherSuite is of type ciphersuite().
negotiated_next_protocol/1
method.
General
When an ssl socket is in active mode (the default), data from the socket is delivered to the owner of the socket in the form of messages:
- {ssl, Socket, Data}
- {ssl_closed, Socket}
- {ssl_error, Socket, Reason}
A Timeout
argument specifies a timeout in milliseconds. The
default value for a Timeout
argument is infinity
.
Functions
cipher_suites() ->
cipher_suites(Type) -> ciphers()
Type = erlang | openssl | all
Returns a list of supported cipher suites. cipher_suites() is equivalent to cipher_suites(erlang). Type openssl is provided for backwards compatibility with old ssl that used openssl. cipher_suites(all) returns all available cipher suites. The cipher suites not present in cipher_suites(erlang) but in included in cipher_suites(all) will not be used unless explicitly configured by the user.
connect(Socket, SslOptions) ->
connect(Socket, SslOptions, Timeout) -> {ok, SslSocket} | {error, Reason}
Socket = socket()
SslOptions = [ssloption()]
Timeout = integer() | infinity
SslSocket = sslsocket()
Reason = term()
Upgrades a gen_tcp, or equivalent, connected socket to an ssl socket i.e. performs the client-side ssl handshake.
connect(Host, Port, Options) ->
connect(Host, Port, Options, Timeout) -> {ok, SslSocket} | {error, Reason}
Host = host()
Port = integer()
Options = [option()]
Timeout = integer() | infinity
SslSocket = sslsocket()
Reason = term()
Opens an ssl connection to Host, Port.
close(SslSocket) -> ok | {error, Reason}
SslSocket = sslsocket()
Reason = term()
Close an ssl connection.
controlling_process(SslSocket, NewOwner) -> ok | {error, Reason}
SslSocket = sslsocket()
NewOwner = pid()
Reason = term()
Assigns a new controlling process to the ssl-socket. A controlling process is the owner of an ssl-socket, and receives all messages from the socket.
connection_info(SslSocket) -> {ok, {ProtocolVersion, CipherSuite}} | {error, Reason}
CipherSuite = ciphersuite()
ProtocolVersion = protocol()
Returns the negotiated protocol version and cipher suite.
format_error(Reason) -> string()
Reason = term()
Presents the error returned by an ssl function as a printable string.
getopts(Socket, OptionNames) -> {ok, [socketoption()]} | {error, Reason}
Socket = sslsocket()
OptionNames = [atom()]
Get the value of the specified socket options.
listen(Port, Options) -> {ok, ListenSocket} | {error, Reason}
Port = integer()
Options = options()
ListenSocket = sslsocket()
Creates an ssl listen socket.
peercert(Socket) -> {ok, Cert} | {error, Reason}
Socket = sslsocket()
Cert = binary()
The peer certificate is returned as a DER encoded binary.
The certificate can be decoded with public_key:pkix_decode_cert/2
.
peername(Socket) -> {ok, {Address, Port}} | {error, Reason}
Socket = sslsocket()
Address = ipaddress()
Port = integer()
Returns the address and port number of the peer.
recv(Socket, Length) ->
recv(Socket, Length, Timeout) -> {ok, Data} | {error, Reason}
Socket = sslsocket()
Length = integer()
Timeout = integer()
Data = [char()] | binary()
This function receives a packet from a socket in passive
mode. A closed socket is indicated by a return value
{error, closed}
.
The Length
argument is only meaningful when
the socket is in raw
mode and denotes the number of
bytes to read. If Length
= 0, all available bytes are
returned. If Length
> 0, exactly Length
bytes are returned, or an error; possibly discarding less
than Length
bytes of data when the socket gets closed
from the other side.
The optional Timeout
parameter specifies a timeout in
milliseconds. The default value is infinity
.
prf(Socket, Secret, Label, Seed, WantedLength) -> {ok, binary()} | {error, reason()}
Socket = sslsocket()
Secret = binary() | master_secret
Label = binary()
Seed = [binary() | prf_random()]
WantedLength = non_neg_integer()
Use the pseudo random function (PRF) of a TLS session to generate
additional key material. It either takes user generated values for
Secret
and Seed
or atoms directing it use a specific
value from the session security parameters.
This function can only be used with TLS connections, {error, undefined}
is returned for SSLv3 connections.
renegotiate(Socket) -> ok | {error, Reason}
Socket = sslsocket()
Initiates a new handshake. A notable return value is
{error, renegotiation_rejected}
indicating that the peer
refused to go through with the renegotiation but the connection
is still active using the previously negotiated session.
send(Socket, Data) -> ok | {error, Reason}
Socket = sslsocket()
Data = iodata()
Writes Data
to Socket
.
A notable return value is {error, closed}
indicating that
the socket is closed.
setopts(Socket, Options) -> ok | {error, Reason}
Socket = sslsocket()
Options = [socketoption]()
Sets options according to Options
for the socket
Socket
.
shutdown(Socket, How) -> ok | {error, Reason}
Socket = sslsocket()
How = read | write | read_write
Reason = reason()
Immediately close a socket in one or two directions.
How == write
means closing the socket for writing,
reading from it is still possible.
To be able to handle that the peer has done a shutdown on
the write side, the {exit_on_close, false}
option
is useful.
ssl_accept(ListenSocket) ->
ssl_accept(ListenSocket, Timeout) -> ok | {error, Reason}
ListenSocket = sslsocket()
Timeout = integer()
Reason = term()
The ssl_accept
function establish the SSL connection
on the server side. It should be called directly after
transport_accept
, in the spawned server-loop.
ssl_accept(ListenSocket, SslOptions) ->
ssl_accept(ListenSocket, SslOptions, Timeout) -> {ok, Socket} | {error, Reason}
ListenSocket = socket()
SslOptions = ssloptions()
Timeout = integer()
Reason = term()
Upgrades a gen_tcp, or equivalent, socket to an ssl socket i.e. performs the ssl server-side handshake.
Warning!
Note that the listen socket should be in {active, false} mode before telling the client that the server is ready to upgrade and calling this function, otherwise the upgrade may or may not succeed depending on timing.
sockname(Socket) -> {ok, {Address, Port}} | {error, Reason}
Socket = sslsocket()
Address = ipaddress()
Port = integer()
Returns the local address and port number of the socket
Socket
.
start() ->
start(Type) -> ok | {error, Reason}
Type = permanent | transient | temporary
Starts the Ssl application. Default type is temporary. application(3)
stop() -> ok
Stops the Ssl application. application(3)
transport_accept(Socket) ->
transport_accept(Socket, Timeout) -> {ok, NewSocket} | {error, Reason}
Socket = NewSocket = sslsocket()
Timeout = integer()
Reason = reason()
Accepts an incoming connection request on a listen socket.
ListenSocket
must be a socket returned from
listen/2
. The socket returned should be passed to
ssl_accept
to complete ssl handshaking and
establishing the connection.
Warning!
The socket returned can only be used with ssl_accept
,
no traffic can be sent or received before that call.
The accepted socket inherits the options set for
ListenSocket
in listen/2
.
The default
value for Timeout
is infinity
. If
Timeout
is specified, and no connection is accepted
within the given time, {error, timeout}
is
returned.
versions() -> [{SslAppVer, SupportedSslVer, AvailableSslVsn}]
SslAppVer = string()
SupportedSslVer = [protocol()]
AvailableSslVsn = [protocol()]
Returns version information relevant for the ssl application.
negotiated_next_protocol(Socket) -> {ok, Protocol} | {error, next_protocol_not_negotiated}
Socket = sslsocket()
Protocol = binary()
Returns the Next Protocol negotiated.
SEE ALSO
inet(3) and gen_tcp(3)