Esempio n. 1
0
File: dh.cpp Progetto: BrownBear2/fc
   bool diffie_hellman::generate_pub_key()
   {
        if( !p.size() ) 
            return valid = false;
        DH* dh = DH_new(); 
        dh->p = BN_bin2bn( (unsigned char*)&p.front(), p.size(), NULL );
        dh->g = BN_bin2bn( (unsigned char*)&g, 1, NULL );

        int check;
        DH_check(dh,&check);
        if( check & DH_CHECK_P_NOT_SAFE_PRIME )
        {
            DH_free(dh);
            return valid = false;
        }
        DH_generate_key(dh);

        pub_key.resize( BN_num_bytes( dh->pub_key ) );
        priv_key.resize( BN_num_bytes( dh->priv_key ) );
        if( pub_key.size() )
            BN_bn2bin( dh->pub_key, (unsigned char*)&pub_key.front()  );
        if( priv_key.size() )
            BN_bn2bin( dh->priv_key, (unsigned char*)&priv_key.front()  );

        DH_free(dh);
        return valid = true;
   }
Esempio n. 2
0
   bool diffie_hellman::compute_shared_key( const char* buf, uint32_t s ) {
        ssl_dh dh = DH_new();
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
        auto bn_p = BN_bin2bn( (unsigned char*)&p.front(), p.size(), NULL );
        auto bn_pub_key = BN_bin2bn( (unsigned char*)&pub_key.front(), pub_key.size(), NULL );
        auto bn_priv_key = BN_bin2bn( (unsigned char*)&priv_key.front(), priv_key.size(), NULL );
        auto bn_g = BN_bin2bn( (unsigned char*)&g, 1, NULL );
        DH_set0_pqg(dh.obj, bn_p, NULL, bn_g);
        DH_set0_key(dh.obj, bn_pub_key, bn_priv_key);
#else
        dh->p = BN_bin2bn( (unsigned char*)&p.front(), p.size(), NULL );
        dh->pub_key = BN_bin2bn( (unsigned char*)&pub_key.front(), pub_key.size(), NULL );
        dh->priv_key = BN_bin2bn( (unsigned char*)&priv_key.front(), priv_key.size(), NULL );
        dh->g = BN_bin2bn( (unsigned char*)&g, 1, NULL );
#endif

        int check;
        DH_check(dh,&check);
        if( !fc::validate( dh, valid ) )
        {
            return false;
        }

        ssl_bignum pk;
        BN_bin2bn( (unsigned char*)buf, s, pk );
        shared_key.resize( DH_size(dh) ); 
        DH_compute_key( (unsigned char*)&shared_key.front(), pk, dh );

        return true;
   }
Esempio n. 3
0
DH * dif_hel_setup()
{
    DH * new_dh = DH_new();
    if ( !new_dh )
    {
	printf("%s \n","Error:Creating new dh");
	error();
    }
    if ( !DH_generate_parameters_ex(new_dh,2,DH_GENERATOR_2,0))
    {
	printf("%s \n","Error:Generating paramters");
	error();
    }
    int dh_code = 0;
    if( !DH_check(new_dh,&dh_code))
    {
	printf("%s \n", "Error:Dh_check failed");
	error();
    }
    if(!DH_generate_key(new_dh))
    {
	printf("%s \n", "Error:Generating key failed");
	error();
    }
    return new_dh;
}
Esempio n. 4
0
void openssl_dh_crypt()
{
	BIO *b;
	DH *d1, *d2;
	int i, len1, len2;
	unsigned char skey1[COMM_LEN], skey2[COMM_LEN];

	d1 = DH_new();
	d2 = DH_new();
	DH_generate_parameters_ex(d1, 64, DH_GENERATOR_2, NULL);
	DH_check(d1, &i);
	printf("\nDH key size: %d\n", DH_size(d1));
	DH_generate_key(d1);

	d2->p = BN_dup(d1->p);
	d2->g = BN_dup(d1->g);
	DH_generate_key(d2);
	DH_check_pub_key(d1, d1->pub_key, &i);
	len1 = DH_compute_key(skey1, d2->pub_key, d1);
	len2 = DH_compute_key(skey2, d1->pub_key, d2);
	if ((len1 != len2) || (memcmp(skey1, skey2, len1) != 0)) {
		printf("DH_compute_key err!\n");
		DH_free(d1);
		DH_free(d2);
		return;
	}

	b = BIO_new(BIO_s_file());
	BIO_set_fp(b, stdout, BIO_NOCLOSE);
	DHparams_print(b, d1);

	BIO_free(b);
	DH_free(d1);
	DH_free(d2);
}
Esempio n. 5
0
static DH *
get_rfc5114_modp(int num)
{
    DH *ret = NULL;
    BIGNUM *p = NULL, *g = NULL, *q = NULL;
    int check = 0;

    ret = DH_new();
    if (!ret)
        goto err;

    switch(num) {
        case 0:
            p = BN_bin2bn(rfc_5114_modp_1_p, sizeof(rfc_5114_modp_1_p), p);
            g = BN_bin2bn(rfc_5114_modp_1_g, sizeof(rfc_5114_modp_1_g), g);
            q = BN_bin2bn(rfc_5114_modp_1_q, sizeof(rfc_5114_modp_1_q), q);
            break;
        case 1:
            p = BN_bin2bn(rfc_5114_modp_2_p, sizeof(rfc_5114_modp_2_p), p);
            g = BN_bin2bn(rfc_5114_modp_2_g, sizeof(rfc_5114_modp_2_g), g);
            q = BN_bin2bn(rfc_5114_modp_2_q, sizeof(rfc_5114_modp_2_q), q);
            break;
        case 2:
            p = BN_bin2bn(rfc_5114_modp_3_p, sizeof(rfc_5114_modp_3_p), p);
            g = BN_bin2bn(rfc_5114_modp_3_g, sizeof(rfc_5114_modp_3_g), g);
            q = BN_bin2bn(rfc_5114_modp_3_q, sizeof(rfc_5114_modp_3_q), q);
            break;
        default:
            log_err("Invalid arguments");
            goto err;
    }

    if (!p || !g || !q)
        goto err;

    if (!DH_set0_pqg(ret, p, q, g))
       goto err;

    /* Perform some checks. OpenSSL only knows generators 2 and 5, so the
     * DH_UNABLE_TO_CHECK_GENERATOR will be set, but the prime should be safe
     * nevertheless */
    if (!DH_check(ret, &check)) goto err;
    if (check & DH_CHECK_P_NOT_PRIME)
        goto err;

    return ret;

err:
    if (ret)
        DH_free(ret);
    if (p)
        BN_free(p);
    if (g)
        BN_free(g);
    if (q)
        BN_free(q);
    return NULL;
}
Esempio n. 6
0
/*
 *	Load precomputed DH parameters.
 *
 *	To prevent "downgrade" attacks, we perform a number of checks
 *	to verify that the DBA-generated DH parameters file contains
 *	what we expect it to contain.
 */
static DH  *
load_dh_file(char *filename, bool isServerStart)
{
	FILE	   *fp;
	DH		   *dh = NULL;
	int			codes;

	/* attempt to open file.  It's not an error if it doesn't exist. */
	if ((fp = AllocateFile(filename, "r")) == NULL)
	{
		ereport(isServerStart ? FATAL : LOG,
				(errcode_for_file_access(),
				 errmsg("could not open DH parameters file \"%s\": %m",
						filename)));
		return NULL;
	}

	dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
	FreeFile(fp);

	if (dh == NULL)
	{
		ereport(isServerStart ? FATAL : LOG,
				(errcode(ERRCODE_CONFIG_FILE_ERROR),
				 errmsg("could not load DH parameters file: %s",
						SSLerrmessage(ERR_get_error()))));
		return NULL;
	}

	/* make sure the DH parameters are usable */
	if (DH_check(dh, &codes) == 0)
	{
		ereport(isServerStart ? FATAL : LOG,
				(errcode(ERRCODE_CONFIG_FILE_ERROR),
				 errmsg("invalid DH parameters: %s",
						SSLerrmessage(ERR_get_error()))));
		return NULL;
	}
	if (codes & DH_CHECK_P_NOT_PRIME)
	{
		ereport(isServerStart ? FATAL : LOG,
				(errcode(ERRCODE_CONFIG_FILE_ERROR),
				 errmsg("invalid DH parameters: p is not prime")));
		return NULL;
	}
	if ((codes & DH_NOT_SUITABLE_GENERATOR) &&
		(codes & DH_CHECK_P_NOT_SAFE_PRIME))
	{
		ereport(isServerStart ? FATAL : LOG,
				(errcode(ERRCODE_CONFIG_FILE_ERROR),
				 errmsg("invalid DH parameters: neither suitable generator or safe prime")));
		return NULL;
	}

	return dh;
}
/*
 *	Load precomputed DH parameters.
 *
 *	To prevent "downgrade" attacks, we perform a number of checks
 *	to verify that the DBA-generated DH parameters file contains
 *	what we expect it to contain.
 */
static DH  *
load_dh_file(int keylength)
{
	FILE	   *fp;
	char		fnbuf[MAXPGPATH];
	DH		   *dh = NULL;
	int			codes;

	/* attempt to open file.  It's not an error if it doesn't exist. */
	snprintf(fnbuf, sizeof(fnbuf), "dh%d.pem", keylength);
	if ((fp = fopen(fnbuf, "r")) == NULL)
		return NULL;

/*	flock(fileno(fp), LOCK_SH); */
	dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
/*	flock(fileno(fp), LOCK_UN); */
	fclose(fp);

	/* is the prime the correct size? */
	if (dh != NULL && 8 * DH_size(dh) < keylength)
	{
		elog(LOG, "DH errors (%s): %d bits expected, %d bits found",
			 fnbuf, keylength, 8 * DH_size(dh));
		dh = NULL;
	}

	/* make sure the DH parameters are usable */
	if (dh != NULL)
	{
		if (DH_check(dh, &codes) == 0)
		{
			elog(LOG, "DH_check error (%s): %s", fnbuf,
				 SSLerrmessage(ERR_get_error()));
			return NULL;
		}
		if (codes & DH_CHECK_P_NOT_PRIME)
		{
			elog(LOG, "DH error (%s): p is not prime", fnbuf);
			return NULL;
		}
		if ((codes & DH_NOT_SUITABLE_GENERATOR) &&
			(codes & DH_CHECK_P_NOT_SAFE_PRIME))
		{
			elog(LOG,
				 "DH error (%s): neither suitable generator or safe prime",
				 fnbuf);
			return NULL;
		}
	}

	return dh;
}
Esempio n. 8
0
/*
 *  call-seq:
 *     dh.params_ok? -> true | false
 *
 * Validates the Diffie-Hellman parameters associated with this instance.
 * It checks whether a safe prime and a suitable generator are used. If this
 * is not the case, +false+ is returned.
 */
