I am trying to use Linux kernel's crypto libraries to calculate an HMAC value, given key and message. The idea is to calculate the HMAC and insert it in a TCP option during an iperf session (this part is not relevant). This is the function I wrote to use the crypto libraries, and it takes two keys of 8 bytes (to be combined) and a variable number of bytes composing the message:
void crypto_hmac_sha1(u8 *key_1, u8 *key_2, u32 *hash_out, int arg_num, ...)
{
struct crypto_ashash *shash;
struct shash_desc *desc = NULL;
const char hmac_alg[] = "hmac(sha1)";
u8 key[16];
int i;
int ret;
int length;
u8 *msg;
va_list list;
/* Initialize result placeholder */
memset(hash_out, 0, sizeof(hash_out));
for (i = 0; i < 8; i++)
key[i] ^= key_1[i];
for (i = 0; i < 8; i++)
key[i + 8] ^= key_2[i];
printk("A1\n");
shash = crypto_alloc_ahash(hmac_alg, 0, 0);
printk("A2\n");
desc = kzalloc(sizeof(*desc) + crypto_shash_descsize(shash), GFP_KERNEL);
if (!desc)
goto out;
desc->tfm = shash;
desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
ret = crypto_shash_setkey(shash, key, 16);
if (ret < 0)
goto out;
crypto_shash_init(desc);
for (i = 0; i < arg_num; i++) {
length = va_arg(list, int);
msg = va_arg(list, u8 *);
ret = crypto_shash_update(desc, msg, length);
if (ret < 0)
goto out;
}
ret = crypto_shash_final(desc, hash_out);
out:
kfree(desc);
}
The error is the following (due to the fact that crypto_alloc_ahash tries to acquire a semaphore and it is not allowed in the current context):
BUG: scheduling while atomic: iperf/769/0x00000100
CPU: 0 PID: 769 Comm: iperf Not tainted 4.1.0-gdee0521-dirty #143
Received SIGSEGV in SIGSEGV handler, aborting stack trace!
Fix suggestions?
Without being familiar with the crypto library: if you have a upper bound for the the number of concurrent executions of crypto_hmac_sha1
, you might use a pool of preallocated hash algorithms structures. Given that scheduling/sleeping does not seem to be allowed, such a bound shouldn't be to hard to find: the number of hardware threads will do it.
Also, CRYPTO_TFM_REQ_MAY_SLEEP
seems suspicious if no scheduling is allowed.