View source with formatted comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan van der Steen, Matt Lilley and Jan Wielemaker,
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2004-2020, SWI-Prolog Foundation
    7                              VU University Amsterdam
    8                              CWI, Amsterdam
    9    All rights reserved.
   10
   11    Redistribution and use in source and binary forms, with or without
   12    modification, are permitted provided that the following conditions
   13    are met:
   14
   15    1. Redistributions of source code must retain the above copyright
   16       notice, this list of conditions and the following disclaimer.
   17
   18    2. Redistributions in binary form must reproduce the above copyright
   19       notice, this list of conditions and the following disclaimer in
   20       the documentation and/or other materials provided with the
   21       distribution.
   22
   23    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   24    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   25    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   26    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   27    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   28    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   29    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   30    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   31    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   32    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   33    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   34    POSSIBILITY OF SUCH DAMAGE.
   35*/
   36
   37:- module(ssl,
   38	  [ certificate_field/2,          % +Certificate, ?Field
   39	    load_certificate/2,           % +Stream, -Certificate
   40	    load_private_key/3,           % +Stream, +Password, -Key
   41            load_public_key/2,            % +Stream, -Key
   42	    load_crl/2,                   % +Stream, -Crl
   43	    write_certificate/3,          % +Stream, -X509, +Options
   44            system_root_certificates/1,   % -List
   45            cert_accept_any/5,            % +SSL, +ProblemCertificate,
   46                                          % +AllCertificates, +FirstCertificate,
   47                                          % +Error
   48            same_certificate/2,           % +CertificateA, +CertificateB
   49            ssl_context/3,                % +Role, -Config, :Options
   50            ssl_add_certificate_key/4,    % +Config, +Cert, +Key, -Config
   51            ssl_set_options/3,            % +Config0, -Config, +Options
   52            ssl_property/2,               % +Config, ?Property
   53            ssl_negotiate/5,              % +Config, +PlainRead, +PlainWrite,
   54                                          %          -SSLRead,   -SSLWrite
   55            ssl_peer_certificate/2,       % +Stream, -Certificate
   56            ssl_peer_certificate_chain/2, % +Stream, -Certificates
   57            ssl_session/2,                % +Stream, -Session
   58	    ssl_secure_ciphers/1,         % -Ciphers,
   59	    verify_certificate/3,         % +X509, +AuxiliaryCertificates, +TrustedCertificates
   60	    verify_certificate_issuer/2,  % +Certificate, +IssuerCertificate
   61
   62            ssl_upgrade_legacy_options/2  % +OptionsIn, -OptionsOut
   63          ]).   64:- autoload(library(option),[select_option/4,select_option/3]).   65:- use_module(library(settings),[setting/4,setting/2]).   66
   67:- use_module(library(crypto), []).     % force initialization of libcrypto
   68
   69:- use_foreign_library(foreign(ssl4pl)).   70
   71:- meta_predicate
   72    ssl_context(+, -, :),
   73    ssl_set_options(+, -, :).   74
   75:- predicate_options(ssl_context/3, 3,
   76                     [ host(atom),
   77                       port(integer),
   78                       cacerts(list),
   79                       certificate_file(atom),
   80                       key_file(atom),
   81                       certificate_key_pairs(any),
   82                       password(any),
   83                       cipher_list(any),
   84                       ecdh_curve(any),
   85                       pem_password_hook(callable),
   86                       cacert_file(any),
   87                       crl(any),
   88                       require_crl(boolean),
   89                       cert_verify_hook(callable),
   90                       peer_cert(boolean),
   91                       close_parent(boolean),
   92                       close_notify(boolean),
   93                       sni_hook(callable),
   94                       alpn_protocols(any),
   95                       alpn_protocol_hook(callable)
   96                     ]).   97
   98/** <module> Secure Socket Layer (SSL) library
   99
  100An SSL server and client can be built with the (abstracted)
  101predicate calls from the table below.  The `tcp_` predicates
  102are provided by library(socket).  The predicate ssl_context/3
  103defines properties of the SSL connection, while ssl_negotiate/5
  104establishes the SSL connection based on the wire streams created
  105by the TCP predicates and the context.
  106
  107        | *The SSL Server*      | *The SSL Client*      |
  108        | ssl_context/3         | ssl_context/3         |
  109        | tcp_socket/1          |                       |
  110        | tcp_accept/3          | tcp_connect/3         |
  111        | tcp_open_socket/3     | stream_pair/3         |
  112        | ssl_negotiate/5       | ssl_negotiate/5       |
  113
  114The library is abstracted to communication over streams, and is not
  115reliant on those streams being directly attached to sockets. The `tcp_`
  116calls here are simply the most common way to use the library. Other
  117two-way communication channels such as (named), pipes can just as
  118easily be used.
  119
  120@see library(socket), library(http/http_open), library(crypto)
  121*/
  122
  123:- setting(secure_ciphers, atom,
  124           'EECDH+AESGCM:EDH+AESGCM:EECDH+AES256:EDH+AES256:EECDH+CHACHA20:EDH+CHACHA20',
  125           "Default set of ciphers considered secure").  126
  127%!  ssl_context(+Role, -SSL, :Options) is det.
  128%
  129%   Create an  SSL context.  The context  defines several properties
  130%   of  the   SSL  connection  such  as   involved  keys,  preferred
  131%   encryption, and passwords. After  establishing a context, an SSL
  132%   connection can be negotiated  using ssl_negotiate/5, turning two
  133%   arbitrary  plain Prolog  streams into  encrypted streams.   This
  134%   predicate processes the options below.
  135%
  136%     * host(+HostName)
  137%     For the client, the host to which it connects.  The server
  138%     certificate must be valid for this host.  This option _must_
  139%     be specified when Role is `client`.  Otherwise, certificate
  140%     verification fails with the error `hostname_mismatch` unless
  141%     the cert_verify_hook/5 accepts the certificate.  The option
  142%     peer_cert(false) disables certificate verification.
  143%     * certificate_file(+FileName)
  144%     Specify where the certificate file can be found. This can be the
  145%     same as the key_file(+FileName) option.  A server _must_ have at
  146%     least one certificate before clients can connect. A client
  147%     _must_ have a certificate only if the server demands the client
  148%     to identify itself with a client certificate using the
  149%     peer_cert(true) option. If a certificate is provided, it is
  150%     necessary to also provide a matching _private key_ via the
  151%     key_file/1 option. To configure multiple certificates, use the
  152%     option certificate_key_pairs/1 instead. Alternatively, use
  153%     ssl_add_certificate_key/4 to add certificates and keys to an
  154%     existing context.
  155%     * key_file(+FileName)
  156%     Specify where the private key that matches the certificate can
  157%     be found.  If the key is encrypted with a password, this must
  158%     be supplied using the password(+Text) or
  159%     =|pem_password_hook(:Goal)|= option.
  160%     * certificate_key_pairs(+Pairs)
  161%     Alternative method for specifying certificates and keys. The
  162%     argument is a list of _pairs_ of the form Certificate-Key,
  163%     where each component is a string or an atom that holds,
  164%     respectively, the PEM-encoded certificate and key. To each
  165%     certificate, further certificates of the chain can be
  166%     appended. Multiple types of certificates can be present at
  167%     the same time to enable different ciphers. Using multiple
  168%     certificate types with completely independent certificate
  169%     chains requires OpenSSL 1.0.2 or greater.
  170%     * password(+Text)
  171%     Specify the password the private key is protected with (if
  172%     any). If you do not want to store the password you can also
  173%     specify an application defined handler to return the password
  174%     (see next option).  Text is either an atom or string.  Using
  175%     a string is preferred as strings are volatile and local
  176%     resources.
  177%     * pem_password_hook(:Goal)
  178%     In case a password is required to access the private key the
  179%     supplied predicate will be called to fetch it. The hook is
  180%     called as call(Goal, +SSL, -Password) and typically unifies
  181%     `Password` with a _string_ containing the password.
  182%     * require_crl(+Boolean)
  183%     If true (default is false), then all certificates will be
  184%     considered invalid unless they can be verified as not being
  185%     revoked. You can do this explicity by passing a list of CRL
  186%     filenames via the crl/1 option, or by doing it yourself in
  187%     the cert_verify_hook. If you specify require_crl(true) and
  188%     provide neither of these options, verification will necessarily
  189%     fail
  190%     * crl(+ListOfFileNames)
  191%     Provide a list of filenames of PEM-encoded CRLs that will be
  192%     given to the context to attempt to establish that a chain of
  193%     certificates is not revoked. You must also set require_crl(true)
  194%     if you want CRLs to actually be checked by OpenSSL.
  195%     * cacert_file(+FileName)
  196%     Deprecated. Use cacerts/1 instead.
  197%     Specify a file containing certificate keys of _trusted_
  198%     certificates. The peer is trusted if its certificate is
  199%     signed (ultimately) by one of the provided certificates. Using
  200%     the FileName `system(root_certificates)` uses a list of
  201%     trusted root certificates as provided by the OS. See
  202%     system_root_certificates/1 for details.
  203%     * cacerts(+ListOfCATerms)
  204%     Specify a list of sources of _trusted_ certificates.
  205%     Each element in the list should be one of the following:
  206%        * file(Filename): A file containing one or more PEM-encoded
  207%          certificates
  208%        * certificate(Blob): A certificate blob
  209%        * system(root_certificates): A special term which refers to
  210%          the certificates trusted by the host OS.
  211%
  212%     Additional verification of the peer certificate as well as
  213%     accepting certificates that are not trusted by the given set
  214%     can be realised using the hook
  215%     cert_verify_hook(:Goal).
  216%     * cert_verify_hook(:Goal)
  217%     The predicate ssl_negotiate/5 calls Goal as follows:
  218%
  219%       ==
  220%       call(Goal, +SSL,
  221%            +ProblemCertificate, +AllCertificates, +FirstCertificate,
  222%            +Error)
  223%       ==
  224%
  225%     In case the certificate was verified by one of the provided
  226%     certifications from the `cacert_file` option, Error is unified
  227%     with the atom `verified`. Otherwise it contains the error
  228%     string passed from OpenSSL. Access will be granted iff the
  229%     predicate succeeds. See load_certificate/2 for a description
  230%     of the certificate terms. See cert_accept_any/5 for a dummy
  231%     implementation that accepts any certificate.
  232%     * cipher_list(+Atom)
  233%     Specify a cipher preference list (one or more cipher strings
  234%     separated by colons, commas or spaces). See ssl_secure_ciphers/1.
  235%     * ecdh_curve(+Atom)
  236%     Specify a curve for ECDHE ciphers. If this option is not
  237%     specified, the OpenSSL default parameters are used.  With
  238%     OpenSSL prior to 1.1.0, `prime256v1` is used by default.
  239%     * peer_cert(+Boolean)
  240%     Trigger the request of our peer's certificate while
  241%     establishing the SSL layer. This option is automatically
  242%     turned on in a client SSL socket.  It can be used in a server
  243%     to ask the client to identify itself using an SSL certificate.
  244%     * close_parent(+Boolean)
  245%     If `true`, close the raw streams if the SSL streams are closed.
  246%     Default is `false`.
  247%     * close_notify(+Boolean)
  248%     If `true` (default is `false`), the server sends TLS
  249%     `close_notify` when closing the connection. In addition,
  250%     this mitigates _truncation attacks_ for both client and
  251%     server role: If EOF is encountered without having received a
  252%     TLS shutdown, an exception is raised. Well-designed
  253%     protocols are self-terminating, and this attack is therefore
  254%     very rarely a concern.
  255%     * min_protocol_version(+Atom)
  256%     Set the _minimum_ protocol version that can be negotiated.
  257%     Atom is one of `sslv3`, `tlsv1`, `tlsv1_1`, `tlsv1_2` and
  258%     `tlsv1_3`. This option is available with OpenSSL 1.1.0 and
  259%     later, and should be used instead of `disable_ssl_methods/1`.
  260%     * max_protocol_version(+Atom)
  261%     Set the _maximum_ protocol version that can be negotiated.
  262%     Atom is one of `sslv3`, `tlsv1`, `tlsv1_1`, `tlsv1_2` and
  263%     `tlsv1_3`. This option is available with OpenSSL 1.1.0 and
  264%     later, and should be used instead of `disable_ssl_methods/1`.
  265%     * disable_ssl_methods(+List)
  266%     A list of methods to disable. Unsupported methods will be
  267%     ignored. Methods include `sslv2`, `sslv3`, `sslv23`,
  268%     `tlsv1`, `tlsv1_1` and `tlsv1_2`. This option is deprecated
  269%     starting with OpenSSL 1.1.0. Use min_protocol_version/1 and
  270%     max_protocol_version/1 instead.
  271%     * ssl_method(+Method)
  272%     Specify the explicit Method to use when negotiating. For
  273%     allowed values, see the list for `disable_ssl_methods` above.
  274%     Using this option is discouraged. When using OpenSSL 1.1.0
  275%     or later, this option is ignored, and a version-flexible method
  276%     is used to negotiate the connection. Using version-specific
  277%     methods is deprecated in recent OpenSSL versions, and this
  278%     option will become obsolete and ignored in the future.
  279%     * sni_hook(:Goal)
  280%     This option provides Server Name Indication (SNI) for SSL
  281%     servers. This means that depending on the host to which a
  282%     client connects, different options (certificates etc.) can
  283%     be used for the server. This TLS extension allows you to host
  284%     different domains using the same IP address and physical
  285%     machine. When a TLS connection is negotiated with a client
  286%     that has provided a host name via SNI, the hook is called as
  287%     follows:
  288%
  289%     ==
  290%     call(Goal, +SSL0, +HostName, -SSL)
  291%     ==
  292%
  293%     Given the current context SSL0, and the host name of the
  294%     client request, the predicate computes SSL which is used as
  295%     the context for negotiating the connection. The first solution
  296%     is used.  If the predicate fails, the default options are
  297%     used, which are those of the encompassing ssl_context/3
  298%     call. In that case, if no default certificate and key are
  299%     specified, the client connection is rejected.
  300%     * alpn_protocols(+ListOfProtoIdentifiers)
  301%     Provide a list of acceptable ALPN protocol identifiers as atoms.
  302%     ALPN support requires OpenSSL 1.0.2 or greater.
  303%     * alpn_protocol_hook(:Goal)
  304%     This options provides a callback for a server context to use to
  305%     select an ALPN protocol. It will be called as follows:
  306%
  307%     ===
  308%     call(Goal, +SSLCtx0, +ListOfClientProtocols, -SSLCtx1, -SelectedProtocol)
  309%     ===
  310%
  311%     If this option is unset and the `alpn_protocols/1` option is
  312%     set, then the first common protocol between client & server will
  313%     be selected.
  314%
  315%   @arg Role is one of `server` or `client` and denotes whether the
  316%   SSL  instance  will  have  a  server   or  client  role  in  the
  317%   established connection.
  318%   @arg SSL is a SWI-Prolog _blob_ of type `ssl_context`, i.e., the
  319%   type-test for an SSL context is `blob(SSL, ssl_context)`.
  320
  321ssl_context(Role, SSL, Module:Options) :-
  322    select_option(ssl_method(Method), Options, O1, sslv23),
  323    ssl_upgrade_legacy_options(O1, O2),
  324    (   select_option(cacerts(_), O2, _)
  325    ->  O3 = O2
  326    ;   O3 = [cacerts([system(root_certificates)])|O2]
  327    ),
  328    '_ssl_context'(Role, SSL, Module:O3, Method).
  329
  330%!  ssl_upgrade_legacy_options(+OptionsIn, -Options) is det.
  331%
  332%   Handle deprecated cacert_file(Spec) option and  map   it  to the new
  333%   cacerts(+List) option.
  334
  335ssl_upgrade_legacy_options(O1, O4) :-
  336    select_option(cacert_file(CACertFile), O1, O2),
  337    !,
  338    print_message(warning, deprecated(ssl_option(cacert_file(CACertFile)))),
  339    (   atom(CACertFile)
  340    ->  Term = file(CACertFile)
  341    ;   Term = CACertFile                % e.g., system(root_certificates)
  342    ),
  343    select_option(cacerts(CACerts), O2, O3, []),
  344    ssl_upgrade_legacy_options([cacerts([Term|CACerts])|O3], O4).
  345ssl_upgrade_legacy_options(Options, Options).
  346
  347
  348%!  ssl_add_certificate_key(+SSL0, +Certificate, +Key, -SSL)
  349%
  350%   Add an additional certificate/key pair to SSL0, yielding SSL.
  351%   Certificate and Key are either strings or atoms that hold the
  352%   PEM-encoded certificate plus certificate chain and private key,
  353%   respectively. Using strings is preferred for security reasons.
  354%
  355%   This predicate allows dual-stack RSA and ECDSA servers (for
  356%   example), and is an alternative for using the
  357%   `certificate_key_pairs/1` option. As of OpenSSL 1.0.2, multiple
  358%   certificate types with completely independent certificate chains
  359%   are supported. If a certificate of the same type is added
  360%   repeatedly to a context, the result is undefined. Currently, up to
  361%   12 additional certificates of different types are admissible.
  362
  363ssl_add_certificate_key(SSL0, Cert, Key, SSL) :-
  364    ssl_copy_context(SSL0, SSL),
  365    '_ssl_add_certificate_key'(SSL, Cert, Key).
  366
  367%!  ssl_set_options(+SSL0, -SSL, +Options)
  368%
  369%   SSL is the same as SSL0, except for the options specified in
  370%   Options.  The following options are supported: close_notify/1,
  371%   close_parent/1, host/1, peer_cert/1, ecdh_curve/1,
  372%   min_protocol_version/1, max_protocol_version/1,
  373%   disable_ssl_methods/1, sni_hook/1, cert_verify_hook/1,
  374%   alpn_protocols/1, and alpn_protocol_hook/1. See ssl_context/3 for
  375%   more information about these options. This predicate allows you to
  376%   tweak existing SSL contexts, which can be useful in hooks when
  377%   creating servers with the HTTP infrastructure.
  378
  379ssl_set_options(SSL0, SSL, Options) :-
  380    ssl_copy_context(SSL0, SSL),
  381    '_ssl_set_options'(SSL, Options).
  382
  383%!  ssl_property(+SSL, ?Property) is semidet.
  384%
  385%   True when Property is a property of SSL. Defined properties are:
  386%
  387%     - close_parent(?Bool)
  388%
  389%   @tbd This version is a very   minimal  implementation of the generic
  390%   property interface. Future versions  will   add  more properties and
  391%   non-determinism.
  392
  393%!  ssl_negotiate(+SSL,
  394%!                +PlainRead, +PlainWrite,
  395%!                -SSLRead, -SSLWrite) is det.
  396%
  397%   Once a connection is established and a read/write stream pair is
  398%   available, (PlainRead and PlainWrite),  this   predicate  can be
  399%   called to negotiate an SSL  session   over  the  streams. If the
  400%   negotiation is successful, SSLRead and SSLWrite are returned.
  401%
  402%   After a successful handshake and finishing the communication the
  403%   user  must  close  SSLRead  and   SSLWrite,  for  example  using
  404%   call_cleanup(close(SSLWrite),  close(SSLRead)).  If    the   SSL
  405%   _context_   (created   with   ssl_context/3   has   the   option
  406%   close_parent(true)  (default  `false`),  closing    SSLRead  and
  407%   SSLWrite also closes  the  original   PlainRead  and  PlainWrite
  408%   streams. Otherwise these must be closed explicitly by the user.
  409%
  410%   @error ssl_error(Code, LibName, FuncName, Reason) is raised
  411%   if the negotiation fails. The streams PlainRead and PlainWrite
  412%   are *not* closed, but an unknown amount of data may have been
  413%   read and written.
  414
  415%!  ssl_peer_certificate(+Stream, -Certificate) is semidet.
  416%
  417%   True if the peer certificate  is   provided  (this is always the
  418%   case for a client connection) and   Certificate unifies with the
  419%   peer certificate. The example below  uses   this  to  obtain the
  420%   _Common Name_ of the peer  after   establishing  an https client
  421%   connection:
  422%
  423%     ==
  424%       http_open(HTTPS_url, In, []),
  425%       ssl_peer_certificate(In, Cert),
  426%       memberchk(subject(Subject), Cert),
  427%       memberchk('CN' = CommonName), Subject)
  428%     ==
  429
  430%!  ssl_peer_certificate_chain(+Stream, -Certificates) is det.
  431%
  432%   Certificates  is the  certificate  chain provided  by the  peer,
  433%   represented as a list of certificates.
  434
  435%!  ssl_session(+Stream, -Session) is det.
  436%
  437%   Retrieves (debugging) properties from the SSL context associated
  438%   with Stream. If Stream  is  not   an  SSL  stream, the predicate
  439%   raises  a  domain  error.  Session  is  a  list  of  properties,
  440%   containing the members described below.   Except  for `Version`,
  441%   all information are byte arrays that   are represented as Prolog
  442%   strings holding characters in the range 0..255.
  443%
  444%     * ssl_version(Version)
  445%     The negotiated version of the session as an integer.
  446%     * cipher(Cipher)
  447%     The negotiated cipher for this connection.
  448%     * session_key(Key)
  449%     The key material used in SSLv2 connections (if present).
  450%     * master_key(Key)
  451%     The key material comprising the master secret. This is
  452%     generated from the server_random, client_random and pre-master
  453%     key.
  454%     * client_random(Random)
  455%     The random data selected by the client during handshaking.
  456%     * server_random(Random)
  457%     The random data selected by the server during handshaking.
  458%     * session_id(SessionId)
  459%     The SSLv3 session ID. Note that if ECDHE is being used (which
  460%     is the default for newer versions of OpenSSL), this data will
  461%     not actually be sent to the server.
  462%     * alpn_protocol(Protocol)
  463%     The negotiated ALPN protocol, if supported. If no protocol was
  464%     negotiated, this will be an empty string.
  465
  466%!  load_certificate(+Stream, -Certificate) is det.
  467%
  468%   Loads a certificate from a PEM- or DER-encoded stream, returning
  469%   a certificate. The fields of the certificate can be inspected
  470%   using certificate_field(+Certificate, ?Field).
  471%
  472%   Note that the OpenSSL `CA.pl`  utility creates certificates that
  473%   have a human readable textual representation in front of the PEM
  474%   representation. You can  use  the  following   to  skip  to  the
  475%   certificate if you know it is a PEM certificate:
  476%
  477%     ==
  478%     skip_to_pem_cert(In) :-
  479%           repeat,
  480%           (   peek_char(In, '-')
  481%           ->  !
  482%           ;   skip(In, 0'\n),
  483%               at_end_of_stream(In), !
  484%           ).
  485%     ==
  486
  487%!  write_certificate(+Stream, +Certificate, +Options) is det.
  488%
  489%   Writes a certificate to the stream Stream. Options is reserved
  490%   for future use.
  491
  492%!  load_crl(+Stream, -CRL) is det.
  493%
  494%   Loads a CRL from a PEM- or  DER-encoded stream, returning a term
  495%   containing  terms  hash/1,   signature/1,    issuer_name/1   and
  496%   revocations/1,  which  is  a  list   of  revoked/2  terms.  Each
  497%   revoked/2 term is of the form revoked(+Serial, DateOfRevocation)
  498
  499%!  system_root_certificates(-List) is det.
  500%
  501%   List is a list of trusted root   certificates as provided by the
  502%   OS. This is the list used by ssl_context/3 when using the option
  503%   `system(root_certificates)`.  The list is obtained using an OS
  504%   specific process.  The current implementation is as follows:
  505%
  506%       - On Windows, CertOpenSystemStore() is used to import
  507%         the `"ROOT"` certificates from the OS.
  508%       - On Unix and macOS, certificates are loaded from a file
  509%         defined by the Prolog flag `system_cacert_filename`.  The
  510%         initial value of this flag is established at build time and
  511%         is =|/etc/ssl/cert.pem|= on macOS.  For security reasons, the
  512%         flag can only be set prior to using the SSL library.  For
  513%         example:
  514%
  515%           ==
  516%           :- use_module(library(ssl)).
  517%           :- set_prolog_flag(system_cacert_filename,
  518%                              '/home/jan/ssl/ca-bundle.crt').
  519%           ==
  520%
  521%       - On macOS the flag may be set to `keychain`, in which case
  522%         the trust anchors are obtained from the keychain using
  523%         SecTrustCopyAnchorCertificates().  This is also used as
  524%         fallback if the file above does not exist or holds no
  525%         certificates.  It is not the default because this API talks
  526%         to the `securityd` daemon over Mach IPC, which can block
  527%         indefinitely if the keychain is not accessible, e.g., in an
  528%         ssh session while the login keychain is locked.  Such a
  529%         block cannot be interrupted using e.g.
  530%         call_with_time_limit/2.
  531%
  532%   Note that a PEM file is a plain list of certificates.  Unlike the
  533%   keychain it cannot express trust settings made by the user or the
  534%   administrator, e.g., root certificates that have been distrusted.
  535%
  536%   If no certificates can be obtained at all a warning is printed and
  537%   List is unified with `[]`, which makes all certificate
  538%   verification fail.
  539
  540%!  load_private_key(+Stream, +Password, -PrivateKey) is det.
  541%
  542%   Load  a private  key PrivateKey  from the  given stream  Stream,
  543%   using Password to decrypt the key  if it is encrypted. Note that
  544%   the  password  is  currently   only  supported  for  PEM  files.
  545%   DER-encoded keys which are password protected will not load. The
  546%   key must be  an RSA, EC, Ed25519 or  X25519 key.  DH and  DSA keys
  547%   are not supported, and PrivateKey will be bound to an atom (dh_key
  548%   or  dsa_key)  if  you try  and  load  such  a key.  Otherwise
  549%   PrivateKey will be unified with private_key(KeyTerm), where
  550%   KeyTerm is one of:
  551%
  552%     - rsa/8 for RSA keys
  553%     - ec/3 for EC keys
  554%     - ed25519/1 holding the hexadecimal key _pair_ in PKCS#8 v2
  555%       format, suitable for ed25519_sign/4
  556%     - x25519/1 holding the hexadecimal scalar, suitable for
  557%       curve25519_scalar_mult/3
  558
  559%!  load_public_key(+Stream, -PublicKey) is det.
  560%
  561%   Load  a  public key  PublicKey  from  the given  stream  Stream.
  562%   Supports loading both DER- and PEM-encoded keys. The key must be
  563%   an RSA, EC, Ed25519 or X25519 key.  DH and DSA keys are not
  564%   supported, and PublicKey will be bound to an atom (dh_key or
  565%   dsa_key) if you try and load such a key.  Otherwise PublicKey
  566%   will be unified with public_key(KeyTerm), where KeyTerm is an
  567%   rsa/8 or ec/3 term as with load_private_key/3, or ed25519/1 or
  568%   x25519/1 holding the hexadecimal public key.
  569
  570
  571%!  cert_accept_any(+SSL,
  572%!                  +ProblemCertificate, +AllCertificates, +FirstCertificate,
  573%!                  +Error) is det.
  574%
  575%   Implementation  for  the  hook   `cert_verify_hook(:Hook)`  that
  576%   accepts _any_ certificate. This is   intended for http_open/3 if
  577%   no certificate verification is desired as illustrated below.
  578%
  579%     ==
  580%       http_open('https:/...', In,
  581%                 [ cert_verify_hook(cert_accept_any)
  582%                 ])
  583%     ==
  584
  585%!  same_certificate(+CertificateA,
  586%!                   +CertificateB).
  587%
  588%   True if CertificateA is logically the same as CertificateB, even if
  589%   they are stored in different blobs
  590
  591%!  verify_certificate_issuer(+Certificate,
  592%!			      +Issuer).
  593%
  594%   True if Certificate is a certificate which was issued by the
  595%   certificate Issuer.
  596
  597%!  verify_certificate(+Certificate,
  598%!		       +AuxiliaryCertificates,
  599%!		       +TrustedCertificates).
  600%
  601%   True if it is possible to build a chain of trust from Certificate to
  602%   one of the certificates in TrustedCertificates, optionally using the
  603%   (untrusted) certificates in AuxiliaryCertificates to complete the
  604%   chain.
  605%   To use the system built-in trust store, specify the special term
  606%   system(root_certificates) for TrustedCertificates.
  607
  608%!  certificate_field(+Certificate,
  609%!		      ?Field) is nondet.
  610%
  611%   Retrieve the field matching Field from Certificate. May be
  612%   one of the following:
  613%     * subject/1 to retrieve the subject
  614%     * issuer/1  to retrieve the issuer's subject
  615%     * version/1  to retrieve the version
  616%     * serial/1  to retrieve the serial number
  617%     * not_before/1 to retrieve the start date
  618%     * not_after/1  to retrieve the expiry date
  619%     * public_key/1 to retrieve the public key
  620%     * crls/1 to retrieve a list of the CRLs
  621%     * sans/1 to retrieve a list of the Subject Alternative Names
  622%     * signature/1 to retrieve the certificate signature
  623%     * signature_algorithm/1 to retrieve the signing algorithm
  624%     * hash/1 to retrieve the certificate hash
  625%     * to_be_signed/1 to retrieve the data on the certificate which
  626%        must be signed
  627
  628
  629
  630cert_accept_any(_SSL,
  631                _ProblemCertificate, _AllCertificates, _FirstCertificate,
  632                _Error).
  633
  634%!  ssl_secure_ciphers(-Ciphers:atom) is det.
  635%
  636%   Ciphers is a  secure cipher preference list that can  be used in the
  637%   cipher_list/1 option of ssl_context/3.
  638%
  639%   Secure ciphers must guarantee forward secrecy, and must mitigate all
  640%   known critical attacks.  As of  2018, using these ciphers allows you
  641%   to obtain grade A on  https://www.ssllabs.com. For A+, you must also
  642%   enable HTTP Strict  Transport Security (HSTS) by  sending a suitable
  643%   header field in replies.
  644%
  645%   Note that obsolete ciphers *must* be   disabled  to reliably prevent
  646%   protocol downgrade attacks.
  647%
  648%   The Ciphers list is read from   the setting `ssl:secure_ciphers` and
  649%   can be controlled using  set_setting/2   and  other  predicates from
  650%   library(settings).
  651%
  652%   *BEWARE*: This list must be changed when attacks on these ciphers
  653%             become known! Keep an eye on this setting and adapt it
  654%             as necessary in the future.
  655
  656ssl_secure_ciphers(Cs) :-
  657    setting(secure_ciphers, Cs).
  658
  659
  660                 /*******************************
  661                 *           MESSAGES           *
  662                 *******************************/
  663
  664:- multifile
  665    prolog:message//1,
  666    prolog:error_message//1,
  667    prolog:deprecated//1.  668
  669prolog:error_message(ssl_error(ID, _Library, Function, Reason)) -->
  670    [ 'SSL(~w) ~w: ~w'-[ID, Function, Reason] ].
  671
  672prolog:message(ssl_cacerts(no_certificates, File)) -->
  673    [ 'SSL: no system root certificates loaded from ~w.'-[File], nl,
  674      'SSL: certificate verification will fail.  See the Prolog flag'-[], nl,
  675      'SSL: system_cacert_filename.'-[]
  676    ].
  677prolog:message(ssl_cacerts(keychain_fallback, File)) -->
  678    [ 'SSL: no system root certificates in ~w.'-[File], nl,
  679      'SSL: falling back to the keychain.'-[]
  680    ].
  681prolog:message(ssl_cacerts(no_anchors, _)) -->
  682    [ 'SSL: failed to copy the trust anchors from the keychain.'-[], nl,
  683      'SSL: certificate verification will fail.'-[]
  684    ].
  685prolog:message(ssl_cacerts(no_keychain, _)) -->
  686    [ 'SSL: the Prolog flag system_cacert_filename is set to `keychain\','-[],
  687      nl,
  688      'SSL: which is only supported on macOS.'-[]
  689    ].
  690prolog:deprecated(ssl_option(cacert_file(CACertFile))) -->
  691    [ 'SSL: cacert_file(~q) has need deprecated.'-[CACertFile],
  692      'Please use the option cacerts(List) instead'
  693    ]