Coverage Report

Created: 2026-12-01 07:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libcups/cups/tls-openssl.c
Line
Count
Source
1
//
2
// TLS support code for CUPS using OpenSSL/LibreSSL.
3
//
4
// Note: This file is included from tls.c
5
//
6
// Copyright © 2020-2026 by OpenPrinting
7
// Copyright © 2007-2019 by Apple Inc.
8
// Copyright © 1997-2007 by Easy Software Products, all rights reserved.
9
//
10
// Licensed under Apache License v2.0.  See the file "LICENSE" for more
11
// information.
12
//
13
14
#include <openssl/x509v3.h>
15
#include <openssl/x509_vfy.h>
16
#include <openssl/evp.h>
17
#include <openssl/objects.h>
18
#include <openssl/obj_mac.h>
19
20
21
//
22
// Local functions...
23
//
24
25
static long   http_bio_ctrl(BIO *h, int cmd, long arg1, void *arg2);
26
static int    http_bio_free(BIO *data);
27
static int    http_bio_new(BIO *h);
28
static int    http_bio_puts(BIO *h, const char *str);
29
static int    http_bio_read(BIO *h, char *buf, int size);
30
static int    http_bio_write(BIO *h, const char *buf, int num);
31
32
static bool   openssl_add_ext(STACK_OF(X509_EXTENSION) *exts, int nid, const char *value);
33
static X509_NAME  *openssl_create_name(const char *organization, const char *org_unit, const char *locality, const char *state_province, const char *country, const char *common_name, const char *email);
34
static EVP_PKEY   *openssl_create_key(cups_credtype_t type);
35
static X509_EXTENSION *openssl_create_san(const char *common_name, size_t num_alt_names, const char * const *alt_names);
36
static time_t   openssl_get_date(X509 *cert, int which);
37
static STACK_OF(X509 *) openssl_load_x509(const char *credentials);
38
static BIO    *openssl_open_file(const char *filename, int mode);
39
static bool   openssl_validate_name(X509 *cert, const char *common_name);
40
static int    openssl_verify_cb(int ok, X509_STORE_CTX *ctx);
41
42
43
//
44
// Local globals...
45
//
46
47
static BIO_METHOD *tls_bio_method = NULL;
48
          // OpenSSL BIO method
49
static const char * const tls_purpose_oids[] =
50
{         // OIDs for each key purpose value
51
  "1.3.6.1.5.5.7.3.1",      // serverAuth
52
  "1.3.6.1.5.5.7.3.2",      // clientAuth
53
  "1.3.6.1.5.5.7.3.3",      // codeSigning
54
  "1.3.6.1.5.5.7.3.4",      // emailProtection
55
  "1.3.6.1.5.5.7.3.8",      // timeStamping
56
  "1.3.6.1.5.5.7.3.9"     // OCSPSigning
57
};
58
static const char * const tls_usage_strings[] =
59
{         // Strings for each key usage value
60
  "digitalSignature",
61
  "nonRepudiation",
62
  "keyEncipherment",
63
  "dataEncipherment",
64
  "keyAgreement",
65
  "keyCertSign",
66
  "cRLSign",
67
  "encipherOnly",
68
  "decipherOnly"
69
};
70
71
72
//
73
// 'cupsAreCredentialsValidForName()' - Return whether the credentials are valid
74
//                                      for the given name.
75
//
76
77
bool          // O - `true` if valid, `false` otherwise
78
cupsAreCredentialsValidForName(
79
    const char *common_name,    // I - Name to check
80
    const char *credentials)    // I - Credentials
81
0
{
82
0
  STACK_OF(X509)  *certs;   // Certificate chain
83
0
  bool      result = false;  // Result
84
85
86
0
  DEBUG_printf("cupsAreCredentialsValidForName(common_name=\"%s\", credentials=\"%s\")", common_name, credentials);
87
88
  // Range check input...
89
0
  if (!common_name || !credentials)
90
0
    return (false);
91
92
  // Load the credentials...
93
0
  if ((certs = openssl_load_x509(credentials)) != NULL)
94
0
  {
95
    // Check the hostname against the primary certificate...
96
0
    result = openssl_validate_name(sk_X509_value(certs, 0), common_name);
97
98
0
    sk_X509_pop_free(certs, X509_free);
99
0
  }
100
101
0
  return (result);
102
0
}
103
104
105
//
106
// 'cupsCreateCredentials()' - Make an X.509 certificate and private key pair.
107
//
108
// This function creates an X.509 certificate and private key pair.  The
109
// certificate and key are stored in the directory "path" or, if "path" is
110
// `NULL`, in a per-user or system-wide (when running as root) certificate/key
111
// store.  The generated certificate is signed by the named root certificate or,
112
// if "root_name" is `NULL`, a site-wide default root certificate.  When
113
// "root_name" is `NULL` and there is no site-wide default root certificate, a
114
// self-signed certificate is generated instead.
115
//
116
// The "ca_cert" argument specifies whether a CA certificate should be created.
117
//
118
// The "purpose" argument specifies the purpose(s) used for the credentials as a
119
// bitwise OR of the following constants:
120
//
121
// - `CUPS_CREDPURPOSE_SERVER_AUTH` for validating TLS servers,
122
// - `CUPS_CREDPURPOSE_CLIENT_AUTH` for validating TLS clients,
123
// - `CUPS_CREDPURPOSE_CODE_SIGNING` for validating compiled code,
124
// - `CUPS_CREDPURPOSE_EMAIL_PROTECTION` for validating email messages,
125
// - `CUPS_CREDPURPOSE_TIME_STAMPING` for signing timestamps to objects, and/or
126
// - `CUPS_CREDPURPOSE_OCSP_SIGNING` for Online Certificate Status Protocol
127
//   message signing.
128
//
129
// The "type" argument specifies the type of credentials using one of the
130
// following constants:
131
//
132
// - `CUPS_CREDTYPE_DEFAULT`: default type (RSA-3072 or P-384),
133
// - `CUPS_CREDTYPE_RSA_2048_SHA256`: RSA with 2048-bit keys and SHA-256 hash,
134
// - `CUPS_CREDTYPE_RSA_3072_SHA256`: RSA with 3072-bit keys and SHA-256 hash,
135
// - `CUPS_CREDTYPE_RSA_4096_SHA256`: RSA with 4096-bit keys and SHA-256 hash,
136
// - `CUPS_CREDTYPE_ECDSA_P256_SHA256`: ECDSA using the P-256 curve with SHA-256 hash,
137
// - `CUPS_CREDTYPE_ECDSA_P384_SHA256`: ECDSA using the P-384 curve with SHA-256 hash, or
138
// - `CUPS_CREDTYPE_ECDSA_P521_SHA256`: ECDSA using the P-521 curve with SHA-256 hash.
139
//
140
// The "usage" argument specifies the usage(s) for the credentials as a bitwise
141
// OR of the following constants:
142
//
143
// - `CUPS_CREDUSAGE_DIGITAL_SIGNATURE`: digital signatures,
144
// - `CUPS_CREDUSAGE_NON_REPUDIATION`: non-repudiation/content commitment,
145
// - `CUPS_CREDUSAGE_KEY_ENCIPHERMENT`: key encipherment,
146
// - `CUPS_CREDUSAGE_DATA_ENCIPHERMENT`: data encipherment,
147
// - `CUPS_CREDUSAGE_KEY_AGREEMENT`: key agreement,
148
// - `CUPS_CREDUSAGE_KEY_CERT_SIGN`: key certicate signing,
149
// - `CUPS_CREDUSAGE_CRL_SIGN`: certificate revocation list signing,
150
// - `CUPS_CREDUSAGE_ENCIPHER_ONLY`: encipherment only,
151
// - `CUPS_CREDUSAGE_DECIPHER_ONLY`: decipherment only,
152
// - `CUPS_CREDUSAGE_DEFAULT_CA`: defaults for CA certificates,
153
// - `CUPS_CREDUSAGE_DEFAULT_TLS`: defaults for TLS certificates, and/or
154
// - `CUPS_CREDUSAGE_ALL`: all usages.
155
//
156
// The "organization", "org_unit", "locality", "state_province", and "country"
157
// arguments specify information about the identity and geolocation of the
158
// issuer.
159
//
160
// The "common_name" argument specifies the common name and the "num_alt_names"
161
// and "alt_names" arguments specify a list of DNS hostnames for the
162
// certificate.
163
//
164
// The "expiration_date" argument specifies the expiration date and time as a
165
// Unix `time_t` value in seconds.
166
//
167
168
bool          // O - `true` on success, `false` on failure
169
cupsCreateCredentials(
170
    const char         *path,   // I - Directory path for certificate/key store or `NULL` for default
171
    bool               ca_cert,   // I - `true` to create a CA certificate, `false` for a client/server certificate
172
    cups_credpurpose_t purpose,   // I - Credential purposes
173
    cups_credtype_t    type,    // I - Credential type
174
    cups_credusage_t   usage,   // I - Credential usages
175
    const char         *organization, // I - Organization or `NULL` to use common name
176
    const char         *org_unit, // I - Organizational unit or `NULL` for none
177
    const char         *locality, // I - City/town or `NULL` for "Unknown"
178
    const char         *state_province, // I - State/province or `NULL` for "Unknown"
179
    const char         *country,  // I - Country or `NULL` for locale-based default
180
    const char         *common_name,  // I - Common name
181
    const char         *email,    // I - Email address or `NULL` for none
182
    size_t             num_alt_names, // I - Number of subject alternate names
183
    const char * const *alt_names,  // I - Subject Alternate Names
184
    const char         *root_name,  // I - Root certificate/domain name or `NULL` for site/self-signed
185
    time_t             expiration_date) // I - Expiration date
