Пример #1
0
/***
load rand seed from file
@function rand_load
@tparam[opt=nil] string file path to laod seed, default openssl management
@treturn boolean result
*/
static int openssl_random_load(lua_State*L)
{
  const char *file = luaL_optstring(L, 1, NULL);
  char buffer[MAX_PATH];
  int len;

  if (file == NULL)
    file = RAND_file_name(buffer, sizeof buffer);
#ifndef OPENSSL_NO_EGD
  else if (RAND_egd(file) > 0)
  {
    /* we try if the given filename is an EGD socket.
       if it is, we don't write anything back to the file. */;
    lua_pushboolean(L, 1);
    return 1;
  }
#endif
  len = luaL_optinteger(L, 2, 2048);
  if (file == NULL || !RAND_load_file(file, len))
  {
    return openssl_pushresult(L, 0);
  }

  lua_pushboolean(L, RAND_status());
  return 1;
}
Пример #2
0
void do_SSL_randomize()
{
	enum { RAND_VALS = 32 };
	int randbuf[RAND_VALS];
	char fname[512];
	int use_rand_file;
	time_t t;
	int i, c;

	/* if they have a /dev/urandom we can skip this function */
	if (RAND_status() != 0)
		return;

	t = time(0);
	RAND_seed((char *)&t, sizeof(time_t));

	/* have they specified a random file with RANDFILE environment variable? */
	use_rand_file = RAND_file_name(fname, sizeof(fname)) ? 1 : 0;
	if (use_rand_file)
		RAND_load_file(fname, 4096);

	/* stuff it with packets of random numbers until it is satisfied */
	for (i = 0; i < 256 && RAND_status() == 0; i++)
	{
		for (c = 0; c < RAND_VALS; c++)
			randbuf[c] = rand();
		RAND_seed((char *)randbuf, sizeof(int) * RAND_VALS);
	}
}
Пример #3
0
    int
