BBS2chProxySecureSocket.cpp 13 KB

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