1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 
4 #include "tomcrypt.h"
5 
6 /*
7  * Internal Macros
8  */
9 
10 #define LTC_PAD_MASK       (0xF000U)
11 
12 /* `NULL` as defined by the standard is not guaranteed to be of a pointer
13  * type. In order to make sure that in vararg API's a pointer type is used,
14  * define our own version and use that one internally.
15  */
16 #ifndef LTC_NULL
17    #define LTC_NULL ((void *)0)
18 #endif
19 
20 /*
21  * Internal Enums
22  */
23 
24 enum ltc_oid_id {
25    LTC_OID_RSA,
26    LTC_OID_DSA,
27    LTC_OID_EC,
28    LTC_OID_EC_PRIMEF,
29    LTC_OID_X25519,
30    LTC_OID_ED25519,
31 };
32 
33 /*
34  * Internal Types
35  */
36 
37 typedef struct {
38   int size;
39   const char *name, *base, *prime;
40 } ltc_dh_set_type;
41 
42 
43 typedef int (*fn_kdf_t)(const unsigned char *password, unsigned long password_len,
44                               const unsigned char *salt,     unsigned long salt_len,
45                               int iteration_count,  int hash_idx,
46                               unsigned char *out,   unsigned long *outlen);
47 
48 typedef struct {
49    /* KDF */
50    fn_kdf_t kdf;
51    /* Hash or HMAC */
52    const char* h;
53    /* cipher */
54    const char* c;
55    unsigned long keylen;
56    /* not used for pbkdf2 */
57    unsigned long blocklen;
58 } pbes_properties;
59 
60 typedef struct
61 {
62    pbes_properties type;
63    const void *pwd;
64    unsigned long pwdlen;
65    ltc_asn1_list *enc_data;
66    ltc_asn1_list *salt;
67    ltc_asn1_list *iv;
68    unsigned long iterations;
69    /* only used for RC2 */
70    unsigned long key_bits;
71 } pbes_arg;
72 
73 /*
74  * Internal functions
75  */
76 
77 
78 /* tomcrypt_cipher.h */
79 
80 void blowfish_enc(ulong32 *data, unsigned long blocks, const symmetric_key *skey);
81 int blowfish_expand(const unsigned char *key, int keylen,
82                     const unsigned char *data, int datalen,
83                     symmetric_key *skey);
84 int blowfish_setup_with_data(const unsigned char *key, int keylen,
85                              const unsigned char *data, int datalen,
86                              symmetric_key *skey);
87 
88 /* tomcrypt_hash.h */
89 
90 /* a macro for making hash "process" functions */
91 #define HASH_PROCESS_(func_name, compress_name, compress_n_name, state_var, block_size)     \
92 int func_name (hash_state * md, const unsigned char *in, unsigned long inlen)               \
93 {                                                                                           \
94     unsigned long n, blocks;                                                                \
95     int           err;                                                                      \
96     int           (*compress)(hash_state *, const unsigned char *) = compress_name;         \
97     int           (*compress_n)(hash_state *, const unsigned char *, int) = compress_n_name;\
98     LTC_ARGCHK(md != NULL);                                                                 \
99     LTC_ARGCHK(in != NULL);                                                                 \
100     if (md-> state_var .curlen > sizeof(md-> state_var .buf)) {                             \
101        return CRYPT_INVALID_ARG;                                                            \
102     }                                                                                       \
103     if (((md-> state_var .length + inlen * 8) < md-> state_var .length)                     \
104           || ((inlen * 8) < inlen)) {                                                       \
105       return CRYPT_HASH_OVERFLOW;                                                           \
106     }                                                                                       \
107     while (inlen > 0) {                                                                     \
108         if (md-> state_var .curlen == 0 && inlen >= block_size) {                           \
109            if (compress_n) {                                                                \
110               blocks = inlen / block_size;                                                  \
111               err = compress_n (md, in, blocks);                                            \
112            } else {                                                                         \
113               blocks = 1;                                                                   \
114               err = compress (md, in);                                                      \
115            }                                                                                \
116            if (err != CRYPT_OK)                                                             \
117               return err;                                                                   \
118            md-> state_var .length += blocks * block_size * 8;                               \
119            in             += blocks * block_size;                                           \
120            inlen          -= blocks * block_size;                                           \
121         } else {                                                                            \
122            n = MIN(inlen, (block_size - md-> state_var .curlen));                           \
123            XMEMCPY(md-> state_var .buf + md-> state_var.curlen, in, (size_t)n);             \
124            md-> state_var .curlen += n;                                                     \
125            in             += n;                                                             \
126            inlen          -= n;                                                             \
127            if (md-> state_var .curlen == block_size) {                                      \
128               if (compress_n) {                                                             \
129                  err = compress_n (md, md-> state_var .buf, 1);                             \
130               } else {                                                                      \
131                  err = compress (md, md-> state_var .buf);                                  \
132               }                                                                             \
133               if (err != CRYPT_OK) {                                                        \
134                  return err;                                                                \
135               }                                                                             \
136               md-> state_var .length += 8*block_size;                                       \
137               md-> state_var .curlen = 0;                                                   \
138            }                                                                                \
139        }                                                                                    \
140     }                                                                                       \
141     return CRYPT_OK;                                                                        \
142 }
143 
144 /* define a hash "process" function based on a 1-block compress function */
145 #define HASH_PROCESS(func_name, compress_name, state_var, block_size)                       \
146         HASH_PROCESS_(func_name, compress_name, NULL, state_var, block_size)
147 
148 /* define a hash "process" function based on a n-block compress function */
149 #define HASH_PROCESS_NBLOCKS(func_name, compress_n_name, state_var, block_size)             \
150        HASH_PROCESS_(func_name, NULL, compress_n_name, state_var, block_size)
151 
152 
153 /* tomcrypt_mac.h */
154 
155 int ocb3_int_ntz(unsigned long x);
156 void ocb3_int_xor_blocks(unsigned char *out, const unsigned char *block_a, const unsigned char *block_b, unsigned long block_len);
157 
158 
159 /* tomcrypt_math.h */
160 
161 #if !defined(DESC_DEF_ONLY)
162 
163 #define MP_DIGIT_BIT                 ltc_mp.bits_per_digit
164 
165 /* some handy macros */
166 #define mp_init(a)                   ltc_mp.init(a)
167 #define mp_init_multi                ltc_init_multi
168 #define mp_init_size(a, b)           ltc_mp.init_size(a, b)
169 #define mp_init_multi_size           ltc_init_multi_size
170 #define mp_clear(a)                  ltc_mp.deinit(a)
171 #define mp_clear_multi               ltc_deinit_multi
172 #define mp_cleanup_multi             ltc_cleanup_multi
173 #define mp_init_copy(a, b)           ltc_mp.init_copy(a, b)
174 
175 #define mp_neg(a, b)                 ltc_mp.neg(a, b)
176 #define mp_copy(a, b)                ltc_mp.copy(a, b)
177 
178 #define mp_set(a, b)                 ltc_mp.set_int(a, b)
179 #define mp_set_int(a, b)             ltc_mp.set_int(a, b)
180 #define mp_get_int(a)                ltc_mp.get_int(a)
181 #define mp_get_digit(a, n)           ltc_mp.get_digit(a, n)
182 #define mp_get_digit_count(a)        ltc_mp.get_digit_count(a)
183 #define mp_cmp(a, b)                 ltc_mp.compare(a, b)
184 #define mp_cmp_d(a, b)               ltc_mp.compare_d(a, b)
185 #define mp_count_bits(a)             ltc_mp.count_bits(a)
186 #define mp_cnt_lsb(a)                ltc_mp.count_lsb_bits(a)
187 #define mp_2expt(a, b)               ltc_mp.twoexpt(a, b)
188 
189 #define mp_read_radix(a, b, c)       ltc_mp.read_radix(a, b, c)
190 #define mp_toradix(a, b, c)          ltc_mp.write_radix(a, b, c)
191 #define mp_unsigned_bin_size(a)      ltc_mp.unsigned_size(a)
192 #define mp_to_unsigned_bin(a, b)     ltc_mp.unsigned_write(a, b)
193 #define mp_read_unsigned_bin(a, b, c) ltc_mp.unsigned_read(a, b, c)
194 
195 #define mp_add(a, b, c)              ltc_mp.add(a, b, c)
196 #define mp_add_d(a, b, c)            ltc_mp.addi(a, b, c)
197 #define mp_sub(a, b, c)              ltc_mp.sub(a, b, c)
198 #define mp_sub_d(a, b, c)            ltc_mp.subi(a, b, c)
199 #define mp_mul(a, b, c)              ltc_mp.mul(a, b, c)
200 #define mp_mul_d(a, b, c)            ltc_mp.muli(a, b, c)
201 #define mp_sqr(a, b)                 ltc_mp.sqr(a, b)
202 #define mp_sqrtmod_prime(a, b, c)    ltc_mp.sqrtmod_prime(a, b, c)
203 #define mp_div(a, b, c, d)           ltc_mp.mpdiv(a, b, c, d)
204 #define mp_div_2(a, b)               ltc_mp.div_2(a, b)
205 #define mp_mod(a, b, c)              ltc_mp.mpdiv(a, b, NULL, c)
206 #define mp_mod_d(a, b, c)            ltc_mp.modi(a, b, c)
207 #define mp_gcd(a, b, c)              ltc_mp.gcd(a, b, c)
208 #define mp_lcm(a, b, c)              ltc_mp.lcm(a, b, c)
209 
210 #define mp_addmod(a, b, c, d)        ltc_mp.addmod(a, b, c, d)
211 #define mp_submod(a, b, c, d)        ltc_mp.submod(a, b, c, d)
212 #define mp_mulmod(a, b, c, d)        ltc_mp.mulmod(a, b, c, d)
213 #define mp_sqrmod(a, b, c)           ltc_mp.sqrmod(a, b, c)
214 #define mp_invmod(a, b, c)           ltc_mp.invmod(a, b, c)
215 
216 #define mp_montgomery_setup(a, b)    ltc_mp.montgomery_setup(a, b)
217 #define mp_montgomery_normalization(a, b) ltc_mp.montgomery_normalization(a, b)
218 #define mp_montgomery_reduce(a, b, c)   ltc_mp.montgomery_reduce(a, b, c)
219 #define mp_montgomery_free(a)        ltc_mp.montgomery_deinit(a)
220 
221 #define mp_exptmod(a,b,c,d)          ltc_mp.exptmod(a,b,c,d)
222 #define mp_prime_is_prime(a, b, c)   ltc_mp.isprime(a, b, c)
223 
224 #define mp_iszero(a)                 (mp_cmp_d(a, 0) == LTC_MP_EQ ? LTC_MP_YES : LTC_MP_NO)
225 #define mp_isodd(a)                  (mp_get_digit_count(a) > 0 ? (mp_get_digit(a, 0) & 1 ? LTC_MP_YES : LTC_MP_NO) : LTC_MP_NO)
226 #define mp_exch(a, b)                do { void *ABC__tmp = a; a = b; b = ABC__tmp; } while(0)
227 
228 #define mp_tohex(a, b)               mp_toradix(a, b, 16)
229 
230 #define mp_rand(a, b)                ltc_mp.rand(a, b)
231 
232 #endif
233 
234 
235 /* tomcrypt_misc.h */
236 
237 typedef enum {
238    /** Use `\r\n` as line separator */
239    BASE64_PEM_CRLF = 1,
240    /** Create output with 72 chars line length */
241    BASE64_PEM_SSH = 2,
242 } base64_pem_flags;
243 
244 int base64_encode_pem(const unsigned char *in,  unsigned long inlen,
245                                      char *out, unsigned long *outlen,
246                             unsigned int  flags);
247 
248 void copy_or_zeromem(const unsigned char* src, unsigned char* dest, unsigned long len, int coz);
249 
250 int pbes_decrypt(const pbes_arg  *arg, unsigned char *dec_data, unsigned long *dec_size);
251 
252 int pbes1_extract(const ltc_asn1_list *s, pbes_arg *res);
253 int pbes2_extract(const ltc_asn1_list *s, pbes_arg *res);
254 
255 
256 /* tomcrypt_pk.h */
257 
258 int rand_bn_bits(void *N, int bits, prng_state *prng, int wprng);
259 int rand_bn_upto(void *N, void *limit, prng_state *prng, int wprng);
260 
261 int pk_get_oid(enum ltc_oid_id id, const char **st);
262 int pk_oid_str_to_num(const char *OID, unsigned long *oid, unsigned long *oidlen);
263 int pk_oid_num_to_str(const unsigned long *oid, unsigned long oidlen, char *OID, unsigned long *outlen);
264 
265 /* ---- DH Routines ---- */
266 #ifdef LTC_MRSA
267 int rsa_init(rsa_key *key);
268 void rsa_shrink_key(rsa_key *key);
269 int rsa_make_key_bn_e(prng_state *prng, int wprng, int size, void *e,
270                       rsa_key *key); /* used by op-tee */
271 int rsa_import_pkcs1(const unsigned char *in, unsigned long inlen, rsa_key *key);
272 #endif /* LTC_MRSA */
273 
274 /* ---- DH Routines ---- */
275 #ifdef LTC_MDH
276 extern const ltc_dh_set_type ltc_dh_sets[];
277 
278 int dh_check_pubkey(const dh_key *key);
279 #endif /* LTC_MDH */
280 
281 /* ---- ECC Routines ---- */
282 #ifdef LTC_MECC
283 int ecc_set_curve_from_mpis(void *a, void *b, void *prime, void *order, void *gx, void *gy, unsigned long cofactor, ecc_key *key);
284 int ecc_copy_curve(const ecc_key *srckey, ecc_key *key);
285 int ecc_set_curve_by_size(int size, ecc_key *key);
286 int ecc_import_subject_public_key_info(const unsigned char *in, unsigned long inlen, ecc_key *key);
287 
288 #ifdef LTC_SSH
289 int ecc_ssh_ecdsa_encode_name(char *buffer, unsigned long *buflen, const ecc_key *key);
290 #endif
291 
292 /* low level functions */
293 ecc_point *ltc_ecc_new_point(void);
294 void       ltc_ecc_del_point(ecc_point *p);
295 int        ltc_ecc_set_point_xyz(ltc_mp_digit x, ltc_mp_digit y, ltc_mp_digit z, ecc_point *p);
296 int        ltc_ecc_copy_point(const ecc_point *src, ecc_point *dst);
297 int        ltc_ecc_is_point(const ltc_ecc_dp *dp, void *x, void *y);
298 int        ltc_ecc_is_point_at_infinity(const ecc_point *P, void *modulus, int *retval);
299 int        ltc_ecc_import_point(const unsigned char *in, unsigned long inlen, void *prime, void *a, void *b, void *x, void *y);
300 int        ltc_ecc_export_point(unsigned char *out, unsigned long *outlen, void *x, void *y, unsigned long size, int compressed);
301 int        ltc_ecc_verify_key(const ecc_key *key);
302 
303 /* point ops (mp == montgomery digit) */
304 #if !defined(LTC_MECC_ACCEL) || defined(LTM_DESC) || defined(GMP_DESC)
305 /* R = 2P */
306 int ltc_ecc_projective_dbl_point(const ecc_point *P, ecc_point *R, void *ma, void *modulus, void *mp);
307 
308 /* R = P + Q */
309 int ltc_ecc_projective_add_point(const ecc_point *P, const ecc_point *Q, ecc_point *R, void *ma, void *modulus, void *mp);
310 #endif
311 
312 #if defined(LTC_MECC_FP)
313 /* optimized point multiplication using fixed point cache (HAC algorithm 14.117) */
314 int ltc_ecc_fp_mulmod(void *k, ecc_point *G, ecc_point *R, void *a, void *modulus, int map);
315 
316 /* functions for saving/loading/freeing/adding to fixed point cache */
317 int ltc_ecc_fp_save_state(unsigned char **out, unsigned long *outlen);
318 int ltc_ecc_fp_restore_state(unsigned char *in, unsigned long inlen);
319 void ltc_ecc_fp_free(void);
320 int ltc_ecc_fp_add_point(ecc_point *g, void *modulus, int lock);
321 
322 /* lock/unlock all points currently in fixed point cache */
323 void ltc_ecc_fp_tablelock(int lock);
324 #endif
325 
326 /* R = kG */
327 int ltc_ecc_mulmod(void *k, const ecc_point *G, ecc_point *R, void *a, void *modulus, int map);
328 
329 #ifdef LTC_ECC_SHAMIR
330 /* kA*A + kB*B = C */
331 int ltc_ecc_mul2add(const ecc_point *A, void *kA,
332                     const ecc_point *B, void *kB,
333                           ecc_point *C,
334                                void *ma,
335                                void *modulus);
336 
337 #ifdef LTC_MECC_FP
338 /* Shamir's trick with optimized point multiplication using fixed point cache */
339 int ltc_ecc_fp_mul2add(const ecc_point *A, void *kA,
340                        const ecc_point *B, void *kB,
341                              ecc_point *C,
342                                   void *ma,
343                                   void *modulus);
344 #endif
345 
346 #endif
347 
348 
349 /* map P to affine from projective */
350 int ltc_ecc_map(ecc_point *P, void *modulus, void *mp);
351 #endif /* LTC_MECC */
352 
353 #ifdef LTC_MDSA
354 int dsa_int_validate_xy(const dsa_key *key, int *stat);
355 int dsa_int_validate_pqg(const dsa_key *key, int *stat);
356 int dsa_int_validate_primes(const dsa_key *key, int *stat);
357 #endif /* LTC_MDSA */
358 
359 
360 #ifdef LTC_CURVE25519
361 
362 int tweetnacl_crypto_sign(
363   unsigned char *sm,unsigned long long *smlen,
364   const unsigned char *m,unsigned long long mlen,
365   const unsigned char *sk,const unsigned char *pk,
366   const unsigned char *ctx,unsigned long long cs);
367 int tweetnacl_crypto_sign_open(
368   int *stat,
369   unsigned char *m,unsigned long long *mlen,
370   const unsigned char *sm,unsigned long long smlen,
371   const unsigned char *ctx, unsigned long long cs,
372   const unsigned char *pk);
373 int tweetnacl_crypto_sign_keypair(prng_state *prng, int wprng, unsigned char *pk,unsigned char *sk);
374 int tweetnacl_crypto_sk_to_pk(unsigned char *pk, const unsigned char *sk);
375 int tweetnacl_crypto_scalarmult(unsigned char *q, const unsigned char *n, const unsigned char *p);
376 int tweetnacl_crypto_scalarmult_base(unsigned char *q,const unsigned char *n);
377 int tweetnacl_crypto_ph(unsigned char *out, const unsigned char *msg, unsigned long long msglen);
378 
379 typedef int (*sk_to_pk)(unsigned char *pk ,const unsigned char *sk);
380 int ec25519_import_pkcs8(const unsigned char *in, unsigned long inlen,
381                        const void *pwd, unsigned long pwdlen,
382                        enum ltc_oid_id id, sk_to_pk fp,
383                        curve25519_key *key);
384 int ec25519_export(       unsigned char *out, unsigned long *outlen,
385                                     int  which,
386                    const curve25519_key *key);
387 int ec25519_crypto_ctx(      unsigned char *out, unsigned long *outlen,
388                              unsigned char flag,
389                        const unsigned char *ctx, unsigned long  ctxlen);
390 #endif /* LTC_CURVE25519 */
391 
392 #ifdef LTC_DER
393 
394 #define LTC_ASN1_IS_TYPE(e, t) (((e) != NULL) && ((e)->type == (t)))
395 
396 /* DER handling */
397 int der_decode_custom_type_ex(const unsigned char *in, unsigned long  inlen,
398                            ltc_asn1_list *root,
399                            ltc_asn1_list *list,     unsigned long  outlen, unsigned int flags);
400 
401 int der_encode_asn1_identifier(const ltc_asn1_list *id, unsigned char *out, unsigned long *outlen);
402 int der_decode_asn1_identifier(const unsigned char *in, unsigned long *inlen, ltc_asn1_list *id);
403 int der_length_asn1_identifier(const ltc_asn1_list *id, unsigned long *idlen);
404 
405 int der_encode_asn1_length(unsigned long len, unsigned char* out, unsigned long* outlen);
406 int der_decode_asn1_length(const unsigned char *in, unsigned long *inlen, unsigned long *outlen);
407 int der_length_asn1_length(unsigned long len, unsigned long *outlen);
408 
409 int der_length_sequence_ex(const ltc_asn1_list *list, unsigned long inlen,
410                            unsigned long *outlen, unsigned long *payloadlen);
411 
412 extern const ltc_asn1_type  der_asn1_tag_to_type_map[];
413 extern const unsigned long  der_asn1_tag_to_type_map_sz;
414 
415 extern const int der_asn1_type_to_identifier_map[];
416 extern const unsigned long der_asn1_type_to_identifier_map_sz;
417 
418 int der_decode_sequence_multi_ex(const unsigned char *in, unsigned long inlen, unsigned int flags, ...)
419                                  LTC_NULL_TERMINATED;
420 
421 int der_teletex_char_encode(int c);
422 int der_teletex_value_decode(int v);
423 
424 int der_utf8_valid_char(const wchar_t c);
425 
426 typedef int (*public_key_decode_cb)(const unsigned char *in, unsigned long inlen, void *ctx);
427 
428 int x509_decode_public_key_from_certificate(const unsigned char *in, unsigned long inlen,
429                                             enum ltc_oid_id algorithm, ltc_asn1_type param_type,
430                                             ltc_asn1_list* parameters, unsigned long *parameters_len,
431                                             public_key_decode_cb callback, void *ctx);
432 
433 /* SUBJECT PUBLIC KEY INFO */
434 int x509_encode_subject_public_key_info(unsigned char *out, unsigned long *outlen,
435         unsigned int algorithm, const void* public_key, unsigned long public_key_len,
436         ltc_asn1_type parameters_type, ltc_asn1_list* parameters, unsigned long parameters_len);
437 
438 int x509_decode_subject_public_key_info(const unsigned char *in, unsigned long inlen,
439         unsigned int algorithm, void* public_key, unsigned long* public_key_len,
440         ltc_asn1_type parameters_type, ltc_asn1_list* parameters, unsigned long *parameters_len);
441 
442 int pk_oid_cmp_with_ulong(const char *o1, const unsigned long *o2, unsigned long o2size);
443 int pk_oid_cmp_with_asn1(const char *o1, const ltc_asn1_list *o2);
444 
445 #endif /* LTC_DER */
446 
447 /* tomcrypt_pkcs.h */
448 
449 #ifdef LTC_PKCS_8
450 
451 int pkcs8_decode_flexi(const unsigned char  *in,  unsigned long inlen,
452                                     const void  *pwd, unsigned long pwdlen,
453                                  ltc_asn1_list **decoded_list);
454 
455 #endif  /* LTC_PKCS_8 */
456 
457 
458 #ifdef LTC_PKCS_12
459 
460 int pkcs12_utf8_to_utf16(const unsigned char *in,  unsigned long  inlen,
461                                unsigned char *out, unsigned long *outlen);
462 
463 int pkcs12_kdf(               int   hash_id,
464                const unsigned char *pw,         unsigned long pwlen,
465                const unsigned char *salt,       unsigned long saltlen,
466                      unsigned int   iterations, unsigned char purpose,
467                      unsigned char *out,        unsigned long outlen);
468 
469 #endif  /* LTC_PKCS_12 */
470 
471 /* tomcrypt_prng.h */
472 
473 #define LTC_PRNG_EXPORT(which) \
474 int which ## _export(unsigned char *out, unsigned long *outlen, prng_state *prng)      \
475 {                                                                                      \
476    unsigned long len = which ## _desc.export_size;                                     \
477                                                                                        \
478    LTC_ARGCHK(prng   != NULL);                                                         \
479    LTC_ARGCHK(out    != NULL);                                                         \
480    LTC_ARGCHK(outlen != NULL);                                                         \
481                                                                                        \
482    if (*outlen < len) {                                                                \
483       *outlen = len;                                                                   \
484       return CRYPT_BUFFER_OVERFLOW;                                                    \
485    }                                                                                   \
486                                                                                        \
487    if (which ## _read(out, len, prng) != len) {                                        \
488       return CRYPT_ERROR_READPRNG;                                                     \
489    }                                                                                   \
490                                                                                        \
491    *outlen = len;                                                                      \
492    return CRYPT_OK;                                                                    \
493 }
494 
495 /* extract a byte portably */
496 #ifdef _MSC_VER
497    #define LTC_BYTE(x, n) ((unsigned char)((x) >> (8 * (n))))
498 #else
499    #define LTC_BYTE(x, n) (((x) >> (8 * (n))) & 255)
500 #endif
501