186
0
{
187
0
  bool    result = false;    // Return value
188
0
  EVP_PKEY  *pkey;      // Key pair
189
0
  X509    *cert;      // Certificate
190
0
  X509    *root_cert = NULL; // Root certificate, if any
191
0
  EVP_PKEY  *root_key = NULL; // Root private key, if any
192
0
  char    defpath[1024],    // Default path
193
0
    crtfile[1024],    // Certificate filename
194
0
    keyfile[1024],    // Private key filename
195
0
    pubfile[1024],    // Public key filename
196
0
    root_crtfile[1024], // Root certificate filename
197
0
    root_keyfile[1024]; // Root private key filename
198
0
  time_t  curtime;    // Current time
199
0
  X509_NAME *name;      // Subject/issuer name
200
0
  ASN1_INTEGER  *serial;    // Serial number
201
0
  ASN1_TIME *notBefore,   // Initial date
202
0
    *notAfter;    // Expiration date
203
0
  BIO   *bio;     // Output file
204
0
  char    temp[1024],   // Temporary string
205
0
    *tempptr;   // Pointer into temporary string
206
0
  STACK_OF(X509_EXTENSION) *exts; // Extensions
207
0
  X509_EXTENSION *ext;      // Current extension
208
0
  unsigned  i;      // Looping var
209
0
  cups_credpurpose_t purpose_bit; // Current purpose
210
0
  cups_credusage_t usage_bit;   // Current usage
211
212
213
0
  DEBUG_printf("cupsCreateCredentials(path=\"%s\", ca_cert=%s, purpose=0x%x, type=%d, usage=0x%x, organization=\"%s\", org_unit=\"%s\", locality=\"%s\", state_province=\"%s\", country=\"%s\", common_name=\"%s\", num_alt_names=%u, alt_names=%p, root_name=\"%s\", expiration_date=%ld)", path, ca_cert ? "true" : "false", purpose, type, usage, organization, org_unit, locality, state_province, country, common_name, (unsigned)num_alt_names, (void *)alt_names, root_name, (long)expiration_date);
214
215
  // Filenames...
216
0
  if (!path)
217
0
    path = http_default_path(defpath, sizeof(defpath));
218
219
0
  if (!path || !common_name || !*common_name)
220
0
  {
221
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
222
0
    return (false);
223
0
  }
224
225
  // Create the encryption key...
226
0
  DEBUG_puts("1cupsCreateCredentials: Creating key pair.");
227
228
0
  if ((pkey = openssl_create_key(type)) == NULL)
229
0
    return (false);
230
231
0
  DEBUG_puts("1cupsCreateCredentials: Key pair created.");
232
233
  // Create the X.509 certificate...
234
0
  DEBUG_puts("1cupsCreateCredentials: Generating X.509 certificate.");
235
236
0
  if ((cert = X509_new()) == NULL)
237
0
  {
238
0
    EVP_PKEY_free(pkey);
239
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to create X.509 certificate."), true);
240
0
    return (false);
241
0
  }
242
243
0
  curtime = time(NULL);
244
245
0
  notBefore = ASN1_TIME_new();
246
0
  ASN1_TIME_set(notBefore, curtime);
247
0
  X509_set_notBefore(cert, notBefore);
248
0
  ASN1_TIME_free(notBefore);
249
250
0
  notAfter = ASN1_TIME_new();
251
0
  ASN1_TIME_set(notAfter, expiration_date);
252
0
  X509_set_notAfter(cert, notAfter);
253
0
  ASN1_TIME_free(notAfter);
254
255
0
  serial = ASN1_INTEGER_new();
256
0
  ASN1_INTEGER_set(serial, (long)curtime);
257
0
  X509_set_serialNumber(cert, serial);
258
0
  ASN1_INTEGER_free(serial);
259
260
0
  X509_set_pubkey(cert, pkey);
261
262
0
  name = openssl_create_name(organization, org_unit, locality, state_province, country, common_name, email);
263
264
0
  X509_set_subject_name(cert, name);
265
266
  // Try loading a root certificate...
267
0
  http_make_path(root_crtfile, sizeof(root_crtfile), path, root_name ? root_name : "_site_", "crt");
268
0
  http_make_path(root_keyfile, sizeof(root_keyfile), path, root_name ? root_name : "_site_", "key");
269
270
0
  if (!ca_cert && !access(root_crtfile, 0) && !access(root_keyfile, 0))
271
0
  {
272
0
    if ((bio = BIO_new_file(root_crtfile, "rb")) != NULL)
273
0
    {
274
0
      PEM_read_bio_X509(bio, &root_cert, /*cb*/NULL, /*u*/NULL);
275
0
      BIO_free(bio);
276
277
0
      if ((bio = BIO_new_file(root_keyfile, "rb")) != NULL)
278
0
      {
279
0
  PEM_read_bio_PrivateKey(bio, &root_key, /*cb*/NULL, /*u*/NULL);
280
0
  BIO_free(bio);
281
0
      }
282
283
0
      if (!root_key)
284
0
      {
285
        // Only use root certificate if we have the key...
286
0
        X509_free(root_cert);
287
0
        root_cert = NULL;
288
0
      }
289
0
    }
290
291
0
    if (!root_cert || !root_key)
292
0
    {
293
0
      _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to load X.509 CA certificate and private key."), true);
294
0
      goto done;
295
0
    }
296
0
  }
297
298
0
  if (root_cert)
299
0
    X509_set_issuer_name(cert, X509_get_subject_name(root_cert));
300
0
  else
301
0
    X509_set_issuer_name(cert, name);
302
303
0
  X509_NAME_free(name);
304
305
0
  exts = sk_X509_EXTENSION_new_null();
306
307
0
  if (ca_cert)
308
0
  {
309
    // Add extensions that are required to make Chrome happy...
310
0
    openssl_add_ext(exts, NID_basic_constraints, "critical,CA:TRUE,pathlen:0");
311
0
  }
312
0
  else
313
0
  {
314
    // Add extension with DNS names and free buffer for GENERAL_NAME
315
0
    if ((ext = openssl_create_san(common_name, num_alt_names, alt_names)) == NULL)
316
0
      goto done;
317
318
0
    sk_X509_EXTENSION_push(exts, ext);
319
320
    // Add extensions that are required to make Chrome happy...
321
0
    openssl_add_ext(exts, NID_basic_constraints, "critical,CA:FALSE,pathlen:0");
322
0
  }
323
324
0
  cupsCopyString(temp, "critical", sizeof(temp));
325
0
  for (tempptr = temp + strlen(temp), i = 0, usage_bit = CUPS_CREDUSAGE_DIGITAL_SIGNATURE; i < (sizeof(tls_usage_strings) / sizeof(tls_usage_strings[0])); i ++, usage_bit *= 2)
326
0
  {
327
0
    if (!(usage & usage_bit))
328
0
      continue;
329
330
0
    snprintf(tempptr, sizeof(temp) - (size_t)(tempptr - temp), ",%s", tls_usage_strings[i]);
331
332
0
    tempptr += strlen(tempptr);
333
0
  }
334
0
  openssl_add_ext(exts, NID_key_usage, temp);
335
336
0
  temp[0] = '\0';
337
0
  for (tempptr = temp, i = 0, purpose_bit = CUPS_CREDPURPOSE_SERVER_AUTH; i < (sizeof(tls_purpose_oids) / sizeof(tls_purpose_oids[0])); i ++, purpose_bit *= 2)
338
0
  {
339
0
    if (!(purpose & purpose_bit))
340
0
      continue;
341
342
0
    if (tempptr == temp)
343
0
      cupsCopyString(temp, tls_purpose_oids[i], sizeof(temp));
344
0
    else
345
0
      snprintf(tempptr, sizeof(temp) - (size_t)(tempptr - temp), ",%s", tls_purpose_oids[i]);
346
347
0
    tempptr += strlen(tempptr);
348
0
  }
349
0
  openssl_add_ext(exts, NID_ext_key_usage, temp);
350
351
0
  openssl_add_ext(exts, NID_subject_key_identifier, "hash");
352
0
  openssl_add_ext(exts, NID_authority_key_identifier, "keyid,issuer");
353
354
0
  while ((ext = sk_X509_EXTENSION_pop(exts)) != NULL)
355
0
  {
356
0
    if (!X509_add_ext(cert, ext, -1))
357
0
    {
358
0
      sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
359
0
      goto done;
360
0
    }
361
0
  }
362
363
0
  X509_set_version(cert, 2); // v3
364
365
0
  if (root_key)
366
0
    X509_sign(cert, root_key, EVP_sha256());
367
0
  else
368
0
    X509_sign(cert, pkey, EVP_sha256());
369
370
  // Save them...
371
0
  http_make_path(crtfile, sizeof(crtfile), path, common_name, "crt");
372
0
  http_make_path(keyfile, sizeof(keyfile), path, common_name, "key");
373
0
  http_make_path(pubfile, sizeof(pubfile), path, common_name, "pub");
374
375
0
  if ((bio = openssl_open_file(keyfile, 0600)) == NULL)
376
0
  {
377
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
378
0
    goto done;
379
0
  }
380
381
0
  if (!PEM_write_bio_PrivateKey(bio, pkey, NULL, NULL, 0, NULL, NULL))
382
0
  {
383
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to write private key."), true);
384
0
    BIO_free(bio);
385
0
    goto done;
386
0
  }
387
388
0
  BIO_free(bio);
389
390
0
  if ((bio = openssl_open_file(pubfile, 0644)) == NULL)
391
0
  {
392
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
393
0
    goto done;
394
0
  }
395
396
0
  if (!PEM_write_bio_PUBKEY(bio, pkey))
397
0
  {
398
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to write public key."), true);
399
0
    BIO_free(bio);
400
0
    goto done;
401
0
  }
402
403
0
  BIO_free(bio);
404
405
0
  if ((bio = openssl_open_file(crtfile, 0644)) == NULL)
406
0
  {
407
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
408
0
    goto done;
409
0
  }
410
411
0
  if (!PEM_write_bio_X509(bio, cert))
412
0
  {
413
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to write X.509 certificate."), true);
414
0
    BIO_free(bio);
415
0
    goto done;
416
0
  }
417
418
0
  if (root_cert)
419
0
    PEM_write_bio_X509(bio, root_cert);
420
421
0
  BIO_free(bio);
422
423
0
  result = true;
424
0
  DEBUG_puts("1cupsCreateCredentials: Successfully created credentials.");
425
426
  // Cleanup...
427
0
  done:
428
429
0
  X509_free(cert);
430
0
  EVP_PKEY_free(pkey);
431
432
0
  if (root_cert)
433
0
    X509_free(root_cert);
434
0
  if (root_key)
435
0
    EVP_PKEY_free(root_key);
436
437
0
  return (result);
438
0
}
439
440
441
//
442
// 'cupsCreateCredentialsRequest()' - Make an X.509 Certificate Signing Request.
443
//
444
// This function creates an X.509 certificate signing request (CSR) and
445
// associated private key.  The CSR and key are stored in the directory "path"
446
// or, if "path" is `NULL`, in a per-user or system-wide (when running as root)
447
// certificate/key store.
448
//
449
// The "purpose" argument specifies the purpose(s) used for the credentials as a
450
// bitwise OR of the following constants:
451
//
452
// - `CUPS_CREDPURPOSE_SERVER_AUTH` for validating TLS servers,
453
// - `CUPS_CREDPURPOSE_CLIENT_AUTH` for validating TLS clients,
454
// - `CUPS_CREDPURPOSE_CODE_SIGNING` for validating compiled code,
455
// - `CUPS_CREDPURPOSE_EMAIL_PROTECTION` for validating email messages,
456
// - `CUPS_CREDPURPOSE_TIME_STAMPING` for signing timestamps to objects, and/or
457
// - `CUPS_CREDPURPOSE_OCSP_SIGNING` for Online Certificate Status Protocol
458
//   message signing.
459
//
460
// The "type" argument specifies the type of credentials using one of the
461
// following constants:
462
//
463
// - `CUPS_CREDTYPE_DEFAULT`: default type (RSA-3072 or P-384),
464
// - `CUPS_CREDTYPE_RSA_2048_SHA256`: RSA with 2048-bit keys and SHA-256 hash,
465
// - `CUPS_CREDTYPE_RSA_3072_SHA256`: RSA with 3072-bit keys and SHA-256 hash,
466
// - `CUPS_CREDTYPE_RSA_4096_SHA256`: RSA with 4096-bit keys and SHA-256 hash,
467
// - `CUPS_CREDTYPE_ECDSA_P256_SHA256`: ECDSA using the P-256 curve with SHA-256 hash,
468
// - `CUPS_CREDTYPE_ECDSA_P384_SHA256`: ECDSA using the P-384 curve with SHA-256 hash, or
469
// - `CUPS_CREDTYPE_ECDSA_P521_SHA256`: ECDSA using the P-521 curve with SHA-256 hash.
470
//
471
// The "usage" argument specifies the usage(s) for the credentials as a bitwise
472
// OR of the following constants:
473
//
474
// - `CUPS_CREDUSAGE_DIGITAL_SIGNATURE`: digital signatures,
475
// - `CUPS_CREDUSAGE_NON_REPUDIATION`: non-repudiation/content commitment,
476
// - `CUPS_CREDUSAGE_KEY_ENCIPHERMENT`: key encipherment,
477
// - `CUPS_CREDUSAGE_DATA_ENCIPHERMENT`: data encipherment,
478
// - `CUPS_CREDUSAGE_KEY_AGREEMENT`: key agreement,
479
// - `CUPS_CREDUSAGE_KEY_CERT_SIGN`: key certicate signing,
480
// - `CUPS_CREDUSAGE_CRL_SIGN`: certificate revocation list signing,
481
// - `CUPS_CREDUSAGE_ENCIPHER_ONLY`: encipherment only,
482
// - `CUPS_CREDUSAGE_DECIPHER_ONLY`: decipherment only,
483
// - `CUPS_CREDUSAGE_DEFAULT_CA`: defaults for CA certificates,
484
// - `CUPS_CREDUSAGE_DEFAULT_TLS`: defaults for TLS certificates, and/or
485
// - `CUPS_CREDUSAGE_ALL`: all usages.
486
//
487
// The "organization", "org_unit", "locality", "state_province", and "country"
488
// arguments specify information about the identity and geolocation of the
489
// issuer.
490
//
491
// The "common_name" argument specifies the common name and the "num_alt_names"
492
// and "alt_names" arguments specify a list of DNS hostnames for the
493
// certificate.
494
//
495
496
bool          // O - `true` on success, `false` on error
497
cupsCreateCredentialsRequest(
498
    const char         *path,   // I - Directory path for certificate/key store or `NULL` for default
499
    cups_credpurpose_t purpose,   // I - Credential purposes
500
    cups_credtype_t    type,    // I - Credential type
501
    cups_credusage_t   usage,   // I - Credential usages
502
    const char         *organization, // I - Organization or `NULL` to use common name
503
    const char         *org_unit, // I - Organizational unit or `NULL` for none
504
    const char         *locality, // I - City/town or `NULL` for "Unknown"
505
    const char         *state_province, // I - State/province or `NULL` for "Unknown"
506
    const char         *country,  // I - Country or `NULL` for locale-based default
507
    const char         *common_name,  // I - Common name
508
    const char         *email,    // I - Email address or `NULL` for none
509
    size_t             num_alt_names, // I - Number of subject alternate names
510
    const char * const *alt_names)  // I - Subject Alternate Names
511
0
{
512
0
  bool    ret = false;    // Return value
513
0
  EVP_PKEY  *pkey;      // Key pair
514
0
  X509_REQ  *csr;     // Certificate signing request
515
0
  X509_NAME *name;      // Subject/issuer name
516
0
  X509_EXTENSION *ext;      // X509 extension
517
0
  BIO   *bio;     // Output file
518
0
  char    temp[1024],   // Temporary directory name
519
0
    *tempptr,   // Pointer into temporary string
520
0
    csrfile[1024],    // Certificate signing request filename
521
0
    keyfile[1024],    // Private key filename
522
0
    pubfile[1024];    // Public key filename
523
0
  STACK_OF(X509_EXTENSION) *exts; // Extensions
524
0
  unsigned  i;      // Looping var
525
0
  cups_credpurpose_t purpose_bit; // Current purpose
526
0
  cups_credusage_t usage_bit;   // Current usage
527
528
529
0
  DEBUG_printf("cupsCreateCredentialsRequest(path=\"%s\", purpose=0x%x, type=%d, usage=0x%x, organization=\"%s\", org_unit=\"%s\", locality=\"%s\", state_province=\"%s\", country=\"%s\", common_name=\"%s\", num_alt_names=%u, alt_names=%p)", path, purpose, type, usage, organization, org_unit, locality, state_province, country, common_name, (unsigned)num_alt_names, (void *)alt_names);
530
531
  // Filenames...
532
0
  if (!path)
533
0
    path = http_default_path(temp, sizeof(temp));
534
535
0
  if (!path || !common_name || !*common_name)
536
0
  {
537
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
538
0
    return (false);
539
0
  }
540
541
0
  http_make_path(csrfile, sizeof(csrfile), path, common_name, "csr");
542
0
  http_make_path(keyfile, sizeof(keyfile), path, common_name, "ktm");
543
0
  http_make_path(pubfile, sizeof(pubfile), path, common_name, "pub");
544
545
  // Create the encryption key...
546
0
  DEBUG_puts("1cupsCreateCredentialsRequest: Creating key pair.");
547
548
0
  if ((pkey = openssl_create_key(type)) == NULL)
549
0
    return (false);
550
551
0
  DEBUG_puts("1cupsCreateCredentialsRequest: Key pair created.");
552
553
  // Create the X.509 certificate...
554
0
  DEBUG_puts("1cupsCreateCredentialsRequest: Generating self-signed X.509 certificate.");
555
556
0
  if ((csr = X509_REQ_new()) == NULL)
557
0
  {
558
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to create X.509 certificate signing request."), true);
559
0
    goto done;
560
0
  }
561
562
0
  X509_REQ_set_pubkey(csr, pkey);
563
564
0
  if ((name = openssl_create_name(organization, org_unit, locality, state_province, country, common_name, email)) == NULL)
565
0
    goto done;
566
567
0
  X509_REQ_set_subject_name(csr, name);
568
0
  X509_NAME_free(name);
569
570
  // Add extension with DNS names and free buffer for GENERAL_NAME
571
0
  exts = sk_X509_EXTENSION_new_null();
572
573
0
  if ((ext = openssl_create_san(common_name, num_alt_names, alt_names)) == NULL)
574
0
    goto done;
575
576
0
  sk_X509_EXTENSION_push(exts, ext);
577
578
0
  cupsCopyString(temp, "critical", sizeof(temp));
579
0
  for (tempptr = temp + strlen(temp), i = 0, usage_bit = CUPS_CREDUSAGE_DIGITAL_SIGNATURE; i < (sizeof(tls_usage_strings) / sizeof(tls_usage_strings[0])); i ++, usage_bit *= 2)
580
0
  {
581
0
    if (!(usage & usage_bit))
582
0
      continue;
583
584
0
    snprintf(tempptr, sizeof(temp) - (size_t)(tempptr - temp), ",%s", tls_usage_strings[i]);
585
586
0
    tempptr += strlen(tempptr);
587
0
  }
588
0
  openssl_add_ext(exts, NID_key_usage, temp);
589
590
0
  temp[0] = '\0';
591
0
  for (tempptr = temp, i = 0, purpose_bit = CUPS_CREDPURPOSE_SERVER_AUTH; i < (sizeof(tls_purpose_oids) / sizeof(tls_purpose_oids[0])); i ++, purpose_bit *= 2)
592
0
  {
593
0
    if (!(purpose & purpose_bit))
594
0
      continue;
595
596
0
    if (tempptr == temp)
597
0
      cupsCopyString(temp, tls_purpose_oids[i], sizeof(temp));
598
0
    else
599
0
      snprintf(tempptr, sizeof(temp) - (size_t)(tempptr - temp), ",%s", tls_purpose_oids[i]);
600
601
0
    tempptr += strlen(tempptr);
602
0
  }
603
0
  openssl_add_ext(exts, NID_ext_key_usage, temp);
604
605
0
  X509_REQ_add_extensions(csr, exts);
606
0
  X509_REQ_sign(csr, pkey, EVP_sha256());
607
608
0
  sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
609
610
  // Save them...
611
0
  if ((bio = openssl_open_file(keyfile, 0600)) == NULL)
612
0
  {
613
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
614
0
    goto done;
615
0
  }
616
617
0
  if (!PEM_write_bio_PrivateKey(bio, pkey, NULL, NULL, 0, NULL, NULL))
618
0
  {
619
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to write private key."), true);
620
0
    BIO_free(bio);
621
0
    goto done;
622
0
  }
623
624
0
  BIO_free(bio);
625
626
0
  if ((bio = openssl_open_file(pubfile, 0644)) == NULL)
627
0
  {
628
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
629
0
    goto done;
630
0
  }
631
632
0
  if (!PEM_write_bio_PUBKEY(bio, pkey))
633
0
  {
634
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to write public key."), true);
635
0
    BIO_free(bio);
636
0
    goto done;
637
0
  }
638
639
0
  BIO_free(bio);
640
641
0
  if ((bio = openssl_open_file(csrfile, 0644)) == NULL)
642
0
  {
643
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
644
0
    goto done;
645
0
  }
646
647
0
  if (!PEM_write_bio_X509_REQ(bio, csr))
648
0
  {
649
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to write X.509 certificate signing request."), true);
650
0
    BIO_free(bio);
651
0
    goto done;
652
0
  }
653
654
0
  BIO_free(bio);
655
656
0
  ret = true;
657
0
  DEBUG_puts("1cupsCreateCredentialsRequest: Successfully created signing request.");
658
659
  // Cleanup...
660
0
  done:
661
662
0
  X509_REQ_free(csr);
663
0
  EVP_PKEY_free(pkey);
664
665
0
  return (ret);
666
0
}
667
668
669
//
670
// 'cupsGetCredentialsExpiration()' - Return the expiration date of the credentials.
671
//
672
673
time_t          // O - Expiration date of credentials
674
cupsGetCredentialsExpiration(
675
    const char *credentials)    // I - Credentials