_randfile( void )
{
    char        randfile[ MAXPATHLEN ];

    /* generates a default path for the random seed file */
    if ( RAND_file_name( randfile, sizeof( randfile )) == NULL ) {
	fprintf( stderr, "RAND_file_name: %s\n",
		ERR_error_string( ERR_get_error(), NULL ));
	return( -1 );
    }

    /* reads the complete randfile and adds them to the PRNG */
    if ( RAND_load_file( randfile, -1 ) <= 0 ) {
	fprintf( stderr, "RAND_load_file: %s: %s\n", randfile,
		ERR_error_string( ERR_get_error(), NULL ));
	return( -1 );
    }

    /* writes a number of random bytes (currently 1024) to randfile */
    if ( RAND_write_file( randfile ) < 0 ) {
	fprintf( stderr, "RAND_write_file: %s: %s\n", randfile,
		ERR_error_string( ERR_get_error(), NULL ));
	return( -1 );
    }
    return( 0 );
}
SSL *getSSL(void)
{
	if (!context) {
		const SSL_METHOD *m;
		unsigned char f_randfile[PATH_MAX];

		const unsigned char *f = (const unsigned char *)RAND_file_name(cast_char f_randfile, sizeof(f_randfile));
		if (f && RAND_egd(cast_const_char f)<0) {
			/* Not an EGD, so read and write to it */
			if (RAND_load_file(cast_const_char f_randfile, -1))
				RAND_write_file(cast_const_char f_randfile);
		}
		SSLeay_add_ssl_algorithms();
		m = SSLv23_client_method();
		if (!m) return NULL;
		context = SSL_CTX_new((void *)m);
		if (!context) return NULL;
		SSL_CTX_set_options(context, SSL_OP_ALL);
		SSL_CTX_set_default_verify_paths(context);
/* needed for systems without /dev/random, but obviously kills security. */
		/*{
			unsigned char pool[32768];
			int i;
			int rs;
			struct timeval tv;
			EINTRLOOP(rs, gettimeofday(&tv, NULL));
			for (i = 0; i < sizeof pool; i++) pool[i] = random() ^ tv.tv_sec ^ tv.tv_usec;
			RAND_add(pool, sizeof pool, sizeof pool);
		}*/
	}
	return (SSL_new(context));
}
Пример #5
0
void openssl_bioBS_random()
{
	int size;
	const char *p;
	unsigned char outs[SHA_DIGEST_LENGTH + 16] = { 0 };
	char buf[32], filename[COMM_LEN];

	strcpy(buf, "bioBS random");
	RAND_add(buf, 32, strlen(buf));
	strcpy(buf, "beike2012");
	RAND_seed(buf, 32);
	while (1) {
		if (RAND_status() == 1)
			break;
		else
			RAND_poll();
	}

	p = RAND_file_name(filename, COMM_LEN);
	RAND_write_file(p);
	RAND_load_file(p, MAX1_LEN);
	RAND_bytes(outs, sizeof(outs));
	printf("\nBIO_RANDOM() = ");
	for (size = 0; size < strlen((char *)&outs); size++)
		printf("%.02x", outs[size]);
	printf("\n");
	RAND_cleanup();
}
Пример #6
0
static void
init_openssl(struct module *module)
{
	unsigned char f_randfile[PATH_MAX];

	/* In a nutshell, on OS's without a /dev/urandom, the OpenSSL library
	 * cannot initialize the PRNG and so every attempt to use SSL fails.
	 * It's actually an OpenSSL FAQ, and according to them, it's up to the
	 * application coders to seed the RNG. -- William Yodlowsky */
	RAND_file_name(f_randfile, sizeof(f_randfile));
#ifdef HAVE_RAND_EGD
	if (RAND_egd(f_randfile) < 0) {
		/* Not an EGD, so read and write to it */
#endif
		if (RAND_load_file(f_randfile, -1))
			RAND_write_file(f_randfile);
#ifdef HAVE_RAND_EGD
	}
#endif

	SSLeay_add_ssl_algorithms();
	context = SSL_CTX_new(SSLv23_client_method());
	SSL_CTX_set_options(context, SSL_OP_ALL);
	SSL_CTX_set_default_verify_paths(context);
	socket_SSL_ex_data_idx = SSL_get_ex_new_index(0, NULL,
						      NULL,
						      socket_SSL_ex_data_dup,
						      NULL);
}
Пример #7
0
static int
seed_something(void)
{
#ifndef NO_RANDFILE
    char buf[1024], seedfile[256];

    /* If there is a seed file, load it. But such a file cannot be trusted,
       so use 0 for the entropy estimate */
    if (RAND_file_name(seedfile, sizeof(seedfile))) {
	int fd;
	fd = open(seedfile, O_RDONLY | O_BINARY | O_CLOEXEC);
	if (fd >= 0) {
	    ssize_t ret;
	    rk_cloexec(fd);
	    ret = read(fd, buf, sizeof(buf));
	    if (ret > 0)
		RAND_add(buf, ret, 0.0);
	    close(fd);
	} else
	    seedfile[0] = '\0';
    } else
	seedfile[0] = '\0';
#endif

    /* Calling RAND_status() will try to use /dev/urandom if it exists so
       we do not have to deal with it. */
    if (RAND_status() != 1) {
#if defined(HAVE_RAND_EGD)
	krb5_context context;
	const char *p;

#ifndef OPENSSL_NO_EGD
	/* Try using egd */
	if (!krb5_init_context(&context)) {
	    p = krb5_config_get_string(context, NULL, "libdefaults",
				       "egd_socket", NULL);
	    if (p != NULL)
		RAND_egd_bytes(p, ENTROPY_NEEDED);
	    krb5_free_context(context);
	}
#endif

#else
	/* TODO: Once a Windows CryptoAPI RAND method is defined, we
	   can use that and failover to another method. */
#endif
    }

    if (RAND_status() == 1)	{
#ifndef NO_RANDFILE
	/* Update the seed file */
	if (seedfile[0])
	    RAND_write_file(seedfile);
#endif

	return 0;
    } else
	return -1;
}
Пример #8
0
int seed_prng(char **errstr)
{
    char randfile[512];
    time_t t;
    int prn;
    int system_prn_max = 1024;

    /* Most systems have /dev/random or other sources of random numbers that
     * OpenSSL can use to seed itself.
     * The only system I know of where we must seed the PRNG is DOS.
     */
    if (!RAND_status())
    {
        if (!RAND_file_name(randfile, 512))
        {
            *errstr = xasprintf(_("no environment variables RANDFILE or HOME, "
                        "or filename of rand file too long"));
            return TLS_ESEED;
        }
        if (RAND_load_file(randfile, -1) < 1)
        {
            *errstr = xasprintf(_("%s: input error"), randfile);
            return TLS_ESEED;
        }
        /* Seed in time. I can't think of other "random" things on DOS
         * systems. */
        if ((t = time(NULL)) < 0)
        {
            *errstr = xasprintf(_("cannot get system time: %s"),
                    strerror(errno));
            return TLS_ESEED;
        }
        RAND_seed((unsigned char *)&t, sizeof(time_t));
        /* If the RANDFILE + time is not enough, we fall back to the insecure
         * and stupid method of seeding OpenSSLs PRNG with the systems PRNG. */
        if (!RAND_status())
        {
            srand((unsigned int)(t % UINT_MAX));
            while (!RAND_status() && system_prn_max > 0)
            {
                prn = rand();
                RAND_seed(&prn, sizeof(int));
                system_prn_max--;
            }
        }
        /* Are we happy now? */
        if (!RAND_status())
        {
            *errstr = xasprintf(_("random file + time + pseudo randomness is "
                        "not enough, giving up"));
            return TLS_ESEED;
        }
        /* Save a rand file for later usage. We ignore errors here as we can't
         * do anything about them. */
        (void)RAND_write_file(randfile);
    }
    return TLS_EOK;
}
void SSLConnection::init () {

  did_init = false;

  buffer_t path;
  buffer_init(&path);
  buffer_grow(&path,_POSIX_PATH_MAX+1);

  if (!HAVE_ENTROPY ()) {
    /* load entropy from files */
    if (SSLEntropyFile)
      add_entropy (SSLEntropyFile);
    add_entropy (RAND_file_name (path.str,path.size));

    /* load entropy from egd sockets */
#ifdef HAVE_RAND_EGD
    add_entropy (getenv ("EGDSOCKET"));
    buffer_shrink(&path,0);
    buffer_add_str(&path,NONULL(Homedir),-1);
    buffer_add_str(&path,"/.entropy",9);
    add_entropy (path.str);
    add_entropy ("/tmp/entropy");
#endif

    /* shuffle $RANDFILE (or ~/.rnd if unset) */
    RAND_write_file (RAND_file_name (path.str,path.size));
    if (!HAVE_ENTROPY ()) {
      buffer_t msg; buffer_init(&msg);
      buffer_add_str(&msg,_("Failed to find enough entropy on your system"),-1);
      displayError.emit(&msg);
      buffer_free(&msg);
      buffer_free(&path);
      return;
    }
  }

  /*
   * I don't think you can do this just before reading the error.
   * The call itself might clobber the last SSL error.
   */
  SSL_load_error_strings ();
  SSL_library_init ();
  did_init = true;
  buffer_free(&path);
}
Пример #10
0
/*
**  Create an SSL application context if not already done
*/
PUBLIC BOOL HTSSL_init (void)
{
    char rnd_filename[HT_MAX_PATH];

    /*
    ** Initialise OpenSSL 0.9.5 random number generator.
    ** The random generator of OpenSSL had to be initialised on platforms
    ** that do not support /dev/random, like Compaq True64 Unix.
    ** This is done in the default way, and means that the user of the
    ** libwww-ssl library needs to have a .rnd file in his/her home-directory.
    */
    RAND_file_name(rnd_filename, sizeof(rnd_filename));
    RAND_load_file(rnd_filename, -1);
    
    if (!app_ctx) {
	SSL_METHOD * meth = NULL;
        SSLeay_add_ssl_algorithms();
	/* Seems to provide English error messages */
        SSL_load_error_strings();

	/* select the protocol method */
	switch (ssl_prot_method) {
	case HTSSL_V2:
	  meth = SSLv2_client_method();
	  break;
	case HTSSL_V3:
	  meth = SSLv3_client_method();
	  break;
	case HTSSL_V23:
	  meth = SSLv23_client_method();
	  break;
	default:
	case HTTLS_V1:
	  meth = TLSv1_client_method();
	  break;
	}

        /* set up the application context */
	if ((app_ctx = SSL_CTX_new(meth)) == NULL) {
            HTTRACE(PROT_TRACE, "HTSSLContext Could not create context\n");
	    return NO;
	}
	HTTRACE(PROT_TRACE, "HTSSLContext Created context %p" _ app_ctx);

	/* See the SSL states in our own callback */
#ifdef HTDEBUG
	SSL_CTX_set_info_callback(app_ctx, apps_ssl_info_callback);
#endif
	
	/* Set the certificate verification callback */
	SSL_CTX_set_verify(app_ctx, SSL_VERIFY_PEER, verify_callback);

	/* Not sure what this does */
        SSL_CTX_set_session_cache_mode(app_ctx, SSL_SESS_CACHE_CLIENT);
     }
    return YES;
}
Пример #11
0
/**
 * ssl_init - Initialise the SSL library
 * @retval  0 Success
 * @retval -1 Error
 *
 * OpenSSL library needs to be fed with sufficient entropy. On systems with
 * /dev/urandom, this is done transparently by the library itself, on other
 * systems we need to fill the entropy pool ourselves.
 *
 * Even though only OpenSSL 0.9.5 and later will complain about the lack of
 * entropy, we try to our best and fill the pool with older versions also.
 * (That's the reason for the ugly ifdefs and macros, otherwise I could have
 * simply ifdef'd the whole ssl_init function)
 */
