View source with formatted comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2007-2022, University of Amsterdam
    7                              VU University Amsterdam
    8    All rights reserved.
    9
   10    Redistribution and use in source and binary forms, with or without
   11    modification, are permitted provided that the following conditions
   12    are met:
   13
   14    1. Redistributions of source code must retain the above copyright
   15       notice, this list of conditions and the following disclaimer.
   16
   17    2. Redistributions in binary form must reproduce the above copyright
   18       notice, this list of conditions and the following disclaimer in
   19       the documentation and/or other materials provided with the
   20       distribution.
   21
   22    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   23    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   24    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   25    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   26    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   27    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   28    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   29    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   30    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   31    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   32    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   33    POSSIBILITY OF SUCH DAMAGE.
   34*/
   35
   36:- module(http_ssl_plugin, []).   37% Requires ssl:upgrade_legacy_options/2 hook
   38:- use_module(library(ssl),
   39              [ ssl_context/3,
   40                ssl_secure_ciphers/1,
   41                ssl_property/2,
   42                ssl_set_options/3,
   43                ssl_negotiate/5
   44              ]).   45:- use_module(library(debug),[debug/3]).   46:- use_module(library(socket),
   47              [ tcp_socket/1,
   48                tcp_setopt/2,
   49                tcp_bind/2,
   50                tcp_listen/2,
   51                tcp_accept/3,
   52                tcp_open_socket/3,
   53                tcp_connect/3
   54              ]).   55
   56:- autoload(library(lists),[select/3]).   57:- autoload(library(option),[option/2,option/3]).   58:- autoload(library(apply), [include/3]).   59:- autoload(library(http/http_header),[http_read_reply_header/2]).   60:- autoload(library(http/thread_httpd),[http_enough_workers/3]).   61
   62/** <module> SSL plugin for HTTP libraries
   63
   64This  module  can  be   loaded    next   to   library(thread_httpd)  and
   65library(http_open) to provide secure HTTP   (HTTPS)  services and client
   66access.
   67
   68An example secure server using self-signed  certificates can be found in
   69the <plbase>/doc/packages/examples/ssl/https.pl, where <plbase>   is the
   70SWI-Prolog installation directory.
   71*/
   72
   73:- multifile
   74    thread_httpd:make_socket_hook/3,
   75    thread_httpd:accept_hook/2,
   76    thread_httpd:open_client_hook/6,
   77    thread_httpd:discard_client_hook/1,
   78    http:http_protocol_hook/5,
   79    http:open_options/2,
   80    http:http_connection_over_proxy/6,
   81    http:ssl_server_create_hook/3,
   82    http:ssl_server_open_client_hook/3.   83
   84
   85                 /*******************************
   86                 *          SERVER HOOKS        *
   87                 *******************************/
   88
   89%!  thread_httpd:make_socket_hook(?Port, :OptionsIn, -OptionsOut)
   90%!                                                          is semidet.
   91%
   92%   Hook into http_server/2 to create an   SSL  server if the option
   93%   ssl(SSLOptions) is provided.
   94%
   95%   @see thread_httpd:accept_hook/2 handles the corresponding accept
   96
   97thread_httpd:make_socket_hook(Port, M:Options0, Options) :-
   98    select(ssl(SSLOptions0), Options0, Options1),
   99    !,
  100    add_secure_ciphers(SSLOptions0, SSLOptions1),
  101    disable_sslv3(SSLOptions1, SSLOptions),
  102    make_socket(Port, Socket, Options1),
  103    ssl_context(server, SSL0, M:[close_parent(true)|SSLOptions]),
  104    (   http:ssl_server_create_hook(SSL0, SSL1, Options1)
  105    ->  ensure_close_parent(SSL1, SSL)
  106    ;   SSL = SSL0
  107    ),
  108    port(Port, PortNum),
  109    atom_concat('httpsd', PortNum, Queue),
  110    Options = [ queue(Queue),
  111                tcp_socket(Socket),
  112                ssl_instance(SSL)
  113              | Options1
  114              ].
  115
  116port(_Host:Port0, Port) => Port = Port0.
  117port(Port0, Port), integer(Port0) => Port = Port0.
  118
  119ensure_close_parent(SSL0, SSL) :-
  120    (   ssl_property(SSL0, close_parent(true))
  121    ->  SSL = SSL0
  122    ;   ssl_set_options(SSL0, SSL, [close_parent(true)])
  123    ).
  124
  125%!  add_secure_ciphers(+SSLOptions0, -SSLOptions)
  126%
  127%   Add ciphers from ssl_secure_ciphers/1 if no ciphers are provided.
  128
  129add_secure_ciphers(SSLOptions0, SSLOptions) :-
  130    (   option(cipher_list(_), SSLOptions0)
  131    ->  SSLOptions = SSLOptions0
  132    ;   ssl_secure_ciphers(Ciphers),
  133        SSLOptions = [cipher_list(Ciphers)|SSLOptions0]
  134    ).
  135
  136%!  disable_sslv3(+SSLOptions0, -SSLOptions)
  137%
  138%   Disable SSLv3, which  is  considered   insecure  unless  the  caller
  139%   specifies the allowed versions explicitly, so   we assume s/he knows
  140%   what s/he is doing.
  141
  142disable_sslv3(SSLOptions0, SSLOptions) :-
  143    (   option(min_protocol_version(_), SSLOptions0)
  144    ;   option(disable_ssl_methods(_), SSLOptions0)
  145    ),
  146    !,
  147    SSLOptions = SSLOptions0.
  148disable_sslv3(SSLOptions0,
  149              [ disable_ssl_methods([sslv3,sslv23]), % old OpenSSL versions
  150                min_protocol_version(tlsv1)          % OpenSSL 1.1.0 and later
  151              | SSLOptions0
  152              ]).
  153
  154
  155make_socket(_Port, Socket, Options) :-
  156    option(tcp_socket(Socket), Options),
  157    !.
  158make_socket(Port, Socket, _Options) :-
  159    tcp_socket(Socket),
  160    tcp_setopt(Socket, reuseaddr),
  161    tcp_bind(Socket, Port),
  162    tcp_listen(Socket, 5).
  163
  164
  165%!  thread_httpd:accept_hook(:Goal, +Options) is semidet.
  166%
  167%   Implement the accept for HTTPS connections.
  168
  169thread_httpd:accept_hook(Goal, Options) :-
  170    memberchk(ssl_instance(SSL0), Options),
  171    !,
  172    ensure_close_parent(SSL0, SSL),
  173    memberchk(queue(Queue), Options),
  174    memberchk(tcp_socket(Socket), Options),
  175    tcp_accept(Socket, Client, Peer),
  176    sig_atomic(send_to_worker(Queue, SSL, Client, Goal, Peer)),
  177    http_enough_workers(Queue, accept, Peer).
  178
  179send_to_worker(Queue, SSL, Client, Goal, Peer) :-
  180    debug(http(connection), 'New HTTPS connection from ~p', [Peer]),
  181    thread_send_message(Queue, ssl_client(SSL, Client, Goal, Peer)).
  182
  183%!  thread_httpd:discard_client_hook(+Msg)
  184%
  185%   Handles connections that where accepted during server shutdown.
  186
  187thread_httpd:discard_client_hook(ssl_client(_SSL, Client, _Goal, _Peer)) :-
  188    tcp_close_socket(Client).
  189
  190
  191%!  http:ssl_server_create_hook(+SSL0, -SSL, +Options) is semidet.
  192%
  193%   Extensible predicate that is called  once   after  creating an HTTPS
  194%   server. If this predicate succeeds, SSL is  the context that is used
  195%   for negotiating new connections. Otherwise, SSL0   is used, which is
  196%   the context that was created with the given options.
  197%
  198%   @see ssl_context/3 for creating an SSL context
  199
  200
  201%!  http:ssl_server_open_client_hook(+SSL0, -SSL, +Options) is semidet.
  202%
  203%   Extensible predicate that is called before  each connection that the
  204%   server negotiates with a client. If  this predicate succeeds, SSL is
  205%   the context that is used for the  new connection. Otherwise, SSL0 is
  206%   used, which is the  context  that   was  created  when launching the
  207%   server.
  208%
  209%   @see ssl_context/3 for creating an SSL context
  210
  211
  212thread_httpd:open_client_hook(ssl_client(SSL0, Client, Goal, Peer),
  213                              Goal, In, Out,
  214                              [peer(Peer), protocol(https)],
  215                              Options) :-
  216    (   http:ssl_server_open_client_hook(SSL0, SSL, Options)
  217    ->  true
  218    ;   SSL = SSL0
  219    ),
  220    option(timeout(TMO), Options, 60),
  221    tcp_open_socket(Client, Read, Write),
  222    set_stream(Read, timeout(TMO)),
  223    set_stream(Write, timeout(TMO)),
  224    catch(ssl_negotiate(SSL, Read, Write, In, Out),
  225          E,
  226          ssl_failed(Read, Write, E)).
  227
  228ssl_failed(Read, Write, E) :-
  229    close(Write, [force(true)]),
  230    close(Read,  [force(true)]),
  231    throw(E).
  232
  233
  234                 /*******************************
  235                 *         CLIENT HOOKS         *
  236                 *******************************/
  237
  238%!  http:http_protocol_hook(+Scheme, +Parts, +PlainStreamPair,
  239%!                          -StreamPair, +Options) is semidet.
  240%
  241%   Hook for http_open/3 to connect  to   an  HTTPS (SSL-based HTTP)
  242%   server.
  243
  244http:http_protocol_hook(https, Parts, PlainStreamPair, StreamPair, Options) :-
  245    ssl_protocol_hook(Parts, PlainStreamPair, StreamPair, Options).
  246http:http_protocol_hook(wss, Parts, PlainStreamPair, StreamPair, Options) :-
  247    ssl_protocol_hook(Parts, PlainStreamPair, StreamPair, Options).
  248
  249ssl_protocol_hook(Parts, PlainStreamPair, StreamPair, Options) :-
  250    memberchk(host(Host), Parts),
  251    include(ssl_option, Options, SSLOptions),
  252    ssl_context(client, SSL, [ host(Host),
  253                               close_parent(true)
  254                             | SSLOptions
  255                             ]),
  256    stream_pair(PlainStreamPair, PlainIn, PlainOut),
  257    % if an exception arises, http_open/3 closes the stream for us
  258    ssl_negotiate(SSL, PlainIn, PlainOut, In, Out),
  259    stream_pair(StreamPair, In, Out).
  260
  261% Might be better to be more  selective,   but  passing the options from
  262% http_open/3 with more than 1 argument makes ssl_context/3 fail.
  263
  264ssl_option(Term) :-
  265    compound(Term),
  266    compound_name_arity(Term, _, 1).
  267
  268%!  http:http_connection_over_proxy(+Proxy, +Parts, +HostPort, -StreamPair,
  269%!                                  +OptionsIn, -OptionsOut)
  270%
  271%   Facilitate an HTTPS connection via a   proxy using HTTP CONNECT.
  272%   Note that most proxies will only  support this for connecting on
  273%   port 443
  274
  275http:http_connection_over_proxy(proxy(ProxyHost, ProxyPort), Parts,
  276                                Host:Port, StreamPair, Options, Options) :-
  277    memberchk(scheme(https), Parts),
  278    !,
  279    tcp_connect(ProxyHost:ProxyPort, StreamPair, [bypass_proxy(true)]),
  280    catch(negotiate_http_connect(StreamPair, Host:Port),
  281          Error,
  282          ( close(StreamPair, [force(true)]),
  283            throw(Error)
  284          )).
  285
  286negotiate_http_connect(StreamPair, Address):-
  287    format(StreamPair, 'CONNECT ~w HTTP/1.1\r\n\r\n', [Address]),
  288    flush_output(StreamPair),
  289    http_read_reply_header(StreamPair, Header),
  290    memberchk(status(_, Status, Message), Header),
  291    (   Status == ok
  292    ->  true
  293    ;   throw(error(proxy_rejection(Message), _))
  294    )