2 * TLS support code for CUPS using GNU TLS.
4 * Copyright 2007-2015 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 char *tls_keypath
= NULL
;
34 /* Server cert keychain path */
35 static _cups_mutex_t tls_mutex
= _CUPS_MUTEX_INITIALIZER
;
36 /* Mutex for keychain/certs */
37 static int tls_options
= -1;/* Options for TLS connections */
44 static gnutls_x509_crt_t
http_gnutls_create_credential(http_credential_t
*credential
);
45 static const char *http_gnutls_default_path(char *buffer
, size_t bufsize
);
46 static const char *http_gnutls_make_path(char *buffer
, size_t bufsize
, const char *dirname
, const char *filename
, const char *ext
);
47 static ssize_t
http_gnutls_read(gnutls_transport_ptr_t ptr
, void *data
, size_t length
);
48 static ssize_t
http_gnutls_write(gnutls_transport_ptr_t ptr
, const void *data
, size_t length
);
52 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
54 * @since CUPS 2.0/OS 10.10@
57 int /* O - 1 on success, 0 on failure */
58 cupsMakeServerCredentials(
59 const char *path
, /* I - Path to keychain/directory */
60 const char *common_name
, /* I - Common name */
61 int num_alt_names
, /* I - Number of subject alternate names */
62 const char **alt_names
, /* I - Subject Alternate Names */
63 time_t expiration_date
) /* I - Expiration date */
65 gnutls_x509_crt_t crt
; /* Self-signed certificate */
66 gnutls_x509_privkey_t key
; /* Encryption private key */
67 char temp
[1024], /* Temporary directory name */
68 crtfile
[1024], /* Certificate filename */
69 keyfile
[1024]; /* Private key filename */
70 cups_lang_t
*language
; /* Default language info */
71 cups_file_t
*fp
; /* Key/cert file */
72 unsigned char buffer
[8192]; /* Buffer for x509 data */
73 size_t bytes
; /* Number of bytes of data */
74 unsigned char serial
[4]; /* Serial number buffer */
75 time_t curtime
; /* Current time */
76 int result
; /* Result of GNU TLS calls */
79 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
));
86 path
= http_gnutls_default_path(temp
, sizeof(temp
));
88 if (!path
|| !common_name
)
90 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
94 http_gnutls_make_path(crtfile
, sizeof(crtfile
), path
, common_name
, "crt");
95 http_gnutls_make_path(keyfile
, sizeof(keyfile
), path
, common_name
, "key");
98 * Create the encryption key...
101 DEBUG_puts("1cupsMakeServerCredentials: Creating key pair.");
103 gnutls_x509_privkey_init(&key
);
104 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
106 DEBUG_puts("1cupsMakeServerCredentials: Key pair created.");
112 bytes
= sizeof(buffer
);
114 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
, buffer
, &bytes
)) < 0)
116 DEBUG_printf(("1cupsMakeServerCredentials: Unable to export private key: %s", gnutls_strerror(result
)));
117 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gnutls_strerror(result
), 0);
118 gnutls_x509_privkey_deinit(key
);
121 else if ((fp
= cupsFileOpen(keyfile
, "w")) != NULL
)
123 DEBUG_printf(("1cupsMakeServerCredentials: Writing private key to \"%s\".", keyfile
));
124 cupsFileWrite(fp
, (char *)buffer
, bytes
);
129 DEBUG_printf(("1cupsMakeServerCredentials: Unable to create private key file \"%s\": %s", keyfile
, strerror(errno
)));
130 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
131 gnutls_x509_privkey_deinit(key
);
136 * Create the self-signed certificate...
139 DEBUG_puts("1cupsMakeServerCredentials: Generating self-signed X.509 certificate.");
141 language
= cupsLangDefault();
142 curtime
= time(NULL
);
143 serial
[0] = curtime
>> 24;
144 serial
[1] = curtime
>> 16;
145 serial
[2] = curtime
>> 8;
148 gnutls_x509_crt_init(&crt
);
149 if (strlen(language
->language
) == 5)
150 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
151 language
->language
+ 3, 2);
153 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
155 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
156 common_name
, strlen(common_name
));
157 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
158 common_name
, strlen(common_name
));
159 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
161 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
163 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
165 /* gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_PKCS9_EMAIL, 0,
166 ServerAdmin, strlen(ServerAdmin));*/
167 gnutls_x509_crt_set_key(crt
, key
);
168 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
169 gnutls_x509_crt_set_activation_time(crt
, curtime
);
170 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
171 gnutls_x509_crt_set_ca_status(crt
, 0);
172 if (num_alt_names
> 0)
173 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
, alt_names
[0]);
174 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
175 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
176 gnutls_x509_crt_set_version(crt
, 3);
178 bytes
= sizeof(buffer
);
179 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
180 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
182 gnutls_x509_crt_sign(crt
, crt
, key
);
188 bytes
= sizeof(buffer
);
189 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
, buffer
, &bytes
)) < 0)
191 DEBUG_printf(("1cupsMakeServerCredentials: Unable to export public key and X.509 certificate: %s", gnutls_strerror(result
)));
192 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gnutls_strerror(result
), 0);
193 gnutls_x509_crt_deinit(crt
);
194 gnutls_x509_privkey_deinit(key
);
197 else if ((fp
= cupsFileOpen(crtfile
, "w")) != NULL
)
199 DEBUG_printf(("1cupsMakeServerCredentials: Writing public key and X.509 certificate to \"%s\".", crtfile
));
200 cupsFileWrite(fp
, (char *)buffer
, bytes
);
205 DEBUG_printf(("1cupsMakeServerCredentials: Unable to create public key and X.509 certificate file \"%s\": %s", crtfile
, strerror(errno
)));
206 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
207 gnutls_x509_crt_deinit(crt
);
208 gnutls_x509_privkey_deinit(key
);
216 gnutls_x509_crt_deinit(crt
);
217 gnutls_x509_privkey_deinit(key
);
219 DEBUG_puts("1cupsMakeServerCredentials: Successfully created credentials.");
226 * 'cupsSetServerCredentials()' - Set the default server credentials.
228 * Note: The server credentials are used by all threads in the running process.
229 * This function is threadsafe.
231 * @since CUPS 2.0/OS 10.10@
234 int /* O - 1 on success, 0 on failure */
235 cupsSetServerCredentials(
236 const char *path
, /* I - Path to keychain/directory */
237 const char *common_name
, /* I - Default common name for server */
238 int auto_create
) /* I - 1 = automatically create self-signed certificates */
240 char temp
[1024]; /* Default path buffer */
243 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path
, common_name
, auto_create
));
246 * Use defaults as needed...
250 path
= http_gnutls_default_path(temp
, sizeof(temp
));
253 * Range check input...
256 if (!path
|| !common_name
)
258 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
262 _cupsMutexLock(&tls_mutex
);
269 _cupsStrFree(tls_keypath
);
272 _cupsStrFree(tls_common_name
);
275 * Save the new values...
278 tls_keypath
= _cupsStrAlloc(path
);
279 tls_auto_create
= auto_create
;
280 tls_common_name
= _cupsStrAlloc(common_name
);
282 _cupsMutexUnlock(&tls_mutex
);
289 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
290 * an encrypted connection.
292 * @since CUPS 1.5/OS X 10.7@
295 int /* O - Status of call (0 = success) */
297 http_t
*http
, /* I - Connection to server */
298 cups_array_t
**credentials
) /* O - Array of credentials */
300 unsigned count
; /* Number of certificates */
301 const gnutls_datum_t
*certs
; /* Certificates */
304 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", http
, credentials
));
309 if (!http
|| !http
->tls
|| !credentials
)
312 *credentials
= cupsArrayNew(NULL
, NULL
);
313 certs
= gnutls_certificate_get_peers(http
->tls
, &count
);
315 DEBUG_printf(("1httpCopyCredentials: certs=%p, count=%u", certs
, count
));
321 httpAddCredential(*credentials
, certs
->data
, certs
->size
);
332 * '_httpCreateCredentials()' - Create credentials in the internal format.
335 http_tls_credentials_t
/* O - Internal credentials */
336 _httpCreateCredentials(
337 cups_array_t
*credentials
) /* I - Array of credentials */
346 * '_httpFreeCredentials()' - Free internal credentials.
350 _httpFreeCredentials(
351 http_tls_credentials_t credentials
) /* I - Internal credentials */
358 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
360 * @since CUPS 2.0/OS 10.10@
363 int /* O - 1 if valid, 0 otherwise */
364 httpCredentialsAreValidForName(
365 cups_array_t
*credentials
, /* I - Credentials */
366 const char *common_name
) /* I - Name to check */
368 gnutls_x509_crt_t cert
; /* Certificate */
369 int result
= 0; /* Result */
372 cert
= http_gnutls_create_credential((http_credential_t
*)cupsArrayFirst(credentials
));
375 result
= gnutls_x509_crt_check_hostname(cert
, common_name
) != 0;
376 gnutls_x509_crt_deinit(cert
);
384 * 'httpCredentialsGetTrust()' - Return the trust of credentials.
386 * @since CUPS 2.0/OS 10.10@
389 http_trust_t
/* O - Level of trust */
390 httpCredentialsGetTrust(
391 cups_array_t
*credentials
, /* I - Credentials */
392 const char *common_name
) /* I - Common name for trust lookup */
394 http_trust_t trust
= HTTP_TRUST_OK
;
396 gnutls_x509_crt_t cert
; /* Certificate */
397 cups_array_t
*tcreds
= NULL
; /* Trusted credentials */
398 _cups_globals_t
*cg
= _cupsGlobals();
399 /* Per-thread globals */
403 return (HTTP_TRUST_UNKNOWN
);
405 if ((cert
= http_gnutls_create_credential((http_credential_t
*)cupsArrayFirst(credentials
))) == NULL
)
406 return (HTTP_TRUST_UNKNOWN
);
408 if (cg
->any_root
< 0)
412 * Look this common name up in the default keychains...
415 httpLoadCredentials(NULL
, &tcreds
, common_name
);
419 char credentials_str
[1024], /* String for incoming credentials */
420 tcreds_str
[1024]; /* String for saved credentials */
422 httpCredentialsString(credentials
, credentials_str
, sizeof(credentials_str
));
423 httpCredentialsString(tcreds
, tcreds_str
, sizeof(tcreds_str
));
425 if (strcmp(credentials_str
, tcreds_str
))
428 * Credentials don't match, let's look at the expiration date of the new
429 * credentials and allow if the new ones have a later expiration...
432 if (httpCredentialsGetExpiration(credentials
) <= httpCredentialsGetExpiration(tcreds
) ||
433 !httpCredentialsAreValidForName(credentials
, common_name
))
436 * Either the new credentials are not newly issued, or the common name
437 * does not match the issued certificate...
440 trust
= HTTP_TRUST_INVALID
;
442 else if (httpCredentialsGetExpiration(tcreds
) < time(NULL
))
445 * Save the renewed credentials...
448 trust
= HTTP_TRUST_RENEWED
;
450 httpSaveCredentials(NULL
, credentials
, common_name
);
454 httpFreeCredentials(tcreds
);
456 else if (cg
->validate_certs
&& !httpCredentialsAreValidForName(credentials
, common_name
))
457 trust
= HTTP_TRUST_INVALID
;
459 if (trust
== HTTP_TRUST_OK
&& !cg
->expired_certs
)
461 time_t curtime
; /* Current date/time */
464 if (curtime
< gnutls_x509_crt_get_activation_time(cert
) ||
465 curtime
> gnutls_x509_crt_get_expiration_time(cert
))
466 trust
= HTTP_TRUST_EXPIRED
;
469 if (trust
== HTTP_TRUST_OK
&& !cg
->any_root
&& cupsArrayCount(credentials
) == 1)
470 trust
= HTTP_TRUST_INVALID
;
472 gnutls_x509_crt_deinit(cert
);
479 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
481 * @since CUPS 2.0/OS 10.10@
484 time_t /* O - Expiration date of credentials */
485 httpCredentialsGetExpiration(
486 cups_array_t
*credentials
) /* I - Credentials */
488 gnutls_x509_crt_t cert
; /* Certificate */
489 time_t result
= 0; /* Result */
492 cert
= http_gnutls_create_credential((http_credential_t
*)cupsArrayFirst(credentials
));
495 result
= gnutls_x509_crt_get_expiration_time(cert
);
496 gnutls_x509_crt_deinit(cert
);
504 * 'httpCredentialsString()' - Return a string representing the credentials.
506 * @since CUPS 2.0/OS 10.10@
509 size_t /* O - Total size of credentials string */
510 httpCredentialsString(
511 cups_array_t
*credentials
, /* I - Credentials */
512 char *buffer
, /* I - Buffer or @code NULL@ */
513 size_t bufsize
) /* I - Size of buffer */
515 http_credential_t
*first
; /* First certificate */
516 gnutls_x509_crt_t cert
; /* Certificate */
519 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT
")", credentials
, buffer
, CUPS_LLCAST bufsize
));
524 if (buffer
&& bufsize
> 0)
527 if ((first
= (http_credential_t
*)cupsArrayFirst(credentials
)) != NULL
&&
528 (cert
= http_gnutls_create_credential(first
)) != NULL
)
530 char name
[256]; /* Common name associated with cert */
531 size_t namelen
; /* Length of name */
532 time_t expiration
; /* Expiration date of cert */
533 _cups_md5_state_t md5_state
; /* MD5 state */
534 unsigned char md5_digest
[16]; /* MD5 result */
536 namelen
= sizeof(name
) - 1;
537 if (gnutls_x509_crt_get_dn_by_oid(cert
, GNUTLS_OID_X520_COMMON_NAME
, 0, 0, name
, &namelen
) >= 0)
538 name
[namelen
] = '\0';
540 strlcpy(name
, "unknown", sizeof(name
));
542 expiration
= gnutls_x509_crt_get_expiration_time(cert
);
544 _cupsMD5Init(&md5_state
);
545 _cupsMD5Append(&md5_state
, first
->data
, (int)first
->datalen
);
546 _cupsMD5Finish(&md5_state
, md5_digest
);
548 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]);
550 gnutls_x509_crt_deinit(cert
);
553 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer
));
555 return (strlen(buffer
));
560 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
562 * @since CUPS 2.0/OS 10.10@
565 int /* O - 0 on success, -1 on error */
567 const char *path
, /* I - Keychain/PKCS#12 path */
568 cups_array_t
**credentials
, /* IO - Credentials */
569 const char *common_name
) /* I - Common name for credentials */
571 cups_file_t
*fp
; /* Certificate file */
572 char filename
[1024], /* filename.crt */
573 temp
[1024], /* Temporary string */
574 line
[256]; /* Base64-encoded line */
575 unsigned char *data
= NULL
; /* Buffer for cert data */
576 size_t alloc_data
= 0, /* Bytes allocated */
577 num_data
= 0; /* Bytes used */
578 int decoded
; /* Bytes decoded */
581 if (!credentials
|| !common_name
)
585 path
= http_gnutls_default_path(temp
, sizeof(temp
));
589 http_gnutls_make_path(filename
, sizeof(filename
), path
, common_name
, "crt");
591 if ((fp
= cupsFileOpen(filename
, "r")) == NULL
)
594 while (cupsFileGets(fp
, line
, sizeof(line
)))
596 if (!strcmp(line
, "-----BEGIN CERTIFICATE-----"))
601 * Missing END CERTIFICATE...
604 httpFreeCredentials(*credentials
);
609 else if (!strcmp(line
, "-----END CERTIFICATE-----"))
617 httpFreeCredentials(*credentials
);
623 *credentials
= cupsArrayNew(NULL
, NULL
);
625 if (httpAddCredential(*credentials
, data
, num_data
))
627 httpFreeCredentials(*credentials
);
644 else if ((num_data
+ strlen(line
)) >= alloc_data
)
646 unsigned char *tdata
= realloc(data
, alloc_data
+ 1024);
647 /* Expanded buffer */
651 httpFreeCredentials(*credentials
);
660 decoded
= alloc_data
- num_data
;
661 httpDecode64_2((char *)data
+ num_data
, &decoded
, line
);
662 num_data
+= (size_t)decoded
;
671 * Missing END CERTIFICATE...
674 httpFreeCredentials(*credentials
);
681 return (*credentials
? 0 : -1);
686 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
688 * @since CUPS 2.0/OS 10.10@
691 int /* O - -1 on error, 0 on success */
693 const char *path
, /* I - Keychain/PKCS#12 path */
694 cups_array_t
*credentials
, /* I - Credentials */
695 const char *common_name
) /* I - Common name for credentials */
697 cups_file_t
*fp
; /* Certificate file */
698 char filename
[1024], /* filename.crt */
699 nfilename
[1024],/* filename.crt.N */
700 temp
[1024], /* Temporary string */
701 line
[256]; /* Base64-encoded line */
702 const unsigned char *ptr
; /* Pointer into certificate */
703 ssize_t remaining
; /* Bytes left */
704 http_credential_t
*cred
; /* Current credential */
707 if (!credentials
|| !common_name
)
711 path
= http_gnutls_default_path(temp
, sizeof(temp
));
715 http_gnutls_make_path(filename
, sizeof(filename
), path
, common_name
, "crt");
716 snprintf(nfilename
, sizeof(nfilename
), "%s.N", filename
);
718 if ((fp
= cupsFileOpen(nfilename
, "w")) == NULL
)
721 fchmod(cupsFileNumber(fp
), 0600);
723 for (cred
= (http_credential_t
*)cupsArrayFirst(credentials
);
725 cred
= (http_credential_t
*)cupsArrayNext(credentials
))
727 cupsFilePuts(fp
, "-----BEGIN CERTIFICATE-----\n");
728 for (ptr
= cred
->data
, remaining
= (ssize_t
)cred
->datalen
; remaining
> 0; remaining
-= 45, ptr
+= 45)
730 httpEncode64_2(line
, sizeof(line
), (char *)ptr
, remaining
> 45 ? 45 : remaining
);
731 cupsFilePrintf(fp
, "%s\n", line
);
733 cupsFilePuts(fp
, "-----END CERTIFICATE-----\n");
738 return (rename(nfilename
, filename
));
743 * 'http_gnutls_create_credential()' - Create a single credential in the internal format.
746 static gnutls_x509_crt_t
/* O - Certificate */
747 http_gnutls_create_credential(
748 http_credential_t
*credential
) /* I - Credential */
750 int result
; /* Result from GNU TLS */
751 gnutls_x509_crt_t cert
; /* Certificate */
752 gnutls_datum_t datum
; /* Data record */
755 DEBUG_printf(("3http_gnutls_create_credential(credential=%p)", credential
));
760 if ((result
= gnutls_x509_crt_init(&cert
)) < 0)
762 DEBUG_printf(("4http_gnutls_create_credential: init error: %s", gnutls_strerror(result
)));
766 datum
.data
= credential
->data
;
767 datum
.size
= credential
->datalen
;
769 if ((result
= gnutls_x509_crt_import(cert
, &datum
, GNUTLS_X509_FMT_DER
)) < 0)
771 DEBUG_printf(("4http_gnutls_create_credential: import error: %s", gnutls_strerror(result
)));
773 gnutls_x509_crt_deinit(cert
);
782 * 'http_gnutls_default_path()' - Get the default credential store path.
785 static const char * /* O - Path or NULL on error */
786 http_gnutls_default_path(char *buffer
,/* I - Path buffer */
787 size_t bufsize
)/* I - Size of path buffer */
789 const char *home
= getenv("HOME"); /* HOME environment variable */
792 if (getuid() && home
)
794 snprintf(buffer
, bufsize
, "%s/.cups", home
);
795 if (access(buffer
, 0))
797 DEBUG_printf(("1http_gnutls_default_path: Making directory \"%s\".", buffer
));
798 if (mkdir(buffer
, 0700))
800 DEBUG_printf(("1http_gnutls_default_path: Failed to make directory: %s", strerror(errno
)));
805 snprintf(buffer
, bufsize
, "%s/.cups/ssl", home
);
806 if (access(buffer
, 0))
808 DEBUG_printf(("1http_gnutls_default_path: Making directory \"%s\".", buffer
));
809 if (mkdir(buffer
, 0700))
811 DEBUG_printf(("1http_gnutls_default_path: Failed to make directory: %s", strerror(errno
)));
817 strlcpy(buffer
, CUPS_SERVERROOT
"/ssl", bufsize
);
819 DEBUG_printf(("1http_gnutls_default_path: Using default path \"%s\".", buffer
));
826 * 'http_gnutls_make_path()' - Format a filename for a certificate or key file.
829 static const char * /* O - Filename */
830 http_gnutls_make_path(
831 char *buffer
, /* I - Filename buffer */
832 size_t bufsize
, /* I - Size of buffer */
833 const char *dirname
, /* I - Directory */
834 const char *filename
, /* I - Filename (usually hostname) */
835 const char *ext
) /* I - Extension */
837 char *bufptr
, /* Pointer into buffer */
838 *bufend
= buffer
+ bufsize
- 1; /* End of buffer */
841 snprintf(buffer
, bufsize
, "%s/", dirname
);
842 bufptr
= buffer
+ strlen(buffer
);
844 while (*filename
&& bufptr
< bufend
)
846 if (_cups_isalnum(*filename
) || *filename
== '-' || *filename
== '.')
847 *bufptr
++ = *filename
;
857 strlcpy(bufptr
, ext
, (size_t)(bufend
- bufptr
+ 1));
864 * 'http_gnutls_read()' - Read function for the GNU TLS library.
867 static ssize_t
/* O - Number of bytes read or -1 on error */
869 gnutls_transport_ptr_t ptr
, /* I - Connection to server */
870 void *data
, /* I - Buffer */
871 size_t length
) /* I - Number of bytes to read */
873 http_t
*http
; /* HTTP connection */
874 ssize_t bytes
; /* Bytes read */
877 DEBUG_printf(("6http_gnutls_read(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
879 http
= (http_t
*)ptr
;
884 * Make sure we have data before we read...
887 while (!_httpWait(http
, http
->wait_value
, 0))
889 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
892 http
->error
= ETIMEDOUT
;
897 bytes
= recv(http
->fd
, data
, length
, 0);
898 DEBUG_printf(("6http_gnutls_read: bytes=%d", (int)bytes
));
904 * 'http_gnutls_write()' - Write function for the GNU TLS library.
907 static ssize_t
/* O - Number of bytes written or -1 on error */
909 gnutls_transport_ptr_t ptr
, /* I - Connection to server */
910 const void *data
, /* I - Data buffer */
911 size_t length
) /* I - Number of bytes to write */
913 ssize_t bytes
; /* Bytes written */
916 DEBUG_printf(("6http_gnutls_write(ptr=%p, data=%p, length=%d)", ptr
, data
,
918 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
919 DEBUG_printf(("http_gnutls_write: bytes=%d", (int)bytes
));
926 * '_httpTLSInitialize()' - Initialize the TLS stack.
930 _httpTLSInitialize(void)
933 * Initialize GNU TLS...
936 gnutls_global_init();
941 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
944 size_t /* O - Bytes available */
945 _httpTLSPending(http_t
*http
) /* I - HTTP connection */
947 return (gnutls_record_check_pending(http
->tls
));
952 * '_httpTLSRead()' - Read from a SSL/TLS connection.
955 int /* O - Bytes read */
956 _httpTLSRead(http_t
*http
, /* I - Connection to server */
957 char *buf
, /* I - Buffer to store data */
958 int len
) /* I - Length of buffer */
960 ssize_t result
; /* Return value */
963 result
= gnutls_record_recv(http
->tls
, buf
, (size_t)len
);
965 if (result
< 0 && !errno
)
968 * Convert GNU TLS error to errno value...
973 case GNUTLS_E_INTERRUPTED
:
977 case GNUTLS_E_AGAIN
:
989 return ((int)result
);
994 * '_httpTLSSetCredentials()' - Set the TLS credentials.
997 int /* O - Status of connection */
998 _httpTLSSetCredentials(http_t
*http
) /* I - Connection to server */
1007 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
1011 _httpTLSSetOptions(int options
) /* I - Options */
1013 tls_options
= options
;
1018 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
1021 int /* O - 0 on success, -1 on failure */
1022 _httpTLSStart(http_t
*http
) /* I - Connection to server */
1024 char hostname
[256], /* Hostname */
1025 *hostptr
; /* Pointer into hostname */
1026 int status
; /* Status of handshake */
1027 gnutls_certificate_credentials_t
*credentials
;
1028 /* TLS credentials */
1029 char priority_string
[1024];
1030 /* Priority string */
1033 DEBUG_printf(("3_httpTLSStart(http=%p)", http
));
1035 if (tls_options
< 0)
1037 DEBUG_puts("4_httpTLSStart: Setting defaults.");
1039 DEBUG_printf(("4_httpTLSStart: tls_options=%x", tls_options
));
1042 if (http
->mode
== _HTTP_MODE_SERVER
&& !tls_keypath
)
1044 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
1045 http
->error
= errno
= EINVAL
;
1046 http
->status
= HTTP_STATUS_ERROR
;
1047 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Server credentials not set."), 1);
1052 credentials
= (gnutls_certificate_credentials_t
*)
1053 malloc(sizeof(gnutls_certificate_credentials_t
));
1054 if (credentials
== NULL
)
1056 DEBUG_printf(("8_httpStartTLS: Unable to allocate credentials: %s",
1058 http
->error
= errno
;
1059 http
->status
= HTTP_STATUS_ERROR
;
1060 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
1065 gnutls_certificate_allocate_credentials(credentials
);
1066 status
= gnutls_init(&http
->tls
, http
->mode
== _HTTP_MODE_CLIENT
? GNUTLS_CLIENT
: GNUTLS_SERVER
);
1068 status
= gnutls_set_default_priority(http
->tls
);
1073 http
->status
= HTTP_STATUS_ERROR
;
1075 DEBUG_printf(("4_httpTLSStart: Unable to initialize common TLS parameters: %s", gnutls_strerror(status
)));
1076 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, gnutls_strerror(status
), 0);
1078 gnutls_deinit(http
->tls
);
1079 gnutls_certificate_free_credentials(*credentials
);
1086 if (http
->mode
== _HTTP_MODE_CLIENT
)
1089 * Client: get the hostname to use for TLS...
1092 if (httpAddrLocalhost(http
->hostaddr
))
1094 strlcpy(hostname
, "localhost", sizeof(hostname
));
1099 * Otherwise make sure the hostname we have does not end in a trailing dot.
1102 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
1103 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
1108 status
= gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, hostname
, strlen(hostname
));
1113 * Server: get certificate and private key...
1116 char crtfile
[1024], /* Certificate file */
1117 keyfile
[1024]; /* Private key file */
1118 int have_creds
= 0; /* Have credentials? */
1120 if (http
->fields
[HTTP_FIELD_HOST
][0])
1123 * Use hostname for TLS upgrade...
1126 strlcpy(hostname
, http
->fields
[HTTP_FIELD_HOST
], sizeof(hostname
));
1131 * Resolve hostname from connection address...
1134 http_addr_t addr
; /* Connection address */
1135 socklen_t addrlen
; /* Length of address */
1137 addrlen
= sizeof(addr
);
1138 if (getsockname(http
->fd
, (struct sockaddr
*)&addr
, &addrlen
))
1140 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno
)));
1143 else if (httpAddrLocalhost(&addr
))
1147 httpAddrLookup(&addr
, hostname
, sizeof(hostname
));
1148 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname
));
1152 if (isdigit(hostname
[0] & 255) || hostname
[0] == '[')
1153 hostname
[0] = '\0'; /* Don't allow numeric addresses */
1157 http_gnutls_make_path(crtfile
, sizeof(crtfile
), tls_keypath
, hostname
, "crt");
1158 http_gnutls_make_path(keyfile
, sizeof(keyfile
), tls_keypath
, hostname
, "key");
1160 have_creds
= !access(crtfile
, 0) && !access(keyfile
, 0);
1162 else if (tls_common_name
)
1164 http_gnutls_make_path(crtfile
, sizeof(crtfile
), tls_keypath
, tls_common_name
, "crt");
1165 http_gnutls_make_path(keyfile
, sizeof(keyfile
), tls_keypath
, tls_common_name
, "key");
1167 have_creds
= !access(crtfile
, 0) && !access(keyfile
, 0);
1170 if (!have_creds
&& tls_auto_create
&& (hostname
[0] || tls_common_name
))
1172 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname
[0] ? hostname
: tls_common_name
));
1174 if (!cupsMakeServerCredentials(tls_keypath
, hostname
[0] ? hostname
: tls_common_name
, 0, NULL
, time(NULL
) + 365 * 86400))
1176 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
1177 http
->error
= errno
= EINVAL
;
1178 http
->status
= HTTP_STATUS_ERROR
;
1179 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to create server credentials."), 1);
1185 DEBUG_printf(("4_httpTLSStart: Using certificate \"%s\" and private key \"%s\".", crtfile
, keyfile
));
1187 status
= gnutls_certificate_set_x509_key_file(*credentials
, crtfile
, keyfile
, GNUTLS_X509_FMT_PEM
);
1191 status
= gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
1196 http
->status
= HTTP_STATUS_ERROR
;
1198 DEBUG_printf(("4_httpTLSStart: Unable to complete client/server setup: %s", gnutls_strerror(status
)));
1199 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, gnutls_strerror(status
), 0);
1201 gnutls_deinit(http
->tls
);
1202 gnutls_certificate_free_credentials(*credentials
);
1209 strlcpy(priority_string
, "NORMAL", sizeof(priority_string
));
1211 if (tls_options
& _HTTP_TLS_DENY_TLS10
)
1212 strlcat(priority_string
, ":+VERS-TLS-ALL:-VERS-TLS1.0:-VERS-SSL3.0", sizeof(priority_string
));
1213 else if (tls_options
& _HTTP_TLS_ALLOW_SSL3
)
1214 strlcat(priority_string
, ":+VERS-TLS-ALL", sizeof(priority_string
));
1216 strlcat(priority_string
, ":+VERS-TLS-ALL:-VERS-SSL3.0", sizeof(priority_string
));
1218 if (!(tls_options
& _HTTP_TLS_ALLOW_RC4
))
1219 strlcat(priority_string
, ":-ARCFOUR-128", sizeof(priority_string
));
1221 if (!(tls_options
& _HTTP_TLS_ALLOW_DH
))
1222 strlcat(priority_string
, ":!ANON-DH", sizeof(priority_string
));
1224 #ifdef HAVE_GNUTLS_PRIORITY_SET_DIRECT
1225 gnutls_priority_set_direct(http
->tls
, priority_string
, NULL
);
1228 gnutls_priority_t priority
; /* Priority */
1230 gnutls_priority_init(&priority
, priority_string
, NULL
);
1231 gnutls_priority_set(http
->tls
, priority
);
1232 gnutls_priority_deinit(priority
);
1233 #endif /* HAVE_GNUTLS_PRIORITY_SET_DIRECT */
1235 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr_t
)http
);
1236 gnutls_transport_set_pull_function(http
->tls
, http_gnutls_read
);
1237 #ifdef HAVE_GNUTLS_TRANSPORT_SET_PULL_TIMEOUT_FUNCTION
1238 gnutls_transport_set_pull_timeout_function(http
->tls
, (gnutls_pull_timeout_func
)httpWait
);
1239 #endif /* HAVE_GNUTLS_TRANSPORT_SET_PULL_TIMEOUT_FUNCTION */
1240 gnutls_transport_set_push_function(http
->tls
, http_gnutls_write
);
1242 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
1244 DEBUG_printf(("5_httpStartTLS: gnutls_handshake returned %d (%s)",
1245 status
, gnutls_strerror(status
)));
1247 if (gnutls_error_is_fatal(status
))
1250 http
->status
= HTTP_STATUS_ERROR
;
1252 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, gnutls_strerror(status
), 0);
1254 gnutls_deinit(http
->tls
);
1255 gnutls_certificate_free_credentials(*credentials
);
1263 http
->tls_credentials
= credentials
;
1270 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1274 _httpTLSStop(http_t
*http
) /* I - Connection to server */
1276 int error
; /* Error code */
1279 error
= gnutls_bye(http
->tls
, http
->mode
== _HTTP_MODE_CLIENT
? GNUTLS_SHUT_RDWR
: GNUTLS_SHUT_WR
);
1280 if (error
!= GNUTLS_E_SUCCESS
)
1281 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gnutls_strerror(errno
), 0);
1283 gnutls_deinit(http
->tls
);
1286 if (http
->tls_credentials
)
1288 gnutls_certificate_free_credentials(*(http
->tls_credentials
));
1289 free(http
->tls_credentials
);
1290 http
->tls_credentials
= NULL
;
1296 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1299 int /* O - Bytes written */
1300 _httpTLSWrite(http_t
*http
, /* I - Connection to server */
1301 const char *buf
, /* I - Buffer holding data */
1302 int len
) /* I - Length of buffer */
1304 ssize_t result
; /* Return value */
1307 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
1309 result
= gnutls_record_send(http
->tls
, buf
, (size_t)len
);
1311 if (result
< 0 && !errno
)
1314 * Convert GNU TLS error to errno value...
1319 case GNUTLS_E_INTERRUPTED
:
1323 case GNUTLS_E_AGAIN
:
1335 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
1337 return ((int)result
);