123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494 |
- #ifdef USE_MITM
- #include <stdexcept>
- #include <stdio.h>
- #include <unistd.h>
- #include <string.h>
- #ifdef USE_GNUTLS
- #include <gnutls/x509.h>
- #include <gnutls/crypto.h>
- #else
- #include <openssl/pem.h>
- #include <openssl/x509v3.h>
- #include <openssl/err.h>
- #endif
- #ifdef _WIN32
- #include <winsock2.h>
- #include <windows.h>
- #define CLOSESOCKET(x) closesocket(x)
- #define SHUT_RDWR SD_BOTH
- #else
- #define CLOSESOCKET(x) ::close(x)
- #endif
- #include "BBS2chProxySecureSocket.h"
- #ifdef USE_GNUTLS
- static gnutls_x509_crt_t ca_cert;
- static gnutls_x509_privkey_t ca_privkey;
- static gnutls_x509_privkey_t server_privkey;
- static gnutls_priority_t priority;
- int BBS2chProxySecureSocket::initializeCerts(const char *certPath, const char *keyPath)
- {
- static int initialized;
- if (initialized) return 0;
- gnutls_global_init();
- gnutls_datum_t data;
- int ret = gnutls_load_file(certPath, &data);
- if (ret < 0) {
- fprintf(stderr, "Unable to open CA certificate from %s\n", certPath);
- return -1;
- }
- gnutls_x509_crt_init(&ca_cert);
- ret = gnutls_x509_crt_import(ca_cert, &data, GNUTLS_X509_FMT_PEM);
- if (ret < 0) {
- fprintf(stderr, "Error loading CA certificate: %s\n", gnutls_strerror(ret));
- return -1;
- }
- gnutls_free(data.data);
- ret = gnutls_load_file(keyPath, &data);
- if (ret < 0) {
- fprintf(stderr, "Unable to open CA private key from %s\n", keyPath);
- return -1;
- }
- gnutls_x509_privkey_init(&ca_privkey);
- ret = gnutls_x509_privkey_import(ca_privkey, &data, GNUTLS_X509_FMT_PEM);
- if (ret < 0) {
- fprintf(stderr, "Error loading CA private key: %s\n", gnutls_strerror(ret));
- return -1;
- }
- gnutls_free(data.data);
- gnutls_x509_privkey_init(&server_privkey);
- #ifdef USE_ECDSA_KEY
- gnutls_x509_privkey_generate(server_privkey, GNUTLS_PK_EC, GNUTLS_CURVE_TO_BITS(GNUTLS_ECC_CURVE_SECP256R1), 0);
- #else
- gnutls_x509_privkey_generate(server_privkey, GNUTLS_PK_RSA, 2048, 0);
- #endif
- gnutls_priority_init(&priority, NULL, NULL);
- initialized = 1;
- return 0;
- }
- void BBS2chProxySecureSocket::generateAndPrintSelfSignedCertificate(void)
- {
- unsigned char tmp[4096];
- size_t bufsize = 4096;
- time_t now = time(NULL);
- unsigned long long serial;
- gnutls_x509_crt_t cert;
- gnutls_x509_privkey_t key;
- gnutls_global_init();
- gnutls_rnd(GNUTLS_RND_NONCE, &serial, sizeof(serial));
- gnutls_x509_privkey_init(&key);
- #ifdef USE_ECDSA_KEY
- gnutls_x509_privkey_generate(key, GNUTLS_PK_EC, GNUTLS_CURVE_TO_BITS(GNUTLS_ECC_CURVE_SECP256R1), 0);
- #else
- gnutls_x509_privkey_generate(key, GNUTLS_PK_RSA, 2048, 0);
- #endif
- gnutls_x509_crt_init(&cert);
- gnutls_x509_crt_set_version(cert, 3);
- gnutls_x509_crt_set_ca_status(cert, 1);
- gnutls_x509_crt_set_activation_time(cert, now);
- gnutls_x509_crt_set_expiration_time(cert, now + 31536000*3);
- gnutls_x509_crt_set_dn_by_oid(cert, GNUTLS_OID_X520_COUNTRY_NAME, 0, "JP", strlen("JP"));
- gnutls_x509_crt_set_dn_by_oid(cert, GNUTLS_OID_X520_ORGANIZATION_NAME, 0, "proxy2ch certificate generator", strlen("proxy2ch certificate generator"));
- gnutls_x509_crt_set_dn_by_oid(cert, GNUTLS_OID_X520_COMMON_NAME, 0, "proxy2ch", strlen("proxy2ch"));
- gnutls_x509_crt_set_serial(cert, &serial, sizeof(serial));
- gnutls_x509_crt_set_key(cert, key);
- gnutls_x509_crt_set_key_purpose_oid(cert, GNUTLS_KP_TLS_WWW_SERVER, 0);
- gnutls_x509_crt_set_key_purpose_oid(cert, GNUTLS_KP_TLS_WWW_CLIENT, 0);
- gnutls_x509_crt_set_key_usage(cert, GNUTLS_KEY_DIGITAL_SIGNATURE|GNUTLS_KEY_KEY_CERT_SIGN|GNUTLS_KEY_CRL_SIGN);
- gnutls_x509_crt_get_key_id(cert, 0, tmp, &bufsize);
- gnutls_x509_crt_set_subject_key_id(cert, tmp, bufsize);
- gnutls_x509_crt_sign2(cert, cert, key, GNUTLS_DIG_SHA256, 0);
- bufsize = 4096;
- gnutls_x509_crt_export(cert, GNUTLS_X509_FMT_PEM, tmp, &bufsize);
- fwrite(tmp, 1, bufsize, stdout);
- bufsize = 4096;
- gnutls_x509_privkey_export(key, GNUTLS_X509_FMT_PEM, tmp, &bufsize);
- fwrite(tmp, 1, bufsize, stdout);
- fflush(stdout);
- gnutls_x509_privkey_deinit(key);
- gnutls_x509_crt_deinit(cert);
- }
- BBS2chProxySecureSocket::BBS2chProxySecureSocket(int sock, const char *host) :
- socket(sock), session(NULL), x509_cred(NULL)
- {
- bool hostIsDomain = false;
- for (int i=strlen(host)-1; i>=0; i--) {
- if (host[i] != '.' && !(host[i] >= '0' && host[i] <= '9')) {
- hostIsDomain = true;
- break;
- }
- }
- unsigned char tmp[4096];
- size_t bufsize = 4096;
- time_t now = time(NULL);
- unsigned long long serial;
- gnutls_x509_crt_t cert;
- gnutls_rnd(GNUTLS_RND_NONCE, &serial, sizeof(serial));
- gnutls_x509_crt_init(&cert);
- gnutls_x509_crt_set_version(cert, 3);
- gnutls_x509_crt_set_ca_status(cert, 0);
- gnutls_x509_crt_set_activation_time(cert, now - 600);
- gnutls_x509_crt_set_expiration_time(cert, now + 31536000);
- gnutls_x509_crt_set_dn_by_oid(cert, GNUTLS_OID_X520_COUNTRY_NAME, 0, "JP", strlen("JP"));
- gnutls_x509_crt_set_dn_by_oid(cert, GNUTLS_OID_X520_ORGANIZATION_NAME, 0, "proxy2ch", strlen("proxy2ch"));
- gnutls_x509_crt_set_dn_by_oid(cert, GNUTLS_OID_X520_COMMON_NAME, 0, host, strlen(host));
- gnutls_x509_crt_set_serial(cert, &serial, sizeof(serial));
- gnutls_x509_crt_set_key(cert, server_privkey);
- gnutls_x509_crt_set_key_purpose_oid(cert, GNUTLS_KP_TLS_WWW_SERVER, 0);
- gnutls_x509_crt_set_key_purpose_oid(cert, GNUTLS_KP_TLS_WWW_CLIENT, 0);
- gnutls_x509_crt_set_key_usage(cert, GNUTLS_KEY_DIGITAL_SIGNATURE|GNUTLS_KEY_KEY_ENCIPHERMENT);
- gnutls_x509_crt_get_key_id(cert, 0, tmp, &bufsize);
- gnutls_x509_crt_set_subject_key_id(cert, tmp, bufsize);
- gnutls_x509_crt_set_subject_alt_name(cert, hostIsDomain ? GNUTLS_SAN_DNSNAME : GNUTLS_SAN_IPADDRESS, host, strlen(host), GNUTLS_FSAN_APPEND);
- gnutls_x509_crt_set_subject_alt_name(cert, GNUTLS_SAN_DNSNAME, "*.5ch.net", strlen("*.5ch.net"), GNUTLS_FSAN_APPEND);
- gnutls_x509_crt_set_subject_alt_name(cert, GNUTLS_SAN_DNSNAME, "*.2ch.net", strlen("*.2ch.net"), GNUTLS_FSAN_APPEND);
- gnutls_x509_crt_set_subject_alt_name(cert, GNUTLS_SAN_DNSNAME, "*.bbspink.com", strlen("*.bbspink.com"), GNUTLS_FSAN_APPEND);
- gnutls_x509_crt_sign2(cert, ca_cert, ca_privkey, GNUTLS_DIG_SHA256, 0);
- gnutls_certificate_allocate_credentials(&x509_cred);
- gnutls_certificate_set_x509_key(x509_cred, &cert, 1, server_privkey);
- gnutls_x509_crt_deinit(cert);
- #if GNUTLS_VERSION_NUMBER >= 0x030506
- gnutls_certificate_set_known_dh_params(x509_cred, GNUTLS_SEC_PARAM_MEDIUM);
- #endif
- int ret = gnutls_init(&session, GNUTLS_SERVER);
- if (ret < 0) {
- gnutls_certificate_free_credentials(x509_cred);
- std::string str("Unable to create GnuTLS session: ");
- str += gnutls_strerror(ret);
- throw std::runtime_error(str);
- }
- gnutls_priority_set(session, priority);
- ret = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, x509_cred);
- if (ret < 0) {
- gnutls_deinit(session);
- gnutls_certificate_free_credentials(x509_cred);
- std::string str("Unable to set server credentials: ");
- str += gnutls_strerror(ret);
- throw std::runtime_error(str);
- }
- gnutls_certificate_server_set_request(session, GNUTLS_CERT_IGNORE);
- gnutls_handshake_set_timeout(session, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
- gnutls_transport_set_int(session, sock);
- ret = gnutls_handshake(session);
- if (ret < 0) {
- gnutls_deinit(session);
- gnutls_certificate_free_credentials(x509_cred);
- std::string str("Unable to establish SSL/TLS connection: ");
- str += gnutls_strerror(ret);
- throw std::runtime_error(str);
- }
- }
- #else
- static X509 *ca_cert;
- static EVP_PKEY *ca_privkey;
- static EVP_PKEY *server_privkey;
- static int add_ext(X509 *cert, int nid, const char *value)
- {
- X509_EXTENSION *ex;
- X509V3_CTX ctx;
- X509V3_set_ctx_nodb(&ctx);
- X509V3_set_ctx(&ctx, cert, cert, NULL, NULL, 0);
- ex = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
- if (!ex)
- return 0;
- X509_add_ext(cert,ex,-1);
- X509_EXTENSION_free(ex);
- return 1;
- }
- int BBS2chProxySecureSocket::initializeCerts(const char *certPath, const char *keyPath)
- {
- static int initialized;
- if (initialized) return 0;
- FILE *fp = fopen(certPath, "rb");
- if (!fp) {
- fprintf(stderr, "Unable to open CA certificate from %s\n", certPath);
- return -1;
- }
- ca_cert = PEM_read_X509(fp, NULL, NULL, NULL);
- if (!ca_cert) {
- fprintf(stderr, "Error loading CA certificate: ");
- ERR_print_errors_fp(stderr);
- return -1;
- }
- fclose(fp);
- fp = fopen(keyPath, "rb");
- if (!fp) {
- fprintf(stderr, "Unable to open CA private key from %s\n", keyPath);
- return -1;
- }
- ca_privkey = PEM_read_PrivateKey(fp, NULL, NULL, NULL);
- if (!ca_privkey) {
- fprintf(stderr, "Error loading CA private key: ");
- ERR_print_errors_fp(stderr);
- return -1;
- }
- fclose(fp);
- #if OPENSSL_VERSION_NUMBER >= 0x30000000L
- #if defined(USE_ECDSA_KEY)
- server_privkey = EVP_EC_gen("P-256");
- #else
- server_privkey = EVP_RSA_gen(2048);
- #endif
- #else
- server_privkey = EVP_PKEY_new();
- #if defined(USE_ECDSA_KEY) && (OPENSSL_VERSION_NUMBER >= 0x10000000L)
- EC_KEY *ec_key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
- EC_KEY_set_asn1_flag(ec_key, OPENSSL_EC_NAMED_CURVE);
- EC_KEY_generate_key(ec_key);
- EVP_PKEY_assign_EC_KEY(server_privkey, ec_key);
- #else
- BIGNUM *bn = BN_new();
- BN_set_word(bn, RSA_F4);
- RSA *rsa = RSA_new();
- RSA_generate_key_ex(rsa, 2048, bn, NULL);
- EVP_PKEY_assign_RSA(server_privkey, rsa);
- BN_free(bn);
- #endif
- #endif
- initialized = 1;
- return 0;
- }
- void BBS2chProxySecureSocket::generateAndPrintSelfSignedCertificate(void)
- {
- BIGNUM *bn;
- #if OPENSSL_VERSION_NUMBER >= 0x30000000L
- #if defined(USE_ECDSA_KEY)
- EVP_PKEY *key = EVP_EC_gen("P-256");
- #else
- EVP_PKEY *key = EVP_RSA_gen(2048);
- #endif
- #else
- EVP_PKEY *key = EVP_PKEY_new();
- #if defined(USE_ECDSA_KEY) && (OPENSSL_VERSION_NUMBER >= 0x10000000L)
- EC_KEY *ec_key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
- EC_KEY_set_asn1_flag(ec_key, OPENSSL_EC_NAMED_CURVE);
- EC_KEY_generate_key(ec_key);
- EVP_PKEY_assign_EC_KEY(key, ec_key);
- #else
- bn = BN_new();
- BN_set_word(bn, RSA_F4);
- RSA *rsa = RSA_new();
- RSA_generate_key_ex(rsa, 2048, bn, NULL);
- EVP_PKEY_assign_RSA(key, rsa);
- BN_free(bn);
- #endif
- #endif
- X509 *cert = X509_new();
- X509_set_version(cert, 2);
- ASN1_INTEGER *serial = ASN1_INTEGER_new();
- bn = BN_new();
- BN_rand(bn, 64, 0, 0);
- BN_to_ASN1_INTEGER(bn, serial);
- X509_set_serialNumber(cert, serial);
- ASN1_INTEGER_free(serial);
- BN_free(bn);
- X509_name_st *name = X509_get_subject_name(cert);
- X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned char *)"JP", -1, -1, 0);
- X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, (unsigned char *)"proxy2ch certificate generator", -1, -1, 0);
- X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned char *)"proxy2ch", -1, -1, 0);
- X509_set_subject_name(cert, name);
- X509_set_issuer_name(cert, name);
- X509_set_pubkey(cert, key);
- X509_gmtime_adj(X509_get_notBefore(cert), 0);
- X509_gmtime_adj(X509_get_notAfter(cert), 31536000*3);
- add_ext(cert, NID_basic_constraints, "critical,CA:TRUE");
- add_ext(cert, NID_key_usage, "critical,digitalSignature,keyCertSign,cRLSign");
- add_ext(cert, NID_ext_key_usage, "serverAuth,clientAuth");
- add_ext(cert, NID_subject_key_identifier, "hash");
- X509_sign(cert, key, EVP_sha256());
- PEM_write_X509(stdout, cert);
- PEM_write_PrivateKey(stdout, key, NULL, NULL, 0, NULL, NULL);
- X509_free(cert);
- EVP_PKEY_free(key);
- }
- BBS2chProxySecureSocket::BBS2chProxySecureSocket(int sock, const char *host) :
- socket(sock), ctx(NULL), ssl(NULL)
- {
- bool hostIsDomain = false;
- for (int i=strlen(host)-1; i>=0; i--) {
- if (host[i] != '.' && !(host[i] >= '0' && host[i] <= '9')) {
- hostIsDomain = true;
- break;
- }
- }
- X509 *cert = X509_new();
- X509_set_version(cert, 2);
- ASN1_INTEGER *serial = ASN1_INTEGER_new();
- BIGNUM *bn = BN_new();
- BN_rand(bn, 64, 0, 0);
- BN_to_ASN1_INTEGER(bn, serial);
- X509_set_serialNumber(cert, serial);
- ASN1_INTEGER_free(serial);
- BN_free(bn);
- X509_name_st *name = X509_get_subject_name(cert);
- X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned char *)"JP", -1, -1, 0);
- X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, (unsigned char *)"proxy2ch", -1, -1, 0);
- X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned char *)host, -1, -1, 0);
- X509_set_subject_name(cert, name);
- X509_set_issuer_name(cert, X509_get_subject_name(ca_cert));
- X509_set_pubkey(cert, server_privkey);
- X509_gmtime_adj(X509_get_notBefore(cert), -600);
- X509_gmtime_adj(X509_get_notAfter(cert), 31536000);
- add_ext(cert, NID_basic_constraints, "critical,CA:FALSE");
- add_ext(cert, NID_key_usage, "critical,digitalSignature,keyEncipherment");
- add_ext(cert, NID_ext_key_usage, "serverAuth,clientAuth");
- add_ext(cert, NID_subject_key_identifier, "hash");
- std::string sni(hostIsDomain ? "DNS:" : "IP:");
- sni += host;
- sni += ",DNS:*.5ch.net,DNS:*.2ch.net,DNS:*.bbspink.com";
- add_ext(cert, NID_subject_alt_name, sni.c_str());
- X509_sign(cert, ca_privkey, EVP_sha256());
- ctx = SSL_CTX_new(TLS_server_method());
- if (!ctx) {
- X509_free(cert);
- throw std::runtime_error("Unable to create SSL context");
- }
- #if OPENSSL_VERSION_NUMBER >= 0x30000000L && !defined(OPENSSL_NO_SECURITY_DOWNGRADE)
- /* Downgrade security level because 3.0 depreacted use of SHA-1 which is used by TLS v1.1 and earlier clients */
- SSL_CTX_set_security_level(ctx, 0);
- #endif
- if (SSL_CTX_use_certificate(ctx, cert) <= 0) {
- fprintf(stderr, "Unable to load server certificate\n");
- }
- if (SSL_CTX_use_PrivateKey(ctx, server_privkey) <= 0) {
- fprintf(stderr, "Unable to load server private key\n");
- }
- X509_free(cert);
- ssl = SSL_new(ctx);
- SSL_set_fd(ssl, socket);
- if (SSL_accept(ssl) <= 0) {
- char errbuf[256];
- ERR_error_string_n(ERR_get_error(), errbuf, 256);
- SSL_free(ssl);
- SSL_CTX_free(ctx);
- std::string str("Unable to establish SSL/TLS connection: ");
- str += errbuf;
- throw std::runtime_error(str);
- }
- }
- #endif
- BBS2chProxySecureSocket::~BBS2chProxySecureSocket()
- {
- }
- int BBS2chProxySecureSocket::read(char *buffer, int length)
- {
- #ifdef USE_GNUTLS
- return gnutls_record_recv(session, buffer, length);
- #else
- return SSL_read(ssl, buffer, length);
- #endif
- }
- int BBS2chProxySecureSocket::readLine(char *buffer, int maxLength)
- {
- char *ptr = buffer;
- while (ptr < buffer + maxLength - 1) {
- #ifdef USE_GNUTLS
- int read = gnutls_record_recv(session, ptr, 1);
- #else
- int read = SSL_read(ssl, ptr, 1);
- #endif
- if (read != 1) {
- return 0;
- }
- if (*ptr++ == '\n') {
- break;
- }
- }
- *ptr = 0;
- return 1;
- }
- int BBS2chProxySecureSocket::write(const char *buffer, int length)
- {
- #ifdef USE_GNUTLS
- int sent = 0;
- while (length > 0) {
- int ret = gnutls_record_send(session, buffer+sent, length);
- if (ret <= 0) break;
- sent += ret;
- length -= ret;
- }
- return sent;
- #else
- return SSL_write(ssl, buffer, length);
- #endif
- }
- int BBS2chProxySecureSocket::writeString(const std::string &str)
- {
- #ifdef USE_GNUTLS
- return write(str.data(), str.length());
- #else
- return SSL_write(ssl, str.data(), str.length());
- #endif
- }
- void BBS2chProxySecureSocket::close(void)
- {
- #ifdef USE_GNUTLS
- if (socket >= 0) {
- gnutls_bye(session, GNUTLS_SHUT_WR);
- #ifdef _WIN32
- Sleep(10);
- #else
- usleep(10000);
- #endif
- CLOSESOCKET(socket);
- socket = -1;
- }
- if (session) {
- gnutls_deinit(session);
- session = NULL;
- }
- if (x509_cred) {
- gnutls_certificate_free_credentials(x509_cred);
- x509_cred = NULL;
- }
- #else
- if (ssl) {
- SSL_shutdown(ssl);
- SSL_free(ssl);
- ssl = NULL;
- #ifdef _WIN32
- Sleep(10);
- #else
- usleep(10000);
- #endif
- }
- if (socket >= 0) {
- CLOSESOCKET(socket);
- socket = -1;
- }
- if (ctx) {
- SSL_CTX_free(ctx);
- ctx = NULL;
- }
- #endif
- }
- #endif
|