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 * Author: Jeremy Filizetti <jfilizet@iu.edu>
34 #include <openssl/dh.h>
35 #include <openssl/engine.h>
36 #include <openssl/err.h>
37 #include <openssl/hmac.h>
38 #include <sys/types.h>
40 #include <lnet/nidstr.h>
43 #include "write_bytes.h"
45 #define SK_PBKDF2_ITERATIONS 10000
47 static struct sk_crypt_type sk_crypt_types[] = {
48 [SK_CRYPT_AES256_CTR] = {
49 .sct_name = "ctr(aes)",
54 static struct sk_hmac_type sk_hmac_types[] = {
56 .sht_name = "hmac(sha256)",
60 .sht_name = "hmac(sha512)",
66 # include "lgss_utils.h"
68 # include "gss_util.h"
69 # include "gss_oids.h"
70 # include "err_util.h"
76 * \param[in] program Program name to output
77 * \param[in] verbose Verbose flag
78 * \param[in] fg Whether or not to run in foreground
81 void sk_init_logging(char *program, int verbose, int fg)
83 initerr(program, verbose, fg);
88 * Loads the key from \a filename and returns the struct sk_keyfile_config.
89 * It should be freed by the caller.
91 * \param[in] filename Disk or key payload data
93 * \return sk_keyfile_config sucess
94 * \return NULL failure
96 struct sk_keyfile_config *sk_read_file(char *filename)
98 struct sk_keyfile_config *config;
104 config = malloc(sizeof(*config));
106 printerr(0, "Failed to allocate memory for config\n");
110 /* allow standard input override */
111 if (strcmp(filename, "-") == 0)
112 fd = dup(STDIN_FILENO);
114 fd = open(filename, O_RDONLY);
117 printerr(0, "Error opening file %s: %s\n", filename,
122 ptr = (char *)config;
123 remain = sizeof(*config);
125 rc = read(fd, ptr, remain);
129 printerr(0, "read() failed on %s: %s\n", filename,
132 } else if (rc == 0) {
133 printerr(0, "File %s does not have a complete key\n",
142 sk_config_disk_to_cpu(config);
153 * Checks if a key matching \a description is found in the keyring for
154 * logging purposes and then attempts to load \a payload of \a psize into a key
155 * with \a description.
157 * \param[in] payload Key payload
158 * \param[in] psize Payload size
159 * \param[in] description Description used for key in keyring
164 static key_serial_t sk_load_key(const struct sk_keyfile_config *skc,
165 const char *description)
167 struct sk_keyfile_config payload;
170 memcpy(&payload, skc, sizeof(*skc));
172 /* In the keyring use the disk layout so keyctl pipe can be used */
173 sk_config_cpu_to_disk(&payload);
175 /* Check to see if a key is already loaded matching description */
176 key = keyctl_search(KEY_SPEC_USER_KEYRING, "user", description, 0);
178 printerr(2, "Key %d found in session keyring, replacing\n",
181 key = add_key("user", description, &payload, sizeof(payload),
182 KEY_SPEC_USER_KEYRING);
184 printerr(2, "Added key %d with description %s\n", key,
187 printerr(0, "Failed to add key with %s\n", description);
193 * Reads the key from \a path, verifies it and loads into the session keyring
194 * using a description determined by the the \a type. Existing keys with the
195 * same description are replaced.
197 * \param[in] path Path to key file
198 * \param[in] type Type of key to load which determines the description
203 int sk_load_keyfile(char *path)
205 struct sk_keyfile_config *config;
206 char description[SK_DESCRIPTION_SIZE + 1];
212 rc = stat(path, &buf);
214 printerr(0, "stat() failed for file %s: %s\n", path,
219 config = sk_read_file(path);
223 /* Similar to ssh, require adequate care of key files */
224 if (buf.st_mode & (S_IRGRP | S_IWGRP | S_IWOTH | S_IXOTH)) {
225 printerr(0, "Shared key files must be read/writeable only by "
230 if (sk_validate_config(config))
233 /* The server side can have multiple key files per file system so
234 * the nodemap name is appended to the key description to uniquely
236 if (config->skc_type & SK_TYPE_MGS) {
237 /* Any key can be an MGS key as long as we are told to use it */
238 rc = snprintf(description, SK_DESCRIPTION_SIZE, "lustre:MGS:%s",
239 config->skc_nodemap);
240 if (rc >= SK_DESCRIPTION_SIZE)
242 if (sk_load_key(config, description) == -1)
245 if (config->skc_type & SK_TYPE_SERVER) {
246 /* Server keys need to have the file system name in the key */
247 if (!config->skc_fsname) {
248 printerr(0, "Key configuration has no file system "
249 "attribute. Can't load as server type\n");
252 rc = snprintf(description, SK_DESCRIPTION_SIZE, "lustre:%s:%s",
253 config->skc_fsname, config->skc_nodemap);
254 if (rc >= SK_DESCRIPTION_SIZE)
256 if (sk_load_key(config, description) == -1)
259 if (config->skc_type & SK_TYPE_CLIENT) {
260 /* Load client file system key */
261 if (config->skc_fsname) {
262 rc = snprintf(description, SK_DESCRIPTION_SIZE,
263 "lustre:%s", config->skc_fsname);
264 if (rc >= SK_DESCRIPTION_SIZE)
266 if (sk_load_key(config, description) == -1)
270 /* Load client MGC keys */
271 for (i = 0; i < MAX_MGSNIDS; i++) {
272 if (config->skc_mgsnids[i] == LNET_NID_ANY)
274 rc = snprintf(description, SK_DESCRIPTION_SIZE,
276 libcfs_nid2str(config->skc_mgsnids[i]));
277 if (rc >= SK_DESCRIPTION_SIZE)
279 if (sk_load_key(config, description) == -1)
292 * Byte swaps config from cpu format to disk
294 * \param[in,out] config sk_keyfile_config to swap
296 void sk_config_cpu_to_disk(struct sk_keyfile_config *config)
303 config->skc_version = htobe32(config->skc_version);
304 config->skc_hmac_alg = htobe16(config->skc_hmac_alg);
305 config->skc_crypt_alg = htobe16(config->skc_crypt_alg);
306 config->skc_expire = htobe32(config->skc_expire);
307 config->skc_shared_keylen = htobe32(config->skc_shared_keylen);
308 config->skc_prime_bits = htobe32(config->skc_prime_bits);
310 for (i = 0; i < MAX_MGSNIDS; i++)
311 config->skc_mgsnids[i] = htobe64(config->skc_mgsnids[i]);
317 * Byte swaps config from disk format to cpu
319 * \param[in,out] config sk_keyfile_config to swap
321 void sk_config_disk_to_cpu(struct sk_keyfile_config *config)
328 config->skc_version = be32toh(config->skc_version);
329 config->skc_hmac_alg = be16toh(config->skc_hmac_alg);
330 config->skc_crypt_alg = be16toh(config->skc_crypt_alg);
331 config->skc_expire = be32toh(config->skc_expire);
332 config->skc_shared_keylen = be32toh(config->skc_shared_keylen);
333 config->skc_prime_bits = be32toh(config->skc_prime_bits);
335 for (i = 0; i < MAX_MGSNIDS; i++)
336 config->skc_mgsnids[i] = be64toh(config->skc_mgsnids[i]);
342 * Verifies the on key payload format is valid
344 * \param[in] config sk_keyfile_config
349 int sk_validate_config(const struct sk_keyfile_config *config)
354 printerr(0, "Null configuration passed\n");
357 if (config->skc_version != SK_CONF_VERSION) {
358 printerr(0, "Invalid version\n");
361 if (config->skc_hmac_alg >= SK_HMAC_MAX) {
362 printerr(0, "Invalid HMAC algorithm\n");
365 if (config->skc_crypt_alg >= SK_CRYPT_MAX) {
366 printerr(0, "Invalid crypt algorithm\n");
369 if (config->skc_expire < 60 || config->skc_expire > INT_MAX) {
370 /* Try to limit key expiration to some reasonable minimum and
371 * also prevent values over INT_MAX because there appears
372 * to be a type conversion issue */
373 printerr(0, "Invalid expiration time should be between %d "
374 "and %d\n", 60, INT_MAX);
377 if (config->skc_prime_bits % 8 != 0 ||
378 config->skc_prime_bits > SK_MAX_P_BYTES * 8) {
379 printerr(0, "Invalid session key length must be a multiple of 8"
380 " and less then %d bits\n",
384 if (config->skc_shared_keylen % 8 != 0 ||
385 config->skc_shared_keylen > SK_MAX_KEYLEN_BYTES * 8){
386 printerr(0, "Invalid shared key max length must be a multiple "
387 "of 8 and less then %d bits\n",
388 SK_MAX_KEYLEN_BYTES * 8);
392 /* Check for terminating nulls on strings */
393 for (i = 0; i < sizeof(config->skc_fsname) &&
394 config->skc_fsname[i] != '\0'; i++)
396 if (i == sizeof(config->skc_fsname)) {
397 printerr(0, "File system name not null terminated\n");
401 for (i = 0; i < sizeof(config->skc_nodemap) &&
402 config->skc_nodemap[i] != '\0'; i++)
404 if (i == sizeof(config->skc_nodemap)) {
405 printerr(0, "Nodemap name not null terminated\n");
409 if (config->skc_type == SK_TYPE_INVALID) {
410 printerr(0, "Invalid key type\n");
418 * Hashes \a string and places the hash in \a hash
421 * \param[in] string Null terminated string to hash
422 * \param[in] hash_alg OpenSSL EVP_MD to use for hash
423 * \param[in,out] hash gss_buffer_desc to hold the result
428 static int sk_hash_string(const char *string, const EVP_MD *hash_alg,
429 gss_buffer_desc *hash)
431 EVP_MD_CTX *ctx = EVP_MD_CTX_create();
432 size_t len = strlen(string);
433 unsigned int hashlen;
435 if (!hash->value || hash->length < EVP_MD_size(hash_alg))
437 if (!EVP_DigestInit_ex(ctx, hash_alg, NULL))
439 if (!EVP_DigestUpdate(ctx, string, len))
441 if (!EVP_DigestFinal_ex(ctx, hash->value, &hashlen))
444 EVP_MD_CTX_destroy(ctx);
445 hash->length = hashlen;
449 EVP_MD_CTX_destroy(ctx);
454 * Hashes \a string and verifies the resulting hash matches the value
457 * \param[in] string Null terminated string to hash
458 * \param[in] hash_alg OpenSSL EVP_MD to use for hash
459 * \param[in,out] current_hash gss_buffer_desc to compare to
461 * \return gss error failure
462 * \return GSS_S_COMPLETE success
464 uint32_t sk_verify_hash(const char *string, const EVP_MD *hash_alg,
465 const gss_buffer_desc *current_hash)
467 gss_buffer_desc hash;
468 unsigned char hashbuf[EVP_MAX_MD_SIZE];
470 hash.value = hashbuf;
471 hash.length = sizeof(hashbuf);
473 if (sk_hash_string(string, hash_alg, &hash))
474 return GSS_S_FAILURE;
475 if (current_hash->length != hash.length)
476 return GSS_S_DEFECTIVE_TOKEN;
477 if (memcmp(current_hash->value, hash.value, hash.length))
478 return GSS_S_BAD_SIG;
480 return GSS_S_COMPLETE;
483 static inline int sk_config_has_mgsnid(struct sk_keyfile_config *config,
489 nid = libcfs_str2nid(mgsnid);
490 if (nid == LNET_NID_ANY)
493 for (i = 0; i < MAX_MGSNIDS; i++)
494 if (config->skc_mgsnids[i] == nid)
500 * Create an sk_cred structure populated with initial configuration info and the
501 * key. \a tgt and \a nodemap are used in determining the expected key
502 * description so the key can be found by searching the keyring.
503 * This is done because there is no easy way to pass keys from the mount command
504 * all the way to the request_key call. In addition any keys can be dynamically
505 * added to the keyrings and still found. The keyring that needs to be used
506 * must be the session keyring.
508 * \param[in] tgt Target file system
509 * \param[in] nodemap Cluster name for the key. This correlates to
510 * the nodemap name and is used by the server side.
511 * For the client this will be NULL.
512 * \param[in] flags Flags for the credentials
514 * \return sk_cred Allocated struct sk_cred on success
515 * \return NULL failure
517 struct sk_cred *sk_create_cred(const char *tgt, const char *nodemap,
518 const uint32_t flags)
520 struct sk_keyfile_config *config;
521 struct sk_kernel_ctx *kctx;
522 struct sk_cred *skc = NULL;
523 char description[SK_DESCRIPTION_SIZE + 1];
524 char fsname[MTI_NAME_MAXLEN + 1];
525 const char *mgsnid = NULL;
532 printerr(2, "Creating credentials for target: %s with nodemap: %s\n",
535 memset(description, 0, sizeof(description));
536 memset(fsname, 0, sizeof(fsname));
538 /* extract the file system name from target */
539 ptr = index(tgt, '-');
543 /* This must be an MGC target */
544 if (strncmp(tgt, "MGC", 3) || len <= 3) {
545 printerr(0, "Invalid target name\n");
553 if (len > MTI_NAME_MAXLEN) {
554 printerr(0, "Invalid target name\n");
557 memcpy(fsname, tgt, len);
561 rc = snprintf(description, SK_DESCRIPTION_SIZE,
562 "lustre:MGS:%s", nodemap);
564 rc = snprintf(description, SK_DESCRIPTION_SIZE,
565 "lustre:%s:%s", fsname, nodemap);
567 rc = snprintf(description, SK_DESCRIPTION_SIZE, "lustre:%s",
571 if (rc >= SK_DESCRIPTION_SIZE) {
572 printerr(0, "Invalid key description\n");
576 /* It may be a good idea to move Lustre keys to the gss_keyring
577 * (lgssc) type so that they expire when Lustre modules are removed.
578 * Unfortunately it can't be done at mount time because the mount
579 * syscall could trigger the Lustre modules to load and until that
580 * point we don't have a lgssc key type.
582 * TODO: Query the community for a consensus here */
583 printerr(2, "Searching for key with description: %s\n", description);
584 sk_key = keyctl_search(KEY_SPEC_USER_KEYRING, "user",
587 printerr(1, "No key found for %s\n", description);
591 keylen = keyctl_read_alloc(sk_key, (void **)&config);
593 printerr(0, "keyctl_read() failed for key %ld: %s\n", sk_key,
596 } else if (keylen != sizeof(*config)) {
597 printerr(0, "Unexpected key size: %d returned for key %ld, "
598 "expected %zu bytes\n",
599 keylen, sk_key, sizeof(*config));
603 sk_config_disk_to_cpu(config);
605 if (sk_validate_config(config)) {
606 printerr(0, "Invalid key configuration for key: %ld\n", sk_key);
610 if (mgsnid && !sk_config_has_mgsnid(config, mgsnid)) {
611 printerr(0, "Target name does not match key's MGS NIDs\n");
615 if (!mgsnid && strcmp(fsname, config->skc_fsname)) {
616 printerr(0, "Target name does not match key's file system\n");
620 skc = malloc(sizeof(*skc));
622 printerr(0, "Failed to allocate memory for sk_cred\n");
626 /* this initializes all gss_buffer_desc to empty as well */
627 memset(skc, 0, sizeof(*skc));
629 skc->sc_flags = flags;
630 skc->sc_tgt.length = strlen(tgt) + 1;
631 skc->sc_tgt.value = malloc(skc->sc_tgt.length);
632 if (!skc->sc_tgt.value) {
633 printerr(0, "Failed to allocate memory for target\n");
636 memcpy(skc->sc_tgt.value, tgt, skc->sc_tgt.length);
638 skc->sc_nodemap_hash.length = EVP_MD_size(EVP_sha256());
639 skc->sc_nodemap_hash.value = malloc(skc->sc_nodemap_hash.length);
640 if (!skc->sc_nodemap_hash.value) {
641 printerr(0, "Failed to allocate memory for nodemap hash\n");
645 if (sk_hash_string(config->skc_nodemap, EVP_sha256(),
646 &skc->sc_nodemap_hash)) {
647 printerr(0, "Failed to generate hash for nodemap name\n");
651 kctx = &skc->sc_kctx;
652 kctx->skc_version = config->skc_version;
653 kctx->skc_hmac_alg = config->skc_hmac_alg;
654 kctx->skc_crypt_alg = config->skc_crypt_alg;
655 kctx->skc_expire = config->skc_expire;
657 /* key payload format is in bits, convert to bytes */
658 kctx->skc_shared_key.length = config->skc_shared_keylen / 8;
659 kctx->skc_shared_key.value = malloc(kctx->skc_shared_key.length);
660 if (!kctx->skc_shared_key.value) {
661 printerr(0, "Failed to allocate memory for shared key\n");
664 memcpy(kctx->skc_shared_key.value, config->skc_shared_key,
665 kctx->skc_shared_key.length);
667 skc->sc_p.length = config->skc_prime_bits / 8;
668 skc->sc_p.value = malloc(skc->sc_p.length);
669 if (!skc->sc_p.value) {
670 printerr(0, "Failed to allocate p\n");
673 memcpy(skc->sc_p.value, config->skc_p, skc->sc_p.length);
687 * Populates the DH parameters for the DHKE
689 * \param[in,out] skc Shared key credentials structure to
690 * populate with DH parameters
692 * \retval GSS_S_COMPLETE success
693 * \retval GSS_S_FAILURE failure
695 uint32_t sk_gen_params(struct sk_cred *skc)
700 /* Random value used by both the request and response as part of the
701 * key binding material. This also should ensure we have unqiue
702 * tokens that are sent to the remote server which is important because
703 * the token is hashed for the sunrpc cache lookups and a failure there
704 * would cause connection attempts to fail indefinitely due to the large
705 * timeout value on the server side */
706 if (RAND_bytes((unsigned char *)&random, sizeof(random)) != 1) {
707 printerr(0, "Failed to get data for random parameter: %s\n",
708 ERR_error_string(ERR_get_error(), NULL));
709 return GSS_S_FAILURE;
712 /* The random value will always be used in byte range operations
713 * so we keep it as big endian from this point on */
714 skc->sc_kctx.skc_host_random = random;
716 /* Populate DH parameters */
717 skc->sc_params = DH_new();
718 if (!skc->sc_params) {
719 printerr(0, "Failed to allocate DH\n");
720 return GSS_S_FAILURE;
723 skc->sc_params->p = BN_bin2bn(skc->sc_p.value, skc->sc_p.length, NULL);
724 if (!skc->sc_params->p) {
725 printerr(0, "Failed to convert binary to BIGNUM\n");
726 return GSS_S_FAILURE;
729 /* We use a static generator for shared key */
730 skc->sc_params->g = BN_new();
731 if (!skc->sc_params->g) {
732 printerr(0, "Failed to allocate new BIGNUM\n");
733 return GSS_S_FAILURE;
735 if (BN_set_word(skc->sc_params->g, SK_GENERATOR) != 1) {
736 printerr(0, "Failed to set g value for DH params\n");
737 return GSS_S_FAILURE;
740 /* Verify that we have a safe prime and valid generator */
741 if (DH_check(skc->sc_params, &rc) != 1) {
742 printerr(0, "DH_check() failed: %d\n", rc);
743 return GSS_S_FAILURE;
745 printerr(0, "DH_check() returned error codes: 0x%x\n", rc);
746 return GSS_S_FAILURE;
749 if (DH_generate_key(skc->sc_params) != 1) {
750 printerr(0, "Failed to generate public DH key: %s\n",
751 ERR_error_string(ERR_get_error(), NULL));
752 return GSS_S_FAILURE;
755 skc->sc_pub_key.length = BN_num_bytes(skc->sc_params->pub_key);
756 skc->sc_pub_key.value = malloc(skc->sc_pub_key.length);
757 if (!skc->sc_pub_key.value) {
758 printerr(0, "Failed to allocate memory for public key\n");
759 return GSS_S_FAILURE;
762 BN_bn2bin(skc->sc_params->pub_key, skc->sc_pub_key.value);
764 return GSS_S_COMPLETE;
768 * Convert SK hash algorithm into openssl message digest
770 * \param[in,out] alg SK hash algorithm
774 static inline const EVP_MD *sk_hash_to_evp_md(enum sk_hmac_alg alg)
782 return EVP_md_null();
787 * Signs (via HMAC) the parameters used only in the key initialization protocol.
789 * \param[in] key Key to use for HMAC
790 * \param[in] bufs Array of gss_buffer_desc to generate
792 * \param[in] numbufs Number of buffers in array
793 * \param[in] hash_alg OpenSSL EVP_MD to use for hash
794 * \param[in,out] hmac HMAC of buffers is allocated and placed
795 * in this gss_buffer_desc. Caller must
801 int sk_sign_bufs(gss_buffer_desc *key, gss_buffer_desc *bufs, const int numbufs,
802 const EVP_MD *hash_alg, gss_buffer_desc *hmac)
805 unsigned int hashlen = EVP_MD_size(hash_alg);
809 if (hash_alg == EVP_md_null()) {
810 printerr(0, "Invalid hash algorithm\n");
814 HMAC_CTX_init(&hctx);
816 hmac->length = hashlen;
817 hmac->value = malloc(hashlen);
819 printerr(0, "Failed to allocate memory for HMAC\n");
823 if (HMAC_Init_ex(&hctx, key->value, key->length, hash_alg, NULL) != 1) {
824 printerr(0, "Failed to init HMAC\n");
828 for (i = 0; i < numbufs; i++) {
829 if (HMAC_Update(&hctx, bufs[i].value, bufs[i].length) != 1) {
830 printerr(0, "Failed to update HMAC\n");
835 /* The result gets populated in hmac */
836 if (HMAC_Final(&hctx, hmac->value, &hashlen) != 1) {
837 printerr(0, "Failed to finalize HMAC\n");
841 if (hmac->length != hashlen) {
842 printerr(0, "HMAC size does not match expected\n");
848 HMAC_CTX_cleanup(&hctx);
853 * Generates an HMAC for gss_buffer_desc array in \a bufs of \a numbufs
854 * and verifies against \a hmac.
856 * \param[in] skc Shared key credentials
857 * \param[in] bufs Array of gss_buffer_desc to generate HMAC for
858 * \param[in] numbufs Number of buffers in array
859 * \param[in] hash_alg OpenSSL EVP_MD to use for hash
860 * \param[in] hmac HMAC to verify against
862 * \retval GSS_S_COMPLETE success (match)
863 * \retval gss error failure
865 uint32_t sk_verify_hmac(struct sk_cred *skc, gss_buffer_desc *bufs,
866 const int numbufs, const EVP_MD *hash_alg,
867 gss_buffer_desc *hmac)
869 gss_buffer_desc bufs_hmac;
872 if (sk_sign_bufs(&skc->sc_kctx.skc_shared_key, bufs, numbufs, hash_alg,
874 printerr(0, "Failed to sign buffers to verify HMAC\n");
876 free(bufs_hmac.value);
877 return GSS_S_FAILURE;
880 if (hmac->length != bufs_hmac.length) {
881 printerr(0, "Invalid HMAC size\n");
882 free(bufs_hmac.value);
883 return GSS_S_BAD_SIG;
886 rc = memcmp(hmac->value, bufs_hmac.value, bufs_hmac.length);
887 free(bufs_hmac.value);
890 return GSS_S_BAD_SIG;
892 return GSS_S_COMPLETE;
896 * Cleanup an sk_cred freeing any resources
898 * \param[in,out] skc Shared key credentials to free
900 void sk_free_cred(struct sk_cred *skc)
906 free(skc->sc_p.value);
907 if (skc->sc_pub_key.value)
908 free(skc->sc_pub_key.value);
909 if (skc->sc_tgt.value)
910 free(skc->sc_tgt.value);
911 if (skc->sc_nodemap_hash.value)
912 free(skc->sc_nodemap_hash.value);
913 if (skc->sc_hmac.value)
914 free(skc->sc_hmac.value);
916 /* Overwrite keys and IV before freeing */
917 if (skc->sc_dh_shared_key.value) {
918 memset(skc->sc_dh_shared_key.value, 0,
919 skc->sc_dh_shared_key.length);
920 free(skc->sc_dh_shared_key.value);
922 if (skc->sc_kctx.skc_hmac_key.value) {
923 memset(skc->sc_kctx.skc_hmac_key.value, 0,
924 skc->sc_kctx.skc_hmac_key.length);
925 free(skc->sc_kctx.skc_hmac_key.value);
927 if (skc->sc_kctx.skc_encrypt_key.value) {
928 memset(skc->sc_kctx.skc_encrypt_key.value, 0,
929 skc->sc_kctx.skc_encrypt_key.length);
930 free(skc->sc_kctx.skc_encrypt_key.value);
932 if (skc->sc_kctx.skc_shared_key.value) {
933 memset(skc->sc_kctx.skc_shared_key.value, 0,
934 skc->sc_kctx.skc_shared_key.length);
935 free(skc->sc_kctx.skc_shared_key.value);
937 if (skc->sc_kctx.skc_session_key.value) {
938 memset(skc->sc_kctx.skc_session_key.value, 0,
939 skc->sc_kctx.skc_session_key.length);
940 free(skc->sc_kctx.skc_session_key.value);
944 DH_free(skc->sc_params);
950 /* This function handles key derivation using the hash algorithm specified in
951 * \a hash_alg, buffers in \a key_binding_bufs, and original key in
952 * \a origin_key to produce a \a derived_key. The first element of the
953 * key_binding_bufs array is reserved for the counter used in the KDF. The
954 * derived key in \a derived_key could differ in size from \a origin_key and
955 * must be populated with the expected size and a valid buffer to hold the
958 * If the derived key size is greater than the HMAC algorithm size it will be
959 * a done using several iterations of a counter and the key binding bufs.
961 * If the size is smaller it will take copy the first N bytes necessary to
962 * fill the derived key. */
963 int sk_kdf(gss_buffer_desc *derived_key , gss_buffer_desc *origin_key,
964 gss_buffer_desc *key_binding_bufs, int numbufs, int hmac_alg)
970 gss_buffer_desc tmp_hash;
977 /* Use a counter as the first buffer followed by the key binding
978 * buffers in the event we need more than one a single cycle to
979 * produced a symmetric key large enough in size */
980 key_binding_bufs[0].value = &counter;
981 key_binding_bufs[0].length = sizeof(counter);
983 remain = derived_key->length;
984 keydata = derived_key->value;
987 counter = htobe32(i++);
988 rc = sk_sign_bufs(origin_key, key_binding_bufs, numbufs,
989 sk_hash_to_evp_md(hmac_alg), &tmp_hash);
992 free(tmp_hash.value);
996 LASSERT(sk_hmac_types[hmac_alg].sht_bytes ==
999 bytes = (remain < tmp_hash.length) ? remain : tmp_hash.length;
1000 memcpy(keydata, tmp_hash.value, bytes);
1001 free(tmp_hash.value);
1009 /* Populates the sk_cred's session_key using the a Key Derviation Function (KDF)
1010 * based on the recommendations in NIST Special Publication SP 800-56B Rev 1
1011 * (Sep 2014) Section 5.5.1
1013 * \param[in,out] skc Shared key credentials structure with
1015 * \return -1 failure
1018 int sk_session_kdf(struct sk_cred *skc, lnet_nid_t client_nid,
1019 gss_buffer_desc *client_token, gss_buffer_desc *server_token)
1021 struct sk_kernel_ctx *kctx = &skc->sc_kctx;
1022 gss_buffer_desc *session_key = &kctx->skc_session_key;
1023 gss_buffer_desc bufs[5];
1026 session_key->length = sk_crypt_types[kctx->skc_crypt_alg].sct_bytes;
1027 session_key->value = malloc(session_key->length);
1028 if (!session_key->value) {
1029 printerr(0, "Failed to allocate memory for session key\n");
1033 /* Key binding info ordering
1034 * 1. Reserved for counter
1038 * 4. Server's token */
1039 bufs[0].value = NULL;
1041 bufs[1] = skc->sc_dh_shared_key;
1042 bufs[2].value = &client_nid;
1043 bufs[2].length = sizeof(client_nid);
1044 bufs[3] = *client_token;
1045 bufs[4] = *server_token;
1047 return sk_kdf(&kctx->skc_session_key, &kctx->skc_shared_key, bufs,
1048 5, kctx->skc_hmac_alg);
1051 /* Uses the session key to create an HMAC key and encryption key. In
1052 * integrity mode the session key used to generate the HMAC key uses
1053 * session information which is available on the wire but by creating
1054 * a session based HMAC key we can prevent potential replay as both the
1055 * client and server have random numbers used as part of the key creation.
1057 * The keys used for integrity and privacy are formulated as below using
1058 * the session key that is the output of the key derivation function. The
1059 * HMAC algorithm is determined by the shared key algorithm selected in the
1063 * Session HMAC Key = PBKDF2("Integrity", KDF derived Session Key)
1066 * Session HMAC Key = PBKDF2("Integrity", KDF derived Session Key)
1067 * Session Encryption Key = PBKDF2("Encrypt", KDF derived Session Key)
1069 * \param[in,out] skc Shared key credentials structure with
1071 * \return -1 failure
1074 int sk_compute_keys(struct sk_cred *skc)
1076 struct sk_kernel_ctx *kctx = &skc->sc_kctx;
1077 gss_buffer_desc *session_key = &kctx->skc_session_key;
1078 gss_buffer_desc *hmac_key = &kctx->skc_hmac_key;
1079 gss_buffer_desc *encrypt_key = &kctx->skc_encrypt_key;
1080 char *encrypt = "Encrypt";
1081 char *integrity = "Integrity";
1084 hmac_key->length = sk_hmac_types[kctx->skc_hmac_alg].sht_bytes;
1085 hmac_key->value = malloc(hmac_key->length);
1086 if (!hmac_key->value)
1089 rc = PKCS5_PBKDF2_HMAC(integrity, -1, session_key->value,
1090 session_key->length, SK_PBKDF2_ITERATIONS,
1091 sk_hash_to_evp_md(kctx->skc_hmac_alg),
1092 hmac_key->length, hmac_key->value);
1096 /* Encryption key is only populated in privacy mode */
1097 if ((skc->sc_flags & LGSS_SVC_PRIV) == 0)
1100 encrypt_key->length = sk_crypt_types[kctx->skc_crypt_alg].sct_bytes;
1101 encrypt_key->value = malloc(encrypt_key->length);
1102 if (!encrypt_key->value)
1105 rc = PKCS5_PBKDF2_HMAC(encrypt, -1, session_key->value,
1106 session_key->length, SK_PBKDF2_ITERATIONS,
1107 sk_hash_to_evp_md(kctx->skc_hmac_alg),
1108 encrypt_key->length, encrypt_key->value);
1116 * Computes a session key based on the DH parameters from the host and its peer
1118 * \param[in,out] skc Shared key credentials structure with
1119 * the session key populated with the
1121 * \param[in] pub_key Public key returned from peer in
1123 * \return gss error failure
1124 * \return GSS_S_COMPLETE success
1126 uint32_t sk_compute_dh_key(struct sk_cred *skc, const gss_buffer_desc *pub_key)
1128 gss_buffer_desc *dh_shared = &skc->sc_dh_shared_key;
1129 BIGNUM *remote_pub_key;
1131 uint32_t rc = GSS_S_FAILURE;
1133 remote_pub_key = BN_bin2bn(pub_key->value, pub_key->length, NULL);
1134 if (!remote_pub_key) {
1135 printerr(0, "Failed to convert binary to BIGNUM\n");
1139 dh_shared->length = DH_size(skc->sc_params);
1140 dh_shared->value = malloc(dh_shared->length);
1141 if (!dh_shared->value) {
1142 printerr(0, "Failed to allocate memory for computed shared "
1147 /* This compute the shared key from the DHKE */
1148 status = DH_compute_key(dh_shared->value, remote_pub_key,
1151 printerr(0, "DH_compute_key() failed: %s\n",
1152 ERR_error_string(ERR_get_error(), NULL));
1154 } else if (status < dh_shared->length) {
1155 printerr(0, "DH_compute_key() returned a short key of %d "
1156 "bytes, expected: %zu\n", status, dh_shared->length);
1157 rc = GSS_S_DEFECTIVE_TOKEN;
1161 rc = GSS_S_COMPLETE;
1164 BN_free(remote_pub_key);
1169 * Creates a serialized buffer for the kernel in the order of struct
1172 * \param[in,out] skc Shared key credentials structure
1173 * \param[in,out] ctx_token Serialized buffer for kernel.
1174 * Caller must free this buffer.
1177 * \return -1 failure
1179 int sk_serialize_kctx(struct sk_cred *skc, gss_buffer_desc *ctx_token)
1181 struct sk_kernel_ctx *kctx = &skc->sc_kctx;
1185 bufsize = sizeof(*kctx) + kctx->skc_hmac_key.length +
1186 kctx->skc_encrypt_key.length;
1188 ctx_token->value = malloc(bufsize);
1189 if (!ctx_token->value)
1191 ctx_token->length = bufsize;
1193 p = ctx_token->value;
1194 end = p + ctx_token->length;
1196 if (WRITE_BYTES(&p, end, kctx->skc_version))
1198 if (WRITE_BYTES(&p, end, kctx->skc_hmac_alg))
1200 if (WRITE_BYTES(&p, end, kctx->skc_crypt_alg))
1202 if (WRITE_BYTES(&p, end, kctx->skc_expire))
1204 if (WRITE_BYTES(&p, end, kctx->skc_host_random))
1206 if (WRITE_BYTES(&p, end, kctx->skc_peer_random))
1208 if (write_buffer(&p, end, &kctx->skc_hmac_key))
1210 if (write_buffer(&p, end, &kctx->skc_encrypt_key))
1213 printerr(2, "Serialized buffer of %zu bytes for kernel\n", bufsize);
1219 * Decodes a netstring \a ns into array of gss_buffer_descs at \a bufs
1220 * up to \a numbufs. Memory is allocated for each value and length
1221 * will be populated with the length
1223 * \param[in,out] bufs Array of gss_buffer_descs
1224 * \param[in,out] numbufs number of gss_buffer_desc in array
1225 * \param[in] ns netstring to decode
1227 * \return buffers populated success
1228 * \return -1 failure
1230 int sk_decode_netstring(gss_buffer_desc *bufs, int numbufs, gss_buffer_desc *ns)
1232 char *ptr = ns->value;
1233 size_t remain = ns->length;
1240 for (i = 0; i < numbufs; i++) {
1241 /* read the size of first buffer */
1242 rc = sscanf(ptr, "%9u", &size);
1245 digits = (size) ? ceil(log10(size + 1)) : 1;
1247 /* sep of current string */
1248 sep = size + digits + 2;
1250 /* check to make sure it's valid */
1251 if (remain < sep || ptr[digits] != ':' ||
1252 ptr[sep - 1] != ',')
1255 bufs[i].length = size;
1257 bufs[i].value = NULL;
1259 bufs[i].value = malloc(size);
1262 memcpy(bufs[i].value, &ptr[digits + 1], size);
1269 printerr(2, "Decoded netstring of %zu bytes\n", ns->length);
1275 free(bufs[i].value);
1282 * Creates a netstring in a gss_buffer_desc that consists of all
1283 * the gss_buffer_desc found in \a bufs. The netstring should be treated
1284 * as binary as it can contain null characters.
1286 * \param[in] bufs Array of gss_buffer_desc to use as input
1287 * \param[in] numbufs Number of buffers in array
1288 * \param[in,out] ns Destination gss_buffer_desc to hold
1291 * \return -1 failure
1294 int sk_encode_netstring(gss_buffer_desc *bufs, int numbufs,
1295 gss_buffer_desc *ns)
1302 /* size of string in decimal, string size, colon, and comma */
1303 for (i = 0; i < numbufs; i++) {
1305 if (bufs[i].length == 0)
1308 size += ceil(log10(bufs[i].length + 1)) +
1313 ns->value = malloc(ns->length);
1320 for (i = 0; i < numbufs; i++) {
1322 rc = snprintf((char *) ptr, size, "%zu:", bufs[i].length);
1326 memcpy(ptr, bufs[i].value, bufs[i].length);
1327 ptr += bufs[i].length;
1332 size -= bufs[i].length + rc + 1;
1334 /* should not happen */
1339 printerr(2, "Encoded netstring of %zu bytes\n", ns->length);