Skip to contentSkip to conversation

settings: Fix a format string

PATCH In review Andrew Zaborowski 3 participants 21 messages Nov 1, 2018 – Nov 2, 2018

lore
Share & tools
lore
#0 lore raw

PATCH 1/11 settings: Fix a format string

The %d conersion specifier is for integers.

---
 ell/settings.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
ell/settings.c +1 -1
index c6cb0ff..e3e8303 100644
@@ -1068,7 +1068,7 @@ LIB_EXPORT bool l_settings_set_double(struct l_settings *settings,
 {
 	L_AUTO_FREE_VAR(char *, buf);
 
-	buf = l_strdup_printf("%d", in);
+	buf = l_strdup_printf("%f", in);
 
 	return l_settings_set_value(settings, group_name, key, buf);
 }
Signature · 1 line
2.19.1
#1 lore raw

PATCH 2/11 Add format string checking to a few declarations

Add the gcc attribute(format(printf)) to function declarations where this may be useful.

---
 ell/dbus.h   | 3 ++-
 ell/string.h | 3 ++-
 ell/util.h   | 6 ++++--
 3 files changed, 8 insertions(+), 4 deletions(-)
ell/dbus.h +2 -1
index a7c08d2..d3af5d7 100644
@@ -118,7 +118,8 @@ struct l_dbus_message *l_dbus_message_new_error_valist(
 struct l_dbus_message *l_dbus_message_new_error(
 					struct l_dbus_message *method_call,
 					const char *name,
-					const char *format, ...);
+					const char *format, ...)
+					__attribute__((format(printf, 3, 4)));
 
 struct l_dbus_message *l_dbus_message_ref(struct l_dbus_message *message);
 void l_dbus_message_unref(struct l_dbus_message *message);
ell/string.h +2 -1
index c947c14..c1948ec 100644
@@ -42,7 +42,8 @@ struct l_string *l_string_append_fixed(struct l_string *dest, const char *src,
 
 void l_string_append_vprintf(struct l_string *dest,
 					const char *format, va_list args);
-void l_string_append_printf(struct l_string *dest, const char *format, ...);
+void l_string_append_printf(struct l_string *dest, const char *format, ...)
+					__attribute__((format(printf, 2, 3)));
 
 struct l_string *l_string_truncate(struct l_string *string, size_t new_size);
 
ell/util.h +4 -2
index 381721f..9fd775e 100644
@@ -258,7 +258,8 @@ static inline void auto_free(void *a)
 
 char *l_strdup(const char *str);
 char *l_strndup(const char *str, size_t max);
-char *l_strdup_printf(const char *format, ...);
+char *l_strdup_printf(const char *format, ...)
+			__attribute__((format(printf, 1, 2)));
 char *l_strdup_vprintf(const char *format, va_list args);
 
 size_t l_strlcpy(char* dst, const char *src, size_t len);
@@ -280,7 +281,8 @@ void l_util_hexdumpv(bool in, const struct iovec *iov, size_t n_iov,
 					l_util_hexdump_func_t function,
 					void *user_data);
 void l_util_debug(l_util_hexdump_func_t function, void *user_data,
-						const char *format, ...);
+						const char *format, ...)
+			__attribute__((format(printf, 3, 4)));
 
 const char *l_util_get_debugfs_path(void);
 
Signature · 1 line
2.19.1
#2 lore raw

PATCH 3/11 tls: Add debug logging API

In reply to Andrew Zaborowski

Add a debug logging API similar to that in dbus.h and genl.h. A lot of messages are added to report on the negotiation progress (Handshake, Alert and ChangeCipherSpec messages) and all the possible error situations. Especially configuration errors -- the most common errors -- should be clear when looking at the logs.

No Application Data messages (plaintext) or raw TLS record contents (encrypted) are logged because this can be easily done by the user code and could add a flood of messages that would make it actually harder to solve TLS issues.

---
 ell/ell.sym       |   1 +
 ell/tls-private.h |  24 +++
 ell/tls-record.c  |  66 ++++---
 ell/tls.c         | 427 +++++++++++++++++++++++++++++++++++-----------
 ell/tls.h         |   6 +
 5 files changed, 400 insertions(+), 124 deletions(-)
ell/ell.sym +1 -0
index f7b17b9..614bc93 100644
@@ -413,6 +413,7 @@ global:
 	l_tls_set_cacert;
 	l_tls_set_auth_data;
 	l_tls_alert_to_str;
+	l_tls_set_debug;
 	/* uintset */
 	l_uintset_new_from_range;
 	l_uintset_new;
ell/tls-private.h +24 -0
index 8cf5be9..4f680a0 100644
@@ -48,6 +48,7 @@ struct tls_hash_algorithm {
 	uint8_t tls_id;
 	enum l_checksum_type l_id;
 	size_t length;
+	const char *name;
 };
 
 typedef bool (*tls_get_hash_t)(struct l_tls *tls, uint8_t tls_id,
@@ -89,6 +90,7 @@ struct tls_cipher_suite {
 
 struct tls_compression_method {
 	int id;
+	const char *name;
 };
 
 enum tls_handshake_state {
@@ -136,6 +138,9 @@ struct l_tls {
 	l_tls_ready_cb_t ready_handle;
 	l_tls_disconnect_cb_t disconnected;
 	void *user_data;
+	l_tls_debug_cb_t debug_handler;
+	l_tls_destroy_cb_t debug_destroy;
+	void *debug_data;
 
 	char *ca_cert_path;
 	char *cert_path;
@@ -254,3 +259,22 @@ void tls_prf_get_bytes(struct l_tls *tls,
 				const char *label,
 				const void *seed, size_t seed_len,
 				uint8_t *buf, size_t len);
+
+#define TLS_DEBUG(fmt, args...)	\
+	l_util_debug(tls->debug_handler, tls->debug_data, "%s:%i " fmt,	\
+			__func__, __LINE__, ## args)
+#define TLS_SET_STATE(new_state)	\
+	do {	\
+		TLS_DEBUG("New state %s",	\
+				tls_handshake_state_to_str(new_state));	\
+		tls->state = new_state;	\
+	} while (0)
+#define TLS_DISCONNECT(desc, local_desc, fmt, args...)	\
+	do {	\
+		TLS_DEBUG("Disconnect desc=%s local-desc=%s reason=" fmt,\
+				l_tls_alert_to_str(desc),	\
+				l_tls_alert_to_str(local_desc), ## args);\
+		tls_disconnect(tls, desc, local_desc);	\
+	} while (0)
+
+const char *tls_handshake_state_to_str(enum tls_handshake_state state);
ell/tls-record.c +42 -24

161 lines not on this page · raw message

ell/tls.c +327 -100

985 lines not on this page · raw message

ell/tls.h +6 -0
index 9ab53fa..893fd63 100644
@@ -60,6 +60,9 @@ typedef void (*l_tls_write_cb_t)(const uint8_t *data, size_t len,
 typedef void (*l_tls_ready_cb_t)(const char *peer_identity, void *user_data);
 typedef void (*l_tls_disconnect_cb_t)(enum l_tls_alert_desc reason,
 					bool remote, void *user_data);
+typedef void (*l_tls_debug_cb_t)(const char *str, void *user_data);
+typedef void (*l_tls_destroy_cb_t)(void *user_data);
+
 
 /*
  * app_data_handler gets called with newly received decrypted data.
@@ -110,6 +113,9 @@ bool l_tls_prf_get_bytes(struct l_tls *tls,
 				size_t hash_len, bool use_master_secret,
 				const char *label, uint8_t *buf, size_t len);
 
+bool l_tls_set_debug(struct l_tls *tls, l_tls_debug_cb_t function,
+			void *user_data, l_tls_destroy_cb_t destroy);
+
 #ifdef __cplusplus
 }
 #endif
Signature · 1 line
2.19.1
#3 lore raw

PATCH 4/11 pem: Add l_pem_load_certificate_list utility

In reply to Andrew Zaborowski

l_pem_load_certificate_list loads all the certificates in a file with multiple concatenated PEM structures. This could also be done previously by calling l_pem_load_file with consecutive index values until it returned an error, this is a faster way to load all of the certificates.

---
 ell/ell.sym |  1 +
 ell/pem.c   | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++--
 ell/pem.h   |  8 +++++
 3 files changed, 90 insertions(+), 3 deletions(-)
ell/ell.sym +1 -0
index 614bc93..2b1d3d7 100644
@@ -337,6 +337,7 @@ global:
 	l_pem_load_buffer;
 	l_pem_load_file;
 	l_pem_load_certificate;
+	l_pem_load_certificate_list;
 	l_pem_load_private_key;
 	/* pkcs5 */
 	l_pkcs5_pbkdf1;
ell/pem.c +81 -3

120 lines not on this page · raw message

ell/pem.h +8 -0
index 93282a3..9cead5c 100644
@@ -27,12 +27,20 @@
 extern "C" {
 #endif
 
+struct l_queue;
+
+struct l_pem_list_element {
+	uint8_t *content;
+	size_t len;
+};
+
 uint8_t *l_pem_load_buffer(const uint8_t *buf, size_t buf_len,
 				int index, char **type_label, size_t *out_len);
 uint8_t *l_pem_load_file(const char *filename, int index,
 				char **type_label, size_t *len);
 
 uint8_t *l_pem_load_certificate(const char *filename, size_t *len);
+struct l_queue *l_pem_load_certificate_list(const char *filename);
 
 uint8_t *l_pem_load_private_key(const char *filename, const char *passphrase,
 				bool *encrypted, size_t *len);
Signature · 1 line
2.19.1
#7 lore raw

PATCH 5/11 tls: Support loading multiple root CAs

In reply to Andrew Zaborowski

If a file with multiple concatenated certificates is supplied to set_auth_data, load all of them and verify received certificate chains aginst any of them instead of just the first one. This is also what wpa_supplicant does for files supplied with the ca_cert= setting and it's actually useful. Some enterprise CAs have multiple root certificates and provision clients with a file that contains all of them concatenated and it does happen that they switch from a certificate chain using one root to a new chain with a different root for their wifi in which case our network config files break while wpa_supplicant configs keep working.

Also simplify tls_cert_verify_certchain slightly.

---
 ell/tls-private.h |   3 +-
 ell/tls.c         | 137 ++++++++++++++++++++++++++++++++--------------
 ell/tls.h         |   2 +-
 3 files changed, 100 insertions(+), 42 deletions(-)
ell/tls-private.h +2 -1
index 4f680a0..95b8c65 100644
@@ -240,6 +240,7 @@ enum tls_cert_key_type {
 };
 
 struct tls_cert *tls_cert_load_file(const char *filename);
+struct l_queue *tls_cert_list_load_file(const char *filename);
 int tls_cert_from_certificate_list(const void *data, size_t len,
 					struct tls_cert **out_certchain);
 
@@ -247,7 +248,7 @@ bool tls_cert_find_certchain(struct tls_cert *cert,
 				const char *cacert_filename);
 
 bool tls_cert_verify_certchain(struct tls_cert *certchain,
-				struct tls_cert *ca_cert);
+				struct l_queue *ca_certs);
 
 void tls_cert_free_certchain(struct tls_cert *cert);
 
ell/tls.c +97 -40

220 lines not on this page · raw message

ell/tls.h +1 -1
index 893fd63..8eec360 100644
@@ -86,7 +86,7 @@ void l_tls_write(struct l_tls *tls, const uint8_t *data, size_t len);
 /* Submit TLS payload from underlying transport to be decrypted */
 void l_tls_handle_rx(struct l_tls *tls, const uint8_t *data, size_t len);
 
-/* If peer is to be authenticated, supply the CA certificate */
+/* If peer is to be authenticated, supply the CA certificate(s) */
 void l_tls_set_cacert(struct l_tls *tls, const char *ca_cert_path);
 
 /*
Signature · 1 line
2.19.1
#9 lore raw

PATCH 6/11 tools: Update tls_cert_verify_certchain parameters

In reply to Andrew Zaborowski
---
 tools/certchain-verify.c | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)
tools/certchain-verify.c +7 -7
index 1800f68..9bd46b1 100644
@@ -87,7 +87,7 @@ static void usage(const char *bin)
 	printf("%s - TLS certificate chain verification utility\n\n", bin);
 
 	printf("Usage: %s [options] <ca_cert file> <raw certificates file>\n"
-		"  <ca_cert file> - local CA Certificate to validate against\n"
+		"  <ca_cert file> - local CA Certificate(s) to validate against\n"
 		"  <raw certificates file> - Certificates obtained from PCAP\n"
 		"  --help\n\n", bin);
 }
@@ -96,7 +96,7 @@ int main(int argc, char *argv[])
 {
 	int status = EXIT_FAILURE;
 	struct tls_cert *certchain;
-	struct tls_cert *ca_cert;
+	struct l_queue *ca_certs;
 	int err;
 
 	if (argc != 3) {
@@ -116,13 +116,13 @@ int main(int argc, char *argv[])
 		goto done;
 	}
 
-	ca_cert = tls_cert_load_file(argv[1]);
-	if (!ca_cert) {
-		fprintf(stderr, "Unable to load CA certifiate\n");
+	ca_certs = tls_cert_list_load_file(argv[1]);
+	if (!ca_certs) {
+		fprintf(stderr, "Unable to load CA certifiates\n");
 		goto free_certchain;
 	}
 
-	if (!tls_cert_verify_certchain(certchain, ca_cert)) {
+	if (!tls_cert_verify_certchain(certchain, ca_certs)) {
 		fprintf(stderr, "Verification failed\n");
 		goto free_cacert;
 	}
@@ -131,7 +131,7 @@ int main(int argc, char *argv[])
 	status = EXIT_SUCCESS;
 
 free_cacert:
-	l_free(ca_cert);
+	l_queue_destroy(ca_certs, l_free);
 free_certchain:
 	tls_cert_free_certchain(certchain);
 done:
Signature · 1 line
2.19.1
#10 lore raw

PATCH 7/11 unit: Update tls_cert_verify_certchain parameters

In reply to Andrew Zaborowski
---
 unit/test-tls.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
unit/test-tls.c +6 -6
index d969ee7..75f36f0 100644
@@ -214,16 +214,16 @@ static void test_tls12_prf(const void *data)
 static void test_certificates(const void *data)
 {
 	struct tls_cert *cert;
-	struct tls_cert *cacert;
-	struct tls_cert *wrongca;
+	struct l_queue *cacert;
+	struct l_queue *wrongca;
 
 	cert = tls_cert_load_file(CERTDIR "cert-server.pem");
 	assert(cert);
 
-	cacert = tls_cert_load_file(CERTDIR "cert-ca.pem");
+	cacert = tls_cert_list_load_file(CERTDIR "cert-ca.pem");
 	assert(cacert);
 
-	wrongca = tls_cert_load_file(CERTDIR "cert-intca.pem");
+	wrongca = tls_cert_list_load_file(CERTDIR "cert-intca.pem");
 	assert(wrongca);
 
 	assert(!tls_cert_verify_certchain(cert, wrongca));
@@ -233,8 +233,8 @@ static void test_certificates(const void *data)
 	assert(tls_cert_verify_certchain(cert, NULL));
 
 	l_free(cert);
-	l_free(cacert);
-	l_free(wrongca);
+	l_queue_destroy(cacert, l_free);
+	l_queue_destroy(wrongca, l_free);
 }
 
 struct tls_conn_test {
Signature · 1 line
2.19.1
#11 lore raw

PATCH 8/11 tls: Stricter certificate chain verification

In reply to Andrew Zaborowski

Rewrite tls_cert_verify_certchain to fix a long standing issue where it didn't verify that each certificate in the chain was trusted by the next one. Since certificates were only being added to the two keyrings and never removed the order in the chain was not being verified. Now use a single ring and remove the previously added certificates from it once they've been used to show that the next certificate was signed with one of them. Add lots of comments.

---
 ell/tls.c | 206 +++++++++++++++++++++++++++++++++---------------------
 1 file changed, 125 insertions(+), 81 deletions(-)
ell/tls.c +125 -81
index fbbc1bf..7f42240 100644
@@ -2687,27 +2687,99 @@ static const struct pkcs1_encryption_oid {
 	},
 };
 
+static struct l_key *tls_cert_verify_root(struct l_key *key,
+						struct l_keyring *ring,
+						struct l_queue *roots)
+{
+	const struct l_queue_entry *entry;
+	unsigned int i, n = l_queue_length(roots);
+	struct l_key *root_keys[n];
+	bool success = true;
+
+	/*
+	 * Check that @key is trusted by one of @roots by linking it
+	 * to a restricted ring containing only the roots.  If successful
+	 * return @key leaving only @key in the keyring.
+	 */
+
+	for (entry = l_queue_get_entries(roots), i = 0; i < n;
+			entry = entry->next, i++) {
+		const struct tls_cert *root = entry->data;
+
+		root_keys[i] = l_key_new(L_KEY_RSA, root->asn1, root->size);
+		if (!root_keys[i] || !l_keyring_link(ring, root_keys[i]))
+			success = false;
+	}
+
+	if (!l_keyring_restrict(ring, L_KEYRING_RESTRICT_ASYM_CHAIN, NULL) ||
+			!l_keyring_link(ring, key))
+		success = false;
+
+	for (i = 0; i < n; i++)
+		l_key_free(root_keys[i]);
+
+	if (success)
+		return key;
+
+	l_key_free(key);
+	return NULL;
+}
+
 static void tls_key_cleanup(struct l_key **p)
 {
-	l_key_free_norevoke(*p);
+	l_key_free(*p);
 }
 
-static bool tls_cert_link(struct tls_cert *cert, struct l_keyring *ring)
+static struct l_key *tls_cert_verify_with_keyring(struct tls_cert *cert,
+							struct l_keyring *ring,
+							struct l_queue *roots)
 {
-	L_AUTO_CLEANUP_VAR(struct l_key *, key, tls_key_cleanup) = NULL;
+	struct l_key *key;
+	const struct l_queue_entry *entry;
 
-	key = l_key_new(L_KEY_RSA, cert->asn1, cert->size);
+	if (cert->issuer) {
+		L_AUTO_CLEANUP_VAR(struct l_key *, trusted, tls_key_cleanup);
 
-	return key && l_keyring_link(ring, key);
-}
+		/*
+		 * Since we have the issuer, this is neither the root
+		 * certificate nor the closest-to-the-root certificate in
+		 * this chain, which may not contain the actual root.  Call
+		 * ourselves to verify that the chain is valid down to this
+		 * certificate's issuer.
+		 */
+		trusted = tls_cert_verify_with_keyring(cert->issuer,
+							ring, roots);
+		if (!trusted)
+			return NULL;
 
-static bool tls_cert_verify_with_keyring(struct tls_cert *cert,
-						struct l_keyring *ring,
-						struct l_queue *roots,
-						struct l_keyring *trusted)
-{
-	if (!cert)
-		return true;
+		/*
+		 * The issuer is trusted, at this point we only have to
+		 * verify the issuer trusts this certificate and we will
+		 * know the whole chain is trusted.  After the call @ring
+		 * conveniently contains only the issuer certificate and
+		 * is restricted so that only certificates trusted by it
+		 * can be linked.
+		 */
+		key = l_key_new(L_KEY_RSA, cert->asn1, cert->size);
+		if (!key)
+			return NULL;
+
+		if (!l_keyring_link(ring, key))
+			goto free_key;
+
+		/*
+		 * The chain is valid down to @cert and @ring now
+		 * contains both the @trusted and @key.  However @trusted
+		 * is autofreed and will be revoked by l_key_free so
+		 * the caller will get a ring with only @key in it and
+		 * can try to link further certificates and unlink @key.
+		 */
+		return key;
+	}
+
+	key = l_key_new(L_KEY_RSA, cert->asn1, cert->size);
+	if (!key)
+		return NULL;
 
 	/*
 	 * RFC5246 7.4.2:
@@ -2717,51 +2789,47 @@ static bool tls_cert_verify_with_keyring(struct tls_cert *cert,
 	 * the chain, under the assumption that the remote end must
 	 * already possess it in order to validate it in any case."
 	 *
-	 * This is an optimization to skip adding the root cert if
-	 * it's already in the trusted keyring.  It also happens to
-	 * work around a kernel issue preventing self-signed certificates
-	 * missing the AKID extension from being linked.
-	 *
-	 * If 'roots' were supplied we assume the keyring is already
-	 * restricted.
+	 * This is either the root cert or the closest-to-the-root
+	 * certificate in the chain.  If @roots were supplied we have
+	 * to verify it is either one of the roots or is trusted by one
+	 * of the roots.  If @roots is NULL, we only have to link it
+	 * to the keyring and restrict the keyring.
 	 */
-	if (!cert->issuer && roots) {
-		const struct l_queue_entry *entry;
+	if (!roots)
+		goto link_and_restrict;
 
-		for (entry = l_queue_get_entries(roots); entry;
-				entry = entry->next) {
-			const struct tls_cert *root = entry->data;
+	/*
+	 * This is an optimization to skip verifying the root cert if
+	 * it's identical to one of the supplied roots.  If it is, we just
+	 * have to add it to the keyring and restrict the keyring.
+	 * This also happens to work around a kernel issue preventing
+	 * self-signed certificates missing the AKID extension from being
+	 * linked.
+	 */
+	for (entry = l_queue_get_entries(roots); entry;
+			entry = entry->next) {
+		const struct tls_cert *root = entry->data;
 
-			if (cert->size == root->size && !memcmp(cert->asn1,
-						root->asn1, root->size))
-				return true;
-		}
+		if (cert->size == root->size && !memcmp(cert->asn1,
+					root->asn1, root->size))
+			goto link_and_restrict;
 	}
 
-	if (tls_cert_verify_with_keyring(cert->issuer, ring, roots, trusted)) {
-		if (!tls_cert_link(cert, ring))
-			return false;
+	return tls_cert_verify_root(key, ring, roots);
 
-		if (trusted || cert->issuer)
-			return true;
+link_and_restrict:
+	if (!l_keyring_link(ring, key))
+		goto free_key;
 
-		/*
-		 * If execution reaches this point, it's known that:
-		 *  * No trusted root key was supplied, so the chain is only
-		 *    being checked against its own root
-		 *  * The keyring 'ring' is not restricted yet
-		 *  * The chain's root cert was just linked in to the
-		 *    previously empty keyring 'ring'.
-		 *
-		 *  By restricting 'ring' now, the rest of the certs in
-		 *  the chain will have their signature validated using 'key'
-		 *  as the root.
-		 */
-		return l_keyring_restrict(ring,	L_KEYRING_RESTRICT_ASYM_CHAIN,
-						trusted);
-	}
+	if (!l_keyring_restrict(ring, L_KEYRING_RESTRICT_ASYM_CHAIN,
+				NULL))
+		goto free_key;
 
-	return false;
+	return key;
+
+free_key:
+	l_key_free(key);
+	return NULL;
 }
 
 static void tls_keyring_cleanup(struct l_keyring **p)
@@ -2772,43 +2840,19 @@ static void tls_keyring_cleanup(struct l_keyring **p)
 bool tls_cert_verify_certchain(struct tls_cert *certchain,
 				struct l_queue *ca_certs)
 {
-	L_AUTO_CLEANUP_VAR(struct l_keyring *, ca_ring, tls_keyring_cleanup);
 	L_AUTO_CLEANUP_VAR(struct l_keyring *, verify_ring,
-				tls_keyring_cleanup);
+				tls_keyring_cleanup) = l_keyring_new();
+	struct l_key *trusted;
 
-	ca_ring = NULL;
-
-	verify_ring = l_keyring_new();
 	if (!verify_ring)
 		return false;
 
-	/*
-	 * If CA cert(s) were supplied, restrict verify_ring now so
-	 * everything else in certchain is validated against the CA(s).
-	 * Otherwise, verify_ring will be restricted after the root of
-	 * certchain is added to verify_ring by
-	 * tls_cert_verify_with_keyring().
-	 */
-	if (ca_certs) {
-		const struct l_queue_entry *entry;
-
-		ca_ring = l_keyring_new();
-		if (!ca_ring)
-			return false;
-
-		for (entry = l_queue_get_entries(ca_certs); entry;
-				entry = entry->next)
-			if (!tls_cert_link(entry->data, ca_ring))
-				return false;
-
-		if (!l_keyring_restrict(verify_ring,
-					L_KEYRING_RESTRICT_ASYM_CHAIN,
-					ca_ring))
-			return false;
-	}
+	trusted = tls_cert_verify_with_keyring(certchain, verify_ring, ca_certs);
+	if (!trusted)
+		return false;
 
-	return tls_cert_verify_with_keyring(certchain, verify_ring, ca_certs,
-						ca_ring);
+	l_key_free(trusted);
+	return true;
 }
 
 void tls_cert_free_certchain(struct tls_cert *cert)
Signature · 1 line
2.19.1
#16 lore raw

PATCH 9/11 tls: Support loading certificate chains from file

In reply to Andrew Zaborowski

When loading the file supplied with l_tls_set_auth_data to be sent as Server Certificate or Client Certificate, allow for the possibility of loading a chain of certificates instead of just one if the file contains multiple concatenated PEM certificates, ordered from the end-entity to the CA. The chain has to end with one of the CA certs set through l_tls_set_cacert or a cert directly signed by one of them, if l_tls_set_cacert was called.

---
 ell/tls.c | 69 +++++++++++++++++++++++++++++++++++++++++--------------
 1 file changed, 52 insertions(+), 17 deletions(-)
ell/tls.c +52 -17
index 7f42240..0aa10e7 100644
@@ -754,7 +754,7 @@ static bool tls_send_certificate(struct l_tls *tls)
 
 	if (tls->server && !cert) {
 		TLS_DISCONNECT(TLS_ALERT_INTERNAL_ERROR, TLS_ALERT_BAD_CERT,
-				"Loading server certificate %s failed",
+				"Loading server certificate chain %s failed",
 				tls->cert_path);
 		return false;
 	}
@@ -828,7 +828,7 @@ static bool tls_send_certificate(struct l_tls *tls)
 	if (cert)
 		tls->cert_sent = true;
 
-	l_free(cert);
+	tls_cert_free_certchain(cert);
 
 	return true;
 }
@@ -2570,27 +2570,41 @@ const char *tls_handshake_state_to_str(enum tls_handshake_state state)
 
 struct tls_cert *tls_cert_load_file(const char *filename)
 {
-	uint8_t *der;
-	size_t len;
-	struct tls_cert *cert;
+	struct l_queue *pem_list;
+	struct tls_cert *chain = NULL;
+	struct tls_cert **root = &chain;
+	bool error = false;
 
-	der = l_pem_load_certificate(filename, &len);
-	if (!der)
+	pem_list = l_pem_load_certificate_list(filename);
+	if (!pem_list)
 		return NULL;
 
-	if (!len || der[0] != ASN1_ID_SEQUENCE) {
-		l_free(der);
-		return NULL;
+	while (!l_queue_isempty(pem_list)) {
+		struct tls_cert *cert;
+		struct l_pem_list_element *elem = l_queue_pop_head(pem_list);
+		uint8_t *der = elem->content;
+
+		if (!elem->len || der[0] != ASN1_ID_SEQUENCE)
+			error = true;
+
+		cert = l_malloc(sizeof(struct tls_cert) + elem->len);
+		cert->size = elem->len;
+		cert->issuer = NULL;
+		memcpy(cert->asn1, der, cert->size);
+		l_free(elem->content);
+		l_free(elem);
+
+		*root = cert;
+		root = &cert->issuer;
 	}
 
-	cert = l_malloc(sizeof(struct tls_cert) + len);
-	cert->size = len;
-	cert->issuer = NULL;
-	memcpy(cert->asn1, der, len);
+	l_queue_destroy(pem_list, NULL);
 
-	l_free(der);
+	if (!error)
+		return chain;
 
-	return cert;
+	tls_cert_free_certchain(chain);
+	return NULL;
 }
 
 struct l_queue *tls_cert_list_load_file(const char *filename)
@@ -2674,7 +2688,28 @@ decode_error:
 bool tls_cert_find_certchain(struct tls_cert *cert,
 				const char *cacert_filename)
 {
-	return true;
+	struct l_queue *ca_certs = NULL;
+	bool valid;
+
+	/* Nothing to do if no CA certificates supplied */
+	if (!cacert_filename)
+		return true;
+
+	ca_certs = tls_cert_list_load_file(cacert_filename);
+	if (!ca_certs)
+		return false;
+
+	/*
+	 * Also nothing to do if the user already supplied a working
+	 * certificate chain.
+	 */
+	valid = tls_cert_verify_certchain(cert, ca_certs);
+	l_queue_destroy(ca_certs, l_free);
+	if (valid)
+		return true;
+
+	/* Actual search for a chain to the CA cert is unimplemented, fail */
+	return false;
 }
 
 static const struct pkcs1_encryption_oid {
Signature · 1 line
2.19.1
#18 lore raw

PATCH 10/11 tls: Propagate errors to l_tls_prf_get_bytes

In reply to Andrew Zaborowski

Add bool return types to tls_prf_get_bytes, tls10_prf, tls12_prf so that l_new_checksum errors can be reported.

---
 ell/tls-private.h |  6 +++---
 ell/tls.c         | 36 +++++++++++++++++++++++-------------
 2 files changed, 26 insertions(+), 16 deletions(-)
ell/tls-private.h +3 -3
index 95b8c65..d71a3bb 100644
@@ -207,12 +207,12 @@ struct l_tls {
 	bool ready;
 };
 
-void tls10_prf(const void *secret, size_t secret_len,
+bool tls10_prf(const void *secret, size_t secret_len,
 		const char *label,
 		const void *seed, size_t seed_len,
 		uint8_t *out, size_t out_len);
 
-void tls12_prf(enum l_checksum_type type, size_t hash_len,
+bool tls12_prf(enum l_checksum_type type, size_t hash_len,
 		const void *secret, size_t secret_len,
 		const char *label,
 		const void *seed, size_t seed_len,
@@ -254,7 +254,7 @@ void tls_cert_free_certchain(struct tls_cert *cert);
 
 enum tls_cert_key_type tls_cert_get_pubkey_type(struct tls_cert *cert);
 
-void tls_prf_get_bytes(struct l_tls *tls,
+bool tls_prf_get_bytes(struct l_tls *tls,
 				enum l_checksum_type type, size_t hash_len,
 				const void *secret, size_t secret_len,
 				const char *label,
ell/tls.c +23 -13
index 0aa10e7..7420772 100644
@@ -40,7 +40,7 @@
 #include "asn1-private.h"
 #include "queue.h"
 
-void tls10_prf(const void *secret, size_t secret_len,
+bool tls10_prf(const void *secret, size_t secret_len,
 		const char *label,
 		const void *seed, size_t seed_len,
 		uint8_t *out, size_t out_len)
@@ -59,24 +59,28 @@ void tls10_prf(const void *secret, size_t secret_len,
 	 * the first byte of S2.
 	 */
 
-	tls12_prf(L_CHECKSUM_MD5, 16,
+	if (!tls12_prf(L_CHECKSUM_MD5, 16,
 			secret, l_s1,
 			label, seed, seed_len,
-			out, out_len);
+			out, out_len))
+		return false;
 
 	if (secret_len > 0)
 		secret += secret_len - l_s1;
 
-	tls12_prf(L_CHECKSUM_SHA1, 20,
+	if (!tls12_prf(L_CHECKSUM_SHA1, 20,
 			secret, l_s1,
 			label, seed, seed_len,
-			p_hash2, out_len);
+			p_hash2, out_len))
+		return false;
 
 	for (i = 0; i < out_len; i++)
 		out[i] ^= p_hash2[i];
+
+	return true;
 }
 
-void tls12_prf(enum l_checksum_type type, size_t hash_len,
+bool tls12_prf(enum l_checksum_type type, size_t hash_len,
 		const void *secret, size_t secret_len,
 		const char *label,
 		const void *seed, size_t seed_len,
@@ -86,6 +90,9 @@ void tls12_prf(enum l_checksum_type type, size_t hash_len,
 	size_t a_len, chunk_len, prfseed_len = strlen(label) + seed_len;
 	uint8_t a[128], prfseed[prfseed_len];
 
+	if (!hmac)
+		return false;
+
 	/* Generate the hash seed or A(0) as label + seed */
 	memcpy(prfseed, label, strlen(label));
 	memcpy(prfseed + strlen(label), seed, seed_len);
@@ -112,9 +119,10 @@ void tls12_prf(enum l_checksum_type type, size_t hash_len,
 	}
 
 	l_checksum_free(hmac);
+	return true;
 }
 
-void tls_prf_get_bytes(struct l_tls *tls,
+bool tls_prf_get_bytes(struct l_tls *tls,
 				enum l_checksum_type type, size_t hash_len,
 				const void *secret, size_t secret_len,
 				const char *label,
@@ -122,10 +130,11 @@ void tls_prf_get_bytes(struct l_tls *tls,
 				uint8_t *buf, size_t len)
 {
 	if (tls->negotiated_version >= TLS_V12)
-		tls12_prf(type, hash_len, secret, secret_len, label,
-				seed, seed_len, buf, len);
+		return tls12_prf(type, hash_len, secret, secret_len, label,
+					seed, seed_len, buf, len);
 	else
-		tls10_prf(secret, secret_len, label, seed, seed_len, buf, len);
+		return tls10_prf(secret, secret_len, label,
+					seed, seed_len, buf, len);
 }
 
 LIB_EXPORT bool l_tls_prf_get_bytes(struct l_tls *tls,
@@ -134,6 +143,7 @@ LIB_EXPORT bool l_tls_prf_get_bytes(struct l_tls *tls,
 				const char *label, uint8_t *buf, size_t len)
 {
 	uint8_t seed[64];
+	bool r;
 
 	if (unlikely(!tls))
 		return false;
@@ -142,16 +152,16 @@ LIB_EXPORT bool l_tls_prf_get_bytes(struct l_tls *tls,
 	memcpy(seed + 32, tls->pending.server_random, 32);
 
 	if (use_master_secret)
-		tls_prf_get_bytes(tls, type, hash_len,
+		r = tls_prf_get_bytes(tls, type, hash_len,
 						tls->pending.master_secret, 48,
 						label, seed, 64, buf, len);
 	else
-		tls_prf_get_bytes(tls, type, hash_len, "", 0,
+		r = tls_prf_get_bytes(tls, type, hash_len, "", 0,
 						label, seed, 64, buf, len);
 
 	memset(seed, 0, 64);
 
-	return true;
+	return r;
 }
 
 static void tls_write_random(uint8_t *buf)
Signature · 1 line
2.19.1
#19 lore raw

PATCH 11/11 unit: More TLS certificate tests

In reply to Andrew Zaborowski

Add a few more certificate chain checks including some using tls_cert_list_load_file and the stricter tls_cert_verify_certchain.

---
 unit/test-tls.c | 39 ++++++++++++++++++++++++++++++++++++++-
 1 file changed, 38 insertions(+), 1 deletion(-)
unit/test-tls.c +38 -1
index 75f36f0..a134125 100644
@@ -216,6 +216,9 @@ static void test_certificates(const void *data)
 	struct tls_cert *cert;
 	struct l_queue *cacert;
 	struct l_queue *wrongca;
+	struct l_queue *twocas;
+	struct tls_cert *chain;
+	struct tls_cert *chain2;
 
 	cert = tls_cert_load_file(CERTDIR "cert-server.pem");
 	assert(cert);
@@ -226,15 +229,49 @@ static void test_certificates(const void *data)
 	wrongca = tls_cert_list_load_file(CERTDIR "cert-intca.pem");
 	assert(wrongca);
 
+	twocas = tls_cert_list_load_file(CERTDIR "cert-chain.pem");
+	assert(wrongca);
+
 	assert(!tls_cert_verify_certchain(cert, wrongca));
 
 	assert(tls_cert_verify_certchain(cert, cacert));
 
 	assert(tls_cert_verify_certchain(cert, NULL));
 
-	l_free(cert);
+	assert(tls_cert_verify_certchain(cert, twocas));
+
+	chain = tls_cert_load_file(CERTDIR "cert-server.pem");
+	assert(chain);
+	chain->issuer = tls_cert_load_file(CERTDIR "cert-entity-int.pem");
+	assert(chain->issuer);
+	chain->issuer->issuer = tls_cert_load_file(CERTDIR "cert-intca.pem");
+	assert(chain->issuer->issuer);
+	chain->issuer->issuer->issuer =
+		tls_cert_load_file(CERTDIR "cert-ca.pem");
+	assert(chain->issuer->issuer->issuer);
+	assert(tls_cert_verify_certchain(chain->issuer, cacert));
+	assert(tls_cert_verify_certchain(chain->issuer, NULL));
+	assert(!tls_cert_verify_certchain(chain->issuer, wrongca));
+	assert(tls_cert_verify_certchain(chain->issuer, twocas));
+	assert(!tls_cert_verify_certchain(chain, cacert));
+	assert(!tls_cert_verify_certchain(chain, NULL));
+	assert(!tls_cert_verify_certchain(chain, twocas));
+
+	chain2 = tls_cert_load_file(CERTDIR "cert-chain.pem");
+	assert(chain2);
+	assert(chain2->issuer);
+	assert(!chain2->issuer->issuer);
+	assert(tls_cert_verify_certchain(chain2, cacert));
+	assert(tls_cert_verify_certchain(chain2, NULL));
+	assert(!tls_cert_verify_certchain(chain2, wrongca));
+	assert(tls_cert_verify_certchain(chain2, twocas));
+
+	tls_cert_free_certchain(cert);
+	tls_cert_free_certchain(chain);
+	tls_cert_free_certchain(chain2);
 	l_queue_destroy(cacert, l_free);
 	l_queue_destroy(wrongca, l_free);
+	l_queue_destroy(twocas, l_free);
 }
 
 struct tls_conn_test {
Signature · 1 line
2.19.1
#20 lore raw
In reply to Andrew Zaborowski

Hi Andrew,

Quoted 5 lines · Andrew Zaborowski

The %d conersion specifier is for integers.

---
  ell/settings.c | 2 +-
  1 file changed, 1 insertion(+), 1 deletion(-)

Patches 1-3 applied, thanks.

Regards,
-Denis

#4 lore raw

Re: [PATCH 04/11] pem: Add l_pem_load_certificate_list utility

In reply to Andrew Zaborowski

Hi Andrew,

Quoted 11 lines · Andrew Zaborowski

l_pem_load_certificate_list loads all the certificates in a file with multiple concatenated PEM structures. This could also be done previously by calling l_pem_load_file with consecutive index values until it returned an error, this is a faster way to load all of the certificates.

---
  ell/ell.sym |  1 +
  ell/pem.c   | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++--
  ell/pem.h   |  8 +++++
  3 files changed, 90 insertions(+), 3 deletions(-)

ell/pem.c LIB_EXPORT uint8_t *l_pem_load_certificate(const char *filename, size_t *len) · line 247

Quoted 7 lines
ell/pem.c +7 -0
+static void pem_element_free(void *data)
+{
+	struct l_pem_list_element *element = data;
+
+	l_free(element->content);
+	l_free(element);
+}

So I see that we duplicate this free function a bunch of times in the later commits in this series. Perhaps we should bite the bullet and make l_pem an actual first class object with some getters and a destructor.

E.g.

const void *l_pem_get_content(struct l_pem *);
size_t l_pem_get_content_length(struct l_pem *);

void l_pem_free(struct l_pem *);

and possibly:
enum l_pem_type l_pem_get_type(struct l_pem *);

Quoted 27 lines
ell/pem.c +27 -0
+
+LIB_EXPORT struct l_queue *l_pem_load_certificate_list(const char *filename)
+{
+	int fd;
+	struct stat st;
+	uint8_t *data;
+	size_t start = 0;
+	struct l_queue *result = NULL;
+
+	fd = open(filename, O_RDONLY);
+	if (fd < 0)
+		return NULL;
+
+	if (fstat(fd, &st) < 0) {
+		close(fd);
+
+		return NULL;
+	}
+
+	data = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
+	if (data == MAP_FAILED) {
+		close(fd);
+
+		return NULL;
+	}
+
+	while (1) {

ell/pem.c LIB_EXPORT uint8_t *l_pem_load_certificate(const char *filename, size_t *len) · line 284

Quoted 10 lines
ell/pem.c +10 -0
+		uint8_t *certificate;
+		size_t len;
+		char *label;
+		struct l_pem_list_element *element;
+		const uint8_t *end;
+
+		certificate = pem_load_buffer(data + start, st.st_size - start, 0,
+						&label, &len, &end);
+		if (!certificate)
+			goto done;

I'm not so sure about this. pem_load_buffer can fail for base64 decode failure reasons. So I wouldn't think that you can assume that a failure means EOF + success.

ell/pem.c LIB_EXPORT uint8_t *l_pem_load_certificate(const char *filename, size_t *len) · line 292

Quoted 8 lines
ell/pem.c +8 -0
+
+		if (strcmp(label, "CERTIFICATE")) {
+			l_free(certificate);
+			break;
+		}
+
+		l_free(label);
+		element = l_malloc(sizeof(struct l_pem_list_element));

l_new?

ell/pem.c LIB_EXPORT uint8_t *l_pem_load_certificate(const char *filename, size_t *len) · line 300

Quoted 8 lines
ell/pem.c +8 -0
+		element->content = certificate;
+		element->len = len;
+
+		if (!result)
+			result = l_queue_new();
+
+		l_queue_push_tail(result, element);
+		start = end - data;

You really need serious mental gymnastics to get this part. Can't we just have a curpos variable or something?

Quoted 21 lines
ell/pem.c +13 -0
+	}
+
+	/* Error occured */
+	l_queue_destroy(result, pem_element_free);
+	result = NULL;
+
+done:
+	munmap(data, st.st_size);
+	close(fd);
+
+	return result;
+}
+
  /**
   * l_pem_load_private_key
   * @filename: path string to the PEM file to load
ell/pem.h +0 -0
index 93282a3..9cead5c 100644

ell/pem.h line 36

Quoted 10 lines
ell/pem.h +7 -0
@@ -27,12 +27,20 @@
  extern "C" {
  #endif
 
+struct l_queue;
+
+struct l_pem_list_element {
+	uint8_t *content;
+	size_t len;
+};
+

As mentioned above, this probably should be a first class opaque data now.

ell/pem.h line 38

Quoted 2 lines
ell/pem.h +0 -0
  uint8_t *l_pem_load_buffer(const uint8_t *buf, size_t buf_len,
  				int index, char **type_label, size_t *out_len);

and we can change this to

struct l_pem *l_pem_load_buffer(buf, buf_len, index, char **);

I also really wonder if we want to take this function out of the public API, though we do need to add support for TPM 1.2 certificates as well.

ell/pem.h line 46

Quoted 9 lines
ell/pem.h +1 -0
  uint8_t *l_pem_load_file(const char *filename, int index,
  				char **type_label, size_t *len);
 
  uint8_t *l_pem_load_certificate(const char *filename, size_t *len);
+struct l_queue *l_pem_load_certificate_list(const char *filename);
 
  uint8_t *l_pem_load_private_key(const char *filename, const char *passphrase,
  				bool *encrypted, size_t *len);

Regards,
-Denis

#8 lore raw

Re: [PATCH 05/11] tls: Support loading multiple root CAs

In reply to Andrew Zaborowski

Hi Andrew,

Quoted 11 lines · Andrew Zaborowski

If a file with multiple concatenated certificates is supplied to set_auth_data, load all of them and verify received certificate chains aginst any of them instead of just the first one. This is also what wpa_supplicant does for files supplied with the ca_cert= setting and it's actually useful. Some enterprise CAs have multiple root certificates and provision clients with a file that contains all of them concatenated and it does happen that they switch from a certificate chain using one root to a new chain with a different root for their wifi in which case our network config files break while wpa_supplicant configs keep working.

Quoted 1 line

Also simplify tls_cert_verify_certchain slightly.

So mostly just a couple of nitpicks here:

Quoted 10 lines
ell/tls.c +9 -0
+struct l_queue *tls_cert_list_load_file(const char *filename)
+{
+	struct l_queue *pem_list;
+	struct l_queue *cert_list;
+	bool error = false;
+
+	pem_list = l_pem_load_certificate_list(filename);
+	if (!pem_list)
+		return NULL;

ell/tls.c struct tls_cert *tls_cert_load_file(const char *filename) · line 2614

Quoted 10 lines
ell/tls.c +10 -0
+
+	cert_list = l_queue_new();
+
+	while (!l_queue_isempty(pem_list)) {
+		struct tls_cert *cert;
+		struct l_pem_list_element *elem = l_queue_pop_head(pem_list);
+		uint8_t *der = elem->content;
+
+		if (!elem->len || der[0] != ASN1_ID_SEQUENCE)
+			error = true;

Can we actually not do that? Lets bugger out right away. No sense in performing additional work when we know that we've failed already.

ell/tls.c struct tls_cert *tls_cert_load_file(const char *filename) · line 2622

Quoted 8 lines
ell/tls.c +8 -0
+
+		cert = l_malloc(sizeof(struct tls_cert) + elem->len);
+		cert->size = elem->len;
+		cert->issuer = NULL;
+		memcpy(cert->asn1, der, cert->size);
+		l_queue_push_tail(cert_list, cert);
+		l_free(elem->content);
+		l_free(elem);

l_pem_free()?

Quoted 4 lines
ell/tls.c +4 -0
+	}
+
+	l_queue_destroy(pem_list, NULL);
+

ell/tls.c struct tls_cert *tls_cert_load_file(const char *filename) · line 2636

Quoted 10 lines
ell/tls.c +7 -0
+	if (!error)
+		return cert_list;
+
+	l_queue_destroy(cert_list, l_free);
+	return NULL;
+}
+
  int tls_cert_from_certificate_list(const void *data, size_t len,
  					struct tls_cert **out_certchain)
  {

Regards,
-Denis

#12 lore raw

Re: [PATCH 08/11] tls: Stricter certificate chain verification

In reply to Andrew Zaborowski

Hi Andrew,

Quoted 7 lines · Andrew Zaborowski

Rewrite tls_cert_verify_certchain to fix a long standing issue where it didn't verify that each certificate in the chain was trusted by the next one. Since certificates were only being added to the two keyrings and never removed the order in the chain was not being verified. Now use a single ring and remove the previously added certificates from it once they've been used to show that the next certificate was signed with one of them. Add lots of comments.

So I actually like this approach a lot. Few nitpicks:

Quoted 9 lines
---
  ell/tls.c | 206 +++++++++++++++++++++++++++++++++---------------------
  1 file changed, 125 insertions(+), 81 deletions(-)
ell/tls.c +0 -0
index fbbc1bf..7f42240 100644

ell/tls.c static const struct pkcs1_encryption_oid { · line 2696

Quoted 10 lines
ell/tls.c +7 -0
@@ -2687,27 +2687,99 @@ static const struct pkcs1_encryption_oid {
  	},
  };
 
+static struct l_key *tls_cert_verify_root(struct l_key *key,
+						struct l_keyring *ring,
+						struct l_queue *roots)
+{
+	const struct l_queue_entry *entry;
+	unsigned int i, n = l_queue_length(roots);
+	struct l_key *root_keys[n];

So Marcel will likely hunt you down for VLA usage. So maybe you want to rethink this.

Quoted 5 lines
ell/tls.c +5 -0
+	bool success = true;
+
+	/*
+	 * Check that @key is trusted by one of @roots by linking it
+	 * to a restricted ring containing only the roots.  If successful

ell/tls.c static const struct pkcs1_encryption_oid { · line 2711

Quoted 10 lines
ell/tls.c +10 -0
+	 * return @key leaving only @key in the keyring.
+	 */
+
+	for (entry = l_queue_get_entries(roots), i = 0; i < n;
+			entry = entry->next, i++) {
+		const struct tls_cert *root = entry->data;
+
+		root_keys[i] = l_key_new(L_KEY_RSA, root->asn1, root->size);
+		if (!root_keys[i] || !l_keyring_link(ring, root_keys[i]))
+			success = false;

So why are we loading the CA keys into the verify ring? Can't we just load all the CA keys into a temporary ring and then remove it when we're done? E.g. the ca ring.

ell/tls.c static const struct pkcs1_encryption_oid { · line 2716

Quoted 5 lines
ell/tls.c +5 -0
+	}
+
+	if (!l_keyring_restrict(ring, L_KEYRING_RESTRICT_ASYM_CHAIN, NULL) ||
+			!l_keyring_link(ring, key))
+		success = false;

And here we could restrict the ring against the ca_ring. If that succeeds, then what we can do is call l_keyring_restrict, this time with last argument being NULL. Or is that not possible? Mat?

ell/tls.c static const struct pkcs1_encryption_oid { · line 2720

Quoted 4 lines
ell/tls.c +4 -0
+
+	for (i = 0; i < n; i++)
+		l_key_free(root_keys[i]);
+

Then this just becomes l_keyring_free(ca_ring);

Quoted 14 lines
ell/tls.c +8 -2
+	if (success)
+		return key;
+
+	l_key_free(key);
+	return NULL;
+}
+
  static void tls_key_cleanup(struct l_key **p)
  {
-	l_key_free_norevoke(*p);
+	l_key_free(*p);
  }
 
-static bool tls_cert_link(struct tls_cert *cert, struct l_keyring *ring)

<snip>

ell/tls.c static void tls_keyring_cleanup(struct l_keyring **p) · line 2845

Quoted 9 lines
ell/tls.c +2 -2
@@ -2772,43 +2840,19 @@ static void tls_keyring_cleanup(struct l_keyring **p)
  bool tls_cert_verify_certchain(struct tls_cert *certchain,
  				struct l_queue *ca_certs)
  {
-	L_AUTO_CLEANUP_VAR(struct l_keyring *, ca_ring, tls_keyring_cleanup);
  	L_AUTO_CLEANUP_VAR(struct l_keyring *, verify_ring,
-				tls_keyring_cleanup);
+				tls_keyring_cleanup) = l_keyring_new();
+	struct l_key *trusted;

This function is so simple I would consider dropping the L_AUTO_CLEANUP_VAR completely.

Quoted 33 lines
ell/tls.c +2 -27
-	ca_ring = NULL;
-
-	verify_ring = l_keyring_new();
  	if (!verify_ring)
  		return false;
 
-	/*
-	 * If CA cert(s) were supplied, restrict verify_ring now so
-	 * everything else in certchain is validated against the CA(s).
-	 * Otherwise, verify_ring will be restricted after the root of
-	 * certchain is added to verify_ring by
-	 * tls_cert_verify_with_keyring().
-	 */
-	if (ca_certs) {
-		const struct l_queue_entry *entry;
-
-		ca_ring = l_keyring_new();
-		if (!ca_ring)
-			return false;
-
-		for (entry = l_queue_get_entries(ca_certs); entry;
-				entry = entry->next)
-			if (!tls_cert_link(entry->data, ca_ring))
-				return false;
-
-		if (!l_keyring_restrict(verify_ring,
-					L_KEYRING_RESTRICT_ASYM_CHAIN,
-					ca_ring))
-			return false;
-	}
+	trusted = tls_cert_verify_with_keyring(certchain, verify_ring, ca_certs);
+	if (!trusted)

ell/tls.c static void tls_keyring_cleanup(struct l_keyring **p)

Quoted 10 lines
ell/tls.c +3 -2
+		return false;
 
-	return tls_cert_verify_with_keyring(certchain, verify_ring, ca_certs,
-						ca_ring);
+	l_key_free(trusted);
+	return true;
  }
 
  void tls_cert_free_certchain(struct tls_cert *cert)
 

Regards,
-Denis

#17 lore raw

Re: [PATCH 09/11] tls: Support loading certificate chains from file

In reply to Andrew Zaborowski

Hi Andrew,

Quoted 61 lines · Andrew Zaborowski

When loading the file supplied with l_tls_set_auth_data to be sent as Server Certificate or Client Certificate, allow for the possibility of loading a chain of certificates instead of just one if the file contains multiple concatenated PEM certificates, ordered from the end-entity to the CA. The chain has to end with one of the CA certs set through l_tls_set_cacert or a cert directly signed by one of them, if l_tls_set_cacert was called.

---
  ell/tls.c | 69 +++++++++++++++++++++++++++++++++++++++++--------------
  1 file changed, 52 insertions(+), 17 deletions(-)
ell/tls.c +15 -10
index 7f42240..0aa10e7 100644
@@ -754,7 +754,7 @@ static bool tls_send_certificate(struct l_tls *tls)
 
  	if (tls->server && !cert) {
  		TLS_DISCONNECT(TLS_ALERT_INTERNAL_ERROR, TLS_ALERT_BAD_CERT,
-				"Loading server certificate %s failed",
+				"Loading server certificate chain %s failed",
  				tls->cert_path);
  		return false;
  	}
@@ -828,7 +828,7 @@ static bool tls_send_certificate(struct l_tls *tls)
  	if (cert)
  		tls->cert_sent = true;
 
-	l_free(cert);
+	tls_cert_free_certchain(cert);
 
  	return true;
  }
@@ -2570,27 +2570,41 @@ const char *tls_handshake_state_to_str(enum tls_handshake_state state)
 
  struct tls_cert *tls_cert_load_file(const char *filename)
  {
-	uint8_t *der;
-	size_t len;
-	struct tls_cert *cert;
+	struct l_queue *pem_list;
+	struct tls_cert *chain = NULL;
+	struct tls_cert **root = &chain;
+	bool error = false;
 
-	der = l_pem_load_certificate(filename, &len);
-	if (!der)
+	pem_list = l_pem_load_certificate_list(filename);
+	if (!pem_list)
  		return NULL;
 
-	if (!len || der[0] != ASN1_ID_SEQUENCE) {
-		l_free(der);
-		return NULL;
+	while (!l_queue_isempty(pem_list)) {
+		struct tls_cert *cert;
+		struct l_pem_list_element *elem = l_queue_pop_head(pem_list);
+		uint8_t *der = elem->content;
+
+		if (!elem->len || der[0] != ASN1_ID_SEQUENCE)
+			error = true;

ell/tls.c const char *tls_handshake_state_to_str(enum tls_handshake_state state) · line 2598

Quoted 10 lines
ell/tls.c +10 -0
+
+		cert = l_malloc(sizeof(struct tls_cert) + elem->len);
+		cert->size = elem->len;
+		cert->issuer = NULL;
+		memcpy(cert->asn1, der, cert->size);
+		l_free(elem->content);
+		l_free(elem);
+
+		*root = cert;
+		root = &cert->issuer;

Isn't this doing almost exactly the same thing as a function in patch 5?

Quoted 8 lines
ell/tls.c +1 -4
  	}
 
-	cert = l_malloc(sizeof(struct tls_cert) + len);
-	cert->size = len;
-	cert->issuer = NULL;
-	memcpy(cert->asn1, der, len);
+	l_queue_destroy(pem_list, NULL);
 

ell/tls.c const char *tls_handshake_state_to_str(enum tls_handshake_state state) · line 2610

Quoted 10 lines
ell/tls.c +4 -2
-	l_free(der);
+	if (!error)
+		return chain;
 
-	return cert;
+	tls_cert_free_certchain(chain);
+	return NULL;
  }
 
  struct l_queue *tls_cert_list_load_file(const char *filename)

Regards,
-Denis

#13 lore raw

Re: [PATCH 08/11] tls: Stricter certificate chain verification

In reply to Denis Kenzior
Quoted 17 lines · Denis Kenzior

Hi Andrew,

Quoted 7 lines · Andrew Zaborowski

Rewrite tls_cert_verify_certchain to fix a long standing issue where it didn't verify that each certificate in the chain was trusted by the next one. Since certificates were only being added to the two keyrings and never removed the order in the chain was not being verified. Now use a single ring and remove the previously added certificates from it once they've been used to show that the next certificate was signed with one of them. Add lots of comments.

So I actually like this approach a lot. Few nitpicks:

Quoted 4 lines
---
  ell/tls.c | 206 +++++++++++++++++++++++++++++++++---------------------
  1 file changed, 125 insertions(+), 81 deletions(-)
Quoted 10 lines

ell/tls.c static const struct pkcs1_encryption_oid { · line 2691

Quoted 10 lines
ell/tls.c +2 -0
index fbbc1bf..7f42240 100644
@@ -2687,27 +2687,99 @@ static const struct pkcs1_encryption_oid {
  	},
  };
  +static struct l_key *tls_cert_verify_root(struct l_key *key,
+						struct l_keyring *ring,
+						struct l_queue *roots)

Have you considered loading the root certs in to a kernel keyring once in l_tls_set_cacert() then keeping it around to reuse?

Quoted 19 lines

ell/tls.c static const struct pkcs1_encryption_oid { · line 2696

Quoted 4 lines
ell/tls.c +4 -0
+{
+	const struct l_queue_entry *entry;
+	unsigned int i, n = l_queue_length(roots);
+	struct l_key *root_keys[n];

So Marcel will likely hunt you down for VLA usage. So maybe you want to rethink this.

Quoted 11 lines
ell/tls.c +11 -0
+	bool success = true;
+
+	/*
+	 * Check that @key is trusted by one of @roots by linking it
+	 * to a restricted ring containing only the roots.  If successful
+	 * return @key leaving only @key in the keyring.
+	 */
+
+	for (entry = l_queue_get_entries(roots), i = 0; i < n;
+			entry = entry->next, i++) {
+		const struct tls_cert *root = entry->data;
Quoted 8 lines

ell/tls.c static const struct pkcs1_encryption_oid { · line 2711

Quoted 4 lines
ell/tls.c +4 -0
+
+		root_keys[i] = l_key_new(L_KEY_RSA, root->asn1, root->size);
+		if (!root_keys[i] || !l_keyring_link(ring, root_keys[i]))
+			success = false;

So why are we loading the CA keys into the verify ring? Can't we just load all the CA keys into a temporary ring and then remove it when we're done? E.g. the ca ring.

This is possible, but I'm not sure it accomplishes much. Either way you still end up deleting all the CA keys, and if you add a temporary ring then you have to create and delete that too.

The use case I had in mind was to have a persistent ca_ring that could be used to restrict many other short-lived keyrings.

Quoted 10 lines

ell/tls.c static const struct pkcs1_encryption_oid { · line 2716

Quoted 6 lines
ell/tls.c +5 -0
+	}
+
+	if (!l_keyring_restrict(ring, L_KEYRING_RESTRICT_ASYM_CHAIN, NULL) ||
+			!l_keyring_link(ring, key))
+		success = false;

And here we could restrict the ring against the ca_ring. If that succeeds, then what we can do is call l_keyring_restrict, this time with last argument being NULL. Or is that not possible? Mat?

I'm not 100% sure I'm following Denis here, but you only get one chance to call l_keyring_restrict() for a given keyring. So if you restrict against ca_ring, you can't change that to NULL later (but you could empty ca_ring and get the same effect).

Quoted 7 lines

ell/tls.c static const struct pkcs1_encryption_oid { · line 2720

Quoted 5 lines
ell/tls.c +4 -0
+
+	for (i = 0; i < n; i++)
+		l_key_free(root_keys[i]);
+

Then this just becomes l_keyring_free(ca_ring);

You still have to l_key_free() each root key. The l_keyring tells the kernel how to group the keys, but ELL doesn't free its l_key objects based on the keyring(s) they are in.

Quoted 17 lines
Quoted 14 lines
ell/tls.c +8 -1
+	if (success)
+		return key;
+
+	l_key_free(key);
+	return NULL;
+}
+
  static void tls_key_cleanup(struct l_key **p)
  {
-	l_key_free_norevoke(*p);
+	l_key_free(*p);
  }
  -static bool tls_cert_link(struct tls_cert *cert, struct l_keyring *ring)

<snip>

Quoted 13 lines

ell/tls.c static void tls_keyring_cleanup(struct l_keyring · line 2846

Quoted 10 lines
ell/tls.c +2 -2
@@ -2772,43 +2840,19 @@ static void tls_keyring_cleanup(struct l_keyring 
 **p)
  bool tls_cert_verify_certchain(struct tls_cert *certchain,
  				struct l_queue *ca_certs)
  {
-	L_AUTO_CLEANUP_VAR(struct l_keyring *, ca_ring, tls_keyring_cleanup);
  	L_AUTO_CLEANUP_VAR(struct l_keyring *, verify_ring,
-				tls_keyring_cleanup);
+				tls_keyring_cleanup) = l_keyring_new();
+	struct l_key *trusted;

This function is so simple I would consider dropping the L_AUTO_CLEANUP_VAR completely.

The auto cleanup stuff was handy when there were many different 'return' statements, but with the simplified version of this function I agree with Denis.

Quoted 33 lines
Quoted 33 lines
ell/tls.c +2 -25
  -	ca_ring = NULL;
-
-	verify_ring = l_keyring_new();
  	if (!verify_ring)
  		return false;
  -	/*
-	 * If CA cert(s) were supplied, restrict verify_ring now so
-	 * everything else in certchain is validated against the CA(s).
-	 * Otherwise, verify_ring will be restricted after the root of
-	 * certchain is added to verify_ring by
-	 * tls_cert_verify_with_keyring().
-	 */
-	if (ca_certs) {
-		const struct l_queue_entry *entry;
-
-		ca_ring = l_keyring_new();
-		if (!ca_ring)
-			return false;
-
-		for (entry = l_queue_get_entries(ca_certs); entry;
-				entry = entry->next)
-			if (!tls_cert_link(entry->data, ca_ring))
-				return false;
-
-		if (!l_keyring_restrict(verify_ring,
-					L_KEYRING_RESTRICT_ASYM_CHAIN,
-					ca_ring))
-			return false;
-	}
+	trusted = tls_cert_verify_with_keyring(certchain, verify_ring, 
 ca_certs);
+	if (!trusted)
Quoted 9 lines

ell/tls.c static void tls_keyring_cleanup(struct l_keyring **p) · line 2858

Quoted 8 lines
ell/tls.c +3 -1
+		return false;
  -	return tls_cert_verify_with_keyring(certchain, verify_ring, ca_certs,
-						ca_ring);
+	l_key_free(trusted);
+	return true;
  }
    void tls_cert_free_certchain(struct tls_cert *cert)

It seems like the implementation is made more complicated by the fact that the cert list is a singly-linked list starting with the end-entity cert (which we then follow toward the root using the issuer pointers), while in order to verify we need to link keys to the restricted keyring starting from the root end of the chain.

If we know that it's a linear cert chain, the code could be simplified by making the cert chain a doubly-linked list that could be walked in the other direction. That would eliminate the recursion, leading to an implementation that looks more like this:

1. Create a keyring
2. Load it with the root certs
3. Try to load the first cert in the chain (from the root-facing end)
4. If that works, clear the root certs
5. Try to load the next cert in the chain
6. If that works, clear the previous cert
7. Repeat 5-6 until you get to the end-entity cert

That's the behavior of this patch (from the perspective of the kernel), but it's hard to see because recursive calls are used to follow the issuer chain toward the root first, then the keyring loads are attempted as the stack gets unwound.

(I realize the recursive code structure is inherited from my earlier implementation :) )

As Denis pointed out above, it would be convenient to add and remove the root certs as a group. The kernel lets keyrings contain keyrings. A restricted keyring R will search for signing keys in the trusted keyring T (if it wasn't NULL), and within R itself. If R "contains" a link to another keyring A, it will search T, R, and A for signing keys.

If we add l_keyring_link_nested(keyring, nested_keyring) to ELL, then you could have a persistent ca_ring that is temporarly linked to the verify ring to check the first cert, then ca_ring gets unlinked in a single operation when you want to check the second cert.

--
Mat Martineau
Intel OTC

#14 lore raw

Re: [PATCH 08/11] tls: Stricter certificate chain verification

Hi Mat,

Quoted 19 lines · Mat Martineau
Quoted 17 lines · Denis Kenzior

Hi Andrew,

Quoted 7 lines · Andrew Zaborowski

Rewrite tls_cert_verify_certchain to fix a long standing issue where it didn't verify that each certificate in the chain was trusted by the next one.  Since certificates were only being added to the two keyrings and never removed the order in the chain was not being verified.  Now use a single ring and remove the previously added certificates from it once they've been used to show that the next certificate was signed with one of them.  Add lots of comments.

So I actually like this approach a lot.  Few nitpicks:

Quoted 4 lines

---
  ell/tls.c | 206 +++++++++++++++++++++++++++++++++---------------------

  1 file changed, 125 insertions(+), 81 deletions(-)
Quoted 14 lines
Quoted 10 lines

ell/tls.c static const struct pkcs1_encryption_oid { · line 2691

Quoted 10 lines
ell/tls.c +2 -0
index fbbc1bf..7f42240 100644
@@ -2687,27 +2687,99 @@ static const struct pkcs1_encryption_oid {
       },
   };
   +static struct l_key *tls_cert_verify_root(struct l_key *key,
+                        struct l_keyring *ring,
+                        struct l_queue *roots)

Have you considered loading the root certs in to a kernel keyring once in l_tls_set_cacert() then keeping it around to reuse?

Exactly. This is ultimately what we want: to load root CAs once and reuse them between multiple connections. So the CA keyring needs to be reusable.

Quoted 28 lines
Quoted 19 lines

ell/tls.c static const struct pkcs1_encryption_oid { · line 2696

Quoted 4 lines
ell/tls.c +4 -0
+{
+    const struct l_queue_entry *entry;
+    unsigned int i, n = l_queue_length(roots);
+    struct l_key *root_keys[n];

So Marcel will likely hunt you down for VLA usage.  So maybe you want to rethink this.

Quoted 11 lines
ell/tls.c +11 -0
+    bool success = true;
+
+    /*
+     * Check that @key is trusted by one of @roots by linking it
+     * to a restricted ring containing only the roots.  If successful
+     * return @key leaving only @key in the keyring.
+     */
+
+    for (entry = l_queue_get_entries(roots), i = 0; i < n;
+            entry = entry->next, i++) {
+        const struct tls_cert *root = entry->data;
Quoted 8 lines

ell/tls.c static const struct pkcs1_encryption_oid { · line 2711

Quoted 4 lines
ell/tls.c +4 -0
+
+        root_keys[i] = l_key_new(L_KEY_RSA, root->asn1, root->size);
+        if (!root_keys[i] || !l_keyring_link(ring, root_keys[i]))
+            success = false;

So why are we loading the CA keys into the verify ring?  Can't we just load all the CA keys into a temporary ring and then remove it when we're done? E.g. the ca ring.

Quoted 3 lines

This is possible, but I'm not sure it accomplishes much. Either way you still end up deleting all the CA keys, and if you add a temporary ring then you have to create and delete that too.

As an intermediate transform until we get to the point where we keep the CAs around in a permanent keyring. What I suggest above is mostly about getting rid of VLA usage. We can l_key_free_norevoke here right away in this case.

Quoted 4 lines

The use case I had in mind was to have a persistent ca_ring that could be used to restrict many other short-lived keyrings.

Yep, I'm with you.

Quoted 8 lines
Quoted 8 lines
Quoted 7 lines
ell/tls.c +3 -0
+    }
+
+    if (!l_keyring_restrict(ring, L_KEYRING_RESTRICT_ASYM_CHAIN, 

NULL) ||
+            !l_keyring_link(ring, key))
+        success = false;

Quoted 8 lines
Quoted 3 lines

And here we could restrict the ring against the ca_ring.  If that succeeds, then what we can do is call l_keyring_restrict, this time with last argument being NULL.  Or is that not possible? Mat?

I'm not 100% sure I'm following Denis here, but you only get one chance to call l_keyring_restrict() for a given keyring. So if you restrict against ca_ring, you can't change that to NULL later (but you could empty ca_ring and get the same effect).

Okay, that's what I was wondering, whether we could call restrict multiple times. So if we can't do that, and given the fact that we only have a single key we're talking about here, why don't we create a temporary keyring. Put the key into that, and restrict the temporary to the CA ring. If that succeeds, put the key into the actual ring and restrict it as we do above. Hope that makes sense.

Quoted 9 lines
Quoted 8 lines

ell/tls.c static const struct pkcs1_encryption_oid { · line 2720

Quoted 6 lines
ell/tls.c +4 -0
+
+    for (i = 0; i < n; i++)
+        l_key_free(root_keys[i]);
+

Then this just becomes l_keyring_free(ca_ring);

Quoted 4 lines

You still have to l_key_free() each root key. The l_keyring tells the kernel how to group the keys, but ELL doesn't free its l_key objects based on the keyring(s) they are in.

Right, I left out the l_key_free_norevoke detail above.

Quoted 100 lines
Quoted 18 lines
Quoted 15 lines

+    if (success)
+        return key;

ell/tls.c +5 -0
+
+    l_key_free(key);
+    return NULL;
+}
+

  static void tls_key_cleanup(struct l_key **p)
  {
-    l_key_free_norevoke(*p);
+    l_key_free(*p);
  }
  -static bool tls_cert_link(struct tls_cert *cert, struct l_keyring *ring)

<snip>

Quoted 14 lines

ell/tls.c static void tls_keyring_cleanup(struct · line 2847

Quoted 11 lines
ell/tls.c +2 -2
@@ -2772,43 +2840,19 @@ static void tls_keyring_cleanup(struct 
 l_keyring **p)
   bool tls_cert_verify_certchain(struct tls_cert *certchain,
                   struct l_queue *ca_certs)
   {
-    L_AUTO_CLEANUP_VAR(struct l_keyring *, ca_ring, 
 tls_keyring_cleanup);
       L_AUTO_CLEANUP_VAR(struct l_keyring *, verify_ring,
-                tls_keyring_cleanup);
+                tls_keyring_cleanup) = l_keyring_new();
+    struct l_key *trusted;

This function is so simple I would consider dropping the L_AUTO_CLEANUP_VAR completely.

The auto cleanup stuff was handy when there were many different 'return' statements, but with the simplified version of this function I agree with Denis.

Quoted 34 lines
Quoted 34 lines
ell/tls.c +0 -2
   -    ca_ring = NULL;
-
-    verify_ring = l_keyring_new();
       if (!verify_ring)
           return false;

  -    /*
-     * If CA cert(s) were supplied, restrict verify_ring now so -     * everything else in certchain is validated against the CA(s). -     * Otherwise, verify_ring will be restricted after the root of -     * certchain is added to verify_ring by
-     * tls_cert_verify_with_keyring().
-     */
-    if (ca_certs) {
-        const struct l_queue_entry *entry;

ell/tls.c +1 -15
-
-        ca_ring = l_keyring_new();
-        if (!ca_ring)
-            return false;
-
-        for (entry = l_queue_get_entries(ca_certs); entry;
-                entry = entry->next)
-            if (!tls_cert_link(entry->data, ca_ring))
-                return false;
-
-        if (!l_keyring_restrict(verify_ring,
-                    L_KEYRING_RESTRICT_ASYM_CHAIN,
-                    ca_ring))
-            return false;
-    }
+    trusted = tls_cert_verify_with_keyring(certchain, verify_ring, 

ca_certs);
+    if (!trusted)
+        return false;

Quoted 9 lines
Quoted 8 lines

  -    return tls_cert_verify_with_keyring(certchain, verify_ring, ca_certs,
-                        ca_ring);
+    l_key_free(trusted);
+    return true;
  }
    void tls_cert_free_certchain(struct tls_cert *cert)

It seems like the implementation is made more complicated by the fact that the cert list is a singly-linked list starting with the end-entity cert (which we then follow toward the root using the issuer pointers), while in order to verify we need to link keys to the restricted keyring starting from the root end of the chain.

If we know that it's a linear cert chain, the code could be simplified by making the cert chain a doubly-linked list that could be walked in the other direction. That would eliminate the recursion, leading to an implementation that looks more like this:

1. Create a keyring
2. Load it with the root certs
3. Try to load the first cert in the chain (from the root-facing end)
4. If that works, clear the root certs
5. Try to load the next cert in the chain
6. If that works, clear the previous cert
7. Repeat 5-6 until you get to the end-entity cert

Quoted 8 lines

That's the behavior of this patch (from the perspective of the kernel), but it's hard to see because recursive calls are used to follow the issuer chain toward the root first, then the keyring loads are attempted as the stack gets unwound.

(I realize the recursive code structure is inherited from my earlier implementation :) )

I agree here, I think recursive implementation is actually harder to read and more resource intensive.

Quoted 7 lines

As Denis pointed out above, it would be convenient to add and remove the root certs as a group. The kernel lets keyrings contain keyrings. A restricted keyring R will search for signing keys in the trusted keyring T (if it wasn't NULL), and within R itself. If R "contains" a link to another keyring A, it will search T, R, and A for signing keys.

Quoted 5 lines

If we add l_keyring_link_nested(keyring, nested_keyring) to ELL, then you could have a persistent ca_ring that is temporarly linked to the verify ring to check the first cert, then ca_ring gets unlinked in a single operation when you want to check the second cert.

So that might actually be an even better solution than what I proposed above with having a temporary restriction ring.

Regards,
-Denis

#5 lore raw

Re: [PATCH 04/11] pem: Add l_pem_load_certificate_list utility

In reply to Denis Kenzior

Hi Denis,

Quoted 12 lines · Denis Kenzior

ell/pem.c LIB_EXPORT uint8_t *l_pem_load_certificate(const char *filename, size_t *len) · line 247

Quoted 7 lines · Andrew Zaborowski
ell/pem.c +7 -0
+static void pem_element_free(void *data)
+{
+     struct l_pem_list_element *element = data;
+
+     l_free(element->content);
+     l_free(element);
+}

So I see that we duplicate this free function a bunch of times in the later commits in this series. Perhaps we should bite the bullet and make l_pem an actual first class object with some getters and a destructor.

So an l_pem would represent a single '----- BEGIN' to '----- END' fragment of a PEM file? I'd the rather call it an l_pem_element or similar, and make l_pem_element_free() public, and could also make the struct non-public and add accessors but that doesn't help much I think.

However what I'd really prefer instead is to add back the l_cert type, which could be a first class object with a lot of functionality and tls.c would become much shorter. It could hide the l_key usage (but could have an accessor for the public key in the certificate) and also could have l_cert_new_from_pem(), or alternatively pem.c could rather have a l_pem_load_cert() returning l_cert objects.

Similarly maybe our current l_pem_load_private_key() could be changed to return an l_key directly.

Quoted 44 lines

E.g.

const void *l_pem_get_content(struct l_pem *);
size_t l_pem_get_content_length(struct l_pem *);

void l_pem_free(struct l_pem *);

and possibly:
enum l_pem_type l_pem_get_type(struct l_pem *);

Quoted 33 lines
ell/pem.c +33 -0
+
+LIB_EXPORT struct l_queue *l_pem_load_certificate_list(const char *filename)
+{
+     int fd;
+     struct stat st;
+     uint8_t *data;
+     size_t start = 0;
+     struct l_queue *result = NULL;
+
+     fd = open(filename, O_RDONLY);
+     if (fd < 0)
+             return NULL;
+
+     if (fstat(fd, &st) < 0) {
+             close(fd);
+
+             return NULL;
+     }
+
+     data = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
+     if (data == MAP_FAILED) {
+             close(fd);
+
+             return NULL;
+     }
+
+     while (1) {
+             uint8_t *certificate;
+             size_t len;
+             char *label;
+             struct l_pem_list_element *element;
+             const uint8_t *end;
+
Quoted 8 lines

ell/pem.c LIB_EXPORT uint8_t *l_pem_load_certificate(const char *filename, size_t *len) · line 284

Quoted 4 lines
ell/pem.c +4 -0
+             certificate = pem_load_buffer(data + start, st.st_size - start, 0,
+                                             &label, &len, &end);
+             if (!certificate)
+                     goto done;

I'm not so sure about this. pem_load_buffer can fail for base64 decode failure reasons. So I wouldn't think that you can assume that a failure means EOF + success.

I was thinking about the case of having 5 certificates already loaded and the last one failing -- in this case we might just want to return the 5 that parsed ok but I can add better error checking.

Quoted 12 lines

ell/pem.c LIB_EXPORT uint8_t *l_pem_load_certificate(const char *filename, size_t *len) · line 292

Quoted 9 lines
ell/pem.c +8 -0
+
+             if (strcmp(label, "CERTIFICATE")) {
+                     l_free(certificate);
+                     break;
+             }
+
+             l_free(label);
+             element = l_malloc(sizeof(struct l_pem_list_element));

l_new?

Quoted 11 lines

ell/pem.c LIB_EXPORT uint8_t *l_pem_load_certificate(const char *filename, size_t *len) · line 300

Quoted 8 lines
ell/pem.c +8 -0
+             element->content = certificate;
+             element->len = len;
+
+             if (!result)
+                     result = l_queue_new();
+
+             l_queue_push_tail(result, element);
+             start = end - data;

You really need serious mental gymnastics to get this part. Can't we just have a curpos variable or something?

Ok, if I rename "start" to "curpos" and "end" to "newendpos" or similar I think it should be pretty clear.

Quoted 38 lines
Quoted 22 lines
ell/pem.c +13 -0
+     }
+
+     /* Error occured */
+     l_queue_destroy(result, pem_element_free);
+     result = NULL;
+
+done:
+     munmap(data, st.st_size);
+     close(fd);
+
+     return result;
+}
+
  /**
   * l_pem_load_private_key
   * @filename: path string to the PEM file to load
ell/pem.h +0 -0
index 93282a3..9cead5c 100644

ell/pem.h line 36

Quoted 10 lines
ell/pem.h +7 -0
@@ -27,12 +27,20 @@
  extern "C" {
  #endif
 
+struct l_queue;
+
+struct l_pem_list_element {
+     uint8_t *content;
+     size_t len;
+};
+

As mentioned above, this probably should be a first class opaque data now.

ell/pem.h line 38

Quoted 2 lines
ell/pem.h +0 -0
  uint8_t *l_pem_load_buffer(const uint8_t *buf, size_t buf_len,
                              int index, char **type_label, size_t *out_len);
Quoted 6 lines

and we can change this to

struct l_pem *l_pem_load_buffer(buf, buf_len, index, char **);

I also really wonder if we want to take this function out of the public API, though we do need to add support for TPM 1.2 certificates as well.

This could be done separately but I think having a public function to just get the first PEM fragment in a file is practical (saves you from loading all of them and freeing all but the first struct.)

Best regards

#15 lore raw

Re: [PATCH 08/11] tls: Stricter certificate chain verification

In reply to Denis Kenzior

Hi,

Quoted 8 lines · Denis Kenzior
Quoted 3 lines · Mat Martineau

Have you considered loading the root certs in to a kernel keyring once in l_tls_set_cacert() then keeping it around to reuse?

Exactly. This is ultimately what we want: to load root CAs once and reuse them between multiple connections. So the CA keyring needs to be reusable.

Ok. With it being possible to add nested keyrings this is easy.

Quoted 16 lines
Quoted 16 lines
Quoted 16 lines

<snip>

ell/tls.c static void tls_keyring_cleanup(struct · line 2847

Quoted 11 lines
ell/tls.c +2 -2
@@ -2772,43 +2840,19 @@ static void tls_keyring_cleanup(struct
 l_keyring **p)
  bool tls_cert_verify_certchain(struct tls_cert *certchain,
                  struct l_queue *ca_certs)
  {
-    L_AUTO_CLEANUP_VAR(struct l_keyring *, ca_ring,
 tls_keyring_cleanup);
      L_AUTO_CLEANUP_VAR(struct l_keyring *, verify_ring,
-                tls_keyring_cleanup);
+                tls_keyring_cleanup) = l_keyring_new();
+    struct l_key *trusted;

This function is so simple I would consider dropping the L_AUTO_CLEANUP_VAR completely.

Ok.

Quoted 73 lines
Quoted 73 lines

The auto cleanup stuff was handy when there were many different 'return' statements, but with the simplified version of this function I agree with Denis.

Quoted 34 lines
Quoted 34 lines
ell/tls.c +3 -25
  -    ca_ring = NULL;
-
-    verify_ring = l_keyring_new();
      if (!verify_ring)
          return false;
  -    /*
-     * If CA cert(s) were supplied, restrict verify_ring now so
-     * everything else in certchain is validated against the CA(s).
-     * Otherwise, verify_ring will be restricted after the root of
-     * certchain is added to verify_ring by
-     * tls_cert_verify_with_keyring().
-     */
-    if (ca_certs) {
-        const struct l_queue_entry *entry;
-
-        ca_ring = l_keyring_new();
-        if (!ca_ring)
-            return false;
-
-        for (entry = l_queue_get_entries(ca_certs); entry;
-                entry = entry->next)
-            if (!tls_cert_link(entry->data, ca_ring))
-                return false;
-
-        if (!l_keyring_restrict(verify_ring,
-                    L_KEYRING_RESTRICT_ASYM_CHAIN,
-                    ca_ring))
-            return false;
-    }
+    trusted = tls_cert_verify_with_keyring(certchain, verify_ring,
 ca_certs);
+    if (!trusted)
+        return false;
Quoted 9 lines

ell/tls.c static void tls_keyring_cleanup(struct l_keyring **p) · line 2858

Quoted 8 lines
ell/tls.c +2 -1
  -    return tls_cert_verify_with_keyring(certchain, verify_ring,
 ca_certs,
-                        ca_ring);
+    l_key_free(trusted);
+    return true;
  }
    void tls_cert_free_certchain(struct tls_cert *cert)

It seems like the implementation is made more complicated by the fact that the cert list is a singly-linked list starting with the end-entity cert (which we then follow toward the root using the issuer pointers), while in order to verify we need to link keys to the restricted keyring starting from the root end of the chain.

If we know that it's a linear cert chain, the code could be simplified by making the cert chain a doubly-linked list that could be walked in the other direction. That would eliminate the recursion, leading to an implementation that looks more like this:

1. Create a keyring
2. Load it with the root certs
3. Try to load the first cert in the chain (from the root-facing end)
4. If that works, clear the root certs
5. Try to load the next cert in the chain
6. If that works, clear the previous cert
7. Repeat 5-6 until you get to the end-entity cert

That's the behavior of this patch (from the perspective of the kernel), but it's hard to see because recursive calls are used to follow the issuer chain toward the root first, then the keyring loads are attempted as the stack gets unwound.

Quoted 6 lines
Quoted 3 lines

(I realize the recursive code structure is inherited from my earlier implementation :) )

I agree here, I think recursive implementation is actually harder to read and more resource intensive.

Yep, definitely, but using a doubly-linked list for all tls_cert structs also seems like unneeded overhead. We can easily create a temporary reversed list or a plain array in tls_cert_verify_certchain, which is only called once per l_tls object anyway.

Quoted 8 lines
Quoted 8 lines

As Denis pointed out above, it would be convenient to add and remove the root certs as a group. The kernel lets keyrings contain keyrings. A restricted keyring R will search for signing keys in the trusted keyring T (if it wasn't NULL), and within R itself. If R "contains" a link to another keyring A, it will search T, R, and A for signing keys.

Quoted 8 lines
Quoted 5 lines

If we add l_keyring_link_nested(keyring, nested_keyring) to ELL, then you could have a persistent ca_ring that is temporarly linked to the verify ring to check the first cert, then ca_ring gets unlinked in a single operation when you want to check the second cert.

So that might actually be an even better solution than what I proposed above with having a temporary restriction ring.

Yes, makes sense, I had actually seen this in the kernel keyring search function but it didn't occur to me to use it.

Best regards

#6 lore raw

Re: [PATCH 04/11] pem: Add l_pem_load_certificate_list utility

In reply to Andrew Zaborowski

Hi Andrew,

Quoted 6 lines

However what I'd really prefer instead is to add back the l_cert type, which could be a first class object with a lot of functionality and tls.c would become much shorter. It could hide the l_key usage (but could have an accessor for the public key in the certificate) and also could have l_cert_new_from_pem(), or alternatively pem.c could rather have a l_pem_load_cert() returning l_cert objects.

Yep, lets try doing that.

Quoted 9 lines
Quoted 4 lines

I'm not so sure about this. pem_load_buffer can fail for base64 decode failure reasons. So I wouldn't think that you can assume that a failure means EOF + success.

I was thinking about the case of having 5 certificates already loaded and the last one failing -- in this case we might just want to return the 5 that parsed ok but I can add better error checking.

No. Please no. We never do things this way. If the parsing was partially successful then it was a failure. Period. Fail early, get the user to address it. Don't hide problems until they become painful to find.

Regards,
-Denis