676
0
{
677
0
  time_t    result = 0; // Result
678
0
  STACK_OF(X509)  *certs;   // Certificate chain
679
680
681
0
  if ((certs = openssl_load_x509(credentials)) != NULL)
682
0
  {
683
0
    result = openssl_get_date(sk_X509_value(certs, 0), 1);
684
0
    sk_X509_pop_free(certs, X509_free);
685
0
  }
686
687
0
  return (result);
688
0
}
689
690
691
//
692
// 'cupsGetCredentialsInfo()' - Return a string describing the credentials.
693
//
694
695
char *          // O - Credentials description or `NULL` on error
696
cupsGetCredentialsInfo(
697
    const char *credentials,    // I - Credentials
698
    char       *buffer,     // I - Buffer
699
    size_t     bufsize)     // I - Size of buffer
700
0
{
701
0
  STACK_OF(X509)  *certs;   // Certificate chain
702
0
  X509      *cert;    // Certificate
703
704
705
  // Range check input...
706
0
  DEBUG_printf("cupsGetCredentialsInfo(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT ")", (void *)credentials, (void *)buffer, CUPS_LLCAST bufsize);
707
708
0
  if (buffer)
709
0
    *buffer = '\0';
710
711
0
  if (!credentials || !buffer || bufsize < 32)
712
0
  {
713
0
    DEBUG_puts("1cupsGetCredentialsInfo: Returning NULL.");
714
0
    return (NULL);
715
0
  }
716
717
0
  if ((certs = openssl_load_x509(credentials)) != NULL)
718
0
  {
719
0
    char    name[256],  // Common name associated with cert
720
0
      issuer[256],  // Issuer associated with cert
721
0
      expdate[256]; // Expiration data as string
722
0
    time_t    expiration; // Expiration date of cert
723
0
    const char    *sigalg;  // Signature algorithm
724
0
    unsigned char md5_digest[16]; // MD5 result
725
726
0
    DEBUG_printf("2cupsGetCredentialsInfo: certs=%p(%d certificates)", certs, sk_X509_num(certs));
727
0
    cert = sk_X509_value(certs, 0);
728
0
    DEBUG_printf("2cupsGetCredentialsInfo: cert=%p", cert);
729
730
0
    if (X509_NAME_get_text_by_NID(X509_get_subject_name(cert), NID_commonName, name, sizeof(name)) < 0)
731
0
      cupsCopyString(name, "unknown", sizeof(name));
732
733
0
    if (X509_NAME_get_text_by_NID(X509_get_issuer_name(cert), NID_commonName, issuer, sizeof(issuer)) < 0)
734
0
      cupsCopyString(issuer, "unknown", sizeof(issuer));
735
736
0
    expiration = openssl_get_date(cert, 1);
737
738
0
    switch (X509_get_signature_nid(cert))
739
0
    {
740
0
      case NID_ecdsa_with_SHA1 :
741
0
          sigalg = "SHA1WithECDSAEncryption";
742
0
          break;
743
0
      case NID_ecdsa_with_SHA224 :
744
0
          sigalg = "SHA224WithECDSAEncryption";
745
0
          break;
746
0
      case NID_ecdsa_with_SHA256 :
747
0
          sigalg = "SHA256WithECDSAEncryption";
748
0
          break;
749
0
      case NID_ecdsa_with_SHA384 :
750
0
          sigalg = "SHA384WithECDSAEncryption";
751
0
          break;
752
0
      case NID_ecdsa_with_SHA512 :
753
0
          sigalg = "SHA512WithECDSAEncryption";
754
0
          break;
755
0
      case NID_sha1WithRSAEncryption :
756
0
          sigalg = "SHA1WithRSAEncryption";
757
0
          break;
758
0
      case NID_sha224WithRSAEncryption :
759
0
          sigalg = "SHA224WithRSAEncryption";
760
0
          break;
761
0
      case NID_sha256WithRSAEncryption :
762
0
          sigalg = "SHA256WithRSAEncryption";
763
0
          break;
764
0
      case NID_sha384WithRSAEncryption :
765
0
          sigalg = "SHA384WithRSAEncryption";
766
0
          break;
767
0
      case NID_sha512WithRSAEncryption :
768
0
          sigalg = "SHA512WithRSAEncryption";
769
0
          break;
770
0
      default :
771
0
          sigalg = "Unknown";
772
0
          break;
773
0
    }
774
775
0
    cupsHashData("md5", credentials, strlen(credentials), md5_digest, sizeof(md5_digest));
776
777
0
    snprintf(buffer, bufsize, "%s (issued by %s) / %s / %s / %02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", name, issuer, httpGetDateString(expiration, expdate, sizeof(expdate)), sigalg, md5_digest[0], md5_digest[1], md5_digest[2], md5_digest[3], md5_digest[4], md5_digest[5], md5_digest[6], md5_digest[7], md5_digest[8], md5_digest[9], md5_digest[10], md5_digest[11], md5_digest[12], md5_digest[13], md5_digest[14], md5_digest[15]);
778
0
    sk_X509_pop_free(certs, X509_free);
779
0
  }
780
781
0
  DEBUG_printf("1cupsGetCredentialsInfo: Returning \"%s\".", buffer);
782
783
0
  return (buffer);
784
0
}
785
786
787
//
788
// 'cupsGetCredentialsTrust()' - Return the trust of credentials.
789
//
790
// This function determines the level of trust for the supplied credentials.
791
// The "path" parameter specifies the certificate/key store for known
792
// credentials and certificate authorities.  The "common_name" parameter
793
// specifies the FQDN of the service being accessed such as
794
// "printer.example.com".  The "credentials" parameter provides the credentials
795
// being evaluated, which are usually obtained with the
796
// @link httpCopyPeerCredentials@ function.  The "require_ca" parameter
797
// specifies whether a CA-signed certificate is required for trust.
798
//
799
// The `AllowAnyRoot`, `AllowExpiredCerts`, `TrustOnFirstUse`, and
800
// `ValidateCerts` options in the "client.conf" file (or corresponding
801
// preferences file on macOS) control the trust policy, which defaults to
802
// AllowAnyRoot=Yes, AllowExpiredCerts=No, TrustOnFirstUse=Yes, and
803
// ValidateCerts=No.  When the "require_ca" parameter is `true` the AllowAnyRoot
804
// and TrustOnFirstUse policies are turned off ("No").
805
//
806
// The returned trust value can be one of the following:
807
//
808
// - `HTTP_TRUST_OK`: Credentials are OK/trusted
809
// - `HTTP_TRUST_INVALID`: Credentials are invalid
810
// - `HTTP_TRUST_EXPIRED`: Credentials are expired
811
// - `HTTP_TRUST_RENEWED`: Credentials have been renewed
812
// - `HTTP_TRUST_UNKNOWN`: Credentials are unknown/new
813
//
814
815
http_trust_t        // O - Level of trust
816
cupsGetCredentialsTrust(
817
    const char *path,     // I - Directory path for certificate/key store or `NULL` for default
818
    const char *common_name,    // I - Common name for trust lookup
819
    const char *credentials,    // I - Credentials
820
    bool       require_ca)    // I - Require a CA-signed certificate?
821
0
{
822
0
  http_trust_t    trust = HTTP_TRUST_OK;
823
          // Trusted?
824
0
  STACK_OF(X509)  *certs;   // Certificate chain
825
0
  X509      *cert;    // Certificate
826
0
  char      *tcreds = NULL; // Trusted credentials
827
0
  char      defpath[1024];  // Default path
828
0
  _cups_globals_t *cg = _cupsGlobals(); // Per-thread globals
829
830
831
0
  DEBUG_printf("cupsGetCredentialsTrust(path=\"%s\", common_name=\"%s\", credentials=\"%lu bytes\", require_ca=%s)", path, common_name, (unsigned long)(credentials ? strlen(credentials) : 0), require_ca ? "true" : "false");
832
833
  // Range check input...
834
0
  if (!path)
835
0
    path = http_default_path(defpath, sizeof(defpath));
836
837
0
  if (!path || !credentials || !common_name)
838
0
  {
839
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), false);
840
0
    DEBUG_printf("1cupsGetCredentialsTrust: Returning %d.", HTTP_TRUST_UNKNOWN);
841
0
    return (HTTP_TRUST_UNKNOWN);
842
0
  }
843
844
  // Load the credentials...
845
0
  if ((certs = openssl_load_x509(credentials)) == NULL)
846
0
  {
847
0
    _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, _("Unable to import credentials."), true);
848
0
    DEBUG_printf("1cupsGetCredentialsTrust: Returning %d.", HTTP_TRUST_UNKNOWN);
849
0
    return (HTTP_TRUST_UNKNOWN);
850
0
  }
851
852
0
  cert = sk_X509_shift(certs);
853
854
0
  if (!cg->client_conf_loaded)
855
0
    _cupsSetDefaults();
856
857
  // Look this common name up in the default keychains...
858
0
  if (sk_X509_num(certs) == 0 && (tcreds = cupsCopyCredentials(path, common_name)) != NULL)
859
0
  {
860
0
    char  credentials_str[1024],  // String for incoming credentials
861
0
    tcreds_str[1024]; // String for saved credentials
862
863
0
    cupsGetCredentialsInfo(credentials, credentials_str, sizeof(credentials_str));
864
0
    cupsGetCredentialsInfo(tcreds, tcreds_str, sizeof(tcreds_str));
865
866
0
    if (strcmp(credentials_str, tcreds_str))
867
0
    {
868
      // Credentials don't match, let's look at the expiration date of the new
869
      // credentials and allow if the new ones have a later expiration...
870
0
      time_t tcreds_exp = cupsGetCredentialsExpiration(tcreds);
871
          // Expiration of saved credentials
872
873
0
      if (!cg->trust_first || require_ca)
874
0
      {
875
        // Do not trust certificates on first use...
876
0
        _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, _("Trust on first use is disabled."), true);
877
878
0
        trust = HTTP_TRUST_INVALID;
879
0
      }
880
0
      else if (openssl_get_date(cert, 1) <= tcreds_exp)
881
0
      {
882
        // The new credentials are not newly issued...
883
0
        _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, _("New credentials are older than stored credentials."), true);
884
885
0
        trust = HTTP_TRUST_INVALID;
886
0
      }
887
0
      else if (!cupsAreCredentialsValidForName(common_name, credentials))
888
0
      {
889
        // The common name does not match the issued certificate...
890
0
        _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, _("New credentials are not valid for name."), true);
891
892
0
        trust = HTTP_TRUST_INVALID;
893
0
      }
894
0
      else if (tcreds_exp < time(NULL))
895
0
      {
896
        // Save the renewed credentials...
897
0
  trust = HTTP_TRUST_RENEWED;
898
899
0
        cupsSaveCredentials(path, common_name, credentials, NULL);
900
0
      }
901
0
    }
902
903
0
    free(tcreds);
904
0
  }
905
0
  else if ((cg->validate_certs || require_ca) && !cupsAreCredentialsValidForName(common_name, credentials))
906
0
  {
907
0
    _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, _("No stored credentials, not valid for name."), true);
908
0
    trust = HTTP_TRUST_INVALID;
909
0
  }
910
0
  else if (sk_X509_num(certs) > 0)
911
0
  {
912
0
    X509_STORE *roots;    // Root certificates
913
914
0
    trust = HTTP_TRUST_INVALID;
915
916
0
    DEBUG_puts("1cupsGetCredentialsTrust: Verifying certificate chain.");
917
918
0
    if ((roots = X509_STORE_new()) != NULL)
919
0
    {
920
      // Create an in-memory certificate store of known system root certs...
921
0
      X509_STORE_CTX  *ctx;   // Verification context
922
0
      char    sitepath[1024]; // _site_ certificate path
923
924
0
      http_make_path(sitepath, sizeof(sitepath), path, "_site_", "crt");
925
0
      if (!access(sitepath, R_OK))
926
0
      {
927
0
        DEBUG_printf("1cupsGetCredentialsTrust: Adding site certificate '%s'.", sitepath);
928
0
        X509_STORE_load_locations(roots, sitepath, /*dir*/NULL);
929
0
      }
930
931
0
      X509_STORE_set_default_paths(roots);
932
0
      X509_STORE_set_trust(roots, X509_TRUST_MAX);
933
934
0
      if ((ctx = X509_STORE_CTX_new()) != NULL)
935
0
      {
936
        // Verify the certificate chain signatures against the trusted root...
937
0
        char    *sitecreds; // Site credentials
938
0
        STACK_OF(X509)  *sitecerts = NULL;
939
          // Site certificate(s)
940
941
0
  X509_STORE_CTX_init(ctx, roots, cert, certs);
942
0
  X509_STORE_CTX_set_verify_cb(ctx, openssl_verify_cb);
943
944
0
        if ((sitecreds = http_copy_file(path, "_site_", "crt")) != NULL)
945
0
        {
946
0
          if ((sitecerts = openssl_load_x509(sitecreds)) != NULL)
947
0
            X509_STORE_CTX_set_ex_data(ctx, 0, sk_X509_value(sitecerts, 0));
948
949
0
          free(sitecreds);
950
0
        }
951
952
#ifdef DEBUG
953
  char  temp[1024];
954
955
  DEBUG_printf("1cupsGetCredentialsTrust: Verifying '%s' with %d chained certs.", X509_NAME_oneline(X509_get_subject_name(cert), temp, (int)sizeof(temp)), sk_X509_num(certs));
956
  DEBUG_printf("1cupsGetCredentialsTrust: issuer: '%s'", X509_NAME_oneline(X509_get_issuer_name(cert), temp, (int)sizeof(temp)));
957
  DEBUG_printf("1cupsGetCredentialsTrust: chain subjectName: '%s'\n", X509_NAME_oneline(X509_get_subject_name(sk_X509_value(certs, sk_X509_num(certs) - 1)), temp, (int)sizeof(temp)));
958
#endif // DEBUG
959
960
0
        if (X509_verify_cert(ctx) == 1)
961
0
    trust = HTTP_TRUST_OK;
962
963
0
        X509_STORE_CTX_free(ctx);
964
0
        if (sitecerts)
965
0
          sk_X509_pop_free(sitecerts, X509_free);
966
0
      }
967
968
0
      X509_STORE_free(roots);
969
0
    }
970
971
0
    if (trust != HTTP_TRUST_OK)
972
0
      _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, _("Credentials do not validate against CA certificates."), true);