static VALUE
ossl_dh_check_params(VALUE self)
{
    DH *dh;
    int codes;

    GetDH(self, dh);
    if (!DH_check(dh, &codes)) {
	return Qfalse;
    }

    return codes == 0 ? Qtrue : Qfalse;
}
Esempio n. 9
0
int s2n_dh_params_check(struct s2n_dh_params *params)
{
    int codes = 0;

    if (DH_check(params->dh, &codes) == 0) {
        S2N_ERROR(S2N_ERR_DH_PARAMETER_CHECK);
    }

    if (codes != 0) {
        S2N_ERROR(S2N_ERR_DH_PARAMETER_CHECK);
    }

    return 0;
}
Esempio n. 10
0
File: dh.cpp Progetto: BrownBear2/fc
   bool diffie_hellman::validate()
   {
        if( !p.size() ) 
            return valid = false;
        DH* dh = DH_new(); 
        dh->p = BN_bin2bn( (unsigned char*)&p.front(), p.size(), NULL );
        dh->g = BN_bin2bn( (unsigned char*)&g, 1, NULL );

        int check;
        DH_check(dh,&check);
        DH_free(dh);
        if( check & DH_CHECK_P_NOT_SAFE_PRIME )
            return valid = false;
        return valid = true;
   }
Esempio n. 11
0
File: dh.cpp Progetto: BrownBear2/fc
   bool diffie_hellman::generate_params( int s, uint8_t g )
   {
        DH* dh = DH_generate_parameters( s, g, NULL, NULL );
        p.resize( BN_num_bytes( dh->p ) );
        if( p.size() )
            BN_bn2bin( dh->p, (unsigned char*)&p.front()  );
        this->g = g;

        int check;
        DH_check(dh,&check);
        DH_free(dh);

        if( check & DH_CHECK_P_NOT_SAFE_PRIME )
            return valid = false;
        return valid = true;
   }
Esempio n. 12
0
/*
 *  call-seq:
 *     dh.params_ok? -> true | false
 *
 * Validates the Diffie-Hellman parameters associated with this instance.
 * It checks whether a safe prime and a suitable generator are used. If this
 * is not the case, +false+ is returned.
 */
static VALUE
ossl_dh_check_params(VALUE self)
{
    DH *dh;
    EVP_PKEY *pkey;
    int codes;

    GetPKeyDH(self, pkey);
    dh = pkey->pkey.dh;

    if (!DH_check(dh, &codes)) {
	return Qfalse;
    }

    return codes == 0 ? Qtrue : Qfalse;
}
Esempio n. 13
0
DH *tr_create_matching_dh (unsigned char *priv_key,
			   size_t keylen,
			   DH *in_dh) {
  DH *dh = NULL;
  int dh_err = 0;

  if (!in_dh)
    return NULL;

  if (NULL == (dh = DH_new())) {
    tr_crit("tr_create_matching_dh: unable to allocate new DH structure.");
    return NULL;
  }

  if ((NULL == (dh->g = BN_dup(in_dh->g))) ||
      (NULL == (dh->p = BN_dup(in_dh->p)))) {
    DH_free(dh);
    tr_debug("tr_create_matching_dh: Invalid dh parameter values, can't be duped.");
    return NULL;
  }

  /* TBD -- share code with previous function */
  if ((priv_key) && (keylen > 0))
    dh->priv_key = BN_bin2bn(priv_key, keylen, NULL);

  DH_generate_key(dh);		/* generates the public key */
  DH_check(dh, &dh_err);
  if (0 != dh_err) {
    tr_warning("Warning: dh_check failed with %d", dh_err);
    if (dh_err & DH_CHECK_P_NOT_PRIME)
      tr_warning(": p value is not prime");
    else if (dh_err & DH_CHECK_P_NOT_SAFE_PRIME)
      tr_warning(": p value is not a safe prime");
    else if (dh_err & DH_UNABLE_TO_CHECK_GENERATOR)
      tr_warning(": unable to check the generator value");
    else if (dh_err & DH_NOT_SUITABLE_GENERATOR)
      tr_warning(": the g value is not a generator");
    else
      tr_warning("unhandled error %i", dh_err);
  }

  return(dh);
}
Esempio n. 14
0
DH *tr_create_dh_params(unsigned char *priv_key,
			size_t keylen) {

  DH *dh = NULL;
  int dh_err = 0;

  if (NULL == (dh = DH_new()))
    return NULL;

  if ((NULL == (dh->g = BN_new())) ||
      (NULL == (dh->p = BN_new())) ||
      (NULL == (dh->q = BN_new()))) {
    DH_free(dh);
    return NULL;
  }

  BN_set_word(dh->g, 2);
  dh->p = BN_bin2bn(tr_2048_dhprime, sizeof(tr_2048_dhprime), NULL);
  BN_rshift1(dh->q, dh->p);

  if ((priv_key) && (keylen > 0))
    dh->priv_key = BN_bin2bn(priv_key, keylen, NULL);

  DH_generate_key(dh);		/* generates the public key */

  DH_check(dh, &dh_err);
  if (0 != dh_err) {
    tr_warning("Warning: dh_check failed with %d", dh_err);
    if (dh_err & DH_CHECK_P_NOT_PRIME)
      tr_warning(": p value is not prime");
    else if (dh_err & DH_CHECK_P_NOT_SAFE_PRIME)
      tr_warning(": p value is not a safe prime");
    else if (dh_err & DH_UNABLE_TO_CHECK_GENERATOR)
      tr_warning(": unable to check the generator value");
    else if (dh_err & DH_NOT_SUITABLE_GENERATOR)
      tr_warning(": the g value is not a generator");
    else
      tr_warning("unhandled error %i", dh_err);
  }

  return(dh);
}
Esempio n. 15
0
/*
 *	Load precomputed DH parameters.
 *
 *	To prevent "downgrade" attacks, we perform a number of checks
 *	to verify that the DBA-generated DH parameters file contains
 *	what we expect it to contain.
 */
static DH  *
load_dh_file(int keylength)
{
	char		homedir[MAXPGPATH];
	char		fnbuf[MAXPGPATH];
	FILE	   *fp;
	DH		   *dh;
	int			codes;

	if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
		return NULL;

	/* attempt to open file.  It's not an error if it doesn't exist. */
	snprintf(fnbuf, sizeof(fnbuf), DHFILEPATTERN, homedir, keylength);

	if ((fp = fopen(fnbuf, "r")) == NULL)
		return NULL;

/*	flock(fileno(fp), LOCK_SH); */
	dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
/*	flock(fileno(fp), LOCK_UN); */
	fclose(fp);

	/* is the prime the correct size? */
	if (dh != NULL && 8 * DH_size(dh) < keylength)
		dh = NULL;

	/* make sure the DH parameters are usable */
	if (dh != NULL)
	{
		if (DH_check(dh, &codes))
			return NULL;
		if (codes & DH_CHECK_P_NOT_PRIME)
			return NULL;
		if ((codes & DH_NOT_SUITABLE_GENERATOR) &&
			(codes & DH_CHECK_P_NOT_SAFE_PRIME))
			return NULL;
	}

	return dh;
}
Esempio n. 16
0
static DH *
load_dh_params(const char *filename) {
  BIO *bio;
  DH *dh = NULL;
  if(filename == NULL) return NULL;
  bio = BIO_new_file(filename, "r");
  if(bio == NULL) return NULL;
  mtevL(eventer_deb, "Loading DH parameters from %s.\n", filename);
  PEM_read_bio_DHparams(bio, &dh, 0, NULL);
  BIO_free(bio);
  if(dh) {
    int code = 0;
    if(DH_check(dh, &code) != 1 || code != 0) {
      mtevL(eventer_err, "DH Parameter in %s is bad [%x], not using.\n",
            filename, code);
      DH_free(dh);
      dh = NULL;
    }
  }
  return dh;
}
Esempio n. 17
0
int
init_dh(DH ** dh, int standardizedDomainParameters)
{
    int i;
    DH *tmp = NULL;

    check(dh, "Invalid arguments");

    if (!*dh) {
        tmp = get_rfc5114_modp(standardizedDomainParameters);
        if (!tmp)
            goto err;
    } else {
        /*Note: this could be something not matching standardizedDomainParameters */
        tmp = *dh;
    }

    if (!DH_check(tmp, &i))
        goto err;

    /* RFC 5114 parameters do not use safe primes and OpenSSL does not know
     * how to deal with generator other then 2 or 5. Therefore we have to
     * ignore some of the checks */
    i &= ~DH_CHECK_P_NOT_SAFE_PRIME;
    i &= ~DH_UNABLE_TO_CHECK_GENERATOR;

    check(!i, "Bad DH key");

    *dh = tmp;

    return 1;

err:
    if (tmp && !*dh) {
        DH_free(tmp);
    }

    return 0;
}
Esempio n. 18
0
File: dh.cpp Progetto: BrownBear2/fc
   bool diffie_hellman::compute_shared_key( const char* buf, uint32_t s ) {
        DH* dh = DH_new(); 
        dh->p = BN_bin2bn( (unsigned char*)&p.front(), p.size(), NULL );
        dh->pub_key = BN_bin2bn( (unsigned char*)&pub_key.front(), pub_key.size(), NULL );
        dh->priv_key = BN_bin2bn( (unsigned char*)&priv_key.front(), priv_key.size(), NULL );
        dh->g = BN_bin2bn( (unsigned char*)&g, 1, NULL );

        int check;
        DH_check(dh,&check);
        if( check & DH_CHECK_P_NOT_SAFE_PRIME )
        {
            DH_free(dh);
            return valid = false;
        }


        BIGNUM* pk = BN_bin2bn( (unsigned char*)buf, s, NULL ); 
        shared_key.resize( DH_size(dh) ); 
        DH_compute_key( (unsigned char*)&shared_key.front(), pk, dh );
        BN_free(pk);
        DH_free(dh);
        return valid = true;
   }
