Coverage Report

Created: 2026-11-12 06:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wget2/libwget/ssl_gnutls.c
Line
Count
Source
1
/*
2
 * Copyright (c) 2012-2015 Tim Ruehsen
3
 * Copyright (c) 2015-2026 Free Software Foundation, Inc.
4
 *
5
 * This file is part of libwget.
6
 *
7
 * Libwget is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU Lesser General Public License as published by
9
 * the Free Software Foundation, either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * Libwget is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public License
18
 * along with libwget.  If not, see <https://www.gnu.org/licenses/>.
19
 *
20
 *
21
 * gnutls SSL/TLS routines
22
 * - some parts have been copied from GnuTLS example code
23
 * - OCSP code has been copied from gnutls-cli/ocsptool code
24
 *
25
 * Changelog
26
 * 03.08.2012  Tim Ruehsen  created inspired from gnutls client example
27
 * 26.08.2012               wget compatibility regarding config options
28
 * 15.01.2015               added OCSP fix from https://gitorious.org/gnutls/gnutls/commit/11eebe14b232ec198d1446a3720e6ed78d118c4b
29
 *
30
 * Resources:
31
 * RFC6066 Transport Layer Security (TLS) Extensions: Extension Definitions (defines OCSP stapling)
32
 * RFC6960 Online Certificate Status Protocol - OCSP
33
 * RFC6961 TLS Multiple Certificate Status Request Extension
34
 *
35
 * Testing revocation:
36
 * https://revoked.grc.com/
37
 * https://test-sspev.verisign.com:2443/test-SSPEV-revoked-verisign.html
38
 *
39
 */
40
41
#include <config.h>
42
43
#include <unistd.h>
44
#include <stdio.h>
45
#include <string.h>
46
#include <dirent.h>
47
#include <sys/stat.h>
48
#include <errno.h>
49
50
#include <gnutls/gnutls.h>
51
#include <gnutls/x509.h>
52
#ifdef WITH_OCSP
53
# include <gnutls/ocsp.h>
54
#endif
55
#ifdef WITH_LIBDANE
56
# include <gnutls/dane.h>
57
#endif
58
#include <gnutls/crypto.h>
59
#include <gnutls/abstract.h>
60
61
#include <wget.h>
62
#include "private.h"
63
#include "net.h"
64
65
#ifdef _WIN32
66
// gnutls.h declares gnutls_free as a dllimport'ed variable on Windows,
67
// which a static libgnutls can't provide. GnuTLS allocates with malloc().
68
#  define gnutls_free free
69
#endif
70
71
/**
72
 * \file
73
 * \brief Functions for establishing and managing SSL/TLS connections
74
 * \defgroup libwget-ssl SSL/TLS engine
75
 *
76
 * @{
77
 */
78
79
static wget_tls_stats_callback
80
  *tls_stats_callback;
81
static void
82
  *tls_stats_ctx;
83
84
static wget_ocsp_stats_callback
85
  *ocsp_stats_callback;
86
static void
87
  *ocsp_stats_ctx;
88
89
static struct config {
90
  const char
91
    *secure_protocol,
92
    *ca_directory,
93
    *ca_file,
94
    *cert_file,
95
    *key_file,
96
    *crl_file,
97
    *ocsp_server,
98
    *alpn;
99
  wget_ocsp_db
100
    *ocsp_cert_cache,
101
    *ocsp_host_cache;
102
  wget_tls_session_db
103
    *tls_session_cache;
104
  wget_hpkp_db
105
    *hpkp_cache;
106
  char
107
    ca_type,
108
    cert_type,
109
    key_type;
110
  bool
111
    check_certificate : 1,
112
    report_invalid_cert : 1,
113
    check_hostname : 1,
114
    print_info : 1,
115
    ocsp : 1,
116
    ocsp_date : 1,
117
    ocsp_stapling : 1,
118
    ocsp_nonce : 1,
119
    dane : 1;
120
} config = {
121
  .check_certificate = true,
122
  .report_invalid_cert = true,
123
  .check_hostname = true,
124
#ifdef WITH_OCSP
125
  .ocsp = false,
126
  .ocsp_stapling = true,
127
#endif
128
  .ca_type = WGET_SSL_X509_FMT_PEM,
129
  .cert_type = WGET_SSL_X509_FMT_PEM,
130
  .key_type = WGET_SSL_X509_FMT_PEM,
131
  .secure_protocol = "AUTO",
132
  .ca_directory = "system",
133
  .ca_file = "system",
134
#ifdef WITH_LIBNGHTTP2
135
  .alpn = "h2,http/1.1",
136
#endif
137
};
138
139
struct session_context {
140
  const char *
141
    hostname;
142
  wget_hpkp_stats_result
143
    stats_hpkp;
144
  uint16_t
145
    port;
146
  bool
147
    ocsp_stapling : 1,
148
    valid : 1,
149
    delayed_session_data : 1;
150
};
151
152
static gnutls_certificate_credentials_t
153
  credentials;
154
static gnutls_priority_t
155
  priority_cache;
156
157
0
#define error_printf_check(...) if (config.report_invalid_cert) wget_error_printf(__VA_ARGS__)
158
159
/**
160
 * \param[in] key An identifier for the config parameter (starting with `WGET_SSL_`) to set
161
 * \param[in] value The value for the config parameter (a NULL-terminated string)
162
 *
163
 * Set a configuration parameter, as a string.
164
 *
165
 * The following parameters accept a string as their value (\p key can have any of those values):
166
 *
167
 *  - WGET_SSL_SECURE_PROTOCOL: A string describing which SSL/TLS version should be used. It can have either
168
 *  an arbitrary value, or one of the following fixed values (case does not matter):
169
 *      - "SSL": SSLv3 will be used. Warning: this protocol is insecure and should be avoided.
170
 *      - "TLSv1": TLS 1.0 will be used.
171
 *      - "TLSv1_1": TLS 1.1 will be used.
172
 *      - "TLSv1_2": TLS 1.2 will be used.
173
 *      - "TLSv1_3": TLS 1.3 will be used.
174
 *      - "AUTO": Let the TLS library decide.
175
 *      - "PFS": Let the TLS library decide, but make sure only forward-secret ciphers are used.
176
 *
177
 *  An arbitrary string can also be supplied (an string that's different from any of the previous ones). If that's the case
178
 *  the string will be directly taken as the priority string and sent to the library. Priority strings provide the greatest flexibility,
179
 *  but have a library-specific syntax. A GnuTLS priority string will not work if your libwget has been compiled with OpenSSL, for instance.
180
 *  - WGET_SSL_CA_DIRECTORY: A path to the directory where the root certificates will be taken from
181
 *  for server cert validation. Every file of that directory is expected to contain an X.509 certificate,
182
 *  encoded in PEM format. If the string "system" is specified, the system's default directory will be used.
183
 *  The default value is "system". Certificates get loaded in wget_ssl_init().
184
 *  - WGET_SSL_CA_FILE: A path to a file containing a single root certificate. This will be used to validate
185
 *  the server's certificate chain. This option can be used together with `WGET_SSL_CA_DIRECTORY`. The certificate
186
 *  can be in either PEM or DER format. The format is specified in the `WGET_SSL_CA_TYPE` option (see
187
 *  wget_ssl_set_config_int()).
188
 *  - WGET_SSL_CERT_FILE: Set the client certificate. It will be used for client authentication if the server requests it.
189
 *  It can be in either PEM or DER format. The format is specified in the `WGET_SSL_CERT_TYPE` option (see
190
 *  wget_ssl_set_config_int()). The `WGET_SSL_KEY_FILE` option specifies the private key corresponding to the cert's
191
 *  public key. If `WGET_SSL_KEY_FILE` is not set, then the private key is expected to be in the same file as the certificate.
192
 *  - WGET_SSL_KEY_FILE: Set the private key corresponding to the client certificate specified in `WGET_SSL_CERT_FILE`.
193
 *  It can be in either PEM or DER format. The format is specified in the `WGET_SSL_KEY_TYPE` option (see
194
 *  wget_ssl_set_config_int()). IF `WGET_SSL_CERT_FILE` is not set, then the certificate is expected to be in the same file
195
 *  as the private key.
196
 *  - WGET_SSL_CRL_FILE: Sets a CRL (Certificate Revocation List) file which will be used to verify client and server certificates.
197
 *  A CRL file is a black list that contains the serial numbers of the certificates that should not be treated as valid. Whenever
198
 *  a client or a server presents a certificate in the TLS handshake whose serial number is contained in the CRL, the handshake
199
 *  will be immediately aborted. The CRL file must be in PEM format.
200
 *  - WGET_SSL_OCSP_SERVER: Set the URL of the OCSP server that will be used to validate certificates.
201
 *  OCSP is a protocol by which a server is queried to tell whether a given certificate is valid or not. It's an approach contrary
202
 *  to that used by CRLs. While CRLs are black lists, OCSP takes a white list approach where a certificate can be checked for validity.
203
 *  Whenever a client or server presents a certificate in a TLS handshake, the provided URL will be queried (using OCSP) to check whether
204
 *  that certificate is valid or not. If the server responds the certificate is not valid, the handshake will be immediately aborted.
205
 *  - WGET_SSL_ALPN: Sets the ALPN string to be sent to the remote host. ALPN is a TLS extension
206
 *  ([RFC 7301](https://tools.ietf.org/html/rfc7301))
207
 *  that allows both the server and the client to signal which application-layer protocols they support (HTTP/2, QUIC, etc.).
208
 *  That information can then be used for the server to ultimately decide which protocol will be used on top of TLS.
209
 *
210
 *  An invalid value for \p key will not harm the operation of TLS, but will cause
211
 *  a complain message to be printed to the error log stream.
212
 */
213
void wget_ssl_set_config_string(int key, const char *value)
214
65.4k
{
215
65.4k
  switch (key) {
216
9.34k
  case WGET_SSL_SECURE_PROTOCOL: config.secure_protocol = value; break;
217
9.34k
  case WGET_SSL_CA_DIRECTORY: config.ca_directory = value; break;
218
9.34k
  case WGET_SSL_CA_FILE: config.ca_file = value; break;
219
9.34k
  case WGET_SSL_CERT_FILE: config.cert_file = value; break;
220
9.34k
  case WGET_SSL_KEY_FILE: config.key_file = value; break;
221
9.34k
  case WGET_SSL_CRL_FILE: config.crl_file = value; break;
222
9.34k
  case WGET_SSL_OCSP_SERVER: config.ocsp_server = value; break;
223
0
  case WGET_SSL_ALPN: config.alpn = value; break;
224
0
  default: error_printf(_("Unknown config key %d (or value must not be a string)\n"), key);
225
65.4k
  }
226
65.4k
}
227
228
/**
229
 * \param[in] key An identifier for the config parameter (starting with `WGET_SSL_`) to set
230
 * \param[in] value The value for the config parameter (a pointer)
231
 *
232
 * Set a configuration parameter, as a libwget object.
233
 *
234
 * The following parameters expect an already initialized libwget object as their value.
235
 *
236
 *  - WGET_SSL_OCSP_CACHE: This option takes a pointer to a \ref wget_ocsp_db
237
 *  structure as an argument. Such a pointer is returned when initializing the OCSP cache with wget_ocsp_db_init().
238
 *  The cache is used to store OCSP responses locally and avoid querying the OCSP server repeatedly for the same certificate.
239
 *  - WGET_SSL_SESSION_CACHE: This option takes a pointer to a \ref wget_tls_session_db structure.
240
 *  Such a pointer is returned when initializing the TLS session cache with wget_tls_session_db_init().
241
 *  This option thus sets the handle to the TLS session cache that will be used to store TLS sessions.
242
 *  The TLS session cache is used to support TLS session resumption. It stores the TLS session parameters derived from a previous TLS handshake
243
 *  (most importantly the session identifier and the master secret) so that there's no need to run the handshake again
244
 *  the next time we connect to the same host. This is useful as the handshake is an expensive process.
245
 *  - WGET_SSL_HPKP_CACHE: Set the HPKP cache to be used to verify known HPKP pinned hosts. This option takes a pointer
246
 *  to a \ref wget_hpkp_db structure. Such a pointer is returned when initializing the HPKP cache
247
 *  with wget_hpkp_db_init(). HPKP is a HTTP-level protocol that allows the server to "pin" its present and future X.509
248
 *  certificate fingerprints, to support rapid certificate change in the event that the higher level root CA
249
 *  gets compromised ([RFC 7469](https://tools.ietf.org/html/rfc7469)).
250
 */