973
0
  }
974
0
  else if (require_ca)
975
0
  {
976
0
    _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, _("Credentials are not CA-signed."), true);
977
0
    trust = HTTP_TRUST_INVALID;
978
0
  }
979
0
  else if (!cg->trust_first)
980
0
  {
981
0
    _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, _("Trust on first use is disabled."), true);
982
0
    trust = HTTP_TRUST_INVALID;
983
0
  }
984
0
  else if (!cg->any_root || require_ca)
985
0
  {
986
0
    _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, _("Self-signed credentials are blocked."), true);
987
0
    trust = HTTP_TRUST_INVALID;
988
0
  }
989
990
0
  if (trust == HTTP_TRUST_OK && !cg->expired_certs)
991
0
  {
992
0
    time_t  curtime;    // Current date/time
993
994
0
    time(&curtime);
995
996
0
    DEBUG_printf("1cupsGetCredentialsTrust: curtime=" CUPS_LLFMT ", notBefore=" CUPS_LLFMT ", notAfter=" CUPS_LLFMT, CUPS_LLCAST curtime, CUPS_LLCAST openssl_get_date(cert, 0), CUPS_LLCAST openssl_get_date(cert, 1));
997
998
0
    if ((curtime + 86400) < openssl_get_date(cert, 0) || curtime > openssl_get_date(cert, 1))
999
0
    {
1000
0
      _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, _("Credentials have expired."), true);
1001
0
      trust = HTTP_TRUST_EXPIRED;
1002
0
    }
1003
0
  }
1004
1005
0
  sk_X509_pop_free(certs, X509_free);
1006
0
  X509_free(cert);
1007
1008
0
  DEBUG_printf("1cupsGetCredentialsTrust: Returning %d.", trust);
1009
1010
0
  return (trust);
1011
0
}
1012
1013
1014
//
1015
// 'cupsSignCredentialsRequest()' - Sign an X.509 certificate signing request to produce an X.509 certificate chain.
1016
//
1017
// This function creates an X.509 certificate from a signing request.  The
1018
// certificate is stored in the directory "path" or, if "path" is `NULL`, in a
1019
// per-user or system-wide (when running as root) certificate/key store.  The
1020
// generated certificate is signed by the named root certificate or, if
1021
// "root_name" is `NULL`, a site-wide default root certificate.  When
1022
// "root_name" is `NULL` and there is no site-wide default root certificate, a
1023
// self-signed certificate is generated instead.
1024
//
1025
// The "allowed_purpose" argument specifies the allowed purpose(s) used for the
1026
// credentials as a bitwise OR of the following constants:
1027
//
1028
// - `CUPS_CREDPURPOSE_SERVER_AUTH` for validating TLS servers,
1029
// - `CUPS_CREDPURPOSE_CLIENT_AUTH` for validating TLS clients,
1030
// - `CUPS_CREDPURPOSE_CODE_SIGNING` for validating compiled code,
1031
// - `CUPS_CREDPURPOSE_EMAIL_PROTECTION` for validating email messages,
1032
// - `CUPS_CREDPURPOSE_TIME_STAMPING` for signing timestamps to objects, and/or
1033
// - `CUPS_CREDPURPOSE_OCSP_SIGNING` for Online Certificate Status Protocol
1034
//   message signing.
1035
//
1036
// The "allowed_usage" argument specifies the allowed usage(s) for the
1037
// credentials as a bitwise OR of the following constants:
1038
//
1039
// - `CUPS_CREDUSAGE_DIGITAL_SIGNATURE`: digital signatures,
1040
// - `CUPS_CREDUSAGE_NON_REPUDIATION`: non-repudiation/content commitment,
1041
// - `CUPS_CREDUSAGE_KEY_ENCIPHERMENT`: key encipherment,
1042
// - `CUPS_CREDUSAGE_DATA_ENCIPHERMENT`: data encipherment,
1043
// - `CUPS_CREDUSAGE_KEY_AGREEMENT`: key agreement,
1044
// - `CUPS_CREDUSAGE_KEY_CERT_SIGN`: key certicate signing,
1045
// - `CUPS_CREDUSAGE_CRL_SIGN`: certificate revocation list signing,
1046
// - `CUPS_CREDUSAGE_ENCIPHER_ONLY`: encipherment only,
1047
// - `CUPS_CREDUSAGE_DECIPHER_ONLY`: decipherment only,
1048
// - `CUPS_CREDUSAGE_DEFAULT_CA`: defaults for CA certificates,
1049
// - `CUPS_CREDUSAGE_DEFAULT_TLS`: defaults for TLS certificates, and/or
1050
// - `CUPS_CREDUSAGE_ALL`: all usages.
1051
//
1052
// The "cb" and "cb_data" arguments specify a function and its data that are
1053
// used to validate any subjectAltName values in the signing request:
1054
//
1055
// ```
1056
// bool san_cb(const char *common_name, const char *alt_name, void *cb_data) {
1057
//   ... return true if OK and false if not ...
1058
// }
1059
// ```
1060
//
1061
// If `NULL`, a default validation function is used that allows "localhost" and
1062
// variations of the common name.
1063
//
1064
// The "expiration_date" argument specifies the expiration date and time as a
1065
// Unix `time_t` value in seconds.
1066
//
1067
1068
bool          // O - `true` on success, `false` on failure
1069
cupsSignCredentialsRequest(
1070
    const char         *path,   // I - Directory path for certificate/key store or `NULL` for default
1071
    const char         *common_name,  // I - Common name to use
1072
    const char         *request,  // I - PEM-encoded CSR
1073
    const char         *root_name,  // I - Root certificate
1074
    cups_credpurpose_t allowed_purpose, // I - Allowed credential purpose(s)
1075
    cups_credusage_t   allowed_usage, // I - Allowed credential usage(s)
1076
    cups_cert_san_cb_t cb,    // I - subjectAltName callback or `NULL` to allow just .local
1077
    void               *cb_data,  // I - Callback data
1078
    time_t             expiration_date) // I - Certificate expiration date
1079
0
{
1080
0
  bool    result = false;    // Return value
1081
0
  X509    *cert = NULL;   // Certificate
1082
0
  X509_REQ  *crq = NULL;   // Certificate request
1083
0
  const X509_NAME *subject;   // Subject name of request
1084
0
  X509    *root_cert = NULL; // Root certificate, if any
1085
0
  EVP_PKEY  *root_key = NULL; // Root private key, if any
1086
0
  char    defpath[1024],    // Default path
1087
0
    crtfile[1024],    // Certificate filename
1088
0
    root_crtfile[1024], // Root certificate filename
1089
0
    root_keyfile[1024]; // Root private key filename
1090
0
  time_t  curtime;    // Current time
1091
0
  ASN1_INTEGER  *serial;    // Serial number
1092
0
  ASN1_TIME *notBefore,   // Initial date
1093
0
    *notAfter;    // Expiration date
1094
0
  BIO   *bio;     // Input/output file
1095
0
  char    temp[1024];   // Temporary string
1096
0
  int   i, j,     // Looping vars
1097
0
    num_exts;   // Number of extensions
1098
0
  STACK_OF(X509_EXTENSION) *exts = NULL;// Extensions
1099
0
  X509_EXTENSION *ext;      // Current extension
1100
0
  cups_credpurpose_t purpose;   // Current purpose
1101
0
  cups_credusage_t usage;   // Current usage
1102
0
  bool    saw_usage = false,  // Saw NID_key_usage?
1103
0
    saw_ext_usage = false,  // Saw NID_ext_key_usage?
1104
0
    saw_san = false;  // Saw NID_subject_alt_name?
1105
1106
1107
0
  DEBUG_printf("cupsSignCredentialsRequest(path=\"%s\", common_name=\"%s\", request=\"%s\", root_name=\"%s\", allowed_purpose=0x%x, allowed_usage=0x%x, cb=%p, cb_data=%p, expiration_date=%ld)", path, common_name, request, root_name, allowed_purpose, allowed_usage, (void *)cb, cb_data, (long)expiration_date);
1108
1109
  // Filenames...
1110
0
  if (!path)
1111
0
    path = http_default_path(defpath, sizeof(defpath));
1112
1113
0
  if (!path || !common_name || !request)
1114
0
  {
1115
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), false);
1116
0
    return (false);
1117
0
  }
1118
1119
0
  if (!cb)
1120
0
    cb = http_default_san_cb;
1121
1122
  // Import the X.509 certificate request...
1123
0
  DEBUG_puts("1cupsCreateCredentials: Importing X.509 certificate request.");
1124
0
  if ((bio = BIO_new_mem_buf(request, (int)strlen(request))) != NULL)
1125
0
  {
1126
0
    PEM_read_bio_X509_REQ(bio, &crq, /*cb*/NULL, /*u*/NULL);
1127
0
    BIO_free(bio);
1128
0
  }
1129
1130
0
  if (!crq)
1131
0
  {
1132
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to import X.509 certificate request."), true);
1133
0
    return (false);
1134
0
  }
1135
1136
0
  if (X509_REQ_verify(crq, X509_REQ_get_pubkey(crq)) <= 0)
1137
0
  {
1138
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to verify X.509 certificate request."), true);
1139
0
    goto done;
1140
0
  }
1141
1142
  // Verify that any commonName values match the common name we are signing for...
1143
0
  subject = X509_REQ_get_subject_name(crq);
1144
1145
0
  for (i = -1; (i = X509_NAME_get_index_by_NID(subject, NID_commonName, i)) >= 0;)
1146
0
  {
1147
0
    const ASN1_STRING *cn = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject, i));
1148
          // commonName value
1149
0
    size_t  cnlen = (size_t)ASN1_STRING_length(cn);
1150
          // Length of commonName value
1151
1152
    // The ASN.1 data is not necessarily nul-terminated, so compare only the
1153
    // encoded length and never read past it...
1154
0
    if (cnlen != strlen(common_name) || _cups_strncasecmp((const char *)ASN1_STRING_get0_data(cn), common_name, cnlen))
1155
0
    {
1156
0
      _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Validation of commonName in X.509 certificate request failed."), true);
1157
0
      goto done;
1158
0
    }
1159
0
  }
1160
1161
  // Create the X.509 certificate...
1162
0
  DEBUG_puts("1cupsSignCredentialsRequest: Generating X.509 certificate.");
1163
1164
0
  if ((cert = X509_new()) == NULL)
1165
0
  {
1166
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to create X.509 certificate."), true);
1167
0
    goto done;
1168
0
  }
1169
1170
0
  curtime = time(NULL);
1171
1172
0
  notBefore = ASN1_TIME_new();
1173
0
  ASN1_TIME_set(notBefore, curtime);
1174
0
  X509_set_notBefore(cert, notBefore);
1175
0
  ASN1_TIME_free(notBefore);
1176
1177
0
  notAfter  = ASN1_TIME_new();
1178
0
  ASN1_TIME_set(notAfter, expiration_date);
1179
0
  X509_set_notAfter(cert, notAfter);
1180
0
  ASN1_TIME_free(notAfter);
1181
1182
0
  serial = ASN1_INTEGER_new();
1183
0
  ASN1_INTEGER_set(serial, (long)curtime);
1184
0
  X509_set_serialNumber(cert, serial);
1185
0
  ASN1_INTEGER_free(serial);
1186
1187
0
  X509_set_pubkey(cert, X509_REQ_get_pubkey(crq));
1188
1189
0
  X509_set_subject_name(cert, X509_REQ_get_subject_name(crq));
1190
0
  X509_set_version(cert, 2); // v3
1191
1192
  // Copy/verify extensions...
1193
0
  exts     = X509_REQ_get_extensions(crq);
1194
0
  num_exts = sk_X509_EXTENSION_num(exts);
1195
1196
0
  for (i = 0; i < num_exts; i ++)
