storage: convert storage to a module
James Prestwood
PATCH v7 1/8 storage: convert storage to a module
--- src/main.c | 6 --- src/storage.c | 102 ++++++++++++++++++++++++++------------------------ src/storage.h | 2 - 3 files changed, 54 insertions(+), 56 deletions(-)
src/main.c +0 -6
@@ -498,9 +498,6 @@ int main(int argc, char *argv[]) exit_status =EXIT_FAILURE ; -if (!storage_create_dirs ()) - goto failed_dirs; - genl =l_genl_new ();if (!genl) {l_error ("Failed to open generic netlink socket" );
@@ -542,9 +539,6 @@ failed_rtnl:l_genl_unref (genl); failed_genl: -storage_cleanup_dirs (); - -failed_dirs:l_settings_free (iwd_config);l_timeout_remove (timeout);l_main_exit ();
src/storage.c +54 -48
117 lines not on this page · raw message
src/storage.h +0 -2
@@ -33,8 +33,6 @@ ssize_t write_file(const void *buffer, size_t len, bool preserve_times, __attribute__((format(printf, 4, 5)));bool storage_is_file (const char *filename); -bool storage_create_dirs (void ); -void storage_cleanup_dirs (void );char *storage_get_path (const char *format, ...);char *storage_get_hotspot_path (const char *format, ...);
Signature · 1 line
2.34.1
James Prestwood
PATCH v7 2/8 knownnetworks: add dependency on storage
Hotspot should be ok since its dependent on knownnetworks
--- src/knownnetworks.c | 1 + 1 file changed, 1 insertion(+)
src/knownnetworks.c +1 -0
@@ -1123,6 +1123,7 @@ static void known_networks_exit(void) } IWD_MODULE(known_networks, known_networks_init, known_networks_exit) +IWD_MODULE_DEPENDS (known_networks, storage);static void known_frequencies_exit (void ) {
Signature · 1 line
2.34.1
James Prestwood
PATCH v7 3/8 storage: implement network profile encryption
In reply to James PrestwoodSome 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.
A few private storage.c helpers were added to serve several purposes:
__storage_set_encryption_key():
This sets the encryption key direct from systemd then uses extract and expand to create a new fixed length key to do encryption/decryption.
__storage_decrypt():
Low level API to decrypt an l_settings object using a previously set key and the SSID/name for the network. This returns a 'changed' out parameter signifying that the settings need to be encrypted and re-written to disk. The purpose of exposing this is for a standalone decryption tool which does not re-write any settings.
__storage_open():
Wrapper around __storage_decrypt() that handles re-writing a new profile to disk. This was exposed in order to support hotspot profiles.
__storage_encrypt():
Encrypts an l_settings object and returns the full profile as data
--- Makefile.am | 3 +- src/storage.c | 287 ++++++++++++++++++++++++++++++++++++++++++++++++-- src/storage.h | 8 ++ 3 files changed, 286 insertions(+), 12 deletions(-)
v7:
* Added mlock/munlock to the system_key buffer
Makefile.am +2 -1
@@ -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 +276 -11
345 lines not on this page · raw message
src/storage.h +8 -0
@@ -48,3 +48,11 @@ 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); +int __storage_decrypt (struct l_settings *settings,const char *ssid, +bool *changed); +char *__storage_encrypt (const struct l_settings *settings,const char *ssid, +size_t *out_len); +bool __storage_open (struct l_settings *settings,const char *path, +enum security type,const char *name);
Signature · 1 line
2.34.1
Marcel Holtmann
Re: [PATCH v7 3/8] storage: implement network profile encryption
Hi James,
Quoted 170 lines
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_openwill be provided the decrypted profile, and will be unaware it was ever encrypted in the first place. Similarly whennetwork_storage_syncis called the profile will by automatically encrypted and written to disk without the caller needing to do anything special.A few private
storage.chelpers were added to serve several purposes:
__storage_set_encryption_key():
This sets the encryption key direct from systemd then uses extract and expand to create a new fixed length key to do encryption/decryption.
__storage_decrypt():
Low level API to decrypt anl_settingsobject using a previously set key and the SSID/name for the network. This returns a 'changed' out parameter signifying that the settings need to be encrypted and re-written to disk. The purpose of exposing this is for a standalone decryption tool which does not re-write any settings.
__storage_open():
Wrapper around__storage_decrypt()that handles re-writing a new profile to disk. This was exposed in order to support hotspot profiles.
__storage_encrypt():
Encrypts anl_settingsobject and returns the full profile as data
---Makefile.am | 3 +- src/storage.c | 287 ++++++++++++++++++++++++++++++++++++++++++++++++-- src/storage.h | 8 ++ 3 files changed, 286 insertions(+), 12 deletions(-)v7:
* Added mlock/munlock to thesystem_keybufferMakefile.am +2
-1@@ -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_POLICYsrc/storage.c +67
-0@@ -39,12 +39,15 @@#include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> +#include <sys/mman.h> #include <ell/ell.h> +#include "ell/useful.h" #include "src/common.h" #include "src/storage.h" #include "src/module.h" +#include "src/crypto.h" #define STORAGE_DIR_MODE (S_IRUSR | S_IWUSR | S_IXUSR)#define STORAGE_FILE_MODE (S_IRUSR | S_IWUSR)@@ -53,6 +56,8 @@static char *storage_path =NULL ;static char *storage_hotspot_path =NULL ; +static uint8_t system_key[32 ]; +static bool system_key_set = false;static int create_dirs (const char *filename) {@@ -300,24 +305,254 @@ const char *storage_network_ssid_from_path(const char *path,return buf; } +/* Groups requiring encryption (if enabled) */ +static char *encrypt_groups[] = { +"Security" , +NULL +}; + +static bool encrypt_group (const char *group) +{ +char **g; + +for (g = encrypt_groups; *g; g++) { +if (!strcmp (*g, group)) +return true; + } + +return false; +} + +/* +* Encrypt needed groups of 'settings' without modifying the object. Returns +* the entire settings object as data, with encrypted groups as a bytestring +* set as the value to [Security].EncryptedSecurity. This also includes any +* embedded groups. +* +* Note: If encryption is not enabled or there is no Security group this is +* effectively l_settings_to_data. +*/ +char *__storage_encrypt (const struct l_settings *settings,const char *ssid, +size_t *out_len) +{ +struct iovec ad[2 ]; +uint8_t salt[32 ]; +size_t len; + _auto_(l_settings_free) struct l_settings *to_encrypt = NULL; + _auto_(l_settings_free) struct l_settings *original = NULL; + _auto_(l_free) char *plaintext = NULL; + _auto_(l_free) uint8_t *enc = NULL; + _auto_(l_strv_free) char **groups = NULL; +char **i; + +if (!system_key_set || !l_settings_has_group (settings,"Security" )) +return l_settings_to_data (settings, out_len); + +/* +* Make two copies of the settings: One will contain only data to be +* encrypted (to_encrypt), the other will contain data to be left +* unencrypted (original). At the end any encrypted data will be set +* into 'original' as EncryptedSecurity. +*/ + to_encrypt =l_settings_clone (settings); + original =l_settings_clone (settings); + + groups =l_settings_get_groups (to_encrypt); +for (i = groups; *i; i++) { +if (encrypt_group (*i)) +l_settings_remove_group (original, *i); +else +l_settings_remove_group (to_encrypt, *i); + } + +l_settings_remove_embedded_groups (original); +
src/storage.c const char *storage_network_ssid_from_path(const char *path, · line 379
Quoted 10 lines
src/storage.c +10
-0+ plaintext =l_settings_to_data (to_encrypt, &len); +if (!plaintext) +return NULL ; + +l_getrandom (salt,32 ); + + ad[0 ].iov_base = (void *) salt; + ad[0 ].iov_len =32 ; + ad[1 ].iov_base = (void *) ssid; + ad[1 ].iov_len =strlen (ssid);
you want to use the SSID as string here since that is how we store it? Or would you rather use the fixed size binary blob of the SSID on how it goes over the air? So a comment is required here.
src/storage.c const char *storage_network_ssid_from_path(const char *path, · line 391
Quoted 12 lines
src/storage.c +12
-0+ + enc =l_malloc (len +16 ); + +if (!aes_siv_encrypt (system_key,sizeof (system_key), plaintext, len, + ad,2 , enc)) { +l_error ("Could not encrypt [Security] group" ); +return NULL ; + } + +l_settings_set_bytes (original,"Security" ,"EncryptedSalt" , salt,32 ); +l_settings_set_bytes (original,"Security" ,"EncryptedSecurity" , + enc, len +16 );
You do need to comment the + 16 since it is not obvious.
Quoted 84 lines
src/storage.c +84
-0+ +return l_settings_to_data (original, out_len); +} + +/* +* Decrypt data in [Security].EncryptedSecurity. This data also includes +* embedded groups potentially. Once decrypted the data is put back into the +* object. +* +* Note: if encryption is not enabled or there is no Security group settings +* is not modified. +*/ +int __storage_decrypt (struct l_settings *settings,const char *ssid, +bool *changed) +{ + _auto_(l_settings_free) struct l_settings *security = NULL; + _auto_(l_free) uint8_t *encrypted = NULL; + _auto_(l_free) uint8_t *decrypted = NULL; + _auto_(l_free) uint8_t *salt = NULL; + _auto_(l_strv_free) char **embedded = NULL; + _auto_(l_strv_free) char **groups = NULL; +char **i; +size_t elen, slen; +struct iovec ad[2 ]; + +if (!system_key_set) + goto done; + +if (!l_settings_has_group (settings,"Security" )) + goto done; + + encrypted =l_settings_get_bytes (settings,"Security" , +"EncryptedSecurity" , &elen); + salt =l_settings_get_bytes (settings,"Security" , +"EncryptedSalt" , &slen); + +/* +* Either profile has never been loaded after enabling encryption or is +* missing Encrypted{Salt,Security} values. If either are missing this +* profile is corrupted and must be fixed. +*/ +if (!(encrypted && salt)) { +/* Profile corrupted */ +if (encrypted || salt) { +l_warn ("Profile %s is corrupted reconfigure manually" , + ssid); +return -EBADMSG ; + } + +if (changed) + *changed = true; + +return 0 ; + } + + decrypted =l_malloc (elen -16 +1 ); + + ad[0 ].iov_base = (void *)salt; + ad[0 ].iov_len = slen; + ad[1 ].iov_base = (void *)ssid; + ad[1 ].iov_len =strlen (ssid); + +if (!aes_siv_decrypt (system_key,sizeof (system_key), encrypted, elen, + ad,2 , decrypted)) { +l_error ("Could not decrypt %s profile, did the secret change?" , + ssid); +return -ENOKEY ; + } + + decrypted[elen -16 ] ='\0' ; + +/* +* Remove any groups that are marked as encrypted (plus embedded), +* and copy the decrypted groups back into settings. +*/ + groups =l_settings_get_groups (settings); +for (i = groups; *i; i++) { +if (encrypt_group (*i)) +l_settings_remove_group (settings, *i); + } + +l_settings_remove_embedded_groups (settings); + +/*
src/storage.c const char *storage_network_ssid_from_path(const char *path, · line 485
Quoted 10 lines
src/storage.c +10
-0+* Load decrypted data into existing settings. This is not how the API +* is indended to be used (since this could result in duplicate groups) +* but since the Security group was just removed and EncryptedSecurity +* should only contain a Security group its safe to use it this way. +*/ +if (!l_settings_load_from_data (settings, (const char *) decrypted, + elen -16 )) { +l_error ("Could not load decrypted security group" ); +return -EBADMSG ; + }
Same as with the other functions. Comments required on the input/output choices.
Quoted 112 lines
src/storage.c +71
-11+ +done: +if (changed) + *changed = false; + +return 0 ; +} + +/* +* Direct open() by path. 'name' is used for decryption and depends on the +* module calling. For regular storage operations 'name' is the SSID. For +* hotspot 'name' is the consortium name (since the SSID is not always the +* same). +*/ +bool __storage_open (struct l_settings *settings,const char *path, +enum security type,const char *name) +{ +bool changed; + _auto_(l_free) char *encrypted = NULL; +size_t elen; + +if (type ==SECURITY_NONE ) +return true; + +if (__storage_decrypt (settings, name, &changed) <0 ) +return false; + +if (!changed) +return true; + +/* Profile never encrypted before. Encrypt and write to disk */ + encrypted =__storage_encrypt (settings, name, &elen); +if (!encrypted) { +l_error ("Could not encrypt new profile %s" , name); +return false; + } + +if (write_file (encrypted, elen, false,"%s" , path) <0 ) { +l_error ("Failed to write out encrypted profile" ); +return false; + } + +l_debug ("Encrypted a new profile %s" , path); + +return true; +} +struct l_settings *storage_network_open (enum security type,const char *ssid) {struct l_settings *settings; -char *path; + _auto_(l_free) char *path = NULL;if (ssid ==NULL )return NULL ; path =storage_get_network_file_path (type, ssid); + settings =l_settings_new (); -if (!l_settings_load_from_file (settings, path)) { -l_settings_free (settings); - settings =NULL ; - } +if (!l_settings_load_from_file (settings, path)) + goto error; + +if (!__storage_open (settings, path, type, ssid)) + goto error; -l_free (path);return settings; + +error: +l_settings_free (settings); +return NULL ; }int storage_network_touch (enum security type,const char *ssid)@@ -341,15 +576,19 @@ int storage_network_touch(enum security type, const char *ssid)void storage_network_sync (enum security type,const char *ssid,struct l_settings *settings) { -char *data; + _auto_(l_free) char *data = NULL; + _auto_(l_free) char *path = NULL;size_t length =0 ; -char *path; path =storage_get_network_file_path (type, ssid); - data =l_settings_to_data (settings, &length); + data =__storage_encrypt (settings, ssid, &length); + +if (!data) { +l_error ("Unable to sync profile %s" , ssid); +return ; + } +write_file (data, length, true,"%s" , path); -l_free (data); -l_free (path); }int storage_network_remove (enum security type,const char *ssid)@@ -417,6 +656,27 @@ bool storage_is_file(const char *filename)return false; } +/* +* Initialize a systemd encryption key for encrypting/decrypting credentials. +* This uses the 'extract and expand' concept from RFC 5869 to derive a new, +* fixed length, key.
src/storage.c bool storage_is_file(const char *filename) · line 672
Quoted 10 lines
src/storage.c +10
-0+*/ +void __storage_set_encryption_key (const uint8_t *key,size_t key_len) +{ +uint8_t tmp[32 ]; + +if (!hkdf_extract (L_CHECKSUM_SHA256 ,NULL ,0 ,1 , tmp, key, key_len)) +return ; + +if (!hkdf_expand (L_CHECKSUM_SHA256 , tmp,sizeof (tmp),"IWD System Key" , + system_key,sizeof (system_key)))
So I have a dislike putting the IWD name in front of it. They are daemon specific to begin with. I would leave it at “System Key”. Key names should be domain specific and any attempt to make the globally unique will fail anyway.
The actual key is required to be provided by a human user creating the unit file. And thus it is specific to iwd’s unit file. If they end up re-using this for another daemon, then that is just plain stupid.
Now that all said, I am not sure you are using this correctly. I know you have defined the extract and expand functions, but I was really more thinking about the simple version of this:
interim-key = func(SALT, system-key) encryption-key = func(interim-key, “System Key”)
While the SALT is just a 32 octet random string instead of the default sequence of 0x00.
Since later on your are using AES for the encryption with a 128-bit key, I would recommend to just go with AES-CMAC. That means you can define func as this:
func(K, ID) = AES-CMAC(K, ID)
Where K is the 128-bit key into the AES-CMAS hash.
src/storage.c bool storage_is_file(const char *filename) · line 675
Quoted 3 lines
src/storage.c +3
-0+return ; + +L_WARN_ON (mlock (system_key,sizeof (system_key)) <0 );
Actually, better to just abort here. Let it fail if we can’t lock the memory. Otherwise also you call to unlock below is unbalanced.
Quoted 25 lines
src/storage.c +9
-0+ + system_key_set = true; +} +static int storage_init (void ) {const char *state_dir;@@ -466,6 +726,11 @@ static void storage_exit(void) {l_free (storage_path);l_free (storage_hotspot_path); + +if (system_key_set) { +explicit_bzero (system_key,sizeof (system_key)); +munlock (system_key,sizeof (system_key)); + } }IWD_MODULE (storage, storage_init, storage_exit);src/storage.h +0
-0@@ -48,3 +48,11 @@ int storage_network_remove(enum security type, const char *ssid);
src/storage.h int storage_network_remove(enum security type, const char *ssid); · line 58
Quoted 10 lines
src/storage.h +8
-0struct 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); +int __storage_decrypt (struct l_settings *settings,const char *ssid, +bool *changed); +char *__storage_encrypt (const struct l_settings *settings,const char *ssid, +size_t *out_len); +bool __storage_open (struct l_settings *settings,const char *path, +enum security type,const char *name);
Regards
Marcel
James Prestwood
Re: [PATCH v7 3/8] storage: implement network profile encryption
Hi Marcel,
<snip>
Quoted 9 lines
Quoted 5 lines
+
+ ad[0].iov_base = (void *) salt;
+ ad[0].iov_len = 32;
+ ad[1].iov_base = (void *) ssid;
+ ad[1].iov_len = strlen(ssid);you want to use the SSID as string here since that is how we store it? Or would you rather use the fixed size binary blob of the SSID on how it goes over the air? So a comment is required here.
So pad the SSID with zero's? I'm not sure this really adds much except an extra step. But I can leave a comment, or if you have a specific reason for doing it I'm all ears.
Quoted 2 lines
<snip>
Quoted 25 lines
Quoted 13 lines
+/*
+ * Initialize a systemd encryption key for encrypting/decrypting credentials.
+ * This uses the 'extract and expand' concept from RFC 5869 to derive a new,
+ * fixed length, key.
+ */
+void__storage_set_encryption_key(const uint8_t *key, size_t key_len)src/storage.c +4
-0+{ + uint8_t tmp[32]; + + if (!hkdf_extract(L_CHECKSUM_SHA256, NULL, 0, 1, tmp, key,Quoted 6 lines
key_len))
+ return;
+
+ if (!hkdf_expand(L_CHECKSUM_SHA256, tmp, sizeof(tmp), "IWD System Key",
+ system_key,sizeof(system_key)))So I have a dislike putting the IWD name in front of it. They are daemon specific to begin with. I would leave it at “System Key”. Key names should be domain specific and any attempt to make the globally unique will fail anyway.
Quoted 4 lines
The actual key is required to be provided by a human user creating the unit file. And thus it is specific to iwd’s unit file. If they end up re-using this for another daemon, then that is just plain stupid.
Sure, makes sense.
Quoted 11 lines
Now that all said, I am not sure you are using this correctly. I know you have defined the extract and expand functions, but I was really more thinking about the simple version of this:
interim-key =
func(SALT, system-key)encryption-key =func(interim-key, “System Key”)While the SALT is just a 32 octet random string instead of the default sequence of
0x00.
Quoted 7 lines
Since later on your are using AES for the encryption with a 128-bit key, I would recommend to just go with AES-CMAC. That means you can define func as this:
func(K, ID) = AES-CMAC(K, ID)
Where K is the 128-bit key into the AES-CMAS hash.
Maybe I'm missing something with how AES-CMAC works, but using a random salt for the system key like this is going to result in a different system key on each boot/run right? So I don't think that is going to work. RFC 5869 mentions using a zero salt like I do here, basically 'salt' is optional.
Also I'm not sure why we want to define our own KDF (using AES-CMAC) when extract-and-expand already exists for this purpose. I think NIST even recommends using extract-and-expand KDFs.
Quoted 51 lines
Quoted 4 lines
+ return;
+
+ L_WARN_ON(mlock(system_key,sizeof(system_key)) < 0);Actually, better to just abort here. Let it fail if we can’t lock the memory. Otherwise also you call to unlock below is unbalanced.
Quoted 32 lines
src/storage.c +4
-0+ + system_key_set = true; +} +static int
storage_init(void)
{
const char*state_dir;src/storage.c +5
-0@@ -466,6 +726,11 @@ static void storage_exit(void) { l_free(storage_path); l_free(storage_hotspot_path); + + if (system_key_set) { + explicit_bzero(system_key, sizeof(system_key)); + munlock(system_key, sizeof(system_key)); + } }IWD_MODULE (storage, storage_init, storage_exit);src/storage.h +0
-0@@ -48,3 +48,11 @@ 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);src/storage.h +2
-0+ +void __storage_set_encryption_key(const uint8_t *key, size_t
key_len);Quoted 8 lines
+int __storage_decrypt(struct
l_settings*settings, const char *ssid,
+ bool *changed);
+char *__storage_encrypt(const structl_settings*settings, const char *ssid,
+ size_t*out_len);
+bool __storage_open(structl_settings*settings, const char *path, + enum security type, const char *name);Regards
Quoted 2 lines
Marcel
Thanks,
James
James Prestwood
PATCH v7 4/8 hotspot: implement hotspot profile encryption
In reply to James PrestwoodUsing __storage_open() hotspot can also support profile encyption. The hotspot consortium name is used as the 'ssid' since this stays consistent between hotspot networks for any profile.
--- src/hotspot.c | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-)
src/hotspot.c +21 -5
@@ -95,12 +95,18 @@ static struct l_settings *hotspot_network_open(struct network_info *info) settings =l_settings_new (); -if (!l_settings_load_from_file (settings, config->filename)) { -l_settings_free (settings); -return NULL ; - } +if (!l_settings_load_from_file (settings, config->filename)) + goto error; + +if (!__storage_open (settings, config->filename,SECURITY_8021X , + config->name)) + goto error;return settings; + +error: +l_settings_free (settings); +return NULL ; } static void hotspot_network_sync(struct network_info *info,
@@ -111,7 +117,12 @@ static void hotspot_network_sync(struct network_info *info, struct hs20_config *config = l_container_of(info, struct hs20_config, super); - data =l_settings_to_data (settings, &length); + data =__storage_encrypt (settings, config->name, &length); +if (!data) { +l_error ("Unable to sync profile %s" , config->filename); +return ; + } +write_file (data, length, true,"%s" , config->filename);l_free (data); }
@@ -338,6 +349,11 @@ static struct hs20_config *hs20_config_new(struct l_settings *settings, goto free_values; } +if (!__storage_open (settings, filename,SECURITY_8021X , name)) { +l_error ("Could not open hotspot profile %s" , filename); + goto free_values; + } + config = l_new(struct hs20_config, 1);if (hessid_str) {
Signature · 1 line
2.34.1
James Prestwood
PATCH v7 5/8 main: add SystemdEncrypt option, and initialize key
In reply to James PrestwoodRecently 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 | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+)
src/main.c +71 -0
@@ -29,6 +29,10 @@#include <errno.h> #include <getopt.h> #include <signal.h> +#include <fcntl.h> +#include <unistd.h> +#include <sys/stat.h> +#include <sys/mman.h> #include <ell/ell.h> #include <ell/useful.h>
@@ -45,6 +49,7 @@#include "src/storage.h" #include "src/anqp.h" #include "src/netconfig.h" +#include "src/crypto.h" #include "src/backtrace.h"
@@ -397,6 +402,70 @@ done:return r; } +/* +* Initialize a systemd encryption key for encrypting/decrypting credentials. +*/ +static void setup_system_key (void ) +{ +int fd; +struct stat st; +const char *cred_dir; +void *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 ; + } + + fd =open (path,O_RDONLY ,0 ); +if (fd <0 ) { +l_warn ("SystemdEncrypt enabled but cannot open secret (%d)" , + fd); +return ; + } + +if (fstat (fd, &st) <0 || st.st_size ==0 ) { +close (fd); +return ; + } + + key =mmap (NULL , st.st_size,PROT_READ ,MAP_SHARED , fd,0 ); +if (key ==MAP_FAILED ) { +l_warn ("SystemdEncrypt enabled but can't mmap secret" ); +close (fd); +return ; + } + +close (fd); + +if (mlock (key, st.st_size) <0 ) { +l_warn ("Failed to mlock Systemd secret file" ); +return ; + } + +__storage_set_encryption_key (key, st.st_size); + +munlock (key, st.st_size); + +munmap (key, st.st_size); +} +int main (int argc,char *argv[]) {int exit_status;
@@ -526,6 +595,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.34.1
James Prestwood
PATCH v7 6/8 tools: add decrypt-profile tool
In reply to James PrestwoodThis 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/iwd-decrypt-profile.c | 212 ++++++++++++++++++++++++++++++++++++ 2 files changed, 219 insertions(+), 1 deletion(-) create mode 100644 tools/iwd-decrypt-profile.c
Makefile.am +7 -1
@@ -362,7 +362,7 @@ man_MANS += wired/ead.8 endif endif -noinst_PROGRAMS += tools/probe-req +noinst_PROGRAMS += tools/probe-req tools/iwd-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_iwd_decrypt_profile_SOURCES = tools/iwd-decrypt-profile.c \ + src/common.h src/common.c \ + src/crypto.h src/crypto.c \ + src/storage.h src/storage.c +tools_iwd_decrypt_profile_LDADD = ${ell_ldadd} + if HWSIM bin_PROGRAMS += tools/hwsim
tools/iwd-decrypt-profile.c new file +212 -0
212 lines not on this page · raw message
Signature · 1 line
2.34.1
James Prestwood
PATCH v7 7/8 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
@@ -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
@@ -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.34.1
James Prestwood
PATCH v7 8/8 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
@@ -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
@@ -0,0 +1,6 @@ +[SETUP] +num_radios=2 +start_iwd=0 + +[HOSTAPD] +rad0=ssidCCMP.conf
autotests/testEncryptedProfiles/iwd-secret new file +1 -0
@@ -0,0 +1 @@ +secret123
autotests/testEncryptedProfiles/main.conf new file +2 -0
@@ -0,0 +1,2 @@ +[General] +SystemdEncrypt=iwd-secret
autotests/testEncryptedProfiles/ssidCCMP.conf new file +10 -0
@@ -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
@@ -0,0 +1,2 @@ +[Security] +Passphrase=secret123
Signature · 1 line
2.34.1
Denis Kenzior
Hi James,
Quoted 6 lines · James Prestwood
--- src/main.c | 6 --- src/storage.c | 102 ++++++++++++++++++++++++++------------------------ src/storage.h | 2 - 3 files changed, 54 insertions(+), 56 deletions(-)
<snip>
Quoted 39 lines
src/storage.c +0
-38-bool storage_create_dirs (void ) -{ -const char *state_dir; -char **state_dirs; - - state_dir =getenv ("STATE_DIRECTORY" ); -if (!state_dir) - state_dir =DAEMON_STORAGEDIR ; - -l_debug ("Using state directory %s" , state_dir); - - state_dirs =l_strsplit (state_dir,':' ); -if (!state_dirs[0 ]) { -l_strv_free (state_dirs); -return false; - } - - storage_path =l_strdup (state_dirs[0 ]); -l_strv_free (state_dirs); - -if (create_dirs (storage_path)) { -l_error ("Failed to create %s" , storage_path); - -l_free (storage_path); - -return false; - } - - storage_hotspot_path =l_strdup_printf ("%s/hotspot/" , storage_path); - -if (create_dirs (storage_hotspot_path)) { -l_error ("Failed to create %s" , storage_hotspot_path); - -l_free (storage_path); -l_free (storage_hotspot_path); - -return false; - }
src/storage.c error_create_dirs: · line 234
Quoted 10 lines
src/storage.c +0
-10- -return true; -} - -void storage_cleanup_dirs (void ) -{ -l_free (storage_path); -l_free (storage_hotspot_path); -} -
So these two functions are actually extremely iwd specific. I think we maybe should just put them into main.c instead.
Quoted 3 lines
char *storage_get_path(const char *format, ...)
{
va_list args;Regards,
-Denis