crypto_misc.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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 void 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 */
  148. read(rng_fd, rand_data, num_rand_bytes); /* read from /dev/urandom */
  149. #elif defined(WIN32) && defined(CONFIG_WIN32_USE_CRYPTO_LIB)
  150. /* use Microsoft Crypto Libraries */
  151. CryptGenRandom(gCryptProv, num_rand_bytes, rand_data);
  152. #else /* nothing else to use, so use a custom RNG */
  153. /* The method we use when we've got nothing better. Use RC4, time
  154. and a couple of random seeds to generate a random sequence */
  155. RC4_CTX rng_ctx;
  156. struct timeval tv;
  157. MD5_CTX rng_digest_ctx;
  158. uint8_t digest[MD5_SIZE];
  159. uint64_t *ep;
  160. int i;
  161. /* A proper implementation would use counters etc for entropy */
  162. gettimeofday(&tv, NULL);
  163. ep = (uint64_t *)entropy_pool;
  164. ep[0] ^= ENTROPY_COUNTER1;
  165. ep[1] ^= ENTROPY_COUNTER2;
  166. /* use a digested version of the entropy pool as a key */
  167. MD5_Init(&rng_digest_ctx);
  168. MD5_Update(&rng_digest_ctx, entropy_pool, ENTROPY_POOL_SIZE);
  169. MD5_Final(digest, &rng_digest_ctx);
  170. /* come up with the random sequence */
  171. RC4_setup(&rng_ctx, digest, MD5_SIZE); /* use as a key */
  172. memcpy(rand_data, entropy_pool, num_rand_bytes < ENTROPY_POOL_SIZE ?
  173. num_rand_bytes : ENTROPY_POOL_SIZE);
  174. RC4_crypt(&rng_ctx, rand_data, rand_data, num_rand_bytes);
  175. /* move things along */
  176. for (i = ENTROPY_POOL_SIZE-1; i >= MD5_SIZE ; i--)
  177. entropy_pool[i] = entropy_pool[i-MD5_SIZE];
  178. /* insert the digest at the start of the entropy pool */
  179. memcpy(entropy_pool, digest, MD5_SIZE);
  180. #endif
  181. }
  182. /**
  183. * Set a series of bytes with a random number. Individual bytes are not zero.
  184. */
  185. void get_random_NZ(int num_rand_bytes, uint8_t *rand_data)
  186. {
  187. int i;
  188. get_random(num_rand_bytes, rand_data);
  189. for (i = 0; i < num_rand_bytes; i++)
  190. {
  191. while (rand_data[i] == 0) /* can't be 0 */
  192. rand_data[i] = (uint8_t)(rand());
  193. }
  194. }
  195. /**
  196. * Some useful diagnostic routines
  197. */
  198. #if defined(CONFIG_SSL_FULL_MODE) || defined(CONFIG_DEBUG)
  199. int hex_finish;
  200. int hex_index;
  201. static void print_hex_init(int finish)
  202. {
  203. hex_finish = finish;
  204. hex_index = 0;
  205. }
  206. static void print_hex(uint8_t hex)
  207. {
  208. static int column;
  209. if (hex_index == 0)
  210. {
  211. column = 0;
  212. }
  213. printf("%02x ", hex);
  214. if (++column == 8)
  215. {
  216. printf(": ");
  217. }
  218. else if (column >= 16)
  219. {
  220. printf("\n");
  221. column = 0;
  222. }
  223. if (++hex_index >= hex_finish && column > 0)
  224. {
  225. printf("\n");
  226. }
  227. }
  228. /**
  229. * Spit out a blob of data for diagnostics. The data is is a nice column format
  230. * for easy reading.
  231. *
  232. * @param format [in] The string (with possible embedded format characters)
  233. * @param size [in] The number of numbers to print
  234. * @param data [in] The start of data to use
  235. * @param ... [in] Any additional arguments
  236. */
  237. EXP_FUNC void STDCALL print_blob(const char *format,
  238. const uint8_t *data, int size, ...)
  239. {
  240. int i;
  241. char tmp[80];
  242. va_list(ap);
  243. va_start(ap, size);
  244. sprintf(tmp, "%s\n", format);
  245. vprintf(tmp, ap);
  246. print_hex_init(size);
  247. for (i = 0; i < size; i++)
  248. {
  249. print_hex(data[i]);
  250. }
  251. va_end(ap);
  252. TTY_FLUSH();
  253. }
  254. #elif defined(WIN32)
  255. /* VC6.0 doesn't handle variadic macros */
  256. EXP_FUNC void STDCALL print_blob(const char *format, const unsigned char *data,
  257. int size, ...) {}
  258. #endif
  259. #if defined(CONFIG_SSL_HAS_PEM) || defined(CONFIG_HTTP_HAS_AUTHORIZATION)
  260. /* base64 to binary lookup table */
  261. static const uint8_t map[128] =
  262. {
  263. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  264. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  265. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  266. 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63,
  267. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255,
  268. 255, 254, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6,
  269. 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
  270. 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255,
  271. 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
  272. 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
  273. 49, 50, 51, 255, 255, 255, 255, 255
  274. };
  275. EXP_FUNC int STDCALL base64_decode(const char *in, int len,
  276. uint8_t *out, int *outlen)
  277. {
  278. int g, t, x, y, z;
  279. uint8_t c;
  280. int ret = -1;
  281. g = 3;
  282. for (x = y = z = t = 0; x < len; x++)
  283. {
  284. if ((c = map[in[x]&0x7F]) == 0xff)
  285. continue;
  286. if (c == 254) /* this is the end... */
  287. {
  288. c = 0;
  289. if (--g < 0)
  290. goto error;
  291. }
  292. else if (g != 3) /* only allow = at end */
  293. goto error;
  294. t = (t<<6) | c;
  295. if (++y == 4)
  296. {
  297. out[z++] = (uint8_t)((t>>16)&255);
  298. if (g > 1)
  299. out[z++] = (uint8_t)((t>>8)&255);
  300. if (g > 2)
  301. out[z++] = (uint8_t)(t&255);
  302. y = t = 0;
  303. }
  304. /* check that we don't go past the output buffer */
  305. if (z > *outlen)
  306. goto error;
  307. }
  308. if (y != 0)
  309. goto error;
  310. *outlen = z;
  311. ret = 0;
  312. error:
  313. #ifdef CONFIG_SSL_FULL_MODE
  314. if (ret < 0)
  315. printf("Error: Invalid base64\n"); TTY_FLUSH();
  316. #endif
  317. TTY_FLUSH();
  318. return ret;
  319. }
  320. #endif