1197
0
  {
1198
    // Get the extension object...
1199
0
    bool    add_ext = false;  // Add this extension?
1200
0
    ASN1_OBJECT   *obj;     // Extension object
1201
0
    ASN1_OCTET_STRING *extdata;   // Extension data string
1202
0
    unsigned char *data = NULL;   // Extension data bytes
1203
0
    int     datalen;    // Length of extension data
1204
1205
0
    ext     = sk_X509_EXTENSION_value(exts, i);
1206
0
    obj     = (ASN1_OBJECT *)X509_EXTENSION_get_object(ext);
1207
0
    extdata = (ASN1_OCTET_STRING *)X509_EXTENSION_get_data(ext);
1208
0
    datalen = i2d_ASN1_OCTET_STRING(extdata, &data);
1209
1210
#ifdef DEBUG
1211
    char *tempptr;        // Pointer into string
1212
1213
    for (j = 0, tempptr = temp; j < datalen && tempptr < (temp + sizeof(temp) - 2); j ++, tempptr += 2)
1214
      snprintf(tempptr, sizeof(temp) - (size_t)(tempptr - temp), "%02X", data[j]);
1215
1216
    DEBUG_printf("1cupsSignCredentialsRequest: EXT%d=%s", OBJ_obj2nid(obj), temp);
1217
#endif // DEBUG
1218
1219
0
    switch (OBJ_obj2nid(obj))
1220
0
    {
1221
0
      case NID_ext_key_usage :
1222
0
          add_ext       = true;
1223
0
          saw_ext_usage = true;
1224
1225
0
          if (datalen < 12 || data[2] != 0x30 || data[3] != (datalen - 4))
1226
0
          {
1227
0
            _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad keyUsage extension in X.509 certificate request."), true);
1228
0
      goto done;
1229
0
          }
1230
1231
0
          for (purpose = 0, j = 4; j < datalen; j += data[j + 1] + 2)
1232
0
          {
1233
0
            if ((j + 2) > datalen || (j + 2 + data[j + 1]) > datalen || data[j] != 0x06 || data[j + 1] != 8 || memcmp(data + j + 2, "+\006\001\005\005\007\003", 7))
1234
0
            {
1235
0
        _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad keyUsage extension in X.509 certificate request."), true);
1236
0
        goto done;
1237
0
            }
1238
1239
0
            switch (data[j + 9])
1240
0
            {
1241
0
              case 1 :
1242
0
                  purpose |= CUPS_CREDPURPOSE_SERVER_AUTH;
1243
0
                  break;
1244
0
              case 2 :
1245
0
                  purpose |= CUPS_CREDPURPOSE_CLIENT_AUTH;
1246
0
                  break;
1247
0
              case 3 :
1248
0
                  purpose |= CUPS_CREDPURPOSE_CODE_SIGNING;
1249
0
                  break;
1250
0
              case 4 :
1251
0
                  purpose |= CUPS_CREDPURPOSE_EMAIL_PROTECTION;
1252
0
                  break;
1253
0
              case 8 :
1254
0
                  purpose |= CUPS_CREDPURPOSE_TIME_STAMPING;
1255
0
                  break;
1256
0
              case 9 :
1257
0
                  purpose |= CUPS_CREDPURPOSE_OCSP_SIGNING;
1258
0
                  break;
1259
0
        default :
1260
0
      _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad keyUsage extension in X.509 certificate request."), true);
1261
0
      goto done;
1262
0
            }
1263
0
          }
1264
1265
0
          DEBUG_printf("1cupsSignCredentialsRequest: purpose=0x%04x", purpose);
1266
1267
0
          if (purpose & ~allowed_purpose)
1268
0
          {
1269
0
            _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad keyUsage extension in X.509 certificate request."), true);
1270
0
      goto done;
1271
0
          }
1272
0
          break;
1273
1274
0
      case NID_key_usage :
1275
0
          add_ext   = true;
1276
0
          saw_usage = true;
1277
1278
0
          if (datalen < 6 || datalen > 7 || data[2] != 0x03 || data[3] != (datalen - 4))
1279
0
          {
1280
0
            _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad extKeyUsage extension in X.509 certificate request."), true);
1281
0
      goto done;
1282
0
          }
1283
1284
0
          usage = 0;
1285
0
          if (data[5] & 0x80)
1286
0
      usage |= CUPS_CREDUSAGE_DIGITAL_SIGNATURE;
1287
0
          if (data[5] & 0x40)
1288
0
      usage |= CUPS_CREDUSAGE_NON_REPUDIATION;
1289
0
          if (data[5] & 0x20)
1290
0
      usage |= CUPS_CREDUSAGE_KEY_ENCIPHERMENT;
1291
0
          if (data[5] & 0x10)
1292
0
      usage |= CUPS_CREDUSAGE_DATA_ENCIPHERMENT;
1293
0
          if (data[5] & 0x08)
1294
0
      usage |= CUPS_CREDUSAGE_KEY_AGREEMENT;
1295
0
          if (data[5] & 0x04)
1296
0
      usage |= CUPS_CREDUSAGE_KEY_CERT_SIGN;
1297
0
          if (data[5] & 0x02)
1298
0
      usage |= CUPS_CREDUSAGE_CRL_SIGN;
1299
0
          if (data[5] & 0x01)
1300
0
      usage |= CUPS_CREDUSAGE_ENCIPHER_ONLY;
1301
0
          if (datalen == 7 && (data[6] & 0x80))
1302
0
      usage |= CUPS_CREDUSAGE_DECIPHER_ONLY;
1303
1304
0
          DEBUG_printf("1cupsSignCredentialsRequest: usage=0x%04x", usage);
1305
1306
0
          if (usage & ~allowed_usage)
1307
0
          {
1308
0
            _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad extKeyUsage extension in X.509 certificate request."), true);
1309
0
      goto done;
1310
0
          }
1311
0
          break;
1312
1313
0
      case NID_subject_alt_name :
1314
0
          add_ext = true;
1315
0
          saw_san = true;
1316
1317
0
          if (datalen < 4 || data[2] != 0x30 || data[3] != (datalen - 4))
1318
0
          {
1319
0
            _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad subjectAltName extension in X.509 certificate request."), true);
1320
0
      goto done;
1321
0
          }
1322
1323
          // Parse the SAN values (there should be an easier/standard OpenSSL API to do this!)
1324
0
          for (j = 4; j < datalen; j += data[j + 1] + 2)
1325
0
          {
1326
      // Reject elements whose header or value runs past the extension data...
1327
0
      if ((j + 2) > datalen || (j + 2 + data[j + 1]) > datalen)
1328
0
      {
1329
0
              _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad subjectAltName extension in X.509 certificate request."), true);
1330
0
        goto done;
1331
0
      }
1332
1333
0
            if (data[j] == 0x82)
1334
0
            {
1335
              // GENERAL_STRING for DNS - reject empty names and names with
1336
              // embedded nul bytes since the callback would not see the whole
1337
              // value...
1338
0
              if (!data[j + 1] || memchr(data + j + 2, '\0', data[j + 1]))
1339
0
              {
1340
0
                _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad subjectAltName extension in X.509 certificate request."), true);
1341
0
                goto done;
1342
0
              }
1343
1344
0
              memcpy(temp, data + j + 2, data[j + 1]);
1345
0
              temp[data[j + 1]] = '\0';
1346
1347
0
              DEBUG_printf("1cupsSignCredentialsRequest: SAN %s", temp);
1348
1349
0
              if (!(cb)(common_name, temp, cb_data))
1350
0
              {
1351
0
                _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Validation of subjectAltName in X.509 certificate request failed."), true);
1352
0
                goto done;
1353
0
              }
1354
0
      }
1355
0
          }
1356
0
          break;
1357
0
    }
1358
1359
0
    OPENSSL_free(data);
1360
1361
    // If we get this far, the object is OK and we can add it...
1362
0
    if (add_ext && !X509_add_ext(cert, ext, -1))
1363
0
      goto done;
1364
0
  }
1365
1366
  // Add basic constraints for an "edge" certificate...
1367
0
  if ((ext = X509V3_EXT_conf_nid(/*conf*/NULL, /*ctx*/NULL, NID_basic_constraints, "critical,CA:FALSE,pathlen:0")) == NULL || !X509_add_ext(cert, ext, -1))
1368
0
  {
1369
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to add extension to X.509 certificate."), true);
1370
0
    goto done;
1371
0
  }
1372
1373
  // Add key usage extensions as needed...
1374
0
  if (!saw_usage)
1375
0
  {
1376
0
    if ((ext = X509V3_EXT_conf_nid(/*conf*/NULL, /*ctx*/NULL, NID_key_usage, "critical,digitalSignature,keyEncipherment")) == NULL || !X509_add_ext(cert, ext, -1))
1377
0
    {
1378
0
      _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to add extension to X.509 certificate."), true);
1379
0
      goto done;
1380
0
    }
1381
0
  }
1382
1383
0
  if (!saw_ext_usage)
1384
0
  {
1385
0
    if ((ext = X509V3_EXT_conf_nid(/*conf*/NULL, /*ctx*/NULL, NID_ext_key_usage, tls_usage_strings[0])) == NULL || !X509_add_ext(cert, ext, -1))
1386
0
    {
1387
0
      _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to add extension to X.509 certificate."), true);
1388
0
      goto done;
1389
0
    }
1390
0
  }
1391
1392
0
  if (!saw_san)
1393
0
  {
1394
0
    if ((ext = openssl_create_san(common_name, /*num_alt_names*/0, /*alt_names*/NULL)) == NULL || !X509_add_ext(cert, ext, -1))
1395
0
    {
1396
0
      _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to add extension to X.509 certificate."), true);
1397
0
      goto done;
1398
0
    }
1399
0
  }
1400
1401
  // Try loading a root certificate...
1402
0
  http_make_path(root_crtfile, sizeof(root_crtfile), path, root_name ? root_name : "_site_", "crt");
1403
0
  http_make_path(root_keyfile, sizeof(root_keyfile), path, root_name ? root_name : "_site_", "key");
1404
1405
0
  if (!access(root_crtfile, 0) && !access(root_keyfile, 0))
1406
0
  {
1407
0
    if ((bio = BIO_new_file(root_crtfile, "rb")) != NULL)
1408
0
    {
1409
0
      PEM_read_bio_X509(bio, &root_cert, /*cb*/NULL, /*u*/NULL);
1410
0
      BIO_free(bio);
1411
1412
0
      if ((bio = BIO_new_file(root_keyfile, "rb")) != NULL)
1413
0
      {
1414
0
  PEM_read_bio_PrivateKey(bio, &root_key, /*cb*/NULL, /*u*/NULL);
1415
0
  BIO_free(bio);
1416
0
      }
1417
1418
0
      if (!root_key)
1419
0
      {
1420
        // Only use root certificate if we have the key...
1421
0
        X509_free(root_cert);
1422
0
        root_cert = NULL;
1423
0
      }
1424
0
    }
1425
0
  }
1426
1427
0
  if (!root_cert || !root_key)
1428
0
  {
1429
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to load X.509 CA certificate and private key."), true);
1430
0
    goto done;
1431
0
  }
1432
1433
0
  X509_set_issuer_name(cert, X509_get_subject_name(root_cert));
1434
0
  X509_sign(cert, root_key, EVP_sha256());
1435
1436
  // Save the certificate...
1437
0
  http_make_path(crtfile, sizeof(crtfile), path, common_name, "crt");
1438
1439
0
  if ((bio = openssl_open_file(crtfile, 0644)) == NULL)
1440
0
  {
1441
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
1442
0
    goto done;
1443
0
  }
1444
1445
0
  if (!PEM_write_bio_X509(bio, cert))
1446
0
  {
1447
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to write X.509 certificate."), true);
1448
0
    BIO_free(bio);
1449
0
    goto done;
1450
0
  }
1451
1452
0
  PEM_write_bio_X509(bio, root_cert);
1453
1454
0
  BIO_free(bio);
1455
0
  result = true;
1456
0
  DEBUG_puts("1cupsSignRequest: Successfully created credentials.");
1457
1458
  // Cleanup...
1459
0
  done:
1460
1461
0
  if (exts)
1462
0
    sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1463
0
  if (crq)
1464
0
    X509_REQ_free(crq);
1465
0
  if (cert)
1466
0
    X509_free(cert);
1467
0
  if (root_cert)
1468
0
    X509_free(root_cert);
1469
0
  if (root_key)
1470
0
    EVP_PKEY_free(root_key);
1471
1472
0
  return (result);
1473
0
}
1474
1475
1476
//
1477
// 'httpCopyPeerCredentials()' - Copy the credentials associated with the peer in an encrypted connection.
1478
//
1479
1480
char *          // O - PEM-encoded X.509 certificate chain or `NULL`
1481
httpCopyPeerCredentials(http_t *http) // I - Connection to server
1482
3.90k
{
1483
3.90k
  char    *credentials = NULL; // Return value
1484
3.90k
  size_t  alloc_creds = 0;  // Allocated size
1485
3.90k
  STACK_OF(X509) *chain;    // Certificate chain
1486
1487
1488
3.90k
  DEBUG_printf("httpCopyPeerCredentials(http=%p)", (void *)http);
1489
1490
3.90k
  if (http && http->tls)
1491
0
  {
1492
    // Get the chain of certificates for the remote end...
1493
0
    chain = SSL_get_peer_cert_chain(http->tls);
1494
1495
0
    DEBUG_printf("1httpCopyPeerCredentials: chain=%p", (void *)chain);
1496
1497
0
    if (chain)
1498
0
    {
1499
      // Loop through the certificates, adding them to the string...
1500
0
      int i,      // Looping var
1501
0
    count;      // Number of certs
1502
1503
0
      for (i = 0, count = sk_X509_num(chain); i < count; i ++)
1504
0
      {
1505
0
  X509  *cert = sk_X509_value(chain, i);
1506
            // Current certificate
1507
0
  BIO *bio = BIO_new(BIO_s_mem());
1508
            // Memory buffer for cert
1509
1510
0
        DEBUG_printf("1httpCopyPeerCredentials: chain[%d/%d]=%p", i + 1, count, (void *)cert);
1511
1512
#ifdef DEBUG
1513
  char subjectName[256], issuerName[256];
1514
1515
  if (X509_NAME_get_text_by_NID(X509_get_subject_name(cert), NID_commonName, subjectName, sizeof(subjectName)) < 0)
1516
    cupsCopyString(subjectName, "unknown", sizeof(subjectName));
1517
1518
  if (X509_NAME_get_text_by_NID(X509_get_issuer_name(cert), NID_commonName, issuerName, sizeof(issuerName)) < 0)
1519
    cupsCopyString(issuerName, "unknown", sizeof(issuerName));
1520
1521
  DEBUG_printf("1httpCopyPeerCredentials: subjectName=\"%s\", issuerName=\"%s\"", subjectName, issuerName);
1522
1523
  STACK_OF(GENERAL_NAME) *names;  // subjectAltName values
1524
  names = X509_get_ext_d2i(cert, NID_subject_alt_name, /*crit*/NULL, /*idx*/NULL);
1525
  DEBUG_printf("1httpCopyPeerCredentials: subjectAltNames=%p(%d)", (void *)names, names ? sk_GENERAL_NAME_num(names) : 0);
1526
        if (names)
1527
          GENERAL_NAMES_free(names);
1528
#endif // DEBUG
1529
1530
0
  if (bio)
1531
0
  {
1532
0
    long  bytes;      // Number of bytes
1533
0
    char  *buffer;    // Pointer to bytes
1534
1535
0
    if (PEM_write_bio_X509(bio, cert))
1536
0
    {
1537
0
      if ((bytes = BIO_get_mem_data(bio, &buffer)) > 0)
1538
0
      {
1539
        // Expand credentials string...
1540
0
        if ((credentials = realloc(credentials, alloc_creds + (size_t)bytes + 1)) != NULL)
1541
0
        {
1542
          // Copy PEM-encoded data...
1543
0
          memcpy(credentials + alloc_creds, buffer, bytes);
1544
0
          credentials[alloc_creds + (size_t)bytes] = '\0';
1545
0
          alloc_creds += (size_t)bytes;
1546
0
        }
1547
0
      }
1548
0
    }
1549
1550
0
    BIO_free(bio);
1551
1552
0
    if (!credentials)
1553
0
      break;
1554
0
  }
1555
0
      }
1556
0
    }
1557
0
  }
1558
1559
3.90k
  DEBUG_printf("1httpCopyPeerCredentials: Returning \"%s\".", credentials);
1560
1561
3.90k
  return (credentials);
1562
3.90k
}
1563
1564
1565
//
1566
// '_httpCreateCredentials()' - Create credentials in the internal format.
1567
//
1568
1569
_http_tls_credentials_t *   // O - Internal credentials
1570
_httpCreateCredentials(
1571
    const char *credentials,    // I - Credentials string
1572
    const char *key)      // I - Private key string
1573
0
{
1574
0
  _http_tls_credentials_t *hcreds;  // Credentials
1575
1576
1577
0
  DEBUG_printf("_httpCreateCredentials(credentials=\"%s\", key=\"%s\")", credentials, key);
1578
1579
0
  if (!credentials || !*credentials || !key || !*key)
1580
0
    return (NULL);
1581
1582
0
  if ((hcreds = calloc(1, sizeof(_http_tls_credentials_t))) == NULL)
1583
0
    return (NULL);
1584
1585
0
  hcreds->use = 1;
1586
1587
  // Load the certificates...
1588
0
  if ((hcreds->certs = openssl_load_x509(credentials)) == NULL)
1589
0
  {
1590
0
    _httpFreeCredentials(hcreds);
1591
0
    hcreds = NULL;
1592
0
  }
1593
0
  else
1594
0
  {
1595
    // Load the private key...
1596
0
    BIO *bio;       // Basic I/O for string
1597
1598
0
    if ((bio = BIO_new_mem_buf(key, strlen(key))) == NULL)
1599
0
    {
1600
0
      _httpFreeCredentials(hcreds);
1601
0
      hcreds = NULL;
1602
0
    }
1603
1604
0
    if (!PEM_read_bio_PrivateKey(bio, &hcreds->key, NULL, NULL))
1605
0
    {
1606
0
      _httpFreeCredentials(hcreds);
1607
0
      hcreds = NULL;
1608
0
    }
1609
0
  }
1610
1611
0
  DEBUG_printf("1_httpCreateCredentials: Returning %p.", (void *)hcreds);
1612
1613
0
  return (hcreds);
1614
0
}
1615
1616
1617
//
1618
// '_httpFreeCredentials()' - Free internal credentials.
1619
//
1620
1621
void
1622
_httpFreeCredentials(
1623
    _http_tls_credentials_t *hcreds)  // I - Internal credentials