251
252
void wget_ssl_set_config_object(int key, void *value)
253
28.0k
{
254
28.0k
  switch (key) {
255
9.34k
  case WGET_SSL_OCSP_CACHE: config.ocsp_cert_cache = (wget_ocsp_db *)value; break;
256
9.34k
  case WGET_SSL_SESSION_CACHE: config.tls_session_cache = (wget_tls_session_db *)value; break;
257
9.34k
  case WGET_SSL_HPKP_CACHE: config.hpkp_cache = (wget_hpkp_db *)value; break;
258
0
  default: error_printf(_("Unknown config key %d (or value must not be an object)\n"), key);
259
28.0k
  }
260
28.0k
}
261
262
/**
263
 * \param[in] key An identifier for the config parameter (starting with `WGET_SSL_`)
264
 * \param[in] value The value for the config parameter
265
 *
266
 * Set a configuration parameter, as an integer.
267
 *
268
 * These are the parameters that can be set (\p key can have any of these values):
269
 *
270
 *  - WGET_SSL_CHECK_CERTIFICATE: whether certificates should be verified (1) or not (0)
271
 *  - WGET_SSL_REPORT_INVALID_CERT: whether to print (1) errors/warnings regarding certificate verification or not (0)
272
 *  - WGET_SSL_CHECK_HOSTNAME: whether or not to check if the certificate's subject field
273
 *  matches the peer's hostname. This check is done according to the rules in [RFC 6125](https://tools.ietf.org/html/rfc6125)
274
 *  and typically involves checking whether the hostname and the common name (CN) field of the subject match.
275
 *  - WGET_SSL_PRINT_INFO: whether or not information should be printed about the established SSL/TLS handshake (negotiated
276
 *  ciphersuites, certificates, etc.). The default is no (0).
277
 *
278
 * The following three options all can take either `WGET_SSL_X509_FMT_PEM` (to specify the PEM format) or `WGET_SSL_X509_FMT_DER`
279
 * (for the DER format). The default in for all of them is `WGET_SSL_X509_FMT_PEM`.
280
 *
281
 *  - WGET_SSL_CA_TYPE: Specifies what's the format of the root CA certificate(s) supplied with either `WGET_SSL_CA_DIRECTORY`
282
 *  or `WGET_SSL_CA_FILE`.
283
 *  - WGET_SSL_CERT_TYPE: Specifies what's the format of the certificate file supplied with `WGET_SSL_CERT_FILE`. **The certificate
284
 *  and the private key supplied must both be of the same format.**
285
 *  - WGET_SSL_KEY_TYPE: Specifies what's the format of the private key file supplied with `WGET_SSL_KEY_FILE`. **The private key
286
 *  and the certificate supplied must both be of the same format.**
287
 *
288
 * The following two options control OCSP queries. These don't affect the CRL set with `WGET_SSL_CRL_FILE`, if any.
289
 * If both CRLs and OCSP are enabled, both will be used.
290
 *
291
 *  - WGET_SSL_OCSP: whether or not OCSP should be used. The default is yes (1).
292
 *  - WGET_SSL_OCSP_STAPLING: whether or not OCSP stapling should be used. The default is yes (1).
293
 *  - WGET_SSL_OCSP_NONCE: whether or not an OCSP nonce should be sent in the request. The default is yes (1).
294
 *  If a nonce was sent in the request, the OCSP verification will fail if the response nonce doesn't match.
295
 *  However if the response does not include a nonce extension, verification will be allowed to continue.
296
 *  The OCSP nonce extension is not a critical one.
297
 *  - WGET_SSL_OCSP_DATE: Reject the OCSP response if it's older than 3 days.
298
 */
299
void wget_ssl_set_config_int(int key, int value)
300
93.4k
{
301
93.4k
  switch (key) {
302
9.34k
  case WGET_SSL_CHECK_CERTIFICATE: config.check_certificate = !!value; break;
303
9.34k
  case WGET_SSL_REPORT_INVALID_CERT: config.report_invalid_cert = !!value; break;
304
9.34k
  case WGET_SSL_CHECK_HOSTNAME: config.check_hostname = !!value; break;
305
0
  case WGET_SSL_CA_TYPE: config.ca_type = (char)value; break;
306
9.34k
  case WGET_SSL_CERT_TYPE: config.cert_type = (char)value; break;
307
0
  case WGET_SSL_DANE: config.dane = !!value; break;
308
9.34k
  case WGET_SSL_KEY_TYPE: config.key_type = (char)value; break;
309
9.34k
  case WGET_SSL_PRINT_INFO: config.print_info = !!value; break;
310
9.34k
  case WGET_SSL_OCSP: config.ocsp = !!value; break;
311
9.34k
  case WGET_SSL_OCSP_DATE: config.ocsp_date = !!value; break;
312
9.34k
  case WGET_SSL_OCSP_STAPLING: config.ocsp_stapling = !!value; break;
313
9.34k
  case WGET_SSL_OCSP_NONCE: config.ocsp_nonce = !!value; break;
314
0
  default: error_printf(_("Unknown config key %d (or value must not be an integer)\n"), key);
315
93.4k
  }
316
93.4k
}
317
318
static const char *safe_ctime(time_t t, char *buf, size_t size)
319
0
{
320
0
  struct tm tm;
321
322
0
#pragma GCC diagnostic push
323
0
#pragma GCC diagnostic ignored "-Wformat-y2k"
324
0
  if (localtime_r(&t, &tm) && strftime(buf, size, "%c", &tm))
325
0
    return buf;
326
0
#pragma GCC diagnostic pop
327
328
0
  return "[error]";
329
0
}
330
331
static void print_x509_certificate_info(gnutls_session_t session)
332
0
{
333
0
  const char *name;
334
0
  char dn[128], timebuf[64];
335
0
  unsigned char digest[64];
336
0
  unsigned char serial[40];
337
0
  size_t dn_size = sizeof(dn);
338
0
  size_t digest_size = sizeof (digest);
339
0
  size_t serial_size = sizeof(serial);
340
0
  time_t expired, activated;
341
0
  unsigned int bits;
342
0
  int algo;
343
0
  unsigned int cert_list_size = 0, ncert;
344
0
  const gnutls_datum_t *cert_list;
345
0
  gnutls_x509_crt_t cert;
346
0
  gnutls_certificate_type_t cert_type;
347
348
0
  cert_list = gnutls_certificate_get_peers(session, &cert_list_size);
349
350
0
  for (ncert = 0; ncert < cert_list_size; ncert++) {
351
0
    if ((cert_type = gnutls_certificate_type_get(session)) == GNUTLS_CRT_X509) {
352
353
0
      if (gnutls_x509_crt_init(&cert) != GNUTLS_E_SUCCESS)
354
0
        continue;
355
356
0
      if (gnutls_x509_crt_import(cert, &cert_list[ncert], GNUTLS_X509_FMT_DER) != GNUTLS_E_SUCCESS) {
357
0
        gnutls_x509_crt_deinit(cert);
358
0
        continue;
359
0
      }
360
361
0
      info_printf(_("Certificate info [%u]:\n"), ncert);
362
363
0
      activated = gnutls_x509_crt_get_activation_time(cert);
364
0
      info_printf(_("  Valid since: %s"), safe_ctime(activated, timebuf, sizeof(timebuf)));
365
366
0
      expired = gnutls_x509_crt_get_expiration_time(cert);
367
0
      info_printf(_("  Expires: %s"), safe_ctime(expired, timebuf, sizeof(timebuf)));
368
369
0
      if (!gnutls_fingerprint(GNUTLS_DIG_SHA256, &cert_list[ncert], digest, &digest_size)) {
370
0
        char digest_hex[sizeof(digest) * 2 + 1];
371
372
0
        wget_memtohex(digest, digest_size, digest_hex, sizeof(digest_hex));
373
374
0
        info_printf(_("  Fingerprint: %s\n"), digest_hex);
375
0
      }
376
377
0
      if (!gnutls_x509_crt_get_serial(cert, serial, &serial_size)) {
378
0
        char serial_hex[sizeof(serial) * 2 + 1];
379
380
0
        wget_memtohex(serial, serial_size, serial_hex, sizeof(serial_hex));
381
382
0
        info_printf(_("  Serial number: %s\n"), serial_hex);
383
0
      }
384
385
0
      algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
386
0
      name = gnutls_pk_algorithm_get_name(algo);
387
0
      info_printf(_("  Public key: %s, %s (%u bits)\n"),
388
0
        name ? name : "Unknown",
389
0
        gnutls_sec_param_get_name(gnutls_pk_bits_to_sec_param(algo, bits)),
390
0
        bits);
391
392
0
      info_printf(_("  Version: #%d\n"), gnutls_x509_crt_get_version(cert));
393
394
0
      dn_size = sizeof(dn);
395
0
      gnutls_x509_crt_get_dn(cert, dn, &dn_size);
396
0
      info_printf(_("  DN: %s\n"), dn);
397
398
0
      dn_size = sizeof(dn);
399
0
      gnutls_x509_crt_get_issuer_dn(cert, dn, &dn_size);
400
0
      info_printf(_("  Issuer's DN: %s\n"), dn);
401
402
0
      dn_size = sizeof(dn);
403
0
      gnutls_x509_crt_get_issuer_dn_oid(cert, 0, dn, &dn_size);
404
0
      info_printf(_("  Issuer's OID: %s\n"), dn);
405
406
0
      dn_size = sizeof(dn);
407
0
      gnutls_x509_crt_get_issuer_unique_id(cert, dn, &dn_size);
408
0
      info_printf(_("  Issuer's UID: %s\n"), dn);
409
/*
410
      dn_size = sizeof(dn);
411
      gnutls_x509_crt_get_subject_key_id(cert, dn, &dn_size, NULL);
412
      info_printf(_("  Certificate Subject ID: %s\n"), dn);
413
414
      dn_size = sizeof(dn);
415
      gnutls_x509_crt_get_subject_unique_id(cert, dn, &dn_size);
416
      info_printf(_("  Certificate Subject UID: %s\n"), dn);
417
*/
418
0
      gnutls_x509_crt_deinit(cert);
419
0
    } else {
420
0
      info_printf(_("  Unknown certificate type %d\n"), (int) cert_type);
421
0
    }
422
0
  }
423
0
}
424
425
static int print_info(gnutls_session_t session)
426
0
{
427
0
  const char *tmp;
428
0
  gnutls_credentials_type_t cred;
429
0
  gnutls_kx_algorithm_t kx;
430
0
  int dhe = 0;
431
0
  int ecdh = 0;
432
433
0
  kx = gnutls_kx_get(session);
434
435
0
  info_printf(_("----\n"));
436
437
  /* Check the authentication type used and switch
438
   * to the appropriate.
439
   */
440
0
  cred = gnutls_auth_get_type(session);
441
0
  switch (cred) {
442
0
  case GNUTLS_CRD_IA:
443
0
    info_printf(_("TLS/IA session\n"));
444
0
    break;
445
446
0
  case GNUTLS_CRD_SRP:
447
0
#ifdef HAVE_GNUTLS_SRP_SERVER_GET_USERNAME
448
0
    info_printf(_("SRP session with username %s\n"), gnutls_srp_server_get_username(session));
449
0
#endif
450
0
    break;
451
452
0
  case GNUTLS_CRD_PSK:
453
    /* This returns NULL in server side.
454
     */
455
0
    if (gnutls_psk_client_get_hint(session) != NULL)
456
0
      info_printf(_("PSK authentication. PSK hint '%s'\n"), gnutls_psk_client_get_hint(session));
457
458
    /* This returns NULL in client side.
459
     */
460
0
    if (gnutls_psk_server_get_username(session) != NULL)
461
0
      info_printf(_("PSK authentication. Connected as '%s'\n"), gnutls_psk_server_get_username(session));
462
463
0
    if (kx == GNUTLS_KX_DHE_PSK)
464
0
      dhe = 1;
465
0
    else if (kx == GNUTLS_KX_ECDHE_PSK)
466
0
      ecdh = 1;
467
0
    break;
468
469
0
  case GNUTLS_CRD_ANON: /* anonymous authentication */
470
471
0
    info_printf(_("Anonymous authentication.\n"));
472
0
    if (kx == GNUTLS_KX_ANON_DH)
473
0
      dhe = 1;
474
0
    else if (kx == GNUTLS_KX_ANON_ECDH)
475
0
      ecdh = 1;
476
0
    break;
477
478
0
  case GNUTLS_CRD_CERTIFICATE: /* certificate authentication */
479
480
    /* Check if we have been using ephemeral Diffie-Hellman.
481
     */
482
0
    if (kx == GNUTLS_KX_DHE_RSA || kx == GNUTLS_KX_DHE_DSS)
483
0
      dhe = 1;
484
0
    else if (kx == GNUTLS_KX_ECDHE_RSA || kx == GNUTLS_KX_ECDHE_ECDSA)
485
0
      ecdh = 1;
486
487
    /* if the certificate list is available, then
488
     * print some information about it.
489
     */
490
0
    print_x509_certificate_info(session);
491
0
    break;
492
493
0
  default:
494
0
    if ((int) cred == -1)
495
0
      info_printf(_("Transport authentication failure\n"));
496
0
    else
497
0
      info_printf(_("Unsupported credential type %d.\n"), (int) cred);
498
0
    break;
499
0
  } /* switch */
500
501
0
  info_printf(_("----\n"));
502
503
0
  if (dhe != 0)
504
0
    info_printf(_("Ephemeral DH using prime of %d bits\n"), gnutls_dh_get_prime_bits(session));
505
0
  else if (ecdh != 0)
506
0
    info_printf(_("Ephemeral ECDH using curve %s\n"), gnutls_ecc_curve_get_name(gnutls_ecc_curve_get(session)));
507
508
  /* print the key exchange's algorithm name */
509
0
  tmp = gnutls_kx_get_name(kx);
510
0
  info_printf(_("Key Exchange: %s\n"), tmp);
511
512
  /* print the protocol's name (ie TLS 1.0) */
513
0
  tmp = gnutls_protocol_get_name(gnutls_protocol_get_version(session));
514
0
  info_printf(_("Protocol: %s\n"), tmp);
515
516
  /* print the certificate type of the peer, ie X.509 */
517
0
  tmp = gnutls_certificate_type_get_name(gnutls_certificate_type_get(session));
518
0
  info_printf(_("Certificate Type: %s\n"), tmp);
519
520
  /* print the name of the cipher used, ie 3DES. */
521
0
  tmp = gnutls_cipher_get_name(gnutls_cipher_get(session));
522
0
  info_printf(_("Cipher: %s\n"), tmp);
523
524
  /* Print the MAC algorithms name, ie SHA1 */
525
0
  tmp = gnutls_mac_get_name(gnutls_mac_get(session));
526
0
  info_printf(_("MAC: %s\n"), tmp);
527
528
0
  info_printf(_("----\n"));
529
530
0
  return 0;
531
0
}
532
533
#ifdef WITH_OCSP
534
static int
535
_generate_ocsp_data(gnutls_x509_crt_t cert, gnutls_x509_crt_t issuer,
536
      gnutls_datum_t * rdata, gnutls_datum_t *nonce)
