You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

467 regels
13 KiB

  1. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  2. * All rights reserved.
  3. *
  4. * This package is an SSL implementation written
  5. * by Eric Young (eay@cryptsoft.com).
  6. * The implementation was written so as to conform with Netscapes SSL.
  7. *
  8. * This library is free for commercial and non-commercial use as long as
  9. * the following conditions are aheared to. The following conditions
  10. * apply to all code found in this distribution, be it the RC4, RSA,
  11. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  12. * included with this distribution is covered by the same copyright terms
  13. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  14. *
  15. * Copyright remains Eric Young's, and as such any Copyright notices in
  16. * the code are not to be removed.
  17. * If this package is used in a product, Eric Young should be given attribution
  18. * as the author of the parts of the library used.
  19. * This can be in the form of a textual message at program startup or
  20. * in documentation (online or textual) provided with the package.
  21. *
  22. * Redistribution and use in source and binary forms, with or without
  23. * modification, are permitted provided that the following conditions
  24. * are met:
  25. * 1. Redistributions of source code must retain the copyright
  26. * notice, this list of conditions and the following disclaimer.
  27. * 2. Redistributions in binary form must reproduce the above copyright
  28. * notice, this list of conditions and the following disclaimer in the
  29. * documentation and/or other materials provided with the distribution.
  30. * 3. All advertising materials mentioning features or use of this software
  31. * must display the following acknowledgement:
  32. * "This product includes cryptographic software written by
  33. * Eric Young (eay@cryptsoft.com)"
  34. * The word 'cryptographic' can be left out if the rouines from the library
  35. * being used are not cryptographic related :-).
  36. * 4. If you include any Windows specific code (or a derivative thereof) from
  37. * the apps directory (application code) you must include an acknowledgement:
  38. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  39. *
  40. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  41. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  42. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  43. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  44. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  45. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  46. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  47. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  48. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  49. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  50. * SUCH DAMAGE.
  51. *
  52. * The licence and distribution terms for any publically available version or
  53. * derivative of this code cannot be changed. i.e. this code cannot simply be
  54. * copied and put under another distribution licence
  55. * [including the GNU Public Licence.] */
  56. #include <openssl/base64.h>
  57. #include <assert.h>
  58. #include <limits.h>
  59. #include <string.h>
  60. #include <openssl/type_check.h>
  61. #include "../internal.h"
  62. // constant_time_lt_args_8 behaves like |constant_time_lt_8| but takes |uint8_t|
  63. // arguments for a slightly simpler implementation.
  64. static inline uint8_t constant_time_lt_args_8(uint8_t a, uint8_t b) {
  65. crypto_word_t aw = a;
  66. crypto_word_t bw = b;
  67. // |crypto_word_t| is larger than |uint8_t|, so |aw| and |bw| have the same
  68. // MSB. |aw| < |bw| iff MSB(|aw| - |bw|) is 1.
  69. return constant_time_msb_w(aw - bw);
  70. }
  71. // constant_time_in_range_8 returns |CONSTTIME_TRUE_8| if |min| <= |a| <= |max|
  72. // and |CONSTTIME_FALSE_8| otherwise.
  73. static inline uint8_t constant_time_in_range_8(uint8_t a, uint8_t min,
  74. uint8_t max) {
  75. a -= min;
  76. return constant_time_lt_args_8(a, max - min + 1);
  77. }
  78. // Encoding.
  79. static uint8_t conv_bin2ascii(uint8_t a) {
  80. // Since PEM is sometimes used to carry private keys, we encode base64 data
  81. // itself in constant-time.
  82. a &= 0x3f;
  83. uint8_t ret = constant_time_select_8(constant_time_eq_8(a, 62), '+', '/');
  84. ret =
  85. constant_time_select_8(constant_time_lt_args_8(a, 62), a - 52 + '0', ret);
  86. ret =
  87. constant_time_select_8(constant_time_lt_args_8(a, 52), a - 26 + 'a', ret);
  88. ret = constant_time_select_8(constant_time_lt_args_8(a, 26), a + 'A', ret);
  89. return ret;
  90. }
  91. OPENSSL_COMPILE_ASSERT(sizeof(((EVP_ENCODE_CTX *)(NULL))->data) % 3 == 0,
  92. data_length_must_be_multiple_of_base64_chunk_size);
  93. int EVP_EncodedLength(size_t *out_len, size_t len) {
  94. if (len + 2 < len) {
  95. return 0;
  96. }
  97. len += 2;
  98. len /= 3;
  99. if (((len << 2) >> 2) != len) {
  100. return 0;
  101. }
  102. len <<= 2;
  103. if (len + 1 < len) {
  104. return 0;
  105. }
  106. len++;
  107. *out_len = len;
  108. return 1;
  109. }
  110. void EVP_EncodeInit(EVP_ENCODE_CTX *ctx) {
  111. OPENSSL_memset(ctx, 0, sizeof(EVP_ENCODE_CTX));
  112. }
  113. void EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx, uint8_t *out, int *out_len,
  114. const uint8_t *in, size_t in_len) {
  115. size_t total = 0;
  116. *out_len = 0;
  117. if (in_len == 0) {
  118. return;
  119. }
  120. assert(ctx->data_used < sizeof(ctx->data));
  121. if (sizeof(ctx->data) - ctx->data_used > in_len) {
  122. OPENSSL_memcpy(&ctx->data[ctx->data_used], in, in_len);
  123. ctx->data_used += (unsigned)in_len;
  124. return;
  125. }
  126. if (ctx->data_used != 0) {
  127. const size_t todo = sizeof(ctx->data) - ctx->data_used;
  128. OPENSSL_memcpy(&ctx->data[ctx->data_used], in, todo);
  129. in += todo;
  130. in_len -= todo;
  131. size_t encoded = EVP_EncodeBlock(out, ctx->data, sizeof(ctx->data));
  132. ctx->data_used = 0;
  133. out += encoded;
  134. *(out++) = '\n';
  135. *out = '\0';
  136. total = encoded + 1;
  137. }
  138. while (in_len >= sizeof(ctx->data)) {
  139. size_t encoded = EVP_EncodeBlock(out, in, sizeof(ctx->data));
  140. in += sizeof(ctx->data);
  141. in_len -= sizeof(ctx->data);
  142. out += encoded;
  143. *(out++) = '\n';
  144. *out = '\0';
  145. if (total + encoded + 1 < total) {
  146. *out_len = 0;
  147. return;
  148. }
  149. total += encoded + 1;
  150. }
  151. if (in_len != 0) {
  152. OPENSSL_memcpy(ctx->data, in, in_len);
  153. }
  154. ctx->data_used = (unsigned)in_len;
  155. if (total > INT_MAX) {
  156. // We cannot signal an error, but we can at least avoid making *out_len
  157. // negative.
  158. total = 0;
  159. }
  160. *out_len = (int)total;
  161. }
  162. void EVP_EncodeFinal(EVP_ENCODE_CTX *ctx, uint8_t *out, int *out_len) {
  163. if (ctx->data_used == 0) {
  164. *out_len = 0;
  165. return;
  166. }
  167. size_t encoded = EVP_EncodeBlock(out, ctx->data, ctx->data_used);
  168. out[encoded++] = '\n';
  169. out[encoded] = '\0';
  170. ctx->data_used = 0;
  171. // ctx->data_used is bounded by sizeof(ctx->data), so this does not
  172. // overflow.
  173. assert(encoded <= INT_MAX);
  174. *out_len = (int)encoded;
  175. }
  176. size_t EVP_EncodeBlock(uint8_t *dst, const uint8_t *src, size_t src_len) {
  177. uint32_t l;
  178. size_t remaining = src_len, ret = 0;
  179. while (remaining) {
  180. if (remaining >= 3) {
  181. l = (((uint32_t)src[0]) << 16L) | (((uint32_t)src[1]) << 8L) | src[2];
  182. *(dst++) = conv_bin2ascii(l >> 18L);
  183. *(dst++) = conv_bin2ascii(l >> 12L);
  184. *(dst++) = conv_bin2ascii(l >> 6L);
  185. *(dst++) = conv_bin2ascii(l);
  186. remaining -= 3;
  187. } else {
  188. l = ((uint32_t)src[0]) << 16L;
  189. if (remaining == 2) {
  190. l |= ((uint32_t)src[1] << 8L);
  191. }
  192. *(dst++) = conv_bin2ascii(l >> 18L);
  193. *(dst++) = conv_bin2ascii(l >> 12L);
  194. *(dst++) = (remaining == 1) ? '=' : conv_bin2ascii(l >> 6L);
  195. *(dst++) = '=';
  196. remaining = 0;
  197. }
  198. ret += 4;
  199. src += 3;
  200. }
  201. *dst = '\0';
  202. return ret;
  203. }
  204. // Decoding.
  205. int EVP_DecodedLength(size_t *out_len, size_t len) {
  206. if (len % 4 != 0) {
  207. return 0;
  208. }
  209. *out_len = (len / 4) * 3;
  210. return 1;
  211. }
  212. void EVP_DecodeInit(EVP_ENCODE_CTX *ctx) {
  213. OPENSSL_memset(ctx, 0, sizeof(EVP_ENCODE_CTX));
  214. }
  215. static uint8_t base64_ascii_to_bin(uint8_t a) {
  216. // Since PEM is sometimes used to carry private keys, we decode base64 data
  217. // itself in constant-time.
  218. const uint8_t is_upper = constant_time_in_range_8(a, 'A', 'Z');
  219. const uint8_t is_lower = constant_time_in_range_8(a, 'a', 'z');
  220. const uint8_t is_digit = constant_time_in_range_8(a, '0', '9');
  221. const uint8_t is_plus = constant_time_eq_8(a, '+');
  222. const uint8_t is_slash = constant_time_eq_8(a, '/');
  223. const uint8_t is_equals = constant_time_eq_8(a, '=');
  224. uint8_t ret = 0xff; // 0xff signals invalid.
  225. ret = constant_time_select_8(is_upper, a - 'A', ret); // [0,26)
  226. ret = constant_time_select_8(is_lower, a - 'a' + 26, ret); // [26,52)
  227. ret = constant_time_select_8(is_digit, a - '0' + 52, ret); // [52,62)
  228. ret = constant_time_select_8(is_plus, 62, ret);
  229. ret = constant_time_select_8(is_slash, 63, ret);
  230. // Padding maps to zero, to be further handled by the caller.
  231. ret = constant_time_select_8(is_equals, 0, ret);
  232. return ret;
  233. }
  234. // base64_decode_quad decodes a single “quad” (i.e. four characters) of base64
  235. // data and writes up to three bytes to |out|. It sets |*out_num_bytes| to the
  236. // number of bytes written, which will be less than three if the quad ended
  237. // with padding. It returns one on success or zero on error.
  238. static int base64_decode_quad(uint8_t *out, size_t *out_num_bytes,
  239. const uint8_t *in) {
  240. const uint8_t a = base64_ascii_to_bin(in[0]);
  241. const uint8_t b = base64_ascii_to_bin(in[1]);
  242. const uint8_t c = base64_ascii_to_bin(in[2]);
  243. const uint8_t d = base64_ascii_to_bin(in[3]);
  244. if (a == 0xff || b == 0xff || c == 0xff || d == 0xff) {
  245. return 0;
  246. }
  247. const uint32_t v = ((uint32_t)a) << 18 | ((uint32_t)b) << 12 |
  248. ((uint32_t)c) << 6 | (uint32_t)d;
  249. const unsigned padding_pattern = (in[0] == '=') << 3 |
  250. (in[1] == '=') << 2 |
  251. (in[2] == '=') << 1 |
  252. (in[3] == '=');
  253. switch (padding_pattern) {
  254. case 0:
  255. // The common case of no padding.
  256. *out_num_bytes = 3;
  257. out[0] = v >> 16;
  258. out[1] = v >> 8;
  259. out[2] = v;
  260. break;
  261. case 1: // xxx=
  262. *out_num_bytes = 2;
  263. out[0] = v >> 16;
  264. out[1] = v >> 8;
  265. break;
  266. case 3: // xx==
  267. *out_num_bytes = 1;
  268. out[0] = v >> 16;
  269. break;
  270. default:
  271. return 0;
  272. }
  273. return 1;
  274. }
  275. int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx, uint8_t *out, int *out_len,
  276. const uint8_t *in, size_t in_len) {
  277. *out_len = 0;
  278. if (ctx->error_encountered) {
  279. return -1;
  280. }
  281. size_t bytes_out = 0, i;
  282. for (i = 0; i < in_len; i++) {
  283. const char c = in[i];
  284. switch (c) {
  285. case ' ':
  286. case '\t':
  287. case '\r':
  288. case '\n':
  289. continue;
  290. }
  291. if (ctx->eof_seen) {
  292. ctx->error_encountered = 1;
  293. return -1;
  294. }
  295. ctx->data[ctx->data_used++] = c;
  296. if (ctx->data_used == 4) {
  297. size_t num_bytes_resulting;
  298. if (!base64_decode_quad(out, &num_bytes_resulting, ctx->data)) {
  299. ctx->error_encountered = 1;
  300. return -1;
  301. }
  302. ctx->data_used = 0;
  303. bytes_out += num_bytes_resulting;
  304. out += num_bytes_resulting;
  305. if (num_bytes_resulting < 3) {
  306. ctx->eof_seen = 1;
  307. }
  308. }
  309. }
  310. if (bytes_out > INT_MAX) {
  311. ctx->error_encountered = 1;
  312. *out_len = 0;
  313. return -1;
  314. }
  315. *out_len = (int)bytes_out;
  316. if (ctx->eof_seen) {
  317. return 0;
  318. }
  319. return 1;
  320. }
  321. int EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, uint8_t *out, int *out_len) {
  322. *out_len = 0;
  323. if (ctx->error_encountered || ctx->data_used != 0) {
  324. return -1;
  325. }
  326. return 1;
  327. }
  328. int EVP_DecodeBase64(uint8_t *out, size_t *out_len, size_t max_out,
  329. const uint8_t *in, size_t in_len) {
  330. *out_len = 0;
  331. if (in_len % 4 != 0) {
  332. return 0;
  333. }
  334. size_t max_len;
  335. if (!EVP_DecodedLength(&max_len, in_len) ||
  336. max_out < max_len) {
  337. return 0;
  338. }
  339. size_t i, bytes_out = 0;
  340. for (i = 0; i < in_len; i += 4) {
  341. size_t num_bytes_resulting;
  342. if (!base64_decode_quad(out, &num_bytes_resulting, &in[i])) {
  343. return 0;
  344. }
  345. bytes_out += num_bytes_resulting;
  346. out += num_bytes_resulting;
  347. if (num_bytes_resulting != 3 && i != in_len - 4) {
  348. return 0;
  349. }
  350. }
  351. *out_len = bytes_out;
  352. return 1;
  353. }
  354. int EVP_DecodeBlock(uint8_t *dst, const uint8_t *src, size_t src_len) {
  355. // Trim spaces and tabs from the beginning of the input.
  356. while (src_len > 0) {
  357. if (src[0] != ' ' && src[0] != '\t') {
  358. break;
  359. }
  360. src++;
  361. src_len--;
  362. }
  363. // Trim newlines, spaces and tabs from the end of the line.
  364. while (src_len > 0) {
  365. switch (src[src_len-1]) {
  366. case ' ':
  367. case '\t':
  368. case '\r':
  369. case '\n':
  370. src_len--;
  371. continue;
  372. }
  373. break;
  374. }
  375. size_t dst_len;
  376. if (!EVP_DecodedLength(&dst_len, src_len) ||
  377. dst_len > INT_MAX ||
  378. !EVP_DecodeBase64(dst, &dst_len, dst_len, src, src_len)) {
  379. return -1;
  380. }
  381. // EVP_DecodeBlock does not take padding into account, so put the
  382. // NULs back in... so the caller can strip them back out.
  383. while (dst_len % 3 != 0) {
  384. dst[dst_len++] = '\0';
  385. }
  386. assert(dst_len <= INT_MAX);
  387. return (int)dst_len;
  388. }