EllipticCurveKeyPair.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 <iostream>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <openssl/bn.h>
  32. #include <openssl/obj_mac.h>
  33. #include <openssl/rand.h>
  34. #include <openssl/ec.h>
  35. #include <openssl/ecdh.h>
  36. #include <openssl/ecdsa.h>
  37. #include <openssl/sha.h>
  38. #include "EllipticCurveKey.hpp"
  39. #include "EllipticCurveKeyPair.hpp"
  40. namespace ZeroTier {
  41. class _EC_Group
  42. {
  43. public:
  44. _EC_Group()
  45. {
  46. g = EC_GROUP_new_by_curve_name(ZT_EC_OPENSSL_CURVE);
  47. }
  48. ~_EC_Group() {}
  49. EC_GROUP *g;
  50. };
  51. static _EC_Group ZT_EC_GROUP;
  52. /* Key derivation function */
  53. static void *_zt_EC_KDF(const void *in,size_t inlen,void *out,size_t *outlen)
  54. {
  55. SHA256_CTX sha;
  56. unsigned char dig[SHA256_DIGEST_LENGTH];
  57. SHA256_Init(&sha);
  58. SHA256_Update(&sha,(const unsigned char *)in,inlen);
  59. SHA256_Final(dig,&sha);
  60. for(unsigned long i=0,k=0;i<(unsigned long)*outlen;) {
  61. if (k == SHA256_DIGEST_LENGTH) {
  62. k = 0;
  63. SHA256_Init(&sha);
  64. SHA256_Update(&sha,(const unsigned char *)in,inlen);
  65. SHA256_Update(&sha,dig,SHA256_DIGEST_LENGTH);
  66. SHA256_Final(dig,&sha);
  67. }
  68. ((unsigned char *)out)[i++] = dig[k++];
  69. }
  70. return out;
  71. }
  72. EllipticCurveKeyPair::EllipticCurveKeyPair() :
  73. _pub(),
  74. _priv(),
  75. _internal_key((void *)0)
  76. {
  77. }
  78. EllipticCurveKeyPair::EllipticCurveKeyPair(const EllipticCurveKeyPair &pair) :
  79. _pub(pair._pub),
  80. _priv(pair._priv),
  81. _internal_key((void *)0)
  82. {
  83. }
  84. EllipticCurveKeyPair::EllipticCurveKeyPair(const EllipticCurveKey &pubk,const EllipticCurveKey &privk) :
  85. _pub(pubk),
  86. _priv(privk),
  87. _internal_key((void *)0)
  88. {
  89. }
  90. EllipticCurveKeyPair::~EllipticCurveKeyPair()
  91. {
  92. if (_internal_key)
  93. EC_KEY_free((EC_KEY *)_internal_key);
  94. }
  95. const EllipticCurveKeyPair &EllipticCurveKeyPair::operator=(const EllipticCurveKeyPair &pair)
  96. {
  97. if (_internal_key)
  98. EC_KEY_free((EC_KEY *)_internal_key);
  99. _pub = pair._pub;
  100. _priv = pair._priv;
  101. _internal_key = (void *)0;
  102. return *this;
  103. }
  104. bool EllipticCurveKeyPair::generate()
  105. {
  106. unsigned char tmp[16384];
  107. EC_KEY *key;
  108. int len;
  109. // Make sure OpenSSL libcrypto has sufficient randomness (on most
  110. // platforms it auto-seeds, so this is a sanity check).
  111. if (!RAND_status()) {
  112. #if defined(__APPLE__) || defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  113. FILE *rf = fopen("/dev/urandom","r");
  114. if (rf) {
  115. fread(tmp,sizeof(tmp),1,rf);
  116. fclose(rf);
  117. } else {
  118. fprintf(stderr,"WARNING: cannot open /dev/urandom\n");
  119. for(unsigned int i=0;i<sizeof(tmp);++i)
  120. tmp[i] = (unsigned char)(rand() >> 3);
  121. }
  122. RAND_seed(tmp,sizeof(tmp));
  123. #else
  124. #ifdef _WIN32
  125. error need win32;
  126. #else
  127. error;
  128. #endif
  129. #endif
  130. }
  131. key = EC_KEY_new();
  132. if (!key) return false;
  133. if (!EC_KEY_set_group(key,ZT_EC_GROUP.g)) {
  134. EC_KEY_free(key);
  135. return false;
  136. }
  137. if (!EC_KEY_generate_key(key)) {
  138. EC_KEY_free(key);
  139. return false;
  140. }
  141. memset(_priv._key,0,sizeof(_priv._key));
  142. len = BN_num_bytes(EC_KEY_get0_private_key(key));
  143. if ((len > ZT_EC_PRIME_BYTES)||(len < 0)) {
  144. EC_KEY_free(key);
  145. return false;
  146. }
  147. BN_bn2bin(EC_KEY_get0_private_key(key),&(_priv._key[ZT_EC_PRIME_BYTES - len]));
  148. _priv._bytes = ZT_EC_PRIME_BYTES;
  149. memset(_pub._key,0,sizeof(_pub._key));
  150. len = EC_POINT_point2oct(ZT_EC_GROUP.g,EC_KEY_get0_public_key(key),POINT_CONVERSION_COMPRESSED,_pub._key,sizeof(_pub._key),0);
  151. if (len != ZT_EC_PUBLIC_KEY_BYTES) {
  152. EC_KEY_free(key);
  153. return false;
  154. }
  155. _pub._bytes = ZT_EC_PUBLIC_KEY_BYTES;
  156. if (_internal_key)
  157. EC_KEY_free((EC_KEY *)_internal_key);
  158. _internal_key = key;
  159. return true;
  160. }
  161. bool EllipticCurveKeyPair::agree(const EllipticCurveKey &theirPublicKey,unsigned char *agreedUponKey,unsigned int agreedUponKeyLength) const
  162. {
  163. if (theirPublicKey._bytes != ZT_EC_PUBLIC_KEY_BYTES)
  164. return false;
  165. if (!_internal_key) {
  166. if (!(const_cast <EllipticCurveKeyPair *> (this))->initInternalKey())
  167. return false;
  168. }
  169. EC_POINT *pub = EC_POINT_new(ZT_EC_GROUP.g);
  170. if (!pub)
  171. return false;
  172. EC_POINT_oct2point(ZT_EC_GROUP.g,pub,theirPublicKey._key,ZT_EC_PUBLIC_KEY_BYTES,0);
  173. int i = ECDH_compute_key(agreedUponKey,agreedUponKeyLength,pub,(EC_KEY *)_internal_key,&_zt_EC_KDF);
  174. EC_POINT_free(pub);
  175. return (i == (int)agreedUponKeyLength);
  176. }
  177. std::string EllipticCurveKeyPair::sign(const void *sha256) const
  178. {
  179. unsigned char buf[256];
  180. std::string sigbin;
  181. if (!_internal_key) {
  182. if (!(const_cast <EllipticCurveKeyPair *> (this))->initInternalKey())
  183. return std::string();
  184. }
  185. ECDSA_SIG *sig = ECDSA_do_sign((const unsigned char *)sha256,SHA256_DIGEST_LENGTH,(EC_KEY *)_internal_key);
  186. if (!sig)
  187. return std::string();
  188. int rlen = BN_num_bytes(sig->r);
  189. if ((rlen > 255)||(rlen <= 0)) {
  190. ECDSA_SIG_free(sig);
  191. return std::string();
  192. }
  193. sigbin.push_back((char)rlen);
  194. BN_bn2bin(sig->r,buf);
  195. sigbin.append((const char *)buf,rlen);
  196. int slen = BN_num_bytes(sig->s);
  197. if ((slen > 255)||(slen <= 0)) {
  198. ECDSA_SIG_free(sig);
  199. return std::string();
  200. }
  201. sigbin.push_back((char)slen);
  202. BN_bn2bin(sig->s,buf);
  203. sigbin.append((const char *)buf,slen);
  204. ECDSA_SIG_free(sig);
  205. return sigbin;
  206. }
  207. std::string EllipticCurveKeyPair::sign(const void *data,unsigned int len) const
  208. {
  209. SHA256_CTX sha;
  210. unsigned char dig[SHA256_DIGEST_LENGTH];
  211. SHA256_Init(&sha);
  212. SHA256_Update(&sha,(const unsigned char *)data,len);
  213. SHA256_Final(dig,&sha);
  214. return sign(dig);
  215. }
  216. bool EllipticCurveKeyPair::verify(const void *sha256,const EllipticCurveKey &pk,const void *sigbytes,unsigned int siglen)
  217. {
  218. bool result = false;
  219. ECDSA_SIG *sig = (ECDSA_SIG *)0;
  220. EC_POINT *pub = (EC_POINT *)0;
  221. EC_KEY *key = (EC_KEY *)0;
  222. int rlen,slen;
  223. if (!siglen)
  224. goto verify_sig_return;
  225. rlen = ((const unsigned char *)sigbytes)[0];
  226. if (!rlen)
  227. goto verify_sig_return;
  228. if (siglen < (unsigned int)(rlen + 2))
  229. goto verify_sig_return;
  230. slen = ((const unsigned char *)sigbytes)[rlen + 1];
  231. if (!slen)
  232. goto verify_sig_return;
  233. if (siglen < (unsigned int)(rlen + slen + 2))
  234. goto verify_sig_return;
  235. sig = ECDSA_SIG_new();
  236. if (!sig)
  237. goto verify_sig_return;
  238. BN_bin2bn((const unsigned char *)sigbytes + 1,rlen,sig->r);
  239. BN_bin2bn((const unsigned char *)sigbytes + (1 + rlen + 1),slen,sig->s);
  240. pub = EC_POINT_new(ZT_EC_GROUP.g);
  241. if (!pub)
  242. goto verify_sig_return;
  243. EC_POINT_oct2point(ZT_EC_GROUP.g,pub,pk._key,ZT_EC_PUBLIC_KEY_BYTES,0);
  244. key = EC_KEY_new();
  245. if (!key)
  246. goto verify_sig_return;
  247. if (!EC_KEY_set_group(key,ZT_EC_GROUP.g))
  248. goto verify_sig_return;
  249. EC_KEY_set_public_key(key,pub);
  250. result = (ECDSA_do_verify((const unsigned char *)sha256,SHA256_DIGEST_LENGTH,sig,key) == 1);
  251. verify_sig_return:
  252. if (key)
  253. EC_KEY_free(key);
  254. if (pub)
  255. EC_POINT_free(pub);
  256. if (sig)
  257. ECDSA_SIG_free(sig);
  258. return result;
  259. }
  260. bool EllipticCurveKeyPair::verify(const void *data,unsigned int len,const EllipticCurveKey &pk,const void *sigbytes,unsigned int siglen)
  261. {
  262. SHA256_CTX sha;
  263. unsigned char dig[SHA256_DIGEST_LENGTH];
  264. SHA256_Init(&sha);
  265. SHA256_Update(&sha,(const unsigned char *)data,len);
  266. SHA256_Final(dig,&sha);
  267. return verify(dig,pk,sigbytes,siglen);
  268. }
  269. bool EllipticCurveKeyPair::initInternalKey()
  270. {
  271. EC_KEY *key;
  272. EC_POINT *kxy;
  273. BIGNUM *pn;
  274. if (_priv._bytes != ZT_EC_PRIME_BYTES) return false;
  275. if (_pub._bytes != ZT_EC_PUBLIC_KEY_BYTES) return false;
  276. key = EC_KEY_new();
  277. if (!key) return false;
  278. if (!EC_KEY_set_group(key,ZT_EC_GROUP.g)) {
  279. EC_KEY_free(key);
  280. return false;
  281. }
  282. pn = BN_new();
  283. if (!pn) {
  284. EC_KEY_free(key);
  285. return false;
  286. }
  287. if (!BN_bin2bn(_priv._key,ZT_EC_PRIME_BYTES,pn)) {
  288. BN_free(pn);
  289. EC_KEY_free(key);
  290. return false;
  291. }
  292. if (!EC_KEY_set_private_key(key,pn)) {
  293. BN_free(pn);
  294. EC_KEY_free(key);
  295. return false;
  296. }
  297. BN_free(pn);
  298. kxy = EC_POINT_new(ZT_EC_GROUP.g);
  299. if (!kxy) {
  300. EC_KEY_free(key);
  301. return false;
  302. }
  303. EC_POINT_oct2point(ZT_EC_GROUP.g,kxy,_pub._key,ZT_EC_PUBLIC_KEY_BYTES,0);
  304. if (!EC_KEY_set_public_key(key,kxy)) {
  305. EC_POINT_free(kxy);
  306. EC_KEY_free(key);
  307. return false;
  308. }
  309. EC_POINT_free(kxy);
  310. if (_internal_key)
  311. EC_KEY_free((EC_KEY *)_internal_key);
  312. _internal_key = key;
  313. return true;
  314. }
  315. } // namespace ZeroTier