Esempio n. 19
0
DH *createPubkey(){

	DH *privkey;
	int codes;
	

	/* Generate the parameters to be used */
	if(NULL == (privkey = DH_new())) handleErrors();
	if(1 != DH_generate_parameters_ex(privkey, 512, DH_GENERATOR_2, NULL)) handleErrors();

	if(1 != DH_check(privkey, &codes)) handleErrors();
	if(codes != 0)
	{
	/* Problems have been found with the generated parameters */
	/* Handle these here - we'll just abort for this example */
	printf("DH_check failed\n");
	abort();
	}

	/* Generate the public and private key pair */
	if(1 != DH_generate_key(privkey)) handleErrors();
	return privkey;
	
}
Esempio n. 20
0
int dhparam_main(int argc, char **argv)
{
    BIO *in = NULL, *out = NULL;
    DH *dh = NULL;
    char *infile = NULL, *outfile = NULL, *prog, *inrand = NULL;
#ifndef OPENSSL_NO_DSA
    int dsaparam = 0;
#endif
    int i, text = 0, C = 0, ret = 1, num = 0, g = 0;
    int informat = FORMAT_PEM, outformat = FORMAT_PEM, check = 0, noout = 0;
    OPTION_CHOICE o;

    prog = opt_init(argc, argv, dhparam_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
 opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            opt_help(dhparam_options);
            ret = 0;
            goto end;
        case OPT_INFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
                goto opthelp;
            break;
        case OPT_OUTFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
                goto opthelp;
            break;
        case OPT_IN:
            infile = opt_arg();
            break;
        case OPT_OUT:
            outfile = opt_arg();
            break;
        case OPT_ENGINE:
            (void)setup_engine(opt_arg(), 0);
            break;
        case OPT_CHECK:
            check = 1;
            break;
        case OPT_TEXT:
            text = 1;
            break;
        case OPT_DSAPARAM:
#ifndef OPENSSL_NO_DSA
            dsaparam = 1;
#endif
            break;
        case OPT_C:
            C = 1;
            break;
        case OPT_2:
            g = 2;
            break;
        case OPT_5:
            g = 5;
            break;
        case OPT_NOOUT:
            noout = 1;
            break;
        case OPT_RAND:
            inrand = opt_arg();
            break;
        }
    }
    argc = opt_num_rest();
    argv = opt_rest();

    if (argv[0] && (!opt_int(argv[0], &num) || num <= 0))
        goto end;

    if (g && !num)
        num = DEFBITS;

# ifndef OPENSSL_NO_DSA
    if (dsaparam && g) {
        BIO_printf(bio_err,
                   "generator may not be chosen for DSA parameters\n");
        goto end;
    }
# endif
    /* DH parameters */
    if (num && !g)
        g = 2;

    if (num) {

        BN_GENCB *cb;
        cb = BN_GENCB_new();
        if (cb == NULL) {
            ERR_print_errors(bio_err);
            goto end;
        }

        BN_GENCB_set(cb, dh_cb, bio_err);
        if (!app_RAND_load_file(NULL, 1) && inrand == NULL) {
            BIO_printf(bio_err,
                       "warning, not much extra random data, consider using the -rand option\n");
        }
        if (inrand != NULL)
            BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
                       app_RAND_load_files(inrand));

# ifndef OPENSSL_NO_DSA
        if (dsaparam) {
            DSA *dsa = DSA_new();

            BIO_printf(bio_err,
                       "Generating DSA parameters, %d bit long prime\n", num);
            if (dsa == NULL
                || !DSA_generate_parameters_ex(dsa, num, NULL, 0, NULL, NULL,
                                               cb)) {
                DSA_free(dsa);
                BN_GENCB_free(cb);
                ERR_print_errors(bio_err);
                goto end;
            }

            dh = DSA_dup_DH(dsa);
            DSA_free(dsa);
            if (dh == NULL) {
                BN_GENCB_free(cb);
                ERR_print_errors(bio_err);
                goto end;
            }
        } else
# endif
        {
            dh = DH_new();
            BIO_printf(bio_err,
                       "Generating DH parameters, %d bit long safe prime, generator %d\n",
                       num, g);
            BIO_printf(bio_err, "This is going to take a long time\n");
            if (dh == NULL || !DH_generate_parameters_ex(dh, num, g, cb)) {
                BN_GENCB_free(cb);
                ERR_print_errors(bio_err);
                goto end;
            }
        }

        BN_GENCB_free(cb);
        app_RAND_write_file(NULL);
    } else {

        in = bio_open_default(infile, 'r', informat);
        if (in == NULL)
            goto end;

# ifndef OPENSSL_NO_DSA
        if (dsaparam) {
            DSA *dsa;

            if (informat == FORMAT_ASN1)
                dsa = d2i_DSAparams_bio(in, NULL);
            else                /* informat == FORMAT_PEM */
                dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL);

            if (dsa == NULL) {
                BIO_printf(bio_err, "unable to load DSA parameters\n");
                ERR_print_errors(bio_err);
                goto end;
            }

            dh = DSA_dup_DH(dsa);
            DSA_free(dsa);
            if (dh == NULL) {
                ERR_print_errors(bio_err);
                goto end;
            }
        } else
