BBS2chProxySecureSocket.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. #ifdef USE_MITM
  2. #include <stdexcept>
  3. #include <stdio.h>
  4. #include <unistd.h>
  5. #include <string.h>
  6. #ifdef USE_GNUTLS
  7. #include <gnutls/x509.h>
  8. #include <gnutls/crypto.h>
  9. #else
  10. #include <openssl/pem.h>
  11. #include <openssl/x509v3.h>
  12. #include <openssl/err.h>
  13. #endif
  14. #ifdef _WIN32
  15. #include <winsock2.h>
  16. #include <windows.h>
  17. #define CLOSESOCKET(x) closesocket(x)
  18. #define SHUT_RDWR SD_BOTH
  19. #else
  20. #define CLOSESOCKET(x) ::close(x)
  21. #endif
  22. #include "BBS2chProxySecureSocket.h"
  23. #ifdef USE_GNUTLS
  24. static gnutls_x509_crt_t ca_cert;
  25. static gnutls_x509_privkey_t ca_privkey;
  26. static gnutls_x509_privkey_t server_privkey;
  27. static gnutls_priority_t priority;
  28. int BBS2chProxySecureSocket::initializeCerts(const char *certPath, const char *keyPath)
  29. {
  30. static int initialized;
  31. if (initialized) return 0;
  32. gnutls_global_init();
  33. gnutls_datum_t data;
  34. int ret = gnutls_load_file(certPath, &data);
  35. if (ret < 0) {
  36. fprintf(stderr, "Unable to open CA certificate from %s\n", certPath);
  37. return -1;
  38. }
  39. gnutls_x509_crt_init(&ca_cert);
  40. ret = gnutls_x509_crt_import(ca_cert, &data, GNUTLS_X509_FMT_PEM);
  41. if (ret < 0) {
  42. fprintf(stderr, "Error loading CA certificate: %s\n", gnutls_strerror(ret));
  43. return -1;
  44. }
  45. gnutls_free(data.data);
  46. ret = gnutls_load_file(keyPath, &data);
  47. if (ret < 0) {
  48. fprintf(stderr, "Unable to open CA private key from %s\n", keyPath);
  49. return -1;
  50. }
  51. gnutls_x509_privkey_init(&ca_privkey);
  52. ret = gnutls_x509_privkey_import(ca_privkey, &data, GNUTLS_X509_FMT_PEM);
  53. if (ret < 0) {
  54. fprintf(stderr, "Error loading CA private key: %s\n", gnutls_strerror(ret));
  55. return -1;
  56. }
  57. gnutls_free(data.data);
  58. gnutls_x509_privkey_init(&server_privkey);
  59. gnutls_x509_privkey_generate(server_privkey, GNUTLS_PK_RSA, 2048, 0);
  60. gnutls_priority_init(&priority, NULL, NULL);
  61. initialized = 1;
  62. return 0;
  63. }
  64. void BBS2chProxySecureSocket::generateAndPrintSelfSignedCertificate(void)
  65. {
  66. unsigned char tmp[4096];
  67. size_t bufsize = 4096;
  68. time_t now = time(NULL);
  69. unsigned long long serial;
  70. gnutls_x509_crt_t cert;
  71. gnutls_x509_privkey_t key;
  72. gnutls_global_init();
  73. gnutls_rnd(GNUTLS_RND_NONCE, &serial, sizeof(serial));
  74. gnutls_x509_privkey_init(&key);
  75. gnutls_x509_privkey_generate(key, GNUTLS_PK_RSA, 2048, 0);
  76. gnutls_x509_crt_init(&cert);
  77. gnutls_x509_crt_set_version(cert, 3);
  78. gnutls_x509_crt_set_ca_status(cert, 1);
  79. gnutls_x509_crt_set_activation_time(cert, now);
  80. gnutls_x509_crt_set_expiration_time(cert, now + 31536000*3);
  81. gnutls_x509_crt_set_dn_by_oid(cert, GNUTLS_OID_X520_COUNTRY_NAME, 0, "JP", strlen("JP"));
  82. gnutls_x509_crt_set_dn_by_oid(cert, GNUTLS_OID_X520_ORGANIZATION_NAME, 0, "proxy2ch certificate generator", strlen("proxy2ch certificate generator"));
  83. gnutls_x509_crt_set_dn_by_oid(cert, GNUTLS_OID_X520_COMMON_NAME, 0, "proxy2ch", strlen("proxy2ch"));
  84. gnutls_x509_crt_set_serial(cert, &serial, sizeof(serial));
  85. gnutls_x509_crt_set_key(cert, key);
  86. gnutls_x509_crt_set_key_purpose_oid(cert, GNUTLS_KP_TLS_WWW_SERVER, 0);
  87. gnutls_x509_crt_set_key_purpose_oid(cert, GNUTLS_KP_TLS_WWW_CLIENT, 0);
  88. gnutls_x509_crt_set_key_usage(cert, GNUTLS_KEY_DIGITAL_SIGNATURE|GNUTLS_KEY_KEY_CERT_SIGN|GNUTLS_KEY_CRL_SIGN);
  89. gnutls_x509_crt_get_key_id(cert, 0, tmp, &bufsize);
  90. gnutls_x509_crt_set_subject_key_id(cert, tmp, bufsize);
  91. gnutls_x509_crt_sign2(cert, cert, key, GNUTLS_DIG_SHA256, 0);
  92. bufsize = 4096;
  93. gnutls_x509_crt_export(cert, GNUTLS_X509_FMT_PEM, tmp, &bufsize);
  94. fwrite(tmp, 1, bufsize, stdout);
  95. bufsize = 4096;
  96. gnutls_x509_privkey_export(key, GNUTLS_X509_FMT_PEM, tmp, &bufsize);
  97. fwrite(tmp, 1, bufsize, stdout);
  98. fflush(stdout);
  99. gnutls_x509_privkey_deinit(key);
  100. gnutls_x509_crt_deinit(cert);
  101. }
  102. BBS2chProxySecureSocket::BBS2chProxySecureSocket(int sock, const char *host) :
  103. socket(sock), session(NULL), x509_cred(NULL)
  104. {
  105. bool hostIsDomain = false;
  106. for (int i=strlen(host)-1; i>=0; i--) {
  107. if (host[i] != '.' && !(host[i] >= '0' && host[i] <= '9')) {
  108. hostIsDomain = true;
  109. break;
  110. }
  111. }
  112. unsigned char tmp[4096];
  113. size_t bufsize = 4096;
  114. time_t now = time(NULL);
  115. unsigned long long serial;
  116. gnutls_x509_crt_t cert;
  117. gnutls_rnd(GNUTLS_RND_NONCE, &serial, sizeof(serial));
  118. gnutls_x509_crt_init(&cert);
  119. gnutls_x509_crt_set_version(cert, 3);
  120. gnutls_x509_crt_set_ca_status(cert, 0);
  121. gnutls_x509_crt_set_activation_time(cert, now - 600);
  122. gnutls_x509_crt_set_expiration_time(cert, now + 31536000);
  123. gnutls_x509_crt_set_dn_by_oid(cert, GNUTLS_OID_X520_COUNTRY_NAME, 0, "JP", strlen("JP"));
  124. gnutls_x509_crt_set_dn_by_oid(cert, GNUTLS_OID_X520_ORGANIZATION_NAME, 0, "proxy2ch", strlen("proxy2ch"));
  125. gnutls_x509_crt_set_dn_by_oid(cert, GNUTLS_OID_X520_COMMON_NAME, 0, host, strlen(host));
  126. gnutls_x509_crt_set_serial(cert, &serial, sizeof(serial));
  127. gnutls_x509_crt_set_key(cert, server_privkey);
  128. gnutls_x509_crt_set_key_purpose_oid(cert, GNUTLS_KP_TLS_WWW_SERVER, 0);
  129. gnutls_x509_crt_set_key_purpose_oid(cert, GNUTLS_KP_TLS_WWW_CLIENT, 0);
  130. gnutls_x509_crt_set_key_usage(cert, GNUTLS_KEY_DIGITAL_SIGNATURE|GNUTLS_KEY_KEY_ENCIPHERMENT);
  131. gnutls_x509_crt_get_key_id(cert, 0, tmp, &bufsize);
  132. gnutls_x509_crt_set_subject_key_id(cert, tmp, bufsize);
  133. gnutls_x509_crt_set_subject_alt_name(cert, hostIsDomain ? GNUTLS_SAN_DNSNAME : GNUTLS_SAN_IPADDRESS, host, strlen(host), GNUTLS_FSAN_APPEND);
  134. gnutls_x509_crt_set_subject_alt_name(cert, GNUTLS_SAN_DNSNAME, "*.5ch.net", strlen("*.5ch.net"), GNUTLS_FSAN_APPEND);
  135. gnutls_x509_crt_set_subject_alt_name(cert, GNUTLS_SAN_DNSNAME, "*.2ch.net", strlen("*.2ch.net"), GNUTLS_FSAN_APPEND);
  136. gnutls_x509_crt_set_subject_alt_name(cert, GNUTLS_SAN_DNSNAME, "*.bbspink.com", strlen("*.bbspink.com"), GNUTLS_FSAN_APPEND);
  137. gnutls_x509_crt_sign2(cert, ca_cert, ca_privkey, GNUTLS_DIG_SHA256, 0);
  138. gnutls_certificate_allocate_credentials(&x509_cred);
  139. gnutls_certificate_set_x509_key(x509_cred, &cert, 1, server_privkey);
  140. gnutls_x509_crt_deinit(cert);
  141. #if GNUTLS_VERSION_NUMBER >= 0x030506
  142. gnutls_certificate_set_known_dh_params(x509_cred, GNUTLS_SEC_PARAM_MEDIUM);
  143. #endif
  144. int ret = gnutls_init(&session, GNUTLS_SERVER);
  145. if (ret < 0) {
  146. gnutls_certificate_free_credentials(x509_cred);
  147. std::string str("Unable to create GnuTLS session: ");
  148. str += gnutls_strerror(ret);
  149. throw std::runtime_error(str);
  150. }
  151. gnutls_priority_set(session, priority);
  152. ret = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, x509_cred);
  153. if (ret < 0) {
  154. gnutls_deinit(session);
  155. gnutls_certificate_free_credentials(x509_cred);
  156. std::string str("Unable to set server credentials: ");
  157. str += gnutls_strerror(ret);
  158. throw std::runtime_error(str);
  159. }
  160. gnutls_certificate_server_set_request(session, GNUTLS_CERT_IGNORE);
  161. gnutls_handshake_set_timeout(session, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
  162. gnutls_transport_set_int(session, sock);
  163. ret = gnutls_handshake(session);
  164. if (ret < 0) {
  165. gnutls_deinit(session);
  166. gnutls_certificate_free_credentials(x509_cred);
  167. std::string str("Unable to establish SSL/TLS connection: ");
  168. str += gnutls_strerror(ret);
  169. throw std::runtime_error(str);
  170. }
  171. }
  172. #else
  173. static X509 *ca_cert;
  174. static EVP_PKEY *ca_privkey;
  175. static EVP_PKEY *server_privkey;
  176. static int add_ext(X509 *cert, int nid, const char *value)
  177. {
  178. X509_EXTENSION *ex;
  179. X509V3_CTX ctx;
  180. X509V3_set_ctx_nodb(&ctx);
  181. X509V3_set_ctx(&ctx, cert, cert, NULL, NULL, 0);
  182. ex = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
  183. if (!ex)
  184. return 0;
  185. X509_add_ext(cert,ex,-1);
  186. X509_EXTENSION_free(ex);
  187. return 1;
  188. }
  189. int BBS2chProxySecureSocket::initializeCerts(const char *certPath, const char *keyPath)
  190. {
  191. static int initialized;
  192. if (initialized) return 0;
  193. FILE *fp = fopen(certPath, "rb");
  194. if (!fp) {
  195. fprintf(stderr, "Unable to open CA certificate from %s\n", certPath);
  196. return -1;
  197. }
  198. ca_cert = PEM_read_X509(fp, NULL, NULL, NULL);
  199. if (!ca_cert) {
  200. fprintf(stderr, "Error loading CA certificate: ");
  201. ERR_print_errors_fp(stderr);
  202. return -1;
  203. }
  204. fclose(fp);
  205. fp = fopen(keyPath, "rb");
  206. if (!fp) {
  207. fprintf(stderr, "Unable to open CA private key from %s\n", keyPath);
  208. return -1;
  209. }
  210. ca_privkey = PEM_read_PrivateKey(fp, NULL, NULL, NULL);
  211. if (!ca_privkey) {
  212. fprintf(stderr, "Error loading CA private key: ");
  213. ERR_print_errors_fp(stderr);
  214. return -1;
  215. }
  216. fclose(fp);
  217. server_privkey = EVP_PKEY_new();
  218. BIGNUM *bn = BN_new();
  219. BN_set_word(bn, RSA_F4);
  220. RSA *rsa = RSA_new();
  221. RSA_generate_key_ex(rsa, 2048, bn, NULL);
  222. EVP_PKEY_assign_RSA(server_privkey, rsa);
  223. BN_free(bn);
  224. initialized = 1;
  225. return 0;
  226. }
  227. void BBS2chProxySecureSocket::generateAndPrintSelfSignedCertificate(void)
  228. {
  229. EVP_PKEY *key = EVP_PKEY_new();
  230. BIGNUM *bn = BN_new();
  231. BN_set_word(bn, RSA_F4);
  232. RSA *rsa = RSA_new();
  233. RSA_generate_key_ex(rsa, 2048, bn, NULL);
  234. EVP_PKEY_assign_RSA(key, rsa);
  235. BN_free(bn);
  236. X509 *cert = X509_new();
  237. X509_set_version(cert, 2);
  238. ASN1_INTEGER *serial = ASN1_INTEGER_new();
  239. bn = BN_new();
  240. BN_rand(bn, 64, 0, 0);
  241. BN_to_ASN1_INTEGER(bn, serial);
  242. X509_set_serialNumber(cert, serial);
  243. ASN1_INTEGER_free(serial);
  244. BN_free(bn);
  245. X509_name_st *name = X509_get_subject_name(cert);
  246. X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned char *)"JP", -1, -1, 0);
  247. X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, (unsigned char *)"proxy2ch certificate generator", -1, -1, 0);
  248. X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned char *)"proxy2ch", -1, -1, 0);
  249. X509_set_subject_name(cert, name);
  250. X509_set_issuer_name(cert, name);
  251. X509_set_pubkey(cert, key);
  252. X509_gmtime_adj(X509_get_notBefore(cert), 0);
  253. X509_gmtime_adj(X509_get_notAfter(cert), 31536000*3);
  254. add_ext(cert, NID_basic_constraints, "critical,CA:TRUE");
  255. add_ext(cert, NID_key_usage, "critical,digitalSignature,keyCertSign,cRLSign");
  256. add_ext(cert, NID_ext_key_usage, "serverAuth,clientAuth");
  257. add_ext(cert, NID_subject_key_identifier, "hash");
  258. X509_sign(cert, key, EVP_sha256());
  259. PEM_write_X509(stdout, cert);
  260. PEM_write_PrivateKey(stdout, key, NULL, NULL, 0, NULL, NULL);
  261. X509_free(cert);
  262. EVP_PKEY_free(key);
  263. }
  264. BBS2chProxySecureSocket::BBS2chProxySecureSocket(int sock, const char *host) :
  265. socket(sock), ctx(NULL), ssl(NULL)
  266. {
  267. bool hostIsDomain = false;
  268. for (int i=strlen(host)-1; i>=0; i--) {
  269. if (host[i] != '.' && !(host[i] >= '0' && host[i] <= '9')) {
  270. hostIsDomain = true;
  271. break;
  272. }
  273. }
  274. X509 *cert = X509_new();
  275. X509_set_version(cert, 2);
  276. ASN1_INTEGER *serial = ASN1_INTEGER_new();
  277. BIGNUM *bn = BN_new();
  278. BN_rand(bn, 64, 0, 0);
  279. BN_to_ASN1_INTEGER(bn, serial);
  280. X509_set_serialNumber(cert, serial);
  281. ASN1_INTEGER_free(serial);
  282. BN_free(bn);
  283. X509_name_st *name = X509_get_subject_name(cert);
  284. X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned char *)"JP", -1, -1, 0);
  285. X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, (unsigned char *)"proxy2ch", -1, -1, 0);
  286. X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned char *)host, -1, -1, 0);
  287. X509_set_subject_name(cert, name);
  288. X509_set_issuer_name(cert, X509_get_subject_name(ca_cert));
  289. X509_set_pubkey(cert, server_privkey);
  290. X509_gmtime_adj(X509_get_notBefore(cert), -600);
  291. X509_gmtime_adj(X509_get_notAfter(cert), 31536000);
  292. add_ext(cert, NID_basic_constraints, "critical,CA:FALSE");
  293. add_ext(cert, NID_key_usage, "critical,digitalSignature,keyEncipherment");
  294. add_ext(cert, NID_ext_key_usage, "serverAuth,clientAuth");
  295. add_ext(cert, NID_subject_key_identifier, "hash");
  296. std::string sni(hostIsDomain ? "DNS:" : "IP:");
  297. sni += host;
  298. sni += ",DNS:*.5ch.net,DNS:*.2ch.net,DNS:*.bbspink.com";
  299. add_ext(cert, NID_subject_alt_name, sni.c_str());
  300. X509_sign(cert, ca_privkey, EVP_sha256());
  301. ctx = SSL_CTX_new(TLS_server_method());
  302. if (!ctx) {
  303. X509_free(cert);
  304. throw std::runtime_error("Unable to create SSL context");
  305. }
  306. if (SSL_CTX_use_certificate(ctx, cert) <= 0) {
  307. fprintf(stderr, "Unable to load server certificate\n");
  308. }
  309. if (SSL_CTX_use_PrivateKey(ctx, server_privkey) <= 0) {
  310. fprintf(stderr, "Unable to load server private key\n");
  311. }
  312. X509_free(cert);
  313. ssl = SSL_new(ctx);
  314. SSL_set_fd(ssl, socket);
  315. if (SSL_accept(ssl) <= 0) {
  316. char errbuf[256];
  317. ERR_error_string_n(ERR_get_error(), errbuf, 256);
  318. SSL_free(ssl);
  319. SSL_CTX_free(ctx);
  320. std::string str("Unable to establish SSL/TLS connection: ");
  321. str += errbuf;
  322. throw std::runtime_error(str);
  323. }
  324. }
  325. #endif
  326. BBS2chProxySecureSocket::~BBS2chProxySecureSocket()
  327. {
  328. }
  329. int BBS2chProxySecureSocket::read(char *buffer, int length)
  330. {
  331. #ifdef USE_GNUTLS
  332. return gnutls_record_recv(session, buffer, length);
  333. #else
  334. return SSL_read(ssl, buffer, length);
  335. #endif
  336. }
  337. int BBS2chProxySecureSocket::readLine(char *buffer, int maxLength)
  338. {
  339. char *ptr = buffer;
  340. while (ptr < buffer + maxLength - 1) {
  341. #ifdef USE_GNUTLS
  342. int read = gnutls_record_recv(session, ptr, 1);
  343. #else
  344. int read = SSL_read(ssl, ptr, 1);
  345. #endif
  346. if (read != 1) {
  347. return 0;
  348. }
  349. if (*ptr++ == '\n') {
  350. break;
  351. }
  352. }
  353. *ptr = 0;
  354. return 1;
  355. }
  356. int BBS2chProxySecureSocket::write(const char *buffer, int length)
  357. {
  358. #ifdef USE_GNUTLS
  359. int sent = 0;
  360. while (length > 0) {
  361. int ret = gnutls_record_send(session, buffer+sent, length);
  362. if (ret <= 0) break;
  363. sent += ret;
  364. length -= ret;
  365. }
  366. return sent;
  367. #else
  368. return SSL_write(ssl, buffer, length);
  369. #endif
  370. }
  371. int BBS2chProxySecureSocket::writeString(const std::string &str)
  372. {
  373. #ifdef USE_GNUTLS
  374. return write(str.data(), str.length());
  375. #else
  376. return SSL_write(ssl, str.data(), str.length());
  377. #endif
  378. }
  379. void BBS2chProxySecureSocket::close(void)
  380. {
  381. #ifdef USE_GNUTLS
  382. if (socket >= 0) {
  383. gnutls_bye(session, GNUTLS_SHUT_WR);
  384. #ifdef _WIN32
  385. Sleep(10);
  386. #else
  387. usleep(10000);
  388. #endif
  389. CLOSESOCKET(socket);
  390. socket = -1;
  391. }
  392. if (session) {
  393. gnutls_deinit(session);
  394. session = NULL;
  395. }
  396. if (x509_cred) {
  397. gnutls_certificate_free_credentials(x509_cred);
  398. x509_cred = NULL;
  399. }
  400. #else
  401. if (ssl) {
  402. SSL_shutdown(ssl);
  403. SSL_free(ssl);
  404. ssl = NULL;
  405. #ifdef _WIN32
  406. Sleep(10);
  407. #else
  408. usleep(10000);
  409. #endif
  410. }
  411. if (socket >= 0) {
  412. CLOSESOCKET(socket);
  413. socket = -1;
  414. }
  415. if (ctx) {
  416. SSL_CTX_free(ctx);
  417. ctx = NULL;
  418. }
  419. #endif
  420. }
  421. #endif