1 /* tlspool/starttls.c -- Setup and validation handler for TLS session */
17 #include <sys/types.h>
18 #include <sys/socket.h>
20 #include <arpa/inet.h>
21 #include <netinet/in.h>
23 #include <gnutls/gnutls.h>
24 #include <gnutls/pkcs11.h>
25 #include <gnutls/abstract.h>
26 #include <gnutls/dane.h>
30 #include <tlspool/internal.h>
37 #if EXPECTED_LID_TYPE_COUNT != LID_TYPE_CNT
38 #error "Set EXPECTED_LID_TYPE_COUNT in <tlspool/internal.h> to match LID_TYPE_CNT"
42 /* This module hosts TLS handlers which treat an individual connection.
44 * Initially, the TLS setup is processed, which means validating the
45 * connection. If and when this succeeds, a continued process is needed
46 * to encrypt and decrypt traffic while it is in transit.
48 * Every TLS connection (including the attempt to set it up) is hosted in
49 * its own thread. This means that it can abide time to wait for PINENTRY,
50 * LOCALID or LIDENTRY responses. It also means a very clear flow when the
51 * time comes to destroy a connection.
53 * While encrypting and decrypting traffic passing through, the thread
54 * will use its own poll() call, and thus offload the potentially large
55 * one of the main thread, which is supposed to be a low-traffic task.
56 * The set of file descriptors used by the session-handler threads are
57 * in contrast very small and can easily be started for every single
58 * packet passing through.
60 * Might the user terminate a process while this one is waiting for a
61 * callback command request, then the main TLS pool thread will take
62 * care of taking down this thread. To that end, it sets the followup
63 * pointer that normally holds a callback response to NULL, and then
64 * permits this thread to run again. This will lead to a shutdown of
65 * this process, and proper closing of all connections. The remote peer
66 * will therefore see the result of a local kill as a connection reset.
68 * In case one of the end points of the connection is terminated, a
69 * similar thing will happen; the thread will terminate itself after
70 * a cleanup of any outstanding resources. This, once again, leads
71 * to passing on the reset of a connection between the encrypted and
72 * side of the connection.
78 * GnuTLS infrastructure setup.
79 * Session-shared DH-keys, credentials structures, and so on.
81 static gnutls_dh_params_t dh_params;
84 gnutls_credentials_type_t credtp;
88 #define EXPECTED_SRV_CREDCOUNT 3
89 #define EXPECTED_CLI_CREDCOUNT 3
90 static struct credinfo srv_creds [EXPECTED_SRV_CREDCOUNT];
91 static struct credinfo cli_creds [EXPECTED_CLI_CREDCOUNT];
92 static int srv_credcount = 0;
93 static int cli_credcount = 0;
94 static const char const *onthefly_p11uri = "pkcs11:manufacturer=ARPA2.net;token=TLS+Pool+internal;object=on-the-fly+signer;type=private;serial=1";
95 static unsigned long long onthefly_serial; //TODO: Fill with now * 1000
96 static gnutls_x509_crt_t onthefly_issuercrt = NULL;
97 static gnutls_privkey_t onthefly_issuerkey = NULL;
98 static gnutls_x509_privkey_t onthefly_subjectkey = NULL;
99 static pthread_mutex_t onthefly_signer_lock = PTHREAD_MUTEX_INITIALIZER;
101 /* The local variation on the ctlkeynode structure, with TLS-specific fields
103 struct ctlkeynode_tls {
104 struct ctlkeynode regent; // Structure for ctlkey_register()
105 gnutls_session_t session; // Additional data specifically for TLS
106 pthread_t owner; // For interruption of copycat()
107 int plainfd; // Plain-side connection
108 int cryptfd; // Crypt-side connection
111 /* The list of accepted Exporter Label Prefixes for starttls_prng()
113 char *tlsprng_label_prefixes [] = {
114 // Forbidden by RFC 5705: "client finished",
115 // Forbidden by RFC 5705: "server finished",
116 // Forbidden by RFC 5705: "master secret",
117 // Forbidden by RFC 5705: "key expansion",
118 "client EAP encryption", // not suited for DTLS
119 "ttls keying material", // not suited for DTLS
120 "ttls challenge", // not suited for DTLS
121 "EXTRACTOR-dtls_srtp",
122 "EXPORTER_DTLS_OVER_SCTP",
123 "EXPORTER-ETSI-TC-M2M-Bootstrap",
124 "EXPORTER-ETSI-TC-M2M-Connection",
126 "EXPORTER_GBA_Digest",
127 "EXPORTER: teap session key seed", // not suited for DTLS
128 "EXPORTER-oneM2M-Bootstrap",
129 "EXPORTER-oneM2M-Connection",
133 /* The registry with the service names that are deemed safe for an
134 * anonymous precursor phase; that is, the service names that may offer
135 * ANON-DH initially, and immediately renegotiate an authenticated
136 * connection. See doc/anonymising-precursor.* for more information.
138 * The registry is ordered by case-independent service name, so it can
139 * be searched in 2log time. Service names are as defined by IANA in the
140 * "Service Name and Transport Protocol Port Number Registry".
142 * The entries in the registry depend on the role played; either as a
143 * client or as a server. This refers to the local node, and depends on
144 * uncertainty of the remote party's TLS implementation and whether or
145 * not the protocol could lead to the remote sending information that
146 * requires authentication before the secure renogiation into an
147 * authenticated connection has been completed by this side. This is
148 * a protocol-dependent matter and the registry provided here serves to
149 * encapsulate this knowledge inside the TLS Pool instead of bothering
150 * application designers with it. Entries that are not found in the
151 * registry are interpreted as not allowing an anonymising precursor.
153 * Note that ANONPRE_EXTEND_MASTER_SECRET cannot be verified before
154 * GnuTLS version 3.4.0; see "imap" below for the resulting impact. This
155 * also impacts dynamic linking, because 3.4.0 introduces the new function
156 * gnutls_ext_get_data() that is used for this requirement.
158 #define ANONPRE_FORBID 0x00
159 #define ANONPRE_CLIENT 0x01
160 #define ANONPRE_SERVER 0x02
161 #define ANONPRE_EITHER (ANONPRE_CLIENT | ANONPRE_SERVER)
162 #define ANONPRE_EXTEND_MASTER_SECRET 0x10
163 struct anonpre_regentry {
167 struct anonpre_regentry anonpre_registry [] = {
168 /* This registry is commented out for now, although the code to use it seems
169 * to work fine. GnuTLS however, does not seem to support making the switch
170 * from ANON-ECDH to an authenticated handshake. Details:
171 * http://lists.gnutls.org/pipermail/gnutls-help/2015-November/003998.html
173 { "generic_anonpre", ANONPRE_EITHER }, // Name invalid as per RFC 6335
174 { "http", ANONPRE_CLIENT }, // Server also if it ignores client ID
175 #if GNUTLS_VERSION_NUMBER < 0x030400
176 { "imap", ANONPRE_SERVER },
178 { "imap", ANONPRE_EITHER | ANONPRE_EXTEND_MASTER_SECRET },
180 { "pop3", ANONPRE_EITHER },
181 { "smtp", ANONPRE_EITHER },
183 * End of commenting out the registry
186 const int anonpre_registry_size = sizeof (anonpre_registry) / sizeof (struct anonpre_regentry);
189 /* The registry of Key Usage and Extended Key Usage for any given service name.
191 static const char *http_noncrit [] = { GNUTLS_KP_TLS_WWW_SERVER, GNUTLS_KP_TLS_WWW_CLIENT, NULL };
192 struct svcusage_regentry {
195 const char **oids_non_critical;
196 const char **oids_critical;
198 struct svcusage_regentry svcusage_registry [] = {
200 GNUTLS_KEY_KEY_ENCIPHERMENT |
201 GNUTLS_KEY_KEY_AGREEMENT,
206 GNUTLS_KEY_DIGITAL_SIGNATURE |
207 GNUTLS_KEY_KEY_ENCIPHERMENT |
208 GNUTLS_KEY_KEY_AGREEMENT,
213 const int svcusage_registry_size = sizeof (svcusage_registry) / sizeof (struct svcusage_regentry);
216 /* The maximum number of bytes that can be passed over a TLS connection before
217 * the authentication is complete in case of a anonymous precursor within a
218 * protocol that ensures that this cannot be a problem.
222 /* The priorities cache for "NORMAL" -- used to preconfigure the server,
223 * actually to overcome its unwillingness to perform the handshake, and
224 * leave it to srv_clienthello() to setup the priority string.
226 gnutls_priority_t priority_normal;
229 /* Map a GnuTLS call (usually a function call) to a POSIX errno,
230 * optionally reporting an errstr to avoid loosing information.
231 * Retain errno if it already exists.
232 * Continue if errno differs from 0, GnuTLS may "damage" it even when OK. */
233 #define E_g2e(errstr,gtlscall) { \
234 if (gtls_errno == GNUTLS_E_SUCCESS) { \
235 gtls_errno = (gtlscall); \
236 if (gtls_errno != GNUTLS_E_SUCCESS) { \
237 error_gnutls2posix (gtls_errno, errstr); \
242 /* Cleanup when GnuTLS leaves errno damaged but returns no gtls_errno */
243 #define E_gnutls_clear_errno() { \
244 if (gtls_errno == GNUTLS_E_SUCCESS) { \
249 /* Error number translation, including error string setup. See E_g2e(). */
250 void error_gnutls2posix (int gtls_errno, char *new_errstr) {
252 register int newerrno;
255 if (gtls_errno == GNUTLS_E_SUCCESS) {
258 errstr = error_getstring ();
259 if (errstr != NULL) {
263 // Report the textual error
264 if (new_errstr == NULL) {
265 new_errstr = "GnuTLS error";
267 tlog (TLOG_TLS, LOG_ERR, "%s: %s",
269 gnutls_strerror (gtls_errno));
270 error_setstring (new_errstr);
272 // Translate error to a POSIX errno value
273 switch (gtls_errno) {
274 case GNUTLS_E_SUCCESS:
276 case GNUTLS_E_UNKNOWN_COMPRESSION_ALGORITHM:
277 case GNUTLS_E_UNKNOWN_CIPHER_TYPE:
278 case GNUTLS_E_UNSUPPORTED_VERSION_PACKET:
279 case GNUTLS_E_UNWANTED_ALGORITHM:
280 case GNUTLS_E_UNKNOWN_CIPHER_SUITE:
281 case GNUTLS_E_UNSUPPORTED_CERTIFICATE_TYPE:
282 case GNUTLS_E_X509_UNKNOWN_SAN:
283 case GNUTLS_E_DH_PRIME_UNACCEPTABLE:
284 case GNUTLS_E_UNKNOWN_PK_ALGORITHM:
285 case GNUTLS_E_NO_TEMPORARY_RSA_PARAMS:
286 case GNUTLS_E_NO_COMPRESSION_ALGORITHMS:
287 case GNUTLS_E_NO_CIPHER_SUITES:
288 case GNUTLS_E_OPENPGP_FINGERPRINT_UNSUPPORTED:
289 case GNUTLS_E_X509_UNSUPPORTED_ATTRIBUTE:
290 case GNUTLS_E_UNKNOWN_HASH_ALGORITHM:
291 case GNUTLS_E_UNKNOWN_PKCS_CONTENT_TYPE:
292 case GNUTLS_E_UNKNOWN_PKCS_BAG_TYPE:
293 case GNUTLS_E_NO_TEMPORARY_DH_PARAMS:
294 case GNUTLS_E_UNKNOWN_ALGORITHM:
295 case GNUTLS_E_UNSUPPORTED_SIGNATURE_ALGORITHM:
296 case GNUTLS_E_UNSAFE_RENEGOTIATION_DENIED:
297 case GNUTLS_E_X509_UNSUPPORTED_OID:
298 case GNUTLS_E_CHANNEL_BINDING_NOT_AVAILABLE:
299 case GNUTLS_E_INCOMPAT_DSA_KEY_WITH_TLS_PROTOCOL:
300 case GNUTLS_E_ECC_NO_SUPPORTED_CURVES:
301 case GNUTLS_E_ECC_UNSUPPORTED_CURVE:
302 case GNUTLS_E_X509_UNSUPPORTED_EXTENSION:
303 case GNUTLS_E_NO_CERTIFICATE_STATUS:
304 case GNUTLS_E_NO_APPLICATION_PROTOCOL:
305 #ifdef GNUTLS_E_NO_SELF_TEST
306 case GNUTLS_E_NO_SELF_TEST:
308 newerrno = EOPNOTSUPP;
310 case GNUTLS_E_UNEXPECTED_PACKET_LENGTH:
311 case GNUTLS_E_INVALID_REQUEST:
314 case GNUTLS_E_INVALID_SESSION:
315 case GNUTLS_E_REHANDSHAKE:
316 case GNUTLS_E_CERTIFICATE_KEY_MISMATCH:
319 case GNUTLS_E_PUSH_ERROR:
320 case GNUTLS_E_PULL_ERROR:
321 case GNUTLS_E_PREMATURE_TERMINATION:
322 case GNUTLS_E_SESSION_EOF:
323 newerrno = ECONNRESET;
325 case GNUTLS_E_UNEXPECTED_PACKET:
326 case GNUTLS_E_WARNING_ALERT_RECEIVED:
327 case GNUTLS_E_FATAL_ALERT_RECEIVED:
328 case GNUTLS_E_LARGE_PACKET:
329 case GNUTLS_E_ERROR_IN_FINISHED_PACKET:
330 case GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET:
331 case GNUTLS_E_MPI_SCAN_FAILED:
332 case GNUTLS_E_DECRYPTION_FAILED:
333 case GNUTLS_E_DECOMPRESSION_FAILED:
334 case GNUTLS_E_COMPRESSION_FAILED:
335 case GNUTLS_E_BASE64_DECODING_ERROR:
336 case GNUTLS_E_MPI_PRINT_FAILED:
337 case GNUTLS_E_GOT_APPLICATION_DATA:
338 case GNUTLS_E_RECORD_LIMIT_REACHED:
339 case GNUTLS_E_ENCRYPTION_FAILED:
340 case GNUTLS_E_PK_ENCRYPTION_FAILED:
341 case GNUTLS_E_PK_DECRYPTION_FAILED:
342 case GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER:
343 case GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE:
344 case GNUTLS_E_PKCS1_WRONG_PAD:
345 case GNUTLS_E_RECEIVED_ILLEGAL_EXTENSION:
346 case GNUTLS_E_FILE_ERROR:
347 case GNUTLS_E_ASN1_ELEMENT_NOT_FOUND:
348 case GNUTLS_E_ASN1_IDENTIFIER_NOT_FOUND:
349 case GNUTLS_E_ASN1_DER_ERROR:
350 case GNUTLS_E_ASN1_VALUE_NOT_FOUND:
351 case GNUTLS_E_ASN1_GENERIC_ERROR:
352 case GNUTLS_E_ASN1_VALUE_NOT_VALID:
353 case GNUTLS_E_ASN1_TAG_ERROR:
354 case GNUTLS_E_ASN1_TAG_IMPLICIT:
355 case GNUTLS_E_ASN1_TYPE_ANY_ERROR:
356 case GNUTLS_E_ASN1_SYNTAX_ERROR:
357 case GNUTLS_E_ASN1_DER_OVERFLOW:
358 case GNUTLS_E_TOO_MANY_EMPTY_PACKETS:
359 case GNUTLS_E_TOO_MANY_HANDSHAKE_PACKETS:
360 case GNUTLS_E_SRP_PWD_PARSING_ERROR:
361 case GNUTLS_E_BASE64_ENCODING_ERROR:
362 case GNUTLS_E_OPENPGP_KEYRING_ERROR:
363 case GNUTLS_E_BASE64_UNEXPECTED_HEADER_ERROR:
364 case GNUTLS_E_OPENPGP_SUBKEY_ERROR:
365 case GNUTLS_E_CRYPTO_ALREADY_REGISTERED:
366 case GNUTLS_E_HANDSHAKE_TOO_LARGE:
367 case GNUTLS_E_BAD_COOKIE:
368 case GNUTLS_E_PARSING_ERROR:
369 case GNUTLS_E_CERTIFICATE_LIST_UNSORTED:
370 case GNUTLS_E_NO_PRIORITIES_WERE_SET:
371 #ifdef GNUTLS_E_PK_GENERATION_ERROR
372 case GNUTLS_E_PK_GENERATION_ERROR:
374 #ifdef GNUTLS_E_SELF_TEST_ERROR
375 case GNUTLS_E_SELF_TEST_ERROR:
377 #ifdef GNUTLS_E_SOCKETS_INIT_ERROR
378 case GNUTLS_E_SOCKETS_INIT_ERROR:
382 case GNUTLS_E_MEMORY_ERROR:
383 case GNUTLS_E_SHORT_MEMORY_BUFFER:
389 case GNUTLS_E_EXPIRED:
390 case GNUTLS_E_TIMEDOUT:
391 newerrno = ETIMEDOUT;
393 case GNUTLS_E_DB_ERROR:
400 case GNUTLS_E_SRP_PWD_ERROR:
401 case GNUTLS_E_INSUFFICIENT_CREDENTIALS:
402 case GNUTLS_E_HASH_FAILED:
403 case GNUTLS_E_PK_SIGN_FAILED:
404 case GNUTLS_E_CERTIFICATE_ERROR:
405 case GNUTLS_E_X509_UNSUPPORTED_CRITICAL_EXTENSION:
406 case GNUTLS_E_KEY_USAGE_VIOLATION:
407 case GNUTLS_E_NO_CERTIFICATE_FOUND:
408 case GNUTLS_E_OPENPGP_UID_REVOKED:
409 case GNUTLS_E_OPENPGP_GETKEY_FAILED:
410 case GNUTLS_E_PK_SIG_VERIFY_FAILED:
411 case GNUTLS_E_ILLEGAL_SRP_USERNAME:
412 case GNUTLS_E_INVALID_PASSWORD:
413 case GNUTLS_E_MAC_VERIFY_FAILED:
414 case GNUTLS_E_IA_VERIFY_FAILED:
415 case GNUTLS_E_UNKNOWN_SRP_USERNAME:
416 case GNUTLS_E_OPENPGP_PREFERRED_KEY_ERROR:
417 case GNUTLS_E_USER_ERROR:
418 case GNUTLS_E_AUTH_ERROR:
421 case GNUTLS_E_INTERRUPTED:
424 case GNUTLS_E_INTERNAL_ERROR:
425 case GNUTLS_E_CONSTRAINT_ERROR:
426 case GNUTLS_E_ILLEGAL_PARAMETER:
429 case GNUTLS_E_SAFE_RENEGOTIATION_FAILED:
430 newerrno = ECONNREFUSED;
432 case GNUTLS_E_INCOMPATIBLE_GCRYPT_LIBRARY:
433 case GNUTLS_E_INCOMPATIBLE_LIBTASN1_LIBRARY:
434 #ifdef GNUTLS_E_LIB_IN_ERROR_STATE
435 case GNUTLS_E_LIB_IN_ERROR_STATE:
439 case GNUTLS_E_RANDOM_FAILED:
442 case GNUTLS_E_CRYPTODEV_IOCTL_ERROR:
443 case GNUTLS_E_CRYPTODEV_DEVICE_ERROR:
444 case GNUTLS_E_HEARTBEAT_PONG_RECEIVED:
445 case GNUTLS_E_HEARTBEAT_PING_RECEIVED:
446 case GNUTLS_E_PKCS11_ERROR:
447 case GNUTLS_E_PKCS11_LOAD_ERROR:
448 case GNUTLS_E_PKCS11_PIN_ERROR:
449 case GNUTLS_E_PKCS11_SLOT_ERROR:
450 case GNUTLS_E_LOCKING_ERROR:
451 case GNUTLS_E_PKCS11_ATTRIBUTE_ERROR:
452 case GNUTLS_E_PKCS11_DEVICE_ERROR:
453 case GNUTLS_E_PKCS11_DATA_ERROR:
454 case GNUTLS_E_PKCS11_UNSUPPORTED_FEATURE_ERROR:
455 case GNUTLS_E_PKCS11_KEY_ERROR:
456 case GNUTLS_E_PKCS11_PIN_EXPIRED:
457 case GNUTLS_E_PKCS11_PIN_LOCKED:
458 case GNUTLS_E_PKCS11_SESSION_ERROR:
459 case GNUTLS_E_PKCS11_SIGNATURE_ERROR:
460 case GNUTLS_E_PKCS11_TOKEN_ERROR:
461 case GNUTLS_E_PKCS11_USER_ERROR:
462 case GNUTLS_E_CRYPTO_INIT_FAILED:
463 case GNUTLS_E_PKCS11_REQUESTED_OBJECT_NOT_AVAILBLE:
464 case GNUTLS_E_TPM_ERROR:
465 case GNUTLS_E_TPM_KEY_PASSWORD_ERROR:
466 case GNUTLS_E_TPM_SRK_PASSWORD_ERROR:
467 case GNUTLS_E_TPM_SESSION_ERROR:
468 case GNUTLS_E_TPM_KEY_NOT_FOUND:
469 case GNUTLS_E_TPM_UNINITIALIZED:
470 case GNUTLS_E_OCSP_RESPONSE_ERROR:
471 case GNUTLS_E_RANDOM_DEVICE_ERROR:
473 newerrno = EREMOTEIO;
486 /* Generate Diffie-Hellman parameters - for use with DHE
487 * kx algorithms. TODO: These should be discarded and regenerated
488 * once a day, once a week or once a month. Depending on the
489 * security requirements.
491 static gtls_error generate_dh_params (void) {
493 int gtls_errno = GNUTLS_E_SUCCESS;
494 bits = gnutls_sec_param_to_pk_bits (
496 GNUTLS_SEC_PARAM_LEGACY);
497 //TODO// Acquire DH-params lock
498 E_g2e ("Failed to initialise DH params",
499 gnutls_dh_params_init (
501 E_g2e ("Failed to generate DH params",
502 gnutls_dh_params_generate2 (
505 //TODO// Release DH-params lock
509 /* Load Diffie-Hellman parameters from file - or generate them when load fails.
511 static gtls_error load_dh_params (void) {
512 gnutls_dh_params_t dhp;
513 gnutls_datum_t pkcs3;
514 char *filename = cfg_tls_dhparamfile ();
515 int gtls_errno = GNUTLS_E_SUCCESS;
516 bzero (&pkcs3, sizeof (pkcs3));
518 E_g2e ("No PKCS #3 PEM file with DH params",
522 E_gnutls_clear_errno ();
523 E_g2e ("Failed to initialise DH params",
524 gnutls_dh_params_init (
526 E_g2e ("Failed to import DH params from PKCS #3 PEM",
527 gnutls_dh_params_import_pkcs3 (
530 GNUTLS_X509_FMT_PEM));
531 E_gnutls_clear_errno ();
533 if (pkcs3.data != NULL) {
536 if (gtls_errno != GNUTLS_E_SUCCESS) {
538 // File failed to load, so try to generate fresh DH params
539 int gtls_errno_stack0;
540 gtls_errno = GNUTLS_E_SUCCESS;
541 tlog (TLOG_CRYPTO, LOG_DEBUG, "Failed to load DH params from %s; generating fresh parameters", filename);
542 E_g2e ("Failed to generate DH params",
543 generate_dh_params ());
544 gtls_errno_stack0 = gtls_errno;
545 //TODO// Acquire DH-params lock
546 E_g2e ("Failed to format DH params as PKCS #3 PEM",
547 gnutls_dh_params_export2_pkcs3 (
551 //TODO// Release DH-params lock
552 if ((gtls_errno == GNUTLS_E_SUCCESS) && (filename != NULL)) {
555 // Best effor file save -- readback will parse
556 pemf = fopen (filename, "w");
558 fwrite (pkcs3.data, 1, pkcs3.size, pemf);
560 tlog (TLOG_FILES, LOG_DEBUG, "Saved DH params to %s (best-effort)", filename);
562 E_gnutls_clear_errno ();
564 gtls_errno = gtls_errno_stack0;
566 gnutls_dh_params_t old_dh;
567 //TODO// Acquire DH-params lock
570 //TODO// Release DH-params lock
572 gnutls_dh_params_deinit (old_dh);
578 /* Remove DH parameters, to be used during program cleanup. */
579 static void remove_dh_params (void) {
581 gnutls_dh_params_deinit (dh_params);
587 /* A log printing function
589 void log_gnutls (int level, const char *msg) {
590 tlog (TLOG_TLS, level, "GnuTLS: %s", msg);
594 /* Implement the GnuTLS function for token insertion callback. This function
595 * refers back to the generic callback for token insertion.
597 int gnutls_token_callback (void *const userdata,
598 const char *const label,
600 if (token_callback (label, retry)) {
601 return GNUTLS_E_SUCCESS;
603 return GNUTLS_E_PKCS11_TOKEN_ERROR;
609 * Implement the GnuTLS function for PIN callback. This function calls
610 * the generic PIN callback operation.
612 int gnutls_pin_callback (void *userdata,
614 const char *token_url,
615 const char *token_label,
619 if (flags & GNUTLS_PIN_SO) {
620 return GNUTLS_E_USER_ERROR;
622 if (pin_callback (attempt, token_url, token_label, pin, pin_max)) {
625 return GNUTLS_E_PKCS11_PIN_ERROR;
630 /* Register a PKCS #11 provider with the GnuTLS environment. */
631 void starttls_pkcs11_provider (char *p11path) {
632 unsigned int token_seq = 0;
634 if (gnutls_pkcs11_add_provider (p11path, NULL) != 0) {
635 fprintf (stderr, "Failed to register PKCS #11 library %s with GnuTLS\n", p11path);
638 while (gnutls_pkcs11_token_get_url (token_seq, 0, &p11uri) == 0) {
640 fprintf (stderr, "DEBUG: Found token URI %s\n", p11uri);
642 //TODO// if (gnutls_pkcs11_token_get_info (p11uri, GNUTLS_PKCS11_TOKEN_LABEL-of-SERIAL-of-MANUFACTURER-of-MODEL, output, utput_size) == 0) { ... }
643 gnutls_free (p11uri);
646 //TODO// Select token by name (value)
647 //TODO// if PIN available then set it up
648 //TODO:WHY?// free_p11pin ();
652 /* The global and static setup function for the starttls functions.
654 void setup_starttls (void) {
655 int setup_starttls_credentials (void); /* Defined below */
657 int gtls_errno = GNUTLS_E_SUCCESS;
658 char *otfsigcrt, *otfsigkey;
660 // Setup configuration variables
661 maxpreauth = cfg_tls_maxpreauth ();
663 // Basic library actions
664 tlog (TLOG_TLS, LOG_DEBUG, "Compiled against GnuTLS version %s", GNUTLS_VERSION);
665 curver = gnutls_check_version (GNUTLS_VERSION);
666 tlog (TLOG_TLS, LOG_DEBUG, "Running against %s GnuTLS version %s", curver? "acceptable": "OLDER", curver? curver: gnutls_check_version (NULL));
667 E_g2e ("GnuTLS global initialisation failed",
668 gnutls_global_init ());
669 E_gnutls_clear_errno ();
670 E_g2e ("GnuTLS PKCS #11 initialisation failed",
672 GNUTLS_PKCS11_FLAG_MANUAL, NULL));
674 // Setup logging / debugging
675 if (cfg_log_level () == LOG_DEBUG) {
676 gnutls_global_set_log_function (log_gnutls);
677 gnutls_global_set_log_level (9);
680 // Setup callbacks for user communication
681 gnutls_pkcs11_set_token_function (gnutls_token_callback, NULL);
682 gnutls_pkcs11_set_pin_function (gnutls_pin_callback, NULL);
684 // Setup DH parameters
685 E_g2e ("Loading DH params failed",
688 // Setup shared credentials for all client server processes
689 E_g2e ("Failed to setup GnuTLS callback credentials",
690 setup_starttls_credentials ());
692 // Parse the default priority string
693 E_g2e ("Failed to setup NORMAL priority cache",
694 gnutls_priority_init (&priority_normal, "NONE:+VERS-TLS-ALL:+VERS-DTLS-ALL:+COMP-NULL:+CIPHER-ALL:+CURVE-ALL:+SIGN-ALL:+MAC-ALL:+ANON-ECDH:+ECDHE-RSA:+DHE-RSA:+ECDHE-ECDSA:+DHE-DSS:+RSA:+CTYPE-X.509:+CTYPE-OPENPGP:+SRP:+SRP-RSA:+SRP-DSS", NULL));
695 // gnutls_priority_init (&priority_normal, "NORMAL:-RSA:+ANON-ECDH:+RSA:+CTYPE-X.509:+CTYPE-OPENPGP:+SRP:+SRP-RSA:+SRP-DSS", NULL));
697 // Try to setup on-the-fly signing key / certificate and gen a certkey
698 otfsigcrt = cfg_tls_onthefly_signcert ();
699 otfsigkey = cfg_tls_onthefly_signkey ();
700 fprintf (stderr, "DEBUG: gtls_errno = %d, otfsigcrt == %s, otfsigkey == %s\n", gtls_errno, otfsigcrt? otfsigcrt: "NULL", otfsigkey? otfsigkey: "NULL");
701 if ((gtls_errno == GNUTLS_E_SUCCESS) && (otfsigcrt != NULL)) {
702 FILE *crtfile = NULL;
703 fprintf (stderr, "DEBUG: gtls_errno==%d when initialising onthefly_issuercrt\n", gtls_errno);
704 E_g2e ("Failed to initialise on-the-fly issuer certificate structure",
705 gnutls_x509_crt_init (&onthefly_issuercrt));
706 if (strncmp (otfsigcrt, "file:", 5) == 0) {
707 // Provisionary support for the "file:" prefix
710 crtfile = fopen (otfsigcrt, "r");
711 if (crtfile == NULL) {
712 E_g2e ("Failed to open on-the-fly issuer certificate file",
713 GNUTLS_E_FILE_ERROR);
714 fprintf (stderr, "DEBUG: gtls_errno==%d after failing to open file for onthefly_issuercrt\n", gtls_errno);
717 size_t len = fread (crt, 1, sizeof (crt), crtfile);
718 if (ferror (crtfile)) {
719 E_g2e ("Failed to read on-the-fly issuer certificate from file",
720 GNUTLS_E_FILE_ERROR);
721 } else if ((len >= sizeof (crt)) || !feof (crtfile)) {
722 E_g2e ("Unexpectedly long on-the-fly issuer certificate file",
723 GNUTLS_E_FILE_ERROR);
725 gnutls_datum_t cd = {
729 fprintf (stderr, "DEBUG: gtls_errno==%d before importing onthefly_issuercrt\n", gtls_errno);
730 E_g2e ("Failed to import on-the-fly certificate from file",
731 gnutls_x509_crt_import (onthefly_issuercrt, &cd, GNUTLS_X509_FMT_DER));
732 fprintf (stderr, "DEBUG: gtls_errno==%d after importing onthefly_issuercrt\n", gtls_errno);
737 if ((gtls_errno == GNUTLS_E_SUCCESS) && (otfsigkey != NULL)) {
738 E_g2e ("Failed to initialise on-the-fly issuer private key structure",
739 gnutls_privkey_init (&onthefly_issuerkey));
740 fprintf (stderr, "DEBUG: before onthefly p11 import, gtlserrno = %d\n", gtls_errno);
741 E_g2e ("Failed to import pkcs11: URI into on-the-fly issuer private key",
742 gnutls_privkey_import_pkcs11_url (onthefly_issuerkey, otfsigkey));
743 fprintf (stderr, "DEBUG: after onthefly p11 import, gtlserrno = %d\n", gtls_errno);
745 fprintf (stderr, "DEBUG: When it matters, gtls_errno = %d, onthefly_issuercrt %s NULL, onthefly_issuerkey %s NULL\n", gtls_errno, onthefly_issuercrt?"!=":"==", onthefly_issuerkey?"!=":"==");
746 if ((gtls_errno == GNUTLS_E_SUCCESS) && (onthefly_issuercrt != NULL) && (onthefly_issuerkey != NULL)) {
747 E_g2e ("Failed to initialise on-the-fly certificate session key",
748 gnutls_x509_privkey_init (&onthefly_subjectkey));
749 E_g2e ("Failed to generate on-the-fly certificate session key",
750 gnutls_x509_privkey_generate (onthefly_subjectkey, GNUTLS_PK_RSA, 2048 /*TODO:FIXED*/, 0));
751 if (gtls_errno == GNUTLS_E_SUCCESS) {
752 tlog (TLOG_TLS, LOG_INFO, "Setup for on-the-fly signing with the TLS Pool");
754 tlog (TLOG_TLS, LOG_ERR, "Failed to setup on-the-fly signing (shall continue without it)");
755 gnutls_x509_privkey_deinit (onthefly_subjectkey);
756 onthefly_subjectkey = NULL;
759 gtls_errno = GNUTLS_E_SUCCESS;
760 E_gnutls_clear_errno ();
762 if (onthefly_subjectkey == NULL) {
763 if (onthefly_issuercrt != NULL) {
764 gnutls_x509_crt_deinit (onthefly_issuercrt);
765 onthefly_issuercrt = NULL;
767 if (onthefly_issuerkey != NULL) {
768 gnutls_privkey_deinit (onthefly_issuerkey);
769 onthefly_issuerkey = NULL;
773 // Finally, check whether there was any error setting up GnuTLS
774 if (gtls_errno != GNUTLS_E_SUCCESS) {
775 tlog (TLOG_TLS, LOG_CRIT, "FATAL: GnuTLS setup failed: %s", gnutls_strerror (gtls_errno));
779 //MOVED// // Setup the management databases
780 //MOVED// tlog (TLOG_DB, LOG_DEBUG, "Setting up management databases");
781 //MOVED// E_e2e ("Failed to setup management databases",
782 //MOVED// setup_management ());
783 //MOVED// if (errno != 0) {
784 //MOVED// tlog (TLOG_DB, LOG_CRIT, "FATAL: Management databases setup failed: %s", strerror (errno));
789 /* Cleanup the structures and resources that were setup for handling TLS.
791 void cleanup_starttls (void) {
792 void cleanup_starttls_credentials (void); /* Defined below */
793 //MOVED// cleanup_management ();
794 if (onthefly_subjectkey != NULL) {
795 gnutls_x509_privkey_deinit (onthefly_subjectkey);
796 onthefly_subjectkey = NULL;
798 if (onthefly_issuercrt != NULL) {
799 gnutls_x509_crt_deinit (onthefly_issuercrt);
800 onthefly_issuercrt = NULL;
802 if (onthefly_issuerkey != NULL) {
803 gnutls_privkey_deinit (onthefly_issuerkey);
804 onthefly_issuerkey = NULL;
806 cleanup_starttls_credentials ();
808 gnutls_pkcs11_set_pin_function (NULL, NULL);
809 gnutls_pkcs11_set_token_function (NULL, NULL);
810 gnutls_pkcs11_deinit ();
811 gnutls_priority_deinit (priority_normal);
812 gnutls_global_deinit ();
817 * The copycat function is a bidirectional transport between the given
818 * remote and local sockets, but it will encrypt traffic from local to
819 * remote, and decrypt traffic from remote to local. It will do this
820 * until one of the end points is shut down, at which time it will
821 * return and assume the context will close down both pre-existing
824 * This copycat actually has a few sharp claws to watch for -- shutdown
825 * of sockets may drop the last bit of information sent. First, the
826 * signal POLLHUP is best ignored because it travels asynchronously.
827 * Second, reading 0 is a good indicator of end-of-file and may be
828 * followed by an shutdown of reading from that stream. But, more
829 * importantly, the other side must have this information forwarded
830 * so it can shutdown. This means that a shutdown for writing to that
831 * stream is to be sent. Even when *both* sides have agreed to not send
832 * anything, they may still not have received all they were offered for
833 * reading, so we should SO_LINGER on the sockets so they can acknowledge,
834 * and after a timeout we can establish that shutdown failed and log and
835 * return an error for it.
836 * Will you believe that I had looked up if close() would suffice? The man
837 * page clearly stated yes. However, these articles offer much more detail:
838 * http://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable
839 * http://www.greenend.org.uk/rjk/tech/poll.html
841 * This function blocks during its call to poll(), in a state that can easily
842 * be restarted. This is when thread cancellation is temporarily enabled.
843 * Other threads may use this to cancel the thread and have it joined with that
844 * thread which will subsume its tasks and restart the handshake. We might
845 * later make this more advanced, by using a cancel stack push/pull mechanisms
846 * to ensure that recv() always results in send() in spite of cancellation.
848 * The return value of copycat is a GNUTLS_E_ code, usually GNUTLS_E_SUCCESS.
849 * For the moment, only one special value is of concern, namely
850 * GNUTLS_E_REHANDSHAKE which client or server side may receive when an
851 * attempt is made to renegotiate the security of the connection.
853 static int copycat (int local, int remote, gnutls_session_t wrapped, int client) {
855 struct pollfd inout [3];
857 struct linger linger = { 1, 10 };
859 int retval = GNUTLS_E_SUCCESS;
861 inout [0].fd = local;
862 inout [1].fd = remote;
863 inout [2].fd = client;
864 have_client = inout [2].fd >= 0;
866 inout [2].revents = 0; // Will not be written by poll
867 //FORK!=DETACH// inout [2].fd = ctlkey_signalling_fd;
869 inout [0].events = POLLIN;
870 inout [1].events = POLLIN;
871 inout [2].events = 0; // error events only
872 tlog (TLOG_COPYCAT, LOG_DEBUG, "Starting copycat cycle for local=%d, remote=%d, control=%d", local, remote, client);
873 while (((inout [0].events | inout [1].events) & POLLIN) != 0) {
875 assert (pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, NULL) == 0);
876 pthread_testcancel (); // Efficiency & Certainty
877 polled = poll (inout, have_client? 3: 2, -1);
878 assert (pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, NULL) == 0);
880 tlog (TLOG_COPYCAT, LOG_DEBUG, "Copycat polling returned an error");
881 break; // Polling sees an error
883 if (inout [0].revents & POLLIN) {
884 // Read local and encrypt to remote
885 sz = recv (local, buf, sizeof (buf), MSG_DONTWAIT | MSG_NOSIGNAL);
886 tlog (TLOG_COPYCAT, LOG_DEBUG, "Copycat received %d local bytes (or error<0) from %d", (int) sz, local);
888 tlog (TLOG_COPYCAT, LOG_ERR, "Error while receiving: %s", strerror (errno));
889 break; // stream error
890 } else if (sz == 0) {
891 inout [0].events &= ~POLLIN;
892 shutdown (local, SHUT_RD);
893 setsockopt (remote, SOL_SOCKET, SO_LINGER, &linger, sizeof (linger));
894 gnutls_bye (wrapped, GNUTLS_SHUT_WR);
895 } else if (gnutls_record_send (wrapped, buf, sz) != sz) {
896 tlog (TLOG_COPYCAT, LOG_ERR, "gnutls_record_send() failed to pass on the requested bytes");
897 break; // communication error
899 tlog (TLOG_COPYCAT, LOG_DEBUG, "Copycat sent %d bytes to remote %d", (int) sz, remote);
902 if (inout [1].revents & POLLIN) {
903 // Read remote and decrypt to local
904 sz = gnutls_record_recv (wrapped, buf, sizeof (buf));
905 tlog (TLOG_COPYCAT, LOG_DEBUG, "Copycat received %d remote bytes from %d (or error if <0)", (int) sz, remote);
907 //TODO// Process GNUTLS_E_REHANDSHAKE
908 if (sz == GNUTLS_E_REHANDSHAKE) {
909 tlog (TLOG_TLS, LOG_INFO, "Received renegotiation request over TLS handle %d", remote);
910 retval = GNUTLS_E_REHANDSHAKE;
912 } else if (gnutls_error_is_fatal (sz)) {
913 tlog (TLOG_TLS, LOG_ERR, "GnuTLS fatal error: %s", gnutls_strerror (sz));
914 break; // stream error
916 tlog (TLOG_TLS, LOG_INFO, "GnuTLS recoverable error: %s", gnutls_strerror (sz));
918 } else if (sz == 0) {
919 inout [1].events &= ~POLLIN;
920 shutdown (remote, SHUT_RD);
921 setsockopt (local, SOL_SOCKET, SO_LINGER, &linger, sizeof (linger));
922 shutdown (local, SHUT_WR);
923 } else if (send (local, buf, sz, MSG_DONTWAIT | MSG_NOSIGNAL) != sz) {
924 break; // communication error
926 tlog (TLOG_COPYCAT, LOG_DEBUG, "Copycat sent %d bytes to local %d", (int) sz, local);
929 inout [0].revents &= ~(POLLIN | POLLHUP); // Thy copying cat?
930 inout [1].revents &= ~(POLLIN | POLLHUP); // Retract thee claws!
931 if ((inout [0].revents | inout [1].revents) & ~POLLIN) {
932 tlog (TLOG_COPYCAT, LOG_DEBUG, "Copycat data connection polling returned a special condition");
933 break; // Apparently, one of POLLERR, POLLHUP, POLLNVAL
935 if (inout [2].revents & ~POLLIN) {
937 // This case is currently not ever triggered
938 tlog (TLOG_COPYCAT, LOG_DEBUG, "Copycat control connection polling returned a special condition");
939 break; // Apparently, one of POLLERR, POLLHUP, POLLNVAL
941 inout [2].fd = client;
942 have_client = inout [2].fd >= 0;
944 tlog (TLOG_COPYCAT, LOG_DEBUG, "Copycat signalling_fd polling raised a signal to set control fd to %d", inout [2].fd);
946 tlog (TLOG_COPYCAT, LOG_DEBUG, "Copycat signalling_fd polling raised a signal that could be ignored");
952 tlog (TLOG_COPYCAT, LOG_DEBUG, "Ending copycat cycle for local=%d, remote=%d", local, remote);
957 /* The callback function that retrieves certification information from either
958 * the client or the server in the course of the handshake procedure.
960 gtls_error clisrv_cert_retrieve (gnutls_session_t session,
961 const gnutls_datum_t* req_ca_dn,
963 const gnutls_pk_algorithm_t* pk_algos,
965 gnutls_pcert_st** pcert,
966 unsigned int *pcert_length,
967 gnutls_privkey_t *pkey) {
968 gnutls_certificate_type_t certtp;
969 gnutls_pcert_st *pc = NULL;
972 gnutls_datum_t privdatum = { NULL, 0 };
973 gnutls_datum_t certdatum = { NULL, 0 };
974 gnutls_openpgp_crt_t pgpcert = NULL;
975 gnutls_openpgp_privkey_t pgppriv = NULL;
976 int gtls_errno = GNUTLS_E_SUCCESS;
980 char sni [sizeof (cmd->cmd.pio_data.pioc_starttls.localid)];
981 size_t snilen = sizeof (sni);
988 gtls_error fetch_local_credentials (struct command *cmd);
989 gnutls_pcert_st *load_certificate_chain (uint32_t flags, unsigned int *chainlen, gnutls_datum_t *certdatum);
992 // Setup a number of common references and structures
994 cmd = (struct command *) gnutls_session_get_ptr (session);
996 E_g2e ("No data pointer with session",
997 GNUTLS_E_INVALID_SESSION);
1000 if (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_CLIENT) {
1001 lidrole = LID_ROLE_CLIENT;
1003 } else if (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_SERVER) {
1004 lidrole = LID_ROLE_SERVER;
1007 E_g2e ("TLS Pool command supports neither local client nor local server role",
1008 GNUTLS_E_INVALID_SESSION);
1011 lid = cmd->cmd.pio_data.pioc_starttls.localid;
1012 rid = cmd->cmd.pio_data.pioc_starttls.remoteid;
1015 // On a server, lookup the server name and match it against lid.
1016 // TODO: For now assume a single server name in SNI (as that is normal).
1017 if (lidrole == LID_ROLE_SERVER) {
1018 if (gnutls_server_name_get (session, sni, &snilen, &snitype, 0) || (snitype != GNUTLS_NAME_DNS)) {
1019 E_g2e ("Requested SNI error or not a DNS name",
1020 GNUTLS_E_NO_CERTIFICATE_FOUND);
1025 for (atidx=128; atidx > 0; atidx--) {
1026 if (lid [atidx-1] == '@') {
1030 if (strncmp (sni, lid + atidx, sizeof (sni)-atidx) != 0) {
1031 tlog (TLOG_TLS, LOG_ERR, "SNI %s does not match preset local identity %s", sni, lid);
1032 E_g2e ("Requested SNI does not match local identity",
1033 GNUTLS_E_NO_CERTIFICATE_FOUND);
1037 // TODO: Should ask for permission before accepting SNI
1038 memcpy (lid, sni, sizeof (sni));
1043 // Setup the lidtype parameter for responding
1044 certtp = gnutls_certificate_type_get_peers (session);
1045 if (certtp == GNUTLS_CRT_OPENPGP) {
1046 tlog (TLOG_TLS, LOG_INFO, "Serving OpenPGP certificate request as a %s", rolestr);
1047 lidtype = LID_TYPE_PGP;
1048 } else if (certtp == GNUTLS_CRT_X509) {
1049 tlog (TLOG_TLS, LOG_INFO, "Serving X.509 certificate request as a %s", rolestr);
1050 lidtype = LID_TYPE_X509;
1051 #ifdef GNUTLS_CRT_KRB
1052 } else if (certtp == GNUTLS_CRT_KRB) {
1053 tlog (TLOG_TLS, LOG_INFO, "Serving X.509 certificate request as a %s", rolestr);
1054 lidtype = LID_TYPE_KRB5;
1057 // GNUTLS_CRT_RAW, GNUTLS_CRT_UNKNOWN, or other
1058 tlog (TLOG_TLS, LOG_ERR, "Funny sort of certificate retrieval attempted as a %s", rolestr);
1059 E_g2e ("Requested certtype is neither X.509 nor OpenPGP",
1060 GNUTLS_E_CERTIFICATE_ERROR);
1065 // Find the prefetched local identity to use towards this remote
1066 // Send a callback to the user if none is available and accessible
1067 if (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALID_CHECK) {
1068 uint32_t oldcmd = cmd->cmd.pio_cmd;
1069 struct command *resp;
1070 cmd->cmd.pio_cmd = PIOC_STARTTLS_LOCALID_V2;
1071 tlog (TLOG_UNIXSOCK, LOG_DEBUG, "Calling send_callback_and_await_response with PIOC_STARTTLS_LOCALID_V2");
1072 resp = send_callback_and_await_response (cmd, 0);
1073 assert (resp != NULL); // No timeout, should be non-NULL
1074 if (resp->cmd.pio_cmd != PIOC_STARTTLS_LOCALID_V2) {
1075 tlog (TLOG_UNIXSOCK, LOG_ERR, "Callback response has unexpected command code");
1076 cmd->cmd.pio_cmd = oldcmd;
1077 return GNUTLS_E_CERTIFICATE_ERROR;
1079 assert (resp == cmd); // No ERROR, so should be the same
1080 tlog (TLOG_UNIXSOCK, LOG_DEBUG, "Processing callback response that sets plainfd:=%d and lid:=\"%s\" for rid==\"%s\"", cmd->passfd, lid, rid);
1081 cmd->cmd.pio_cmd = oldcmd;
1083 // Check that new rid is a generalisation of original rid
1084 // Note: This is only of interest for client operation
1085 if (lidrole == LID_ROLE_CLIENT) {
1086 selector_t newrid = donai_from_stable_string (rid, strlen (rid));
1087 donai_t oldrid = donai_from_stable_string (cmd->orig_starttls->remoteid, strlen (cmd->orig_starttls->remoteid));
1088 if (!donai_matches_selector (&oldrid, &newrid)) {
1089 return GNUTLS_E_NO_CERTIFICATE_FOUND;
1093 // Now reiterate to lookup lid credentials in db_localid
1094 E_g2e ("Missing local credentials",
1095 fetch_local_credentials (cmd));
1097 if (cmd->lids [lidtype - LID_TYPE_MIN].data == NULL) {
1098 fprintf (stderr, "DEBUG: Missing certificate for local ID %s and remote ID %s\n", lid, rid);
1099 E_g2e ("Missing certificate for local ID",
1100 GNUTLS_E_NO_CERTIFICATE_FOUND);
1105 // Split the credential into its various aspects
1106 ok = dbcred_interpret (
1107 &cmd->lids [lidtype - LID_TYPE_MIN],
1112 tlog (TLOG_DB, LOG_DEBUG, "BDB entry has flags=0x%08x, p11priv=\"%s\", cert.size=%d", flags, p11priv, certdatum.size);
1113 //TODO// ok = ok && verify_cert_... (...); -- keyidlookup
1115 gtls_errno = GNUTLS_E_CERTIFICATE_ERROR;
1119 // Allocate response structures
1121 *pcert = load_certificate_chain (flags, pcert_length, &certdatum);
1122 if (*pcert == NULL) {
1123 E_g2e ("Failed to load certificate chain",
1124 GNUTLS_E_CERTIFICATE_ERROR);
1127 cmd->session_certificate = (intptr_t) (void *) *pcert; //TODO// Used for session cleanup
1130 // Setup private key
1131 E_g2e ("Failed to initialise private key",
1132 gnutls_privkey_init (
1134 if ((onthefly_subjectkey != NULL) && (strcmp (p11priv, onthefly_p11uri) == 0)) {
1135 E_g2e ("Failed to import on-the-fly subject private key",
1136 gnutls_privkey_import_x509 (
1138 onthefly_subjectkey,
1139 GNUTLS_PRIVKEY_IMPORT_COPY));
1141 if (gtls_errno == GNUTLS_E_SUCCESS) {
1142 cmd->session_privatekey = (intptr_t) (void *) *pkey; //TODO// Used for session cleanup
1144 E_g2e ("Failed to import PKCS #11 private key URI",
1145 gnutls_privkey_import_pkcs11_url (
1149 E_gnutls_clear_errno ();
1151 //TODO// Moved out (start)
1154 // Setup public key certificate
1157 E_g2e ("MOVED: Failed to import X.509 certificate into chain",
1158 gnutls_pcert_import_x509_raw (
1161 GNUTLS_X509_FMT_DER,
1165 E_g2e ("MOVED: Failed to import OpenPGP certificate",
1166 gnutls_pcert_import_openpgp_raw (
1169 GNUTLS_OPENPGP_FMT_RAW,
1170 NULL, /* use master key */
1173 #ifdef GNUTLS_CRT_KRB
1175 if (lidrole == LID_ROLE_CLIENT) {
1176 // KDH-Only or KDH-Enhanced; fetch ticket for localid
1177 // and a TGT based on it for service/remoteid@REALM
1178 char *svc = cmd->service;
1179 gnutls_datum_t *server_tgt = NULL;
1180 // If the server provides a TGT, employ ENC-TKT-IN-SKEY
1181 if (gnutls_certificate_type_get_peers (cmd->session) == GNUTLS_CRT_KRB) {
1182 // Try to get the server's TGT; it returns NULL
1183 // if it wasn't found. We will not try this
1184 // unless we know what we'd find would be KRB.
1185 server_tgt = gnutls_certificate_get_peers (cmd->session, NULL);
1187 // The servicename may need mapping to another form
1188 if (strcmp (svc, "http")) {
1191 //TODO: Have a client ticket matching the found localid
1192 //TODO: From the client ticket, obtain a service ticket
1193 //TODO: Export the service ticket
1195 // KDH-Only with server-side TGT
1196 //TODO: Have a server-side TGT for the service/remoteid
1197 //TODO: Export the server-side TGT
1199 E_g2e ("Failed to import Kerberos ticket",
1200 gnutls_pcert_import_pgp_raw (
1202 &certdatum, //TODO// Service ticket
1206 /* Should not happen */
1210 //TODO// Moved out (end)
1213 // Lap up any overseen POSIX error codes in errno
1215 tlog (TLOG_TLS, LOG_DEBUG, "Failing TLS on errno=%d / %s", errno, strerror (errno));
1216 cmd->session_errno = errno;
1217 gtls_errno = GNUTLS_E_NO_CIPHER_SUITES; /* Vaguely matching */
1221 // Return the overral error code, hopefully GNUTLS_E_SUCCESS
1222 tlog (TLOG_TLS, LOG_DEBUG, "Returning %d / %s from clisrv_cert_retrieve()", gtls_errno, gnutls_strerror (gtls_errno));
1223 printf ("DEBUG: clisrv_cert_retrieve() sets *pcert to 0x%xl (length %d)... {pubkey = 0x%lx, cert= {data = 0x%lx, size=%ld}, type=%ld}\n", (long) *pcert, *pcert_length, (long) (*pcert)->pubkey, (long) (*pcert)->cert.data, (long) (*pcert)->cert.size, (long) (*pcert)->type);
1227 /* Load a single certificate in the given gnutls_pcert_st from the given
1228 * gnutls_datum_t. Use the lidtype to determine how to do this.
1230 gtls_error load_certificate (int lidtype, gnutls_pcert_st *pcert, gnutls_datum_t *certdatum) {
1231 int gtls_errno = GNUTLS_E_SUCCESS;
1233 // Setup public key certificate
1236 fprintf (stderr, "DEBUG: About to import %d bytes worth of X.509 certificate into chain: %02x %02x %02x %02x...\n", certdatum->size, certdatum->data[0], certdatum->data[1], certdatum->data[2], certdatum->data[3]);
1237 E_g2e ("Failed to import X.509 certificate into chain",
1238 gnutls_pcert_import_x509_raw (
1241 GNUTLS_X509_FMT_DER,
1245 E_g2e ("Failed to import OpenPGP certificate",
1246 gnutls_pcert_import_openpgp_raw (
1249 GNUTLS_OPENPGP_FMT_RAW,
1250 NULL, /* use master key */
1254 /* Should not happen */
1261 /* Load a certificate chain. This returns a value for a retrieval function's
1262 * pcert, and also modifies the chainlen. The latter starts at 0, and is
1263 * incremented in a nested procedure that unrolls until all certificates are
1266 gnutls_pcert_st *load_certificate_chain (uint32_t flags, unsigned int *chainlen, gnutls_datum_t *certdatum) {
1267 gnutls_pcert_st *chain;
1268 unsigned int mypos = *chainlen;
1269 int gtls_errno = GNUTLS_E_SUCCESS;
1272 // Quick and easy: No chaining required, just add the literal data.
1273 // Note however, this may be the end of a chain, so allocate all
1274 // structures and load the single one at the end.
1275 if ((flags & (LID_CHAINED | LID_NEEDS_CHAIN)) == 0) {
1277 chain = (gnutls_pcert_st *) calloc (*chainlen, sizeof (gnutls_pcert_st));
1278 if (chain != NULL) {
1279 bzero (chain, (*chainlen) * sizeof (gnutls_pcert_st));
1281 gtls_errno = GNUTLS_E_MEMORY_ERROR;
1283 E_g2e ("Failed to load certificate into chain",
1285 flags & LID_TYPE_MASK,
1288 if (gtls_errno != GNUTLS_E_SUCCESS) {
1299 // First extended case. Chain certs in response to LID_CHAINED.
1300 // Recursive calls are depth-first, so we only add our first cert
1301 // after a recursive call succeeds. Any LID_NEEDS_CHAIN work is
1302 // added after LID_CHAINED, so is higher up in the hierarchy, but
1303 // it is loaded as part of the recursion. To support that, a
1304 // recursive call with certdatum.size==0 is possible when the
1305 // LID_NEEDS_CHAIN flag is set, and this section then skips.
1306 // Note that this code is also used to load the certificate chain
1307 // provided by LID_NEEDS_CHAIN, but by then the flag in a recursive
1308 // call is replaced with LID_CHAINED and no more LID_NEEDS_CHAIN.
1309 if (((flags & LID_CHAINED) != 0) && (certdatum->size > 0)) {
1312 gnutls_datum_t nextdatum;
1314 // Note: Accept BER because the outside SEQUENCE is not signed
1315 certlen = asn1_get_length_ber (
1316 ((char *) certdatum->data) + 1,
1319 certlen += 1 + lenlen;
1320 tlog (TLOG_CERT, LOG_DEBUG, "Found LID_CHAINED certificate size %d", certlen);
1321 if (certlen > certdatum->size) {
1322 tlog (TLOG_CERT, LOG_ERR, "Refusing LID_CHAINED certificate beyond data size %d", certdatum->size);
1325 } else if (certlen <= 0) {
1326 tlog (TLOG_CERT, LOG_ERR, "Refusing LID_CHAINED certificate of too-modest data size %d", certlen);
1330 nextdatum.data = ((char *) certdatum->data) + certlen;
1331 nextdatum.size = certdatum->size - certlen;
1332 certdatum->size = certlen;
1333 nextlen = asn1_get_length_ber (
1334 ((char *) nextdatum.data) + 1,
1337 nextlen += 1 + lenlen;
1338 if (nextlen == nextdatum.size) {
1339 // The last cert is loaded thinking it is not CHAINED,
1340 // but NEEDS_CHAIN can still be present for expansion.
1341 flags &= ~LID_CHAINED;
1344 chain = load_certificate_chain (flags, chainlen, &nextdatum);
1345 if (chain != NULL) {
1346 E_g2e ("Failed to add chained certificate",
1348 flags & LID_TYPE_MASK,
1351 if (gtls_errno != GNUTLS_E_SUCCESS) {
1361 // Second extended case. Chain certs in response to LID_NEEDS_CHAIN.
1362 // These are the highest-up in the hierarchy, above any LID_CHAINED
1363 // certificates. The procedure for adding them is looking them up
1364 // in a central database by their authority key identifier. What is
1365 // found is assumed to be a chain, and will be unrolled by replacing
1366 // the LID_NEEDS_CHAIN flag with LID_CHAINED and calling recursively.
1367 if (((flags & LID_NEEDS_CHAIN) != 0) && (certdatum->size == 0)) {
1368 //TODO//CODE// lookup new certdatum
1369 flags &= ~LID_NEEDS_CHAIN;
1370 flags |= LID_CHAINED;
1371 //TODO//CODE// recursive call
1372 //TODO//CODE// no structures to fill here
1373 //TODO//CODE// cleanup new certdatum
1377 // Final judgement. Nothing worked. Return failure.
1383 /* valexp_valflag_set -- set a validation flag bit for an uppercase predicate.
1385 static void valexp_valflag_set (struct command *cmd, char pred) {
1386 int len = strlen (cmd->valflags);
1387 cmd->valflags [len++] = pred;
1388 cmd->valflags [len ] = '\0';
1391 /* valexp_valflag_start -- get a prior set bit with validation information.
1392 * Where cmd->valflags is a string of uppercase letters that were ensured.
1394 static void valexp_valflag_start (void *vcmd, struct valexp *ve, char pred) {
1395 struct command *cmd = (struct command *) vcmd;
1396 pred &= 0xdf; // lowercase->uppercase
1397 valexp_setpredicate (ve, pred, NULL != strchr (cmd->valflags, pred));
1400 /* valexp_0_start -- validation function for the GnuTLS backend.
1401 * This function immediately sends failure on something impossible.
1403 static void valexp_0_start (void *vcmd, struct valexp *ve, char pred) {
1404 valexp_setpredicate (ve, pred, 0);
1407 /* valexp_1_start -- validation function for the GnuTLS backend.
1408 * This function immediately sends success on something trivial.
1410 static void valexp_1_start (void *vcmd, struct valexp *ve, char pred) {
1411 valexp_setpredicate (ve, pred, 1);
1414 //TODO// valexp_L_start, valexp_l_start
1416 /* valexp_I_start -- validation function for the GnuTLS backend.
1417 * This function ensures that the remote peer provides an identity.
1418 * TODO: We should compare the hostname as well, or compare if in remoteid
1419 * TODO: We may need to support more than just X509/PGP certificates
1421 static void valexp_I_start (void *vcmd, struct valexp *ve, char pred) {
1422 struct command *cmd = (struct command *) vcmd;
1423 unsigned int num_certs = 0;
1424 // peer-returned "certs" points into GnuTLS' internal data structures
1425 valexp_setpredicate (ve, pred,
1426 (gnutls_certificate_get_peers (cmd->session, &num_certs) != NULL)
1427 && (num_certs > 0));
1430 /* valexp_i_start -- is opportunistic and will always succeed
1432 #define valexp_i_start valexp_1_start
1434 /* valexp_Ff_start -- validation function for the GnuTLS backend.
1435 * This functin ensures that forward secrecy is applied.
1436 * While _F_ only accepts DHE, _f_ will also accept DH.
1437 * Note: GnuTLS does not seem to show DH that is not also DHE.
1439 static void valexp_Ff_start (void *vcmd, struct valexp *ve, char pred) {
1440 struct command *cmd = (struct command *) vcmd;
1441 gnutls_kx_algorithm_t kx = gnutls_kx_get (cmd->session);
1443 case GNUTLS_KX_UNKNOWN:
1445 case GNUTLS_KX_RSA_EXPORT:
1448 valexp_setpredicate (ve, pred, 0);
1450 case GNUTLS_KX_DHE_DSS:
1451 case GNUTLS_KX_DHE_RSA:
1453 case GNUTLS_KX_SRP_RSA:
1454 case GNUTLS_KX_SRP_DSS:
1455 case GNUTLS_KX_DHE_PSK:
1456 case GNUTLS_KX_ECDHE_RSA:
1457 case GNUTLS_KX_ECDHE_ECDSA:
1458 case GNUTLS_KX_ECDHE_PSK:
1459 case GNUTLS_KX_ANON_ECDH: // Assume DHE is in fact implemented
1460 case GNUTLS_KX_ANON_DH: // Assume DHE is in fact implemented
1461 valexp_setpredicate (ve, pred, 1);
1463 // case GNUTLS_KX_xxx_DH:
1464 // valexp_setpredicate (ve, pred, pred != 'F');
1469 /* valexp_A_start -- validation function for the GnuTLS backend.
1470 * This function ensures that an anonymising precursor is used.
1472 #define valexp_A_start valexp_valflag_start
1474 /* valexp_a_start -- is opportunistic and will always succeed */
1475 #define valexp_a_start valexp_1_start
1477 /* valexp_Tt_start -- validation function for the GnuTLS backend.
1478 * This function ensures trust based on a trusted certificate/key list.
1479 * In the _t_ case, self-signed certificates are also accepted.
1481 static void valexp_Tt_start (void *vcmd, struct valexp *ve, char pred) {
1482 struct command *cmd = (struct command *) vcmd;
1484 gnutls_credentials_type_t authtp;
1485 const gnutls_datum_t *certs;
1486 unsigned int num_certs;
1487 if (cmd->vfystatus == 0) {
1490 authtp = gnutls_auth_get_type (cmd->session);
1491 if (authtp != GNUTLS_CRD_CERTIFICATE) {
1494 certs = gnutls_certificate_get_peers (cmd->session, &num_certs);
1495 // "certs" points into GnuTLS' internal data structures
1496 if (num_certs < 1) {
1499 if ((num_certs == 1) && (pred == 't')) {
1500 //TODO// if (self-signature-correct) {
1501 //TODO// flagval = 1;
1502 //TODO// goto setflagval;
1505 //TODO// Look in trust.db for H(cert[num_certs-1])
1506 //TODO// flagval = 1;
1508 valexp_setpredicate (ve, pred, flagval);
1511 /* valexp_Dd_start -- validation function for the GnuTLS backend.
1512 * This function validates through DNSSEC.
1513 * While _D_ enforces DNSSEC, _d_ also accepts opted-out security.
1515 static void valexp_Dd_start (void *vcmd, struct valexp *ve, char pred) {
1516 struct command *cmd = (struct command *) vcmd;
1519 unsigned int vfystat;
1523 struct sockaddr peername;
1524 socklen_t peernamesz = sizeof (peername);
1526 host = strchr (cmd->cmd.pio_data.pioc_starttls.remoteid, '@');
1528 host = cmd->cmd.pio_data.pioc_starttls.remoteid;
1530 switch (cmd->cmd.pio_data.pioc_starttls.ipproto) {
1543 sox = gnutls_transport_get_int (cmd->session);
1547 if (getpeername (sox, &peername, &peernamesz) != 0) {
1550 if ((peername.sa_family == AF_INET) &&
1551 (peernamesz == sizeof (struct sockaddr_in))) {
1552 port = ntohs (((struct sockaddr_in *) &peername)->sin_port);
1553 } else if ((peername.sa_family == AF_INET6) &&
1554 (peernamesz == sizeof (struct sockaddr_in6))) {
1556 port = ntohs (((struct sockaddr_in6 *) &peername)->sin6_port);
1559 if (dane_state_init (&stat, /*TODO:*/ 0) != GNUTLS_E_SUCCESS) {
1562 if (dane_verify_session_crt (stat,
1568 DANE_VFLAG_FAIL_IF_NOT_CHECKED,
1569 &vfystat) == DANE_E_SUCCESS) {
1570 if ((pred == 'D') && (vfystat & DANE_VERIFY_UNKNOWN_DANE_INFO)) {
1571 dane_state_deinit (stat);
1574 flagval = ((vfystat & ~DANE_VERIFY_UNKNOWN_DANE_INFO) == 0);
1576 dane_state_deinit (stat);
1578 valexp_setpredicate (ve, pred, flagval);
1581 /* valexp_Rr_start -- validation function for the GnuTLS backend.
1582 * This function validates through a CRL.
1583 * While _R_ requires the CRL to be present, _r_ accepts confirmed absense.
1584 * TODO: This is not implemented yet.
1586 static void valexp_Rr_start (void *vcmd, struct valexp *ve, char pred) {
1588 valexp_setpredicate (ve, pred, 0);
1591 /* valexp_Ee_start -- validation function for the GnuTLS backend.
1592 * This function validates certificate extensions for the named service.
1593 * While _E_ required OIDs to be marked critical, _e_ also accepts non-crit.
1595 static void valexp_Ee_start (void *vcmd, struct valexp *ve, char pred) {
1597 valexp_setpredicate (ve, pred, 0);
1600 /* valexp_Oo_start -- validation function for the GnuTLS backend.
1601 * This function validates with online/live information.
1602 * While _O_ required positive confirmation, _o_ also accepts unknown.
1603 * -> For X.509, look in OCSP
1604 * -> For OpenPGP, redirect O->G, o->g
1605 * -> For Kerberos, accept anything as sufficiently live / online
1607 static void valexp_Oo_start (void *vcmd, struct valexp *ve, char pred) {
1608 struct command *cmd = (struct command *) vcmd;
1612 gnutls_credentials_type_t authtp;
1613 gnutls_certificate_type_t certtp;
1614 online2success_t o2vf;
1616 gnutls_datum_t *crt;
1617 unsigned int crtcount;
1618 authtp = gnutls_auth_get_type (cmd->session);
1619 if (authtp != GNUTLS_CRD_CERTIFICATE) {
1620 // No authentication types other than certificates yet
1623 if ((pred >= 'a') && (pred <= 'z')) {
1624 o2vf = online2success_optional;
1626 o2vf = online2success_enforced;
1628 certtp = gnutls_certificate_type_get (cmd->session);
1629 crt = gnutls_certificate_get_peers (cmd->session, &crtcount);
1630 rid = cmd->cmd.pio_data.pioc_starttls.remoteid;
1631 if (certtp == GNUTLS_CRT_OPENPGP) {
1632 valflag = o2vf (online_globaldir_pgp (
1633 rid, crt->data, crt->size));
1634 } else if (certtp == GNUTLS_CRT_X509) {
1635 //TODO// OCSP inquiry or globaldir
1636 valflag = o2vf (online_globaldir_x509 (
1637 rid, crt->data, crt->size));
1638 #ifdef GNUTLS_CRT_KRB
1639 } else if (certtp == GNUTLS_CRT_KRB) {
1640 // Kerberos is sufficiently "live" to be pass O
1645 // GNUTLS_CRT_RAW, GNUTLS_CRT_UNKNOWN, or other
1650 valexp_setpredicate (ve, pred, valflag);
1653 /* valexp_Gg_start -- validation function for the GnuTLS backend.
1654 * This function validates through the LDAP global directory.
1655 * While _G_ requires information to be present, _g_ also accepts absense.
1656 * -> For X.509, lookup userCertificate
1657 * -> For OpenPGP, lookup pgpKey
1658 * -> For KDH, lookup krbPrincipalName
1659 * -> For SRP, nothing is defined
1660 * -> For OpenSSH, no TLS support
1662 static void valexp_Gg_start (void *vcmd, struct valexp *ve, char pred) {
1663 struct command *cmd = (struct command *) vcmd;
1667 gnutls_credentials_type_t authtp;
1668 gnutls_certificate_type_t certtp;
1669 online2success_t o2vf;
1671 gnutls_datum_t *crt;
1672 unsigned int crtcount;
1673 authtp = gnutls_auth_get_type (cmd->session);
1674 if (authtp != GNUTLS_CRD_CERTIFICATE) {
1675 // No authentication types other than certificates yet
1678 if ((pred >= 'a') && (pred <= 'z')) {
1679 o2vf = online2success_optional;
1681 o2vf = online2success_enforced;
1683 certtp = gnutls_certificate_type_get (cmd->session);
1684 crt = gnutls_certificate_get_peers (cmd->session, &crtcount);
1685 rid = cmd->cmd.pio_data.pioc_starttls.remoteid;
1686 if (certtp == GNUTLS_CRT_OPENPGP) {
1687 valflag = o2vf (online_globaldir_pgp (
1688 rid, crt->data, crt->size));
1689 } else if (certtp == GNUTLS_CRT_X509) {
1690 //TODO// OCSP inquiry or globaldir
1691 valflag = o2vf (online_globaldir_x509 (
1692 rid, crt->data, crt->size));
1693 #ifdef GNUTLS_CRT_KRB
1694 } else if (certtp == GNUTLS_CRT_KRB) {
1696 //TODO// valflag = o2vf (online_globaldir_kerberos (
1697 //TODO// rid, crt->data, crt->size));
1700 // GNUTLS_CRT_RAW, GNUTLS_CRT_UNKNOWN, or other
1705 valexp_setpredicate (ve, pred, valflag);
1708 /* valexp_Pp_start -- validation function for the GnuTLS backend.
1709 * This function validates through pinning information.
1710 * While _P_ requires pinning to be present, _p_ will Trust On First Use.
1712 static void valexp_Pp_start (void *vcmd, struct valexp *ve, char pred) {
1714 valexp_setpredicate (ve, pred, 0);
1717 /* valexp_U_start -- validation function for the GnuTLS backend.
1718 * This function validates a matching username.
1720 static void valexp_U_start (void *vcmd, struct valexp *ve, char pred) {
1722 valexp_setpredicate (ve, pred, 0);
1725 /* valexp_Ss_start -- validation function for the GnuTLS backend.
1726 * This function ensures that the local end is a server.
1727 * While _S_ denies credentials also usable for clients, _s_ permits them.
1729 static void valexp_Ss_start (void *vcmd, struct valexp *ve, char pred) {
1730 struct command *cmd = (struct command *) vcmd;
1732 if ((pred == 'S') && (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_CLIENT)) {
1735 flagval = (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_SERVER) != 0;
1737 valexp_setpredicate (ve, pred, flagval);
1740 /* valexp_Cc_start -- validation function for the GnuTLS backend.
1741 * This function ensures that the local end is a client.
1742 * While _C_ denies credentials also usable for servers, _c_ permits them.
1744 static void valexp_Cc_start (void *vcmd, struct valexp *ve, char pred) {
1745 struct command *cmd = (struct command *) vcmd;
1747 if ((pred == 'C') && (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_SERVER)) {
1750 flagval = (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_CLIENT) != 0;
1752 valexp_setpredicate (ve, pred, flagval);
1757 /* Fetch local credentials. This can be done before TLS is started, to find
1758 * the possible authentication forms that can be offered. The function
1759 * can additionally be used after interaction with the client to establish
1760 * a local identity that was not initially provided, or that was not
1761 * considered public at the time.
1763 gtls_error fetch_local_credentials (struct command *cmd) {
1766 DBC *crs_disclose = NULL;
1767 DBC *crs_localid = NULL;
1771 selector_t remote_selector;
1775 gtls_error certificate_onthefly (struct command *cmd);
1778 // When applicable, try to create an on-the-fly certificate
1779 if (((cmd->cmd.pio_cmd == PIOC_STARTTLS_V2) &&
1780 (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALID_ONTHEFLY))
1781 || ((cmd->cmd.pio_cmd == PIOC_LIDENTRY_CALLBACK_V2) &&
1782 (cmd->cmd.pio_data.pioc_lidentry.flags & PIOF_LIDENTRY_ONTHEFLY))) {
1783 gtls_errno = certificate_onthefly (cmd);
1784 if (gtls_errno != GNUTLS_E_AGAIN) {
1785 // This includes GNUTLS_E_SUCCESS
1786 fprintf (stderr, "DEBUG: otfcert retrieval returned %d\n", gtls_errno);
1789 fprintf (stderr, "DEBUG: otfcert retrieval returned GNUTLS_E_AGAIN, so skip it\n", gtls_errno);
1790 gtls_errno = GNUTLS_E_SUCCESS; // Attempt failed, ignore
1795 // Setup a number of common references and structures
1796 // Note: Current GnuTLS cannot support being a peer
1797 if (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_CLIENT) {
1798 lidrole = LID_ROLE_CLIENT;
1799 } else if (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_SERVER) {
1800 lidrole = LID_ROLE_SERVER;
1802 E_g2e ("TLS Pool command supports neither local client nor local server role",
1803 GNUTLS_E_INVALID_SESSION);
1806 lid = cmd->cmd.pio_data.pioc_starttls.localid;
1807 rid = cmd->cmd.pio_data.pioc_starttls.remoteid;
1810 // Refuse to disclose client credentials when the server name is unset;
1811 // note that server-claimed identities are unproven during handshake.
1812 if ((lidrole == LID_ROLE_CLIENT) && (*rid == '\0')) {
1813 tlog (TLOG_USER, LOG_ERR, "No remote identity (server name) set, so no client credential disclosure");
1814 E_g2e ("Missing remote ID",
1815 GNUTLS_E_NO_CERTIFICATE_FOUND);
1819 // Setup database iterators to map identities to credentials
1820 if (lidrole == LID_ROLE_CLIENT) {
1821 E_d2e ("Failed to create db_disclose cursor",
1822 dbh_disclose->cursor (
1828 E_d2e ("Failed to create db_localid cursor",
1829 dbh_localid->cursor (
1835 // Prepare for iteration over possible local identities / credentials
1838 if (gtls_errno != 0) {
1840 } else if (lidrole == LID_ROLE_CLIENT) {
1841 memcpy (cid, rid, sizeof (cid));
1842 dbt_init_fixbuf (&discpatn, cid, strlen (cid));
1843 dbt_init_fixbuf (&keydata, mid, sizeof (mid)-1);
1844 dbt_init_malloc (&creddata);
1846 donai_t remote_donai = donai_from_stable_string (rid, strlen (rid));
1847 if (!selector_iterate_init (&remote_selector, &remote_donai)) {
1848 E_g2e ("Syntax of remote ID unsuitable for selector",
1849 GNUTLS_E_INVALID_REQUEST);
1851 E_d2e ("Failed to start iterator on remote ID selector",
1852 dbcred_iterate_from_remoteid_selector (
1861 dbt_init_fixbuf (&discpatn, "", 0); // Unused but good style
1862 dbt_init_fixbuf (&keydata, lid, strlen (lid));
1863 dbt_init_malloc (&creddata);
1864 E_d2e ("Failed to start iterator on local ID",
1865 dbcred_iterate_from_localid (
1870 if (db_errno != 0) {
1871 gtls_errno = GNUTLS_E_DB_ERROR;
1875 // Now store the local identities inasfar as they are usable
1877 while ((gtls_errno == GNUTLS_E_SUCCESS) && (db_errno == 0)) {
1882 tlog (TLOG_DB, LOG_DEBUG, "Found BDB entry %s disclosed to %s", creddata.data + 4, (lidrole == LID_ROLE_CLIENT)? rid: "all clients");
1886 lidtype = flags & LID_TYPE_MASK;
1887 ok = ok && ((flags & lidrole) != 0);
1888 ok = ok && ((flags & LID_NO_PKCS11) == 0);
1889 ok = ok && (lidtype >= LID_TYPE_MIN);
1890 ok = ok && (lidtype <= LID_TYPE_MAX);
1891 tlog (TLOG_DB, LOG_DEBUG, "BDB entry has flags=0x%08x, so we (%04x/%04x) %s it", flags, lidrole, LID_ROLE_MASK, ok? "store": "skip ");
1893 // Move the credential into the command structure
1894 dbt_store (&creddata,
1895 &cmd->lids [lidtype - LID_TYPE_MIN]);
1898 // Skip the credential by freeing its data structure
1899 dbt_free (&creddata);
1901 db_errno = dbcred_iterate_next (crs_disclose, crs_localid, &discpatn, &keydata, &creddata);
1904 if (db_errno == DB_NOTFOUND) {
1906 gtls_errno = GNUTLS_E_NO_CERTIFICATE_FOUND;
1909 if (crs_localid != NULL) {
1910 crs_localid->close (crs_localid);
1913 if (crs_disclose != NULL) {
1914 crs_disclose->close (crs_disclose);
1915 crs_disclose = NULL;
1922 * Check if a given cmd has the given LID_TYPE setup.
1923 * Return 1 for yes or 0 for no; this is used in priority strings.
1925 static inline int lidtpsup (struct command *cmd, int lidtp) {
1926 return 1; //TODO// Can we decide if we needn't authenticate?
1927 return cmd->lids [lidtp - LID_TYPE_MIN].data != NULL;
1930 /* Configure the GnuTLS session with suitable credentials and priority string.
1931 * The anonpre_ok flag should be non-zero to permit Anonymous Precursor.
1933 * The credential setup is optional; when creds is NULL, no changes will
1936 static int configure_session (struct command *cmd,
1937 gnutls_session_t session,
1938 struct credinfo *creds,
1942 int gtls_errno = GNUTLS_E_SUCCESS;
1944 // Install the shared credentials for the client or server role
1945 if (creds != NULL) {
1946 gnutls_credentials_clear (session);
1947 for (i=0; i<credcount; i++) {
1948 E_g2e ("Failed to install credentials into TLS session",
1949 gnutls_credentials_set (
1956 // Setup the priority string for this session; this avoids future
1957 // credential callbacks that ask for something impossible or
1960 // Variation factors:
1961 // - starting configuration (can it be empty?)
1962 // - Configured security parameters (database? variable?)
1963 // - CTYPEs, SRP, ANON-or-not --> fill in as + or - characters
1964 if (gtls_errno == GNUTLS_E_SUCCESS) {
1966 snprintf (priostr, sizeof (priostr)-1,
1967 // "NORMAL:-RSA:" -- also ECDH-RSA, ECDHE-RSA, ...DSA...
1969 "+VERS-TLS-ALL:+VERS-DTLS-ALL:"
1971 "+CIPHER-ALL:+CURVE-ALL:+SIGN-ALL:+MAC-ALL:"
1973 "+ECDHE-RSA:+DHE-RSA:+ECDHE-ECDSA:+DHE-DSS:+RSA:" //TODO//
1976 "%cSRP:%cSRP-RSA:%cSRP-DSS",
1977 anonpre_ok ?'+':'-',
1978 lidtpsup (cmd, LID_TYPE_X509) ?'+':'-',
1979 lidtpsup (cmd, LID_TYPE_PGP) ?'+':'-',
1980 //TODO// Temporarily patched out SRP
1981 lidtpsup (cmd, LID_TYPE_SRP) ?'+':'-',
1982 lidtpsup (cmd, LID_TYPE_SRP) ?'+':'-',
1983 lidtpsup (cmd, LID_TYPE_SRP) ?'+':'-');
1984 // strcpy (priostr, "NONE:+VERS-TLS-ALL:+MAC-ALL:+RSA:+AES-128-CBC:+SIGN-ALL:+COMP-NULL"); //TODO:TEST//
1985 // strcpy (priostr, "NONE:+VERS-TLS-ALL:+VERS-DTLS-ALL:+MAC-ALL:+RSA:+AES-128-CBC:+SIGN-ALL:+COMP-NULL"); //TODO:TEST//
1986 tlog (TLOG_TLS, LOG_DEBUG, "Constructed priority string %s for local ID %s",
1987 priostr, cmd->cmd.pio_data.pioc_starttls.localid);
1988 E_g2e ("Failed to set GnuTLS priority string",
1989 gnutls_priority_set_direct (
1995 // Return the application GNUTLS_E_ code including _SUCCESS
1999 /* The callback functions retrieve various bits of information for the client
2000 * or server in the course of the handshake procedure.
2002 * The logic here is based on client-sent information, such as:
2003 * - TLS hints -- X.509 or alternatives like OpenPGP, SRP, PSK
2004 * - TLS hints -- Server Name Indication
2005 * - User hints -- local and remote identities provided
2007 int srv_clienthello (gnutls_session_t session) {
2008 struct command *cmd;
2009 char sni [sizeof (cmd->cmd.pio_data.pioc_starttls.remoteid)]; // static
2010 size_t snilen = sizeof (sni);
2012 int gtls_errno = GNUTLS_E_SUCCESS;
2015 fprintf (stderr, "DEBUG: Got errno = %d / %s at %d\n", errno, strerror (errno), __LINE__);
2017 fprintf (stderr, "DEBUG: Got errno = %d / %s at %d\n", errno, strerror (errno), __LINE__);
2019 // Setup a number of common references
2020 cmd = (struct command *) gnutls_session_get_ptr (session);
2022 return GNUTLS_E_INVALID_SESSION;
2024 lid = cmd->cmd.pio_data.pioc_starttls.localid;
2027 // Setup server-specific credentials and priority string
2028 //TODO// get anonpre value here
2029 fprintf (stderr, "DEBUG: Got gtls_errno = %d at %d\n", gtls_errno, __LINE__);
2030 fprintf (stderr, "DEBUG: Got errno = %d / %s at %d\n", errno, strerror (errno), __LINE__);
2031 E_g2e ("Failed to reconfigure GnuTLS as a server",
2032 configure_session (cmd,
2034 srv_creds, srv_credcount,
2035 cmd->anonpre & ANONPRE_SERVER));
2036 fprintf (stderr, "DEBUG: Got gtls_errno = %d at %d\n", gtls_errno, __LINE__);
2039 // Setup to ignore/request/require remote identity (from client)
2040 fprintf (stderr, "DEBUG: Got errno = %d / %s at %d\n", errno, strerror (errno), __LINE__);
2041 if (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_IGNORE_REMOTEID) {
2042 // Neither Request nor Require remoteid; ignore it
2044 } else if (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_REQUEST_REMOTEID) {
2045 // Use Request instead of Require for remoteid
2046 ( //RETURNS_VOID// E_g2e ("Failed to request remote identity",
2047 gnutls_certificate_server_set_request (
2049 GNUTLS_CERT_REQUEST));
2050 fprintf (stderr, "DEBUG: Got gtls_errno = %d at %d\n", gtls_errno, __LINE__);
2052 // Require a remoteid from the client (default)
2053 ( //RETURNS_VOID// E_g2e ("Failed to require remote identity (the default)",
2054 gnutls_certificate_server_set_request (
2056 GNUTLS_CERT_REQUIRE));
2057 fprintf (stderr, "DEBUG: Got gtls_errno = %d at %d\n", gtls_errno, __LINE__);
2061 // Find the client-helloed ServerNameIndication, or the service name
2062 fprintf (stderr, "DEBUG: Got errno = %d / %s at %d\n", errno, strerror (errno), __LINE__);
2064 if (gnutls_server_name_get (session, sni, &snilen, &snitype, 0) == 0) {
2065 fprintf (stderr, "DEBUG: Got errno = %d / %s at %d\n", errno, strerror (errno), __LINE__);
2067 case GNUTLS_NAME_DNS:
2069 // Note: In theory, other name types could be sent, and it would
2070 // be useful to access indexes beyond 0. In practice, nobody
2071 // uses other name types than exactly one GNUTLS_NAME_DNS.
2074 tlog (TLOG_TLS, LOG_ERR, "Received an unexpected SNI type; that is possible but uncommon; skipping SNI");
2075 fprintf (stderr, "DEBUG: Got errno = %d / %s at %d\n", errno, strerror (errno), __LINE__);
2079 fprintf (stderr, "DEBUG: Got errno = %d / %s at %d\n", errno, strerror (errno), __LINE__);
2080 if (sni [0] != '\0') {
2083 for (atidx=128; atidx > 0; atidx--) {
2084 if (lid [atidx-1] == '@') {
2088 if (strncmp (sni, lid + atidx, sizeof (sni)-atidx) != 0) {
2089 tlog (TLOG_USER | TLOG_TLS, LOG_ERR, "Mismatch between client-sent SNI %s and local identity %s", sni, lid);
2090 fprintf (stderr, "DEBUG: Got errno = %d / %s at %d\n", errno, strerror (errno), __LINE__);
2091 return GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET;
2094 memcpy (lid, sni, sizeof (sni));
2095 fprintf (stderr, "DEBUG: Got errno = %d / %s at %d\n", errno, strerror (errno), __LINE__);
2098 memcpy (sni, lid, sizeof (sni)-1);
2099 fprintf (stderr, "DEBUG: Got errno = %d / %s at %d\n", errno, strerror (errno), __LINE__);
2100 sni [sizeof (sni) - 1] = '\0';
2102 fprintf (stderr, "DEBUG: Got gtls_errno = %d at %d\n", gtls_errno, __LINE__);
2105 // Lap up any unnoticed POSIX error messages
2107 cmd->session_errno = errno;
2108 fprintf (stderr, "DEBUG: Got errno = %d / %s at %d\n", errno, strerror (errno), __LINE__);
2109 gtls_errno = GNUTLS_E_NO_CIPHER_SUITES; /* Vaguely matching */
2110 fprintf (stderr, "DEBUG: Got gtls_errno = %d at %d\n", gtls_errno, __LINE__);
2114 // Round off with an overal judgement
2115 fprintf (stderr, "DEBUG: Returning gtls_errno = %d or \"%s\" from srv_clihello()\n", gtls_errno, gnutls_strerror (gtls_errno));
2120 int cli_srpcreds_retrieve (gnutls_session_t session,
2124 tlog (TLOG_CRYPTO, LOG_DEBUG, "Picking up SRP credentials");
2125 *username = strdup ("tester");
2126 *password = strdup ("test");
2127 return GNUTLS_E_SUCCESS;
2131 /* Setup credentials to be shared by all clients and servers.
2132 * Credentials are generally implemented through callback functions.
2133 * This should be called after setting up DH parameters.
2135 int setup_starttls_credentials (void) {
2136 gnutls_anon_server_credentials_t srv_anoncred = NULL;
2137 gnutls_anon_client_credentials_t cli_anoncred = NULL;
2138 gnutls_certificate_credentials_t clisrv_certcred = NULL;
2139 //TODO:NOTHERE// int srpbits;
2140 gnutls_srp_server_credentials_t srv_srpcred = NULL;
2141 gnutls_srp_client_credentials_t cli_srpcred = NULL;
2142 //TODO// gnutls_kdh_server_credentials_t srv_kdhcred = NULL;
2143 //TODO// gnutls_kdh_server_credentials_t cli_kdhcred = NULL;
2144 int gtls_errno = GNUTLS_E_SUCCESS;
2145 int gtls_errno_stack0 = GNUTLS_E_SUCCESS;
2148 // Construct anonymous server credentials
2149 E_g2e ("Failed to allocate ANON-DH server credentials",
2150 gnutls_anon_allocate_server_credentials (
2152 if (!have_error_codes ()) /* E_g2e (...) */ gnutls_anon_set_server_dh_params (
2155 if (gtls_errno == GNUTLS_E_SUCCESS) {
2156 tlog (TLOG_CRYPTO, LOG_INFO, "Setting server anonymous credentials");
2157 srv_creds [srv_credcount].credtp = GNUTLS_CRD_ANON;
2158 srv_creds [srv_credcount].cred = (void *) srv_anoncred;
2160 } else if (srv_anoncred != NULL) {
2161 gnutls_anon_free_server_credentials (srv_anoncred);
2162 srv_anoncred = NULL;
2166 // Construct anonymous client credentials
2167 gtls_errno = gtls_errno_stack0; // Don't pop, just forget last failures
2168 E_g2e ("Failed to allocate ANON-DH client credentials",
2169 gnutls_anon_allocate_client_credentials (
2171 #ifdef MIRROR_IMAGE_OF_SERVER_ANONYMOUS_CREDENTIALS
2172 // NOTE: This is not done under TLS; server always provides DH params
2173 if (!have_error_codes ()) gnutls_anon_set_client_dh_params (
2177 if (gtls_errno == GNUTLS_E_SUCCESS) {
2178 tlog (TLOG_CRYPTO, LOG_INFO, "Setting client anonymous credentials");
2179 cli_creds [cli_credcount].credtp = GNUTLS_CRD_ANON;
2180 cli_creds [cli_credcount].cred = (void *) cli_anoncred;
2182 } else if (cli_anoncred != NULL) {
2183 gnutls_anon_free_client_credentials (cli_anoncred);
2184 cli_anoncred = NULL;
2188 // Construct certificate credentials for X.509 and OpenPGP cli/srv
2189 gtls_errno = gtls_errno_stack0; // Don't pop, just forget last failures
2190 E_g2e ("Failed to allocate certificate credentials",
2191 gnutls_certificate_allocate_credentials (
2193 //TODO// What to do here when we add locking on DH params?
2194 gnutls_certificate_set_dh_params (
2197 gtls_errno_stack0 = gtls_errno;
2198 /* TODO: Bad code. GnuTLS 3.2.1 ignores retrieve_function2 when
2199 * checking if it can handle the OpenPGP certificate type in
2200 * _gnutls_session_cert_type_supported (gnutls_status.c:175) but
2201 * it does see the "1" version field. It does not callback the
2202 * "1" version if "2" is present though.
2204 if (!have_error_codes ()) /* TODO:GnuTLSversions E_g2e (...) */ gnutls_certificate_set_retrieve_function (
2207 if (!have_error_codes ()) /* TODO:GnuTLSversions E_g2e (...) */ gnutls_certificate_set_retrieve_function2 (
2209 clisrv_cert_retrieve);
2210 if (gtls_errno == GNUTLS_E_SUCCESS) {
2211 // Setup for certificates
2212 tlog (TLOG_CERT, LOG_INFO, "Setting client and server certificate credentials");
2213 cli_creds [cli_credcount].credtp = GNUTLS_CRD_CERTIFICATE;
2214 cli_creds [cli_credcount].cred = (void *) clisrv_certcred;
2216 srv_creds [srv_credcount].credtp = GNUTLS_CRD_CERTIFICATE;
2217 srv_creds [srv_credcount].cred = (void *) clisrv_certcred;
2219 } else if (clisrv_certcred != NULL) {
2220 gnutls_certificate_free_credentials (clisrv_certcred);
2221 clisrv_certcred = NULL;
2225 // Construct server credentials for SRP authentication
2226 gtls_errno = gtls_errno_stack0; // Don't pop, just forget last failures
2227 E_g2e ("Failed to allocate SRP server credentials",
2228 gnutls_srp_allocate_server_credentials (
2230 E_g2e ("Failed to set SRP server credentials",
2231 gnutls_srp_set_server_credentials_file (
2233 "../testdata/tlspool-test-srp.passwd",
2234 "../testdata/tlspool-test-srp.conf"));
2235 if (gtls_errno == GNUTLS_E_SUCCESS) {
2236 tlog (TLOG_CRYPTO, LOG_INFO, "Setting server SRP credentials");
2237 srv_creds [srv_credcount].credtp = GNUTLS_CRD_SRP;
2238 srv_creds [srv_credcount].cred = (void *) srv_srpcred;
2240 } else if (srv_srpcred != NULL) {
2241 gnutls_srp_free_server_credentials (srv_srpcred);
2246 // Construct client credentials for SRP authentication
2247 gtls_errno = gtls_errno_stack0; // Don't pop, just forget last failures
2248 E_g2e ("Failed to allocate SRP client credentials",
2249 gnutls_srp_allocate_client_credentials (
2251 if (!have_error_codes ()) gnutls_srp_set_client_credentials_function (
2253 cli_srpcreds_retrieve);
2254 if (gtls_errno == GNUTLS_E_SUCCESS) {
2255 tlog (TLOG_CRYPTO, LOG_INFO, "Setting client SRP credentials");
2256 cli_creds [cli_credcount].credtp = GNUTLS_CRD_SRP;
2257 cli_creds [cli_credcount].cred = (void *) cli_srpcred;
2259 } else if (cli_srpcred != NULL) {
2260 gnutls_srp_free_client_credentials (cli_srpcred);
2265 // Construct server credentials for KDH authentication
2266 //TODO// gtls_errno = gtls_errno_stack0; // Don't pop, just forget last failures
2267 //TODO// E_g2e ("Failed to allocate KDH server credentials",
2268 //TODO// gnutls_kdh_allocate_server_credentials (
2269 //TODO// &srv_kdhcred));
2270 //TODO// E_g2e ("Failed to set KDH server DH params",
2271 //TODO// gnutls_kdh_set_server_dh_params (
2272 //TODO// srv_kdhcred,
2273 //TODO// dh_params));
2274 //TODO// if (gtls_errno == GNUTLS_E_SUCCESS) {
2275 //TODO// tlog (TLOG_CRYPTO, LOG_INFO, "Setting server KDH credentials");
2276 //TODO// srv_creds [srv_credcount].credtp = GNUTLS_CRD_KDH;
2277 //TODO// srv_creds [srv_credcount].cred = (void *) srv_kdhcred;
2278 //TODO// srv_credcount++;
2279 //TODO// } else if (srv_kdhcred != NULL) {
2280 //TODO// gnutls_kdh_free_server_credentials (srv_kdhcred);
2281 //TODO// srv_kdhcred = NULL;
2285 // Construct client credentials for KDH
2286 //TODO// gtls_errno = gtls_errno_stack0; // Don't pop, just forget last failures
2287 //TODO// E_g2e ("Failed to allocate KDH client credentials",
2288 //TODO// gnutls_kdh_allocate_client_credentials (
2289 //TODO// &cli_kdhcred));
2290 //TODO// E_g2e ("Failed to set KDH client credentials",
2291 //TODO// gnutls_kdh_set_client_credentials_function (
2292 //TODO// cli_kdhcred,
2293 //TODO// cli_kdh_retrieve));
2294 //TODO// if (gtls_errno == GNUTLS_E_SUCCESS) {
2295 //TODO// tlog (TLOG_CRYPTO, LOG_INFO, "Setting client KDH credentials");
2296 //TODO// cli_creds [cli_credcount].credtp = GNUTLS_CRD_KDH;
2297 //TODO// cli_creds [cli_credcount].cred = (void *) cli_kdhcred;
2298 //TODO// cli_credcount++;
2299 //TODO// } else if (cli_kdhcred != NULL) {
2300 //TODO// gnutls_kdh_free_client_credentials (cli_kdhcred);
2301 //TODO// cli_kdhcred = NULL;
2305 // Ensure that at least one credential has been set
2306 // TODO: Look at the counters; but at boot, we can require all okay
2307 if ((gtls_errno == GNUTLS_E_SUCCESS) &&
2308 ( (cli_credcount != EXPECTED_CLI_CREDCOUNT) ||
2309 (srv_credcount != EXPECTED_SRV_CREDCOUNT) ) ) {
2310 tlog (TLOG_CRYPTO, LOG_ERR, "Not all credential types could be setup (cli %d/%d, srv %d/%d, gtls_errno %d)", cli_credcount, EXPECTED_CLI_CREDCOUNT, srv_credcount, EXPECTED_SRV_CREDCOUNT, gtls_errno);
2311 E_g2e ("Not all credentials could be setup",
2312 GNUTLS_E_INSUFFICIENT_CREDENTIALS);
2316 // Report overall error or success
2321 /* Cleanup all credentials created, just before exiting the daemon.
2323 void cleanup_starttls_credentials (void) {
2324 while (srv_credcount-- > 0) {
2325 struct credinfo *crd = &srv_creds [srv_credcount];
2326 switch (crd->credtp) {
2327 case GNUTLS_CRD_CERTIFICATE:
2328 // Shared with client; skipped in server and removed in client
2329 // gnutls_certificate_free_credentials (crd->cred);
2331 case GNUTLS_CRD_ANON:
2332 gnutls_anon_free_server_credentials (crd->cred);
2334 case GNUTLS_CRD_SRP:
2335 gnutls_srp_free_server_credentials (crd->cred);
2337 //TODO// case GNUTLS_CRD_KDH:
2338 //TODO// gnutls_kdh_free_server_credentials (crd->cred);
2342 while (cli_credcount-- > 0) {
2343 struct credinfo *crd = &cli_creds [cli_credcount];
2344 switch (crd->credtp) {
2345 case GNUTLS_CRD_CERTIFICATE:
2346 // Shared with client; skipped in server and removed in client
2347 gnutls_certificate_free_credentials (crd->cred);
2349 case GNUTLS_CRD_ANON:
2350 gnutls_anon_free_client_credentials (crd->cred);
2352 case GNUTLS_CRD_SRP:
2353 gnutls_srp_free_client_credentials (crd->cred);
2355 //TODO// case GNUTLS_CRD_KDH:
2356 //TODO// gnutls_kdh_free_client_credentials (crd->cred);
2364 * The starttls_thread is a main program for the setup of a TLS connection,
2365 * either in client mode or server mode. Note that the distinction between
2366 * client and server mode is only a TLS concern, but not of interest to the
2367 * application or the records exchanged.
2369 * If the STARTTLS operation succeeds, this will be reported back to the
2370 * application, but the TLS pool will continue to be active in a copycat
2371 * procedure: encrypting outgoing traffic and decrypting incoming traffic.
2373 * A new handshake may be initiated with a STARTTLS command with the special
2374 * flag PIOF_STARTTLS_RENEGOTIATE and the ctlkey set to a previously setup
2375 * TLS connection. This command runs in a new thread, that cancels the old
2376 * one (which it can only do while it is waiting in copycat) and then join
2377 * that thread (and its data) with the current one. This is based on the
2378 * ctlkey, which serves to lookup the old thread's data. When the
2379 * connection ends for other reasons than a permitted cancel by another
2380 * thread, will the thread cleanup its own resources. In these situations,
2381 * the new command determines the negotiation parameters, and returns identity
2384 * In addition, the remote side may initiate renegotiation. This is accepted
2385 * without further ado (although future versions of the TLS Pool may add a
2386 * callback mechanism to get it approved). The renegotiation now runs under
2387 * the originally supplied negotiation parameters. In case it needs a new
2388 * local identity, it may also perform callbacks. Possibly repeating what
2389 * happened before -- but most often, a server will start processing a
2390 * protocol and determine that it requires more for the requested level of
2391 * service, and then renegotiate. This is common, for example, with HTTPS
2392 * connections that decide they need a client certificate for certain URLs.
2393 * The implementation of this facility is currently as unstructured as the
2394 * facility itself, namely through a goto. We may come to the conclusion
2395 * that a loop is in fact a warranted alternative, but we're not yet
2396 * convinced that this would match with other "structures" in TLS.
2398 * In conclusion, there are three possible ways of running this code:
2399 * 1. For a new connection. Many variables are not known and build up
2400 * in the course of running the function.
2401 * 2. After a command requesting renegotiation. This overtakes the prior
2402 * connection's thread, and copies its data from the ctlkeynode_tls.
2403 * The resulting code has a number of variables filled in already at
2405 * 3. After a remote request for renegotiation. This loops back to an
2406 * earlier phase, but after the thread takeover and ctlkeynode_tls copy
2407 * of the explicit command for renegotation. Its behaviour is subtly
2408 * different in that it has no command to act on, and so it cannot
2409 * send responses or error codes. It will however log and shutdown
2410 * as the command-driven options would. It will not perform callbacks
2411 * for PIOC_STARTTLS_LOCALID_V2 or PIOC_PLAINTEXT_CONNECT_V2. It will
2412 * however trigger the PIOC_LIDENTRY_CALLBACK_V2 through the separate
2413 * callback command, if one is registered.
2414 * Yeah, it's great fun, coding TLS and keeping it both flexible and secure.
2416 static void *starttls_thread (void *cmd_void) {
2417 struct command *cmd, *replycmd;
2418 struct command cmd_copy; // for relooping during renegotiation
2419 struct pioc_starttls orig_starttls;
2420 uint32_t orig_cmdcode;
2423 gnutls_session_t session;
2424 int got_session = 0;
2425 int gtls_errno = GNUTLS_E_SUCCESS;
2427 struct ctlkeynode_tls *ckn = NULL;
2430 int want_remoteid = 1;
2431 int got_remoteid = 0;
2432 int renegotiating = 0;
2433 char *preauth = NULL;
2434 unsigned int preauthlen = 0;
2435 int taking_over = 0;
2436 int my_maxpreauth = 0;
2440 // Block thread cancellation -- and re-enable it in copycat()
2441 assert (pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, NULL) == 0);
2444 // General thread setup
2445 replycmd = cmd = (struct command *) cmd_void;
2447 send_error (replycmd, EINVAL, "Command structure not received");
2448 assert (pthread_detach (pthread_self ()) == 0);
2451 *cmd->valflags = '\0';
2452 cmd->session_errno = 0;
2454 orig_cmdcode = cmd->cmd.pio_cmd;
2455 memcpy (&orig_starttls, &cmd->cmd.pio_data.pioc_starttls, sizeof (orig_starttls));
2456 cmd->orig_starttls = &orig_starttls;
2457 cryptfd = cmd->passfd;
2459 //TODO:TEST Removed here because it is tested below
2462 tlog (TLOG_UNIXSOCK, LOG_ERR, "No ciphertext file descriptor supplied to TLS Pool");
2463 send_error (replycmd, EINVAL, "No ciphertext file descriptor supplied to TLS Pool");
2464 assert (pthread_detach (pthread_self ()) == 0);
2468 cmd->session_certificate = (intptr_t) (void *) NULL;
2469 cmd->session_privatekey = (intptr_t) (void *) NULL;
2472 // In case of renegotiation, lookup the previous ctlkeynode by its
2473 // ctlkey. The fact that we have ckn != NULL indicates that we are
2474 // renegotiating in the code below; it will supply information as
2475 // we continue to run the TLS process.
2476 if (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_RENEGOTIATE) {
2477 fprintf (stderr, "DEBUG: Got a request to renegotiate existing TLS connection\n");
2479 // Check that no FD was passed (and ended up in cryptfd)
2481 tlog (TLOG_UNIXSOCK, LOG_ERR, "Renegotiation started with extraneous file descriptor");
2482 send_error (replycmd, EPROTO, "File handle supplied for renegotiation");
2484 assert (pthread_detach (pthread_self ()) == 0);
2488 // First find the ctlkeynode_tls
2489 ckn = (struct ctlkeynode_tls *) ctlkey_find (cmd->cmd.pio_data.pioc_starttls.ctlkey, security_tls, cmd->clientfd);
2490 fprintf (stderr, "DEBUG: Got ckn == 0x%0x\n", (intptr_t) ckn);
2492 tlog (TLOG_UNIXSOCK, LOG_ERR, "Failed to find TLS connection for renegotiation by its ctlkey");
2493 send_error (replycmd, ESRCH, "Cannot find TLS connection for renegotiation");
2494 assert (pthread_detach (pthread_self ()) == 0);
2498 // Now cancel the pthread for this process
2499 errno = pthread_cancel (ckn->owner);
2500 fprintf (stderr, "DEBUG: pthread_cancel returned %d\n", errno);
2503 errno = pthread_join (ckn->owner, &retval);
2504 fprintf (stderr, "DEBUG: pthread_join returned %d\n", errno);
2507 tlog (TLOG_UNIXSOCK, LOG_ERR, "Failed to interrupt TLS connection for renegotiation");
2508 send_error (replycmd, errno, "Cannot interrupt TLS connection for renegotiation");
2509 ctlkey_unfind (&ckn->regent);
2510 assert (pthread_detach (pthread_self ()) == 0);
2511 // Do not free the ckn, as the other thread still runs
2515 // We are in control! Assimilate the TLS connection data.
2517 plainfd = ckn->plainfd;
2518 cryptfd = ckn->cryptfd;
2519 session = ckn->session;
2522 ctlkey_unfind (&ckn->regent);
2525 // Then follows the unstructured entry point for the unstructured
2526 // request to a TLS connection to renegotiate its security parameters.
2527 // Doing this in any other way than with goto would add a lot of
2528 // make-belief structure that only existed to make this looping
2529 // possible. We'd rather be honest and admit the lack of structure
2530 // that TLS has in this respect. Maybe we'll capture it one giant loop
2531 // at some point, but for now that does not seem to add any relief.
2533 printf ("DEBUG: Renegotiating = %d, anonpost = %d, plainfd = %d, cryptfd = %d, flags = 0x%x, session = 0x%x, got_session = %d, lid = \"%s\", rid = \"%s\"\n", renegotiating, anonpost, plainfd, cryptfd, cmd->cmd.pio_data.pioc_starttls.flags, session, got_session, cmd->cmd.pio_data.pioc_starttls.localid, cmd->cmd.pio_data.pioc_starttls.remoteid);
2536 // If this is server renegotiating, send a request to that end
2537 //TODO// Only invoke gnutls_rehandshake() on the server
2538 if (renegotiating && (taking_over || anonpost) && (gtls_errno == GNUTLS_E_SUCCESS)) {
2539 printf ("DEBUG: Invoking gnutls_rehandshake in renegotiation loop\n");
2540 gtls_errno = gnutls_rehandshake (session);
2541 if (gtls_errno == GNUTLS_E_INVALID_REQUEST) {
2542 // Clients should not do this; be forgiving
2543 gtls_errno = GNUTLS_E_SUCCESS;
2544 printf ("DEBUG: Client-side invocation flagged as wrong; compensated error\n");
2549 // When renegotiating TLS security, ensure that it is done securely
2550 if (renegotiating && (gnutls_safe_renegotiation_status (session) == 0)) {
2551 send_error (replycmd, EPROTO, "Renegotiation requested while secure renegotiation is unavailable on remote");
2561 if (ctlkey_unregister (ckn->regent.ctlkey)) {
2566 assert (pthread_detach (pthread_self ()) == 0);
2571 // Potentially decouple the controlling fd (ctlkey is in orig_starttls)
2572 if (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_FORK) {
2573 cmd->cmd.pio_data.pioc_starttls.flags &= ~PIOF_STARTTLS_FORK;
2578 // Setup BDB transactions and reset credential datum fields
2580 bzero (&cmd->lids, sizeof (cmd->lids));
2581 manage_txn_begin (&cmd->txn);
2585 // Permit cancellation of this thread -- TODO: Cleanup?
2586 //TODO:TEST// Defer setcancelstate untill copycat() activity
2588 errno = pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, NULL);
2590 send_error (replycmd, ESRCH, "STARTTLS handler thread cancellability refused");
2600 if (ctlkey_unregister (ckn->regent.ctlkey)) {
2605 manage_txn_rollback (&cmd->txn);
2606 assert (pthread_detach (pthread_self ()) == 0);
2611 // Check and setup the plaintext file handle
2613 send_error (replycmd, EPROTO, "You must supply a TLS-protected socket");
2618 fprintf (stderr, "ctlkey_unregister under ckn=0x%x at %d\n", ckn, __LINE__);
2619 if (ckn != NULL) { /* TODO: CHECK NEEDED? */
2620 if (ctlkey_unregister (ckn->regent.ctlkey)) {
2625 manage_txn_rollback (&cmd->txn);
2626 assert (pthread_detach (pthread_self ()) == 0);
2631 // Decide on support for the Anonymous Precursor, based on the
2632 // service name and its appearance in the anonpre_registry.
2633 // If the remoteid is not interesting to the client then also
2634 // support an Anonymous Precursor; we have nothing to loose.
2635 cmd->anonpre &= ~ANONPRE_EITHER;
2636 if (renegotiating) {
2637 ; // Indeed, during renegotiation we always disable ANON-DH
2638 } else if (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_IGNORE_REMOTEID) {
2639 cmd->anonpre = ANONPRE_EITHER;
2642 int anonpre_regidx = anonpre_registry_size >> 1;
2643 int anonpre_regjmp = (anonpre_registry_size + 1) >> 1;
2645 while (anonpre_regjmp > 0) {
2646 anonpre_regjmp = anonpre_regjmp >> 1;
2647 cmp = strncasecmp (anonpre_registry [anonpre_regidx].service,
2648 cmd->cmd.pio_data.pioc_starttls.service,
2649 TLSPOOL_SERVICELEN);
2650 printf ("DEBUG: anonpre_determination, comparing [%d] %s to %s, found cmp==%d\n", anonpre_regidx, anonpre_registry [anonpre_regidx].service, cmd->cmd.pio_data.pioc_starttls.service, cmp);
2652 // anonpre_regent matches
2653 cmd->anonpre = anonpre_registry [anonpre_regidx].flags;
2655 } else if (cmp > 0) {
2656 // anonpre_regent too high
2657 anonpre_regidx -= 1 + anonpre_regjmp;
2658 if (anonpre_regidx < 0) {
2662 // anonpre_regent too low
2663 anonpre_regidx += 1 + anonpre_regjmp;
2664 if (anonpre_regidx >= anonpre_registry_size) {
2665 anonpre_regidx = anonpre_registry_size - 1;
2672 // Setup flags for client and/or server roles (make sure there is one)
2673 if ((!renegotiating) && ((cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_REMOTEROLE_CLIENT) == 0)) {
2674 cmd->cmd.pio_data.pioc_starttls.flags &= ~PIOF_STARTTLS_LOCALROLE_SERVER;
2676 if ((!renegotiating) && ((cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_REMOTEROLE_SERVER) == 0)) {
2677 cmd->cmd.pio_data.pioc_starttls.flags &= ~PIOF_STARTTLS_LOCALROLE_CLIENT;
2679 if ((cmd->cmd.pio_data.pioc_starttls.flags & (PIOF_STARTTLS_LOCALROLE_CLIENT | PIOF_STARTTLS_LOCALROLE_SERVER)) == 0) {
2681 // Neither a TLS client nor a TLS server
2683 send_error (replycmd, ENOTSUP, "Command not supported");
2689 fprintf (stderr, "ctlkey_unregister under ckn=0x%x at %d\n", ckn, __LINE__);
2690 if (ckn != NULL) { /* TODO: CHECK NEEDED? */
2691 if (ctlkey_unregister (ckn->regent.ctlkey)) {
2696 manage_txn_rollback (&cmd->txn);
2697 assert (pthread_detach (pthread_self ()) == 0);
2702 // Setup the TLS session. Also see doc/p2p-tls.*
2704 // TODO: GnuTLS cannot yet setup p2p connections
2706 gnutls_session_set_ptr (
2709 //TODO:DONE?// Clear various settings... creds, flags, modes? CLI/SRV?
2711 E_g2e ("Failed to initialise GnuTLS peer session",
2714 (((cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_CLIENT)? GNUTLS_CLIENT: 0) |
2715 ((cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_SERVER)? GNUTLS_SERVER: 0))
2717 if (gtls_errno == GNUTLS_E_SUCCESS) {
2719 gnutls_session_set_ptr (
2724 cmd->session = session;
2726 // Setup client-specific behaviour if needed
2727 if (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_CLIENT) {
2728 if (!renegotiating) { //TODO:TEST//
2730 // Setup as a TLS client
2734 // Require a minimum security level for SRP
2736 //TODO:CRASH// if (gtls_errno == GNUTLS_E_SUCCESS) gnutls_srp_set_prime_bits (
2737 //TODO:CRASH// session,
2738 //TODO:CRASH// srpbits);
2740 // Setup as a TLS client
2742 // Setup for potential sending of SNI
2743 if ((cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_WITHOUT_SNI) == 0) {
2744 char *str = cmd->cmd.pio_data.pioc_starttls.remoteid;
2747 while (str [len] && (len < 128)) {
2748 if (str [len] == '@') {
2753 // If no usable remoteid was setup, ignore it
2754 if ((len + ofs > 0) && (len < 128)) {
2755 cmd->cmd.pio_data.pioc_starttls.remoteid [sizeof (cmd->cmd.pio_data.pioc_starttls.remoteid)-1] = '\0';
2756 E_g2e ("Client failed to setup SNI",
2757 gnutls_server_name_set (
2766 // Setup for client credential installation in this session
2768 // Setup client-specific credentials and priority string
2769 printf ("DEBUG: Configuring client credentials\n");
2770 E_g2e ("Failed to configure GnuTLS as a client",
2771 configure_session (cmd,
2773 anonpost? NULL: cli_creds,
2774 anonpost? 0: cli_credcount,
2775 cmd->anonpre & ANONPRE_CLIENT));
2778 // Setup callback to server-specific behaviour if needed
2779 if (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_SERVER) {
2780 printf ("DEBUG: Configuring for server credentials callback if %d==0\n", gtls_errno);
2781 if (!renegotiating) { //TODO:TEST//
2782 if (gtls_errno == GNUTLS_E_SUCCESS) {
2783 gnutls_handshake_set_post_client_hello_function (
2788 //TODO:TEST// configure_session _if_ not setup as a client (too)
2790 // Setup for server credential installation in this session
2792 // Setup server-specific credentials and priority string
2794 if (! (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_CLIENT)) {
2795 printf ("DEBUG: Configuring server credentials (because it is not a client)\n");
2796 E_g2e ("Failed to configure GnuTLS as a server",
2797 configure_session (cmd,
2799 anonpost? NULL: srv_creds,
2800 anonpost? 0: srv_credcount,
2801 cmd->anonpre & ANONPRE_SERVER));
2807 // Prefetch local identities that might be used in this session
2809 E_g2e ("Failed to fetch local credentials",
2810 fetch_local_credentials (cmd));
2814 // Setup a temporary priority string so handshaking can start
2815 if ((cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_CLIENT) == 0) {
2816 E_g2e ("Failed to preconfigure server token priority string",
2817 gnutls_priority_set (
2823 // Check if past code stored an error code through POSIX
2824 if (cmd->session_errno) {
2825 gtls_errno = GNUTLS_E_USER_ERROR;
2829 // Setup a timeout value as specified in the command, where TLS Pool
2830 // defines 0 as default and ~0 as infinite (GnuTLS has 0 as infinite).
2831 tout = cmd->cmd.pio_data.pioc_starttls.timeout;
2832 if (renegotiating) {
2833 ; // Do not set timeout
2835 if (tout == TLSPOOL_TIMEOUT_DEFAULT) {
2836 gnutls_handshake_set_timeout (session, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
2837 } else if (tout == TLSPOOL_TIMEOUT_INFINITE) {
2838 gnutls_handshake_set_timeout (session, 0);
2840 gnutls_handshake_set_timeout (session, tout);
2844 // Now setup for the GnuTLS handshake
2846 if (renegotiating) {
2847 ; // Do not setup cryptfd
2849 if (gtls_errno == GNUTLS_E_SUCCESS) {
2850 gnutls_transport_set_int (session, cryptfd);
2852 if (gtls_errno != GNUTLS_E_SUCCESS) {
2853 tlog (TLOG_TLS, LOG_ERR, "Failed to prepare for TLS: %s", gnutls_strerror (gtls_errno));
2854 if (cmd->session_errno) {
2855 send_error (replycmd, cmd->session_errno, error_getstring ());
2857 send_error (replycmd, EIO, "Failed to prepare for TLS");
2860 fprintf (stderr, "gnutls_deinit (0x%x) at %d\n", session, __LINE__);
2861 gnutls_deinit (session);
2869 fprintf (stderr, "ctlkey_unregister under ckn=0x%x at %d\n", ckn, __LINE__);
2870 if (ckn != NULL) { /* TODO: CHECK NEEDED? */
2871 if (ctlkey_unregister (ckn->regent.ctlkey)) {
2876 manage_txn_rollback (&cmd->txn);
2877 assert (pthread_detach (pthread_self ()) == 0);
2880 tlog (TLOG_UNIXSOCK | TLOG_TLS, LOG_DEBUG, "TLS handshake started over %d", cryptfd);
2883 // Take a rehandshaking step forward.
2885 gtls_errno = gnutls_handshake (session);
2887 // When data is sent before completing
2888 // the rehandshake, then it's something
2889 // harmless, given the criteria for the
2890 // anonpre_registry. We pass it on and
2891 // don't worry about it. We do report
2894 // Note: Applications should be willing
2895 // to buffer or process such early data
2896 // before the handshake is over or else
2897 // the handshake will bail out in error.
2899 if (gtls_errno == GNUTLS_E_GOT_APPLICATION_DATA) {
2900 if (my_maxpreauth <= 0) {
2901 tlog (TLOG_COPYCAT, LOG_ERR, "Received unwanted early data before authentication is complete");
2902 break; // Terminate the handshake
2903 } else if (preauth == NULL) {
2904 preauth = malloc (my_maxpreauth);
2905 if (preauth == NULL) {
2906 gtls_errno = GNUTLS_E_MEMORY_ERROR;
2907 break; // Terminate the handshake
2911 if (gtls_errno == GNUTLS_E_GOT_APPLICATION_DATA) {
2912 if (preauthlen >= my_maxpreauth) {
2913 tlog (TLOG_COPYCAT, LOG_ERR, "Received more early data than willing to receive (%d bytes)", my_maxpreauth);
2914 break; // Terminate the handshake
2917 if (gtls_errno == GNUTLS_E_GOT_APPLICATION_DATA) {
2919 sz = gnutls_record_recv (session, preauth + preauthlen, my_maxpreauth - preauthlen);
2920 tlog (TLOG_COPYCAT, LOG_DEBUG, "Received %d remote bytes (or error if <0) from %d during anonymous precursor\n", (int) sz, cryptfd);
2923 gtls_errno = GNUTLS_E_SUCCESS;
2925 gtls_errno = sz; // It's actually an error code
2928 } while ((gtls_errno < 0) &&
2929 //DROPPED// (gtls_errno != GNUTLS_E_GOT_APPLICATION_DATA) &&
2930 //DROPPED// (gtls_errno != GNUTLS_E_WARNING_ALERT_RECEIVED) &&
2931 (gnutls_error_is_fatal (gtls_errno) == 0));
2932 if (gtls_errno == 0) {
2933 const gnutls_datum_t *certs;
2934 unsigned int num_certs;
2936 switch (gnutls_auth_get_type (session)) { // Peer's cred type
2937 case GNUTLS_CRD_CERTIFICATE:
2938 certs = gnutls_certificate_get_peers (session, &num_certs);
2939 if ((certs != NULL) && (num_certs >= 1)) {
2942 // "certs" points into GnuTLS' internal data structures
2943 E_g2e ("Failed to validate peer",
2944 gnutls_certificate_verify_peers2 (
2948 case GNUTLS_CRD_PSK:
2949 // Difficult... what did the history say about this?
2951 cmd->vfystatus = GNUTLS_CERT_SIGNER_NOT_FOUND;
2953 case GNUTLS_CRD_SRP:
2954 // Got a credential, validation follows later on
2955 //TODO// SRP does not really auth the server
2957 cmd->vfystatus = GNUTLS_CERT_SIGNER_NOT_FOUND;
2959 case GNUTLS_CRD_ANON:
2960 // Did not get a credential, perhaps due to anonpre
2962 cmd->vfystatus = GNUTLS_CERT_INVALID | GNUTLS_CERT_SIGNER_NOT_FOUND | GNUTLS_CERT_SIGNATURE_FAILURE;
2965 // Inner Application extension is no true credential
2966 // Should we compare the client-requested service?
2967 // Should we renegotiate into the ALPN protocol?
2969 cmd->vfystatus = GNUTLS_CERT_INVALID | GNUTLS_CERT_SIGNER_NOT_FOUND | GNUTLS_CERT_SIGNATURE_FAILURE;
2972 // Unknown creds cautiously considered unauthentitcated
2974 cmd->vfystatus = ~ (unsigned short) 0; // It's all bad
2978 // Now recognise and handle the Anonymous Precursor
2979 if (((cmd->anonpre & ANONPRE_EITHER) != 0)
2980 && want_remoteid && !got_remoteid) {
2981 assert (anonpost == 0);
2982 valexp_valflag_set (cmd, 'A');
2983 // Disable ANON-protocols but keep creds from before
2984 //TODO:ELSEWHERE// tlog (TLOG_TLS, LOG_DEBUG, "Reconfiguring TLS over %d without Anonymous Precursor\n", cryptfd);
2985 //TODO:ELSEWHERE// E_g2e ("Failed to reconfigure GnuTLS without anonymous precursor",
2986 //TODO:ELSEWHERE// configure_session (cmd,
2987 //TODO:ELSEWHERE// session,
2988 //TODO:ELSEWHERE// NULL, 0,
2989 //TODO:ELSEWHERE// 0));
2990 // We do not want to use ANON-DH if the flag
2991 // ANONPRE_EXTEND_MASTER_SECRET is set for the protocol
2992 // but the remote peer does not support it. Only if
2993 // this problem cannot possibly occur, permit
2994 // my_maxpreauth > 0 for early data acceptance.
2996 if (cmd->anonpre & ANONPRE_EXTEND_MASTER_SECRET) {
2997 #if GNUTLS_VERSION_NUMBER >= 0x030400
2998 gnutls_ext_priv_data_t ext;
2999 if (!gnutls_ext_get_data (session, 23, &ext)) {
3000 my_maxpreauth = maxpreauth;
3004 my_maxpreauth = maxpreauth;
3006 if (gtls_errno == 0) {
3007 tlog (TLOG_UNIXSOCK | TLOG_TLS, LOG_DEBUG, "TLS handshake continued over %d after anonymous precursor", cryptfd);
3008 renegotiating = 1; // (de)selects steps
3009 anonpost = 1; // (de)selects steps
3014 if ((gtls_errno == GNUTLS_E_SUCCESS) && cmd->session_errno) {
3015 gtls_errno = GNUTLS_E_USER_ERROR;
3020 // Cleanup any prefetched identities
3021 for (i=LID_TYPE_MIN; i<=LID_TYPE_MAX; i++) {
3022 if (cmd->lids [i - LID_TYPE_MIN].data != NULL) {
3023 free (cmd->lids [i - LID_TYPE_MIN].data);
3026 bzero (cmd->lids, sizeof (cmd->lids));
3029 /* This is not proper. gnutls_certificate_set_key() suggests that these are
3030 * automatically cleaned up, and although this is not repeated in
3031 * gnutls_certificate_set_retrieve_function2() it is likely to be related.
3032 * Plus, renegotiation with this code in place bogged down on failed pcerts;
3033 * they were detected in _gnutls_selected_cert_supported_kx() but their
3034 * key exchange algorithm was never found.
3036 if (NULL != (void *) cmd->session_privatekey) {
3037 gnutls_privkey_deinit ((void *) cmd->session_privatekey);
3038 cmd->session_privatekey = (intptr_t) (void *) NULL;
3040 if (NULL != (void *) cmd->session_certificate) {
3041 gnutls_pcert_deinit ((void *) cmd->session_certificate);
3042 free ((void *) cmd->session_certificate);
3043 cmd->session_certificate = (intptr_t) (void *) NULL;
3048 // From here, assume nothing about the cmd->cmd structure; as part of
3049 // the handshake, it may have passed through the client's control, as
3050 // part of a callback. So, reinitialise the entire return structure.
3051 //TODO// Or backup the (struct pioc_starttls) before handshaking
3052 cmd->cmd.pio_cmd = orig_cmdcode;
3053 cmd->cmd.pio_data.pioc_starttls.localid [0] =
3054 cmd->cmd.pio_data.pioc_starttls.remoteid [0] = 0;
3057 // Respond to positive or negative outcome of the handshake
3058 if (gtls_errno != GNUTLS_E_SUCCESS) {
3059 tlog (TLOG_TLS, LOG_ERR, "TLS handshake failed: %s", gnutls_strerror (gtls_errno));
3060 if (cmd->session_errno) {
3062 tlog (TLOG_TLS, LOG_ERR, "Underlying cause may be: %s", strerror (cmd->session_errno));
3063 errstr = error_getstring ();
3064 if (errstr == NULL) {
3065 errstr = "TLS handshake failed";
3067 send_error (replycmd, cmd->session_errno, errstr);
3069 send_error (replycmd, EPERM, "TLS handshake failed");
3075 fprintf (stderr, "gnutls_deinit (0x%x) at %d\n", session, __LINE__);
3076 gnutls_deinit (session);
3084 fprintf (stderr, "ctlkey_unregister under ckn=0x%x at %d\n", ckn, __LINE__);
3085 if (ckn != NULL) { /* TODO: CHECK NEEDED? */
3086 if (ctlkey_unregister (ckn->regent.ctlkey)) {
3091 manage_txn_rollback (&cmd->txn);
3092 assert (pthread_detach (pthread_self ()) == 0);
3095 tlog (TLOG_UNIXSOCK | TLOG_TLS, LOG_INFO, "TLS handshake succeeded over %d", cryptfd);
3096 //TODO// extract_authenticated_remote_identity (cmd);
3100 // Request the plaintext file descriptor with a callback
3102 uint32_t oldcmd = cmd->cmd.pio_cmd;
3103 struct command *resp;
3104 cmd->cmd.pio_cmd = PIOC_PLAINTEXT_CONNECT_V2;
3105 tlog (TLOG_UNIXSOCK, LOG_DEBUG, "Calling send_callback_and_await_response with PIOC_PLAINTEXT_CONNECT_V2");
3106 resp = send_callback_and_await_response (replycmd, 0);
3107 assert (resp != NULL); // No timeout, should be non-NULL
3108 if (resp->cmd.pio_cmd != PIOC_PLAINTEXT_CONNECT_V2) {
3109 tlog (TLOG_UNIXSOCK, LOG_ERR, "Callback response has unexpected command code");
3110 send_error (replycmd, EINVAL, "Callback response has bad command code");
3115 fprintf (stderr, "gnutls_deinit (0x%x) at %d\n", session, __LINE__);
3116 gnutls_deinit (session);
3120 fprintf (stderr, "ctlkey_unregister under ckn=0x%x at %d\n", ckn, __LINE__);
3121 if (ckn) { /* TODO: CHECK NEEDED? PRACTICE=>YES */
3122 if (ctlkey_unregister (ckn->regent.ctlkey)) {
3127 manage_txn_rollback (&cmd->txn);
3128 assert (pthread_detach (pthread_self ()) == 0);
3131 cmd->cmd.pio_cmd = oldcmd;
3132 tlog (TLOG_UNIXSOCK, LOG_DEBUG, "Processing callback response that set plainfd:=%d for lid==\"%s\" and rid==\"%s\"", cmd->passfd, cmd->cmd.pio_data.pioc_starttls.localid, cmd->cmd.pio_data.pioc_starttls.remoteid);
3133 plainfd = resp->passfd;
3137 tlog (TLOG_UNIXSOCK, LOG_ERR, "No plaintext file descriptor supplied to TLS Pool");
3138 send_error (replycmd, EINVAL, "No plaintext file descriptor supplied to TLS Pool");
3143 fprintf (stderr, "gnutls_deinit (0x%x) at %d\n", session, __LINE__);
3144 gnutls_deinit (session);
3148 fprintf (stderr, "ctlkey_unregister under ckn=0x%x at %d\n", ckn, __LINE__);
3149 if (ckn != NULL) { /* TODO: CHECK NEEDED? */
3150 if (ctlkey_unregister (ckn->regent.ctlkey)) {
3155 manage_txn_rollback (&cmd->txn);
3156 assert (pthread_detach (pthread_self ()) == 0);
3159 //DEFERRED// send_command (replycmd, -1); // app sent plainfd to us
3162 // Copy TLS records until the connection is closed
3163 manage_txn_commit (&cmd->txn);
3164 if (!renegotiating) {
3165 ckn = (struct ctlkeynode_tls *) malloc (sizeof (struct ctlkeynode_tls));
3168 send_error (replycmd, ENOMEM, "Out of memory allocating control key structure");
3170 int detach = (orig_starttls.flags & PIOF_STARTTLS_DETACH) != 0;
3171 ckn->session = session;
3172 ckn->owner = pthread_self ();
3173 ckn->cryptfd = cryptfd;
3174 ckn->plainfd = plainfd;
3175 //DEBUG// fprintf (stderr, "Registering control key\n");
3176 if (renegotiating || (ctlkey_register (orig_starttls.ctlkey, &ckn->regent, security_tls, detach? -1: cmd->clientfd, forked) == 0)) {
3177 int copied = GNUTLS_E_SUCCESS;
3178 send_command (replycmd, -1); // app sent plainfd to us
3182 // Check on extended master secret if desired
3183 if (cmd->anonpre & ANONPRE_EXTEND_MASTER_SECRET) {
3184 #if GNUTLS_VERSION_NUMBER >= 0x030400
3185 gnutls_ext_priv_data_t ext;
3186 if (!gnutls_ext_get_data (session, 23, &ext)) {
3187 cmd->anonpre &= ~ANONPRE_EXTEND_MASTER_SECRET;
3191 if (cmd->anonpre & ANONPRE_EXTEND_MASTER_SECRET) {
3192 tlog (TLOG_COPYCAT, LOG_ERR, "Received %d remote bytes from anonymous precursor but lacking %s-required authentication through extended master secret", orig_starttls.service);
3193 gtls_errno = GNUTLS_E_LARGE_PACKET;
3196 } else if (write (plainfd, preauth, preauthlen) == preauthlen) {
3197 tlog (TLOG_COPYCAT, LOG_DEBUG, "Passed on %d remote bytes from anonymous precursor to %d\n", preauthlen, plainfd);
3200 copied = copycat (plainfd, cryptfd, session, detach? -1: cmd->clientfd);
3202 tlog (TLOG_COPYCAT, LOG_DEBUG, "Failed to pass on %d remote bytes from anonymous precursor to %d\n", preauthlen, plainfd);
3205 copied = copycat (plainfd, cryptfd, session, detach? -1: cmd->clientfd);
3207 // Renegotiate if copycat asked us to
3208 if (copied == GNUTLS_E_REHANDSHAKE) {
3209 // Yes, goto is a dirty technique. On the
3210 // other hand, so is forcing unstructured
3211 // code flows into a make-belief structure
3212 // that needs changing over and over again.
3213 // I fear goto is the most reasonable way
3214 // of handling this rather obtuse structure
3215 // of renegotiation of security in TLS :(
3216 //TODO// Ensure secure renegotiation!!!
3218 replycmd = NULL; // Bypass all send_XXX()
3219 memcpy (&cmd_copy, cmd, sizeof (cmd_copy));
3221 memcpy (cmd->cmd.pio_data.pioc_starttls.localid, orig_starttls.localid, sizeof (cmd->cmd.pio_data.pioc_starttls.localid));
3222 memcpy (cmd->cmd.pio_data.pioc_starttls.remoteid, orig_starttls.remoteid, sizeof (cmd->cmd.pio_data.pioc_starttls.remoteid));
3223 cmd->cmd.pio_data.pioc_starttls.flags = orig_starttls.flags & ~PIOF_STARTTLS_LOCALID_CHECK;
3224 // Disabling the flag causing LOCALID_CHECK
3225 // ...and plainfd >= 0 so no PLAINTEXT_CONNECT
3226 // ...so there will be no callbacks to cmd
3227 printf ("DEBUG: Goto renegotiate with cmd.lid = \"%s\" and orig_cmd.lid = \"%s\" and cmd.rid = \"%s\" and orig_cmd.rid = \"%s\" and cmd.flags = 0x%x and orig_cmd.flags = 0x%x\n", cmd->cmd.pio_data.pioc_starttls.localid, orig_starttls.localid, cmd->cmd.pio_data.pioc_starttls.remoteid, orig_starttls.remoteid, cmd->cmd.pio_data.pioc_starttls.flags, orig_starttls.flags);
3230 //DEBUG// fprintf (stderr, "Unregistering control key\n");
3231 // Unregister by ctlkey, which should always succeed
3232 // if the TLS connection hadn't been closed down yet;
3233 // and if it does, the memory can be freed. Note that
3234 // the ctlkey is not taken from the ckn, which may
3235 // already have been freed if the ctlfd was closed
3236 // and the connection could not continue detached
3237 // (such as after forking it).
3238 fprintf (stderr, "ctlkey_unregister under ckn=0x%x at %d\n", ckn, __LINE__);
3239 if (ctlkey_unregister (orig_starttls.ctlkey)) {
3243 //DEBUG// fprintf (stderr, "Unregistered control key\n");
3245 send_error (replycmd, ENOENT, "Failed to register control key for TLS connection");
3255 fprintf (stderr, "gnutls_deinit (0x%x) at %d\n", session, __LINE__);
3256 gnutls_deinit (session);
3259 assert (pthread_detach (pthread_self ()) == 0);
3265 * The starttls function responds to an application's request to
3266 * setup TLS for a given file descriptor, and return a file descriptor
3267 * with the unencrypted view when done. The main thing done here is to
3268 * spark off a new thread that handles the operations.
3270 void starttls (struct command *cmd) {
3271 /* Create a thread and, if successful, wait for it to unlock cmd */
3272 errno = pthread_create (&cmd->handler, NULL, starttls_thread, (void *) cmd);
3274 send_error (cmd, ESRCH, "STARTTLS thread refused");
3277 //TODO:TEST// Thread detaches itself before terminating w/o followup
3279 errno = pthread_detach (cmd->handler);
3281 pthread_cancel (cmd->handler);
3282 send_error (cmd, ESRCH, "STARTTLS thread detachment refused");
3290 * Run the PRNG for a TLS connection, identified by its control key. If the connection
3291 * is not a TLS connection, or if the control key is not found, reply with ERROR;
3292 * otherwise, the session should help to create pseudo-random bytes.
3294 void starttls_prng (struct command *cmd) {
3295 uint8_t in1 [TLSPOOL_PRNGBUFLEN];
3296 uint8_t in2 [TLSPOOL_PRNGBUFLEN];
3297 int16_t in1len, in2len, prnglen;
3298 struct ctlkeynode_tls *ckn = NULL;
3301 int gtls_errno = GNUTLS_E_SUCCESS;
3302 struct pioc_prng *prng = &cmd->cmd.pio_data.pioc_prng;
3304 // Find arguments and validate them
3305 in1len = prng->in1_len;
3306 in2len = prng->in2_len;
3307 prnglen = prng->prng_len;
3308 err = err || (in1len <= 0);
3309 err = err || (prnglen > TLSPOOL_PRNGBUFLEN);
3310 err = err || ((TLSPOOL_CTLKEYLEN + in1len + (in2len >= 0? in2len: 0))
3311 > TLSPOOL_PRNGBUFLEN);
3313 memcpy (in1, prng->buffer + TLSPOOL_CTLKEYLEN , in1len);
3315 memcpy (in2, prng->buffer + TLSPOOL_CTLKEYLEN + in1len, in2len);
3318 // - check the label string
3319 prefixes = tlsprng_label_prefixes;
3320 while ((!err) && (*prefixes)) {
3321 char *pf = *prefixes++;
3322 if (strlen (pf) != in1len) {
3325 if (strcmp (pf, in1) != 0) {
3329 if (*prefixes == NULL) {
3330 // RFC 5705 defines a private-use prefix "EXPERIMENTAL"
3331 if ((in1len <= 12) || (strncmp (in1, "EXPERIMENTAL", 12) != 0)) {
3335 // - check the ctlkey (and ensure it is for TLS)
3337 //DEBUG// fprintf (stderr, "Hoping to find control key\n");
3338 ckn = (struct ctlkeynode_tls *) ctlkey_find (prng->buffer, security_tls, cmd->clientfd);
3341 // Now wipe the PRNG buffer to get rid of any sensitive bytes
3342 memset (prng->buffer, 0, TLSPOOL_PRNGBUFLEN);
3344 // If an error occurrend with the command, report it now
3346 send_error (cmd, EINVAL, "TLS PRNG request invalid");
3347 // ckn is NULL if err != 0, so no need for ctlkey_unfind()
3351 send_error (cmd, ENOENT, "Invalid control key");
3355 // Now actually invoke the PRNG command in the GnuTLS backend
3357 E_g2e ("GnuTLS PRNG based on session master key failed",
3358 gnutls_prf_rfc5705 (ckn->session,
3360 (in2len >= 0)? in2len: 0, (in2len >= 0) ? in2: NULL,
3361 prnglen, prng->buffer));
3362 err = err || (errno != 0);
3364 // Wipe temporary data / buffers for security reasons
3365 memset (in1, 0, sizeof (in1));
3366 memset (in2, 0, sizeof (in2));
3367 ctlkey_unfind ((struct ctlkeynode *) ckn);
3369 // Return the outcome to the user
3371 send_error (cmd, errno? errno: EIO, "PRNG in TLS backend failed");
3373 send_command (cmd, -1);
3378 /* Flying signer functionality. Create an on-the-fly certificate because
3379 * the lidentry daemon and/or application asks for this to represent the
3380 * local identity. Note that this will only work if the remote party
3381 * accepts the root identity under which on-the-signing is done.
3383 * When no root credentials have been configured, this function will
3384 * fail with GNUTLS_E_AGAIN; it may be used as a hint to try through
3385 * other (more conventional) means to obtain a client certificate.
3387 * The API of this function matches that of fetch_local_credentials()
3388 * and that is not a coincidence; this is a drop-in replacement in some
3391 * Limitations: The current implementation only supports X.509 certificates
3392 * to be generated on the fly. So, this will set LID_TYPE_X509, if anything.
3394 gtls_error certificate_onthefly (struct command *cmd) {
3395 gtls_error gtls_errno = GNUTLS_E_SUCCESS;
3396 gnutls_x509_crt_t otfcert;
3398 gnutls_x509_subject_alt_name_t altnmtp;
3403 if ((onthefly_issuercrt == NULL) || (onthefly_issuerkey == NULL) || (onthefly_subjectkey == NULL)) {
3404 // Not able to supply on-the-fly certificates; try someway else
3405 return GNUTLS_E_AGAIN;
3407 if (cmd->cmd.pio_data.pioc_starttls.localid [0] == '\0') {
3408 return GNUTLS_E_NO_CERTIFICATE_FOUND;
3410 if (cmd->lids [LID_TYPE_X509 - LID_TYPE_MIN].data != NULL) {
3411 free (cmd->lids [LID_TYPE_X509 - LID_TYPE_MIN].data);
3412 cmd->lids [LID_TYPE_X509 - LID_TYPE_MIN].data = NULL;
3413 cmd->lids [LID_TYPE_X509 - LID_TYPE_MIN].size = 0;
3417 // Create an empty certificate
3418 E_g2e ("Failed to initialise on-the-fly certificate",
3419 gnutls_x509_crt_init (&otfcert));
3420 if (gtls_errno != GNUTLS_E_SUCCESS) {
3425 // Fill the certificate with the usual field
3426 E_g2e ("Failed to set on-the-fly certificate to non-CA mode",
3427 gnutls_x509_crt_set_ca_status (otfcert, 0));
3428 E_g2e ("Failed to set on-the-fly certificate version",
3429 gnutls_x509_crt_set_version (otfcert, 3));
3430 onthefly_serial++; //TODO// Consider a random byte string
3431 E_g2e ("Failed to set on-the-fly serial number",
3432 gnutls_x509_crt_set_serial (otfcert, &onthefly_serial, sizeof (onthefly_serial)));
3433 // Skip gnutls_x509_crt_set_issuer_by_dn_by_oid(), added when signing
3435 E_g2e ("Failed to set on-the-fly activation time to now - 2 min",
3436 gnutls_x509_crt_set_activation_time (otfcert, now - 120));
3437 E_g2e ("Failed to set on-the-fly expiration time to now + 3 min",
3438 gnutls_x509_crt_set_expiration_time (otfcert, now + 180));
3439 E_g2e ("Setup certificate CN with local identity",
3440 gnutls_x509_crt_set_dn_by_oid (otfcert, GNUTLS_OID_X520_COMMON_NAME, 0, cmd->cmd.pio_data.pioc_starttls.localid, strnlen (cmd->cmd.pio_data.pioc_starttls.localid, sizeof (cmd->cmd.pio_data.pioc_starttls.localid)-1))); /* TODO: Consider pioc_lidentry as well? */
3441 E_g2e ("Setup certificate OU with TLS Pool on-the-fly",
3442 gnutls_x509_crt_set_dn_by_oid (otfcert, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME, 0, "TLS Pool on-the-fly", 19));
3443 if (strchr (cmd->cmd.pio_data.pioc_starttls.localid, '@')) {
3444 // localid has the format of an emailAddress
3445 altnmtp = GNUTLS_SAN_RFC822NAME;
3447 // localid has the format of a dnsName
3448 altnmtp = GNUTLS_SAN_DNSNAME;
3450 E_g2e ("Failed to set subjectAltName to localid",
3451 gnutls_x509_crt_set_subject_alt_name (otfcert, altnmtp, &cmd->cmd.pio_data.pioc_starttls.localid, strnlen (cmd->cmd.pio_data.pioc_starttls.localid, sizeof (cmd->cmd.pio_data.pioc_starttls.localid) - 1), GNUTLS_FSAN_APPEND));
3452 //TODO:SKIP, hoping that signing adds: gnutls_x509_crt_set_authority_key_id()
3453 //TODO:SKIP, hoping that a cert without also works: gnutls_x509_crt_set_subjectkey_id()
3454 //TODO:SKIP? gnutls_x509_crt_set_extension_by_oid
3455 //TODO: gnutls_x509_crt_set_key_usage
3456 //TODO:SKIP? gnutls_x509_crt_set_ca_status
3457 for (i=0; i < svcusage_registry_size; i++) {
3458 if (strcmp (svcusage_registry [i].service, cmd->cmd.pio_data.pioc_starttls.service) == 0) {
3459 const char **walker;
3460 E_g2e ("Failed to setup basic key usage during on-the-fly certificate creation",
3461 gnutls_x509_crt_set_key_usage (otfcert, svcusage_registry [i].usage));
3462 walker = svcusage_registry [i].oids_non_critical;
3465 E_g2e ("Failed to append non-critical extended key purpose during on-the-fly certificate creation",
3466 gnutls_x509_crt_set_key_purpose_oid (otfcert, *walker, 0));
3470 walker = svcusage_registry [i].oids_critical;
3473 E_g2e ("Failed to append critical extended key purpose during on-the-fly certificate creation",
3474 gnutls_x509_crt_set_key_purpose_oid (otfcert, *walker, 1));
3481 E_g2e ("Failed to et the on-the-fly subject key",
3482 gnutls_x509_crt_set_key (otfcert, onthefly_subjectkey));
3483 /* TODO: The lock below should not be necessary; it is handled by p11-kit
3484 * or at least it ought to be. What I found however, was that
3485 * a client and server would try to use the onthefly_issuerkey
3486 * at virtually the same time, and then the second call to
3487 * C_SignInit returns CKR_OPERATION_ACTIVE. The lock solved this.
3488 * This makes me frown about server keys stored in PKCS #11...
3490 {gnutls_datum_t data = { 0, 0}; if (gnutls_x509_crt_print (otfcert, GNUTLS_CRT_PRINT_UNSIGNED_FULL, &data) == 0) { fprintf (stderr, "DEBUG: PRESIGCERT: %s\n", data.data); gnutls_free (data.data); } else {fprintf (stderr, "DEBUG: PRESIGCERT failed to print\n"); } }
3491 assert (pthread_mutex_lock (&onthefly_signer_lock) == 0);
3492 E_g2e ("Failed to sign on-the-fly certificate",
3493 gnutls_x509_crt_privkey_sign (otfcert, onthefly_issuercrt, onthefly_issuerkey, GNUTLS_DIG_SHA256, 0));
3494 pthread_mutex_unlock (&onthefly_signer_lock);
3497 // Construct cmd->lids [LID_TYPE_X509 - LID_TYPE_MIN].data+size for this certificate
3498 cmd->lids [LID_TYPE_X509 - LID_TYPE_MIN].size = 0;
3499 if (gtls_errno == GNUTLS_E_SUCCESS) {
3500 gtls_errno = gnutls_x509_crt_export (otfcert, GNUTLS_X509_FMT_DER, NULL, &cmd->lids [LID_TYPE_X509 - LID_TYPE_MIN].size);
3501 if (gtls_errno == GNUTLS_E_SHORT_MEMORY_BUFFER) {
3502 // This is as expected, now .size will have been set
3503 gtls_errno = GNUTLS_E_SUCCESS;
3505 if (gtls_errno = GNUTLS_E_SUCCESS) {
3506 // Something must be wrong if we receive OK
3507 gtls_errno = GNUTLS_E_INVALID_REQUEST;
3510 E_g2e ("Error while measuring on-the-fly certificate size",
3513 uint8_t *ptr = NULL;
3514 if (gtls_errno == GNUTLS_E_SUCCESS) {
3515 cmd->lids [LID_TYPE_X509 - LID_TYPE_MIN].size += 4 + strlen (onthefly_p11uri) + 1;
3516 ptr = malloc (cmd->lids [LID_TYPE_X509 - LID_TYPE_MIN].size);
3518 cmd->lids [LID_TYPE_X509 - LID_TYPE_MIN].size = 0;
3519 gnutls_x509_crt_deinit (otfcert);
3520 return GNUTLS_E_MEMORY_ERROR;
3525 cmd->lids [LID_TYPE_X509 - LID_TYPE_MIN].data = ptr;
3526 * (uint32_t *) ptr = htonl (LID_TYPE_X509 | LID_ROLE_BOTH);
3528 strcpy (ptr, onthefly_p11uri);
3529 ptr += strlen (onthefly_p11uri) + 1;
3530 restsz = cmd->lids [LID_TYPE_X509 - LID_TYPE_MIN].size - 4 - strlen (onthefly_p11uri) - 1;
3531 E_g2e ("Failed to export on-the-fly certificate as a credential",
3532 gnutls_x509_crt_export (otfcert, GNUTLS_X509_FMT_DER, ptr, &restsz));
3533 char *pembuf [10000];
3534 size_t pemlen = sizeof (pembuf) - 1;
3535 int exporterror = gnutls_x509_crt_export (otfcert, GNUTLS_X509_FMT_PEM, pembuf, &pemlen);
3536 if (exporterror == 0) {
3537 pembuf [pemlen] = '\0';
3538 fprintf (stderr, "DEBUG: otfcert ::=\n%s\n", pembuf);
3540 fprintf (stderr, "DEBUG: otfcert export to PEM failed with %d, gtls_errno already was %d\n", exporterror, gtls_errno);
3545 // Cleanup the allocated and built structures
3546 gnutls_x509_crt_deinit (otfcert);
3549 // Return the overall result that might have stopped otf halfway