# endif
        {
            if (informat == FORMAT_ASN1)
                dh = d2i_DHparams_bio(in, NULL);
            else                /* informat == FORMAT_PEM */
                dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);

            if (dh == NULL) {
                BIO_printf(bio_err, "unable to load DH parameters\n");
                ERR_print_errors(bio_err);
                goto end;
            }
        }

        /* dh != NULL */
    }

    out = bio_open_default(outfile, 'w', outformat);
    if (out == NULL)
        goto end;

    if (text) {
        DHparams_print(out, dh);
    }

    if (check) {
        if (!DH_check(dh, &i)) {
            ERR_print_errors(bio_err);
            goto end;
        }
        if (i & DH_CHECK_P_NOT_PRIME)
            printf("p value is not prime\n");
        if (i & DH_CHECK_P_NOT_SAFE_PRIME)
            printf("p value is not a safe prime\n");
        if (i & DH_UNABLE_TO_CHECK_GENERATOR)
            printf("unable to check the generator value\n");
        if (i & DH_NOT_SUITABLE_GENERATOR)
            printf("the g value is not a generator\n");
        if (i == 0)
            printf("DH parameters appear to be ok.\n");
    }
    if (C) {
        unsigned char *data;
        int len, bits;

        len = BN_num_bytes(dh->p);
        bits = BN_num_bits(dh->p);
        data = app_malloc(len, "print a BN");
        BIO_printf(out, "#ifndef HEADER_DH_H\n"
                        "# include <openssl/dh.h>\n"
                        "#endif\n"
                        "\n");
        BIO_printf(out, "DH *get_dh%d()\n{\n", bits);
        print_bignum_var(out, dh->p, "dhp", bits, data);
        print_bignum_var(out, dh->g, "dhg", bits, data);
        BIO_printf(out, "    DH *dh = DN_new();\n"
                        "\n"
                        "    if (dh == NULL)\n"
                        "        return NULL;\n");
        BIO_printf(out, "    dh->p = BN_bin2bn(dhp_%d, sizeof (dhp_%d), NULL);\n",
               bits, bits);
        BIO_printf(out, "    dh->g = BN_bin2bn(dhg_%d, sizeof (dhg_%d), NULL);\n",
               bits, bits);
        BIO_printf(out, "    if (!dh->p || !dh->g) {\n"
                        "        DH_free(dh);\n"
                        "        return NULL;\n"
                        "    }\n");
        if (dh->length)
            BIO_printf(out,
                        "    dh->length = %ld;\n", dh->length);
        BIO_printf(out, "    return dh;\n}\n");
        OPENSSL_free(data);
    }

    if (!noout) {
        if (outformat == FORMAT_ASN1)
            i = i2d_DHparams_bio(out, dh);
        else if (dh->q)
            i = PEM_write_bio_DHxparams(out, dh);
        else
            i = PEM_write_bio_DHparams(out, dh);
        if (!i) {
            BIO_printf(bio_err, "unable to write DH parameters\n");
            ERR_print_errors(bio_err);
            goto end;
        }
    }
    ret = 0;
 end:
    BIO_free(in);
    BIO_free_all(out);
    DH_free(dh);
    return (ret);
}
Esempio n. 21
0
int main(void)
{
    DH* dh_store;
    int codes;

    // Allocate and initialize a DH structure
    dh_store = DH_new();

    // If allocation failed
    if (dh_store == NULL)
    {
        fprintf(stderr, "Error allocating DH structure.\n");
        fprintf(stderr, "%s", ERR_reason_error_string(ERR_get_error()));
        return 1;
    }


    // Generate the prime, and and initialize the generator to be used for this exchange
    if (DH_generate_parameters_ex(dh_store, PRIME_LENGTH, DH_GENERATOR_2, NULL) != 1)
    {
        fprintf(stderr, "Error allocating parameters.\n");
        fprintf(stderr, "%s", ERR_reason_error_string(ERR_get_error()));
        return 1;
    }


    // Validate the generated prime (p) and the supplied generator (g).
    if (!DH_check(dh_store, &codes))
    {
        fprintf(stderr, "Could not perform check.\n");
        fprintf(stderr, "%s", ERR_reason_error_string(ERR_get_error()));
        return 1;
    }
    

    // Examine the results of the check performed earlier.
    if (codes != 0)
    {
        // Check and print out what kind of error was identified.
        if (codes & DH_UNABLE_TO_CHECK_GENERATOR)
            fprintf(stderr, "Generator must be either 2 or 5.\n");
        else if (codes & DH_NOT_SUITABLE_GENERATOR)
            fprintf(stderr, "Generator is not suitable.\n");
        else if (codes & DH_CHECK_P_NOT_PRIME)
            fprintf(stderr, "Non-prime value found in structure.");
        else if (codes & DH_CHECK_P_NOT_SAFE_PRIME)
            fprintf(stderr, "Unsafe prime found in structure.\n");
        else
            fprintf(stderr, "Unknown error.\n");
     
        fprintf(stderr, "%s", ERR_reason_error_string(ERR_get_error()));

        return 1;
    }


    // Generate the private value (aka private key) and the 
    // public value (aka public key).
    if (!DH_generate_key(dh_store))
    {
        fprintf(stderr, "Error generating public and private keys.");
        fprintf(stderr, "%s", ERR_reason_error_string(ERR_get_error()));        

        return 1;
    }

    printf("Generator:\n");
    BN_print_fp(stdout, dh_store->g);
    printf("\n\n");
    printf("Prime:\n");
    BN_print_fp(stdout, dh_store->p);
    printf("\n\n");
    printf("Private key:\n");
    BN_print_fp(stdout, dh_store->priv_key);
    printf("\n\n");
    printf("Public key:\n");
    BN_print_fp(stdout, dh_store->pub_key);
    printf("\n\n");

    // Free the DH structure.
    DH_free(dh_store);

    return 0;
}
Esempio n. 22
0
int
dhparam_main(int argc, char **argv)
{
	BIO *in = NULL, *out = NULL;
	char *num_bits = NULL;
	DH *dh = NULL;
	int num = 0;
	int ret = 1;
	int i;

	memset(&dhparam_config, 0, sizeof(dhparam_config));

	dhparam_config.informat = FORMAT_PEM;
	dhparam_config.outformat = FORMAT_PEM;

	if (options_parse(argc, argv, dhparam_options, &num_bits, NULL) != 0) {
		dhparam_usage();
		return (1);
	}

	if (num_bits != NULL) {
		if(sscanf(num_bits, "%d", &num) == 0 || num <= 0) {
			BIO_printf(bio_err, "invalid number of bits: %s\n",
			    num_bits);
			return (1);
		}
	}

	if (dhparam_config.g && !num)
		num = DEFBITS;

	if (dhparam_config.dsaparam) {
		if (dhparam_config.g) {
			BIO_printf(bio_err, "generator may not be chosen for DSA parameters\n");
			goto end;
		}
	} else {
		/* DH parameters */
		if (num && !dhparam_config.g)
			dhparam_config.g = 2;
	}

	if (num) {

		BN_GENCB cb;
		BN_GENCB_set(&cb, dh_cb, bio_err);
		if (dhparam_config.dsaparam) {
			DSA *dsa = DSA_new();

			BIO_printf(bio_err, "Generating DSA parameters, %d bit long prime\n", num);
			if (!dsa || !DSA_generate_parameters_ex(dsa, num,
				NULL, 0, NULL, NULL, &cb)) {
				if (dsa)
					DSA_free(dsa);
				ERR_print_errors(bio_err);
				goto end;
			}
			dh = DSA_dup_DH(dsa);
			DSA_free(dsa);
			if (dh == NULL) {
				ERR_print_errors(bio_err);
				goto end;
			}
		} else {
			dh = DH_new();
			BIO_printf(bio_err, "Generating DH parameters, %d bit long safe prime, generator %d\n", num, dhparam_config.g);
			BIO_printf(bio_err, "This is going to take a long time\n");
			if (!dh || !DH_generate_parameters_ex(dh, num, dhparam_config.g, &cb)) {
				ERR_print_errors(bio_err);
				goto end;
			}
		}
	} else {

		in = BIO_new(BIO_s_file());
		if (in == NULL) {
			ERR_print_errors(bio_err);
			goto end;
		}
		if (dhparam_config.infile == NULL)
			BIO_set_fp(in, stdin, BIO_NOCLOSE);
		else {
			if (BIO_read_filename(in, dhparam_config.infile) <= 0) {
				perror(dhparam_config.infile);
				goto end;
			}
		}

		if (dhparam_config.informat != FORMAT_ASN1 &&
		    dhparam_config.informat != FORMAT_PEM) {
			BIO_printf(bio_err, "bad input format specified\n");
			goto end;
		}
		if (dhparam_config.dsaparam) {
			DSA *dsa;

			if (dhparam_config.informat == FORMAT_ASN1)
				dsa = d2i_DSAparams_bio(in, NULL);
			else	/* informat == FORMAT_PEM */
				dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL);

			if (dsa == NULL) {
				BIO_printf(bio_err, "unable to load DSA parameters\n");
				ERR_print_errors(bio_err);
				goto end;
			}
			dh = DSA_dup_DH(dsa);
			DSA_free(dsa);
			if (dh == NULL) {
				ERR_print_errors(bio_err);
				goto end;
			}
		} else
		{
			if (dhparam_config.informat == FORMAT_ASN1)
				dh = d2i_DHparams_bio(in, NULL);
			else	/* informat == FORMAT_PEM */
				dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);

			if (dh == NULL) {
				BIO_printf(bio_err, "unable to load DH parameters\n");
				ERR_print_errors(bio_err);
				goto end;
			}
		}

		/* dh != NULL */
	}

	out = BIO_new(BIO_s_file());
	if (out == NULL) {
		ERR_print_errors(bio_err);
		goto end;
	}
	if (dhparam_config.outfile == NULL) {
		BIO_set_fp(out, stdout, BIO_NOCLOSE);
	} else {
		if (BIO_write_filename(out, dhparam_config.outfile) <= 0) {
			perror(dhparam_config.outfile);
			goto end;
		}
	}


	if (dhparam_config.text) {
		DHparams_print(out, dh);
	}
	if (dhparam_config.check) {
		if (!DH_check(dh, &i)) {
			ERR_print_errors(bio_err);
			goto end;
		}
		if (i & DH_CHECK_P_NOT_PRIME)
			printf("p value is not prime\n");
		if (i & DH_CHECK_P_NOT_SAFE_PRIME)
			printf("p value is not a safe prime\n");
		if (i & DH_UNABLE_TO_CHECK_GENERATOR)
			printf("unable to check the generator value\n");
		if (i & DH_NOT_SUITABLE_GENERATOR)
			printf("the g value is not a generator\n");
		if (i == 0)
			printf("DH parameters appear to be ok.\n");
	}
	if (dhparam_config.C) {
		unsigned char *data;
		int len, l, bits;

		len = BN_num_bytes(dh->p);
		bits = BN_num_bits(dh->p);
		data = malloc(len);
		if (data == NULL) {
			perror("malloc");
			goto end;
		}
		printf("#ifndef HEADER_DH_H\n"
		    "#include <openssl/dh.h>\n"
		    "#endif\n");
		printf("DH *get_dh%d()\n\t{\n", bits);

		l = BN_bn2bin(dh->p, data);
		printf("\tstatic unsigned char dh%d_p[] = {", bits);
		for (i = 0; i < l; i++) {
			if ((i % 12) == 0)
				printf("\n\t\t");
			printf("0x%02X, ", data[i]);
		}
		printf("\n\t\t};\n");

		l = BN_bn2bin(dh->g, data);
		printf("\tstatic unsigned char dh%d_g[] = {", bits);
		for (i = 0; i < l; i++) {
			if ((i % 12) == 0)
				printf("\n\t\t");
			printf("0x%02X, ", data[i]);
		}
		printf("\n\t\t};\n");

		printf("\tDH *dh;\n\n");
		printf("\tif ((dh = DH_new()) == NULL) return(NULL);\n");
		printf("\tdh->p = BN_bin2bn(dh%d_p, sizeof(dh%d_p), NULL);\n",
		    bits, bits);
		printf("\tdh->g = BN_bin2bn(dh%d_g, sizeof(dh%d_g), NULL);\n",
		    bits, bits);
		printf("\tif ((dh->p == NULL) || (dh->g == NULL))\n");
		printf("\t\t{ DH_free(dh); return(NULL); }\n");
		if (dh->length)
			printf("\tdh->length = %ld;\n", dh->length);
		printf("\treturn(dh);\n\t}\n");
		free(data);
	}
	if (!dhparam_config.noout) {
		if (dhparam_config.outformat == FORMAT_ASN1)
			i = i2d_DHparams_bio(out, dh);
		else if (dhparam_config.outformat == FORMAT_PEM)
			i = PEM_write_bio_DHparams(out, dh);
		else {
			BIO_printf(bio_err, "bad output format specified for outfile\n");
			goto end;
		}
		if (!i) {
			BIO_printf(bio_err, "unable to write DH parameters\n");
			ERR_print_errors(bio_err);
			goto end;
		}
	}
	ret = 0;

end:
	BIO_free(in);
	if (out != NULL)
		BIO_free_all(out);
	if (dh != NULL)
		DH_free(dh);

	return (ret);
}
Esempio n. 23
0
int MAIN(int argc, char **argv)
{
    BIO *in = NULL, *out = NULL;
    char *infile, *outfile, *prog;
    char *inrand = NULL;
    char *id = NULL;

    apps_startup();

    if (bio_err == NULL)
        if ((bio_err = BIO_new(BIO_s_file())) != NULL)
            BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);

    if (!load_config(bio_err, NULL))
        goto end;

    outfile = NULL;

    prog = argv[0];
    argc--;
    argv++;
    while (argc >= 1) {
        if (strcmp(*argv, "-inform") == 0) {
            if (--argc < 1)
                goto bad;
            informat = str2fmt(*(++argv));
        } else if (strcmp(*argv, "-outform") == 0) {
            if (--argc < 1)
                goto bad;
            outformat = str2fmt(*(++argv));
        } else if (strcmp(*argv, "-in") == 0) {
            if (--argc < 1)
                goto bad;
            infile = *(++argv);
        } else if (strcmp(*argv, "-out") == 0) {
            if (--argc < 1)
                goto bad;
            outfile = *(++argv);
        }
        else if (strcmp(*argv, "-check") == 0)
            check = 1;
        else if (strcmp(*argv, "-text") == 0)
            text = 1;
        else if (strcmp(*argv, "-dsaparam") == 0)
            dsaparam = 1;
        else if (strcmp(*argv, "-C") == 0)
            C = 1;
        else if (strcmp(*argv, "-noout") == 0)
            noout = 1;
        else if (strcmp(*argv, "-2") == 0)
            g = 2;
        else if (strcmp(*argv, "-5") == 0)
            g = 5;
        else if (strcmp(*argv, "-rand") == 0) {
            if (--argc < 1)
                goto bad;
            inrand = *(++argv);
        } else if (((sscanf(*argv, "%d", &num) == 0) || (num <= 0)))
            goto bad;
        argv++;
        argc--;
    }

    if (badops) {
 bad:
        BIO_printf(bio_err, "%s [options] [numbits]\n", prog);
        BIO_printf(bio_err, "where options are\n");
        BIO_printf(bio_err, " -inform arg   input format - one of DER PEM\n");
        BIO_printf(bio_err,
                   " -outform arg  output format - one of DER PEM\n");
        BIO_printf(bio_err, " -in arg       input file\n");
        BIO_printf(bio_err, " -out arg      output file\n");
        BIO_printf(bio_err,
                   " -dsaparam     read or generate DSA parameters, convert to DH\n");
        BIO_printf(bio_err, " -check        check the DH parameters\n");
        BIO_printf(bio_err,
                   " -text         print a text form of the DH parameters\n");
        BIO_printf(bio_err, " -C            Output C code\n");
        BIO_printf(bio_err,
                   " -2            generate parameters using  2 as the generator value\n");
        BIO_printf(bio_err,
                   " -5            generate parameters using  5 as the generator value\n");
        BIO_printf(bio_err,
                   " numbits       number of bits in to generate (default 2048)\n");
        BIO_printf(bio_err, " -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR,
                   LIST_SEPARATOR_CHAR);
        BIO_printf(bio_err,
                   "               - load the file (or the files in the directory) into\n");
        BIO_printf(bio_err, "               the random number generator\n");
        BIO_printf(bio_err, " -noout        no output\n");
        goto end;
    }

    ERR_load_crypto_strings();

    if (g && !num)
        num = DEFBITS;

    if (dsaparam) {
        if (g) {
            BIO_printf(bio_err,
                       "generator may not be chosen for DSA parameters\n");
            goto end;
        }
    } else
    {
        /* DH parameters */
        if (num && !g)
            g = 2;
    }

    if (num) {

        BN_GENCB cb;
        BN_GENCB_set(&cb, dh_cb, bio_err);
        if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL) {
            BIO_printf(bio_err,
                       "warning, not much extra random data, consider using the -rand option\n");
        }
        if (inrand != NULL)
            BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
                       app_RAND_load_files(inrand));