537
0
{
538
0
  gnutls_ocsp_req_t req;
539
0
  int ret = gnutls_ocsp_req_init(&req);
540
541
0
  if (ret < 0) {
542
0
    debug_printf("ocsp_req_init: %s", gnutls_strerror(ret));
543
0
    return -1;
544
0
  }
545
546
0
  ret = gnutls_ocsp_req_add_cert(req, GNUTLS_DIG_SHA1, issuer, cert);
547
0
  if (ret < 0) {
548
0
    debug_printf("ocsp_req_add_cert: %s", gnutls_strerror(ret));
549
0
    goto error;
550
0
  }
551
552
0
  if (nonce) {
553
0
    ret = gnutls_ocsp_req_set_nonce(req, 0, nonce);
554
0
    if (ret < 0) {
555
0
      debug_printf("ocsp_req_set_nonce: %s", gnutls_strerror(ret));
556
0
      goto error;
557
0
    }
558
0
  }
559
560
0
  ret = gnutls_ocsp_req_export(req, rdata);
561
0
  if (ret) {
562
0
    debug_printf("ocsp_req_export: %s", gnutls_strerror(ret));
563
0
    goto error;
564
0
  }
565
566
0
  ret = 0;
567
0
error:
568
0
  gnutls_ocsp_req_deinit(req);
569
0
  return ret;
570
0
}
571
572
/* Returns 0 on ok, and -1 on error */
573
static int send_ocsp_request(const char *server,
574
          gnutls_x509_crt_t cert, gnutls_x509_crt_t issuer,
575
          wget_buffer **ocsp_data, gnutls_datum_t *nonce)
576
0
{
577
0
  int ret = -1;
578
0
  int server_allocated = 0;
579
0
  gnutls_datum_t body;
580
0
  wget_iri *iri;
581
0
  wget_http_request *req = NULL;
582
583
0
  if (!server) {
584
    /* try to read URL from issuer certificate */
585
0
    gnutls_datum_t data;
586
0
    unsigned i = 0;
587
0
    int rc;
588
589
0
    do {
590
0
      rc = gnutls_x509_crt_get_authority_info_access(cert, i++, GNUTLS_IA_OCSP_URI, &data, NULL);
591
0
    } while(rc < 0 && rc != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);
592
593
0
    if (rc < 0) {
594
0
      i = 0;
595
0
      do {
596
0
        rc = gnutls_x509_crt_get_authority_info_access(issuer, i++, GNUTLS_IA_OCSP_URI, &data, NULL);
597
0
      } while(rc < 0 && rc != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);
598
0
    }
599
600
0
    if (rc < 0) {
601
0
      debug_printf("Cannot find URL from issuer: %s\n", gnutls_strerror(rc));
602
0
      return -1;
603
0
    }
604
605
0
    server = wget_strmemdup((char *)data.data, data.size);
606
0
    server_allocated = 1;
607
608
0
    gnutls_free(data.data);
609
0
  }
610
611
0
  iri = wget_iri_parse(server, NULL);
612
613
0
  if (server_allocated)
614
0
    xfree(server);
615
616
0
  if (!iri)
617
0
    return -1;
618
619
0
  if (_generate_ocsp_data(cert, issuer, &body, nonce))
620
0
    goto out;
621
622
0
  if (!(req = wget_http_create_request(iri, "POST")))
623
0
    goto out;
624
625
0
  wget_http_add_header(req, "Accept-Encoding", "identity");
626
0
  wget_http_add_header(req, "Accept", "*/*");
627
0
  wget_http_add_header(req, "Connection", "close");
628
629
0
  wget_http_connection *conn;
630
0
  if (wget_http_open(&conn, iri) == WGET_E_SUCCESS) {
631
0
    wget_http_request_set_body(req, "application/ocsp-request", wget_memdup(body.data, body.size), body.size);
632
0
    req->debug_skip_body = 1;
633
0
    if (wget_http_send_request(conn, &req) == WGET_E_SUCCESS) {
634
0
      wget_http_response *resp;
635
636
0
      if ((resp = wget_http_get_response(conn))) {
637
0
        *ocsp_data = resp->body;
638
0
        resp->body = NULL;
639
0
        wget_http_free_response(&resp);
640
0
        ret = 0;
641
0
      }
642
0
    }
643
0
    wget_http_close(&conn);
644
0
  }
645
646
0
  xfree(body.data);
647
648
0
out:
649
0
  wget_http_free_request(&req);
650
0
  wget_iri_free(&iri);
651
0
  return ret;
652
0
}
653
654
static void print_ocsp_verify_res(unsigned int status)
655
0
{
656
0
  debug_printf("*** Verifying OCSP Response: ");
657
658
0
  if (status) {
659
0
    debug_printf("Failure");
660
661
0
    if (status & GNUTLS_OCSP_VERIFY_SIGNER_NOT_FOUND)
662
0
      debug_printf(", Signer cert not found");
663
664
0
    if (status & GNUTLS_OCSP_VERIFY_SIGNER_KEYUSAGE_ERROR)
665
0
      debug_printf(", Signer cert keyusage error");
666
667
0
    if (status & GNUTLS_OCSP_VERIFY_UNTRUSTED_SIGNER)
668
0
      debug_printf(", Signer cert is not trusted");
669
670
0
    if (status & GNUTLS_OCSP_VERIFY_INSECURE_ALGORITHM)
671
0
      debug_printf(", Insecure algorithm");
672
673
0
    if (status & GNUTLS_OCSP_VERIFY_SIGNATURE_FAILURE)
674
0
      debug_printf(", Signature failure");
675
676
0
    if (status & GNUTLS_OCSP_VERIFY_CERT_NOT_ACTIVATED)
677
0
      debug_printf(", Signer cert not yet activated");
678
679
0
    if (status & GNUTLS_OCSP_VERIFY_CERT_EXPIRED)
680
0
      debug_printf(", Signer cert expired");
681
682
0
    debug_printf("\n");
683
0
  } else
684
0
    debug_printf("Success\n");
685
0
}
686
687
/* three days */
688
0
#define OCSP_VALIDITY_SECS (3*60*60*24)
689
690
/* Returns:
691
 *  0: certificate is revoked
692
 *  1: certificate is ok
693
 *  -1: dunno
694
 */
695
static int check_ocsp_response(gnutls_x509_crt_t cert,
696
  gnutls_x509_crt_t issuer, wget_buffer *data,
697
  gnutls_datum_t *nonce)
