ff4d86c2e0c2011c94050a657c7cb99af706e3e1
[strongswan.git] / src / charon-tkm / src / tkm / tkm_spi_generator.c
1 /*
2 * Copyright (C) 2015 Reto Buerki
3 * Copyright (C) 2015 Adrian-Ken Rueegsegger
4 * HSR Hochschule fuer Technik Rapperswil
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2 of the License, or (at your
9 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * for more details.
15 */
16
17 #include <inttypes.h>
18 #include <library.h>
19 #include <daemon.h>
20
21 #include "tkm_spi_generator.h"
22
23 /**
24 * Get SPI callback arguments
25 */
26 typedef struct {
27 rng_t *rng;
28 uint64_t spi_mask;
29 uint64_t spi_label;
30 } get_spi_args_t;
31
32 static get_spi_args_t *spi_args;
33
34 /**
35 * Callback called to generate an IKE SPI.
36 *
37 * @param this Callback args containing rng_t and spi mask & label
38 * @return labeled SPI
39 */
40 CALLBACK(tkm_get_spi, uint64_t,
41 const get_spi_args_t const *this)
42 {
43 uint64_t spi;
44
45 if (!this->rng->get_bytes(this->rng, sizeof(spi), (uint8_t*)&spi))
46 {
47 return 0;
48 }
49
50 return (spi & ~this->spi_mask) | this->spi_label;
51 }
52
53 bool tkm_spi_generator_register(plugin_t *plugin,
54 plugin_feature_t *feature,
55 bool reg, void *cb_data)
56 {
57 uint64_t spi_mask, spi_label;
58 char *spi_val;
59 rng_t *rng;
60
61 if (reg)
62 {
63 rng = lib->crypto->create_rng(lib->crypto, RNG_WEAK);
64 if (!rng)
65 {
66 return FALSE;
67 }
68
69 spi_val = lib->settings->get_str(lib->settings, "%s.spi_mask", NULL,
70 lib->ns);
71 spi_mask = settings_value_as_uint64(spi_val, 0);
72
73 spi_val = lib->settings->get_str(lib->settings, "%s.spi_label", NULL,
74 lib->ns);
75 spi_label = settings_value_as_uint64(spi_val, 0);
76
77 INIT(spi_args,
78 .rng = rng,
79 .spi_mask = spi_mask,
80 .spi_label = spi_label,
81 );
82
83 charon->ike_sa_manager->set_spi_cb(charon->ike_sa_manager,
84 tkm_get_spi, spi_args);
85 DBG1(DBG_IKE, "using SPI label 0x%.16"PRIx64" and mask 0x%.16"PRIx64,
86 spi_label, spi_mask);
87 }
88 else
89 {
90 if (spi_args)
91 {
92 DESTROY_IF(spi_args->rng);
93 free(spi_args);
94 }
95 }
96
97 return TRUE;
98 }