crypto_misc.c 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 "crypto_misc.h"
  38. #ifdef CONFIG_WIN32_USE_CRYPTO_LIB
  39. #include "wincrypt.h"
  40. #endif
  41. #ifndef WIN32
  42. static int rng_fd = -1;
  43. #elif defined(CONFIG_WIN32_USE_CRYPTO_LIB)
  44. static HCRYPTPROV gCryptProv;
  45. #endif
  46. #if (!defined(CONFIG_USE_DEV_URANDOM) && !defined(CONFIG_WIN32_USE_CRYPTO_LIB))
  47. static uint64_t rng_num;
  48. #endif
  49. static int rng_ref_count;
  50. const char * const unsupported_str = "Error: Feature not supported\n";
  51. #ifndef CONFIG_SSL_SKELETON_MODE
  52. /**
  53. * Retrieve a file and put it into memory
  54. * @return The size of the file, or -1 on failure.
  55. */
  56. int get_file(const char *filename, uint8_t **buf)
  57. {
  58. int total_bytes = 0;
  59. int bytes_read = 0;
  60. int filesize;
  61. FILE *stream = fopen(filename, "rb");
  62. if (stream == NULL)
  63. {
  64. #ifdef CONFIG_SSL_FULL_MODE
  65. printf("file '%s' does not exist\n", filename); TTY_FLUSH();
  66. #endif
  67. return -1;
  68. }
  69. /* Win CE doesn't support stat() */
  70. fseek(stream, 0, SEEK_END);
  71. filesize = ftell(stream);
  72. *buf = (uint8_t *)malloc(filesize);
  73. fseek(stream, 0, SEEK_SET);
  74. do
  75. {
  76. bytes_read = fread(*buf+total_bytes, 1, filesize-total_bytes, stream);
  77. total_bytes += bytes_read;
  78. } while (total_bytes < filesize && bytes_read > 0);
  79. fclose(stream);
  80. return filesize;
  81. }
  82. #endif
  83. /**
  84. * Initialise the Random Number Generator engine.
  85. * - On Win32 use the platform SDK's crypto engine.
  86. * - On Linux use /dev/urandom
  87. * - If none of these work then use a custom RNG.
  88. */
  89. EXP_FUNC void STDCALL RNG_initialize(const uint8_t *seed_buf, int size)
  90. {
  91. if (rng_ref_count == 0)
  92. {
  93. #if !defined(WIN32) && defined(CONFIG_USE_DEV_URANDOM)
  94. rng_fd = ax_open("/dev/urandom", O_RDONLY);
  95. #elif defined(WIN32) && defined(CONFIG_WIN32_USE_CRYPTO_LIB)
  96. if (!CryptAcquireContext(&gCryptProv,
  97. NULL, NULL, PROV_RSA_FULL, 0))
  98. {
  99. if (GetLastError() == NTE_BAD_KEYSET &&
  100. !CryptAcquireContext(&gCryptProv,
  101. NULL,
  102. NULL,
  103. PROV_RSA_FULL,
  104. CRYPT_NEWKEYSET))
  105. {
  106. printf("CryptoLib: %x\n", unsupported_str, GetLastError());
  107. exit(1);
  108. }
  109. }
  110. #else
  111. /* help seed with the user's private key - this is a number that
  112. should be hard to find, due to the fact that it relies on knowing
  113. the private key */
  114. int i;
  115. for (i = 0; i < size/(int)sizeof(uint64_t); i++)
  116. rng_num ^= *((uint64_t *)&seed_buf[i*sizeof(uint64_t)]);
  117. srand((long)&seed_buf); /* use the stack ptr as another rnd seed */
  118. #endif
  119. }
  120. rng_ref_count++;
  121. }
  122. /**
  123. * Terminate the RNG engine.
  124. */
  125. EXP_FUNC void STDCALL RNG_terminate(void)
  126. {
  127. if (--rng_ref_count == 0)
  128. {
  129. #ifndef WIN32
  130. close(rng_fd);
  131. #elif defined(CONFIG_WIN32_USE_CRYPTO_LIB)
  132. CryptReleaseContext(gCryptProv, 0);
  133. #endif
  134. }
  135. }
  136. /**
  137. * Set a series of bytes with a random number. Individual bytes can be 0
  138. */
  139. EXP_FUNC void STDCALL get_random(int num_rand_bytes, uint8_t *rand_data)
  140. {
  141. #if !defined(WIN32) && defined(CONFIG_USE_DEV_URANDOM)
  142. /* use the Linux default */
  143. read(rng_fd, rand_data, num_rand_bytes); /* read from /dev/urandom */
  144. #elif defined(WIN32) && defined(CONFIG_WIN32_USE_CRYPTO_LIB)
  145. /* use Microsoft Crypto Libraries */
  146. CryptGenRandom(gCryptProv, num_rand_bytes, rand_data);
  147. #else /* nothing else to use, so use a custom RNG */
  148. /* The method we use when we've got nothing better. Use RC4, time
  149. and a couple of random seeds to generate a random sequence */
  150. RC4_CTX rng_ctx;
  151. struct timeval tv;
  152. uint64_t big_num1, big_num2;
  153. gettimeofday(&tv, NULL); /* yes I know we shouldn't do this */
  154. /* all numbers by themselves are pretty simple, but combined should
  155. * be a challenge */
  156. big_num1 = (uint64_t)tv.tv_sec*(tv.tv_usec+1);
  157. big_num2 = (uint64_t)rand()*big_num1;
  158. big_num1 ^= rng_num;
  159. memcpy(rand_data, &big_num1, sizeof(uint64_t));
  160. if (num_rand_bytes > sizeof(uint64_t))
  161. memcpy(&rand_data[8], &big_num2, sizeof(uint64_t));
  162. if (num_rand_bytes > 16)
  163. {
  164. /* clear rest of data */
  165. memset(&rand_data[16], 0, num_rand_bytes-16);
  166. }
  167. RC4_setup(&rng_ctx, rand_data, 16); /* use as a key */
  168. RC4_crypt(&rng_ctx, rand_data, rand_data, num_rand_bytes);
  169. /* use last 8 bytes for next time */
  170. memcpy(&rng_num, &rand_data[num_rand_bytes-8], sizeof(uint64_t));
  171. #endif
  172. }
  173. /**
  174. * Set a series of bytes with a random number. Individual bytes are not zero.
  175. */
  176. void get_random_NZ(int num_rand_bytes, uint8_t *rand_data)
  177. {
  178. int i;
  179. get_random(num_rand_bytes, rand_data);
  180. for (i = 0; i < num_rand_bytes; i++)
  181. {
  182. while (rand_data[i] == 0) /* can't be 0 */
  183. rand_data[i] = (uint8_t)(rand());
  184. }
  185. }
  186. /**
  187. * Some useful diagnostic routines
  188. */
  189. #if defined(CONFIG_SSL_FULL_MODE) || defined(CONFIG_DEBUG)
  190. int hex_finish;
  191. int hex_index;
  192. static void print_hex_init(int finish)
  193. {
  194. hex_finish = finish;
  195. hex_index = 0;
  196. }
  197. static void print_hex(uint8_t hex)
  198. {
  199. static int column;
  200. if (hex_index == 0)
  201. {
  202. column = 0;
  203. }
  204. printf("%02x ", hex);
  205. if (++column == 8)
  206. {
  207. printf(": ");
  208. }
  209. else if (column >= 16)
  210. {
  211. printf("\n");
  212. column = 0;
  213. }
  214. if (++hex_index >= hex_finish && column > 0)
  215. {
  216. printf("\n");
  217. }
  218. }
  219. /**
  220. * Spit out a blob of data for diagnostics. The data is is a nice column format
  221. * for easy reading.
  222. *
  223. * @param format [in] The string (with possible embedded format characters)
  224. * @param size [in] The number of numbers to print
  225. * @param data [in] The start of data to use
  226. * @param ... [in] Any additional arguments
  227. */
  228. EXP_FUNC void STDCALL print_blob(const char *format,
  229. const uint8_t *data, int size, ...)
  230. {
  231. int i;
  232. char tmp[80];
  233. va_list(ap);
  234. va_start(ap, size);
  235. sprintf(tmp, "%s\n", format);
  236. vprintf(tmp, ap);
  237. print_hex_init(size);
  238. for (i = 0; i < size; i++)
  239. {
  240. print_hex(data[i]);
  241. }
  242. va_end(ap);
  243. TTY_FLUSH();
  244. }
  245. #elif defined(WIN32)
  246. /* VC6.0 doesn't handle variadic macros */
  247. EXP_FUNC void STDCALL print_blob(const char *format, const unsigned char *data,
  248. int size, ...) {}
  249. #endif
  250. #if defined(CONFIG_SSL_HAS_PEM) || defined(CONFIG_HTTP_HAS_AUTHORIZATION)
  251. /* base64 to binary lookup table */
  252. static const uint8_t map[128] =
  253. {
  254. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  255. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  256. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  257. 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63,
  258. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255,
  259. 255, 254, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6,
  260. 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
  261. 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255,
  262. 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
  263. 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
  264. 49, 50, 51, 255, 255, 255, 255, 255
  265. };
  266. EXP_FUNC int STDCALL base64_decode(const char *in, int len,
  267. uint8_t *out, int *outlen)
  268. {
  269. int g, t, x, y, z;
  270. uint8_t c;
  271. int ret = -1;
  272. g = 3;
  273. for (x = y = z = t = 0; x < len; x++)
  274. {
  275. if ((c = map[in[x]&0x7F]) == 0xff)
  276. continue;
  277. if (c == 254) /* this is the end... */
  278. {
  279. c = 0;
  280. if (--g < 0)
  281. goto error;
  282. }
  283. else if (g != 3) /* only allow = at end */
  284. goto error;
  285. t = (t<<6) | c;
  286. if (++y == 4)
  287. {
  288. out[z++] = (uint8_t)((t>>16)&255);
  289. if (g > 1)
  290. out[z++] = (uint8_t)((t>>8)&255);
  291. if (g > 2)
  292. out[z++] = (uint8_t)(t&255);
  293. y = t = 0;
  294. }
  295. }
  296. if (y != 0)
  297. goto error;
  298. if (outlen)
  299. *outlen = z;
  300. ret = 0;
  301. error:
  302. #ifdef CONFIG_SSL_FULL_MODE
  303. if (ret < 0)
  304. printf("Error: Invalid base64\n"); TTY_FLUSH();
  305. #endif
  306. TTY_FLUSH();
  307. return ret;
  308. }
  309. #endif