698
0
{
699
0
  gnutls_ocsp_resp_t resp;
700
0
  int ret = -1, rc;
701
0
  unsigned int status, cert_status;
702
0
  time_t rtime = 0, vtime = 0, ntime = 0, now;
703
0
  char timebuf[64];
704
705
0
  now = time(NULL);
706
707
0
  if ((rc = gnutls_ocsp_resp_init(&resp)) < 0) {
708
0
    debug_printf("ocsp_resp_init: %s", gnutls_strerror(rc));
709
0
    return -1;
710
0
  }
711
712
0
  rc = gnutls_ocsp_resp_import(resp, &(gnutls_datum_t){ .data = (unsigned char *) data->data, .size = (unsigned) data->length });
713
0
  if (rc < 0) {
714
0
    debug_printf("importing response: %s", gnutls_strerror(rc));
715
0
    goto cleanup;
716
0
  }
717
718
0
  if ((rc = gnutls_ocsp_resp_check_crt(resp, 0, cert)) < 0) {
719
0
    if (rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
720
0
      debug_printf("got OCSP response with no data (ignoring)\n");
721
0
    } else {
722
0
      debug_printf("got OCSP response on an unrelated certificate (ignoring)\n");
723
0
    }
724
0
    goto cleanup;
725
0
  }
726
727
0
  if ((rc = gnutls_ocsp_resp_verify_direct(resp, issuer, &status, 0)) < 0) {
728
0
    debug_printf("gnutls_ocsp_resp_verify_direct: %s", gnutls_strerror(rc));
729
0
    goto cleanup;
730
0
  }
731
732
0
  if (status) {
733
0
    print_ocsp_verify_res(status);
734
0
    goto cleanup;
735
0
  }
736
737
0
  rc = gnutls_ocsp_resp_get_single(resp, 0, NULL, NULL, NULL, NULL,
738
0
            &cert_status, &vtime, &ntime, &rtime, NULL);
739
0
  if (rc < 0) {
740
0
    debug_printf("reading response: %s", gnutls_strerror(rc));
741
0
    goto cleanup;
742
0
  }
743
744
0
  if (cert_status == GNUTLS_OCSP_CERT_REVOKED) {
745
0
    debug_printf("*** Certificate was revoked at %s", safe_ctime(rtime, timebuf, sizeof(timebuf)));
746
0
    ret = 0;
747
0
    goto cleanup;
748
0
  }
749
750
0
  debug_printf("*** OCSP issued time: %s\n", safe_ctime(vtime, timebuf, sizeof(timebuf)));
751
0
  debug_printf("*** OCSP update time  : %s\n", safe_ctime(ntime, timebuf, sizeof(timebuf)));
752
753
0
  if (ntime == -1) {
754
0
    if (config.ocsp_date && now - vtime > OCSP_VALIDITY_SECS) {
755
0
      debug_printf("*** The OCSP response is old (was issued at: %s) ignoring", safe_ctime(vtime, timebuf, sizeof(timebuf)));
756
0
      goto cleanup;
757
0
    }
758
0
  } else {
759
    /* there is a newer OCSP answer, don't trust this one */
760
0
    if (ntime < now) {
761
0
      debug_printf("*** The OCSP response was issued at: %s", safe_ctime(vtime, timebuf, sizeof(timebuf)));
762
0
      debug_printf("    but there is a newer issue at %s", safe_ctime(ntime, timebuf, sizeof(timebuf)));
763
0
      goto cleanup;
764
0
    }
765
0
  }
766
767
0
  if (nonce) {
768
0
    gnutls_datum_t rnonce;
769
770
0
    rc = gnutls_ocsp_resp_get_nonce(resp, NULL, &rnonce);
771
0
    if (rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
772
0
      debug_printf("*** The OCSP reply did not include the requested nonce.\n");
773
0
      goto finish_ok;
774
0
    }
775
776
0
    if (rc < 0) {
777
0
      debug_printf("could not read response's nonce: %s\n", gnutls_strerror(rc));
778
0
      goto cleanup;
779
0
    }
780
781
0
    if (config.ocsp_nonce && (rnonce.size != nonce->size || memcmp(nonce->data, rnonce.data, nonce->size) != 0)) {
782
0
      debug_printf("nonce in the response doesn't match\n");
783
0
      xfree(rnonce.data);
784
0
      goto cleanup;
785
0
    }
786
787
0
    xfree(rnonce.data);
788
0
  }
789
790
0
 finish_ok:
791
0
  debug_printf("OCSP server flags certificate not revoked as of %s", safe_ctime(vtime, timebuf, sizeof(timebuf)));
792
0
  ret = 1;
793
794
0
cleanup:
795
0
  gnutls_ocsp_resp_deinit(resp);
796
0
  return ret;
797
0
}
798
799
/*
800
 * Calculate fingerprint from certificate
801
 */
802
static char *_get_cert_fingerprint(gnutls_x509_crt_t cert, char *fingerprint_hex, size_t length)
803
0
{
804
0
  unsigned char fingerprint[64];
805
0
  size_t fingerprint_size = sizeof(fingerprint);
806
0
  int err;
807
808
0
  if ((err = gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA256, fingerprint, &fingerprint_size)) < 0) {
809
0
    debug_printf("Failed to get fingerprint: %s\n", gnutls_strerror(err));
810
0
    wget_strscpy(fingerprint_hex, "00", length);
811
0
  } else {
812
0
    wget_memtohex(fingerprint, fingerprint_size, fingerprint_hex, length);
813
0
  }
814
815
0
  return fingerprint_hex;
816
0
}
817
818
/*
819
 * Add cert to OCSP cache, being either valid or revoked (valid==0)
820
 */
821
static void add_cert_to_ocsp_cache(gnutls_x509_crt_t cert, bool valid)
822
0
{
823
0
  if (config.ocsp_cert_cache) {
824
0
    char fingerprint_hex[64 * 2 +1];
825
826
0
    _get_cert_fingerprint(cert, fingerprint_hex, sizeof(fingerprint_hex));
827
0
    wget_ocsp_db_add_fingerprint(config.ocsp_cert_cache, fingerprint_hex, time(NULL) + 3600, valid); // 1h valid
828
0
  }
829
0
}
830
831
/* OCSP check for the peer's certificate. Should be called
832
 * only after the certificate list verification is complete.
833
 * Returns:
834
 * 0: certificate is revoked
835
 * 1: certificate is ok
836
 * -1: dunno
837
 */
838
//static int cert_verify_ocsp(gnutls_session_t session)
839
static int cert_verify_ocsp(gnutls_x509_crt_t cert, gnutls_x509_crt_t issuer)
840
0
{
841
0
  wget_buffer *resp = NULL;
842
0
  unsigned char noncebuf[23];
843
0
  gnutls_datum_t nonce = { noncebuf, sizeof(noncebuf) };
844
0
  int ret;
845
846
0
  ret = gnutls_rnd(GNUTLS_RND_NONCE, nonce.data, nonce.size);
847
0
  if (ret < 0) {
848
0
    debug_printf("gnutls_rnd: %s", gnutls_strerror(ret));
849
0
    return -1;
850
0
  }
851
852
0
  if (send_ocsp_request(config.ocsp_server, cert, issuer, &resp, &nonce) < 0) {
853
0
    debug_printf("Cannot contact OCSP server\n");
854
0
    return -1;
855
0
  }
856
857
0
  if (!resp) {
858
0
    debug_printf("Missing response from OCSP server\n");
859
0
    return -1;
860
0
  }
861
862
  /* verify and check the response for revoked cert */
863
0
  ret = check_ocsp_response(cert, issuer, resp, &nonce);
864
0
  wget_buffer_free(&resp);
865
866
0
  return ret;
867
0
}
868
#endif // WITH_OCSP
869
870
static int cert_verify_hpkp(gnutls_x509_crt_t cert, const char *hostname, gnutls_session_t session)
871
0
{
872
0
  gnutls_pubkey_t key = NULL;
873
0
  int rc, ret = -1;
874
0
  struct session_context *ctx = gnutls_session_get_ptr(session);
875
876
0
  if (!config.hpkp_cache)
877
0
    return 0;
878
879
0
  gnutls_pubkey_init(&key);
880
881
0
  if ((rc = gnutls_pubkey_import_x509(key, cert, 0)) != GNUTLS_E_SUCCESS) {
882
0
    error_printf(_("Failed to import pubkey: %s\n"), gnutls_strerror(rc));
883
0
    return 0;
884
0
  }
885
886
0
  gnutls_datum_t pubkey;
887
888
0
  if ((rc = gnutls_pubkey_export2(key, GNUTLS_X509_FMT_DER, &pubkey)) != GNUTLS_E_SUCCESS) {
889
0
    error_printf(_("Failed to export pubkey: %s\n"), gnutls_strerror(rc));
890
0
    ret = 0;
891
0
    goto out;
892
0
  }
893
894
0
  rc = wget_hpkp_db_check_pubkey(config.hpkp_cache, hostname, pubkey.data, pubkey.size);
895
0
  xfree(pubkey.data);
896
897
0
  if (rc != -2) {
898
0
    if (rc == 0) {
899
0
      debug_printf("host has no pubkey pinnings stored in hpkp db\n");
900
0
      ctx->stats_hpkp = WGET_STATS_HPKP_NO;
901
0
    } else if (rc == 1) {
902
0
      debug_printf("pubkey is matching a pinning\n");
903
0
      ctx->stats_hpkp = WGET_STATS_HPKP_MATCH;
904
0
    } else if (rc == -1) {
905
0
      debug_printf("Error while checking pubkey pinning\n");
906
0
      ctx->stats_hpkp = WGET_STATS_HPKP_ERROR;
907
0
    }
908
0
    ret = 0;
909
0
  } else
910
0
    ctx->stats_hpkp = WGET_STATS_HPKP_NOMATCH;
911
912
0
out:
913
0
  gnutls_pubkey_deinit(key);
914
0
  return ret; // Pubkey not found
915
0
}
916
917
0
static void print_verification_status(gnutls_session_t session, const char *tag, int status) {
918
0
  gnutls_datum_t out;
919
920
0
  if (gnutls_certificate_verification_status_print(
921
0
    status, gnutls_certificate_type_get(session), &out, 0) == GNUTLS_E_SUCCESS)
922
0
  {
923
0
    error_printf_check("%s: %s\n", tag, out.data); // no translation
924
0
    xfree(out.data);
925
0
  }
926
0
}
927
928
/* This function will verify the peer's certificate, and check
929
 * if the hostname matches, as well as the activation, expiration dates.
930
 */
931
static int verify_certificate_callback(gnutls_session_t session)
932
0
{
933
0
  unsigned int status, deinit_cert = 0, deinit_issuer = 0;
934
0
  const gnutls_datum_t *cert_list = NULL;
935
0
  unsigned int cert_list_size;
936
0
  int ret = -1, err, ocsp_ok = 0;
937
0
  gnutls_x509_crt_t cert = NULL, issuer = NULL;
938
0
  const char *tag = config.check_certificate ? _("ERROR") : _("WARNING");
939
0
#ifdef WITH_OCSP
940
0
  bool skip_server_cert_check = false;
941
0
  unsigned nvalid = 0, nrevoked = 0, nignored = 0;
942
0
#endif
943
944
  // read hostname
945
0
  struct session_context *ctx = gnutls_session_get_ptr(session);
946
0
  const char *hostname = ctx->hostname;
947
948
  /* This verification function uses the trusted CAs in the credentials
949
   * structure. So you must have installed one or more CA certificates.
950
   */
951
0
  gnutls_typed_vdata_st data[] = {
952
0
    {
953
0
      .type = GNUTLS_DT_DNS_HOSTNAME,
954
0
      .data = (void *) hostname,
955
0
    },
956
0
    {
957
0
      .type = GNUTLS_DT_KEY_PURPOSE_OID,
958
0
      .data = (void *) GNUTLS_KP_TLS_WWW_SERVER,
959
0
    }
960
0
  };
961
0
  unsigned elements = config.check_certificate ? countof(data) : 1;
962
963
0
  if (gnutls_certificate_verify_peers(session, data, elements, &status) != GNUTLS_E_SUCCESS) {
964
0
    error_printf_check(_("%s: Certificate verification error\n"), tag);
965
0
    goto out;
966
0
  }
967
968
0
#ifdef WITH_OCSP
969
0
  if (status & GNUTLS_CERT_REVOKED) {
970
0
    if (config.ocsp_cert_cache)
971
0
      wget_ocsp_db_add_host(config.ocsp_cert_cache, hostname, 0); // remove entry from cache
972
0
    if (ctx->ocsp_stapling) {
973
0
      if (gnutls_x509_crt_init(&cert) == GNUTLS_E_SUCCESS) {
974
0
        if ((cert_list = gnutls_certificate_get_peers(session, &cert_list_size))) {
975
0
          if (gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER) == GNUTLS_E_SUCCESS) {
976
0
            add_cert_to_ocsp_cache(cert, false);
977
0
          }
978
0
        }
979
0
        gnutls_x509_crt_deinit(cert);
980
0
      }
981
0
    }
982
0
  }