static int ssl_init(void)
{
  static bool init_complete = false;

  if (init_complete)
    return 0;

  if (!HAVE_ENTROPY())
  {
    /* load entropy from files */
    char path[PATH_MAX];
    add_entropy(C_EntropyFile);
    add_entropy(RAND_file_name(path, sizeof(path)));

/* load entropy from egd sockets */
#ifdef HAVE_RAND_EGD
    add_entropy(mutt_str_getenv("EGDSOCKET"));
    snprintf(path, sizeof(path), "%s/.entropy", NONULL(HomeDir));
    add_entropy(path);
    add_entropy("/tmp/entropy");
#endif

    /* shuffle $RANDFILE (or ~/.rnd if unset) */
    RAND_write_file(RAND_file_name(path, sizeof(path)));
    mutt_clear_error();
    if (!HAVE_ENTROPY())
    {
      mutt_error(_("Failed to find enough entropy on your system"));
      return -1;
    }
  }

/* OpenSSL performs automatic initialization as of 1.1.
 * However LibreSSL does not (as of 2.8.3). */
#if (defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER < 0x10100000L) || \
    (defined(LIBRESSL_VERSION_NUMBER))
  /* I don't think you can do this just before reading the error. The call
   * itself might clobber the last SSL error. */
  SSL_load_error_strings();
  SSL_library_init();
#endif
  init_complete = true;
  return 0;
}
Пример #12
0
/***
save rand seed to file
@function rand_write
@tparam[opt=nil] string file path to save seed, default openssl management
@treturn bool result
*/
static int openssl_random_write(lua_State *L)
{
  const char *file = luaL_optstring(L, 1, NULL);
  char buffer[MAX_PATH];

  if (file == NULL && (file = RAND_file_name(buffer, sizeof buffer)) == NULL)
    return openssl_pushresult(L, 0);

  RAND_write_file(file);
  return openssl_pushresult(L, 1);
}
Пример #13
0
/*
 * OpenSSL library needs to be fed with sufficient entropy. On systems
 * with /dev/urandom, this is done transparently by the library itself,
 * on other systems we need to fill the entropy pool ourselves.
 *
 * Even though only OpenSSL 0.9.5 and later will complain about the
 * lack of entropy, we try to our best and fill the pool with older
 * versions also. (That's the reason for the ugly #ifdefs and macros,
 * otherwise I could have simply #ifdef'd the whole ssl_init funcion)
 */
