From 3c77290c2c93cb16f7504e7e371699c6ca9bb289 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Thu, 31 Dec 2020 11:26:22 +0530 Subject: [PATCH] Code to get random bytes in C, cross-platform --- kitty/cross-platform-random.h | 35 +++++++++++++++++++++++++++++++++++ kitty/disk-cache.c | 2 ++ 2 files changed, 37 insertions(+) create mode 100644 kitty/cross-platform-random.h diff --git a/kitty/cross-platform-random.h b/kitty/cross-platform-random.h new file mode 100644 index 000000000..c877c57bd --- /dev/null +++ b/kitty/cross-platform-random.h @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2020 Kovid Goyal + * + * Distributed under terms of the GPL3 license. + */ + +#pragma once +#include +#include + +#if __linux__ +#include +#include + +static inline bool +secure_random_bytes(void *buf, size_t nbytes) { + unsigned char* p = buf; + ssize_t left = nbytes; + while(1) { + ssize_t n = getrandom(p, left, 0); + if (n >= left) return true; + if (n < 0) { + if (errno != EINTR) return false; // should never happen but if it does, we fail without any feedback + continue; + } + left -= n; p += n; + } +} +#else +static inline bool +secure_random_bytes(void *buf, size_t nbytes) { + arc4random_buf(buf, nbytes); + return true; +} +#endif diff --git a/kitty/disk-cache.c b/kitty/disk-cache.c index 901adc6ed..215139171 100644 --- a/kitty/disk-cache.c +++ b/kitty/disk-cache.c @@ -10,6 +10,7 @@ #include "disk-cache.h" #include "uthash.h" #include "loop-utils.h" +#include "cross-platform-random.h" #include #include #include @@ -186,6 +187,7 @@ add_to_disk_cache(PyObject *self_, const void *key, size_t key_sz, const uint8_t if (s == NULL) { s = calloc(1, sizeof(CacheEntry)); if (!s) { PyErr_NoMemory(); goto end; } + if (!secure_random_bytes(s->encryption_key, sizeof(s->encryption_key))) { free(s); PyErr_SetFromErrno(PyExc_OSError); goto end; } s->hash_key = malloc(key_sz); if (!s->hash_key) { free(s); PyErr_NoMemory(); goto end; } s->hash_keylen = key_sz;