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-2020, 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    http:http_protocol_hook/5,
   78    http:open_options/2,
   79    http:http_connection_over_proxy/6,
   80    http:ssl_server_create_hook/3,
   81    http:ssl_server_open_client_hook/3.   82
   83
   84                 /*******************************
   85                 *          SERVER HOOKS        *
   86                 *******************************/
   87
   88%!  thread_httpd:make_socket_hook(?Port, :OptionsIn, -OptionsOut)
   89%!                                                          is semidet.
   90%
   91%   Hook into http_server/2 to create an   SSL  server if the option
   92%   ssl(SSLOptions) is provided.
   93%
   94%   @see thread_httpd:accept_hook/2 handles the corresponding accept
   95
   96thread_httpd:make_socket_hook(Port, M:Options0, Options) :-
   97    select(ssl(SSLOptions0), Options0, Options1),
   98    !,
   99    add_secure_ciphers(SSLOptions0, SSLOptions1),
  100    disable_sslv3(SSLOptions1, SSLOptions),
  101    make_socket(Port, Socket, Options1),
  102    ssl_context(server, SSL0, M:[close_parent(true)|SSLOptions]),
  103    (   http:ssl_server_create_hook(SSL0, SSL1, Options1)
  104    ->  ensure_close_parent(SSL1, SSL)
  105    ;   SSL = SSL0
  106    ),
  107    atom_concat('httpsd', Port, Queue),
  108    Options = [ queue(Queue),
  109                tcp_socket(Socket),
  110                ssl_instance(SSL)
  111              | Options1
  112              ].
  113
  114ensure_close_parent(SSL0, SSL) :-
  115    (   ssl_property(SSL0, close_parent(true))
  116    ->  SSL = SSL0
  117    ;   ssl_set_options(SSL0, SSL, [close_parent(true)])
  118    ).
  119
  120%!  add_secure_ciphers(+SSLOptions0, -SSLOptions)
  121%
  122%   Add ciphers from ssl_secure_ciphers/1 if no ciphers are provided.
  123
  124add_secure_ciphers(SSLOptions0, SSLOptions) :-
  125    (   option(cipher_list(_), SSLOptions0)
  126    ->  SSLOptions = SSLOptions0
  127    ;   ssl_secure_ciphers(Ciphers),
  128        SSLOptions = [cipher_list(Ciphers)|SSLOptions0]
  129    ).
  130
  131%!  disable_sslv3(+SSLOptions0, -SSLOptions)
  132%
  133%   Disable SSLv3, which  is  considered   insecure  unless  the  caller
  134%   specifies the allowed versions explicitly, so   we assume s/he knows
  135%   what s/he is doing.
  136
  137disable_sslv3(SSLOptions0, SSLOptions) :-
  138    (   option(min_protocol_version(_), SSLOptions0)
  139    ;   option(disable_ssl_methods(_), SSLOptions0)
  140    ),
  141    !,
  142    SSLOptions = SSLOptions0.
  143disable_sslv3(SSLOptions0,
  144              [ disable_ssl_methods([sslv3,sslv23]), % old OpenSSL versions
  145                min_protocol_version(tlsv1)          % OpenSSL 1.1.0 and later
  146              | SSLOptions0
  147              ]).
  148
  149
  150make_socket(_Port, Socket, Options) :-
  151    option(tcp_socket(Socket), Options),
  152    !.
  153make_socket(Port, Socket, _Options) :-
  154    tcp_socket(Socket),
  155    tcp_setopt(Socket, reuseaddr),
  156    tcp_bind(Socket, Port),
  157    tcp_listen(Socket, 5).
  158
  159
  160%!  thread_httpd:accept_hook(:Goal, +Options) is semidet.
  161%
  162%   Implement the accept for HTTPS connections.
  163
  164thread_httpd:accept_hook(Goal, Options) :-
  165    memberchk(ssl_instance(SSL0), Options),
  166    !,
  167    memberchk(queue(Queue), Options),
  168    memberchk(tcp_socket(Socket), Options),
  169    tcp_accept(Socket, Client, Peer),
  170    debug(http(connection), 'New HTTPS connection from ~p', [Peer]),
  171    http_enough_workers(Queue, accept, Peer),
  172    ensure_close_parent(SSL0, SSL),
  173    thread_send_message(Queue, ssl_client(SSL, Client, Goal, Peer)).
  174
  175%!  http:ssl_server_create_hook(+SSL0, -SSL, +Options) is semidet.
  176%
  177%   Extensible predicate that is called  once   after  creating an HTTPS
  178%   server. If this predicate succeeds, SSL is  the context that is used
  179%   for negotiating new connections. Otherwise, SSL0   is used, which is
  180%   the context that was created with the given options.
  181%
  182%   @see ssl_context/3 for creating an SSL context
  183
  184
  185%!  http:ssl_server_open_client_hook(+SSL0, -SSL, +Options) is semidet.
  186%
  187%   Extensible predicate that is called before  each connection that the
  188%   server negotiates with a client. If  this predicate succeeds, SSL is
  189%   the context that is used for the  new connection. Otherwise, SSL0 is
  190%   used, which is the  context  that   was  created  when launching the
  191%   server.
  192%
  193%   @see ssl_context/3 for creating an SSL context
  194
  195
  196thread_httpd:open_client_hook(ssl_client(SSL0, Client, Goal, Peer),
  197                              Goal, In, Out,
  198                              [peer(Peer), protocol(https)],
  199                              Options) :-
  200    (   http:ssl_server_open_client_hook(SSL0, SSL, Options)
  201    ->  true
  202    ;   SSL = SSL0
  203    ),
  204    option(timeout(TMO), Options, 60),
  205    tcp_open_socket(Client, Read, Write),
  206    set_stream(Read, timeout(TMO)),
  207    set_stream(Write, timeout(TMO)),
  208    catch(ssl_negotiate(SSL, Read, Write, In, Out),
  209          E,
  210          ssl_failed(Read, Write, E)).
  211
  212ssl_failed(Read, Write, E) :-
  213    close(Write, [force(true)]),
  214    close(Read,  [force(true)]),
  215    throw(E).
  216
  217
  218                 /*******************************
  219                 *         CLIENT HOOKS         *
  220                 *******************************/
  221
  222%!  http:http_protocol_hook(+Scheme, +Parts, +PlainStreamPair,
  223%!                          -StreamPair, +Options) is semidet.
  224%
  225%   Hook for http_open/3 to connect  to   an  HTTPS (SSL-based HTTP)
  226%   server.
  227
  228http:http_protocol_hook(https, Parts, PlainStreamPair, StreamPair, Options) :-
  229    ssl_protocol_hook(Parts, PlainStreamPair, StreamPair, Options).
  230http:http_protocol_hook(wss, Parts, PlainStreamPair, StreamPair, Options) :-
  231    ssl_protocol_hook(Parts, PlainStreamPair, StreamPair, Options).
  232
  233ssl_protocol_hook(Parts, PlainStreamPair, StreamPair, Options) :-
  234    memberchk(host(Host), Parts),
  235    include(ssl_option, Options, SSLOptions),
  236    ssl_context(client, SSL, [ host(Host),
  237                               close_parent(true)
  238                             | SSLOptions
  239                             ]),
  240    stream_pair(PlainStreamPair, PlainIn, PlainOut),
  241    % if an exception arises, http_open/3 closes the stream for us
  242    ssl_negotiate(SSL, PlainIn, PlainOut, In, Out),
  243    stream_pair(StreamPair, In, Out).
  244
  245% Might be better to be more  selective,   but  passing the options from
  246% http_open/3 with more than 1 argument makes ssl_context/3 fail.
  247
  248ssl_option(Term) :-
  249    compound(Term),
  250    compound_name_arity(Term, _, 1).
  251
  252%!  http:http_connection_over_proxy(+Proxy, +Parts, +HostPort, -StreamPair,
  253%!                                  +OptionsIn, -OptionsOut)
  254%
  255%   Facilitate an HTTPS connection via a   proxy using HTTP CONNECT.
  256%   Note that most proxies will only  support this for connecting on
  257%   port 443
  258
  259http:http_connection_over_proxy(proxy(ProxyHost, ProxyPort), Parts,
  260                                Host:Port, StreamPair, Options, Options) :-
  261    memberchk(scheme(https), Parts),
  262    !,
  263    tcp_connect(ProxyHost:ProxyPort, StreamPair, [bypass_proxy(true)]),
  264    catch(negotiate_http_connect(StreamPair, Host:Port),
  265          Error,
  266          ( close(StreamPair, [force(true)]),
  267            throw(Error)
  268          )).
  269
  270negotiate_http_connect(StreamPair, Address):-
  271    format(StreamPair, 'CONNECT ~w HTTP/1.1\r\n\r\n', [Address]),
  272    flush_output(StreamPair),
  273    http_read_reply_header(StreamPair, Header),
  274    memberchk(status(_, Status, Message), Header),
  275    (   Status == ok
  276    ->  true
  277    ;   throw(error(proxy_rejection(Message), _))
  278    )