# ifndef OPENSSL_NO_DSA
        if (dsaparam) {
            DSA *dsa = DSA_new();

            BIO_printf(bio_err,
                       "Generating DSA parameters, %d bit long prime\n", num);
            if (!dsa
                || !DSA_generate_parameters_ex(dsa, num, NULL, 0, NULL, NULL,
                                               &cb)) {
                if (dsa)
                    DSA_free(dsa);
                ERR_print_errors(bio_err);
                goto end;
            }

            dh = DSA_dup_DH(dsa);
            DSA_free(dsa);
            if (dh == NULL) {
                ERR_print_errors(bio_err);
                goto end;
            }
        } else
# endif
        {
            dh = DH_new();
            BIO_printf(bio_err,
                       "Generating DH parameters, %d bit long safe prime, generator %d\n",
                       num, g);
            BIO_printf(bio_err, "This is going to take a long time\n");
            if (!dh || !DH_generate_parameters_ex(dh, num, g, &cb)) {
                ERR_print_errors(bio_err);
                goto end;
            }
        }

        app_RAND_write_file(NULL, bio_err);
    } else {

        in = BIO_new(BIO_s_file());
        if (in == NULL) {
            ERR_print_errors(bio_err);
            goto end;
        }
        if (infile == NULL)
            BIO_set_fp(in, stdin, BIO_NOCLOSE);
        else {
            if (BIO_read_filename(in, infile) <= 0) {
                perror(infile);
                goto end;
            }
        }

        if (informat != FORMAT_ASN1 && informat != FORMAT_PEM) {
            BIO_printf(bio_err, "bad input format specified\n");
            goto end;
        }
# ifndef OPENSSL_NO_DSA
        if (dsaparam) {
            DSA *dsa;

            if (informat == FORMAT_ASN1)
                dsa = d2i_DSAparams_bio(in, NULL);
            else                /* informat == FORMAT_PEM */
                dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL);

            if (dsa == NULL) {
                BIO_printf(bio_err, "unable to load DSA parameters\n");
                ERR_print_errors(bio_err);
                goto end;
            }

            dh = DSA_dup_DH(dsa);
            DSA_free(dsa);
            if (dh == NULL) {
                ERR_print_errors(bio_err);
                goto end;
            }
        } else
# endif
        {
            if (informat == FORMAT_ASN1)
                dh = d2i_DHparams_bio(in, NULL);
            else                /* informat == FORMAT_PEM */
                dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);

            if (dh == NULL) {
                BIO_printf(bio_err, "unable to load DH parameters\n");
                ERR_print_errors(bio_err);
                goto end;
            }
        }

        /* dh != NULL */
    }

    out = BIO_new(BIO_s_file());
    if (out == NULL) {
        ERR_print_errors(bio_err);
        goto end;
    }
    if (outfile == NULL) {
        BIO_set_fp(out, stdout, BIO_NOCLOSE);
    } else {
        if (BIO_write_filename(out, outfile) <= 0) {
            perror(outfile);
            goto end;
        }
    }

    if (text) {
        DHparams_print(out, dh);
    }

    if (check) {
        if (!DH_check(dh, &i)) {
            ERR_print_errors(bio_err);
            goto end;
        }
        if (i & DH_CHECK_P_NOT_PRIME)
            printf("p value is not prime\n");
        if (i & DH_CHECK_P_NOT_SAFE_PRIME)
            printf("p value is not a safe prime\n");
        if (i & DH_UNABLE_TO_CHECK_GENERATOR)
            printf("unable to check the generator value\n");
        if (i & DH_NOT_SUITABLE_GENERATOR)
            printf("the g value is not a generator\n");
        if (i == 0)
            printf("DH parameters appear to be ok.\n");
    }
    if (C) {
        unsigned char *data;
        int len, l, bits;

        len = BN_num_bytes(dh->p);
        bits = BN_num_bits(dh->p);
        data = (unsigned char *)OPENSSL_malloc(len);
        if (data == NULL) {
            perror("OPENSSL_malloc");
            goto end;
        }
        printf("#ifndef HEADER_DH_H\n"
               "#include <openssl/dh.h>\n" "#endif\n");
        printf("DH *get_dh%d()\n\t{\n", bits);

        l = BN_bn2bin(dh->p, data);
        printf("\tstatic unsigned char dh%d_p[]={", bits);
        for (i = 0; i < l; i++) {
            if ((i % 12) == 0)
                printf("\n\t\t");
            printf("0x%02X,", data[i]);
        }
        printf("\n\t\t};\n");

        l = BN_bn2bin(dh->g, data);
        printf("\tstatic unsigned char dh%d_g[]={", bits);
        for (i = 0; i < l; i++) {
            if ((i % 12) == 0)
                printf("\n\t\t");
            printf("0x%02X,", data[i]);
        }
        printf("\n\t\t};\n");

        printf("\tDH *dh;\n\n");
        printf("\tif ((dh=DH_new()) == NULL) return(NULL);\n");
        printf("\tdh->p=BN_bin2bn(dh%d_p,sizeof(dh%d_p),NULL);\n",
               bits, bits);
        printf("\tdh->g=BN_bin2bn(dh%d_g,sizeof(dh%d_g),NULL);\n",
               bits, bits);
        printf("\tif ((dh->p == NULL) || (dh->g == NULL))\n");
        printf("\t\t{ DH_free(dh); return(NULL); }\n");
        if (dh->length)
            printf("\tdh->length = %ld;\n", dh->length);
        printf("\treturn(dh);\n\t}\n");
        OPENSSL_free(data);
    }

    if (!noout) {
        if (outformat == FORMAT_ASN1)
            i = i2d_DHparams_bio(out, dh);
        else if (outformat == FORMAT_PEM) {
            if (dh->q)
                i = PEM_write_bio_DHxparams(out, dh);
            else
                i = PEM_write_bio_DHparams(out, dh);
        } else {
            BIO_printf(bio_err, "bad output format specified for outfile\n");
            goto end;
        }
        if (!i) {
            BIO_printf(bio_err, "unable to write DH parameters\n");
            ERR_print_errors(bio_err);
            goto end;
        }
    }
    ret = 0;
 end:
    if (in != NULL)
        BIO_free(in);
    if (out != NULL)
        BIO_free_all(out);
    if (dh != NULL)
        DH_free(dh);
    apps_shutdown();
    OPENSSL_EXIT(ret);
}
Esempio n. 24
0
int dhparam_main(int argc, char **argv)
{
    BIO *in = NULL, *out = NULL;
    DH *dh = NULL;
    char *infile = NULL, *outfile = NULL, *prog;
    ENGINE *e = NULL;
#ifndef OPENSSL_NO_DSA
    int dsaparam = 0;
#endif
    int i, text = 0, C = 0, ret = 1, num = 0, g = 0;
    int informat = FORMAT_PEM, outformat = FORMAT_PEM, check = 0, noout = 0;
    OPTION_CHOICE o;

    prog = opt_init(argc, argv, dhparam_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
 opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            opt_help(dhparam_options);
            ret = 0;
            goto end;
        case OPT_INFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
                goto opthelp;
            break;
        case OPT_OUTFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
                goto opthelp;
            break;
        case OPT_IN:
            infile = opt_arg();
            break;
        case OPT_OUT:
            outfile = opt_arg();
            break;
        case OPT_ENGINE:
            e = setup_engine(opt_arg(), 0);
            break;
        case OPT_CHECK:
            check = 1;
            break;
        case OPT_TEXT:
            text = 1;
            break;
        case OPT_DSAPARAM:
#ifndef OPENSSL_NO_DSA
            dsaparam = 1;
#endif
            break;
        case OPT_C:
            C = 1;
            break;
        case OPT_2:
            g = 2;
            break;
        case OPT_5:
            g = 5;
            break;
        case OPT_NOOUT:
            noout = 1;
            break;
        case OPT_R_CASES:
            if (!opt_rand(o))
                goto end;
            break;
        }
    }
    argc = opt_num_rest();
    argv = opt_rest();

    if (argv[0] != NULL && (!opt_int(argv[0], &num) || num <= 0))
        goto end;

    if (g && !num)
        num = DEFBITS;

# ifndef OPENSSL_NO_DSA
    if (dsaparam && g) {
        BIO_printf(bio_err,
                   "generator may not be chosen for DSA parameters\n");
        goto end;
    }