static int ssl_init (void)
{
  char path[_POSIX_PATH_MAX];
  static unsigned char init_complete = 0;

  if (init_complete)
    return 0;

  if (! HAVE_ENTROPY())
  {
    /* load entropy from files */
    add_entropy (SslEntropyFile);
    add_entropy (RAND_file_name (path, sizeof (path)));

    /* load entropy from egd sockets */
#ifdef HAVE_RAND_EGD
    add_entropy (getenv ("EGDSOCKET"));
    snprintf (path, sizeof(path), "%s/.entropy", NONULL(Homedir));
    add_entropy (path);
    add_entropy ("/tmp/entropy");
#endif

    /* shuffle $RANDFILE (or ~/.rnd if unset) */
    RAND_write_file (RAND_file_name (path, sizeof (path)));
    mutt_clear_error ();
    if (! HAVE_ENTROPY())
    {
      mutt_error (_("Failed to find enough entropy on your system"));
      mutt_sleep (2);
      return -1;
    }
  }

  /* I don't think you can do this just before reading the error. The call
   * itself might clobber the last SSL error. */
  SSL_load_error_strings();
  SSL_library_init();
  init_complete = 1;
  return 0;
}
Пример #14
0
static int rand_write(lua_State *L)
{
  const char *name = luaL_optstring(L, 1, 0);
  char tmp[256];
  int n;
  if (!name && !(name = RAND_file_name(tmp, sizeof tmp)))
    return crypto_error(L);
  n = RAND_write_file(name);
  if (n == 0)
    return crypto_error(L);
  lua_pushnumber(L, n);
  return 1;
}
Пример #15
0
void
crypto_deinit(void)
{
    char rnd_file[256];

    if (randfile_loaded)
    {
        RAND_file_name(rnd_file, sizeof(rnd_file));
        if (rnd_file[0])
            RAND_write_file(rnd_file);
    }
    crypto_deinit_threading();
}
Пример #16
0
//VOXOX - JRT - 2009.09.30 - Improve OpenSSL initialization.
const char* getRandomFileName()
{
	static bool initialized = false;
	static std::string s_randFileName = "";

	if ( !initialized )
	{
		char buffer[MAX_PATH+1];
		s_randFileName = RAND_file_name(buffer, sizeof(buffer) );
		initialized = true;
	}

	return s_randFileName.c_str();
}
Пример #17
0
int app_RAND_load_file(const char *file, BIO *bio_e, int dont_warn)
{
    int consider_randfile = (file == NULL);
    char buffer[200];

#ifdef OPENSSL_SYS_WINDOWS
    /*
     * allocate 2 to dont_warn not to use RAND_screen() via
     * -no_rand_screen option in s_client
     */
    if (dont_warn != 2) {
      BIO_printf(bio_e, "Loading 'screen' into random state -");
      BIO_flush(bio_e);
      RAND_screen();
      BIO_printf(bio_e, " done\n");
    }
#endif

    if (file == NULL)
        file = RAND_file_name(buffer, sizeof buffer);
    else if (RAND_egd(file) > 0) {
        /*
         * we try if the given filename is an EGD socket. if it is, we don't
         * write anything back to the file.
         */
        egdsocket = 1;
        return 1;
    }
    if (file == NULL || !RAND_load_file(file, -1)) {
        if (RAND_status() == 0) {
            if (!dont_warn) {
                BIO_printf(bio_e, "unable to load 'random state'\n");
                BIO_printf(bio_e,
                           "This means that the random number generator has not been seeded\n");
                BIO_printf(bio_e, "with much random data.\n");
                if (consider_randfile) { /* explanation does not apply when a
                                          * file is explicitly named */
                    BIO_printf(bio_e,
                               "Consider setting the RANDFILE environment variable to point at a file that\n");
                    BIO_printf(bio_e,
                               "'random' data can be kept in (the file will be overwritten).\n");
                }
            }
            return 0;
        }
    }
    seeded = 1;
    return 1;
}
Пример #18
0
void	HttpsRetriever::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

}
Пример #19
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
        PSTR cmdline, int iCmdShow)
	{
	static char appname[] = "OpenSSL";
	HWND hwnd;
	MSG msg;
	WNDCLASSEX wndclass;
        char buffer[200];

        if (cmdline[0] == '\0')
                filename = RAND_file_name(buffer, sizeof buffer);
        else
                filename = cmdline;

        RAND_load_file(filename, -1);

	wndclass.cbSize = sizeof(wndclass);
	wndclass.style = CS_HREDRAW | CS_VREDRAW;
	wndclass.lpfnWndProc = WndProc;
	wndclass.cbClsExtra = 0;
	wndclass.cbWndExtra = 0;
	wndclass.hInstance = hInstance;
	wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
	wndclass.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
	wndclass.lpszMenuName = NULL;
        wndclass.lpszClassName = appname;
	wndclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
	RegisterClassEx(&wndclass);

        hwnd = CreateWindow(appname, OPENSSL_VERSION_TEXT,
		WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
		CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);

	ShowWindow(hwnd, iCmdShow);
	UpdateWindow(hwnd);


	while (GetMessage(&msg, NULL, 0, 0))
		{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
		}

	return msg.wParam;
	}
