crypto_misc.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. /*
  2. * Copyright (c) 2007, Cameron Rich
  3. *
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * * Redistributions of source code must retain the above copyright notice,
  10. * this list of conditions and the following disclaimer.
  11. * * Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. * * Neither the name of the axTLS project nor the names of its contributors
  15. * may be used to endorse or promote products derived from this software
  16. * without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  22. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  23. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  24. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  25. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  26. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  27. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  28. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. /**
  31. * Some misc. routines to help things out
  32. */
  33. #include <stdlib.h>
  34. #include <string.h>
  35. #include <stdarg.h>
  36. #include <stdio.h>
  37. #include "os_port.h"
  38. #include "crypto_misc.h"
  39. #ifdef CONFIG_WIN32_USE_CRYPTO_LIB
  40. #include "wincrypt.h"
  41. #endif
  42. #ifndef WIN32
  43. static int rng_fd = -1;
  44. #elif defined(CONFIG_WIN32_USE_CRYPTO_LIB)
  45. static HCRYPTPROV gCryptProv;
  46. #endif
  47. #if (!defined(CONFIG_USE_DEV_URANDOM) && !defined(CONFIG_WIN32_USE_CRYPTO_LIB))
  48. /* change to processor registers as appropriate */
  49. #define ENTROPY_POOL_SIZE 32
  50. #define ENTROPY_COUNTER1 ((((uint64_t)tv.tv_sec)<<32) | tv.tv_usec)
  51. #define ENTROPY_COUNTER2 rand()
  52. static uint8_t entropy_pool[ENTROPY_POOL_SIZE];
  53. #endif
  54. const char * const unsupported_str = "Error: Feature not supported\n";
  55. #ifndef CONFIG_SSL_SKELETON_MODE
  56. /**
  57. * Retrieve a file and put it into memory
  58. * @return The size of the file, or -1 on failure.
  59. */
  60. int get_file(const char *filename, uint8_t **buf)
  61. {
  62. int total_bytes = 0;
  63. int bytes_read = 0;
  64. int filesize;
  65. FILE *stream = fopen(filename, "rb");
  66. if (stream == NULL)
  67. {
  68. #ifdef CONFIG_SSL_FULL_MODE
  69. printf("file '%s' does not exist\n", filename); TTY_FLUSH();
  70. #endif
  71. return -1;
  72. }
  73. /* Win CE doesn't support stat() */
  74. fseek(stream, 0, SEEK_END);
  75. filesize = ftell(stream);
  76. *buf = (uint8_t *)malloc(filesize);
  77. fseek(stream, 0, SEEK_SET);
  78. do
  79. {
  80. bytes_read = fread(*buf+total_bytes, 1, filesize-total_bytes, stream);
  81. total_bytes += bytes_read;
  82. } while (total_bytes < filesize && bytes_read > 0);
  83. fclose(stream);
  84. return filesize;
  85. }
  86. #endif
  87. /**
  88. * Initialise the Random Number Generator engine.
  89. * - On Win32 use the platform SDK's crypto engine.
  90. * - On Linux use /dev/urandom
  91. * - If none of these work then use a custom RNG.
  92. */
  93. EXP_FUNC void STDCALL RNG_initialize()
  94. {
  95. #if !defined(WIN32) && defined(CONFIG_USE_DEV_URANDOM)
  96. rng_fd = ax_open("/dev/urandom", O_RDONLY);
  97. #elif defined(WIN32) && defined(CONFIG_WIN32_USE_CRYPTO_LIB)
  98. if (!CryptAcquireContext(&gCryptProv,
  99. NULL, NULL, PROV_RSA_FULL, 0))
  100. {
  101. if (GetLastError() == NTE_BAD_KEYSET &&
  102. !CryptAcquireContext(&gCryptProv,
  103. NULL,
  104. NULL,
  105. PROV_RSA_FULL,
  106. CRYPT_NEWKEYSET))
  107. {
  108. printf("CryptoLib: %x\n", unsupported_str, GetLastError());
  109. exit(1);
  110. }
  111. }
  112. #else
  113. /* start of with a stack to copy across */
  114. int i;
  115. memcpy(entropy_pool, &i, ENTROPY_POOL_SIZE);
  116. srand((unsigned int)&i);
  117. #endif
  118. }
  119. /**
  120. * If no /dev/urandom, then initialise the RNG with something interesting.
  121. */
  122. EXP_FUNC void STDCALL RNG_custom_init(const uint8_t *seed_buf, int size)
  123. {
  124. #if defined(WIN32) || defined(CONFIG_WIN32_USE_CRYPTO_LIB)
  125. int i;
  126. for (i = 0; i < ENTROPY_POOL_SIZE && i < size; i++)
  127. entropy_pool[i] ^= seed_buf[i];
  128. #endif
  129. }
  130. /**
  131. * Terminate the RNG engine.
  132. */
  133. EXP_FUNC void STDCALL RNG_terminate(void)
  134. {
  135. #ifndef WIN32
  136. close(rng_fd);
  137. #elif defined(CONFIG_WIN32_USE_CRYPTO_LIB)
  138. CryptReleaseContext(gCryptProv, 0);
  139. #endif
  140. }
  141. /**
  142. * Set a series of bytes with a random number. Individual bytes can be 0
  143. */
  144. EXP_FUNC int STDCALL get_random(int num_rand_bytes, uint8_t *rand_data)
  145. {
  146. #if !defined(WIN32) && defined(CONFIG_USE_DEV_URANDOM)
  147. /* use the Linux default - read from /dev/urandom */
  148. if (read(rng_fd, rand_data, num_rand_bytes) < 0)
  149. return -1;
  150. #elif defined(WIN32) && defined(CONFIG_WIN32_USE_CRYPTO_LIB)
  151. /* use Microsoft Crypto Libraries */
  152. CryptGenRandom(gCryptProv, num_rand_bytes, rand_data);
  153. #else /* nothing else to use, so use a custom RNG */
  154. /* The method we use when we've got nothing better. Use RC4, time
  155. and a couple of random seeds to generate a random sequence */
  156. RC4_CTX rng_ctx;
  157. struct timeval tv;
  158. MD5_CTX rng_digest_ctx;
  159. uint8_t digest[MD5_SIZE];
  160. uint64_t *ep;
  161. int i;
  162. /* A proper implementation would use counters etc for entropy */
  163. gettimeofday(&tv, NULL);
  164. ep = (uint64_t *)entropy_pool;
  165. ep[0] ^= ENTROPY_COUNTER1;
  166. ep[1] ^= ENTROPY_COUNTER2;
  167. /* use a digested version of the entropy pool as a key */
  168. MD5_Init(&rng_digest_ctx);
  169. MD5_Update(&rng_digest_ctx, entropy_pool, ENTROPY_POOL_SIZE);
  170. MD5_Final(digest, &rng_digest_ctx);
  171. /* come up with the random sequence */
  172. RC4_setup(&rng_ctx, digest, MD5_SIZE); /* use as a key */
  173. memcpy(rand_data, entropy_pool, num_rand_bytes < ENTROPY_POOL_SIZE ?
  174. num_rand_bytes : ENTROPY_POOL_SIZE);
  175. RC4_crypt(&rng_ctx, rand_data, rand_data, num_rand_bytes);
  176. /* move things along */
  177. for (i = ENTROPY_POOL_SIZE-1; i >= MD5_SIZE ; i--)
  178. entropy_pool[i] = entropy_pool[i-MD5_SIZE];
  179. /* insert the digest at the start of the entropy pool */
  180. memcpy(entropy_pool, digest, MD5_SIZE);
  181. #endif
  182. return 0;
  183. }
  184. /**
  185. * Set a series of bytes with a random number. Individual bytes are not zero.
  186. */
  187. int get_random_NZ(int num_rand_bytes, uint8_t *rand_data)
  188. {
  189. int i;
  190. if (get_random(num_rand_bytes, rand_data))
  191. return -1;
  192. for (i = 0; i < num_rand_bytes; i++)
  193. {
  194. while (rand_data[i] == 0) /* can't be 0 */
  195. rand_data[i] = (uint8_t)(rand());
  196. }
  197. return 0;
  198. }
  199. /**
  200. * Some useful diagnostic routines
  201. */
  202. #if defined(CONFIG_SSL_FULL_MODE) || defined(CONFIG_DEBUG)
  203. int hex_finish;
  204. int hex_index;
  205. static void print_hex_init(int finish)
  206. {
  207. hex_finish = finish;
  208. hex_index = 0;
  209. }
  210. static void print_hex(uint8_t hex)
  211. {
  212. static int column;
  213. if (hex_index == 0)
  214. {
  215. column = 0;
  216. }
  217. printf("%02x ", hex);
  218. if (++column == 8)
  219. {
  220. printf(": ");
  221. }
  222. else if (column >= 16)
  223. {
  224. printf("\n");
  225. column = 0;
  226. }
  227. if (++hex_index >= hex_finish && column > 0)
  228. {
  229. printf("\n");
  230. }
  231. }
  232. /**
  233. * Spit out a blob of data for diagnostics. The data is is a nice column format
  234. * for easy reading.
  235. *
  236. * @param format [in] The string (with possible embedded format characters)
  237. * @param size [in] The number of numbers to print
  238. * @param data [in] The start of data to use
  239. * @param ... [in] Any additional arguments
  240. */
  241. EXP_FUNC void STDCALL print_blob(const char *format,
  242. const uint8_t *data, int size, ...)
  243. {
  244. int i;
  245. char tmp[80];
  246. va_list(ap);
  247. va_start(ap, size);
  248. sprintf(tmp, "%s\n", format);
  249. vprintf(tmp, ap);
  250. print_hex_init(size);
  251. for (i = 0; i < size; i++)
  252. {
  253. print_hex(data[i]);
  254. }
  255. va_end(ap);
  256. TTY_FLUSH();
  257. }
  258. #elif defined(WIN32)
  259. /* VC6.0 doesn't handle variadic macros */
  260. EXP_FUNC void STDCALL print_blob(const char *format, const unsigned char *data,
  261. int size, ...) {}
  262. #endif
  263. #if defined(CONFIG_SSL_HAS_PEM) || defined(CONFIG_HTTP_HAS_AUTHORIZATION)
  264. /* base64 to binary lookup table */
  265. static const uint8_t map[128] =
  266. {
  267. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  268. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  269. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  270. 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63,
  271. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255,
  272. 255, 254, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6,
  273. 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
  274. 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255,
  275. 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
  276. 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
  277. 49, 50, 51, 255, 255, 255, 255, 255
  278. };
  279. EXP_FUNC int STDCALL base64_decode(const char *in, int len,
  280. uint8_t *out, int *outlen)
  281. {
  282. int g, t, x, y, z;
  283. uint8_t c;
  284. int ret = -1;
  285. g = 3;
  286. for (x = y = z = t = 0; x < len; x++)
  287. {
  288. if ((c = map[in[x]&0x7F]) == 0xff)
  289. continue;
  290. if (c == 254) /* this is the end... */
  291. {
  292. c = 0;
  293. if (--g < 0)
  294. goto error;
  295. }
  296. else if (g != 3) /* only allow = at end */
  297. goto error;
  298. t = (t<<6) | c;
  299. if (++y == 4)
  300. {
  301. out[z++] = (uint8_t)((t>>16)&255);
  302. if (g > 1)
  303. out[z++] = (uint8_t)((t>>8)&255);
  304. if (g > 2)
  305. out[z++] = (uint8_t)(t&255);
  306. y = t = 0;
  307. }
  308. /* check that we don't go past the output buffer */
  309. if (z > *outlen)
  310. goto error;
  311. }
  312. if (y != 0)
  313. goto error;
  314. *outlen = z;
  315. ret = 0;
  316. error:
  317. #ifdef CONFIG_SSL_FULL_MODE
  318. if (ret < 0)
  319. printf("Error: Invalid base64\n"); TTY_FLUSH();
  320. #endif
  321. TTY_FLUSH();
  322. return ret;
  323. }
  324. #endif