# endif

    out = bio_open_default(outfile, 'w', outformat);
    if (out == NULL)
        goto end;

    /* DH parameters */
    if (num && !g)
        g = 2;

    if (num) {

        BN_GENCB *cb;
        cb = BN_GENCB_new();
        if (cb == NULL) {
            ERR_print_errors(bio_err);
            goto end;
        }

        BN_GENCB_set(cb, dh_cb, bio_err);

# ifndef OPENSSL_NO_DSA
        if (dsaparam) {
            DSA *dsa = DSA_new();

            BIO_printf(bio_err,
                       "Generating DSA parameters, %d bit long prime\n", num);
            if (dsa == NULL
                || !DSA_generate_parameters_ex(dsa, num, NULL, 0, NULL, NULL,
                                               cb)) {
                DSA_free(dsa);
                BN_GENCB_free(cb);
                ERR_print_errors(bio_err);
                goto end;
            }

            dh = DSA_dup_DH(dsa);
            DSA_free(dsa);
            if (dh == NULL) {
                BN_GENCB_free(cb);
                ERR_print_errors(bio_err);
                goto end;
            }
        } else
# endif
        {
            dh = DH_new();
            BIO_printf(bio_err,
                       "Generating DH parameters, %d bit long safe prime, generator %d\n",
                       num, g);
            BIO_printf(bio_err, "This is going to take a long time\n");
            if (dh == NULL || !DH_generate_parameters_ex(dh, num, g, cb)) {
                BN_GENCB_free(cb);
                ERR_print_errors(bio_err);
                goto end;
            }
        }

        BN_GENCB_free(cb);
    } else {

        in = bio_open_default(infile, 'r', informat);
        if (in == NULL)
            goto end;

# ifndef OPENSSL_NO_DSA
        if (dsaparam) {
            DSA *dsa;

            if (informat == FORMAT_ASN1)
                dsa = d2i_DSAparams_bio(in, NULL);
            else                /* informat == FORMAT_PEM */
                dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL);

            if (dsa == NULL) {
                BIO_printf(bio_err, "unable to load DSA parameters\n");
                ERR_print_errors(bio_err);
                goto end;
            }

            dh = DSA_dup_DH(dsa);
            DSA_free(dsa);
            if (dh == NULL) {
                ERR_print_errors(bio_err);
                goto end;
            }
        } else
# endif
        {
            if (informat == FORMAT_ASN1) {
                /*
                 * We have no PEM header to determine what type of DH params it
                 * is. We'll just try both.
                 */
                dh = d2i_DHparams_bio(in, NULL);
                /* BIO_reset() returns 0 for success for file BIOs only!!! */
                if (dh == NULL && BIO_reset(in) == 0)
                    dh = d2i_DHxparams_bio(in, NULL);
            } else {
                /* informat == FORMAT_PEM */
                dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
            }

            if (dh == NULL) {
                BIO_printf(bio_err, "unable to load DH parameters\n");
                ERR_print_errors(bio_err);
                goto end;
            }
        }

        /* dh != NULL */
    }

    if (text) {
        DHparams_print(out, dh);
    }

    if (check) {
        if (!DH_check(dh, &i)) {
            ERR_print_errors(bio_err);
            goto end;
        }
        if (i & DH_CHECK_P_NOT_PRIME)
            BIO_printf(bio_err, "WARNING: p value is not prime\n");
        if (i & DH_CHECK_P_NOT_SAFE_PRIME)
            BIO_printf(bio_err, "WARNING: p value is not a safe prime\n");
        if (i & DH_CHECK_Q_NOT_PRIME)
            BIO_printf(bio_err, "WARNING: q value is not a prime\n");
        if (i & DH_CHECK_INVALID_Q_VALUE)
            BIO_printf(bio_err, "WARNING: q value is invalid\n");
        if (i & DH_CHECK_INVALID_J_VALUE)
            BIO_printf(bio_err, "WARNING: j value is invalid\n");
        if (i & DH_UNABLE_TO_CHECK_GENERATOR)
            BIO_printf(bio_err,
                       "WARNING: unable to check the generator value\n");
        if (i & DH_NOT_SUITABLE_GENERATOR)
            BIO_printf(bio_err, "WARNING: the g value is not a generator\n");
        if (i == 0)
            BIO_printf(bio_err, "DH parameters appear to be ok.\n");
        if (num != 0 && i != 0) {
            /*
             * We have generated parameters but DH_check() indicates they are
             * invalid! This should never happen!
             */
            BIO_printf(bio_err, "ERROR: Invalid parameters generated\n");
            goto end;
        }
    }
    if (C) {
        unsigned char *data;
        int len, bits;
        const BIGNUM *pbn, *gbn;

        len = DH_size(dh);
        bits = DH_bits(dh);
        DH_get0_pqg(dh, &pbn, NULL, &gbn);
        data = app_malloc(len, "print a BN");

        BIO_printf(out, "static DH *get_dh%d(void)\n{\n", bits);
        print_bignum_var(out, pbn, "dhp", bits, data);
        print_bignum_var(out, gbn, "dhg", bits, data);
        BIO_printf(out, "    DH *dh = DH_new();\n"
                        "    BIGNUM *p, *g;\n"
                        "\n"
                        "    if (dh == NULL)\n"
                        "        return NULL;\n");
        BIO_printf(out, "    p = BN_bin2bn(dhp_%d, sizeof(dhp_%d), NULL);\n",
                   bits, bits);
        BIO_printf(out, "    g = BN_bin2bn(dhg_%d, sizeof(dhg_%d), NULL);\n",
                   bits, bits);
        BIO_printf(out, "    if (p == NULL || g == NULL\n"
                        "            || !DH_set0_pqg(dh, p, NULL, g)) {\n"
                        "        DH_free(dh);\n"
                        "        BN_free(p);\n"
                        "        BN_free(g);\n"
                        "        return NULL;\n"
                        "    }\n");
        if (DH_get_length(dh) > 0)
            BIO_printf(out,
                        "    if (!DH_set_length(dh, %ld)) {\n"
                        "        DH_free(dh);\n"
                        "        return NULL;\n"
                        "    }\n", DH_get_length(dh));
        BIO_printf(out, "    return dh;\n}\n");
        OPENSSL_free(data);
    }

    if (!noout) {
        const BIGNUM *q;
        DH_get0_pqg(dh, NULL, &q, NULL);
        if (outformat == FORMAT_ASN1) {
            if (q != NULL)
                i = i2d_DHxparams_bio(out, dh);
            else
                i = i2d_DHparams_bio(out, dh);
        } else if (q != NULL) {
            i = PEM_write_bio_DHxparams(out, dh);
        } else {
            i = PEM_write_bio_DHparams(out, dh);
        }
        if (!i) {
            BIO_printf(bio_err, "unable to write DH parameters\n");
            ERR_print_errors(bio_err);
            goto end;
        }
    }
    ret = 0;
 end:
    BIO_free(in);
    BIO_free_all(out);
    DH_free(dh);
    release_engine(e);
    return ret;
}
Esempio n. 25
0
 static bool validate( const ssl_dh& dh, bool& valid ) {
     int check;
     DH_check(dh,&check);
     return valid = !(check /*& DH_CHECK_P_NOT_SAFE_PRIME*/);
 }