Пример #20
0
static int
tlso_seed_PRNG( const char *randfile )
{
#ifndef URANDOM_DEVICE
	/* no /dev/urandom (or equiv) */
	long total=0;
	char buffer[MAXPATHLEN];

	if (randfile == NULL) {
		/* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
		 * If $HOME is not set or buffer too small to hold the pathname,
		 * an error occurs.	- From RAND_file_name() man page.
		 * The fact is that when $HOME is NULL, .rnd is used.
		 */
		randfile = RAND_file_name( buffer, sizeof( buffer ) );

	} else if (RAND_egd(randfile) > 0) {
		/* EGD socket */
		return 0;
	}

	if (randfile == NULL) {
		Debug( LDAP_DEBUG_ANY,
			"TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
			0, 0, 0);
		return -1;
	}

	total = RAND_load_file(randfile, -1);

	if (RAND_status() == 0) {
		Debug( LDAP_DEBUG_ANY,
			"TLS: PRNG not been seeded with enough data\n",
			0, 0, 0);
		return -1;
	}

	/* assume if there was enough bits to seed that it's okay
	 * to write derived bits to the file
	 */
	RAND_write_file(randfile);

#endif

	return 0;
}
Пример #21
0
static int rand_load(lua_State *L)
{
  const char *name = luaL_optstring(L, 1, NULL);
#if CRYPTO_OPENSSL
  char tmp[256];
  int n;
  if (!name && !(name = RAND_file_name(tmp, sizeof tmp)))
    return crypto_error(L);
  n = RAND_load_file(name, WRITE_FILE_COUNT);
  if (n == 0)
    return crypto_error(L);
  lua_pushnumber(L, n);
#elif CRYPTO_GCRYPT
  if (name != NULL)
    gcry_control(GCRYCTL_SET_RANDOM_SEED_FILE, name);
  lua_pushnumber(L, 0.0);
#endif
  return 1;
}
Пример #22
0
int app_RAND_write_file(const char *file)
{
    char buffer[200];

    if (egdsocket || !seeded)
        /*
         * If we did not manage to read the seed file, we should not write a
         * low-entropy seed file back -- it would suppress a crucial warning
         * the next time we want to use it.
         */
        return 0;

    if (file == NULL)
        file = RAND_file_name(buffer, sizeof buffer);
    if (file == NULL || !RAND_write_file(file)) {
        BIO_printf(bio_err, "unable to write 'random state'\n");
        return 0;
    }
    return 1;
}
Пример #23
0
static void init_prng (void)
{
	char namebuf[256];
	const char *random_file;
	
	if (RAND_status ()) return;

	namebuf[0] = '\0';
	random_file = RAND_file_name (namebuf, sizeof (namebuf));

	if (random_file && *random_file)
		RAND_load_file(random_file, 16384);
	
	if (RAND_status ()) return;

#ifdef WIN32
	RAND_screen ();
	if (RAND_status ())
	return;
#endif
}
Пример #24
0
/* Seeds the PRNG
 *
 * Only does something if the system doesn't have enough entropy.
 * If there is no random file, one will be created either at
 * $RANDFILE if set or at $HOME/.rnd
 *
 * Return value: 0 on success, !=0 on failure.
 */
