Skip to contentSkip to conversation

storage: implement network profile encryption

PATCH Superseded James Prestwood 2 participants 8 messages Feb 2, 2022 Kbuild

v2 of 8 Superseded Latest is v8 →

lore
Share & tools
lore

James Prestwood

author
#0 lore raw

PATCH v2 1/5 storage: implement network profile encryption

Some users don't like the idea of storing network credentials in plaintext on the file system. As far as IWD goes the credential directory permissions should be set up such that nobody but the owner/root have access but nevertheless they are still plaintext.

For added security these credentials can be encrypted using a secret key. In this patch the origination of the key does not matter, but in this patch series IWD will support a systemd provided key.

The encryption itself will operate on the entire [Security] group as well as all embedded groups. Once encrypted the [Security] group will be replaced with two key/values:

EncryptedSalt - A random string of bytes used for the encryption EncryptedSecurity - A string of bytes containing the encrypted [Security]
group, as well as all embedded groups.

After the profile has been encrypted these values should not be modified. Note that any values added to [Security] after encryption has no effect. Once the profile is encrypted there is no way to modify [Security] without manually decrypting first, or just removing it entirely which effectively treated a 'new' profile.

The encryption/decryption is done using AES-SIV with a salt value and the network SSID as the IV.

Once a key is set any profiles opened will automatically be encrypted and re-written to disk. Modules using network_storage_open will be provided the decrypted profile, and will be unaware it was ever encrypted in the first place. Similarly when network_storage_sync is called the profile will by automatically encrypted and written to disk without the caller needing to do anything special.

---
 Makefile.am   |   3 +-
 src/storage.c | 239 +++++++++++++++++++++++++++++++++++++++++++++++---
 src/storage.h |   4 +
 3 files changed, 235 insertions(+), 11 deletions(-)
Makefile.am +2 -1
index 89c053a6..35938d22 100644
@@ -381,7 +381,8 @@ tools_hwsim_SOURCES = tools/hwsim.c src/mpdu.h \
 					src/nl80211util.h src/nl80211util.c \
 					src/storage.h src/storage.c \
 					src/common.h src/common.c \
-					src/band.h src/band.c
+					src/band.h src/band.c \
+					src/crypto.h src/crypto.c
 tools_hwsim_LDADD = $(ell_ldadd)
 
 if DBUS_POLICY
src/storage.c +229 -10

285 lines not on this page · raw message

src/storage.h +4 -0
index e1ec2cd4..5e703bac 100644
@@ -50,3 +50,7 @@ int storage_network_remove(enum security type, const char *ssid);
 
 struct l_settings *storage_known_frequencies_load(void);
 void storage_known_frequencies_sync(struct l_settings *known_freqs);
+
+void __storage_set_encryption_key(const uint8_t *key, size_t key_len);
+bool __storage_decrypt(struct l_settings *settings, const char *ssid,
+				bool *changed);
Signature · 1 line
2.31.1
author
#1 lore raw

PATCH v2 2/5 main: add SystemdEncrypt option, and initialize key

Recently systemd added the ability to pass secret credentials to services via LoadCredentialEncrypted/SetCredentialEncrypted. Once set up the service is able to read the decrypted credentials from a file. The file path is found in the environment variable CREDENTIALS_DIRECTORY + an identifier. The value of SystemdEncrypt should be set to the systemd key ID used when the credential was created.

When SystemdEncrypt is set IWD will attempt to read the decrypted secret from systemd. If at any point this fails warnings will be printed but IWD will continue normally. Its expected that any failures will result in the inability to connect to any networks which have previously encrypted the passphrase/PSK without re-entering the passphrase manually. This could happen, for example, if the systemd secret was changed.

Once the secret is read in it is set into storage to be used for profile encryption/decryption.

---
 src/main.c | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 54 insertions(+)
src/main.c +54 -0
index d0dbedc8..661303d1 100644
@@ -29,6 +29,7 @@
 #include <errno.h>
 #include <getopt.h>
 #include <signal.h>
+#include <sys/stat.h>
 #include <ell/ell.h>
 
 #include <ell/useful.h>
@@ -45,6 +46,7 @@
 #include "src/storage.h"
 #include "src/anqp.h"
 #include "src/netconfig.h"
+#include "src/crypto.h"
 
 #include "src/backtrace.h"
 