Esempio n. 26
0
int
dh_main(int argc, char **argv)
{
    DH *dh = NULL;
    int i;
    BIO *in = NULL, *out = NULL;
    int ret = 1;

    memset(&dh_config, 0, sizeof(dh_config));

    dh_config.informat = FORMAT_PEM;
    dh_config.outformat = FORMAT_PEM;

    if (options_parse(argc, argv, dh_options, NULL, NULL) != 0) {
        dh_usage();
        goto end;
    }

    in = BIO_new(BIO_s_file());
    out = BIO_new(BIO_s_file());
    if (in == NULL || out == NULL) {
        ERR_print_errors(bio_err);
        goto end;
    }
    if (dh_config.infile == NULL)
        BIO_set_fp(in, stdin, BIO_NOCLOSE);
    else {
        if (BIO_read_filename(in, dh_config.infile) <= 0) {
            perror(dh_config.infile);
            goto end;
        }
    }
    if (dh_config.outfile == NULL) {
        BIO_set_fp(out, stdout, BIO_NOCLOSE);
    } else {
        if (BIO_write_filename(out, dh_config.outfile) <= 0) {
            perror(dh_config.outfile);
            goto end;
        }
    }

    if (dh_config.informat == FORMAT_ASN1)
        dh = d2i_DHparams_bio(in, NULL);
    else if (dh_config.informat == FORMAT_PEM)
        dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
    else {
        BIO_printf(bio_err, "bad input format specified\n");
        goto end;
    }
    if (dh == NULL) {
        BIO_printf(bio_err, "unable to load DH parameters\n");
        ERR_print_errors(bio_err);
        goto end;
    }
    if (dh_config.text) {
        DHparams_print(out, dh);
    }
    if (dh_config.check) {
        if (!DH_check(dh, &i)) {
            ERR_print_errors(bio_err);
            goto end;
        }
        if (i & DH_CHECK_P_NOT_PRIME)
            printf("p value is not prime\n");
        if (i & DH_CHECK_P_NOT_SAFE_PRIME)
            printf("p value is not a safe prime\n");
        if (i & DH_UNABLE_TO_CHECK_GENERATOR)
            printf("unable to check the generator value\n");
        if (i & DH_NOT_SUITABLE_GENERATOR)
            printf("the g value is not a generator\n");
        if (i == 0)
            printf("DH parameters appear to be ok.\n");
    }
    if (dh_config.C) {
        unsigned char *data;
        int len, l, bits;

        len = BN_num_bytes(dh->p);
        bits = BN_num_bits(dh->p);
        data = malloc(len);
        if (data == NULL) {
            perror("malloc");
            goto end;
        }
        l = BN_bn2bin(dh->p, data);
        printf("static unsigned char dh%d_p[] = {", bits);
        for (i = 0; i < l; i++) {
            if ((i % 12) == 0)
                printf("\n\t");
            printf("0x%02X, ", data[i]);
        }
        printf("\n\t};\n");

        l = BN_bn2bin(dh->g, data);
        printf("static unsigned char dh%d_g[] = {", bits);
        for (i = 0; i < l; i++) {
            if ((i % 12) == 0)
                printf("\n\t");
            printf("0x%02X, ", data[i]);
        }
        printf("\n\t};\n\n");

        printf("DH *get_dh%d()\n\t{\n", bits);
        printf("\tDH *dh;\n\n");
        printf("\tif ((dh = DH_new()) == NULL) return(NULL);\n");
        printf("\tdh->p = BN_bin2bn(dh%d_p, sizeof(dh%d_p), NULL);\n",
               bits, bits);
        printf("\tdh->g = BN_bin2bn(dh%d_g, sizeof(dh%d_g), NULL);\n",
               bits, bits);
        printf("\tif ((dh->p == NULL) || (dh->g == NULL))\n");
        printf("\t\treturn(NULL);\n");
        printf("\treturn(dh);\n\t}\n");
        free(data);
    }
    if (!dh_config.noout) {
        if (dh_config.outformat == FORMAT_ASN1)
            i = i2d_DHparams_bio(out, dh);
        else if (dh_config.outformat == FORMAT_PEM)
            i = PEM_write_bio_DHparams(out, dh);
        else {
            BIO_printf(bio_err, "bad output format specified for outfile\n");
            goto end;
        }
        if (!i) {
            BIO_printf(bio_err, "unable to write DH parameters\n");
            ERR_print_errors(bio_err);
            goto end;
        }
    }
    ret = 0;

end:
    BIO_free(in);
    if (out != NULL)
        BIO_free_all(out);
    if (dh != NULL)
        DH_free(dh);

    return (ret);
}
Esempio n. 27
0
void Connector::onTextMsg(QString msg)
{
    //qDebug() << msg;
    QJsonDocument doc;
    QJsonDocument firDoc = QJsonDocument::fromJson(msg.toUtf8());
    QJsonObject firObj = firDoc.object();

    if(firObj["type"].toInt() == messType::rsaOpenkey){
        int codes;

        myPrivKey = DH_new();

        myPrivKey->p = BN_new();
        myPrivKey->g = BN_new();
        QByteArray pA = QByteArray::fromBase64(firObj["p"].toString().toLatin1());
        QByteArray gA = QByteArray::fromBase64(firObj["g"].toString().toLatin1());
        QACrypt::binArr2bn(QByteArray::fromBase64(firObj["p"].toString().toLatin1()), &myPrivKey->p);
        QACrypt::binArr2bn(QByteArray::fromBase64(firObj["g"].toString().toLatin1()), &myPrivKey->g);
        //BN_bin2bn((unsigned char*)pA.constData(), pA.size(), myPrivKey->p);
        //BN_bin2bn((unsigned char*)gA.constData(), gA.size(), myPrivKey->g);

        DH_check(myPrivKey, &codes);
        if(codes!=0){
            qDebug() << "DH check failed";
            abort();
        }

        DH_generate_key(myPrivKey);

        BIGNUM *pubKey = BN_new();
        //QByteArray pubbK = QByteArray::fromBase64(firObj["pubKey"].toString().toLatin1());
        //BN_bin2bn((unsigned char*)pubbK.constData(), pubbK.size(), pubKey);
        QACrypt::binArr2bn(QByteArray::fromBase64(firObj["pubKey"].toString().toLatin1()), &pubKey);
        qDebug() << "DH pubkey recieved!";

        unsigned char* sharedSecret = new unsigned char[1024];
        int keyLen = DH_compute_key(sharedSecret, pubKey, myPrivKey);
        if(keyLen == -1){
            ERR_print_errors_fp(stderr);
        }

        QByteArray keyArr = QByteArray::fromRawData((char*)sharedSecret, keyLen);

        //qDebug() << "sharedSecret: " << keyArr.toBase64();

        QJsonObject uData;
        uData["type"] = messType::rsaOpenkey;
        uData["pubKey"] = QString(QACrypt::bn2binArr(myPrivKey->pub_key).toBase64());
        QJsonDocument uDoc(uData);

        sendTextMess(uDoc.toJson(QJsonDocument::Compact));

        aesKey = keyArr;
        useAes = true;
        emit this->enableLogin();
    } else if(firObj["type"].toInt() == messType::aesKey){

    } else {
        if(useAes){
        doc = QJsonDocument::fromJson(QACrypt::decrypt2(QByteArray::fromBase64(firObj["data"].toString().toLatin1()),
                                      aesKey, QByteArray::fromBase64(firObj["iv"].toString().toLatin1())));
        } else {
            doc = QJsonDocument::fromJson(msg.toUtf8());
        }
        QJsonObject obj = doc.object();

        switch (obj["command"].toInt()) {
        case successLogin:
        {
            emit this->onSuccessLogin();
            break;
        }
        case error:
        {
            emit this->onErr(obj["eRRoRcode"].toInt());
            break;
        }
        case getItemGroups:
        {
            emit this->clearGr();
            QJsonDocument grDoc;
            grDoc = QJsonDocument::fromJson(obj["groupArr"].toString().toUtf8());
            QJsonArray grArr = grDoc.array();
            for (int i = 0; i < grArr.size(); i++){
                emit this->onNewGroup(grArr.at(i).toObject());
            }
            emit this->groupsToWidget();
            break;
        }
        case getItemsFromGroup:
        {
            emit this->clearItms();
            QJsonDocument itmDoc;
            itmDoc = QJsonDocument::fromJson(obj["itmsArr"].toString().toUtf8());
            qDebug() << itmDoc.toJson(QJsonDocument::Compact);
            QJsonArray itmArr = itmDoc.array();
            for (int i = 0; i < itmArr.size(); i++){
                emit this->onNewItem(itmArr.at(i).toObject());
            }
            emit this->itemsToList();
            break;
        }
        case getItemCharValues:
        {
            if(obj["type"].toInt() == valuesToShow){
                QStringList s1, s2, s3;
                QJsonObject valObj;
                //emit this->clearItms();
                QJsonDocument itmDoc;
                itmDoc = QJsonDocument::fromJson(obj["itmsArr"].toString().toUtf8());
                QJsonArray itmArr = itmDoc.array();
                for (int i = 0; i < itmArr.count(); i++){
                    valObj = itmArr.at(i).toObject();
                    s1.append(valObj["charName"].toString());
                    s2.append(valObj["charValue"].toString());
                    s3.append(valObj["charUnits"].toString());
                }
                emit this->sendItemValuesToShow(&s1,&s2,&s3);
            }else{
                //TODO
                //qDebug() << msg;
                QList<itemChars> ql;

                QJsonObject valObj;
                //emit this->clearItms();
                QJsonDocument itmDoc;
                itmDoc = QJsonDocument::fromJson(obj["itmsArr"].toString().toUtf8());
                QJsonArray itmArr = itmDoc.array();
                for (int i = 0; i < itmArr.count(); i++){
                    itemChars chr;
                    valObj = itmArr.at(i).toObject();
                    chr.charname = valObj["charName"].toString();
                    chr.charValue = valObj["charValue"].toString();
                    chr.charUnits = valObj["charUnits"].toString();
                    chr.charId = valObj["charId"].toInt();
                    ql.append(chr);
                }
                emit this->sendItemValuesToEdit(&ql, &itmArr);
            }
            break;
        }
        case placeOrd:
        {
            emit this->orderPlacedSig(obj["orderId"].toInt());
            break;
        }
        case getPermissions:
        {
            qDebug() << "obtained permissions " << obj["permissions"].toString();
            emit this->obtaintedPermsSig(obj["permissions"].toString());
            break;
        }
        case getCharNames:
        {
            QList<chars> *ql = new QList<chars>();

            QJsonObject valObj;
            QJsonDocument itmDoc;
            itmDoc = QJsonDocument::fromJson(obj["chars"].toString().toUtf8());
            QJsonArray itmArr = itmDoc.array();
            for (int i = 0; i < itmArr.count(); i++){
                chars chr;
                valObj = itmArr.at(i).toObject();
                chr.charname = valObj["charName"].toString();
                chr.charId = valObj["charId"].toInt();
                ql->append(chr);
            }
            emit this->onCharNames(ql);
            break;
        }
        case successDelItem:
        {
            emit this->succDelItem();
            break;
        }
        case reqUserList:
        {
            QJsonDocument usDoc;
            QJsonArray userArr;
            usDoc = QJsonDocument::fromJson(obj["users"].toString().toUtf8());
            userArr = usDoc.array();
            emit this->onUserList(&userArr);
            break;
        }
        case succUserMod:
        {
            emit this->onSuccUserMod();
            break;
        }
        case reqOrderList:
        {
            QJsonDocument ordDoc;
            QJsonArray ordArr;
            ordDoc = QJsonDocument::fromJson(obj["orders"].toString().toUtf8());
            ordArr = ordDoc.array();
            emit this->onOrderList(&ordArr);
        }
        case getCharsWithTypes:
        {
            QJsonDocument odcc;
            QJsonArray arrr;
            odcc = QJsonDocument::fromJson(obj["list"].toString().toUtf8());
            arrr = odcc.array();

            emit this->GodOfCharsAppears(&arrr);
            break;
        }
        case getCharLinks:
        {
            QJsonDocument odcc;
            QJsonArray arrr;
            odcc = QJsonDocument::fromJson(obj["list"].toString().toUtf8());
            arrr = odcc.array();

            emit this->LinksKing(&arrr);
            break;
        }
        default:
            break;
        }
    }
}
Esempio n. 28
0
File: dh.c Progetto: 119120119/node
int MAIN(int argc, char **argv)
{
    DH *dh = NULL;
    int i, badops = 0, text = 0;
    BIO *in = NULL, *out = NULL;
    int informat, outformat, check = 0, noout = 0, C = 0, ret = 1;
    char *infile, *outfile, *prog;
# ifndef OPENSSL_NO_ENGINE
    char *engine;
# endif

    apps_startup();

    if (bio_err == NULL)
        if ((bio_err = BIO_new(BIO_s_file())) != NULL)
            BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);

    if (!load_config(bio_err, NULL))
        goto end;

# ifndef OPENSSL_NO_ENGINE
    engine = NULL;