1624
5.72k
{
1625
5.72k
  if (!hcreds)
1626
5.72k
    return;
1627
1628
0
  if (hcreds->use)
1629
0
    hcreds->use --;
1630
1631
0
  if (hcreds->use)
1632
0
    return;
1633
1634
0
  sk_X509_free(hcreds->certs);
1635
0
  free(hcreds);
1636
0
}
1637
1638
1639
//
1640
// 'httpGetSecurity()' - Get the TLS version and cipher suite used by a connection.
1641
//
1642
// This function gets the TLS version and cipher suite being used by a
1643
// connection, if any.  The string is copied to "buffer" and is of the form
1644
// "TLS/major.minor CipherSuite".  If not encrypted, the buffer is cleared to
1645
// the empty string.
1646
//
1647
1648
const char *        // O - Security information or `NULL` if not encrypted
1649
httpGetSecurity(http_t *http,   // I - HTTP connection
1650
                char   *buffer,   // I - String buffer
1651
                size_t bufsize)   // I - Size of buffer
1652
0
{
1653
0
  const char  *cipherName;    // Cipher suite name
1654
1655
1656
  // Range check input...
1657
0
  if (buffer)
1658
0
    *buffer = '\0';
1659
1660
0
  if (!http || !http->tls || !buffer || bufsize < 16)
1661
0
    return (NULL);
1662
1663
  // Record the TLS version and cipher suite...
1664
0
  cipherName = SSL_get_cipher_name(http->tls);
1665
1666
0
  switch (SSL_version(http->tls))
1667
0
  {
1668
0
    default :
1669
0
        snprintf(buffer, bufsize, "TLS/?.? %s", cipherName);
1670
0
        break;
1671
1672
0
    case TLS1_VERSION :
1673
0
        snprintf(buffer, bufsize, "TLS/1.0 %s", cipherName);
1674
0
        break;
1675
1676
0
    case TLS1_1_VERSION :
1677
0
        snprintf(buffer, bufsize, "TLS/1.1 %s", cipherName);
1678
0
        break;
1679
1680
0
    case TLS1_2_VERSION :
1681
0
        snprintf(buffer, bufsize, "TLS/1.2 %s", cipherName);
1682
0
        break;
1683
1684
0
#  ifdef TLS1_3_VERSION
1685
0
    case TLS1_3_VERSION :
1686
0
        snprintf(buffer, bufsize, "TLS/1.3 %s", cipherName);
1687
0
        break;
1688
0
#  endif // TLS1_3_VERSION
1689
0
  }
1690
1691
0
  return (buffer);
1692
0
}
1693
1694
1695
//
1696
// '_httpTLSInitialize()' - Initialize the TLS stack.
1697
//
1698
1699
void
1700
_httpTLSInitialize(void)
1701
1
{
1702
  // OpenSSL no longer requires explicit initialization...
1703
1
}
1704
1705
1706
//
1707
// '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
1708
//
1709
1710
size_t          // O - Bytes available
1711
_httpTLSPending(http_t *http)   // I - HTTP connection
1712
0
{
1713
0
  return ((size_t)SSL_pending(http->tls));
1714
0
}
1715
1716
1717
//
1718
// '_httpTLSRead()' - Read from a SSL/TLS connection.
1719
//
1720
1721
int         // O - Bytes read
1722
_httpTLSRead(http_t *http,    // I - Connection to server
1723
       char   *buf,   // I - Buffer to store data
1724
       int    len)    // I - Length of buffer
1725
0
{
1726
0
  int bytes = SSL_read((SSL *)(http->tls), buf, len);
1727
          // Bytes read
1728
1729
0
  DEBUG_printf("7_httpTLSRead(http=%p, buf=%p, len=%d) got %d", (void *)http, (void *)buf, len, bytes);
1730
1731
0
  if (bytes > 0)
1732
0
    return (bytes);
1733
1734
  // For now, make difference only for error after which we can retry, EPIPE otherwise...
1735
0
  if (SSL_get_error(http->tls, bytes) == SSL_ERROR_WANT_READ)
1736
0
    errno = EAGAIN;
1737
0
  else
1738
0
    errno = EPIPE;
1739
1740
0
  return (-1);
1741
0
}
1742
1743
1744
//
1745
// '_httpTLSStart()' - Set up SSL/TLS support on a connection.
1746
//
1747
1748
bool          // O - `true` on success, `false` on failure
1749
_httpTLSStart(http_t *http)   // I - Connection to server
1750
9
{
1751
9
  const char  *keypath;   // Certificate store path
1752
9
  BIO   *bio;     // Basic input/output context
1753
9
  SSL_CTX *context;   // Encryption context
1754
9
  char    hostname[256],    // Hostname
1755
9
    cipherlist[256];  // List of cipher suites
1756
9
  unsigned long error;      // Error code, if any
1757
9
  _cups_globals_t *cg = _cupsGlobals(); // Per-thread globals
1758
9
  static const uint16_t versions[] =  // SSL/TLS versions
1759
9
  {
1760
9
    TLS1_VERSION,     // No more SSL support in OpenSSL
1761
9
    TLS1_VERSION,     // TLS/1.0
1762
9
    TLS1_1_VERSION,     // TLS/1.1
1763
9
    TLS1_2_VERSION,     // TLS/1.2
1764
9
#ifdef TLS1_3_VERSION
1765
9
    TLS1_3_VERSION,     // TLS/1.3
1766
    TLS1_3_VERSION      // TLS/1.3 (max)
1767
#else
1768
    TLS1_2_VERSION,     // TLS/1.2
1769
    TLS1_2_VERSION      // TLS/1.2 (max)
1770
#endif // TLS1_3_VERSION
1771
9
  };
1772
1773
1774
9
  DEBUG_printf("3_httpTLSStart(http=%p)", (void *)http);
1775
1776
9
  if (!cg->client_conf_loaded)
1777
1
  {
1778
1
    DEBUG_puts("4_httpTLSStart: Setting defaults.");
1779
1
    _cupsSetDefaults();
1780
1
    DEBUG_printf("4_httpTLSStart: tls_options=%x", tls_options);
1781
1
  }
1782
1783
9
  cupsMutexLock(&tls_mutex);
1784
9
  keypath = tls_keypath;
1785
9
  cupsMutexUnlock(&tls_mutex);
1786
1787
9
  if (http->mode == _HTTP_MODE_SERVER && !keypath)
1788
0
  {
1789
0
    DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
1790
0
    http->error  = errno = EINVAL;
1791
0
    http->status = HTTP_STATUS_ERROR;
1792
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Server credentials not set."), true);
1793
1794
0
    return (false);
1795
0
  }
1796
1797
9
  if (http->mode == _HTTP_MODE_CLIENT)
1798
9
  {
1799
    // Negotiate a TLS connection as a client...
1800
9
    context = SSL_CTX_new(TLS_client_method());
1801
9
    if (http->tls_credentials)
1802
0
    {
1803
0
      int i,      // Looping var
1804
0
    count;      // Number of certificates
1805
1806
0
      DEBUG_puts("4_httpTLSStart: Using client certificate.");
1807
0
      SSL_CTX_use_certificate(context, sk_X509_value(http->tls_credentials->certs, 0));
1808
0
      SSL_CTX_use_PrivateKey(context, http->tls_credentials->key);
1809
1810
0
      count = sk_X509_num(http->tls_credentials->certs);
1811
0
      for (i = 1; i < count; i ++)
1812
0
        SSL_CTX_add_extra_chain_cert(context, sk_X509_value(http->tls_credentials->certs, i));
1813
0
    }
1814
9
  }
1815
0
  else
1816
0
  {
1817
    // Negotiate a TLS connection as a server
1818
0
    char  crtfile[1024],    // Certificate file
1819
0
    keyfile[1024];    // Private key file
1820
0
    const char  *cn = NULL,   // Common name to lookup
1821
0
    *cnptr;     // Pointer into common name
1822
0
    bool  have_creds = false;  // Have credentials?
1823
1824
0
    context = SSL_CTX_new(TLS_server_method());
1825
1826
    // Find the TLS certificate...
1827
0
    cupsMutexLock(&tls_mutex);
1828
1829
0
    if (!tls_common_name)
1830
0
    {
1831
0
      cupsMutexUnlock(&tls_mutex);
1832
1833
0
      if (http->fields[HTTP_FIELD_HOST])
1834
0
      {
1835
  // Use hostname for TLS upgrade...
1836
0
  cupsCopyString(hostname, http->fields[HTTP_FIELD_HOST], sizeof(hostname));
1837
0
      }
1838
0
      else
1839
0
      {
1840
  // Resolve hostname from connection address...
1841
0
  http_addr_t addr;   // Connection address
1842
0
  socklen_t addrlen;  // Length of address
1843
1844
0
  addrlen = sizeof(addr);
1845
0
  if (getsockname(http->fd, (struct sockaddr *)&addr, &addrlen))
1846
0
  {
1847
    // Unable to get local socket address so use default...
1848
0
    DEBUG_printf("4_httpTLSStart: Unable to get socket address: %s", strerror(errno));
1849
0
    hostname[0] = '\0';
1850
0
  }
1851
0
  else if (httpAddrIsLocalhost(&addr))
1852
0
  {
1853
    // Local access top use default...
1854
0
    hostname[0] = '\0';
1855
0
  }
1856
0
  else
1857
0
  {
1858
    // Lookup the socket address...
1859
0
    httpAddrLookup(&addr, hostname, sizeof(hostname));
1860
0
    DEBUG_printf("4_httpTLSStart: Resolved socket address to \"%s\".", hostname);
1861
0
  }
1862
0
      }
1863
1864
0
      if (_cups_isdigit(hostname[0]) || hostname[0] == '[')
1865
0
  hostname[0] = '\0';   // Don't allow numeric addresses
1866
1867
0
      if (hostname[0])
1868
0
  cn = hostname;
1869
1870
0
      cupsMutexLock(&tls_mutex);
1871
0
    }
1872
1873
0
    if (!cn)
1874
0
      cn = tls_common_name;
1875
1876
0
    DEBUG_printf("4_httpTLSStart: Using common name \"%s\"...", cn);
1877
1878
0
    if (cn)
1879
0
    {
1880
      // First look in the CUPS keystore...
1881
0
      http_make_path(crtfile, sizeof(crtfile), tls_keypath, cn, "crt");
1882
0
      http_make_path(keyfile, sizeof(keyfile), tls_keypath, cn, "key");
1883
1884
0
      if (access(crtfile, R_OK) || access(keyfile, R_OK))
1885
0
      {
1886
        // No CUPS-managed certs, look for CA certs...
1887
0
        char cacrtfile[1024], cakeyfile[1024];  // CA cert files
1888
1889
0
        snprintf(cacrtfile, sizeof(cacrtfile), "/etc/letsencrypt/live/%s/fullchain.pem", cn);
1890
0
        snprintf(cakeyfile, sizeof(cakeyfile), "/etc/letsencrypt/live/%s/privkey.pem", cn);
1891
1892
0
        if ((access(cacrtfile, R_OK) || access(cakeyfile, R_OK)) && (cnptr = strchr(cn, '.')) != NULL)
1893
0
        {
1894
          // Try just domain name...
1895
0
          cnptr ++;
1896
0
          if (strchr(cnptr, '.'))
1897
0
          {
1898
0
            snprintf(cacrtfile, sizeof(cacrtfile), "/etc/letsencrypt/live/%s/fullchain.pem", cnptr);
1899
0
            snprintf(cakeyfile, sizeof(cakeyfile), "/etc/letsencrypt/live/%s/privkey.pem", cnptr);
1900
0
          }
1901
0
        }
1902
1903
0
        if (!access(cacrtfile, R_OK) && !access(cakeyfile, R_OK))
1904
0
        {
1905
          // Use the CA certs...
1906
0
          cupsCopyString(crtfile, cacrtfile, sizeof(crtfile));
1907
0
          cupsCopyString(keyfile, cakeyfile, sizeof(keyfile));
1908
1909
0
          have_creds = true;
1910
0
        }
1911
0
      }
1912
0
      else
1913
0
      {
1914
        // CUPS-managed self-signed certs: use them only if they have
1915
        // not expired, otherwise let the auto-create code path below
1916
        // regenerate them (Issue #1519). cupsGetCredentialsExpiration()
1917
        // expects a PEM string, not a file path, so load the cert via
1918
        // cupsCopyCredentials() first.
1919
0
        char  *creds = cupsCopyCredentials(tls_keypath, cn);
1920
          // PEM-encoded certificate
1921
1922
0
        have_creds = cupsGetCredentialsExpiration(creds) > time(NULL);
1923
0
        free(creds);
1924
0
      }
1925
0
    }
1926
1927
0
    if (!have_creds && tls_auto_create && cn)
1928
0
    {
1929
0
      DEBUG_printf("4_httpTLSStart: Auto-create credentials for \"%s\".", cn);
1930
1931
0
      if (!cupsCreateCredentials(tls_keypath, false, CUPS_CREDPURPOSE_SERVER_AUTH, CUPS_CREDTYPE_DEFAULT, CUPS_CREDUSAGE_DEFAULT_TLS, NULL, NULL, NULL, NULL, NULL, cn, NULL, 0, NULL, NULL, time(NULL) + 3650 * 86400))
1932
0
      {
1933
0
  DEBUG_printf("4_httpTLSStart: cupsCreateCredentials failed: %s", cupsGetErrorString());
1934
0
  http->error  = errno = EINVAL;
1935
0
  http->status = HTTP_STATUS_ERROR;
1936
0
  SSL_CTX_free(context);
1937
0
        cupsMutexUnlock(&tls_mutex);
1938
1939
0
  return (false);
1940
0
      }
1941
0
    }
1942
1943
0
    cupsMutexUnlock(&tls_mutex);
1944
1945
0
    DEBUG_printf("4_httpTLSStart: Using private key file '%s'.", keyfile);
1946
0
    DEBUG_printf("4_httpTLSStart: Using certificate file '%s'.", crtfile);
1947
1948
0
    if (!SSL_CTX_use_PrivateKey_file(context, keyfile, SSL_FILETYPE_PEM) || !SSL_CTX_use_certificate_chain_file(context, crtfile))
1949
0
    {
1950
      // Unable to load private key or certificate...
1951
0
      DEBUG_puts("4_httpTLSStart: Unable to use private key or certificate chain file.");
1952
0
      if ((error = ERR_get_error()) != 0)
1953
0
        _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, ERR_error_string(error, NULL), 0);
1954
1955
0
      http->status = HTTP_STATUS_ERROR;
1956
0
      http->error  = EIO;
1957
1958
0
      SSL_CTX_free(context);
1959
1960
0
      return (false);
1961
0
    }
1962
0
  }
1963
1964
  // Set TLS options...
1965
9
  cupsCopyString(cipherlist, "HIGH:!DH:+DHE", sizeof(cipherlist));
