4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 2 only,
8 * as published by the Free Software Foundation.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License version 2 for more details (a copy is included
14 * in the LICENSE file that accompanied this code).
16 * You should have received a copy of the GNU General Public License
17 * version 2 along with this program; If not, see
18 * http://www.gnu.org/licenses/gpl-2.0.html
23 * Copyright (C) 2015, Trustees of Indiana University
25 * Copyright (c) 2016, Intel Corporation.
27 * Author: Jeremy Filizetti <jfilizet@iu.edu>
36 #include <openssl/dh.h>
37 #include <openssl/engine.h>
38 #include <openssl/err.h>
39 #include <openssl/hmac.h>
40 #include <sys/types.h>
42 #include <lnet/nidstr.h>
45 #include "write_bytes.h"
47 #define SK_PBKDF2_ITERATIONS 10000
49 static struct sk_crypt_type sk_crypt_types[] = {
50 [SK_CRYPT_AES256_CTR] = {
51 .sct_name = "ctr(aes)",
56 static struct sk_hmac_type sk_hmac_types[] = {
58 .sht_name = "hmac(sha256)",
62 .sht_name = "hmac(sha512)",
68 # include "lgss_utils.h"
70 # include "gss_util.h"
71 # include "gss_oids.h"
72 # include "err_util.h"
78 * \param[in] program Program name to output
79 * \param[in] verbose Verbose flag
80 * \param[in] fg Whether or not to run in foreground
83 void sk_init_logging(char *program, int verbose, int fg)
85 initerr(program, verbose, fg);
90 * Loads the key from \a filename and returns the struct sk_keyfile_config.
91 * It should be freed by the caller.
93 * \param[in] filename Disk or key payload data
95 * \return sk_keyfile_config sucess
96 * \return NULL failure
98 struct sk_keyfile_config *sk_read_file(char *filename)
100 struct sk_keyfile_config *config;
106 config = malloc(sizeof(*config));
108 printerr(0, "Failed to allocate memory for config\n");
112 /* allow standard input override */
113 if (strcmp(filename, "-") == 0)
116 fd = open(filename, O_RDONLY);
119 printerr(0, "Error opening key file '%s': %s\n", filename,
122 } else if (fd != STDIN_FILENO) {
126 if (rc == 0 && (st.st_mode & ~0600))
127 fprintf(stderr, "warning: "
128 "secret key '%s' has insecure file mode %#o\n",
129 filename, st.st_mode);
132 ptr = (char *)config;
133 remain = sizeof(*config);
135 rc = read(fd, ptr, remain);
139 printerr(0, "read() failed on %s: %s\n", filename,
142 } else if (rc == 0) {
143 printerr(0, "File %s does not have a complete key\n",
151 if (fd != STDIN_FILENO)
153 sk_config_disk_to_cpu(config);
164 * Checks if a key matching \a description is found in the keyring for
165 * logging purposes and then attempts to load \a payload of \a psize into a key
166 * with \a description.
168 * \param[in] payload Key payload
169 * \param[in] psize Payload size
170 * \param[in] description Description used for key in keyring
175 static key_serial_t sk_load_key(const struct sk_keyfile_config *skc,
176 const char *description)
178 struct sk_keyfile_config payload;
181 memcpy(&payload, skc, sizeof(*skc));
183 /* In the keyring use the disk layout so keyctl pipe can be used */
184 sk_config_cpu_to_disk(&payload);
186 /* Check to see if a key is already loaded matching description */
187 key = keyctl_search(KEY_SPEC_USER_KEYRING, "user", description, 0);
189 printerr(2, "Key %d found in session keyring, replacing\n",
192 key = add_key("user", description, &payload, sizeof(payload),
193 KEY_SPEC_USER_KEYRING);
195 printerr(2, "Added key %d with description %s\n", key,
198 printerr(0, "Failed to add key with %s\n", description);
204 * Reads the key from \a path, verifies it and loads into the session keyring
205 * using a description determined by the the \a type. Existing keys with the
206 * same description are replaced.
208 * \param[in] path Path to key file
209 * \param[in] type Type of key to load which determines the description
214 int sk_load_keyfile(char *path)
216 struct sk_keyfile_config *config;
217 char description[SK_DESCRIPTION_SIZE + 1];
223 rc = stat(path, &buf);
225 printerr(0, "stat() failed for file %s: %s\n", path,
230 config = sk_read_file(path);
234 /* Similar to ssh, require adequate care of key files */
235 if (buf.st_mode & (S_IRGRP | S_IWGRP | S_IWOTH | S_IXOTH)) {
236 printerr(0, "Shared key files must be read/writeable only by "
241 if (sk_validate_config(config))
244 /* The server side can have multiple key files per file system so
245 * the nodemap name is appended to the key description to uniquely
247 if (config->skc_type & SK_TYPE_MGS) {
248 /* Any key can be an MGS key as long as we are told to use it */
249 rc = snprintf(description, SK_DESCRIPTION_SIZE, "lustre:MGS:%s",
250 config->skc_nodemap);
251 if (rc >= SK_DESCRIPTION_SIZE)
253 if (sk_load_key(config, description) == -1)
256 if (config->skc_type & SK_TYPE_SERVER) {
257 /* Server keys need to have the file system name in the key */
258 if (!config->skc_fsname) {
259 printerr(0, "Key configuration has no file system "
260 "attribute. Can't load as server type\n");
263 rc = snprintf(description, SK_DESCRIPTION_SIZE, "lustre:%s:%s",
264 config->skc_fsname, config->skc_nodemap);
265 if (rc >= SK_DESCRIPTION_SIZE)
267 if (sk_load_key(config, description) == -1)
270 if (config->skc_type & SK_TYPE_CLIENT) {
271 /* Load client file system key */
272 if (config->skc_fsname) {
273 rc = snprintf(description, SK_DESCRIPTION_SIZE,
274 "lustre:%s", config->skc_fsname);
275 if (rc >= SK_DESCRIPTION_SIZE)
277 if (sk_load_key(config, description) == -1)
281 /* Load client MGC keys */
282 for (i = 0; i < MAX_MGSNIDS; i++) {
283 if (config->skc_mgsnids[i] == LNET_NID_ANY)
285 rc = snprintf(description, SK_DESCRIPTION_SIZE,
287 libcfs_nid2str(config->skc_mgsnids[i]));
288 if (rc >= SK_DESCRIPTION_SIZE)
290 if (sk_load_key(config, description) == -1)
303 * Byte swaps config from cpu format to disk
305 * \param[in,out] config sk_keyfile_config to swap
307 void sk_config_cpu_to_disk(struct sk_keyfile_config *config)
314 config->skc_version = htobe32(config->skc_version);
315 config->skc_hmac_alg = htobe16(config->skc_hmac_alg);
316 config->skc_crypt_alg = htobe16(config->skc_crypt_alg);
317 config->skc_expire = htobe32(config->skc_expire);
318 config->skc_shared_keylen = htobe32(config->skc_shared_keylen);
319 config->skc_prime_bits = htobe32(config->skc_prime_bits);
321 for (i = 0; i < MAX_MGSNIDS; i++)
322 config->skc_mgsnids[i] = htobe64(config->skc_mgsnids[i]);
328 * Byte swaps config from disk format to cpu
330 * \param[in,out] config sk_keyfile_config to swap
332 void sk_config_disk_to_cpu(struct sk_keyfile_config *config)
339 config->skc_version = be32toh(config->skc_version);
340 config->skc_hmac_alg = be16toh(config->skc_hmac_alg);
341 config->skc_crypt_alg = be16toh(config->skc_crypt_alg);
342 config->skc_expire = be32toh(config->skc_expire);
343 config->skc_shared_keylen = be32toh(config->skc_shared_keylen);
344 config->skc_prime_bits = be32toh(config->skc_prime_bits);
346 for (i = 0; i < MAX_MGSNIDS; i++)
347 config->skc_mgsnids[i] = be64toh(config->skc_mgsnids[i]);
353 * Verifies the on key payload format is valid
355 * \param[in] config sk_keyfile_config
360 int sk_validate_config(const struct sk_keyfile_config *config)
365 printerr(0, "Null configuration passed\n");
368 if (config->skc_version != SK_CONF_VERSION) {
369 printerr(0, "Invalid version\n");
372 if (config->skc_hmac_alg >= SK_HMAC_MAX) {
373 printerr(0, "Invalid HMAC algorithm\n");
376 if (config->skc_crypt_alg >= SK_CRYPT_MAX) {
377 printerr(0, "Invalid crypt algorithm\n");
380 if (config->skc_expire < 60 || config->skc_expire > INT_MAX) {
381 /* Try to limit key expiration to some reasonable minimum and
382 * also prevent values over INT_MAX because there appears
383 * to be a type conversion issue */
384 printerr(0, "Invalid expiration time should be between %d "
385 "and %d\n", 60, INT_MAX);
388 if (config->skc_prime_bits % 8 != 0 ||
389 config->skc_prime_bits > SK_MAX_P_BYTES * 8) {
390 printerr(0, "Invalid session key length must be a multiple of 8"
391 " and less then %d bits\n",
395 if (config->skc_shared_keylen % 8 != 0 ||
396 config->skc_shared_keylen > SK_MAX_KEYLEN_BYTES * 8){
397 printerr(0, "Invalid shared key max length must be a multiple "
398 "of 8 and less then %d bits\n",
399 SK_MAX_KEYLEN_BYTES * 8);
403 /* Check for terminating nulls on strings */
404 for (i = 0; i < sizeof(config->skc_fsname) &&
405 config->skc_fsname[i] != '\0'; i++)
407 if (i == sizeof(config->skc_fsname)) {
408 printerr(0, "File system name not null terminated\n");
412 for (i = 0; i < sizeof(config->skc_nodemap) &&
413 config->skc_nodemap[i] != '\0'; i++)
415 if (i == sizeof(config->skc_nodemap)) {
416 printerr(0, "Nodemap name not null terminated\n");
420 if (config->skc_type == SK_TYPE_INVALID) {
421 printerr(0, "Invalid key type\n");
429 * Hashes \a string and places the hash in \a hash
432 * \param[in] string Null terminated string to hash
433 * \param[in] hash_alg OpenSSL EVP_MD to use for hash
434 * \param[in,out] hash gss_buffer_desc to hold the result
439 static int sk_hash_string(const char *string, const EVP_MD *hash_alg,
440 gss_buffer_desc *hash)
442 EVP_MD_CTX *ctx = EVP_MD_CTX_create();
443 size_t len = strlen(string);
444 unsigned int hashlen;
446 if (!hash->value || hash->length < EVP_MD_size(hash_alg))
448 if (!EVP_DigestInit_ex(ctx, hash_alg, NULL))
450 if (!EVP_DigestUpdate(ctx, string, len))
452 if (!EVP_DigestFinal_ex(ctx, hash->value, &hashlen))
455 EVP_MD_CTX_destroy(ctx);
456 hash->length = hashlen;
460 EVP_MD_CTX_destroy(ctx);
465 * Hashes \a string and verifies the resulting hash matches the value
468 * \param[in] string Null terminated string to hash
469 * \param[in] hash_alg OpenSSL EVP_MD to use for hash
470 * \param[in,out] current_hash gss_buffer_desc to compare to
472 * \return gss error failure
473 * \return GSS_S_COMPLETE success
475 uint32_t sk_verify_hash(const char *string, const EVP_MD *hash_alg,
476 const gss_buffer_desc *current_hash)
478 gss_buffer_desc hash;
479 unsigned char hashbuf[EVP_MAX_MD_SIZE];
481 hash.value = hashbuf;
482 hash.length = sizeof(hashbuf);
484 if (sk_hash_string(string, hash_alg, &hash))
485 return GSS_S_FAILURE;
486 if (current_hash->length != hash.length)
487 return GSS_S_DEFECTIVE_TOKEN;
488 if (memcmp(current_hash->value, hash.value, hash.length))
489 return GSS_S_BAD_SIG;
491 return GSS_S_COMPLETE;
494 static inline int sk_config_has_mgsnid(struct sk_keyfile_config *config,
500 nid = libcfs_str2nid(mgsnid);
501 if (nid == LNET_NID_ANY)
504 for (i = 0; i < MAX_MGSNIDS; i++)
505 if (config->skc_mgsnids[i] == nid)
511 * Create an sk_cred structure populated with initial configuration info and the
512 * key. \a tgt and \a nodemap are used in determining the expected key
513 * description so the key can be found by searching the keyring.
514 * This is done because there is no easy way to pass keys from the mount command
515 * all the way to the request_key call. In addition any keys can be dynamically
516 * added to the keyrings and still found. The keyring that needs to be used
517 * must be the session keyring.
519 * \param[in] tgt Target file system
520 * \param[in] nodemap Cluster name for the key. This correlates to
521 * the nodemap name and is used by the server side.
522 * For the client this will be NULL.
523 * \param[in] flags Flags for the credentials
525 * \return sk_cred Allocated struct sk_cred on success
526 * \return NULL failure
528 struct sk_cred *sk_create_cred(const char *tgt, const char *nodemap,
529 const uint32_t flags)
531 struct sk_keyfile_config *config;
532 struct sk_kernel_ctx *kctx;
533 struct sk_cred *skc = NULL;
534 char description[SK_DESCRIPTION_SIZE + 1];
535 char fsname[MTI_NAME_MAXLEN + 1];
536 const char *mgsnid = NULL;
543 printerr(2, "Creating credentials for target: %s with nodemap: %s\n",
546 memset(description, 0, sizeof(description));
547 memset(fsname, 0, sizeof(fsname));
549 /* extract the file system name from target */
550 ptr = index(tgt, '-');
554 /* This must be an MGC target */
555 if (strncmp(tgt, "MGC", 3) || len <= 3) {
556 printerr(0, "Invalid target name\n");
564 if (len > MTI_NAME_MAXLEN) {
565 printerr(0, "Invalid target name\n");
568 memcpy(fsname, tgt, len);
572 rc = snprintf(description, SK_DESCRIPTION_SIZE,
573 "lustre:MGS:%s", nodemap);
575 rc = snprintf(description, SK_DESCRIPTION_SIZE,
576 "lustre:%s:%s", fsname, nodemap);
578 rc = snprintf(description, SK_DESCRIPTION_SIZE, "lustre:%s",
582 if (rc >= SK_DESCRIPTION_SIZE) {
583 printerr(0, "Invalid key description\n");
587 /* It may be a good idea to move Lustre keys to the gss_keyring
588 * (lgssc) type so that they expire when Lustre modules are removed.
589 * Unfortunately it can't be done at mount time because the mount
590 * syscall could trigger the Lustre modules to load and until that
591 * point we don't have a lgssc key type.
593 * TODO: Query the community for a consensus here */
594 printerr(2, "Searching for key with description: %s\n", description);
595 sk_key = keyctl_search(KEY_SPEC_USER_KEYRING, "user",
598 printerr(1, "No key found for %s\n", description);
602 keylen = keyctl_read_alloc(sk_key, (void **)&config);
604 printerr(0, "keyctl_read() failed for key %ld: %s\n", sk_key,
607 } else if (keylen != sizeof(*config)) {
608 printerr(0, "Unexpected key size: %d returned for key %ld, "
609 "expected %zu bytes\n",
610 keylen, sk_key, sizeof(*config));
614 sk_config_disk_to_cpu(config);
616 if (sk_validate_config(config)) {
617 printerr(0, "Invalid key configuration for key: %ld\n", sk_key);
621 if (mgsnid && !sk_config_has_mgsnid(config, mgsnid)) {
622 printerr(0, "Target name does not match key's MGS NIDs\n");
626 if (!mgsnid && strcmp(fsname, config->skc_fsname)) {
627 printerr(0, "Target name does not match key's file system\n");
631 skc = malloc(sizeof(*skc));
633 printerr(0, "Failed to allocate memory for sk_cred\n");
637 /* this initializes all gss_buffer_desc to empty as well */
638 memset(skc, 0, sizeof(*skc));
640 skc->sc_flags = flags;
641 skc->sc_tgt.length = strlen(tgt) + 1;
642 skc->sc_tgt.value = malloc(skc->sc_tgt.length);
643 if (!skc->sc_tgt.value) {
644 printerr(0, "Failed to allocate memory for target\n");
647 memcpy(skc->sc_tgt.value, tgt, skc->sc_tgt.length);
649 skc->sc_nodemap_hash.length = EVP_MD_size(EVP_sha256());
650 skc->sc_nodemap_hash.value = malloc(skc->sc_nodemap_hash.length);
651 if (!skc->sc_nodemap_hash.value) {
652 printerr(0, "Failed to allocate memory for nodemap hash\n");
656 if (sk_hash_string(config->skc_nodemap, EVP_sha256(),
657 &skc->sc_nodemap_hash)) {
658 printerr(0, "Failed to generate hash for nodemap name\n");
662 kctx = &skc->sc_kctx;
663 kctx->skc_version = config->skc_version;
664 kctx->skc_hmac_alg = config->skc_hmac_alg;
665 kctx->skc_crypt_alg = config->skc_crypt_alg;
666 kctx->skc_expire = config->skc_expire;
668 /* key payload format is in bits, convert to bytes */
669 kctx->skc_shared_key.length = config->skc_shared_keylen / 8;
670 kctx->skc_shared_key.value = malloc(kctx->skc_shared_key.length);
671 if (!kctx->skc_shared_key.value) {
672 printerr(0, "Failed to allocate memory for shared key\n");
675 memcpy(kctx->skc_shared_key.value, config->skc_shared_key,
676 kctx->skc_shared_key.length);
678 skc->sc_p.length = config->skc_prime_bits / 8;
679 skc->sc_p.value = malloc(skc->sc_p.length);
680 if (!skc->sc_p.value) {
681 printerr(0, "Failed to allocate p\n");
684 memcpy(skc->sc_p.value, config->skc_p, skc->sc_p.length);
698 * Populates the DH parameters for the DHKE
700 * \param[in,out] skc Shared key credentials structure to
701 * populate with DH parameters
703 * \retval GSS_S_COMPLETE success
704 * \retval GSS_S_FAILURE failure
706 uint32_t sk_gen_params(struct sk_cred *skc)
711 /* Random value used by both the request and response as part of the
712 * key binding material. This also should ensure we have unqiue
713 * tokens that are sent to the remote server which is important because
714 * the token is hashed for the sunrpc cache lookups and a failure there
715 * would cause connection attempts to fail indefinitely due to the large
716 * timeout value on the server side */
717 if (RAND_bytes((unsigned char *)&random, sizeof(random)) != 1) {
718 printerr(0, "Failed to get data for random parameter: %s\n",
719 ERR_error_string(ERR_get_error(), NULL));
720 return GSS_S_FAILURE;
723 /* The random value will always be used in byte range operations
724 * so we keep it as big endian from this point on */
725 skc->sc_kctx.skc_host_random = random;
727 /* Populate DH parameters */
728 skc->sc_params = DH_new();
729 if (!skc->sc_params) {
730 printerr(0, "Failed to allocate DH\n");
731 return GSS_S_FAILURE;
734 skc->sc_params->p = BN_bin2bn(skc->sc_p.value, skc->sc_p.length, NULL);
735 if (!skc->sc_params->p) {
736 printerr(0, "Failed to convert binary to BIGNUM\n");
737 return GSS_S_FAILURE;
740 /* We use a static generator for shared key */
741 skc->sc_params->g = BN_new();
742 if (!skc->sc_params->g) {
743 printerr(0, "Failed to allocate new BIGNUM\n");
744 return GSS_S_FAILURE;
746 if (BN_set_word(skc->sc_params->g, SK_GENERATOR) != 1) {
747 printerr(0, "Failed to set g value for DH params\n");
748 return GSS_S_FAILURE;
751 /* Verify that we have a safe prime and valid generator */
752 if (DH_check(skc->sc_params, &rc) != 1) {
753 printerr(0, "DH_check() failed: %d\n", rc);
754 return GSS_S_FAILURE;
756 printerr(0, "DH_check() returned error codes: 0x%x\n", rc);
757 return GSS_S_FAILURE;
760 if (DH_generate_key(skc->sc_params) != 1) {
761 printerr(0, "Failed to generate public DH key: %s\n",
762 ERR_error_string(ERR_get_error(), NULL));
763 return GSS_S_FAILURE;
766 skc->sc_pub_key.length = BN_num_bytes(skc->sc_params->pub_key);
767 skc->sc_pub_key.value = malloc(skc->sc_pub_key.length);
768 if (!skc->sc_pub_key.value) {
769 printerr(0, "Failed to allocate memory for public key\n");
770 return GSS_S_FAILURE;
773 BN_bn2bin(skc->sc_params->pub_key, skc->sc_pub_key.value);
775 return GSS_S_COMPLETE;
779 * Convert SK hash algorithm into openssl message digest
781 * \param[in,out] alg SK hash algorithm
785 static inline const EVP_MD *sk_hash_to_evp_md(enum sk_hmac_alg alg)
793 return EVP_md_null();
798 * Signs (via HMAC) the parameters used only in the key initialization protocol.
800 * \param[in] key Key to use for HMAC
801 * \param[in] bufs Array of gss_buffer_desc to generate
803 * \param[in] numbufs Number of buffers in array
804 * \param[in] hash_alg OpenSSL EVP_MD to use for hash
805 * \param[in,out] hmac HMAC of buffers is allocated and placed
806 * in this gss_buffer_desc. Caller must
812 int sk_sign_bufs(gss_buffer_desc *key, gss_buffer_desc *bufs, const int numbufs,
813 const EVP_MD *hash_alg, gss_buffer_desc *hmac)
816 unsigned int hashlen = EVP_MD_size(hash_alg);
820 if (hash_alg == EVP_md_null()) {
821 printerr(0, "Invalid hash algorithm\n");
825 HMAC_CTX_init(&hctx);
827 hmac->length = hashlen;
828 hmac->value = malloc(hashlen);
830 printerr(0, "Failed to allocate memory for HMAC\n");
834 if (HMAC_Init_ex(&hctx, key->value, key->length, hash_alg, NULL) != 1) {
835 printerr(0, "Failed to init HMAC\n");
839 for (i = 0; i < numbufs; i++) {
840 if (HMAC_Update(&hctx, bufs[i].value, bufs[i].length) != 1) {
841 printerr(0, "Failed to update HMAC\n");
846 /* The result gets populated in hmac */
847 if (HMAC_Final(&hctx, hmac->value, &hashlen) != 1) {
848 printerr(0, "Failed to finalize HMAC\n");
852 if (hmac->length != hashlen) {
853 printerr(0, "HMAC size does not match expected\n");
859 HMAC_CTX_cleanup(&hctx);
864 * Generates an HMAC for gss_buffer_desc array in \a bufs of \a numbufs
865 * and verifies against \a hmac.
867 * \param[in] skc Shared key credentials
868 * \param[in] bufs Array of gss_buffer_desc to generate HMAC for
869 * \param[in] numbufs Number of buffers in array
870 * \param[in] hash_alg OpenSSL EVP_MD to use for hash
871 * \param[in] hmac HMAC to verify against
873 * \retval GSS_S_COMPLETE success (match)
874 * \retval gss error failure
876 uint32_t sk_verify_hmac(struct sk_cred *skc, gss_buffer_desc *bufs,
877 const int numbufs, const EVP_MD *hash_alg,
878 gss_buffer_desc *hmac)
880 gss_buffer_desc bufs_hmac;
883 if (sk_sign_bufs(&skc->sc_kctx.skc_shared_key, bufs, numbufs, hash_alg,
885 printerr(0, "Failed to sign buffers to verify HMAC\n");
887 free(bufs_hmac.value);
888 return GSS_S_FAILURE;
891 if (hmac->length != bufs_hmac.length) {
892 printerr(0, "Invalid HMAC size\n");
893 free(bufs_hmac.value);
894 return GSS_S_BAD_SIG;
897 rc = memcmp(hmac->value, bufs_hmac.value, bufs_hmac.length);
898 free(bufs_hmac.value);
901 return GSS_S_BAD_SIG;
903 return GSS_S_COMPLETE;
907 * Cleanup an sk_cred freeing any resources
909 * \param[in,out] skc Shared key credentials to free
911 void sk_free_cred(struct sk_cred *skc)
917 free(skc->sc_p.value);
918 if (skc->sc_pub_key.value)
919 free(skc->sc_pub_key.value);
920 if (skc->sc_tgt.value)
921 free(skc->sc_tgt.value);
922 if (skc->sc_nodemap_hash.value)
923 free(skc->sc_nodemap_hash.value);
924 if (skc->sc_hmac.value)
925 free(skc->sc_hmac.value);
927 /* Overwrite keys and IV before freeing */
928 if (skc->sc_dh_shared_key.value) {
929 memset(skc->sc_dh_shared_key.value, 0,
930 skc->sc_dh_shared_key.length);
931 free(skc->sc_dh_shared_key.value);
933 if (skc->sc_kctx.skc_hmac_key.value) {
934 memset(skc->sc_kctx.skc_hmac_key.value, 0,
935 skc->sc_kctx.skc_hmac_key.length);
936 free(skc->sc_kctx.skc_hmac_key.value);
938 if (skc->sc_kctx.skc_encrypt_key.value) {
939 memset(skc->sc_kctx.skc_encrypt_key.value, 0,
940 skc->sc_kctx.skc_encrypt_key.length);
941 free(skc->sc_kctx.skc_encrypt_key.value);
943 if (skc->sc_kctx.skc_shared_key.value) {
944 memset(skc->sc_kctx.skc_shared_key.value, 0,
945 skc->sc_kctx.skc_shared_key.length);
946 free(skc->sc_kctx.skc_shared_key.value);
948 if (skc->sc_kctx.skc_session_key.value) {
949 memset(skc->sc_kctx.skc_session_key.value, 0,
950 skc->sc_kctx.skc_session_key.length);
951 free(skc->sc_kctx.skc_session_key.value);
955 DH_free(skc->sc_params);
961 /* This function handles key derivation using the hash algorithm specified in
962 * \a hash_alg, buffers in \a key_binding_bufs, and original key in
963 * \a origin_key to produce a \a derived_key. The first element of the
964 * key_binding_bufs array is reserved for the counter used in the KDF. The
965 * derived key in \a derived_key could differ in size from \a origin_key and
966 * must be populated with the expected size and a valid buffer to hold the
969 * If the derived key size is greater than the HMAC algorithm size it will be
970 * a done using several iterations of a counter and the key binding bufs.
972 * If the size is smaller it will take copy the first N bytes necessary to
973 * fill the derived key. */
974 int sk_kdf(gss_buffer_desc *derived_key , gss_buffer_desc *origin_key,
975 gss_buffer_desc *key_binding_bufs, int numbufs, int hmac_alg)
981 gss_buffer_desc tmp_hash;
988 /* Use a counter as the first buffer followed by the key binding
989 * buffers in the event we need more than one a single cycle to
990 * produced a symmetric key large enough in size */
991 key_binding_bufs[0].value = &counter;
992 key_binding_bufs[0].length = sizeof(counter);
994 remain = derived_key->length;
995 keydata = derived_key->value;
998 counter = htobe32(i++);
999 rc = sk_sign_bufs(origin_key, key_binding_bufs, numbufs,
1000 sk_hash_to_evp_md(hmac_alg), &tmp_hash);
1003 free(tmp_hash.value);
1007 LASSERT(sk_hmac_types[hmac_alg].sht_bytes ==
1010 bytes = (remain < tmp_hash.length) ? remain : tmp_hash.length;
1011 memcpy(keydata, tmp_hash.value, bytes);
1012 free(tmp_hash.value);
1020 /* Populates the sk_cred's session_key using the a Key Derviation Function (KDF)
1021 * based on the recommendations in NIST Special Publication SP 800-56B Rev 1
1022 * (Sep 2014) Section 5.5.1
1024 * \param[in,out] skc Shared key credentials structure with
1026 * \return -1 failure
1029 int sk_session_kdf(struct sk_cred *skc, lnet_nid_t client_nid,
1030 gss_buffer_desc *client_token, gss_buffer_desc *server_token)
1032 struct sk_kernel_ctx *kctx = &skc->sc_kctx;
1033 gss_buffer_desc *session_key = &kctx->skc_session_key;
1034 gss_buffer_desc bufs[5];
1037 session_key->length = sk_crypt_types[kctx->skc_crypt_alg].sct_bytes;
1038 session_key->value = malloc(session_key->length);
1039 if (!session_key->value) {
1040 printerr(0, "Failed to allocate memory for session key\n");
1044 /* Key binding info ordering
1045 * 1. Reserved for counter
1049 * 4. Server's token */
1050 bufs[0].value = NULL;
1052 bufs[1] = skc->sc_dh_shared_key;
1053 bufs[2].value = &client_nid;
1054 bufs[2].length = sizeof(client_nid);
1055 bufs[3] = *client_token;
1056 bufs[4] = *server_token;
1058 return sk_kdf(&kctx->skc_session_key, &kctx->skc_shared_key, bufs,
1059 5, kctx->skc_hmac_alg);
1062 /* Uses the session key to create an HMAC key and encryption key. In
1063 * integrity mode the session key used to generate the HMAC key uses
1064 * session information which is available on the wire but by creating
1065 * a session based HMAC key we can prevent potential replay as both the
1066 * client and server have random numbers used as part of the key creation.
1068 * The keys used for integrity and privacy are formulated as below using
1069 * the session key that is the output of the key derivation function. The
1070 * HMAC algorithm is determined by the shared key algorithm selected in the
1074 * Session HMAC Key = PBKDF2("Integrity", KDF derived Session Key)
1077 * Session HMAC Key = PBKDF2("Integrity", KDF derived Session Key)
1078 * Session Encryption Key = PBKDF2("Encrypt", KDF derived Session Key)
1080 * \param[in,out] skc Shared key credentials structure with
1082 * \return -1 failure
1085 int sk_compute_keys(struct sk_cred *skc)
1087 struct sk_kernel_ctx *kctx = &skc->sc_kctx;
1088 gss_buffer_desc *session_key = &kctx->skc_session_key;
1089 gss_buffer_desc *hmac_key = &kctx->skc_hmac_key;
1090 gss_buffer_desc *encrypt_key = &kctx->skc_encrypt_key;
1091 char *encrypt = "Encrypt";
1092 char *integrity = "Integrity";
1095 hmac_key->length = sk_hmac_types[kctx->skc_hmac_alg].sht_bytes;
1096 hmac_key->value = malloc(hmac_key->length);
1097 if (!hmac_key->value)
1100 rc = PKCS5_PBKDF2_HMAC(integrity, -1, session_key->value,
1101 session_key->length, SK_PBKDF2_ITERATIONS,
1102 sk_hash_to_evp_md(kctx->skc_hmac_alg),
1103 hmac_key->length, hmac_key->value);
1107 /* Encryption key is only populated in privacy mode */
1108 if ((skc->sc_flags & LGSS_SVC_PRIV) == 0)
1111 encrypt_key->length = sk_crypt_types[kctx->skc_crypt_alg].sct_bytes;
1112 encrypt_key->value = malloc(encrypt_key->length);
1113 if (!encrypt_key->value)
1116 rc = PKCS5_PBKDF2_HMAC(encrypt, -1, session_key->value,
1117 session_key->length, SK_PBKDF2_ITERATIONS,
1118 sk_hash_to_evp_md(kctx->skc_hmac_alg),
1119 encrypt_key->length, encrypt_key->value);
1127 * Computes a session key based on the DH parameters from the host and its peer
1129 * \param[in,out] skc Shared key credentials structure with
1130 * the session key populated with the
1132 * \param[in] pub_key Public key returned from peer in
1134 * \return gss error failure
1135 * \return GSS_S_COMPLETE success
1137 uint32_t sk_compute_dh_key(struct sk_cred *skc, const gss_buffer_desc *pub_key)
1139 gss_buffer_desc *dh_shared = &skc->sc_dh_shared_key;
1140 BIGNUM *remote_pub_key;
1142 uint32_t rc = GSS_S_FAILURE;
1144 remote_pub_key = BN_bin2bn(pub_key->value, pub_key->length, NULL);
1145 if (!remote_pub_key) {
1146 printerr(0, "Failed to convert binary to BIGNUM\n");
1150 dh_shared->length = DH_size(skc->sc_params);
1151 dh_shared->value = malloc(dh_shared->length);
1152 if (!dh_shared->value) {
1153 printerr(0, "Failed to allocate memory for computed shared "
1158 /* This compute the shared key from the DHKE */
1159 status = DH_compute_key(dh_shared->value, remote_pub_key,
1162 printerr(0, "DH_compute_key() failed: %s\n",
1163 ERR_error_string(ERR_get_error(), NULL));
1165 } else if (status < dh_shared->length) {
1166 printerr(0, "DH_compute_key() returned a short key of %d "
1167 "bytes, expected: %zu\n", status, dh_shared->length);
1168 rc = GSS_S_DEFECTIVE_TOKEN;
1172 rc = GSS_S_COMPLETE;
1175 BN_free(remote_pub_key);
1180 * Creates a serialized buffer for the kernel in the order of struct
1183 * \param[in,out] skc Shared key credentials structure
1184 * \param[in,out] ctx_token Serialized buffer for kernel.
1185 * Caller must free this buffer.
1188 * \return -1 failure
1190 int sk_serialize_kctx(struct sk_cred *skc, gss_buffer_desc *ctx_token)
1192 struct sk_kernel_ctx *kctx = &skc->sc_kctx;
1196 bufsize = sizeof(*kctx) + kctx->skc_hmac_key.length +
1197 kctx->skc_encrypt_key.length;
1199 ctx_token->value = malloc(bufsize);
1200 if (!ctx_token->value)
1202 ctx_token->length = bufsize;
1204 p = ctx_token->value;
1205 end = p + ctx_token->length;
1207 if (WRITE_BYTES(&p, end, kctx->skc_version))
1209 if (WRITE_BYTES(&p, end, kctx->skc_hmac_alg))
1211 if (WRITE_BYTES(&p, end, kctx->skc_crypt_alg))
1213 if (WRITE_BYTES(&p, end, kctx->skc_expire))
1215 if (WRITE_BYTES(&p, end, kctx->skc_host_random))
1217 if (WRITE_BYTES(&p, end, kctx->skc_peer_random))
1219 if (write_buffer(&p, end, &kctx->skc_hmac_key))
1221 if (write_buffer(&p, end, &kctx->skc_encrypt_key))
1224 printerr(2, "Serialized buffer of %zu bytes for kernel\n", bufsize);
1230 * Decodes a netstring \a ns into array of gss_buffer_descs at \a bufs
1231 * up to \a numbufs. Memory is allocated for each value and length
1232 * will be populated with the length
1234 * \param[in,out] bufs Array of gss_buffer_descs
1235 * \param[in,out] numbufs number of gss_buffer_desc in array
1236 * \param[in] ns netstring to decode
1238 * \return buffers populated success
1239 * \return -1 failure
1241 int sk_decode_netstring(gss_buffer_desc *bufs, int numbufs, gss_buffer_desc *ns)
1243 char *ptr = ns->value;
1244 size_t remain = ns->length;
1251 for (i = 0; i < numbufs; i++) {
1252 /* read the size of first buffer */
1253 rc = sscanf(ptr, "%9u", &size);
1256 digits = (size) ? ceil(log10(size + 1)) : 1;
1258 /* sep of current string */
1259 sep = size + digits + 2;
1261 /* check to make sure it's valid */
1262 if (remain < sep || ptr[digits] != ':' ||
1263 ptr[sep - 1] != ',')
1266 bufs[i].length = size;
1268 bufs[i].value = NULL;
1270 bufs[i].value = malloc(size);
1273 memcpy(bufs[i].value, &ptr[digits + 1], size);
1280 printerr(2, "Decoded netstring of %zu bytes\n", ns->length);
1286 free(bufs[i].value);
1293 * Creates a netstring in a gss_buffer_desc that consists of all
1294 * the gss_buffer_desc found in \a bufs. The netstring should be treated
1295 * as binary as it can contain null characters.
1297 * \param[in] bufs Array of gss_buffer_desc to use as input
1298 * \param[in] numbufs Number of buffers in array
1299 * \param[in,out] ns Destination gss_buffer_desc to hold
1302 * \return -1 failure
1305 int sk_encode_netstring(gss_buffer_desc *bufs, int numbufs,
1306 gss_buffer_desc *ns)
1313 /* size of string in decimal, string size, colon, and comma */
1314 for (i = 0; i < numbufs; i++) {
1316 if (bufs[i].length == 0)
1319 size += ceil(log10(bufs[i].length + 1)) +
1324 ns->value = malloc(ns->length);
1331 for (i = 0; i < numbufs; i++) {
1333 rc = snprintf((char *) ptr, size, "%zu:", bufs[i].length);
1337 memcpy(ptr, bufs[i].value, bufs[i].length);
1338 ptr += bufs[i].length;
1343 size -= bufs[i].length + rc + 1;
1345 /* should not happen */
1350 printerr(2, "Encoded netstring of %zu bytes\n", ns->length);