983
0
#endif
984
985
#ifdef WITH_LIBDANE
986
  // If CA cert verification failed due to missing certificates, we try DANE verification (if requested by the user).
987
  if (status) {
988
    if (!config.dane) {
989
      print_verification_status(session, tag, status);
990
      goto out;
991
    }
992
    if (status != (GNUTLS_CERT_INVALID | GNUTLS_CERT_SIGNER_NOT_FOUND)) {
993
      print_verification_status(session, tag, status);
994
      goto out;
995
    }
996
997
    // GNUTLS_CERT_SIGNER_NOT_FOUND indicates that no matching CA cert exists.
998
999
    unsigned verify = 0;
1000
1001
    int rc = dane_verify_session_crt(NULL, session, hostname, "tcp", ctx->port, 0,
1002
      DANE_VFLAG_FAIL_IF_NOT_CHECKED,
1003
      &verify);
1004
1005
    if (rc < 0) {
1006
      debug_printf("DANE verification error for %s: %s\n", hostname, dane_strerror(rc));
1007
      goto out;
1008
    } else if (verify) {
1009
      gnutls_datum_t out;
1010
      rc = dane_verification_status_print(verify, &out, 0);
1011
      if (rc < 0) {
1012
        error_printf(_("DANE verification print error for %s: %s\n"), hostname, dane_strerror(rc));
1013
      } else {
1014
        error_printf(_("DANE verification failed for %s: %s\n"), hostname, out.data);
1015
      }
1016
      gnutls_free(out.data);
1017
      goto out;
1018
    } else {
1019
      debug_printf("DANE verification: %s\n", dane_strerror(rc));
1020
    }
1021
  }
1022
#else
1023
0
  if (status) {
1024
0
    print_verification_status(session, tag, status);
1025
0
    goto out;
1026
0
  }
1027
0
#endif
1028
1029
  /* Up to here the process is the same for X.509 certificates and
1030
   * OpenPGP keys. From now on X.509 certificates are assumed. This can
1031
   * be easily extended to work with openpgp keys as well.
1032
   */
1033
0
  if (gnutls_certificate_type_get(session) != GNUTLS_CRT_X509) {
1034
0
    error_printf_check(_("%s: Certificate must be X.509\n"), tag);
1035
0
    goto out;
1036
0
  }
1037
1038
0
  if (gnutls_x509_crt_init(&cert) != GNUTLS_E_SUCCESS) {
1039
0
    error_printf_check(_("%s: Error initializing X.509 certificate\n"), tag);
1040
0
    goto out;
1041
0
  }
1042
0
  deinit_cert = 1;
1043
1044
0
  if (!(cert_list = gnutls_certificate_get_peers(session, &cert_list_size))) {
1045
0
    error_printf_check(_("%s: No certificate was found!\n"), tag);
1046
0
    goto out;
1047
0
  }
1048
1049
0
  if ((err = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER)) != GNUTLS_E_SUCCESS) {
1050
0
    error_printf_check(_("%s: Failed to parse certificate: %s\n"), tag, gnutls_strerror (err));
1051
0
    goto out;
1052
0
  }
1053
1054
0
  if (config.check_hostname) {
1055
0
    if (!hostname || !gnutls_x509_crt_check_hostname(cert, hostname)) {
1056
0
      error_printf_check(_("%s: Hostname mismatch or missing\n"), tag);
1057
0
      goto out; // Fail immediately
1058
0
    }
1059
0
  }
1060
1061
  // At this point, the cert chain has been found valid regarding the locally available CA certificates and CRLs.
1062
  // Now, we are going to check the revocation status via OCSP
1063
0
#ifdef WITH_OCSP
1064
0
  if (config.ocsp_stapling) {
1065
0
    if (!ctx->valid && ctx->ocsp_stapling) {
1066
0
      if (gnutls_ocsp_status_request_is_checked(session, 0)) {
1067
0
        debug_printf("Server certificate is valid regarding OCSP stapling\n");
1068
//        _get_cert_fingerprint(cert, fingerprint, sizeof(fingerprint)); // calc hexadecimal fingerprint string
1069
0
        add_cert_to_ocsp_cache(cert, true);
1070
0
        nvalid = 1;
1071
0
        skip_server_cert_check = true;
1072
0
      }
1073
0
      else if (gnutls_ocsp_status_request_is_checked(session, GNUTLS_OCSP_SR_IS_AVAIL)) {
1074
0
        error_printf_check(_("WARNING: The certificate's (stapled) OCSP status is invalid\n"));
1075
0
        skip_server_cert_check = true;
1076
0
      }
1077
0
      else if (!config.ocsp) {
1078
0
        debug_printf("OCSP stapling is not supported by '%s'\n", hostname);
1079
0
      } else {
1080
0
        error_printf_check(_("WARNING: OCSP stapling is not supported by '%s', but OCSP validation has been requested.\n"), hostname);
1081
0
        error_printf_check(_("WARNING: This implies a privacy leak: the client sends the certificate serial ID over HTTP to the CA.\n"));
1082
0
      }
1083
0
    } else if (ctx->valid)
1084
0
      debug_printf("OCSP: Host '%s' is valid (from cache)\n", hostname);
1085
0
  }
1086
0
#endif
1087
1088
0
  for (unsigned it = 0; it < cert_list_size; it++) {
1089
0
    gnutls_x509_crt_deinit(cert);
1090
0
    gnutls_x509_crt_init(&cert);
1091
1092
0
    if ((err = gnutls_x509_crt_import(cert, &cert_list[it], GNUTLS_X509_FMT_DER)) != GNUTLS_E_SUCCESS) {
1093
0
      error_printf_check(_("%s: Failed to parse certificate[%u]: %s\n"), tag, it, gnutls_strerror (err));
1094
0
      goto out;
1095
0
    }
1096
1097
0
    if (cert_verify_hpkp(cert, hostname, session) != 0) {
1098
0
      error_printf_check(_("%s: Pubkey pinning mismatch!\n"), tag);
1099
0
      goto out;
1100
0
    }
1101
1102
0
#ifdef WITH_OCSP
1103
0
    if (!config.ocsp || (skip_server_cert_check && it == 0))
1104
0
      continue;
1105
1106
0
    char fingerprint[64 * 2 +1];
1107
0
    _get_cert_fingerprint(cert, fingerprint, sizeof(fingerprint)); // calc hexadecimal fingerprint string
1108
1109
0
    int revoked;
1110
0
    if (wget_ocsp_fingerprint_in_cache(config.ocsp_cert_cache, fingerprint, &revoked)) {
1111
      // found cert's fingerprint in cache
1112
0
      if (revoked) {
1113
0
        debug_printf("Certificate[%u] of '%s' has been revoked (cached)\n", it, hostname);
1114
0
        nrevoked++;
1115
0
      } else {
1116
0
        debug_printf("Certificate[%u] of '%s' is valid (cached)\n", it, hostname);
1117
0
        nvalid++;
1118
0
      }
1119
0
      continue;
1120
0
    }
1121
1122
0
    if (deinit_issuer) {
1123
0
      gnutls_x509_crt_deinit(issuer);
1124
0
      deinit_issuer = 0;
1125
0
    }
1126
0
    if ((err = gnutls_certificate_get_issuer(credentials, cert, &issuer, 0)) != GNUTLS_E_SUCCESS && it < cert_list_size - 1) {
1127
0
      gnutls_x509_crt_init(&issuer);
1128
0
      deinit_issuer = 1;
1129
0
      if ((err = gnutls_x509_crt_import(issuer, &cert_list[it + 1], GNUTLS_X509_FMT_DER))  != GNUTLS_E_SUCCESS) {
1130
0
        debug_printf("Decoding error: %s\n", gnutls_strerror(err));
1131
0
        goto out;
1132
0
      }
1133
0
    } else if (err  != GNUTLS_E_SUCCESS) {
1134
0
      debug_printf("Cannot find issuer: %s\n", gnutls_strerror(err));
1135
0
      goto out;
1136
0
    }
1137
1138
0
    ocsp_ok = cert_verify_ocsp(cert, issuer);
1139
0
    debug_printf("check_ocsp_response() returned %d\n", ocsp_ok);
1140
1141
0
    if (ocsp_ok == 1) {
1142
0
      debug_printf("Certificate[%u] of '%s' is valid (via OCSP)\n", it, hostname);
1143
0
      wget_ocsp_db_add_fingerprint(config.ocsp_cert_cache, fingerprint, time(NULL) + 3600, true); // 1h valid
1144
0
      nvalid++;
1145
0
    } else if (ocsp_ok == 0) {
1146
0
      debug_printf("%s: Certificate[%u] of '%s' has been revoked (via OCSP)\n", tag, it, hostname);
1147
0
      wget_ocsp_db_add_fingerprint(config.ocsp_cert_cache, fingerprint, time(NULL) + 3600, false);  // cert has been revoked
1148
0
      nrevoked++;
1149
0
    } else {
1150
0
      debug_printf("WARNING: OCSP response not available or ignored\n");
1151
0
      nignored++;
1152
0
    }
1153
0
#endif
1154
0
  }
1155
1156
0
#ifdef WITH_OCSP
1157
0
  if (config.ocsp && ocsp_stats_callback) {
1158
0
    wget_ocsp_stats_data stats;
1159
0
    stats.hostname = hostname;
1160
0
    stats.nvalid = nvalid;
1161
0
    stats.nrevoked = nrevoked;
1162
0
    stats.nignored = nignored;
1163
0
    stats.stapling = ctx->ocsp_stapling;
1164
1165
0
    ocsp_stats_callback(&stats, ocsp_stats_ctx);
1166
0
  }
1167
1168
0
  if (config.ocsp_stapling || config.ocsp) {
1169
0
    if (nvalid == cert_list_size) {
1170
0
      wget_ocsp_db_add_host(config.ocsp_cert_cache, hostname, time(NULL) + 3600); // 1h valid
1171
0
    } else if (nrevoked) {
1172
0
      wget_ocsp_db_add_host(config.ocsp_cert_cache, hostname, 0); // remove entry from cache
1173
0
      goto out;
1174
0
    }
1175
0
  }
1176
0
#endif
1177
1178
0
  ret = 0;
1179
1180
  // 0: continue handshake
1181
  // else: stop handshake
1182
0
out:
1183
0
  if (deinit_cert)
1184
0
    gnutls_x509_crt_deinit(cert);
1185
0
  if (deinit_issuer)
1186
0
    gnutls_x509_crt_deinit(issuer);
1187
1188
0
  return config.check_certificate ? ret : 0;
