2 * TLS support code for CUPS using GNU TLS.
4 * Copyright 2007-2017 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 * 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; /* Auto-create self-signed certs? */
30 static char *tls_common_name
= NULL
; /* Default common name */
31 static gnutls_x509_crl_t tls_crl
= NULL
; /* Certificate revocation list */
32 static char *tls_keypath
= NULL
; /* Server cert keychain path */
33 static _cups_mutex_t tls_mutex
= _CUPS_MUTEX_INITIALIZER
; /* Mutex for keychain/certs */
34 static unsigned int tls_options
= _HTTP_TLS_NONE
; /* Options for TLS connections */
41 static gnutls_x509_crt_t
http_gnutls_create_credential(http_credential_t
*credential
);
42 static const char *http_gnutls_default_path(char *buffer
, size_t bufsize
);
43 static void http_gnutls_load_crl(void);
44 static const char *http_gnutls_make_path(char *buffer
, size_t bufsize
, const char *dirname
, const char *filename
, const char *ext
);
45 static ssize_t
http_gnutls_read(gnutls_transport_ptr_t ptr
, void *data
, size_t length
);
46 static ssize_t
http_gnutls_write(gnutls_transport_ptr_t ptr
, const void *data
, size_t length
);
50 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
52 * @since CUPS 2.0/OS 10.10@
55 int /* O - 1 on success, 0 on failure */
56 cupsMakeServerCredentials(
57 const char *path
, /* I - Path to keychain/directory */
58 const char *common_name
, /* I - Common name */
59 int num_alt_names
, /* I - Number of subject alternate names */
60 const char **alt_names
, /* I - Subject Alternate Names */
61 time_t expiration_date
) /* I - Expiration date */
63 gnutls_x509_crt_t crt
; /* Self-signed certificate */
64 gnutls_x509_privkey_t key
; /* Encryption private key */
65 char temp
[1024], /* Temporary directory name */
66 crtfile
[1024], /* Certificate filename */
67 keyfile
[1024]; /* Private key filename */
68 cups_lang_t
*language
; /* Default language info */
69 cups_file_t
*fp
; /* Key/cert file */
70 unsigned char buffer
[8192]; /* Buffer for x509 data */
71 size_t bytes
; /* Number of bytes of data */
72 unsigned char serial
[4]; /* Serial number buffer */
73 time_t curtime
; /* Current time */
74 int result
; /* Result of GNU TLS calls */
77 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 path
= http_gnutls_default_path(temp
, sizeof(temp
));
86 if (!path
|| !common_name
)
88 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
92 http_gnutls_make_path(crtfile
, sizeof(crtfile
), path
, common_name
, "crt");
93 http_gnutls_make_path(keyfile
, sizeof(keyfile
), path
, common_name
, "key");
96 * Create the encryption key...
99 DEBUG_puts("1cupsMakeServerCredentials: Creating key pair.");
101 gnutls_x509_privkey_init(&key
);
102 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
104 DEBUG_puts("1cupsMakeServerCredentials: Key pair created.");
110 bytes
= sizeof(buffer
);
112 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
, buffer
, &bytes
)) < 0)
114 DEBUG_printf(("1cupsMakeServerCredentials: Unable to export private key: %s", gnutls_strerror(result
)));
115 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gnutls_strerror(result
), 0);
116 gnutls_x509_privkey_deinit(key
);
119 else if ((fp
= cupsFileOpen(keyfile
, "w")) != NULL
)
121 DEBUG_printf(("1cupsMakeServerCredentials: Writing private key to \"%s\".", keyfile
));
122 cupsFileWrite(fp
, (char *)buffer
, bytes
);
127 DEBUG_printf(("1cupsMakeServerCredentials: Unable to create private key file \"%s\": %s", keyfile
, strerror(errno
)));
128 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
129 gnutls_x509_privkey_deinit(key
);
134 * Create the self-signed certificate...
137 DEBUG_puts("1cupsMakeServerCredentials: Generating self-signed X.509 certificate.");
139 language
= cupsLangDefault();
140 curtime
= time(NULL
);
141 serial
[0] = curtime
>> 24;
142 serial
[1] = curtime
>> 16;
143 serial
[2] = curtime
>> 8;
146 gnutls_x509_crt_init(&crt
);
147 if (strlen(language
->language
) == 5)
148 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
149 language
->language
+ 3, 2);
151 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
153 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
154 common_name
, strlen(common_name
));
155 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
156 common_name
, strlen(common_name
));
157 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
159 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
161 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
163 /* gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_PKCS9_EMAIL, 0,
164 ServerAdmin, strlen(ServerAdmin));*/
165 gnutls_x509_crt_set_key(crt
, key
);
166 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
167 gnutls_x509_crt_set_activation_time(crt
, curtime
);
168 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
169 gnutls_x509_crt_set_ca_status(crt
, 0);
170 if (num_alt_names
> 0)
171 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
, alt_names
[0]);
172 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
173 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
174 gnutls_x509_crt_set_version(crt
, 3);
176 bytes
= sizeof(buffer
);
177 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
178 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
180 gnutls_x509_crt_sign(crt
, crt
, key
);
186 bytes
= sizeof(buffer
);
187 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
, buffer
, &bytes
)) < 0)
189 DEBUG_printf(("1cupsMakeServerCredentials: Unable to export public key and X.509 certificate: %s", gnutls_strerror(result
)));
190 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gnutls_strerror(result
), 0);
191 gnutls_x509_crt_deinit(crt
);
192 gnutls_x509_privkey_deinit(key
);
195 else if ((fp
= cupsFileOpen(crtfile
, "w")) != NULL
)
197 DEBUG_printf(("1cupsMakeServerCredentials: Writing public key and X.509 certificate to \"%s\".", crtfile
));
198 cupsFileWrite(fp
, (char *)buffer
, bytes
);
203 DEBUG_printf(("1cupsMakeServerCredentials: Unable to create public key and X.509 certificate file \"%s\": %s", crtfile
, strerror(errno
)));
204 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
205 gnutls_x509_crt_deinit(crt
);
206 gnutls_x509_privkey_deinit(key
);
214 gnutls_x509_crt_deinit(crt
);
215 gnutls_x509_privkey_deinit(key
);
217 DEBUG_puts("1cupsMakeServerCredentials: Successfully created credentials.");
224 * 'cupsSetServerCredentials()' - Set the default server credentials.
226 * Note: The server credentials are used by all threads in the running process.
227 * This function is threadsafe.
229 * @since CUPS 2.0/OS 10.10@
232 int /* O - 1 on success, 0 on failure */
233 cupsSetServerCredentials(
234 const char *path
, /* I - Path to keychain/directory */
235 const char *common_name
, /* I - Default common name for server */
236 int auto_create
) /* I - 1 = automatically create self-signed certificates */
238 char temp
[1024]; /* Default path buffer */
241 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path
, common_name
, auto_create
));
244 * Use defaults as needed...
248 path
= http_gnutls_default_path(temp
, sizeof(temp
));
251 * Range check input...
254 if (!path
|| !common_name
)
256 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
260 _cupsMutexLock(&tls_mutex
);
267 _cupsStrFree(tls_keypath
);
270 _cupsStrFree(tls_common_name
);
273 * Save the new values...
276 tls_keypath
= _cupsStrAlloc(path
);
277 tls_auto_create
= auto_create
;
278 tls_common_name
= _cupsStrAlloc(common_name
);
280 _cupsMutexUnlock(&tls_mutex
);
287 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
288 * an encrypted connection.
290 * @since CUPS 1.5/macOS 10.7@
293 int /* O - Status of call (0 = success) */
295 http_t
*http
, /* I - Connection to server */
296 cups_array_t
**credentials
) /* O - Array of credentials */
298 unsigned count
; /* Number of certificates */
299 const gnutls_datum_t
*certs
; /* Certificates */
302 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", http
, credentials
));
307 if (!http
|| !http
->tls
|| !credentials
)
310 *credentials
= cupsArrayNew(NULL
, NULL
);
311 certs
= gnutls_certificate_get_peers(http
->tls
, &count
);
313 DEBUG_printf(("1httpCopyCredentials: certs=%p, count=%u", certs
, count
));
319 httpAddCredential(*credentials
, certs
->data
, certs
->size
);
330 * '_httpCreateCredentials()' - Create credentials in the internal format.
333 http_tls_credentials_t
/* O - Internal credentials */
334 _httpCreateCredentials(
335 cups_array_t
*credentials
) /* I - Array of credentials */
344 * '_httpFreeCredentials()' - Free internal credentials.
348 _httpFreeCredentials(
349 http_tls_credentials_t credentials
) /* I - Internal credentials */
356 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
358 * @since CUPS 2.0/OS 10.10@
361 int /* O - 1 if valid, 0 otherwise */
362 httpCredentialsAreValidForName(
363 cups_array_t
*credentials
, /* I - Credentials */
364 const char *common_name
) /* I - Name to check */
366 gnutls_x509_crt_t cert
; /* Certificate */
367 int result
= 0; /* Result */
370 cert
= http_gnutls_create_credential((http_credential_t
*)cupsArrayFirst(credentials
));
373 result
= gnutls_x509_crt_check_hostname(cert
, common_name
) != 0;
377 int i
, /* Looping var */
378 count
; /* Number of revoked certificates */
379 unsigned char cserial
[1024], /* Certificate serial number */
380 rserial
[1024]; /* Revoked serial number */
381 size_t cserial_size
, /* Size of cert serial number */
382 rserial_size
; /* Size of revoked serial number */
384 _cupsMutexLock(&tls_mutex
);
386 count
= gnutls_x509_crl_get_crt_count(tls_crl
);
390 cserial_size
= sizeof(cserial
);
391 gnutls_x509_crt_get_serial(cert
, cserial
, &cserial_size
);
393 for (i
= 0; i
< count
; i
++)
395 rserial_size
= sizeof(rserial
);
396 if (!gnutls_x509_crl_get_crt_serial(tls_crl
, (unsigned)i
, rserial
, &rserial_size
, NULL
) && cserial_size
== rserial_size
&& !memcmp(cserial
, rserial
, rserial_size
))
404 _cupsMutexUnlock(&tls_mutex
);
407 gnutls_x509_crt_deinit(cert
);
415 * 'httpCredentialsGetTrust()' - Return the trust of credentials.
417 * @since CUPS 2.0/OS 10.10@
420 http_trust_t
/* O - Level of trust */
421 httpCredentialsGetTrust(
422 cups_array_t
*credentials
, /* I - Credentials */
423 const char *common_name
) /* I - Common name for trust lookup */
425 http_trust_t trust
= HTTP_TRUST_OK
;
427 gnutls_x509_crt_t cert
; /* Certificate */
428 cups_array_t
*tcreds
= NULL
; /* Trusted credentials */
429 _cups_globals_t
*cg
= _cupsGlobals();
430 /* Per-thread globals */
435 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No common name specified."), 1);
436 return (HTTP_TRUST_UNKNOWN
);
439 if ((cert
= http_gnutls_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
441 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to create credentials from array."), 1);
442 return (HTTP_TRUST_UNKNOWN
);
445 if (cg
->any_root
< 0)
448 http_gnutls_load_crl();
452 * Look this common name up in the default keychains...
455 httpLoadCredentials(NULL
, &tcreds
, common_name
);
459 char credentials_str
[1024], /* String for incoming credentials */
460 tcreds_str
[1024]; /* String for saved credentials */
462 httpCredentialsString(credentials
, credentials_str
, sizeof(credentials_str
));
463 httpCredentialsString(tcreds
, tcreds_str
, sizeof(tcreds_str
));
465 if (strcmp(credentials_str
, tcreds_str
))
468 * Credentials don't match, let's look at the expiration date of the new
469 * credentials and allow if the new ones have a later expiration...
472 if (!cg
->trust_first
)
475 * Do not trust certificates on first use...
478 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Trust on first use is disabled."), 1);
480 trust
= HTTP_TRUST_INVALID
;
482 else if (httpCredentialsGetExpiration(credentials
) <= httpCredentialsGetExpiration(tcreds
))
485 * The new credentials are not newly issued...
488 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("New credentials are older than stored credentials."), 1);
490 trust
= HTTP_TRUST_INVALID
;
492 else if (!httpCredentialsAreValidForName(credentials
, common_name
))
495 * The common name does not match the issued certificate...
498 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("New credentials are not valid for name."), 1);
500 trust
= HTTP_TRUST_INVALID
;
502 else if (httpCredentialsGetExpiration(tcreds
) < time(NULL
))
505 * Save the renewed credentials...
508 trust
= HTTP_TRUST_RENEWED
;
510 httpSaveCredentials(NULL
, credentials
, common_name
);
514 httpFreeCredentials(tcreds
);
516 else if (cg
->validate_certs
&& !httpCredentialsAreValidForName(credentials
, common_name
))
518 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No stored credentials, not valid for name."), 1);
519 trust
= HTTP_TRUST_INVALID
;
521 else if (!cg
->trust_first
)
524 * See if we have a site CA certificate we can compare...
527 if (!httpLoadCredentials(NULL
, &tcreds
, "site"))
529 if (cupsArrayCount(credentials
) != (cupsArrayCount(tcreds
) + 1))
532 * Certificate isn't directly generated from the CA cert...
535 trust
= HTTP_TRUST_INVALID
;
540 * Do a tail comparison of the two certificates...
543 http_credential_t
*a
, *b
; /* Certificates */
545 for (a
= (http_credential_t
*)cupsArrayFirst(tcreds
), b
= (http_credential_t
*)cupsArrayIndex(credentials
, 1);
547 a
= (http_credential_t
*)cupsArrayNext(tcreds
), b
= (http_credential_t
*)cupsArrayNext(credentials
))
548 if (a
->datalen
!= b
->datalen
|| memcmp(a
->data
, b
->data
, a
->datalen
))
552 trust
= HTTP_TRUST_INVALID
;
555 if (trust
!= HTTP_TRUST_OK
)
556 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Credentials do not validate against site CA certificate."), 1);
560 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Trust on first use is disabled."), 1);
561 trust
= HTTP_TRUST_INVALID
;
565 if (trust
== HTTP_TRUST_OK
&& !cg
->expired_certs
)
567 time_t curtime
; /* Current date/time */
570 if (curtime
< gnutls_x509_crt_get_activation_time(cert
) ||
571 curtime
> gnutls_x509_crt_get_expiration_time(cert
))
573 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Credentials have expired."), 1);
574 trust
= HTTP_TRUST_EXPIRED
;
578 if (trust
== HTTP_TRUST_OK
&& !cg
->any_root
&& cupsArrayCount(credentials
) == 1)
580 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Self-signed credentials are blocked."), 1);
581 trust
= HTTP_TRUST_INVALID
;
584 gnutls_x509_crt_deinit(cert
);
591 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
593 * @since CUPS 2.0/OS 10.10@
596 time_t /* O - Expiration date of credentials */
597 httpCredentialsGetExpiration(
598 cups_array_t
*credentials
) /* I - Credentials */
600 gnutls_x509_crt_t cert
; /* Certificate */
601 time_t result
= 0; /* Result */
604 cert
= http_gnutls_create_credential((http_credential_t
*)cupsArrayFirst(credentials
));
607 result
= gnutls_x509_crt_get_expiration_time(cert
);
608 gnutls_x509_crt_deinit(cert
);
616 * 'httpCredentialsString()' - Return a string representing the credentials.
618 * @since CUPS 2.0/OS 10.10@
621 size_t /* O - Total size of credentials string */
622 httpCredentialsString(
623 cups_array_t
*credentials
, /* I - Credentials */
624 char *buffer
, /* I - Buffer or @code NULL@ */
625 size_t bufsize
) /* I - Size of buffer */
627 http_credential_t
*first
; /* First certificate */
628 gnutls_x509_crt_t cert
; /* Certificate */
631 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT
")", credentials
, buffer
, CUPS_LLCAST bufsize
));
636 if (buffer
&& bufsize
> 0)
639 if ((first
= (http_credential_t
*)cupsArrayFirst(credentials
)) != NULL
&&
640 (cert
= http_gnutls_create_credential(first
)) != NULL
)
642 char name
[256]; /* Common name associated with cert */
643 size_t namelen
; /* Length of name */
644 time_t expiration
; /* Expiration date of cert */
645 _cups_md5_state_t md5_state
; /* MD5 state */
646 unsigned char md5_digest
[16]; /* MD5 result */
648 namelen
= sizeof(name
) - 1;
649 if (gnutls_x509_crt_get_dn_by_oid(cert
, GNUTLS_OID_X520_COMMON_NAME
, 0, 0, name
, &namelen
) >= 0)
650 name
[namelen
] = '\0';
652 strlcpy(name
, "unknown", sizeof(name
));
654 expiration
= gnutls_x509_crt_get_expiration_time(cert
);
656 _cupsMD5Init(&md5_state
);
657 _cupsMD5Append(&md5_state
, first
->data
, (int)first
->datalen
);
658 _cupsMD5Finish(&md5_state
, md5_digest
);
660 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]);
662 gnutls_x509_crt_deinit(cert
);
665 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer
));
667 return (strlen(buffer
));
672 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
674 * @since CUPS 2.0/OS 10.10@
677 int /* O - 0 on success, -1 on error */
679 const char *path
, /* I - Keychain/PKCS#12 path */
680 cups_array_t
**credentials
, /* IO - Credentials */
681 const char *common_name
) /* I - Common name for credentials */
683 cups_file_t
*fp
; /* Certificate file */
684 char filename
[1024], /* filename.crt */
685 temp
[1024], /* Temporary string */
686 line
[256]; /* Base64-encoded line */
687 unsigned char *data
= NULL
; /* Buffer for cert data */
688 size_t alloc_data
= 0, /* Bytes allocated */
689 num_data
= 0; /* Bytes used */
690 int decoded
; /* Bytes decoded */
691 int in_certificate
= 0;
692 /* In a certificate? */
695 if (!credentials
|| !common_name
)
699 path
= http_gnutls_default_path(temp
, sizeof(temp
));
703 http_gnutls_make_path(filename
, sizeof(filename
), path
, common_name
, "crt");
705 if ((fp
= cupsFileOpen(filename
, "r")) == NULL
)
708 while (cupsFileGets(fp
, line
, sizeof(line
)))
710 if (!strcmp(line
, "-----BEGIN CERTIFICATE-----"))
715 * Missing END CERTIFICATE...
718 httpFreeCredentials(*credentials
);
725 else if (!strcmp(line
, "-----END CERTIFICATE-----"))
727 if (!in_certificate
|| !num_data
)
733 httpFreeCredentials(*credentials
);
739 *credentials
= cupsArrayNew(NULL
, NULL
);
741 if (httpAddCredential(*credentials
, data
, num_data
))
743 httpFreeCredentials(*credentials
);
751 else if (in_certificate
)
761 else if ((num_data
+ strlen(line
)) >= alloc_data
)
763 unsigned char *tdata
= realloc(data
, alloc_data
+ 1024);
764 /* Expanded buffer */
768 httpFreeCredentials(*credentials
);
777 decoded
= alloc_data
- num_data
;
778 httpDecode64_2((char *)data
+ num_data
, &decoded
, line
);
779 num_data
+= (size_t)decoded
;
788 * Missing END CERTIFICATE...
791 httpFreeCredentials(*credentials
);
798 return (*credentials
? 0 : -1);
803 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
805 * @since CUPS 2.0/OS 10.10@
808 int /* O - -1 on error, 0 on success */
810 const char *path
, /* I - Keychain/PKCS#12 path */
811 cups_array_t
*credentials
, /* I - Credentials */
812 const char *common_name
) /* I - Common name for credentials */
814 cups_file_t
*fp
; /* Certificate file */
815 char filename
[1024], /* filename.crt */
816 nfilename
[1024],/* filename.crt.N */
817 temp
[1024], /* Temporary string */
818 line
[256]; /* Base64-encoded line */
819 const unsigned char *ptr
; /* Pointer into certificate */
820 ssize_t remaining
; /* Bytes left */
821 http_credential_t
*cred
; /* Current credential */
824 if (!credentials
|| !common_name
)
828 path
= http_gnutls_default_path(temp
, sizeof(temp
));
832 http_gnutls_make_path(filename
, sizeof(filename
), path
, common_name
, "crt");
833 snprintf(nfilename
, sizeof(nfilename
), "%s.N", filename
);
835 if ((fp
= cupsFileOpen(nfilename
, "w")) == NULL
)
838 fchmod(cupsFileNumber(fp
), 0600);
840 for (cred
= (http_credential_t
*)cupsArrayFirst(credentials
);
842 cred
= (http_credential_t
*)cupsArrayNext(credentials
))
844 cupsFilePuts(fp
, "-----BEGIN CERTIFICATE-----\n");
845 for (ptr
= cred
->data
, remaining
= (ssize_t
)cred
->datalen
; remaining
> 0; remaining
-= 45, ptr
+= 45)
847 httpEncode64_2(line
, sizeof(line
), (char *)ptr
, remaining
> 45 ? 45 : remaining
);
848 cupsFilePrintf(fp
, "%s\n", line
);
850 cupsFilePuts(fp
, "-----END CERTIFICATE-----\n");
855 return (rename(nfilename
, filename
));
860 * 'http_gnutls_create_credential()' - Create a single credential in the internal format.
863 static gnutls_x509_crt_t
/* O - Certificate */
864 http_gnutls_create_credential(
865 http_credential_t
*credential
) /* I - Credential */
867 int result
; /* Result from GNU TLS */
868 gnutls_x509_crt_t cert
; /* Certificate */
869 gnutls_datum_t datum
; /* Data record */
872 DEBUG_printf(("3http_gnutls_create_credential(credential=%p)", credential
));
877 if ((result
= gnutls_x509_crt_init(&cert
)) < 0)
879 DEBUG_printf(("4http_gnutls_create_credential: init error: %s", gnutls_strerror(result
)));
883 datum
.data
= credential
->data
;
884 datum
.size
= credential
->datalen
;
886 if ((result
= gnutls_x509_crt_import(cert
, &datum
, GNUTLS_X509_FMT_DER
)) < 0)
888 DEBUG_printf(("4http_gnutls_create_credential: import error: %s", gnutls_strerror(result
)));
890 gnutls_x509_crt_deinit(cert
);
899 * 'http_gnutls_default_path()' - Get the default credential store path.
902 static const char * /* O - Path or NULL on error */
903 http_gnutls_default_path(char *buffer
,/* I - Path buffer */
904 size_t bufsize
)/* I - Size of path buffer */
906 const char *home
= getenv("HOME"); /* HOME environment variable */
909 if (getuid() && home
)
911 snprintf(buffer
, bufsize
, "%s/.cups", home
);
912 if (access(buffer
, 0))
914 DEBUG_printf(("1http_gnutls_default_path: Making directory \"%s\".", buffer
));
915 if (mkdir(buffer
, 0700))
917 DEBUG_printf(("1http_gnutls_default_path: Failed to make directory: %s", strerror(errno
)));
922 snprintf(buffer
, bufsize
, "%s/.cups/ssl", home
);
923 if (access(buffer
, 0))
925 DEBUG_printf(("1http_gnutls_default_path: Making directory \"%s\".", buffer
));
926 if (mkdir(buffer
, 0700))
928 DEBUG_printf(("1http_gnutls_default_path: Failed to make directory: %s", strerror(errno
)));
934 strlcpy(buffer
, CUPS_SERVERROOT
"/ssl", bufsize
);
936 DEBUG_printf(("1http_gnutls_default_path: Using default path \"%s\".", buffer
));
943 * 'http_gnutls_load_crl()' - Load the certificate revocation list, if any.
947 http_gnutls_load_crl(void)
949 _cupsMutexLock(&tls_mutex
);
951 if (!gnutls_x509_crl_init(&tls_crl
))
953 cups_file_t
*fp
; /* CRL file */
954 char filename
[1024], /* site.crl */
955 line
[256]; /* Base64-encoded line */
956 unsigned char *data
= NULL
; /* Buffer for cert data */
957 size_t alloc_data
= 0, /* Bytes allocated */
958 num_data
= 0; /* Bytes used */
959 int decoded
; /* Bytes decoded */
960 gnutls_datum_t datum
; /* Data record */
963 http_gnutls_make_path(filename
, sizeof(filename
), CUPS_SERVERROOT
, "site", "crl");
965 if ((fp
= cupsFileOpen(filename
, "r")) != NULL
)
967 while (cupsFileGets(fp
, line
, sizeof(line
)))
969 if (!strcmp(line
, "-----BEGIN X509 CRL-----"))
974 * Missing END X509 CRL...
980 else if (!strcmp(line
, "-----END X509 CRL-----"))
992 datum
.size
= num_data
;
994 gnutls_x509_crl_import(tls_crl
, &datum
, GNUTLS_X509_FMT_PEM
);
1000 if (alloc_data
== 0)
1002 data
= malloc(2048);
1008 else if ((num_data
+ strlen(line
)) >= alloc_data
)
1010 unsigned char *tdata
= realloc(data
, alloc_data
+ 1024);
1011 /* Expanded buffer */
1020 decoded
= alloc_data
- num_data
;
1021 httpDecode64_2((char *)data
+ num_data
, &decoded
, line
);
1022 num_data
+= (size_t)decoded
;
1033 _cupsMutexUnlock(&tls_mutex
);
1038 * 'http_gnutls_make_path()' - Format a filename for a certificate or key file.
1041 static const char * /* O - Filename */
1042 http_gnutls_make_path(
1043 char *buffer
, /* I - Filename buffer */
1044 size_t bufsize
, /* I - Size of buffer */
1045 const char *dirname
, /* I - Directory */
1046 const char *filename
, /* I - Filename (usually hostname) */
1047 const char *ext
) /* I - Extension */
1049 char *bufptr
, /* Pointer into buffer */
1050 *bufend
= buffer
+ bufsize
- 1; /* End of buffer */
1053 snprintf(buffer
, bufsize
, "%s/", dirname
);
1054 bufptr
= buffer
+ strlen(buffer
);
1056 while (*filename
&& bufptr
< bufend
)
1058 if (_cups_isalnum(*filename
) || *filename
== '-' || *filename
== '.')
1059 *bufptr
++ = *filename
;
1066 if (bufptr
< bufend
)
1069 strlcpy(bufptr
, ext
, (size_t)(bufend
- bufptr
+ 1));
1076 * 'http_gnutls_read()' - Read function for the GNU TLS library.
1079 static ssize_t
/* O - Number of bytes read or -1 on error */
1081 gnutls_transport_ptr_t ptr
, /* I - Connection to server */
1082 void *data
, /* I - Buffer */
1083 size_t length
) /* I - Number of bytes to read */
1085 http_t
*http
; /* HTTP connection */
1086 ssize_t bytes
; /* Bytes read */
1089 DEBUG_printf(("6http_gnutls_read(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
1091 http
= (http_t
*)ptr
;
1093 if (!http
->blocking
)
1096 * Make sure we have data before we read...
1099 while (!_httpWait(http
, http
->wait_value
, 0))
1101 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1104 http
->error
= ETIMEDOUT
;
1109 bytes
= recv(http
->fd
, data
, length
, 0);
1110 DEBUG_printf(("6http_gnutls_read: bytes=%d", (int)bytes
));
1116 * 'http_gnutls_write()' - Write function for the GNU TLS library.
1119 static ssize_t
/* O - Number of bytes written or -1 on error */
1121 gnutls_transport_ptr_t ptr
, /* I - Connection to server */
1122 const void *data
, /* I - Data buffer */
1123 size_t length
) /* I - Number of bytes to write */
1125 ssize_t bytes
; /* Bytes written */
1128 DEBUG_printf(("6http_gnutls_write(ptr=%p, data=%p, length=%d)", ptr
, data
,
1130 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
1131 DEBUG_printf(("http_gnutls_write: bytes=%d", (int)bytes
));
1138 * '_httpTLSInitialize()' - Initialize the TLS stack.
1142 _httpTLSInitialize(void)
1145 * Initialize GNU TLS...
1148 gnutls_global_init();
1153 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
1156 size_t /* O - Bytes available */
1157 _httpTLSPending(http_t
*http
) /* I - HTTP connection */
1159 return (gnutls_record_check_pending(http
->tls
));
1164 * '_httpTLSRead()' - Read from a SSL/TLS connection.
1167 int /* O - Bytes read */
1168 _httpTLSRead(http_t
*http
, /* I - Connection to server */
1169 char *buf
, /* I - Buffer to store data */
1170 int len
) /* I - Length of buffer */
1172 ssize_t result
; /* Return value */
1175 result
= gnutls_record_recv(http
->tls
, buf
, (size_t)len
);
1177 if (result
< 0 && !errno
)
1180 * Convert GNU TLS error to errno value...
1185 case GNUTLS_E_INTERRUPTED
:
1189 case GNUTLS_E_AGAIN
:
1201 return ((int)result
);
1206 * '_httpTLSSetCredentials()' - Set the TLS credentials.
1209 int /* O - Status of connection */
1210 _httpTLSSetCredentials(http_t
*http
) /* I - Connection to server */
1219 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
1223 _httpTLSSetOptions(unsigned int options
) /* I - Options */
1225 tls_options
= options
;
1230 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
1233 int /* O - 0 on success, -1 on failure */
1234 _httpTLSStart(http_t
*http
) /* I - Connection to server */
1236 char hostname
[256], /* Hostname */
1237 *hostptr
; /* Pointer into hostname */
1238 int status
; /* Status of handshake */
1239 gnutls_certificate_credentials_t
*credentials
;
1240 /* TLS credentials */
1241 char priority_string
[2048];
1242 /* Priority string */
1245 DEBUG_printf(("3_httpTLSStart(http=%p)", http
));
1247 if ((tls_options
== _HTTP_TLS_UNCHANGED
) || (tls_options
== _HTTP_TLS_NONE
))
1249 DEBUG_puts("4_httpTLSStart: Setting defaults.");
1251 DEBUG_printf(("4_httpTLSStart: tls_options=%x", tls_options
));
1254 if (http
->mode
== _HTTP_MODE_SERVER
&& !tls_keypath
)
1256 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
1257 http
->error
= errno
= EINVAL
;
1258 http
->status
= HTTP_STATUS_ERROR
;
1259 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Server credentials not set."), 1);
1264 credentials
= (gnutls_certificate_credentials_t
*)
1265 malloc(sizeof(gnutls_certificate_credentials_t
));
1266 if (credentials
== NULL
)
1268 DEBUG_printf(("8_httpStartTLS: Unable to allocate credentials: %s",
1270 http
->error
= errno
;
1271 http
->status
= HTTP_STATUS_ERROR
;
1272 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
1277 gnutls_certificate_allocate_credentials(credentials
);
1278 status
= gnutls_init(&http
->tls
, http
->mode
== _HTTP_MODE_CLIENT
? GNUTLS_CLIENT
: GNUTLS_SERVER
);
1280 status
= gnutls_set_default_priority(http
->tls
);
1285 http
->status
= HTTP_STATUS_ERROR
;
1287 DEBUG_printf(("4_httpTLSStart: Unable to initialize common TLS parameters: %s", gnutls_strerror(status
)));
1288 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, gnutls_strerror(status
), 0);
1290 gnutls_deinit(http
->tls
);
1291 gnutls_certificate_free_credentials(*credentials
);
1298 if (http
->mode
== _HTTP_MODE_CLIENT
)
1301 * Client: get the hostname to use for TLS...
1304 if (httpAddrLocalhost(http
->hostaddr
))
1306 strlcpy(hostname
, "localhost", sizeof(hostname
));
1311 * Otherwise make sure the hostname we have does not end in a trailing dot.
1314 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
1315 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
1320 status
= gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, hostname
, strlen(hostname
));
1325 * Server: get certificate and private key...
1328 char crtfile
[1024], /* Certificate file */
1329 keyfile
[1024]; /* Private key file */
1330 int have_creds
= 0; /* Have credentials? */
1332 if (http
->fields
[HTTP_FIELD_HOST
][0])
1335 * Use hostname for TLS upgrade...
1338 strlcpy(hostname
, http
->fields
[HTTP_FIELD_HOST
], sizeof(hostname
));
1343 * Resolve hostname from connection address...
1346 http_addr_t addr
; /* Connection address */
1347 socklen_t addrlen
; /* Length of address */
1349 addrlen
= sizeof(addr
);
1350 if (getsockname(http
->fd
, (struct sockaddr
*)&addr
, &addrlen
))
1352 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno
)));
1355 else if (httpAddrLocalhost(&addr
))
1359 httpAddrLookup(&addr
, hostname
, sizeof(hostname
));
1360 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname
));
1364 if (isdigit(hostname
[0] & 255) || hostname
[0] == '[')
1365 hostname
[0] = '\0'; /* Don't allow numeric addresses */
1370 * First look in the CUPS keystore...
1373 http_gnutls_make_path(crtfile
, sizeof(crtfile
), tls_keypath
, hostname
, "crt");
1374 http_gnutls_make_path(keyfile
, sizeof(keyfile
), tls_keypath
, hostname
, "key");
1376 if (access(crtfile
, R_OK
) || access(keyfile
, R_OK
))
1379 * No CUPS-managed certs, look for CA certs...
1382 char cacrtfile
[1024], cakeyfile
[1024]; /* CA cert files */
1384 snprintf(cacrtfile
, sizeof(cacrtfile
), "/etc/letsencrypt/live/%s/fullchain.pem", hostname
);
1385 snprintf(cakeyfile
, sizeof(cakeyfile
), "/etc/letsencrypt/live/%s/privkey.pem", hostname
);
1387 if ((access(cacrtfile
, R_OK
) || access(cakeyfile
, R_OK
)) && (hostptr
= strchr(hostname
, '.')) != NULL
)
1390 * Try just domain name...
1394 if (strchr(hostptr
, '.'))
1396 snprintf(cacrtfile
, sizeof(cacrtfile
), "/etc/letsencrypt/live/%s/fullchain.pem", hostptr
);
1397 snprintf(cakeyfile
, sizeof(cakeyfile
), "/etc/letsencrypt/live/%s/privkey.pem", hostptr
);
1401 if (!access(cacrtfile
, R_OK
) && !access(cakeyfile
, R_OK
))
1404 * Use the CA certs...
1407 strlcpy(crtfile
, cacrtfile
, sizeof(crtfile
));
1408 strlcpy(keyfile
, cakeyfile
, sizeof(keyfile
));
1412 have_creds
= !access(crtfile
, R_OK
) && !access(keyfile
, R_OK
);
1414 else if (tls_common_name
)
1417 * First look in the CUPS keystore...
1420 http_gnutls_make_path(crtfile
, sizeof(crtfile
), tls_keypath
, tls_common_name
, "crt");
1421 http_gnutls_make_path(keyfile
, sizeof(keyfile
), tls_keypath
, tls_common_name
, "key");
1423 if (access(crtfile
, R_OK
) || access(keyfile
, R_OK
))
1426 * No CUPS-managed certs, look for CA certs...
1429 char cacrtfile
[1024], cakeyfile
[1024]; /* CA cert files */
1431 snprintf(cacrtfile
, sizeof(cacrtfile
), "/etc/letsencrypt/live/%s/fullchain.pem", tls_common_name
);
1432 snprintf(cakeyfile
, sizeof(cakeyfile
), "/etc/letsencrypt/live/%s/privkey.pem", tls_common_name
);
1434 if ((access(cacrtfile
, R_OK
) || access(cakeyfile
, R_OK
)) && (hostptr
= strchr(tls_common_name
, '.')) != NULL
)
1437 * Try just domain name...
1441 if (strchr(hostptr
, '.'))
1443 snprintf(cacrtfile
, sizeof(cacrtfile
), "/etc/letsencrypt/live/%s/fullchain.pem", hostptr
);
1444 snprintf(cakeyfile
, sizeof(cakeyfile
), "/etc/letsencrypt/live/%s/privkey.pem", hostptr
);
1448 if (!access(cacrtfile
, R_OK
) && !access(cakeyfile
, R_OK
))
1451 * Use the CA certs...
1454 strlcpy(crtfile
, cacrtfile
, sizeof(crtfile
));
1455 strlcpy(keyfile
, cakeyfile
, sizeof(keyfile
));
1459 have_creds
= !access(crtfile
, R_OK
) && !access(keyfile
, R_OK
);
1462 if (!have_creds
&& tls_auto_create
&& (hostname
[0] || tls_common_name
))
1464 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname
[0] ? hostname
: tls_common_name
));
1466 if (!cupsMakeServerCredentials(tls_keypath
, hostname
[0] ? hostname
: tls_common_name
, 0, NULL
, time(NULL
) + 365 * 86400))
1468 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
1469 http
->error
= errno
= EINVAL
;
1470 http
->status
= HTTP_STATUS_ERROR
;
1471 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to create server credentials."), 1);
1477 DEBUG_printf(("4_httpTLSStart: Using certificate \"%s\" and private key \"%s\".", crtfile
, keyfile
));
1480 status
= gnutls_certificate_set_x509_key_file(*credentials
, crtfile
, keyfile
, GNUTLS_X509_FMT_PEM
);
1484 status
= gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
1489 http
->status
= HTTP_STATUS_ERROR
;
1491 DEBUG_printf(("4_httpTLSStart: Unable to complete client/server setup: %s", gnutls_strerror(status
)));
1492 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, gnutls_strerror(status
), 0);
1494 gnutls_deinit(http
->tls
);
1495 gnutls_certificate_free_credentials(*credentials
);
1502 strlcpy(priority_string
, "NORMAL", sizeof(priority_string
));
1504 if (tls_options
& _HTTP_TLS_DENY_TLS10
)
1505 strlcat(priority_string
, ":+VERS-TLS-ALL:!VERS-TLS1.0:!VERS-SSL3.0", sizeof(priority_string
));
1506 else if (tls_options
& _HTTP_TLS_ALLOW_SSL3
)
1507 strlcat(priority_string
, ":+VERS-TLS-ALL", sizeof(priority_string
));
1508 else if (tls_options
& _HTTP_TLS_ONLY_TLS10
)
1509 strlcat(priority_string
, ":!VERS-TLS-ALL:!VERS-SSL3.0:+VERS-TLS1.0", sizeof(priority_string
));
1511 strlcat(priority_string
, ":+VERS-TLS-ALL:!VERS-SSL3.0", sizeof(priority_string
));
1513 if (tls_options
& _HTTP_TLS_ALLOW_RC4
)
1514 strlcat(priority_string
, ":+ARCFOUR-128", sizeof(priority_string
));
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 strlcat(priority_string
, ":!ANON-DH", sizeof(priority_string
));
1523 if (tls_options
& _HTTP_TLS_DENY_CBC
)
1524 strlcat(priority_string
, ":!AES-128-CBC:!AES-256-CBC:!CAMELLIA-128-CBC:!CAMELLIA-256-CBC:!3DES-CBC", sizeof(priority_string
));
1526 #ifdef HAVE_GNUTLS_PRIORITY_SET_DIRECT
1527 gnutls_priority_set_direct(http
->tls
, priority_string
, NULL
);
1530 gnutls_priority_t priority
; /* Priority */
1532 gnutls_priority_init(&priority
, priority_string
, NULL
);
1533 gnutls_priority_set(http
->tls
, priority
);
1534 gnutls_priority_deinit(priority
);
1535 #endif /* HAVE_GNUTLS_PRIORITY_SET_DIRECT */
1537 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr_t
)http
);
1538 gnutls_transport_set_pull_function(http
->tls
, http_gnutls_read
);
1539 #ifdef HAVE_GNUTLS_TRANSPORT_SET_PULL_TIMEOUT_FUNCTION
1540 gnutls_transport_set_pull_timeout_function(http
->tls
, (gnutls_pull_timeout_func
)httpWait
);
1541 #endif /* HAVE_GNUTLS_TRANSPORT_SET_PULL_TIMEOUT_FUNCTION */
1542 gnutls_transport_set_push_function(http
->tls
, http_gnutls_write
);
1544 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
1546 DEBUG_printf(("5_httpStartTLS: gnutls_handshake returned %d (%s)",
1547 status
, gnutls_strerror(status
)));
1549 if (gnutls_error_is_fatal(status
))
1552 http
->status
= HTTP_STATUS_ERROR
;
1554 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, gnutls_strerror(status
), 0);
1556 gnutls_deinit(http
->tls
);
1557 gnutls_certificate_free_credentials(*credentials
);
1565 http
->tls_credentials
= credentials
;
1572 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1576 _httpTLSStop(http_t
*http
) /* I - Connection to server */
1578 int error
; /* Error code */
1581 error
= gnutls_bye(http
->tls
, http
->mode
== _HTTP_MODE_CLIENT
? GNUTLS_SHUT_RDWR
: GNUTLS_SHUT_WR
);
1582 if (error
!= GNUTLS_E_SUCCESS
)
1583 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gnutls_strerror(errno
), 0);
1585 gnutls_deinit(http
->tls
);
1588 if (http
->tls_credentials
)
1590 gnutls_certificate_free_credentials(*(http
->tls_credentials
));
1591 free(http
->tls_credentials
);
1592 http
->tls_credentials
= NULL
;
1598 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1601 int /* O - Bytes written */
1602 _httpTLSWrite(http_t
*http
, /* I - Connection to server */
1603 const char *buf
, /* I - Buffer holding data */
1604 int len
) /* I - Length of buffer */
1606 ssize_t result
; /* Return value */
1609 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
1611 result
= gnutls_record_send(http
->tls
, buf
, (size_t)len
);
1613 if (result
< 0 && !errno
)
1616 * Convert GNU TLS error to errno value...
1621 case GNUTLS_E_INTERRUPTED
:
1625 case GNUTLS_E_AGAIN
:
1637 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
1639 return ((int)result
);