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