static void init_prng (void) { char namebuf[256]; const char *random_file; if (RAND_status ()) /* The PRNG has been seeded; no further action is necessary. */ return; /* Seed from a file specified by the user. This will be the file specified with --random-file, $RANDFILE, if set, or ~/.rnd, if it exists. */ if (opt.random_file) random_file = opt.random_file; else { /* Get the random file name using RAND_file_name. */ namebuf[0] = '\0'; random_file = RAND_file_name (namebuf, sizeof (namebuf)); } if (random_file && *random_file) /* Seed at most 16k (apparently arbitrary value borrowed from curl) from random file. */ RAND_load_file (random_file, 16384); if (RAND_status ()) return; /* Get random data from EGD if opt.egd_file was used. */ if (opt.egd_file && *opt.egd_file) RAND_egd (opt.egd_file); if (RAND_status ()) return; #ifdef WINDOWS /* Under Windows, we can try to seed the PRNG using screen content. This may or may not work, depending on whether we'll calling Wget interactively. */ RAND_screen (); if (RAND_status ()) return; #endif #if 0 /* don't do this by default */ { int maxrand = 500; /* Still not random enough, presumably because neither /dev/random nor EGD were available. Try to seed OpenSSL's PRNG with libc PRNG. This is cryptographically weak and defeats the purpose of using OpenSSL, which is why it is highly discouraged. */ logprintf (LOG_NOTQUIET, _("WARNING: using a weak random seed.\n")); while (RAND_status () == 0 && maxrand-- > 0) { unsigned char rnd = random_number (256); RAND_seed (&rnd, sizeof (rnd)); } } #endif }
/** Initialize the SSL context. * \return pointer to SSL context object. */ SSL_CTX * ssl_init(char *private_key_file, char *ca_file, int req_client_cert) { const SSL_METHOD *meth; /* If this const gives you a warning, you're using an old version of OpenSSL. */ unsigned char context[128]; DH *dh; unsigned int reps = 1; if (!bio_err) { if (!SSL_library_init()) return NULL; SSL_load_error_strings(); /* Error write context */ bio_err = BIO_new_fp(stderr, BIO_NOCLOSE); } do_rawlog(LT_ERR, "Seeding OpenSSL random number pool."); while (!RAND_status()) { /* At this point, a system with /dev/urandom or a EGD file in the usual places will have enough entropy. Otherwise, be lazy and use random numbers until it's satisfied. */ uint32_t gibberish[4]; int n; for (n = 0; n < 4; n++) gibberish[n] = gen_rand32(); RAND_seed(gibberish, sizeof gibberish); reps += 1; } do_rawlog(LT_ERR, "Seeded after %u %s.", reps, reps > 1 ? "cycles" : "cycle"); /* Set up SIGPIPE handler here? */ /* Create context */ meth = SSLv23_server_method(); ctx = SSL_CTX_new(meth); /* Load keys/certs */ if (private_key_file && *private_key_file) { if (!SSL_CTX_use_certificate_chain_file(ctx, private_key_file)) { ssl_errordump ("Unable to load server certificate - only anonymous ciphers supported."); } if (!SSL_CTX_use_PrivateKey_file(ctx, private_key_file, SSL_FILETYPE_PEM)) { ssl_errordump ("Unable to load private key - only anonymous ciphers supported."); } } /* Load trusted CAs */ if (ca_file && *ca_file) { if (!SSL_CTX_load_verify_locations(ctx, ca_file, NULL)) { ssl_errordump("Unable to load CA certificates"); } else { if (req_client_cert) SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, client_verify_callback); else SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, client_verify_callback); #if (OPENSSL_VERSION_NUMBER < 0x0090600fL) SSL_CTX_set_verify_depth(ctx, 1); #endif } } SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE | SSL_OP_ALL); SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); /* Set up DH callback */ dh = get_dh1024(); SSL_CTX_set_tmp_dh(ctx, dh); /* The above function makes a private copy of this */ DH_free(dh); /* Set the cipher list to the usual default list, except that * we'll allow anonymous diffie-hellman, too. */ SSL_CTX_set_cipher_list(ctx, "ALL:ADH:RC4+RSA:+SSLv2:@STRENGTH"); /* Set up session cache if we can */ strncpy((char *) context, MUDNAME, 128); SSL_CTX_set_session_id_context(ctx, context, u_strlen(context)); /* Load hash algorithms */ OpenSSL_add_all_digests(); return ctx; }
/** Main routine for unbound-control */ int main(int argc, char* argv[]) { int c, ret; int quiet = 0; const char* cfgfile = CONFIGFILE; char* svr = NULL; #ifdef USE_WINSOCK int r; WSADATA wsa_data; #endif #ifdef USE_THREAD_DEBUG /* stop the file output from unbound-control, overwites the servers */ extern int check_locking_order; check_locking_order = 0; #endif /* USE_THREAD_DEBUG */ log_ident_set("unbound-control"); log_init(NULL, 0, NULL); checklock_start(); #ifdef USE_WINSOCK if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0) fatal_exit("WSAStartup failed: %s", wsa_strerror(r)); /* use registry config file in preference to compiletime location */ if(!(cfgfile=w_lookup_reg_str("Software\\Unbound", "ConfigFile"))) cfgfile = CONFIGFILE; #endif ERR_load_crypto_strings(); ERR_load_SSL_strings(); OpenSSL_add_all_algorithms(); (void)SSL_library_init(); if(!RAND_status()) { /* try to seed it */ unsigned char buf[256]; unsigned int seed=(unsigned)time(NULL) ^ (unsigned)getpid(); unsigned int v = seed; size_t i; for(i=0; i<256/sizeof(v); i++) { memmove(buf+i*sizeof(v), &v, sizeof(v)); v = v*seed + (unsigned int)i; } RAND_seed(buf, 256); log_warn("no entropy, seeding openssl PRNG with time\n"); } /* parse the options */ while( (c=getopt(argc, argv, "c:s:qh")) != -1) { switch(c) { case 'c': cfgfile = optarg; break; case 's': svr = optarg; break; case 'q': quiet = 1; break; case '?': case 'h': default: usage(); } } argc -= optind; argv += optind; if(argc == 0) usage(); if(argc >= 1 && strcmp(argv[0], "start")==0) { if(execlp("unbound", "unbound", "-c", cfgfile, (char*)NULL) < 0) { fatal_exit("could not exec unbound: %s", strerror(errno)); } } ret = go(cfgfile, svr, quiet, argc, argv); #ifdef USE_WINSOCK WSACleanup(); #endif checklock_stop(); return ret; }
void HC_DEPRECATED DES_set_random_generator_seed(DES_cblock *seed) { RAND_seed(seed, sizeof(*seed)); }
void HC_DEPRECATED DES_init_random_number_generator(DES_cblock *seed) { RAND_seed(seed, sizeof(*seed)); }
int main(int argc, char *argv[]) { BN_CTX *ctx; BIO *out; char *outfile=NULL; results = 0; RAND_seed(rnd_seed, sizeof rnd_seed); /* or BN_generate_prime may fail */ argc--; argv++; while (argc >= 1) { if (strcmp(*argv,"-results") == 0) results=1; else if (strcmp(*argv,"-out") == 0) { if (--argc < 1) break; outfile= *(++argv); } argc--; argv++; } ctx=BN_CTX_new(); if (ctx == NULL) EXIT(1); out=BIO_new(BIO_s_file()); if (out == NULL) EXIT(1); if (outfile == NULL) { BIO_set_fp(out,stdout,BIO_NOCLOSE); } else { if (!BIO_write_filename(out,outfile)) { perror(outfile); EXIT(1); } } if (!results) BIO_puts(out,"obase=16\nibase=16\n"); message(out,"BN_add"); if (!test_add(out)) goto err; (void)BIO_flush(out); message(out,"BN_sub"); if (!test_sub(out)) goto err; (void)BIO_flush(out); message(out,"BN_lshift1"); if (!test_lshift1(out)) goto err; (void)BIO_flush(out); message(out,"BN_lshift (fixed)"); if (!test_lshift(out,ctx,BN_bin2bn(lst,sizeof(lst)-1,NULL))) goto err; (void)BIO_flush(out); message(out,"BN_lshift"); if (!test_lshift(out,ctx,NULL)) goto err; (void)BIO_flush(out); message(out,"BN_rshift1"); if (!test_rshift1(out)) goto err; (void)BIO_flush(out); message(out,"BN_rshift"); if (!test_rshift(out,ctx)) goto err; (void)BIO_flush(out); message(out,"BN_sqr"); if (!test_sqr(out,ctx)) goto err; (void)BIO_flush(out); message(out,"BN_mul"); if (!test_mul(out)) goto err; (void)BIO_flush(out); message(out,"BN_div"); if (!test_div(out,ctx)) goto err; (void)BIO_flush(out); message(out,"BN_div_word"); if (!test_div_word(out)) goto err; (void)BIO_flush(out); message(out,"BN_div_recp"); if (!test_div_recp(out,ctx)) goto err; (void)BIO_flush(out); message(out,"BN_mod"); if (!test_mod(out,ctx)) goto err; (void)BIO_flush(out); message(out,"BN_mod_mul"); if (!test_mod_mul(out,ctx)) goto err; (void)BIO_flush(out); message(out,"BN_mont"); if (!test_mont(out,ctx)) goto err; (void)BIO_flush(out); message(out,"BN_mod_exp"); if (!test_mod_exp(out,ctx)) goto err; (void)BIO_flush(out); message(out,"BN_mod_exp_mont_consttime"); if (!test_mod_exp_mont_consttime(out,ctx)) goto err; if (!test_mod_exp_mont5(out,ctx)) goto err; (void)BIO_flush(out); message(out,"BN_exp"); if (!test_exp(out,ctx)) goto err; (void)BIO_flush(out); message(out,"BN_kronecker"); if (!test_kron(out,ctx)) goto err; (void)BIO_flush(out); message(out,"BN_mod_sqrt"); if (!test_sqrt(out,ctx)) goto err; (void)BIO_flush(out); message(out,"Small prime generation"); if (!test_small_prime(out,ctx)) goto err; (void)BIO_flush(out); #ifndef OPENSSL_NO_EC2M message(out,"BN_GF2m_add"); if (!test_gf2m_add(out)) goto err; (void)BIO_flush(out); message(out,"BN_GF2m_mod"); if (!test_gf2m_mod(out)) goto err; (void)BIO_flush(out); message(out,"BN_GF2m_mod_mul"); if (!test_gf2m_mod_mul(out,ctx)) goto err; (void)BIO_flush(out); message(out,"BN_GF2m_mod_sqr"); if (!test_gf2m_mod_sqr(out,ctx)) goto err; (void)BIO_flush(out); message(out,"BN_GF2m_mod_inv"); if (!test_gf2m_mod_inv(out,ctx)) goto err; (void)BIO_flush(out); message(out,"BN_GF2m_mod_div"); if (!test_gf2m_mod_div(out,ctx)) goto err; (void)BIO_flush(out); message(out,"BN_GF2m_mod_exp"); if (!test_gf2m_mod_exp(out,ctx)) goto err; (void)BIO_flush(out); message(out,"BN_GF2m_mod_sqrt"); if (!test_gf2m_mod_sqrt(out,ctx)) goto err; (void)BIO_flush(out); message(out,"BN_GF2m_mod_solve_quad"); if (!test_gf2m_mod_solve_quad(out,ctx)) goto err; (void)BIO_flush(out); #endif BN_CTX_free(ctx); BIO_free(out); /**/ EXIT(0); err: BIO_puts(out,"1\n"); /* make sure the Perl script fed by bc notices * the failure, see test_bn in test/Makefile.ssl*/ (void)BIO_flush(out); ERR_load_crypto_strings(); ERR_print_errors_fp(stderr); EXIT(1); return(1); }
void nsock_init(void) { u_char seeded = 0; u_int rand_seed; #if defined(HAVE_DEV_RANDOM) || defined(HAVE_DEV_URANDOM) FILE *fp; u_char *rand_file; #endif #ifdef HAVE_SSL u_char entropy_pool[128]; u_char ssl_seeded = 0; u_int i; #endif /* first we must initialize our pseudo-random generators */ #if defined(HAVE_DEV_RANDOM) || defined(HAVE_DEV_URANDOM) /* figure out which file to use if we have one */ # if defined(HAVE_DEV_RANDOM) rand_file = (u_char *)"/dev/random"; # elif defined(HAVE_DEV_URANDOM) rand_file = (u_char *)"/dev/urandom"; # endif /* get some random bytes from our pool */ fp = fopen((char *)rand_file, "r"); if (fp) { /* seed the random number generator from the dev */ if (fread(&rand_seed, sizeof(rand_seed), 1, fp) == 1) { srandom(rand_seed); memset(&rand_seed, 0, sizeof(rand_seed)); seeded = 1; } # ifdef HAVE_SSL if (fread(entropy_pool, sizeof(entropy_pool), 1, fp) == 1) { RAND_seed(entropy_pool, sizeof(entropy_pool)); ssl_seeded = 1; } # endif fclose(fp); } #endif /* if we failed to seed any of the required values, lets do crappy seeding here */ if (!seeded) { rand_seed = getpid() + time(NULL); srandom(rand_seed); memset(&rand_seed, 0, sizeof(rand_seed)); } #ifdef HAVE_SSL /* initialize ssl stuff */ SSL_load_error_strings(); SSL_library_init(); if (!ssl_seeded) { for (i = 0; i < sizeof(entropy_pool); i++) entropy_pool[i] = (u_char)(random() & 0xff); RAND_seed(entropy_pool, sizeof(entropy_pool)); } #endif /* any other initialization stuff shall go here. */ }
int tls_init_library(void) { unsigned int rnd; tls_cnx_handshook = 0; tls_data_cnx_handshook = 0; SSL_library_init(); SSL_load_error_strings(); OpenSSL_add_all_algorithms(); while (RAND_status() == 0) { rnd = zrand(); RAND_seed(&rnd, (int) sizeof rnd); } if ((tls_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) { tls_error(__LINE__, 0); } # ifdef SSL_OP_CIPHER_SERVER_PREFERENCE SSL_CTX_set_options(tls_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE); # endif # ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION SSL_CTX_set_options(tls_ctx, SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); # endif SSL_CTX_set_options(tls_ctx, SSL_OP_NO_SSLv2); SSL_CTX_set_options(tls_ctx, SSL_OP_NO_SSLv3); # ifdef SSL_OP_NO_TLSv1 SSL_CTX_clear_options(tls_ctx, SSL_OP_NO_TLSv1); # endif # ifdef SSL_OP_NO_TLSv1_1 SSL_CTX_clear_options(tls_ctx, SSL_OP_NO_TLSv1_1); # endif # ifdef SSL_OP_NO_TLSv1_2 SSL_CTX_clear_options(tls_ctx, SSL_OP_NO_TLSv1_2); # endif if (tlsciphersuite != NULL) { if (SSL_CTX_set_cipher_list(tls_ctx, tlsciphersuite) != 1) { logfile(LOG_ERR, MSG_TLS_CIPHER_FAILED, tlsciphersuite); _EXIT(EXIT_FAILURE); } } if (SSL_CTX_use_certificate_chain_file(tls_ctx, cert_file) != 1) { die(421, LOG_ERR, MSG_FILE_DOESNT_EXIST ": [%s]", cert_file); } if (SSL_CTX_use_PrivateKey_file(tls_ctx, cert_file, SSL_FILETYPE_PEM) != 1) { tls_error(__LINE__, 0); } if (SSL_CTX_check_private_key(tls_ctx) != 1) { tls_error(__LINE__, 0); } tls_init_cache(); # ifdef SSL_CTRL_SET_ECDH_AUTO SSL_CTX_ctrl(tls_ctx, SSL_CTRL_SET_ECDH_AUTO, 1, NULL); # else tls_init_ecdh_curve(); # endif # ifdef SSL_CTRL_SET_DH_AUTO if (tls_init_dhparams() != 0) { SSL_CTX_ctrl(tls_ctx, SSL_CTRL_SET_DH_AUTO, 1, NULL); } # else if (tls_init_dhparams() != 0) { tls_init_dhparams_default(); } # endif # ifdef DISABLE_SSL_RENEGOTIATION SSL_CTX_set_info_callback(tls_ctx, ssl_info_cb); # endif SSL_CTX_set_verify_depth(tls_ctx, 6); if (ssl_verify_client_cert) { SSL_CTX_set_verify(tls_ctx, SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_PEER, NULL); if (SSL_CTX_load_verify_locations(tls_ctx, cert_file, NULL) != 1) { tls_error(__LINE__, 0); } } return 0; }
int main(int argc, char **argv) { int i; sigset_t set; #if ENABLE_MPEGTS uint32_t adapter_mask = 0; #endif int log_level = LOG_INFO; int log_options = TVHLOG_OPT_MILLIS | TVHLOG_OPT_STDERR | TVHLOG_OPT_SYSLOG; const char *log_debug = NULL, *log_trace = NULL; gid_t gid = -1; uid_t uid = -1; char buf[512]; FILE *pidfile = NULL; static struct { void *thread_id; struct timeval tv; uint8_t ru[32]; } randseed; extern int dvb_bouquets_parse; main_tid = pthread_self(); /* Setup global mutexes */ pthread_mutex_init(&fork_lock, NULL); pthread_mutex_init(&global_lock, NULL); pthread_mutex_init(&tasklet_lock, NULL); pthread_mutex_init(&atomic_lock, NULL); pthread_cond_init(>imer_cond, NULL); pthread_cond_init(&tasklet_cond, NULL); TAILQ_INIT(&tasklets); /* Defaults */ tvheadend_webui_port = 9981; tvheadend_webroot = NULL; tvheadend_htsp_port = 9982; tvheadend_htsp_port_extra = 0; time(&dispatch_clock); /* Command line options */ int opt_help = 0, opt_version = 0, opt_fork = 0, opt_firstrun = 0, opt_stderr = 0, opt_nostderr = 0, opt_syslog = 0, opt_nosyslog = 0, opt_uidebug = 0, opt_abort = 0, opt_noacl = 0, opt_fileline = 0, opt_threadid = 0, opt_libav = 0, opt_ipv6 = 0, opt_nosatip = 0, opt_satip_rtsp = 0, #if ENABLE_TSFILE opt_tsfile_tuner = 0, #endif opt_dump = 0, opt_xspf = 0, opt_dbus = 0, opt_dbus_session = 0, opt_nobackup = 0, opt_nobat = 0; const char *opt_config = NULL, *opt_user = NULL, *opt_group = NULL, *opt_logpath = NULL, *opt_log_debug = NULL, *opt_log_trace = NULL, *opt_pidpath = "/var/run/tvheadend.pid", #if ENABLE_LINUXDVB *opt_dvb_adapters = NULL, #endif *opt_bindaddr = NULL, *opt_subscribe = NULL, *opt_user_agent = NULL; str_list_t opt_satip_xml = { .max = 10, .num = 0, .str = calloc(10, sizeof(char*)) }; str_list_t opt_tsfile = { .max = 10, .num = 0, .str = calloc(10, sizeof(char*)) }; cmdline_opt_t cmdline_opts[] = { { 0, NULL, N_("Generic options"), OPT_BOOL, NULL }, { 'h', "help", N_("Show this page"), OPT_BOOL, &opt_help }, { 'v', "version", N_("Show version information"),OPT_BOOL, &opt_version }, { 0, NULL, N_("Service configuration"), OPT_BOOL, NULL }, { 'c', "config", N_("Alternate configuration path"), OPT_STR, &opt_config }, { 'B', "nobackup", N_("Don't backup configuration tree at upgrade"), OPT_BOOL, &opt_nobackup }, { 'f', "fork", N_("Fork and run as daemon"), OPT_BOOL, &opt_fork }, { 'u', "user", N_("Run as user"), OPT_STR, &opt_user }, { 'g', "group", N_("Run as group"), OPT_STR, &opt_group }, { 'p', "pid", N_("Alternate PID path"), OPT_STR, &opt_pidpath }, { 'C', "firstrun", N_("If no user account exists then create one with\n" "no username and no password. Use with care as\n" "it will allow world-wide administrative access\n" "to your Tvheadend installation until you create or edit\n" "the access control from within the Tvheadend web interface."), OPT_BOOL, &opt_firstrun }, #if ENABLE_DBUS_1 { 'U', "dbus", N_("Enable DBus"), OPT_BOOL, &opt_dbus }, { 'e', "dbus_session", N_("DBus - use the session message bus instead of the system one"), OPT_BOOL, &opt_dbus_session }, #endif #if ENABLE_LINUXDVB { 'a', "adapters", N_("Only use specified DVB adapters (comma separated, -1 = none)"), OPT_STR, &opt_dvb_adapters }, #endif #if ENABLE_SATIP_SERVER { 0, "satip_rtsp", N_("SAT>IP RTSP port number for server\n" "(default: -1 = disable, 0 = webconfig, standard port is 554)"), OPT_INT, &opt_satip_rtsp }, #endif #if ENABLE_SATIP_CLIENT { 0, "nosatip", N_("Disable SAT>IP client"), OPT_BOOL, &opt_nosatip }, { 0, "satip_xml", N_("URL with the SAT>IP server XML location"), OPT_STR_LIST, &opt_satip_xml }, #endif { 0, NULL, N_("Server connectivity"), OPT_BOOL, NULL }, { '6', "ipv6", N_("Listen on IPv6"), OPT_BOOL, &opt_ipv6 }, { 'b', "bindaddr", N_("Specify bind address"), OPT_STR, &opt_bindaddr}, { 0, "http_port", N_("Specify alternative http port"), OPT_INT, &tvheadend_webui_port }, { 0, "http_root", N_("Specify alternative http webroot"), OPT_STR, &tvheadend_webroot }, { 0, "htsp_port", N_("Specify alternative htsp port"), OPT_INT, &tvheadend_htsp_port }, { 0, "htsp_port2", N_("Specify extra htsp port"), OPT_INT, &tvheadend_htsp_port_extra }, { 0, "useragent", N_("Specify User-Agent header for the http client"), OPT_STR, &opt_user_agent }, { 0, "xspf", N_("Use XSPF playlist instead of M3U"), OPT_BOOL, &opt_xspf }, { 0, NULL, N_("Debug options"), OPT_BOOL, NULL }, { 'd', "stderr", N_("Enable debug on stderr"), OPT_BOOL, &opt_stderr }, { 'n', "nostderr", N_("Disable debug on stderr"), OPT_BOOL, &opt_nostderr }, { 's', "syslog", N_("Enable debug to syslog"), OPT_BOOL, &opt_syslog }, { 'S', "nosyslog", N_("Disable syslog (all messages)"), OPT_BOOL, &opt_nosyslog }, { 'l', "logfile", N_("Enable debug to file"), OPT_STR, &opt_logpath }, { 0, "debug", N_("Enable debug subsystems"), OPT_STR, &opt_log_debug }, #if ENABLE_TRACE { 0, "trace", N_("Enable trace subsystems"), OPT_STR, &opt_log_trace }, #endif { 0, "fileline", N_("Add file and line numbers to debug"), OPT_BOOL, &opt_fileline }, { 0, "threadid", N_("Add the thread ID to debug"), OPT_BOOL, &opt_threadid }, #if ENABLE_LIBAV { 0, "libav", N_("More verbose libav log"), OPT_BOOL, &opt_libav }, #endif { 0, "uidebug", N_("Enable web UI debug (non-minified JS)"), OPT_BOOL, &opt_uidebug }, { 'A', "abort", N_("Immediately abort"), OPT_BOOL, &opt_abort }, { 'D', "dump", N_("Enable coredumps for daemon"), OPT_BOOL, &opt_dump }, { 0, "noacl", N_("Disable all access control checks"), OPT_BOOL, &opt_noacl }, { 0, "nobat", N_("Disable DVB bouquets"), OPT_BOOL, &opt_nobat }, { 'j', "join", N_("Subscribe to a service permanently"), OPT_STR, &opt_subscribe }, #if ENABLE_TSFILE || ENABLE_TSDEBUG { 0, NULL, N_("Testing options"), OPT_BOOL, NULL }, { 0, "tsfile_tuners", N_("Number of tsfile tuners"), OPT_INT, &opt_tsfile_tuner }, { 0, "tsfile", N_("tsfile input (mux file)"), OPT_STR_LIST, &opt_tsfile }, #endif #if ENABLE_TSDEBUG { 0, "tsdebug", N_("Output directory for tsdebug"), OPT_STR, &tvheadend_tsdebug }, #endif }; /* Get current directory */ tvheadend_cwd0 = dirname(tvh_strdupa(argv[0])); tvheadend_cwd = dirname(tvh_strdupa(tvheadend_cwd0)); /* Set locale */ setlocale(LC_ALL, ""); setlocale(LC_NUMERIC, "C"); tvh_gettext_init(); /* make sure the timezone is set */ tzset(); /* Process command line */ for (i = 1; i < argc; i++) { /* Find option */ cmdline_opt_t *opt = cmdline_opt_find(cmdline_opts, ARRAY_SIZE(cmdline_opts), argv[i]); if (!opt) { show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts), _("invalid option specified [%s]"), argv[i]); continue; } /* Process */ if (opt->type == OPT_BOOL) *((int*)opt->param) = 1; else if (++i == argc) show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts), _("option %s requires a value"), opt->lopt); else if (opt->type == OPT_INT) *((int*)opt->param) = atoi(argv[i]); else if (opt->type == OPT_STR_LIST) { str_list_t *strl = opt->param; if (strl->num < strl->max) strl->str[strl->num++] = argv[i]; } else *((char**)opt->param) = argv[i]; /* Stop processing */ if (opt_help) show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts), NULL); if (opt_version) show_version(argv[0]); } /* Additional cmdline processing */ if (opt_nobat) dvb_bouquets_parse = 0; #if ENABLE_LINUXDVB if (!opt_dvb_adapters) { adapter_mask = ~0; } else { char *p, *e; char *r = NULL; char *dvb_adapters = strdup(opt_dvb_adapters); adapter_mask = 0x0; i = 0; p = strtok_r(dvb_adapters, ",", &r); while (p) { int a = strtol(p, &e, 10); if (*e != 0 || a > 31) { fprintf(stderr, _("Invalid adapter number '%s'\n"), p); free(dvb_adapters); return 1; } i = 1; if (a < 0) adapter_mask = 0; else adapter_mask |= (1 << a); p = strtok_r(NULL, ",", &r); } free(dvb_adapters); if (!i) { fprintf(stderr, "%s", _("No adapters specified!\n")); return 1; } } #endif if (tvheadend_webroot) { char *tmp; if (*tvheadend_webroot == '/') tmp = strdup(tvheadend_webroot); else { tmp = malloc(strlen(tvheadend_webroot)+2); *tmp = '/'; strcpy(tmp+1, tvheadend_webroot); } if (tmp[strlen(tmp)-1] == '/') tmp[strlen(tmp)-1] = '\0'; tvheadend_webroot = tmp; } tvheadend_webui_debug = opt_uidebug; /* Setup logging */ if (isatty(2)) log_options |= TVHLOG_OPT_DECORATE; if (opt_stderr || opt_syslog || opt_logpath) { if (!opt_log_trace && !opt_log_debug) log_debug = "all"; log_level = LOG_DEBUG; if (opt_stderr) log_options |= TVHLOG_OPT_DBG_STDERR; if (opt_syslog) log_options |= TVHLOG_OPT_DBG_SYSLOG; if (opt_logpath) log_options |= TVHLOG_OPT_DBG_FILE; } if (opt_nostderr) log_options &= ~(TVHLOG_OPT_DECORATE|TVHLOG_OPT_STDERR|TVHLOG_OPT_DBG_STDERR); if (opt_nosyslog) log_options &= ~(TVHLOG_OPT_SYSLOG|TVHLOG_OPT_DBG_SYSLOG); if (opt_fileline) log_options |= TVHLOG_OPT_FILELINE; if (opt_threadid) log_options |= TVHLOG_OPT_THREAD; if (opt_libav) log_options |= TVHLOG_OPT_LIBAV; if (opt_log_trace) { log_level = LOG_TRACE; log_trace = opt_log_trace; } if (opt_log_debug) log_debug = opt_log_debug; tvhlog_init(log_level, log_options, opt_logpath); tvhlog_set_debug(log_debug); tvhlog_set_trace(log_trace); tvhinfo("main", "Log started"); signal(SIGPIPE, handle_sigpipe); // will be redundant later signal(SIGILL, handle_sigill); // see handler.. /* Set priviledges */ if(opt_fork || opt_group || opt_user) { const char *homedir; struct group *grp = getgrnam(opt_group ?: "video"); struct passwd *pw = opt_user ? getpwnam(opt_user) : NULL; if(grp != NULL) { gid = grp->gr_gid; } else { gid = 1; } if (pw != NULL) { if (getuid() != pw->pw_uid) { gid_t glist[16]; int gnum; gnum = get_user_groups(pw, glist, ARRAY_SIZE(glist)); if (gnum > 0 && setgroups(gnum, glist)) { char buf[256] = ""; int i; for (i = 0; i < gnum; i++) snprintf(buf + strlen(buf), sizeof(buf) - 1 - strlen(buf), ",%d", glist[i]); tvhlog(LOG_ALERT, "START", "setgroups(%s) failed, do you have permission?", buf+1); return 1; } } uid = pw->pw_uid; homedir = pw->pw_dir; setenv("HOME", homedir, 1); } else { uid = 1; } } uuid_init(); config_boot(opt_config, gid, uid); tcp_server_preinit(opt_ipv6); http_server_init(opt_bindaddr); // bind to ports only htsp_init(opt_bindaddr); // bind to ports only satip_server_init(opt_satip_rtsp); // bind to ports only if (opt_fork) pidfile = tvh_fopen(opt_pidpath, "w+"); if (gid != -1 && (getgid() != gid) && setgid(gid)) { tvhlog(LOG_ALERT, "START", "setgid(%d) failed, do you have permission?", gid); return 1; } if (uid != -1 && (getuid() != uid) && setuid(uid)) { tvhlog(LOG_ALERT, "START", "setuid(%d) failed, do you have permission?", uid); return 1; } /* Daemonise */ if(opt_fork) { if(daemon(0, 0)) { exit(2); } if(pidfile != NULL) { fprintf(pidfile, "%d\n", getpid()); fclose(pidfile); } /* Make dumpable */ if (opt_dump) { #ifdef PLATFORM_LINUX if (chdir("/tmp")) tvhwarn("START", "failed to change cwd to /tmp"); prctl(PR_SET_DUMPABLE, 1); #else tvhwarn("START", "Coredumps not implemented on your platform"); #endif } umask(0); } tvheadend_running = 1; /* Start log thread (must be done post fork) */ tvhlog_start(); /* Alter logging */ if (opt_fork) tvhlog_options &= ~TVHLOG_OPT_STDERR; if (!isatty(2)) tvhlog_options &= ~TVHLOG_OPT_DECORATE; /* Initialise clock */ pthread_mutex_lock(&global_lock); time(&dispatch_clock); /* Signal handling */ sigfillset(&set); sigprocmask(SIG_BLOCK, &set, NULL); trap_init(argv[0]); /* SSL library init */ OPENSSL_config(NULL); SSL_load_error_strings(); SSL_library_init(); /* Rand seed */ randseed.thread_id = (void *)main_tid; gettimeofday(&randseed.tv, NULL); uuid_random(randseed.ru, sizeof(randseed.ru)); RAND_seed(&randseed, sizeof(randseed)); /* Initialise configuration */ notify_init(); idnode_init(); spawn_init(); config_init(opt_nobackup == 0); /** * Initialize subsystems */ epg_in_load = 1; tvhthread_create(&tasklet_tid, NULL, tasklet_thread, NULL, "tasklet"); dbus_server_init(opt_dbus, opt_dbus_session); intlconv_init(); api_init(); fsmonitor_init(); libav_init(); tvhtime_init(); profile_init(); imagecache_init(); http_client_init(opt_user_agent); esfilter_init(); bouquet_init(); service_init(); dvb_init(); #if ENABLE_MPEGTS mpegts_init(adapter_mask, opt_nosatip, &opt_satip_xml, &opt_tsfile, opt_tsfile_tuner); #endif channel_init(); bouquet_service_resolve(); subscription_init(); dvr_config_init(); access_init(opt_firstrun, opt_noacl); #if ENABLE_TIMESHIFT timeshift_init(); #endif tcp_server_init(); webui_init(opt_xspf); #if ENABLE_UPNP upnp_server_init(opt_bindaddr); #endif service_mapper_init(); descrambler_init(); epggrab_init(); epg_init(); dvr_init(); dbus_server_start(); http_server_register(); satip_server_register(); htsp_register(); if(opt_subscribe != NULL) subscription_dummy_join(opt_subscribe, 1); avahi_init(); bonjour_init(); epg_updated(); // cleanup now all prev ref's should have been created epg_in_load = 0; pthread_mutex_unlock(&global_lock); /** * Wait for SIGTERM / SIGINT, but only in this thread */ sigemptyset(&set); sigaddset(&set, SIGTERM); sigaddset(&set, SIGINT); signal(SIGTERM, doexit); signal(SIGINT, doexit); pthread_sigmask(SIG_UNBLOCK, &set, NULL); tvhlog(LOG_NOTICE, "START", "HTS Tvheadend version %s started, " "running as PID:%d UID:%d GID:%d, CWD:%s CNF:%s", tvheadend_version, getpid(), getuid(), getgid(), getcwd(buf, sizeof(buf)), hts_settings_get_root()); if(opt_abort) abort(); mainloop(); #if ENABLE_DBUS_1 tvhftrace("main", dbus_server_done); #endif #if ENABLE_UPNP tvhftrace("main", upnp_server_done); #endif tvhftrace("main", satip_server_done); tvhftrace("main", htsp_done); tvhftrace("main", http_server_done); tvhftrace("main", webui_done); tvhftrace("main", fsmonitor_done); tvhftrace("main", http_client_done); tvhftrace("main", tcp_server_done); // Note: the locking is obviously a bit redundant, but without // we need to disable the gtimer_arm call in epg_save() pthread_mutex_lock(&global_lock); tvhftrace("main", epg_save); #if ENABLE_TIMESHIFT tvhftrace("main", timeshift_term); #endif pthread_mutex_unlock(&global_lock); tvhftrace("main", epggrab_done); #if ENABLE_MPEGTS tvhftrace("main", mpegts_done); #endif tvhftrace("main", descrambler_done); tvhftrace("main", service_mapper_done); tvhftrace("main", service_done); tvhftrace("main", channel_done); tvhftrace("main", bouquet_done); tvhftrace("main", dvr_done); tvhftrace("main", subscription_done); tvhftrace("main", access_done); tvhftrace("main", epg_done); tvhftrace("main", avahi_done); tvhftrace("main", bonjour_done); tvhftrace("main", imagecache_done); tvhftrace("main", lang_code_done); tvhftrace("main", api_done); tvhtrace("main", "tasklet enter"); pthread_cond_signal(&tasklet_cond); pthread_join(tasklet_tid, NULL); tvhtrace("main", "tasklet thread end"); tasklet_flush(); tvhtrace("main", "tasklet leave"); tvhftrace("main", hts_settings_done); tvhftrace("main", dvb_done); tvhftrace("main", lang_str_done); tvhftrace("main", esfilter_done); tvhftrace("main", profile_done); tvhftrace("main", intlconv_done); tvhftrace("main", urlparse_done); tvhftrace("main", idnode_done); tvhftrace("main", notify_done); tvhftrace("main", spawn_done); tvhlog(LOG_NOTICE, "STOP", "Exiting HTS Tvheadend"); tvhlog_end(); tvhftrace("main", config_done); if(opt_fork) unlink(opt_pidpath); #if ENABLE_TSFILE free(opt_tsfile.str); #endif free(opt_satip_xml.str); /* OpenSSL - welcome to the "cleanup" hell */ ENGINE_cleanup(); RAND_cleanup(); CRYPTO_cleanup_all_ex_data(); EVP_cleanup(); CONF_modules_free(); #ifndef OPENSSL_NO_COMP COMP_zlib_cleanup(); #endif ERR_remove_state(0); ERR_free_strings(); #ifndef OPENSSL_NO_COMP sk_SSL_COMP_free(SSL_COMP_get_compression_methods()); #endif /* end of OpenSSL cleanup code */ #if ENABLE_DBUS_1 extern void dbus_shutdown(void); if (opt_dbus) dbus_shutdown(); #endif tvh_gettext_done(); return 0; } /** * */ void tvh_str_set(char **strp, const char *src) { free(*strp); *strp = src ? strdup(src) : NULL; } /** * */ int tvh_str_update(char **strp, const char *src) { if(src == NULL) return 0; free(*strp); *strp = strdup(src); return 1; } /** * */ void scopedunlock(pthread_mutex_t **mtxp) { pthread_mutex_unlock(*mtxp); }
int main(int argc, char *argv[]) { BN_CTX *ctx; BIO *out = NULL; int i, ret; unsigned char c; BIGNUM *r_mont, *r_mont_const, *r_recp, *r_simple, *a, *b, *m; RAND_seed(rnd_seed, sizeof rnd_seed); /* or BN_rand may fail, and we * don't even check its return * value (which we should) */ ERR_load_BN_strings(); ctx = BN_CTX_new(); if (ctx == NULL) EXIT(1); r_mont = BN_new(); r_mont_const = BN_new(); r_recp = BN_new(); r_simple = BN_new(); a = BN_new(); b = BN_new(); m = BN_new(); if ((r_mont == NULL) || (r_recp == NULL) || (a == NULL) || (b == NULL)) goto err; out = BIO_new(BIO_s_file()); if (out == NULL) EXIT(1); BIO_set_fp(out, stdout, BIO_NOCLOSE); for (i = 0; i < 200; i++) { RAND_bytes(&c, 1); c = (c % BN_BITS) - BN_BITS2; BN_rand(a, NUM_BITS + c, 0, 0); RAND_bytes(&c, 1); c = (c % BN_BITS) - BN_BITS2; BN_rand(b, NUM_BITS + c, 0, 0); RAND_bytes(&c, 1); c = (c % BN_BITS) - BN_BITS2; BN_rand(m, NUM_BITS + c, 0, 1); BN_mod(a, a, m, ctx); BN_mod(b, b, m, ctx); ret = BN_mod_exp_mont(r_mont, a, b, m, ctx, NULL); if (ret <= 0) { printf("BN_mod_exp_mont() problems\n"); ERR_print_errors(out); EXIT(1); } ret = BN_mod_exp_recp(r_recp, a, b, m, ctx); if (ret <= 0) { printf("BN_mod_exp_recp() problems\n"); ERR_print_errors(out); EXIT(1); } ret = BN_mod_exp_simple(r_simple, a, b, m, ctx); if (ret <= 0) { printf("BN_mod_exp_simple() problems\n"); ERR_print_errors(out); EXIT(1); } ret = BN_mod_exp_mont_consttime(r_mont_const, a, b, m, ctx, NULL); if (ret <= 0) { printf("BN_mod_exp_mont_consttime() problems\n"); ERR_print_errors(out); EXIT(1); } if (BN_cmp(r_simple, r_mont) == 0 && BN_cmp(r_simple, r_recp) == 0 && BN_cmp(r_simple, r_mont_const) == 0) { printf("."); fflush(stdout); } else { if (BN_cmp(r_simple, r_mont) != 0) printf("\nsimple and mont results differ\n"); if (BN_cmp(r_simple, r_mont_const) != 0) printf("\nsimple and mont const time results differ\n"); if (BN_cmp(r_simple, r_recp) != 0) printf("\nsimple and recp results differ\n"); printf("a (%3d) = ", BN_num_bits(a)); BN_print(out, a); printf("\nb (%3d) = ", BN_num_bits(b)); BN_print(out, b); printf("\nm (%3d) = ", BN_num_bits(m)); BN_print(out, m); printf("\nsimple ="); BN_print(out, r_simple); printf("\nrecp ="); BN_print(out, r_recp); printf("\nmont ="); BN_print(out, r_mont); printf("\nmont_ct ="); BN_print(out, r_mont_const); printf("\n"); EXIT(1); } } BN_free(r_mont); BN_free(r_mont_const); BN_free(r_recp); BN_free(r_simple); BN_free(a); BN_free(b); BN_free(m); BN_CTX_free(ctx); ERR_remove_thread_state(NULL); CRYPTO_mem_leaks(out); BIO_free(out); printf("\n"); if (test_exp_mod_zero() != 0) goto err; printf("done\n"); EXIT(0); err: ERR_load_crypto_strings(); ERR_print_errors(out); #ifdef OPENSSL_SYS_NETWARE printf("ERROR\n"); #endif EXIT(1); return (1); }
int main( int argc, char ** argv ) { int ret; char *function = "Tspi_TESI_Init"; TSS_RESULT result = 0; TSS_HKEY hCAKey; TSS_HKEY hSignKey; TSS_HKEY hReloadKey; TSS_HKEY hReloadPubKey; X509_REQ * cert_req; X509 * cert; char uuid[DIGEST_SIZE*2]; char buf[4096]; RSA * rsa; RSA * rsa1; RSA * rsa2; if(argc!=3) { printf("Error Usage: Should be %s [CA_name] [Key_passwd])",argv[0]); return -EINVAL; } OpenSSL_add_all_algorithms(); ERR_load_crypto_strings(); result=TESI_Local_Reload(); if ( result != TSS_SUCCESS ) { printf("TESI_Local_Load Err!\n"); return result; } int num=1024; result=TESI_Local_GetRandom(buf,num); if(result == TSS_SUCCESS) printf("Get %d Random num SUCCEED!\n",num); else return -EINVAL; RAND_seed(buf,num); rsa=Generate_RSA_Key(); if(rsa==NULL) { printf("Generate RSA Key Failed!\n"); return -EINVAL; } printf("Generate RSA Key Succeed!\n",num); WritePrivKey(rsa,argv[1],argv[2]); WritePubKey(rsa,argv[1]); result=ReadPubKey(&rsa1,argv[1]); if(result != TSS_SUCCESS) return -EINVAL; result=ReadPrivKey(&rsa2,argv[1],argv[2]); if(result != TSS_SUCCESS) return -EINVAL; result=Create_X509_RSA_Cert(argv[1],6,entries,rsa1,rsa2); return result; }
int main(int argc, char **argv) { Buffer b; Options options; Key *keys[2], *key; struct passwd *pw; int key_fd[2], i, found, version = 2, fd; u_char *signature, *data; char *host; u_int slen, dlen; u_int32_t rnd[256]; key_fd[0] = open(_PATH_HOST_RSA_KEY_FILE, O_RDONLY); key_fd[1] = open(_PATH_HOST_DSA_KEY_FILE, O_RDONLY); seteuid(getuid()); setuid(getuid()); init_rng(); seed_rng(); arc4random_stir(); #ifdef DEBUG_SSH_KEYSIGN log_init("ssh-keysign", SYSLOG_LEVEL_DEBUG3, SYSLOG_FACILITY_AUTH, 0); #endif /* verify that ssh-keysign is enabled by the admin */ original_real_uid = getuid(); /* XXX readconf.c needs this */ initialize_options(&options); (void)read_config_file(_PATH_HOST_CONFIG_FILE, "", &options); fill_default_options(&options); if (options.enable_ssh_keysign != 1) fatal("ssh-keysign not enabled in %s", _PATH_HOST_CONFIG_FILE); if (key_fd[0] == -1 && key_fd[1] == -1) fatal("could not open any host key"); if ((pw = getpwuid(getuid())) == NULL) fatal("getpwuid failed"); pw = pwcopy(pw); SSLeay_add_all_algorithms(); for (i = 0; i < 256; i++) rnd[i] = arc4random(); RAND_seed(rnd, sizeof(rnd)); found = 0; for (i = 0; i < 2; i++) { keys[i] = NULL; if (key_fd[i] == -1) continue; keys[i] = key_load_private_pem(key_fd[i], KEY_UNSPEC, NULL, NULL); close(key_fd[i]); if (keys[i] != NULL) found = 1; } if (!found) fatal("no hostkey found"); buffer_init(&b); if (ssh_msg_recv(STDIN_FILENO, &b) < 0) fatal("ssh_msg_recv failed"); if (buffer_get_char(&b) != version) fatal("bad version"); fd = buffer_get_int(&b); if ((fd == STDIN_FILENO) || (fd == STDOUT_FILENO)) fatal("bad fd"); if ((host = get_local_name(fd)) == NULL) fatal("cannot get sockname for fd"); data = buffer_get_string(&b, &dlen); if (valid_request(pw, host, &key, data, dlen) < 0) fatal("not a valid request"); xfree(host); found = 0; for (i = 0; i < 2; i++) { if (keys[i] != NULL && key_equal(key, keys[i])) { found = 1; break; } } if (!found) fatal("no matching hostkey found"); if (key_sign(keys[i], &signature, &slen, data, dlen) != 0) fatal("key_sign failed"); xfree(data); /* send reply */ buffer_clear(&b); buffer_put_string(&b, signature, slen); ssh_msg_send(STDOUT_FILENO, version, &b); return (0); }
int main(int argc, char *argv[]) { BN_CTX *ctx = NULL; int ret = 1; BIO *out; CRYPTO_malloc_debug_init(); CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); #ifdef OPENSSL_SYS_WIN32 CRYPTO_malloc_init(); #endif RAND_seed(rnd_seed, sizeof rnd_seed); out = BIO_new(BIO_s_file()); if (out == NULL) EXIT(1); BIO_set_fp(out, stdout, BIO_NOCLOSE); if ((ctx = BN_CTX_new()) == NULL) goto err; /* NIST PRIME CURVES TESTS */ if (!test_ecdh_curve(NID_X9_62_prime192v1, "NIST Prime-Curve P-192", ctx, out)) goto err; if (!test_ecdh_curve(NID_secp224r1, "NIST Prime-Curve P-224", ctx, out)) goto err; if (!test_ecdh_curve(NID_X9_62_prime256v1, "NIST Prime-Curve P-256", ctx, out)) goto err; if (!test_ecdh_curve(NID_secp384r1, "NIST Prime-Curve P-384", ctx, out)) goto err; if (!test_ecdh_curve(NID_secp521r1, "NIST Prime-Curve P-521", ctx, out)) goto err; /* NIST BINARY CURVES TESTS */ if (!test_ecdh_curve(NID_sect163k1, "NIST Binary-Curve K-163", ctx, out)) goto err; if (!test_ecdh_curve(NID_sect163r2, "NIST Binary-Curve B-163", ctx, out)) goto err; if (!test_ecdh_curve(NID_sect233k1, "NIST Binary-Curve K-233", ctx, out)) goto err; if (!test_ecdh_curve(NID_sect233r1, "NIST Binary-Curve B-233", ctx, out)) goto err; if (!test_ecdh_curve(NID_sect283k1, "NIST Binary-Curve K-283", ctx, out)) goto err; if (!test_ecdh_curve(NID_sect283r1, "NIST Binary-Curve B-283", ctx, out)) goto err; if (!test_ecdh_curve(NID_sect409k1, "NIST Binary-Curve K-409", ctx, out)) goto err; if (!test_ecdh_curve(NID_sect409r1, "NIST Binary-Curve B-409", ctx, out)) goto err; if (!test_ecdh_curve(NID_sect571k1, "NIST Binary-Curve K-571", ctx, out)) goto err; if (!test_ecdh_curve(NID_sect571r1, "NIST Binary-Curve B-571", ctx, out)) goto err; ret = 0; err: ERR_print_errors_fp(stderr); if (ctx) BN_CTX_free(ctx); BIO_free(out); CRYPTO_cleanup_all_ex_data(); ERR_remove_state(0); CRYPTO_mem_leaks_fp(stderr); EXIT(ret); return (ret); }
void Security::generateSessionKey() throw (SecurityException) { int seedSize; unsigned char seed[SEED_SIZE]; #ifndef _WINDOWS // Reads 256 bytes from file /dev/urandom and adds them to // PRNG to use as seed of the random number generator int fd = open("/dev/urandom", O_RDONLY); if (fd < 0) #ifdef MXHPUXPA // HP-UX PA-RISC // /dev/urandom file does not exist on HP-UX PA-RISK. If customers // do not choose to install the HP-UX Strong Random Number Generator // package which can be obtained from this link, provide the following // weak Random Number Generator { seedSize = WEAK_SEED_SIZE; if (seedGenerator((char*)seed) != seedSize) throw SecurityException(UNABLE_TO_SEED_RNG, NULL); } #else // other UNIX platforms throw SecurityException(UNABLE_TO_SEED_RNG, NULL); seedSize = SEED_SIZE; int num = 0; // This can infinitely loops if /dev/urandom does not return 256 bytes // However, it's very very unlikely to happen. while (num != seedSize) { int count = 0; count = read(fd, &seed[num], seedSize - num); if (count > 0) num += count; else if (count == 0) { close(fd); throw SecurityException(FAILED_GENERATE_RANDOM_NUM, NULL); } else //count < 0 { switch (errno) { #ifdef EINTR case EINTR: // Interrupted system call #endif #ifdef EAGAIN case EAGAIN: // Resource temporarily unavailable #endif /* No error, try again */ break; default: close(fd); throw SecurityException(FAILED_GENERATE_RANDOM_NUM, NULL); } } } close(fd); #endif //MXHPUXPA #else // _WINDOWS seedSize=SEED_SIZE; // Get a handle to the DLL module. HINSTANCE hLib = LoadLibrary(TEXT("advapi32.dll")); // Do the following to avoid the overhead of loading the entire CryptoAPI if (hLib) { BOOLEAN (APIENTRY *pfn)(void*, ULONG) = (BOOLEAN (APIENTRY *)(void*,ULONG))GetProcAddress(hLib, "SystemFunction036"); if (pfn) { if(!pfn(seed, seedSize)) { throw SecurityException(UNABLE_TO_SEED_RNG, NULL); } } } else { throw SecurityException(FAILED_LOADING_LIB, NULL); } #endif // _WINDOWS getMutex(); RAND_seed((const void *)seed, seedSize); // Check if the PRNG has been seeded with enough randomness if (!RAND_status ()) { releaseMutex(); throw SecurityException(UNABLE_TO_SEED_RNG, NULL); } // Generate 64 bytes of random number using the seed generated above int errcode = RAND_bytes((unsigned char*) &m_pwdKey.data.session_key[0], SESSION_KEYLEN + NONCE_SIZE); releaseMutex(); if (errcode != 1) throw SecurityException(SESSION_KEY_GENERATION_FAILED, NULL); // Get nonce sequence memcpy((char*) &m_nonceSeq, &m_pwdKey.data.nonce[NONCE_RANDOM], NONCE_SEQNUM); if (!m_littleEndian) { m_nonceSeq = swapByteOrderOfLL(m_nonceSeq); // Store the swap bytes back in nonce //intLLong.llVal = m_nonceSeq; memcpy(&m_pwdKey.data.nonce[NONCE_RANDOM], (char*) &m_nonceSeq, NONCE_SEQNUM); } // Set time when session key is generated m_keyTime = get_msts(); }
/* * RSA public cryptography function. * Encrypt 'in_len' bytes from 'plaintext' buffer with the public key contained in 'pub_key_file' * Parameter 'outlen' is the size of output buffer * It returns the envelope which has to be sent to the receiver or NULL if an error occurs. */ unsigned char* asym_crypto(unsigned char* plaintext, int in_len, int* out_len, char* pub_key_file){ EVP_PKEY* pubkey; int ret; EVP_CIPHER_CTX* ctx; unsigned char* encrypted_key; int encrypted_key_len; unsigned char* iv; int iv_len; unsigned char* ciphertext; int cipher_len; int app; unsigned char* output; int total_output_size = 0; if(plaintext == NULL || in_len < 0 || out_len == NULL || pub_key_file == NULL) return NULL; //Reads the receiver's public key for its file pubkey = retrieve_pubkey(pub_key_file); if(pubkey == NULL) return NULL; encrypted_key_len = EVP_PKEY_size(pubkey); total_output_size += encrypted_key_len; iv_len = EVP_CIPHER_iv_length(SYM_CIPHER); total_output_size += iv_len; //Allocation of encrypted symmetric key and initialization vector encrypted_key = malloc(encrypted_key_len); iv = malloc(iv_len); //Seeding the RNG RAND_seed(iv, 8); //Instantiate and initialize the context ctx = (EVP_CIPHER_CTX*)malloc(sizeof(EVP_CIPHER_CTX)); EVP_CIPHER_CTX_init(ctx); ret = EVP_SealInit(ctx, SYM_CIPHER, &encrypted_key, &encrypted_key_len, iv, &pubkey ,1); if(ret == 0){ fprintf(stderr, "Error in SealInit\n"); goto error; } //Encrypt the input buffer cipher_len = in_len + EVP_CIPHER_block_size(SYM_CIPHER); ciphertext = malloc(cipher_len); cipher_len = 0; ret = EVP_SealUpdate(ctx, ciphertext, &app, plaintext, in_len); cipher_len += app; if(ret == 0){ fprintf(stderr, "Error in SealUpdate\n"); goto error; } ret = EVP_SealFinal(ctx, ciphertext + app, &app); cipher_len += app; if(ret == 0){ fprintf(stderr, "Error in SealFinal\n"); goto error; } total_output_size += cipher_len; //Concatenates the envelop in the outbuffer with format: <IV><Dim_Key><Ecrypt_KEY><Ciphertext> total_output_size += sizeof(int); output = malloc(total_output_size); app = 0; //<IV> memcpy(output, iv, iv_len); app += iv_len; //<Dim_Key> memcpy(output + app, &encrypted_key_len, sizeof(int)); app += sizeof(int); //<Ecrypt_KEY> memcpy(output + app, encrypted_key, encrypted_key_len); app += encrypted_key_len; //<Ciphertext> memcpy(output + app, ciphertext, cipher_len); app += encrypted_key_len; *out_len = total_output_size; //Cleanup EVP_CIPHER_CTX_cleanup(ctx); free(ctx); free(ciphertext); free(pubkey); free(iv); return output; error: if(ctx != NULL){ EVP_CIPHER_CTX_cleanup(ctx); free(ctx); } if(encrypted_key != NULL) free(ciphertext); if(pubkey != NULL) free(pubkey); if(iv != NULL) free(iv); if(ciphertext != NULL) free(ciphertext); if(output != NULL) free(output); return NULL; }
int main(int argc, char **argv) { DSA *dsa=NULL; int counter,ret=0,i,j; unsigned char buf[256]; unsigned long h; unsigned char sig[256]; unsigned int siglen; if (bio_err == NULL) bio_err=BIO_new_fp(stderr,BIO_NOCLOSE); CRYPTO_malloc_debug_init(); CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); ERR_load_crypto_strings(); RAND_seed(rnd_seed, sizeof rnd_seed); BIO_printf(bio_err,"test generation of DSA parameters\n"); dsa=DSA_generate_parameters(512,seed,20,&counter,&h,dsa_cb,bio_err); BIO_printf(bio_err,"seed\n"); for (i=0; i<20; i+=4) { BIO_printf(bio_err,"%02X%02X%02X%02X ", seed[i],seed[i+1],seed[i+2],seed[i+3]); } BIO_printf(bio_err,"\ncounter=%d h=%d\n",counter,h); if (dsa == NULL) goto end; DSA_print(bio_err,dsa,0); if (counter != 105) { BIO_printf(bio_err,"counter should be 105\n"); goto end; } if (h != 2) { BIO_printf(bio_err,"h should be 2\n"); goto end; } i=BN_bn2bin(dsa->q,buf); j=sizeof(out_q); if ((i != j) || (memcmp(buf,out_q,i) != 0)) { BIO_printf(bio_err,"q value is wrong\n"); goto end; } i=BN_bn2bin(dsa->p,buf); j=sizeof(out_p); if ((i != j) || (memcmp(buf,out_p,i) != 0)) { BIO_printf(bio_err,"p value is wrong\n"); goto end; } i=BN_bn2bin(dsa->g,buf); j=sizeof(out_g); if ((i != j) || (memcmp(buf,out_g,i) != 0)) { BIO_printf(bio_err,"g value is wrong\n"); goto end; } DSA_generate_key(dsa); DSA_sign(0, str1, 20, sig, &siglen, dsa); if (DSA_verify(0, str1, 20, sig, siglen, dsa) == 1) ret=1; end: if (!ret) ERR_print_errors(bio_err); if (dsa != NULL) DSA_free(dsa); CRYPTO_cleanup_all_ex_data(); ERR_remove_state(0); ERR_free_strings(); CRYPTO_mem_leaks(bio_err); if (bio_err != NULL) { BIO_free(bio_err); bio_err = NULL; } EXIT(!ret); return(0); }
int main(int argc, char **argv) { struct sshbuf *b; Options options; #define NUM_KEYTYPES 4 struct sshkey *keys[NUM_KEYTYPES], *key = NULL; struct passwd *pw; int r, key_fd[NUM_KEYTYPES], i, found, version = 2, fd; u_char *signature, *data, rver; char *host, *fp; size_t slen, dlen; #ifdef WITH_OPENSSL u_int32_t rnd[256]; #endif /* Ensure that stdin and stdout are connected */ if ((fd = open(_PATH_DEVNULL, O_RDWR)) < 2) exit(1); /* Leave /dev/null fd iff it is attached to stderr */ if (fd > 2) close(fd); i = 0; /* XXX This really needs to read sshd_config for the paths */ key_fd[i++] = open(_PATH_HOST_DSA_KEY_FILE, O_RDONLY); key_fd[i++] = open(_PATH_HOST_ECDSA_KEY_FILE, O_RDONLY); key_fd[i++] = open(_PATH_HOST_ED25519_KEY_FILE, O_RDONLY); key_fd[i++] = open(_PATH_HOST_RSA_KEY_FILE, O_RDONLY); original_real_uid = getuid(); /* XXX readconf.c needs this */ if ((pw = getpwuid(original_real_uid)) == NULL) fatal("getpwuid failed"); pw = pwcopy(pw); permanently_set_uid(pw); seed_rng(); #ifdef DEBUG_SSH_KEYSIGN log_init("ssh-keysign", SYSLOG_LEVEL_DEBUG3, SYSLOG_FACILITY_AUTH, 0); #endif /* verify that ssh-keysign is enabled by the admin */ initialize_options(&options); (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw, "", "", &options, 0); fill_default_options(&options); if (options.enable_ssh_keysign != 1) fatal("ssh-keysign not enabled in %s", _PATH_HOST_CONFIG_FILE); for (i = found = 0; i < NUM_KEYTYPES; i++) { if (key_fd[i] != -1) found = 1; } if (found == 0) fatal("could not open any host key"); #ifdef WITH_OPENSSL OpenSSL_add_all_algorithms(); arc4random_buf(rnd, sizeof(rnd)); RAND_seed(rnd, sizeof(rnd)); #endif found = 0; for (i = 0; i < NUM_KEYTYPES; i++) { keys[i] = NULL; if (key_fd[i] == -1) continue; r = sshkey_load_private_type_fd(key_fd[i], KEY_UNSPEC, NULL, &key, NULL); close(key_fd[i]); if (r != 0) debug("parse key %d: %s", i, ssh_err(r)); else if (key != NULL) { keys[i] = key; found = 1; } } if (!found) fatal("no hostkey found"); if ((b = sshbuf_new()) == NULL) fatal("%s: sshbuf_new failed", __func__); if (ssh_msg_recv(STDIN_FILENO, b) < 0) fatal("ssh_msg_recv failed"); if ((r = sshbuf_get_u8(b, &rver)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); if (rver != version) fatal("bad version: received %d, expected %d", rver, version); if ((r = sshbuf_get_u32(b, (u_int *)&fd)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); if (fd < 0 || fd == STDIN_FILENO || fd == STDOUT_FILENO) fatal("bad fd"); if ((host = get_local_name(fd)) == NULL) fatal("cannot get local name for fd"); if ((r = sshbuf_get_string(b, &data, &dlen)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); if (valid_request(pw, host, &key, data, dlen) < 0) fatal("not a valid request"); free(host); found = 0; for (i = 0; i < NUM_KEYTYPES; i++) { if (keys[i] != NULL && sshkey_equal_public(key, keys[i])) { found = 1; break; } } if (!found) { if ((fp = sshkey_fingerprint(key, options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) fatal("%s: sshkey_fingerprint failed", __func__); fatal("no matching hostkey found for key %s %s", sshkey_type(key), fp ? fp : ""); } if ((r = sshkey_sign(keys[i], &signature, &slen, data, dlen, 0)) != 0) fatal("sshkey_sign failed: %s", ssh_err(r)); free(data); /* send reply */ sshbuf_reset(b); if ((r = sshbuf_put_string(b, signature, slen)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); if (ssh_msg_send(STDOUT_FILENO, version, b) == -1) fatal("ssh_msg_send failed"); return (0); }
status_t POP3Protocol::Open(const char *server, int port, int) { runner->ReportProgress(0, 0, MDR_DIALECT_CHOICE("Connecting to POP3 server...", "POP3サーバに接続しています...")); if (port <= 0) { #ifdef USE_SSL port = fUseSSL ? 995 : 110; #else port = 110; #endif } fLog = ""; // Prime the error message BString error_msg; error_msg << MDR_DIALECT_CHOICE("Error while connecting to server ", "サーバに接続中にエラーが発生しました ") << server; if (port != 110) error_msg << ":" << port; uint32 hostIP = inet_addr(server); // first see if we can parse it as a numeric address if (hostIP == 0 || hostIP == ~0UL) { struct hostent * he = gethostbyname(server); hostIP = he ? *((uint32*)he->h_addr) : 0; } if (hostIP == 0) { error_msg << MDR_DIALECT_CHOICE(": Connection refused or host not found", ": :接続が拒否されたかサーバーが見つかりません"); runner->ShowError(error_msg.String()); return B_NAME_NOT_FOUND; } #ifndef HAIKU_TARGET_PLATFORM_BEOS fSocket = socket(AF_INET, SOCK_STREAM, 0); #else fSocket = socket(AF_INET, 2, 0); #endif if (fSocket >= 0) { struct sockaddr_in saAddr; memset(&saAddr, 0, sizeof(saAddr)); saAddr.sin_family = AF_INET; saAddr.sin_port = htons(port); saAddr.sin_addr.s_addr = hostIP; int result = connect(fSocket, (struct sockaddr *) &saAddr, sizeof(saAddr)); if (result < 0) { #ifndef HAIKU_TARGET_PLATFORM_BEOS close(fSocket); #else closesocket(fSocket); #endif fSocket = -1; error_msg << ": " << strerror(errno); runner->ShowError(error_msg.String()); return errno; } } else { error_msg << ": Could not allocate socket."; runner->ShowError(error_msg.String()); return B_ERROR; } #ifdef USE_SSL if (fUseSSL) { SSL_library_init(); SSL_load_error_strings(); RAND_seed(this,sizeof(POP3Protocol)); /*--- Because we're an add-on loaded at an unpredictable time, all the memory addresses and things contained in ourself are esssentially random. */ fSSLContext = SSL_CTX_new(SSLv23_method()); fSSL = SSL_new(fSSLContext); fSSLBio = BIO_new_socket(fSocket, BIO_NOCLOSE); SSL_set_bio(fSSL, fSSLBio, fSSLBio); if (SSL_connect(fSSL) <= 0) { BString error; error << "Could not connect to POP3 server " << settings->FindString("server"); if (port != 995) error << ":" << port; error << ". (SSL connection error)"; runner->ShowError(error.String()); SSL_CTX_free(fSSLContext); #ifndef HAIKU_TARGET_PLATFORM_BEOS close(fSocket); #else closesocket(fSocket); #endif runner->Stop(true); return B_ERROR; } } #endif BString line; status_t err; #ifndef HAIKU_TARGET_PLATFORM_BEOS err = ReceiveLine(line); #else int32 tries = 200000; // no endless loop here while ((err = ReceiveLine(line)) == 0) { if (tries-- < 0) return B_ERROR; } #endif if (err < 0) { #ifndef HAIKU_TARGET_PLATFORM_BEOS close(fSocket); #else closesocket(fSocket); #endif fSocket = -1; error_msg << ": " << strerror(err); runner->ShowError(error_msg.String()); return B_ERROR; } if (strncmp(line.String(), "+OK", 3) != 0) { if (line.Length() > 0) { error_msg << MDR_DIALECT_CHOICE(". The server said:\n", "サーバのメッセージです\n") << line.String(); } else error_msg << ": No reply.\n"; runner->ShowError(error_msg.String()); return B_ERROR; } fLog = line; return B_OK; }
static void handle_connect(int cnum, struct timeval* nowP, int double_check) { int url_num; char buf[600]; int bytes, r; url_num = connections[cnum].url_num; if (double_check) { /* Check to make sure the non-blocking connect succeeded. */ int err, errlen; if (connect(connections[cnum].conn_fd, (struct sockaddr*)&connections[cnum].sa, connections[cnum].sa_len) < 0) { switch(errno) { case EISCONN: /* Ok! */ break; case EINVAL: errlen = sizeof(err); if ( getsockopt( connections[cnum].conn_fd, SOL_SOCKET, SO_ERROR, (void*) &err, (socklen_t*)&errlen ) < 0 ) { (void) fprintf(stderr, "%s: unknown connect error\n", urls[url_num].url_str ); } else { (void) fprintf(stderr, "%s: %s\n", urls[url_num].url_str, strerror( err )); } close_connection( cnum ); return; default: perror( urls[url_num].url_str ); close_connection( cnum ); return; } } } #ifdef USE_SSL if ( urls[url_num].protocol == PROTO_HTTPS ) { int flags; /* Make SSL connection. */ if ( ssl_ctx == (SSL_CTX*) 0 ) { SSL_load_error_strings(); SSLeay_add_ssl_algorithms(); ssl_ctx = SSL_CTX_new( SSLv23_client_method() ); if ( cipher != (char*) 0 ) { if ( ! SSL_CTX_set_cipher_list( ssl_ctx, cipher ) ) { (void) fprintf( stderr, "%s: cannot set cipher list\n", argv0 ); ERR_print_errors_fp( stderr ); close_connection( cnum ); return; } } } if ( ! RAND_status() ) { unsigned char bytes[1024]; int i; for ( i = 0; i < sizeof(bytes); ++i ) bytes[i] = random() % 0xff; RAND_seed( bytes, sizeof(bytes) ); } flags = fcntl( connections[cnum].conn_fd, F_GETFL, 0 ); if ( flags != -1 ) (void) fcntl( connections[cnum].conn_fd, F_SETFL, flags & ~ (int) O_NDELAY ); connections[cnum].ssl = SSL_new( ssl_ctx ); SSL_set_fd( connections[cnum].ssl, connections[cnum].conn_fd ); r = SSL_connect( connections[cnum].ssl ); if ( r <= 0 ) { (void) fprintf( stderr, "%s: SSL connection failed - %d\n", argv0, r ); ERR_print_errors_fp( stderr ); close_connection( cnum ); return; } } #endif connections[cnum].did_connect = 1; /* Format the request. */ if (do_proxy) { #ifdef USE_SSL bytes = snprintf( buf, sizeof(buf), "GET %s://%.500s:%d%.500s HTTP/1.0\r\n", urls[url_num].protocol == PROTO_HTTPS ? "https" : "http", urls[url_num].hostname, (int) urls[url_num].port, urls[url_num].filename ); #else bytes = snprintf(buf, sizeof(buf), "GET http://%.500s:%d%.500s HTTP/1.0\r\n", urls[url_num].hostname, (int)urls[url_num].port, urls[url_num].filename); #endif } else { bytes = snprintf(buf, sizeof(buf), "GET %.500s HTTP/1.0\r\n", urls[url_num].filename); } bytes += snprintf(&buf[bytes], sizeof(buf) - bytes, "Host: %s\r\n", urls[url_num].hostname); bytes += snprintf(&buf[bytes], sizeof(buf) - bytes, "User-Agent: %s\r\n", VERSION); bytes += snprintf(&buf[bytes], sizeof(buf) - bytes, "\r\n"); /* Send the request. */ connections[cnum].request_at = *nowP; #ifdef USE_SSL if ( urls[url_num].protocol == PROTO_HTTPS ) r = SSL_write( connections[cnum].ssl, buf, bytes ); else r = write( connections[cnum].conn_fd, buf, bytes ); #else r = write(connections[cnum].conn_fd, buf, bytes); #endif if (r < 0) { perror(urls[url_num].url_str); close_connection(cnum); return; } connections[cnum].conn_state = CNST_HEADERS; connections[cnum].header_state = HDST_LINE1_PROTOCOL; }
/** @memo Seed the pseudorandom number generator for SSL @doc Seed the pseudorandom number generator. @return void */ void ssl_rand_seed( const void *seed, int length ) { RAND_seed(seed, length); }
BOOL CHTTPClient::SendSSLRequest(char *szHost, char *szHostName, char *szPath, char *szUserID, char *szPassword, long lPort, char *szProxy, long lProxyPort, char *szProxyUser, char *szProxyPswd, char *szUserAgent, char *szPost, long dwTimeout, SSL **pssl, SSL_CTX **pssl_ctx, char *szTransaction) { char *szConnectHost; char *szConnectionHeader = "Connection: close\r\n"; char *szContentLength = "Content-Length: %d\r\n"; char *szContentType = "Content-Type: application/x-www-form-urlencoded\r\n"; char *szProxyConn = "Proxy-Connection: Keep-Alive\r\n"; char *szPragma = "Pragma: no-cache\r\n"; long lConnectPort; char *szBuffer = szSendBuffer; char szWork[256]; char *lpWork; char *szGetMethod = "GET"; char *szPostMethod = "POST"; char *szMethod; BOOL RC = TRUE; BOOL bBIOset = FALSE; Base64Coder cBase64Coder; BIO *bio = 0; int done = 0, i, n; char buf[2048]; // Got to have a host if (!szHost) return(FALSE); // Initialize strings used for cookies cDomain = szHostName; cPath = szPath; if (szTransaction) cTransaction = szTransaction; else cTransaction = ""; // Clean up ssl storage try { if (ssl) { SSL_free(ssl); ssl = 0; } } catch(...) { ssl = 0; } try { // Initialise the ssl library now in rtm startup // Create the context structure. Operate in the normal default SSLv3 // in a SSLv2 header mode to maximize the number of servers // we can connect to. if (!ssl_ctx) { if (!pssl_ctx || !*pssl_ctx) { if ((ssl_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) { bConnectFailed = TRUE; throw FALSE; } } else ssl_ctx = *pssl_ctx; } // Reset variables for response bHeader = FALSE; bReadComplete = FALSE; bHeadRequest = FALSE; lReceivedLength = 0; lContentLength = 0; cHeader = ""; cContent = ""; // turn on all vendor bug compatibility options SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL); // Create the SSL structure - defaults are inherited from the SSL_CTX if ((ssl = SSL_new(ssl_ctx)) == NULL) { bConnectFailed = TRUE; throw FALSE; }; // Set as client side SSL_set_connect_state(ssl); if (!szProxy) { // No proxy szConnectHost = szHost; lConnectPort = lPort; } else { // Proxy szConnectHost = szProxy; lConnectPort = lProxyPort; }; sprintf(szWork, "%s:%u", szConnectHost, (unsigned int) lConnectPort); // Create a BIO to handle the connect and SSL handling if ((bio = BIO_new_connect(szWork)) == NULL) { bConnectFailed = TRUE; throw FALSE; }; // If using proxy then have to tunnel through to the actual ssl server if (szProxy) { sprintf(szBuffer, "CONNECT %s:%u HTTP/1.0\r\nUser-Agent: %s\r\n", szHostName, (unsigned int) lPort, szUserAgent); if (szProxyUser && szProxyPswd && strlen(szProxyUser) > 0 && strlen(szProxyPswd) > 0) { sprintf(szWork, "%s:%s", szProxyUser, szProxyPswd); cBase64Coder.Encode(szWork); sprintf(szWork, "Proxy-Authorization: Basic %s\r\n", (LPCTSTR) cBase64Coder.EncodedMessage()); strcat(szBuffer, szWork); } strcat(szBuffer, szProxyConn); strcat(szBuffer, szPragma); strcat(szBuffer, "\r\n"); // Send connect request n = strlen(szBuffer); i = 0; do { i = BIO_write(bio, &(szBuffer[i]), n); if (i <= 0) { bConnectFailed = TRUE; BIO_free(bio); throw FALSE; } n -= i; } while(n > 0); // Read response from proxy i = BIO_read(bio, buf, sizeof(buf)); if (i <= 0) { bConnectFailed = TRUE; BIO_free(bio); throw FALSE; }; buf[i] = '\0'; lpWork = strstr(buf, "200"); if (!lpWork) { bConnectFailed = TRUE; BIO_free(bio); throw FALSE; }; }; // Use the newly created connect BIO SSL_set_bio(ssl, bio, bio); bBIOset = TRUE; if (pSession && pssl) { SSL_set_session(ssl, pSession); } else { while(!done) { int i; struct tm *ptr; time_t lt; lt = time(NULL); PROTECT_CALL ptr = localtime(<); char *pszTime = asctime(ptr); RAND_seed((unsigned char *) pszTime, strlen(pszTime)); UNPROTECT_CALL // The all important handshake i = SSL_do_handshake(ssl); switch(SSL_get_error(ssl, i)) { case SSL_ERROR_NONE: // Handshake has finished, so proceed done = 1; break; case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_CONNECT: // Perform the handshake again. sleep(1); break; default: bConnectFailed = TRUE; throw FALSE; break; }; }; pSession = SSL_get_session(ssl); }; if (szPost) szMethod = szPostMethod; else szMethod = szGetMethod; // Build the request sprintf(szBuffer, "%s %s HTTP/1.0\r\nUser-Agent: %s\r\nHost: %s\r\n", szMethod, szPath, szUserAgent, szHostName); if (szUserID) { sprintf(szWork, "%s:%s", szUserID, szPassword); cBase64Coder.Encode(szWork); sprintf(szWork, "Authorization: Basic %s\r\n", (LPCTSTR) cBase64Coder.EncodedMessage()); strcat(szBuffer, szWork); } if (szPost) { strcat(szBuffer, szContentType); sprintf(szWork, szContentLength, strlen(szPost)); strcat(szBuffer, szWork); strcat(szBuffer, szProxyConn); strcat(szBuffer, szPragma); } else { strcat(szBuffer, szConnectionHeader); } if (!cTransaction.empty()) SendCookie(szBuffer); // Indicate end of header strcat(szBuffer, "\r\n"); sDebugSendHeader = szBuffer; if (szPost) strcat(szBuffer, szPost); dwStartTime = ::XPlatGetMilliseconds(); // Send request n = strlen(szBuffer); i = 0; do { i = SSL_write(ssl, &(szBuffer[i]), n); if (i <= 0) { bConnectFailed = FALSE; throw FALSE; } n -= i; } while(n > 0); // Read from the other side of the protocol while(1) { i = SSL_read(ssl, buf, sizeof(buf)); if (i <= 0) break; ProcessData((unsigned char *) buf, i); if (!GetTimeLeft(dwTimeout, dwStartTime)) { // Timed out bConnectFailed = FALSE; throw FALSE; }; }; if (szPost && !strcmp(szStatus, "100")) { printf("status 100"); strcat(szBuffer, szPost); // Reset variables for response bHeader = FALSE; bReadComplete = FALSE; bHeadRequest = FALSE; lReceivedLength = 0; lContentLength = 0; cHeader = ""; cContent = ""; // Send request n = strlen(szBuffer); i = 0; do { i = SSL_write(ssl, &(szBuffer[i]), n); if (i <= 0) { bConnectFailed = FALSE; throw FALSE; } n -= i; } while(n > 0); // Read from the other side of the protocol while(1) { i = SSL_read(ssl, buf, sizeof(buf)); if (i <= 0) break; ProcessData((unsigned char *) buf, i); if (!GetTimeLeft(dwTimeout, dwStartTime)) { // Timed out bConnectFailed = FALSE; throw FALSE; }; }; }; Disconnected(); throw TRUE; } catch(BOOL rc) { RC = rc; } catch(...) { RC = FALSE; if (!bBIOset && bio) { try { BIO_free(bio); } catch(...) { } } } if (pssl && pssl_ctx) { if (*pssl == 0) { *pssl = ssl; *pssl_ctx = ssl_ctx; ssl = 0; } ssl_ctx = 0; } return RC; };
int main(int argc, char *argv[]) { BN_GENCB _cb; DH *a; DH *b=NULL; char buf[12]; unsigned char *abuf=NULL,*bbuf=NULL; int i,alen,blen,aout,bout,ret=1; BIO *out; CRYPTO_malloc_debug_init(); CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); #ifdef OPENSSL_SYS_WIN32 CRYPTO_malloc_init(); #endif RAND_seed(rnd_seed, sizeof rnd_seed); out=BIO_new(BIO_s_file()); if (out == NULL) EXIT(1); BIO_set_fp(out,stdout,BIO_NOCLOSE); BN_GENCB_set(&_cb, &cb, out); if(((a = DH_new()) == NULL) || !DH_generate_parameters_ex(a, 64, DH_GENERATOR_5, &_cb)) goto err; if (!DH_check(a, &i)) goto err; if (i & DH_CHECK_P_NOT_PRIME) BIO_puts(out, "p value is not prime\n"); if (i & DH_CHECK_P_NOT_SAFE_PRIME) BIO_puts(out, "p value is not a safe prime\n"); if (i & DH_UNABLE_TO_CHECK_GENERATOR) BIO_puts(out, "unable to check the generator value\n"); if (i & DH_NOT_SUITABLE_GENERATOR) BIO_puts(out, "the g value is not a generator\n"); BIO_puts(out,"\np ="); BN_print(out,a->p); BIO_puts(out,"\ng ="); BN_print(out,a->g); BIO_puts(out,"\n"); b=DH_new(); if (b == NULL) goto err; b->p=BN_dup(a->p); b->g=BN_dup(a->g); if ((b->p == NULL) || (b->g == NULL)) goto err; /* Set a to run with normal modexp and b to use constant time */ a->flags &= ~DH_FLAG_NO_EXP_CONSTTIME; b->flags |= DH_FLAG_NO_EXP_CONSTTIME; if (!DH_generate_key(a)) goto err; BIO_puts(out,"pri 1="); BN_print(out,a->priv_key); BIO_puts(out,"\npub 1="); BN_print(out,a->pub_key); BIO_puts(out,"\n"); if (!DH_generate_key(b)) goto err; BIO_puts(out,"pri 2="); BN_print(out,b->priv_key); BIO_puts(out,"\npub 2="); BN_print(out,b->pub_key); BIO_puts(out,"\n"); alen=DH_size(a); abuf=(unsigned char *)OPENSSL_malloc(alen); aout=DH_compute_key(abuf,b->pub_key,a); BIO_puts(out,"key1 ="); for (i=0; i<aout; i++) { op_sprintf(buf,"%02X",abuf[i]); BIO_puts(out,buf); } BIO_puts(out,"\n"); blen=DH_size(b); bbuf=(unsigned char *)OPENSSL_malloc(blen); bout=DH_compute_key(bbuf,a->pub_key,b); BIO_puts(out,"key2 ="); for (i=0; i<bout; i++) { op_sprintf(buf,"%02X",bbuf[i]); BIO_puts(out,buf); } BIO_puts(out,"\n"); if ((aout < 4) || (bout != aout) || (op_memcmp(abuf,bbuf,aout) != 0)) { fprintf(stderr,"Error in DH routines\n"); ret=1; } else ret=0; err: ERR_print_errors_fp(stderr); if (abuf != NULL) OPENSSL_free(abuf); if (bbuf != NULL) OPENSSL_free(bbuf); if(b != NULL) DH_free(b); if(a != NULL) DH_free(a); BIO_free(out); #ifdef OPENSSL_SYS_NETWARE if (ret) printf("ERROR: %d\n", ret); #endif EXIT(ret); return(ret); }
int main(int argc, char *argv[]) { BN_CTX *ctx = NULL; int nid, ret = 1; EC_builtin_curve *curves = NULL; size_t crv_len = 0, n = 0; BIO *out; CRYPTO_set_mem_debug(1); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); RAND_seed(rnd_seed, sizeof rnd_seed); out = BIO_new(BIO_s_file()); if (out == NULL) EXIT(1); BIO_set_fp(out, stdout, BIO_NOCLOSE | BIO_FP_TEXT); if ((ctx = BN_CTX_new()) == NULL) goto err; /* get a list of all internal curves */ crv_len = EC_get_builtin_curves(NULL, 0); curves = OPENSSL_malloc(sizeof(*curves) * crv_len); if (curves == NULL) goto err; if (!EC_get_builtin_curves(curves, crv_len)) goto err; /* NAMED CURVES TESTS */ for (n = 0; n < crv_len; n++) { nid = curves[n].nid; /* * Skipped for X25519 because affine coordinate operations are not * supported for this curve. * Higher level ECDH tests are performed in evptests.txt instead. */ if (nid == NID_X25519) continue; if (!test_ecdh_curve(nid, ctx, out)) goto err; } /* KATs */ for (n = 0; n < (sizeof(ecdh_kats)/sizeof(ecdh_kat_t)); n++) { if (!ecdh_kat(out, &ecdh_kats[n])) goto err; } /* NIST SP800-56A co-factor ECDH KATs */ for (n = 0; n < (sizeof(ecdh_cavs_kats)/sizeof(ecdh_cavs_kat_t)); n++) { if (!ecdh_cavs_kat(out, &ecdh_cavs_kats[n])) goto err; } ret = 0; err: ERR_print_errors_fp(stderr); OPENSSL_free(curves); BN_CTX_free(ctx); BIO_free(out); #ifndef OPENSSL_NO_CRYPTO_MDEBUG if (CRYPTO_mem_leaks_fp(stderr) <= 0) ret = 1; #endif EXIT(ret); }
/** Main routine for nsd-control */ int main(int argc, char* argv[]) { int c; const char* cfgfile = CONFIGFILE; char* svr = NULL; #ifdef USE_WINSOCK int r; WSADATA wsa_data; #endif log_init("nsd-control"); #ifdef HAVE_ERR_LOAD_CRYPTO_STRINGS ERR_load_crypto_strings(); #endif ERR_load_SSL_strings(); #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO) OpenSSL_add_all_algorithms(); #else OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS | OPENSSL_INIT_ADD_ALL_DIGESTS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL); #endif #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL) (void)SSL_library_init(); #else OPENSSL_init_ssl(0, NULL); #endif if(!RAND_status()) { /* try to seed it */ unsigned char buf[256]; unsigned int v, seed=(unsigned)time(NULL) ^ (unsigned)getpid(); size_t i; v = seed; for(i=0; i<256/sizeof(v); i++) { memmove(buf+i*sizeof(v), &v, sizeof(v)); v = v*seed + (unsigned int)i; } RAND_seed(buf, 256); fprintf(stderr, "warning: no entropy, seeding openssl PRNG with time\n"); } /* parse the options */ while( (c=getopt(argc, argv, "c:s:h")) != -1) { switch(c) { case 'c': cfgfile = optarg; break; case 's': svr = optarg; break; case '?': case 'h': default: usage(); } } argc -= optind; argv += optind; if(argc == 0) usage(); if(argc >= 1 && strcmp(argv[0], "start")==0) { if(execl(NSD_START_PATH, "nsd", "-c", cfgfile, (char*)NULL) < 0) { fprintf(stderr, "could not exec %s: %s\n", NSD_START_PATH, strerror(errno)); exit(1); } } return go(cfgfile, svr, argc, argv); }
return NULL; #endif } int main(void) { unsigned char *abuf = NULL; //const EC_POINT *public_key; int i, alen, aout, jj = 0; int sockfd, new_fd; // listen on sock_fd, new connection on new_fd struct sockaddr_in my_addr; // my address information struct sockaddr_in their_addr; // connector's address information socklen_t sin_size; int yes = 1, numbytes; char buf[MAXDATASIZE]; /*//////////////////////////////////////////////////////////////Generating Keys/////////////////////////////////////*/ BN_CTX *ctx = NULL; int nid; BIO *out; CRYPTO_malloc_debug_init(); CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); const char *text = "NIST Prime-Curve P-192"; #ifdef OPENSSL_SYS_WIN32 CRYPTO_malloc_init(); #endif RAND_seed(rnd_seed, sizeof rnd_seed); out = BIO_new(BIO_s_file()); if (out == NULL) EXIT(1); BIO_set_fp(out, stdout, BIO_NOCLOSE); if ((ctx = BN_CTX_new()) == NULL) goto err; nid = NID_X9_62_prime192v1; EC_KEY *a = NULL; //EC_KEY is a structure BIGNUM *x_a = NULL, *y_a = NULL; const BIGNUM *BIG = NULL; char *buff; //unsigned char *abuf=NULL,*bbuf=NULL; const EC_GROUP *group; a = EC_KEY_new_by_curve_name(nid); if (a == NULL) goto err; group = EC_KEY_get0_group(a); // aa=EC_POINT_new(group); if ((x_a = BN_new()) == NULL) goto err; //BN_new returns a pointer to the bignum if ((y_a = BN_new()) == NULL) goto err; // if ((BIG=BN_new()) == NULL) goto err; BIO_puts(out, "Testing key generation with "); BIO_puts(out, text); if (!EC_KEY_generate_key(a)) goto err; printf("\n1 ) generating keys\n"); if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) == NID_X9_62_prime_field) { if (!EC_POINT_get_affine_coordinates_GFp(group, EC_KEY_get0_public_key(a), x_a, y_a, ctx)) goto err; } //returns the public key else { if (!EC_POINT_get_affine_coordinates_GF2m(group, EC_KEY_get0_public_key(a), x_a, y_a, ctx)) goto err; } BIO_puts(out, " pri 1="); BN_print(out, EC_KEY_get0_private_key(a)); BIO_puts(out, "\n pub 1="); BN_print(out, x_a); BIO_puts(out, ","); BN_print(out, y_a); BIO_puts(out, "\n"); /* printf("importnt work\n"); //BN_print(out,x_a); buff=BN_bn2dec(x_a); printf("%s\n",buff); BN_dec2bn(&(x_a),buff); printf("%s\n",buff); BN_print(out,x_a); */ /*//////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/ if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } my_addr.sin_family = AF_INET; // host byte order my_addr.sin_port = htons(MYPORT); // short, network byte order my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP memset(my_addr.sin_zero, '\0', sizeof my_addr.sin_zero); if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof my_addr) == -1) { perror("bind"); exit(1); } if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } while (1) { // main accept() loop sin_size = sizeof their_addr; if ((new_fd = accept(sockfd, (struct sockaddr *) &their_addr, &sin_size)) == -1) { perror("accept"); continue; } printf("server: got connection from %s\n", inet_ntoa(their_addr.sin_addr)); if (send(new_fd, "Hello, world!\n", 14, 0) == -1) perror("send"); // BN_print(out,x_a); // if ((jj=send(new_fd, &aa, sizeof(BIGNUM), 0)) == -1) // perror("send"); ////////////////////////////////////////////////////////////////////////////// //printf("side %d\n",sizeof(EC_POINT*)); //aa= EC_KEY_get0_public_key(a); //printf("side %d\n",sizeof(aa)); // if ((jj=send(new_fd, &aa, sizeof(EC_POINT*), 0)) == -1) //perror("send"); //printf("\nbytes send %d\n",jj); //////////////////////////////////////////////////////////////////////////////// //x_a=(BIGNUM*)&buff; //BN_print(out,x_a); //printf("%d",sizeof(EC_POINT)); //buff=(char*)&x_a; //if (send(new_fd, &x_a, sizeof(x_a), 0) == -1) //perror("send"); //buff[10]='\0'; //BIG =EC_KEY_get0_private_key(a); //BN_print(out,BIG); /* buff=BN_bn2dec(x_a); // BN_print(out,BIG); buff=(char*)&x_a; //buff[10]='\0'; printf("%s\n",buff); x_a=(BIGNUM*)&buff; BN_dec2bn(&(y_a),buff); printf("%s",buff); */ //sprintf(buff,"%u",EC_KEY_get0_private_key(a)); //printf("send: %d\n",BIG); //printf("%s",buff); //printf("%d",strlen(buff)); // float data1; //char data2[64]; //BIG=(BIGNUM*)(buff); //BIO_puts(out,BIG); //memcpy((void*)buff, (void*)EC_KEY_get0_private_key(a), 20); //printf("%s",buff); //for (i=0; i<10; i++) //{ //printf("%c",buff[i]); //BIO_puts(out,buff); //} //if (send(new_fd,buff,strlen(buff), 0) == -1) // { // perror("send"); // } //printf("\npublic key send\n"); /* //EC_POINT *bb; if ((numbytes=recv(new_fd,(char*)&bb,500, 0)) == -1) { perror("recv"); exit(1); } printf("\npublic key received\n"); */ /* if ((numbytes=recv(new_fd, buf, MAXDATASIZE-1, 0)) == -1) { perror("recv"); exit(1); } */ // buf[numbytes] = '\0'; /* printf("Received: %d",numbytes); printf("working\n"); alen=KDF1_SHA1_len; ///it is a static constant integer. printf("working\n"); abuf=(unsigned char *)OPENSSL_malloc(alen); printf("working\n"); if(abuf==NULL || bb==NULL || a==NULL) printf("i hate you error\n"); aout=ECDH_compute_key(abuf,alen,bb,a,KDF1_SHA1); //generating session key printf("working\n"); // BN_print(out, abuf); //BIO_puts(out,"\n"); BIO_puts(out," key1 ="); for (i=0; i<aout; i++) { sprintf(buf,"%02X",abuf[i]); BIO_puts(out,buf); } BIO_puts(out,"\n"); */ close(new_fd); exit(0); close(new_fd); // parent doesn't need this } err: ERR_print_errors_fp(stderr); if (x_a) BN_free(x_a); if (y_a) BN_free(y_a); if (a) EC_KEY_free(a); if (ctx) BN_CTX_free(ctx); BIO_free(out); CRYPTO_cleanup_all_ex_data(); ERR_remove_state(0);
int main(int argc, char **argv) { BN_GENCB *cb; DSA *dsa = NULL; int counter, ret = 0, i, j; unsigned char buf[256]; unsigned long h; unsigned char sig[256]; unsigned int siglen; if (bio_err == NULL) bio_err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT); CRYPTO_set_mem_debug(1); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); ERR_load_crypto_strings(); RAND_seed(rnd_seed, sizeof rnd_seed); BIO_printf(bio_err, "test generation of DSA parameters\n"); cb = BN_GENCB_new(); if (!cb) goto end; BN_GENCB_set(cb, dsa_cb, bio_err); if (((dsa = DSA_new()) == NULL) || !DSA_generate_parameters_ex(dsa, 512, seed, 20, &counter, &h, cb)) goto end; BIO_printf(bio_err, "seed\n"); for (i = 0; i < 20; i += 4) { BIO_printf(bio_err, "%02X%02X%02X%02X ", seed[i], seed[i + 1], seed[i + 2], seed[i + 3]); } BIO_printf(bio_err, "\ncounter=%d h=%ld\n", counter, h); DSA_print(bio_err, dsa, 0); if (counter != 105) { BIO_printf(bio_err, "counter should be 105\n"); goto end; } if (h != 2) { BIO_printf(bio_err, "h should be 2\n"); goto end; } i = BN_bn2bin(dsa->q, buf); j = sizeof(out_q); if ((i != j) || (memcmp(buf, out_q, i) != 0)) { BIO_printf(bio_err, "q value is wrong\n"); goto end; } i = BN_bn2bin(dsa->p, buf); j = sizeof(out_p); if ((i != j) || (memcmp(buf, out_p, i) != 0)) { BIO_printf(bio_err, "p value is wrong\n"); goto end; } i = BN_bn2bin(dsa->g, buf); j = sizeof(out_g); if ((i != j) || (memcmp(buf, out_g, i) != 0)) { BIO_printf(bio_err, "g value is wrong\n"); goto end; } dsa->flags |= DSA_FLAG_NO_EXP_CONSTTIME; DSA_generate_key(dsa); DSA_sign(0, str1, 20, sig, &siglen, dsa); if (DSA_verify(0, str1, 20, sig, siglen, dsa) == 1) ret = 1; dsa->flags &= ~DSA_FLAG_NO_EXP_CONSTTIME; DSA_generate_key(dsa); DSA_sign(0, str1, 20, sig, &siglen, dsa); if (DSA_verify(0, str1, 20, sig, siglen, dsa) == 1) ret = 1; end: if (!ret) ERR_print_errors(bio_err); DSA_free(dsa); BN_GENCB_free(cb); CRYPTO_cleanup_all_ex_data(); ERR_remove_thread_state(NULL); ERR_free_strings(); #ifdef CRYPTO_MDEBUG CRYPTO_mem_leaks(bio_err); #endif BIO_free(bio_err); bio_err = NULL; # ifdef OPENSSL_SYS_NETWARE if (!ret) printf("ERROR\n"); # endif EXIT(!ret); }
/* * 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_umalloc_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 = umalloc(ssl_mutex_num * sizeof(*ssl_mutex)); int i; for (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 cupsdStartServer(void) { #ifdef HAVE_LIBSSL int i; /* Looping var */ struct timeval curtime; /* Current time in microseconds */ unsigned char data[1024]; /* Seed data */ #endif /* HAVE_LIBSSL */ #ifdef HAVE_LIBSSL /* * Initialize the encryption libraries... */ printf("[server.c::cupsdStartServer()] initializing the SSL encryption libraries\n"); SSL_library_init(); SSL_load_error_strings(); /* * Using the current time is a dubious random seed, but on some systems * it is the best we can do (on others, this seed isn't even used...) */ gettimeofday(&curtime, NULL); srand(curtime.tv_sec + curtime.tv_usec); for (i = 0; i < sizeof(data); i ++) data[i] = rand(); /* Yes, this is a poor source of random data... */ RAND_seed(&data, sizeof(data)); printf("[server.c::cupsdStartServer()] seeding a lot of crap \n"); #elif defined(HAVE_GNUTLS) /* * Initialize the encryption libraries... */ printf("[server.c::cupsdStartServer()] initializing the gnutils libraries \n"); gnutls_global_init(); #endif /* HAVE_LIBSSL */ /* * Startup all the networking stuff... */ cupsdStartListening(); cupsdStartBrowsing(); cupsdStartPolling(); /* * Create a pipe for CGI processes... */ if (cupsdOpenPipe(CGIPipes)) cupsdLogMessage(CUPSD_LOG_ERROR, "cupsdStartServer: Unable to create pipes for CGI status!"); else { CGIStatusBuffer = cupsdStatBufNew(CGIPipes[0], "[CGI]"); printf("[server.c::cupsdStartServer()] created a pipe for cgi processes, adding to polling engine \n"); cupsdAddSelect(CGIPipes[0], (cupsd_selfunc_t)cupsdUpdateCGI, NULL, NULL); } /* * Mark that the server has started and printers and jobs may be changed... */ LastEvent = CUPSD_EVENT_PRINTER_CHANGED | CUPSD_EVENT_JOB_STATE_CHANGED | CUPSD_EVENT_SERVER_STARTED; started = 1; printf("[server.c::cupsdStartServer()] done \n"); }
int ssl_test_rsa(int argc, char *argv[]) { int err=0; int v; RSA *key; unsigned char ptext[256]; unsigned char ctext[256]; static unsigned char ptext_ex[] = "\x54\x85\x9b\x34\x2c\x49\xea\x2a"; unsigned char ctext_ex[256]; int plen; int clen = 0; int num; int n; CRYPTO_malloc_debug_init(); CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); RAND_seed(rnd_seed, sizeof rnd_seed); /* or OAEP may fail */ plen = sizeof(ptext_ex) - 1; for (v = 0; v < 6; v++) { key = RSA_new(); switch (v%3) { case 0: clen = key1(key, ctext_ex); break; case 1: clen = key2(key, ctext_ex); break; case 2: clen = key3(key, ctext_ex); break; } if (v/3 >= 1) key->flags |= RSA_FLAG_NO_CONSTTIME; num = RSA_public_encrypt(plen, ptext_ex, ctext, key, RSA_PKCS1_PADDING); if (num != clen) { TINYCLR_SSL_PRINTF("PKCS#1 v1.5 encryption failed!\n"); err=1; goto oaep; } num = RSA_private_decrypt(num, ctext, ptext, key, RSA_PKCS1_PADDING); if (num != plen || TINYCLR_SSL_MEMCMP(ptext, ptext_ex, num) != 0) { TINYCLR_SSL_PRINTF("PKCS#1 v1.5 decryption failed!\n"); err=1; } else TINYCLR_SSL_PRINTF("PKCS #1 v1.5 encryption/decryption ok\n"); oaep: ERR_clear_error(); num = RSA_public_encrypt(plen, ptext_ex, ctext, key, RSA_PKCS1_OAEP_PADDING); if (num == -1 && pad_unknown()) { TINYCLR_SSL_PRINTF("No OAEP support\n"); goto next; } if (num != clen) { TINYCLR_SSL_PRINTF("OAEP encryption failed!\n"); err=1; goto next; } num = RSA_private_decrypt(num, ctext, ptext, key, RSA_PKCS1_OAEP_PADDING); if (num != plen || TINYCLR_SSL_MEMCMP(ptext, ptext_ex, num) != 0) { TINYCLR_SSL_PRINTF("OAEP decryption (encrypted data) failed!\n"); err=1; } else if (TINYCLR_SSL_MEMCMP(ctext, ctext_ex, num) == 0) TINYCLR_SSL_PRINTF("OAEP test vector %d passed!\n", v); /* Different ciphertexts (rsa_oaep.c without -DPKCS_TESTVECT). Try decrypting ctext_ex */ num = RSA_private_decrypt(clen, ctext_ex, ptext, key, RSA_PKCS1_OAEP_PADDING); if (num != plen || TINYCLR_SSL_MEMCMP(ptext, ptext_ex, num) != 0) { TINYCLR_SSL_PRINTF("OAEP decryption (test vector data) failed!\n"); err=1; } else TINYCLR_SSL_PRINTF("OAEP encryption/decryption ok\n"); /* Try decrypting corrupted ciphertexts */ for(n = 0 ; n < clen ; ++n) { int b; unsigned char saved = ctext[n]; for(b = 0 ; b < 256 ; ++b) { if(b == saved) continue; ctext[n] = b; num = RSA_private_decrypt(num, ctext, ptext, key, RSA_PKCS1_OAEP_PADDING); if(num > 0) { TINYCLR_SSL_PRINTF("Corrupt data decrypted!\n"); err = 1; } } } next: RSA_free(key); } CRYPTO_cleanup_all_ex_data(); ERR_remove_thread_state(NULL); CRYPTO_mem_leaks_fp(OPENSSL_TYPE__FILE_STDERR); #ifdef OPENSSL_SYS_NETWARE if (err) TINYCLR_SSL_PRINTF("ERROR: %d\n", err); #endif return err; }
int main(int argc, char *argv[]) { char *CApath=NULL,*CAfile=NULL; int badop=0; int ret=1; int client_auth=0; int server_auth=0; SSL_CTX *s_ctx=NULL; SSL_CTX *c_ctx=NULL; char *scert=TEST_SERVER_CERT; char *ccert=TEST_CLIENT_CERT; SSL_METHOD *ssl_method=SSLv23_method(); RAND_seed(rnd_seed, sizeof rnd_seed); if (bio_err == NULL) bio_err=BIO_new_fp(stderr,BIO_NOCLOSE); if (bio_stdout == NULL) bio_stdout=BIO_new_fp(stdout,BIO_NOCLOSE); argc--; argv++; while (argc >= 1) { if (strcmp(*argv,"-server_auth") == 0) server_auth=1; else if (strcmp(*argv,"-client_auth") == 0) client_auth=1; else if (strcmp(*argv,"-reconnect") == 0) reconnect=1; else if (strcmp(*argv,"-stats") == 0) cache_stats=1; else if (strcmp(*argv,"-ssl3") == 0) ssl_method=SSLv3_method(); else if (strcmp(*argv,"-ssl2") == 0) ssl_method=SSLv2_method(); else if (strcmp(*argv,"-CApath") == 0) { if (--argc < 1) goto bad; CApath= *(++argv); } else if (strcmp(*argv,"-CAfile") == 0) { if (--argc < 1) goto bad; CAfile= *(++argv); } else if (strcmp(*argv,"-cert") == 0) { if (--argc < 1) goto bad; scert= *(++argv); } else if (strcmp(*argv,"-ccert") == 0) { if (--argc < 1) goto bad; ccert= *(++argv); } else if (strcmp(*argv,"-threads") == 0) { if (--argc < 1) goto bad; thread_number= atoi(*(++argv)); if (thread_number == 0) thread_number=1; if (thread_number > MAX_THREAD_NUMBER) thread_number=MAX_THREAD_NUMBER; } else if (strcmp(*argv,"-loops") == 0) { if (--argc < 1) goto bad; number_of_loops= atoi(*(++argv)); if (number_of_loops == 0) number_of_loops=1; } else { fprintf(stderr,"unknown option %s\n",*argv); badop=1; break; } argc--; argv++; } if (badop) { bad: sv_usage(); goto end; } if (cipher == NULL) cipher=getenv("SSL_CIPHER"); SSL_load_error_strings(); OpenSSL_add_ssl_algorithms(); c_ctx=SSL_CTX_new(ssl_method); s_ctx=SSL_CTX_new(ssl_method); if ((c_ctx == NULL) || (s_ctx == NULL)) { ERR_print_errors(bio_err); goto end; } SSL_CTX_set_session_cache_mode(s_ctx, SSL_SESS_CACHE_NO_AUTO_CLEAR|SSL_SESS_CACHE_SERVER); SSL_CTX_set_session_cache_mode(c_ctx, SSL_SESS_CACHE_NO_AUTO_CLEAR|SSL_SESS_CACHE_SERVER); if (!SSL_CTX_use_certificate_file(s_ctx,scert,SSL_FILETYPE_PEM)) { ERR_print_errors(bio_err); } else if (!SSL_CTX_use_RSAPrivateKey_file(s_ctx,scert,SSL_FILETYPE_PEM)) { ERR_print_errors(bio_err); goto end; } if (client_auth) { SSL_CTX_use_certificate_file(c_ctx,ccert, SSL_FILETYPE_PEM); SSL_CTX_use_RSAPrivateKey_file(c_ctx,ccert, SSL_FILETYPE_PEM); } if ( (!SSL_CTX_load_verify_locations(s_ctx,CAfile,CApath)) || (!SSL_CTX_set_default_verify_paths(s_ctx)) || (!SSL_CTX_load_verify_locations(c_ctx,CAfile,CApath)) || (!SSL_CTX_set_default_verify_paths(c_ctx))) { fprintf(stderr,"SSL_load_verify_locations\n"); ERR_print_errors(bio_err); goto end; } if (client_auth) { fprintf(stderr,"client authentication\n"); SSL_CTX_set_verify(s_ctx, SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback); } if (server_auth) { fprintf(stderr,"server authentication\n"); SSL_CTX_set_verify(c_ctx,SSL_VERIFY_PEER, verify_callback); } thread_setup(); do_threads(s_ctx,c_ctx); thread_cleanup(); end: if (c_ctx != NULL) { fprintf(stderr,"Client SSL_CTX stats then free it\n"); print_stats(stderr,c_ctx); SSL_CTX_free(c_ctx); } if (s_ctx != NULL) { fprintf(stderr,"Server SSL_CTX stats then free it\n"); print_stats(stderr,s_ctx); if (cache_stats) { fprintf(stderr,"-----\n"); lh_stats(SSL_CTX_sessions(s_ctx),stderr); fprintf(stderr,"-----\n"); /* lh_node_stats(SSL_CTX_sessions(s_ctx),stderr); fprintf(stderr,"-----\n"); */ lh_node_usage_stats(SSL_CTX_sessions(s_ctx),stderr); fprintf(stderr,"-----\n"); } SSL_CTX_free(s_ctx); fprintf(stderr,"done free\n"); } exit(ret); return(0); }