1189
0
}
1190
1191
static int init;
1192
static wget_thread_mutex mutex;
1193
1194
static void tls_exit(void)
1195
0
{
1196
0
  if (mutex)
1197
0
    wget_thread_mutex_destroy(&mutex);
1198
0
}
1199
1200
INITIALIZER(tls_init)
1201
4
{
1202
4
  if (!mutex) {
1203
4
    wget_thread_mutex_init(&mutex);
1204
1205
    // Initialize paths while in a thread-safe environment (mostly for _WIN32).
1206
4
    wget_ssl_default_cert_dir();
1207
4
    wget_ssl_default_ca_bundle_path();
1208
1209
4
    atexit(tls_exit);
1210
4
  }
1211
4
}
1212
1213
static int key_type(int type)
1214
0
{
1215
0
  if (type == WGET_SSL_X509_FMT_DER)
1216
0
    return GNUTLS_X509_FMT_DER;
1217
1218
0
  return GNUTLS_X509_FMT_PEM;
1219
0
}
1220
1221
// ssl_init() is thread safe
1222
1223
static void set_credentials(gnutls_certificate_credentials_t creds)
1224
0
{
1225
0
  if (config.cert_file && !config.key_file) {
1226
    // Use the private key from the cert file unless otherwise specified.
1227
0
    config.key_file = config.cert_file;
1228
0
    config.key_type = config.cert_type;
1229
0
  }
1230
0
  else if (!config.cert_file && config.key_file) {
1231
    // Use the cert from the private key file unless otherwise specified.
1232
0
    config.cert_file = config.key_file;
1233
0
    config.cert_type = config.key_type;
1234
0
  }
1235
1236
0
  if (config.cert_file && config.key_file) {
1237
0
    if (config.key_type != config.cert_type) {
1238
      // GnuTLS can't handle this
1239
0
      error_printf(_("GnuTLS requires the key and the cert to be of the same type.\n"));
1240
0
    }
1241
1242
0
    if (gnutls_certificate_set_x509_key_file(creds, config.cert_file, config.key_file, key_type(config.key_type)) != GNUTLS_E_SUCCESS)
1243
0
      error_printf(_("No certificates or keys were found\n"));
1244
0
  }
1245
1246
0
  if (config.ca_file && !wget_strcmp(config.ca_file, "system"))
1247
0
    config.ca_file = wget_ssl_default_ca_bundle_path();
1248
0
  if (config.ca_file) {
1249
0
    if (gnutls_certificate_set_x509_trust_file(creds, config.ca_file, key_type(config.ca_type)) <= 0)
1250
0
      error_printf(_("No CAs were found in '%s'\n"), config.ca_file);
1251
0
  }
1252
0
}
1253
1254
/**
1255
 * Initialize the SSL/TLS engine as a client.
1256
 *
1257
 * This function assumes the caller is an SSL client connecting to a server.
1258
 * The functions wget_ssl_open(), wget_ssl_close() and wget_ssl_deinit() can be called
1259
 * after this.
1260
 *
1261
 * This is where the root certificates get loaded from the folder specified in the
1262
 * `WGET_SSL_CA_DIRECTORY` parameter. If any of the files in that folder cannot be loaded
1263
 * for whatever reason, that file will be silently skipped without harm (a message will be
1264
 * printed to the debug log stream).
1265
 *
1266
 * CLRs and private keys and their certificates are also loaded here.
1267
 *
1268
 * On systems with automatic library constructors/destructors, this function
1269
 * is thread-safe. On other systems it is not thread-safe.
1270
 *
1271
 * This function may be called several times. Only the first call really
1272
 * takes action.
1273
 */
1274
void wget_ssl_init(void)
1275
0
{
1276
0
  tls_init();
1277
1278
0
  wget_thread_mutex_lock(mutex);
1279
1280
0
  if (!init) {
1281
0
    int rc, ncerts = -1;
1282
1283
0
    debug_printf("GnuTLS init\n");
1284
0
    gnutls_global_init();
1285
0
    gnutls_certificate_allocate_credentials(&credentials);
1286
0
    gnutls_certificate_set_verify_function(credentials, verify_certificate_callback);
1287
1288
0
    if (config.ca_directory && *config.ca_directory && config.check_certificate) {
1289
0
      if (!strcmp(config.ca_directory, "system")) {
1290
0
        ncerts = gnutls_certificate_set_x509_system_trust(credentials);
1291
0
        if (ncerts < 0)
1292
0
          debug_printf("GnuTLS system certificate store error %d\n", ncerts);
1293
0
        else
1294
0
          debug_printf("GnuTLS system certificate store is empty\n");
1295
0
      }
1296
1297
0
      if (ncerts < 0) {
1298
0
        DIR *dir;
1299
1300
0
        ncerts = 0;
1301
1302
0
        if (!strcmp(config.ca_directory, "system"))
1303
0
          config.ca_directory = wget_ssl_default_cert_dir();
1304
1305
0
        if ((dir = opendir(config.ca_directory))) {
1306
0
          struct dirent *dp;
1307
1308
0
          while ((dp = readdir(dir))) {
1309
0
            size_t len = strlen(dp->d_name);
1310
1311
0
            if (len >= 4 && !wget_strncasecmp_ascii(dp->d_name + len - 4, ".pem", 4)) {
1312
0
              char *fname = wget_aprintf("%s/%s", config.ca_directory, dp->d_name);
1313
1314
0
              if (!fname) {
1315
0
                error_printf(_("Failed to allocate file name for cert '%s/%s'\n"), config.ca_directory, dp->d_name);
1316
0
                continue;
1317
0
              }
1318
1319
0
              struct stat st;
1320
0
              if (stat(fname, &st) == 0 && S_ISREG(st.st_mode)) {
1321
0
                debug_printf("GnuTLS loading %s\n", fname);
1322
0
                if ((rc = gnutls_certificate_set_x509_trust_file(credentials, fname, GNUTLS_X509_FMT_PEM)) <= 0)
1323
0
                  debug_printf("Failed to load cert '%s': (%d)\n", fname, rc);
1324
0
                else
1325
0
                  ncerts += rc;
1326
0
              }
1327
1328
0
              xfree(fname);
1329
0
            }
1330
0
          }
1331
1332
0
          closedir(dir);
1333
0
        } else {
1334
0
          error_printf(_("Failed to opendir %s\n"), config.ca_directory);
1335
0
        }
1336
0
      }
1337
0
    }
1338
1339
0
    if (config.crl_file) {
1340
0
      if ((rc = gnutls_certificate_set_x509_crl_file(credentials, config.crl_file, GNUTLS_X509_FMT_PEM)) <= 0)
1341
0
        error_printf(_("Failed to load CRL '%s': (%d)\n"), config.crl_file, rc);
1342
0
    }
1343
1344
0
    set_credentials(credentials);
1345
1346
0
    debug_printf("Certificates loaded: %d\n", ncerts);
1347
1348
0
    if (!config.secure_protocol || !wget_strcasecmp_ascii(config.secure_protocol, "auto")) {
1349
      // use GnuTLS defaults, which might hold insecure ciphers
1350
0
      if ((rc = gnutls_priority_init(&priority_cache, NULL, NULL)))
1351
0
        error_printf(_("GnuTLS: Unsupported default priority 'NULL': %s\n"), gnutls_strerror(rc));
1352
0
    } else {
1353
0
      const char *priorities = NULL;
1354
1355
0
      if (!wget_strcasecmp_ascii(config.secure_protocol, "PFS"))
1356
0
        priorities = "PFS:-RSA:-VERS-SSL3.0";
1357
0
      else if (!wget_strncasecmp_ascii(config.secure_protocol, "SSL", 3))
1358
0
        priorities = "-VERS-TLS-ALL:+VERS-SSL3.0"; // SSLv3 only
1359
0
      else if (!wget_strcasecmp_ascii(config.secure_protocol, "TLSv1"))
1360
0
        priorities = "-VERS-SSL3.0";
1361
0
      else if (!wget_strcasecmp_ascii(config.secure_protocol, "TLSv1_1"))
1362
0
        priorities = "-VERS-SSL3.0:-VERS-TLS1.0";
1363
0
      else if (!wget_strcasecmp_ascii(config.secure_protocol, "TLSv1_2"))
1364
0
        priorities = "-VERS-SSL3.0:-VERS-TLS1.0:-VERS-TLS1.1";
1365
0
      else if (!wget_strcasecmp_ascii(config.secure_protocol, "TLSv1_3"))
1366
0
        priorities = "-VERS-SSL3.0:-VERS-TLS1.0:-VERS-TLS1.1:-VERS-TLS1.2:+VERS-TLS1.3";
1367
0
      else if (*config.secure_protocol)
1368
0
        priorities = config.secure_protocol; // user-defined priorities
1369
1370
0
      rc = gnutls_priority_init2(&priority_cache, priorities, NULL, GNUTLS_PRIORITY_INIT_DEF_APPEND);
1371
0
      if (rc != GNUTLS_E_SUCCESS)
1372
0
        error_printf(_("GnuTLS: Unsupported priority string '%s': %s\n"), priorities ? priorities : "(null)", gnutls_strerror(rc));
1373
0
    }
1374
1375
0
    init++;
1376
1377
0
    debug_printf("GnuTLS init done\n");
1378
0
  }
1379
1380
0
  wget_thread_mutex_unlock(mutex);
1381
0
}
1382
1383
/**
1384
 * Deinitialize the SSL/TLS engine, after it has been initialized
1385
 * with wget_ssl_init().
1386
 *
1387
 * This function unloads everything that was loaded in wget_ssl_init().
1388
 *
1389
 * On systems with automatic library constructors/destructors, this function
1390
 * is thread-safe. On other systems it is not thread-safe.
1391
 *
1392
 * This function may be called several times. Only the last deinit really
1393
 * takes action.
1394
 */