# endif
    infile = NULL;
    outfile = NULL;
    informat = FORMAT_PEM;
    outformat = FORMAT_PEM;

    prog = argv[0];
    argc--;
    argv++;
    while (argc >= 1) {
        if (strcmp(*argv, "-inform") == 0) {
            if (--argc < 1)
                goto bad;
            informat = str2fmt(*(++argv));
        } else if (strcmp(*argv, "-outform") == 0) {
            if (--argc < 1)
                goto bad;
            outformat = str2fmt(*(++argv));
        } else if (strcmp(*argv, "-in") == 0) {
            if (--argc < 1)
                goto bad;
            infile = *(++argv);
        } else if (strcmp(*argv, "-out") == 0) {
            if (--argc < 1)
                goto bad;
            outfile = *(++argv);
        }
# ifndef OPENSSL_NO_ENGINE
        else if (strcmp(*argv, "-engine") == 0) {
            if (--argc < 1)
                goto bad;
            engine = *(++argv);
        }
# endif
        else if (strcmp(*argv, "-check") == 0)
            check = 1;
        else if (strcmp(*argv, "-text") == 0)
            text = 1;
        else if (strcmp(*argv, "-C") == 0)
            C = 1;
        else if (strcmp(*argv, "-noout") == 0)
            noout = 1;
        else {
            BIO_printf(bio_err, "unknown option %s\n", *argv);
            badops = 1;
            break;
        }
        argc--;
        argv++;
    }

    if (badops) {
 bad:
        BIO_printf(bio_err, "%s [options] <infile >outfile\n", prog);
        BIO_printf(bio_err, "where options are\n");
        BIO_printf(bio_err, " -inform arg   input format - one of DER PEM\n");
        BIO_printf(bio_err,
                   " -outform arg  output format - one of DER PEM\n");
        BIO_printf(bio_err, " -in arg       input file\n");
        BIO_printf(bio_err, " -out arg      output file\n");
        BIO_printf(bio_err, " -check        check the DH parameters\n");
        BIO_printf(bio_err,
                   " -text         print a text form of the DH parameters\n");
        BIO_printf(bio_err, " -C            Output C code\n");
        BIO_printf(bio_err, " -noout        no output\n");
# ifndef OPENSSL_NO_ENGINE
        BIO_printf(bio_err,
                   " -engine e     use engine e, possibly a hardware device.\n");
# endif
        goto end;
    }

    ERR_load_crypto_strings();

# ifndef OPENSSL_NO_ENGINE
    setup_engine(bio_err, engine, 0);
# endif

    in = BIO_new(BIO_s_file());
    out = BIO_new(BIO_s_file());
    if ((in == NULL) || (out == NULL)) {
        ERR_print_errors(bio_err);
        goto end;
    }

    if (infile == NULL)
        BIO_set_fp(in, stdin, BIO_NOCLOSE);
    else {
        if (BIO_read_filename(in, infile) <= 0) {
            perror(infile);
            goto end;
        }
    }
    if (outfile == NULL) {
        BIO_set_fp(out, stdout, BIO_NOCLOSE);
# ifdef OPENSSL_SYS_VMS
        {
            BIO *tmpbio = BIO_new(BIO_f_linebuffer());
            out = BIO_push(tmpbio, out);
        }
# endif
    } else {
        if (BIO_write_filename(out, outfile) <= 0) {
            perror(outfile);
            goto end;
        }
    }

    if (informat == FORMAT_ASN1)
        dh = d2i_DHparams_bio(in, NULL);
    else if (informat == FORMAT_PEM)
        dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
    else {
        BIO_printf(bio_err, "bad input format specified\n");
        goto end;
    }
    if (dh == NULL) {
        BIO_printf(bio_err, "unable to load DH parameters\n");
        ERR_print_errors(bio_err);
        goto end;
    }

    if (text) {
        DHparams_print(out, dh);
# ifdef undef
        printf("p=");
        BN_print(stdout, dh->p);
        printf("\ng=");
        BN_print(stdout, dh->g);
        printf("\n");
        if (dh->length != 0)
            printf("recommended private length=%ld\n", dh->length);
# endif
    }

    if (check) {
        if (!DH_check(dh, &i)) {
            ERR_print_errors(bio_err);
            goto end;
        }
        if (i & DH_CHECK_P_NOT_PRIME)
            printf("p value is not prime\n");
        if (i & DH_CHECK_P_NOT_SAFE_PRIME)
            printf("p value is not a safe prime\n");
        if (i & DH_UNABLE_TO_CHECK_GENERATOR)
            printf("unable to check the generator value\n");
        if (i & DH_NOT_SUITABLE_GENERATOR)
            printf("the g value is not a generator\n");
        if (i == 0)
            printf("DH parameters appear to be ok.\n");
    }
    if (C) {
        unsigned char *data;
        int len, l, bits;

        len = BN_num_bytes(dh->p);
        bits = BN_num_bits(dh->p);
        data = (unsigned char *)OPENSSL_malloc(len);
        if (data == NULL) {
            perror("OPENSSL_malloc");
            goto end;
        }
        l = BN_bn2bin(dh->p, data);
        printf("static unsigned char dh%d_p[]={", bits);
        for (i = 0; i < l; i++) {
            if ((i % 12) == 0)
                printf("\n\t");
            printf("0x%02X,", data[i]);
        }
        printf("\n\t};\n");

        l = BN_bn2bin(dh->g, data);
        printf("static unsigned char dh%d_g[]={", bits);
        for (i = 0; i < l; i++) {
            if ((i % 12) == 0)
                printf("\n\t");
            printf("0x%02X,", data[i]);
        }
        printf("\n\t};\n\n");

        printf("DH *get_dh%d()\n\t{\n", bits);
        printf("\tDH *dh;\n\n");
        printf("\tif ((dh=DH_new()) == NULL) return(NULL);\n");
        printf("\tdh->p=BN_bin2bn(dh%d_p,sizeof(dh%d_p),NULL);\n",
               bits, bits);
        printf("\tdh->g=BN_bin2bn(dh%d_g,sizeof(dh%d_g),NULL);\n",
               bits, bits);
        printf("\tif ((dh->p == NULL) || (dh->g == NULL))\n");
        printf("\t\treturn(NULL);\n");
        printf("\treturn(dh);\n\t}\n");
        OPENSSL_free(data);
    }

    if (!noout) {
        if (outformat == FORMAT_ASN1)
            i = i2d_DHparams_bio(out, dh);
        else if (outformat == FORMAT_PEM)
            i = PEM_write_bio_DHparams(out, dh);
        else {
            BIO_printf(bio_err, "bad output format specified for outfile\n");
            goto end;
        }
        if (!i) {
            BIO_printf(bio_err, "unable to write DH parameters\n");
            ERR_print_errors(bio_err);
            goto end;
        }
    }
    ret = 0;
 end:
    if (in != NULL)
        BIO_free(in);
    if (out != NULL)
        BIO_free_all(out);
    if (dh != NULL)
        DH_free(dh);
    apps_shutdown();
    OPENSSL_EXIT(ret);
}
Esempio n. 29
0
static Ecore_Con_Ssl_Error
_ecore_con_ssl_server_prepare_openssl(Ecore_Con_Server *svr,
                                      int               ssl_type)
{
   long options;
   int dh = 0;

   if (ssl_type & ECORE_CON_USE_SSL2)
     return ECORE_CON_SSL_ERROR_SSL2_NOT_SUPPORTED;

   switch (ssl_type)
     {
      case ECORE_CON_USE_SSL3:
      case ECORE_CON_USE_SSL3 | ECORE_CON_LOAD_CERT:
        if (!svr->created)
          SSL_ERROR_CHECK_GOTO_ERROR(!(svr->ssl_ctx = SSL_CTX_new(SSLv3_client_method())));
        else
          SSL_ERROR_CHECK_GOTO_ERROR(!(svr->ssl_ctx = SSL_CTX_new(SSLv3_server_method())));
        break;

      case ECORE_CON_USE_TLS:
      case ECORE_CON_USE_TLS | ECORE_CON_LOAD_CERT:
        if (!svr->created)
          SSL_ERROR_CHECK_GOTO_ERROR(!(svr->ssl_ctx = SSL_CTX_new(TLSv1_client_method())));
        else
          SSL_ERROR_CHECK_GOTO_ERROR(!(svr->ssl_ctx = SSL_CTX_new(TLSv1_server_method())));
        break;

      case ECORE_CON_USE_MIXED:
      case ECORE_CON_USE_MIXED | ECORE_CON_LOAD_CERT:
        if (!svr->created)
          SSL_ERROR_CHECK_GOTO_ERROR(!(svr->ssl_ctx = SSL_CTX_new(SSLv23_client_method())));
        else
          SSL_ERROR_CHECK_GOTO_ERROR(!(svr->ssl_ctx = SSL_CTX_new(SSLv23_server_method())));
        options = SSL_CTX_get_options(svr->ssl_ctx);
        SSL_CTX_set_options(svr->ssl_ctx, options | SSL_OP_NO_SSLv2 | SSL_OP_SINGLE_DH_USE);
        break;

      default:
        return ECORE_CON_SSL_ERROR_NONE;
     }

   if ((!svr->use_cert) && svr->created)
     {
        DH *dh_params;
        INF("Generating DH params");
        SSL_ERROR_CHECK_GOTO_ERROR(!(dh_params = DH_new()));
        SSL_ERROR_CHECK_GOTO_ERROR(!DH_generate_parameters_ex(dh_params, 1024, DH_GENERATOR_5, NULL));
        SSL_ERROR_CHECK_GOTO_ERROR(!DH_check(dh_params, &dh));
        SSL_ERROR_CHECK_GOTO_ERROR((dh & DH_CHECK_P_NOT_PRIME) || (dh & DH_CHECK_P_NOT_SAFE_PRIME));
        SSL_ERROR_CHECK_GOTO_ERROR(!DH_generate_key(dh_params));
        SSL_ERROR_CHECK_GOTO_ERROR(!SSL_CTX_set_tmp_dh(svr->ssl_ctx, dh_params));
        DH_free(dh_params);
        INF("DH params successfully generated and applied!");
        SSL_ERROR_CHECK_GOTO_ERROR(!SSL_CTX_set_cipher_list(svr->ssl_ctx, "aNULL:!eNULL:!LOW:!EXPORT:@STRENGTH"));
     }
   else if (!svr->use_cert)
     SSL_ERROR_CHECK_GOTO_ERROR(!SSL_CTX_set_cipher_list(svr->ssl_ctx, "aNULL:!eNULL:!LOW:!EXPORT:!ECDH:RSA:AES:!PSK:@STRENGTH"));

   return ECORE_CON_SSL_ERROR_NONE;

error:
   if (dh)
     {
        if (dh & DH_CHECK_P_NOT_PRIME)
          ERR("openssl error: dh_params could not generate a prime!");
        else
          ERR("openssl error: dh_params could not generate a safe prime!");
     }
   else
     _openssl_print_errors();
   _ecore_con_ssl_server_shutdown_openssl(svr);
   return ECORE_CON_SSL_ERROR_SERVER_INIT_FAILED;
}
Esempio n. 30
0
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++)
		{
		snprintf(buf, sizeof(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++)
		{
		snprintf(buf, sizeof(buf), "%02X",bbuf[i]);
		BIO_puts(out,buf);
		}
	BIO_puts(out,"\n");
	if ((aout < 4) || (bout != aout) || (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);
	}