]> git.ipfire.org Git - thirdparty/cups.git/blame - cups/tls-gnutls.c
Support AddressSanitizer in builds.
[thirdparty/cups.git] / cups / tls-gnutls.c
CommitLineData
2c85b752 1/*
2c85b752
MS
2 * TLS support code for CUPS using GNU TLS.
3 *
a7aabde8
MS
4 * Copyright © 2007-2018 by Apple Inc.
5 * Copyright © 1997-2007 by Easy Software Products, all rights reserved.
2c85b752 6 *
ff82ce17
MS
7 * Licensed under Apache License v2.0. See the file "LICENSE" for more
8 * information.
2c85b752
MS
9 */
10
ebb24a07 11/**** This file is included from tls.c ****/
2c85b752 12
d0facf48
MS
13/*
14 * Include necessary headers...
15 */
16
17#include <sys/stat.h>
18
19
07623986
MS
20/*
21 * Local globals...
22 */
23
24static int tls_auto_create = 0;
25 /* Auto-create self-signed certs? */
26static char *tls_common_name = NULL;
27 /* Default common name */
08d56b1f 28static gnutls_x509_crl_t tls_crl = NULL;/* Certificate revocation list */
07623986
MS
29static char *tls_keypath = NULL;
30 /* Server cert keychain path */
31static _cups_mutex_t tls_mutex = _CUPS_MUTEX_INITIALIZER;
32 /* Mutex for keychain/certs */
8f1fbdec
MS
33static int tls_options = -1,/* Options for TLS connections */
34 tls_min_version = _HTTP_TLS_1_0,
35 tls_max_version = _HTTP_TLS_MAX;
07623986
MS
36
37
2c85b752
MS
38/*
39 * Local functions...
40 */
41
ff82e169 42static gnutls_x509_crt_t http_gnutls_create_credential(http_credential_t *credential);
d0facf48 43static const char *http_gnutls_default_path(char *buffer, size_t bufsize);
08d56b1f 44static void http_gnutls_load_crl(void);
a2751f30 45static const char *http_gnutls_make_path(char *buffer, size_t bufsize, const char *dirname, const char *filename, const char *ext);
d0facf48
MS
46static ssize_t http_gnutls_read(gnutls_transport_ptr_t ptr, void *data, size_t length);
47static ssize_t http_gnutls_write(gnutls_transport_ptr_t ptr, const void *data, size_t length);
dd332638
MS
48
49
07623986
MS
50/*
51 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
52 *
e1f19878 53 * @since CUPS 2.0/OS 10.10@
07623986
MS
54 */
55
56int /* O - 1 on success, 0 on failure */
57cupsMakeServerCredentials(
58 const char *path, /* I - Path to keychain/directory */
59 const char *common_name, /* I - Common name */
60 int num_alt_names, /* I - Number of subject alternate names */
61 const char **alt_names, /* I - Subject Alternate Names */
62 time_t expiration_date) /* I - Expiration date */
63{
f394e0f7
MS
64 gnutls_x509_crt_t crt; /* Self-signed certificate */
65 gnutls_x509_privkey_t key; /* Encryption private key */
66 char temp[1024], /* Temporary directory name */
67 crtfile[1024], /* Certificate filename */
172bdf5d
MS
68 keyfile[1024]; /* Private key filename */
69 cups_lang_t *language; /* Default language info */
70 cups_file_t *fp; /* Key/cert file */
71 unsigned char buffer[8192]; /* Buffer for x509 data */
72 size_t bytes; /* Number of bytes of data */
73 unsigned char serial[4]; /* Serial number buffer */
74 time_t curtime; /* Current time */
75 int result; /* Result of GNU TLS calls */
07623986 76
172bdf5d
MS
77
78 DEBUG_printf(("cupsMakeServerCredentials(path=\"%s\", common_name=\"%s\", num_alt_names=%d, alt_names=%p, expiration_date=%d)", path, common_name, num_alt_names, alt_names, (int)expiration_date));
79
80 /*
81 * Filenames...
82 */
83
84 if (!path)
d0facf48 85 path = http_gnutls_default_path(temp, sizeof(temp));
172bdf5d 86
d0facf48
MS
87 if (!path || !common_name)
88 {
89 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
90 return (0);
172bdf5d 91 }
26435c51
MS
92
93 http_gnutls_make_path(crtfile, sizeof(crtfile), path, common_name, "crt");
94 http_gnutls_make_path(keyfile, sizeof(keyfile), path, common_name, "key");
172bdf5d
MS
95
96 /*
97 * Create the encryption key...
98 */
99
d0facf48
MS
100 DEBUG_puts("1cupsMakeServerCredentials: Creating key pair.");
101
172bdf5d
MS
102 gnutls_x509_privkey_init(&key);
103 gnutls_x509_privkey_generate(key, GNUTLS_PK_RSA, 2048, 0);
104
d0facf48
MS
105 DEBUG_puts("1cupsMakeServerCredentials: Key pair created.");
106
172bdf5d
MS
107 /*
108 * Save it...
109 */
110
111 bytes = sizeof(buffer);
112
d0facf48 113 if ((result = gnutls_x509_privkey_export(key, GNUTLS_X509_FMT_PEM, buffer, &bytes)) < 0)
172bdf5d 114 {
d0facf48 115 DEBUG_printf(("1cupsMakeServerCredentials: Unable to export private key: %s", gnutls_strerror(result)));
172bdf5d
MS
116 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, gnutls_strerror(result), 0);
117 gnutls_x509_privkey_deinit(key);
118 return (0);
119 }
120 else if ((fp = cupsFileOpen(keyfile, "w")) != NULL)
121 {
d0facf48 122 DEBUG_printf(("1cupsMakeServerCredentials: Writing private key to \"%s\".", keyfile));
172bdf5d
MS
123 cupsFileWrite(fp, (char *)buffer, bytes);
124 cupsFileClose(fp);
125 }
126 else
127 {
d0facf48 128 DEBUG_printf(("1cupsMakeServerCredentials: Unable to create private key file \"%s\": %s", keyfile, strerror(errno)));
172bdf5d
MS
129 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
130 gnutls_x509_privkey_deinit(key);
131 return (0);
132 }
133
134 /*
135 * Create the self-signed certificate...
136 */
137
d0facf48 138 DEBUG_puts("1cupsMakeServerCredentials: Generating self-signed X.509 certificate.");
172bdf5d
MS
139
140 language = cupsLangDefault();
141 curtime = time(NULL);
142 serial[0] = curtime >> 24;
143 serial[1] = curtime >> 16;
144 serial[2] = curtime >> 8;
145 serial[3] = curtime;
146
147 gnutls_x509_crt_init(&crt);
148 if (strlen(language->language) == 5)
149 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
150 language->language + 3, 2);
151 else
152 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
153 "US", 2);
154 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COMMON_NAME, 0,
155 common_name, strlen(common_name));
156 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATION_NAME, 0,
157 common_name, strlen(common_name));
158 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME,
159 0, "Unknown", 7);
160 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME, 0,
161 "Unknown", 7);
162 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_LOCALITY_NAME, 0,
163 "Unknown", 7);
164/* gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_PKCS9_EMAIL, 0,
165 ServerAdmin, strlen(ServerAdmin));*/
166 gnutls_x509_crt_set_key(crt, key);
167 gnutls_x509_crt_set_serial(crt, serial, sizeof(serial));
168 gnutls_x509_crt_set_activation_time(crt, curtime);
169 gnutls_x509_crt_set_expiration_time(crt, curtime + 10 * 365 * 86400);
170 gnutls_x509_crt_set_ca_status(crt, 0);
171 if (num_alt_names > 0)
172 gnutls_x509_crt_set_subject_alternative_name(crt, GNUTLS_SAN_DNSNAME, alt_names[0]);
173 gnutls_x509_crt_set_key_purpose_oid(crt, GNUTLS_KP_TLS_WWW_SERVER, 0);
174 gnutls_x509_crt_set_key_usage(crt, GNUTLS_KEY_KEY_ENCIPHERMENT);
175 gnutls_x509_crt_set_version(crt, 3);
176
177 bytes = sizeof(buffer);
178 if (gnutls_x509_crt_get_key_id(crt, 0, buffer, &bytes) >= 0)
179 gnutls_x509_crt_set_subject_key_id(crt, buffer, bytes);
180
181 gnutls_x509_crt_sign(crt, crt, key);
182
183 /*
184 * Save it...
185 */
186
187 bytes = sizeof(buffer);
188 if ((result = gnutls_x509_crt_export(crt, GNUTLS_X509_FMT_PEM, buffer, &bytes)) < 0)
189 {
d0facf48 190 DEBUG_printf(("1cupsMakeServerCredentials: Unable to export public key and X.509 certificate: %s", gnutls_strerror(result)));
172bdf5d
MS
191 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, gnutls_strerror(result), 0);
192 gnutls_x509_crt_deinit(crt);
193 gnutls_x509_privkey_deinit(key);
194 return (0);
195 }
196 else if ((fp = cupsFileOpen(crtfile, "w")) != NULL)
197 {
d0facf48 198 DEBUG_printf(("1cupsMakeServerCredentials: Writing public key and X.509 certificate to \"%s\".", crtfile));
172bdf5d
MS
199 cupsFileWrite(fp, (char *)buffer, bytes);
200 cupsFileClose(fp);
201 }
202 else
203 {
d0facf48 204 DEBUG_printf(("1cupsMakeServerCredentials: Unable to create public key and X.509 certificate file \"%s\": %s", crtfile, strerror(errno)));
172bdf5d
MS
205 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
206 gnutls_x509_crt_deinit(crt);
207 gnutls_x509_privkey_deinit(key);
208 return (0);
209 }
210
211 /*
212 * Cleanup...
213 */
214
215 gnutls_x509_crt_deinit(crt);
216 gnutls_x509_privkey_deinit(key);
217
d0facf48
MS
218 DEBUG_puts("1cupsMakeServerCredentials: Successfully created credentials.");
219
172bdf5d 220 return (1);
07623986
MS
221}
222
223
224/*
225 * 'cupsSetServerCredentials()' - Set the default server credentials.
226 *
227 * Note: The server credentials are used by all threads in the running process.
228 * This function is threadsafe.
229 *
e1f19878 230 * @since CUPS 2.0/OS 10.10@
07623986
MS
231 */
232
233int /* O - 1 on success, 0 on failure */
234cupsSetServerCredentials(
235 const char *path, /* I - Path to keychain/directory */
236 const char *common_name, /* I - Default common name for server */
237 int auto_create) /* I - 1 = automatically create self-signed certificates */
238{
f394e0f7 239 char temp[1024]; /* Default path buffer */
172bdf5d
MS
240
241
242 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path, common_name, auto_create));
243
07623986 244 /*
d0facf48 245 * Use defaults as needed...
07623986
MS
246 */
247
d0facf48
MS
248 if (!path)
249 path = http_gnutls_default_path(temp, sizeof(temp));
07623986 250
172bdf5d 251 /*
d0facf48 252 * Range check input...
172bdf5d
MS
253 */
254
d0facf48 255 if (!path || !common_name)
172bdf5d 256 {
d0facf48
MS
257 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
258 return (0);
259 }
172bdf5d 260
d0facf48
MS
261 _cupsMutexLock(&tls_mutex);
262
263 /*
264 * Free old values...
265 */
172bdf5d 266
d0facf48
MS
267 if (tls_keypath)
268 _cupsStrFree(tls_keypath);
172bdf5d 269
d0facf48
MS
270 if (tls_common_name)
271 _cupsStrFree(tls_common_name);
172bdf5d 272
07623986
MS
273 /*
274 * Save the new values...
275 */
276
277 tls_keypath = _cupsStrAlloc(path);
278 tls_auto_create = auto_create;
279 tls_common_name = _cupsStrAlloc(common_name);
280
281 _cupsMutexUnlock(&tls_mutex);
282
283 return (1);
284}
285
286
dd332638
MS
287/*
288 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
289 * an encrypted connection.
290 *
8072030b 291 * @since CUPS 1.5/macOS 10.7@
dd332638
MS
292 */
293
294int /* O - Status of call (0 = success) */
295httpCopyCredentials(
296 http_t *http, /* I - Connection to server */
297 cups_array_t **credentials) /* O - Array of credentials */
298{
bdc8d1ad
MS
299 unsigned count; /* Number of certificates */
300 const gnutls_datum_t *certs; /* Certificates */
301
302
303 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", http, credentials));
304
dd332638
MS
305 if (credentials)
306 *credentials = NULL;
307
308 if (!http || !http->tls || !credentials)
309 return (-1);
310
bdc8d1ad
MS
311 *credentials = cupsArrayNew(NULL, NULL);
312 certs = gnutls_certificate_get_peers(http->tls, &count);
313
314 DEBUG_printf(("1httpCopyCredentials: certs=%p, count=%u", certs, count));
315
316 if (certs && count)
317 {
318 while (count > 0)
319 {
320 httpAddCredential(*credentials, certs->data, certs->size);
321 certs ++;
322 count --;
323 }
324 }
325
dd332638
MS
326 return (0);
327}
328
329
330/*
331 * '_httpCreateCredentials()' - Create credentials in the internal format.
332 */
333
334http_tls_credentials_t /* O - Internal credentials */
335_httpCreateCredentials(
336 cups_array_t *credentials) /* I - Array of credentials */
337{
338 (void)credentials;
339
340 return (NULL);
341}
342
343
344/*
345 * '_httpFreeCredentials()' - Free internal credentials.
346 */
347
348void
349_httpFreeCredentials(
350 http_tls_credentials_t credentials) /* I - Internal credentials */
351{
352 (void)credentials;
353}
354
355
a15960a1
MS
356/*
357 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
358 *
e1f19878 359 * @since CUPS 2.0/OS 10.10@
a15960a1
MS
360 */
361
362int /* O - 1 if valid, 0 otherwise */
363httpCredentialsAreValidForName(
364 cups_array_t *credentials, /* I - Credentials */
365 const char *common_name) /* I - Name to check */
366{
ff82e169
MS
367 gnutls_x509_crt_t cert; /* Certificate */
368 int result = 0; /* Result */
a15960a1
MS
369
370
ff82e169
MS
371 cert = http_gnutls_create_credential((http_credential_t *)cupsArrayFirst(credentials));
372 if (cert)
a15960a1 373 {
ff82e169 374 result = gnutls_x509_crt_check_hostname(cert, common_name) != 0;
08d56b1f
MS
375
376 if (result)
377 {
378 int i, /* Looping var */
379 count; /* Number of revoked certificates */
380 unsigned char cserial[1024], /* Certificate serial number */
381 rserial[1024]; /* Revoked serial number */
382 size_t cserial_size, /* Size of cert serial number */
383 rserial_size; /* Size of revoked serial number */
384
385 _cupsMutexLock(&tls_mutex);
386
387 count = gnutls_x509_crl_get_crt_count(tls_crl);
388
389 if (count > 0)
390 {
391 cserial_size = sizeof(cserial);
392 gnutls_x509_crt_get_serial(cert, cserial, &cserial_size);
393
394 for (i = 0; i < count; i ++)
395 {
396 rserial_size = sizeof(rserial);
c4edc066 397 if (!gnutls_x509_crl_get_crt_serial(tls_crl, (unsigned)i, rserial, &rserial_size, NULL) && cserial_size == rserial_size && !memcmp(cserial, rserial, rserial_size))
08d56b1f
MS
398 {
399 result = 0;
400 break;
401 }
402 }
403 }
404
405 _cupsMutexUnlock(&tls_mutex);
406 }
407
ff82e169 408 gnutls_x509_crt_deinit(cert);
a15960a1 409 }
a15960a1 410
ff82e169 411 return (result);
a15960a1
MS
412}
413
414
415/*
416 * 'httpCredentialsGetTrust()' - Return the trust of credentials.
417 *
e1f19878 418 * @since CUPS 2.0/OS 10.10@
a15960a1
MS
419 */
420
421http_trust_t /* O - Level of trust */
422httpCredentialsGetTrust(
423 cups_array_t *credentials, /* I - Credentials */
424 const char *common_name) /* I - Common name for trust lookup */
425{
426 http_trust_t trust = HTTP_TRUST_OK;
427 /* Trusted? */
ff82e169 428 gnutls_x509_crt_t cert; /* Certificate */
a15960a1
MS
429 cups_array_t *tcreds = NULL; /* Trusted credentials */
430 _cups_globals_t *cg = _cupsGlobals();
431 /* Per-thread globals */
432
433
434 if (!common_name)
e5aa186c
MS
435 {
436 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No common name specified."), 1);
a15960a1 437 return (HTTP_TRUST_UNKNOWN);
e5aa186c 438 }
a15960a1 439
ff82e169 440 if ((cert = http_gnutls_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
e5aa186c
MS
441 {
442 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to create credentials from array."), 1);
a15960a1 443 return (HTTP_TRUST_UNKNOWN);
e5aa186c 444 }
a15960a1 445
3abb875b 446 if (cg->any_root < 0)
08d56b1f 447 {
3abb875b 448 _cupsSetDefaults();
08d56b1f
MS
449 http_gnutls_load_crl();
450 }
3abb875b 451
a15960a1
MS
452 /*
453 * Look this common name up in the default keychains...
454 */
455
456 httpLoadCredentials(NULL, &tcreds, common_name);
457
458 if (tcreds)
459 {
460 char credentials_str[1024], /* String for incoming credentials */
461 tcreds_str[1024]; /* String for saved credentials */
462
463 httpCredentialsString(credentials, credentials_str, sizeof(credentials_str));
464 httpCredentialsString(tcreds, tcreds_str, sizeof(tcreds_str));
465
466 if (strcmp(credentials_str, tcreds_str))
467 {
468 /*
469 * Credentials don't match, let's look at the expiration date of the new
470 * credentials and allow if the new ones have a later expiration...
471 */
472
08d56b1f
MS
473 if (!cg->trust_first)
474 {
475 /*
476 * Do not trust certificates on first use...
477 */
478
e5aa186c
MS
479 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Trust on first use is disabled."), 1);
480
08d56b1f
MS
481 trust = HTTP_TRUST_INVALID;
482 }
e5aa186c 483 else if (httpCredentialsGetExpiration(credentials) <= httpCredentialsGetExpiration(tcreds))
a15960a1
MS
484 {
485 /*
e5aa186c 486 * The new credentials are not newly issued...
a15960a1
MS
487 */
488
e5aa186c
MS
489 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("New credentials are older than stored credentials."), 1);
490
491 trust = HTTP_TRUST_INVALID;
492 }
493 else if (!httpCredentialsAreValidForName(credentials, common_name))
494 {
495 /*
496 * The common name does not match the issued certificate...
497 */
498
499 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("New credentials are not valid for name."), 1);
500
a15960a1
MS
501 trust = HTTP_TRUST_INVALID;
502 }
503 else if (httpCredentialsGetExpiration(tcreds) < time(NULL))
504 {
505 /*
506 * Save the renewed credentials...
507 */
508
509 trust = HTTP_TRUST_RENEWED;
510
511 httpSaveCredentials(NULL, credentials, common_name);
512 }
513 }
514
515 httpFreeCredentials(tcreds);
516 }
517 else if (cg->validate_certs && !httpCredentialsAreValidForName(credentials, common_name))
e5aa186c
MS
518 {
519 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No stored credentials, not valid for name."), 1);
a15960a1 520 trust = HTTP_TRUST_INVALID;
e5aa186c 521 }
7aeb3615
MS
522 else if (!cg->trust_first)
523 {
f8e19681
MS
524 /*
525 * See if we have a site CA certificate we can compare...
526 */
527
528 if (!httpLoadCredentials(NULL, &tcreds, "site"))
529 {
530 if (cupsArrayCount(credentials) != (cupsArrayCount(tcreds) + 1))
531 {
532 /*
533 * Certificate isn't directly generated from the CA cert...
534 */
535
536 trust = HTTP_TRUST_INVALID;
537 }
538 else
539 {
540 /*
541 * Do a tail comparison of the two certificates...
542 */
543
544 http_credential_t *a, *b; /* Certificates */
545
546 for (a = (http_credential_t *)cupsArrayFirst(tcreds), b = (http_credential_t *)cupsArrayIndex(credentials, 1);
547 a && b;
548 a = (http_credential_t *)cupsArrayNext(tcreds), b = (http_credential_t *)cupsArrayNext(credentials))
549 if (a->datalen != b->datalen || memcmp(a->data, b->data, a->datalen))
550 break;
551
552 if (a || b)
553 trust = HTTP_TRUST_INVALID;
554 }
555
556 if (trust != HTTP_TRUST_OK)
557 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Credentials do not validate against site CA certificate."), 1);
558 }
559 else
560 {
561 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Trust on first use is disabled."), 1);
562 trust = HTTP_TRUST_INVALID;
563 }
7aeb3615 564 }
a15960a1 565
ff82e169
MS
566 if (trust == HTTP_TRUST_OK && !cg->expired_certs)
567 {
568 time_t curtime; /* Current date/time */
569
570 time(&curtime);
571 if (curtime < gnutls_x509_crt_get_activation_time(cert) ||
572 curtime > gnutls_x509_crt_get_expiration_time(cert))
e5aa186c
MS
573 {
574 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Credentials have expired."), 1);
ff82e169 575 trust = HTTP_TRUST_EXPIRED;
e5aa186c 576 }
ff82e169
MS
577 }
578
579 if (trust == HTTP_TRUST_OK && !cg->any_root && cupsArrayCount(credentials) == 1)
e5aa186c
MS
580 {
581 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Self-signed credentials are blocked."), 1);
a15960a1 582 trust = HTTP_TRUST_INVALID;
e5aa186c 583 }
a15960a1 584
ff82e169 585 gnutls_x509_crt_deinit(cert);
a15960a1
MS
586
587 return (trust);
588}
589
590
591/*
592 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
593 *
e1f19878 594 * @since CUPS 2.0/OS 10.10@
a15960a1
MS
595 */
596
597time_t /* O - Expiration date of credentials */
598httpCredentialsGetExpiration(
599 cups_array_t *credentials) /* I - Credentials */
600{
ff82e169
MS
601 gnutls_x509_crt_t cert; /* Certificate */
602 time_t result = 0; /* Result */
603
604
605 cert = http_gnutls_create_credential((http_credential_t *)cupsArrayFirst(credentials));
606 if (cert)
607 {
bdc8d1ad 608 result = gnutls_x509_crt_get_expiration_time(cert);
ff82e169
MS
609 gnutls_x509_crt_deinit(cert);
610 }
a15960a1 611
ff82e169 612 return (result);
a15960a1
MS
613}
614
615
616/*
617 * 'httpCredentialsString()' - Return a string representing the credentials.
618 *
e1f19878 619 * @since CUPS 2.0/OS 10.10@
a15960a1
MS
620 */
621
622size_t /* O - Total size of credentials string */
623httpCredentialsString(
624 cups_array_t *credentials, /* I - Credentials */
625 char *buffer, /* I - Buffer or @code NULL@ */
626 size_t bufsize) /* I - Size of buffer */
627{
ff82e169
MS
628 http_credential_t *first; /* First certificate */
629 gnutls_x509_crt_t cert; /* Certificate */
630
631
a15960a1
MS
632 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT ")", credentials, buffer, CUPS_LLCAST bufsize));
633
634 if (!buffer)
635 return (0);
636
637 if (buffer && bufsize > 0)
638 *buffer = '\0';
639
a15960a1 640 if ((first = (http_credential_t *)cupsArrayFirst(credentials)) != NULL &&
ff82e169 641 (cert = http_gnutls_create_credential(first)) != NULL)
a15960a1 642 {
af62b316
MS
643 char name[256], /* Common name associated with cert */
644 issuer[256]; /* Issuer associated with cert */
645 size_t len; /* Length of string */
a15960a1 646 time_t expiration; /* Expiration date of cert */
ff82ce17 647 int sigalg; /* Signature algorithm */
a15960a1
MS
648 unsigned char md5_digest[16]; /* MD5 result */
649
af62b316
MS
650 len = sizeof(name) - 1;
651 if (gnutls_x509_crt_get_dn_by_oid(cert, GNUTLS_OID_X520_COMMON_NAME, 0, 0, name, &len) >= 0)
652 name[len] = '\0';
bdc8d1ad 653 else
a15960a1
MS
654 strlcpy(name, "unknown", sizeof(name));
655
af62b316 656 len = sizeof(issuer) - 1;
ff82ce17 657 if (gnutls_x509_crt_get_issuer_dn_by_oid(cert, GNUTLS_OID_X520_ORGANIZATION_NAME, 0, 0, issuer, &len) >= 0)
af62b316
MS
658 issuer[len] = '\0';
659 else
660 strlcpy(issuer, "unknown", sizeof(issuer));
661
ff82e169 662 expiration = gnutls_x509_crt_get_expiration_time(cert);
ff82ce17 663 sigalg = gnutls_x509_crt_get_signature_algorithm(cert);
a15960a1 664
7ec11630 665 cupsHashData("md5", first->data, first->datalen, md5_digest, sizeof(md5_digest));
a15960a1 666
ff82ce17 667 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), gnutls_sign_get_name(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]);
a15960a1 668
ff82e169 669 gnutls_x509_crt_deinit(cert);
a15960a1 670 }
a15960a1
MS
671
672 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer));
673
674 return (strlen(buffer));
675}
676
677
678/*
679 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
680 *
e1f19878 681 * @since CUPS 2.0/OS 10.10@
a15960a1
MS
682 */
683
684int /* O - 0 on success, -1 on error */
685httpLoadCredentials(
686 const char *path, /* I - Keychain/PKCS#12 path */
687 cups_array_t **credentials, /* IO - Credentials */
688 const char *common_name) /* I - Common name for credentials */
689{
ff82e169
MS
690 cups_file_t *fp; /* Certificate file */
691 char filename[1024], /* filename.crt */
692 temp[1024], /* Temporary string */
693 line[256]; /* Base64-encoded line */
694 unsigned char *data = NULL; /* Buffer for cert data */
695 size_t alloc_data = 0, /* Bytes allocated */
696 num_data = 0; /* Bytes used */
697 int decoded; /* Bytes decoded */
0de71d36
MS
698 int in_certificate = 0;
699 /* In a certificate? */
ff82e169
MS
700
701
702 if (!credentials || !common_name)
703 return (-1);
704
705 if (!path)
706 path = http_gnutls_default_path(temp, sizeof(temp));
707 if (!path)
708 return (-1);
709
26435c51 710 http_gnutls_make_path(filename, sizeof(filename), path, common_name, "crt");
ff82e169
MS
711
712 if ((fp = cupsFileOpen(filename, "r")) == NULL)
713 return (-1);
714
715 while (cupsFileGets(fp, line, sizeof(line)))
716 {
717 if (!strcmp(line, "-----BEGIN CERTIFICATE-----"))
718 {
0de71d36 719 if (in_certificate)
ff82e169
MS
720 {
721 /*
722 * Missing END CERTIFICATE...
723 */
724
725 httpFreeCredentials(*credentials);
726 *credentials = NULL;
727 break;
728 }
0de71d36
MS
729
730 in_certificate = 1;
ff82e169
MS
731 }
732 else if (!strcmp(line, "-----END CERTIFICATE-----"))
733 {
0de71d36 734 if (!in_certificate || !num_data)
ff82e169
MS
735 {
736 /*
737 * Missing data...
738 */
a15960a1 739
ff82e169
MS
740 httpFreeCredentials(*credentials);
741 *credentials = NULL;
742 break;
743 }
744
745 if (!*credentials)
746 *credentials = cupsArrayNew(NULL, NULL);
747
748 if (httpAddCredential(*credentials, data, num_data))
749 {
750 httpFreeCredentials(*credentials);
751 *credentials = NULL;
752 break;
753 }
754
0de71d36
MS
755 num_data = 0;
756 in_certificate = 0;
ff82e169 757 }
0de71d36 758 else if (in_certificate)
ff82e169
MS
759 {
760 if (alloc_data == 0)
761 {
762 data = malloc(2048);
763 alloc_data = 2048;
764
765 if (!data)
766 break;
767 }
768 else if ((num_data + strlen(line)) >= alloc_data)
769 {
770 unsigned char *tdata = realloc(data, alloc_data + 1024);
771 /* Expanded buffer */
772
773 if (!tdata)
774 {
775 httpFreeCredentials(*credentials);
776 *credentials = NULL;
777 break;
778 }
779
780 data = tdata;
781 alloc_data += 1024;
782 }
783
784 decoded = alloc_data - num_data;
bdc8d1ad
MS
785 httpDecode64_2((char *)data + num_data, &decoded, line);
786 num_data += (size_t)decoded;
ff82e169
MS
787 }
788 }
789
790 cupsFileClose(fp);
791
0de71d36 792 if (in_certificate)
ff82e169
MS
793 {
794 /*
795 * Missing END CERTIFICATE...
796 */
797
798 httpFreeCredentials(*credentials);
799 *credentials = NULL;
800 }
801
802 if (data)
803 free(data);
804
805 return (*credentials ? 0 : -1);
a15960a1
MS
806}
807
808
809/*
810 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
811 *
e1f19878 812 * @since CUPS 2.0/OS 10.10@
a15960a1
MS
813 */
814
815int /* O - -1 on error, 0 on success */
816httpSaveCredentials(
817 const char *path, /* I - Keychain/PKCS#12 path */
818 cups_array_t *credentials, /* I - Credentials */
819 const char *common_name) /* I - Common name for credentials */
820{
ff82e169
MS
821 cups_file_t *fp; /* Certificate file */
822 char filename[1024], /* filename.crt */
823 nfilename[1024],/* filename.crt.N */
824 temp[1024], /* Temporary string */
bdc8d1ad 825 line[256]; /* Base64-encoded line */
ff82e169 826 const unsigned char *ptr; /* Pointer into certificate */
bdc8d1ad 827 ssize_t remaining; /* Bytes left */
ff82e169
MS
828 http_credential_t *cred; /* Current credential */
829
830
831 if (!credentials || !common_name)
832 return (-1);
833
834 if (!path)
835 path = http_gnutls_default_path(temp, sizeof(temp));
836 if (!path)
837 return (-1);
838
26435c51
MS
839 http_gnutls_make_path(filename, sizeof(filename), path, common_name, "crt");
840 snprintf(nfilename, sizeof(nfilename), "%s.N", filename);
ff82e169
MS
841
842 if ((fp = cupsFileOpen(nfilename, "w")) == NULL)
843 return (-1);
844
845 fchmod(cupsFileNumber(fp), 0600);
846
847 for (cred = (http_credential_t *)cupsArrayFirst(credentials);
848 cred;
849 cred = (http_credential_t *)cupsArrayNext(credentials))
850 {
851 cupsFilePuts(fp, "-----BEGIN CERTIFICATE-----\n");
bdc8d1ad 852 for (ptr = cred->data, remaining = (ssize_t)cred->datalen; remaining > 0; remaining -= 45, ptr += 45)
ff82e169 853 {
bdc8d1ad 854 httpEncode64_2(line, sizeof(line), (char *)ptr, remaining > 45 ? 45 : remaining);
ff82e169
MS
855 cupsFilePrintf(fp, "%s\n", line);
856 }
857 cupsFilePuts(fp, "-----END CERTIFICATE-----\n");
858 }
859
860 cupsFileClose(fp);
861
862 return (rename(nfilename, filename));
863}
864
865
866/*
867 * 'http_gnutls_create_credential()' - Create a single credential in the internal format.
868 */
869
870static gnutls_x509_crt_t /* O - Certificate */
871http_gnutls_create_credential(
872 http_credential_t *credential) /* I - Credential */
873{
bdc8d1ad
MS
874 int result; /* Result from GNU TLS */
875 gnutls_x509_crt_t cert; /* Certificate */
ff82e169
MS
876 gnutls_datum_t datum; /* Data record */
877
878
bdc8d1ad
MS
879 DEBUG_printf(("3http_gnutls_create_credential(credential=%p)", credential));
880
ff82e169
MS
881 if (!credential)
882 return (NULL);
883
bdc8d1ad
MS
884 if ((result = gnutls_x509_crt_init(&cert)) < 0)
885 {
886 DEBUG_printf(("4http_gnutls_create_credential: init error: %s", gnutls_strerror(result)));
ff82e169 887 return (NULL);
bdc8d1ad 888 }
ff82e169 889
bdc8d1ad
MS
890 datum.data = credential->data;
891 datum.size = credential->datalen;
ff82e169 892
bdc8d1ad 893 if ((result = gnutls_x509_crt_import(cert, &datum, GNUTLS_X509_FMT_DER)) < 0)
ff82e169 894 {
bdc8d1ad
MS
895 DEBUG_printf(("4http_gnutls_create_credential: import error: %s", gnutls_strerror(result)));
896
ff82e169
MS
897 gnutls_x509_crt_deinit(cert);
898 return (NULL);
899 }
a15960a1 900
ff82e169 901 return (cert);
a15960a1
MS
902}
903
904
d0facf48
MS
905/*
906 * 'http_gnutls_default_path()' - Get the default credential store path.
907 */
908
909static const char * /* O - Path or NULL on error */
910http_gnutls_default_path(char *buffer,/* I - Path buffer */
911 size_t bufsize)/* I - Size of path buffer */
912{
913 const char *home = getenv("HOME"); /* HOME environment variable */
914
915
916 if (getuid() && home)
917 {
918 snprintf(buffer, bufsize, "%s/.cups", home);
919 if (access(buffer, 0))
920 {
921 DEBUG_printf(("1http_gnutls_default_path: Making directory \"%s\".", buffer));
922 if (mkdir(buffer, 0700))
923 {
924 DEBUG_printf(("1http_gnutls_default_path: Failed to make directory: %s", strerror(errno)));
925 return (NULL);
926 }
927 }
928
929 snprintf(buffer, bufsize, "%s/.cups/ssl", home);
930 if (access(buffer, 0))
931 {
932 DEBUG_printf(("1http_gnutls_default_path: Making directory \"%s\".", buffer));
933 if (mkdir(buffer, 0700))
934 {
935 DEBUG_printf(("1http_gnutls_default_path: Failed to make directory: %s", strerror(errno)));
936 return (NULL);
937 }
938 }
939 }
940 else
941 strlcpy(buffer, CUPS_SERVERROOT "/ssl", bufsize);
942
943 DEBUG_printf(("1http_gnutls_default_path: Using default path \"%s\".", buffer));
944
945 return (buffer);
946}
947
948
08d56b1f
MS
949/*
950 * 'http_gnutls_load_crl()' - Load the certificate revocation list, if any.
951 */
952
953static void
954http_gnutls_load_crl(void)
955{
956 _cupsMutexLock(&tls_mutex);
957
958 if (!gnutls_x509_crl_init(&tls_crl))
959 {
960 cups_file_t *fp; /* CRL file */
961 char filename[1024], /* site.crl */
962 line[256]; /* Base64-encoded line */
963 unsigned char *data = NULL; /* Buffer for cert data */
964 size_t alloc_data = 0, /* Bytes allocated */
965 num_data = 0; /* Bytes used */
966 int decoded; /* Bytes decoded */
967 gnutls_datum_t datum; /* Data record */
968
969
970 http_gnutls_make_path(filename, sizeof(filename), CUPS_SERVERROOT, "site", "crl");
971
972 if ((fp = cupsFileOpen(filename, "r")) != NULL)
973 {
974 while (cupsFileGets(fp, line, sizeof(line)))
975 {
976 if (!strcmp(line, "-----BEGIN X509 CRL-----"))
977 {
978 if (num_data)
979 {
980 /*
981 * Missing END X509 CRL...
982 */
983
984 break;
985 }
986 }
987 else if (!strcmp(line, "-----END X509 CRL-----"))
988 {
989 if (!num_data)
990 {
991 /*
992 * Missing data...
993 */
994
995 break;
996 }
997
998 datum.data = data;
999 datum.size = num_data;
1000
0eff12fa 1001 gnutls_x509_crl_import(tls_crl, &datum, GNUTLS_X509_FMT_PEM);
08d56b1f
MS
1002
1003 num_data = 0;
1004 }
1005 else
1006 {
1007 if (alloc_data == 0)
1008 {
1009 data = malloc(2048);
1010 alloc_data = 2048;
1011
1012 if (!data)
1013 break;
1014 }
1015 else if ((num_data + strlen(line)) >= alloc_data)
1016 {
1017 unsigned char *tdata = realloc(data, alloc_data + 1024);
1018 /* Expanded buffer */
1019
1020 if (!tdata)
08d56b1f 1021 break;
08d56b1f
MS
1022
1023 data = tdata;
1024 alloc_data += 1024;
1025 }
1026
1027 decoded = alloc_data - num_data;
1028 httpDecode64_2((char *)data + num_data, &decoded, line);
1029 num_data += (size_t)decoded;
1030 }
1031 }
1032
1033 cupsFileClose(fp);
1034
1035 if (data)
1036 free(data);
1037 }
1038 }
1039
1040 _cupsMutexUnlock(&tls_mutex);
1041}
1042
1043
26435c51
MS
1044/*
1045 * 'http_gnutls_make_path()' - Format a filename for a certificate or key file.
1046 */
1047
1048static const char * /* O - Filename */
1049http_gnutls_make_path(
1050 char *buffer, /* I - Filename buffer */
1051 size_t bufsize, /* I - Size of buffer */
1052 const char *dirname, /* I - Directory */
1053 const char *filename, /* I - Filename (usually hostname) */
1054 const char *ext) /* I - Extension */
1055{
1056 char *bufptr, /* Pointer into buffer */
1057 *bufend = buffer + bufsize - 1; /* End of buffer */
1058
1059
1060 snprintf(buffer, bufsize, "%s/", dirname);
1061 bufptr = buffer + strlen(buffer);
1062
1063 while (*filename && bufptr < bufend)
1064 {
1065 if (_cups_isalnum(*filename) || *filename == '-' || *filename == '.')
1066 *bufptr++ = *filename;
1067 else
1068 *bufptr++ = '_';
1069
1070 filename ++;
1071 }
1072
1073 if (bufptr < bufend)
1074 *bufptr++ = '.';
1075
a2751f30 1076 strlcpy(bufptr, ext, (size_t)(bufend - bufptr + 1));
26435c51
MS
1077
1078 return (buffer);
1079}
1080
1081
dd332638
MS
1082/*
1083 * 'http_gnutls_read()' - Read function for the GNU TLS library.
1084 */
1085
1086static ssize_t /* O - Number of bytes read or -1 on error */
1087http_gnutls_read(
1088 gnutls_transport_ptr_t ptr, /* I - Connection to server */
1089 void *data, /* I - Buffer */
1090 size_t length) /* I - Number of bytes to read */
1091{
1092 http_t *http; /* HTTP connection */
1093 ssize_t bytes; /* Bytes read */
1094
1095
1096 DEBUG_printf(("6http_gnutls_read(ptr=%p, data=%p, length=%d)", ptr, data, (int)length));
1097
1098 http = (http_t *)ptr;
1099
a7aabde8 1100 if (!http->blocking || http->timeout_value > 0.0)
dd332638
MS
1101 {
1102 /*
1103 * Make sure we have data before we read...
1104 */
1105
1106 while (!_httpWait(http, http->wait_value, 0))
1107 {
1108 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
1109 continue;
1110
1111 http->error = ETIMEDOUT;
1112 return (-1);
1113 }
1114 }
1115
1116 bytes = recv(http->fd, data, length, 0);
1117 DEBUG_printf(("6http_gnutls_read: bytes=%d", (int)bytes));
1118 return (bytes);
1119}
1120
1121
1122/*
1123 * 'http_gnutls_write()' - Write function for the GNU TLS library.
1124 */
1125
1126static ssize_t /* O - Number of bytes written or -1 on error */
1127http_gnutls_write(
1128 gnutls_transport_ptr_t ptr, /* I - Connection to server */
1129 const void *data, /* I - Data buffer */
1130 size_t length) /* I - Number of bytes to write */
1131{
1132 ssize_t bytes; /* Bytes written */
1133
1134
1135 DEBUG_printf(("6http_gnutls_write(ptr=%p, data=%p, length=%d)", ptr, data,
1136 (int)length));
dd332638
MS
1137 bytes = send(((http_t *)ptr)->fd, data, length, 0);
1138 DEBUG_printf(("http_gnutls_write: bytes=%d", (int)bytes));
1139
1140 return (bytes);
1141}
2c85b752
MS
1142
1143
1144/*
172bdf5d 1145 * '_httpTLSInitialize()' - Initialize the TLS stack.
2c85b752
MS
1146 */
1147
172bdf5d
MS
1148void
1149_httpTLSInitialize(void)
2c85b752 1150{
2c85b752
MS
1151 /*
1152 * Initialize GNU TLS...
1153 */
1154
1155 gnutls_global_init();
dd332638 1156}
2c85b752 1157
2c85b752 1158
dd332638 1159/*
172bdf5d 1160 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
dd332638 1161 */
2c85b752 1162
172bdf5d
MS
1163size_t /* O - Bytes available */
1164_httpTLSPending(http_t *http) /* I - HTTP connection */
dd332638
MS
1165{
1166 return (gnutls_record_check_pending(http->tls));
2c85b752
MS
1167}
1168
1169
2c85b752 1170/*
172bdf5d 1171 * '_httpTLSRead()' - Read from a SSL/TLS connection.
2c85b752
MS
1172 */
1173
172bdf5d
MS
1174int /* O - Bytes read */
1175_httpTLSRead(http_t *http, /* I - Connection to server */
1176 char *buf, /* I - Buffer to store data */
1177 int len) /* I - Length of buffer */
2c85b752 1178{
2c85b752
MS
1179 ssize_t result; /* Return value */
1180
1181
07623986 1182 result = gnutls_record_recv(http->tls, buf, (size_t)len);
2c85b752
MS
1183
1184 if (result < 0 && !errno)
1185 {
1186 /*
1187 * Convert GNU TLS error to errno value...
1188 */
1189
1190 switch (result)
1191 {
1192 case GNUTLS_E_INTERRUPTED :
1193 errno = EINTR;
1194 break;
1195
1196 case GNUTLS_E_AGAIN :
1197 errno = EAGAIN;
1198 break;
1199
1200 default :
1201 errno = EPIPE;
1202 break;
1203 }
1204
1205 result = -1;
1206 }
1207
1208 return ((int)result);
dd332638 1209}
2c85b752
MS
1210
1211
63aefcd5
MS
1212/*
1213 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
1214 */
1215
1216void
454619c7
MS
1217_httpTLSSetOptions(int options, /* I - Options */
1218 int min_version, /* I - Minimum TLS version */
1219 int max_version) /* I - Maximum TLS version */
63aefcd5 1220{
02c88e67 1221 if (!(options & _HTTP_TLS_SET_DEFAULT) || tls_options < 0)
8f1fbdec
MS
1222 {
1223 tls_options = options;
1224 tls_min_version = min_version;
1225 tls_max_version = max_version;
1226 }
63aefcd5
MS
1227}
1228
1229
2c85b752 1230/*
172bdf5d 1231 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
2c85b752
MS
1232 */
1233
172bdf5d
MS
1234int /* O - 0 on success, -1 on failure */
1235_httpTLSStart(http_t *http) /* I - Connection to server */
2c85b752
MS
1236{
1237 char hostname[256], /* Hostname */
1238 *hostptr; /* Pointer into hostname */
2c85b752 1239 int status; /* Status of handshake */
172bdf5d 1240 gnutls_certificate_credentials_t *credentials;
2c85b752 1241 /* TLS credentials */
5e59cd06 1242 char priority_string[2048];
ee6226a5 1243 /* Priority string */
8f1fbdec 1244 int version; /* Current version */
a7aabde8
MS
1245 double old_timeout; /* Old timeout value */
1246 http_timeout_cb_t old_cb; /* Old timeout callback */
1247 void *old_data; /* Old timeout data */
8f1fbdec
MS
1248 static const char * const versions[] =/* SSL/TLS versions */
1249 {
1250 "VERS-SSL3.0",
1251 "VERS-TLS1.0",
1252 "VERS-TLS1.1",
1253 "VERS-TLS1.2",
1254 "VERS-TLS1.3",
1255 "VERS-TLS-ALL"
1256 };
2c85b752
MS
1257
1258
b37d45d9
MS
1259 DEBUG_printf(("3_httpTLSStart(http=%p)", http));
1260
1261 if (tls_options < 0)
1262 {
1263 DEBUG_puts("4_httpTLSStart: Setting defaults.");
1264 _cupsSetDefaults();
1265 DEBUG_printf(("4_httpTLSStart: tls_options=%x", tls_options));
1266 }
2c85b752 1267
172bdf5d 1268 if (http->mode == _HTTP_MODE_SERVER && !tls_keypath)
2c85b752 1269 {
172bdf5d
MS
1270 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
1271 http->error = errno = EINVAL;
1272 http->status = HTTP_STATUS_ERROR;
1273 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Server credentials not set."), 1);
2c85b752 1274
172bdf5d 1275 return (-1);
2c85b752
MS
1276 }
1277
172bdf5d
MS
1278 credentials = (gnutls_certificate_credentials_t *)
1279 malloc(sizeof(gnutls_certificate_credentials_t));
2c85b752
MS
1280 if (credentials == NULL)
1281 {
172bdf5d 1282 DEBUG_printf(("8_httpStartTLS: Unable to allocate credentials: %s",
2c85b752
MS
1283 strerror(errno)));
1284 http->error = errno;
1285 http->status = HTTP_STATUS_ERROR;
1286 _cupsSetHTTPError(HTTP_STATUS_ERROR);
1287
1288 return (-1);
1289 }
1290
1291 gnutls_certificate_allocate_credentials(credentials);
d0facf48 1292 status = gnutls_init(&http->tls, http->mode == _HTTP_MODE_CLIENT ? GNUTLS_CLIENT : GNUTLS_SERVER);
d0facf48 1293 if (!status)
005f7f1f 1294 status = gnutls_set_default_priority(http->tls);
d0facf48
MS
1295
1296 if (status)
1297 {
1298 http->error = EIO;
1299 http->status = HTTP_STATUS_ERROR;
1300
1301 DEBUG_printf(("4_httpTLSStart: Unable to initialize common TLS parameters: %s", gnutls_strerror(status)));
1302 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, gnutls_strerror(status), 0);
1303
1304 gnutls_deinit(http->tls);
1305 gnutls_certificate_free_credentials(*credentials);
1306 free(credentials);
1307 http->tls = NULL;
1308
1309 return (-1);
1310 }
2c85b752 1311
f394e0f7 1312 if (http->mode == _HTTP_MODE_CLIENT)
172bdf5d
MS
1313 {
1314 /*
1315 * Client: get the hostname to use for TLS...
1316 */
1317
1318 if (httpAddrLocalhost(http->hostaddr))
1319 {
1320 strlcpy(hostname, "localhost", sizeof(hostname));
1321 }
1322 else
1323 {
1324 /*
1325 * Otherwise make sure the hostname we have does not end in a trailing dot.
1326 */
1327
1328 strlcpy(hostname, http->hostname, sizeof(hostname));
1329 if ((hostptr = hostname + strlen(hostname) - 1) >= hostname &&
1330 *hostptr == '.')
1331 *hostptr = '\0';
1332 }
1333
d0facf48 1334 status = gnutls_server_name_set(http->tls, GNUTLS_NAME_DNS, hostname, strlen(hostname));
172bdf5d
MS
1335 }
1336 else
1337 {
1338 /*
1339 * Server: get certificate and private key...
1340 */
1341
1342 char crtfile[1024], /* Certificate file */
1343 keyfile[1024]; /* Private key file */
1344 int have_creds = 0; /* Have credentials? */
1345
378eeedf 1346 if (http->fields[HTTP_FIELD_HOST])
172bdf5d
MS
1347 {
1348 /*
1349 * Use hostname for TLS upgrade...
1350 */
1351
1352 strlcpy(hostname, http->fields[HTTP_FIELD_HOST], sizeof(hostname));
1353 }
1354 else
1355 {
1356 /*
1357 * Resolve hostname from connection address...
1358 */
1359
1360 http_addr_t addr; /* Connection address */
1361 socklen_t addrlen; /* Length of address */
1362
1363 addrlen = sizeof(addr);
1364 if (getsockname(http->fd, (struct sockaddr *)&addr, &addrlen))
1365 {
1366 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno)));
1367 hostname[0] = '\0';
1368 }
1369 else if (httpAddrLocalhost(&addr))
1370 hostname[0] = '\0';
1371 else
1372 {
1373 httpAddrLookup(&addr, hostname, sizeof(hostname));
1374 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname));
1375 }
1376 }
1377
1378 if (isdigit(hostname[0] & 255) || hostname[0] == '[')
1379 hostname[0] = '\0'; /* Don't allow numeric addresses */
1380
1381 if (hostname[0])
1382 {
9e5e2cef 1383 /*
7b98e44e 1384 * First look in the CUPS keystore...
9e5e2cef
MS
1385 */
1386
7b98e44e
MS
1387 http_gnutls_make_path(crtfile, sizeof(crtfile), tls_keypath, hostname, "crt");
1388 http_gnutls_make_path(keyfile, sizeof(keyfile), tls_keypath, hostname, "key");
9e5e2cef
MS
1389
1390 if (access(crtfile, R_OK) || access(keyfile, R_OK))
1391 {
1392 /*
7b98e44e
MS
1393 * No CUPS-managed certs, look for CA certs...
1394 */
1395
1396 char cacrtfile[1024], cakeyfile[1024]; /* CA cert files */
1397
1398 snprintf(cacrtfile, sizeof(cacrtfile), "/etc/letsencrypt/live/%s/fullchain.pem", hostname);
1399 snprintf(cakeyfile, sizeof(cakeyfile), "/etc/letsencrypt/live/%s/privkey.pem", hostname);
1400
1401 if ((access(cacrtfile, R_OK) || access(cakeyfile, R_OK)) && (hostptr = strchr(hostname, '.')) != NULL)
1402 {
1403 /*
1404 * Try just domain name...
1405 */
1406
1407 hostptr ++;
1408 if (strchr(hostptr, '.'))
1409 {
1410 snprintf(cacrtfile, sizeof(cacrtfile), "/etc/letsencrypt/live/%s/fullchain.pem", hostptr);
1411 snprintf(cakeyfile, sizeof(cakeyfile), "/etc/letsencrypt/live/%s/privkey.pem", hostptr);
1412 }
1413 }
1414
1415 if (!access(cacrtfile, R_OK) && !access(cakeyfile, R_OK))
1416 {
1417 /*
1418 * Use the CA certs...
1419 */
1420
1421 strlcpy(crtfile, cacrtfile, sizeof(crtfile));
1422 strlcpy(keyfile, cakeyfile, sizeof(keyfile));
1423 }
9e5e2cef 1424 }
172bdf5d 1425
9e5e2cef 1426 have_creds = !access(crtfile, R_OK) && !access(keyfile, R_OK);
172bdf5d
MS
1427 }
1428 else if (tls_common_name)
1429 {
9e5e2cef 1430 /*
7b98e44e 1431 * First look in the CUPS keystore...
9e5e2cef
MS
1432 */
1433
7b98e44e
MS
1434 http_gnutls_make_path(crtfile, sizeof(crtfile), tls_keypath, tls_common_name, "crt");
1435 http_gnutls_make_path(keyfile, sizeof(keyfile), tls_keypath, tls_common_name, "key");
9e5e2cef
MS
1436
1437 if (access(crtfile, R_OK) || access(keyfile, R_OK))
1438 {
1439 /*
7b98e44e
MS
1440 * No CUPS-managed certs, look for CA certs...
1441 */
1442
1443 char cacrtfile[1024], cakeyfile[1024]; /* CA cert files */
1444
1445 snprintf(cacrtfile, sizeof(cacrtfile), "/etc/letsencrypt/live/%s/fullchain.pem", tls_common_name);
1446 snprintf(cakeyfile, sizeof(cakeyfile), "/etc/letsencrypt/live/%s/privkey.pem", tls_common_name);
1447
1448 if ((access(cacrtfile, R_OK) || access(cakeyfile, R_OK)) && (hostptr = strchr(tls_common_name, '.')) != NULL)
1449 {
1450 /*
1451 * Try just domain name...
1452 */
1453
1454 hostptr ++;
1455 if (strchr(hostptr, '.'))
1456 {
1457 snprintf(cacrtfile, sizeof(cacrtfile), "/etc/letsencrypt/live/%s/fullchain.pem", hostptr);
1458 snprintf(cakeyfile, sizeof(cakeyfile), "/etc/letsencrypt/live/%s/privkey.pem", hostptr);
1459 }
1460 }
1461
1462 if (!access(cacrtfile, R_OK) && !access(cakeyfile, R_OK))
1463 {
1464 /*
1465 * Use the CA certs...
1466 */
1467
1468 strlcpy(crtfile, cacrtfile, sizeof(crtfile));
1469 strlcpy(keyfile, cakeyfile, sizeof(keyfile));
1470 }
9e5e2cef 1471 }
172bdf5d 1472
9e5e2cef 1473 have_creds = !access(crtfile, R_OK) && !access(keyfile, R_OK);
172bdf5d
MS
1474 }
1475
1476 if (!have_creds && tls_auto_create && (hostname[0] || tls_common_name))
1477 {
1478 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname[0] ? hostname : tls_common_name));
1479
1480 if (!cupsMakeServerCredentials(tls_keypath, hostname[0] ? hostname : tls_common_name, 0, NULL, time(NULL) + 365 * 86400))
1481 {
1482 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
1483 http->error = errno = EINVAL;
1484 http->status = HTTP_STATUS_ERROR;
1485 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to create server credentials."), 1);
1486
1487 return (-1);
1488 }
1489 }
1490
d0facf48
MS
1491 DEBUG_printf(("4_httpTLSStart: Using certificate \"%s\" and private key \"%s\".", crtfile, keyfile));
1492
9e5e2cef
MS
1493 if (!status)
1494 status = gnutls_certificate_set_x509_key_file(*credentials, crtfile, keyfile, GNUTLS_X509_FMT_PEM);
d0facf48
MS
1495 }
1496
1497 if (!status)
1498 status = gnutls_credentials_set(http->tls, GNUTLS_CRD_CERTIFICATE, *credentials);
1499
1500 if (status)
1501 {
1502 http->error = EIO;
1503 http->status = HTTP_STATUS_ERROR;
1504
1505 DEBUG_printf(("4_httpTLSStart: Unable to complete client/server setup: %s", gnutls_strerror(status)));
1506 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, gnutls_strerror(status), 0);
1507
1508 gnutls_deinit(http->tls);
1509 gnutls_certificate_free_credentials(*credentials);
1510 free(credentials);
1511 http->tls = NULL;
1512
1513 return (-1);
172bdf5d
MS
1514 }
1515
838bcb92
MS
1516 strlcpy(priority_string, "NORMAL", sizeof(priority_string));
1517
8f1fbdec
MS
1518 if (tls_max_version < _HTTP_TLS_MAX)
1519 {
1520 /*
1521 * Require specific TLS versions...
1522 */
1523
1524 strlcat(priority_string, ":-VERS-TLS-ALL", sizeof(priority_string));
1525 for (version = tls_min_version; version <= tls_max_version; version ++)
1526 {
1527 strlcat(priority_string, ":+", sizeof(priority_string));
1528 strlcat(priority_string, versions[version], sizeof(priority_string));
1529 }
1530 }
1531 else if (tls_min_version == _HTTP_TLS_SSL3)
1532 {
1533 /*
1534 * Allow all versions of TLS and SSL/3.0...
1535 */
1536
fad82159 1537 strlcat(priority_string, ":+VERS-TLS-ALL:+VERS-SSL3.0", sizeof(priority_string));
8f1fbdec 1538 }
63aefcd5 1539 else
8f1fbdec
MS
1540 {
1541 /*
1542 * Require a minimum version...
1543 */
1544
1545 strlcat(priority_string, ":+VERS-TLS-ALL", sizeof(priority_string));
1546 for (version = 0; version < tls_min_version; version ++)
1547 {
1548 strlcat(priority_string, ":-", sizeof(priority_string));
1549 strlcat(priority_string, versions[version], sizeof(priority_string));
1550 }
1551 }
ee6226a5 1552
fad82159
PE
1553 if (tls_options & _HTTP_TLS_ALLOW_RC4)
1554 strlcat(priority_string, ":+ARCFOUR-128", sizeof(priority_string));
1555 else
ce0d9679 1556 strlcat(priority_string, ":!ARCFOUR-128", sizeof(priority_string));
ee6226a5 1557
02c88e67 1558 strlcat(priority_string, ":!ANON-DH", sizeof(priority_string));
ee6226a5 1559
02c88e67 1560 if (tls_options & _HTTP_TLS_DENY_CBC)
5e59cd06 1561 strlcat(priority_string, ":!AES-128-CBC:!AES-256-CBC:!CAMELLIA-128-CBC:!CAMELLIA-256-CBC:!3DES-CBC", sizeof(priority_string));
f2e87147 1562
ee6226a5
MS
1563#ifdef HAVE_GNUTLS_PRIORITY_SET_DIRECT
1564 gnutls_priority_set_direct(http->tls, priority_string, NULL);
63aefcd5 1565
19ba6878
MS
1566#else
1567 gnutls_priority_t priority; /* Priority */
1568
ee6226a5 1569 gnutls_priority_init(&priority, priority_string, NULL);
19ba6878
MS
1570 gnutls_priority_set(http->tls, priority);
1571 gnutls_priority_deinit(priority);
1572#endif /* HAVE_GNUTLS_PRIORITY_SET_DIRECT */
1573
d0facf48
MS
1574 gnutls_transport_set_ptr(http->tls, (gnutls_transport_ptr_t)http);
1575 gnutls_transport_set_pull_function(http->tls, http_gnutls_read);
e7312eb4 1576#ifdef HAVE_GNUTLS_TRANSPORT_SET_PULL_TIMEOUT_FUNCTION
d0facf48 1577 gnutls_transport_set_pull_timeout_function(http->tls, (gnutls_pull_timeout_func)httpWait);
e7312eb4 1578#endif /* HAVE_GNUTLS_TRANSPORT_SET_PULL_TIMEOUT_FUNCTION */
d0facf48
MS
1579 gnutls_transport_set_push_function(http->tls, http_gnutls_write);
1580
a7aabde8
MS
1581 /*
1582 * Enforce a minimum timeout of 10 seconds for the TLS handshake...
1583 */
1584
1585 old_timeout = http->timeout_value;
1586 old_cb = http->timeout_cb;
1587 old_data = http->timeout_data;
1588
1589 if (!old_cb || old_timeout < 10.0)
1590 {
1591 DEBUG_puts("4_httpTLSStart: Setting timeout to 10 seconds.");
1592 httpSetTimeout(http, 10.0, NULL, NULL);
1593 }
1594
1595 /*
1596 * Do the TLS handshake...
1597 */
1598
2c85b752
MS
1599 while ((status = gnutls_handshake(http->tls)) != GNUTLS_E_SUCCESS)
1600 {
d0facf48 1601 DEBUG_printf(("5_httpStartTLS: gnutls_handshake returned %d (%s)",
2c85b752
MS
1602 status, gnutls_strerror(status)));
1603
1604 if (gnutls_error_is_fatal(status))
1605 {
1606 http->error = EIO;
1607 http->status = HTTP_STATUS_ERROR;
1608
1609 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, gnutls_strerror(status), 0);
1610
1611 gnutls_deinit(http->tls);
1612 gnutls_certificate_free_credentials(*credentials);
1613 free(credentials);
1614 http->tls = NULL;
1615
a7aabde8
MS
1616 httpSetTimeout(http, old_timeout, old_cb, old_data);
1617
2c85b752
MS
1618 return (-1);
1619 }
1620 }
1621
a7aabde8
MS
1622 /*
1623 * Restore the previous timeout settings...
1624 */
1625
1626 httpSetTimeout(http, old_timeout, old_cb, old_data);
1627
2c85b752
MS
1628 http->tls_credentials = credentials;
1629
2c85b752
MS
1630 return (0);
1631}
1632
1633
1634/*
172bdf5d 1635 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
2c85b752
MS
1636 */
1637
172bdf5d
MS
1638void
1639_httpTLSStop(http_t *http) /* I - Connection to server */
2c85b752 1640{
172bdf5d
MS
1641 int error; /* Error code */
1642
2c85b752 1643
f394e0f7 1644 error = gnutls_bye(http->tls, http->mode == _HTTP_MODE_CLIENT ? GNUTLS_SHUT_RDWR : GNUTLS_SHUT_WR);
172bdf5d 1645 if (error != GNUTLS_E_SUCCESS)
f394e0f7 1646 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, gnutls_strerror(errno), 0);
2c85b752 1647
2c85b752 1648 gnutls_deinit(http->tls);
172bdf5d
MS
1649 http->tls = NULL;
1650
d0facf48
MS
1651 if (http->tls_credentials)
1652 {
1653 gnutls_certificate_free_credentials(*(http->tls_credentials));
1654 free(http->tls_credentials);
1655 http->tls_credentials = NULL;
1656 }
2c85b752 1657}
2c85b752
MS
1658
1659
2c85b752 1660/*
172bdf5d 1661 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
2c85b752
MS
1662 */
1663
172bdf5d
MS
1664int /* O - Bytes written */
1665_httpTLSWrite(http_t *http, /* I - Connection to server */
1666 const char *buf, /* I - Buffer holding data */
1667 int len) /* I - Length of buffer */
2c85b752
MS
1668{
1669 ssize_t result; /* Return value */
1670
1671
1672 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http, buf, len));
1673
07623986 1674 result = gnutls_record_send(http->tls, buf, (size_t)len);
2c85b752
MS
1675
1676 if (result < 0 && !errno)
1677 {
1678 /*
1679 * Convert GNU TLS error to errno value...
1680 */
1681
1682 switch (result)
1683 {
1684 case GNUTLS_E_INTERRUPTED :
1685 errno = EINTR;
1686 break;
1687
1688 case GNUTLS_E_AGAIN :
1689 errno = EAGAIN;
1690 break;
1691
1692 default :
1693 errno = EPIPE;
1694 break;
1695 }
1696
1697 result = -1;
1698 }
1699
2c85b752
MS
1700 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result));
1701
1702 return ((int)result);
1703}