EllipticCurveKeyPair.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <openssl/bn.h>
  31. #include <openssl/obj_mac.h>
  32. #include <openssl/rand.h>
  33. #include <openssl/ec.h>
  34. #include <openssl/ecdh.h>
  35. #include <openssl/ecdsa.h>
  36. #include <openssl/sha.h>
  37. #include "EllipticCurveKey.hpp"
  38. #include "EllipticCurveKeyPair.hpp"
  39. namespace ZeroTier {
  40. class _EC_Group
  41. {
  42. public:
  43. _EC_Group()
  44. {
  45. g = EC_GROUP_new_by_curve_name(ZT_EC_OPENSSL_CURVE);
  46. }
  47. ~_EC_Group() {}
  48. EC_GROUP *g;
  49. };
  50. static _EC_Group ZT_EC_GROUP;
  51. /**
  52. * Key derivation function
  53. *
  54. * TODO:
  55. * If/when we document the protocol, this will have to be documented as
  56. * well. It's a fairly standard KDF that uses SHA-256 to transform the
  57. * raw EC key. It's generally considered good crypto practice to do this
  58. * to eliminate the possibility of leaking information from EC exchange to
  59. * downstream algorithms.
  60. *
  61. * In our code it is used to produce a two 32-bit keys. One key is used
  62. * for Salsa20 and the other for HMAC-SHA-256. They are generated together
  63. * as a single 64-bit key.
  64. */
  65. static void *_zt_EC_KDF(const void *in,size_t inlen,void *out,size_t *outlen)
  66. {
  67. SHA256_CTX sha;
  68. unsigned char dig[SHA256_DIGEST_LENGTH];
  69. SHA256_Init(&sha);
  70. SHA256_Update(&sha,(const unsigned char *)in,inlen);
  71. SHA256_Final(dig,&sha);
  72. for(unsigned long i=0,k=0;i<(unsigned long)*outlen;) {
  73. if (k == SHA256_DIGEST_LENGTH) {
  74. k = 0;
  75. SHA256_Init(&sha);
  76. SHA256_Update(&sha,(const unsigned char *)in,inlen);
  77. SHA256_Update(&sha,dig,SHA256_DIGEST_LENGTH);
  78. SHA256_Final(dig,&sha);
  79. }
  80. ((unsigned char *)out)[i++] = dig[k++];
  81. }
  82. return out;
  83. }
  84. EllipticCurveKeyPair::EllipticCurveKeyPair() :
  85. _pub(),
  86. _priv(),
  87. _internal_key((void *)0)
  88. {
  89. }
  90. EllipticCurveKeyPair::EllipticCurveKeyPair(const EllipticCurveKeyPair &pair) :
  91. _pub(pair._pub),
  92. _priv(pair._priv),
  93. _internal_key((void *)0)
  94. {
  95. }
  96. EllipticCurveKeyPair::EllipticCurveKeyPair(const EllipticCurveKey &pubk,const EllipticCurveKey &privk) :
  97. _pub(pubk),
  98. _priv(privk),
  99. _internal_key((void *)0)
  100. {
  101. }
  102. EllipticCurveKeyPair::~EllipticCurveKeyPair()
  103. {
  104. if (_internal_key)
  105. EC_KEY_free((EC_KEY *)_internal_key);
  106. }
  107. const EllipticCurveKeyPair &EllipticCurveKeyPair::operator=(const EllipticCurveKeyPair &pair)
  108. {
  109. if (_internal_key)
  110. EC_KEY_free((EC_KEY *)_internal_key);
  111. _pub = pair._pub;
  112. _priv = pair._priv;
  113. _internal_key = (void *)0;
  114. return *this;
  115. }
  116. bool EllipticCurveKeyPair::generate()
  117. {
  118. unsigned char tmp[16384];
  119. EC_KEY *key;
  120. int len;
  121. // Make sure OpenSSL libcrypto has sufficient randomness (on most
  122. // platforms it auto-seeds, so this is a sanity check).
  123. if (!RAND_status()) {
  124. #if defined(__APPLE__) || defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  125. FILE *rf = fopen("/dev/urandom","r");
  126. if (rf) {
  127. fread(tmp,sizeof(tmp),1,rf);
  128. fclose(rf);
  129. } else {
  130. fprintf(stderr,"FATAL: could not open /dev/urandom\n");
  131. exit(-1);
  132. }
  133. RAND_seed(tmp,sizeof(tmp));
  134. #else
  135. #ifdef _WIN32
  136. error need win32;
  137. #else
  138. error;
  139. #endif
  140. #endif
  141. }
  142. key = EC_KEY_new();
  143. if (!key) return false;
  144. if (!EC_KEY_set_group(key,ZT_EC_GROUP.g)) {
  145. EC_KEY_free(key);
  146. return false;
  147. }
  148. if (!EC_KEY_generate_key(key)) {
  149. EC_KEY_free(key);
  150. return false;
  151. }
  152. memset(_priv._key,0,sizeof(_priv._key));
  153. len = BN_num_bytes(EC_KEY_get0_private_key(key));
  154. if ((len > ZT_EC_PRIME_BYTES)||(len < 0)) {
  155. EC_KEY_free(key);
  156. return false;
  157. }
  158. BN_bn2bin(EC_KEY_get0_private_key(key),&(_priv._key[ZT_EC_PRIME_BYTES - len]));
  159. _priv._bytes = ZT_EC_PRIME_BYTES;
  160. memset(_pub._key,0,sizeof(_pub._key));
  161. len = EC_POINT_point2oct(ZT_EC_GROUP.g,EC_KEY_get0_public_key(key),POINT_CONVERSION_COMPRESSED,_pub._key,sizeof(_pub._key),0);
  162. if (len != ZT_EC_PUBLIC_KEY_BYTES) {
  163. EC_KEY_free(key);
  164. return false;
  165. }
  166. _pub._bytes = ZT_EC_PUBLIC_KEY_BYTES;
  167. if (_internal_key)
  168. EC_KEY_free((EC_KEY *)_internal_key);
  169. _internal_key = key;
  170. return true;
  171. }
  172. bool EllipticCurveKeyPair::agree(const EllipticCurveKey &theirPublicKey,unsigned char *agreedUponKey,unsigned int agreedUponKeyLength) const
  173. {
  174. if (theirPublicKey._bytes != ZT_EC_PUBLIC_KEY_BYTES)
  175. return false;
  176. if (!_internal_key) {
  177. if (!(const_cast <EllipticCurveKeyPair *> (this))->initInternalKey())
  178. return false;
  179. }
  180. EC_POINT *pub = EC_POINT_new(ZT_EC_GROUP.g);
  181. if (!pub)
  182. return false;
  183. EC_POINT_oct2point(ZT_EC_GROUP.g,pub,theirPublicKey._key,ZT_EC_PUBLIC_KEY_BYTES,0);
  184. int i = ECDH_compute_key(agreedUponKey,agreedUponKeyLength,pub,(EC_KEY *)_internal_key,&_zt_EC_KDF);
  185. EC_POINT_free(pub);
  186. return (i == (int)agreedUponKeyLength);
  187. }
  188. std::string EllipticCurveKeyPair::sign(const void *sha256) const
  189. {
  190. unsigned char buf[256];
  191. std::string sigbin;
  192. if (!_internal_key) {
  193. if (!(const_cast <EllipticCurveKeyPair *> (this))->initInternalKey())
  194. return std::string();
  195. }
  196. ECDSA_SIG *sig = ECDSA_do_sign((const unsigned char *)sha256,SHA256_DIGEST_LENGTH,(EC_KEY *)_internal_key);
  197. if (!sig)
  198. return std::string();
  199. int rlen = BN_num_bytes(sig->r);
  200. if ((rlen > 255)||(rlen <= 0)) {
  201. ECDSA_SIG_free(sig);
  202. return std::string();
  203. }
  204. sigbin.push_back((char)rlen);
  205. BN_bn2bin(sig->r,buf);
  206. sigbin.append((const char *)buf,rlen);
  207. int slen = BN_num_bytes(sig->s);
  208. if ((slen > 255)||(slen <= 0)) {
  209. ECDSA_SIG_free(sig);
  210. return std::string();
  211. }
  212. sigbin.push_back((char)slen);
  213. BN_bn2bin(sig->s,buf);
  214. sigbin.append((const char *)buf,slen);
  215. ECDSA_SIG_free(sig);
  216. return sigbin;
  217. }
  218. std::string EllipticCurveKeyPair::sign(const void *data,unsigned int len) const
  219. {
  220. SHA256_CTX sha;
  221. unsigned char dig[SHA256_DIGEST_LENGTH];
  222. SHA256_Init(&sha);
  223. SHA256_Update(&sha,(const unsigned char *)data,len);
  224. SHA256_Final(dig,&sha);
  225. return sign(dig);
  226. }
  227. bool EllipticCurveKeyPair::verify(const void *sha256,const EllipticCurveKey &pk,const void *sigbytes,unsigned int siglen)
  228. {
  229. bool result = false;
  230. ECDSA_SIG *sig = (ECDSA_SIG *)0;
  231. EC_POINT *pub = (EC_POINT *)0;
  232. EC_KEY *key = (EC_KEY *)0;
  233. int rlen,slen;
  234. if (!siglen)
  235. goto verify_sig_return;
  236. rlen = ((const unsigned char *)sigbytes)[0];
  237. if (!rlen)
  238. goto verify_sig_return;
  239. if (siglen < (unsigned int)(rlen + 2))
  240. goto verify_sig_return;
  241. slen = ((const unsigned char *)sigbytes)[rlen + 1];
  242. if (!slen)
  243. goto verify_sig_return;
  244. if (siglen < (unsigned int)(rlen + slen + 2))
  245. goto verify_sig_return;
  246. sig = ECDSA_SIG_new();
  247. if (!sig)
  248. goto verify_sig_return;
  249. BN_bin2bn((const unsigned char *)sigbytes + 1,rlen,sig->r);
  250. BN_bin2bn((const unsigned char *)sigbytes + (1 + rlen + 1),slen,sig->s);
  251. pub = EC_POINT_new(ZT_EC_GROUP.g);
  252. if (!pub)
  253. goto verify_sig_return;
  254. EC_POINT_oct2point(ZT_EC_GROUP.g,pub,pk._key,ZT_EC_PUBLIC_KEY_BYTES,0);
  255. key = EC_KEY_new();
  256. if (!key)
  257. goto verify_sig_return;
  258. if (!EC_KEY_set_group(key,ZT_EC_GROUP.g))
  259. goto verify_sig_return;
  260. EC_KEY_set_public_key(key,pub);
  261. result = (ECDSA_do_verify((const unsigned char *)sha256,SHA256_DIGEST_LENGTH,sig,key) == 1);
  262. verify_sig_return:
  263. if (key)
  264. EC_KEY_free(key);
  265. if (pub)
  266. EC_POINT_free(pub);
  267. if (sig)
  268. ECDSA_SIG_free(sig);
  269. return result;
  270. }
  271. bool EllipticCurveKeyPair::verify(const void *data,unsigned int len,const EllipticCurveKey &pk,const void *sigbytes,unsigned int siglen)
  272. {
  273. SHA256_CTX sha;
  274. unsigned char dig[SHA256_DIGEST_LENGTH];
  275. SHA256_Init(&sha);
  276. SHA256_Update(&sha,(const unsigned char *)data,len);
  277. SHA256_Final(dig,&sha);
  278. return verify(dig,pk,sigbytes,siglen);
  279. }
  280. bool EllipticCurveKeyPair::initInternalKey()
  281. {
  282. EC_KEY *key;
  283. EC_POINT *kxy;
  284. BIGNUM *pn;
  285. if (_priv._bytes != ZT_EC_PRIME_BYTES) return false;
  286. if (_pub._bytes != ZT_EC_PUBLIC_KEY_BYTES) return false;
  287. key = EC_KEY_new();
  288. if (!key) return false;
  289. if (!EC_KEY_set_group(key,ZT_EC_GROUP.g)) {
  290. EC_KEY_free(key);
  291. return false;
  292. }
  293. pn = BN_new();
  294. if (!pn) {
  295. EC_KEY_free(key);
  296. return false;
  297. }
  298. if (!BN_bin2bn(_priv._key,ZT_EC_PRIME_BYTES,pn)) {
  299. BN_free(pn);
  300. EC_KEY_free(key);
  301. return false;
  302. }
  303. if (!EC_KEY_set_private_key(key,pn)) {
  304. BN_free(pn);
  305. EC_KEY_free(key);
  306. return false;
  307. }
  308. BN_free(pn);
  309. kxy = EC_POINT_new(ZT_EC_GROUP.g);
  310. if (!kxy) {
  311. EC_KEY_free(key);
  312. return false;
  313. }
  314. EC_POINT_oct2point(ZT_EC_GROUP.g,kxy,_pub._key,ZT_EC_PUBLIC_KEY_BYTES,0);
  315. if (!EC_KEY_set_public_key(key,kxy)) {
  316. EC_POINT_free(kxy);
  317. EC_KEY_free(key);
  318. return false;
  319. }
  320. EC_POINT_free(kxy);
  321. if (_internal_key)
  322. EC_KEY_free((EC_KEY *)_internal_key);
  323. _internal_key = key;
  324. return true;
  325. }
  326. } // namespace ZeroTier