1395
void wget_ssl_deinit(void)
1396
0
{
1397
0
  wget_thread_mutex_lock(mutex);
1398
1399
0
  if (init == 1) {
1400
0
    gnutls_certificate_free_credentials(credentials);
1401
0
    gnutls_priority_deinit(priority_cache);
1402
0
    gnutls_global_deinit();
1403
0
  }
1404
1405
0
  if (init > 0) init--;
1406
1407
0
  wget_thread_mutex_unlock(mutex);
1408
0
}
1409
1410
static int do_handshake(gnutls_session_t session, int sockfd, int timeout)
1411
0
{
1412
0
  int ret;
1413
1414
  // Wait for socket being ready before we call gnutls_handshake().
1415
  // I had problems on a KVM Win7 + CygWin (gnutls 3.2.4-1).
1416
0
  int rc = wget_ready_2_write(sockfd, timeout);
1417
1418
0
  if (rc == 0)
1419
0
    ret = WGET_E_TIMEOUT;
1420
0
  else
1421
0
    ret = WGET_E_HANDSHAKE;
1422
1423
  // Perform the TLS handshake
1424
0
  while (rc > 0) {
1425
0
    rc = gnutls_handshake(session);
1426
1427
0
    if (rc == GNUTLS_E_SUCCESS) {
1428
0
      ret = WGET_E_SUCCESS;
1429
0
      break;
1430
0
    }
1431
1432
0
    if (gnutls_error_is_fatal(rc)) {
1433
0
      debug_printf("gnutls_handshake: (%d) %s (errno=%d)\n", rc, gnutls_strerror(rc), errno);
1434
1435
0
      if (rc == GNUTLS_E_CERTIFICATE_ERROR) {
1436
0
        ret = WGET_E_CERTIFICATE;
1437
0
      } else if (rc == GNUTLS_E_PUSH_ERROR && (errno == ECONNREFUSED || errno == ENOTCONN)) {
1438
        /*
1439
         * ECONNREFUSED: on Linux
1440
         * ENOTCONN: MinGW (in out Gitlab CI runner)
1441
         */
1442
0
        ret = WGET_E_CONNECT;
1443
0
      } else if (rc == GNUTLS_E_PULL_ERROR && errno == 61 /* ENODATA, but not on OSX/Travis ? */) {
1444
        // We see this with older versions of GnuTLS, e.g. on TravisCI. (Tim, 11.4.2018)
1445
        // It happens when trying to connect to a port without a listener
1446
0
        ret = WGET_E_CONNECT;
1447
0
      } else if (rc == GNUTLS_E_PREMATURE_TERMINATION && errno == EAGAIN) {
1448
        // It happens when trying to connect to a closed port
1449
0
        ret = WGET_E_CONNECT;
1450
0
      } else if (rc == GNUTLS_E_UNEXPECTED_PACKET_LENGTH && errno == EAGAIN) {
1451
        // We see this with older versions of GnuTLS, e.g. on TravisCI. (Tim, 11.4.2018)
1452
        // It happens when trying to connect to a port without a listener
1453
0
        ret = WGET_E_CONNECT;
1454
0
      } else
1455
0
        ret = WGET_E_HANDSHAKE;
1456
1457
0
      break;
1458
0
    }
1459
1460
0
    if (gnutls_record_get_direction(session)) {
1461
      // wait for writeability
1462
0
      rc = wget_ready_2_write(sockfd, timeout);
1463
0
    } else {
1464
      // wait for readability
1465
0
      rc = wget_ready_2_read(sockfd, timeout);
1466
0
    }
1467
0
  }
1468
1469
0
  if (ret == WGET_E_SUCCESS)
1470
0
    debug_printf("TLS False Start: %s\n",
1471
0
      (gnutls_session_get_flags(session) & GNUTLS_SFLAGS_FALSE_START) ? "on" : "off");
1472
1473
0
  return ret;
1474
0
}
1475
1476
#ifdef MSG_FASTOPEN
1477
#include <sys/socket.h>
1478
#include <sys/uio.h> // writev
1479
#include <netdb.h>
1480
#include <errno.h>
1481
static ssize_t ssl_writev(gnutls_transport_ptr_t *p, const giovec_t *iov, int iovcnt)
1482
0
{
1483
0
  wget_tcp *tcp = (wget_tcp *) p;
1484
0
  ssize_t ret;
1485
1486
  // info_printf("%s: %d %zu\n", __func__, iovcnt, iov[0].iov_len);
1487
0
  if (tcp->first_send) {
1488
0
    struct msghdr hdr = {
1489
0
      .msg_name = tcp->connect_addrinfo->ai_addr,
1490
0
      .msg_namelen = tcp->connect_addrinfo->ai_addrlen,
1491
0
      .msg_iov = (struct iovec *) iov,
1492
0
      .msg_iovlen = iovcnt,
1493
0
    };
1494
1495
//    ret = sendto(tcp->sockfd, iov[0].iov_base, iov[0].iov_len, MSG_FASTOPEN,
1496
//        tcp->connect_addrinfo->ai_addr, tcp->connect_addrinfo->ai_addrlen);
1497
0
    ret = sendmsg(tcp->sockfd, &hdr, MSG_FASTOPEN);
1498
0
    if (ret < 0) {
1499
0
      if (errno == EINPROGRESS) {
1500
0
        errno = EAGAIN; // GnuTLS does not handle EINPROGRESS
1501
0
      } else if (errno == EOPNOTSUPP) {
1502
        // fallback from fastopen, e.g. when fastopen is disabled in system
1503
0
        debug_printf("Fallback from TCP Fast Open... TFO is disabled at system level\n");
1504
0
        tcp->tcp_fastopen = 0;
1505
0
        set_socket_timeout(tcp->sockfd, tcp->connect_timeout);
1506
0
        ret = connect(tcp->sockfd, tcp->connect_addrinfo->ai_addr, tcp->connect_addrinfo->ai_addrlen);
1507
0
        set_socket_timeout(tcp->sockfd, tcp->timeout);
1508
0
        if (ret < 0 && (errno == ENOTCONN || errno == EINPROGRESS))
1509
0
          errno = EAGAIN;
1510
0
      }
1511
0
    }
1512
1513
0
    tcp->first_send = 0;
1514
0
  } else {
1515
0
    ret = writev(tcp->sockfd, (struct iovec *) iov, iovcnt);
1516
0
  }
1517
  // info_printf("errno=%d ret=%d\n", errno, ret);
1518
1519
  // after the first write we set back the transport push function and the transport pointer to standard functions
1520
0
  gnutls_transport_set_int(tcp->ssl_session, tcp->sockfd);
1521
1522
0
#if defined __clang__
1523
0
  #pragma clang diagnostic push
1524
0
  #pragma clang diagnostic ignored "-Wcast-function-type"
1525
0
#endif
1526
0
  gnutls_transport_set_vec_push_function(tcp->ssl_session, (ssize_t (*) (gnutls_transport_ptr_t, const giovec_t * iov, int iovcnt)) writev);
1527
0
#if defined __clang__
1528
0
  #pragma clang diagnostic pop
1529
0
#endif
1530
1531
0
  return ret;
1532
0
}
1533
#endif
1534
1535
#ifdef _WIN32
1536
static ssize_t win32_send(gnutls_transport_ptr_t p, const void *buf, size_t size)
1537
{
1538
  int sockfd = (int) (ptrdiff_t) p;
1539
1540
  return send(sockfd, buf, size, 0);
1541
}
1542
static ssize_t win32_recv(gnutls_transport_ptr_t p, void *buf, size_t size)
1543
{
1544
  int sockfd = (int) (ptrdiff_t) p;
1545
1546
  return recv(sockfd, buf, size, 0);
1547
}
1548
#endif
1549
1550
/**
1551
 * \param[in] tcp A TCP connection (see wget_tcp_init())
1552
 * \return `WGET_E_SUCCESS` on success or an error code (`WGET_E_*`) on failure
1553
 *
1554
 * Run an SSL/TLS handshake.
1555
 *
1556
 * This functions establishes an SSL/TLS tunnel (performs an SSL/TLS handshake)
1557
 * over an active TCP connection. A pointer to the (internal) SSL/TLS session context
1558
 * can be found in `tcp->ssl_session` after successful execution of this function. This pointer
1559
 * has to be passed to wget_ssl_close() to close the SSL/TLS tunnel.
1560
 *
1561
 * If the handshake cannot be completed in the specified timeout for the provided TCP connection
1562
 * this function fails and returns `WGET_E_TIMEOUT`. You can set the timeout with wget_tcp_set_timeout().
1563
 */
1564
int wget_ssl_open(wget_tcp *tcp)
1565
0
{
1566
0
  gnutls_session_t session;
1567
0
  wget_tls_stats_data stats = {
1568
0
      .alpn_protocol = NULL,
1569
0
      .version = -1,
1570
0
      .false_start = -1,
1571
0
      .tfo = -1,
1572
0
      .resumed = 0,
1573
0
      .http_protocol = WGET_PROTOCOL_HTTP_1_1,
1574
0
      .cert_chain_size = 0
1575
0
  };
1576
1577
0
  int ret = WGET_E_UNKNOWN;
1578
0
  int rc, sockfd, tls_connect_timeout;
1579
0
  const char *hostname;
1580
0
  long long before_millisecs = 0;
1581
1582
0
  if (!tcp)
1583
0
    return WGET_E_INVALID;
1584
1585
0
  struct session_context *ctx = wget_calloc(1, sizeof(struct session_context));
1586
0
  if (!ctx)
1587
0
    return WGET_E_MEMORY;
1588
1589
0
  if (!init)
1590
0
    wget_ssl_init();
1591
1592
0
  hostname = tcp->ssl_hostname;
1593
0
  sockfd= tcp->sockfd;
1594
0
  tls_connect_timeout = tcp->timeout;
1595
1596
0
  unsigned int flags = GNUTLS_CLIENT | GNUTLS_AUTO_REAUTH | GNUTLS_POST_HANDSHAKE_AUTH;
1597
1598
0
  if (tcp->tls_false_start) {
1599
0
    debug_printf("TLS False Start requested\n");
1600
1601
0
    flags |= GNUTLS_NONBLOCK | GNUTLS_ENABLE_FALSE_START;
1602
1603
0
    gnutls_init(&session, flags);
1604
0
  } else {
1605
0
    flags |= GNUTLS_NONBLOCK;
1606
1607
0
    gnutls_init(&session, flags);
1608
0
  }
1609
1610
0
  if ((rc = gnutls_priority_set(session, priority_cache)) != GNUTLS_E_SUCCESS)
1611
0
    error_printf(_("GnuTLS: Failed to set priorities: %s\n"), gnutls_strerror(rc));
1612
1613
0
  if (!config.check_certificate && !wget_strcasecmp_ascii(config.secure_protocol, "auto"))
1614
0
    gnutls_session_enable_compatibility_mode(session);
1615
1616
  // RFC 6066 SNI Server Name Indication
1617
0
  if (hostname) {
1618
0
    gnutls_server_name_set(session, GNUTLS_NAME_DNS, hostname, strlen(hostname));
1619
0
    debug_printf("SNI %s\n", hostname);
1620
0
  }
1621
0
  gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, credentials);
1622
1623
0
  ctx->hostname = wget_strdup(hostname);
1624
0
  ctx->port = tcp->remote_port;
1625
1626
0
#ifdef WITH_OCSP
1627
  // If we know the cert chain for the hostname being valid at the moment,
1628
  // we don't ask for OCSP stapling to avoid unneeded IP traffic.
1629
  // In the unlikely case that the server's certificate chain changed right now,
1630
  // we fallback to OCSP responder request later (if enabled).
1631
0
  if (hostname) {
1632
0
    if (!(ctx->valid = wget_ocsp_hostname_is_valid(config.ocsp_host_cache, hostname))) {
1633
0
      if ((rc = gnutls_ocsp_status_request_enable_client(session, NULL, 0, NULL)) == GNUTLS_E_SUCCESS) {
1634
0
        debug_printf("OCSP stapling requested for %s\n", hostname);
1635
0
        ctx->ocsp_stapling = 1;
1636
0
      } else
1637
0
        error_printf("GnuTLS: %s\n", gnutls_strerror(rc)); // no translation
1638
0
    }
1639
0
  }
1640
#else
1641
  if (config.ocsp || config.ocsp_stapling)
1642
    error_printf(_("WARNING: OCSP is not available in this version of GnuTLS.\n"));
1643
#endif
1644
1645
0
  if (config.alpn) {
1646
0
    unsigned nprot;
1647
0
    const char *e, *s;
1648
1649
0
    for (nprot = 0, s = e = config.alpn; *e; s = e + 1)
1650
0
      if ((e = strchrnul(s, ',')) != s)
1651
0
        nprot++;
1652
1653
0
    if (nprot) {
1654
0
      gnutls_datum_t data[16];
1655
1656
0
      for (nprot = 0, s = e = config.alpn; *e && nprot < countof(data); s = e + 1) {
1657
0
        if ((e = strchrnul(s, ',')) != s) {
1658
0
          data[nprot].data = (unsigned char *) s;
1659
0
          data[nprot].size = (unsigned) (e - s);
1660
0
          debug_printf("ALPN offering %.*s\n", (int) data[nprot].size, data[nprot].data);
1661
0
          nprot++;
1662
0
        }
1663
0
      }
1664
1665
0
      if ((rc = gnutls_alpn_set_protocols(session, data, nprot, 0)))
1666
0
        debug_printf("GnuTLS: Set ALPN: %s\n", gnutls_strerror(rc));
1667
0
    }
1668
0
  }
1669
1670
0
  tcp->ssl_session = session;
1671
0
  gnutls_session_set_ptr(session, ctx);
1672
1673
0
#ifdef MSG_FASTOPEN
1674
0
  if ((rc = wget_tcp_get_tcp_fastopen(tcp))) {
1675
0
    if (tls_stats_callback)
1676
0
      stats.tfo = (char)rc;
1677
1678
    // prepare for TCP FASTOPEN... sendmsg() instead of connect/write on first write
1679
0
    gnutls_transport_set_vec_push_function(session, (ssize_t (*)(gnutls_transport_ptr_t, const giovec_t *iov, int iovcnt)) ssl_writev);
1680
0
    gnutls_transport_set_ptr(session, tcp);
1681
0
  } else {
1682
0
#endif
1683
1684
#ifdef _WIN32
1685
  gnutls_transport_set_push_function(session, (gnutls_push_func) win32_send);
1686
  gnutls_transport_set_pull_function(session, (gnutls_pull_func) win32_recv);
1687
#endif
1688
1689
0
  gnutls_transport_set_int(session, sockfd);
1690
1691
0
#ifdef MSG_FASTOPEN
1692
0
  }