1966
9
  if ((tls_options & _HTTP_TLS_ALLOW_RC4) && http->mode == _HTTP_MODE_CLIENT)
1967
0
    cupsConcatString(cipherlist, ":+RC4", sizeof(cipherlist));
1968
9
  else
1969
9
    cupsConcatString(cipherlist, ":!RC4", sizeof(cipherlist));
1970
9
  if (tls_options & _HTTP_TLS_DENY_CBC)
1971
0
    cupsConcatString(cipherlist, ":!SHA1:!SHA256:!SHA384", sizeof(cipherlist));
1972
9
  cupsConcatString(cipherlist, ":@STRENGTH", sizeof(cipherlist));
1973
1974
9
  DEBUG_printf("4_httpTLSStart: cipherlist='%s', tls_min_version=%d, tls_max_version=%d", cipherlist, tls_min_version, tls_max_version);
1975
1976
9
  SSL_CTX_set_min_proto_version(context, versions[tls_min_version]);
1977
9
  SSL_CTX_set_max_proto_version(context, versions[tls_max_version]);
1978
9
  SSL_CTX_set_cipher_list(context, cipherlist);
1979
1980
  // Setup a TLS session
1981
9
  cupsMutexLock(&tls_mutex);
1982
9
  if (!tls_bio_method)
1983
1
  {
1984
1
    tls_bio_method = BIO_meth_new(BIO_get_new_index(), "http");
1985
1
    BIO_meth_set_ctrl(tls_bio_method, http_bio_ctrl);
1986
1
    BIO_meth_set_create(tls_bio_method, http_bio_new);
1987
1
    BIO_meth_set_destroy(tls_bio_method, http_bio_free);
1988
1
    BIO_meth_set_read(tls_bio_method, http_bio_read);
1989
1
    BIO_meth_set_puts(tls_bio_method, http_bio_puts);
1990
1
    BIO_meth_set_write(tls_bio_method, http_bio_write);
1991
1
  }
1992
1993
9
  bio = BIO_new(tls_bio_method);
1994
9
  cupsMutexUnlock(&tls_mutex);
1995
1996
9
  BIO_ctrl(bio, BIO_C_SET_FILE_PTR, 0, (char *)http);
1997
1998
9
  http->tls = SSL_new(context);
1999
9
  SSL_set_bio(http->tls, bio, bio);
2000
2001
9
  if (http->mode == _HTTP_MODE_CLIENT)
2002
9
  {
2003
    // Negotiate as a client...
2004
9
    DEBUG_printf("4_httpTLSStart: Setting server name TLS extension to '%s'...", http->hostname);
2005
9
    SSL_set_tlsext_host_name(http->tls, http->hostname);
2006
2007
9
    DEBUG_puts("4_httpTLSStart: Calling SSL_connect...");
2008
9
    if (SSL_connect(http->tls) < 1)
2009
9
    {
2010
      // Failed
2011
9
      if ((error = ERR_get_error()) != 0)
2012
4
        _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, ERR_error_string(error, NULL), 0);
2013
2014
9
      http->status = HTTP_STATUS_ERROR;
2015
9
      http->error  = EPIPE;
2016
2017
9
      SSL_CTX_free(context);
2018
2019
9
      SSL_free(http->tls);
2020
9
      http->tls = NULL;
2021
2022
9
      DEBUG_printf("4_httpTLSStart: Returning false (%s)", ERR_error_string(error, NULL));
2023
2024
9
      return (false);
2025
9
    }
2026
9
  }
2027
0
  else
2028
0
  {
2029
    // Negotiate as a server...
2030
0
    DEBUG_puts("4_httpTLSStart: Calling SSL_accept...");
2031
0
    if (SSL_accept(http->tls) < 1)
2032
0
    {
2033
      // Failed
2034
0
      if ((error = ERR_get_error()) != 0)
2035
0
        _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, ERR_error_string(error, NULL), 0);
2036
2037
0
      http->status = HTTP_STATUS_ERROR;
2038
0
      http->error  = EPIPE;
2039
2040
0
      SSL_CTX_free(context);
2041
2042
0
      SSL_free(http->tls);
2043
0
      http->tls = NULL;
2044
2045
0
      DEBUG_printf("4_httpTLSStart: Returning false (%s)", ERR_error_string(error, NULL));
2046
2047
0
      return (false);
2048
0
    }
2049
0
  }
2050
2051
0
  DEBUG_puts("4_httpTLSStart: Returning true.");
2052
2053
0
  return (true);
2054
9
}
2055
2056
2057
//
2058
// '_httpTLSStop()' - Shut down SSL/TLS on a connection.
2059
//
2060
2061
void
2062
_httpTLSStop(http_t *http)    // I - Connection to server
2063
0
{
2064
0
  SSL_CTX *context;   // Context for encryption
2065
2066
2067
0
  context = SSL_get_SSL_CTX(http->tls);
2068
2069
0
  SSL_shutdown(http->tls);
2070
0
  SSL_CTX_free(context);
2071
0
  SSL_free(http->tls);
2072
2073
0
  http->tls = NULL;
2074
0
}
2075
2076
2077
//
2078
// '_httpTLSWrite()' - Write to a SSL/TLS connection.
2079
//
2080
2081
int         // O - Bytes written
2082
_httpTLSWrite(http_t     *http,   // I - Connection to server
2083
        const char *buf,    // I - Buffer holding data
2084
        int        len)   // I - Length of buffer
2085
0
{
2086
0
  int bytes = SSL_write(http->tls, buf, len);
2087
          // Bytes written
2088
2089
0
  DEBUG_printf("7_httpTLSWrite(http=%p, buf=%p, len=%d) got %d", (void *)http, (void *)buf, len, bytes);
2090
2091
0
  if (bytes > 0)
2092
0
    return (bytes);
2093
2094
  // For now, make difference only for error after which we can retry, EPIPE otherwise...
2095
0
  if (SSL_get_error(http->tls, bytes) == SSL_ERROR_WANT_WRITE)
2096
0
    errno = EAGAIN;
2097
0
  else
2098
0
    errno = EPIPE;
2099
2100
0
  return (-1);
2101
0
}
2102
2103
2104
//
2105
// '_httpUseCredentials()' - Increment the use count for internal credentials.
2106
//
2107
2108
_http_tls_credentials_t *   // O - Internal credentials
2109
_httpUseCredentials(
2110
    _http_tls_credentials_t *hcreds)  // I - Internal credentials
2111
5.72k
{
2112
5.72k
  if (hcreds)
2113
0
    hcreds->use ++;
2114
2115
5.72k
  return (hcreds);
2116
5.72k
}
2117
2118
2119
//
2120
// 'http_bio_ctrl()' - Control the HTTP connection.
2121
//
2122
2123
static long       // O - Result/data
2124
http_bio_ctrl(BIO  *h,      // I - BIO data
2125
              int  cmd,     // I - Control command
2126
        long arg1,    // I - First argument
2127
        void *arg2)   // I - Second argument
2128
157
{
2129
157
  DEBUG_printf("8http_bio_ctl(h=%p, cmd=%d, arg1=%ld, arg2=%p)", (void *)h, cmd, arg1, arg2);
2130
2131
157
  (void)arg1;
2132
2133
157
  switch (cmd)
2134
157
  {
2135
137
    default :
2136
137
        return (0);
2137
2138
0
    case BIO_CTRL_RESET :
2139
0
        BIO_set_data(h, NULL);
2140
0
  return (0);
2141
2142
9
    case BIO_C_SET_FILE_PTR :
2143
9
        BIO_set_data(h, arg2);
2144
9
        BIO_set_init(h, 1);
2145
9
  return (1);
2146
2147
0
    case BIO_C_GET_FILE_PTR :
2148
0
        if (arg2)
2149
0
  {
2150
0
    *((void **)arg2) = BIO_get_data(h);
2151
0
    return (1);
2152
0
  }
2153
0
  else
2154
0
    return (0);
2155
2156
0
    case BIO_CTRL_DUP :
2157
11
    case BIO_CTRL_FLUSH :
2158
11
        return (1);
2159
157
  }
2160
157
}
2161
2162
2163
//
2164
// 'http_bio_free()' - Free OpenSSL data.
2165
//
2166
2167
static int        // O - 1 on success, 0 on failure
2168
http_bio_free(BIO *h)     // I - BIO data
2169
9
{
2170
9
  DEBUG_printf("8http_bio_free(h=%p)", (void *)h);
2171
2172
9
  if (!h)
2173
0
    return (0);
2174
2175
9
  if (BIO_get_shutdown(h))
2176
9
    BIO_set_init(h, 0);
2177
2178
9
  return (1);
2179
9
}
2180
2181
2182
//
2183
// 'http_bio_new()' - Initialize an OpenSSL BIO structure.
2184
//
2185
2186
static int        // O - 1 on success, 0 on failure
2187
http_bio_new(BIO *h)      // I - BIO data
2188
9
{
2189
9
  DEBUG_printf("8http_bio_new(h=%p)", (void *)h);
2190
2191
9
  if (!h)
2192
0
    return (0);
2193
2194
9
  BIO_set_init(h, 0);
2195
9
  BIO_set_data(h, NULL);
2196
2197
9
  return (1);
2198
9
}
2199
2200
2201
//
2202
// 'http_bio_puts()' - Send a string for OpenSSL.
2203
//
2204
2205
static int        // O - Bytes written
2206
http_bio_puts(BIO        *h,    // I - BIO data
2207
              const char *str)    // I - String to write
2208
0
{
2209
0
  DEBUG_printf("8http_bio_puts(h=%p, str=\"%s\")", (void *)h, str);
2210
2211
#ifdef WIN32
2212
  return (send(((http_t *)BIO_get_data(h))->fd, str, (int)strlen(str), 0));
2213
#else
2214
0
  return ((int)send(((http_t *)BIO_get_data(h))->fd, str, strlen(str), 0));
2215
0
#endif // WIN32
2216
0
}
2217
2218
2219
//
2220
// 'http_bio_read()' - Read data for OpenSSL.
2221
//
2222
2223
static int        // O - Bytes read
2224
http_bio_read(BIO  *h,      // I - BIO data
2225
              char *buf,    // I - Buffer
2226
        int  size)    // I - Number of bytes to read
2227
12
{
2228
12
  http_t  *http;      // HTTP connection
2229
12
  int   bytes;      // Bytes read
2230
2231
2232
12
  DEBUG_printf("8http_bio_read(h=%p, buf=%p, size=%d)", (void *)h, (void *)buf, size);
2233
2234
12
  http = (http_t *)BIO_get_data(h);
2235
12
  DEBUG_printf("9http_bio_read: http=%p", (void *)http);
2236
2237
12
  if (!http->blocking || http->timeout_value > 0.0)
2238
0
  {
2239
    // Make sure we have data before we read...
2240
0
    while (!_httpWait(http, http->wait_value, false))
2241
0
    {
2242
0
      if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
2243
0
  continue;
2244
2245
#ifdef WIN32
2246
      http->error = WSAETIMEDOUT;
2247
#else
2248
0
      http->error = ETIMEDOUT;
2249
0
#endif // WIN32
2250
2251
0
      DEBUG_puts("9http_bio_read: Timeout, returning -1.");
2252
0
      return (-1);
2253
0
    }
2254
0
  }
2255
2256
12
  bytes = (int)recv(http->fd, buf, (size_t)size, 0);
2257
12
  DEBUG_printf("9http_bio_read: Returning %d.", bytes);
2258
2259
12
  return (bytes);
2260
12
}
2261
2262
2263
//
2264
// 'http_bio_write()' - Write data for OpenSSL.
2265
//
2266
2267
static int        // O - Bytes written
2268
http_bio_write(BIO        *h,   // I - BIO data
2269
               const char *buf,   // I - Buffer to write
2270
         int        num)    // I - Number of bytes to write
2271
11
{
2272
11
  int bytes;        // Bytes written
2273
2274
2275
11
  DEBUG_printf("8http_bio_write(h=%p, buf=%p, num=%d)", (void *)h, (void *)buf, num);
2276
2277
11
  bytes = (int)send(((http_t *)BIO_get_data(h))->fd, buf, (size_t)num, 0);
2278
2279
11
  DEBUG_printf("9http_bio_write: Returning %d.", bytes);
2280
11
  return (bytes);
2281
11
}
2282
2283
2284
//
2285
// 'openssl_add_ext()' - Add an extension.
2286
//
2287
2288
static bool       // O - `true` on success, `false` on error
2289
openssl_add_ext(
2290
    STACK_OF(X509_EXTENSION) *exts, // I - Stack of extensions
2291
    int                      nid, // I - Extension ID
2292
    const char               *value)  // I - Value
2293
0
{
2294
0
  X509_EXTENSION *ext = NULL;   // Extension
2295
2296
2297
0
  DEBUG_printf("3openssl_add_ext(exts=%p, nid=%d, value=\"%s\")", (void *)exts, nid, value);
2298
2299
  // Create and add the extension...
2300
0
  if ((ext = X509V3_EXT_conf_nid(/*conf*/NULL, /*ctx*/NULL, nid, value)) == NULL)
2301
0
  {
2302
0
    DEBUG_puts("4openssl_add_ext: Unable to create extension, returning false.");
2303
0
    return (false);
2304
0
  }
2305
2306
0
  sk_X509_EXTENSION_push(exts, ext);
2307
2308
0
  return (true);
2309
0
}
2310
2311
2312
//
2313
// 'openssl_create_key()' - Create a suitable key pair for a certificate/signing request.
2314
//
2315
2316
static EVP_PKEY *     // O - Key pair
2317
openssl_create_key(
2318
    cups_credtype_t type)   // I - Type of key
2319
0
{
2320
0
  EVP_PKEY  *pkey;      // Key pair
2321
0
  EVP_PKEY_CTX  *ctx;     // Key generation context
2322
0
  int   algid;      // Algorithm NID
2323
0
  int   bits = 0;   // Bits
2324
0
  int   curveid = 0;    // Curve NID
2325
2326
2327
0
  switch (type)
2328
0
  {
2329
0
    case CUPS_CREDTYPE_ECDSA_P256_SHA256 :
2330
0
        algid   = EVP_PKEY_EC;
2331
0
        curveid = NID_X9_62_prime256v1;
2332
0
  break;
2333
2334
0
    case CUPS_CREDTYPE_ECDSA_P384_SHA256 :
2335
0
        algid   = EVP_PKEY_EC;
2336
0
        curveid = NID_secp384r1;
2337
0
  break;
2338
2339
0
    case CUPS_CREDTYPE_ECDSA_P521_SHA256 :
2340
0
        algid   = EVP_PKEY_EC;
2341
0
        curveid = NID_secp521r1;
2342
0
  break;
2343
2344
0
    case CUPS_CREDTYPE_RSA_2048_SHA256 :
2345
0
        algid = EVP_PKEY_RSA;
2346
0
        bits  = 2048;
2347
0
  break;
2348
2349
0
    default :
2350
0
    case CUPS_CREDTYPE_RSA_3072_SHA256 :
2351
0
        algid = EVP_PKEY_RSA;
2352
0
        bits  = 3072;
2353
0
  break;
2354
2355
0
    case CUPS_CREDTYPE_RSA_4096_SHA256 :
2356
0
        algid = EVP_PKEY_RSA;
2357
0
        bits  = 4096;
2358
0
  break;
2359
0
  }
2360
2361
0
  pkey = NULL;
2362
2363
0
  if ((ctx = EVP_PKEY_CTX_new_id(algid, NULL)) == NULL)
2364
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to create private key context."), true);
2365
0
  else if (EVP_PKEY_keygen_init(ctx) <= 0)
2366
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to initialize private key context."), true);
2367
0
  else if (bits && EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, bits) <= 0)
