util_format.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. /* Copyright (c) 2001, Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2017, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file util_format.c
  8. *
  9. * \brief Miscellaneous functions for encoding and decoding various things
  10. * in base{16,32,64}.
  11. */
  12. #include "orconfig.h"
  13. #include "torlog.h"
  14. #include "util.h"
  15. #include "util_format.h"
  16. #include "torint.h"
  17. #include <stddef.h>
  18. #include <string.h>
  19. #include <stdlib.h>
  20. /* Return the base32 encoded size in bytes using the source length srclen.
  21. *
  22. * (WATCH OUT: This API counts the terminating NUL byte, but
  23. * base64_encode_size does not.)
  24. */
  25. size_t
  26. base32_encoded_size(size_t srclen)
  27. {
  28. size_t enclen;
  29. tor_assert(srclen < SIZE_T_CEILING / 8);
  30. enclen = BASE32_NOPAD_BUFSIZE(srclen);
  31. tor_assert(enclen < INT_MAX && enclen > srclen);
  32. return enclen;
  33. }
  34. /** Implements base32 encoding as in RFC 4648. */
  35. void
  36. base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  37. {
  38. unsigned int i, v, u;
  39. size_t nbits = srclen * 8;
  40. size_t bit;
  41. /* We need enough space for the encoded data and the extra NUL byte. */
  42. tor_assert(base32_encoded_size(srclen) <= destlen);
  43. tor_assert(destlen < SIZE_T_CEILING);
  44. /* Make sure we leave no uninitialized data in the destination buffer. */
  45. memset(dest, 0, destlen);
  46. for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
  47. /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
  48. size_t idx = bit / 8;
  49. v = ((uint8_t)src[idx]) << 8;
  50. if (idx+1 < srclen)
  51. v += (uint8_t)src[idx+1];
  52. /* set u to the 5-bit value at the bit'th bit of buf. */
  53. u = (v >> (11-(bit%8))) & 0x1F;
  54. dest[i] = BASE32_CHARS[u];
  55. }
  56. dest[i] = '\0';
  57. }
  58. /** Implements base32 decoding as in RFC 4648.
  59. * Returns 0 if successful, -1 otherwise.
  60. */
  61. int
  62. base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  63. {
  64. /* XXXX we might want to rewrite this along the lines of base64_decode, if
  65. * it ever shows up in the profile. */
  66. unsigned int i;
  67. size_t nbits, j, bit;
  68. char *tmp;
  69. nbits = ((srclen * 5) / 8) * 8;
  70. tor_assert(srclen < SIZE_T_CEILING / 5);
  71. tor_assert((nbits/8) <= destlen); /* We need enough space. */
  72. tor_assert(destlen < SIZE_T_CEILING);
  73. /* Make sure we leave no uninitialized data in the destination buffer. */
  74. memset(dest, 0, destlen);
  75. /* Convert base32 encoded chars to the 5-bit values that they represent. */
  76. tmp = tor_malloc_zero(srclen);
  77. for (j = 0; j < srclen; ++j) {
  78. if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
  79. else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
  80. else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
  81. else {
  82. log_warn(LD_GENERAL, "illegal character in base32 encoded string");
  83. tor_free(tmp);
  84. return -1;
  85. }
  86. }
  87. /* Assemble result byte-wise by applying five possible cases. */
  88. for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
  89. switch (bit % 40) {
  90. case 0:
  91. dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
  92. (((uint8_t)tmp[(bit/5)+1]) >> 2);
  93. break;
  94. case 8:
  95. dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
  96. (((uint8_t)tmp[(bit/5)+1]) << 1) +
  97. (((uint8_t)tmp[(bit/5)+2]) >> 4);
  98. break;
  99. case 16:
  100. dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
  101. (((uint8_t)tmp[(bit/5)+1]) >> 1);
  102. break;
  103. case 24:
  104. dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
  105. (((uint8_t)tmp[(bit/5)+1]) << 2) +
  106. (((uint8_t)tmp[(bit/5)+2]) >> 3);
  107. break;
  108. case 32:
  109. dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
  110. ((uint8_t)tmp[(bit/5)+1]);
  111. break;
  112. }
  113. }
  114. memset(tmp, 0, srclen); /* on the heap, this should be safe */
  115. tor_free(tmp);
  116. tmp = NULL;
  117. return 0;
  118. }
  119. #define BASE64_OPENSSL_LINELEN 64
  120. /** Return the Base64 encoded size of <b>srclen</b> bytes of data in
  121. * bytes.
  122. *
  123. * (WATCH OUT: This API <em>does not</em> count the terminating NUL byte,
  124. * but base32_encoded_size does.)
  125. *
  126. * If <b>flags</b>&amp;BASE64_ENCODE_MULTILINE is true, return the size
  127. * of the encoded output as multiline output (64 character, `\n' terminated
  128. * lines).
  129. */
  130. size_t
  131. base64_encode_size(size_t srclen, int flags)
  132. {
  133. size_t enclen;
  134. /* Use INT_MAX for overflow checking because base64_encode() returns int. */
  135. tor_assert(srclen < INT_MAX);
  136. tor_assert(CEIL_DIV(srclen, 3) < INT_MAX / 4);
  137. enclen = BASE64_LEN(srclen);
  138. if (flags & BASE64_ENCODE_MULTILINE)
  139. enclen += CEIL_DIV(enclen, BASE64_OPENSSL_LINELEN);
  140. tor_assert(enclen < INT_MAX && (enclen == 0 || enclen > srclen));
  141. return enclen;
  142. }
  143. /** Internal table mapping 6 bit values to the Base64 alphabet. */
  144. static const char base64_encode_table[64] = {
  145. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
  146. 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
  147. 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
  148. 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
  149. 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
  150. 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  151. 'w', 'x', 'y', 'z', '0', '1', '2', '3',
  152. '4', '5', '6', '7', '8', '9', '+', '/'
  153. };
  154. /** Base64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
  155. * the result into <b>dest</b>, if it will fit within <b>destlen</b>
  156. * bytes. Return the number of bytes written on success; -1 if
  157. * destlen is too short, or other failure.
  158. *
  159. * If <b>flags</b>&amp;BASE64_ENCODE_MULTILINE is true, return encoded
  160. * output in multiline format (64 character, `\n' terminated lines).
  161. */
  162. int
  163. base64_encode(char *dest, size_t destlen, const char *src, size_t srclen,
  164. int flags)
  165. {
  166. const unsigned char *usrc = (unsigned char *)src;
  167. const unsigned char *eous = usrc + srclen;
  168. char *d = dest;
  169. uint32_t n = 0;
  170. size_t linelen = 0;
  171. size_t enclen;
  172. int n_idx = 0;
  173. if (!src || !dest)
  174. return -1;
  175. /* Ensure that there is sufficient space, including the NUL. */
  176. enclen = base64_encode_size(srclen, flags);
  177. if (destlen < enclen + 1)
  178. return -1;
  179. if (destlen > SIZE_T_CEILING)
  180. return -1;
  181. if (enclen > INT_MAX)
  182. return -1;
  183. /* Make sure we leave no uninitialized data in the destination buffer. */
  184. memset(dest, 0, destlen);
  185. /* XXX/Yawning: If this ends up being too slow, this can be sped up
  186. * by separating the multiline format case and the normal case, and
  187. * processing 48 bytes of input at a time when newlines are desired.
  188. */
  189. #define ENCODE_CHAR(ch) \
  190. STMT_BEGIN \
  191. *d++ = ch; \
  192. if (flags & BASE64_ENCODE_MULTILINE) { \
  193. if (++linelen % BASE64_OPENSSL_LINELEN == 0) { \
  194. linelen = 0; \
  195. *d++ = '\n'; \
  196. } \
  197. } \
  198. STMT_END
  199. #define ENCODE_N(idx) \
  200. ENCODE_CHAR(base64_encode_table[(n >> ((3 - idx) * 6)) & 0x3f])
  201. #define ENCODE_PAD() ENCODE_CHAR('=')
  202. /* Iterate over all the bytes in src. Each one will add 8 bits to the
  203. * value we're encoding. Accumulate bits in <b>n</b>, and whenever we
  204. * have 24 bits, batch them into 4 bytes and flush those bytes to dest.
  205. */
  206. for ( ; usrc < eous; ++usrc) {
  207. n = (n << 8) | *usrc;
  208. if ((++n_idx) == 3) {
  209. ENCODE_N(0);
  210. ENCODE_N(1);
  211. ENCODE_N(2);
  212. ENCODE_N(3);
  213. n_idx = 0;
  214. n = 0;
  215. }
  216. }
  217. switch (n_idx) {
  218. case 0:
  219. /* 0 leftover bits, no pading to add. */
  220. break;
  221. case 1:
  222. /* 8 leftover bits, pad to 12 bits, write the 2 6-bit values followed
  223. * by 2 padding characters.
  224. */
  225. n <<= 4;
  226. ENCODE_N(2);
  227. ENCODE_N(3);
  228. ENCODE_PAD();
  229. ENCODE_PAD();
  230. break;
  231. case 2:
  232. /* 16 leftover bits, pad to 18 bits, write the 3 6-bit values followed
  233. * by 1 padding character.
  234. */
  235. n <<= 2;
  236. ENCODE_N(1);
  237. ENCODE_N(2);
  238. ENCODE_N(3);
  239. ENCODE_PAD();
  240. break;
  241. // LCOV_EXCL_START -- we can't reach this point, because we enforce
  242. // 0 <= ncov_idx < 3 in the loop above.
  243. default:
  244. /* Something went catastrophically wrong. */
  245. tor_fragile_assert();
  246. return -1;
  247. // LCOV_EXCL_STOP
  248. }
  249. #undef ENCODE_N
  250. #undef ENCODE_PAD
  251. #undef ENCODE_CHAR
  252. /* Multiline output always includes at least one newline. */
  253. if (flags & BASE64_ENCODE_MULTILINE && linelen != 0)
  254. *d++ = '\n';
  255. tor_assert(d - dest == (ptrdiff_t)enclen);
  256. *d++ = '\0'; /* NUL terminate the output. */
  257. return (int) enclen;
  258. }
  259. /** As base64_encode, but do not add any internal spaces or external padding
  260. * to the output stream. */
  261. int
  262. base64_encode_nopad(char *dest, size_t destlen,
  263. const uint8_t *src, size_t srclen)
  264. {
  265. int n = base64_encode(dest, destlen, (const char*) src, srclen, 0);
  266. if (n <= 0)
  267. return n;
  268. tor_assert((size_t)n < destlen && dest[n] == 0);
  269. char *in, *out;
  270. in = out = dest;
  271. while (*in) {
  272. if (*in == '=' || *in == '\n') {
  273. ++in;
  274. } else {
  275. *out++ = *in++;
  276. }
  277. }
  278. *out = 0;
  279. tor_assert(out - dest <= INT_MAX);
  280. return (int)(out - dest);
  281. }
  282. #undef BASE64_OPENSSL_LINELEN
  283. /** @{ */
  284. /** Special values used for the base64_decode_table */
  285. #define X 255
  286. #define SP 64
  287. #define PAD 65
  288. /** @} */
  289. /** Internal table mapping byte values to what they represent in base64.
  290. * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
  291. * skipped. Xs are invalid and must not appear in base64. PAD indicates
  292. * end-of-string. */
  293. static const uint8_t base64_decode_table[256] = {
  294. X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
  295. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  296. SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
  297. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
  298. X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  299. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
  300. X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  301. 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
  302. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  303. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  304. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  305. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  306. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  307. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  308. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  309. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  310. };
  311. /** Base64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
  312. * the result into <b>dest</b>, if it will fit within <b>destlen</b>
  313. * bytes. Return the number of bytes written on success; -1 if
  314. * destlen is too short, or other failure.
  315. *
  316. * NOTE 1: destlen is checked conservatively, as though srclen contained no
  317. * spaces or padding.
  318. *
  319. * NOTE 2: This implementation does not check for the correct number of
  320. * padding "=" characters at the end of the string, and does not check
  321. * for internal padding characters.
  322. */
  323. int
  324. base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  325. {
  326. const char *eos = src+srclen;
  327. uint32_t n=0;
  328. int n_idx=0;
  329. size_t di = 0;
  330. if (destlen > INT_MAX)
  331. return -1;
  332. /* Make sure we leave no uninitialized data in the destination buffer. */
  333. memset(dest, 0, destlen);
  334. /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
  335. * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
  336. * 24 bits, batch them into 3 bytes and flush those bytes to dest.
  337. */
  338. for ( ; src < eos; ++src) {
  339. unsigned char c = (unsigned char) *src;
  340. uint8_t v = base64_decode_table[c];
  341. switch (v) {
  342. case X:
  343. /* This character isn't allowed in base64. */
  344. return -1;
  345. case SP:
  346. /* This character is whitespace, and has no effect. */
  347. continue;
  348. case PAD:
  349. /* We've hit an = character: the data is over. */
  350. goto end_of_loop;
  351. default:
  352. /* We have an actual 6-bit value. Append it to the bits in n. */
  353. n = (n<<6) | v;
  354. if ((++n_idx) == 4) {
  355. /* We've accumulated 24 bits in n. Flush them. */
  356. if (destlen < 3 || di > destlen - 3)
  357. return -1;
  358. dest[di++] = (n>>16);
  359. dest[di++] = (n>>8) & 0xff;
  360. dest[di++] = (n) & 0xff;
  361. n_idx = 0;
  362. n = 0;
  363. }
  364. }
  365. }
  366. end_of_loop:
  367. /* If we have leftover bits, we need to cope. */
  368. switch (n_idx) {
  369. case 0:
  370. default:
  371. /* No leftover bits. We win. */
  372. break;
  373. case 1:
  374. /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
  375. return -1;
  376. case 2:
  377. /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
  378. if (destlen < 1 || di > destlen - 1)
  379. return -1;
  380. dest[di++] = n >> 4;
  381. break;
  382. case 3:
  383. /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
  384. if (destlen < 2 || di > destlen - 2)
  385. return -1;
  386. dest[di++] = n >> 10;
  387. dest[di++] = n >> 2;
  388. }
  389. tor_assert(di <= destlen);
  390. return (int)di;
  391. }
  392. #undef X
  393. #undef SP
  394. #undef PAD
  395. /** Encode the <b>srclen</b> bytes at <b>src</b> in a NUL-terminated,
  396. * uppercase hexadecimal string; store it in the <b>destlen</b>-byte buffer
  397. * <b>dest</b>.
  398. */
  399. void
  400. base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  401. {
  402. const char *end;
  403. char *cp;
  404. tor_assert(srclen < SIZE_T_CEILING / 2 - 1);
  405. tor_assert(destlen >= BASE16_BUFSIZE(srclen));
  406. tor_assert(destlen < SIZE_T_CEILING);
  407. /* Make sure we leave no uninitialized data in the destination buffer. */
  408. memset(dest, 0, destlen);
  409. cp = dest;
  410. end = src+srclen;
  411. while (src<end) {
  412. *cp++ = "0123456789ABCDEF"[ (*(const uint8_t*)src) >> 4 ];
  413. *cp++ = "0123456789ABCDEF"[ (*(const uint8_t*)src) & 0xf ];
  414. ++src;
  415. }
  416. *cp = '\0';
  417. }
  418. /** Helper: given a hex digit, return its value, or -1 if it isn't hex. */
  419. static inline int
  420. hex_decode_digit_(char c)
  421. {
  422. switch (c) {
  423. case '0': return 0;
  424. case '1': return 1;
  425. case '2': return 2;
  426. case '3': return 3;
  427. case '4': return 4;
  428. case '5': return 5;
  429. case '6': return 6;
  430. case '7': return 7;
  431. case '8': return 8;
  432. case '9': return 9;
  433. case 'A': case 'a': return 10;
  434. case 'B': case 'b': return 11;
  435. case 'C': case 'c': return 12;
  436. case 'D': case 'd': return 13;
  437. case 'E': case 'e': return 14;
  438. case 'F': case 'f': return 15;
  439. default:
  440. return -1;
  441. }
  442. }
  443. /** Helper: given a hex digit, return its value, or -1 if it isn't hex. */
  444. int
  445. hex_decode_digit(char c)
  446. {
  447. return hex_decode_digit_(c);
  448. }
  449. /** Given a hexadecimal string of <b>srclen</b> bytes in <b>src</b>, decode
  450. * it and store the result in the <b>destlen</b>-byte buffer at <b>dest</b>.
  451. * Return the number of bytes decoded on success, -1 on failure. If
  452. * <b>destlen</b> is greater than INT_MAX or less than half of
  453. * <b>srclen</b>, -1 is returned. */
  454. int
  455. base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  456. {
  457. const char *end;
  458. char *dest_orig = dest;
  459. int v1,v2;
  460. if ((srclen % 2) != 0)
  461. return -1;
  462. if (destlen < srclen/2 || destlen > INT_MAX)
  463. return -1;
  464. /* Make sure we leave no uninitialized data in the destination buffer. */
  465. memset(dest, 0, destlen);
  466. end = src+srclen;
  467. while (src<end) {
  468. v1 = hex_decode_digit_(*src);
  469. v2 = hex_decode_digit_(*(src+1));
  470. if (v1<0||v2<0)
  471. return -1;
  472. *(uint8_t*)dest = (v1<<4)|v2;
  473. ++dest;
  474. src+=2;
  475. }
  476. tor_assert((dest-dest_orig) <= (ptrdiff_t) destlen);
  477. return (int) (dest-dest_orig);
  478. }