1693
0
#endif
1694
1695
0
  {
1696
0
    void *data;
1697
0
    size_t size;
1698
1699
0
    if (wget_tls_session_get(config.tls_session_cache, ctx->hostname, &data, &size) == 0) {
1700
0
      debug_printf("found cached session data for %s\n", ctx->hostname);
1701
0
      if ((rc = gnutls_session_set_data(session, data, size)) != GNUTLS_E_SUCCESS)
1702
0
        error_printf(_("GnuTLS: Failed to set session data: %s\n"), gnutls_strerror(rc));
1703
0
      xfree(data);
1704
0
    }
1705
0
  }
1706
1707
0
  if (tls_stats_callback)
1708
0
    before_millisecs = wget_get_timemillis();
1709
1710
0
  ret = do_handshake(session, sockfd, tls_connect_timeout);
1711
1712
0
  if (tls_stats_callback) {
1713
0
    long long after_millisecs = wget_get_timemillis();
1714
0
    stats.tls_secs = after_millisecs - before_millisecs;
1715
0
    stats.tls_con = 1;
1716
0
    stats.false_start = (gnutls_session_get_flags(session) & GNUTLS_SFLAGS_FALSE_START) != 0;
1717
0
  }
1718
1719
0
  if (config.alpn) {
1720
0
    gnutls_datum_t protocol;
1721
0
    if ((rc = gnutls_alpn_get_selected_protocol(session, &protocol))) {
1722
0
      debug_printf("GnuTLS: Get ALPN: %s\n", gnutls_strerror(rc));
1723
0
      if (!strstr(config.alpn,"http/1.1"))
1724
0
        ret = WGET_E_CONNECT;
1725
0
    } else {
1726
0
      debug_printf("ALPN: Server accepted protocol '%.*s'\n", (int) protocol.size, protocol.data);
1727
0
      if (tls_stats_callback)
1728
0
        stats.alpn_protocol = wget_strmemdup(protocol.data, protocol.size);
1729
1730
0
      if (!memcmp(protocol.data, "h2", 2)) {
1731
0
        tcp->protocol = WGET_PROTOCOL_HTTP_2_0;
1732
0
        if (tls_stats_callback)
1733
0
          stats.http_protocol = WGET_PROTOCOL_HTTP_2_0;
1734
0
      }
1735
0
    }
1736
0
  }
1737
1738
0
  if (config.print_info)
1739
0
    print_info(session);
1740
1741
0
  if (ret == WGET_E_SUCCESS) {
1742
0
    int resumed = gnutls_session_is_resumed(session);
1743
1744
0
    if (tls_stats_callback) {
1745
0
      stats.resumed = resumed;
1746
0
      stats.version = gnutls_protocol_get_version(session);
1747
0
      gnutls_certificate_get_peers(session, (unsigned int *)&(stats.cert_chain_size));
1748
0
    }
1749
1750
0
    debug_printf("Handshake completed%s\n", resumed ? " (resumed session)" : "");
1751
1752
0
    if (!resumed && config.tls_session_cache) {
1753
0
      if (tcp->tls_false_start) {
1754
0
        ctx->delayed_session_data = 1;
1755
0
      } else {
1756
0
        gnutls_datum_t session_data;
1757
1758
0
        if ((rc = gnutls_session_get_data2(session, &session_data)) == GNUTLS_E_SUCCESS) {
1759
0
          wget_tls_session_db_add(config.tls_session_cache,
1760
0
            wget_tls_session_new(ctx->hostname, 18 * 3600, session_data.data, session_data.size)); // 18h valid
1761
0
          xfree(session_data.data);
1762
0
        } else
1763
0
          debug_printf("Failed to get session data: %s", gnutls_strerror(rc));
1764
0
      }
1765
0
    }
1766
0
  }
1767
1768
0
  if (tls_stats_callback) {
1769
0
    stats.hostname = hostname;
1770
0
    tls_stats_callback(&stats, tls_stats_ctx);
1771
0
    xfree(stats.alpn_protocol);
1772
0
  }
1773
1774
0
  tcp->hpkp = ctx->stats_hpkp;
1775
1776
0
  if (ret != WGET_E_SUCCESS) {
1777
0
    if (ret == WGET_E_TIMEOUT)
1778
0
      debug_printf("Handshake timed out\n");
1779
0
    xfree(ctx->hostname);
1780
0
    xfree(ctx);
1781
0
    gnutls_deinit(session);
1782
0
    tcp->ssl_session = NULL;
1783
0
  }
1784
1785
0
  return ret;
1786
0
}
1787
1788
/**
1789
 * \param[in] session The SSL/TLS session (a pointer to it), which is located at the `ssl_session` field
1790
 * of the TCP connection (see wget_ssl_open()).
1791
 *
1792
 * Close an active SSL/TLS tunnel, which was opened with wget_ssl_open().
1793
 *
1794
 * The underlying TCP connection is kept open.
1795
 */
1796
void wget_ssl_close(void **session)
1797
3.66k
{
1798
3.66k
  if (session && *session) {
1799
0
    gnutls_session_t s = *session;
1800
0
    struct session_context *ctx = gnutls_session_get_ptr(s);
1801
0
    int ret;
1802
1803
0
    do
1804
0
      ret = gnutls_bye(s, GNUTLS_SHUT_WR);
1805
0
    while (ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN);
1806
1807
0
    if (ret < 0)
1808
0
      debug_printf("TLS shutdown failed: %s\n", gnutls_strerror(ret));
1809
1810
0
    gnutls_deinit(s);
1811
0
    *session = NULL;
1812
1813
0
    xfree(ctx->hostname);
1814
0
    xfree(ctx);
1815
0
  }
1816
3.66k
}
1817
1818
/**
1819
 * \param[in] session An opaque pointer to the SSL/TLS session (obtained with wget_ssl_open() or wget_ssl_server_open())
1820
 * \param[in] buf Destination buffer where the read data will be placed
1821
 * \param[in] count Length of the buffer \p buf
1822
 * \param[in] timeout The amount of time to wait until data becomes available (in milliseconds)
1823
 * \return The number of bytes read, or a negative value on error.
1824
 *
1825
 * Read data from the SSL/TLS tunnel.
1826
 *
1827
 * This function will read at most \p count bytes, which will be stored
1828
 * in the buffer \p buf.
1829
 *
1830
 * The \p timeout parameter tells how long to wait until some data becomes
1831
 * available to read. A \p timeout value of zero causes this function to return
1832
 * immediately, whereas a negative value will cause it to wait indefinitely.
1833
 * This function returns the number of bytes read, which may be zero if the timeout elapses
1834
 * without any data having become available.
1835
 *
1836
 * If a rehandshake is needed, this function does it automatically and tries
1837
 * to read again.
1838
 */
1839
ssize_t wget_ssl_read_timeout(void *session, char *buf, size_t count, int timeout)
1840
0
{
1841
0
  int sockfd = gnutls_transport_get_int(session);
1842
1843
0
  ssize_t nbytes;
1844
1845
0
  for (;;) {
1846
0
    int rc;
1847
1848
0
    if (gnutls_record_check_pending(session) <= 0 && (rc = wget_ready_2_read(sockfd, timeout)) <= 0)
1849
0
      return rc;
1850
1851
0
    nbytes = gnutls_record_recv(session, buf, count);
1852
1853
    // If False Start + Session Resumption are enabled, we get the session data after the first read()
1854
0
    struct session_context *ctx = gnutls_session_get_ptr(session);
1855
0
    if (ctx && ctx->delayed_session_data) {
1856
0
      gnutls_datum_t session_data;
1857
1858
0
      if ((rc = gnutls_session_get_data2(session, &session_data)) == GNUTLS_E_SUCCESS) {
1859
0
        debug_printf("Got delayed session data\n");
1860
0
        ctx->delayed_session_data = 0;
1861
0
        wget_tls_session_db_add(config.tls_session_cache,
1862
0
          wget_tls_session_new(ctx->hostname, 18 * 3600, session_data.data, session_data.size)); // 18h valid
1863
0
        xfree(session_data.data);
1864
0
      } else
1865
0
        debug_printf("No delayed session data%s\n", gnutls_strerror(rc));
1866
0
    }
1867
1868
0
    if (nbytes == GNUTLS_E_REHANDSHAKE) {
1869
0
      debug_printf("*** REHANDSHAKE while reading\n");
1870
0
      if ((nbytes = do_handshake(session, sockfd, timeout)) == 0)
1871
0
        nbytes = GNUTLS_E_AGAIN; /* restart reading */
1872
0
    }
1873
0
    if (nbytes >= 0 || nbytes != GNUTLS_E_AGAIN)
1874
0
      break;
1875
0
  }
1876
1877
0
  return nbytes < -1 ? -1 : nbytes;
1878
0
}
1879
1880
/**
1881
 * \param[in] session An opaque pointer to the SSL/TLS session (obtained with wget_ssl_open() or wget_ssl_server_open())
1882
 * \param[in] buf Buffer with the data to be sent
1883
 * \param[in] count Length of the buffer \p buf
1884
 * \param[in] timeout The amount of time to wait until data can be sent to the wire (in milliseconds)
1885
 * \return The number of bytes written, or a negative value on error.
1886
 *
1887
 * Send data through the SSL/TLS tunnel.
1888
 *
1889
 * This function will write \p count bytes from \p buf.
1890
 *
1891
 * The \p timeout parameter tells how long to wait until data can be finally sent
1892
 * over the SSL/TLS tunnel. A \p timeout value of zero causes this function to return
1893
 * immediately, whereas a negative value will cause it to wait indefinitely.
1894
 * This function returns the number of bytes sent, which may be zero if the timeout elapses
1895
 * before any data could be sent.
1896
 *
1897
 * If a rehandshake is needed, this function does it automatically and tries
1898
 * to write again.
1899
 */
1900
ssize_t wget_ssl_write_timeout(void *session, const char *buf, size_t count, int timeout)
1901
0
{
1902
0
  int sockfd = gnutls_transport_get_int(session);
1903
1904
0
  for (;;) {
1905
0
    ssize_t nbytes;
1906
0
    int rc;
1907
1908
0
    if ((rc = wget_ready_2_write(sockfd, timeout)) <= 0)
1909
0
      return rc;
1910
1911
0
    if ((nbytes = gnutls_record_send(session, buf, count)) >= 0)
1912
0
      return nbytes;
1913
1914
0
    if (nbytes == GNUTLS_E_REHANDSHAKE) {
1915
0
      debug_printf("*** REHANDSHAKE while writing\n");
1916
0
      if ((nbytes = do_handshake(session, sockfd, timeout)) == 0)
1917
0
        continue; /* restart writing */
1918
0
    }
1919
0
    if (nbytes == GNUTLS_E_AGAIN)
1920
0
      return 0; // indicate timeout
1921
1922
0
    return -1;
1923
0
  }
1924
0
}
1925
1926
/**
1927
 * \param[in] fn A `wget_ssl_stats_callback_tls_t` callback function to receive TLS statistics data
1928
 * \param[in] ctx Context data given to \p fn
1929
 *
1930
 * Set callback function to be called when TLS statistics are available
1931
 */
1932
void wget_ssl_set_stats_callback_tls(wget_tls_stats_callback *fn, void *ctx)
1933
34
{
1934
34
  tls_stats_callback = fn;
1935
34
  tls_stats_ctx = ctx;
1936
34
}
1937
1938
/**
1939
 * \param[in] fn A `wget_ssl_stats_callback_ocsp_t` callback function to receive OCSP statistics data
1940
 * \param[in] ctx Context data given to \p fn
1941
 *
1942
 * Set callback function to be called when OCSP statistics are available
1943
 */
1944
void wget_ssl_set_stats_callback_ocsp(wget_ocsp_stats_callback *fn, void *ctx)
1945
5
{
1946
5
  ocsp_stats_callback = fn;
1947
5
  ocsp_stats_ctx = ctx;
1948
5
}
1949
1950
/** @} */