2368
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to configure private key context."), true);
2369
0
  else if (curveid && EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx, curveid) <= 0)
2370
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to configure private key context."), true);
2371
0
  else if (EVP_PKEY_keygen(ctx, &pkey) <= 0)
2372
0
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to create private key."), true);
2373
2374
0
  EVP_PKEY_CTX_free(ctx);
2375
2376
0
  return (pkey);
2377
0
}
2378
2379
2380
//
2381
// 'openssl_create_name()' - Create an X.509 name value for a certificate/signing request.
2382
//
2383
2384
static X509_NAME *      // O - X.509 name value
2385
openssl_create_name(
2386
    const char      *organization,  // I - Organization or `NULL` to use common name
2387
    const char      *org_unit,    // I - Organizational unit or `NULL` for none
2388
    const char      *locality,    // I - City/town or `NULL` for "Unknown"
2389
    const char      *state_province,  // I - State/province or `NULL` for "Unknown"
2390
    const char      *country,   // I - Country or `NULL` for locale-based default
2391
    const char      *common_name, // I - Common name
2392
    const char      *email)   // I - Email address or `NULL` for none
2393
0
{
2394
0
  X509_NAME *name;      // Subject/issuer name
2395
0
  cups_lang_t *language;    // Default language info
2396
0
  const char  *langname;    // Language name
2397
2398
2399
0
  language = cupsLangDefault();
2400
0
  langname = cupsLangGetName(language);
2401
0
  name     = X509_NAME_new();
2402
0
  if (country)
2403
0
    X509_NAME_add_entry_by_txt(name, SN_countryName, MBSTRING_ASC, (unsigned char *)country, -1, -1, 0);
2404
0
  else if (strlen(langname) == 5)
2405
0
    X509_NAME_add_entry_by_txt(name, SN_countryName, MBSTRING_ASC, (unsigned char *)langname + 3, -1, -1, 0);
2406
0
  else
2407
0
    X509_NAME_add_entry_by_txt(name, SN_countryName, MBSTRING_ASC, (unsigned char *)"US", -1, -1, 0);
2408
0
  X509_NAME_add_entry_by_txt(name, SN_commonName, MBSTRING_ASC, (unsigned char *)common_name, -1, -1, 0);
2409
0
  X509_NAME_add_entry_by_txt(name, SN_organizationName, MBSTRING_ASC, (unsigned char *)(organization ? organization : common_name), -1, -1, 0);
2410
0
  X509_NAME_add_entry_by_txt(name, SN_organizationalUnitName, MBSTRING_ASC, (unsigned char *)(org_unit ? org_unit : ""), -1, -1, 0);
2411
0
  X509_NAME_add_entry_by_txt(name, SN_stateOrProvinceName, MBSTRING_ASC, (unsigned char *)(state_province ? state_province : "Unknown"), -1, -1, 0);
2412
0
  X509_NAME_add_entry_by_txt(name, SN_localityName, MBSTRING_ASC, (unsigned char *)(locality ? locality : "Unknown"), -1, -1, 0);
2413
0
  if (email && *email)
2414
0
    X509_NAME_add_entry_by_txt(name, "emailAddress", MBSTRING_ASC, (unsigned char *)email, -1, -1, 0);
2415
2416
0
  return (name);
2417
0
}
2418
2419
2420
//
2421
// 'openssl_create_san()' - Create a list of subjectAltName values for a certificate/signing request.
2422
//
2423
2424
static X509_EXTENSION *     // O - Extension
2425
openssl_create_san(
2426
    const char         *common_name,  // I - Common name
2427
    size_t             num_alt_names, // I - Number of alternate names
2428
    const char * const *alt_names)  // I - List of alternate names
2429
0
{
2430
0
  char    temp[2048],   // Temporary string
2431
0
    *tempptr;   // Pointer into temporary string
2432
0
  size_t  i;      // Looping var
2433
2434
2435
  // Add the common name
2436
0
  snprintf(temp, sizeof(temp), "DNS:%s", common_name);
2437
0
  tempptr = temp + strlen(temp);
2438
2439
0
  if (strstr(common_name, ".local") == NULL)
2440
0
  {
2441
    // Add common_name.local to the list, too...
2442
0
    char  localname[256],   // hostname.local
2443
0
    *localptr;    // Pointer into localname
2444
2445
0
    cupsCopyString(localname, common_name, sizeof(localname));
2446
0
    if ((localptr = (char *)strchr(localname, '.')) != NULL)
2447
0
      *localptr = '\0';
2448
2449
0
    snprintf(tempptr, sizeof(temp) - (size_t)(tempptr - temp), ",DNS:%s.local", localname);
2450
0
    tempptr += strlen(tempptr);
2451
0
  }
2452
2453
  // Add any alternate names...
2454
0
  for (i = 0; i < num_alt_names; i ++)
2455
0
  {
2456
0
    if (strcmp(alt_names[i], "localhost"))
2457
0
    {
2458
0
      snprintf(tempptr, sizeof(temp) - (size_t)(tempptr - temp), ",DNS:%s", alt_names[i]);
2459
0
      tempptr += strlen(tempptr);
2460
0
    }
2461
0
  }
2462
2463
  // Return the stack
2464
0
  return (X509V3_EXT_conf_nid(/*conf*/NULL, /*ctx*/NULL, NID_subject_alt_name, temp));
2465
0
}
2466
2467
2468
//
2469
// 'openssl_get_date()' - Get the notBefore or notAfter date of a certificate.
2470
//
2471
2472
static time_t       // O - UNIX time in seconds
2473
openssl_get_date(X509 *cert,    // I - Certificate
2474
                 int  which)    // I - 0 for notBefore, 1 for notAfter
2475
0
{
2476
0
  struct tm exptm;      // Expiration date components
2477
2478
2479
0
  if (which)
2480
0
    ASN1_TIME_to_tm(X509_get0_notAfter(cert), &exptm);
2481
0
  else
2482
0
    ASN1_TIME_to_tm(X509_get0_notBefore(cert), &exptm);
2483
2484
0
  return (mktime(&exptm));
2485
0
}
2486
2487
2488
//
2489
// 'openssl_load_x509()' - Load a stack of X.509 certificates.
2490
//
2491
2492
static STACK_OF(X509) *     // O - Stack of X.509 certificates
2493
openssl_load_x509(
2494
    const char *credentials)    // I - Credentials string
2495
0
{
2496
0
  STACK_OF(X509)  *certs = NULL; // Certificate chain
2497
0
  X509      *cert = NULL; // Current certificate
2498
0
  BIO     *bio;   // Basic I/O for string
2499
2500
2501
  // Range check input...
2502
0
  DEBUG_printf("4openssl_load_x509(credentials=\"%s\")", credentials);
2503
0
  if (!credentials || !*credentials)
2504
0
    return (NULL);
2505
2506
  // Make a BIO memory buffer for the string...
2507
0
  if ((bio = BIO_new_mem_buf(credentials, strlen(credentials))) == NULL)
2508
0
    return (NULL);
2509
2510
  // Read all the X509 certificates from the string...
2511
0
  while (PEM_read_bio_X509(bio, &cert, NULL, (void *)""))
2512
0
  {
2513
0
    if (!certs)
2514
0
    {
2515
      // Make a new stack of X509 certs...
2516
0
      certs = sk_X509_new_null();
2517
0
    }
2518
2519
0
    if (certs)
2520
0
    {
2521
      // Add the X509 certificate...
2522
0
      sk_X509_push(certs, cert);
2523
0
    }
2524
0
    else
2525
0
    {
2526
      // Unable to add, free and stop...
2527
0
      X509_free(cert);
2528
0
      break;
2529
0
    }
2530
2531
0
    cert = NULL;
2532
0
  }
2533
2534
0
  BIO_free(bio);
2535
2536
0
  return (certs);
2537
0
}
2538
2539
2540
//
2541
// 'openssl_open_file()' - Create a file for writing with the given permissions.
2542
//
2543
2544
static BIO *        // O - File BIO or `NULL` on error
2545
openssl_open_file(const char *filename, // I - Filename
2546
                  int        mode)  // I - Permissions
2547
0
{
2548
0
  int fd;       // File descriptor
2549
0
  BIO *bio;       // File BIO
2550
2551
2552
0
  if ((fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, mode)) < 0)
2553
0
    return (NULL);
2554
2555
0
  if ((bio = BIO_new_fd(fd, BIO_CLOSE)) == NULL)
2556
0
    close(fd);
2557
2558
0
  return (bio);
2559
0
}
2560
2561
2562
//
2563
// 'openssl_validate_name()' - Check that the certificate is valid for the given name.
2564
//
2565
2566
static bool       // O - `true` if valid, `false` otherwise
2567
openssl_validate_name(
2568
    X509       *cert,     // I - Certificate
2569
    const char *common_name)    // I - Common name
2570
0
{
2571
0
  bool    result = false;    // Return value
2572
0
  char    subjectName[256]; // Common name from certificate
2573
0
  STACK_OF(GENERAL_NAME) *names = NULL;
2574
          // subjectAltName values
2575
2576
2577
0
  if (X509_NAME_get_text_by_NID(X509_get_subject_name(cert), NID_commonName, subjectName, sizeof(subjectName)) < 0)
2578
0
    cupsCopyString(subjectName, "unknown", sizeof(subjectName));
2579
2580
0
  DEBUG_printf("1openssl_validate_name: subjectName=\"%s\"", subjectName);
2581
2582
0
  if (!_cups_strcasecmp(common_name, subjectName))
2583
0
  {
2584
0
    DEBUG_puts("1openssl_validate_name: Match.");
2585
0
    return (true);
2586
0
  }
2587
2588
0
  if ((names = X509_get_ext_d2i(cert, NID_subject_alt_name, /*crit*/NULL, /*idx*/NULL)) != NULL)
2589
0
  {
2590
    // Got subjectAltName values, look at them...
2591
0
    int i,        // Looping var
2592
0
  count;        // Number of values
2593
2594
0
    DEBUG_printf("1openssl_validate_name: names=%p", names);
2595
0
    for (i = 0, count = sk_GENERAL_NAME_num(names); i < count && !result; i ++)
2596
0
    {
2597
0
      const GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
2598
          // subjectAltName value
2599
2600
0
      if (!name)
2601
0
  continue;
2602
2603
0
      DEBUG_printf("1openssl_validate_name: subjectAltName[%d/%d].type=%d", i + 1, count, name->type);
2604
0
      if (name->type == GEN_DNS)
2605
0
      {
2606
  // Match a DNS name...
2607
0
  char  *dNSName;   // DNS name value
2608
0
  int dNSNameLen;   // Length of DNS name value
2609
2610
0
  if ((dNSNameLen = ASN1_STRING_to_UTF8((unsigned char **)&dNSName, name->d.dNSName)) > 0)
2611
0
  {
2612
    // Only trust this value if its declared length matches a C
2613
    // string's length - a mismatch means the certificate's SAN
2614
    // contains an embedded NUL byte, which could otherwise be used
2615
    // to spoof a match against a prefix of the real value...
2616
0
    if ((size_t)dNSNameLen == strlen(dNSName))
2617
0
    {
2618
0
      DEBUG_printf("1openssl_validate_name: subjectAltName[%d/%d].dNSName=\"%s\"", i + 1, count, dNSName);
2619
2620
0
      if (!_cups_strcasecmp(common_name, dNSName))
2621
0
      {
2622
        // Direct name match...
2623
0
        DEBUG_puts("1openssl_validate_name: Match.");
2624
0
        result = true;
2625
0
      }
2626
0
      else if (!strncmp(dNSName, "*.", 2))
2627
0
      {
2628
        // Compare wildcard...
2629
0
        const char *domain_name = strchr(common_name, '.');
2630
          // Domain name of common name
2631
2632
0
        if (domain_name && !_cups_strcasecmp(domain_name, dNSName + 1))
2633
0
        {
2634
0
    DEBUG_puts("1openssl_validate_name: Match.");
2635
0
    result = true;
2636
0
        }
2637
0
      }
2638
0
    }
2639
2640
0
    OPENSSL_free(dNSName);
2641
0
  }
2642
0
      }
2643
0
    }
2644
2645
0
    GENERAL_NAMES_free(names);
2646
0
  }
2647
2648
0
  return (result);
2649
0
}
2650
2651
2652
//
2653
// 'openssl_verify_cb()' - Handle verification issues...
2654
//
2655
2656
static int        // O - 1 to continue, 0 to stop
2657
openssl_verify_cb(int            ok,  // I - Default return value
2658
                  X509_STORE_CTX *ctx)  // I - Verification context
2659
0
{
2660
0
  DEBUG_printf("4openssl_verify_cb(ok=%d, ctx=%p), error=%d (%s)", ok, (void *)ctx, X509_STORE_CTX_get_error(ctx), X509_verify_cert_error_string(X509_STORE_CTX_get_error(ctx)));
2661
2662
0
  if (!ok && X509_STORE_CTX_get_error(ctx) == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
2663
0
  {
2664
    // See if the issuer is "_site_"...
2665
    // TODO: Spend more time figuring out why OpenSSL can't find a "_site_" cert in the X509_STORE
2666
0
    X509  *cert = X509_STORE_CTX_get_current_cert(ctx);
2667
          // Problematic certificate
2668
0
    char  issuer[256];    // Issuer name
2669
2670
0
    DEBUG_printf("5openssl_verify_cb: Unable to get local issuer for certificate '%s'.", X509_NAME_oneline(X509_get_subject_name(cert), issuer, (int)sizeof(issuer)));
2671
0
    DEBUG_printf("5openssl_verify_cb: Issuer identified as '%s'.", X509_NAME_oneline(X509_get_issuer_name(cert), issuer, (int)sizeof(issuer)));
2672
2673
0
    if (X509_NAME_get_text_by_NID(X509_get_issuer_name(cert), NID_commonName, issuer, sizeof(issuer)) >= 0 && !strcmp(issuer, "_site_"))
2674
0
    {
2675
      // Yes, verify that this certificate was signed by the site certificate...
2676
0
      X509  *sitecert = (X509 *)X509_STORE_CTX_get_ex_data(ctx, 0);
2677
          // Site certificate
2678
0
      EVP_PKEY  *sitekey;   // Public key for the site cert
2679
2680
0
      DEBUG_puts("5openssl_verify_cb: Issuer is '_site_'.");
2681
2682
0
      if (sitecert && (sitekey = X509_get_pubkey(sitecert)) != NULL)
2683
0
      {
2684
0
  if (X509_verify(cert, sitekey) == 1)
2685
0
  {
2686
    // Yes, signature matches...
2687
0
    DEBUG_puts("5openssl_verify_cb: Verified signature against local site certificate, OK.");
2688
0
    ok = 1;
2689
0
  }
2690
2691
0
  EVP_PKEY_free(sitekey);
2692
0
      }
2693
0
    }
2694
0
  }
2695
2696
0
  return (ok);
2697
0
}