2 * TLS support code for CUPS using GNU TLS.
4 * Copyright 2007-2016 by Apple Inc.
5 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
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 * file is missing or damaged, see the license at "http://www.cups.org/".
13 * This file is subject to the Apple OS-Developed Software exception.
16 /**** This file is included from tls.c ****/
19 * Include necessary headers...
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 */
45 static gnutls_x509_crt_t http_gnutls_create_credential(http_credential_t *credential);
46 static const char *http_gnutls_default_path(char *buffer, size_t bufsize);
47 static void http_gnutls_load_crl(void);
48 static const char *http_gnutls_make_path(char *buffer, size_t bufsize, const char *dirname, const char *filename, const char *ext);
49 static ssize_t http_gnutls_read(gnutls_transport_ptr_t ptr, void *data, size_t length);
50 static ssize_t http_gnutls_write(gnutls_transport_ptr_t ptr, const void *data, size_t length);
54 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
56 * @since CUPS 2.0/OS 10.10@
59 int /* O - 1 on success, 0 on failure */
60 cupsMakeServerCredentials(
61 const char *path, /* I - Path to keychain/directory */
62 const char *common_name, /* I - Common name */
63 int num_alt_names, /* I - Number of subject alternate names */
64 const char **alt_names, /* I - Subject Alternate Names */
65 time_t expiration_date) /* I - Expiration date */
67 gnutls_x509_crt_t crt; /* Self-signed certificate */
68 gnutls_x509_privkey_t key; /* Encryption private key */
69 char temp[1024], /* Temporary directory name */
70 crtfile[1024], /* Certificate filename */
71 keyfile[1024]; /* Private key filename */
72 cups_lang_t *language; /* Default language info */
73 cups_file_t *fp; /* Key/cert file */
74 unsigned char buffer[8192]; /* Buffer for x509 data */
75 size_t bytes; /* Number of bytes of data */
76 unsigned char serial[4]; /* Serial number buffer */
77 time_t curtime; /* Current time */
78 int result; /* Result of GNU TLS calls */
81 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));
88 path = http_gnutls_default_path(temp, sizeof(temp));
90 if (!path || !common_name)
92 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
96 http_gnutls_make_path(crtfile, sizeof(crtfile), path, common_name, "crt");
97 http_gnutls_make_path(keyfile, sizeof(keyfile), path, common_name, "key");
100 * Create the encryption key...
103 DEBUG_puts("1cupsMakeServerCredentials: Creating key pair.");
105 gnutls_x509_privkey_init(&key);
106 gnutls_x509_privkey_generate(key, GNUTLS_PK_RSA, 2048, 0);
108 DEBUG_puts("1cupsMakeServerCredentials: Key pair created.");
114 bytes = sizeof(buffer);
116 if ((result = gnutls_x509_privkey_export(key, GNUTLS_X509_FMT_PEM, buffer, &bytes)) < 0)
118 DEBUG_printf(("1cupsMakeServerCredentials: Unable to export private key: %s", gnutls_strerror(result)));
119 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, gnutls_strerror(result), 0);
120 gnutls_x509_privkey_deinit(key);
123 else if ((fp = cupsFileOpen(keyfile, "w")) != NULL)
125 DEBUG_printf(("1cupsMakeServerCredentials: Writing private key to \"%s\".", keyfile));
126 cupsFileWrite(fp, (char *)buffer, bytes);
131 DEBUG_printf(("1cupsMakeServerCredentials: Unable to create private key file \"%s\": %s", keyfile, strerror(errno)));
132 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
133 gnutls_x509_privkey_deinit(key);
138 * Create the self-signed certificate...
141 DEBUG_puts("1cupsMakeServerCredentials: Generating self-signed X.509 certificate.");
143 language = cupsLangDefault();
144 curtime = time(NULL);
145 serial[0] = curtime >> 24;
146 serial[1] = curtime >> 16;
147 serial[2] = curtime >> 8;
150 gnutls_x509_crt_init(&crt);
151 if (strlen(language->language) == 5)
152 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
153 language->language + 3, 2);
155 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
157 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COMMON_NAME, 0,
158 common_name, strlen(common_name));
159 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATION_NAME, 0,
160 common_name, strlen(common_name));
161 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME,
163 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME, 0,
165 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_LOCALITY_NAME, 0,
167 /* gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_PKCS9_EMAIL, 0,
168 ServerAdmin, strlen(ServerAdmin));*/
169 gnutls_x509_crt_set_key(crt, key);
170 gnutls_x509_crt_set_serial(crt, serial, sizeof(serial));
171 gnutls_x509_crt_set_activation_time(crt, curtime);
172 gnutls_x509_crt_set_expiration_time(crt, curtime + 10 * 365 * 86400);
173 gnutls_x509_crt_set_ca_status(crt, 0);
174 if (num_alt_names > 0)
175 gnutls_x509_crt_set_subject_alternative_name(crt, GNUTLS_SAN_DNSNAME, alt_names[0]);
176 gnutls_x509_crt_set_key_purpose_oid(crt, GNUTLS_KP_TLS_WWW_SERVER, 0);
177 gnutls_x509_crt_set_key_usage(crt, GNUTLS_KEY_KEY_ENCIPHERMENT);
178 gnutls_x509_crt_set_version(crt, 3);
180 bytes = sizeof(buffer);
181 if (gnutls_x509_crt_get_key_id(crt, 0, buffer, &bytes) >= 0)
182 gnutls_x509_crt_set_subject_key_id(crt, buffer, bytes);
184 gnutls_x509_crt_sign(crt, crt, key);
190 bytes = sizeof(buffer);
191 if ((result = gnutls_x509_crt_export(crt, GNUTLS_X509_FMT_PEM, buffer, &bytes)) < 0)
193 DEBUG_printf(("1cupsMakeServerCredentials: Unable to export public key and X.509 certificate: %s", gnutls_strerror(result)));
194 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, gnutls_strerror(result), 0);
195 gnutls_x509_crt_deinit(crt);
196 gnutls_x509_privkey_deinit(key);
199 else if ((fp = cupsFileOpen(crtfile, "w")) != NULL)
201 DEBUG_printf(("1cupsMakeServerCredentials: Writing public key and X.509 certificate to \"%s\".", crtfile));
202 cupsFileWrite(fp, (char *)buffer, bytes);
207 DEBUG_printf(("1cupsMakeServerCredentials: Unable to create public key and X.509 certificate file \"%s\": %s", crtfile, strerror(errno)));
208 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
209 gnutls_x509_crt_deinit(crt);
210 gnutls_x509_privkey_deinit(key);
218 gnutls_x509_crt_deinit(crt);
219 gnutls_x509_privkey_deinit(key);
221 DEBUG_puts("1cupsMakeServerCredentials: Successfully created credentials.");
228 * 'cupsSetServerCredentials()' - Set the default server credentials.
230 * Note: The server credentials are used by all threads in the running process.
231 * This function is threadsafe.
233 * @since CUPS 2.0/OS 10.10@
236 int /* O - 1 on success, 0 on failure */
237 cupsSetServerCredentials(
238 const char *path, /* I - Path to keychain/directory */
239 const char *common_name, /* I - Default common name for server */
240 int auto_create) /* I - 1 = automatically create self-signed certificates */
242 char temp[1024]; /* Default path buffer */
245 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path, common_name, auto_create));
248 * Use defaults as needed...
252 path = http_gnutls_default_path(temp, sizeof(temp));
255 * Range check input...
258 if (!path || !common_name)
260 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
264 _cupsMutexLock(&tls_mutex);
271 _cupsStrFree(tls_keypath);
274 _cupsStrFree(tls_common_name);
277 * Save the new values...
280 tls_keypath = _cupsStrAlloc(path);
281 tls_auto_create = auto_create;
282 tls_common_name = _cupsStrAlloc(common_name);
284 _cupsMutexUnlock(&tls_mutex);
291 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
292 * an encrypted connection.
294 * @since CUPS 1.5/macOS 10.7@
297 int /* O - Status of call (0 = success) */
299 http_t *http, /* I - Connection to server */
300 cups_array_t **credentials) /* O - Array of credentials */
302 unsigned count; /* Number of certificates */
303 const gnutls_datum_t *certs; /* Certificates */
306 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", http, credentials));
311 if (!http || !http->tls || !credentials)
314 *credentials = cupsArrayNew(NULL, NULL);
315 certs = gnutls_certificate_get_peers(http->tls, &count);
317 DEBUG_printf(("1httpCopyCredentials: certs=%p, count=%u", certs, count));
323 httpAddCredential(*credentials, certs->data, certs->size);
334 * '_httpCreateCredentials()' - Create credentials in the internal format.
337 http_tls_credentials_t /* O - Internal credentials */
338 _httpCreateCredentials(
339 cups_array_t *credentials) /* I - Array of credentials */
348 * '_httpFreeCredentials()' - Free internal credentials.
352 _httpFreeCredentials(
353 http_tls_credentials_t credentials) /* I - Internal credentials */
360 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
362 * @since CUPS 2.0/OS 10.10@
365 int /* O - 1 if valid, 0 otherwise */
366 httpCredentialsAreValidForName(
367 cups_array_t *credentials, /* I - Credentials */
368 const char *common_name) /* I - Name to check */
370 gnutls_x509_crt_t cert; /* Certificate */
371 int result = 0; /* Result */
374 cert = http_gnutls_create_credential((http_credential_t *)cupsArrayFirst(credentials));
377 result = gnutls_x509_crt_check_hostname(cert, common_name) != 0;
381 int i, /* Looping var */
382 count; /* Number of revoked certificates */
383 unsigned char cserial[1024], /* Certificate serial number */
384 rserial[1024]; /* Revoked serial number */
385 size_t cserial_size, /* Size of cert serial number */
386 rserial_size; /* Size of revoked serial number */
388 _cupsMutexLock(&tls_mutex);
390 count = gnutls_x509_crl_get_crt_count(tls_crl);
394 cserial_size = sizeof(cserial);
395 gnutls_x509_crt_get_serial(cert, cserial, &cserial_size);
397 for (i = 0; i < count; i ++)
399 rserial_size = sizeof(rserial);
400 if (!gnutls_x509_crl_get_crt_serial(tls_crl, i, rserial, &rserial_size, NULL) && cserial_size == rserial_size && !memcmp(cserial, rserial, rserial_size))
408 _cupsMutexUnlock(&tls_mutex);
411 gnutls_x509_crt_deinit(cert);
419 * 'httpCredentialsGetTrust()' - Return the trust of credentials.
421 * @since CUPS 2.0/OS 10.10@
424 http_trust_t /* O - Level of trust */
425 httpCredentialsGetTrust(
426 cups_array_t *credentials, /* I - Credentials */
427 const char *common_name) /* I - Common name for trust lookup */
429 http_trust_t trust = HTTP_TRUST_OK;
431 gnutls_x509_crt_t cert; /* Certificate */
432 cups_array_t *tcreds = NULL; /* Trusted credentials */
433 _cups_globals_t *cg = _cupsGlobals();
434 /* Per-thread globals */
439 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No common name specified."), 1);
440 return (HTTP_TRUST_UNKNOWN);
443 if ((cert = http_gnutls_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
445 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to create credentials from array."), 1);
446 return (HTTP_TRUST_UNKNOWN);
449 if (cg->any_root < 0)
452 http_gnutls_load_crl();
456 * Look this common name up in the default keychains...
459 httpLoadCredentials(NULL, &tcreds, common_name);
463 char credentials_str[1024], /* String for incoming credentials */
464 tcreds_str[1024]; /* String for saved credentials */
466 httpCredentialsString(credentials, credentials_str, sizeof(credentials_str));
467 httpCredentialsString(tcreds, tcreds_str, sizeof(tcreds_str));
469 if (strcmp(credentials_str, tcreds_str))
472 * Credentials don't match, let's look at the expiration date of the new
473 * credentials and allow if the new ones have a later expiration...
476 if (!cg->trust_first)
479 * Do not trust certificates on first use...
482 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Trust on first use is disabled."), 1);
484 trust = HTTP_TRUST_INVALID;
486 else if (httpCredentialsGetExpiration(credentials) <= httpCredentialsGetExpiration(tcreds))
489 * The new credentials are not newly issued...
492 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("New credentials are older than stored credentials."), 1);
494 trust = HTTP_TRUST_INVALID;
496 else if (!httpCredentialsAreValidForName(credentials, common_name))
499 * The common name does not match the issued certificate...
502 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("New credentials are not valid for name."), 1);
504 trust = HTTP_TRUST_INVALID;
506 else if (httpCredentialsGetExpiration(tcreds) < time(NULL))
509 * Save the renewed credentials...
512 trust = HTTP_TRUST_RENEWED;
514 httpSaveCredentials(NULL, credentials, common_name);
518 httpFreeCredentials(tcreds);
520 else if (cg->validate_certs && !httpCredentialsAreValidForName(credentials, common_name))
522 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No stored credentials, not valid for name."), 1);
523 trust = HTTP_TRUST_INVALID;
525 else if (!cg->trust_first)
528 * See if we have a site CA certificate we can compare...
531 if (!httpLoadCredentials(NULL, &tcreds, "site"))
533 if (cupsArrayCount(credentials) != (cupsArrayCount(tcreds) + 1))
536 * Certificate isn't directly generated from the CA cert...
539 trust = HTTP_TRUST_INVALID;
544 * Do a tail comparison of the two certificates...
547 http_credential_t *a, *b; /* Certificates */
549 for (a = (http_credential_t *)cupsArrayFirst(tcreds), b = (http_credential_t *)cupsArrayIndex(credentials, 1);
551 a = (http_credential_t *)cupsArrayNext(tcreds), b = (http_credential_t *)cupsArrayNext(credentials))
552 if (a->datalen != b->datalen || memcmp(a->data, b->data, a->datalen))
556 trust = HTTP_TRUST_INVALID;
559 if (trust != HTTP_TRUST_OK)
560 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Credentials do not validate against site CA certificate."), 1);
564 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Trust on first use is disabled."), 1);
565 trust = HTTP_TRUST_INVALID;
569 if (trust == HTTP_TRUST_OK && !cg->expired_certs)
571 time_t curtime; /* Current date/time */
574 if (curtime < gnutls_x509_crt_get_activation_time(cert) ||
575 curtime > gnutls_x509_crt_get_expiration_time(cert))
577 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Credentials have expired."), 1);
578 trust = HTTP_TRUST_EXPIRED;
582 if (trust == HTTP_TRUST_OK && !cg->any_root && cupsArrayCount(credentials) == 1)
584 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Self-signed credentials are blocked."), 1);
585 trust = HTTP_TRUST_INVALID;
588 gnutls_x509_crt_deinit(cert);
595 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
597 * @since CUPS 2.0/OS 10.10@
600 time_t /* O - Expiration date of credentials */
601 httpCredentialsGetExpiration(
602 cups_array_t *credentials) /* I - Credentials */
604 gnutls_x509_crt_t cert; /* Certificate */
605 time_t result = 0; /* Result */
608 cert = http_gnutls_create_credential((http_credential_t *)cupsArrayFirst(credentials));
611 result = gnutls_x509_crt_get_expiration_time(cert);
612 gnutls_x509_crt_deinit(cert);
620 * 'httpCredentialsString()' - Return a string representing the credentials.
622 * @since CUPS 2.0/OS 10.10@
625 size_t /* O - Total size of credentials string */
626 httpCredentialsString(
627 cups_array_t *credentials, /* I - Credentials */
628 char *buffer, /* I - Buffer or @code NULL@ */
629 size_t bufsize) /* I - Size of buffer */
631 http_credential_t *first; /* First certificate */
632 gnutls_x509_crt_t cert; /* Certificate */
635 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT ")", credentials, buffer, CUPS_LLCAST bufsize));
640 if (buffer && bufsize > 0)
643 if ((first = (http_credential_t *)cupsArrayFirst(credentials)) != NULL &&
644 (cert = http_gnutls_create_credential(first)) != NULL)
646 char name[256]; /* Common name associated with cert */
647 size_t namelen; /* Length of name */
648 time_t expiration; /* Expiration date of cert */
649 _cups_md5_state_t md5_state; /* MD5 state */
650 unsigned char md5_digest[16]; /* MD5 result */
652 namelen = sizeof(name) - 1;
653 if (gnutls_x509_crt_get_dn_by_oid(cert, GNUTLS_OID_X520_COMMON_NAME, 0, 0, name, &namelen) >= 0)
654 name[namelen] = '\0';
656 strlcpy(name, "unknown", sizeof(name));
658 expiration = gnutls_x509_crt_get_expiration_time(cert);
660 _cupsMD5Init(&md5_state);
661 _cupsMD5Append(&md5_state, first->data, (int)first->datalen);
662 _cupsMD5Finish(&md5_state, md5_digest);
664 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]);
666 gnutls_x509_crt_deinit(cert);
669 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer));
671 return (strlen(buffer));
676 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
678 * @since CUPS 2.0/OS 10.10@
681 int /* O - 0 on success, -1 on error */
683 const char *path, /* I - Keychain/PKCS#12 path */
684 cups_array_t **credentials, /* IO - Credentials */
685 const char *common_name) /* I - Common name for credentials */
687 cups_file_t *fp; /* Certificate file */
688 char filename[1024], /* filename.crt */
689 temp[1024], /* Temporary string */
690 line[256]; /* Base64-encoded line */
691 unsigned char *data = NULL; /* Buffer for cert data */
692 size_t alloc_data = 0, /* Bytes allocated */
693 num_data = 0; /* Bytes used */
694 int decoded; /* Bytes decoded */
695 int in_certificate = 0;
696 /* In a certificate? */
699 if (!credentials || !common_name)
703 path = http_gnutls_default_path(temp, sizeof(temp));
707 http_gnutls_make_path(filename, sizeof(filename), path, common_name, "crt");
709 if ((fp = cupsFileOpen(filename, "r")) == NULL)
712 while (cupsFileGets(fp, line, sizeof(line)))
714 if (!strcmp(line, "-----BEGIN CERTIFICATE-----"))
719 * Missing END CERTIFICATE...
722 httpFreeCredentials(*credentials);
729 else if (!strcmp(line, "-----END CERTIFICATE-----"))
731 if (!in_certificate || !num_data)
737 httpFreeCredentials(*credentials);
743 *credentials = cupsArrayNew(NULL, NULL);
745 if (httpAddCredential(*credentials, data, num_data))
747 httpFreeCredentials(*credentials);
755 else if (in_certificate)
765 else if ((num_data + strlen(line)) >= alloc_data)
767 unsigned char *tdata = realloc(data, alloc_data + 1024);
768 /* Expanded buffer */
772 httpFreeCredentials(*credentials);
781 decoded = alloc_data - num_data;
782 httpDecode64_2((char *)data + num_data, &decoded, line);
783 num_data += (size_t)decoded;
792 * Missing END CERTIFICATE...
795 httpFreeCredentials(*credentials);
802 return (*credentials ? 0 : -1);
807 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
809 * @since CUPS 2.0/OS 10.10@
812 int /* O - -1 on error, 0 on success */
814 const char *path, /* I - Keychain/PKCS#12 path */
815 cups_array_t *credentials, /* I - Credentials */
816 const char *common_name) /* I - Common name for credentials */
818 cups_file_t *fp; /* Certificate file */
819 char filename[1024], /* filename.crt */
820 nfilename[1024],/* filename.crt.N */
821 temp[1024], /* Temporary string */
822 line[256]; /* Base64-encoded line */
823 const unsigned char *ptr; /* Pointer into certificate */
824 ssize_t remaining; /* Bytes left */
825 http_credential_t *cred; /* Current credential */
828 if (!credentials || !common_name)
832 path = http_gnutls_default_path(temp, sizeof(temp));
836 http_gnutls_make_path(filename, sizeof(filename), path, common_name, "crt");
837 snprintf(nfilename, sizeof(nfilename), "%s.N", filename);
839 if ((fp = cupsFileOpen(nfilename, "w")) == NULL)
842 fchmod(cupsFileNumber(fp), 0600);
844 for (cred = (http_credential_t *)cupsArrayFirst(credentials);
846 cred = (http_credential_t *)cupsArrayNext(credentials))
848 cupsFilePuts(fp, "-----BEGIN CERTIFICATE-----\n");
849 for (ptr = cred->data, remaining = (ssize_t)cred->datalen; remaining > 0; remaining -= 45, ptr += 45)
851 httpEncode64_2(line, sizeof(line), (char *)ptr, remaining > 45 ? 45 : remaining);
852 cupsFilePrintf(fp, "%s\n", line);
854 cupsFilePuts(fp, "-----END CERTIFICATE-----\n");
859 return (rename(nfilename, filename));
864 * 'http_gnutls_create_credential()' - Create a single credential in the internal format.
867 static gnutls_x509_crt_t /* O - Certificate */
868 http_gnutls_create_credential(
869 http_credential_t *credential) /* I - Credential */
871 int result; /* Result from GNU TLS */
872 gnutls_x509_crt_t cert; /* Certificate */
873 gnutls_datum_t datum; /* Data record */
876 DEBUG_printf(("3http_gnutls_create_credential(credential=%p)", credential));
881 if ((result = gnutls_x509_crt_init(&cert)) < 0)
883 DEBUG_printf(("4http_gnutls_create_credential: init error: %s", gnutls_strerror(result)));
887 datum.data = credential->data;
888 datum.size = credential->datalen;
890 if ((result = gnutls_x509_crt_import(cert, &datum, GNUTLS_X509_FMT_DER)) < 0)
892 DEBUG_printf(("4http_gnutls_create_credential: import error: %s", gnutls_strerror(result)));
894 gnutls_x509_crt_deinit(cert);
903 * 'http_gnutls_default_path()' - Get the default credential store path.
906 static const char * /* O - Path or NULL on error */
907 http_gnutls_default_path(char *buffer,/* I - Path buffer */
908 size_t bufsize)/* I - Size of path buffer */
910 const char *home = getenv("HOME"); /* HOME environment variable */
913 if (getuid() && home)
915 snprintf(buffer, bufsize, "%s/.cups", home);
916 if (access(buffer, 0))
918 DEBUG_printf(("1http_gnutls_default_path: Making directory \"%s\".", buffer));
919 if (mkdir(buffer, 0700))
921 DEBUG_printf(("1http_gnutls_default_path: Failed to make directory: %s", strerror(errno)));
926 snprintf(buffer, bufsize, "%s/.cups/ssl", home);
927 if (access(buffer, 0))
929 DEBUG_printf(("1http_gnutls_default_path: Making directory \"%s\".", buffer));
930 if (mkdir(buffer, 0700))
932 DEBUG_printf(("1http_gnutls_default_path: Failed to make directory: %s", strerror(errno)));
938 strlcpy(buffer, CUPS_SERVERROOT "/ssl", bufsize);
940 DEBUG_printf(("1http_gnutls_default_path: Using default path \"%s\".", buffer));
947 * 'http_gnutls_load_crl()' - Load the certificate revocation list, if any.
951 http_gnutls_load_crl(void)
953 _cupsMutexLock(&tls_mutex);
955 if (!gnutls_x509_crl_init(&tls_crl))
957 cups_file_t *fp; /* CRL file */
958 char filename[1024], /* site.crl */
959 line[256]; /* Base64-encoded line */
960 unsigned char *data = NULL; /* Buffer for cert data */
961 size_t alloc_data = 0, /* Bytes allocated */
962 num_data = 0; /* Bytes used */
963 int decoded; /* Bytes decoded */
964 gnutls_datum_t datum; /* Data record */
967 http_gnutls_make_path(filename, sizeof(filename), CUPS_SERVERROOT, "site", "crl");
969 if ((fp = cupsFileOpen(filename, "r")) != NULL)
971 while (cupsFileGets(fp, line, sizeof(line)))
973 if (!strcmp(line, "-----BEGIN X509 CRL-----"))
978 * Missing END X509 CRL...
984 else if (!strcmp(line, "-----END X509 CRL-----"))
996 datum.size = num_data;
998 gnutls_x509_crl_import(tls_crl, &datum, GNUTLS_X509_FMT_PEM);
1004 if (alloc_data == 0)
1006 data = malloc(2048);
1012 else if ((num_data + strlen(line)) >= alloc_data)
1014 unsigned char *tdata = realloc(data, alloc_data + 1024);
1015 /* Expanded buffer */
1024 decoded = alloc_data - num_data;
1025 httpDecode64_2((char *)data + num_data, &decoded, line);
1026 num_data += (size_t)decoded;
1037 _cupsMutexUnlock(&tls_mutex);
1042 * 'http_gnutls_make_path()' - Format a filename for a certificate or key file.
1045 static const char * /* O - Filename */
1046 http_gnutls_make_path(
1047 char *buffer, /* I - Filename buffer */
1048 size_t bufsize, /* I - Size of buffer */
1049 const char *dirname, /* I - Directory */
1050 const char *filename, /* I - Filename (usually hostname) */
1051 const char *ext) /* I - Extension */
1053 char *bufptr, /* Pointer into buffer */
1054 *bufend = buffer + bufsize - 1; /* End of buffer */
1057 snprintf(buffer, bufsize, "%s/", dirname);
1058 bufptr = buffer + strlen(buffer);
1060 while (*filename && bufptr < bufend)
1062 if (_cups_isalnum(*filename) || *filename == '-' || *filename == '.')
1063 *bufptr++ = *filename;
1070 if (bufptr < bufend)
1073 strlcpy(bufptr, ext, (size_t)(bufend - bufptr + 1));
1080 * 'http_gnutls_read()' - Read function for the GNU TLS library.
1083 static ssize_t /* O - Number of bytes read or -1 on error */
1085 gnutls_transport_ptr_t ptr, /* I - Connection to server */
1086 void *data, /* I - Buffer */
1087 size_t length) /* I - Number of bytes to read */
1089 http_t *http; /* HTTP connection */
1090 ssize_t bytes; /* Bytes read */
1093 DEBUG_printf(("6http_gnutls_read(ptr=%p, data=%p, length=%d)", ptr, data, (int)length));
1095 http = (http_t *)ptr;
1097 if (!http->blocking)
1100 * Make sure we have data before we read...
1103 while (!_httpWait(http, http->wait_value, 0))
1105 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
1108 http->error = ETIMEDOUT;
1113 bytes = recv(http->fd, data, length, 0);
1114 DEBUG_printf(("6http_gnutls_read: bytes=%d", (int)bytes));
1120 * 'http_gnutls_write()' - Write function for the GNU TLS library.
1123 static ssize_t /* O - Number of bytes written or -1 on error */
1125 gnutls_transport_ptr_t ptr, /* I - Connection to server */
1126 const void *data, /* I - Data buffer */
1127 size_t length) /* I - Number of bytes to write */
1129 ssize_t bytes; /* Bytes written */
1132 DEBUG_printf(("6http_gnutls_write(ptr=%p, data=%p, length=%d)", ptr, data,
1134 bytes = send(((http_t *)ptr)->fd, data, length, 0);
1135 DEBUG_printf(("http_gnutls_write: bytes=%d", (int)bytes));
1142 * '_httpTLSInitialize()' - Initialize the TLS stack.
1146 _httpTLSInitialize(void)
1149 * Initialize GNU TLS...
1152 gnutls_global_init();
1157 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
1160 size_t /* O - Bytes available */
1161 _httpTLSPending(http_t *http) /* I - HTTP connection */
1163 return (gnutls_record_check_pending(http->tls));
1168 * '_httpTLSRead()' - Read from a SSL/TLS connection.
1171 int /* O - Bytes read */
1172 _httpTLSRead(http_t *http, /* I - Connection to server */
1173 char *buf, /* I - Buffer to store data */
1174 int len) /* I - Length of buffer */
1176 ssize_t result; /* Return value */
1179 result = gnutls_record_recv(http->tls, buf, (size_t)len);
1181 if (result < 0 && !errno)
1184 * Convert GNU TLS error to errno value...
1189 case GNUTLS_E_INTERRUPTED :
1193 case GNUTLS_E_AGAIN :
1205 return ((int)result);
1210 * '_httpTLSSetCredentials()' - Set the TLS credentials.
1213 int /* O - Status of connection */
1214 _httpTLSSetCredentials(http_t *http) /* I - Connection to server */
1223 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
1227 _httpTLSSetOptions(int options) /* I - Options */
1229 tls_options = options;
1234 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
1237 int /* O - 0 on success, -1 on failure */
1238 _httpTLSStart(http_t *http) /* I - Connection to server */
1240 char hostname[256], /* Hostname */
1241 *hostptr; /* Pointer into hostname */
1242 int status; /* Status of handshake */
1243 gnutls_certificate_credentials_t *credentials;
1244 /* TLS credentials */
1245 char priority_string[1024];
1246 /* Priority string */
1249 DEBUG_printf(("3_httpTLSStart(http=%p)", http));
1251 if (tls_options < 0)
1253 DEBUG_puts("4_httpTLSStart: Setting defaults.");
1255 DEBUG_printf(("4_httpTLSStart: tls_options=%x", tls_options));
1258 if (http->mode == _HTTP_MODE_SERVER && !tls_keypath)
1260 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
1261 http->error = errno = EINVAL;
1262 http->status = HTTP_STATUS_ERROR;
1263 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Server credentials not set."), 1);
1268 credentials = (gnutls_certificate_credentials_t *)
1269 malloc(sizeof(gnutls_certificate_credentials_t));
1270 if (credentials == NULL)
1272 DEBUG_printf(("8_httpStartTLS: Unable to allocate credentials: %s",
1274 http->error = errno;
1275 http->status = HTTP_STATUS_ERROR;
1276 _cupsSetHTTPError(HTTP_STATUS_ERROR);
1281 gnutls_certificate_allocate_credentials(credentials);
1282 status = gnutls_init(&http->tls, http->mode == _HTTP_MODE_CLIENT ? GNUTLS_CLIENT : GNUTLS_SERVER);
1284 status = gnutls_set_default_priority(http->tls);
1289 http->status = HTTP_STATUS_ERROR;
1291 DEBUG_printf(("4_httpTLSStart: Unable to initialize common TLS parameters: %s", gnutls_strerror(status)));
1292 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, gnutls_strerror(status), 0);
1294 gnutls_deinit(http->tls);
1295 gnutls_certificate_free_credentials(*credentials);
1302 if (http->mode == _HTTP_MODE_CLIENT)
1305 * Client: get the hostname to use for TLS...
1308 if (httpAddrLocalhost(http->hostaddr))
1310 strlcpy(hostname, "localhost", sizeof(hostname));
1315 * Otherwise make sure the hostname we have does not end in a trailing dot.
1318 strlcpy(hostname, http->hostname, sizeof(hostname));
1319 if ((hostptr = hostname + strlen(hostname) - 1) >= hostname &&
1324 status = gnutls_server_name_set(http->tls, GNUTLS_NAME_DNS, hostname, strlen(hostname));
1329 * Server: get certificate and private key...
1332 char crtfile[1024], /* Certificate file */
1333 keyfile[1024]; /* Private key file */
1334 int have_creds = 0; /* Have credentials? */
1336 if (http->fields[HTTP_FIELD_HOST][0])
1339 * Use hostname for TLS upgrade...
1342 strlcpy(hostname, http->fields[HTTP_FIELD_HOST], sizeof(hostname));
1347 * Resolve hostname from connection address...
1350 http_addr_t addr; /* Connection address */
1351 socklen_t addrlen; /* Length of address */
1353 addrlen = sizeof(addr);
1354 if (getsockname(http->fd, (struct sockaddr *)&addr, &addrlen))
1356 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno)));
1359 else if (httpAddrLocalhost(&addr))
1363 httpAddrLookup(&addr, hostname, sizeof(hostname));
1364 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname));
1368 if (isdigit(hostname[0] & 255) || hostname[0] == '[')
1369 hostname[0] = '\0'; /* Don't allow numeric addresses */
1374 * First look in the CUPS keystore...
1377 http_gnutls_make_path(crtfile, sizeof(crtfile), tls_keypath, hostname, "crt");
1378 http_gnutls_make_path(keyfile, sizeof(keyfile), tls_keypath, hostname, "key");
1380 if (access(crtfile, R_OK) || access(keyfile, R_OK))
1383 * No CUPS-managed certs, look for CA certs...
1386 char cacrtfile[1024], cakeyfile[1024]; /* CA cert files */
1388 snprintf(cacrtfile, sizeof(cacrtfile), "/etc/letsencrypt/live/%s/fullchain.pem", hostname);
1389 snprintf(cakeyfile, sizeof(cakeyfile), "/etc/letsencrypt/live/%s/privkey.pem", hostname);
1391 if ((access(cacrtfile, R_OK) || access(cakeyfile, R_OK)) && (hostptr = strchr(hostname, '.')) != NULL)
1394 * Try just domain name...
1398 if (strchr(hostptr, '.'))
1400 snprintf(cacrtfile, sizeof(cacrtfile), "/etc/letsencrypt/live/%s/fullchain.pem", hostptr);
1401 snprintf(cakeyfile, sizeof(cakeyfile), "/etc/letsencrypt/live/%s/privkey.pem", hostptr);
1405 if (!access(cacrtfile, R_OK) && !access(cakeyfile, R_OK))
1408 * Use the CA certs...
1411 strlcpy(crtfile, cacrtfile, sizeof(crtfile));
1412 strlcpy(keyfile, cakeyfile, sizeof(keyfile));
1416 have_creds = !access(crtfile, R_OK) && !access(keyfile, R_OK);
1418 else if (tls_common_name)
1421 * First look in the CUPS keystore...
1424 http_gnutls_make_path(crtfile, sizeof(crtfile), tls_keypath, tls_common_name, "crt");
1425 http_gnutls_make_path(keyfile, sizeof(keyfile), tls_keypath, tls_common_name, "key");
1427 if (access(crtfile, R_OK) || access(keyfile, R_OK))
1430 * No CUPS-managed certs, look for CA certs...
1433 char cacrtfile[1024], cakeyfile[1024]; /* CA cert files */
1435 snprintf(cacrtfile, sizeof(cacrtfile), "/etc/letsencrypt/live/%s/fullchain.pem", tls_common_name);
1436 snprintf(cakeyfile, sizeof(cakeyfile), "/etc/letsencrypt/live/%s/privkey.pem", tls_common_name);
1438 if ((access(cacrtfile, R_OK) || access(cakeyfile, R_OK)) && (hostptr = strchr(tls_common_name, '.')) != NULL)
1441 * Try just domain name...
1445 if (strchr(hostptr, '.'))
1447 snprintf(cacrtfile, sizeof(cacrtfile), "/etc/letsencrypt/live/%s/fullchain.pem", hostptr);
1448 snprintf(cakeyfile, sizeof(cakeyfile), "/etc/letsencrypt/live/%s/privkey.pem", hostptr);
1452 if (!access(cacrtfile, R_OK) && !access(cakeyfile, R_OK))
1455 * Use the CA certs...
1458 strlcpy(crtfile, cacrtfile, sizeof(crtfile));
1459 strlcpy(keyfile, cakeyfile, sizeof(keyfile));
1463 have_creds = !access(crtfile, R_OK) && !access(keyfile, R_OK);
1466 if (!have_creds && tls_auto_create && (hostname[0] || tls_common_name))
1468 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname[0] ? hostname : tls_common_name));
1470 if (!cupsMakeServerCredentials(tls_keypath, hostname[0] ? hostname : tls_common_name, 0, NULL, time(NULL) + 365 * 86400))
1472 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
1473 http->error = errno = EINVAL;
1474 http->status = HTTP_STATUS_ERROR;
1475 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to create server credentials."), 1);
1481 DEBUG_printf(("4_httpTLSStart: Using certificate \"%s\" and private key \"%s\".", crtfile, keyfile));
1484 status = gnutls_certificate_set_x509_key_file(*credentials, crtfile, keyfile, GNUTLS_X509_FMT_PEM);
1488 status = gnutls_credentials_set(http->tls, GNUTLS_CRD_CERTIFICATE, *credentials);
1493 http->status = HTTP_STATUS_ERROR;
1495 DEBUG_printf(("4_httpTLSStart: Unable to complete client/server setup: %s", gnutls_strerror(status)));
1496 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, gnutls_strerror(status), 0);
1498 gnutls_deinit(http->tls);
1499 gnutls_certificate_free_credentials(*credentials);
1506 strlcpy(priority_string, "NORMAL", sizeof(priority_string));
1508 if (tls_options & _HTTP_TLS_DENY_TLS10)
1509 strlcat(priority_string, ":+VERS-TLS-ALL:-VERS-TLS1.0:-VERS-SSL3.0", sizeof(priority_string));
1510 else if (tls_options & _HTTP_TLS_ALLOW_SSL3)
1511 strlcat(priority_string, ":+VERS-TLS-ALL", sizeof(priority_string));
1513 strlcat(priority_string, ":+VERS-TLS-ALL:-VERS-SSL3.0", sizeof(priority_string));
1515 if (!(tls_options & _HTTP_TLS_ALLOW_RC4))
1516 strlcat(priority_string, ":-ARCFOUR-128", sizeof(priority_string));
1518 if (!(tls_options & _HTTP_TLS_ALLOW_DH))
1519 strlcat(priority_string, ":!ANON-DH", sizeof(priority_string));
1521 #ifdef HAVE_GNUTLS_PRIORITY_SET_DIRECT
1522 gnutls_priority_set_direct(http->tls, priority_string, NULL);
1525 gnutls_priority_t priority; /* Priority */
1527 gnutls_priority_init(&priority, priority_string, NULL);
1528 gnutls_priority_set(http->tls, priority);
1529 gnutls_priority_deinit(priority);
1530 #endif /* HAVE_GNUTLS_PRIORITY_SET_DIRECT */
1532 gnutls_transport_set_ptr(http->tls, (gnutls_transport_ptr_t)http);
1533 gnutls_transport_set_pull_function(http->tls, http_gnutls_read);
1534 #ifdef HAVE_GNUTLS_TRANSPORT_SET_PULL_TIMEOUT_FUNCTION
1535 gnutls_transport_set_pull_timeout_function(http->tls, (gnutls_pull_timeout_func)httpWait);
1536 #endif /* HAVE_GNUTLS_TRANSPORT_SET_PULL_TIMEOUT_FUNCTION */
1537 gnutls_transport_set_push_function(http->tls, http_gnutls_write);
1539 while ((status = gnutls_handshake(http->tls)) != GNUTLS_E_SUCCESS)
1541 DEBUG_printf(("5_httpStartTLS: gnutls_handshake returned %d (%s)",
1542 status, gnutls_strerror(status)));
1544 if (gnutls_error_is_fatal(status))
1547 http->status = HTTP_STATUS_ERROR;
1549 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, gnutls_strerror(status), 0);
1551 gnutls_deinit(http->tls);
1552 gnutls_certificate_free_credentials(*credentials);
1560 http->tls_credentials = credentials;
1567 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1571 _httpTLSStop(http_t *http) /* I - Connection to server */
1573 int error; /* Error code */
1576 error = gnutls_bye(http->tls, http->mode == _HTTP_MODE_CLIENT ? GNUTLS_SHUT_RDWR : GNUTLS_SHUT_WR);
1577 if (error != GNUTLS_E_SUCCESS)
1578 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, gnutls_strerror(errno), 0);
1580 gnutls_deinit(http->tls);
1583 if (http->tls_credentials)
1585 gnutls_certificate_free_credentials(*(http->tls_credentials));
1586 free(http->tls_credentials);
1587 http->tls_credentials = NULL;
1593 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1596 int /* O - Bytes written */
1597 _httpTLSWrite(http_t *http, /* I - Connection to server */
1598 const char *buf, /* I - Buffer holding data */
1599 int len) /* I - Length of buffer */
1601 ssize_t result; /* Return value */
1604 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http, buf, len));
1606 result = gnutls_record_send(http->tls, buf, (size_t)len);
1608 if (result < 0 && !errno)
1611 * Convert GNU TLS error to errno value...
1616 case GNUTLS_E_INTERRUPTED :
1620 case GNUTLS_E_AGAIN :
1632 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result));
1634 return ((int)result);