]>
git.ipfire.org Git - thirdparty/pdns.git/blob - pdns/dns_random.cc
2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of version 2 of the GNU General Public License as
7 * published by the Free Software Foundation.
9 * In addition, for the avoidance of any doubt, permission is granted to
10 * link this program with OpenSSL and to (re)distribute the binaries
11 * produced as the result of such linking.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include <openssl/aes.h>
26 #include <openssl/opensslv.h>
27 #if OPENSSL_VERSION_NUMBER > 0x1010000fL && !defined LIBRESSL_VERSION_NUMBER
28 // Older OpenSSL does not have CRYPTO_ctr128_encrypt. Before 1.1.0 the header
29 // file did not have the necessary extern "C" wrapper. In 1.1.0, AES_ctr128_encrypt
31 #include <openssl/modes.h>
36 #include <sys/types.h>
42 #include "dns_random.hh"
46 static AES_KEY aes_key
;
47 static unsigned int g_offset
;
48 static unsigned char g_counter
[16], g_stream
[16];
51 static bool g_initialized
;
53 void dns_random_init(const char data
[16])
56 memset(&g_stream
, 0, sizeof(g_stream
));
57 if (AES_set_encrypt_key((const unsigned char*)data
, 128, &aes_key
) < 0) {
58 throw std::runtime_error("AES_set_encrypt_key failed");
62 gettimeofday(&now
, 0);
64 static_assert(sizeof(g_counter
) >= (sizeof(now
.tv_usec
) + sizeof(now
.tv_sec
)), "g_counter must be large enough to get tv_sec + tv_usec");
65 memcpy(g_counter
, &now
.tv_usec
, sizeof(now
.tv_usec
));
66 memcpy(g_counter
+sizeof(now
.tv_usec
), &now
.tv_sec
, sizeof(now
.tv_sec
));
67 g_in
= getpid() | (getppid()<<16);
70 srandom(dns_random(numeric_limits
<uint32_t>::max()));
73 unsigned int dns_random(unsigned int n
)
78 #if OPENSSL_VERSION_NUMBER > 0x1010000fL && !defined LIBRESSL_VERSION_NUMBER
79 CRYPTO_ctr128_encrypt((const unsigned char*)&g_in
, (unsigned char*) &out
, sizeof(g_in
), &aes_key
, g_counter
, g_stream
, &g_offset
, (block128_f
) AES_encrypt
);
81 AES_ctr128_encrypt((const unsigned char*)&g_in
, (unsigned char*) &out
, sizeof(g_in
), &aes_key
, g_counter
, g_stream
, &g_offset
);
89 dns_random_init("0123456789abcdef");
91 for(int n
= 0; n
< 16; n
++)
92 cerr
<<dns_random(16384)<<endl
;