TLS plugin for the TQt Cryptographic Architecture
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

1511 lines
29KB

  1. /*
  2. * qca-tls.cpp - TLS plugin for TQCA
  3. * Copyright (C) 2003 Justin Karneges
  4. *
  5. * This library is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU Lesser General Public
  7. * License as published by the Free Software Foundation; either
  8. * version 2.1 of the License, or (at your option) any later version.
  9. *
  10. * This library 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 GNU
  13. * Lesser General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Lesser General Public
  16. * License along with this library; if not, write to the Free Software
  17. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. *
  19. */
  20. #include"qca-tls.h"
  21. #include<tqregexp.h>
  22. #include<openssl/sha.h>
  23. #include<openssl/md5.h>
  24. #include<openssl/evp.h>
  25. #include<openssl/bio.h>
  26. #include<openssl/pem.h>
  27. #include<openssl/rsa.h>
  28. #include<openssl/x509.h>
  29. #include<openssl/x509v3.h>
  30. #include<openssl/ssl.h>
  31. #include<openssl/err.h>
  32. #include<openssl/rand.h>
  33. #ifndef OSSL_097
  34. #define NO_AES
  35. #endif
  36. static TQByteArray lib_randomArray(int size)
  37. {
  38. if(RAND_status() == 0) {
  39. srand(time(NULL));
  40. char buf[128];
  41. for(int n = 0; n < 128; ++n)
  42. buf[n] = rand();
  43. RAND_seed(buf, 128);
  44. }
  45. TQByteArray a(size);
  46. RAND_bytes((unsigned char *)a.data(), a.size());
  47. return a;
  48. }
  49. static bool lib_generateKeyIV(const EVP_CIPHER *_type, const TQByteArray &data, const TQByteArray &salt, TQByteArray *key, TQByteArray *iv, int keysize=-1)
  50. {
  51. TQByteArray k, i;
  52. unsigned char *kp = 0;
  53. unsigned char *ip = 0;
  54. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  55. EVP_CIPHER type = *_type;
  56. EVP_CIPHER *loctype = &type;
  57. if(keysize != -1)
  58. type.key_len = keysize;
  59. #else
  60. EVP_CIPHER *loctype = EVP_CIPHER_meth_dup(_type);
  61. Q_UNUSED(keysize)
  62. #endif
  63. if(key) {
  64. k.resize(EVP_CIPHER_key_length(loctype));
  65. kp = (unsigned char *)k.data();
  66. }
  67. if(iv) {
  68. i.resize(EVP_CIPHER_iv_length(loctype));
  69. ip = (unsigned char *)i.data();
  70. }
  71. int res = EVP_BytesToKey(loctype, EVP_sha1(), (unsigned char *)salt.data(), (unsigned char *)data.data(), data.size(), 1, kp, ip);
  72. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  73. EVP_CIPHER_meth_free(loctype);
  74. #endif
  75. if (!res)
  76. return false;
  77. if(key)
  78. *key = k;
  79. if(iv)
  80. *iv = i;
  81. return true;
  82. }
  83. static void appendArray(TQByteArray *a, const TQByteArray &b)
  84. {
  85. int oldsize = a->size();
  86. a->resize(oldsize + b.size());
  87. memcpy(a->data() + oldsize, b.data(), b.size());
  88. }
  89. static TQByteArray bio2buf(BIO *b)
  90. {
  91. TQByteArray buf;
  92. while(1) {
  93. char block[1024];
  94. int ret = BIO_read(b, block, 1024);
  95. int oldsize = buf.size();
  96. buf.resize(oldsize + ret);
  97. memcpy(buf.data() + oldsize, block, ret);
  98. if(ret != 1024)
  99. break;
  100. }
  101. BIO_free(b);
  102. return buf;
  103. }
  104. class SHA1Context : public TQCA_HashContext
  105. {
  106. public:
  107. SHA1Context()
  108. {
  109. reset();
  110. }
  111. TQCA_HashContext *clone()
  112. {
  113. return new SHA1Context(*this);
  114. }
  115. void reset()
  116. {
  117. SHA1_Init(&c);
  118. }
  119. void update(const char *in, unsigned int len)
  120. {
  121. SHA1_Update(&c, in, len);
  122. }
  123. void final(TQByteArray *out)
  124. {
  125. TQByteArray buf(20);
  126. SHA1_Final((unsigned char *)buf.data(), &c);
  127. *out = buf;
  128. }
  129. SHA_CTX c;
  130. };
  131. class MD5Context : public TQCA_HashContext
  132. {
  133. public:
  134. MD5Context()
  135. {
  136. reset();
  137. }
  138. TQCA_HashContext *clone()
  139. {
  140. return new MD5Context(*this);
  141. }
  142. void reset()
  143. {
  144. MD5_Init(&c);
  145. }
  146. void update(const char *in, unsigned int len)
  147. {
  148. MD5_Update(&c, in, len);
  149. }
  150. void final(TQByteArray *out)
  151. {
  152. TQByteArray buf(16);
  153. MD5_Final((unsigned char *)buf.data(), &c);
  154. *out = buf;
  155. }
  156. MD5_CTX c;
  157. };
  158. class EVPCipherContext : public TQCA_CipherContext
  159. {
  160. public:
  161. EVPCipherContext()
  162. {
  163. type = 0;
  164. }
  165. virtual ~EVPCipherContext()
  166. {
  167. if(type) {
  168. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  169. EVP_CIPHER_CTX_cleanup(c);
  170. OPENSSL_free(c);
  171. #else
  172. EVP_CIPHER_CTX_free(c);
  173. #endif
  174. type = 0;
  175. }
  176. }
  177. TQCA_CipherContext *clone()
  178. {
  179. EVPCipherContext *cc = cloneSelf();
  180. cc->r = r.copy();
  181. return cc;
  182. }
  183. virtual EVPCipherContext *cloneSelf() const=0;
  184. virtual const EVP_CIPHER *getType(int mode) const=0;
  185. int keySize() { return EVP_CIPHER_key_length(getType(TQCA::CBC)); }
  186. int blockSize() { return EVP_CIPHER_block_size(getType(TQCA::CBC)); }
  187. bool generateKey(char *out, int keysize)
  188. {
  189. TQByteArray a;
  190. if(!lib_generateKeyIV(getType(TQCA::CBC), lib_randomArray(128), lib_randomArray(2), &a, 0, keysize))
  191. return false;
  192. memcpy(out, a.data(), a.size());
  193. return true;
  194. }
  195. bool generateIV(char *out)
  196. {
  197. TQByteArray a;
  198. if(!lib_generateKeyIV(getType(TQCA::CBC), lib_randomArray(128), lib_randomArray(2), 0, &a))
  199. return false;
  200. memcpy(out, a.data(), a.size());
  201. return true;
  202. }
  203. bool setup(int _dir, int mode, const char *key, int keysize, const char *iv, bool _pad)
  204. {
  205. dir = _dir;
  206. pad = _pad;
  207. type = getType(mode);
  208. r.resize(0);
  209. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  210. c = (EVP_CIPHER_CTX*)OPENSSL_malloc(sizeof(EVP_CIPHER_CTX));
  211. EVP_CIPHER_CTX_init(c);
  212. #else
  213. c = EVP_CIPHER_CTX_new();
  214. #endif
  215. if(dir == TQCA::Encrypt) {
  216. if(!EVP_EncryptInit(c, type, NULL, NULL))
  217. return false;
  218. if(keysize != EVP_CIPHER_key_length(type))
  219. EVP_CIPHER_CTX_set_key_length(c, keysize);
  220. if(!EVP_EncryptInit(c, NULL, (unsigned char *)key, (unsigned char *)iv))
  221. return false;
  222. }
  223. else {
  224. if(!EVP_DecryptInit(c, type, NULL, NULL))
  225. return false;
  226. if(keysize != EVP_CIPHER_key_length(type))
  227. EVP_CIPHER_CTX_set_key_length(c, keysize);
  228. if(!EVP_DecryptInit(c, NULL, (unsigned char *)key, (unsigned char *)iv))
  229. return false;
  230. }
  231. return true;
  232. }
  233. bool update(const char *in, unsigned int len)
  234. {
  235. TQByteArray result(len + EVP_CIPHER_block_size(type));
  236. int olen;
  237. if(dir == TQCA::Encrypt || !pad) {
  238. if(!EVP_EncryptUpdate(c, (unsigned char *)result.data(), &olen, (unsigned char *)in, len))
  239. return false;
  240. }
  241. else {
  242. if(!EVP_DecryptUpdate(c, (unsigned char *)result.data(), &olen, (unsigned char *)in, len))
  243. return false;
  244. }
  245. result.resize(olen);
  246. appendArray(&r, result);
  247. return true;
  248. }
  249. bool final(TQByteArray *out)
  250. {
  251. if(pad) {
  252. TQByteArray result(EVP_CIPHER_block_size(type));
  253. int olen;
  254. if(dir == TQCA::Encrypt) {
  255. if(!EVP_EncryptFinal(c, (unsigned char *)result.data(), &olen))
  256. return false;
  257. }
  258. else {
  259. if(!EVP_DecryptFinal(c, (unsigned char *)result.data(), &olen))
  260. return false;
  261. }
  262. result.resize(olen);
  263. appendArray(&r, result);
  264. }
  265. *out = r.copy();
  266. r.resize(0);
  267. return true;
  268. }
  269. EVP_CIPHER_CTX *c;
  270. const EVP_CIPHER *type;
  271. TQByteArray r;
  272. int dir;
  273. bool pad;
  274. };
  275. class BlowFishContext : public EVPCipherContext
  276. {
  277. public:
  278. EVPCipherContext *cloneSelf() const { return new BlowFishContext(*this); }
  279. const EVP_CIPHER *getType(int mode) const
  280. {
  281. if(mode == TQCA::CBC)
  282. return EVP_bf_cbc();
  283. else if(mode == TQCA::CFB)
  284. return EVP_bf_cfb();
  285. else
  286. return 0;
  287. }
  288. };
  289. class TripleDESContext : public EVPCipherContext
  290. {
  291. public:
  292. EVPCipherContext *cloneSelf() const { return new TripleDESContext(*this); }
  293. const EVP_CIPHER *getType(int mode) const
  294. {
  295. if(mode == TQCA::CBC)
  296. return EVP_des_ede3_cbc();
  297. else if(mode == TQCA::CFB)
  298. return EVP_des_ede3_cfb();
  299. else
  300. return 0;
  301. }
  302. };
  303. #ifndef NO_AES
  304. class AES128Context : public EVPCipherContext
  305. {
  306. public:
  307. EVPCipherContext *cloneSelf() const { return new AES128Context(*this); }
  308. const EVP_CIPHER *getType(int mode) const
  309. {
  310. if(mode == TQCA::CBC)
  311. return EVP_aes_128_cbc();
  312. else if(mode == TQCA::CFB)
  313. return EVP_aes_128_cfb();
  314. else
  315. return 0;
  316. }
  317. };
  318. class AES256Context : public EVPCipherContext
  319. {
  320. public:
  321. EVPCipherContext *cloneSelf() const { return new AES256Context(*this); }
  322. const EVP_CIPHER *getType(int mode) const
  323. {
  324. if(mode == TQCA::CBC)
  325. return EVP_aes_256_cbc();
  326. else if(mode == TQCA::CFB)
  327. return EVP_aes_256_cfb();
  328. else
  329. return 0;
  330. }
  331. };
  332. #endif
  333. class RSAKeyContext : public TQCA_RSAKeyContext
  334. {
  335. public:
  336. RSAKeyContext()
  337. {
  338. pub = 0;
  339. sec = 0;
  340. }
  341. ~RSAKeyContext()
  342. {
  343. reset();
  344. }
  345. void reset()
  346. {
  347. if(pub) {
  348. RSA_free(pub);
  349. pub = 0;
  350. }
  351. if(sec) {
  352. RSA_free(sec);
  353. sec = 0;
  354. }
  355. }
  356. void separate(RSA *r, RSA **_pub, RSA **_sec)
  357. {
  358. // public
  359. unsigned char *buf, *p;
  360. int len = i2d_RSAPublicKey(r, NULL);
  361. if(len > 0) {
  362. buf = (unsigned char *)malloc(len);
  363. p = buf;
  364. i2d_RSAPublicKey(r, &p);
  365. p = buf;
  366. #ifdef OSSL_097
  367. *_pub = d2i_RSAPublicKey(NULL, (const unsigned char **)&p, len);
  368. #else
  369. *_pub = d2i_RSAPublicKey(NULL, (unsigned char **)&p, len);
  370. #endif
  371. free(buf);
  372. }
  373. len = i2d_RSAPrivateKey(r, NULL);
  374. if(len > 0) {
  375. buf = (unsigned char *)malloc(len);
  376. p = buf;
  377. i2d_RSAPrivateKey(r, &p);
  378. p = buf;
  379. #ifdef OSSL_097
  380. *_sec = d2i_RSAPrivateKey(NULL, (const unsigned char **)&p, len);
  381. #else
  382. *_sec = d2i_RSAPrivateKey(NULL, (unsigned char **)&p, len);
  383. #endif
  384. free(buf);
  385. }
  386. }
  387. bool isNull() const
  388. {
  389. if(!pub && !sec)
  390. return true;
  391. return false;
  392. }
  393. bool havePublic() const
  394. {
  395. return pub ? true : false;
  396. }
  397. bool havePrivate() const
  398. {
  399. return sec ? true : false;
  400. }
  401. bool createFromDER(const char *in, unsigned int len)
  402. {
  403. RSA *r;
  404. void *p;
  405. // private?
  406. p = (void *)in;
  407. #ifdef OSSL_097
  408. r = d2i_RSAPrivateKey(NULL, (const unsigned char **)&p, len);
  409. #else
  410. r = d2i_RSAPrivateKey(NULL, (unsigned char **)&p, len);
  411. #endif
  412. if(r) {
  413. reset();
  414. // private means both, I think, so separate them
  415. separate(r, &pub, &sec);
  416. return true;
  417. }
  418. else {
  419. // public?
  420. p = (void *)in;
  421. #ifdef OSSL_097
  422. r = d2i_RSAPublicKey(NULL, (const unsigned char **)&p, len);
  423. #else
  424. r = d2i_RSAPublicKey(NULL, (unsigned char **)&p, len);
  425. #endif
  426. if(!r) {
  427. // try this other public function, for whatever reason
  428. p = (void *)in;
  429. r = d2i_RSA_PUBKEY(NULL, (const unsigned char **)&p, len);
  430. }
  431. if(r) {
  432. if(pub) {
  433. RSA_free(pub);
  434. }
  435. pub = r;
  436. return true;
  437. }
  438. }
  439. return false;
  440. }
  441. bool createFromPEM(const char *in, unsigned int len)
  442. {
  443. BIO *bi;
  444. // private?
  445. bi = BIO_new(BIO_s_mem());
  446. BIO_write(bi, in, len);
  447. RSA *r = PEM_read_bio_RSAPrivateKey(bi, NULL, NULL, NULL);
  448. BIO_free(bi);
  449. if(r) {
  450. reset();
  451. separate(r, &pub, &sec);
  452. return true;
  453. }
  454. else {
  455. // public?
  456. bi = BIO_new(BIO_s_mem());
  457. BIO_write(bi, in, len);
  458. r = PEM_read_bio_RSAPublicKey(bi, NULL, NULL, NULL);
  459. BIO_free(bi);
  460. if(r) {
  461. if(pub) {
  462. RSA_free(pub);
  463. }
  464. pub = r;
  465. return true;
  466. }
  467. }
  468. return false;
  469. }
  470. bool createFromNative(void *in)
  471. {
  472. reset();
  473. separate((RSA *)in, &pub, &sec);
  474. return true;
  475. }
  476. bool generate(unsigned int bits)
  477. {
  478. BIGNUM *bign = BN_new();
  479. if (BN_set_word(bign, RSA_F4) != 1)
  480. {
  481. BN_free(bign);
  482. return false;
  483. }
  484. RSA *r = RSA_new();
  485. if(!r)
  486. {
  487. BN_free(bign);
  488. return false;
  489. }
  490. RSA_generate_key_ex(r, bits, bign, NULL);
  491. separate(r, &pub, &sec);
  492. RSA_free(r);
  493. BN_free(bign);
  494. return true;
  495. }
  496. TQCA_RSAKeyContext *clone() const
  497. {
  498. // deep copy
  499. RSAKeyContext *c = new RSAKeyContext;
  500. if(pub) {
  501. c->pub = RSAPublicKey_dup(pub);
  502. }
  503. if(sec) {
  504. c->sec = RSAPrivateKey_dup(sec);
  505. }
  506. return c;
  507. }
  508. bool toDER(TQByteArray *out, bool publicOnly)
  509. {
  510. if(sec && !publicOnly) {
  511. int len = i2d_RSAPrivateKey(sec, NULL);
  512. TQByteArray buf(len);
  513. unsigned char *p;
  514. p = (unsigned char *)buf.data();
  515. i2d_RSAPrivateKey(sec, &p);
  516. *out = buf;
  517. return true;
  518. }
  519. else if(pub) {
  520. int len = i2d_RSAPublicKey(pub, NULL);
  521. TQByteArray buf(len);
  522. unsigned char *p;
  523. p = (unsigned char *)buf.data();
  524. i2d_RSAPublicKey(pub, &p);
  525. *out = buf;
  526. return true;
  527. }
  528. else
  529. return false;
  530. }
  531. bool toPEM(TQByteArray *out, bool publicOnly)
  532. {
  533. if(sec && !publicOnly) {
  534. BIO *bo = BIO_new(BIO_s_mem());
  535. PEM_write_bio_RSAPrivateKey(bo, sec, NULL, NULL, 0, NULL, NULL);
  536. *out = bio2buf(bo);
  537. return true;
  538. }
  539. else if(pub) {
  540. BIO *bo = BIO_new(BIO_s_mem());
  541. PEM_write_bio_RSAPublicKey(bo, pub);
  542. *out = bio2buf(bo);
  543. return true;
  544. }
  545. else
  546. return false;
  547. }
  548. bool encrypt(const TQByteArray &in, TQByteArray *out, bool oaep)
  549. {
  550. if(!pub)
  551. return false;
  552. int size = RSA_size(pub);
  553. int flen = in.size();
  554. if(oaep) {
  555. if(flen >= size - 41)
  556. flen = size - 41;
  557. }
  558. else {
  559. if(flen >= size - 11)
  560. flen = size - 11;
  561. }
  562. TQByteArray result(size);
  563. unsigned char *from = (unsigned char *)in.data();
  564. unsigned char *to = (unsigned char *)result.data();
  565. int ret = RSA_public_encrypt(flen, from, to, pub, oaep ? RSA_PKCS1_OAEP_PADDING : RSA_PKCS1_PADDING);
  566. if(ret == -1)
  567. return false;
  568. result.resize(ret);
  569. *out = result;
  570. return true;
  571. }
  572. bool decrypt(const TQByteArray &in, TQByteArray *out, bool oaep)
  573. {
  574. if(!sec)
  575. return false;
  576. int size = RSA_size(sec);
  577. int flen = in.size();
  578. TQByteArray result(size);
  579. unsigned char *from = (unsigned char *)in.data();
  580. unsigned char *to = (unsigned char *)result.data();
  581. int ret = RSA_private_decrypt(flen, from, to, sec, oaep ? RSA_PKCS1_OAEP_PADDING : RSA_PKCS1_PADDING);
  582. if(ret == -1)
  583. return false;
  584. result.resize(ret);
  585. *out = result;
  586. return true;
  587. }
  588. RSA *pub, *sec;
  589. };
  590. static TQValueList<TQCA_CertProperty> nameToProperties(struct X509_name_st *name)
  591. {
  592. TQValueList<TQCA_CertProperty> list;
  593. for(int n = 0; n < X509_NAME_entry_count(name); ++n) {
  594. X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, n);
  595. TQCA_CertProperty p;
  596. ASN1_OBJECT *ao = X509_NAME_ENTRY_get_object(ne);
  597. int nid = OBJ_obj2nid(ao);
  598. if(nid == NID_undef)
  599. continue;
  600. p.var = OBJ_nid2sn(nid);
  601. ASN1_STRING *as = X509_NAME_ENTRY_get_data(ne);
  602. TQCString c;
  603. c.resize(as->length+1);
  604. strncpy(c.data(), (char *)as->data, as->length);
  605. p.val = TQString::fromLatin1(c);
  606. list += p;
  607. }
  608. return list;
  609. }
  610. // (taken from tdelibs) -- Justin
  611. //
  612. // This code is mostly taken from OpenSSL v0.9.5a
  613. // by Eric Young
  614. TQDateTime ASN1_UTCTIME_TQDateTime(ASN1_UTCTIME *tm, int *isGmt)
  615. {
  616. TQDateTime qdt;
  617. char *v;
  618. int gmt=0;
  619. int i;
  620. int y=0,M=0,d=0,h=0,m=0,s=0;
  621. TQDate qdate;
  622. TQTime qtime;
  623. i = tm->length;
  624. v = (char *)tm->data;
  625. if (i < 10) goto auq_err;
  626. if (v[i-1] == 'Z') gmt=1;
  627. for (i=0; i<10; i++)
  628. if ((v[i] > '9') || (v[i] < '0')) goto auq_err;
  629. y = (v[0]-'0')*10+(v[1]-'0');
  630. if (y < 50) y+=100;
  631. M = (v[2]-'0')*10+(v[3]-'0');
  632. if ((M > 12) || (M < 1)) goto auq_err;
  633. d = (v[4]-'0')*10+(v[5]-'0');
  634. h = (v[6]-'0')*10+(v[7]-'0');
  635. m = (v[8]-'0')*10+(v[9]-'0');
  636. if ( (v[10] >= '0') && (v[10] <= '9') &&
  637. (v[11] >= '0') && (v[11] <= '9'))
  638. s = (v[10]-'0')*10+(v[11]-'0');
  639. // localize the date and display it.
  640. qdate.setYMD(y+1900, M, d);
  641. qtime.setHMS(h,m,s);
  642. qdt.setDate(qdate); qdt.setTime(qtime);
  643. auq_err:
  644. if (isGmt) *isGmt = gmt;
  645. return qdt;
  646. }
  647. // (adapted from tdelibs) -- Justin
  648. static bool cnMatchesAddress(const TQString &_cn, const TQString &peerHost)
  649. {
  650. TQString cn = _cn.stripWhiteSpace().lower();
  651. TQRegExp rx;
  652. // Check for invalid characters
  653. if(TQRegExp("[^a-zA-Z0-9\\.\\*\\-]").search(cn) >= 0)
  654. return false;
  655. // Domains can legally end with '.'s. We don't need them though.
  656. while(cn.endsWith("."))
  657. cn.truncate(cn.length()-1);
  658. // Do not let empty CN's get by!!
  659. if(cn.isEmpty())
  660. return false;
  661. // Check for IPv4 address
  662. rx.setPattern("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}");
  663. if(rx.exactMatch(peerHost))
  664. return peerHost == cn;
  665. // Check for IPv6 address here...
  666. rx.setPattern("^\\[.*\\]$");
  667. if(rx.exactMatch(peerHost))
  668. return peerHost == cn;
  669. if(cn.contains('*')) {
  670. // First make sure that there are at least two valid parts
  671. // after the wildcard (*).
  672. TQStringList parts = TQStringList::split('.', cn, false);
  673. while(parts.count() > 2)
  674. parts.remove(parts.begin());
  675. if(parts.count() != 2) {
  676. return false; // we don't allow *.root - that's bad
  677. }
  678. if(parts[0].contains('*') || parts[1].contains('*')) {
  679. return false;
  680. }
  681. // RFC2818 says that *.example.com should match against
  682. // foo.example.com but not bar.foo.example.com
  683. // (ie. they must have the same number of parts)
  684. if(TQRegExp(cn, false, true).exactMatch(peerHost) &&
  685. TQStringList::split('.', cn, false).count() ==
  686. TQStringList::split('.', peerHost, false).count())
  687. return true;
  688. return false;
  689. }
  690. // We must have an exact match in this case (insensitive though)
  691. // (note we already did .lower())
  692. if(cn == peerHost)
  693. return true;
  694. return false;
  695. }
  696. class CertContext : public TQCA_CertContext
  697. {
  698. public:
  699. CertContext()
  700. {
  701. x = 0;
  702. }
  703. ~CertContext()
  704. {
  705. reset();
  706. }
  707. TQCA_CertContext *clone() const
  708. {
  709. CertContext *c = new CertContext(*this);
  710. if(x) {
  711. c->x = X509_dup(x);
  712. }
  713. return c;
  714. }
  715. void reset()
  716. {
  717. if(x) {
  718. X509_free(x);
  719. x = 0;
  720. serial = "";
  721. v_subject = "";
  722. v_issuer = "";
  723. cp_subject.clear();
  724. cp_issuer.clear();
  725. na = TQDateTime();
  726. nb = TQDateTime();
  727. }
  728. }
  729. bool isNull() const
  730. {
  731. return (x ? false: true);
  732. }
  733. bool createFromDER(const char *in, unsigned int len)
  734. {
  735. const unsigned char *p = (const unsigned char *)in;
  736. X509 *t = d2i_X509(NULL, &p, len);
  737. if(!t)
  738. return false;
  739. fromX509(t);
  740. X509_free(t);
  741. return true;
  742. }
  743. bool createFromPEM(const char *in, unsigned int len)
  744. {
  745. BIO *bi = BIO_new(BIO_s_mem());
  746. BIO_write(bi, in, len);
  747. X509 *t = PEM_read_bio_X509(bi, NULL, NULL, NULL);
  748. BIO_free(bi);
  749. if(!t)
  750. return false;
  751. fromX509(t);
  752. X509_free(t);
  753. return true;
  754. }
  755. bool toDER(TQByteArray *out)
  756. {
  757. int len = i2d_X509(x, NULL);
  758. TQByteArray buf(len);
  759. unsigned char *p = (unsigned char *)buf.data();
  760. i2d_X509(x, &p);
  761. *out = buf;
  762. return true;
  763. }
  764. bool toPEM(TQByteArray *out)
  765. {
  766. BIO *bo = BIO_new(BIO_s_mem());
  767. PEM_write_bio_X509(bo, x);
  768. *out = bio2buf(bo);
  769. return true;
  770. }
  771. void fromX509(X509 *t)
  772. {
  773. reset();
  774. x = X509_dup(t);
  775. // serial number
  776. ASN1_INTEGER *ai = X509_get_serialNumber(x);
  777. if(ai) {
  778. char *rep = i2s_ASN1_INTEGER(NULL, ai);
  779. serial = rep;
  780. OPENSSL_free(rep);
  781. }
  782. // validity dates
  783. nb = ASN1_UTCTIME_TQDateTime(X509_get_notBefore(x), NULL);
  784. na = ASN1_UTCTIME_TQDateTime(X509_get_notAfter(x), NULL);
  785. // extract the subject/issuer strings
  786. struct X509_name_st *sn = X509_get_subject_name(x);
  787. struct X509_name_st *in = X509_get_issuer_name(x);
  788. char buf[1024];
  789. X509_NAME_oneline(sn, buf, 1024);
  790. v_subject = buf;
  791. X509_NAME_oneline(in, buf, 1024);
  792. v_issuer = buf;
  793. // extract the subject/issuer contents
  794. cp_subject = nameToProperties(sn);
  795. cp_issuer = nameToProperties(in);
  796. }
  797. TQString serialNumber() const
  798. {
  799. return serial;
  800. }
  801. TQString subjectString() const
  802. {
  803. return v_subject;
  804. }
  805. TQString issuerString() const
  806. {
  807. return v_issuer;
  808. }
  809. TQValueList<TQCA_CertProperty> subject() const
  810. {
  811. return cp_subject;
  812. }
  813. TQValueList<TQCA_CertProperty> issuer() const
  814. {
  815. return cp_issuer;
  816. }
  817. TQDateTime notBefore() const
  818. {
  819. return nb;
  820. }
  821. TQDateTime notAfter() const
  822. {
  823. return na;
  824. }
  825. bool matchesAddress(const TQString &realHost) const
  826. {
  827. TQString peerHost = realHost.stripWhiteSpace();
  828. while(peerHost.endsWith("."))
  829. peerHost.truncate(peerHost.length()-1);
  830. peerHost = peerHost.lower();
  831. TQString cn;
  832. for(TQValueList<TQCA_CertProperty>::ConstIterator it = cp_subject.begin(); it != cp_subject.end(); ++it) {
  833. if((*it).var == "CN") {
  834. cn = (*it).val;
  835. break;
  836. }
  837. }
  838. if(cnMatchesAddress(cn, peerHost))
  839. return true;
  840. return false;
  841. }
  842. X509 *x;
  843. TQString serial, v_subject, v_issuer;
  844. TQValueList<TQCA_CertProperty> cp_subject, cp_issuer;
  845. TQDateTime nb, na;
  846. };
  847. static bool ssl_init = false;
  848. class TLSContext : public TQCA_TLSContext
  849. {
  850. public:
  851. enum { Good, TryAgain, Bad };
  852. enum { Idle, Connect, Accept, Handshake, Active, Closing };
  853. bool serv;
  854. int mode;
  855. TQByteArray sendQueue, recvQueue;
  856. CertContext *cert;
  857. RSAKeyContext *key;
  858. SSL *ssl;
  859. SSL_METHOD *method;
  860. SSL_CTX *context;
  861. BIO *rbio, *wbio;
  862. CertContext cc;
  863. int vr;
  864. bool v_eof;
  865. TLSContext()
  866. {
  867. if(!ssl_init) {
  868. SSL_library_init();
  869. SSL_load_error_strings();
  870. ssl_init = true;
  871. }
  872. ssl = 0;
  873. context = 0;
  874. cert = 0;
  875. key = 0;
  876. }
  877. ~TLSContext()
  878. {
  879. reset();
  880. }
  881. void reset()
  882. {
  883. if(ssl) {
  884. SSL_free(ssl);
  885. ssl = 0;
  886. }
  887. if(context) {
  888. SSL_CTX_free(context);
  889. context = 0;
  890. }
  891. if(cert) {
  892. delete cert;
  893. cert = 0;
  894. }
  895. if(key) {
  896. delete key;
  897. key = 0;
  898. }
  899. sendQueue.resize(0);
  900. recvQueue.resize(0);
  901. mode = Idle;
  902. cc.reset();
  903. vr = TQCA::TLS::Unknown;
  904. v_eof = false;
  905. }
  906. bool eof() const
  907. {
  908. return v_eof;
  909. }
  910. bool startClient(const TQPtrList<TQCA_CertContext> &store, const TQCA_CertContext &_cert, const TQCA_RSAKeyContext &_key)
  911. {
  912. reset();
  913. serv = false;
  914. method = const_cast<SSL_METHOD*>(SSLv23_client_method());
  915. if(!setup(store, _cert, _key))
  916. return false;
  917. mode = Connect;
  918. return true;
  919. }
  920. bool startServer(const TQPtrList<TQCA_CertContext> &store, const TQCA_CertContext &_cert, const TQCA_RSAKeyContext &_key)
  921. {
  922. reset();
  923. serv = true;
  924. method = const_cast<SSL_METHOD*>(SSLv23_server_method());
  925. if(!setup(store, _cert, _key))
  926. return false;
  927. mode = Accept;
  928. return true;
  929. }
  930. bool setup(const TQPtrList<TQCA_CertContext> &list, const TQCA_CertContext &_cc, const TQCA_RSAKeyContext &kc)
  931. {
  932. context = SSL_CTX_new(method);
  933. if(!context) {
  934. reset();
  935. return false;
  936. }
  937. // load the cert store
  938. if(!list.isEmpty()) {
  939. X509_STORE *store = SSL_CTX_get_cert_store(context);
  940. TQPtrListIterator<TQCA_CertContext> it(list);
  941. for(CertContext *i; (i = (CertContext *)it.current()); ++it)
  942. X509_STORE_add_cert(store, i->x);
  943. }
  944. ssl = SSL_new(context);
  945. if(!ssl) {
  946. reset();
  947. return false;
  948. }
  949. SSL_set_ssl_method(ssl, method); // can this return error?
  950. // setup the memory bio
  951. rbio = BIO_new(BIO_s_mem());
  952. wbio = BIO_new(BIO_s_mem());
  953. // this passes control of the bios to ssl. we don't need to free them.
  954. SSL_set_bio(ssl, rbio, wbio);
  955. // setup the cert to send
  956. if(!_cc.isNull() && !kc.isNull()) {
  957. cert = static_cast<CertContext*>(_cc.clone());
  958. key = static_cast<RSAKeyContext*>(kc.clone());
  959. if(SSL_use_certificate(ssl, cert->x) != 1) {
  960. reset();
  961. return false;
  962. }
  963. if(SSL_use_RSAPrivateKey(ssl, key->sec) != 1) {
  964. reset();
  965. return false;
  966. }
  967. }
  968. return true;
  969. }
  970. int handshake(const TQByteArray &in, TQByteArray *out)
  971. {
  972. if(!in.isEmpty())
  973. BIO_write(rbio, in.data(), in.size());
  974. if(mode == Connect) {
  975. int ret = doConnect();
  976. if(ret == Good) {
  977. mode = Handshake;
  978. }
  979. else if(ret == Bad) {
  980. reset();
  981. return Error;
  982. }
  983. }
  984. if(mode == Accept) {
  985. int ret = doAccept();
  986. if(ret == Good) {
  987. getCert();
  988. mode = Active;
  989. }
  990. else if(ret == Bad) {
  991. reset();
  992. return Error;
  993. }
  994. }
  995. if(mode == Handshake) {
  996. int ret = doHandshake();
  997. if(ret == Good) {
  998. getCert();
  999. mode = Active;
  1000. }
  1001. else if(ret == Bad) {
  1002. reset();
  1003. return Error;
  1004. }
  1005. }
  1006. // process outgoing
  1007. *out = readOutgoing();
  1008. if(mode == Active)
  1009. return Success;
  1010. else
  1011. return Continue;
  1012. }
  1013. int shutdown(const TQByteArray &in, TQByteArray *out)
  1014. {
  1015. if(!in.isEmpty())
  1016. BIO_write(rbio, in.data(), in.size());
  1017. int ret = doShutdown();
  1018. if(ret == Bad) {
  1019. reset();
  1020. return Error;
  1021. }
  1022. *out = readOutgoing();
  1023. if(ret == Good) {
  1024. mode = Idle;
  1025. return Success;
  1026. }
  1027. else {
  1028. mode = Closing;
  1029. return Continue;
  1030. }
  1031. }
  1032. void getCert()
  1033. {
  1034. // verify the certificate
  1035. int code = TQCA::TLS::Unknown;
  1036. X509 *x = SSL_get_peer_certificate(ssl);
  1037. if(x) {
  1038. cc.fromX509(x);
  1039. X509_free(x);
  1040. int ret = SSL_get_verify_result(ssl);
  1041. if(ret == X509_V_OK)
  1042. code = TQCA::TLS::Valid;
  1043. else
  1044. code = resultToCV(ret);
  1045. }
  1046. else {
  1047. cc.reset();
  1048. code = TQCA::TLS::NoCert;
  1049. }
  1050. vr = code;
  1051. }
  1052. bool encode(const TQByteArray &plain, TQByteArray *to_net, int *enc)
  1053. {
  1054. if(mode != Active)
  1055. return false;
  1056. appendArray(&sendQueue, plain);
  1057. int encoded = 0;
  1058. if(sendQueue.size() > 0) {
  1059. int ret = SSL_write(ssl, sendQueue.data(), sendQueue.size());
  1060. enum { Good, Continue, Done, Error };
  1061. int m;
  1062. if(ret <= 0) {
  1063. int x = SSL_get_error(ssl, ret);
  1064. if(x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE)
  1065. m = Continue;
  1066. else if(x == SSL_ERROR_ZERO_RETURN)
  1067. m = Done;
  1068. else
  1069. m = Error;
  1070. }
  1071. else {
  1072. m = Good;
  1073. encoded = ret;
  1074. int newsize = sendQueue.size() - encoded;
  1075. char *r = sendQueue.data();
  1076. memmove(r, r + encoded, newsize);
  1077. sendQueue.resize(newsize);
  1078. }
  1079. if(m == Done) {
  1080. sendQueue.resize(0);
  1081. v_eof = true;
  1082. return false;
  1083. }
  1084. if(m == Error) {
  1085. sendQueue.resize(0);
  1086. return false;
  1087. }
  1088. }
  1089. *to_net = readOutgoing();
  1090. *enc = encoded;
  1091. return true;
  1092. }
  1093. bool decode(const TQByteArray &from_net, TQByteArray *plain, TQByteArray *to_net)
  1094. {
  1095. if(mode != Active)
  1096. return false;
  1097. if(!from_net.isEmpty())
  1098. BIO_write(rbio, from_net.data(), from_net.size());
  1099. TQByteArray a;
  1100. while(!v_eof) {
  1101. a.resize(8192);
  1102. int ret = SSL_read(ssl, a.data(), a.size());
  1103. if(ret > 0) {
  1104. if(ret != (int)a.size())
  1105. a.resize(ret);
  1106. appendArray(&recvQueue, a);
  1107. }
  1108. else if(ret <= 0) {
  1109. int x = SSL_get_error(ssl, ret);
  1110. if(x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE)
  1111. break;
  1112. else if(x == SSL_ERROR_ZERO_RETURN)
  1113. v_eof = true;
  1114. else
  1115. return false;
  1116. }
  1117. }
  1118. *plain = recvQueue.copy();
  1119. recvQueue.resize(0);
  1120. // could be outgoing data also
  1121. *to_net = readOutgoing();
  1122. return true;
  1123. }
  1124. TQByteArray unprocessed()
  1125. {
  1126. TQByteArray a;
  1127. int size = BIO_pending(rbio);
  1128. if(size <= 0)
  1129. return a;
  1130. a.resize(size);
  1131. int r = BIO_read(rbio, a.data(), size);
  1132. if(r <= 0) {
  1133. a.resize(0);
  1134. return a;
  1135. }
  1136. if(r != size)
  1137. a.resize(r);
  1138. return a;
  1139. }
  1140. TQByteArray readOutgoing()
  1141. {
  1142. TQByteArray a;
  1143. int size = BIO_pending(wbio);
  1144. if(size <= 0)
  1145. return a;
  1146. a.resize(size);
  1147. int r = BIO_read(wbio, a.data(), size);
  1148. if(r <= 0) {
  1149. a.resize(0);
  1150. return a;
  1151. }
  1152. if(r != size)
  1153. a.resize(r);
  1154. return a;
  1155. }
  1156. int doConnect()
  1157. {
  1158. int ret = SSL_connect(ssl);
  1159. if(ret < 0) {
  1160. int x = SSL_get_error(ssl, ret);
  1161. if(x == SSL_ERROR_WANT_CONNECT || x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE)
  1162. return TryAgain;
  1163. else
  1164. return Bad;
  1165. }
  1166. else if(ret == 0)
  1167. return Bad;
  1168. return Good;
  1169. }
  1170. int doAccept()
  1171. {
  1172. int ret = SSL_accept(ssl);
  1173. if(ret < 0) {
  1174. int x = SSL_get_error(ssl, ret);
  1175. if(x == SSL_ERROR_WANT_CONNECT || x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE)
  1176. return TryAgain;
  1177. else
  1178. return Bad;
  1179. }
  1180. else if(ret == 0)
  1181. return Bad;
  1182. return Good;
  1183. }
  1184. int doHandshake()
  1185. {
  1186. int ret = SSL_do_handshake(ssl);
  1187. if(ret < 0) {
  1188. int x = SSL_get_error(ssl, ret);
  1189. if(x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE)
  1190. return TryAgain;
  1191. else
  1192. return Bad;
  1193. }
  1194. else if(ret == 0)
  1195. return Bad;
  1196. return Good;
  1197. }
  1198. int doShutdown()
  1199. {
  1200. int ret = SSL_shutdown(ssl);
  1201. if(ret >= 1)
  1202. return Good;
  1203. else {
  1204. if(ret == 0)
  1205. return TryAgain;
  1206. int x = SSL_get_error(ssl, ret);
  1207. if(x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE)
  1208. return TryAgain;
  1209. return Bad;
  1210. }
  1211. }
  1212. TQCA_CertContext *peerCertificate() const
  1213. {
  1214. return cc.clone();
  1215. }
  1216. int validityResult() const
  1217. {
  1218. return vr;
  1219. }
  1220. int resultToCV(int ret) const
  1221. {
  1222. int rc;
  1223. switch(ret) {
  1224. case X509_V_ERR_CERT_REJECTED:
  1225. rc = TQCA::TLS::Rejected;
  1226. break;
  1227. case X509_V_ERR_CERT_UNTRUSTED:
  1228. rc = TQCA::TLS::Untrusted;
  1229. break;
  1230. case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
  1231. case X509_V_ERR_CERT_SIGNATURE_FAILURE:
  1232. case X509_V_ERR_CRL_SIGNATURE_FAILURE:
  1233. case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
  1234. case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
  1235. rc = TQCA::TLS::SignatureFailed;
  1236. break;
  1237. case X509_V_ERR_INVALID_CA:
  1238. case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
  1239. case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
  1240. case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
  1241. rc = TQCA::TLS::InvalidCA;
  1242. break;
  1243. case X509_V_ERR_INVALID_PURPOSE:
  1244. rc = TQCA::TLS::InvalidPurpose;
  1245. break;
  1246. case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
  1247. case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
  1248. rc = TQCA::TLS::SelfSigned;
  1249. break;
  1250. case X509_V_ERR_CERT_REVOKED:
  1251. rc = TQCA::TLS::Revoked;
  1252. break;
  1253. case X509_V_ERR_PATH_LENGTH_EXCEEDED:
  1254. rc = TQCA::TLS::PathLengthExceeded;
  1255. break;
  1256. case X509_V_ERR_CERT_NOT_YET_VALID:
  1257. case X509_V_ERR_CERT_HAS_EXPIRED:
  1258. case X509_V_ERR_CRL_NOT_YET_VALID:
  1259. case X509_V_ERR_CRL_HAS_EXPIRED:
  1260. case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
  1261. case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
  1262. case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
  1263. case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
  1264. rc = TQCA::TLS::Expired;
  1265. break;
  1266. case X509_V_ERR_APPLICATION_VERIFICATION:
  1267. case X509_V_ERR_OUT_OF_MEM:
  1268. case X509_V_ERR_UNABLE_TO_GET_CRL:
  1269. case X509_V_ERR_CERT_CHAIN_TOO_LONG:
  1270. default:
  1271. rc = TQCA::TLS::Unknown;
  1272. break;
  1273. }
  1274. return rc;
  1275. }
  1276. };
  1277. class TQCAOpenSSL : public TQCAProvider
  1278. {
  1279. public:
  1280. TQCAOpenSSL() {}
  1281. ~TQCAOpenSSL() {}
  1282. void init()
  1283. {
  1284. }
  1285. int qcaVersion() const
  1286. {
  1287. return TQCA_PLUGIN_VERSION;
  1288. }
  1289. int capabilities() const
  1290. {
  1291. int caps =
  1292. TQCA::CAP_SHA1 |
  1293. TQCA::CAP_MD5 |
  1294. TQCA::CAP_BlowFish |
  1295. TQCA::CAP_TripleDES |
  1296. #ifndef NO_AES
  1297. TQCA::CAP_AES128 |
  1298. TQCA::CAP_AES256 |
  1299. #endif
  1300. TQCA::CAP_RSA |
  1301. TQCA::CAP_X509 |
  1302. TQCA::CAP_TLS;
  1303. return caps;
  1304. }
  1305. void *context(int cap)
  1306. {
  1307. if(cap == TQCA::CAP_SHA1)
  1308. return new SHA1Context;
  1309. else if(cap == TQCA::CAP_MD5)
  1310. return new MD5Context;
  1311. else if(cap == TQCA::CAP_BlowFish)
  1312. return new BlowFishContext;
  1313. else if(cap == TQCA::CAP_TripleDES)
  1314. return new TripleDESContext;
  1315. #ifndef NO_AES
  1316. else if(cap == TQCA::CAP_AES128)
  1317. return new AES128Context;
  1318. else if(cap == TQCA::CAP_AES256)
  1319. return new AES256Context;
  1320. #endif
  1321. else if(cap == TQCA::CAP_RSA)
  1322. return new RSAKeyContext;
  1323. else if(cap == TQCA::CAP_X509)
  1324. return new CertContext;
  1325. else if(cap == TQCA::CAP_TLS)
  1326. return new TLSContext;
  1327. return 0;
  1328. }
  1329. };
  1330. #ifdef TQCA_PLUGIN
  1331. TQCAProvider *createProvider()
  1332. #else
  1333. TQCAProvider *createProviderTLS()
  1334. #endif
  1335. {
  1336. return (new TQCAOpenSSL);
  1337. }