1 /*
2 * Copyright (c) 2013-2021, The PurpleI2P Project
3 *
4 * This file is part of Purple i2pd project and licensed under BSD3
5 *
6 * See full license text in LICENSE file at top of project tree
7 */
8 
9 #ifndef CRYPTO_H__
10 #define CRYPTO_H__
11 
12 #include <inttypes.h>
13 #include <string>
14 #include <vector>
15 #include <openssl/bn.h>
16 #include <openssl/dh.h>
17 #include <openssl/aes.h>
18 #include <openssl/dsa.h>
19 #include <openssl/ecdsa.h>
20 #include <openssl/rsa.h>
21 #include <openssl/sha.h>
22 #include <openssl/evp.h>
23 #include <openssl/rand.h>
24 #include <openssl/engine.h>
25 #include <openssl/opensslv.h>
26 
27 #include "Base.h"
28 #include "Tag.h"
29 #include "CPU.h"
30 
31 // recognize openssl version and features
32 #if ((OPENSSL_VERSION_NUMBER < 0x010100000) || defined(LIBRESSL_VERSION_NUMBER)) // 1.0.2 and below or LibreSSL
33 #   define LEGACY_OPENSSL 1
34 #   define X509_getm_notBefore X509_get_notBefore
35 #   define X509_getm_notAfter X509_get_notAfter
36 #else
37 #   define LEGACY_OPENSSL 0
38 #   if (OPENSSL_VERSION_NUMBER >= 0x010101000) // 1.1.1
39 #       define OPENSSL_HKDF 1
40 #       define OPENSSL_EDDSA 1
41 #       define OPENSSL_X25519 1
42 #		if (OPENSSL_VERSION_NUMBER < 0x030000000) // 3.0.0, regression in SipHash
43 #       	define OPENSSL_SIPHASH 1
44 #		endif
45 #   endif
46 #   if !defined OPENSSL_NO_CHACHA && !defined OPENSSL_NO_POLY1305 // some builds might not include them
47 #       define OPENSSL_AEAD_CHACHA20_POLY1305 1
48 #   endif
49 #endif
50 
51 namespace i2p
52 {
53 namespace crypto
54 {
55 	bool bn2buf (const BIGNUM * bn, uint8_t * buf, size_t len);
56 
57 	// DSA
58 	DSA * CreateDSA ();
59 
60 	// RSA
61 	const BIGNUM * GetRSAE ();
62 
63 	// DH
64 	class DHKeys
65 	{
66 		public:
67 
68 			DHKeys ();
69 			~DHKeys ();
70 
71 			void GenerateKeys ();
GetPublicKey()72 			const uint8_t * GetPublicKey () const { return m_PublicKey; };
73 			void Agree (const uint8_t * pub, uint8_t * shared);
74 
75 		private:
76 
77 			DH * m_DH;
78 			uint8_t m_PublicKey[256];
79 	};
80 
81 	// x25519
82 	class X25519Keys
83 	{
84 		public:
85 
86 			X25519Keys ();
87 			X25519Keys (const uint8_t * priv, const uint8_t * pub); // if pub is null, derive from priv
88 			~X25519Keys ();
89 
90 			void GenerateKeys ();
GetPublicKey()91 			const uint8_t * GetPublicKey () const { return m_PublicKey; };
92 			void GetPrivateKey (uint8_t * priv) const;
93 			void SetPrivateKey (const uint8_t * priv, bool calculatePublic = false);
94 			bool Agree (const uint8_t * pub, uint8_t * shared);
95 
IsElligatorIneligible()96 			bool IsElligatorIneligible () const { return m_IsElligatorIneligible; }
SetElligatorIneligible()97 			void SetElligatorIneligible () { m_IsElligatorIneligible = true; }
98 
99 		private:
100 
101 			uint8_t m_PublicKey[32];
102 #if OPENSSL_X25519
103 			EVP_PKEY_CTX * m_Ctx;
104 			EVP_PKEY * m_Pkey;
105 #else
106 			BN_CTX * m_Ctx;
107 			uint8_t m_PrivateKey[32];
108 #endif
109 			bool m_IsElligatorIneligible = false; // true if definitely ineligible
110 	};
111 
112 	// ElGamal
113 	void ElGamalEncrypt (const uint8_t * key, const uint8_t * data, uint8_t * encrypted); // 222 bytes data, 514 bytes encrypted
114 	bool ElGamalDecrypt (const uint8_t * key, const uint8_t * encrypted, uint8_t * data); // 514 bytes encrypted, 222 data
115 	void GenerateElGamalKeyPair (uint8_t * priv, uint8_t * pub);
116 
117 	// ECIES
118 	void ECIESEncrypt (const EC_GROUP * curve, const EC_POINT * key, const uint8_t * data, uint8_t * encrypted); // 222 bytes data, 514 bytes encrypted
119 	bool ECIESDecrypt (const EC_GROUP * curve, const BIGNUM * key, const uint8_t * encrypted, uint8_t * data); // 514 bytes encrypted, 222 data
120 	void GenerateECIESKeyPair (const EC_GROUP * curve, BIGNUM *& priv, EC_POINT *& pub);
121 
122 	// HMAC
123 	typedef i2p::data::Tag<32> MACKey;
124 	void HMACMD5Digest (uint8_t * msg, size_t len, const MACKey& key, uint8_t * digest);
125 
126 	// AES
127 	struct ChipherBlock
128 	{
129 		uint8_t buf[16];
130 
131 		void operator^=(const ChipherBlock& other) // XOR
132 		{
133 			if (!(((size_t)buf | (size_t)other.buf) & 0x03)) // multiple of 4 ?
134 			{
135 				for (int i = 0; i < 4; i++)
136 					reinterpret_cast<uint32_t *>(buf)[i] ^= reinterpret_cast<const uint32_t *>(other.buf)[i];
137 			}
138 			else
139 			{
140 				for (int i = 0; i < 16; i++)
141 					buf[i] ^= other.buf[i];
142 			}
143 		}
144 	};
145 
146 	typedef i2p::data::Tag<32> AESKey;
147 
148 	template<size_t sz>
149 	class AESAlignedBuffer // 16 bytes alignment
150 	{
151 		public:
152 
AESAlignedBuffer()153 			AESAlignedBuffer ()
154 			{
155 				m_Buf = m_UnalignedBuffer;
156 				uint8_t rem = ((size_t)m_Buf) & 0x0f;
157 				if (rem)
158 					m_Buf += (16 - rem);
159 			}
160 
161 			operator uint8_t * () { return m_Buf; };
162 			operator const uint8_t * () const { return m_Buf; };
GetChipherBlock()163 			ChipherBlock * GetChipherBlock () { return (ChipherBlock *)m_Buf; };
GetChipherBlock()164 			const ChipherBlock * GetChipherBlock () const { return (const ChipherBlock *)m_Buf; };
165 
166 		private:
167 
168 			uint8_t m_UnalignedBuffer[sz + 15]; // up to 15 bytes alignment
169 			uint8_t * m_Buf;
170 	};
171 
172 
173 #ifdef __AES__
174 	class ECBCryptoAESNI
175 	{
176 		public:
177 
GetKeySchedule()178 			uint8_t * GetKeySchedule () { return m_KeySchedule; };
179 
180 		protected:
181 
182 			void ExpandKey (const AESKey& key);
183 
184 		private:
185 
186 			AESAlignedBuffer<240> m_KeySchedule;	// 14 rounds for AES-256, 240 bytes
187 	};
188 #endif
189 
190 #ifdef __AES__
191 	class ECBEncryption: public ECBCryptoAESNI
192 #else
193 	class ECBEncryption
194 #endif
195 	{
196 		public:
197 
198 		void SetKey (const AESKey& key);
199 
200 		void Encrypt(const ChipherBlock * in, ChipherBlock * out);
201 
202 	private:
203 		AES_KEY m_Key;
204 	};
205 
206 #ifdef __AES__
207 	class ECBDecryption: public ECBCryptoAESNI
208 #else
209 	class ECBDecryption
210 #endif
211 	{
212 		public:
213 
214 			void SetKey (const AESKey& key);
215 			void Decrypt (const ChipherBlock * in, ChipherBlock * out);
216 		private:
217 			AES_KEY m_Key;
218 	};
219 
220 	class CBCEncryption
221 	{
222 		public:
223 
CBCEncryption()224 			CBCEncryption () { memset ((uint8_t *)m_LastBlock, 0, 16); };
225 
SetKey(const AESKey & key)226 			void SetKey (const AESKey& key) { m_ECBEncryption.SetKey (key); }; // 32 bytes
SetIV(const uint8_t * iv)227 			void SetIV (const uint8_t * iv) { memcpy ((uint8_t *)m_LastBlock, iv, 16); }; // 16 bytes
GetIV(uint8_t * iv)228 			void GetIV (uint8_t * iv) const { memcpy (iv, (const uint8_t *)m_LastBlock, 16); };
229 
230 			void Encrypt (int numBlocks, const ChipherBlock * in, ChipherBlock * out);
231 			void Encrypt (const uint8_t * in, std::size_t len, uint8_t * out);
232 			void Encrypt (const uint8_t * in, uint8_t * out); // one block
233 
ECB()234 			ECBEncryption & ECB() { return m_ECBEncryption; }
235 
236 		private:
237 
238 			AESAlignedBuffer<16> m_LastBlock;
239 
240 			ECBEncryption m_ECBEncryption;
241 	};
242 
243 	class CBCDecryption
244 	{
245 		public:
246 
CBCDecryption()247 			CBCDecryption () { memset ((uint8_t *)m_IV, 0, 16); };
248 
SetKey(const AESKey & key)249 			void SetKey (const AESKey& key) { m_ECBDecryption.SetKey (key); }; // 32 bytes
SetIV(const uint8_t * iv)250 			void SetIV (const uint8_t * iv) { memcpy ((uint8_t *)m_IV, iv, 16); }; // 16 bytes
GetIV(uint8_t * iv)251 			void GetIV (uint8_t * iv) const { memcpy (iv, (const uint8_t *)m_IV, 16); };
252 
253 			void Decrypt (int numBlocks, const ChipherBlock * in, ChipherBlock * out);
254 			void Decrypt (const uint8_t * in, std::size_t len, uint8_t * out);
255 			void Decrypt (const uint8_t * in, uint8_t * out); // one block
256 
ECB()257 			ECBDecryption & ECB() { return m_ECBDecryption; }
258 
259 		private:
260 
261 			AESAlignedBuffer<16> m_IV;
262 			ECBDecryption m_ECBDecryption;
263 	};
264 
265 	class TunnelEncryption // with double IV encryption
266 	{
267 		public:
268 
SetKeys(const AESKey & layerKey,const AESKey & ivKey)269 			void SetKeys (const AESKey& layerKey, const AESKey& ivKey)
270 			{
271 				m_LayerEncryption.SetKey (layerKey);
272 				m_IVEncryption.SetKey (ivKey);
273 			}
274 
275 			void Encrypt (const uint8_t * in, uint8_t * out); // 1024 bytes (16 IV + 1008 data)
276 
277 		private:
278 
279 			ECBEncryption m_IVEncryption;
280 			CBCEncryption m_LayerEncryption;
281 	};
282 
283 	class TunnelDecryption // with double IV encryption
284 	{
285 		public:
286 
SetKeys(const AESKey & layerKey,const AESKey & ivKey)287 			void SetKeys (const AESKey& layerKey, const AESKey& ivKey)
288 			{
289 				m_LayerDecryption.SetKey (layerKey);
290 				m_IVDecryption.SetKey (ivKey);
291 			}
292 
293 			void Decrypt (const uint8_t * in, uint8_t * out); // 1024 bytes (16 IV + 1008 data)
294 
295 		private:
296 
297 			ECBDecryption m_IVDecryption;
298 			CBCDecryption m_LayerDecryption;
299 	};
300 
301 // AEAD/ChaCha20/Poly1305
302 	bool AEADChaCha20Poly1305 (const uint8_t * msg, size_t msgLen, const uint8_t * ad, size_t adLen, const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len, bool encrypt); // msgLen is len without tag
303 
304 	void AEADChaCha20Poly1305Encrypt (const std::vector<std::pair<uint8_t *, size_t> >& bufs, const uint8_t * key, const uint8_t * nonce, uint8_t * mac); // encrypt multiple buffers with zero ad
305 
306 // ChaCha20
307 	void ChaCha20 (const uint8_t * msg, size_t msgLen, const uint8_t * key, const uint8_t * nonce, uint8_t * out);
308 
309 // HKDF
310 
311 	void HKDF (const uint8_t * salt, const uint8_t * key, size_t keyLen, const std::string& info, uint8_t * out, size_t outLen = 64); // salt - 32, out - 32 or 64, info <= 32
312 
313 // Noise
314 
315 	struct NoiseSymmetricState
316 	{
317 		uint8_t m_H[32] /*h*/, m_CK[64] /*[ck, k]*/;
318 
319 		void MixHash (const uint8_t * buf, size_t len);
320 		void MixKey (const uint8_t * sharedSecret);
321 	};
322 
323 	void InitNoiseNState (NoiseSymmetricState& state, const uint8_t * pub); // Noise_N (tunnels, router)
324 	void InitNoiseXKState (NoiseSymmetricState& state, const uint8_t * pub); // Noise_XK (NTCP2)
325 	void InitNoiseIKState (NoiseSymmetricState& state, const uint8_t * pub); // Noise_IK (ratchets)
326 
327 // init and terminate
328 	void InitCrypto (bool precomputation, bool aesni, bool avx, bool force);
329 	void TerminateCrypto ();
330 }
331 }
332 
333 // take care about openssl below 1.1.0
334 #if LEGACY_OPENSSL
335 // define getters and setters introduced in 1.1.0
DSA_set0_pqg(DSA * d,BIGNUM * p,BIGNUM * q,BIGNUM * g)336 inline int DSA_set0_pqg(DSA *d, BIGNUM *p, BIGNUM *q, BIGNUM *g)
337 	{
338 		if (d->p) BN_free (d->p);
339 		if (d->q) BN_free (d->q);
340 		if (d->g) BN_free (d->g);
341 		d->p = p; d->q = q; d->g = g; return 1;
342 	}
DSA_set0_key(DSA * d,BIGNUM * pub_key,BIGNUM * priv_key)343 inline int DSA_set0_key(DSA *d, BIGNUM *pub_key, BIGNUM *priv_key)
344 	{
345 		if (d->pub_key) BN_free (d->pub_key);
346 		if (d->priv_key) BN_free (d->priv_key);
347 		d->pub_key = pub_key; d->priv_key = priv_key; return 1;
348 	}
DSA_get0_key(const DSA * d,const BIGNUM ** pub_key,const BIGNUM ** priv_key)349 inline void DSA_get0_key(const DSA *d, const BIGNUM **pub_key, const BIGNUM **priv_key)
350 	{ *pub_key = d->pub_key; *priv_key = d->priv_key; }
DSA_SIG_set0(DSA_SIG * sig,BIGNUM * r,BIGNUM * s)351 inline int DSA_SIG_set0(DSA_SIG *sig, BIGNUM *r, BIGNUM *s)
352 	{
353 		if (sig->r) BN_free (sig->r);
354 		if (sig->s) BN_free (sig->s);
355 		sig->r = r; sig->s = s; return 1;
356 	}
DSA_SIG_get0(const DSA_SIG * sig,const BIGNUM ** pr,const BIGNUM ** ps)357 inline void DSA_SIG_get0(const DSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps)
358 	{ *pr = sig->r; *ps = sig->s; }
359 
ECDSA_SIG_set0(ECDSA_SIG * sig,BIGNUM * r,BIGNUM * s)360 inline int ECDSA_SIG_set0(ECDSA_SIG *sig, BIGNUM *r, BIGNUM *s)
361 	{
362 		if (sig->r) BN_free (sig->r);
363 		if (sig->s) BN_free (sig->s);
364 		sig->r = r; sig->s = s; return 1;
365 	}
ECDSA_SIG_get0(const ECDSA_SIG * sig,const BIGNUM ** pr,const BIGNUM ** ps)366 inline void ECDSA_SIG_get0(const ECDSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps)
367 	{ *pr = sig->r; *ps = sig->s; }
368 
RSA_set0_key(RSA * r,BIGNUM * n,BIGNUM * e,BIGNUM * d)369 inline int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d)
370 	{
371 		if (r->n) BN_free (r->n);
372 		if (r->e) BN_free (r->e);
373 		if (r->d) BN_free (r->d);
374 		r->n = n; r->e = e; r->d = d; return 1;
375 	}
RSA_get0_key(const RSA * r,const BIGNUM ** n,const BIGNUM ** e,const BIGNUM ** d)376 inline void RSA_get0_key(const RSA *r, const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
377 	{ *n = r->n; *e = r->e; *d = r->d; }
378 
DH_set0_pqg(DH * dh,BIGNUM * p,BIGNUM * q,BIGNUM * g)379 inline int DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g)
380 	{
381 		if (dh->p) BN_free (dh->p);
382 		if (dh->q) BN_free (dh->q);
383 		if (dh->g) BN_free (dh->g);
384 		dh->p = p; dh->q = q; dh->g = g;  return 1;
385 	}
DH_set0_key(DH * dh,BIGNUM * pub_key,BIGNUM * priv_key)386 inline int DH_set0_key(DH *dh, BIGNUM *pub_key, BIGNUM *priv_key)
387 	{
388 		if (dh->pub_key) BN_free (dh->pub_key);
389 		if (dh->priv_key) BN_free (dh->priv_key);
390 		dh->pub_key = pub_key; dh->priv_key = priv_key; return 1;
391 	}
DH_get0_key(const DH * dh,const BIGNUM ** pub_key,const BIGNUM ** priv_key)392 inline void DH_get0_key(const DH *dh, const BIGNUM **pub_key, const BIGNUM **priv_key)
393 	{ *pub_key = dh->pub_key; *priv_key = dh->priv_key; }
394 
EVP_PKEY_get0_RSA(EVP_PKEY * pkey)395 inline RSA *EVP_PKEY_get0_RSA(EVP_PKEY *pkey)
396 	{ return pkey->pkey.rsa; }
397 
EVP_MD_CTX_new()398 inline EVP_MD_CTX *EVP_MD_CTX_new ()
399 	{ return EVP_MD_CTX_create(); }
EVP_MD_CTX_free(EVP_MD_CTX * ctx)400 inline void EVP_MD_CTX_free (EVP_MD_CTX *ctx)
401 	{ EVP_MD_CTX_destroy (ctx); }
402 
403 // ssl
404 #define TLS_method TLSv1_method
405 
406 #endif
407 
408 #endif
409