From: Michael R Sweet Date: Tue, 22 Mar 2022 21:49:59 +0000 (-0400) Subject: Save initial work on integrating OpenSSL support back into libcups. X-Git-Tag: v2.4.2~29^2~13 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=3e9f2c04d620cccf2a09c43791ed9d8bb717c9da;p=thirdparty%2Fcups.git Save initial work on integrating OpenSSL support back into libcups. --- diff --git a/config-scripts/cups-tls.m4 b/config-scripts/cups-tls.m4 index 93100011ff..880ea559b0 100644 --- a/config-scripts/cups-tls.m4 +++ b/config-scripts/cups-tls.m4 @@ -9,10 +9,10 @@ dnl Licensed under Apache License v2.0. See the file "LICENSE" for more dnl information. dnl -AC_ARG_WITH([tls], AS_HELP_STRING([--with-tls=...], [use cdsa (macOS) or gnutls for TLS support])) +AC_ARG_WITH([tls], AS_HELP_STRING([--with-tls=...], [use cdsa (macOS), gnutls, or openssl for TLS support])) AS_IF([test "x$with_tls" = x], [ with_tls="yes" -], [test "$with_tls" != cdsa -a "$with_tls" != gnutls -a "$with_tls" != no -a "$with_tls" != yes], [ +], [test "$with_tls" != cdsa -a "$with_tls" != gnutls -a "$with_tls" != openssl -a "$with_tls" != no -a "$with_tls" != yes], [ AC_MSG_ERROR([Unsupported --with-tls value "$with_tls" specified.]) ]) @@ -21,30 +21,28 @@ TLSLIBS="" have_tls="0" CUPS_SERVERKEYCHAIN="" -dnl First try using CSDA SSL (macOS)... -AS_IF([test $with_tls = yes -o $with_tls = cdsa], [ - dnl Look for CDSA... - AS_IF([test $host_os_name = darwin], [ - AC_CHECK_HEADER([Security/SecureTransport.h], [ +dnl First look for OpenSSL/LibreSSL... +AS_IF([test $with_tls = yes -o $with_tls = openssl], [ + AS_IF([test "x$PKGCONFIG" != x], [ + AC_MSG_CHECKING([for openssl package]) + AS_IF([$PKGCONFIG --exists openssl], [ + AC_MSG_RESULT([yes]) have_tls="1" - with_tls="cdsa" + with_tls="openssl" + TLSLIBS="$($PKGCONFIG --libs openssl)" + TLSFLAGS="$($PKGCONFIG --cflags openssl)" + PKGCONFIG_REQUIRES="$PKGCONFIG_REQUIRES openssl" AC_DEFINE([HAVE_TLS], [1], [Do we support TLS?]) - AC_DEFINE([HAVE_CDSASSL], [1], [Do we have the macOS SecureTransport API?]) - CUPS_SERVERKEYCHAIN="/Library/Keychains/System.keychain" - - dnl Check for the various security headers... - AC_CHECK_HEADER([Security/SecCertificate.h], [ - AC_DEFINE([HAVE_SECCERTIFICATE_H], [1], [Have the header?]) - ]) - AC_CHECK_HEADER([Security/SecItem.h], [ - AC_DEFINE([HAVE_SECITEM_H], [1], [Have the header?]) - ]) - AC_CHECK_HEADER([Security/SecPolicy.h], [ - AC_DEFINE([HAVE_SECPOLICY_H], [1], [Have the header?]) + ]) + AC_CHECK_HEADER([Security/SecItem.h], [ + AC_DEFINE([HAVE_SECITEM_H], [1], [Have the header?]) + ]) + AC_CHECK_HEADER([Security/SecPolicy.h], [ + AC_DEFINE([HAVE_SECPOLICY_H], [1], [Have the &5 +printf %s "checking for openssl package... " >&6; } + if $PKGCONFIG --exists openssl then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } have_tls="1" - with_tls="cdsa" + with_tls="openssl" + TLSLIBS="$($PKGCONFIG --libs openssl)" + TLSFLAGS="$($PKGCONFIG --cflags openssl)" + PKGCONFIG_REQUIRES="$PKGCONFIG_REQUIRES openssl" printf "%s\n" "#define HAVE_TLS 1" >>confdefs.h -printf "%s\n" "#define HAVE_CDSASSL 1" >>confdefs.h - - CUPS_SERVERKEYCHAIN="/Library/Keychains/System.keychain" +printf "%s\n" "#define HAVE_OPENSSL 1" >>confdefs.h - ac_fn_c_check_header_compile "$LINENO" "Security/SecCertificate.h" "ac_cv_header_Security_SecCertificate_h" "$ac_includes_default" -if test "x$ac_cv_header_Security_SecCertificate_h" = xyes -then : +else $as_nop -printf "%s\n" "#define HAVE_SECCERTIFICATE_H 1" >>confdefs.h - + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } fi - ac_fn_c_check_header_compile "$LINENO" "Security/SecItem.h" "ac_cv_header_Security_SecItem_h" "$ac_includes_default" -if test "x$ac_cv_header_Security_SecItem_h" = xyes -then : - - -printf "%s\n" "#define HAVE_SECITEM_H 1" >>confdefs.h - - fi - ac_fn_c_check_header_compile "$LINENO" "Security/SecPolicy.h" "ac_cv_header_Security_SecPolicy_h" "$ac_includes_default" -if test "x$ac_cv_header_Security_SecPolicy_h" = xyes + if test $have_tls = 1 then : + CUPS_SERVERKEYCHAIN="ssl" -printf "%s\n" "#define HAVE_SECPOLICY_H 1" >>confdefs.h - - -fi - - -fi - - -elif test $with_tls = cdsa +elif test $with_tls = openssl then : - as_fn_error $? "--with-tls=cdsa is not compatible with your host operating system." "$LINENO" 5 + as_fn_error $? "--with-tls=openssl was specified but neither the OpenSSL nor LibreSSL library were found." "$LINENO" 5 fi @@ -9929,6 +9914,69 @@ fi fi +if test $with_tls = yes -o $with_tls = cdsa +then : + + if test $host_os_name = darwin +then : + + ac_fn_c_check_header_compile "$LINENO" "Security/SecureTransport.h" "ac_cv_header_Security_SecureTransport_h" "$ac_includes_default" +if test "x$ac_cv_header_Security_SecureTransport_h" = xyes +then : + + have_tls="1" + with_tls="cdsa" + +printf "%s\n" "#define HAVE_TLS 1" >>confdefs.h + + +printf "%s\n" "#define HAVE_CDSASSL 1" >>confdefs.h + + CUPS_SERVERKEYCHAIN="/Library/Keychains/System.keychain" + + ac_fn_c_check_header_compile "$LINENO" "Security/SecCertificate.h" "ac_cv_header_Security_SecCertificate_h" "$ac_includes_default" +if test "x$ac_cv_header_Security_SecCertificate_h" = xyes +then : + + +printf "%s\n" "#define HAVE_SECCERTIFICATE_H 1" >>confdefs.h + + +fi + + ac_fn_c_check_header_compile "$LINENO" "Security/SecItem.h" "ac_cv_header_Security_SecItem_h" "$ac_includes_default" +if test "x$ac_cv_header_Security_SecItem_h" = xyes +then : + + +printf "%s\n" "#define HAVE_SECITEM_H 1" >>confdefs.h + + +fi + + ac_fn_c_check_header_compile "$LINENO" "Security/SecPolicy.h" "ac_cv_header_Security_SecPolicy_h" "$ac_includes_default" +if test "x$ac_cv_header_Security_SecPolicy_h" = xyes +then : + + +printf "%s\n" "#define HAVE_SECPOLICY_H 1" >>confdefs.h + + +fi + + +fi + + +elif test $with_tls = cdsa +then : + + as_fn_error $? "--with-tls=cdsa is not compatible with your host operating system." "$LINENO" 5 + +fi + +fi + IPPALIASES="http" if test $have_tls = 1 then : diff --git a/cups/Makefile b/cups/Makefile index 798b32199f..4110b98d0b 100644 --- a/cups/Makefile +++ b/cups/Makefile @@ -774,4 +774,4 @@ sloc: # include Dependencies -tls.o: tls-darwin.c tls-gnutls.c tls-sspi.c +tls.o: tls-darwin.c tls-gnutls.c tls-openssl.c tls-sspi.c diff --git a/cups/http-private.h b/cups/http-private.h index 212fea7c49..fcf4c74a8e 100644 --- a/cups/http-private.h +++ b/cups/http-private.h @@ -66,7 +66,11 @@ typedef int socklen_t; # include # include "ipp-private.h" -# ifdef HAVE_GNUTLS +# ifdef HAVE_OPENSSL +# include +# include +# include +# elif defined(HAVE_GNUTLS) # include # include # elif defined(HAVE_CDSASSL) @@ -87,7 +91,7 @@ typedef int socklen_t; # define SECURITY_WIN32 # include # include -# endif /* HAVE_GNUTLS */ +# endif /* HAVE_OPENSSL */ # ifndef _WIN32 # include @@ -140,11 +144,11 @@ extern "C" { * Types and functions for SSL support... */ -# ifdef HAVE_GNUTLS -/* - * The GNU TLS library is more of a "bare metal" SSL/TLS library... - */ +# ifdef HAVE_OPENSSL +typedef SSL *http_tls_t; +typedef X509 *http_tls_credentials_t; +# elif defined(HAVE_GNUTLS) typedef gnutls_session_t http_tls_t; typedef gnutls_certificate_credentials_t *http_tls_credentials_t; @@ -190,7 +194,7 @@ typedef PCCERT_CONTEXT http_tls_credentials_t; typedef void *http_tls_t; typedef void *http_tls_credentials_t; -# endif /* HAVE_GNUTLS */ +# endif /* HAVE_OPENSSL */ typedef enum _http_coding_e /**** HTTP content coding enumeration ****/ { diff --git a/cups/tls-openssl.c b/cups/tls-openssl.c new file mode 100644 index 0000000000..714b6da23d --- /dev/null +++ b/cups/tls-openssl.c @@ -0,0 +1,1729 @@ +/* + * TLS support code for CUPS using GNU TLS. + * + * Copyright © 2020-2022 by OpenPrinting + * Copyright © 2007-2019 by Apple Inc. + * Copyright © 1997-2007 by Easy Software Products, all rights reserved. + * + * Licensed under Apache License v2.0. See the file "LICENSE" for more + * information. + */ + +/**** This file is included from tls.c ****/ + +/* + * Include necessary headers... + */ + +#include + + +/* + * Local globals... + */ + +static int tls_auto_create = 0; + /* Auto-create self-signed certs? */ +static char *tls_common_name = NULL; + /* Default common name */ +static X509_CRL *tls_crl = NULL;/* Certificate revocation list */ +static char *tls_keypath = NULL; + /* Server cert keychain path */ +static _cups_mutex_t tls_mutex = _CUPS_MUTEX_INITIALIZER; + /* Mutex for keychain/certs */ +static int tls_options = -1,/* Options for TLS connections */ + tls_min_version = _HTTP_TLS_1_0, + tls_max_version = _HTTP_TLS_MAX; + + +/* + * Local functions... + */ + +static X509 *http_openssl_create_credential(http_credential_t *credential); +static const char *http_openssl_default_path(char *buffer, size_t bufsize); +static void http_openssl_load_crl(void); +static const char *http_openssl_make_path(char *buffer, size_t bufsize, const char *dirname, const char *filename, const char *ext); +static ssize_t http_openssl_read(openssl_transport_ptr_t ptr, void *data, size_t length); +static ssize_t http_openssl_write(openssl_transport_ptr_t ptr, const void *data, size_t length); + + +/* + * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair. + * + * @since CUPS 2.0/OS 10.10@ + */ + +int /* O - 1 on success, 0 on failure */ +cupsMakeServerCredentials( + const char *path, /* I - Path to keychain/directory */ + const char *common_name, /* I - Common name */ + int num_alt_names, /* I - Number of subject alternate names */ + const char **alt_names, /* I - Subject Alternate Names */ + time_t expiration_date) /* I - Expiration date */ +{ + openssl_x509_crt_t crt; /* Self-signed certificate */ + openssl_x509_privkey_t key; /* Encryption private key */ + char temp[1024], /* Temporary directory name */ + crtfile[1024], /* Certificate filename */ + keyfile[1024]; /* Private key filename */ + cups_lang_t *language; /* Default language info */ + cups_file_t *fp; /* Key/cert file */ + unsigned char buffer[8192]; /* Buffer for x509 data */ + size_t bytes; /* Number of bytes of data */ + unsigned char serial[4]; /* Serial number buffer */ + time_t curtime; /* Current time */ + int result; /* Result of GNU TLS calls */ + + + 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)); + + /* + * Filenames... + */ + + if (!path) + path = http_openssl_default_path(temp, sizeof(temp)); + + if (!path || !common_name) + { + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0); + return (0); + } + + http_openssl_make_path(crtfile, sizeof(crtfile), path, common_name, "crt"); + http_openssl_make_path(keyfile, sizeof(keyfile), path, common_name, "key"); + + /* + * Create the encryption key... + */ + + DEBUG_puts("1cupsMakeServerCredentials: Creating key pair."); + + openssl_x509_privkey_init(&key); + openssl_x509_privkey_generate(key, GNUTLS_PK_RSA, 2048, 0); + + DEBUG_puts("1cupsMakeServerCredentials: Key pair created."); + + /* + * Save it... + */ + + bytes = sizeof(buffer); + + if ((result = openssl_x509_privkey_export(key, GNUTLS_X509_FMT_PEM, buffer, &bytes)) < 0) + { + DEBUG_printf(("1cupsMakeServerCredentials: Unable to export private key: %s", openssl_strerror(result))); + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, openssl_strerror(result), 0); + openssl_x509_privkey_deinit(key); + return (0); + } + else if ((fp = cupsFileOpen(keyfile, "w")) != NULL) + { + DEBUG_printf(("1cupsMakeServerCredentials: Writing private key to \"%s\".", keyfile)); + cupsFileWrite(fp, (char *)buffer, bytes); + cupsFileClose(fp); + } + else + { + DEBUG_printf(("1cupsMakeServerCredentials: Unable to create private key file \"%s\": %s", keyfile, strerror(errno))); + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0); + openssl_x509_privkey_deinit(key); + return (0); + } + + /* + * Create the self-signed certificate... + */ + + DEBUG_puts("1cupsMakeServerCredentials: Generating self-signed X.509 certificate."); + + language = cupsLangDefault(); + curtime = time(NULL); + serial[0] = curtime >> 24; + serial[1] = curtime >> 16; + serial[2] = curtime >> 8; + serial[3] = curtime; + + openssl_x509_crt_init(&crt); + if (strlen(language->language) == 5) + openssl_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0, + language->language + 3, 2); + else + openssl_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0, + "US", 2); + openssl_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COMMON_NAME, 0, + common_name, strlen(common_name)); + openssl_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATION_NAME, 0, + common_name, strlen(common_name)); + openssl_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME, + 0, "Unknown", 7); + openssl_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME, 0, + "Unknown", 7); + openssl_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_LOCALITY_NAME, 0, + "Unknown", 7); +/* openssl_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_PKCS9_EMAIL, 0, + ServerAdmin, strlen(ServerAdmin));*/ + openssl_x509_crt_set_key(crt, key); + openssl_x509_crt_set_serial(crt, serial, sizeof(serial)); + openssl_x509_crt_set_activation_time(crt, curtime); + openssl_x509_crt_set_expiration_time(crt, curtime + 10 * 365 * 86400); + openssl_x509_crt_set_ca_status(crt, 0); + openssl_x509_crt_set_subject_alt_name(crt, GNUTLS_SAN_DNSNAME, common_name, (unsigned)strlen(common_name), GNUTLS_FSAN_SET); + if (!strchr(common_name, '.')) + { + /* + * Add common_name.local to the list, too... + */ + + char localname[256]; /* hostname.local */ + + snprintf(localname, sizeof(localname), "%s.local", common_name); + openssl_x509_crt_set_subject_alt_name(crt, GNUTLS_SAN_DNSNAME, localname, (unsigned)strlen(localname), GNUTLS_FSAN_APPEND); + } + openssl_x509_crt_set_subject_alt_name(crt, GNUTLS_SAN_DNSNAME, "localhost", 9, GNUTLS_FSAN_APPEND); + if (num_alt_names > 0) + { + int i; /* Looping var */ + + for (i = 0; i < num_alt_names; i ++) + { + if (strcmp(alt_names[i], "localhost")) + { + openssl_x509_crt_set_subject_alt_name(crt, GNUTLS_SAN_DNSNAME, alt_names[i], (unsigned)strlen(alt_names[i]), GNUTLS_FSAN_APPEND); + } + } + } + openssl_x509_crt_set_key_purpose_oid(crt, GNUTLS_KP_TLS_WWW_SERVER, 0); + openssl_x509_crt_set_key_usage(crt, GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT); + openssl_x509_crt_set_version(crt, 3); + + bytes = sizeof(buffer); + if (openssl_x509_crt_get_key_id(crt, 0, buffer, &bytes) >= 0) + openssl_x509_crt_set_subject_key_id(crt, buffer, bytes); + + openssl_x509_crt_sign(crt, crt, key); + + /* + * Save it... + */ + + bytes = sizeof(buffer); + if ((result = openssl_x509_crt_export(crt, GNUTLS_X509_FMT_PEM, buffer, &bytes)) < 0) + { + DEBUG_printf(("1cupsMakeServerCredentials: Unable to export public key and X.509 certificate: %s", openssl_strerror(result))); + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, openssl_strerror(result), 0); + openssl_x509_crt_deinit(crt); + openssl_x509_privkey_deinit(key); + return (0); + } + else if ((fp = cupsFileOpen(crtfile, "w")) != NULL) + { + DEBUG_printf(("1cupsMakeServerCredentials: Writing public key and X.509 certificate to \"%s\".", crtfile)); + cupsFileWrite(fp, (char *)buffer, bytes); + cupsFileClose(fp); + } + else + { + DEBUG_printf(("1cupsMakeServerCredentials: Unable to create public key and X.509 certificate file \"%s\": %s", crtfile, strerror(errno))); + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0); + openssl_x509_crt_deinit(crt); + openssl_x509_privkey_deinit(key); + return (0); + } + + /* + * Cleanup... + */ + + openssl_x509_crt_deinit(crt); + openssl_x509_privkey_deinit(key); + + DEBUG_puts("1cupsMakeServerCredentials: Successfully created credentials."); + + return (1); +} + + +/* + * 'cupsSetServerCredentials()' - Set the default server credentials. + * + * Note: The server credentials are used by all threads in the running process. + * This function is threadsafe. + * + * @since CUPS 2.0/OS 10.10@ + */ + +int /* O - 1 on success, 0 on failure */ +cupsSetServerCredentials( + const char *path, /* I - Path to keychain/directory */ + const char *common_name, /* I - Default common name for server */ + int auto_create) /* I - 1 = automatically create self-signed certificates */ +{ + char temp[1024]; /* Default path buffer */ + + + DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path, common_name, auto_create)); + + /* + * Use defaults as needed... + */ + + if (!path) + path = http_openssl_default_path(temp, sizeof(temp)); + + /* + * Range check input... + */ + + if (!path || !common_name) + { + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0); + return (0); + } + + _cupsMutexLock(&tls_mutex); + + /* + * Free old values... + */ + + if (tls_keypath) + _cupsStrFree(tls_keypath); + + if (tls_common_name) + _cupsStrFree(tls_common_name); + + /* + * Save the new values... + */ + + tls_keypath = _cupsStrAlloc(path); + tls_auto_create = auto_create; + tls_common_name = _cupsStrAlloc(common_name); + + _cupsMutexUnlock(&tls_mutex); + + return (1); +} + + +/* + * 'httpCopyCredentials()' - Copy the credentials associated with the peer in + * an encrypted connection. + * + * @since CUPS 1.5/macOS 10.7@ + */ + +int /* O - Status of call (0 = success) */ +httpCopyCredentials( + http_t *http, /* I - Connection to server */ + cups_array_t **credentials) /* O - Array of credentials */ +{ + unsigned count; /* Number of certificates */ + const openssl_datum_t *certs; /* Certificates */ + + + DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", http, credentials)); + + if (credentials) + *credentials = NULL; + + if (!http || !http->tls || !credentials) + return (-1); + + *credentials = cupsArrayNew(NULL, NULL); + certs = openssl_certificate_get_peers(http->tls, &count); + + DEBUG_printf(("1httpCopyCredentials: certs=%p, count=%u", certs, count)); + + if (certs && count) + { + while (count > 0) + { + httpAddCredential(*credentials, certs->data, certs->size); + certs ++; + count --; + } + } + + return (0); +} + + +/* + * '_httpCreateCredentials()' - Create credentials in the internal format. + */ + +http_tls_credentials_t /* O - Internal credentials */ +_httpCreateCredentials( + cups_array_t *credentials) /* I - Array of credentials */ +{ + (void)credentials; + + return (NULL); +} + + +/* + * '_httpFreeCredentials()' - Free internal credentials. + */ + +void +_httpFreeCredentials( + http_tls_credentials_t credentials) /* I - Internal credentials */ +{ + (void)credentials; +} + + +/* + * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name. + * + * @since CUPS 2.0/OS 10.10@ + */ + +int /* O - 1 if valid, 0 otherwise */ +httpCredentialsAreValidForName( + cups_array_t *credentials, /* I - Credentials */ + const char *common_name) /* I - Name to check */ +{ + openssl_x509_crt_t cert; /* Certificate */ + int result = 0; /* Result */ + + + cert = http_openssl_create_credential((http_credential_t *)cupsArrayFirst(credentials)); + if (cert) + { + result = openssl_x509_crt_check_hostname(cert, common_name) != 0; + + if (result) + { + openssl_x509_crl_iter_t iter = NULL; + /* Iterator */ + unsigned char cserial[1024], /* Certificate serial number */ + rserial[1024]; /* Revoked serial number */ + size_t cserial_size, /* Size of cert serial number */ + rserial_size; /* Size of revoked serial number */ + + _cupsMutexLock(&tls_mutex); + + if (openssl_x509_crl_get_crt_count(tls_crl) > 0) + { + cserial_size = sizeof(cserial); + openssl_x509_crt_get_serial(cert, cserial, &cserial_size); + + rserial_size = sizeof(rserial); + + while (!openssl_x509_crl_iter_crt_serial(tls_crl, &iter, rserial, &rserial_size, NULL)) + { + if (cserial_size == rserial_size && !memcmp(cserial, rserial, rserial_size)) + { + result = 0; + break; + } + + rserial_size = sizeof(rserial); + } + openssl_x509_crl_iter_deinit(iter); + } + + _cupsMutexUnlock(&tls_mutex); + } + + openssl_x509_crt_deinit(cert); + } + + return (result); +} + + +/* + * 'httpCredentialsGetTrust()' - Return the trust of credentials. + * + * @since CUPS 2.0/OS 10.10@ + */ + +http_trust_t /* O - Level of trust */ +httpCredentialsGetTrust( + cups_array_t *credentials, /* I - Credentials */ + const char *common_name) /* I - Common name for trust lookup */ +{ + http_trust_t trust = HTTP_TRUST_OK; + /* Trusted? */ + openssl_x509_crt_t cert; /* Certificate */ + cups_array_t *tcreds = NULL; /* Trusted credentials */ + _cups_globals_t *cg = _cupsGlobals(); + /* Per-thread globals */ + + + if (!common_name) + { + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No common name specified."), 1); + return (HTTP_TRUST_UNKNOWN); + } + + if ((cert = http_openssl_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL) + { + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to create credentials from array."), 1); + return (HTTP_TRUST_UNKNOWN); + } + + if (cg->any_root < 0) + { + _cupsSetDefaults(); + http_openssl_load_crl(); + } + + /* + * Look this common name up in the default keychains... + */ + + httpLoadCredentials(NULL, &tcreds, common_name); + + if (tcreds) + { + char credentials_str[1024], /* String for incoming credentials */ + tcreds_str[1024]; /* String for saved credentials */ + + httpCredentialsString(credentials, credentials_str, sizeof(credentials_str)); + httpCredentialsString(tcreds, tcreds_str, sizeof(tcreds_str)); + + if (strcmp(credentials_str, tcreds_str)) + { + /* + * Credentials don't match, let's look at the expiration date of the new + * credentials and allow if the new ones have a later expiration... + */ + + if (!cg->trust_first) + { + /* + * Do not trust certificates on first use... + */ + + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Trust on first use is disabled."), 1); + + trust = HTTP_TRUST_INVALID; + } + else if (httpCredentialsGetExpiration(credentials) <= httpCredentialsGetExpiration(tcreds)) + { + /* + * The new credentials are not newly issued... + */ + + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("New credentials are older than stored credentials."), 1); + + trust = HTTP_TRUST_INVALID; + } + else if (!httpCredentialsAreValidForName(credentials, common_name)) + { + /* + * The common name does not match the issued certificate... + */ + + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("New credentials are not valid for name."), 1); + + trust = HTTP_TRUST_INVALID; + } + else if (httpCredentialsGetExpiration(tcreds) < time(NULL)) + { + /* + * Save the renewed credentials... + */ + + trust = HTTP_TRUST_RENEWED; + + httpSaveCredentials(NULL, credentials, common_name); + } + } + + httpFreeCredentials(tcreds); + } + else if (cg->validate_certs && !httpCredentialsAreValidForName(credentials, common_name)) + { + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No stored credentials, not valid for name."), 1); + trust = HTTP_TRUST_INVALID; + } + else if (!cg->trust_first) + { + /* + * See if we have a site CA certificate we can compare... + */ + + if (!httpLoadCredentials(NULL, &tcreds, "site")) + { + if (cupsArrayCount(credentials) != (cupsArrayCount(tcreds) + 1)) + { + /* + * Certificate isn't directly generated from the CA cert... + */ + + trust = HTTP_TRUST_INVALID; + } + else + { + /* + * Do a tail comparison of the two certificates... + */ + + http_credential_t *a, *b; /* Certificates */ + + for (a = (http_credential_t *)cupsArrayFirst(tcreds), b = (http_credential_t *)cupsArrayIndex(credentials, 1); + a && b; + a = (http_credential_t *)cupsArrayNext(tcreds), b = (http_credential_t *)cupsArrayNext(credentials)) + if (a->datalen != b->datalen || memcmp(a->data, b->data, a->datalen)) + break; + + if (a || b) + trust = HTTP_TRUST_INVALID; + } + + if (trust != HTTP_TRUST_OK) + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Credentials do not validate against site CA certificate."), 1); + } + else + { + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Trust on first use is disabled."), 1); + trust = HTTP_TRUST_INVALID; + } + } + + if (trust == HTTP_TRUST_OK && !cg->expired_certs) + { + time_t curtime; /* Current date/time */ + + time(&curtime); + if (curtime < openssl_x509_crt_get_activation_time(cert) || + curtime > openssl_x509_crt_get_expiration_time(cert)) + { + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Credentials have expired."), 1); + trust = HTTP_TRUST_EXPIRED; + } + } + + if (trust == HTTP_TRUST_OK && !cg->any_root && cupsArrayCount(credentials) == 1) + { + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Self-signed credentials are blocked."), 1); + trust = HTTP_TRUST_INVALID; + } + + openssl_x509_crt_deinit(cert); + + return (trust); +} + + +/* + * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials. + * + * @since CUPS 2.0/OS 10.10@ + */ + +time_t /* O - Expiration date of credentials */ +httpCredentialsGetExpiration( + cups_array_t *credentials) /* I - Credentials */ +{ + openssl_x509_crt_t cert; /* Certificate */ + time_t result = 0; /* Result */ + + + cert = http_openssl_create_credential((http_credential_t *)cupsArrayFirst(credentials)); + if (cert) + { + result = openssl_x509_crt_get_expiration_time(cert); + openssl_x509_crt_deinit(cert); + } + + return (result); +} + + +/* + * 'httpCredentialsString()' - Return a string representing the credentials. + * + * @since CUPS 2.0/OS 10.10@ + */ + +size_t /* O - Total size of credentials string */ +httpCredentialsString( + cups_array_t *credentials, /* I - Credentials */ + char *buffer, /* I - Buffer or @code NULL@ */ + size_t bufsize) /* I - Size of buffer */ +{ + http_credential_t *first; /* First certificate */ + openssl_x509_crt_t cert; /* Certificate */ + + + DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT ")", credentials, buffer, CUPS_LLCAST bufsize)); + + if (!buffer) + return (0); + + if (bufsize > 0) + *buffer = '\0'; + + if ((first = (http_credential_t *)cupsArrayFirst(credentials)) != NULL && + (cert = http_openssl_create_credential(first)) != NULL) + { + char name[256], /* Common name associated with cert */ + issuer[256]; /* Issuer associated with cert */ + size_t len; /* Length of string */ + time_t expiration; /* Expiration date of cert */ + int sigalg; /* Signature algorithm */ + unsigned char md5_digest[16]; /* MD5 result */ + + len = sizeof(name) - 1; + if (openssl_x509_crt_get_dn_by_oid(cert, GNUTLS_OID_X520_COMMON_NAME, 0, 0, name, &len) >= 0) + name[len] = '\0'; + else + strlcpy(name, "unknown", sizeof(name)); + + len = sizeof(issuer) - 1; + if (openssl_x509_crt_get_issuer_dn_by_oid(cert, GNUTLS_OID_X520_ORGANIZATION_NAME, 0, 0, issuer, &len) >= 0) + issuer[len] = '\0'; + else + strlcpy(issuer, "unknown", sizeof(issuer)); + + expiration = openssl_x509_crt_get_expiration_time(cert); + sigalg = openssl_x509_crt_get_signature_algorithm(cert); + + cupsHashData("md5", first->data, first->datalen, md5_digest, sizeof(md5_digest)); + + snprintf(buffer, bufsize, "%s (issued by %s) / %s / %s / %02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", name, issuer, httpGetDateString(expiration), openssl_sign_get_name((openssl_sign_algorithm_t)sigalg), 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]); + + openssl_x509_crt_deinit(cert); + } + + DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer)); + + return (strlen(buffer)); +} + + +/* + * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file. + * + * @since CUPS 2.0/OS 10.10@ + */ + +int /* O - 0 on success, -1 on error */ +httpLoadCredentials( + const char *path, /* I - Keychain/PKCS#12 path */ + cups_array_t **credentials, /* IO - Credentials */ + const char *common_name) /* I - Common name for credentials */ +{ + cups_file_t *fp; /* Certificate file */ + char filename[1024], /* filename.crt */ + temp[1024], /* Temporary string */ + line[256]; /* Base64-encoded line */ + unsigned char *data = NULL; /* Buffer for cert data */ + size_t alloc_data = 0, /* Bytes allocated */ + num_data = 0; /* Bytes used */ + int decoded; /* Bytes decoded */ + int in_certificate = 0; + /* In a certificate? */ + + + if (!credentials || !common_name) + return (-1); + + if (!path) + path = http_openssl_default_path(temp, sizeof(temp)); + if (!path) + return (-1); + + http_openssl_make_path(filename, sizeof(filename), path, common_name, "crt"); + + if ((fp = cupsFileOpen(filename, "r")) == NULL) + return (-1); + + while (cupsFileGets(fp, line, sizeof(line))) + { + if (!strcmp(line, "-----BEGIN CERTIFICATE-----")) + { + if (in_certificate) + { + /* + * Missing END CERTIFICATE... + */ + + httpFreeCredentials(*credentials); + *credentials = NULL; + break; + } + + in_certificate = 1; + } + else if (!strcmp(line, "-----END CERTIFICATE-----")) + { + if (!in_certificate || !num_data) + { + /* + * Missing data... + */ + + httpFreeCredentials(*credentials); + *credentials = NULL; + break; + } + + if (!*credentials) + *credentials = cupsArrayNew(NULL, NULL); + + if (httpAddCredential(*credentials, data, num_data)) + { + httpFreeCredentials(*credentials); + *credentials = NULL; + break; + } + + num_data = 0; + in_certificate = 0; + } + else if (in_certificate) + { + if (alloc_data == 0) + { + data = malloc(2048); + alloc_data = 2048; + + if (!data) + break; + } + else if ((num_data + strlen(line)) >= alloc_data) + { + unsigned char *tdata = realloc(data, alloc_data + 1024); + /* Expanded buffer */ + + if (!tdata) + { + httpFreeCredentials(*credentials); + *credentials = NULL; + break; + } + + data = tdata; + alloc_data += 1024; + } + + decoded = alloc_data - num_data; + httpDecode64_2((char *)data + num_data, &decoded, line); + num_data += (size_t)decoded; + } + } + + cupsFileClose(fp); + + if (in_certificate) + { + /* + * Missing END CERTIFICATE... + */ + + httpFreeCredentials(*credentials); + *credentials = NULL; + } + + if (data) + free(data); + + return (*credentials ? 0 : -1); +} + + +/* + * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file. + * + * @since CUPS 2.0/OS 10.10@ + */ + +int /* O - -1 on error, 0 on success */ +httpSaveCredentials( + const char *path, /* I - Keychain/PKCS#12 path */ + cups_array_t *credentials, /* I - Credentials */ + const char *common_name) /* I - Common name for credentials */ +{ + cups_file_t *fp; /* Certificate file */ + char filename[1024], /* filename.crt */ + nfilename[1024],/* filename.crt.N */ + temp[1024], /* Temporary string */ + line[256]; /* Base64-encoded line */ + const unsigned char *ptr; /* Pointer into certificate */ + ssize_t remaining; /* Bytes left */ + http_credential_t *cred; /* Current credential */ + + + if (!credentials || !common_name) + return (-1); + + if (!path) + path = http_openssl_default_path(temp, sizeof(temp)); + if (!path) + return (-1); + + http_openssl_make_path(filename, sizeof(filename), path, common_name, "crt"); + snprintf(nfilename, sizeof(nfilename), "%s.N", filename); + + if ((fp = cupsFileOpen(nfilename, "w")) == NULL) + return (-1); + + fchmod(cupsFileNumber(fp), 0600); + + for (cred = (http_credential_t *)cupsArrayFirst(credentials); + cred; + cred = (http_credential_t *)cupsArrayNext(credentials)) + { + cupsFilePuts(fp, "-----BEGIN CERTIFICATE-----\n"); + for (ptr = cred->data, remaining = (ssize_t)cred->datalen; remaining > 0; remaining -= 45, ptr += 45) + { + httpEncode64_2(line, sizeof(line), (char *)ptr, remaining > 45 ? 45 : remaining); + cupsFilePrintf(fp, "%s\n", line); + } + cupsFilePuts(fp, "-----END CERTIFICATE-----\n"); + } + + cupsFileClose(fp); + + return (rename(nfilename, filename)); +} + + +/* + * 'http_openssl_create_credential()' - Create a single credential in the internal format. + */ + +static openssl_x509_crt_t /* O - Certificate */ +http_openssl_create_credential( + http_credential_t *credential) /* I - Credential */ +{ + int result; /* Result from GNU TLS */ + openssl_x509_crt_t cert; /* Certificate */ + openssl_datum_t datum; /* Data record */ + + + DEBUG_printf(("3http_openssl_create_credential(credential=%p)", credential)); + + if (!credential) + return (NULL); + + if ((result = openssl_x509_crt_init(&cert)) < 0) + { + DEBUG_printf(("4http_openssl_create_credential: init error: %s", openssl_strerror(result))); + return (NULL); + } + + datum.data = credential->data; + datum.size = credential->datalen; + + if ((result = openssl_x509_crt_import(cert, &datum, GNUTLS_X509_FMT_DER)) < 0) + { + DEBUG_printf(("4http_openssl_create_credential: import error: %s", openssl_strerror(result))); + + openssl_x509_crt_deinit(cert); + return (NULL); + } + + return (cert); +} + + +/* + * 'http_openssl_default_path()' - Get the default credential store path. + */ + +static const char * /* O - Path or NULL on error */ +http_openssl_default_path(char *buffer,/* I - Path buffer */ + size_t bufsize)/* I - Size of path buffer */ +{ + _cups_globals_t *cg = _cupsGlobals(); + /* Pointer to library globals */ + + + if (cg->home && getuid()) + { + snprintf(buffer, bufsize, "%s/.cups", cg->home); + if (access(buffer, 0)) + { + DEBUG_printf(("1http_openssl_default_path: Making directory \"%s\".", buffer)); + if (mkdir(buffer, 0700)) + { + DEBUG_printf(("1http_openssl_default_path: Failed to make directory: %s", strerror(errno))); + return (NULL); + } + } + + snprintf(buffer, bufsize, "%s/.cups/ssl", cg->home); + if (access(buffer, 0)) + { + DEBUG_printf(("1http_openssl_default_path: Making directory \"%s\".", buffer)); + if (mkdir(buffer, 0700)) + { + DEBUG_printf(("1http_openssl_default_path: Failed to make directory: %s", strerror(errno))); + return (NULL); + } + } + } + else + strlcpy(buffer, CUPS_SERVERROOT "/ssl", bufsize); + + DEBUG_printf(("1http_openssl_default_path: Using default path \"%s\".", buffer)); + + return (buffer); +} + + +/* + * 'http_openssl_load_crl()' - Load the certificate revocation list, if any. + */ + +static void +http_openssl_load_crl(void) +{ + _cupsMutexLock(&tls_mutex); + + if (!openssl_x509_crl_init(&tls_crl)) + { + cups_file_t *fp; /* CRL file */ + char filename[1024], /* site.crl */ + line[256]; /* Base64-encoded line */ + unsigned char *data = NULL; /* Buffer for cert data */ + size_t alloc_data = 0, /* Bytes allocated */ + num_data = 0; /* Bytes used */ + int decoded; /* Bytes decoded */ + openssl_datum_t datum; /* Data record */ + + + http_openssl_make_path(filename, sizeof(filename), CUPS_SERVERROOT, "site", "crl"); + + if ((fp = cupsFileOpen(filename, "r")) != NULL) + { + while (cupsFileGets(fp, line, sizeof(line))) + { + if (!strcmp(line, "-----BEGIN X509 CRL-----")) + { + if (num_data) + { + /* + * Missing END X509 CRL... + */ + + break; + } + } + else if (!strcmp(line, "-----END X509 CRL-----")) + { + if (!num_data) + { + /* + * Missing data... + */ + + break; + } + + datum.data = data; + datum.size = num_data; + + openssl_x509_crl_import(tls_crl, &datum, GNUTLS_X509_FMT_PEM); + + num_data = 0; + } + else + { + if (alloc_data == 0) + { + data = malloc(2048); + alloc_data = 2048; + + if (!data) + break; + } + else if ((num_data + strlen(line)) >= alloc_data) + { + unsigned char *tdata = realloc(data, alloc_data + 1024); + /* Expanded buffer */ + + if (!tdata) + break; + + data = tdata; + alloc_data += 1024; + } + + decoded = alloc_data - num_data; + httpDecode64_2((char *)data + num_data, &decoded, line); + num_data += (size_t)decoded; + } + } + + cupsFileClose(fp); + + if (data) + free(data); + } + } + + _cupsMutexUnlock(&tls_mutex); +} + + +/* + * 'http_openssl_make_path()' - Format a filename for a certificate or key file. + */ + +static const char * /* O - Filename */ +http_openssl_make_path( + char *buffer, /* I - Filename buffer */ + size_t bufsize, /* I - Size of buffer */ + const char *dirname, /* I - Directory */ + const char *filename, /* I - Filename (usually hostname) */ + const char *ext) /* I - Extension */ +{ + char *bufptr, /* Pointer into buffer */ + *bufend = buffer + bufsize - 1; /* End of buffer */ + + + snprintf(buffer, bufsize, "%s/", dirname); + bufptr = buffer + strlen(buffer); + + while (*filename && bufptr < bufend) + { + if (_cups_isalnum(*filename) || *filename == '-' || *filename == '.') + *bufptr++ = *filename; + else + *bufptr++ = '_'; + + filename ++; + } + + if (bufptr < bufend) + *bufptr++ = '.'; + + strlcpy(bufptr, ext, (size_t)(bufend - bufptr + 1)); + + return (buffer); +} + + +/* + * 'http_openssl_read()' - Read function for the GNU TLS library. + */ + +static ssize_t /* O - Number of bytes read or -1 on error */ +http_openssl_read( + openssl_transport_ptr_t ptr, /* I - Connection to server */ + void *data, /* I - Buffer */ + size_t length) /* I - Number of bytes to read */ +{ + http_t *http; /* HTTP connection */ + ssize_t bytes; /* Bytes read */ + + + DEBUG_printf(("5http_openssl_read(ptr=%p, data=%p, length=%d)", ptr, data, (int)length)); + + http = (http_t *)ptr; + + if (!http->blocking || http->timeout_value > 0.0) + { + /* + * Make sure we have data before we read... + */ + + while (!_httpWait(http, http->wait_value, 0)) + { + if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data)) + continue; + + http->error = ETIMEDOUT; + return (-1); + } + } + + bytes = recv(http->fd, data, length, 0); + DEBUG_printf(("5http_openssl_read: bytes=%d", (int)bytes)); + return (bytes); +} + + +/* + * 'http_openssl_write()' - Write function for the GNU TLS library. + */ + +static ssize_t /* O - Number of bytes written or -1 on error */ +http_openssl_write( + openssl_transport_ptr_t ptr, /* I - Connection to server */ + const void *data, /* I - Data buffer */ + size_t length) /* I - Number of bytes to write */ +{ + ssize_t bytes; /* Bytes written */ + + + DEBUG_printf(("5http_openssl_write(ptr=%p, data=%p, length=%d)", ptr, data, + (int)length)); + bytes = send(((http_t *)ptr)->fd, data, length, 0); + DEBUG_printf(("5http_openssl_write: bytes=%d", (int)bytes)); + + return (bytes); +} + + +/* + * '_httpTLSInitialize()' - Initialize the TLS stack. + */ + +void +_httpTLSInitialize(void) +{ + /* + * Initialize GNU TLS... + */ + + openssl_global_init(); +} + + +/* + * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes. + */ + +size_t /* O - Bytes available */ +_httpTLSPending(http_t *http) /* I - HTTP connection */ +{ + return (openssl_record_check_pending(http->tls)); +} + + +/* + * '_httpTLSRead()' - Read from a SSL/TLS connection. + */ + +int /* O - Bytes read */ +_httpTLSRead(http_t *http, /* I - Connection to server */ + char *buf, /* I - Buffer to store data */ + int len) /* I - Length of buffer */ +{ + ssize_t result; /* Return value */ + + + result = openssl_record_recv(http->tls, buf, (size_t)len); + + if (result < 0 && !errno) + { + /* + * Convert GNU TLS error to errno value... + */ + + switch (result) + { + case GNUTLS_E_INTERRUPTED : + errno = EINTR; + break; + + case GNUTLS_E_AGAIN : + errno = EAGAIN; + break; + + default : + errno = EPIPE; + break; + } + + result = -1; + } + + return ((int)result); +} + + +/* + * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options. + */ + +void +_httpTLSSetOptions(int options, /* I - Options */ + int min_version, /* I - Minimum TLS version */ + int max_version) /* I - Maximum TLS version */ +{ + if (!(options & _HTTP_TLS_SET_DEFAULT) || tls_options < 0) + { + tls_options = options; + tls_min_version = min_version; + tls_max_version = max_version; + } +} + + +/* + * '_httpTLSStart()' - Set up SSL/TLS support on a connection. + */ + +int /* O - 0 on success, -1 on failure */ +_httpTLSStart(http_t *http) /* I - Connection to server */ +{ + char hostname[256], /* Hostname */ + *hostptr; /* Pointer into hostname */ + int status; /* Status of handshake */ + openssl_certificate_credentials_t *credentials; + /* TLS credentials */ + char priority_string[2048]; + /* Priority string */ + int version; /* Current version */ + double old_timeout; /* Old timeout value */ + http_timeout_cb_t old_cb; /* Old timeout callback */ + void *old_data; /* Old timeout data */ + static const char * const versions[] =/* SSL/TLS versions */ + { + "VERS-SSL3.0", + "VERS-TLS1.0", + "VERS-TLS1.1", + "VERS-TLS1.2", + "VERS-TLS1.3", + "VERS-TLS-ALL" + }; + + + DEBUG_printf(("3_httpTLSStart(http=%p)", http)); + + if (tls_options < 0) + { + DEBUG_puts("4_httpTLSStart: Setting defaults."); + _cupsSetDefaults(); + DEBUG_printf(("4_httpTLSStart: tls_options=%x", tls_options)); + } + + if (http->mode == _HTTP_MODE_SERVER && !tls_keypath) + { + DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called."); + http->error = errno = EINVAL; + http->status = HTTP_STATUS_ERROR; + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Server credentials not set."), 1); + + return (-1); + } + + credentials = (openssl_certificate_credentials_t *) + malloc(sizeof(openssl_certificate_credentials_t)); + if (credentials == NULL) + { + DEBUG_printf(("8_httpStartTLS: Unable to allocate credentials: %s", + strerror(errno))); + http->error = errno; + http->status = HTTP_STATUS_ERROR; + _cupsSetHTTPError(HTTP_STATUS_ERROR); + + return (-1); + } + + openssl_certificate_allocate_credentials(credentials); + status = openssl_init(&http->tls, http->mode == _HTTP_MODE_CLIENT ? GNUTLS_CLIENT : GNUTLS_SERVER); + if (!status) + status = openssl_set_default_priority(http->tls); + + if (status) + { + http->error = EIO; + http->status = HTTP_STATUS_ERROR; + + DEBUG_printf(("4_httpTLSStart: Unable to initialize common TLS parameters: %s", openssl_strerror(status))); + _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, openssl_strerror(status), 0); + + openssl_deinit(http->tls); + openssl_certificate_free_credentials(*credentials); + free(credentials); + http->tls = NULL; + + return (-1); + } + + if (http->mode == _HTTP_MODE_CLIENT) + { + /* + * Client: get the hostname to use for TLS... + */ + + if (httpAddrLocalhost(http->hostaddr)) + { + strlcpy(hostname, "localhost", sizeof(hostname)); + } + else + { + /* + * Otherwise make sure the hostname we have does not end in a trailing dot. + */ + + strlcpy(hostname, http->hostname, sizeof(hostname)); + if ((hostptr = hostname + strlen(hostname) - 1) >= hostname && + *hostptr == '.') + *hostptr = '\0'; + } + + status = openssl_server_name_set(http->tls, GNUTLS_NAME_DNS, hostname, strlen(hostname)); + } + else + { + /* + * Server: get certificate and private key... + */ + + char crtfile[1024], /* Certificate file */ + keyfile[1024]; /* Private key file */ + int have_creds = 0; /* Have credentials? */ + + if (http->fields[HTTP_FIELD_HOST]) + { + /* + * Use hostname for TLS upgrade... + */ + + strlcpy(hostname, http->fields[HTTP_FIELD_HOST], sizeof(hostname)); + } + else + { + /* + * Resolve hostname from connection address... + */ + + http_addr_t addr; /* Connection address */ + socklen_t addrlen; /* Length of address */ + + addrlen = sizeof(addr); + if (getsockname(http->fd, (struct sockaddr *)&addr, &addrlen)) + { + DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno))); + hostname[0] = '\0'; + } + else if (httpAddrLocalhost(&addr)) + hostname[0] = '\0'; + else + { + httpAddrLookup(&addr, hostname, sizeof(hostname)); + DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname)); + } + } + + if (isdigit(hostname[0] & 255) || hostname[0] == '[') + hostname[0] = '\0'; /* Don't allow numeric addresses */ + + if (hostname[0]) + { + /* + * First look in the CUPS keystore... + */ + + http_openssl_make_path(crtfile, sizeof(crtfile), tls_keypath, hostname, "crt"); + http_openssl_make_path(keyfile, sizeof(keyfile), tls_keypath, hostname, "key"); + + if (access(crtfile, R_OK) || access(keyfile, R_OK)) + { + /* + * No CUPS-managed certs, look for CA certs... + */ + + char cacrtfile[1024], cakeyfile[1024]; /* CA cert files */ + + snprintf(cacrtfile, sizeof(cacrtfile), "/etc/letsencrypt/live/%s/fullchain.pem", hostname); + snprintf(cakeyfile, sizeof(cakeyfile), "/etc/letsencrypt/live/%s/privkey.pem", hostname); + + if ((access(cacrtfile, R_OK) || access(cakeyfile, R_OK)) && (hostptr = strchr(hostname, '.')) != NULL) + { + /* + * Try just domain name... + */ + + hostptr ++; + if (strchr(hostptr, '.')) + { + snprintf(cacrtfile, sizeof(cacrtfile), "/etc/letsencrypt/live/%s/fullchain.pem", hostptr); + snprintf(cakeyfile, sizeof(cakeyfile), "/etc/letsencrypt/live/%s/privkey.pem", hostptr); + } + } + + if (!access(cacrtfile, R_OK) && !access(cakeyfile, R_OK)) + { + /* + * Use the CA certs... + */ + + strlcpy(crtfile, cacrtfile, sizeof(crtfile)); + strlcpy(keyfile, cakeyfile, sizeof(keyfile)); + } + } + + have_creds = !access(crtfile, R_OK) && !access(keyfile, R_OK); + } + else if (tls_common_name) + { + /* + * First look in the CUPS keystore... + */ + + http_openssl_make_path(crtfile, sizeof(crtfile), tls_keypath, tls_common_name, "crt"); + http_openssl_make_path(keyfile, sizeof(keyfile), tls_keypath, tls_common_name, "key"); + + if (access(crtfile, R_OK) || access(keyfile, R_OK)) + { + /* + * No CUPS-managed certs, look for CA certs... + */ + + char cacrtfile[1024], cakeyfile[1024]; /* CA cert files */ + + snprintf(cacrtfile, sizeof(cacrtfile), "/etc/letsencrypt/live/%s/fullchain.pem", tls_common_name); + snprintf(cakeyfile, sizeof(cakeyfile), "/etc/letsencrypt/live/%s/privkey.pem", tls_common_name); + + if ((access(cacrtfile, R_OK) || access(cakeyfile, R_OK)) && (hostptr = strchr(tls_common_name, '.')) != NULL) + { + /* + * Try just domain name... + */ + + hostptr ++; + if (strchr(hostptr, '.')) + { + snprintf(cacrtfile, sizeof(cacrtfile), "/etc/letsencrypt/live/%s/fullchain.pem", hostptr); + snprintf(cakeyfile, sizeof(cakeyfile), "/etc/letsencrypt/live/%s/privkey.pem", hostptr); + } + } + + if (!access(cacrtfile, R_OK) && !access(cakeyfile, R_OK)) + { + /* + * Use the CA certs... + */ + + strlcpy(crtfile, cacrtfile, sizeof(crtfile)); + strlcpy(keyfile, cakeyfile, sizeof(keyfile)); + } + } + + have_creds = !access(crtfile, R_OK) && !access(keyfile, R_OK); + } + + if (!have_creds && tls_auto_create && (hostname[0] || tls_common_name)) + { + DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname[0] ? hostname : tls_common_name)); + + if (!cupsMakeServerCredentials(tls_keypath, hostname[0] ? hostname : tls_common_name, 0, NULL, time(NULL) + 365 * 86400)) + { + DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed."); + http->error = errno = EINVAL; + http->status = HTTP_STATUS_ERROR; + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to create server credentials."), 1); + + return (-1); + } + } + + DEBUG_printf(("4_httpTLSStart: Using certificate \"%s\" and private key \"%s\".", crtfile, keyfile)); + + status = openssl_certificate_set_x509_key_file(*credentials, crtfile, keyfile, GNUTLS_X509_FMT_PEM); + } + + if (!status) + status = openssl_credentials_set(http->tls, GNUTLS_CRD_CERTIFICATE, *credentials); + + if (status) + { + http->error = EIO; + http->status = HTTP_STATUS_ERROR; + + DEBUG_printf(("4_httpTLSStart: Unable to complete client/server setup: %s", openssl_strerror(status))); + _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, openssl_strerror(status), 0); + + openssl_deinit(http->tls); + openssl_certificate_free_credentials(*credentials); + free(credentials); + http->tls = NULL; + + return (-1); + } + + strlcpy(priority_string, "NORMAL", sizeof(priority_string)); + + if (tls_max_version < _HTTP_TLS_MAX) + { + /* + * Require specific TLS versions... + */ + + strlcat(priority_string, ":-VERS-TLS-ALL", sizeof(priority_string)); + for (version = tls_min_version; version <= tls_max_version; version ++) + { + strlcat(priority_string, ":+", sizeof(priority_string)); + strlcat(priority_string, versions[version], sizeof(priority_string)); + } + } + else if (tls_min_version == _HTTP_TLS_SSL3) + { + /* + * Allow all versions of TLS and SSL/3.0... + */ + + strlcat(priority_string, ":+VERS-TLS-ALL:+VERS-SSL3.0", sizeof(priority_string)); + } + else + { + /* + * Require a minimum version... + */ + + strlcat(priority_string, ":+VERS-TLS-ALL", sizeof(priority_string)); + for (version = 0; version < tls_min_version; version ++) + { + strlcat(priority_string, ":-", sizeof(priority_string)); + strlcat(priority_string, versions[version], sizeof(priority_string)); + } + } + + if (tls_options & _HTTP_TLS_ALLOW_RC4) + strlcat(priority_string, ":+ARCFOUR-128", sizeof(priority_string)); + else + strlcat(priority_string, ":!ARCFOUR-128", sizeof(priority_string)); + + strlcat(priority_string, ":!ANON-DH", sizeof(priority_string)); + + if (tls_options & _HTTP_TLS_DENY_CBC) + strlcat(priority_string, ":!AES-128-CBC:!AES-256-CBC:!CAMELLIA-128-CBC:!CAMELLIA-256-CBC:!3DES-CBC", sizeof(priority_string)); + +#ifdef HAVE_GNUTLS_PRIORITY_SET_DIRECT + openssl_priority_set_direct(http->tls, priority_string, NULL); + +#else + openssl_priority_t priority; /* Priority */ + + openssl_priority_init(&priority, priority_string, NULL); + openssl_priority_set(http->tls, priority); + openssl_priority_deinit(priority); +#endif /* HAVE_GNUTLS_PRIORITY_SET_DIRECT */ + + openssl_transport_set_ptr(http->tls, (openssl_transport_ptr_t)http); + openssl_transport_set_pull_function(http->tls, http_openssl_read); +#ifdef HAVE_GNUTLS_TRANSPORT_SET_PULL_TIMEOUT_FUNCTION + openssl_transport_set_pull_timeout_function(http->tls, (openssl_pull_timeout_func)httpWait); +#endif /* HAVE_GNUTLS_TRANSPORT_SET_PULL_TIMEOUT_FUNCTION */ + openssl_transport_set_push_function(http->tls, http_openssl_write); + + /* + * Enforce a minimum timeout of 10 seconds for the TLS handshake... + */ + + old_timeout = http->timeout_value; + old_cb = http->timeout_cb; + old_data = http->timeout_data; + + if (!old_cb || old_timeout < 10.0) + { + DEBUG_puts("4_httpTLSStart: Setting timeout to 10 seconds."); + httpSetTimeout(http, 10.0, NULL, NULL); + } + + /* + * Do the TLS handshake... + */ + + while ((status = openssl_handshake(http->tls)) != GNUTLS_E_SUCCESS) + { + DEBUG_printf(("5_httpStartTLS: openssl_handshake returned %d (%s)", + status, openssl_strerror(status))); + + if (openssl_error_is_fatal(status)) + { + http->error = EIO; + http->status = HTTP_STATUS_ERROR; + + _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, openssl_strerror(status), 0); + + openssl_deinit(http->tls); + openssl_certificate_free_credentials(*credentials); + free(credentials); + http->tls = NULL; + + httpSetTimeout(http, old_timeout, old_cb, old_data); + + return (-1); + } + } + + /* + * Restore the previous timeout settings... + */ + + httpSetTimeout(http, old_timeout, old_cb, old_data); + + http->tls_credentials = credentials; + + return (0); +} + + +/* + * '_httpTLSStop()' - Shut down SSL/TLS on a connection. + */ + +void +_httpTLSStop(http_t *http) /* I - Connection to server */ +{ + int error; /* Error code */ + + + error = openssl_bye(http->tls, http->mode == _HTTP_MODE_CLIENT ? GNUTLS_SHUT_RDWR : GNUTLS_SHUT_WR); + if (error != GNUTLS_E_SUCCESS) + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, openssl_strerror(errno), 0); + + openssl_deinit(http->tls); + http->tls = NULL; + + if (http->tls_credentials) + { + openssl_certificate_free_credentials(*(http->tls_credentials)); + free(http->tls_credentials); + http->tls_credentials = NULL; + } +} + + +/* + * '_httpTLSWrite()' - Write to a SSL/TLS connection. + */ + +int /* O - Bytes written */ +_httpTLSWrite(http_t *http, /* I - Connection to server */ + const char *buf, /* I - Buffer holding data */ + int len) /* I - Length of buffer */ +{ + ssize_t result; /* Return value */ + + + DEBUG_printf(("5_httpTLSWrite(http=%p, buf=%p, len=%d)", http, buf, len)); + + result = openssl_record_send(http->tls, buf, (size_t)len); + + if (result < 0 && !errno) + { + /* + * Convert GNU TLS error to errno value... + */ + + switch (result) + { + case GNUTLS_E_INTERRUPTED : + errno = EINTR; + break; + + case GNUTLS_E_AGAIN : + errno = EAGAIN; + break; + + default : + errno = EPIPE; + break; + } + + result = -1; + } + + DEBUG_printf(("5_httpTLSWrite: Returning %d.", (int)result)); + + return ((int)result); +} diff --git a/cups/tls.c b/cups/tls.c index 273213cad5..43b988ba20 100644 --- a/cups/tls.c +++ b/cups/tls.c @@ -2,12 +2,9 @@ * TLS routines for CUPS. * * Copyright © 2021-2022 by OpenPrinting. - * Copyright @2007-2014 by Apple Inc. + * Copyright @ 2007-2014 by Apple Inc. * Copyright @ 1997-2007 by Easy Software Products, all rights reserved. * - * This file contains Kerberos support code, copyright 2006 by - * Jelmer Vernooij. - * * Licensed under Apache License v2.0. See the file "LICENSE" for more * information. */ @@ -37,7 +34,9 @@ */ #ifdef HAVE_TLS -# ifdef HAVE_GNUTLS +# ifdef HAVE_OPENSSL +# include "tls-openssl.c" +# elif defined(HAVE_GNUTLS) # include "tls-gnutls.c" # elif defined(HAVE_CDSASSL) # include "tls-darwin.c" diff --git a/vcnet/config.h b/vcnet/config.h index e58373206a..f2bc3dd17c 100644 --- a/vcnet/config.h +++ b/vcnet/config.h @@ -387,8 +387,9 @@ typedef unsigned long useconds_t; #define HAVE_TLS 1 /* #undef HAVE_CDSASSL */ +#define HAVE_OPENSSL 1 /* #undef HAVE_GNUTLS */ -#define HAVE_SSPISSL 1 +/* #undef HAVE_SSPISSL */ /* diff --git a/xcode/config.h b/xcode/config.h index 34e34aea7c..ada160e50e 100644 --- a/xcode/config.h +++ b/xcode/config.h @@ -308,6 +308,7 @@ #define HAVE_TLS 1 #define HAVE_CDSASSL 1 +/* #undef HAVE_OPENSSL */ /* #undef HAVE_GNUTLS */ /* #undef HAVE_SSPISSL */