TLS plugin for the TQt Cryptographic Architecture
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

1515 lines
30 KiB

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