4 * TLS support code for CUPS using GNU TLS.
6 * Copyright 2007-2014 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * These coded instructions, statements, and computer programs are the
10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
12 * which should have been included with this file. If this file is
13 * file is missing or damaged, see the license at "http://www.cups.org/".
15 * This file is subject to the Apple OS-Developed Software exception.
20 * Include necessary headers...
30 static int tls_auto_create
= 0;
31 /* Auto-create self-signed certs? */
32 static char *tls_common_name
= NULL
;
33 /* Default common name */
34 static char *tls_keypath
= NULL
;
35 /* Server cert keychain path */
36 static _cups_mutex_t tls_mutex
= _CUPS_MUTEX_INITIALIZER
;
37 /* Mutex for keychain/certs */
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
);
409 * Look this common name up in the default keychains...
412 httpLoadCredentials(NULL
, &tcreds
, common_name
);
416 char credentials_str
[1024], /* String for incoming credentials */
417 tcreds_str
[1024]; /* String for saved credentials */
419 httpCredentialsString(credentials
, credentials_str
, sizeof(credentials_str
));
420 httpCredentialsString(tcreds
, tcreds_str
, sizeof(tcreds_str
));
422 if (strcmp(credentials_str
, tcreds_str
))
425 * Credentials don't match, let's look at the expiration date of the new
426 * credentials and allow if the new ones have a later expiration...
429 if (httpCredentialsGetExpiration(credentials
) <= httpCredentialsGetExpiration(tcreds
) ||
430 !httpCredentialsAreValidForName(credentials
, common_name
))
433 * Either the new credentials are not newly issued, or the common name
434 * does not match the issued certificate...
437 trust
= HTTP_TRUST_INVALID
;
439 else if (httpCredentialsGetExpiration(tcreds
) < time(NULL
))
442 * Save the renewed credentials...
445 trust
= HTTP_TRUST_RENEWED
;
447 httpSaveCredentials(NULL
, credentials
, common_name
);
451 httpFreeCredentials(tcreds
);
453 else if (cg
->validate_certs
&& !httpCredentialsAreValidForName(credentials
, common_name
))
454 trust
= HTTP_TRUST_INVALID
;
456 if (trust
== HTTP_TRUST_OK
&& !cg
->expired_certs
)
458 time_t curtime
; /* Current date/time */
461 if (curtime
< gnutls_x509_crt_get_activation_time(cert
) ||
462 curtime
> gnutls_x509_crt_get_expiration_time(cert
))
463 trust
= HTTP_TRUST_EXPIRED
;
466 if (trust
== HTTP_TRUST_OK
&& !cg
->any_root
&& cupsArrayCount(credentials
) == 1)
467 trust
= HTTP_TRUST_INVALID
;
469 gnutls_x509_crt_deinit(cert
);
476 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
478 * @since CUPS 2.0/OS 10.10@
481 time_t /* O - Expiration date of credentials */
482 httpCredentialsGetExpiration(
483 cups_array_t
*credentials
) /* I - Credentials */
485 gnutls_x509_crt_t cert
; /* Certificate */
486 time_t result
= 0; /* Result */
489 cert
= http_gnutls_create_credential((http_credential_t
*)cupsArrayFirst(credentials
));
492 result
= gnutls_x509_crt_get_expiration_time(cert
);
493 gnutls_x509_crt_deinit(cert
);
501 * 'httpCredentialsString()' - Return a string representing the credentials.
503 * @since CUPS 2.0/OS 10.10@
506 size_t /* O - Total size of credentials string */
507 httpCredentialsString(
508 cups_array_t
*credentials
, /* I - Credentials */
509 char *buffer
, /* I - Buffer or @code NULL@ */
510 size_t bufsize
) /* I - Size of buffer */
512 http_credential_t
*first
; /* First certificate */
513 gnutls_x509_crt_t cert
; /* Certificate */
516 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT
")", credentials
, buffer
, CUPS_LLCAST bufsize
));
521 if (buffer
&& bufsize
> 0)
524 if ((first
= (http_credential_t
*)cupsArrayFirst(credentials
)) != NULL
&&
525 (cert
= http_gnutls_create_credential(first
)) != NULL
)
527 char name
[256]; /* Common name associated with cert */
528 size_t namelen
; /* Length of name */
529 time_t expiration
; /* Expiration date of cert */
530 _cups_md5_state_t md5_state
; /* MD5 state */
531 unsigned char md5_digest
[16]; /* MD5 result */
533 namelen
= sizeof(name
) - 1;
534 if (gnutls_x509_crt_get_dn_by_oid(cert
, GNUTLS_OID_X520_COMMON_NAME
, 0, 0, name
, &namelen
) >= 0)
535 name
[namelen
] = '\0';
537 strlcpy(name
, "unknown", sizeof(name
));
539 expiration
= gnutls_x509_crt_get_expiration_time(cert
);
541 _cupsMD5Init(&md5_state
);
542 _cupsMD5Append(&md5_state
, first
->data
, (int)first
->datalen
);
543 _cupsMD5Finish(&md5_state
, md5_digest
);
545 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]);
547 gnutls_x509_crt_deinit(cert
);
550 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer
));
552 return (strlen(buffer
));
557 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
559 * @since CUPS 2.0/OS 10.10@
562 int /* O - 0 on success, -1 on error */
564 const char *path
, /* I - Keychain/PKCS#12 path */
565 cups_array_t
**credentials
, /* IO - Credentials */
566 const char *common_name
) /* I - Common name for credentials */
568 cups_file_t
*fp
; /* Certificate file */
569 char filename
[1024], /* filename.crt */
570 temp
[1024], /* Temporary string */
571 line
[256]; /* Base64-encoded line */
572 unsigned char *data
= NULL
; /* Buffer for cert data */
573 size_t alloc_data
= 0, /* Bytes allocated */
574 num_data
= 0; /* Bytes used */
575 int decoded
; /* Bytes decoded */
578 if (!credentials
|| !common_name
)
582 path
= http_gnutls_default_path(temp
, sizeof(temp
));
586 http_gnutls_make_path(filename
, sizeof(filename
), path
, common_name
, "crt");
588 if ((fp
= cupsFileOpen(filename
, "r")) == NULL
)
591 while (cupsFileGets(fp
, line
, sizeof(line
)))
593 if (!strcmp(line
, "-----BEGIN CERTIFICATE-----"))
598 * Missing END CERTIFICATE...
601 httpFreeCredentials(*credentials
);
606 else if (!strcmp(line
, "-----END CERTIFICATE-----"))
614 httpFreeCredentials(*credentials
);
620 *credentials
= cupsArrayNew(NULL
, NULL
);
622 if (httpAddCredential(*credentials
, data
, num_data
))
624 httpFreeCredentials(*credentials
);
641 else if ((num_data
+ strlen(line
)) >= alloc_data
)
643 unsigned char *tdata
= realloc(data
, alloc_data
+ 1024);
644 /* Expanded buffer */
648 httpFreeCredentials(*credentials
);
657 decoded
= alloc_data
- num_data
;
658 httpDecode64_2((char *)data
+ num_data
, &decoded
, line
);
659 num_data
+= (size_t)decoded
;
668 * Missing END CERTIFICATE...
671 httpFreeCredentials(*credentials
);
678 return (*credentials
? 0 : -1);
683 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
685 * @since CUPS 2.0/OS 10.10@
688 int /* O - -1 on error, 0 on success */
690 const char *path
, /* I - Keychain/PKCS#12 path */
691 cups_array_t
*credentials
, /* I - Credentials */
692 const char *common_name
) /* I - Common name for credentials */
694 cups_file_t
*fp
; /* Certificate file */
695 char filename
[1024], /* filename.crt */
696 nfilename
[1024],/* filename.crt.N */
697 temp
[1024], /* Temporary string */
698 line
[256]; /* Base64-encoded line */
699 const unsigned char *ptr
; /* Pointer into certificate */
700 ssize_t remaining
; /* Bytes left */
701 http_credential_t
*cred
; /* Current credential */
704 if (!credentials
|| !common_name
)
708 path
= http_gnutls_default_path(temp
, sizeof(temp
));
712 http_gnutls_make_path(filename
, sizeof(filename
), path
, common_name
, "crt");
713 snprintf(nfilename
, sizeof(nfilename
), "%s.N", filename
);
715 if ((fp
= cupsFileOpen(nfilename
, "w")) == NULL
)
718 fchmod(cupsFileNumber(fp
), 0600);
720 for (cred
= (http_credential_t
*)cupsArrayFirst(credentials
);
722 cred
= (http_credential_t
*)cupsArrayNext(credentials
))
724 cupsFilePuts(fp
, "-----BEGIN CERTIFICATE-----\n");
725 for (ptr
= cred
->data
, remaining
= (ssize_t
)cred
->datalen
; remaining
> 0; remaining
-= 45, ptr
+= 45)
727 httpEncode64_2(line
, sizeof(line
), (char *)ptr
, remaining
> 45 ? 45 : remaining
);
728 cupsFilePrintf(fp
, "%s\n", line
);
730 cupsFilePuts(fp
, "-----END CERTIFICATE-----\n");
735 return (rename(nfilename
, filename
));
740 * 'http_gnutls_create_credential()' - Create a single credential in the internal format.
743 static gnutls_x509_crt_t
/* O - Certificate */
744 http_gnutls_create_credential(
745 http_credential_t
*credential
) /* I - Credential */
747 int result
; /* Result from GNU TLS */
748 gnutls_x509_crt_t cert
; /* Certificate */
749 gnutls_datum_t datum
; /* Data record */
752 DEBUG_printf(("3http_gnutls_create_credential(credential=%p)", credential
));
757 if ((result
= gnutls_x509_crt_init(&cert
)) < 0)
759 DEBUG_printf(("4http_gnutls_create_credential: init error: %s", gnutls_strerror(result
)));
763 datum
.data
= credential
->data
;
764 datum
.size
= credential
->datalen
;
766 if ((result
= gnutls_x509_crt_import(cert
, &datum
, GNUTLS_X509_FMT_DER
)) < 0)
768 DEBUG_printf(("4http_gnutls_create_credential: import error: %s", gnutls_strerror(result
)));
770 gnutls_x509_crt_deinit(cert
);
779 * 'http_gnutls_default_path()' - Get the default credential store path.
782 static const char * /* O - Path or NULL on error */
783 http_gnutls_default_path(char *buffer
,/* I - Path buffer */
784 size_t bufsize
)/* I - Size of path buffer */
786 const char *home
= getenv("HOME"); /* HOME environment variable */
789 if (getuid() && home
)
791 snprintf(buffer
, bufsize
, "%s/.cups", home
);
792 if (access(buffer
, 0))
794 DEBUG_printf(("1http_gnutls_default_path: Making directory \"%s\".", buffer
));
795 if (mkdir(buffer
, 0700))
797 DEBUG_printf(("1http_gnutls_default_path: Failed to make directory: %s", strerror(errno
)));
802 snprintf(buffer
, bufsize
, "%s/.cups/ssl", home
);
803 if (access(buffer
, 0))
805 DEBUG_printf(("1http_gnutls_default_path: Making directory \"%s\".", buffer
));
806 if (mkdir(buffer
, 0700))
808 DEBUG_printf(("1http_gnutls_default_path: Failed to make directory: %s", strerror(errno
)));
814 strlcpy(buffer
, CUPS_SERVERROOT
"/ssl", bufsize
);
816 DEBUG_printf(("1http_gnutls_default_path: Using default path \"%s\".", buffer
));
823 * 'http_gnutls_make_path()' - Format a filename for a certificate or key file.
826 static const char * /* O - Filename */
827 http_gnutls_make_path(
828 char *buffer
, /* I - Filename buffer */
829 size_t bufsize
, /* I - Size of buffer */
830 const char *dirname
, /* I - Directory */
831 const char *filename
, /* I - Filename (usually hostname) */
832 const char *ext
) /* I - Extension */
834 char *bufptr
, /* Pointer into buffer */
835 *bufend
= buffer
+ bufsize
- 1; /* End of buffer */
838 snprintf(buffer
, bufsize
, "%s/", dirname
);
839 bufptr
= buffer
+ strlen(buffer
);
841 while (*filename
&& bufptr
< bufend
)
843 if (_cups_isalnum(*filename
) || *filename
== '-' || *filename
== '.')
844 *bufptr
++ = *filename
;
854 strlcpy(bufptr
, ext
, (size_t)(bufend
- bufptr
+ 1));
861 * 'http_gnutls_read()' - Read function for the GNU TLS library.
864 static ssize_t
/* O - Number of bytes read or -1 on error */
866 gnutls_transport_ptr_t ptr
, /* I - Connection to server */
867 void *data
, /* I - Buffer */
868 size_t length
) /* I - Number of bytes to read */
870 http_t
*http
; /* HTTP connection */
871 ssize_t bytes
; /* Bytes read */
874 DEBUG_printf(("6http_gnutls_read(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
876 http
= (http_t
*)ptr
;
881 * Make sure we have data before we read...
884 while (!_httpWait(http
, http
->wait_value
, 0))
886 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
889 http
->error
= ETIMEDOUT
;
894 bytes
= recv(http
->fd
, data
, length
, 0);
895 DEBUG_printf(("6http_gnutls_read: bytes=%d", (int)bytes
));
901 * 'http_gnutls_write()' - Write function for the GNU TLS library.
904 static ssize_t
/* O - Number of bytes written or -1 on error */
906 gnutls_transport_ptr_t ptr
, /* I - Connection to server */
907 const void *data
, /* I - Data buffer */
908 size_t length
) /* I - Number of bytes to write */
910 ssize_t bytes
; /* Bytes written */
913 DEBUG_printf(("6http_gnutls_write(ptr=%p, data=%p, length=%d)", ptr
, data
,
915 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
916 DEBUG_printf(("http_gnutls_write: bytes=%d", (int)bytes
));
923 * '_httpTLSInitialize()' - Initialize the TLS stack.
927 _httpTLSInitialize(void)
930 * Initialize GNU TLS...
933 gnutls_global_init();
938 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
941 size_t /* O - Bytes available */
942 _httpTLSPending(http_t
*http
) /* I - HTTP connection */
944 return (gnutls_record_check_pending(http
->tls
));
949 * '_httpTLSRead()' - Read from a SSL/TLS connection.
952 int /* O - Bytes read */
953 _httpTLSRead(http_t
*http
, /* I - Connection to server */
954 char *buf
, /* I - Buffer to store data */
955 int len
) /* I - Length of buffer */
957 ssize_t result
; /* Return value */
960 result
= gnutls_record_recv(http
->tls
, buf
, (size_t)len
);
962 if (result
< 0 && !errno
)
965 * Convert GNU TLS error to errno value...
970 case GNUTLS_E_INTERRUPTED
:
974 case GNUTLS_E_AGAIN
:
986 return ((int)result
);
991 * '_httpTLSSetCredentials()' - Set the TLS credentials.
994 int /* O - Status of connection */
995 _httpTLSSetCredentials(http_t
*http
) /* I - Connection to server */
1004 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
1007 int /* O - 0 on success, -1 on failure */
1008 _httpTLSStart(http_t
*http
) /* I - Connection to server */
1010 char hostname
[256], /* Hostname */
1011 *hostptr
; /* Pointer into hostname */
1012 int status
; /* Status of handshake */
1013 gnutls_certificate_credentials_t
*credentials
;
1014 /* TLS credentials */
1017 DEBUG_printf(("7_httpTLSStart(http=%p)", http
));
1019 if (http
->mode
== _HTTP_MODE_SERVER
&& !tls_keypath
)
1021 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
1022 http
->error
= errno
= EINVAL
;
1023 http
->status
= HTTP_STATUS_ERROR
;
1024 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Server credentials not set."), 1);
1029 credentials
= (gnutls_certificate_credentials_t
*)
1030 malloc(sizeof(gnutls_certificate_credentials_t
));
1031 if (credentials
== NULL
)
1033 DEBUG_printf(("8_httpStartTLS: Unable to allocate credentials: %s",
1035 http
->error
= errno
;
1036 http
->status
= HTTP_STATUS_ERROR
;
1037 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
1042 gnutls_certificate_allocate_credentials(credentials
);
1043 status
= gnutls_init(&http
->tls
, http
->mode
== _HTTP_MODE_CLIENT
? GNUTLS_CLIENT
: GNUTLS_SERVER
);
1045 status
= gnutls_set_default_priority(http
->tls
);
1050 http
->status
= HTTP_STATUS_ERROR
;
1052 DEBUG_printf(("4_httpTLSStart: Unable to initialize common TLS parameters: %s", gnutls_strerror(status
)));
1053 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, gnutls_strerror(status
), 0);
1055 gnutls_deinit(http
->tls
);
1056 gnutls_certificate_free_credentials(*credentials
);
1063 if (http
->mode
== _HTTP_MODE_CLIENT
)
1066 * Client: get the hostname to use for TLS...
1069 if (httpAddrLocalhost(http
->hostaddr
))
1071 strlcpy(hostname
, "localhost", sizeof(hostname
));
1076 * Otherwise make sure the hostname we have does not end in a trailing dot.
1079 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
1080 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
1085 status
= gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, hostname
, strlen(hostname
));
1090 * Server: get certificate and private key...
1093 char crtfile
[1024], /* Certificate file */
1094 keyfile
[1024]; /* Private key file */
1095 int have_creds
= 0; /* Have credentials? */
1098 if (http
->fields
[HTTP_FIELD_HOST
][0])
1101 * Use hostname for TLS upgrade...
1104 strlcpy(hostname
, http
->fields
[HTTP_FIELD_HOST
], sizeof(hostname
));
1109 * Resolve hostname from connection address...
1112 http_addr_t addr
; /* Connection address */
1113 socklen_t addrlen
; /* Length of address */
1115 addrlen
= sizeof(addr
);
1116 if (getsockname(http
->fd
, (struct sockaddr
*)&addr
, &addrlen
))
1118 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno
)));
1121 else if (httpAddrLocalhost(&addr
))
1125 httpAddrLookup(&addr
, hostname
, sizeof(hostname
));
1126 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname
));
1130 if (isdigit(hostname
[0] & 255) || hostname
[0] == '[')
1131 hostname
[0] = '\0'; /* Don't allow numeric addresses */
1135 http_gnutls_make_path(crtfile
, sizeof(crtfile
), tls_keypath
, hostname
, "crt");
1136 http_gnutls_make_path(keyfile
, sizeof(keyfile
), tls_keypath
, hostname
, "key");
1138 have_creds
= !access(crtfile
, 0) && !access(keyfile
, 0);
1140 else if (tls_common_name
)
1142 http_gnutls_make_path(crtfile
, sizeof(crtfile
), tls_keypath
, tls_common_name
, "crt");
1143 http_gnutls_make_path(keyfile
, sizeof(keyfile
), tls_keypath
, tls_common_name
, "key");
1145 have_creds
= !access(crtfile
, 0) && !access(keyfile
, 0);
1148 if (!have_creds
&& tls_auto_create
&& (hostname
[0] || tls_common_name
))
1150 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname
[0] ? hostname
: tls_common_name
));
1152 if (!cupsMakeServerCredentials(tls_keypath
, hostname
[0] ? hostname
: tls_common_name
, 0, NULL
, time(NULL
) + 365 * 86400))
1154 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
1155 http
->error
= errno
= EINVAL
;
1156 http
->status
= HTTP_STATUS_ERROR
;
1157 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to create server credentials."), 1);
1163 DEBUG_printf(("4_httpTLSStart: Using certificate \"%s\" and private key \"%s\".", crtfile
, keyfile
));
1165 status
= gnutls_certificate_set_x509_key_file(*credentials
, crtfile
, keyfile
, GNUTLS_X509_FMT_PEM
);
1169 status
= gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
1174 http
->status
= HTTP_STATUS_ERROR
;
1176 DEBUG_printf(("4_httpTLSStart: Unable to complete client/server setup: %s", gnutls_strerror(status
)));
1177 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, gnutls_strerror(status
), 0);
1179 gnutls_deinit(http
->tls
);
1180 gnutls_certificate_free_credentials(*credentials
);
1187 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr_t
)http
);
1188 gnutls_transport_set_pull_function(http
->tls
, http_gnutls_read
);
1189 gnutls_transport_set_pull_timeout_function(http
->tls
, (gnutls_pull_timeout_func
)httpWait
);
1190 gnutls_transport_set_push_function(http
->tls
, http_gnutls_write
);
1192 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
1194 DEBUG_printf(("5_httpStartTLS: gnutls_handshake returned %d (%s)",
1195 status
, gnutls_strerror(status
)));
1197 if (gnutls_error_is_fatal(status
))
1200 http
->status
= HTTP_STATUS_ERROR
;
1202 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, gnutls_strerror(status
), 0);
1204 gnutls_deinit(http
->tls
);
1205 gnutls_certificate_free_credentials(*credentials
);
1213 http
->tls_credentials
= credentials
;
1220 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1224 _httpTLSStop(http_t
*http
) /* I - Connection to server */
1226 int error
; /* Error code */
1229 error
= gnutls_bye(http
->tls
, http
->mode
== _HTTP_MODE_CLIENT
? GNUTLS_SHUT_RDWR
: GNUTLS_SHUT_WR
);
1230 if (error
!= GNUTLS_E_SUCCESS
)
1231 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, gnutls_strerror(errno
), 0);
1233 gnutls_deinit(http
->tls
);
1236 if (http
->tls_credentials
)
1238 gnutls_certificate_free_credentials(*(http
->tls_credentials
));
1239 free(http
->tls_credentials
);
1240 http
->tls_credentials
= NULL
;
1246 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1249 int /* O - Bytes written */
1250 _httpTLSWrite(http_t
*http
, /* I - Connection to server */
1251 const char *buf
, /* I - Buffer holding data */
1252 int len
) /* I - Length of buffer */
1254 ssize_t result
; /* Return value */
1257 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
1259 result
= gnutls_record_send(http
->tls
, buf
, (size_t)len
);
1261 if (result
< 0 && !errno
)
1264 * Convert GNU TLS error to errno value...
1269 case GNUTLS_E_INTERRUPTED
:
1273 case GNUTLS_E_AGAIN
:
1285 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
1287 return ((int)result
);