static int ssl_seed(void)
{
  char stackdata[1024];
  static char rand_file[120];
  FILE *fh;

#ifdef HAVE_RAND_STATUS
  if (RAND_status())
    return 0;     /* Status OK */
#endif
  /* If '/dev/urandom' is present, OpenSSL will use it by default.
   * Otherwise we'll have to generate pseudorandom data ourselves,
   * using system time, our process ID and some unitialized static
   * storage.
   */
  if ((fh = fopen("/dev/urandom", "r"))) {
    fclose(fh);
    return 0;
  }
  if (RAND_file_name(rand_file, sizeof(rand_file)))
    tls_randfile = rand_file;
  else
    return 1;
  if (!RAND_load_file(rand_file, -1)) {
    /* generate some pseudo random data */
    unsigned int c;
    c = time(NULL);
    RAND_seed(&c, sizeof(c));
    c = getpid();
    RAND_seed(&c, sizeof(c));
    RAND_seed(stackdata, sizeof(stackdata));
  }
#ifdef HAVE_RAND_STATUS
  if (!RAND_status())
    return 2;   /* pseudo random data still not ehough */
#endif
  return 0;
}
Пример #25
0
int app_RAND_load_file(const char *file, int dont_warn)
{
    int consider_randfile = (file == NULL);
    char buffer[200];

    if (file == NULL)
        file = RAND_file_name(buffer, sizeof(buffer));
#ifndef OPENSSL_NO_EGD
    else if (RAND_egd(file) > 0) {
        /*
         * we try if the given filename is an EGD socket. if it is, we don't
         * write anything back to the file.
         */
        egdsocket = 1;
        return 1;
    }
#endif
    if (file == NULL || !RAND_load_file(file, -1)) {
        if (RAND_status() == 0) {
            if (!dont_warn) {
                BIO_printf(bio_err, "unable to load 'random state'\n");
                BIO_printf(bio_err,
                           "This means that the random number generator has not been seeded\n");
                BIO_printf(bio_err, "with much random data.\n");
                if (consider_randfile) { /* explanation does not apply when a
                                          * file is explicitly named */
                    BIO_printf(bio_err,
                               "Consider setting the RANDFILE environment variable to point at a file that\n");
                    BIO_printf(bio_err,
                               "'random' data can be kept in (the file will be overwritten).\n");
                }
            }
            return 0;
        }
    }
    seeded = 1;
    return 1;
}
Пример #26
0
static void
seed_prng(void)
{
	const char *file;
	int res;

	if (*g_seed_file)
		file = g_seed_file;
	else
		file = RAND_file_name(g_seed_file, sizeof(g_seed_file));

	if (!file)
		panic("Unable to obtain name for random seed file.");

	if (RAND_load_file(file, -1)) {
		g_seeded = 1;

		/* for a good measure */
		RAND_load_file("/dev/random", 8);

		return;
	}

	/*
	 * This is a special case, I hope it won't be normally used
	 * please review if this is sufficient, I'm not using purely /dev/random
	 * because some computers don't have enough enthropy
	 */
	res = RAND_load_file("/dev/urandom", 2048);
	if (res < 2048)
		panic("Unable to gather seed, /dev/urandom not available?");

	res = RAND_load_file("/dev/random", 32);
	if (res < 32)
		panic("Unable to gather enough entropy, /dev/random not available?");

	g_seeded = 1;
}
Пример #27
0
SSL *getSSL(void)
{
	if (!context) {
		const SSL_METHOD *m;
		unsigned char *os_pool;
		int os_pool_size;

#if defined(HAVE_RAND_EGD) && defined(HAVE_RAND_FILE_NAME) && defined(HAVE_RAND_LOAD_FILE) && defined(HAVE_RAND_WRITE_FILE)
		{
			unsigned char f_randfile[PATH_MAX];
			const unsigned char *f = (const unsigned char *)RAND_file_name(cast_char f_randfile, sizeof(f_randfile));
			if (f && RAND_egd(cast_const_char f) < 0) {
				/* Not an EGD, so read and write to it */
				if (RAND_load_file(cast_const_char f_randfile, -1))
					RAND_write_file(cast_const_char f_randfile);
			}
		}
#endif

#if defined(HAVE_RAND_ADD)
		os_seed_random(&os_pool, &os_pool_size);
		if (os_pool_size) RAND_add(os_pool, os_pool_size, os_pool_size);
		mem_free(os_pool);
#endif

		SSLeay_add_ssl_algorithms();
		m = SSLv23_client_method();
		if (!m) return NULL;
		context = SSL_CTX_new((void *)m);
		if (!context) return NULL;
		SSL_CTX_set_options(context, SSL_OP_ALL);
		if (ssl_set_private_paths())
			SSL_CTX_set_default_verify_paths(context);
		SSL_CTX_set_default_passwd_cb(context, ssl_password_callback);

	}
	return SSL_new(context);
}
Пример #28
0
void
crypto_init(void)
{
    SSL_library_init();
    SSL_load_error_strings();
    OpenSSL_add_all_algorithms();
    crypto_init_threading();

    if (RAND_status() < 0 || getenv("RANDFILE"))
    {
        char rnd_file[256];

        RAND_file_name(rnd_file, sizeof(rnd_file));
        if (rnd_file[0])
        {
            RAND_load_file(rnd_file, -1);
            randfile_loaded = TRUE;
        }

        if (RAND_status() < 0)
            fprintf(stderr, "WARNING: a trusted random number source is not available, crypto operations will probably fail. Please set the RANDFILE environment variable.");
    }
}
Пример #29
0
static int rand_write(lua_State *L)
{
  const char *name = luaL_optstring(L, 1, NULL);
#if CRYPTO_OPENSSL
  char tmp[256];
  int n;
  if (!name && !(name = RAND_file_name(tmp, sizeof tmp)))
    return crypto_error(L);
  n = RAND_write_file(name);
  if (n == 0)
    return crypto_error(L);
  lua_pushnumber(L, n);
#elif CRYPTO_GCRYPT
  /* this is a BUG() in gcrypt. not sure if it refers to the lib or to
    the caller, but it does not work (to set twice this file) */
  /*
  if (name != NULL)
    gcry_control(GCRYCTL_SET_RANDOM_SEED_FILE,name);
  */
  gcry_control(GCRYCTL_UPDATE_RANDOM_SEED_FILE);
  lua_pushnumber(L, 0.0);
#endif
  return 1;
}
Пример #30
0
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
}