@@ -60,6 +62,7 @@ static const char *debugopt;
 static bool developeropt;
 static bool terminating;
 static bool nl80211_complete;
+static uint8_t system_key[32];
 
 static void main_loop_quit(struct l_timeout *timeout, void *user_data)
 {
@@ -397,6 +400,55 @@ done:
 	return r;
 }
 
+/*
+ * Initialize a systemd encryption key for encrypting/decrypting credentials.
+ */
+static void setup_system_key(void)
+{
+	const char *cred_dir;
+	ssize_t len;
+	struct stat st;
+	_auto_(l_free) uint8_t *key = NULL;
+	_auto_(l_free) char *path = NULL;
+	_auto_(l_free) char *key_id = NULL;
+
+	key_id = l_settings_get_string(iwd_config, "General", "SystemdEncrypt");
+	if (!key_id)
+		return;
+
+	cred_dir = getenv("CREDENTIALS_DIRECTORY");
+	if (!cred_dir) {
+		l_warn("SystemdEncrypt enabled, but CREDENTIALS_DIRECTORY not "
+			"set, check iwd.service file");
+		return;
+	}
+
+	path = l_strdup_printf("%s/%s", cred_dir, key_id);
+
+	if (stat(path, &st) < 0) {
+		l_warn("SystemdEncrypt enabled, but could not stat %s",
+			path);
+		return;
+	}
+
+	key = l_malloc(st.st_size);
+
+	len = read_file(key, st.st_size, "%s", path);
+	if (len < 0) {
+		l_warn("SystemdEncrypt enabled, but reading %s failed (%ld)",
+			path, len);
+		return;
+	}
+
+	if (!hkdf_expand(L_CHECKSUM_SHA256, key, st.st_size, "IWD System Key",
+				system_key, sizeof(system_key))) {
+		l_warn("Failed to expand system key");
+		return;
+	}
+
+	__storage_set_encryption_key(system_key, sizeof(system_key));
+}
+
 int main(int argc, char *argv[])
 {
 	int exit_status;
@@ -529,6 +581,8 @@ int main(int argc, char *argv[])
 	l_dbus_set_disconnect_handler(dbus, dbus_disconnected, NULL, NULL);
 	dbus_init(dbus);
 
+	setup_system_key();
+
 	exit_status = l_main_run_with_signal(signal_handler, NULL);
 
 	iwd_modules_exit();
Signature · 1 line
2.31.1
author
#2 lore raw

PATCH v2 3/5 tools: add decrypt-profile tool

In reply to James Prestwood

This tool will decrypt an IWD network profile which was previously encrypted using a systemd provided key. Either a text passphrase can be provided (--pass) or a file containing the secret (--file).

This can be useful for debugging, or recovering an encrypted profile after enabling SystemdEncrypt.

---
 Makefile.am             |   8 +-
 tools/decrypt-profile.c | 232 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 239 insertions(+), 1 deletion(-)
 create mode 100644 tools/decrypt-profile.c
Makefile.am +7 -1
index 35938d22..a106b56f 100644
@@ -362,7 +362,7 @@ man_MANS += wired/ead.8
 endif
 endif
 
-noinst_PROGRAMS += tools/probe-req
+noinst_PROGRAMS += tools/probe-req tools/decrypt-profile
 
 tools_probe_req_SOURCES = tools/probe-req.c src/mpdu.h src/mpdu.c \
 					src/ie.h src/ie.c \
@@ -372,6 +372,12 @@ tools_probe_req_SOURCES = tools/probe-req.c src/mpdu.h src/mpdu.c \
 					src/band.h src/band.c
 tools_probe_req_LDADD = $(ell_ldadd)
 
+tools_decrypt_profile_SOURCES = tools/decrypt-profile.c \
+					src/common.h src/common.c \
+					src/crypto.h src/crypto.c \
+					src/storage.h src/storage.c
+tools_decrypt_profile_LDADD = ${ell_ldadd}
+
 if HWSIM
 bin_PROGRAMS += tools/hwsim
 
tools/decrypt-profile.c new file +232 -0

232 lines not on this page · raw message

Signature · 1 line
2.31.1
#3 lore raw

Re: [PATCH v2 3/5] tools: add decrypt-profile tool

Hi James,

Quoted 3 lines · James Prestwood

This tool will decrypt an IWD network profile which was previously encrypted using a systemd provided key. Either a text passphrase can be provided (--pass) or a file containing the secret (--file).

You may want to provide some usage examples in the commit description. Maybe even mention stdin/--infile and stdout/-outfile use.

Quoted 14 lines

This can be useful for debugging, or recovering an encrypted profile after enabling SystemdEncrypt.

---
  Makefile.am             |   8 +-
  tools/decrypt-profile.c | 232 ++++++++++++++++++++++++++++++++++++++++
  2 files changed, 239 insertions(+), 1 deletion(-)

create mode 100644 tools/decrypt-profile.c

Makefile.am +0 -0
index 35938d22..a106b56f 100644

Makefile.am man_MANS += wired/ead.8 · line 365

Quoted 5 lines
Makefile.am +1 -1
@@ -362,7 +362,7 @@ man_MANS += wired/ead.8
  endif
  endif
 
-noinst_PROGRAMS += tools/probe-req
+noinst_PROGRAMS += tools/probe-req tools/decrypt-profile

Should this be an installed binary? Something like iwd-decrypt-profile?

Makefile.am man_MANS += wired/ead.8 · line 368

Quoted 3 lines
Makefile.am +3 -0
+#include <stdio.h>
+#include <unistd.h>
+#include <libgen.h> > +#include <fcntl.h>

Isn't sys/stat.h enough? In any case, you might want to group related #includes together.

Quoted 8 lines
Makefile.am +8 -0
+#include <getopt.h>
+#include <sys/stat.h>
+#include <ell/ell.h>
+
+#include "ell/useful.h"
+
+#include "src/storage.h"
+

<snip>

Quoted 8 lines
Makefile.am +8 -0
+int main(int argc, char *argv[])
+{
+	const char *pass = NULL;
+	const char *file = NULL;
+	const char *infile = NULL;
+	const char *outfile = NULL;
+	_auto_(l_free) char *ssid = NULL;
+	_auto_(l_free) char *decrypted = NULL;

Makefile.am

Quoted 10 lines
Makefile.am +10 -0
+	_auto_(l_settings_free) struct l_settings *settings = NULL;
+	_auto_(l_free) uint8_t *secret = NULL;
+	size_t secret_len = 0;
+	int ret = EXIT_FAILURE;
+	char profile[BUFSIZ];
+	ssize_t len = 0;
+	char *line;
+
+	if (isatty(0))
+		goto done_reading;

Err, why is the command line arguments not being parsed first? I mean you might want to use 'decrypt-profile --help' ?

Makefile.am

Quoted 3 lines
Makefile.am +3 -0
+
+	while ((line = fgets(profile + len, sizeof(profile) - len, stdin)))
+		len += strlen(profile + len);

You should check whether infile was specified prior to attempting this.

Quoted 29 lines
Makefile.am +29 -0
+
+done_reading:
+	for (;;) {
+		int opt;
+
+		opt = getopt_long(argc, argv, "pfhio",
+					main_options, NULL);
+		if (opt < 0)
+			break;
+
+		switch (opt) {
+		case 'p':
+			pass = optarg;
+			break;
+		case 'f':
+			file = optarg;
+			break;
+		case 'i':
+			infile = optarg;
+			break;
+		case 'o':
+			outfile = optarg;
+			break;
+		case 's':
+			ssid = l_strdup(optarg);
+			break;
+		case 'h':
+			usage();
+			return EXIT_SUCCESS;

Makefile.am

Quoted 10 lines
Makefile.am +10 -0
+		default:
+			goto failed;
+		}
+	}
+
+	if (!file && !pass) {
+		usage();
+		goto failed;
+	}
+

So if infile specified, read that. Otherwise, if no --ssid, fail. Read stdin...

Makefile.am

Quoted 12 lines
Makefile.am +12 -0
+	if (!len && !infile) {
+		printf("No input file (use stdin or --infile)\n\n");
+		usage();
+		goto failed;
+	}
+
+	if (len && infile) {
+		printf("Use only stdin or --infile for input profile\n\n");
+		usage();
+		goto failed;
+	}
+

Check for ssid and override that.

Quoted 4 lines
Makefile.am +4 -0
+	if (infile) {
+		/* Try and detect SSID from input file */
+		if (!ssid) {
+			char *dot;

Makefile.am

Quoted 10 lines
Makefile.am +10 -0
+
+			ssid = l_strdup(basename((char *)infile));
+			/* remove extension */
+			dot = strchr(ssid, '.');
+			if (!dot)
+				goto no_ssid;
+
+			*dot = '\0';
+		}
+

That isn't how ssids are stored in the profile. You're better off relying on storage_network_ssid_from_path() from storage.c here.

Makefile.am

Quoted 5 lines
Makefile.am +5 -0
+		len = read_file(profile, sizeof(profile), "%s", infile);
+		if (len < 0) {
+			printf("Could not read from %s (%ld)\n", infile, len);
+			goto failed;
+		}

Why not rely on the new functions from patch 1? We could introduce a full-path version of storage_network_open maybe.

Makefile.am

Quoted 11 lines
Makefile.am +11 -0
+	}
+
+	if (!ssid) {
+no_ssid:
+		printf("Can't detect SSID from input source (use --ssid)\n");
+		goto failed;
+	}
+
+	if (pass) {
+		secret_len = strlen(pass);
+		secret = l_memdup(pass, secret_len);

Why do we need the memdup?

Makefile.am

Quoted 2 lines
Makefile.am +2 -0
+	} else
+		secret = secret_from_file(file, &secret_len);

This could actually be an mmap instead.

Makefile.am

Quoted 11 lines
Makefile.am +11 -0
+
+	__storage_set_encryption_key(secret, secret_len);
+
+	settings = l_settings_new();
+
+	if (!l_settings_load_from_data(settings, profile, len)) {
+		printf("Profile is not formatted correctly\n");
+		goto failed;
+	}
+
+	if (!__storage_decrypt(settings, ssid, NULL)) {

Note that you will also get errors from this function as well. So I'm not sure if you want to re-design it to not print unnecessarily.

Quoted 23 lines
Makefile.am +22 -0
+		printf("Unable to decrypt profile\n");
+		goto failed;
+	}
+
+	decrypted = l_settings_to_data(settings, (size_t *)&len);
+
+	if (!outfile)
+		printf("%s\n", decrypted);
+	else {
+		int fd = open(outfile, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
+
+		if (fd < 0) {
+			printf("Unable to open %s (%d)\n\n", outfile, fd);
+			close(fd);
+			goto failed;
+		}
+
+		len = write(fd, decrypted, len);
+
+		close(fd);
+
+		if (len < 0) {

Makefile.am

Quoted 10 lines
Makefile.am +10 -0
+			printf("Unable to write to %s (%ld)\n\n", outfile, len);
+			goto failed;
+		}
+	}
+
+	ret = EXIT_SUCCESS;
+
+failed:
+	return ret;
+}

Regards,
-Denis

author
#4 lore raw

Re: [PATCH v2 3/5] tools: add decrypt-profile tool

Quoted 21 lines · Denis Kenzior

Hi James,

Quoted 3 lines · James Prestwood

This tool will decrypt an IWD network profile which was previously encrypted using a systemd provided key. Either a text passphrase can be provided (--pass) or a file containing the secret (--file).

You may want to provide some usage examples in the commit description.  Maybe
even mention stdin/--infile and stdout/-outfile use.

Quoted 10 lines

This can be useful for debugging, or recovering an encrypted profile after enabling SystemdEncrypt.
---
  Makefile.am             |   8 +- tools/decrypt-profile.c | 232
++++++++++++++++++++++++++++++++++++++++

  2 files changed, 239 insertions(+), 1 deletion(-)

  create mode 100644 tools/decrypt-profile.c

Quoted 13 lines

Makefile.am man_MANS += wired/ead.8 · line 365

Quoted 10 lines
Makefile.am +0 -0
index 35938d22..a106b56f 100644
@@ -362,7 +362,7 @@ man_MANS += wired/ead.8

  endif
  endif

Makefile.am +1 -1
-noinst_PROGRAMS += tools/probe-req
+noinst_PROGRAMS += tools/probe-req tools/decrypt-profile

Should this be an installed binary?  Something like iwd-decrypt- profile?

Sure, is there anything else I need to do for that? or anything named iwd-* gets installed?

Quoted 8 lines

Makefile.am

Quoted 4 lines
Makefile.am +3 -0
+#include <stdio.h>
+#include <unistd.h>
+#include <libgen.h> > +#include <fcntl.h>

Isn't sys/stat.h enough? In any case, you might want to group related #includes
together.

libgen.h is for basename(). The pattern I usually follow groups all system includes together, then ELL, then locals, so I could put a newline before <ell/ell.h> but I'm not sure how else I could group the system includes...

Quoted 112 lines
Quoted 9 lines
Makefile.am +8 -0
+#include <getopt.h>
+#include <sys/stat.h>
+#include <ell/ell.h>
+
+#include "ell/useful.h"
+
+#include "src/storage.h"
+

<snip>

Quoted 8 lines
Makefile.am +8 -0
+int main(int argc, char *argv[])
+{
+       const char *pass = NULL;
+       const char *file = NULL;
+       const char *infile = NULL;
+       const char *outfile = NULL;
+       _auto_(l_free) char *ssid = NULL;
+       _auto_(l_free) char *decrypted = NULL;

Makefile.am

Quoted 10 lines
Makefile.am +10 -0
+       _auto_(l_settings_free) struct l_settings *settings = NULL;
+       _auto_(l_free) uint8_t *secret = NULL;
+       size_t secret_len = 0;
+       int ret = EXIT_FAILURE;
+       char profile[BUFSIZ];
+       ssize_t len = 0;
+       char *line;
+
+       if (isatty(0))
+               goto done_reading;

Err, why is the command line arguments not being parsed first?  I mean you might
want to use 'decrypt-profile --help' ?

Quoted 4 lines

+
+       while ((line = fgets(profile + len, sizeof(profile) - len, stdin)))
+               len += strlen(profile + len);

You should check whether infile was specified prior to attempting this.

Quoted 29 lines
Makefile.am +29 -0
+
+done_reading:
+       for (;;) {
+               int opt;
+
+               opt = getopt_long(argc, argv, "pfhio",
+                                       main_options, NULL);
+               if (opt < 0)
+                       break;
+
+               switch (opt) {
+               case 'p':
+                       pass = optarg;
+                       break;
+               case 'f':
+                       file = optarg;
+                       break;
+               case 'i':
+                       infile = optarg;
+                       break;
+               case 'o':
+                       outfile = optarg;
+                       break;
+               case 's':
+                       ssid = l_strdup(optarg);
+                       break;
+               case 'h':
+                       usage();
+                       return EXIT_SUCCESS;

Makefile.am

Quoted 10 lines
Makefile.am +10 -0
+               default:
+                       goto failed;
+               }
+       }
+
+       if (!file && !pass) {
+               usage();
+               goto failed;
+       }
+

So if infile specified, read that.  Otherwise, if no --ssid, fail. Read stdin...

Quoted 6 lines

+       if (!len && !infile) {
+               printf("No input file (use stdin or -- infile)\n\n");
+               usage();
+               goto failed;
+       }

Quoted 8 lines

+
+       if (len && infile) {
+               printf("Use only stdin or --infile for input profile\n\n");
+               usage();
+               goto failed;
+       }
+

Check for ssid and override that.

Quoted 10 lines

+       if (infile) {
+               /* Try and detect SSID from input file */ +               if (!ssid) {
+                       char *dot;
+
+                       ssid = l_strdup(basename((char *)infile)); +                       /* remove extension */
+                       dot = strchr(ssid, '.');
+                       if (!dot)
+                               goto no_ssid;

Quoted 8 lines

Makefile.am

Quoted 4 lines
Makefile.am +4 -0
+
+                       *dot = '\0';
+               }
+

That isn't how ssids are stored in the profile.  You're better off relying on
storage_network_ssid_from_path() from storage.c here.

Ok, that one is actually safe to use so I'll use it instead.

Quoted 9 lines
Quoted 8 lines

+               len = read_file(profile, sizeof(profile), "%s", infile);
+               if (len < 0) {
+                       printf("Could not read from %s (%ld)\n", infile, len);
+                       goto failed;
+               }

Quoted 3 lines

Why not rely on the new functions from patch 1?  We could introduce a full-path
version of storage_network_open maybe.

We could if you want. I just didn't want to add another API.

Quoted 15 lines
Quoted 6 lines

+       }

Makefile.am +4 -0
+
+       if (!ssid) {
+no_ssid:
+               printf("Can't detect SSID from input source (use --
Quoted 7 lines

ssid)\n");
+               goto failed;
+       }
+
+       if (pass) {
+               secret_len = strlen(pass);
+               secret = l_memdup(pass, secret_len);

Why do we need the memdup?

Consistency with secret_from_file(), but yes, mmap will avoid the need for this.

Quoted 6 lines
Quoted 3 lines

+       } else
+               secret = secret_from_file(file, &secret_len);

This could actually be an mmap instead.

Quoted 15 lines

Makefile.am

Quoted 11 lines
Makefile.am +11 -0
+
+       __storage_set_encryption_key(secret, secret_len);
+
+       settings = l_settings_new();
+
+       if (!l_settings_load_from_data(settings, profile, len)) {
+               printf("Profile is not formatted correctly\n");
+               goto failed;
+       }
+
+       if (!__storage_decrypt(settings, ssid, NULL)) {

Note that you will also get errors from this function as well.  So I'm not sure
if you want to re-design it to not print unnecessarily.

__storage_decrypt() shouldn't print anything in this context since I haven't enabled logging (previous patch sets did though).

Quoted 40 lines
Quoted 31 lines

+               printf("Unable to decrypt profile\n"); +               goto failed;
+       }

Makefile.am +7 -0
+
+       decrypted = l_settings_to_data(settings, (size_t *)&len);
+
+       if (!outfile)
+               printf("%s\n", decrypted);
+       else {
+               int fd = open(outfile, O_CREAT | O_WRONLY, S_IRUSR

| S_IWUSR);
+
+               if (fd < 0) {
+                       printf("Unable to open %s (%d)\n\n", outfile, fd);
+                       close(fd);
+                       goto failed;
+               }

Makefile.am +7 -0
+
+               len = write(fd, decrypted, len);
+
+               close(fd);
+
+               if (len < 0) {
+                       printf("Unable to write to %s (%ld)\n\n",

outfile, len);
+                       goto failed;
+               }
+       }

Makefile.am

Quoted 6 lines
Makefile.am +6 -0
+
+       ret = EXIT_SUCCESS;
+
+failed:
+       return ret;
+}

Regards,
-Denis

#5 lore raw

Re: [PATCH v2 3/5] tools: add decrypt-profile tool

Hi James,

Quoted 9 lines
Quoted 7 lines

tools/decrypt-profile.c

Quoted 3 lines
tools/decrypt-profile.c new file +3 -0
+#include <stdio.h>
+#include <unistd.h>
+#include <libgen.h> > +#include <fcntl.h>

Isn't sys/stat.h enough? In any case, you might want to group related #includes
together.

libgen.h is for basename(). The pattern I usually follow groups all

I meant for fcntl.h and stat.h. They usually go together. Having libgen.h in between was sort of unusual.

Quoted 7 lines
Quoted 4 lines

Note that you will also get errors from this function as well.  So I'm not sure
if you want to re-design it to not print unnecessarily.

__storage_decrypt() shouldn't print anything in this context since I haven't enabled logging (previous patch sets did though).

Ok fair enough. I couldn't recall whether l_error was always printed or not. Still, it may be better to return a -ERRNO and print based on that from a higher level function.

Regards,
-Denis

author
#6 lore raw

PATCH v2 4/5 doc: document SystemdEncrypt

In reply to James Prestwood
---
 src/iwd.config.rst  | 16 ++++++++++++++++
 src/iwd.network.rst |  6 +++++-
 2 files changed, 21 insertions(+), 1 deletion(-)
src/iwd.config.rst +16 -0
index 54943702..a3d19fe5 100644
@@ -188,6 +188,22 @@ The group ``[General]`` contains general settings.
        by the kernel so if kernels/drivers exist which don't support OCV it can
        be disabled here.
 
+   * - SystemdEncrypt
+     - Value: Systemd key ID
+
+       Enables network profile encryption using a systemd provided secret key.
+       Once enabled all PSK/8021x network profiles will be encrypted
+       automatically. Once the profile is encrypted there is no way of going
+       back using IWD alone. A tool, decrypt-profile, is provided assuming the
+       secret is known which will decrypt a profile. This decrypted profile
+       could manually be set to /var/lib/iwd to 'undo' any profile encryption,
+       but its going to be a manual process.
+
+       Setting up systemd to provide the secret is left up to the user as IWD
+       has no way of performing this automatically. The systemd options required
+       are LoadCredentialEncrypted or SetCredentialEncrypted, and the secret
+       identifier should be named whatever SystemdEncrypt is set to.
+
 Network
 -------
 
src/iwd.network.rst +5 -1
index e3d1a90a..34f8de1a 100644
@@ -179,7 +179,11 @@ Network Authentication Settings
 -------------------------------
 
 The group ``[Security]`` contains settings for Wi-Fi security and
-authentication configuration.
+authentication configuration. This group can be encrypted by enabling
+``SystemdEncrypt``, see *iwd.config* for details on this option. If this section
+is encrypted (only contains EncryptedSalt/EncryptedSecurity) it should not be
+modified. Modifying these values will result in the inability to connect to that
+network.
 
 .. list-table::
    :header-rows: 0
Signature · 1 line
2.31.1
author
#7 lore raw

PATCH v2 5/5 auto-t: add test for encrypted profiles

In reply to James Prestwood
---
 .../testEncryptedProfiles/connection_test.py  | 154 ++++++++++++++++++
 autotests/testEncryptedProfiles/hw.conf       |   6 +
 autotests/testEncryptedProfiles/iwd-secret    |   1 +
 autotests/testEncryptedProfiles/main.conf     |   2 +
 autotests/testEncryptedProfiles/ssidCCMP.conf |  10 ++
 autotests/testEncryptedProfiles/ssidCCMP.psk  |   2 +
 6 files changed, 175 insertions(+)
 create mode 100644 autotests/testEncryptedProfiles/connection_test.py
 create mode 100644 autotests/testEncryptedProfiles/hw.conf
 create mode 100644 autotests/testEncryptedProfiles/iwd-secret
 create mode 100644 autotests/testEncryptedProfiles/main.conf
 create mode 100644 autotests/testEncryptedProfiles/ssidCCMP.conf
 create mode 100644 autotests/testEncryptedProfiles/ssidCCMP.psk
autotests/testEncryptedProfiles/connection_test.py new file +154 -0
new file mode 100644
index 00000000..dd4892ca
@@ -0,0 +1,154 @@
+#!/usr/bin/python3
+
+import unittest
+import sys
+
+sys.path.append('../util')
+import iwd
+import os
+from iwd import IWD
+from iwd import NetworkType
+from iwd import PSKAgent
+
+class Test(unittest.TestCase):
+    def profile_is_encrypted(self, profile):
+        with open('/tmp/iwd/' + profile) as f:
+            contents = f.read()
+
+        if 'Passphrase' in contents:
+            return False
+
+        return True
+
+    def validate(self, wd):
+        devices = wd.list_devices(1)
+        device = devices[0]
+
+        ordered_network = device.get_ordered_network('ssidCCMP')
+
+        self.assertEqual(ordered_network.type, NetworkType.psk)
+
+        condition = 'not obj.connected'
+        wd.wait_for_object_condition(ordered_network.network_object, condition)
+
+        ordered_network.network_object.connect()
+
+        condition = 'obj.state == DeviceState.connected'
+        wd.wait_for_object_condition(device, condition)
+
+        device.disconnect()
+
+        condition = 'not obj.connected'
+        wd.wait_for_object_condition(ordered_network.network_object, condition)
+
+    # Tests that an existing plaintext profile gets encrypted
+    def test_new_profile(self):
+        IWD.copy_to_storage('ssidCCMP.psk')
+
+        mtime = os.path.getmtime('/tmp/iwd/' + 'ssidCCMP.psk')
+        self.assertFalse(self.profile_is_encrypted('ssidCCMP.psk'))
+
+        wd = IWD(True)
+
+        # Make sure profile was accepted
+        condition = 'len(obj.list_known_networks()) == 1'
+        wd.wait_for_object_condition(wd, condition)
+
+        # Check the file was modified (should be encrypted now)
+        self.assertNotEqual(mtime, os.path.getmtime('/tmp/iwd/' + 'ssidCCMP.psk'))
+
+        self.validate(wd)
+
+        self.assertTrue(self.profile_is_encrypted('ssidCCMP.psk'))
+
+    # Tests that a new connection with agent gets written to an encrypted profile
+    def test_agent_profile(self):
+        wd = IWD(True)
+
+        psk_agent = PSKAgent("secret123")
+        wd.register_psk_agent(psk_agent)
+
+        with self.assertRaises(FileNotFoundError):
+            self.profile_is_encrypted('ssidCCMP.psk')
+
+        self.validate(wd)
+
+        self.assertTrue(self.profile_is_encrypted('ssidCCMP.psk'))
+
+        wd.unregister_psk_agent(psk_agent)
+
+    # Tests that an invalid profile gets re-written after an agent request
+    def test_invalid_profile_rewritten(self):
+        bad_config = '[Security]\nPassphrase=incorrect\n'
+        os.system('echo "%s" > /tmp/iwd/ssidCCMP.psk' % bad_config)
+
+        wd = IWD(True)
+
+        condition = 'len(obj.list_known_networks()) == 1'
+        wd.wait_for_object_condition(wd, condition)
+
+        # IWD should still encrypt the profile automatically
+        self.assertTrue(self.profile_is_encrypted('ssidCCMP.psk'))
+
+        # This should fail
+        with self.assertRaises(iwd.FailedEx):
+            self.validate(wd)
+
+        psk_agent = PSKAgent("secret123")
+        wd.register_psk_agent(psk_agent)
+
+        self.validate(wd)
+
+        self.assertTrue(self.profile_is_encrypted('ssidCCMP.psk'))
+
+    # Tests that a profile that doesn't decrypt wont become a known network
+    def test_decryption_failure(self):
+        bad_config = \
+'''
+[Security]
+EncryptedSalt=000102030405060708090a0b0c0d0e0f
+EncryptedSecurity=aabbccddeeff00112233445566778899
+'''
+        os.system('echo "%s" > /tmp/iwd/ssidCCMP.psk' % bad_config)
+
+        wd = IWD(True)
+
+        self.assertEqual(wd.list_known_networks(), [])
+
+    def test_runtime_profile(self):
+        wd = IWD(True)
+
+        self.assertEqual(wd.list_known_networks(), [])
+
+        # Add profile after IWD starts
+        IWD.copy_to_storage('ssidCCMP.psk')
+
+        self.validate(wd)
+
+        # Should now be encrypted
+        self.assertTrue(self.profile_is_encrypted('ssidCCMP.psk'))
+
+        with open('/tmp/iwd/ssidCCMP.psk') as f:
+            profile = f.read()
+
+        # Edit the profile, corrupting it
+        profile.replace('EncryptedSecurity=', 'EncryptedSecurity=00')
+
+        devices = wd.list_devices(1)
+        device = devices[0]
+        condition = 'obj.state == DeviceState.disconnected'
+        wd.wait_for_object_condition(device, condition)
+
+    def tearDown(self):
+        IWD.clear_storage()
+
+    @classmethod
+    def setUpClass(cls):
+        os.environ['CREDENTIALS_DIRECTORY'] = '/tmp'
+
+    @classmethod
+    def tearDownClass(cls):
+        IWD.clear_storage()
+
+if __name__ == '__main__':
+    unittest.main(exit=True)
autotests/testEncryptedProfiles/hw.conf new file +6 -0
new file mode 100644
index 00000000..de81e1e2
@@ -0,0 +1,6 @@
+[SETUP]
+num_radios=2
+start_iwd=0
+
+[HOSTAPD]
+rad0=ssidCCMP.conf
autotests/testEncryptedProfiles/iwd-secret new file +1 -0
new file mode 100644
index 00000000..c2afca48
@@ -0,0 +1 @@
+secret123
autotests/testEncryptedProfiles/main.conf new file +2 -0
new file mode 100644
index 00000000..35d40c5e
@@ -0,0 +1,2 @@
+[General]
+SystemdEncrypt=iwd-secret
autotests/testEncryptedProfiles/ssidCCMP.conf new file +10 -0
new file mode 100644
index 00000000..c79f5e55
@@ -0,0 +1,10 @@
+hw_mode=g
+channel=1
+ssid=ssidCCMP
+
+wpa=2
+wpa_pairwise=CCMP
+wpa_passphrase=secret123
+
+ieee80211w=2
+wpa_key_mgmt=WPA-PSK-SHA256
autotests/testEncryptedProfiles/ssidCCMP.psk new file +2 -0
new file mode 100644
index 00000000..abafdb66
@@ -0,0 +1,2 @@
+[Security]
+Passphrase=secret123
Signature · 1 line
2.31.1