int main(int argc, char **argv) { SSL_library_init(); SSL_load_error_strings(); BIO * bio_err = BIO_new_fp(stderr, BIO_NOCLOSE); /* Set up a SIGPIPE handler */ signal(SIGPIPE, SIG_IGN); /* Create our context*/ SSL_CTX * ctx = SSL_CTX_new(SSLv23_method()); /* Load our keys and certificates*/ if(!(SSL_CTX_use_certificate_chain_file(ctx, "ftests/fixtures/rdpproxy-cert.pem"))) { BIO_printf(bio_err, "Can't read certificate file\n"); ERR_print_errors(bio_err); exit(0); } SSL_CTX_set_default_passwd_cb(ctx, password_cb0); SSL_CTX_set_default_passwd_cb_userdata(ctx, (void*)"inquisition"); if(!(SSL_CTX_use_PrivateKey_file(ctx, "ftests/fixtures/rdpproxy-key.pem", SSL_FILETYPE_PEM))) { BIO_printf(bio_err,"Can't read key file\n"); ERR_print_errors(bio_err); exit(0); } DH *ret=0; BIO *bio; if ((bio=BIO_new_file("ftests/fixtures/dh1024.pem","r")) == NULL){ BIO_printf(bio_err,"Couldn't open DH file\n"); ERR_print_errors(bio_err); exit(0); } ret=PEM_read_bio_DHparams(bio, NULL, NULL, NULL); BIO_free(bio); if(SSL_CTX_set_tmp_dh(ctx, ret)<0) { BIO_printf(bio_err,"Couldn't set DH parameters\n"); ERR_print_errors(bio_err); exit(0); } union { struct sockaddr s; struct sockaddr_storage ss; struct sockaddr_in s4; struct sockaddr_in6 s6; } ucs; memset(&ucs, 0, sizeof(ucs)); int val=1; int sock = socket(AF_INET, SOCK_STREAM,0); if(sock < 0) { fprintf(stderr, "Failed to make socket\n"); exit(0); } memset(&ucs.s4, 0, sizeof(ucs)); ucs.s4.sin_addr.s_addr = INADDR_ANY; ucs.s4.sin_family = AF_INET; ucs.s4.sin_port = htons(4433); setsockopt(sock,SOL_SOCKET,SO_REUSEADDR, &val,sizeof(val)); int bind_res = bind(sock,&ucs.s, sizeof(ucs)); if(bind_res < 0){ fprintf(stderr, "Failed to bind\n"); exit(0); } listen(sock,5); while(1){ int s = accept(sock,0,0); if(s < 0){ fprintf(stderr,"Problem accepting\n"); exit(0); } pid_t pid = fork(); if(pid){ close(s); } else { rdp_serve(ctx, s, bio_err); exit(0); } } SSL_CTX_free(ctx); exit(0); }
static void init_ssl() { SSL_load_error_strings(); SSL_library_init(); }
LUA_API int luaopen_openssl(lua_State*L) { char * config_filename; CRYPTO_thread_setup(); OpenSSL_add_all_ciphers(); OpenSSL_add_all_digests(); SSL_library_init(); ERR_load_ERR_strings(); ERR_load_crypto_strings(); ERR_load_EVP_strings(); ERR_load_SSL_strings(); ENGINE_load_dynamic(); ENGINE_load_openssl(); /* Determine default SSL configuration file */ config_filename = getenv("OPENSSL_CONF"); if (config_filename == NULL) { config_filename = getenv("SSLEAY_CONF"); } /* default to 'openssl.cnf' if no environment variable is set */ if (config_filename == NULL) { snprintf(default_ssl_conf_filename, sizeof(default_ssl_conf_filename), "%s/%s", X509_get_default_cert_area(), "openssl.cnf"); } else { strncpy(default_ssl_conf_filename, config_filename, sizeof(default_ssl_conf_filename)); } openssl_register_pkey(L); openssl_register_x509(L); openssl_register_csr(L); openssl_register_digest(L); openssl_register_cipher(L); openssl_register_sk_x509(L); openssl_register_bio(L); openssl_register_crl(L); #ifdef OPENSSL_HAVE_TS openssl_register_ts(L); #endif openssl_register_conf(L); openssl_register_pkcs7(L); openssl_register_misc(L); openssl_register_engine(L); openssl_register_ssl(L); openssl_register_ocsp(L); #if LUA_VERSION_NUM==501 luaL_register(L,"openssl",eay_functions); #elif LUA_VERSION_NUM==502 lua_newtable(L); luaL_setfuncs(L, eay_functions, 0); #endif setNamedIntegers(L, consts); /* third part */ luaopen_bn(L); lua_setfield(L, -2, "bn"); return 1; }
/* * Create Global context SSL and use it in every new session * * - Load the trusted CAs * - Load the Private key & the certificate * - Set the Context options & Verify options */ static SSL_CTX *init_tls_ctx(EAP_TLS_CONF *conf) { SSL_METHOD *meth; SSL_CTX *ctx; X509_STORE *certstore; int verify_mode = SSL_VERIFY_NONE; int ctx_options = 0; int type; /* * Add all the default ciphers and message digests * Create our context. */ SSL_library_init(); SSL_load_error_strings(); meth = TLSv1_method(); ctx = SSL_CTX_new(meth); /* * Identify the type of certificates that needs to be loaded */ if (conf->file_type) { type = SSL_FILETYPE_PEM; } else { type = SSL_FILETYPE_ASN1; } /* * Set the password to load private key */ if (conf->private_key_password) { SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->private_key_password); SSL_CTX_set_default_passwd_cb(ctx, cbtls_password); } /* * Load our keys and certificates * * If certificates are of type PEM then we can make use * of cert chain authentication using openssl api call * SSL_CTX_use_certificate_chain_file. Please see how * the cert chain needs to be given in PEM from * openSSL.org */ if (type == SSL_FILETYPE_PEM) { radlog(L_INFO, "rlm_eap_tls: Loading the certificate file as a chain"); if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) { radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL)); radlog(L_ERR, "rlm_eap_tls: Error reading certificate file"); return NULL; } } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) { radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL)); radlog(L_ERR, "rlm_eap_tls: Error reading certificate file"); return NULL; } /* Load the CAs we trust */ if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) { radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL)); radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list"); return NULL; } SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file)); if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) { radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL)); radlog(L_ERR, "rlm_eap_tls: Error reading private key file"); return NULL; } /* * Check if the loaded private key is the right one */ if (!SSL_CTX_check_private_key(ctx)) { radlog(L_ERR, "rlm_eap_tls: Private key does not match the certificate public key"); return NULL; } /* * Set ctx_options */ ctx_options |= SSL_OP_NO_SSLv2; ctx_options |= SSL_OP_NO_SSLv3; /* * SSL_OP_SINGLE_DH_USE must be used in order to prevent * small subgroup attacks and forward secrecy. Always * using * * SSL_OP_SINGLE_DH_USE has an impact on the computer * time needed during negotiation, but it is not very * large. */ ctx_options |= SSL_OP_SINGLE_DH_USE; SSL_CTX_set_options(ctx, ctx_options); /* * TODO: Set the RSA & DH * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa); * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh); */ /* * set the message callback to identify the type of * message. For every new session, there can be a * different callback argument. * * SSL_CTX_set_msg_callback(ctx, cbtls_msg); */ /* Set Info callback */ SSL_CTX_set_info_callback(ctx, cbtls_info); /* * Check the certificates for revocation. */ #ifdef X509_V_FLAG_CRL_CHECK if (conf->check_crl) { certstore = SSL_CTX_get_cert_store(ctx); if (certstore == NULL) { radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL)); radlog(L_ERR, "rlm_eap_tls: Error reading Certificate Store"); return NULL; } X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK); } #endif /* * Set verify modes * Always verify the peer certificate */ verify_mode |= SSL_VERIFY_PEER; verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; verify_mode |= SSL_VERIFY_CLIENT_ONCE; SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify); if (conf->verify_depth) { SSL_CTX_set_verify_depth(ctx, conf->verify_depth); } /* Load randomness */ if (!(RAND_load_file(conf->random_file, 1024*1024))) { radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL)); radlog(L_ERR, "rlm_eap_tls: Error loading randomness"); return NULL; } /* * Set the cipher list if we were told to */ if (conf->cipher_list) { if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) { radlog(L_ERR, "rlm_eap_tls: Error setting cipher list"); return NULL; } } return ctx; }
static int mod_init(void){ str s; int n; LM_INFO("initializing TLS protocol\n"); if (tls_db_enabled != 0 && tls_db_enabled != 1) { tls_db_enabled = 1; } if (tls_db_enabled) { /* create & init lock */ if ((dom_lock = lock_init_rw()) == NULL) { LM_CRIT("failed to init lock\n"); return -1; } init_db_url(tls_db_url, 0 /*cannot be null*/); tls_db_table.len = strlen(tls_db_table.s); if (tls_db_table.len == 0) { LM_ERR("db url not specified\n"); return -1; } id_col.len = strlen(id_col.s); address_col.len = strlen(address_col.s); type_col.len = strlen(type_col.s); method_col.len = strlen(method_col.s); verify_cert_col.len = strlen(verify_cert_col.s); require_cert_col.len = strlen(require_cert_col.s); certificate_col.len = strlen(certificate_col.s); pk_col.len = strlen(pk_col.s); crl_check_col.len = strlen(crl_check_col.s); calist_col.len = strlen(calist_col.s); cadir_col.len = strlen(cadir_col.s); cplist_col.len = strlen(cplist_col.s); dhparams_col.len = strlen(dhparams_col.s); eccurve_col.len = strlen(eccurve_col.s); if (db_bind_mod(&tls_db_url, &dr_dbf)) { LM_CRIT("cannot bind to database module! " "Did you forget to load a database module ?\n"); return -1; } /* init DB connection */ if ((db_hdl = dr_dbf.init(&tls_db_url)) == 0) { LM_CRIT("cannot initialize database connection\n"); return -1; } if (dr_dbf.use_table(db_hdl, &tls_db_table) < 0) { LM_ERR("cannot select table \"%.*s\"\n", tls_db_table.len, tls_db_table.s); return -1; } } if (tls_domain_avp) { s.s = tls_domain_avp; s.len = strlen(s.s); if (parse_avp_spec( &s, &tls_client_domain_avp)) { LM_ERR("cannot parse tls_client_avp"); return -1; } } /* * this has to be called before any function calling CRYPTO_malloc, * CRYPTO_malloc will set allow_customize in openssl to 0 */ if (!CRYPTO_set_mem_functions(os_malloc, os_realloc, os_free)) { LM_ERR("unable to set the memory allocation functions\n"); return -1; } #if !defined(OPENSSL_NO_COMP) STACK_OF(SSL_COMP)* comp_methods; /* disabling compression */ LM_WARN("disabling compression due ZLIB problems\n"); comp_methods = SSL_COMP_get_compression_methods(); if (comp_methods==0) { LM_INFO("openssl compression already disabled\n"); } else { sk_SSL_COMP_zero(comp_methods); } #endif if (tls_init_multithread() < 0) { LM_ERR("failed to init multi-threading support\n"); return -1; } SSL_library_init(); SSL_load_error_strings(); init_ssl_methods(); n = check_for_krb(); if (n==-1) { LM_ERR("kerberos check failed\n"); return -1; } if ( ( n ^ #ifndef OPENSSL_NO_KRB5 1 #else 0 #endif )!=0 ) { LM_ERR("compiled agaist an openssl with %s" "kerberos, but run with one with %skerberos\n", (n==1)?"":"no ",(n!=1)?"no ":""); return -1; } /* * finish setting up the tls default domains */ tls_default_client_domain.type = TLS_DOMAIN_DEF|TLS_DOMAIN_CLI ; tls_default_client_domain.addr.af = AF_INET; tls_default_server_domain.type = TLS_DOMAIN_DEF|TLS_DOMAIN_SRV; tls_default_server_domain.addr.af = AF_INET; /* * now initialize tls default domains */ if ( (n=init_tls_domains(&tls_default_server_domain)) ) { return n; } if ( (n=init_tls_domains(&tls_default_client_domain)) ) { return n; } /* * now initialize tls virtual domains */ if (tls_db_enabled && load_info(&dr_dbf, db_hdl, &tls_db_table, &tls_server_domains, &tls_client_domains)){ return -1; } if ( (n=init_tls_domains(tls_server_domains)) ) { return n; } if ( (n=init_tls_domains(tls_client_domains)) ) { return n; } /* * we are all set */ return 0; }
/* * IMAPFilter: an IMAP mail filtering utility. */ int main(int argc, char *argv[]) { int c; setlocale(LC_CTYPE, ""); opts.verbose = 0; opts.interactive = 0; opts.log = NULL; opts.config = NULL; opts.oneline = NULL; opts.debug = NULL; env.home = NULL; env.pathmax = -1; while ((c = getopt(argc, argv, "Vc:d:e:il:v?")) != -1) { switch (c) { case 'V': version(); /* NOTREACHED */ break; case 'c': opts.config = optarg; break; case 'd': opts.debug = optarg; break; case 'e': opts.oneline = optarg; break; case 'i': opts.interactive = 1; break; case 'l': opts.log = optarg; break; case 'v': opts.verbose = 1; break; case '?': default: usage(); /* NOTREACHED */ break; } } get_pathmax(); open_debug(); create_homedir(); catch_signals(); open_log(); if (opts.config == NULL) opts.config = get_filepath("config.lua"); buffer_init(&ibuf, INPUT_BUF); buffer_init(&obuf, OUTPUT_BUF); buffer_init(&nbuf, NAMESPACE_BUF); buffer_init(&cbuf, CONVERSION_BUF); regexp_compile(responses); SSL_library_init(); SSL_load_error_strings(); start_lua(); #if LUA_VERSION_NUM < 502 { list *l; session *s; l = sessions; while (l != NULL) { s = l->data; l = l->next; request_logout(s); } } #endif stop_lua(); ERR_free_strings(); regexp_free(responses); buffer_free(&ibuf); buffer_free(&obuf); buffer_free(&nbuf); buffer_free(&cbuf); xfree(env.home); close_log(); close_debug(); exit(0); }
int main(int argc, char *argv[]) { const char *allowed_args = "hl:x:p:o:sv:i:r:V"; char *node = NULL; int retval; int async = 1; val_log_t *logp; char *label_str = NULL; struct val_daneparams daneparams; struct val_danestatus *danestatus = NULL; struct val_ssl_data *ssl_dane_data = NULL; int port = 443; int proto = DANE_PARAM_PROTO_TCP; val_context_t *context = NULL; val_status_t val_status; struct addrinfo *val_ainfo = NULL; struct addrinfo hints; int ret = 0; int dane_retval = VAL_DANE_INTERNAL_ERROR; int ai_retval = 0; int err; /* Parse the command line */ while (1) { int c; #ifdef HAVE_GETOPT_LONG int opt_index = 0; #ifdef HAVE_GETOPT_LONG_ONLY c = getopt_long_only(argc, argv, allowed_args, prog_options, &opt_index); #else c = getopt_long(argc, argv, allowed_args, prog_options, &opt_index); #endif #else /* only have getopt */ c = getopt(argc, argv, allowed_args); #endif if (c == -1) { break; } switch (c) { case 'h': usage(argv[0]); return -1; case 'l': label_str = optarg; break; case 'o': logp = val_log_add_optarg(optarg, 1); if (NULL == logp) { /* err msg already logged */ usage(argv[0]); return -1; } break; case 's': async = 0; break; case 'p': port = atoi(optarg); break; case 'x': if(strncmp(optarg, DANE_PARAM_PROTO_STR_TCP, strlen(DANE_PARAM_PROTO_STR_TCP))) proto = DANE_PARAM_PROTO_TCP; else if (strncmp(optarg, DANE_PARAM_PROTO_STR_UDP, strlen(DANE_PARAM_PROTO_STR_UDP))) proto = DANE_PARAM_PROTO_UDP; else if (strncmp(optarg, DANE_PARAM_PROTO_STR_SCTP, strlen(DANE_PARAM_PROTO_STR_SCTP))) proto = DANE_PARAM_PROTO_SCTP; else { usage(argv[0]); return -1; } break; case 'v': dnsval_conf_set(optarg); break; case 'i': root_hints_set(optarg); break; case 'r': resolv_conf_set(optarg); break; case 'V': version(); return 0; default: fprintf(stderr, "Invalid option %s\n", argv[optind - 1]); usage(argv[0]); return -1; } } if (optind < argc) { node = argv[optind++]; } else { fprintf(stderr, "Error: node name not specified\n"); usage(argv[0]); return -1; } if (VAL_NO_ERROR != (retval = val_create_context(label_str, &context))) { fprintf(stderr, "Cannot create context %s(%d)\n", p_val_error(retval), retval); return -1; } daneparams.port = port; daneparams.proto = proto; memset(&hints, 0, sizeof(struct addrinfo)); #ifdef AI_ADDRCONFIG hints.ai_flags = AI_ADDRCONFIG; #endif if (!async) { /* synchronous lookup and validation */ ai_retval = val_getaddrinfo(context, node, NULL, &hints, &val_ainfo, &val_status); dane_retval = val_getdaneinfo(context, node, &daneparams, &danestatus); } else { #ifdef VAL_NO_ASYNC fprintf(stderr, "async support not available\n"); #else struct dane_cb cb_data_dane = { &dane_retval, &danestatus, 0 }; val_dane_callback my_dane_cb = &_danecallback; struct timeval tv; val_async_status *das = NULL; /* helps us cancel the lookup if we need to */ struct getaddr_s cb_data_ai = { &ai_retval, &val_ainfo, &val_status, 0 }; val_gai_callback my_ai_cb = &_aicallback; val_gai_status *status = NULL; /* * submit requests */ if (VAL_NO_ERROR != val_dane_submit(context, node, &daneparams, my_dane_cb, &cb_data_dane, &das) || VAL_NO_ERROR != val_getaddrinfo_submit(context, node, NULL, &hints, my_ai_cb, &cb_data_ai, 0, &status)) { dane_retval = VAL_DANE_INTERNAL_ERROR; goto done; } /* * wait for it to complete */ #if 0 while(0 == cb_data_dane.done || 0 == cb_data_ai.done) { tv.tv_sec = 10; tv.tv_usec = 0; val_async_check_wait(context, NULL, NULL, &tv, 0); } #endif #if 1 while(0 == cb_data_dane.done || 0 == cb_data_ai.done) { fd_set activefds; int nfds = 0; int ready; FD_ZERO(&activefds); tv.tv_sec = 10; /* 10 sec */ tv.tv_usec = 0; val_async_select_info(context, &activefds, &nfds, &tv); ready = select(nfds+1, &activefds, NULL, NULL, &tv); if (ready < 0) { continue; } val_async_check(context, &activefds, &nfds, 0); } #endif #endif } done: if (ai_retval != 0) { fprintf(stderr, "Error in val_getaddrinfo(): %d\n", ai_retval); return -1; } if (!val_istrusted(val_status)) { fprintf(stderr, "Address lookup information could not be validated: %s\n", p_val_status(val_status)); } else if(dane_retval == VAL_DANE_NOERROR && proto == DANE_PARAM_PROTO_TCP) { /* Set up the SSL connection */ SSL_library_init(); SSL_load_error_strings(); const SSL_METHOD *meth = SSLv23_client_method(); SSL_CTX *sslctx = SSL_CTX_new(meth); struct addrinfo *ai = NULL; int presetup_okay; /* * OpenSSL only does protocol negotiation on SSLv23_client_method; * we need to set SNI to get the correct certificate from many * modern browsers, so we disable both SSLv2 and SSLv3 if we can. * That leaves (currently) TLSv1.0 TLSv1.1 TLSv1.2 */ long ssl_options = 0 #ifdef SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv2 #endif #ifdef SSL_OP_NO_SSLv3 | SSL_OP_NO_SSLv3 #endif ; if (!SSL_CTX_set_options(sslctx, ssl_options)) { fprintf(stderr, "Failed to set SSL context options (%ld): %s\n", ssl_options, ssl_error()); presetup_okay = 0; } else { presetup_okay = 1; } if (VAL_NO_ERROR != (err = val_enable_dane_ssl(context, sslctx, node, danestatus, &ssl_dane_data))) { fprintf(stderr, "Could not set danestatus for SSL connection %s\n", p_val_error(err)); } ai = val_ainfo; while(presetup_okay && ai && (ai->ai_protocol == IPPROTO_TCP) && (ai->ai_family == AF_INET || ai->ai_family == AF_INET6)) { int sock; char buf[INET6_ADDRSTRLEN]; size_t buflen = sizeof(buf); const char *addr = NULL; if (ai->ai_family == AF_INET) { sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); ((struct sockaddr_in *)(ai)->ai_addr)->sin_port = htons(port); } else { sock = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP); ((struct sockaddr_in6 *)(ai)->ai_addr)->sin6_port = htons(port); } INET_NTOP(ai->ai_family, ai->ai_addr, sizeof(ai->ai_addr), buf, buflen, addr); fprintf(stderr, "Connecting to %s\n", addr); if (0 == connect(sock, ai->ai_addr, ai->ai_addrlen)) { SSL *ssl = SSL_new(sslctx); BIO * sbio = BIO_new_socket(sock,BIO_NOCLOSE); #if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT) SSL_set_tlsext_host_name(ssl, node); #endif SSL_set_bio(ssl,sbio,sbio); if ((err = SSL_connect(ssl)) != 1) { fprintf(stderr, "SSL Connect to %s failed: %d\n", node, err); } SSL_shutdown(ssl); SSL_free(ssl); } else { fprintf(stderr, "TCP Connect to %s failed\n", node); } ai = (struct addrinfo *) (ai->ai_next); } } else if (dane_retval == VAL_DANE_IGNORE_TLSA) { fprintf(stderr, "TLSA is either provably non-existant or provably insecure. It will be ignored.\n"); } else { fprintf(stderr, "TLSA record could not be validated.\n"); ret = 1; } if (danestatus != NULL) val_free_dane(danestatus); if (val_ainfo != NULL) val_freeaddrinfo(val_ainfo); val_free_dane_ssl(ssl_dane_data);/* MUST happen before we free the context*/ val_free_context(context); val_free_validator_state(); return ret; }
int ssl_client_libssl(void) { int verify_peer = ON; const SSL_METHOD *client_meth; SSL_CTX *ssl_client_ctx; int clientsocketfd; struct sockaddr_in serveraddr; int handshakestatus; SSL *clientssl; char buffer[1024] = "Client Say Hello Server"; int ret; SSL_library_init(); //添加国密算法对ssl的支持 SSL_load_error_strings(); // TODO 1 //client_meth = SSLv23_client_method(); //client_meth = TLSv1_1_client_method(); client_meth = GMSSLv1_client_method(); // TODO 2 ssl_client_ctx = SSL_CTX_new(client_meth); if(!ssl_client_ctx) { ERR_print_errors_fp(stderr); return -1; } if(verify_peer) { if(SSL_CTX_use_certificate_file(ssl_client_ctx, SSL_CLIENT_RSA_CERT, SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); return -1; } if(SSL_CTX_use_PrivateKey_file(ssl_client_ctx, SSL_CLIENT_RSA_KEY, SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); return -1; } // TODO 3 if(SSL_CTX_check_private_key(ssl_client_ctx) != 1) { printf("Private and certificate is not matching\n"); return -1; } //See function man pages for instructions on generating CERT files if(!SSL_CTX_load_verify_locations(ssl_client_ctx, SSL_CLIENT_RSA_CA_CERT, NULL)) { ERR_print_errors_fp(stderr); return -1; } SSL_CTX_set_verify(ssl_client_ctx, SSL_VERIFY_PEER, NULL); SSL_CTX_set_verify_depth(ssl_client_ctx, 1); } if((clientsocketfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("Error on socket creation\n"); return -1; } memset(&serveraddr, 0, sizeof(struct sockaddr_in)); serveraddr.sin_family = AF_INET; //serveraddr.sin_addr.s_addr = inet_addr("192.168.2.75"); serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1"); serveraddr.sin_port=htons(4433); if(connect(clientsocketfd, (struct sockaddr *)&serveraddr, sizeof(struct sockaddr_in)) < 0) { perror("connect"); return -1; } /* ----------------------------------------------- */ /* Now we hava a real socket to use for ssl */ // TODO 4 clientssl = SSL_new(ssl_client_ctx); if(!clientssl) { printf("Error SSL_new\n"); return -1; } SSL_set_info_callback(clientssl,apps_ssl_info_callback); SSL_set_fd(clientssl, clientsocketfd); // TODO 5 if((ret = SSL_connect(clientssl)) != 1) { printf("Handshake Error %d\n", SSL_get_error(clientssl, ret)); return -1; } /* ------------------------------------------------------- */ /* SSL Connect Success Now we print some information */ printf ("SSL connection using %s\n", SSL_get_cipher (clientssl)); /* -------------------------------------------------------- */ /* There if we need verify peer */ if(verify_peer) { X509 *ssl_client_cert = NULL; ssl_client_cert = SSL_get_peer_certificate(clientssl); if(ssl_client_cert) { long verifyresult; verifyresult = SSL_get_verify_result(clientssl); if(verifyresult == X509_V_OK) printf("Certificate Verify Success\n"); else printf("Certificate Verify Failed\n"); X509_free(ssl_client_cert); } else printf("There is no client certificate\n"); } SSL_write(clientssl, buffer, strlen(buffer) + 1); SSL_read(clientssl, buffer, sizeof(buffer)); printf("SSL server send %s\n", buffer); SSL_shutdown(clientssl); close(clientsocketfd); SSL_free(clientssl); SSL_CTX_free(ssl_client_ctx); return 0; }
/* * Initialize OpenSSL and verify the random number generator works. * Returns -1 on failure, 0 on success. */ int ssl_init(void) { #ifndef PURIFY int fd; #endif /* !PURIFY */ char buf[256]; if (ssl_initialized) return 0; /* general initialization */ SSL_library_init(); #ifdef PURIFY CRYPTO_malloc_init(); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); #endif /* PURIFY */ SSL_load_error_strings(); OpenSSL_add_all_algorithms(); /* thread-safety */ #ifdef OPENSSL_THREADS ssl_mutex_num = CRYPTO_num_locks(); ssl_mutex = malloc(ssl_mutex_num * sizeof(*ssl_mutex)); for (int i = 0; i < ssl_mutex_num; i++) { pthread_mutex_init(&ssl_mutex[i], NULL); } CRYPTO_set_locking_callback(ssl_thr_locking_cb); CRYPTO_set_dynlock_create_callback(ssl_thr_dyn_create_cb); CRYPTO_set_dynlock_lock_callback(ssl_thr_dyn_lock_cb); CRYPTO_set_dynlock_destroy_callback(ssl_thr_dyn_destroy_cb); #ifdef OPENSSL_NO_THREADID CRYPTO_set_id_callback(ssl_thr_id_cb); #else /* !OPENSSL_NO_THREADID */ CRYPTO_THREADID_set_callback(ssl_thr_id_cb); #endif /* !OPENSSL_NO_THREADID */ #endif /* OPENSSL_THREADS */ /* randomness */ #ifndef PURIFY if ((fd = open("/dev/urandom", O_RDONLY)) == -1) { log_err_printf("Error opening /dev/urandom for reading: %s\n", strerror(errno)); return -1; } while (!RAND_status()) { if (read(fd, buf, sizeof(buf)) == -1) { log_err_printf("Error reading from /dev/urandom: %s\n", strerror(errno)); close(fd); return -1; } RAND_seed(buf, sizeof(buf)); } close(fd); if (!RAND_poll()) { log_err_printf("RAND_poll() failed.\n"); return -1; } #else /* PURIFY */ log_err_printf("Warning: not seeding OpenSSL RAND due to PURITY!\n"); memset(buf, 0, sizeof(buf)); while (!RAND_status()) { RAND_seed(buf, sizeof(buf)); } #endif /* PURIFY */ #ifdef USE_FOOTPRINT_HACKS /* HACK: disable compression by zeroing the global comp algo stack. * This lowers the per-connection memory footprint by ~500k. */ STACK_OF(SSL_COMP)* comp_methods = SSL_COMP_get_compression_methods(); sk_SSL_COMP_zero(comp_methods); #endif /* USE_FOOTPRINT_HACKS */ ssl_initialized = 1; return 0; }
void ssl_load_globals(void) { // Global system initialization. SSL_library_init(); SSL_load_error_strings(); }
int openconnect_setup_dtls(struct openconnect_info *vpninfo, int dtls_attempt_period) { struct oc_vpn_option *dtls_opt = vpninfo->dtls_options; int dtls_port = 0; vpninfo->dtls_attempt_period = dtls_attempt_period; if (!dtls_attempt_period) return 0; #if defined(OPENCONNECT_GNUTLS) && defined(DTLS_OPENSSL) /* If we're using GnuTLS for authentication but OpenSSL for DTLS, we'll need to initialise OpenSSL now... */ SSL_library_init(); ERR_clear_error(); SSL_load_error_strings(); OpenSSL_add_all_algorithms(); #endif while (dtls_opt) { vpn_progress(vpninfo, PRG_DEBUG, _("DTLS option %s : %s\n"), dtls_opt->option, dtls_opt->value); if (!strcmp(dtls_opt->option + 7, "Port")) { dtls_port = atol(dtls_opt->value); } else if (!strcmp(dtls_opt->option + 7, "Keepalive")) { vpninfo->dtls_times.keepalive = atol(dtls_opt->value); } else if (!strcmp(dtls_opt->option + 7, "DPD")) { int j = atol(dtls_opt->value); if (j && (!vpninfo->dtls_times.dpd || j < vpninfo->dtls_times.dpd)) vpninfo->dtls_times.dpd = j; } else if (!strcmp(dtls_opt->option + 7, "Rekey-Method")) { if (!strcmp(dtls_opt->value, "new-tunnel")) vpninfo->dtls_times.rekey_method = REKEY_TUNNEL; else if (!strcmp(dtls_opt->value, "ssl")) vpninfo->dtls_times.rekey_method = REKEY_SSL; else vpninfo->dtls_times.rekey_method = REKEY_NONE; } else if (!strcmp(dtls_opt->option + 7, "Rekey-Time")) { vpninfo->dtls_times.rekey = atol(dtls_opt->value); } else if (!strcmp(dtls_opt->option + 7, "CipherSuite")) { vpninfo->dtls_cipher = strdup(dtls_opt->value); } dtls_opt = dtls_opt->next; } if (!dtls_port) { vpninfo->dtls_attempt_period = 0; return -EINVAL; } if (vpninfo->dtls_times.rekey <= 0) vpninfo->dtls_times.rekey_method = REKEY_NONE; vpninfo->dtls_addr = malloc(vpninfo->peer_addrlen); if (!vpninfo->dtls_addr) { vpninfo->dtls_attempt_period = 0; return -ENOMEM; } memcpy(vpninfo->dtls_addr, vpninfo->peer_addr, vpninfo->peer_addrlen); if (vpninfo->peer_addr->sa_family == AF_INET) { struct sockaddr_in *sin = (void *)vpninfo->dtls_addr; sin->sin_port = htons(dtls_port); } else if (vpninfo->peer_addr->sa_family == AF_INET6) { struct sockaddr_in6 *sin = (void *)vpninfo->dtls_addr; sin->sin6_port = htons(dtls_port); } else { vpn_progress(vpninfo, PRG_ERR, _("Unknown protocol family %d. Cannot do DTLS\n"), vpninfo->peer_addr->sa_family); vpninfo->dtls_attempt_period = 0; return -EINVAL; } if (connect_dtls_socket(vpninfo)) return -EINVAL; vpn_progress(vpninfo, PRG_DEBUG, _("DTLS initialised. DPD %d, Keepalive %d\n"), vpninfo->dtls_times.dpd, vpninfo->dtls_times.keepalive); return 0; }
void ssl_init(void) { SSL_library_init(); SSL_load_error_strings(); }
int luaopen_coevent(lua_State *L) { luaopen_uthread(L); LM = L; _loop_fd = -1; swop_top = malloc(sizeof(cosocket_swop_t)); swop_top->next = NULL; pid = getpid(); update_time(); SSL_library_init(); OpenSSL_add_all_algorithms(); lua_pushlightuserdata(L, NULL); lua_setglobal(L, "null"); lua_register(L, "startloop", lua_f_startloop); lua_register(L, "swop", lua_f_coroutine_swop); lua_register(L, "sleep", lua_f_sleep); lua_register(L, "md5", lua_f_md5); lua_register(L, "sha1bin", lua_f_sha1bin); lua_register(L, "hmac_sha1", lua_f_hmac_sha1); lua_register(L, "base64_encode", lua_f_base64_encode); lua_register(L, "base64_decode", lua_f_base64_decode); lua_register(L, "base64_encode_url", lua_f_base64_encode_url); lua_register(L, "base64_decode_url", lua_f_base64_decode_url); lua_register(L, "escape", cosocket_lua_f_escape); lua_register(L, "escape_uri", lua_f_escape_uri); lua_register(L, "unescape_uri", lua_f_unescape_uri); lua_register(L, "time", lua_f_time); lua_register(L, "longtime", lua_f_longtime); lua_register(L, "build_dns_query_packet", lua_co_build_dns_query_packet); lua_register(L, "parse_dns_result", lua_co_parse_dns_result); lua_register(L, "LOG", lua_f_log); lua_register(L, "open_log", lua_f_open_log); luaopen_eio(L); luaL_loadstring(L, " \ DEBUG,INFO,NOTICE,WARN,ALERT,ERR = 1,2,3,4,5,6 \ coroutine_resume=coroutine.resume \ coroutine_create=coroutine.create \ coroutine_wait=coroutine.wait \ wait=coroutine.wait \ newthread=coroutine.spawn \ newco = newthread "); lua_pcall(L, 0, 0, 0); luaL_newmetatable(L, "cosocket:tcp"); lua_pushvalue(L, lua_upvalueindex(1)); setfuncs(L, M, 1); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); lua_pop(L, 1); luaL_newmetatable(L, "cosocket:udp"); lua_pushvalue(L, lua_upvalueindex(1)); setfuncs(L, M_UDP, 1); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); lua_pop(L, 1); static const struct luaL_reg _MT[] = {{NULL, NULL}}; luaL_openlib(L, "cosocket", cosocket_methods, 0); luaL_newmetatable(L, "cosocket*"); luaL_register(L, NULL, _MT); lua_pushliteral(L, "__index"); lua_pushvalue(L, -3); /* dup methods table*/ lua_rawset(L, -3); /* metatable.__index = methods */ lua_pushliteral(L, "__metatable"); lua_pushvalue(L, -3); /* dup methods table*/ lua_rawset(L, -3); /* hide metatable: metatable.__metatable = methods */ lua_pop(L, 1); /* drop metatable */ lua_pushcfunction(L, lua_f_startloop); return 1; }
void init_ssl(void) { SSL_library_init(); }
int main() { char dest_url[] = "https://127.0.0.1:443"; BIO *certbio = NULL; BIO *outbio = NULL; X509 *cert = NULL; X509_NAME *certname = NULL; const SSL_METHOD *method; SSL_CTX *ctx; SSL *ssl; int server = 0; int ret, i; /* ---------------------------------------------------------- * * These function calls initialize openssl for correct work. * * ---------------------------------------------------------- */ OpenSSL_add_all_algorithms(); ERR_load_BIO_strings(); ERR_load_crypto_strings(); SSL_load_error_strings(); /* ---------------------------------------------------------- * * Create the Input/Output BIO's. * * ---------------------------------------------------------- */ certbio = BIO_new(BIO_s_file()); outbio = BIO_new_fp(stdout, BIO_NOCLOSE); /* ---------------------------------------------------------- * * initialize SSL library and register algorithms * * ---------------------------------------------------------- */ if(SSL_library_init() < 0) BIO_printf(outbio, "Could not initialize the OpenSSL library !\n"); /* ---------------------------------------------------------- * * Set SSLv2 client hello, also announce SSLv3 and TLSv1 * * ---------------------------------------------------------- */ //method = SSLv23_client_method(); method = TLSv1_2_method(); /* ---------------------------------------------------------- * * Try to create a new SSL context * * ---------------------------------------------------------- */ if ( (ctx = SSL_CTX_new(method)) == NULL) BIO_printf(outbio, "Unable to create a new SSL context structure.\n"); /* ---------------------------------------------------------- * * Disabling SSLv2 will leave v3 and TSLv1 for negotiation * * ---------------------------------------------------------- */ //SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2); /* ---------------------------------------------------------- * * Create new SSL connection state object * * ---------------------------------------------------------- */ ssl = SSL_new(ctx); /* ---------------------------------------------------------- * * Make the underlying TCP socket connection * * ---------------------------------------------------------- */ server = create_socket(dest_url, outbio); if(server != 0) BIO_printf(outbio, "Successfully made the TCP connection to: %s.\n", dest_url); /* ---------------------------------------------------------- * * Attach the SSL session to the socket descriptor * * ---------------------------------------------------------- */ SSL_set_fd(ssl, server); /* ---------------------------------------------------------- * * Try to SSL-connect here, returns 1 for success * * ---------------------------------------------------------- */ if ( SSL_connect(ssl) != 1 ) BIO_printf(outbio, "Error: Could not build a SSL session to: %s.\n", dest_url); else BIO_printf(outbio, "Successfully enabled SSL/TLS session to: %s.\n", dest_url); /* ---------------------------------------------------------- * * Get the remote certificate into the X509 structure * * ---------------------------------------------------------- */ cert = SSL_get_peer_certificate(ssl); if (cert == NULL) BIO_printf(outbio, "Error: Could not get a certificate from: %s.\n", dest_url); else BIO_printf(outbio, "Retrieved the server's certificate from: %s.\n", dest_url); verify_test(ssl); /* ---------------------------------------------------------- * * extract various certificate information * * -----------------------------------------------------------*/ certname = X509_NAME_new(); certname = X509_get_subject_name(cert); /* ---------------------------------------------------------- * * display the cert subject here * * -----------------------------------------------------------*/ BIO_printf(outbio, "Displaying the certificate subject data:\n"); X509_NAME_print_ex(outbio, certname, 0, 0); BIO_printf(outbio, "\n"); /* ---------------------------------------------------------- * * Free the structures we don't need anymore * * -----------------------------------------------------------*/ SSL_free(ssl); close(server); X509_free(cert); SSL_CTX_free(ctx); BIO_printf(outbio, "Finished SSL/TLS connection with server: %s.\n", dest_url); return(0); }
/* caller == ssl client, !client == ssl server */ int ssl_init(int caller, int fd, int iscontrol) { const SSL_METHOD *method; int ret; SSL_CTX **curctx; SSL **curssl; if (!_use_ssl) return 0; SSL_library_init (); SSL_load_error_strings (); if (iscontrol) { curctx = &control_ctx; curssl = &control_ssl; } else { curctx = &ctx; curssl = &ssl; } #if 0 if (caller) // method = SSLv23_client_method(); method = TLSv1_1_client_method(); else //method = SSLv23_method(); method = TLSv1_1_server_method(); #endif method = SSLv23_method(); *curctx = SSL_CTX_new (method); if (*curctx == NULL) { ERR_print_errors_fp(stderr); return -1; } /* Load cert */ if(!(SSL_CTX_use_certificate_file(*curctx, certfile, SSL_FILETYPE_PEM))) { ERR_print_errors_fp(stderr); return -1; } /* Load private key */ if(!(SSL_CTX_use_PrivateKey_file(*curctx, keyfile, SSL_FILETYPE_PEM))) { ERR_print_errors_fp(stderr); return -1; } /* Load the CAs we trust*/ if(!(SSL_CTX_load_verify_locations(*curctx, cafile, 0))) { ERR_print_errors_fp(stderr); return -1; } /* if in server role request peer's cert */ //if (!caller) SSL_CTX_set_verify(*curctx, SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT|SSL_VERIFY_CLIENT_ONCE, 0); SSL_CTX_set_verify_depth(*curctx, 1); STACK_OF(X509_NAME) *cert_names; cert_names = SSL_load_client_CA_file(cafile); if (cert_names != NULL) { printf("loaded client ca list\n"); SSL_CTX_set_client_CA_list(*curctx, cert_names); } else printf("not loaded client ca list\n"); SSL_CTX_set_mode(*curctx, SSL_MODE_AUTO_RETRY); *curssl = SSL_new(*curctx); if (*curssl == NULL) { ERR_print_errors_fp(stderr); return -1; } if (!SSL_set_fd (*curssl, fd)) { ERR_print_errors_fp(stderr); return -1; } if (caller) { if (SSL_connect (*curssl) != 1) { ERR_print_errors_fp(stderr); printf("ssl error %d\n", SSL_get_error(*curssl, ret)); return -1; } } else { if((ret = SSL_accept(*curssl)) <=0 ) { ERR_print_errors_fp(stderr); printf("ssl error %d\n", SSL_get_error(*curssl, ret)); return -1; } } return check_cert(*curssl); }
int main(int argc, char **argv) { int i = 0; if(argc < 7) { fprintf(stderr, "Usage:%s sock_type(0/TCP|1/UDP) iskeepalive ip port concurrecy limit\n", argv[0]); _exit(-1); } ev_sock_type = atoi(argv[1]); if(ev_sock_type < 0 || ev_sock_type > ev_sock_count) { fprintf(stderr, "sock_type must be 0/TCP OR 1/UDP\n"); _exit(-1); } sock_type = ev_sock_list[ev_sock_type]; keepalive = atoi(argv[2]); ip = argv[3]; port = atoi(argv[4]); conn_num = atoi(argv[5]); limit = atoi(argv[6]); TIMER_INIT(timer); /* Set resource limit */ setrlimiter("RLIMIT_NOFILE", RLIMIT_NOFILE, CONN_MAX); /* Initialize global vars */ if((conns = (CONN *)calloc(CONN_MAX, sizeof(CONN)))) { //memset(events, 0, sizeof(EVENT *) * CONN_MAX); /* Initialize inet */ memset(&xsa, 0, sizeof(struct sockaddr_in)); xsa.sin_family = AF_INET; xsa.sin_addr.s_addr = inet_addr(ip); xsa.sin_port = htons(port); xsa_len = sizeof(struct sockaddr); /* set evbase */ if((evbase = evbase_init(0))) { if(is_use_ssl) { #ifdef USE_SSL SSL_library_init(); OpenSSL_add_all_algorithms(); SSL_load_error_strings(); if((ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) { ERR_print_errors_fp(stdout); _exit(-1); } #endif } for(i = 0; i < conn_num; i++) { new_request(); i++; } running_status = 1; do { evbase->loop(evbase, 0, NULL); //usleep(1000); }while(running_status); for(i = 0; i < CONN_MAX; i++) { if(conns[i].fd > 0) { event_destroy(&conns[i].event); shutdown(conns[i].fd, SHUT_RDWR); close(conns[i].fd); #ifdef USE_SSL if(conns[i].ssl) { SSL_shutdown(conns[i].ssl); SSL_free(conns[i].ssl); } #endif } } #ifdef USE_SSL ERR_free_strings(); SSL_CTX_free(ctx); #endif } free(conns); TIMER_CLEAN(timer); } return -1; }
int main(int argc, char* argv[]) { char* config_path = NULL; char* pid_path = NULL; int daemon = 1; int c = 0; int pid_path_set = 0; int daemon_set = 0; pid_t pid = 0; eemo_rv rv = ERV_OK; while ((c = getopt(argc, argv, "fc:p:Ghv")) != -1) { switch(c) { case 'f': daemon = 0; daemon_set = 1; break; case 'c': config_path = strdup(optarg); if (config_path == NULL) { fprintf(stderr, "Error allocating memory, exiting\n"); return ERV_MEMORY; } break; case 'p': pid_path = strdup(optarg); if (pid_path == NULL) { fprintf(stderr, "Error allocating memory, exiting\n"); return ERV_MEMORY; } pid_path_set = 1; break; case 'G': generate_guid(); return 0; break; case 'h': usage(); return 0; case 'v': version(); return 0; } } if (config_path == NULL) { config_path = strdup(DEFAULT_EEMO_SENSOR_CONF); if (config_path == NULL) { fprintf(stderr, "Error allocating memory, exiting\n"); return ERV_MEMORY; } } if (pid_path == NULL) { pid_path = strdup(DEFAULT_EEMO_SENSOR_PIDFILE); if (pid_path == NULL) { fprintf(stderr, "Error allocating memory, exiting\n"); return ERV_MEMORY; } } /* Load the configuration */ if (eemo_init_config_handling(config_path) != ERV_OK) { fprintf(stderr, "Failed to load the configuration, exiting\n"); return ERV_CONFIG_ERROR; } /* Initialise logging */ if (eemo_init_log() != ERV_OK) { fprintf(stderr, "Failed to initialise logging, exiting\n"); return ERV_LOG_INIT_FAIL; } /* Determine configuration settings that were not specified on the command line */ if (!pid_path_set) { char* conf_pid_path = NULL; if (eemo_conf_get_string("daemon", "pidfile", &conf_pid_path, NULL) != ERV_OK) { ERROR_MSG("Failed to retrieve pidfile information from the configuration"); } else { if (conf_pid_path != NULL) { free(pid_path); pid_path = conf_pid_path; } } } if (!daemon_set) { if (eemo_conf_get_bool("daemon", "fork", &daemon, 1) != ERV_OK) { ERROR_MSG("Failed to retrieve daemon information from the configuration"); } } /* Now fork if that was requested */ if (daemon) { pid = fork(); if (pid != 0) { /* This is the parent process; write the PID file and exit */ write_pid(pid_path, pid); /* Unload the configuration */ if (eemo_uninit_config_handling() != ERV_OK) { ERROR_MSG("Failed to uninitialise configuration handling"); } /* Uninitialise logging */ if (eemo_uninit_log() != ERV_OK) { fprintf(stderr, "Failed to uninitialise logging\n"); } free(pid_path); free(config_path); return ERV_OK; } } /* If we forked, this is the child */ INFO_MSG("Starting the Extensible Ethernet Monitor Sensor (eemo_sensor) version %s", VERSION); INFO_MSG("eemo_sensor %sprocess ID is %d", daemon ? "daemon " : "", getpid()); /* Install signal handlers */ signal(SIGABRT, signal_handler); signal(SIGBUS, signal_handler); signal(SIGFPE, signal_handler); signal(SIGILL, signal_handler); signal(SIGPIPE, signal_handler); signal(SIGQUIT, signal_handler); signal(SIGSEGV, signal_handler); signal(SIGSYS, signal_handler); signal(SIGXCPU, signal_handler); signal(SIGXFSZ, signal_handler); /* Initialise OpenSSL */ SSL_library_init(); SSL_load_error_strings(); DEBUG_MSG("Initialised OpenSSL"); if (eemo_mt_openssl_init() != ERV_OK) { ERROR_MSG("Failed to initialise multi-thread use of OpenSSL"); return ERV_GENERAL_ERROR; } /* Initialise the sensor */ if (eemo_sensor_init() == ERV_OK) { /* Run the multiplexer until it is stopped */ eemo_sensor_run(); /* Uninitialise the sensor */ eemo_sensor_finalize(); } else { ERROR_MSG("Failed to initialise the sensor"); rv = ERV_GENERAL_ERROR; } /* Remove signal handlers */ signal(SIGABRT, SIG_DFL); signal(SIGBUS, SIG_DFL); signal(SIGFPE, SIG_DFL); signal(SIGILL, SIG_DFL); signal(SIGPIPE, SIG_DFL); signal(SIGQUIT, SIG_DFL); signal(SIGSEGV, SIG_DFL); signal(SIGSYS, SIG_DFL); signal(SIGXCPU, SIG_DFL); signal(SIGXFSZ, SIG_DFL); INFO_MSG("Extensible Ethernet Monitor Sensor exiting"); eemo_mt_openssl_finalize(); /* Uninitialise logging */ if (eemo_uninit_log() != ERV_OK) { fprintf(stderr, "Failed to uninitialise logging\n"); } free(pid_path); free(config_path); return rv; }
int main(int argc, char** argv){ int sock = 0; // declaración del socket e inicializado a 0 int error = 0; /** declaramos una variable que nos servirá para detectar * errores */ int serverTalk = 0; //socklen_t length = (socklen_t) sizeof (struct sockaddr_in); // tamaño del paquete //struct sockaddr_in addr; // definimos el contenedor de la dirección unsigned int port = 5678; /** creamos la variable que identifica el puerto * de conexión, siendo el puerto por defecto 5678 */ char dir[DIM] = "localhost"; /** definimos la cadena que contendrá a la * dirección del servidor, la cual, será por * defecto localhost */ //struct hostent* server; // estructura utilizada para la gestión de direcciones sms auxMsj; char name[DIM] = {0}; int nbytes = 0; // contador de bytes leidos y escritos char aux[DIM] = {0}; // inicializamos las variables de SSL BIO* bio = NULL; SSL_CTX* ctx = NULL; SSL* ssl = NULL; char cert[DIM] = "/usr/share/doc/libssl-dev/demos/sign/cert.pem"; //analizamos los parámetros de entrada int i = 0; for(; i < argc; i++){ if(strcmp(argv[i], "-p") == 0){ // leemos el puerto if(argc <= i + 1 || isNum(argv[i+1]) == 0){ perror("Se esperaba un número después de -p"); exit(-1); }else{ PDEBUG("INFO: Puerto identificado\n"); i++; port = atoi(argv[i]); } continue; }else if(strcmp(argv[i], "-d") == 0){ // dirección de destino if(argc <= i + 1){ perror("Se esperaba una dirección después de -d"); exit(-1); }else{ PDEBUG("INFO: Destino identificado"); i++; strcpy(dir, argv[i]); } continue; }else if(strcmp(argv[i], "-cert") == 0){ // dirección de destino if(argc <= i + 1){ perror("Se esperaba una ruta de certificado después de -cert"); exit(-1); }else{ PDEBUG("INFO: Destino identificado"); i++; strcpy(cert, argv[i]); } continue; } } /***********************************SSL************************************/ PDEBUG("INFO: Iniciamos la librería SSL\n"); SSL_load_error_strings(); // strings de error SSL_library_init(); // iniciams la libreria en sí ERR_load_BIO_strings(); // strings de error de BIO OpenSSL_add_all_algorithms(); // inicializamos los algoritmos de la librería PDEBUG("INFO: Conectando...\n"); PDEBUG("INFO: Inicializando los punteros\n"); ctx = SSL_CTX_new(SSLv23_client_method()); ssl = NULL; PDEBUG("INFO: Cargamos el certificado\n"); if(SSL_CTX_load_verify_locations(ctx, cert, NULL) == 0){ char aux[] = "ERROR: No se pudo comprobar el certificado\n"; write(WRITE, aux, strlen(aux)); exit(-1); } PDEBUG("INFO: Inicializando BIO\n"); bio = BIO_new_ssl_connect(ctx); BIO_get_ssl(bio, &ssl); if(ssl == 0){ char aux[] = "ERROR: Error al crear el objeto ssl\n"; write(WRITE, aux, strlen(aux)); exit(-1); } PDEBUG("INFO: Estableciendo el modo de trabajo, no queremos reintentos\n"); SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); PDEBUG("INFO: Intentando realizar la conexión\n"); PDEBUG("INFO: Conectando a -> "); sprintf(aux, "%s:%i", dir, port); PDEBUG(aux);PDEBUG("\n"); BIO_set_conn_hostname(bio, aux); PDEBUG("INFO: Verificando la conexión\n"); if (BIO_do_connect(bio) < 1){ char aux[] = "ERROR: al conectar el BIO\n"; write(WRITE, aux, strlen(aux)); exit(-1); } //PDEBUG("INFO: Verificando el resultado de la conexión\n"); //printf("--%i-%i--\n", X509_V_OK, SSL_get_verify_result(ssl)); //if (SSL_get_verify_result(ssl) != X509_V_OK) { // char aux[] = "ERROR: verificar el resultado de la conexión\n"; // write(WRITE, aux, strlen(aux)); // exit(-1); //} PDEBUG("INFO: Conectado\n"); /***********************************SSL************************************/ ////Creamos el socket //PDEBUG("INFO: Creando el socket\n"); //sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); ////Comprobamos si ha ocurrido un error al crear el socket //if(sock < 0){ // char aux[] = "ERROR: creación del socket {{socket()}}:\n"; // write(WRITE, aux, strlen(aux)); // exit(-1); //} // // //addr.sin_family = AF_INET; // familia AF_INET //addr.sin_port = htons(port); // definimos el puerto de conexión //PDEBUG("INFO: Traducimos la dirección del servidor\n"); //server = gethostbyname(dir); /** convertimos la dirección dada // * en una dirección válida para el // * equipo y la metemos en addr // */ ////Comprobamos si ha ocurrido un error obtener el host //if(server == NULL){ // write(WRITE, "ERROR: Host inválido\n", DIM); // // terminamos la ejecución del programa // exit(-1); //} //// copiamos el contenido correspondiente a la dirección de server en addr //bcopy(server->h_addr, &(addr.sin_addr.s_addr), server->h_length); // //// realizamos la conexión al servidor //PDEBUG("INFO: Nos conectamos al servidor\n"); //error = connect(sock, (struct sockaddr*) &addr, length); //if(error < 0){ // char aux[] = "ERROR: al establecer la conexion con el servidor {{connect()}}: \n"; // write(WRITE, aux, strlen(aux)); // // terminamos la ejecución del programa // exit(-1); //} // //PDEBUG("INFO: Conexión establecida\n"); PDEBUG("INFO: Esperando mensaje de bienvenida\n"); memset(&auxMsj, 0, sizeof(sms)); if(client_read(bio, &auxMsj, sizeof(sms)) <= 0){ PDEBUG("INFO: El socket está cerrado\n"); perror("Error al leer contenido del socket porque está cerrado\n"); perror("El cliente se parará\n"); exit(-1); } // atendemos la autentificación del cliente do{ bzero(aux, DIM); sprintf(aux, "%s ~$> %s\n", auxMsj.name, auxMsj.text); write(WRITE, aux, DIM); bzero(&auxMsj.text, SMS_LEN); if(auxMsj.flag == MSJ){ // si es un mensaje, solo imprimimos por la salida estandar memset(&auxMsj, 0, sizeof(sms)); if(client_read(bio, &auxMsj, sizeof(sms)) <= 0){ PDEBUG("INFO: El socket está cerrado\n"); perror("Error al leer contenido del socket porque está cerrado\n"); perror("El cliente se parará\n"); exit(-1); } continue; } if(auxMsj.flag == REQ_PASS){ // si es password desactivamos el echo echo_off(); } nbytes = read(READ, &auxMsj.text, SMS_LEN); if(auxMsj.flag == REQ_PASS){// si es password activamos el echo echo_on(); } auxMsj.text[nbytes - 1] = '\0'; // eliminamos el retorno de carro // nos salimos? if(strcmp(auxMsj.text, "-x") == 0){ PDEBUG("EXIT: Cerrando el cliente, avisando al servidor...\n"); auxMsj.flag = CLI_EXIT; client_write(bio, &auxMsj, sizeof(sms)); PDEBUG("EXIT: Cerrando el socket\n"); shutdown(sock, 2); PDEBUG("EXIT: Cerrando el cliente\n"); exit(0); }else{ // es un mensaje strcpy(name, auxMsj.text); // hacemos una copia del nombre introducido para no perderlo if(auxMsj.flag == REQ_TEXT){ auxMsj.flag = REQ_AUTH; }else if(auxMsj.flag == REQ_PASS){ // entonces REQ_PASS auxMsj.flag = CHECK_PASS; }else if(auxMsj.flag == REQ_ROOM){ // entonces REQ_ROOM auxMsj.flag = CHECK_ROOM; } client_write(bio, &auxMsj, sizeof(sms)); memset(&auxMsj, 0, sizeof(sms)); if(client_read(bio, &auxMsj, sizeof(sms)) <= 0){ PDEBUG("INFO: El socket está cerrado\n"); perror("Error al leer contenido del socket porque está cerrado\n"); perror("El cliente se parará\n"); exit(-1); } } }while(auxMsj.flag != OK); PDEBUG("INFO: Usuario conectado\n"); printf("Usuario conectado...\n"); fd_set desc, descCopy; // definimos un descriptor que contendrá nuestros descriptores //inicializamos la lista de conexiones FD_ZERO(&desc); // Inicio del bit descriptor sock con el valor de sock int fd; if(BIO_get_fd(bio, &fd) < 0){ write(WRITE, "ERROR: crear le descriptor %s\n", DIM); // terminamos la ejecución del programa exit(-1); } FD_SET (fd, &desc); // Inicio del bit descriptor connList con el valor del descriptor de entrada estándar FD_SET (READ, &desc); while(1){ // hacemos una copia de seguridad para asegurarnos de no perder los datos descCopy = desc; // ¿Hay algún socket listo para leer? PDEBUG("INFO: ¿Hay algún socket listo para leer?\n"); error = select(fd + 1, &descCopy, NULL, NULL, NULL); //Comprobamos si ha ocurrido un error al ponernos a escuchar if(error < 0){ write(WRITE, "ERROR: al realizar la selección {{select()}}: %s\n", DIM); // terminamos la ejecución del programa exit(-1); } // recorriendo los sockets para ver los que están activos PDEBUG("INFO: recorriendo los sockets para ver los que están activos\n"); if(FD_ISSET(fd, &descCopy)){ PDEBUG("INFO: Nuevo mensaje recibido\n"); if(client_read(bio, &auxMsj, sizeof(sms)) <= 0){ PDEBUG("INFO: El socket está cerrado\n"); perror("Error al leer contenido del socket porque está cerrado\n"); perror("El cliente se parará\n"); exit(-1); } switch(auxMsj.flag){ case OK: // mensaje de aceptacion, mismo comportamiento que msj case MSJ: // mensaje recibido if(serverTalk != 1 || strcmp(auxMsj.name, SERVER) == 0){ PDEBUG("INFO: Recibido mensaje\n"); sprintf(aux, "%s ~$> %s\n", auxMsj.name, auxMsj.text); write(WRITE, aux, strlen(aux)); sync(); } break; case SERV_EXIT: // el servidor se va a cerrar PDEBUG("EXIT: El servidor se está cerrando, se dejará de leer\n"); shutdown(sock, SHUT_RDWR); sprintf(aux, "%s ~$> Servidor desconectado\n", SERVER); write(WRITE, aux, strlen(aux)); sprintf(aux, "El proceso cliente se cerrará\n"); write(WRITE, aux, strlen(aux)); exit(0); break; default: sprintf(aux, "Recibido un mensaje mal formado\n"); write(WRITE, aux, strlen(aux)); sync(); break; } }else if(FD_ISSET(READ, &descCopy)){ PDEBUG("INFO: Nuevo mensaje escrito\n"); bzero(&auxMsj.text, SMS_LEN); // inicializamos el array nbytes = read(READ, &auxMsj.text, SMS_LEN); // leemos de la entrada estándar auxMsj.text[nbytes - 1] = 0; // eliminamos el retorno de carro // nos salimos? if(strcmp(auxMsj.text, "-x") == 0 && serverTalk != 1){ PDEBUG("EXIT: Cerrando el cliente, avisando al servidor...\n"); auxMsj.flag = CLI_EXIT; }else if(strcmp(auxMsj.text, "--serv") == 0){ // queremos hablar con el servidor PDEBUG("SERV_ADMIN: Iniciando la comunicación directa con el servidor\n"); sprintf(aux, "%s ~$> Iniciada conversación con el servidor\n", SERVER); write(WRITE, aux, strlen(aux)); serverTalk = 1; continue; }else if(sscanf(auxMsj.text, "--mp %s", aux) == 1){ // queremos hablar con el servidor PDEBUG("MP: Mensaje privado detectado\n"); strcpy(auxMsj.to, aux); sprintf(aux, "%s ~$> Inserte el mensaje privado\n", SERVER); write(WRITE, aux, strlen(aux)); auxMsj.flag = MP; nbytes = read(READ, &auxMsj.text, SMS_LEN); // leemos de la entrada estándar auxMsj.text[nbytes - 1] = 0; // eliminamos el retorno de carro }else{ // es un mensaje if(serverTalk == 1){ PDEBUG("SERV_ADMIN: Enviando mensaje al servidor\n"); auxMsj.flag = SERV_ADMIN; if(strcmp(auxMsj.text, "exit") == 0){ serverTalk = 0; sprintf(aux, "%s ~$> Envio de mensajes de configuración terminada:\n", SERVER); write(WRITE, aux, strlen(aux)); continue; } }else{ auxMsj.flag = MSJ; } } strcpy(auxMsj.name, name); // hacemos una copia del nombre introducido para no perderlo PDEBUG("INFO: Enviando mensaje...\n"); client_write(bio, &auxMsj, sizeof(sms)); PDEBUG("INFO: Mensaje Enviado\n"); // nos salimos? if(auxMsj.flag == CLI_EXIT){ PDEBUG("EXIT: Cerrando el socket\n"); shutdown(sock, SHUT_RDWR); PDEBUG("EXIT: Cerrando el cliente\n"); exit(0); } } } return 0; }
int WebRequest::Request ( int request_type , std::string url_host , int url_port , std::string url_path , std::string data ) { bool secure = false; mMessageHeader = ""; mMessageBody.clear(); // temp fix for POST recognition data = "_start_=1&" + data + "&_end_=1"; mReadSize = 1024; mError = 0; if(request_type == HTTPS_GET || request_type == HTTPS_POST || request_type == HTTPS_PUT || request_type == HTTPS_DELETE) { secure = true; } #ifdef WIN32 WSADATA wsa; // startup winsock mError = WSAStartup(MAKEWORD(2,0),&wsa); if(mError) { printf("Error in Startup = %d\n", mError); return -1; } #endif // socket int socket = 0; // struct for socket struct sockaddr_in host_addr = {0}; // information about host struct hostent *host = {0}; // request of client std::string request; // SSL context SSL_CTX *sslContext = NULL; // SSL socket SSL *sslSocket = NULL; // get IP from name host host = gethostbyname(url_host.c_str()); if (host == NULL) { printf("Unknown Host %s\n", url_host.c_str()); return -1; } // create socket TCP socket = ::socket(PF_INET, SOCK_STREAM, 0); if (socket < 0) { printf("Socket Error\n"); return -1; } // create host struct host_addr.sin_family = AF_INET; // set IP addres host_addr.sin_addr = *((struct in_addr *)host->h_addr); // set HTTP port host_addr.sin_port = htons(url_port); // connect mError = connect(socket, (struct sockaddr *)&host_addr, sizeof(host_addr)); if (mError == -1) { CloseSocket(socket); printf("Connection Error\n"); return -1; } if(secure) { // init OpenSSL SSL_load_error_strings(); SSL_library_init(); // create context sslContext = SSL_CTX_new(SSLv23_client_method()); //create ssl socket sslSocket = SSL_new(sslContext); if(!sslSocket) { CloseSocket(socket); printf("SSL creation error\n"); return -1; } // join sslSocket and socket SSL_set_fd(sslSocket, socket); // conect sslSocket mError = SSL_connect(sslSocket); if(!mError) { CloseSocket(socket); printf("SSL connect error = %d\n", mError); mError = SSL_get_error(sslSocket, mError); printf("SSL error: %d\n", mError); //std::cin.get(); return -1; } } if(request_type == HTTP_GET || request_type == HTTPS_GET) { //create get request request = "GET " + url_path + " HTTP/1.0\nHost: " + url_host + " \r\n\r\n"; } else if(request_type == HTTP_POST || request_type == HTTPS_POST) { //create get request request = "POST " + url_path + " HTTP/1.0\nHost: " + url_host + "\nContent-Length: " + to_string(data.length()) + "\nContent-Type: application/x-www-form-urlencoded\n" + "\r\n\r\n" + data + "\r\n"; } // TODO add DELETE and PUT // send data to server if(secure) { mError = SSL_write(sslSocket, request.c_str(), strlen(request.c_str())); } else { mError = send(socket, request.c_str(), strlen(request.c_str()), 0); } // read in header and body char bufferHeader[1]; int readHeader; int lineLength; bool loop = true; bool bHeader = false; // header mMessageHeader = ""; while(loop) { if(secure) readHeader = SSL_read(sslSocket, bufferHeader, 1); else readHeader = recv(socket, bufferHeader, 1, 0); if(readHeader < 0) loop = false; if(bufferHeader[0]=='\n') { if(lineLength == 0) loop = false; lineLength = 0; if(mMessageHeader.find("200") != std::string::npos) bHeader = true; } else if(bufferHeader[0]!='\r') lineLength++; mMessageHeader += bufferHeader[0]; } // body mMessageBody.clear(); if(bHeader) { unsigned char bufferBody[1024]; if(secure) { while((readHeader = SSL_read(sslSocket, bufferBody, sizeof(bufferBody))) > 0) { mMessageBody.insert(mMessageBody.end(), bufferBody, bufferBody + readHeader); } } else { while((readHeader = recv(socket, (char*)bufferBody, sizeof(bufferBody), 0)) > 0) { mMessageBody.insert(mMessageBody.end(), bufferBody, bufferBody + readHeader); } } } if(secure) { switch(SSL_get_error( sslSocket, mReadSize )) { case SSL_ERROR_ZERO_RETURN: printf( "\n\nSSL::ZERO\n\n" ); break; case SSL_ERROR_NONE: printf( "\n\nSSL::No Error\n\n" ); break; case SSL_ERROR_SSL: printf( "\n\nSSL::SSL ERROR\n\n" ); break; } } #if WIN32 Sleep(1); #else sleep(1); #endif if(secure) { //close SSLsocket SSL_shutdown(sslSocket); //free memory SSL_free(sslSocket); // free context SSL_CTX_free(sslContext); } //close scoket CloseSocket(socket); return 0; }
int main(int argc, char **argv) { BIO *sbio = NULL, *out = NULL; int len; char tmpbuf[1024]; SSL_CTX *ctx; SSL_CONF_CTX *cctx; SSL *ssl; char **args = argv + 1; const char *connect_str = "localhost:4433"; int nargs = argc - 1; ERR_load_crypto_strings(); ERR_load_SSL_strings(); SSL_library_init(); ctx = SSL_CTX_new(TLS_client_method()); cctx = SSL_CONF_CTX_new(); SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT); SSL_CONF_CTX_set_ssl_ctx(cctx, ctx); while (*args && **args == '-') { int rv; /* Parse standard arguments */ rv = SSL_CONF_cmd_argv(cctx, &nargs, &args); if (rv == -3) { fprintf(stderr, "Missing argument for %s\n", *args); goto end; } if (rv < 0) { fprintf(stderr, "Error in command %s\n", *args); ERR_print_errors_fp(stderr); goto end; } /* If rv > 0 we processed something so proceed to next arg */ if (rv > 0) continue; /* Otherwise application specific argument processing */ if (strcmp(*args, "-connect") == 0) { connect_str = args[1]; if (connect_str == NULL) { fprintf(stderr, "Missing -connect argument\n"); goto end; } args += 2; nargs -= 2; continue; } else { fprintf(stderr, "Unknown argument %s\n", *args); goto end; } } if (!SSL_CONF_CTX_finish(cctx)) { fprintf(stderr, "Finish error\n"); ERR_print_errors_fp(stderr); goto end; } /* * We'd normally set some stuff like the verify paths and * mode here * because as things stand this will connect to * any server whose * certificate is signed by any CA. */ sbio = BIO_new_ssl_connect(ctx); BIO_get_ssl(sbio, &ssl); if (!ssl) { fprintf(stderr, "Can't locate SSL pointer\n"); goto end; } /* Don't want any retries */ SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); /* We might want to do other things with ssl here */ BIO_set_conn_hostname(sbio, connect_str); out = BIO_new_fp(stdout, BIO_NOCLOSE); if (BIO_do_connect(sbio) <= 0) { fprintf(stderr, "Error connecting to server\n"); ERR_print_errors_fp(stderr); goto end; } if (BIO_do_handshake(sbio) <= 0) { fprintf(stderr, "Error establishing SSL connection\n"); ERR_print_errors_fp(stderr); goto end; } /* Could examine ssl here to get connection info */ BIO_puts(sbio, "GET / HTTP/1.0\n\n"); for (;;) { len = BIO_read(sbio, tmpbuf, 1024); if (len <= 0) break; BIO_write(out, tmpbuf, len); } end: SSL_CONF_CTX_free(cctx); BIO_free_all(sbio); BIO_free(out); return 0; }
int evhtp_ssl_init(evhtp * htp, evhtp_ssl_cfg * cfg) { long cache_mode; evhtp_ssl_scache_init init_cb = NULL; evhtp_ssl_scache_add add_cb = NULL; evhtp_ssl_scache_get get_cb = NULL; evhtp_ssl_scache_del del_cb = NULL; if (cfg == NULL || htp == NULL || cfg->pemfile == NULL) { return -1; } SSL_library_init(); SSL_load_error_strings(); RAND_poll(); STACK_OF(SSL_COMP) * comp_methods = SSL_COMP_get_compression_methods(); sk_SSL_COMP_zero(comp_methods); htp->ssl_cfg = cfg; htp->ssl_ctx = SSL_CTX_new(SSLv23_server_method()); #if OPENSSL_VERSION_NUMBER >= 0x10000000L SSL_CTX_set_options(htp->ssl_ctx, SSL_MODE_RELEASE_BUFFERS); SSL_CTX_set_timeout(htp->ssl_ctx, 60 * 60 * 48); #endif SSL_CTX_set_options(htp->ssl_ctx, cfg->ssl_opts); if (cfg->ciphers != NULL) { SSL_CTX_set_cipher_list(htp->ssl_ctx, cfg->ciphers); } SSL_CTX_load_verify_locations(htp->ssl_ctx, cfg->cafile, cfg->capath); X509_STORE_set_flags(SSL_CTX_get_cert_store(htp->ssl_ctx), cfg->store_flags); SSL_CTX_set_verify(htp->ssl_ctx, cfg->verify_peer, cfg->x509_verify_cb); if (cfg->x509_chk_issued_cb != NULL) { htp->ssl_ctx->cert_store->check_issued = cfg->x509_chk_issued_cb; } if (cfg->verify_depth) { SSL_CTX_set_verify_depth(htp->ssl_ctx, cfg->verify_depth); } switch (cfg->scache_type) { case evhtp_ssl_scache_type_disabled: cache_mode = SSL_SESS_CACHE_OFF; break; case evhtp_ssl_scache_type_user: cache_mode = SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_INTERNAL | SSL_SESS_CACHE_NO_INTERNAL_LOOKUP; init_cb = cfg->scache_init; add_cb = cfg->scache_add; get_cb = cfg->scache_get; del_cb = cfg->scache_del; break; case evhtp_ssl_scache_type_builtin: cache_mode = SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_INTERNAL | SSL_SESS_CACHE_NO_INTERNAL_LOOKUP; #if 0 init_cb = _evhtp_ssl_builtin_init; add_cb = _evhtp_ssl_builtin_add; get_cb = _evhtp_ssl_builtin_get; del_cb = _evhtp_ssl_builtin_del; #endif break; case evhtp_ssl_scache_type_internal: default: cache_mode = SSL_SESS_CACHE_SERVER; break; } /* switch */ SSL_CTX_use_certificate_file(htp->ssl_ctx, cfg->pemfile, SSL_FILETYPE_PEM); SSL_CTX_use_PrivateKey_file(htp->ssl_ctx, cfg->privfile ? cfg->privfile: cfg->pemfile, SSL_FILETYPE_PEM); SSL_CTX_set_session_id_context(htp->ssl_ctx, (const unsigned char*)&session_id_context, sizeof(session_id_context)); SSL_CTX_set_app_data(htp->ssl_ctx, htp); SSL_CTX_set_session_cache_mode(htp->ssl_ctx, cache_mode); if (cache_mode != SSL_SESS_CACHE_OFF) { SSL_CTX_sess_set_cache_size(htp->ssl_ctx, cfg->scache_size ? cfg->scache_size : 1024); if (cfg->scache_type == evhtp_ssl_scache_type_builtin || cfg->scache_type == evhtp_ssl_scache_type_user) { SSL_CTX_sess_set_new_cb(htp->ssl_ctx, _evhtp_ssl_add_scache_ent); SSL_CTX_sess_set_get_cb(htp->ssl_ctx, _evhtp_ssl_get_scache_ent); SSL_CTX_sess_set_remove_cb(htp->ssl_ctx, _evhtp_ssl_delete_scache_ent); if (cfg->scache_init) { cfg->args = (cfg->scache_init)(htp); } } } return 0; } /* evhtp_use_ssl */
/** * @warning Make sure you've called CryptoInitialize() first! */ bool ServerTLSInitialize() { int ret; /* OpenSSL is needed for our new protocol over TLS. */ SSL_library_init(); SSL_load_error_strings(); assert(SSLSERVERCONTEXT == NULL); SSLSERVERCONTEXT = SSL_CTX_new(SSLv23_server_method()); if (SSLSERVERCONTEXT == NULL) { Log(LOG_LEVEL_ERR, "SSL_CTX_new: %s", ERR_reason_error_string(ERR_get_error())); goto err1; } /* Use only TLS v1 or later. TODO option for SSL_OP_NO_TLSv{1,1_1} */ SSL_CTX_set_options(SSLSERVERCONTEXT, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3); /* Never bother with retransmissions, SSL_write() should * always either write the whole amount or fail. */ SSL_CTX_set_mode(SSLSERVERCONTEXT, SSL_MODE_AUTO_RETRY); /* * Create cert into memory and load it into SSL context. */ if (PRIVKEY == NULL || PUBKEY == NULL) { Log(LOG_LEVEL_ERR, "No public/private key pair is loaded, create one with cf-key"); goto err2; } assert(SSLSERVERCERT == NULL); /* Generate self-signed cert valid from now to 50 years later. */ { X509 *x509 = X509_new(); X509_gmtime_adj(X509_get_notBefore(x509), 0); X509_time_adj(X509_get_notAfter(x509), 60*60*24*365*50, NULL); EVP_PKEY *pkey = EVP_PKEY_new(); EVP_PKEY_set1_RSA(pkey, PRIVKEY); X509_NAME *name = X509_get_subject_name(x509); X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (const char *) "", -1, -1, 0); X509_set_issuer_name(x509, name); X509_set_pubkey(x509, pkey); const EVP_MD *md = EVP_get_digestbyname("sha384"); if (md == NULL) { Log(LOG_LEVEL_ERR, "Uknown digest algorithm %s", "sha384"); return false; } ret = X509_sign(x509, pkey, md); EVP_PKEY_free(pkey); SSLSERVERCERT = x509; if (ret <= 0) { Log(LOG_LEVEL_ERR, "Couldn't sign the public key for the TLS handshake: %s", ERR_reason_error_string(ERR_get_error())); goto err3; } } /* Log(LOG_LEVEL_ERR, "generate cert from priv key: %s", */ /* ERR_reason_error_string(ERR_get_error())); */ SSL_CTX_use_certificate(SSLSERVERCONTEXT, SSLSERVERCERT); ret = SSL_CTX_use_RSAPrivateKey(SSLSERVERCONTEXT, PRIVKEY); if (ret != 1) { Log(LOG_LEVEL_ERR, "Failed to use RSA private key: %s", ERR_reason_error_string(ERR_get_error())); goto err3; } /* Verify cert consistency. */ ret = SSL_CTX_check_private_key(SSLSERVERCONTEXT); if (ret != 1) { Log(LOG_LEVEL_ERR, "Inconsistent key and TLS cert: %s", ERR_reason_error_string(ERR_get_error())); goto err3; } /* Set options to always request a certificate from the peer, either we * are client or server. */ SSL_CTX_set_verify(SSLSERVERCONTEXT, SSL_VERIFY_PEER, NULL); /* Always accept that certificate, we do proper checking after TLS * connection is established since OpenSSL can't pass a connection * specific pointer to the callback (so we would have to lock). */ SSL_CTX_set_cert_verify_callback(SSLSERVERCONTEXT, TLSVerifyCallback, NULL); return true; err3: X509_free(SSLSERVERCERT); SSLSERVERCERT = NULL; err2: SSL_CTX_free(SSLSERVERCONTEXT); SSLSERVERCONTEXT = NULL; err1: return false; }
void enclave_main() { SSL_METHOD *method; SSL_CTX *ctx; BIO *bio_cert; BIO *bio_pkey; X509 *cert = NULL; EVP_PKEY *pkey = NULL; int port = 5566; int srvr_fd; int clnt_fd; struct sockaddr_in addr; // Initialize ssl SSL_library_init(); // Initialize ctx OpenSSL_add_all_algorithms(); method = TLSv1_2_server_method(); ctx = SSL_CTX_new(method); // Load certificate bio_cert = BIO_new(BIO_s_mem()); BIO_puts(bio_cert, cert_s); cert = PEM_read_bio_X509(bio_cert, NULL, 0, NULL); if (cert == NULL) { sgx_debug("cert is NULL"); } else { sgx_debug("cert is not NULL"); } bio_pkey = BIO_new(BIO_s_mem()); BIO_puts(bio_pkey, pkey_s); pkey = PEM_read_bio_PrivateKey(bio_pkey, NULL, 0, NULL); if (pkey == NULL) { sgx_debug("key is NULL\n"); } else { sgx_debug("key is not NULL\n"); } if (SSL_CTX_use_certificate(ctx, cert) <= 0) { sgx_debug("SSL_CTX_use_certificate failed\n"); //sgx_exit(NULL); } else { sgx_debug("SSL_CTX_use_certificate succeeded\n"); } if (SSL_CTX_use_PrivateKey(ctx, pkey) <= 0) { sgx_debug("SSL_CTX_use_PrivateKey failed\n"); //sgx_exit(NULL); } else { sgx_debug("SSL_CTX_use_PrivateKey succeeded\n"); } SSL_CTX_set_ecdh_auto(ctx, 1); SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE); srvr_fd = sgx_socket(PF_INET, SOCK_STREAM, 0); if (srvr_fd == -1) { sgx_exit(NULL); } sgx_memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = sgx_htons(port); addr.sin_addr.s_addr = INADDR_ANY; if (sgx_bind(srvr_fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) { sgx_exit(NULL); } if (sgx_listen(srvr_fd, 10) != 0) { sgx_exit(NULL); } while (1) { struct sockaddr_in addr; socklen_t len = sizeof(addr); SSL *ssl; int sd; int bytes; char buf[256]; const char* echo="<html><body><pre>%s</pre></body></html>\n\n"; clnt_fd = sgx_accept(srvr_fd, (struct sockaddr *)&addr, &len); if (clnt_fd < 0) { sgx_puts("ERROR on accept\n"); continue; } ssl = SSL_new(ctx); SSL_set_fd(ssl, clnt_fd); if (SSL_accept(ssl) == -1) sgx_puts("SSL accept failed\n"); else { sgx_puts("SSL accept succeeded\n"); bytes = SSL_read(ssl, buf, sizeof(buf)); if (bytes > 0) { buf[bytes] = 0; sgx_puts(buf); char msg[] = "Successfully connected\n"; SSL_write(ssl, msg, sgx_strlen(msg)); } } sd = SSL_get_fd(ssl); //SSL_free(ssl); sgx_close(sd); //sgx_close(clnt_fd); } sgx_close(srvr_fd); sgx_exit(NULL); }
int main(int argc, char **argv) { int rc = 0; SSL_METHOD *meth = NULL; SSL * ssl = NULL; SSL_CTX * ctx = NULL; X509 *server_cert = NULL; long res; int max_size = 813*1024*1024; int i, j; char *buf = NULL; char *srv; int sd; unsigned long addr; struct sockaddr_in saddr; unsigned short port = 4422; int lcipher = 1; if ( argc < 2 ) usage(basename(argv[0]), 1); if (parse_cmd_line(argc, argv)) usage(basename(argv[0]), 1); srv = argv[optind]; if ((addr = inet_addr(srv)) == INADDR_NONE) { /* need to resolve address */ struct hostent *host; if ((host = gethostbyname(srv)) == NULL) { fprintf(stderr, "gethostbyname(%s) err : %m\n", srv); return 1; } memcpy(&addr, host->h_addr, sizeof(addr)); } if (crtfile == NULL) crtfile = strdup("certificate.pem"); if (keyfile == NULL) keyfile = strdup("private.key"); if (ciphers) if (strcasecmp(ciphers, "none") == 0) lcipher = 0; srand(time(NULL)); /* Set up the library */ SSL_library_init(); SSL_load_error_strings(); if ((buf = malloc(bufsize)) == NULL) { fprintf(stderr, "malloc() : %m"); return 1; } /* Create SSL context (framework) */ meth = SSLv23_client_method(); if ((ctx = SSL_CTX_new(meth)) == NULL) { fprintf(stderr, "SSL_CTX_new() : %m\n"); ERR_print_errors_fp(stderr); rc = 1; goto cleanup_0; } /* load certificat from file */ if(SSL_CTX_use_certificate_file(ctx, crtfile, SSL_FILETYPE_PEM) < 1) { ERR_print_errors_fp(stderr); rc = 1; goto cleanup_1; } if(SSL_CTX_use_PrivateKey_file(ctx, keyfile, SSL_FILETYPE_PEM) < 1) { ERR_print_errors_fp(stdout); rc = 1; goto cleanup_1; } if (ciphers) { if (strcasecmp(ciphers, "none")) { /* load available cipher list */ if (SSL_CTX_set_cipher_list(ctx, ciphers) == 0) { fprintf(stderr, "Error loading cipher list\n"); ERR_print_errors_fp(stderr); rc = 1; goto cleanup_1; } } } SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL); // SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL); /* ----------------------------------------------- */ /* Create a socket and connect to server using normal socket calls. */ if ((sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) { fprintf(stderr, "socket() err : %m\n"); rc = 1; goto cleanup_1; } saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = addr; saddr.sin_port = htons(port); if (connect(sd, (struct sockaddr *)&saddr, sizeof(saddr))) { // if (errno != EINPROGRESS) - for NONBLOCK fprintf(stderr, "connect() : %m\n"); rc = 1; goto cleanup_1; } /* ----------------------------------------------- */ /* Now we have TCP connection. Start SSL negotiation. */ /* Create SSL obj */ if ((ssl = SSL_new(ctx)) == NULL) { fprintf(stderr, "Error creating SSL object\n"); ERR_print_errors_fp(stderr); rc = 1; goto cleanup_1; } SSL_set_fd(ssl, sd); SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); /* try to connect */ if(SSL_connect(ssl) <= 0) { fprintf(stderr, "Error attempting to connect\n"); /* TODO SSL_get_error() */ ERR_print_errors_fp(stderr); rc = 1; goto cleanup_2; } /* Get server's certificate. Note: dynamic allocation */ if ((server_cert = SSL_get_peer_certificate(ssl)) == NULL) { fprintf(stderr, "Can't get peer certificate\n"); ERR_print_errors_fp(stderr); rc = 1; goto cleanup_2; } X509_free(server_cert); /* verify the certificate From SSL_get_verify_result() man page: If no peer certificate was presented, the returned result code is X509_V_OK. This is because no verification error occurred, it does how- ever not indicate success. SSL_get_verify_result() is only useful in connection with SSL_get_peer_certificate(3). */ res = SSL_get_verify_result(ssl); /* will use expired certificate for test */ if ( (res != X509_V_OK) && (res != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) && (res != X509_V_ERR_CERT_HAS_EXPIRED)) { fprintf(stderr, "Certificate verification error: %ld\n", res); fprintf(stderr, "See verify man page for more info\n"); ERR_print_errors_fp(stderr); rc = 1; goto cleanup_2; } printf("Server certificate verified\n"); i = 0; while (i < max_size) { for (j = 0; (j < bufsize) && (i < max_size); j++, i++) { buf[j] = (char) (255.0*rand()/(RAND_MAX+1.0)); } if (lcipher) j = SSL_write(ssl, buf, j); else j = write(sd, buf, j); /* TODO: use SSL_get_fd */ if (j <= 0) { fprintf(stderr, "write() error\n"); ERR_print_errors_fp(stderr); rc = 1; break; } } printf("%d bytes wrote\n", i); SSL_shutdown(ssl); /* Close the connection and free the context */ cleanup_2: if (ssl) SSL_free(ssl); cleanup_1: if (ctx) SSL_CTX_free(ctx); cleanup_0: if (buf) free(buf); return rc; }
int main(int argc, char **argv){ u_int32_t packet_crc32; u_int32_t calculated_crc32; int16_t result; int rc; packet send_packet; packet receive_packet; int bytes_to_send; int bytes_to_recv; result=process_arguments(argc,argv); if(result!=OK || show_help==TRUE || show_license==TRUE || show_version==TRUE){ if(result!=OK) printf("Incorrect command line arguments supplied\n"); printf("\n"); printf("NRPE Plugin for Nagios\n"); printf("Copyright (c) 1999-2003 Ethan Galstad ([email protected])\n"); printf("Version: %s\n",PROGRAM_VERSION); printf("Last Modified: %s\n",MODIFICATION_DATE); printf("License: GPL with exemptions (-l for more info)\n"); #ifdef HAVE_SSL printf("SSL/TLS Available: Anonymous DH Mode, OpenSSL 0.9.6 or higher required\n"); #endif printf("\n"); } if(result!=OK || show_help==TRUE){ printf("Usage: check_nrpe -H <host> [-p <port>] [-t <timeout>] [-c <command>] [-a <arglist...>]\n"); printf("\n"); printf("Options:\n"); printf(" <host> = The address of the host running the NRPE daemon\n"); printf(" [port] = The port on which the daemon is running (default=%d)\n",DEFAULT_SERVER_PORT); printf(" [timeout] = Number of seconds before connection times out (default=%d)\n",DEFAULT_SOCKET_TIMEOUT); printf(" [command] = The name of the command that the remote daemon should run\n"); printf(" [arglist] = Optional arguments that should be passed to the command. Multiple\n"); printf(" arguments should be separated by a space. If provided, this must be\n"); printf(" the last option supplied on the command line.\n"); printf("\n"); printf("Note:\n"); printf("This plugin requires that you have the NRPE daemon running on the remote host.\n"); printf("You must also have configured the daemon to associate a specific plugin command\n"); printf("with the [command] option you are specifying here. Upon receipt of the\n"); printf("[command] argument, the NRPE daemon will run the appropriate plugin command and\n"); printf("send the plugin output and return code back to *this* plugin. This allows you\n"); printf("to execute plugins on remote hosts and 'fake' the results to make Nagios think\n"); printf("the plugin is being run locally.\n"); printf("\n"); } if(show_license==TRUE) display_license(); if(result!=OK || show_help==TRUE || show_license==TRUE || show_version==TRUE) exit(STATE_UNKNOWN); /* generate the CRC 32 table */ generate_crc32_table(); #ifdef HAVE_SSL /* initialize SSL */ if(use_ssl==TRUE){ SSL_library_init(); SSLeay_add_ssl_algorithms(); meth=SSLv23_client_method(); SSL_load_error_strings(); if((ctx=SSL_CTX_new(meth))==NULL){ printf("CHECK_NRPE: Error - could not create SSL context.\n"); exit(STATE_CRITICAL); } } #endif /* initialize alarm signal handling */ signal(SIGALRM,alarm_handler); /* set socket timeout */ alarm(socket_timeout); /* try to connect to the host at the given port number */ result=my_tcp_connect(server_name,server_port,&sd); #ifdef HAVE_SSL /* do SSL handshake */ if(result==STATE_OK && use_ssl==TRUE){ if((ssl=SSL_new(ctx))!=NULL){ SSL_CTX_set_cipher_list(ctx,"ADH"); SSL_set_fd(ssl,sd); if((rc=SSL_connect(ssl))!=1){ printf("CHECK_NRPE: Error - Could not complete SSL handshake.\n"); #ifdef DEBUG printf("SSL_connect=%d\n",rc); /* rc=SSL_get_error(ssl,rc); printf("SSL_get_error=%d\n",rc); printf("ERR_get_error=%lu\n",ERR_get_error()); printf("%s\n",ERR_error_string(rc,NULL)); */ ERR_print_errors_fp(stdout); #endif result=STATE_CRITICAL; } } else{ printf("CHECK_NRPE: Error - Could not create SSL connection structure.\n"); result=STATE_CRITICAL; } /* bail if we had errors */ if(result!=STATE_OK){ SSL_CTX_free(ctx); close(sd); exit(result); } } #endif /* we're connected and ready to go */ if(result==STATE_OK){ /* clear the packet buffer */ bzero(&send_packet,sizeof(send_packet)); /* fill the packet with semi-random data */ randomize_buffer((char *)&send_packet,sizeof(send_packet)); /* initialize packet data */ send_packet.packet_version=(int16_t)htons(NRPE_PACKET_VERSION_2); send_packet.packet_type=(int16_t)htons(QUERY_PACKET); strncpy(&send_packet.buffer[0],query,MAX_PACKETBUFFER_LENGTH); send_packet.buffer[MAX_PACKETBUFFER_LENGTH-1]='\x0'; /* calculate the crc 32 value of the packet */ send_packet.crc32_value=(u_int32_t)0L; calculated_crc32=calculate_crc32((char *)&send_packet,sizeof(send_packet)); send_packet.crc32_value=(u_int32_t)htonl(calculated_crc32); /***** ENCRYPT REQUEST *****/ /* send the packet */ bytes_to_send=sizeof(send_packet); if(use_ssl==FALSE) rc=sendall(sd,(char *)&send_packet,&bytes_to_send); #ifdef HAVE_SSL else{ rc=SSL_write(ssl,&send_packet,bytes_to_send); if(rc<0) rc=-1; } #endif if(rc==-1){ printf("CHECK_NRPE: Error sending query to host.\n"); close(sd); return STATE_UNKNOWN; } /* wait for the response packet */ bytes_to_recv=sizeof(receive_packet); if(use_ssl==FALSE) rc=recvall(sd,(char *)&receive_packet,&bytes_to_recv,socket_timeout); #ifdef HAVE_SSL else rc=SSL_read(ssl,&receive_packet,bytes_to_recv); #endif /* reset timeout */ alarm(0); /* close the connection */ #ifdef HAVE_SSL if(use_ssl==TRUE){ SSL_shutdown(ssl); SSL_free(ssl); SSL_CTX_free(ctx); } #endif close(sd); /* recv() error */ if(rc<0){ printf("CHECK_NRPE: Error receiving data from daemon.\n"); return STATE_UNKNOWN; } /* server disconnected */ else if(rc==0){ printf("CHECK_NRPE: Received 0 bytes from daemon. Check the remote server logs for error messages.\n"); return STATE_UNKNOWN; } /* receive underflow */ else if(bytes_to_recv<sizeof(receive_packet)){ printf("CHECK_NRPE: Receive underflow - only %d bytes received (%d expected).\n",bytes_to_recv,sizeof(receive_packet)); return STATE_UNKNOWN; } /***** DECRYPT RESPONSE *****/ /* check the crc 32 value */ packet_crc32=ntohl(receive_packet.crc32_value); receive_packet.crc32_value=0L; calculated_crc32=calculate_crc32((char *)&receive_packet,sizeof(receive_packet)); if(packet_crc32!=calculated_crc32){ printf("CHECK_NRPE: Response packet had invalid CRC32.\n"); close(sd); return STATE_UNKNOWN; } /* check packet version */ if(ntohs(receive_packet.packet_version)!=NRPE_PACKET_VERSION_2){ printf("CHECK_NRPE: Invalid packet version received from server.\n"); close(sd); return STATE_UNKNOWN; } /* check packet type */ if(ntohs(receive_packet.packet_type)!=RESPONSE_PACKET){ printf("CHECK_NRPE: Invalid packet type received from server.\n"); close(sd); return STATE_UNKNOWN; } /* get the return code from the remote plugin */ result=(int16_t)ntohs(receive_packet.result_code); /* print the output returned by the daemon */ receive_packet.buffer[MAX_PACKETBUFFER_LENGTH-1]='\x0'; if(!strcmp(receive_packet.buffer,"")) printf("CHECK_NRPE: No output returned from daemon.\n"); else printf("%s\n",receive_packet.buffer); } /* reset the alarm */ else alarm(0); return result; }
void ape_ssl_library_init() { SSL_library_init(); SSL_load_error_strings(); OpenSSL_add_all_algorithms(); }
void tls_initialize(void) { SSL_library_init(); SSL_load_error_strings(); }
int lws_context_init_client_ssl(struct lws_context_creation_info *info, struct libwebsocket_context *context) { int error; int n; SSL_METHOD *method; if (info->provided_client_ssl_ctx) { /* use the provided OpenSSL context if given one */ context->ssl_client_ctx = info->provided_client_ssl_ctx; /* nothing for lib to delete */ context->user_supplied_ssl_ctx = 1; return 0; } if (info->port != CONTEXT_PORT_NO_LISTEN) return 0; /* basic openssl init */ SSL_library_init(); OpenSSL_add_all_algorithms(); SSL_load_error_strings(); method = (SSL_METHOD *)SSLv23_client_method(); if (!method) { error = ERR_get_error(); lwsl_err("problem creating ssl method %lu: %s\n", error, ERR_error_string(error, (char *)context->service_buffer)); return 1; } /* create context */ context->ssl_client_ctx = SSL_CTX_new(method); if (!context->ssl_client_ctx) { error = ERR_get_error(); lwsl_err("problem creating ssl context %lu: %s\n", error, ERR_error_string(error, (char *)context->service_buffer)); return 1; } #ifdef SSL_OP_NO_COMPRESSION SSL_CTX_set_options(context->ssl_client_ctx, SSL_OP_NO_COMPRESSION); #endif SSL_CTX_set_options(context->ssl_client_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE); if (info->ssl_cipher_list) SSL_CTX_set_cipher_list(context->ssl_client_ctx, info->ssl_cipher_list); #ifdef LWS_SSL_CLIENT_USE_OS_CA_CERTS if (!(info->options & LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS)) /* loads OS default CA certs */ SSL_CTX_set_default_verify_paths(context->ssl_client_ctx); #endif /* openssl init for cert verification (for client sockets) */ if (!info->ssl_ca_filepath) { if (!SSL_CTX_load_verify_locations( context->ssl_client_ctx, NULL, LWS_OPENSSL_CLIENT_CERTS)) lwsl_err( "Unable to load SSL Client certs from %s " "(set by --with-client-cert-dir= " "in configure) -- client ssl isn't " "going to work", LWS_OPENSSL_CLIENT_CERTS); } else if (!SSL_CTX_load_verify_locations( context->ssl_client_ctx, info->ssl_ca_filepath, NULL)) lwsl_err( "Unable to load SSL Client certs " "file from %s -- client ssl isn't " "going to work", info->ssl_ca_filepath); /* * callback allowing user code to load extra verification certs * helping the client to verify server identity */ /* support for client-side certificate authentication */ if (info->ssl_cert_filepath) { n = SSL_CTX_use_certificate_chain_file( context->ssl_client_ctx, info->ssl_cert_filepath); if (n != 1) { lwsl_err("problem getting cert '%s' %lu: %s\n", info->ssl_cert_filepath, ERR_get_error(), ERR_error_string(ERR_get_error(), (char *)context->service_buffer)); return 1; } } if (info->ssl_private_key_filepath) { /* check for provided by user password to private key */ if (info->ssl_private_key_password) { /* * password provided, set ssl callback and user data * for checking password which will be trigered during * SSL_CTX_use_PrivateKey_file function */ SSL_CTX_set_default_passwd_cb_userdata( context->ssl_client_ctx, (void *)info); SSL_CTX_set_default_passwd_cb(context->ssl_client_ctx, lws_context_init_client_ssl_pem_passwd_cb); } /* set the private key from KeyFile */ if (SSL_CTX_use_PrivateKey_file(context->ssl_client_ctx, info->ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) { lwsl_err("use_PrivateKey_file '%s' %lu: %s\n", info->ssl_private_key_filepath, ERR_get_error(), ERR_error_string(ERR_get_error(), (char *)context->service_buffer)); return 1; } /* verify private key */ if (!SSL_CTX_check_private_key( context->ssl_client_ctx)) { lwsl_err("Private SSL key doesn't match cert\n"); return 1; } } context->protocols[0].callback(context, NULL, LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS, context->ssl_client_ctx, NULL, 0); return 0; }
static void init() { if ( real_accept == NULL ) { char *cert_path, *pkey_path, *pass_path; real_accept = (int (*)(int, struct sockaddr *, socklen_t *)) dlsym(RTLD_NEXT,"accept"); real_fork = (int (*)()) dlsym(RTLD_NEXT,"fork"); real_close = (int (*)(int)) dlsym(RTLD_NEXT,"close"); real_recv = (ssize_t (*)(int s, void *buf, size_t len, int flags)) dlsym(RTLD_NEXT,"recv"); real_send = (ssize_t (*)(int s, const void *buf, size_t len, int flags)) dlsym(RTLD_NEXT,"send"); if ( (real_accept == NULL) || (real_accept == accept) || (real_fork == NULL) || (real_fork == fork) || (real_close == NULL) || (real_close == close) || (real_recv == NULL) || (real_recv == recv) || (real_send == NULL) || (real_send == send) ) { fprintf(stderr,"could not load real functions!\n"); real_accept = NULL; real_fork = NULL; real_close = NULL; real_recv = NULL; real_send = NULL; exit(1); } SSL_load_error_strings(); SSL_library_init(); OpenSSL_add_all_algorithms(); cert_path = getenv("WARSOLVE_CERT"); pkey_path = getenv("WARSOLVE_PKEY"); pass_path = getenv("WARSOLVE_PASS"); ssl_ctx = SSL_CTX_new(SSLv23_server_method()); SSL_CTX_set_options(ssl_ctx, SSL_OP_SINGLE_DH_USE); if (cert_path != NULL) { if (!SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path)) { ERR_print_errors_fp(stdout); SSL_CTX_free(ssl_ctx); exit(1); } } if (pass_path != NULL) { char pass[MAX_PASS_SIZE]; int i; FILE *pass_fd = fopen(pass_path,"r"); if (!pass_fd || !fgets(pass, MAX_PASS_SIZE, pass_fd)) { perror("WARSOLVE_PASS"); fprintf(stderr,"error: could not read password file\n"); SSL_CTX_free(ssl_ctx); exit(1); } fclose(pass_fd); pass[MAX_PASS_SIZE-1] = '\0'; for (i=strlen(pass)-1; (i>=0) && (pass[i] == '\n'); i--) { pass[i] = '\0'; } SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, pass); } if (pkey_path != NULL) { if (!SSL_CTX_use_PrivateKey_file(ssl_ctx, pkey_path, SSL_FILETYPE_PEM)) { ERR_print_errors_fp(stdout); SSL_CTX_free(ssl_ctx); exit(1); } } } }