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 * Licensed under Apache License v2.0. See the file "LICENSE" for more information.
10 /**** This file is included from tls.c ****/
13 * Include necessary headers...
23 static int tls_auto_create
= 0;
24 /* Auto-create self-signed certs? */
25 static char *tls_common_name
= NULL
;
26 /* Default common name */
27 static gnutls_x509_crl_t tls_crl
= NULL
;/* Certificate revocation list */
28 static char *tls_keypath
= NULL
;
29 /* Server cert keychain path */
30 static _cups_mutex_t tls_mutex
= _CUPS_MUTEX_INITIALIZER
;
31 /* Mutex for keychain/certs */
32 static int tls_options
= -1,/* Options for TLS connections */
33 tls_min_version
= _HTTP_TLS_1_0
,
34 tls_max_version
= _HTTP_TLS_MAX
;
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 unsigned char md5_digest
[16]; /* MD5 result */
647 namelen
= sizeof(name
) - 1;
648 if (gnutls_x509_crt_get_dn_by_oid(cert
, GNUTLS_OID_X520_COMMON_NAME
, 0, 0, name
, &namelen
) >= 0)
649 name
[namelen
] = '\0';
651 strlcpy(name
, "unknown", sizeof(name
));
653 expiration
= gnutls_x509_crt_get_expiration_time(cert
);
655 cupsHashData("md5", first
->data
, first
->datalen
, md5_digest
, sizeof(md5_digest
));
657 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]);
659 gnutls_x509_crt_deinit(cert
);
662 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer
));
664 return (strlen(buffer
));
669 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
671 * @since CUPS 2.0/OS 10.10@
674 int /* O - 0 on success, -1 on error */
676 const char *path
, /* I - Keychain/PKCS#12 path */
677 cups_array_t
**credentials
, /* IO - Credentials */
678 const char *common_name
) /* I - Common name for credentials */
680 cups_file_t
*fp
; /* Certificate file */
681 char filename
[1024], /* filename.crt */
682 temp
[1024], /* Temporary string */
683 line
[256]; /* Base64-encoded line */
684 unsigned char *data
= NULL
; /* Buffer for cert data */
685 size_t alloc_data
= 0, /* Bytes allocated */
686 num_data
= 0; /* Bytes used */
687 int decoded
; /* Bytes decoded */
688 int in_certificate
= 0;
689 /* In a certificate? */
692 if (!credentials
|| !common_name
)
696 path
= http_gnutls_default_path(temp
, sizeof(temp
));
700 http_gnutls_make_path(filename
, sizeof(filename
), path
, common_name
, "crt");
702 if ((fp
= cupsFileOpen(filename
, "r")) == NULL
)
705 while (cupsFileGets(fp
, line
, sizeof(line
)))
707 if (!strcmp(line
, "-----BEGIN CERTIFICATE-----"))
712 * Missing END CERTIFICATE...
715 httpFreeCredentials(*credentials
);
722 else if (!strcmp(line
, "-----END CERTIFICATE-----"))
724 if (!in_certificate
|| !num_data
)
730 httpFreeCredentials(*credentials
);
736 *credentials
= cupsArrayNew(NULL
, NULL
);
738 if (httpAddCredential(*credentials
, data
, num_data
))
740 httpFreeCredentials(*credentials
);
748 else if (in_certificate
)
758 else if ((num_data
+ strlen(line
)) >= alloc_data
)
760 unsigned char *tdata
= realloc(data
, alloc_data
+ 1024);
761 /* Expanded buffer */
765 httpFreeCredentials(*credentials
);
774 decoded
= alloc_data
- num_data
;
775 httpDecode64_2((char *)data
+ num_data
, &decoded
, line
);
776 num_data
+= (size_t)decoded
;
785 * Missing END CERTIFICATE...
788 httpFreeCredentials(*credentials
);
795 return (*credentials
? 0 : -1);
800 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
802 * @since CUPS 2.0/OS 10.10@
805 int /* O - -1 on error, 0 on success */
807 const char *path
, /* I - Keychain/PKCS#12 path */
808 cups_array_t
*credentials
, /* I - Credentials */
809 const char *common_name
) /* I - Common name for credentials */
811 cups_file_t
*fp
; /* Certificate file */
812 char filename
[1024], /* filename.crt */
813 nfilename
[1024],/* filename.crt.N */
814 temp
[1024], /* Temporary string */
815 line
[256]; /* Base64-encoded line */
816 const unsigned char *ptr
; /* Pointer into certificate */
817 ssize_t remaining
; /* Bytes left */
818 http_credential_t
*cred
; /* Current credential */
821 if (!credentials
|| !common_name
)
825 path
= http_gnutls_default_path(temp
, sizeof(temp
));
829 http_gnutls_make_path(filename
, sizeof(filename
), path
, common_name
, "crt");
830 snprintf(nfilename
, sizeof(nfilename
), "%s.N", filename
);
832 if ((fp
= cupsFileOpen(nfilename
, "w")) == NULL
)
835 fchmod(cupsFileNumber(fp
), 0600);
837 for (cred
= (http_credential_t
*)cupsArrayFirst(credentials
);
839 cred
= (http_credential_t
*)cupsArrayNext(credentials
))
841 cupsFilePuts(fp
, "-----BEGIN CERTIFICATE-----\n");
842 for (ptr
= cred
->data
, remaining
= (ssize_t
)cred
->datalen
; remaining
> 0; remaining
-= 45, ptr
+= 45)
844 httpEncode64_2(line
, sizeof(line
), (char *)ptr
, remaining
> 45 ? 45 : remaining
);
845 cupsFilePrintf(fp
, "%s\n", line
);
847 cupsFilePuts(fp
, "-----END CERTIFICATE-----\n");
852 return (rename(nfilename
, filename
));
857 * 'http_gnutls_create_credential()' - Create a single credential in the internal format.
860 static gnutls_x509_crt_t
/* O - Certificate */
861 http_gnutls_create_credential(
862 http_credential_t
*credential
) /* I - Credential */
864 int result
; /* Result from GNU TLS */
865 gnutls_x509_crt_t cert
; /* Certificate */
866 gnutls_datum_t datum
; /* Data record */
869 DEBUG_printf(("3http_gnutls_create_credential(credential=%p)", credential
));
874 if ((result
= gnutls_x509_crt_init(&cert
)) < 0)
876 DEBUG_printf(("4http_gnutls_create_credential: init error: %s", gnutls_strerror(result
)));
880 datum
.data
= credential
->data
;
881 datum
.size
= credential
->datalen
;
883 if ((result
= gnutls_x509_crt_import(cert
, &datum
, GNUTLS_X509_FMT_DER
)) < 0)
885 DEBUG_printf(("4http_gnutls_create_credential: import error: %s", gnutls_strerror(result
)));
887 gnutls_x509_crt_deinit(cert
);
896 * 'http_gnutls_default_path()' - Get the default credential store path.
899 static const char * /* O - Path or NULL on error */
900 http_gnutls_default_path(char *buffer
,/* I - Path buffer */
901 size_t bufsize
)/* I - Size of path buffer */
903 const char *home
= getenv("HOME"); /* HOME environment variable */
906 if (getuid() && home
)
908 snprintf(buffer
, bufsize
, "%s/.cups", home
);
909 if (access(buffer
, 0))
911 DEBUG_printf(("1http_gnutls_default_path: Making directory \"%s\".", buffer
));
912 if (mkdir(buffer
, 0700))
914 DEBUG_printf(("1http_gnutls_default_path: Failed to make directory: %s", strerror(errno
)));
919 snprintf(buffer
, bufsize
, "%s/.cups/ssl", home
);
920 if (access(buffer
, 0))
922 DEBUG_printf(("1http_gnutls_default_path: Making directory \"%s\".", buffer
));
923 if (mkdir(buffer
, 0700))
925 DEBUG_printf(("1http_gnutls_default_path: Failed to make directory: %s", strerror(errno
)));
931 strlcpy(buffer
, CUPS_SERVERROOT
"/ssl", bufsize
);
933 DEBUG_printf(("1http_gnutls_default_path: Using default path \"%s\".", buffer
));
940 * 'http_gnutls_load_crl()' - Load the certificate revocation list, if any.
944 http_gnutls_load_crl(void)
946 _cupsMutexLock(&tls_mutex
);
948 if (!gnutls_x509_crl_init(&tls_crl
))
950 cups_file_t
*fp
; /* CRL file */
951 char filename
[1024], /* site.crl */
952 line
[256]; /* Base64-encoded line */
953 unsigned char *data
= NULL
; /* Buffer for cert data */
954 size_t alloc_data
= 0, /* Bytes allocated */
955 num_data
= 0; /* Bytes used */
956 int decoded
; /* Bytes decoded */
957 gnutls_datum_t datum
; /* Data record */
960 http_gnutls_make_path(filename
, sizeof(filename
), CUPS_SERVERROOT
, "site", "crl");
962 if ((fp
= cupsFileOpen(filename
, "r")) != NULL
)
964 while (cupsFileGets(fp
, line
, sizeof(line
)))
966 if (!strcmp(line
, "-----BEGIN X509 CRL-----"))
971 * Missing END X509 CRL...
977 else if (!strcmp(line
, "-----END X509 CRL-----"))
989 datum
.size
= num_data
;
991 gnutls_x509_crl_import(tls_crl
, &datum
, GNUTLS_X509_FMT_PEM
);
1005 else if ((num_data
+ strlen(line
)) >= alloc_data
)
1007 unsigned char *tdata
= realloc(data
, alloc_data
+ 1024);
1008 /* Expanded buffer */
1017 decoded
= alloc_data
- num_data
;
1018 httpDecode64_2((char *)data
+ num_data
, &decoded
, line
);
1019 num_data
+= (size_t)decoded
;
1030 _cupsMutexUnlock(&tls_mutex
);
1035 * 'http_gnutls_make_path()' - Format a filename for a certificate or key file.
1038 static const char * /* O - Filename */
1039 http_gnutls_make_path(
1040 char *buffer
, /* I - Filename buffer */
1041 size_t bufsize
, /* I - Size of buffer */
1042 const char *dirname
, /* I - Directory */
1043 const char *filename
, /* I - Filename (usually hostname) */
1044 const char *ext
) /* I - Extension */
1046 char *bufptr
, /* Pointer into buffer */
1047 *bufend
= buffer
+ bufsize
- 1; /* End of buffer */
1050 snprintf(buffer
, bufsize
, "%s/", dirname
);
1051 bufptr
= buffer
+ strlen(buffer
);
1053 while (*filename
&& bufptr
< bufend
)
1055 if (_cups_isalnum(*filename
) || *filename
== '-' || *filename
== '.')
1056 *bufptr
++ = *filename
;
1063 if (bufptr
< bufend
)
1066 strlcpy(bufptr
, ext
, (size_t)(bufend
- bufptr
+ 1));
1073 * 'http_gnutls_read()' - Read function for the GNU TLS library.
1076 static ssize_t
/* O - Number of bytes read or -1 on error */
1078 gnutls_transport_ptr_t ptr
, /* I - Connection to server */
1079 void *data
, /* I - Buffer */
1080 size_t length
) /* I - Number of bytes to read */
1082 http_t
*http
; /* HTTP connection */
1083 ssize_t bytes
; /* Bytes read */
1086 DEBUG_printf(("6http_gnutls_read(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
1088 http
= (http_t
*)ptr
;
1090 if (!http
->blocking
)
1093 * Make sure we have data before we read...
1096 while (!_httpWait(http
, http
->wait_value
, 0))
1098 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1101 http
->error
= ETIMEDOUT
;
1106 bytes
= recv(http
->fd
, data
, length
, 0);
1107 DEBUG_printf(("6http_gnutls_read: bytes=%d", (int)bytes
));
1113 * 'http_gnutls_write()' - Write function for the GNU TLS library.
1116 static ssize_t
/* O - Number of bytes written or -1 on error */
1118 gnutls_transport_ptr_t ptr
, /* I - Connection to server */
1119 const void *data
, /* I - Data buffer */
1120 size_t length
) /* I - Number of bytes to write */
1122 ssize_t bytes
; /* Bytes written */
1125 DEBUG_printf(("6http_gnutls_write(ptr=%p, data=%p, length=%d)", ptr
, data
,
1127 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
1128 DEBUG_printf(("http_gnutls_write: bytes=%d", (int)bytes
));
1135 * '_httpTLSInitialize()' - Initialize the TLS stack.
1139 _httpTLSInitialize(void)
1142 * Initialize GNU TLS...
1145 gnutls_global_init();
1150 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
1153 size_t /* O - Bytes available */
1154 _httpTLSPending(http_t
*http
) /* I - HTTP connection */
1156 return (gnutls_record_check_pending(http
->tls
));
1161 * '_httpTLSRead()' - Read from a SSL/TLS connection.
1164 int /* O - Bytes read */
1165 _httpTLSRead(http_t
*http
, /* I - Connection to server */
1166 char *buf
, /* I - Buffer to store data */
1167 int len
) /* I - Length of buffer */
1169 ssize_t result
; /* Return value */
1172 result
= gnutls_record_recv(http
->tls
, buf
, (size_t)len
);
1174 if (result
< 0 && !errno
)
1177 * Convert GNU TLS error to errno value...
1182 case GNUTLS_E_INTERRUPTED
:
1186 case GNUTLS_E_AGAIN
:
1198 return ((int)result
);
1203 * '_httpTLSSetCredentials()' - Set the TLS credentials.
1206 int /* O - Status of connection */
1207 _httpTLSSetCredentials(http_t
*http
) /* I - Connection to server */
1216 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
1220 _httpTLSSetOptions(int options
, /* I - Options */
1221 int min_version
, /* I - Minimum TLS version */
1222 int max_version
) /* I - Maximum TLS version */
1224 if (!(options
& _HTTP_TLS_SET_DEFAULT
) || tls_options
< 0)
1226 tls_options
= options
;
1227 tls_min_version
= min_version
;
1228 tls_max_version
= max_version
;
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
[2048];
1246 /* Priority string */
1247 int version
; /* Current version */
1248 static const char * const versions
[] =/* SSL/TLS versions */
1259 DEBUG_printf(("3_httpTLSStart(http=%p)", http
));
1261 if (tls_options
< 0)
1263 DEBUG_puts("4_httpTLSStart: Setting defaults.");
1265 DEBUG_printf(("4_httpTLSStart: tls_options=%x", tls_options
));
1268 if (http
->mode
== _HTTP_MODE_SERVER
&& !tls_keypath
)
1270 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
1271 http
->error
= errno
= EINVAL
;
1272 http
->status
= HTTP_STATUS_ERROR
;
1273 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Server credentials not set."), 1);
1278 credentials
= (gnutls_certificate_credentials_t
*)
1279 malloc(sizeof(gnutls_certificate_credentials_t
));
1280 if (credentials
== NULL
)
1282 DEBUG_printf(("8_httpStartTLS: Unable to allocate credentials: %s",
1284 http
->error
= errno
;
1285 http
->status
= HTTP_STATUS_ERROR
;
1286 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
1291 gnutls_certificate_allocate_credentials(credentials
);
1292 status
= gnutls_init(&http
->tls
, http
->mode
== _HTTP_MODE_CLIENT
? GNUTLS_CLIENT
: GNUTLS_SERVER
);
1294 status
= gnutls_set_default_priority(http
->tls
);
1299 http
->status
= HTTP_STATUS_ERROR
;
1301 DEBUG_printf(("4_httpTLSStart: Unable to initialize common TLS parameters: %s", gnutls_strerror(status
)));
1302 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, gnutls_strerror(status
), 0);
1304 gnutls_deinit(http
->tls
);
1305 gnutls_certificate_free_credentials(*credentials
);
1312 if (http
->mode
== _HTTP_MODE_CLIENT
)
1315 * Client: get the hostname to use for TLS...
1318 if (httpAddrLocalhost(http
->hostaddr
))
1320 strlcpy(hostname
, "localhost", sizeof(hostname
));
1325 * Otherwise make sure the hostname we have does not end in a trailing dot.
1328 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
1329 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
1334 status
= gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, hostname
, strlen(hostname
));
1339 * Server: get certificate and private key...
1342 char crtfile
[1024], /* Certificate file */
1343 keyfile
[1024]; /* Private key file */
1344 int have_creds
= 0; /* Have credentials? */
1346 if (http
->fields
[HTTP_FIELD_HOST
][0])
1349 * Use hostname for TLS upgrade...
1352 strlcpy(hostname
, http
->fields
[HTTP_FIELD_HOST
], sizeof(hostname
));
1357 * Resolve hostname from connection address...
1360 http_addr_t addr
; /* Connection address */
1361 socklen_t addrlen
; /* Length of address */
1363 addrlen
= sizeof(addr
);
1364 if (getsockname(http
->fd
, (struct sockaddr
*)&addr
, &addrlen
))
1366 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno
)));
1369 else if (httpAddrLocalhost(&addr
))
1373 httpAddrLookup(&addr
, hostname
, sizeof(hostname
));
1374 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname
));
1378 if (isdigit(hostname
[0] & 255) || hostname
[0] == '[')
1379 hostname
[0] = '\0'; /* Don't allow numeric addresses */
1384 * First look in the CUPS keystore...
1387 http_gnutls_make_path(crtfile
, sizeof(crtfile
), tls_keypath
, hostname
, "crt");
1388 http_gnutls_make_path(keyfile
, sizeof(keyfile
), tls_keypath
, hostname
, "key");
1390 if (access(crtfile
, R_OK
) || access(keyfile
, R_OK
))
1393 * No CUPS-managed certs, look for CA certs...
1396 char cacrtfile
[1024], cakeyfile
[1024]; /* CA cert files */
1398 snprintf(cacrtfile
, sizeof(cacrtfile
), "/etc/letsencrypt/live/%s/fullchain.pem", hostname
);
1399 snprintf(cakeyfile
, sizeof(cakeyfile
), "/etc/letsencrypt/live/%s/privkey.pem", hostname
);
1401 if ((access(cacrtfile
, R_OK
) || access(cakeyfile
, R_OK
)) && (hostptr
= strchr(hostname
, '.')) != NULL
)
1404 * Try just domain name...
1408 if (strchr(hostptr
, '.'))
1410 snprintf(cacrtfile
, sizeof(cacrtfile
), "/etc/letsencrypt/live/%s/fullchain.pem", hostptr
);
1411 snprintf(cakeyfile
, sizeof(cakeyfile
), "/etc/letsencrypt/live/%s/privkey.pem", hostptr
);
1415 if (!access(cacrtfile
, R_OK
) && !access(cakeyfile
, R_OK
))
1418 * Use the CA certs...
1421 strlcpy(crtfile
, cacrtfile
, sizeof(crtfile
));
1422 strlcpy(keyfile
, cakeyfile
, sizeof(keyfile
));
1426 have_creds
= !access(crtfile
, R_OK
) && !access(keyfile
, R_OK
);
1428 else if (tls_common_name
)
1431 * First look in the CUPS keystore...
1434 http_gnutls_make_path(crtfile
, sizeof(crtfile
), tls_keypath
, tls_common_name
, "crt");
1435 http_gnutls_make_path(keyfile
, sizeof(keyfile
), tls_keypath
, tls_common_name
, "key");
1437 if (access(crtfile
, R_OK
) || access(keyfile
, R_OK
))
1440 * No CUPS-managed certs, look for CA certs...
1443 char cacrtfile
[1024], cakeyfile
[1024]; /* CA cert files */
1445 snprintf(cacrtfile
, sizeof(cacrtfile
), "/etc/letsencrypt/live/%s/fullchain.pem", tls_common_name
);
1446 snprintf(cakeyfile
, sizeof(cakeyfile
), "/etc/letsencrypt/live/%s/privkey.pem", tls_common_name
);
1448 if ((access(cacrtfile
, R_OK
) || access(cakeyfile
, R_OK
)) && (hostptr
= strchr(tls_common_name
, '.')) != NULL
)
1451 * Try just domain name...
1455 if (strchr(hostptr
, '.'))
1457 snprintf(cacrtfile
, sizeof(cacrtfile
), "/etc/letsencrypt/live/%s/fullchain.pem", hostptr
);
1458 snprintf(cakeyfile
, sizeof(cakeyfile
), "/etc/letsencrypt/live/%s/privkey.pem", hostptr
);
1462 if (!access(cacrtfile
, R_OK
) && !access(cakeyfile
, R_OK
))
1465 * Use the CA certs...
1468 strlcpy(crtfile
, cacrtfile
, sizeof(crtfile
));
1469 strlcpy(keyfile
, cakeyfile
, sizeof(keyfile
));
1473 have_creds
= !access(crtfile
, R_OK
) && !access(keyfile
, R_OK
);
1476 if (!have_creds
&& tls_auto_create
&& (hostname
[0] || tls_common_name
))
1478 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname
[0] ? hostname
: tls_common_name
));
1480 if (!cupsMakeServerCredentials(tls_keypath
, hostname
[0] ? hostname
: tls_common_name
, 0, NULL
, time(NULL
) + 365 * 86400))
1482 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
1483 http
->error
= errno
= EINVAL
;
1484 http
->status
= HTTP_STATUS_ERROR
;
1485 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to create server credentials."), 1);
1491 DEBUG_printf(("4_httpTLSStart: Using certificate \"%s\" and private key \"%s\".", crtfile
, keyfile
));
1494 status
= gnutls_certificate_set_x509_key_file(*credentials
, crtfile
, keyfile
, GNUTLS_X509_FMT_PEM
);
1498 status
= gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
1503 http
->status
= HTTP_STATUS_ERROR
;
1505 DEBUG_printf(("4_httpTLSStart: Unable to complete client/server setup: %s", gnutls_strerror(status
)));
1506 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, gnutls_strerror(status
), 0);
1508 gnutls_deinit(http
->tls
);
1509 gnutls_certificate_free_credentials(*credentials
);
1516 strlcpy(priority_string
, "NORMAL", sizeof(priority_string
));
1518 if (tls_max_version
< _HTTP_TLS_MAX
)
1521 * Require specific TLS versions...
1524 strlcat(priority_string
, ":-VERS-TLS-ALL", sizeof(priority_string
));
1525 for (version
= tls_min_version
; version
<= tls_max_version
; version
++)
1527 strlcat(priority_string
, ":+", sizeof(priority_string
));
1528 strlcat(priority_string
, versions
[version
], sizeof(priority_string
));
1531 else if (tls_min_version
== _HTTP_TLS_SSL3
)
1534 * Allow all versions of TLS and SSL/3.0...
1537 strlcat(priority_string
, ":+VERS-TLS-ALL:+VERS-SSL3.0", sizeof(priority_string
));
1542 * Require a minimum version...
1545 strlcat(priority_string
, ":+VERS-TLS-ALL", sizeof(priority_string
));
1546 for (version
= 0; version
< tls_min_version
; version
++)
1548 strlcat(priority_string
, ":-", sizeof(priority_string
));
1549 strlcat(priority_string
, versions
[version
], sizeof(priority_string
));
1553 if (tls_options
& _HTTP_TLS_ALLOW_RC4
)
1554 strlcat(priority_string
, ":+ARCFOUR-128", sizeof(priority_string
));
1556 strlcat(priority_string
, ":!ARCFOUR-128", sizeof(priority_string
));
1558 strlcat(priority_string
, ":!ANON-DH", sizeof(priority_string
));
1560 if (tls_options
& _HTTP_TLS_DENY_CBC
)
1561 strlcat(priority_string
, ":!AES-128-CBC:!AES-256-CBC:!CAMELLIA-128-CBC:!CAMELLIA-256-CBC:!3DES-CBC", sizeof(priority_string
));
1563 #ifdef HAVE_GNUTLS_PRIORITY_SET_DIRECT
1564 gnutls_priority_set_direct(http
->tls
, priority_string
, NULL
);
1567 gnutls_priority_t priority
; /* Priority */
1569 gnutls_priority_init(&priority
, priority_string
, NULL
);
1570 gnutls_priority_set(http
->tls
, priority
);
1571 gnutls_priority_deinit(priority
);
1572 #endif /* HAVE_GNUTLS_PRIORITY_SET_DIRECT */
1574 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr_t
)http
);
1575 gnutls_transport_set_pull_function(http
->tls
, http_gnutls_read
);
1576 #ifdef HAVE_GNUTLS_TRANSPORT_SET_PULL_TIMEOUT_FUNCTION
1577 gnutls_transport_set_pull_timeout_function(http
->tls
, (gnutls_pull_timeout_func
)httpWait
);
1578 #endif /* HAVE_GNUTLS_TRANSPORT_SET_PULL_TIMEOUT_FUNCTION */
1579 gnutls_transport_set_push_function(http
->tls
, http_gnutls_write
);
1581 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
1583 DEBUG_printf(("5_httpStartTLS: gnutls_handshake returned %d (%s)",
1584 status
, gnutls_strerror(status
)));
1586 if (gnutls_error_is_fatal(status
))
1589 http
->status
= HTTP_STATUS_ERROR
;
1591 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, gnutls_strerror(status
), 0);
1593 gnutls_deinit(http
->tls
);
1594 gnutls_certificate_free_credentials(*credentials
);
1602 http
->tls_credentials
= credentials
;
1609 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1613 _httpTLSStop(http_t
*http
) /* I - Connection to server */
1615 int error
; /* Error code */
1618 error
= gnutls_bye(http
->tls
, http
->mode
== _HTTP_MODE_CLIENT
? GNUTLS_SHUT_RDWR
: GNUTLS_SHUT_WR
);
1619 if (error
!= GNUTLS_E_SUCCESS
)
1620 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gnutls_strerror(errno
), 0);
1622 gnutls_deinit(http
->tls
);
1625 if (http
->tls_credentials
)
1627 gnutls_certificate_free_credentials(*(http
->tls_credentials
));
1628 free(http
->tls_credentials
);
1629 http
->tls_credentials
= NULL
;
1635 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1638 int /* O - Bytes written */
1639 _httpTLSWrite(http_t
*http
, /* I - Connection to server */
1640 const char *buf
, /* I - Buffer holding data */
1641 int len
) /* I - Length of buffer */
1643 ssize_t result
; /* Return value */
1646 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
1648 result
= gnutls_record_send(http
->tls
, buf
, (size_t)len
);
1650 if (result
< 0 && !errno
)
1653 * Convert GNU TLS error to errno value...
1658 case GNUTLS_E_INTERRUPTED
:
1662 case GNUTLS_E_AGAIN
:
1674 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
1676 return ((int)result
);