% This LaTeX document was generated using the LaTeX backend of PlDoc, % The SWI-Prolog documentation system \section{library(ssl): Secure Socket Layer (SSL) library} \label{sec:ssl} \begin{tags} \tag{See also} \file{library(socket)}, \file{library(http/http_open)}, \file{library(crypto)} \end{tags} An SSL server and client can be built with the (abstracted) predicate calls from the table below. The \verb$tcp_$ predicates are provided by \file{library(socket)}. The predicate \predref{ssl_context}{3} defines properties of the SSL connection, while \predref{ssl_negotiate}{5} establishes the SSL connection based on the wire streams created by the TCP predicates and the context. \begin{quote} \begin{tabulary}{0.9\textwidth}{|l|l|} \hline \textbf{The SSL Server} & \textbf{The SSL Client} \\ \predref{ssl_context}{3} & \predref{ssl_context}{3} \\ \predref{tcp_socket}{1} & \\ \predref{tcp_accept}{3} & \predref{tcp_connect}{3} \\ \predref{tcp_open_socket}{3} & \predref{stream_pair}{3} \\ \predref{ssl_negotiate}{5} & \predref{ssl_negotiate}{5} \\ \hline \end{tabulary} \end{quote} The library is abstracted to communication over streams, and is not reliant on those streams being directly attached to sockets. The \verb$tcp_$ calls here are simply the most common way to use the library. Other two-way communication channels such as (named), pipes can just as easily be used.\vspace{0.7cm} \begin{description} \predicate[det]{ssl_context}{3}{+Role, -SSL, :Options} Create an \arg{SSL} context. The context defines several properties of the \arg{SSL} connection such as involved keys, preferred encryption, and passwords. After establishing a context, an \arg{SSL} connection can be negotiated using \predref{ssl_negotiate}{5}, turning two arbitrary plain Prolog streams into encrypted streams. This predicate processes the options below. \begin{description} \termitem{host}{+HostName} For the client, the host to which it connects. This option \textit{should} be specified when \arg{Role} is \const{client}. Otherwise, certificate verification may fail when negotiating a secure connection. \termitem{certificate_file}{+FileName} Specify where the certificate file can be found. This can be the same as the \verb$key_file(+FileName)$ option. A server \textit{must} have at least one certificate before clients can connect. A client \textit{must} have a certificate only if the server demands the client to identify itself with a client certificate using the \verb$peer_cert(true)$ option. If a certificate is provided, it is necessary to also provide a matching \textit{private key} via the \predref{key_file}{1} option. To configure multiple certificates, use the option \predref{certificate_key_pairs}{1} instead. Alternatively, use \predref{ssl_add_certificate_key}{4} to add certificates and keys to an existing context. \termitem{key_file}{+FileName} Specify where the private key that matches the certificate can be found. If the key is encrypted with a password, this must be supplied using the \verb$password(+Text)$ or \verb$pem_password_hook(:Goal)$ option. \termitem{certificate_key_pairs}{+Pairs} Alternative method for specifying certificates and keys. The argument is a list of \textit{pairs} of the form Certificate-Key, where each component is a string or an atom that holds, respectively, the PEM-encoded certificate and key. To each certificate, further certificates of the chain can be appended. Multiple types of certificates can be present at the same time to enable different ciphers. Using multiple certificate types with completely independent certificate chains requires OpenSSL 1.0.2 or greater. \termitem{password}{+Text} Specify the password the private key is protected with (if any). If you do not want to store the password you can also specify an application defined handler to return the password (see next option). \arg{Text} is either an atom or string. Using a string is preferred as strings are volatile and local resources. \termitem{pem_password_hook}{:Goal} In case a password is required to access the private key the supplied predicate will be called to fetch it. The hook is called as \verb$call(Goal, +SSL, -Password)$ and typically unifies \arg{Password} with a \textit{string} containing the password. \termitem{require_crl}{+Boolean} If true (default is false), then all certificates will be considered invalid unless they can be verified as not being revoked. You can do this explicity by passing a list of CRL filenames via the \predref{crl}{1} option, or by doing it yourself in the cert_verify_hook. If you specify \verb$require_crl(true)$ and provide neither of these options, verification will necessarily fail \termitem{crl}{+ListOfFileNames} Provide a list of filenames of PEM-encoded CRLs that will be given to the context to attempt to establish that a chain of certificates is not revoked. You must also set \verb$require_crl(true)$ if you want CRLs to actually be checked by OpenSSL. \termitem{cacert_file}{+FileName} Deprecated. Use \predref{cacerts}{1} instead. Specify a file containing certificate keys of \textit{trusted} certificates. The peer is trusted if its certificate is signed (ultimately) by one of the provided certificates. Using the \arg{FileName} \verb$system(root_certificates)$ uses a list of trusted root certificates as provided by the OS. See \predref{system_root_certificates}{1} for details. \termitem{cacerts}{+ListOfCATerms} Specify a list of sources of \textit{trusted} certificates. Each element in the list should be one of the following: \begin{itemize} \item \verb$file(Filename)$: A file containing one or more PEM-encoded certificates \item \verb$certificate(Blob)$: A certificate blob \item \verb$system(root_certificates)$: A special term which refers to the certificates trusted by the host OS. \end{itemize} Additional verification of the peer certificate as well as accepting certificates that are not trusted by the given set can be realised using the hook cert_verify_hook(:Goal). \termitem{cert_verify_hook}{:Goal} The predicate \predref{ssl_negotiate}{5} calls \arg{Goal} as follows: \begin{code} call(Goal, +SSL, +ProblemCertificate, +AllCertificates, +FirstCertificate, +Error) \end{code} In case the certificate was verified by one of the provided certifications from the \verb$cacert_file$ option, Error is unified with the atom \const{verified}. Otherwise it contains the error string passed from OpenSSL. Access will be granted iff the predicate succeeds. See \predref{load_certificate}{2} for a description of the certificate terms. See \predref{cert_accept_any}{5} for a dummy implementation that accepts any certificate. \termitem{cipher_list}{+Atom} Specify a cipher preference list (one or more cipher strings separated by colons, commas or spaces). See \predref{ssl_secure_ciphers}{1}. \termitem{ecdh_curve}{+Atom} Specify a curve for ECDHE ciphers. If this option is not specified, the OpenSSL default parameters are used. With OpenSSL prior to 1.1.0, \const{prime256v1} is used by default. \termitem{peer_cert}{+Boolean} Trigger the request of our peer's certificate while establishing the \arg{SSL} layer. This option is automatically turned on in a client \arg{SSL} socket. It can be used in a server to ask the client to identify itself using an \arg{SSL} certificate. \termitem{close_parent}{+Boolean} If \const{true}, close the raw streams if the \arg{SSL} streams are closed. Default is \const{false}. \termitem{close_notify}{+Boolean} If \const{true} (default is \const{false}), the server sends TLS \verb$close_notify$ when closing the connection. In addition, this mitigates \textit{truncation attacks} for both client and server role: If EOF is encountered without having received a TLS shutdown, an exception is raised. Well-designed protocols are self-terminating, and this attack is therefore very rarely a concern. \termitem{min_protocol_version}{+Atom} Set the \textit{minimum} protocol version that can be negotiated. \arg{Atom} is one of \const{sslv3}, \const{tlsv1}, \verb$tlsv1_1$, \verb$tlsv1_2$ and \verb$tlsv1_3$. This option is available with OpenSSL 1.1.0 and later, and should be used instead of \predref{disable_ssl_methods}{1}. \termitem{max_protocol_version}{+Atom} Set the \textit{maximum} protocol version that can be negotiated. \arg{Atom} is one of \const{sslv3}, \const{tlsv1}, \verb$tlsv1_1$, \verb$tlsv1_2$ and \verb$tlsv1_3$. This option is available with OpenSSL 1.1.0 and later, and should be used instead of \predref{disable_ssl_methods}{1}. \termitem{disable_ssl_methods}{+List} A list of methods to disable. Unsupported methods will be ignored. Methods include \const{sslv2}, \const{sslv3}, \const{sslv23}, \const{tlsv1}, \verb$tlsv1_1$ and \verb$tlsv1_2$. This option is deprecated starting with OpenSSL 1.1.0. Use \predref{min_protocol_version}{1} and \predref{max_protocol_version}{1} instead. \termitem{ssl_method}{+Method} Specify the explicit \arg{Method} to use when negotiating. For allowed values, see the list for \verb$disable_ssl_methods$ above. Using this option is discouraged. When using OpenSSL 1.1.0 or later, this option is ignored, and a version-flexible method is used to negotiate the connection. Using version-specific methods is deprecated in recent OpenSSL versions, and this option will become obsolete and ignored in the future. \termitem{sni_hook}{:Goal} This option provides Server Name Indication (SNI) for \arg{SSL} servers. This means that depending on the host to which a client connects, different options (certificates etc.) can be used for the server. This TLS extension allows you to host different domains using the same IP address and physical machine. When a TLS connection is negotiated with a client that has provided a host name via SNI, the hook is called as follows: \begin{code} call(Goal, +SSL0, +HostName, -SSL) \end{code} Given the current context SSL0, and the host name of the client request, the predicate computes \arg{SSL} which is used as the context for negotiating the connection. The first solution is used. If the predicate fails, the default options are used, which are those of the encompassing \predref{ssl_context}{3} call. In that case, if no default certificate and key are specified, the client connection is rejected. \termitem{alpn_protocols}{+ListOfProtoIdentifiers} Provide a list of acceptable ALPN protocol identifiers as atoms. ALPN support requires OpenSSL 1.0.2 or greater. \termitem{alpn_protocol_hook}{:Goal} This options provides a callback for a server context to use to select an ALPN protocol. It will be called as follows: =\Sequal{} \verb$call(Goal, +SSLCtx0, +ListOfClientProtocols, -SSLCtx1, -SelectedProtocol)$ =\Sequal{} If this option is unset and the \predref{alpn_protocols}{1} option is set, then the first common protocol between client \& server will be selected. \end{description} \begin{arguments} \arg{Role} & is one of \const{server} or \const{client} and denotes whether the \arg{SSL} instance will have a server or client role in the established connection. \\ \arg{SSL} & is a SWI-Prolog \textit{blob} of type \verb$ssl_context$, i.e., the type-test for an \arg{SSL} context is \verb$blob(SSL, ssl_context)$. \\ \end{arguments} \predicate[det]{ssl_upgrade_legacy_options}{2}{+OptionsIn, -Options} Handle deprecated \verb$cacert_file(Spec)$ option and map it to the new \verb$cacerts(+List)$ option. \predicate{ssl_add_certificate_key}{4}{+SSL0, +Certificate, +Key, -SSL} Add an additional certificate/key pair to \arg{SSL0}, yielding \arg{SSL}. \arg{Certificate} and \arg{Key} are either strings or atoms that hold the PEM-encoded certificate plus certificate chain and private key, respectively. Using strings is preferred for security reasons. This predicate allows dual-stack RSA and ECDSA servers (for example), and is an alternative for using the \predref{certificate_key_pairs}{1} option. As of OpenSSL 1.0.2, multiple certificate types with completely independent certificate chains are supported. If a certificate of the same type is added repeatedly to a context, the result is undefined. Currently, up to 12 additional certificates of different types are admissible. \predicate{ssl_set_options}{3}{+SSL0, -SSL, +Options} \arg{SSL} is the same as \arg{SSL0}, except for the options specified in \arg{Options}. The following options are supported: \predref{close_notify}{1}, \predref{close_parent}{1}, \predref{host}{1}, \predref{peer_cert}{1}, \predref{ecdh_curve}{1}, \predref{min_protocol_version}{1}, \predref{max_protocol_version}{1}, \predref{disable_ssl_methods}{1}, \predref{sni_hook}{1}, \predref{cert_verify_hook}{1}, \predref{alpn_protocols}{1}, and \predref{alpn_protocol_hook}{1}. See \predref{ssl_context}{3} for more information about these options. This predicate allows you to tweak existing \arg{SSL} contexts, which can be useful in hooks when creating servers with the HTTP infrastructure. \predicate[semidet]{ssl_property}{2}{+SSL, ?Property} True when \arg{Property} is a property of \arg{SSL}. Defined properties are: \begin{shortlist} \item close_parent(?Bool) \end{shortlist} \begin{tags} \tag{To be done} This version is a very minimal implementation of the generic property interface. Future versions will add more properties and non-determinism. \end{tags} \predicate[det]{ssl_negotiate}{5}{+SSL, +PlainRead, +PlainWrite, -SSLRead, -SSLWrite} Once a connection is established and a read/write stream pair is available, (\arg{PlainRead} and \arg{PlainWrite}), this predicate can be called to negotiate an \arg{SSL} session over the streams. If the negotiation is successful, \arg{SSLRead} and \arg{SSLWrite} are returned. After a successful handshake and finishing the communication the user must close \arg{SSLRead} and \arg{SSLWrite}, for example using \verb$call_cleanup(close(SSLWrite), close(SSLRead))$. If the \arg{SSL} \textit{context} (created with \predref{ssl_context}{3} has the option \verb$close_parent(true)$ (default \const{false}), closing \arg{SSLRead} and \arg{SSLWrite} also closes the original \arg{PlainRead} and \arg{PlainWrite} streams. Otherwise these must be closed explicitly by the user. \begin{tags} \tag{Errors} \verb$ssl_error(Code, LibName, FuncName, Reason)$ is raised if the negotiation fails. The streams \arg{PlainRead} and \arg{PlainWrite} are \textbf{not} closed, but an unknown amount of data may have been read and written. \end{tags} \predicate[semidet]{ssl_peer_certificate}{2}{+Stream, -Certificate} True if the peer certificate is provided (this is always the case for a client connection) and \arg{Certificate} unifies with the peer certificate. The example below uses this to obtain the \textit{Common Name} of the peer after establishing an https client connection: \begin{code} http_open(HTTPS_url, In, []), ssl_peer_certificate(In, Cert), memberchk(subject(Subject), Cert), memberchk('CN' = CommonName), Subject) \end{code} \predicate[det]{ssl_peer_certificate_chain}{2}{+Stream, -Certificates} \arg{Certificates} is the certificate chain provided by the peer, represented as a list of certificates. \predicate[det]{ssl_session}{2}{+Stream, -Session} Retrieves (debugging) properties from the SSL context associated with \arg{Stream}. If \arg{Stream} is not an SSL stream, the predicate raises a domain error. \arg{Session} is a list of properties, containing the members described below. Except for \arg{Version}, all information are byte arrays that are represented as Prolog strings holding characters in the range 0..255. \begin{description} \termitem{ssl_version}{Version} The negotiated version of the session as an integer. \termitem{cipher}{Cipher} The negotiated cipher for this connection. \termitem{session_key}{Key} The key material used in SSLv2 connections (if present). \termitem{master_key}{Key} The key material comprising the master secret. This is generated from the server_random, client_random and pre-master key. \termitem{client_random}{Random} The random data selected by the client during handshaking. \termitem{server_random}{Random} The random data selected by the server during handshaking. \termitem{session_id}{SessionId} The SSLv3 session ID. Note that if ECDHE is being used (which is the default for newer versions of OpenSSL), this data will not actually be sent to the server. \termitem{alpn_protocol}{Protocol} The negotiated ALPN protocol, if supported. If no protocol was negotiated, this will be an empty string. \end{description} \predicate[det]{load_certificate}{2}{+Stream, -Certificate} Loads a certificate from a PEM- or DER-encoded stream, returning a certificate. The fields of the certificate can be inspected using certificate_field(+\arg{Certificate}, ?Field). Note that the OpenSSL \verb$CA.pl$ utility creates certificates that have a human readable textual representation in front of the PEM representation. You can use the following to skip to the certificate if you know it is a PEM certificate: \begin{code} skip_to_pem_cert(In) :- repeat, ( peek_char(In, '-') -> ! ; skip(In, 0'\n), at_end_of_stream(In), ! ). \end{code} \predicate[det]{write_certificate}{3}{+Stream, +Certificate, +Options} Writes a certificate to the stream \arg{Stream}. \arg{Options} is reserved for future use. \predicate[det]{load_crl}{2}{+Stream, -CRL} Loads a \arg{CRL} from a PEM- or DER-encoded stream, returning a term containing terms \predref{hash}{1}, \predref{signature}{1}, \predref{issuer_name}{1} and \predref{revocations}{1}, which is a list of \predref{revoked}{2} terms. Each \predref{revoked}{2} term is of the form \verb$revoked(+Serial, DateOfRevocation)$ \predicate[det]{system_root_certificates}{1}{-List} \arg{List} is a list of trusted root certificates as provided by the OS. This is the list used by \predref{ssl_context}{3} when using the option \verb$system(root_certificates)$. The list is obtained using an OS specific process. The current implementation is as follows: \begin{itemize} \item On Windows, CertOpenSystemStore() is used to import the \verb$"ROOT"$ certificates from the OS. \item On MacOSX, the trusted keys are loaded from the \textit{SystemRootCertificates} key chain. The Apple API for this requires the SSL interface to be compiled with an XCode compiler, i.e., \textbf{not} with native gcc. \item Otherwise, certificates are loaded from a file defined by the Prolog flag \prologflag{system_cacert_filename}. The initial value of this flag is operating system dependent. For security reasons, the flag can only be set prior to using the SSL library. For example: \begin{code} :- use_module(library(ssl)). :- set_prolog_flag(system_cacert_filename, '/home/jan/ssl/ca-bundle.crt'). \end{code} \end{itemize} \predicate[det]{load_private_key}{3}{+Stream, +Password, -PrivateKey} Load a private key \arg{PrivateKey} from the given stream \arg{Stream}, using \arg{Password} to decrypt the key if it is encrypted. Note that the password is currently only supported for PEM files. DER-encoded keys which are password protected will not load. The key must be an RSA or EC key. DH and DSA keys are not supported, and \arg{PrivateKey} will be bound to an atom (dh_key or dsa_key) if you try and load such a key. Otherwise \arg{PrivateKey} will be unified with \verb$private_key(KeyTerm)$ where KeyTerm is an \predref{rsa}{8} term representing an RSA key, or \predref{ec}{3} for EC keys. \predicate[det]{load_public_key}{2}{+Stream, -PublicKey} Load a public key \arg{PublicKey} from the given stream \arg{Stream}. Supports loading both DER- and PEM-encoded keys. The key must be an RSA or EC key. DH and DSA keys are not supported, and \arg{PublicKey} will be bound to an atom (dh_key or dsa_key) if you try and load such a key. Otherwise \arg{PublicKey} will be unified with \verb$public_key(KeyTerm)$ where KeyTerm is an \predref{rsa}{8} term representing an RSA key, or \predref{ec}{3} for EC keys. \predicate[det]{cert_accept_any}{5}{+SSL, +ProblemCertificate, +AllCertificates, +FirstCertificate, +Error} Implementation for the hook `cert_verify_hook(:Hook)` that accepts \textit{any} certificate. This is intended for \predref{http_open}{3} if no certificate verification is desired as illustrated below. \begin{code} http_open('https:/...', In, [ cert_verify_hook(cert_accept_any) ]) \end{code} \predicate{same_certificate}{2}{+CertificateA, +CertificateB} True if \arg{CertificateA} is logically the same as \arg{CertificateB}, even if they are stored in different blobs \predicate{verify_certificate_issuer}{2}{+Certificate, +Issuer} True if \arg{Certificate} is a certificate which was issued by the certificate \arg{Issuer}. \predicate{verify_certificate}{3}{+Certificate, +AuxiliaryCertificates, +TrustedCertificates} True if it is possible to build a chain of trust from \arg{Certificate} to one of the certificates in \arg{TrustedCertificates}, optionally using the (untrusted) certificates in \arg{AuxiliaryCertificates} to complete the chain. To use the system built-in trust store, specify the special term \verb$system(root_certificates)$ for \arg{TrustedCertificates}. \predicate[nondet]{certificate_field}{2}{+Certificate, ?Field} Retrieve the field matching \arg{Field} from \arg{Certificate}. May be one of the following: \begin{itemize} \item \predref{subject}{1} to retrieve the subject \item \predref{issuer}{1} to retrieve the issuer's subject \item \predref{version}{1} to retrieve the version \item \predref{serial}{1} to retrieve the serial number \item \predref{not_before}{1} to retrieve the start date \item \predref{not_after}{1} to retrieve the expiry date \item \predref{public_key}{1} to retrieve the public key \item \predref{crls}{1} to retrieve a list of the CRLs \item \predref{sans}{1} to retrieve a list of the Subject Alternative Names \item \predref{signature}{1} to retrieve the certificate signature \item \predref{signature_algorithm}{1} to retrieve the signing algorithm \item \predref{hash}{1} to retrieve the certificate hash \item \predref{to_be_signed}{1} to retrieve the data on the certificate which must be signed \end{itemize} \predicate[det]{ssl_secure_ciphers}{1}{-Ciphers:atom} \arg{Ciphers} is a secure cipher preference list that can be used in the \predref{cipher_list}{1} option of \predref{ssl_context}{3}. Secure ciphers must guarantee forward secrecy, and must mitigate all known critical attacks. As of 2018, using these ciphers allows you to obtain grade A on \url{https://www.ssllabs.com}. For A+, you must also enable HTTP Strict Transport Security (HSTS) by sending a suitable header field in replies. Note that obsolete ciphers \textbf{must} be disabled to reliably prevent protocol downgrade attacks. The \arg{Ciphers} list is read from the setting \verb$ssl:secure_ciphers$ and can be controlled using \predref{set_setting}{2} and other predicates from \file{library(settings)}. \textbf{BEWARE}: This list must be changed when attacks on these ciphers become known! Keep an eye on this setting and adapt it as necessary in the future. \end{description}