storage.c (18791B)
1 /* 2 * 3 * Wireless daemon for Linux 4 * 5 * Copyright (C) 2013-2019 Intel Corporation. All rights reserved. 6 * 7 * This library is free software; you can redistribute it and/or 8 * modify it under the terms of the GNU Lesser General Public 9 * License as published by the Free Software Foundation; either 10 * version 2.1 of the License, or (at your option) any later version. 11 * 12 * This library is distributed in the hope that it will be useful, 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 * Lesser General Public License for more details. 16 * 17 * You should have received a copy of the GNU Lesser General Public 18 * License along with this library; if not, write to the Free Software 19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 20 * 21 */ 22 23 #ifdef HAVE_CONFIG_H 24 #include <config.h> 25 #endif 26 27 #define _GNU_SOURCE 28 #include <stdio.h> 29 #include <errno.h> 30 #include <ctype.h> 31 #include <fcntl.h> 32 #include <stdbool.h> 33 #include <string.h> 34 #include <stdarg.h> 35 #include <stdlib.h> 36 #include <unistd.h> 37 #include <time.h> 38 #include <sys/stat.h> 39 #include <sys/time.h> 40 #include <sys/types.h> 41 #include <sys/stat.h> 42 #include <sys/mman.h> 43 44 #include <ell/ell.h> 45 #include "ell/useful.h" 46 47 #include "src/missing.h" 48 #include "src/defs.h" 49 #include "src/common.h" 50 #include "src/storage.h" 51 #include "src/crypto.h" 52 53 #define STORAGE_DIR_MODE (S_IRUSR | S_IWUSR | S_IXUSR) 54 #define STORAGE_FILE_MODE (S_IRUSR | S_IWUSR) 55 56 #define KNOWN_FREQ_FILENAME ".known_network.freq" 57 #define EAP_TLS_CACHE_FILENAME ".eap-tls-session-cache" 58 59 static char *storage_path = NULL; 60 static char *storage_hotspot_path = NULL; 61 static uint8_t system_key[32]; 62 static bool system_key_set = false; 63 64 static int create_dirs(const char *filename) 65 { 66 struct stat st; 67 char *dir; 68 const char *prev, *next; 69 int err; 70 71 if (filename[0] != '/') 72 return -1; 73 74 err = stat(filename, &st); 75 if (!err && S_ISREG(st.st_mode)) 76 return 0; 77 78 dir = l_malloc(strlen(filename) + 1); 79 strcpy(dir, "/"); 80 81 for (prev = filename; (next = strchr(prev + 1, '/')); prev = next) { 82 /* Skip consecutive '/' characters */ 83 if (next - prev == 1) 84 continue; 85 86 strncat(dir, prev + 1, next - prev); 87 88 if (mkdir(dir, STORAGE_DIR_MODE) == -1 && errno != EEXIST) { 89 l_free(dir); 90 return -1; 91 } 92 } 93 94 l_free(dir); 95 return 0; 96 } 97 98 ssize_t read_file(void *buffer, size_t len, const char *path_fmt, ...) 99 { 100 va_list ap; 101 char *path; 102 ssize_t r; 103 int fd; 104 105 va_start(ap, path_fmt); 106 path = l_strdup_vprintf(path_fmt, ap); 107 va_end(ap); 108 109 fd = L_TFR(open(path, O_RDONLY)); 110 111 l_free(path); 112 113 if (fd == -1) 114 return -1; 115 116 r = L_TFR(read(fd, buffer, len)); 117 118 L_TFR(close(fd)); 119 120 return r; 121 } 122 123 /* 124 * Write a buffer to a file in a transactionally safe form 125 * 126 * Given a buffer, write it to a file named after 127 * @path_fmt+args. However, to make sure the file contents are 128 * consistent (ie: a crash right after opening or during write() 129 * doesn't leave a file half baked), the contents are written to a 130 * file with a temporary name and when closed, it is renamed to the 131 * specified name (@path_fmt+args). 132 */ 133 ssize_t write_file(const void *buffer, size_t len, bool preserve_times, 134 const char *path_fmt, ...) 135 { 136 va_list ap; 137 char *tmp_path, *path; 138 ssize_t r; 139 int fd; 140 141 va_start(ap, path_fmt); 142 path = l_strdup_vprintf(path_fmt, ap); 143 va_end(ap); 144 145 tmp_path = l_strdup_printf("%s.XXXXXX.tmp", path); 146 147 r = -1; 148 if (create_dirs(path) != 0) 149 goto error_create_dirs; 150 151 fd = L_TFR(mkostemps(tmp_path, 4, O_CLOEXEC)); 152 if (fd == -1) 153 goto error_mkostemps; 154 155 r = L_TFR(write(fd, buffer, len)); 156 L_TFR(close(fd)); 157 158 if (r != (ssize_t) len) { 159 r = -1; 160 goto error_write; 161 } 162 163 if (preserve_times) { 164 struct stat st; 165 166 if (stat(path, &st) == 0) { 167 struct timespec times[2]; 168 169 times[0] = st.st_atim; 170 times[1] = st.st_mtim; 171 utimensat(0, tmp_path, times, 0); 172 } 173 } 174 175 /* 176 * Now that the file contents are written, rename to the real 177 * file name; this way we are uniquely sure that the whole 178 * thing is there. 179 * conserve @r's value from 'write' 180 */ 181 182 if (rename(tmp_path, path) == -1) 183 r = -1; 184 185 error_write: 186 if (r < 0) 187 unlink(tmp_path); 188 error_mkostemps: 189 error_create_dirs: 190 l_free(tmp_path); 191 l_free(path); 192 return r; 193 } 194 195 bool storage_create_dirs(void) 196 { 197 const char *state_dir; 198 char **state_dirs; 199 200 state_dir = getenv("STATE_DIRECTORY"); 201 if (!state_dir) 202 state_dir = DAEMON_STORAGEDIR; 203 204 l_debug("Using state directory %s", state_dir); 205 206 state_dirs = l_strsplit(state_dir, ':'); 207 if (!state_dirs[0]) { 208 l_strv_free(state_dirs); 209 return false; 210 } 211 212 storage_path = l_strdup(state_dirs[0]); 213 l_strv_free(state_dirs); 214 215 if (create_dirs(storage_path)) { 216 l_error("Failed to create %s", storage_path); 217 218 l_free(storage_path); 219 220 return false; 221 } 222 223 storage_hotspot_path = l_strdup_printf("%s/hotspot/", storage_path); 224 225 if (create_dirs(storage_hotspot_path)) { 226 l_error("Failed to create %s", storage_hotspot_path); 227 228 l_free(storage_path); 229 l_free(storage_hotspot_path); 230 231 return false; 232 } 233 234 return true; 235 } 236 237 void storage_cleanup_dirs(void) 238 { 239 l_free(storage_path); 240 l_free(storage_hotspot_path); 241 } 242 243 char *storage_get_path(const char *format, ...) 244 { 245 va_list args; 246 char *fmt, *str; 247 248 if (!format) 249 return l_strdup(storage_path); 250 251 fmt = l_strdup_printf("%s/%s", storage_path, format); 252 253 va_start(args, format); 254 str = l_strdup_vprintf(fmt, args); 255 va_end(args); 256 257 l_free(fmt); 258 return str; 259 } 260 261 char *storage_get_hotspot_path(const char *format, ...) 262 { 263 va_list args; 264 char *fmt, *str; 265 266 if (!format) 267 return l_strdup(storage_hotspot_path); 268 269 fmt = l_strdup_printf("%s/%s", storage_hotspot_path, format); 270 271 va_start(args, format); 272 str = l_strdup_vprintf(fmt, args); 273 va_end(args); 274 275 l_free(fmt); 276 return str; 277 } 278 279 char *storage_get_network_file_path(enum security type, const char *ssid) 280 { 281 char *path; 282 const char *c; 283 char *hex = NULL; 284 285 for (c = ssid; *c; c++) 286 if (!isalnum(*c) && !strchr("-_ ", *c)) 287 break; 288 289 if (*c) { 290 hex = l_util_hexstring((const unsigned char *) ssid, 291 strlen(ssid)); 292 path = storage_get_path("/=%s.%s", hex, security_to_str(type)); 293 l_free(hex); 294 } else 295 path = storage_get_path("/%s.%s", ssid, security_to_str(type)); 296 297 return path; 298 } 299 300 const char *storage_network_ssid_from_path(const char *path, 301 enum security *type) 302 { 303 const char *filename = strrchr(path, '/'); 304 const char *c, *end; 305 char *decoded; 306 static char buf[67]; 307 308 if (filename) 309 filename++; /* Skip the / */ 310 else 311 filename = path; 312 313 end = strchr(filename, '.'); 314 315 if (!end || !security_from_str(end + 1, type)) 316 return NULL; 317 318 if (filename[0] != '=') { 319 if (end == filename || end - filename > SSID_MAX_SIZE) 320 return NULL; 321 322 for (c = filename; c < end; c++) 323 if (!isalnum(*c) && !strchr("-_ ", *c)) 324 break; 325 326 if (c < end) { 327 l_warn("Provisioning file %s contains non-alphanumeric " 328 "characters in the name. Please hex-encode. " 329 "See man iwd.network", path); 330 return NULL; 331 } 332 333 memcpy(buf, filename, end - filename); 334 buf[end - filename] = '\0'; 335 336 return buf; 337 } 338 339 if (end - filename <= 1 || end - filename > 65) 340 return NULL; 341 342 memcpy(buf, filename + 1, end - filename - 1); 343 buf[end - filename - 1] = '0'; 344 buf[end - filename + 0] = '0'; 345 buf[end - filename + 1] = '\0'; 346 347 decoded = (char *) l_util_from_hexstring(buf, NULL); 348 if (!decoded) 349 return NULL; 350 351 if (!l_utf8_validate(decoded, (end - filename) / 2, NULL)) { 352 l_free(decoded); 353 return NULL; 354 } 355 356 strcpy(buf, decoded); 357 l_free(decoded); 358 359 return buf; 360 } 361 362 /* Groups requiring encryption (if enabled) */ 363 static char *encrypt_groups[] = { 364 "Security", 365 NULL 366 }; 367 368 static bool encrypt_group(const char *group) 369 { 370 char **g; 371 372 for (g = encrypt_groups; *g; g++) { 373 if (!strcmp(*g, group)) 374 return true; 375 } 376 377 return false; 378 } 379 380 /* 381 * Encrypt needed groups of 'settings' without modifying the object. Returns 382 * the entire settings object as data, with encrypted groups as a bytestring 383 * set as the value to [Security].EncryptedSecurity. This also includes any 384 * embedded groups. 385 * 386 * Note: If encryption is not enabled or there is no Security group this is 387 * effectively l_settings_to_data. 388 */ 389 char *__storage_encrypt(const struct l_settings *settings, const char *name, 390 size_t *out_len) 391 { 392 struct iovec ad[2]; 393 uint8_t salt[32]; 394 size_t len; 395 _auto_(l_settings_free) struct l_settings *to_encrypt = NULL; 396 _auto_(l_settings_free) struct l_settings *original = NULL; 397 _auto_(l_free) char *plaintext = NULL; 398 _auto_(l_free) uint8_t *enc = NULL; 399 _auto_(l_strv_free) char **groups = NULL; 400 char **i; 401 402 if (!system_key_set || !l_settings_has_group(settings, "Security")) 403 return l_settings_to_data(settings, out_len); 404 405 /* 406 * Make two copies of the settings: One will contain only data to be 407 * encrypted (to_encrypt), the other will contain data to be left 408 * unencrypted (original). At the end any encrypted data will be set 409 * into 'original' as EncryptedSecurity. 410 */ 411 to_encrypt = l_settings_clone(settings); 412 original = l_settings_clone(settings); 413 414 groups = l_settings_get_groups(to_encrypt); 415 for (i = groups; *i; i++) { 416 if (encrypt_group(*i)) 417 l_settings_remove_group(original, *i); 418 else 419 l_settings_remove_group(to_encrypt, *i); 420 } 421 422 l_settings_remove_embedded_groups(original); 423 424 plaintext = l_settings_to_data(to_encrypt, &len); 425 if (!plaintext) 426 return NULL; 427 428 l_getrandom(salt, 32); 429 430 ad[0].iov_base = (void *) salt; 431 ad[0].iov_len = 32; 432 ad[1].iov_base = (void *) name; 433 ad[1].iov_len = strlen(name); 434 435 /* 436 * AES-SIV automatically prepends the IV (16 bytes) to the encrypted 437 * data. 438 */ 439 enc = l_malloc(len + 16); 440 441 if (!aes_siv_encrypt(system_key, sizeof(system_key), plaintext, len, 442 ad, 2, enc)) { 443 l_error("Could not encrypt [Security] group"); 444 return NULL; 445 } 446 447 l_settings_set_bytes(original, "Security", "EncryptedSalt", salt, 32); 448 l_settings_set_bytes(original, "Security", "EncryptedSecurity", 449 enc, len + 16); 450 451 return l_settings_to_data(original, out_len); 452 } 453 454 /* 455 * Decrypt data in [Security].EncryptedSecurity. This data also includes 456 * embedded groups potentially. Once decrypted the data is put back into the 457 * object. 458 * 459 * Note: if encryption is not enabled or there is no Security group settings 460 * is not modified. 461 */ 462 int __storage_decrypt(struct l_settings *settings, const char *ssid, 463 bool *encrypt) 464 { 465 _auto_(l_free) uint8_t *encrypted = NULL; 466 _auto_(l_free) uint8_t *decrypted = NULL; 467 _auto_(l_free) uint8_t *salt = NULL; 468 _auto_(l_strv_free) char **groups = NULL; 469 char **i; 470 size_t elen, slen; 471 struct iovec ad[2]; 472 473 if (!system_key_set) 474 goto done; 475 476 if (!l_settings_has_group(settings, "Security")) 477 goto done; 478 479 encrypted = l_settings_get_bytes(settings, "Security", 480 "EncryptedSecurity", &elen); 481 salt = l_settings_get_bytes(settings, "Security", 482 "EncryptedSalt", &slen); 483 484 /* 485 * Either profile has never been loaded after enabling encryption or is 486 * missing Encrypted{Salt,Security} values. If either are missing this 487 * profile is corrupted and must be fixed. 488 */ 489 if (!(encrypted && salt)) { 490 /* Profile corrupted */ 491 if (encrypted || salt) { 492 l_warn("Profile %s is corrupted reconfigure manually", 493 ssid); 494 return -EBADMSG; 495 } 496 497 if (encrypt) 498 *encrypt = true; 499 500 return 0; 501 } 502 503 /* 504 * It should likely be far larger than this, but that will get caught 505 * later when reloading the decrypted data. 506 */ 507 if (elen < 16) 508 return -EBADMSG; 509 510 /* 511 * AES-SIV automatically verifies the IV (16 bytes) and returns only 512 * the decrypted data portion. We add one here for the NULL terminator 513 * since this is always going to be textual data after decryption. 514 */ 515 decrypted = l_malloc(elen - 16 + 1); 516 517 ad[0].iov_base = (void *)salt; 518 ad[0].iov_len = slen; 519 ad[1].iov_base = (void *)ssid; 520 ad[1].iov_len = strlen(ssid); 521 522 if (!aes_siv_decrypt(system_key, sizeof(system_key), encrypted, elen, 523 ad, 2, decrypted)) { 524 l_error("Could not decrypt %s profile, did the secret change?", 525 ssid); 526 return -ENOKEY; 527 } 528 529 decrypted[elen - 16] = '\0'; 530 531 /* 532 * Remove any groups that are marked as encrypted (plus embedded), 533 * and copy the decrypted groups back into settings. 534 */ 535 groups = l_settings_get_groups(settings); 536 for (i = groups; *i; i++) { 537 if (encrypt_group(*i)) 538 l_settings_remove_group(settings, *i); 539 } 540 541 l_settings_remove_embedded_groups(settings); 542 543 /* 544 * Load decrypted data into existing settings. This is not how the API 545 * is intended to be used (since this could result in duplicate groups) 546 * but since the Security group was just removed and EncryptedSecurity 547 * should only contain a Security group its safe to use it this way. 548 */ 549 if (!l_settings_load_from_data(settings, (const char *) decrypted, 550 elen - 16)) { 551 l_error("Could not load decrypted security group"); 552 return -EBADMSG; 553 } 554 555 done: 556 if (encrypt) 557 *encrypt = false; 558 559 return 0; 560 } 561 562 /* 563 * Decrypts a network profile (if needed). If profile encryption is enabled 564 * and the profile is unencrypted it will be encrypted and written back to 565 * the file system automatically. 566 * 567 * 'name' is used for decryption and is used as part of the IV. Callers 568 * should provide a unique identifier here if available. For example, the 569 * SSID, consortium name, etc. 570 */ 571 bool storage_decrypt(struct l_settings *settings, const char *path, 572 const char *name) 573 { 574 bool needs_encryption; 575 _auto_(l_free) char *encrypted = NULL; 576 size_t elen; 577 578 if (__storage_decrypt(settings, name, &needs_encryption) < 0) 579 return false; 580 581 if (!needs_encryption) 582 return true; 583 584 /* Profile never encrypted before. Encrypt and write to disk */ 585 encrypted = __storage_encrypt(settings, name, &elen); 586 if (!encrypted) { 587 l_error("Could not encrypt new profile %s", name); 588 return false; 589 } 590 591 if (write_file(encrypted, elen, false, "%s", path) < 0) { 592 l_error("Failed to write out encrypted profile"); 593 return false; 594 } 595 596 l_debug("Encrypted a new profile %s", path); 597 598 return true; 599 } 600 601 struct l_settings *storage_network_open(enum security type, const char *ssid) 602 { 603 struct l_settings *settings; 604 _auto_(l_free) char *path = NULL; 605 606 if (!ssid) 607 return NULL; 608 609 path = storage_get_network_file_path(type, ssid); 610 611 settings = l_settings_new(); 612 613 if (!l_settings_load_from_file(settings, path)) { 614 l_error("Error loading %s", path); 615 goto error; 616 } 617 618 if (type != SECURITY_NONE && !storage_decrypt(settings, path, ssid)) 619 goto error; 620 621 return settings; 622 623 error: 624 l_settings_free(settings); 625 return NULL; 626 } 627 628 int storage_network_touch(enum security type, const char *ssid) 629 { 630 char *path; 631 int ret; 632 633 if (!ssid) 634 return -EINVAL; 635 636 path = storage_get_network_file_path(type, ssid); 637 ret = utimensat(0, path, NULL, 0); 638 l_free(path); 639 640 if (!ret) 641 return 0; 642 643 return -errno; 644 } 645 646 void storage_network_sync(enum security type, const char *ssid, 647 struct l_settings *settings) 648 { 649 _auto_(l_free) char *data = NULL; 650 _auto_(l_free) char *path = NULL; 651 size_t length = 0; 652 653 path = storage_get_network_file_path(type, ssid); 654 data = __storage_encrypt(settings, ssid, &length); 655 656 if (!data) { 657 l_error("Unable to sync profile %s", ssid); 658 return; 659 } 660 661 write_file(data, length, true, "%s", path); 662 } 663 664 int storage_network_remove(enum security type, const char *ssid) 665 { 666 char *path; 667 int ret; 668 669 path = storage_get_network_file_path(type, ssid); 670 ret = unlink(path); 671 l_free(path); 672 673 return ret < 0 ? -errno : 0; 674 } 675 676 struct l_settings *storage_known_frequencies_load(void) 677 { 678 struct l_settings *known_freqs; 679 char *known_freq_file_path; 680 681 known_freqs = l_settings_new(); 682 683 known_freq_file_path = storage_get_path("/%s", KNOWN_FREQ_FILENAME); 684 685 if (!l_settings_load_from_file(known_freqs, known_freq_file_path)) { 686 l_settings_free(known_freqs); 687 known_freqs = NULL; 688 } 689 690 l_free(known_freq_file_path); 691 692 return known_freqs; 693 } 694 695 void storage_known_frequencies_sync(struct l_settings *known_freqs) 696 { 697 char *known_freq_file_path; 698 char *data; 699 size_t len; 700 701 if (!known_freqs) 702 return; 703 704 known_freq_file_path = storage_get_path("/%s", KNOWN_FREQ_FILENAME); 705 706 data = l_settings_to_data(known_freqs, &len); 707 write_file(data, len, false, "%s", known_freq_file_path); 708 l_free(data); 709 710 l_free(known_freq_file_path); 711 } 712 713 struct l_settings *storage_eap_tls_cache_load(void) 714 { 715 _auto_(l_free) char *path = 716 storage_get_path("%s", EAP_TLS_CACHE_FILENAME); 717 struct l_settings *cache = l_settings_new(); 718 719 if (!l_settings_load_from_file(cache, path)) 720 l_debug("No session cache loaded from %s, starting with an " 721 "empty cache", path); 722 723 return cache; 724 } 725 726 void storage_eap_tls_cache_sync(const struct l_settings *cache) 727 { 728 _auto_(l_free) char *path = 729 storage_get_path("%s", EAP_TLS_CACHE_FILENAME); 730 _auto_(l_free) char *settings_data = NULL; 731 _auto_(l_free) char *data = NULL; 732 size_t len; 733 static const char comment[] = 734 "# External changes to this file are not tracked by IWD " 735 "and will be overwritten.\n\n"; 736 static const size_t comment_len = L_ARRAY_SIZE(comment) - 1; 737 738 settings_data = l_settings_to_data(cache, &len); 739 data = l_malloc(comment_len + len); 740 memcpy(data, comment, comment_len); 741 memcpy(data + comment_len, settings_data, len); 742 743 /* 744 * Note this data contains cryptographic secrets. write_file() 745 * happens to set the right permissions on the file. 746 * 747 * TODO: consider encrypting with system_key. 748 */ 749 write_file(data, comment_len + len, false, "%s", path); 750 explicit_bzero(settings_data, len); 751 explicit_bzero(data, len); 752 } 753 754 bool storage_is_file(const char *filename) 755 { 756 char *path; 757 struct stat st; 758 int err; 759 760 path = storage_get_path("%s", filename); 761 err = stat(path, &st); 762 l_free(path); 763 764 if (!err && S_ISREG(st.st_mode) != 0) 765 return true; 766 767 return false; 768 } 769 770 /* 771 * Initialize a systemd encryption key for encrypting/decrypting credentials. 772 * This uses the 'extract and expand' concept from RFC 5869 to derive a new 773 * fixed length key. Note that a 'zero salt' is used in this derivation which 774 * is handled internally in hkdf_extract(). 'TK' denotes the temporary key 775 * derived from 'extract' and used as the input to 'expand'. 776 * 777 * Inputs: 778 * IKM - Input keying material of arbitrary length. This is the key 779 * obtained directly from systemd. 780 * Outputs: 781 * OKM - Output key material of 32 bytes 782 * 783 * TK = HKDF-Extract(<zero>, IKM) 784 * OKM = HKDF-Expand(TK, "System Key", 32) 785 */ 786 bool storage_init(const uint8_t *key, size_t key_len) 787 { 788 uint8_t tmp[32]; 789 790 if (mlock(system_key, sizeof(system_key)) < 0) 791 return false; 792 793 if (!hkdf_extract(L_CHECKSUM_SHA256, NULL, 0, 1, tmp, key, key_len)) 794 return false; 795 796 system_key_set = hkdf_expand(L_CHECKSUM_SHA256, tmp, sizeof(tmp), 797 "System Key", 798 system_key, sizeof(system_key)); 799 800 explicit_bzero(tmp, sizeof(tmp)); 801 return system_key_set; 802 } 803 804 void storage_exit(void) 805 { 806 if (system_key_set) { 807 explicit_bzero(system_key, sizeof(system_key)); 808 munlock(system_key, sizeof(system_key)); 809 } 810 }