Initial use of proposed GUI for TLS-KDH
[tlspool] / src / starttls.c
1 /* tlspool/starttls.c -- Setup and validation handler for TLS session */
2
3
4 #include <stdlib.h>
5 #include <stdint.h>
6 #include <stdio.h>
7 #include <memory.h>
8 #include <string.h>
9 #include <pthread.h>
10 #include <assert.h>
11
12 #include <unistd.h>
13 #include <syslog.h>
14 #include <errno.h>
15 #include <poll.h>
16
17 #include <sys/types.h>
18 #include <sys/socket.h>
19
20 #include <arpa/inet.h>
21 #include <netinet/in.h>
22
23 #include <gnutls/gnutls.h>
24 #include <gnutls/pkcs11.h>
25 #include <gnutls/abstract.h>
26 #include <gnutls/dane.h>
27
28 #include <libtasn1.h>
29
30 #include <tlspool/internal.h>
31
32
33 #include "manage.h"
34 #include "donai.h"
35
36
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"
39 #endif
40
41
42 /* This module hosts TLS handlers which treat an individual connection.
43  *
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.
47  *
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.
52  *
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.
59  *
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.
67  *
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.
73  */
74
75
76
77 /*
78  * GnuTLS infrastructure setup.
79  * Session-shared DH-keys, credentials structures, and so on.
80  */
81 static gnutls_dh_params_t dh_params;
82
83 struct credinfo {
84         gnutls_credentials_type_t credtp;
85         void *cred;
86 };
87
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;
100
101 /* The local variation on the ctlkeynode structure, with TLS-specific fields
102  */
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
109 };
110
111 /* The list of accepted Exporter Label Prefixes for starttls_prng()
112  */
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",
125         "TLS_MK_Extr",
126         "EXPORTER_GBA_Digest",
127         "EXPORTER: teap session key seed",      // not suited for DTLS
128         "EXPORTER-oneM2M-Bootstrap",
129         "EXPORTER-oneM2M-Connection",
130         NULL
131 };
132
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.
137  *
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".
141  *
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.
152  *
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.
157  */
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 {
164         char *service;
165         uint8_t flags;
166 };
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
172  *
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 },
177 #else
178         { "imap", ANONPRE_EITHER | ANONPRE_EXTEND_MASTER_SECRET },
179 #endif
180         { "pop3", ANONPRE_EITHER },
181         { "smtp", ANONPRE_EITHER },
182  *
183  * End of commenting out the registry
184  */
185 };
186 const int anonpre_registry_size = sizeof (anonpre_registry) / sizeof (struct anonpre_regentry);
187
188
189 /* The registry of Key Usage and Extended Key Usage for any given service name.
190  */
191 static const char *http_noncrit [] = { GNUTLS_KP_TLS_WWW_SERVER, GNUTLS_KP_TLS_WWW_CLIENT, NULL };
192 struct svcusage_regentry {
193         char *service;
194         unsigned int usage;
195         const char **oids_non_critical;
196         const char **oids_critical;
197 };
198 struct svcusage_regentry svcusage_registry [] = {
199         { "generic_anonpre",
200                 GNUTLS_KEY_KEY_ENCIPHERMENT |
201                 GNUTLS_KEY_KEY_AGREEMENT,
202                 NULL,
203                 NULL
204         },
205         { "http",
206                 GNUTLS_KEY_DIGITAL_SIGNATURE |
207                 GNUTLS_KEY_KEY_ENCIPHERMENT |
208                 GNUTLS_KEY_KEY_AGREEMENT,
209                 http_noncrit,
210                 NULL
211         },
212 };
213 const int svcusage_registry_size = sizeof (svcusage_registry) / sizeof (struct svcusage_regentry);
214
215
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.
219  */
220 int maxpreauth;
221
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.
225  */
226 gnutls_priority_t priority_normal;
227
228
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); \
238                 } \
239         } \
240 }
241
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) { \
245                 errno = 0; \
246         } \
247 }
248
249 /* Error number translation, including error string setup.  See E_g2e(). */
250 void error_gnutls2posix (int gtls_errno, char *new_errstr) {
251         char *errstr;
252         register int newerrno;
253         //
254         // Sanity checks
255         if (gtls_errno == GNUTLS_E_SUCCESS) {
256                 return;
257         }
258         errstr =  error_getstring ();
259         if (errstr != NULL) {
260                 return;
261         }
262         //
263         // Report the textual error
264         if (new_errstr == NULL) {
265                 new_errstr = "GnuTLS error";
266         }
267         tlog (TLOG_TLS, LOG_ERR, "%s: %s",
268                 new_errstr,
269                 gnutls_strerror (gtls_errno));
270         error_setstring (new_errstr);
271         //
272         // Translate error to a POSIX errno value
273         switch (gtls_errno) {
274         case GNUTLS_E_SUCCESS:
275                 return;
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:
307 #endif
308                 newerrno = EOPNOTSUPP;
309                 break;
310         case GNUTLS_E_UNEXPECTED_PACKET_LENGTH:
311         case GNUTLS_E_INVALID_REQUEST:
312                 newerrno = EINVAL;
313                 break;
314         case GNUTLS_E_INVALID_SESSION:
315         case GNUTLS_E_REHANDSHAKE:
316         case GNUTLS_E_CERTIFICATE_KEY_MISMATCH:
317                 newerrno = ENOTCONN;
318                 break;
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;
324                 break;
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:
373 #endif
374 #ifdef GNUTLS_E_SELF_TEST_ERROR
375         case GNUTLS_E_SELF_TEST_ERROR:
376 #endif
377 #ifdef GNUTLS_E_SOCKETS_INIT_ERROR
378         case GNUTLS_E_SOCKETS_INIT_ERROR:
379 #endif
380                 newerrno = EIO;
381                 break;
382         case GNUTLS_E_MEMORY_ERROR:
383         case GNUTLS_E_SHORT_MEMORY_BUFFER:
384                 newerrno = ENOMEM;
385                 break;
386         case GNUTLS_E_AGAIN:
387                 newerrno = EAGAIN;
388                 break;
389         case GNUTLS_E_EXPIRED:
390         case GNUTLS_E_TIMEDOUT:
391                 newerrno = ETIMEDOUT;
392                 break;
393         case GNUTLS_E_DB_ERROR:
394 #ifdef ENODATA
395                 newerrno = ENODATA;
396 #else
397                 newerrno = ENOENT;
398 #endif
399                 break;
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:
419                 newerrno = EACCES;
420                 break;
421         case GNUTLS_E_INTERRUPTED:
422                 newerrno = EINTR;
423                 break;
424         case GNUTLS_E_INTERNAL_ERROR:
425         case GNUTLS_E_CONSTRAINT_ERROR:
426         case GNUTLS_E_ILLEGAL_PARAMETER:
427                 newerrno = EINVAL;
428                 break;
429         case GNUTLS_E_SAFE_RENEGOTIATION_FAILED:
430                 newerrno = ECONNREFUSED;
431                 break;
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:
436 #endif
437                 newerrno = ENOEXEC;
438                 break;
439         case GNUTLS_E_RANDOM_FAILED:
440                 newerrno = EBADF;
441                 break;
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:
472 #ifdef EREMOTEIO
473                 newerrno = EREMOTEIO;
474 #else
475                 newerrno = EIO;
476 #endif
477                 break;
478         default:
479                 newerrno = EIO;
480                 break;
481         }
482         errno = newerrno;
483         return;
484 }
485
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.
490  */
491 static gtls_error generate_dh_params (void) {
492         unsigned int bits;
493         int gtls_errno = GNUTLS_E_SUCCESS;
494         bits = gnutls_sec_param_to_pk_bits (
495                 GNUTLS_PK_DH,
496                 GNUTLS_SEC_PARAM_LEGACY);
497         //TODO// Acquire DH-params lock
498         E_g2e ("Failed to initialise DH params",
499                 gnutls_dh_params_init (
500                         &dh_params));
501         E_g2e ("Failed to generate DH params",
502                 gnutls_dh_params_generate2 (
503                         dh_params,
504                         bits));
505         //TODO// Release DH-params lock
506         return gtls_errno;
507 }
508
509 /* Load Diffie-Hellman parameters from file - or generate them when load fails.
510  */
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));
517         if (filename) {
518                 E_g2e ("No PKCS #3 PEM file with DH params",
519                         gnutls_load_file (
520                                 filename,
521                                 &pkcs3));
522                 E_gnutls_clear_errno ();
523                 E_g2e ("Failed to initialise DH params",
524                         gnutls_dh_params_init (
525                                 &dhp));
526                 E_g2e ("Failed to import DH params from PKCS #3 PEM",
527                         gnutls_dh_params_import_pkcs3 (
528                                 dhp,
529                                 &pkcs3,
530                                 GNUTLS_X509_FMT_PEM));
531                 E_gnutls_clear_errno ();
532         }
533         if (pkcs3.data != NULL) {
534                 free (pkcs3.data);
535         }
536         if (gtls_errno != GNUTLS_E_SUCCESS) {
537                 //
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 (
548                                 dh_params,
549                                 GNUTLS_X509_FMT_PEM,
550                                 &pkcs3));
551                 //TODO// Release DH-params lock
552                 if ((gtls_errno == GNUTLS_E_SUCCESS) && (filename != NULL)) {
553                         FILE *pemf;
554                         //
555                         // Best effor file save -- readback will parse
556                         pemf = fopen (filename, "w");
557                         if (pemf != NULL) {
558                                 fwrite (pkcs3.data, 1, pkcs3.size, pemf);
559                                 fclose (pemf);
560                                 tlog (TLOG_FILES, LOG_DEBUG, "Saved DH params to %s (best-effort)", filename);
561                         }
562                         E_gnutls_clear_errno ();
563                 }
564                 gtls_errno = gtls_errno_stack0;
565         } else {
566                 gnutls_dh_params_t old_dh;
567                 //TODO// Acquire DH-params lock
568                 old_dh = dh_params;
569                 dh_params = dhp;
570                 //TODO// Release DH-params lock
571                 if (old_dh) {
572                         gnutls_dh_params_deinit (old_dh);
573                 }
574         }
575         return gtls_errno;
576 }
577
578 /* Remove DH parameters, to be used during program cleanup. */
579 static void remove_dh_params (void) {
580         if (dh_params) {
581                 gnutls_dh_params_deinit (dh_params);
582                 dh_params = NULL;
583         }
584 }
585
586
587 /* A log printing function
588  */
589 void log_gnutls (int level, const char *msg) {
590         tlog (TLOG_TLS, level, "GnuTLS: %s", msg);
591 }
592
593
594 /* Implement the GnuTLS function for token insertion callback.  This function
595  * refers back to the generic callback for token insertion.
596  */
597 int gnutls_token_callback (void *const userdata,
598                                 const char *const label,
599                                 unsigned retry) {
600         if (token_callback (label, retry)) {
601                 return GNUTLS_E_SUCCESS;
602         } else {
603                 return GNUTLS_E_PKCS11_TOKEN_ERROR;
604         }
605 }
606  
607
608 /*
609  * Implement the GnuTLS function for PIN callback.  This function calls
610  * the generic PIN callback operation.
611  */
612 int gnutls_pin_callback (void *userdata,
613                                 int attempt,
614                                 const char *token_url,
615                                 const char *token_label,
616                                 unsigned int flags,
617                                 char *pin,
618                                 size_t pin_max) {
619         if (flags & GNUTLS_PIN_SO) {
620                 return GNUTLS_E_USER_ERROR;
621         }
622         if (pin_callback (attempt, token_url, token_label, pin, pin_max)) {
623                 return 0;
624         } else {
625                 return GNUTLS_E_PKCS11_PIN_ERROR;
626         }
627 }
628
629
630 /* Register a PKCS #11 provider with the GnuTLS environment. */
631 void starttls_pkcs11_provider (char *p11path) {
632         unsigned int token_seq = 0;
633         char *p11uri;
634         if (gnutls_pkcs11_add_provider (p11path, NULL) != 0) {
635                 fprintf (stderr, "Failed to register PKCS #11 library %s with GnuTLS\n", p11path);
636                 exit (1);
637         }
638         while (gnutls_pkcs11_token_get_url (token_seq, 0, &p11uri) == 0) {
639 #ifdef DEBUG
640                 fprintf (stderr, "DEBUG: Found token URI %s\n", p11uri);
641 #endif
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);
644                 token_seq++;
645         }
646         //TODO// Select token by name (value)
647         //TODO// if PIN available then set it up
648         //TODO:WHY?// free_p11pin ();
649 }
650
651
652 /* The global and static setup function for the starttls functions.
653  */
654 void setup_starttls (void) {
655         int setup_starttls_credentials (void);  /* Defined below */
656         const char *curver;
657         int gtls_errno = GNUTLS_E_SUCCESS;
658         char *otfsigcrt, *otfsigkey;
659         //
660         // Setup configuration variables
661         maxpreauth = cfg_tls_maxpreauth ();
662         //
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",
671                 gnutls_pkcs11_init (
672                         GNUTLS_PKCS11_FLAG_MANUAL, NULL));
673         //
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);
678         }
679         //
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);
683         //
684         // Setup DH parameters
685         E_g2e ("Loading DH params failed",
686                 load_dh_params ());
687         //
688         // Setup shared credentials for all client server processes
689         E_g2e ("Failed to setup GnuTLS callback credentials",
690                 setup_starttls_credentials ());
691         //
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));
696         //
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
708                         otfsigcrt += 5;
709                 }
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);
715                 } else {
716                         char crt [5001];
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);
724                         } else {
725                                 gnutls_datum_t cd = {
726                                         .data = crt,
727                                         .size = len
728                                 };
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);
733                         }
734                         fclose (crtfile);
735                 }
736         }
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);
744         }
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");
753                 } else {
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;
757                 }
758         } else {
759                 gtls_errno = GNUTLS_E_SUCCESS;
760                 E_gnutls_clear_errno ();
761         }
762         if (onthefly_subjectkey == NULL) {
763                 if (onthefly_issuercrt != NULL) {
764                         gnutls_x509_crt_deinit (onthefly_issuercrt);
765                         onthefly_issuercrt = NULL;
766                 }
767                 if (onthefly_issuerkey != NULL) {
768                         gnutls_privkey_deinit (onthefly_issuerkey);
769                         onthefly_issuerkey = NULL;
770                 }
771         }
772         //
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));
776                 exit (1);
777         }
778         //MOVED// //
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));
785         //MOVED//       exit (1);
786         //MOVED// }
787 }
788
789 /* Cleanup the structures and resources that were setup for handling TLS.
790  */
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;
797         }
798         if (onthefly_issuercrt != NULL) {
799                 gnutls_x509_crt_deinit (onthefly_issuercrt);
800                 onthefly_issuercrt = NULL;
801         }
802         if (onthefly_issuerkey != NULL) {
803                 gnutls_privkey_deinit (onthefly_issuerkey);
804                 onthefly_issuerkey = NULL;
805         }
806         cleanup_starttls_credentials ();
807         remove_dh_params ();
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 ();
813 }
814
815
816 /*
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
822  * sockets.
823  *
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
840  *
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.
847  *
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.
852  */
853 static int copycat (int local, int remote, gnutls_session_t wrapped, int client) {
854         char buf [1024];
855         struct pollfd inout [3];
856         ssize_t sz;
857         struct linger linger = { 1, 10 };
858         int have_client;
859         int retval = GNUTLS_E_SUCCESS;
860
861         inout [0].fd = local;
862         inout [1].fd = remote;
863         inout [2].fd = client;
864         have_client = inout [2].fd >= 0;
865         if (!have_client) {
866                 inout [2].revents = 0;  // Will not be written by poll
867                 //FORK!=DETACH// inout [2].fd = ctlkey_signalling_fd;
868         }
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) {
874                 int polled;
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);
879                 if (polled == -1) {
880                         tlog (TLOG_COPYCAT, LOG_DEBUG, "Copycat polling returned an error");
881                         break;  // Polling sees an error
882                 }
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);
887                         if (sz == -1) {
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
898                         } else {
899                                 tlog (TLOG_COPYCAT, LOG_DEBUG, "Copycat sent %d bytes to remote %d", (int) sz, remote);
900                         }
901                 }
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);
906                         if (sz < 0) {
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;
911                                         break;
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
915                                 } else {
916                                         tlog (TLOG_TLS, LOG_INFO, "GnuTLS recoverable error: %s", gnutls_strerror (sz));
917                                 }
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
925                         } else {
926                                 tlog (TLOG_COPYCAT, LOG_DEBUG, "Copycat sent %d bytes to local %d", (int) sz, local);
927                         }
928                 }
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
934                 }
935                 if (inout [2].revents & ~POLLIN) {
936                         if (have_client) {
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
940                         } else {
941                                 inout [2].fd = client;
942                                 have_client = inout [2].fd >= 0;
943                                 if (have_client) {
944                                         tlog (TLOG_COPYCAT, LOG_DEBUG, "Copycat signalling_fd polling raised a signal to set control fd to %d", inout [2].fd);
945                                 } else {
946                                         tlog (TLOG_COPYCAT, LOG_DEBUG, "Copycat signalling_fd polling raised a signal that could be ignored");
947                                 }
948                                 continue;
949                         }
950                 }
951         }
952         tlog (TLOG_COPYCAT, LOG_DEBUG, "Ending copycat cycle for local=%d, remote=%d", local, remote);
953         return retval;
954 }
955
956
957 /* The callback function that retrieves certification information from either
958  * the client or the server in the course of the handshake procedure.
959  */
960 gtls_error clisrv_cert_retrieve (gnutls_session_t session,
961                                 const gnutls_datum_t* req_ca_dn,
962                                 int nreqs,
963                                 const gnutls_pk_algorithm_t* pk_algos,
964                                 int pk_algos_length,
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;
970         struct command *cmd;
971         char *lid, *rid;
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;
977         int lidtype;
978         int lidrole = 0;
979         char *rolestr;
980         char sni [sizeof (cmd->cmd.pio_data.pioc_starttls.localid)];
981         size_t snilen = sizeof (sni);
982         int snitype;
983         int ok;
984         uint32_t flags;
985         char *p11priv;
986         uint8_t *pubdata;
987         int pubdatalen;
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);
990
991         //
992         // Setup a number of common references and structures
993         *pcert = NULL;
994         cmd = (struct command *) gnutls_session_get_ptr (session);
995         if (cmd == NULL) {
996                 E_g2e ("No data pointer with session",
997                         GNUTLS_E_INVALID_SESSION);
998                 return gtls_errno;
999         }
1000         if (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_CLIENT) {
1001                 lidrole = LID_ROLE_CLIENT;
1002                 rolestr = "client";
1003         } else if (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_SERVER) {
1004                 lidrole = LID_ROLE_SERVER;
1005                 rolestr = "server";
1006         } else {
1007                 E_g2e ("TLS Pool command supports neither local client nor local server role",
1008                         GNUTLS_E_INVALID_SESSION);
1009                 return gtls_errno;
1010         }
1011         lid = cmd->cmd.pio_data.pioc_starttls.localid;
1012         rid = cmd->cmd.pio_data.pioc_starttls.remoteid;
1013
1014         //
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);
1021                         return gtls_errno;
1022                 }
1023                 if (*lid != '\0') {
1024                         int atidx;
1025                         for (atidx=128; atidx > 0; atidx--) {
1026                                 if (lid [atidx-1] == '@') {
1027                                         break;
1028                                 }
1029                         }
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);
1034                                 return gtls_errno;
1035                         }
1036                 } else {
1037                         // TODO: Should ask for permission before accepting SNI
1038                         memcpy (lid, sni, sizeof (sni));
1039                 }
1040         }
1041
1042         //
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;
1055 #endif
1056         } else {
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);
1061                 return gtls_errno;
1062         }
1063
1064         //
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;
1078                 }
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;
1082                 //
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;
1090                         }
1091                 }
1092                 //
1093                 // Now reiterate to lookup lid credentials in db_localid
1094                 E_g2e ("Missing local credentials",
1095                         fetch_local_credentials (cmd));
1096         }
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);
1101                 return gtls_errno;
1102         }
1103
1104         //
1105         // Split the credential into its various aspects
1106         ok = dbcred_interpret (
1107                 &cmd->lids [lidtype - LID_TYPE_MIN],
1108                 &flags,
1109                 &p11priv,
1110                 &certdatum.data,
1111                 &certdatum.size);
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
1114         if (!ok) {
1115                 gtls_errno = GNUTLS_E_CERTIFICATE_ERROR;
1116         }
1117
1118         //
1119         // Allocate response structures
1120         *pcert_length = 0;
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);
1125                 return gtls_errno;
1126         }
1127         cmd->session_certificate = (intptr_t) (void *) *pcert;  //TODO// Used for session cleanup
1128
1129         //
1130         // Setup private key
1131         E_g2e ("Failed to initialise private key",
1132                 gnutls_privkey_init (
1133                         pkey));
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 (
1137                                 *pkey,
1138                                 onthefly_subjectkey,
1139                                 GNUTLS_PRIVKEY_IMPORT_COPY));
1140         } else {
1141                 if (gtls_errno == GNUTLS_E_SUCCESS) {
1142                         cmd->session_privatekey = (intptr_t) (void *) *pkey;    //TODO// Used for session cleanup
1143                 }
1144                 E_g2e ("Failed to import PKCS #11 private key URI",
1145                         gnutls_privkey_import_pkcs11_url (
1146                                 *pkey,
1147                                 p11priv));
1148         }
1149         E_gnutls_clear_errno ();
1150
1151 //TODO// Moved out (start)
1152
1153         //
1154         // Setup public key certificate
1155         switch (lidtype) {
1156         case LID_TYPE_X509:
1157                 E_g2e ("MOVED: Failed to import X.509 certificate into chain",
1158                         gnutls_pcert_import_x509_raw (
1159                                 *pcert,
1160                                 &certdatum,
1161                                 GNUTLS_X509_FMT_DER,
1162                                 0));
1163                 break;
1164         case LID_TYPE_PGP:
1165                 E_g2e ("MOVED: Failed to import OpenPGP certificate",
1166                         gnutls_pcert_import_openpgp_raw (
1167                                 *pcert,
1168                                 &certdatum,
1169                                 GNUTLS_OPENPGP_FMT_RAW,
1170                                 NULL,   /* use master key */
1171                                 0));
1172                 break;
1173 #ifdef GNUTLS_CRT_KRB
1174         case LID_TYPE_KRB5:
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);
1186                         }
1187                         // The servicename may need mapping to another form
1188                         if (strcmp (svc, "http")) {
1189                                 svc = "HTTP";
1190                         }
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
1194                 } else {
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
1198                 }
1199                 E_g2e ("Failed to import Kerberos ticket",
1200                         gnutls_pcert_import_pgp_raw (
1201                                 *pcert,
1202                                 &certdatum,     //TODO// Service ticket
1203                                 0));
1204 #endif
1205         default:
1206                 /* Should not happen */
1207                 break;
1208         }
1209
1210 //TODO// Moved out (end)
1211
1212         //
1213         // Lap up any overseen POSIX error codes in errno
1214         if (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 */
1218         }
1219
1220         //
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);
1224         return gtls_errno;
1225 }
1226
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.
1229  */
1230 gtls_error load_certificate (int lidtype, gnutls_pcert_st *pcert, gnutls_datum_t *certdatum) {
1231         int gtls_errno = GNUTLS_E_SUCCESS;
1232         //
1233         // Setup public key certificate
1234         switch (lidtype) {
1235         case LID_TYPE_X509:
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 (
1239                                 pcert,
1240                                 certdatum,
1241                                 GNUTLS_X509_FMT_DER,
1242                                 0));
1243                 break;
1244         case LID_TYPE_PGP:
1245                 E_g2e ("Failed to import OpenPGP certificate",
1246                         gnutls_pcert_import_openpgp_raw (
1247                                 pcert,
1248                                 certdatum,
1249                                 GNUTLS_OPENPGP_FMT_RAW,
1250                                 NULL,   /* use master key */
1251                                 0));
1252                 break;
1253         default:
1254                 /* Should not happen */
1255                 break;
1256         }
1257         return gtls_errno;
1258 }
1259
1260
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
1264  * loaded.
1265  */
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;
1270
1271         //
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) {
1276                 (*chainlen)++;
1277                 chain = (gnutls_pcert_st *) calloc (*chainlen, sizeof (gnutls_pcert_st));
1278                 if (chain != NULL) {
1279                         bzero (chain, (*chainlen) * sizeof (gnutls_pcert_st));
1280                 } else {
1281                         gtls_errno = GNUTLS_E_MEMORY_ERROR;
1282                 }
1283                 E_g2e ("Failed to load certificate into chain",
1284                         load_certificate (
1285                                 flags & LID_TYPE_MASK,
1286                                 &chain [mypos],
1287                                 certdatum));
1288                 if (gtls_errno != GNUTLS_E_SUCCESS) {
1289                         if (chain) {
1290                                 free (chain);
1291                         }
1292                         *chainlen = 0;
1293                         chain = NULL;
1294                 }
1295                 return chain;
1296         }
1297
1298         //
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)) {
1310                 long certlen;
1311                 int lenlen;
1312                 gnutls_datum_t nextdatum;
1313                 long nextlen;
1314                 // Note: Accept BER because the outside SEQUENCE is not signed
1315                 certlen = asn1_get_length_ber (
1316                         ((char *) certdatum->data) + 1,
1317                         certdatum->size,
1318                         &lenlen);
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);
1323                         *chainlen = 0;
1324                         return NULL;
1325                 } else if (certlen <= 0) {
1326                         tlog (TLOG_CERT, LOG_ERR, "Refusing LID_CHAINED certificate of too-modest data size %d", certlen);
1327                         *chainlen = 0;
1328                         return NULL;
1329                 }
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,
1335                         nextdatum.size,
1336                         &lenlen);
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;
1342                 }
1343                 (*chainlen)++;
1344                 chain = load_certificate_chain (flags, chainlen, &nextdatum);
1345                 if (chain != NULL) {
1346                         E_g2e ("Failed to add chained certificate",
1347                                 load_certificate (
1348                                         flags & LID_TYPE_MASK,
1349                                         &chain [mypos],
1350                                         certdatum));
1351                         if (gtls_errno != GNUTLS_E_SUCCESS) {
1352                                 free (chain);
1353                                 chain = NULL;
1354                                 *chainlen = 0;
1355                         }
1356                 }
1357                 return chain;
1358         }
1359
1360         //
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
1374         }
1375
1376         //
1377         // Final judgement.  Nothing worked.  Return failure.
1378         *chainlen = 0;
1379         return NULL;
1380 }
1381
1382
1383 /* valexp_valflag_set -- set a validation flag bit for an uppercase predicate.
1384  */
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';
1389 }
1390
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.
1393  */
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));
1398 }
1399
1400 /* valexp_0_start -- validation function for the GnuTLS backend.
1401  * This function immediately sends failure on something impossible.
1402  */
1403 static void valexp_0_start (void *vcmd, struct valexp *ve, char pred) {
1404         valexp_setpredicate (ve, pred, 0);
1405 }
1406
1407 /* valexp_1_start -- validation function for the GnuTLS backend.
1408  * This function immediately sends success on something trivial.
1409  */
1410 static void valexp_1_start (void *vcmd, struct valexp *ve, char pred) {
1411         valexp_setpredicate (ve, pred, 1);
1412 }
1413
1414 //TODO// valexp_L_start, valexp_l_start
1415
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 
1420  */
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));
1428 }
1429
1430 /* valexp_i_start -- is opportunistic and will always succeed
1431  */
1432 #define valexp_i_start valexp_1_start
1433
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.
1438  */
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);
1442         switch (kx) {
1443         case GNUTLS_KX_UNKNOWN:
1444         case GNUTLS_KX_RSA:
1445         case GNUTLS_KX_RSA_EXPORT:
1446         case GNUTLS_KX_PSK:
1447         default:
1448                 valexp_setpredicate (ve, pred, 0);
1449                 break;
1450         case GNUTLS_KX_DHE_DSS:
1451         case GNUTLS_KX_DHE_RSA:
1452         case GNUTLS_KX_SRP:
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);
1462                 break;
1463         // case GNUTLS_KX_xxx_DH:
1464         //      valexp_setpredicate (ve, pred, pred != 'F');
1465         //      break;
1466         }
1467 }
1468
1469 /* valexp_A_start -- validation function for the GnuTLS backend.
1470  * This function ensures that an anonymising precursor is used.
1471  */
1472 #define valexp_A_start valexp_valflag_start
1473
1474 /* valexp_a_start -- is opportunistic and will always succeed */
1475 #define valexp_a_start valexp_1_start
1476
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.
1480  */
1481 static void valexp_Tt_start (void *vcmd, struct valexp *ve, char pred) {
1482         struct command *cmd = (struct command *) vcmd;
1483         int flagval = 0;
1484         gnutls_credentials_type_t authtp;
1485         const gnutls_datum_t *certs;
1486         unsigned int num_certs;
1487         if (cmd->vfystatus == 0) {
1488                 goto setflagval;
1489         }
1490         authtp = gnutls_auth_get_type (cmd->session);
1491         if (authtp != GNUTLS_CRD_CERTIFICATE) {
1492                 goto setflagval;
1493         }
1494         certs = gnutls_certificate_get_peers (cmd->session, &num_certs);
1495         // "certs" points into GnuTLS' internal data structures
1496         if (num_certs < 1) {
1497                 goto setflagval;
1498         }
1499         if ((num_certs == 1) && (pred == 't')) {
1500                 //TODO// if (self-signature-correct) {
1501                 //TODO//        flagval = 1;
1502                 //TODO//        goto setflagval;
1503                 //TODO// }
1504         }
1505         //TODO// Look in trust.db for H(cert[num_certs-1])
1506         //TODO// flagval = 1;
1507 setflagval:
1508         valexp_setpredicate (ve, pred, flagval);
1509 }
1510
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.
1514  */
1515 static void valexp_Dd_start (void *vcmd, struct valexp *ve, char pred) {
1516         struct command *cmd = (struct command *) vcmd;
1517         int flagval = 0;
1518         dane_state_t stat;
1519         unsigned int vfystat;
1520         char *host;
1521         char *proto;
1522         int sox;
1523         struct sockaddr peername;
1524         socklen_t peernamesz = sizeof (peername);
1525         uint16_t port;
1526         host = strchr (cmd->cmd.pio_data.pioc_starttls.remoteid, '@');
1527         if (host == NULL) {
1528                 host = cmd->cmd.pio_data.pioc_starttls.remoteid;
1529         }
1530         switch (cmd->cmd.pio_data.pioc_starttls.ipproto) {
1531         case IPPROTO_TCP:
1532                 proto = "tcp";
1533                 break;
1534         case IPPROTO_UDP:
1535                 proto = "udp";
1536                 break;
1537         case IPPROTO_SCTP:
1538                 proto = "sctp";
1539                 break;
1540         default:
1541                 goto setflagval;
1542         }
1543         sox = gnutls_transport_get_int (cmd->session);
1544         if (sox < 0) {
1545                 goto setflagval;
1546         }
1547         if (getpeername (sox, &peername, &peernamesz) != 0) {
1548                 goto setflagval;
1549         }
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))) {
1555         } else {
1556                 port = ntohs (((struct sockaddr_in6 *) &peername)->sin6_port);
1557                 goto setflagval;
1558         }
1559         if (dane_state_init (&stat, /*TODO:*/ 0) != GNUTLS_E_SUCCESS) {
1560                 goto setflagval;
1561         }
1562         if (dane_verify_session_crt (stat,
1563                                 cmd->session,
1564                                 host,
1565                                 proto,
1566                                 port,
1567                                 0,
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);
1572                         goto setflagval;
1573                 }
1574                 flagval = ((vfystat & ~DANE_VERIFY_UNKNOWN_DANE_INFO) == 0);
1575         }
1576         dane_state_deinit (stat);
1577 setflagval:
1578         valexp_setpredicate (ve, pred, flagval);
1579 }
1580
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.
1585  */
1586 static void valexp_Rr_start (void *vcmd, struct valexp *ve, char pred) {
1587         //TODO//;
1588         valexp_setpredicate (ve, pred, 0);
1589 }
1590
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.
1594  */
1595 static void valexp_Ee_start (void *vcmd, struct valexp *ve, char pred) {
1596         //TODO//;
1597         valexp_setpredicate (ve, pred, 0);
1598 }
1599
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
1606  */
1607 static void valexp_Oo_start (void *vcmd, struct valexp *ve, char pred) {
1608         struct command *cmd = (struct command *) vcmd;
1609         int valflag = 0;
1610         char *atnam = NULL;
1611         char *atoid = NULL;
1612         gnutls_credentials_type_t authtp;
1613         gnutls_certificate_type_t certtp;
1614         online2success_t o2vf;
1615         char *rid;
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
1621                 goto setvalflag;
1622         } else {
1623                 if ((pred >= 'a') && (pred <= 'z')) {
1624                         o2vf = online2success_optional;
1625                 } else {
1626                         o2vf = online2success_enforced;
1627                 }
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
1641                         valflag = 1;
1642                         goto setvalflag;
1643 #endif
1644                 } else {
1645                         // GNUTLS_CRT_RAW, GNUTLS_CRT_UNKNOWN, or other
1646                         goto setvalflag;
1647                 }
1648         }
1649 setvalflag:
1650         valexp_setpredicate (ve, pred, valflag);
1651 }
1652
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
1661  */
1662 static void valexp_Gg_start (void *vcmd, struct valexp *ve, char pred) {
1663         struct command *cmd = (struct command *) vcmd;
1664         int valflag = 0;
1665         char *atnam = NULL;
1666         char *atoid = NULL;
1667         gnutls_credentials_type_t authtp;
1668         gnutls_certificate_type_t certtp;
1669         online2success_t o2vf;
1670         char *rid;
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
1676                 goto setvalflag;
1677         } else {
1678                 if ((pred >= 'a') && (pred <= 'z')) {
1679                         o2vf = online2success_optional;
1680                 } else {
1681                         o2vf = online2success_enforced;
1682                 }
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) {
1695                         valflag = 0;
1696                         //TODO// valflag = o2vf (online_globaldir_kerberos (
1697                         //TODO//                rid, crt->data, crt->size));
1698 #endif
1699                 } else {
1700                         // GNUTLS_CRT_RAW, GNUTLS_CRT_UNKNOWN, or other
1701                         goto setvalflag;
1702                 }
1703         }
1704 setvalflag:
1705         valexp_setpredicate (ve, pred, valflag);
1706 }
1707
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.
1711  */
1712 static void valexp_Pp_start (void *vcmd, struct valexp *ve, char pred) {
1713         //TODO//;
1714         valexp_setpredicate (ve, pred, 0);
1715 }
1716
1717 /* valexp_U_start -- validation function for the GnuTLS backend.
1718  * This function validates a matching username.
1719  */
1720 static void valexp_U_start (void *vcmd, struct valexp *ve, char pred) {
1721         //TODO//;
1722         valexp_setpredicate (ve, pred, 0);
1723 }
1724
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.
1728  */
1729 static void valexp_Ss_start (void *vcmd, struct valexp *ve, char pred) {
1730         struct command *cmd = (struct command *) vcmd;
1731         int flagval;
1732         if ((pred == 'S') && (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_CLIENT)) {
1733                 flagval = 0;
1734         } else {
1735                 flagval = (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_SERVER) != 0;
1736         }
1737         valexp_setpredicate (ve, pred, flagval);
1738 }
1739
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.
1743  */
1744 static void valexp_Cc_start (void *vcmd, struct valexp *ve, char pred) {
1745         struct command *cmd = (struct command *) vcmd;
1746         int flagval;
1747         if ((pred == 'C') && (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_SERVER)) {
1748                 flagval = 0;
1749         } else {
1750                 flagval = (cmd->cmd.pio_data.pioc_starttls.flags & PIOF_STARTTLS_LOCALROLE_CLIENT) != 0;
1751         }
1752         valexp_setpredicate (ve, pred, flagval);
1753 }
1754
1755
1756
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.
1762  */
1763 gtls_error fetch_local_credentials (struct command *cmd) {
1764         int lidrole;
1765         char *lid, *rid;
1766         DBC *crs_disclose = NULL;
1767         DBC *crs_localid = NULL;
1768         DBT discpatn;
1769         DBT keydata;
1770         DBT creddata;
1771         selector_t remote_selector;
1772         int gtls_errno = 0;
1773         int db_errno = 0;
1774         int found = 0;
1775         gtls_error certificate_onthefly (struct command *cmd);
1776
1777         //
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);
1787                         return gtls_errno;
1788                 } else {
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
1791                 }
1792         }
1793
1794         //
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;
1801         } else {
1802                 E_g2e ("TLS Pool command supports neither local client nor local server role",
1803                         GNUTLS_E_INVALID_SESSION);
1804                 return gtls_errno;
1805         }
1806         lid = cmd->cmd.pio_data.pioc_starttls.localid;
1807         rid = cmd->cmd.pio_data.pioc_starttls.remoteid;
1808
1809         //
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);
1816                 return gtls_errno;
1817         }
1818         //
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 (
1823                                 dbh_disclose,
1824                                 cmd->txn,
1825                                 &crs_disclose,
1826                                 0));
1827         }
1828         E_d2e ("Failed to create db_localid cursor",
1829                 dbh_localid->cursor (
1830                         dbh_localid,
1831                         cmd->txn,
1832                         &crs_localid,
1833                         0));
1834         //
1835         // Prepare for iteration over possible local identities / credentials
1836         char mid [128];
1837         char cid [128];
1838         if (gtls_errno != 0) {
1839                 ; // Skip setup
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);
1845                 selector_t ridsel;
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);
1850                 } else {
1851                         E_d2e ("Failed to start iterator on remote ID selector",
1852                                 dbcred_iterate_from_remoteid_selector (
1853                                         crs_disclose,
1854                                         crs_localid,
1855                                         &remote_selector,
1856                                         &discpatn,
1857                                         &keydata,
1858                                         &creddata));
1859                 }
1860         } else {
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 (
1866                         crs_localid,
1867                         &keydata,
1868                         &creddata));
1869         }
1870         if (db_errno != 0) {
1871                 gtls_errno = GNUTLS_E_DB_ERROR;
1872         }
1873
1874         //
1875         // Now store the local identities inasfar as they are usable
1876         db_errno = 0;
1877         while ((gtls_errno == GNUTLS_E_SUCCESS) && (db_errno == 0)) {
1878                 int ok;
1879                 uint32_t flags;
1880                 int lidtype;
1881
1882                 tlog (TLOG_DB, LOG_DEBUG, "Found BDB entry %s disclosed to %s", creddata.data + 4, (lidrole == LID_ROLE_CLIENT)? rid: "all clients");
1883                 ok = dbcred_flags (
1884                         &creddata,
1885                         &flags);
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 ");
1892                 if (ok) {
1893                         // Move the credential into the command structure
1894                         dbt_store (&creddata,
1895                                 &cmd->lids [lidtype - LID_TYPE_MIN]);
1896                         found = 1;
1897                 } else {
1898                         // Skip the credential by freeing its data structure
1899                         dbt_free (&creddata);
1900                 }
1901                 db_errno = dbcred_iterate_next (crs_disclose, crs_localid, &discpatn, &keydata, &creddata);
1902         }
1903
1904         if (db_errno == DB_NOTFOUND) {
1905                 if (!found) {
1906                         gtls_errno = GNUTLS_E_NO_CERTIFICATE_FOUND;
1907                 }
1908         }
1909         if (crs_localid != NULL) {
1910                 crs_localid->close (crs_localid);
1911                 crs_localid = NULL;
1912         }
1913         if (crs_disclose != NULL) {
1914                 crs_disclose->close (crs_disclose);
1915                 crs_disclose = NULL;
1916         }
1917         return gtls_errno;
1918 }
1919
1920
1921 /*
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.
1924  */
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;
1928 }
1929
1930 /* Configure the GnuTLS session with suitable credentials and priority string.
1931  * The anonpre_ok flag should be non-zero to permit Anonymous Precursor.
1932  *
1933  * The credential setup is optional; when creds is NULL, no changes will
1934  * be made.
1935  */
1936 static int configure_session (struct command *cmd,
1937                         gnutls_session_t session,
1938                         struct credinfo *creds,
1939                         int credcount,
1940                         int anonpre_ok) {
1941         int i;
1942         int gtls_errno = GNUTLS_E_SUCCESS;
1943         //
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 (
1950                                         session,
1951                                         creds [i].credtp,
1952                                         creds [i].cred  ));
1953                 }
1954         }
1955         //
1956         // Setup the priority string for this session; this avoids future
1957         // credential callbacks that ask for something impossible or
1958         // undesired.
1959         //
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) {
1965                 char priostr [256];
1966                 snprintf (priostr, sizeof (priostr)-1,
1967                         // "NORMAL:-RSA:" -- also ECDH-RSA, ECDHE-RSA, ...DSA...
1968                         "NONE:"
1969                         "+VERS-TLS-ALL:+VERS-DTLS-ALL:"
1970                         "+COMP-NULL:"
1971                         "+CIPHER-ALL:+CURVE-ALL:+SIGN-ALL:+MAC-ALL:"
1972                         "%cANON-ECDH:"
1973                         "+ECDHE-RSA:+DHE-RSA:+ECDHE-ECDSA:+DHE-DSS:+RSA:" //TODO//
1974                         "%cCTYPE-X.509:"
1975                         "%cCTYPE-OPENPGP:"
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 (
1990                         session,
1991                         priostr,
1992                         NULL));
1993         }
1994         //
1995         // Return the application GNUTLS_E_ code including _SUCCESS
1996         return gtls_errno;
1997 }
1998
1999 /* The callback functions retrieve various bits of information for the client
2000  * or server in the course of the handshake procedure.
2001  *
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
2006  */
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);
2011         int snitype;
2012         int gtls_errno = GNUTLS_E_SUCCESS;
2013         char *lid;
2014
2015 fprintf (stderr, "DEBUG: Got errno = %d / %s at %d\n", errno, strerror (errno), __LINE__);
2016 errno = 0;
2017 fprintf (stderr, "DEBUG: Got errno = %d / %s at %d\n", errno, strerror (errno), __LINE__);
2018         //
2019         // Setup a number of common references
2020         cmd = (struct command *) gnutls_session_get_ptr (session);
2021         if (cmd == NULL) {
2022                 return GNUTLS_E_INVALID_SESSION;
2023         }
2024         lid = cmd->cmd.pio_data.pioc_starttls.localid;
2025
2026         //
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,
2033                         session,
2034                         srv_creds, srv_credcount, 
2035                         cmd->anonpre & ANONPRE_SERVER));
2036 fprintf (stderr, "DEBUG: Got gtls_errno = %d at %d\n", gtls_errno, __LINE__);
2037
2038         //
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
2043                 ;
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 (
2048                                 session,
2049                                 GNUTLS_CERT_REQUEST));
2050 fprintf (stderr, "DEBUG: Got gtls_errno = %d at %d\n", gtls_errno, __LINE__);
2051         } else {
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 (
2055                                 session,
2056                                 GNUTLS_CERT_REQUIRE));
2057 fprintf (stderr, "DEBUG: Got gtls_errno = %d at %d\n", gtls_errno, __LINE__);
2058         }
2059
2060         //
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__);
2063         sni [0] = '\0';
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__);
2066                 switch (snitype) {
2067                 case GNUTLS_NAME_DNS:
2068                         break;
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.
2072                 default:
2073                         sni [0] = '\0';
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__);
2076                         break;
2077                 }
2078         }
2079 fprintf (stderr, "DEBUG: Got errno = %d / %s at %d\n", errno, strerror (errno), __LINE__);
2080         if (sni [0] != '\0') {
2081                 if (*lid != '\0') {
2082                         int atidx;
2083                         for (atidx=128; atidx > 0; atidx--) {
2084                                 if (lid [atidx-1] == '@') {
2085                                         break;
2086                                 }
2087                         }
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;
2092                         }
2093                 } else {
2094                         memcpy (lid, sni, sizeof (sni));
2095 fprintf (stderr, "DEBUG: Got errno = %d / %s at %d\n", errno, strerror (errno), __LINE__);
2096                 }
2097         } else {
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';
2101         }
2102 fprintf (stderr, "DEBUG: Got gtls_errno = %d at %d\n", gtls_errno, __LINE__);
2103
2104         //
2105         // Lap up any unnoticed POSIX error messages
2106         if (errno != 0) {
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__);
2111         }
2112
2113         //
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));
2116         return gtls_errno;
2117 }
2118
2119
2120 int cli_srpcreds_retrieve (gnutls_session_t session,
2121                                 char **username,
2122                                 char **password) {
2123         //TODO:FIXED//
2124         tlog (TLOG_CRYPTO, LOG_DEBUG, "Picking up SRP credentials");
2125         *username = strdup ("tester");
2126         *password = strdup ("test");
2127         return GNUTLS_E_SUCCESS;
2128 }
2129
2130
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.
2134  */
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;
2146
2147         //
2148         // Construct anonymous server credentials
2149         E_g2e ("Failed to allocate ANON-DH server credentials",
2150                 gnutls_anon_allocate_server_credentials (
2151                         &srv_anoncred));
2152         if (!have_error_codes ()) /* E_g2e (...) */ gnutls_anon_set_server_dh_params (
2153                 srv_anoncred,
2154                 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;
2159                 srv_credcount++;
2160         } else if (srv_anoncred != NULL) {
2161                 gnutls_anon_free_server_credentials (srv_anoncred);
2162                 srv_anoncred = NULL;
2163         }
2164
2165         //
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 (
2170                         &cli_anoncred));
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 (
2174                 cli_anoncred,
2175                 dh_params);
2176 #endif
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;
2181                 cli_credcount++;
2182         } else if (cli_anoncred != NULL) {
2183                 gnutls_anon_free_client_credentials (cli_anoncred);
2184                 cli_anoncred = NULL;
2185         }
2186
2187         //
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 (
2192                         &clisrv_certcred));
2193         //TODO// What to do here when we add locking on DH params?
2194         gnutls_certificate_set_dh_params (
2195                 clisrv_certcred,
2196                 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.
2203          */
2204         if (!have_error_codes ()) /* TODO:GnuTLSversions E_g2e (...) */ gnutls_certificate_set_retrieve_function (
2205                 clisrv_certcred,
2206                 (void *) exit);
2207         if (!have_error_codes ()) /* TODO:GnuTLSversions E_g2e (...) */ gnutls_certificate_set_retrieve_function2 (
2208                 clisrv_certcred,
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;
2215                 cli_credcount++;
2216                 srv_creds [srv_credcount].credtp = GNUTLS_CRD_CERTIFICATE;
2217                 srv_creds [srv_credcount].cred   = (void *) clisrv_certcred;
2218                 srv_credcount++;
2219         } else if (clisrv_certcred != NULL) {
2220                 gnutls_certificate_free_credentials (clisrv_certcred);
2221                 clisrv_certcred = NULL;
2222         }
2223
2224         //
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 (
2229                         &srv_srpcred));
2230         E_g2e ("Failed to set SRP server credentials",
2231                 gnutls_srp_set_server_credentials_file (
2232                         srv_srpcred,
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;
2239                 srv_credcount++;
2240         } else if (srv_srpcred != NULL) {
2241                 gnutls_srp_free_server_credentials (srv_srpcred);
2242                 srv_srpcred = NULL;
2243         }
2244
2245         //
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 (
2250                         &cli_srpcred));
2251         if (!have_error_codes ()) gnutls_srp_set_client_credentials_function (
2252                 cli_srpcred,
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;
2258                 cli_credcount++;
2259         } else if (cli_srpcred != NULL) {
2260                 gnutls_srp_free_client_credentials (cli_srpcred);
2261                 cli_srpcred = NULL;
2262         }
2263
2264         //
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;
2282         //TODO// }
2283
2284         //
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;
2302         //TODO// }
2303
2304         //
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);
2313         }
2314
2315         //
2316         // Report overall error or success
2317         return gtls_errno;
2318 }
2319
2320
2321 /* Cleanup all credentials created, just before exiting the daemon.
2322  */
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);
2330                         break;
2331                 case GNUTLS_CRD_ANON:
2332                         gnutls_anon_free_server_credentials (crd->cred);
2333                         break;
2334                 case GNUTLS_CRD_SRP:
2335                         gnutls_srp_free_server_credentials (crd->cred);
2336                         break;
2337                 //TODO// case GNUTLS_CRD_KDH:
2338                 //TODO//        gnutls_kdh_free_server_credentials (crd->cred);
2339                 //TODO//        break;
2340                 }
2341         }
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);
2348                         break;
2349                 case GNUTLS_CRD_ANON:
2350                         gnutls_anon_free_client_credentials (crd->cred);
2351                         break;
2352                 case GNUTLS_CRD_SRP:
2353                         gnutls_srp_free_client_credentials (crd->cred);
2354                         break;
2355                 //TODO// case GNUTLS_CRD_KDH:
2356                 //TODO//        gnutls_kdh_free_client_credentials (crd->cred);
2357                 //TODO//        break;
2358                 }
2359         }
2360 }
2361
2362
2363 /*
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.
2368  *
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.
2372  *
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
2382  * information.
2383  *
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.
2397  *
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
2404  *     an earlier stage.
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.
2415  */
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;
2421         int plainfd = -1;
2422         int cryptfd = -1;
2423         gnutls_session_t session;
2424         int got_session = 0;
2425         int gtls_errno = GNUTLS_E_SUCCESS;
2426         int i;
2427         struct ctlkeynode_tls *ckn = NULL;
2428         uint32_t tout;
2429         int forked = 0;
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;
2437         int anonpost = 0;
2438
2439         //
2440         // Block thread cancellation -- and re-enable it in copycat()
2441         assert (pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, NULL) == 0);
2442
2443         //
2444         // General thread setup
2445         replycmd = cmd = (struct command *) cmd_void;
2446         if (cmd == NULL) {
2447                 send_error (replycmd, EINVAL, "Command structure not received");
2448                 assert (pthread_detach (pthread_self ()) == 0);
2449                 return NULL;
2450         }
2451         *cmd->valflags = '\0';
2452         cmd->session_errno = 0;
2453         cmd->anonpre = 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;
2458         cmd->passfd = -1;
2459 //TODO:TEST Removed here because it is tested below
2460 /*
2461         if (cryptfd < 0) {
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);
2465                 return NULL;
2466         }
2467 */
2468         cmd->session_certificate = (intptr_t) (void *) NULL;
2469         cmd->session_privatekey  = (intptr_t) (void *) NULL;
2470
2471         //
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");
2478                 //
2479                 // Check that no FD was passed (and ended up in cryptfd)
2480                 if (cryptfd >= 0) {
2481                         tlog (TLOG_UNIXSOCK, LOG_ERR, "Renegotiation started with extraneous file descriptor");
2482                         send_error (replycmd, EPROTO, "File handle supplied for renegotiation");
2483                         close (cryptfd);
2484                         assert (pthread_detach (pthread_self ()) == 0);
2485                         return NULL;
2486                 }
2487                 //
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);
2491                 if (ckn == NULL) {
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);
2495                         return NULL;
2496                 }
2497                 //
2498                 // Now cancel the pthread for this process
2499                 errno = pthread_cancel (ckn->owner);
2500 fprintf (stderr, "DEBUG: pthread_cancel returned %d\n", errno);
2501                 if (errno == 0) {
2502                         void *retval;
2503                         errno = pthread_join (ckn->owner, &retval);
2504 fprintf (stderr, "DEBUG: pthread_join returned %d\n", errno);
2505                 }
2506                 if (errno != 0) {
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
2512                         return NULL;
2513                 }
2514                 //
2515                 // We are in control!  Assimilate the TLS connection data.
2516                 renegotiating = 1;
2517                 plainfd = ckn->plainfd;
2518                 cryptfd = ckn->cryptfd;
2519                 session = ckn->session;
2520                 got_session = 1;
2521                 taking_over = 1;
2522                 ctlkey_unfind (&ckn->regent);
2523         }
2524
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.
2532         renegotiate:
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);
2534
2535         //
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");
2545                 }
2546         }
2547
2548         //
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");
2552                 if (cryptfd >= 0) {
2553                         close (cryptfd);
2554                         cryptfd = -1;
2555                 }
2556                 if (plainfd >= 0) {
2557                         close (plainfd);
2558                         plainfd = -1;
2559                 }
2560                 if (ckn != NULL) {
2561                         if (ctlkey_unregister (ckn->regent.ctlkey)) {
2562                                 free (ckn);
2563                                 ckn = NULL;
2564                         }
2565                 }
2566                 assert (pthread_detach (pthread_self ()) == 0);
2567                 return NULL;
2568         }
2569
2570         //
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;
2574                 forked = 1;
2575         }
2576
2577         //
2578         // Setup BDB transactions and reset credential datum fields
2579         if (!anonpost) {
2580                 bzero (&cmd->lids, sizeof (cmd->lids));
2581                 manage_txn_begin (&cmd->txn);
2582         }
2583
2584         //
2585         // Permit cancellation of this thread -- TODO: Cleanup?
2586 //TODO:TEST// Defer setcancelstate untill copycat() activity
2587 /*
2588         errno = pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, NULL);
2589         if (errno != 0) {
2590                 send_error (replycmd, ESRCH, "STARTTLS handler thread cancellability refused");
2591                 if (cryptfd >= 0) {
2592                         close (cryptfd);
2593                         cryptfd = -1;
2594                 }
2595                 if (plainfd >= 0) {
2596                         close (plainfd);
2597                         plainfd = -1;
2598                 }
2599                 if (ckn != NULL) {
2600                         if (ctlkey_unregister (ckn->regent.ctlkey)) {
2601                                 free (ckn);
2602                                 ckn = NULL;
2603                         }
2604                 }
2605                 manage_txn_rollback (&cmd->txn);
2606                 assert (pthread_detach (pthread_self ()) == 0);
2607                 return NULL;
2608         }
2609 */
2610         //
2611         // Check and setup the plaintext file handle
2612         if (cryptfd < 0) {
2613                 send_error (replycmd, EPROTO, "You must supply a TLS-protected socket");
2614                 if (plainfd >= 0) {
2615                         close (plainfd);
2616                         plainfd = -1;
2617                 }
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)) {
2621                                 free (ckn);
2622                                 ckn = NULL;
2623                         }
2624                 }
2625                 manage_txn_rollback (&cmd->txn);
2626                 assert (pthread_detach (pthread_self ()) == 0);
2627                 return NULL;
2628         }
2629
2630         //
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;
2640                 want_remoteid = 0;
2641         } else {
2642                 int anonpre_regidx =  anonpre_registry_size      >> 1;
2643                 int anonpre_regjmp = (anonpre_registry_size + 1) >> 1;
2644                 int cmp;
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);
2651                         if (cmp == 0) {
2652                                 // anonpre_regent matches
2653                                 cmd->anonpre = anonpre_registry [anonpre_regidx].flags;
2654                                 break;
2655                         } else if (cmp > 0) {
2656                                 // anonpre_regent too high
2657                                 anonpre_regidx -= 1 + anonpre_regjmp;
2658                                 if (anonpre_regidx < 0) {
2659                                         anonpre_regidx = 0;
2660                                 }
2661                         } else {
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;
2666                                 }
2667                         }
2668                 }
2669         }
2670
2671         //
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;
2675         }
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;
2678         }
2679         if ((cmd->cmd.pio_data.pioc_starttls.flags & (PIOF_STARTTLS_LOCALROLE_CLIENT | PIOF_STARTTLS_LOCALROLE_SERVER)) == 0) {
2680                 //
2681                 // Neither a TLS client nor a TLS server
2682                 //
2683                 send_error (replycmd, ENOTSUP, "Command not supported");
2684                 close (cryptfd);
2685                 if (plainfd >= 0) {
2686                         close (plainfd);
2687                         plainfd = -1;
2688                 }
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)) {
2692                                 free (ckn);
2693                                 ckn = NULL;
2694                         }
2695                 }
2696                 manage_txn_rollback (&cmd->txn);
2697                 assert (pthread_detach (pthread_self ()) == 0);
2698                 return NULL;
2699         }
2700
2701         //
2702         // Setup the TLS session.  Also see doc/p2p-tls.*
2703         //
2704         // TODO: GnuTLS cannot yet setup p2p connections
2705         if (ckn != NULL) {
2706                 gnutls_session_set_ptr (
2707                         session,
2708                         cmd);
2709                 //TODO:DONE?// Clear various settings... creds, flags, modes? CLI/SRV?
2710         } else {
2711                 E_g2e ("Failed to initialise GnuTLS peer session",
2712                         gnutls_init (
2713                                 &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))
2716                                 ));
2717                 if (gtls_errno == GNUTLS_E_SUCCESS) {
2718                         got_session = 1;
2719                         gnutls_session_set_ptr (
2720                                 session,
2721                                 cmd);
2722                 }
2723         }
2724         cmd->session = session;
2725         //
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//
2729                 //
2730                 // Setup as a TLS client
2731                 //
2732                 int srpbits;
2733                 //
2734                 // Require a minimum security level for SRP
2735                 srpbits = 3072;
2736                 //TODO:CRASH// if (gtls_errno == GNUTLS_E_SUCCESS) gnutls_srp_set_prime_bits (
2737                         //TODO:CRASH// session,
2738                         //TODO:CRASH// srpbits);
2739                 //
2740                 // Setup as a TLS client
2741                 //
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;
2745                         int ofs = 0;
2746                         int len = 0;
2747                         while (str [len] && (len < 128)) {
2748                                 if (str [len] == '@') {
2749                                         ofs = len + 1;
2750                                 }
2751                                 len++;
2752                         }
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 (
2758                                                 session,
2759                                                 GNUTLS_NAME_DNS,
2760                                                 str + ofs,
2761                                                 len - ofs));
2762                         }
2763                 }
2764 } //TODO:TEST//
2765                 //
2766                 // Setup for client credential installation in this session
2767                 //
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,
2772                                 session,
2773                                 anonpost? NULL: cli_creds,
2774                                 anonpost?    0: cli_credcount, 
2775                                 cmd->anonpre & ANONPRE_CLIENT));
2776         }
2777         //
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 (
2784                                 session,
2785                                 srv_clienthello);
2786                 }
2787 } //TODO:TEST//
2788                 //TODO:TEST// configure_session _if_ not setup as a client (too)
2789                 //
2790                 // Setup for server credential installation in this session
2791                 //
2792                 // Setup server-specific credentials and priority string
2793 #if 0
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,
2798                                         session,
2799                                         anonpost? NULL: srv_creds,
2800                                         anonpost?    0: srv_credcount, 
2801                                         cmd->anonpre & ANONPRE_SERVER));
2802                 }
2803 #endif
2804         }
2805
2806         //
2807         // Prefetch local identities that might be used in this session
2808         if (!anonpost) {
2809                 E_g2e ("Failed to fetch local credentials",
2810                         fetch_local_credentials (cmd));
2811         }
2812
2813         //
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 (
2818                                         session,
2819                                         priority_normal));
2820         }
2821
2822         //
2823         // Check if past code stored an error code through POSIX
2824         if (cmd->session_errno) {
2825                 gtls_errno = GNUTLS_E_USER_ERROR;
2826         }
2827
2828         //
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
2834 } else
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);
2839         } else {
2840                 gnutls_handshake_set_timeout (session, tout);
2841         }
2842
2843         //
2844         // Now setup for the GnuTLS handshake
2845         //
2846 if (renegotiating) {
2847 ; // Do not setup cryptfd
2848 } else
2849         if (gtls_errno == GNUTLS_E_SUCCESS) {
2850                 gnutls_transport_set_int (session, cryptfd);
2851         }
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 ());
2856                 } else {
2857                         send_error (replycmd, EIO, "Failed to prepare for TLS");
2858                 }
2859                 if (got_session) {
2860 fprintf (stderr, "gnutls_deinit (0x%x) at %d\n", session, __LINE__);
2861                         gnutls_deinit (session);
2862                         got_session = 0;
2863                 }
2864                 close (cryptfd);
2865                 if (plainfd >= 0) {
2866                         close (plainfd);
2867                         plainfd = -1;
2868                 }
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)) {
2872                                 free (ckn);
2873                                 ckn = NULL;
2874                         }
2875                 }
2876                 manage_txn_rollback (&cmd->txn);
2877                 assert (pthread_detach (pthread_self ()) == 0);
2878                 return NULL;
2879         }
2880         tlog (TLOG_UNIXSOCK | TLOG_TLS, LOG_DEBUG, "TLS handshake started over %d", cryptfd);
2881         do {
2882                 //
2883                 // Take a rehandshaking step forward.
2884                 //
2885                 gtls_errno = gnutls_handshake (session);
2886                 //
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
2892                 // it though!
2893                 //
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.
2898                 //
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
2908                                 }
2909                         }
2910                 }
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
2915                         }
2916                 }
2917                 if (gtls_errno == GNUTLS_E_GOT_APPLICATION_DATA) {
2918                         ssize_t sz;
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);
2921                         if (sz > 0) {
2922                                 preauthlen += sz;
2923                                 gtls_errno = GNUTLS_E_SUCCESS;
2924                         } else {
2925                                 gtls_errno = sz; // It's actually an error code
2926                         }
2927                 }
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;
2935                 got_remoteid = 0;
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)) {
2940                                 got_remoteid = 1;
2941                         }
2942                         // "certs" points into GnuTLS' internal data structures
2943                         E_g2e ("Failed to validate peer",
2944                                 gnutls_certificate_verify_peers2 (
2945                                         session,
2946                                         &cmd->vfystatus));
2947                         break;
2948                 case GNUTLS_CRD_PSK:
2949                         // Difficult... what did the history say about this?
2950                         got_remoteid = 0;
2951                         cmd->vfystatus = GNUTLS_CERT_SIGNER_NOT_FOUND;
2952                         break;
2953                 case GNUTLS_CRD_SRP:
2954                         // Got a credential, validation follows later on
2955                         //TODO// SRP does not really auth the server
2956                         got_remoteid = 1;
2957                         cmd->vfystatus = GNUTLS_CERT_SIGNER_NOT_FOUND;
2958                         break;
2959                 case GNUTLS_CRD_ANON:
2960                         // Did not get a credential, perhaps due to anonpre
2961                         got_remoteid = 0;
2962                         cmd->vfystatus = GNUTLS_CERT_INVALID | GNUTLS_CERT_SIGNER_NOT_FOUND | GNUTLS_CERT_SIGNATURE_FAILURE;
2963                         break;
2964                 case GNUTLS_CRD_IA:
2965                         // Inner Application extension is no true credential
2966                         // Should we compare the client-requested service?
2967                         // Should we renegotiate into the ALPN protocol?
2968                         got_remoteid = 0;
2969                         cmd->vfystatus = GNUTLS_CERT_INVALID | GNUTLS_CERT_SIGNER_NOT_FOUND | GNUTLS_CERT_SIGNATURE_FAILURE;
2970                         break;
2971                 default:
2972                         // Unknown creds cautiously considered unauthentitcated
2973                         got_remoteid = 0;
2974                         cmd->vfystatus = ~ (unsigned short) 0;  // It's all bad
2975                         break;
2976                 }
2977                 //
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.
2995                         my_maxpreauth = 0;
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;
3001                                 }
3002 #endif
3003                         } else {
3004                                 my_maxpreauth = maxpreauth;
3005                         }
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
3010                                 goto renegotiate;
3011                         }
3012                 }
3013         }
3014         if ((gtls_errno == GNUTLS_E_SUCCESS) && cmd->session_errno) {
3015                 gtls_errno = GNUTLS_E_USER_ERROR;
3016         }
3017         taking_over = 0;
3018
3019         //
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);
3024                 }
3025         }
3026         bzero (cmd->lids, sizeof (cmd->lids));
3027
3028 #if 0
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.
3035  */
3036         if (NULL != (void *) cmd->session_privatekey) {
3037                 gnutls_privkey_deinit ((void *) cmd->session_privatekey);
3038                 cmd->session_privatekey = (intptr_t) (void *) NULL;
3039         }
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;
3044         }
3045 #endif
3046
3047         //
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;
3055
3056         //
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) {
3061                         char *errstr;
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";
3066                         }
3067                         send_error (replycmd, cmd->session_errno, errstr);
3068                 } else {
3069                         send_error (replycmd, EPERM, "TLS handshake failed");
3070                 }
3071                 if (preauth) {
3072                         free (preauth);
3073                 }
3074                 if (got_session) {
3075 fprintf (stderr, "gnutls_deinit (0x%x) at %d\n", session, __LINE__);
3076                         gnutls_deinit (session);
3077                         got_session = 0;
3078                 }
3079                 close (cryptfd);
3080                 if (plainfd >= 0) {
3081                         close (plainfd);
3082                         plainfd = -1;
3083                 }
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)) {
3087                                 free (ckn);
3088                                 ckn = NULL;
3089                         }
3090                 }
3091                 manage_txn_rollback (&cmd->txn);
3092                 assert (pthread_detach (pthread_self ()) == 0);
3093                 return NULL;
3094         } else {
3095                 tlog (TLOG_UNIXSOCK | TLOG_TLS, LOG_INFO, "TLS handshake succeeded over %d", cryptfd);
3096                 //TODO// extract_authenticated_remote_identity (cmd);
3097         }
3098
3099         //
3100         // Request the plaintext file descriptor with a callback
3101         if (plainfd < 0) {
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");
3111                         if (preauth) {
3112                                 free (preauth);
3113                         }
3114                         if (got_session) {
3115 fprintf (stderr, "gnutls_deinit (0x%x) at %d\n", session, __LINE__);
3116                                 gnutls_deinit (session);
3117                                 got_session = 0;
3118                         }
3119                         close (cryptfd);
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)) {
3123                                         free (ckn);
3124                                         ckn = NULL;
3125                                 }
3126                         }
3127                         manage_txn_rollback (&cmd->txn);
3128                         assert (pthread_detach (pthread_self ()) == 0);
3129                         return NULL;
3130                 }
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;
3134                 resp->passfd = -1;
3135         }
3136         if (plainfd < 0) {
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");
3139                 if (preauth) {
3140                         free (preauth);
3141                 }
3142                 if (got_session) {
3143 fprintf (stderr, "gnutls_deinit (0x%x) at %d\n", session, __LINE__);
3144                         gnutls_deinit (session);
3145                         got_session = 0;
3146                 }
3147                 close (cryptfd);
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)) {
3151                                 free (ckn);
3152                                 ckn = NULL;
3153                         }
3154                 }
3155                 manage_txn_rollback (&cmd->txn);
3156                 assert (pthread_detach (pthread_self ()) == 0);
3157                 return NULL;
3158         }
3159         //DEFERRED// send_command (replycmd, -1);               // app sent plainfd to us
3160
3161         //
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));
3166         }
3167         if (ckn == NULL) {
3168                 send_error (replycmd, ENOMEM, "Out of memory allocating control key structure");
3169         } else {
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
3179                         if (preauth) {
3180
3181                                 //
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;
3188                                         }
3189 #endif
3190                                 }
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;
3194                                         copied = 0;
3195
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);
3198                                         free (preauth);
3199                                         preauth = NULL;
3200                                         copied = copycat (plainfd, cryptfd, session, detach? -1: cmd->clientfd);
3201                                 } else {
3202                                         tlog (TLOG_COPYCAT, LOG_DEBUG, "Failed to pass on %d remote bytes from anonymous precursor to %d\n", preauthlen, plainfd);
3203                                 }
3204                         } else {
3205                                 copied = copycat (plainfd, cryptfd, session, detach? -1: cmd->clientfd);
3206                         }
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!!!
3217                                 renegotiating = 1;
3218                                 replycmd = NULL; // Bypass all send_XXX()
3219                                 memcpy (&cmd_copy, cmd, sizeof (cmd_copy));
3220                                 cmd = &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);
3228                                 goto renegotiate;
3229                         }
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)) {
3240                                 free (ckn);
3241                         }
3242                         ckn = NULL;
3243 //DEBUG// fprintf (stderr, "Unregistered  control key\n");
3244                 } else {
3245                         send_error (replycmd, ENOENT, "Failed to register control key for TLS connection");
3246                 }
3247         }
3248         if (preauth) {
3249                 free (preauth);
3250                 preauth = NULL;
3251         }
3252         close (plainfd);
3253         close (cryptfd);
3254         if (got_session) {
3255 fprintf (stderr, "gnutls_deinit (0x%x) at %d\n", session, __LINE__);
3256                 gnutls_deinit (session);
3257                 got_session = 0;
3258         }
3259         assert (pthread_detach (pthread_self ()) == 0);
3260         return NULL;
3261 }
3262
3263
3264 /*
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.
3269  */
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);
3273         if (errno != 0) {
3274                 send_error (cmd, ESRCH, "STARTTLS thread refused");
3275                 return;
3276         }
3277 //TODO:TEST// Thread detaches itself before terminating w/o followup
3278 /*
3279         errno = pthread_detach (cmd->handler);
3280         if (errno != 0) {
3281                 pthread_cancel (cmd->handler);
3282                 send_error (cmd, ESRCH, "STARTTLS thread detachment refused");
3283                 return;
3284         }
3285 */
3286 }
3287
3288
3289 /*
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.
3293  */
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;
3299         char **prefixes;
3300         int err = 0;
3301         int gtls_errno = GNUTLS_E_SUCCESS;
3302         struct pioc_prng *prng = &cmd->cmd.pio_data.pioc_prng;
3303         //
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);
3312         if (!err) {
3313                 memcpy (in1, prng->buffer + TLSPOOL_CTLKEYLEN         , in1len);
3314                 if (in2len > 0) {
3315                         memcpy (in2, prng->buffer + TLSPOOL_CTLKEYLEN + in1len, in2len);
3316                 }
3317         }
3318         //  - check the label string
3319         prefixes = tlsprng_label_prefixes;
3320         while ((!err) && (*prefixes)) {
3321                 char *pf = *prefixes++;
3322                 if (strlen (pf) != in1len) {
3323                         continue;
3324                 }
3325                 if (strcmp (pf, in1) != 0) {
3326                         continue;
3327                 }
3328         }
3329         if (*prefixes == NULL) {
3330                 // RFC 5705 defines a private-use prefix "EXPERIMENTAL"
3331                 if ((in1len <= 12) || (strncmp (in1, "EXPERIMENTAL", 12) != 0)) {
3332                         err = 1;
3333                 }
3334         }
3335         //  - check the ctlkey (and ensure it is for TLS)
3336         if (!err) {
3337 //DEBUG// fprintf (stderr, "Hoping to find control key\n");
3338                 ckn = (struct ctlkeynode_tls *) ctlkey_find (prng->buffer, security_tls, cmd->clientfd);
3339         }
3340         //
3341         // Now wipe the PRNG buffer to get rid of any sensitive bytes
3342         memset (prng->buffer, 0, TLSPOOL_PRNGBUFLEN);
3343         //
3344         // If an error occurrend with the command, report it now
3345         if (err) {
3346                 send_error (cmd, EINVAL, "TLS PRNG request invalid");
3347                 // ckn is NULL if err != 0, so no need for ctlkey_unfind()
3348                 return;
3349         }
3350         if (ckn == NULL) {
3351                 send_error (cmd, ENOENT, "Invalid control key");
3352                 return;
3353         }
3354         //
3355         // Now actually invoke the PRNG command in the GnuTLS backend
3356         errno = 0;
3357         E_g2e ("GnuTLS PRNG based on session master key failed",
3358                 gnutls_prf_rfc5705 (ckn->session,
3359                         in1len, in1,
3360                         (in2len >= 0)? in2len: 0, (in2len >= 0) ? in2: NULL,
3361                         prnglen, prng->buffer));
3362         err = err || (errno != 0);
3363         //
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);
3368         //
3369         // Return the outcome to the user
3370         if (err) {
3371                 send_error (cmd, errno? errno: EIO, "PRNG in TLS backend failed");
3372         } else {
3373                 send_command (cmd, -1);
3374         }
3375 }
3376
3377
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.
3382  *
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.
3386  *
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
3389  * cases.
3390  *
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.
3393  */
3394 gtls_error certificate_onthefly (struct command *cmd) {
3395         gtls_error gtls_errno = GNUTLS_E_SUCCESS;
3396         gnutls_x509_crt_t otfcert;
3397         time_t now;
3398         gnutls_x509_subject_alt_name_t altnmtp;
3399         int i;
3400
3401         //
3402         // Sanity checks
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;
3406         }
3407         if (cmd->cmd.pio_data.pioc_starttls.localid [0] == '\0') {
3408                 return GNUTLS_E_NO_CERTIFICATE_FOUND;
3409         }
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;
3414         }
3415         
3416         //
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) {
3421                 return gtls_errno;
3422         }
3423
3424         //
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
3434         time (&now);
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;
3446         } else {
3447                 // localid has the format of a dnsName
3448                 altnmtp = GNUTLS_SAN_DNSNAME;
3449         }
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;
3463                         if (walker) {
3464                                 while (*walker) {
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));
3467                                         walker++;
3468                                 }
3469                         }
3470                         walker = svcusage_registry [i].oids_critical;
3471                         if (walker) {
3472                                 while (*walker) {
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));
3475                                         walker++;
3476                                 }
3477                         }
3478                         break;
3479                 }
3480         }
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...
3489          */
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);
3495
3496         //
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;
3504                 } else {
3505                         if (gtls_errno = GNUTLS_E_SUCCESS) {
3506                                 // Something must be wrong if we receive OK
3507                                 gtls_errno = GNUTLS_E_INVALID_REQUEST;
3508                         }
3509                 }
3510                 E_g2e ("Error while measuring on-the-fly certificate size",
3511                         gtls_errno);
3512         }
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);
3517                 if (ptr == NULL) {
3518                         cmd->lids [LID_TYPE_X509 - LID_TYPE_MIN].size = 0;
3519                         gnutls_x509_crt_deinit (otfcert);
3520                         return GNUTLS_E_MEMORY_ERROR;
3521                 }
3522         }
3523         if (ptr != NULL) {
3524                 size_t restsz;
3525                 cmd->lids [LID_TYPE_X509 - LID_TYPE_MIN].data = ptr;
3526                 * (uint32_t *) ptr = htonl (LID_TYPE_X509 | LID_ROLE_BOTH);
3527                 ptr += 4;
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);
3539 } else {
3540 fprintf (stderr, "DEBUG: otfcert export to PEM failed with %d, gtls_errno already was %d\n", exporterror, gtls_errno);
3541 }
3542         }
3543
3544         //
3545         // Cleanup the allocated and built structures
3546         gnutls_x509_crt_deinit (otfcert);
3547
3548         //
3549         // Return the overall result that might have stopped otf halfway
3550         return gtls_errno;
3551 }
3552