예제 #1
0
/**
 * \brief Test for a pair of moduluses having a prime factor in common.
 *
 */
int test(BIGNUM *n, BIGNUM *m)
{
  BIGNUM *g;
  BN_CTX *ctx;
  int ret = 0;

  if (!BN_cmp(n, m)) return 1;

  g = BN_new();
  ctx = BN_CTX_new();
  BN_gcd(g, n, m, ctx);

  if (!BN_is_one(g)) {
    fprintf(stdout, "%-8s: ", PRIME);
    BN_print_fp(stdout, n);
    fprintf(stdout, "  ");
    BN_print_fp(stdout, m);
    fprintf(stdout, "\n");
    ret = 1;
  }

  BN_CTX_free(ctx);
  BN_free(g);

  return ret;
}
예제 #2
0
void dump_dsa_sig(const char *message, DSA_SIG *sig)
	{
	fprintf(stderr,"%s\nR=",message);
	BN_print_fp(stderr,sig->r);
	fprintf(stderr,"\nS=");
	BN_print_fp(stderr,sig->s);
	fprintf(stderr,"\n");
	}
void dump_dsa_sig(const char *message, DSA_SIG *sig)
	{
	TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"%s\nR=",message);
	BN_print_fp(OPENSSL_TYPE__FILE_STDERR,sig->r);
	TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"\nS=");
	BN_print_fp(OPENSSL_TYPE__FILE_STDERR,sig->s);
	TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"\n");
	}
예제 #4
0
int test_lshift(BIO *bp,BN_CTX *ctx,BIGNUM *a_)
	{
	BIGNUM *a,*b,*c,*d;
	int i;

	b=BN_new();
	c=BN_new();
	d=BN_new();
	BN_one(c);

	if(a_)
	    a=a_;
	else
	    {
	    a=BN_new();
	    BN_bntest_rand(a,200,0,0); /**/
	    a->neg=rand_neg();
	    }
	for (i=0; i<num0; i++)
		{
		BN_lshift(b,a,i+1);
		BN_add(c,c,c);
		if (bp != NULL)
			{
			if (!results)
				{
				BN_print(bp,a);
				BIO_puts(bp," * ");
				BN_print(bp,c);
				BIO_puts(bp," - ");
				}
			BN_print(bp,b);
			BIO_puts(bp,"\n");
			}
		BN_mul(d,a,c,ctx);
		BN_sub(d,d,b);
		if(!BN_is_zero(d))
		    {
		    fprintf(stderr,"Left shift test failed!\n");
		    fprintf(stderr,"a=");
		    BN_print_fp(stderr,a);
		    fprintf(stderr,"\nb=");
		    BN_print_fp(stderr,b);
		    fprintf(stderr,"\nc=");
		    BN_print_fp(stderr,c);
		    fprintf(stderr,"\nd=");
		    BN_print_fp(stderr,d);
		    fprintf(stderr,"\n");
		    return 0;
		    }
		}
	BN_free(a);
	BN_free(b);
	BN_free(c);
	BN_free(d);
	return(1);
	}
예제 #5
0
void bn8_cmp_bn(bn8 a, uint8_t size, BIGNUM *b, int i)
{
	BIGNUM *aBN = BN_new();
	BN_bin2bn(a, size, aBN);
	if(BN_cmp(aBN, b) != 0) {
		printf("cmp fail %d\n", i);
		BN_print_fp(stdout, aBN); printf("\n");
		BN_print_fp(stdout, b); printf("\n");
	}
}
예제 #6
0
파일: exptest.c 프로젝트: Castaglia/openssl
/*
 * Test that r == 0 in test_exp_mod_zero(). Returns one on success,
 * returns zero and prints debug output otherwise.
 */
static int a_is_zero_mod_one(const char *method, const BIGNUM *r,
                             const BIGNUM *a) {
    if (!BN_is_zero(r)) {
        fprintf(stderr, "%s failed:\n", method);
        fprintf(stderr, "a ** 0 mod 1 = r (should be 0)\n");
        fprintf(stderr, "a = ");
        BN_print_fp(stderr, a);
        fprintf(stderr, "\nr = ");
        BN_print_fp(stderr, r);
        fprintf(stderr, "\n");
        return 0;
    }
    return 1;
}
예제 #7
0
int main(int argc, char **argv)
{
  FILE *fp;
  RSA *rsa;
  int proc, procs;
  int i;
  QA_library_init();

  MPI_Comm_rank(MPI_COMM_WORLD, &proc);
  MPI_Comm_size(MPI_COMM_WORLD, &procs);

  if (argc < 1) return EXIT_FAILURE;
  if (!(fp = fopen(argv[argc-1], "r"))) return EXIT_FAILURE;

  rsa = RSA_new();
  rsa->n = BN_new();
  rsa->e = BN_new();
  for (i=0; next_pkey(rsa, fp); i = (i+1) % procs) {
    if (i != proc) continue;
    if (run_question(question, NULL, rsa) == 1) {
      BN_print_fp(stdout, rsa->n);
      fprintf(stdout, "\t broken\n");
    }
  }

  MPI_Finalize();
  return EXIT_SUCCESS;
}
예제 #8
0
/*
 * pr_fact - print the factors of a number
 *
 * Print the factors of the number, from the lowest to the highest.
 * A factor will be printed multiple times if it divides the value
 * multiple times.
 *
 * Factors are printed with leading tabs.
 */
static void
pr_fact(BIGNUM *val)
{
	const ubig *fact;	/* The factor found. */

	/* Firewall - catch 0 and 1. */
	if (BN_is_zero(val))	/* Historical practice; 0 just exits. */
		exit(0);
	if (BN_is_one(val)) {
		printf("1: 1\n");
		return;
	}

	/* Factor value. */

	if (hflag) {
		fputs("0x", stdout);
		BN_print_fp(stdout, val);
	} else
		BN_print_dec_fp(stdout, val);
	putchar(':');
	for (fact = &prime[0]; !BN_is_one(val); ++fact) {
		/* Look for the smallest factor. */
		do {
			if (BN_mod_word(val, (BN_ULONG)*fact) == 0)
				break;
		} while (++fact <= pr_limit);

		/* Watch for primes larger than the table. */
		if (fact > pr_limit) {
#ifdef HAVE_OPENSSL
			BIGNUM *bnfact;

			bnfact = BN_new();
			BN_set_word(bnfact, *(fact - 1));
			if (!BN_sqr(bnfact, bnfact, ctx))
				errx(1, "error in BN_sqr()");
			if (BN_cmp(bnfact, val) > 0 ||
			    BN_is_prime(val, PRIME_CHECKS,
					NULL, NULL, NULL) == 1)
				pr_print(val);
			else
				pollard_pminus1(val);
#else
			pr_print(val);
#endif
			break;
		}

		/* Divide factor out until none are left. */
		do {
			printf(hflag ? " 0x%lx" : " %lu", *fact);
			BN_div_word(val, (BN_ULONG)*fact);
		} while (BN_mod_word(val, (BN_ULONG)*fact) == 0);

		/* Let the user know we're doing something. */
		fflush(stdout);
	}
	putchar('\n');
}
예제 #9
0
int main(int argc, char* argv[]){
   int res;
   int toGet;

   std::vector<RSA*> allPrivateKeys;
   uint32_t allPublicKeys[100][32];

   if(argc != 3){
      puts("wrong number of args. takes db to open, num to get");
      return 0;
   }

   puts("Starting key printer...");

   toGet = atoi(argv[2]);

   //run through the DB passed in and get all they keys from it
   res = getAllKeys(argv[1], toGet, &allPrivateKeys, allPublicKeys);

   printf("Asked for %d keys, got %d\n", toGet, res);
   printf("after, vector of private keys was %d\n", (int)allPrivateKeys.size());
   printf("after, vector of public keys was %d\n", res);

   //RSA_print_fp(stdout, allPrivateKeys.at(0), 0);

   //0 is MSB for our 1024
   BIGNUM *n = allPrivateKeys.at(0)->n;
   BN_print_fp(stdout, n);
   printf("\ntop = %d and 0th is\t%02x\n", n->dmax, (uint32_t)n->d[0]);
   printf("bottom = \t\t%02x\n", allPublicKeys[0][31]);

   return 0;
}
예제 #10
0
static void showbn(const char *name, const BIGNUM *bn)
	{
	fputs(name, stdout);
	fputs(" = ", stdout);
	BN_print_fp(stdout, bn);
	putc('\n', stdout);
	}
예제 #11
0
/*
 * test_exp_mod_zero tests that x**0 mod 1 == 0. It returns zero on success.
 */
static int test_exp_mod_zero()
{
    BIGNUM a, p, m;
    BIGNUM r;
    BN_CTX *ctx = BN_CTX_new();
    int ret = 1;

    BN_init(&m);
    BN_one(&m);

    BN_init(&a);
    BN_one(&a);

    BN_init(&p);
    BN_zero(&p);

    BN_init(&r);
    BN_mod_exp(&r, &a, &p, &m, ctx);
    BN_CTX_free(ctx);

    if (BN_is_zero(&r))
        ret = 0;
    else {
        printf("1**0 mod 1 = ");
        BN_print_fp(stdout, &r);
        printf(", should be 0\n");
    }

    BN_free(&r);
    BN_free(&a);
    BN_free(&p);
    BN_free(&m);

    return ret;
}
static int pkey_gost01_cp_verify(EVP_PKEY_CTX *ctx, const unsigned char *sig,
	size_t siglen, const unsigned char *tbs, size_t tbs_len)
	{
	int ok = 0;
	EVP_PKEY* pub_key = EVP_PKEY_CTX_get0_pkey(ctx);
	DSA_SIG *s=unpack_cp_signature(sig,siglen);
	if (!s) return 0;
#ifdef DEBUG_SIGN	
	TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"R=");
	BN_print_fp(OPENSSL_TYPE__FILE_STDERR,s->r);
	TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"\nS=");
	BN_print_fp(OPENSSL_TYPE__FILE_STDERR,s->s);
	TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"\n");
#endif	
	if (pub_key) ok = gost2001_do_verify(tbs,tbs_len,s,(EC_KEY*)EVP_PKEY_get0(pub_key));
	DSA_SIG_free(s);
	return ok;
	}
예제 #13
0
static int pkey_gost01_cp_verify(EVP_PKEY_CTX *ctx, const unsigned char *sig,
	size_t siglen, const unsigned char *tbs, size_t tbs_len)
	{
	int ok = 0;
	EVP_PKEY* pub_key = EVP_PKEY_CTX_get0_pkey(ctx);
	DSA_SIG *s=unpack_cp_signature(sig,siglen);
	if (!s) return 0;
#ifdef DEBUG_SIGN	
	fprintf(stderr,"R=");
	BN_print_fp(stderr,s->r);
	fprintf(stderr,"\nS=");
	BN_print_fp(stderr,s->s);
	fprintf(stderr,"\n");
#endif	
	if (pub_key) ok = gost2001_do_verify(tbs,tbs_len,s,EVP_PKEY_get0(pub_key));
	DSA_SIG_free(s);
	return ok;
	}
예제 #14
0
static void
pr_print(BIGNUM *val)
{
    if (hflag) {
        fputs(" 0x", stdout);
        BN_print_fp(stdout, val);
    } else {
        putchar(' ');
        BN_print_dec_fp(stdout, val);
    }
}
예제 #15
0
파일: gost2001.c 프로젝트: 4872866/node
/*
 * Fills EC_KEY structure hidden in the app_data field of DSA structure
 * with parameter information, extracted from parameter array in
 * params.c file.
 *
 * Also fils DSA->q field with copy of EC_GROUP order field to make
 * DSA_size function work
 */
int fill_GOST2001_params(EC_KEY *eckey, int nid)
{
    R3410_2001_params *params = R3410_2001_paramset;
    EC_GROUP *grp = NULL;
    BIGNUM *p = NULL, *q = NULL, *a = NULL, *b = NULL, *x = NULL, *y = NULL;
    EC_POINT *P = NULL;
    BN_CTX *ctx = BN_CTX_new();
    int ok = 0;

    BN_CTX_start(ctx);
    p = BN_CTX_get(ctx);
    a = BN_CTX_get(ctx);
    b = BN_CTX_get(ctx);
    x = BN_CTX_get(ctx);
    y = BN_CTX_get(ctx);
    q = BN_CTX_get(ctx);
    while (params->nid != NID_undef && params->nid != nid)
        params++;
    if (params->nid == NID_undef) {
        GOSTerr(GOST_F_FILL_GOST2001_PARAMS,
                GOST_R_UNSUPPORTED_PARAMETER_SET);
        goto err;
    }
    BN_hex2bn(&p, params->p);
    BN_hex2bn(&a, params->a);
    BN_hex2bn(&b, params->b);

    grp = EC_GROUP_new_curve_GFp(p, a, b, ctx);

    P = EC_POINT_new(grp);

    BN_hex2bn(&x, params->x);
    BN_hex2bn(&y, params->y);
    EC_POINT_set_affine_coordinates_GFp(grp, P, x, y, ctx);
    BN_hex2bn(&q, params->q);
#ifdef DEBUG_KEYS
    fprintf(stderr, "Set params index %d oid %s\nq=",
            (params - R3410_2001_paramset), OBJ_nid2sn(params->nid));
    BN_print_fp(stderr, q);
    fprintf(stderr, "\n");
#endif

    EC_GROUP_set_generator(grp, P, q, NULL);
    EC_GROUP_set_curve_name(grp, params->nid);

    EC_KEY_set_group(eckey, grp);
    ok = 1;
 err:
    EC_POINT_free(P);
    EC_GROUP_free(grp);
    BN_CTX_end(ctx);
    BN_CTX_free(ctx);
    return ok;
}
예제 #16
0
/* test the function of hashpassword */
void test_hash()
{
    const char *pwd1 = "123456";
    const char *pwd2 = "123457";
    BIGNUM *secret = BN_new();
    BN_CTX *ctx = BN_CTX_new();
    BIGNUM *q = BN_new();
    BN_set_word(q, 0xFFFFFF);

    printf("test hash start!\n");

    hashpassword(secret, pwd1, ctx, q);
    BN_print_fp(stdout, secret);
    printf("\n");

    hashpassword(secret, pwd2, ctx, q);
    BN_print_fp(stdout, secret);
    printf("\n");

    printf("test hash end!\n");
}
예제 #17
0
static int
input_kex_dh_gex_group(int type, u_int32_t seq, void *ctxt)
{
	struct ssh *ssh = ctxt;
	struct kex *kex = ssh->kex;
	BIGNUM *p = NULL, *g = NULL;
	int r, bits;

	debug("got SSH2_MSG_KEX_DH_GEX_GROUP");

	if ((p = BN_new()) == NULL ||
	    (g = BN_new()) == NULL) {
		r = SSH_ERR_ALLOC_FAIL;
		goto out;
	}
	if ((r = sshpkt_get_bignum2(ssh, p)) != 0 ||
	    (r = sshpkt_get_bignum2(ssh, g)) != 0 ||
	    (r = sshpkt_get_end(ssh)) != 0)
		goto out;
	if ((bits = BN_num_bits(p)) < 0 ||
	    (u_int)bits < kex->min || (u_int)bits > kex->max) {
		r = SSH_ERR_DH_GEX_OUT_OF_RANGE;
		goto out;
	}
	if ((kex->dh = dh_new_group(g, p)) == NULL) {
		r = SSH_ERR_ALLOC_FAIL;
		goto out;
	}
	p = g = NULL; /* belong to kex->dh now */

	/* generate and send 'e', client DH public key */
	if ((r = dh_gen_key(kex->dh, kex->we_need * 8)) != 0 ||
	    (r = sshpkt_start(ssh, SSH2_MSG_KEX_DH_GEX_INIT)) != 0 ||
	    (r = sshpkt_put_bignum2(ssh, kex->dh->pub_key)) != 0 ||
	    (r = sshpkt_send(ssh)) != 0)
		goto out;
	debug("SSH2_MSG_KEX_DH_GEX_INIT sent");
#ifdef DEBUG_KEXDH
	DHparams_print_fp(stderr, kex->dh);
	fprintf(stderr, "pub= ");
	BN_print_fp(stderr, kex->dh->pub_key);
	fprintf(stderr, "\n");
#endif
	ssh_dispatch_set(ssh, SSH2_MSG_KEX_DH_GEX_GROUP, NULL);
	ssh_dispatch_set(ssh, SSH2_MSG_KEX_DH_GEX_REPLY, &input_kex_dh_gex_reply);
	r = 0;
out:
	if (p)
		BN_clear_free(p);
	if (g)
		BN_clear_free(g);
	return r;
}
예제 #18
0
void print_bn( const char *name, const BIGNUM *bn)
    {
    print_indent();
    printf("%s=",name);
    if(bn)
	{
	BN_print_fp(stdout,bn);
	putchar('\n');
	}
    else
	puts("(unset)");
    }
예제 #19
0
static int check_bn(const char *name, const BIGNUM *bn, const char *hexbn)
{
    BIGNUM *tmp = NULL;
    int rv;
    if (BN_hex2bn(&tmp, hexbn) == 0)
        return 0;
    rv = BN_cmp(bn, tmp);
    if (rv == 0) {
        printf("%s = ", name);
        BN_print_fp(stdout, bn);
        printf("\n");
        BN_free(tmp);
        return 1;
    }
    printf("Unexpected %s value\n", name);
    printf("Expecting: ");
    BN_print_fp(stdout, tmp);
    printf("\nReceived: ");
    BN_print_fp(stdout, bn);
    printf("\n");
    BN_free(tmp);
    return 0;
}
예제 #20
0
int
kexdh_client(struct ssh *ssh)
{
	struct kex *kex = ssh->kex;
	int r;

	/* generate and send 'e', client DH public key */
	switch (kex->kex_type) {
	case KEX_DH_GRP1_SHA1:
		kex->dh = dh_new_group1();
		break;
	case KEX_DH_GRP14_SHA1:
	case KEX_DH_GRP14_SHA256:
		kex->dh = dh_new_group14();
		break;
	case KEX_DH_GRP16_SHA512:
		kex->dh = dh_new_group16();
		break;
	case KEX_DH_GRP18_SHA512:
		kex->dh = dh_new_group18();
		break;
	default:
		r = SSH_ERR_INVALID_ARGUMENT;
		goto out;
	}
	if (kex->dh == NULL) {
		r = SSH_ERR_ALLOC_FAIL;
		goto out;
	}
	debug("sending SSH2_MSG_KEXDH_INIT");
	if ((r = dh_gen_key(kex->dh, kex->we_need * 8)) != 0 ||
	    (r = sshpkt_start(ssh, SSH2_MSG_KEXDH_INIT)) != 0 ||
	    (r = sshpkt_put_bignum2(ssh, kex->dh->pub_key)) != 0 ||
	    (r = sshpkt_send(ssh)) != 0)
		goto out;
#ifdef DEBUG_KEXDH
	DHparams_print_fp(stderr, kex->dh);
	fprintf(stderr, "pub= ");
	BN_print_fp(stderr, kex->dh->pub_key);
	fprintf(stderr, "\n");
#endif
	debug("expecting SSH2_MSG_KEXDH_REPLY");
	ssh_dispatch_set(ssh, SSH2_MSG_KEXDH_REPLY, &input_kex_dh);
	r = 0;
 out:
	return r;
}
예제 #21
0
파일: exptest.c 프로젝트: GH-JY/openssl
/*
 * test_exp_mod_zero tests that x**0 mod 1 == 0. It returns zero on success.
 */
static int test_exp_mod_zero()
{
    BIGNUM *a = NULL, *p = NULL, *m = NULL;
    BIGNUM *r = NULL;
    BN_CTX *ctx = BN_CTX_new();
    int ret = 1;

    m = BN_new();
    if (!m)
        goto err;
    BN_one(m);

    a = BN_new();
    if (!a)
        goto err;
    BN_one(a);

    p = BN_new();
    if (!p)
        goto err;
    BN_zero(p);

    r = BN_new();
    if (!r)
        goto err;
    BN_mod_exp(r, a, p, m, ctx);
    BN_CTX_free(ctx);

    if (BN_is_zero(r))
        ret = 0;
    else {
        printf("1**0 mod 1 = ");
        BN_print_fp(stdout, r);
        printf(", should be 0\n");
    }

 err:
    BN_free(r);
    BN_free(a);
    BN_free(p);
    BN_free(m);

    return ret;
}
예제 #22
0
파일: kexgexc.c 프로젝트: mpitzl/libopenssh
static int
input_kex_dh_gex_reply(int type, u_int32_t seq, struct ssh *ssh)
{
	Kex *kex = ssh->kex;
	BIGNUM *dh_server_pub = NULL, *shared_secret = NULL;
	struct sshkey *server_host_key;
	u_char *kbuf = NULL, *hash, *signature = NULL, *server_host_key_blob = NULL;
	size_t klen = 0, slen, sbloblen, hashlen;
	int kout, r;

	debug("got SSH2_MSG_KEX_DH_GEX_REPLY");
	if (kex->verify_host_key == NULL) {
		r = SSH_ERR_INVALID_ARGUMENT;
		goto out;
	}
	/* key, cert */
	if ((r = sshpkt_get_string(ssh, &server_host_key_blob,
	    &sbloblen)) != 0 ||
	    (r = sshkey_from_blob(server_host_key_blob, sbloblen,
	    &server_host_key)) != 0)
		goto out;
	if (server_host_key->type != kex->hostkey_type) {
		r = SSH_ERR_KEY_TYPE_MISMATCH;
		goto out;
	}
	if (kex->verify_host_key(server_host_key, ssh) == -1) {
		r = SSH_ERR_SIGNATURE_INVALID;
		goto out;
	}
	/* DH parameter f, server public DH key */
	if ((dh_server_pub = BN_new()) == NULL) {
		r = SSH_ERR_ALLOC_FAIL;
		goto out;
	}
	/* signed H */
	if ((r = sshpkt_get_bignum2(ssh, dh_server_pub)) != 0 ||
	    (r = sshpkt_get_string(ssh, &signature, &slen)) != 0 ||
	    (r = sshpkt_get_end(ssh)) != 0)
		goto out;
#ifdef DEBUG_KEXDH
	fprintf(stderr, "dh_server_pub= ");
	BN_print_fp(stderr, dh_server_pub);
	fprintf(stderr, "\n");
	debug("bits %d", BN_num_bits(dh_server_pub));
#endif
	if (!dh_pub_is_valid(kex->dh, dh_server_pub)) {
		sshpkt_disconnect(ssh, "bad server public DH value");
		r = SSH_ERR_MESSAGE_INCOMPLETE;
		goto out;
	}

	klen = DH_size(kex->dh);
	if ((kbuf = malloc(klen)) == NULL ||
	    (shared_secret = BN_new()) == NULL) {
		r = SSH_ERR_ALLOC_FAIL;
		goto out;
	}
	if ((kout = DH_compute_key(kbuf, dh_server_pub, kex->dh)) < 0 ||
	    BN_bin2bn(kbuf, kout, shared_secret) == NULL) {
		r = SSH_ERR_LIBCRYPTO_ERROR;
		goto out;
	}
#ifdef DEBUG_KEXDH
	dump_digest("shared secret", kbuf, kout);
#endif
	if (ssh->compat & SSH_OLD_DHGEX)
		kex->min = kex->max = -1;

	/* calc and verify H */
	if ((r = kexgex_hash(
	    kex->evp_md,
	    kex->client_version_string,
	    kex->server_version_string,
	    sshbuf_ptr(kex->my), sshbuf_len(kex->my),
	    sshbuf_ptr(kex->peer), sshbuf_len(kex->peer),
	    server_host_key_blob, sbloblen,
	    kex->min, kex->nbits, kex->max,
	    kex->dh->p, kex->dh->g,
	    kex->dh->pub_key,
	    dh_server_pub,
	    shared_secret,
	    &hash, &hashlen)) != 0)
		goto out;

	if ((r = sshkey_verify(server_host_key, signature, slen, hash,
	    hashlen, ssh->compat)) != 0)
		goto out;

	/* save session id */
	if (kex->session_id == NULL) {
		kex->session_id_len = hashlen;
		kex->session_id = malloc(kex->session_id_len);
		if (kex->session_id == NULL) {
			r = SSH_ERR_ALLOC_FAIL;
			goto out;
		}
		memcpy(kex->session_id, hash, kex->session_id_len);
	}

	if ((r = kex_derive_keys(ssh, hash, hashlen, shared_secret)) == 0)
		r = kex_send_newkeys(ssh);
 out:
	DH_free(kex->dh);
	kex->dh = NULL;
	if (server_host_key_blob)
		free(server_host_key_blob);
	if (server_host_key)
		sshkey_free(server_host_key);
	if (dh_server_pub)
		BN_clear_free(dh_server_pub);
	if (kbuf) {
		bzero(kbuf, klen);
		free(kbuf);
	}
	if (shared_secret)
		BN_clear_free(shared_secret);
	if (signature)
		free(signature);
	return r;
}
예제 #23
0
파일: kexdhc.c 프로젝트: lbdroid/openssh
void
kexdh_client(Kex *kex)
{
	BIGNUM *dh_server_pub = NULL, *shared_secret = NULL;
	DH *dh;
	Key *server_host_key;
	u_char *server_host_key_blob = NULL, *signature = NULL;
	u_char *kbuf, *hash;
	u_int klen, slen, sbloblen, hashlen;
	int kout;

	/* generate and send 'e', client DH public key */
	switch (kex->kex_type) {
	case KEX_DH_GRP1_SHA1:
		dh = dh_new_group1();
		break;
	case KEX_DH_GRP14_SHA1:
		dh = dh_new_group14();
		break;
	default:
		fatal("%s: Unexpected KEX type %d", __func__, kex->kex_type);
	}
	dh_gen_key(dh, kex->we_need * 8);
	packet_start(SSH2_MSG_KEXDH_INIT);
	packet_put_bignum2(dh->pub_key);
	packet_send();

	debug("sending SSH2_MSG_KEXDH_INIT");
#ifdef DEBUG_KEXDH
	DHparams_print_fp(stderr, dh);
	fprintf(stderr, "pub= ");
	BN_print_fp(stderr, dh->pub_key);
	fprintf(stderr, "\n");
#endif

	debug("expecting SSH2_MSG_KEXDH_REPLY");
	packet_read_expect(SSH2_MSG_KEXDH_REPLY);

	/* key, cert */
	server_host_key_blob = packet_get_string(&sbloblen);
	server_host_key = key_from_blob(server_host_key_blob, sbloblen);
	if (server_host_key == NULL)
		fatal("cannot decode server_host_key_blob");
	if (server_host_key->type != kex->hostkey_type)
		fatal("type mismatch for decoded server_host_key_blob");
	if (kex->verify_host_key == NULL)
		fatal("cannot verify server_host_key");
	if (kex->verify_host_key(server_host_key) == -1)
		fatal("server_host_key verification failed");

	/* DH parameter f, server public DH key */
	if ((dh_server_pub = BN_new()) == NULL)
		fatal("dh_server_pub == NULL");
	packet_get_bignum2(dh_server_pub);

#ifdef DEBUG_KEXDH
	fprintf(stderr, "dh_server_pub= ");
	BN_print_fp(stderr, dh_server_pub);
	fprintf(stderr, "\n");
	debug("bits %d", BN_num_bits(dh_server_pub));
#endif

	/* signed H */
	signature = packet_get_string(&slen);
	packet_check_eom();

	if (!dh_pub_is_valid(dh, dh_server_pub))
		packet_disconnect("bad server public DH value");

	klen = DH_size(dh);
	kbuf = xmalloc(klen);
	if ((kout = DH_compute_key(kbuf, dh_server_pub, dh)) < 0)
		fatal("DH_compute_key: failed");
#ifdef DEBUG_KEXDH
	dump_digest("shared secret", kbuf, kout);
#endif
	if ((shared_secret = BN_new()) == NULL)
		fatal("kexdh_client: BN_new failed");
	if (BN_bin2bn(kbuf, kout, shared_secret) == NULL)
		fatal("kexdh_client: BN_bin2bn failed");
	memset(kbuf, 0, klen);
	free(kbuf);

	/* calc and verify H */
	kex_dh_hash(
	    kex->client_version_string,
	    kex->server_version_string,
	    buffer_ptr(&kex->my), buffer_len(&kex->my),
	    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
	    server_host_key_blob, sbloblen,
	    dh->pub_key,
	    dh_server_pub,
	    shared_secret,
	    &hash, &hashlen
	);
	free(server_host_key_blob);
	BN_clear_free(dh_server_pub);
	DH_free(dh);

	if (key_verify(server_host_key, signature, slen, hash, hashlen) != 1)
		fatal("key_verify failed for server_host_key");
	key_free(server_host_key);
	free(signature);

	/* save session id */
	if (kex->session_id == NULL) {
		kex->session_id_len = hashlen;
		kex->session_id = xmalloc(kex->session_id_len);
		memcpy(kex->session_id, hash, kex->session_id_len);
	}

	kex_derive_keys(kex, hash, hashlen, shared_secret);
	BN_clear_free(shared_secret);
	kex_finish(kex);
}
예제 #24
0
파일: main.c 프로젝트: jamella/matasano
int main(int argc, char *argv[])
{
	// seed RNG (in a shitty way)
	// !!proper seeding needed here!!
	unsigned int rseed = time(NULL);
	void *buf = &rseed;
	RAND_seed(buf, 9);

	/**       Set 6 Challenge 41       **/
	/** RSA unpadded msg oracle attack **/
	rsa_unpadded_msg_oracle_attack_test();

	/**       Set 6 Challenge 42       **/
	/** Bleichenbacher e=3 RSA attack **/
	rsa_simple_pad_test();

	rsa_key_t pik, puk;
	unsigned int sign_len;
	unsigned char *sign;
	unsigned char *sign_hex;

	pik.e = BN_new();
	pik.n = BN_new();
	puk.e = BN_new();
	puk.n = BN_new();

	rsa_generate_keypair(&puk, &pik, 512);

	sign_len = rsa_sign(&sign, "hi mom", 6, &pik);

	hex_encode(&sign_hex, sign, sign_len);

	printf("[s6c2] RSA signature (%d bits): %s\n", sign_len*8, sign_hex);

	if(rsa_sign_verify("hi mom", 6, sign, sign_len, &puk)) {
		printf("[s6c2] RSA signature successfully verified!\n");
	} else {
		printf("[s6c2] RSA signature *NOT* verified!\n");
	}

	free(sign_hex);

	unsigned char *forged_sign = NULL;
	unsigned int forged_sign_len = 0;

	forged_sign_len = rsa_sign_forge(&forged_sign, "hi mom", 6, &puk);

	sign_len = hex_encode(&sign_hex, forged_sign, forged_sign_len);

	printf("[s6c2] Forged RSA signature (%d bits): %s\n", sign_len*8, sign_hex);

	if(rsa_sign_verify("hi mom", 6, forged_sign, forged_sign_len, &puk)) {
		printf("[s6c2] Forged RSA signature successfully verified!\n");
	} else {
		printf("[s6c2] Forged RSA signature *NOT* verified!\n");
	}

	free(forged_sign);
	free(sign_hex);
	free(sign);

	/**      Set 6 Challenge 43     **/
	/** DSA key recovery from nonce **/
	unsigned char sha1sum[41];
	unsigned char *test_msg = "For those that envy a MC it can be hazardous to your health\n\
So be friendly, a matter of life and death, just like a etch-a-sketch\n";

	hash_sha1(sha1sum, test_msg, strlen(test_msg));

	printf("[s6c3] sha1() = %s\n", sha1sum);

	dsa_key_t dsa_puk;
	dsa_key_t dsa_pik;
	dsa_signature_t dsa_sign;

	dsa_puk.g = BN_new();
	dsa_puk.p = BN_new();
	dsa_puk.q = BN_new();
	dsa_puk.xy = BN_new();

	dsa_pik.g = BN_new();
	dsa_pik.p = BN_new();
	dsa_pik.q = BN_new();
	dsa_pik.xy = BN_new();

	dsa_sign.r = BN_new();
	dsa_sign.s = BN_new();

	dsa_generate_keypair(&dsa_puk, &dsa_pik, 256);
	dsa_sha1_sign(&dsa_sign, test_msg, strlen(test_msg), &dsa_pik);
	if(dsa_sha1_sign_verify(test_msg, strlen(test_msg), &dsa_sign, &dsa_puk)) {
		printf("[s6c3] DSA-SHA1 signature successfully verified!\n");
	} else {
		printf("[s6c3] DSA-SHA1 signature *NOT* verified!\n");
	}

	BN_hex2bn(&dsa_puk.xy, "84ad4719d044495496a3201c8ff484feb45b962e7302e56a392aee4\
bab3e4bdebf2955b4736012f21a08084056b19bcd7fee56048e004\
e44984e2f411788efdc837a0d2e5abb7b555039fd243ac01f0fb2ed\
1dec568280ce678e931868d23eb095fde9d3779191b8c0299d6e07b\
bb283e6633451e535c45513b2d33c99ea17");
	BN_dec2bn(&dsa_sign.r, "548099063082341131477253921760299949438196259240");
	BN_dec2bn(&dsa_sign.s, "857042759984254168557880549501802188789837994940");

//	BN_print_fp(stdout, dsa_sign.s);
//	printf("\n");

//	BN_dec2bn(&dsa_puk.g, "60");
//	BN_dec2bn(&dsa_puk.p, "283");
//	BN_dec2bn(&dsa_puk.q, "47");
//	BN_dec2bn(&dsa_puk.xy, "158");
//
//	BN_dec2bn(&dsa_sign.r, "19");
//	BN_dec2bn(&dsa_sign.s, "30");

	if(dsa_calc_private_key_from_k_range(&dsa_pik, &dsa_sign, 65536, test_msg, strlen(test_msg), &dsa_puk)) {
		unsigned char *dsa_pik_hex = BN_bn2hex(dsa_pik.xy);
		unsigned int i;

		// convert to lower case
		for(i=0; i<strlen(dsa_pik_hex); i++) {
			dsa_pik_hex[i] = tolower(dsa_pik_hex[i]);
		}
		printf("[s6c3] DSA private key: %s\n", dsa_pik_hex);

		unsigned char dsa_pik_hex_sha1[SHA_DIGEST_LENGTH*2+1];
		hash_sha1(dsa_pik_hex_sha1, dsa_pik_hex, strlen(dsa_pik_hex));
		printf("[s6c3] SHA1(private key): %s\n", dsa_pik_hex_sha1);

		OPENSSL_free(dsa_pik_hex);
	} else {
		printf("[s6c3] DSA private key *NOT* found!\n");
	}

	dsa_signature_free(&dsa_sign);

	/**   Set 6 Challenge 44    **/
	/** DSA nonce recovery from **/
	/**     repeated nonce     **/
	dsa_signature_t sigs[11];
	// input messages
	unsigned char *msgs[] = {
			"Listen for me, you better listen for me now. ",
			"Listen for me, you better listen for me now. ",
			"When me rockin' the microphone me rock on steady, ",
			"Yes a Daddy me Snow me are de article dan. ",
			"But in a in an' a out de dance em ",
			"Aye say where you come from a, ",
			"People em say ya come from Jamaica, ",
			"But me born an' raised in the ghetto that I want yas to know, ",
			"Pure black people mon is all I mon know. ",
			"Yeah me shoes a an tear up an' now me toes is a show a ",
			"Where me a born in are de one Toronto, so "
	};
	// signature r values for msgs
	unsigned char *sig_r[] = {
			"1105520928110492191417703162650245113664610474875",
			"51241962016175933742870323080382366896234169532",
			"228998983350752111397582948403934722619745721541",
			"1099349585689717635654222811555852075108857446485",
			"425320991325990345751346113277224109611205133736",
			"486260321619055468276539425880393574698069264007",
			"537050122560927032962561247064393639163940220795",
			"826843595826780327326695197394862356805575316699",
			"1105520928110492191417703162650245113664610474875",
			"51241962016175933742870323080382366896234169532",
			"228998983350752111397582948403934722619745721541"
	};
	// signature s values for msgs
	unsigned char *sig_s[] = {
			"1267396447369736888040262262183731677867615804316",
			"29097472083055673620219739525237952924429516683",
			"277954141006005142760672187124679727147013405915",
			"1013310051748123261520038320957902085950122277350",
			"203941148183364719753516612269608665183595279549",
			"502033987625712840101435170279955665681605114553",
			"1133410958677785175751131958546453870649059955513",
			"559339368782867010304266546527989050544914568162",
			"1021643638653719618255840562522049391608552714967",
			"506591325247687166499867321330657300306462367256",
			"458429062067186207052865988429747640462282138703"
	};

	unsigned int i, j;
	int identical_nonce[11];
	BIGNUM *k = BN_new();

	// init
	BN_hex2bn(&dsa_puk.xy, "2d026f4bf30195ede3a088da85e398ef869611d0f68f07\
13d51c9c1a3a26c95105d915e2d8cdf26d056b86b8a7b8\
5519b1c23cc3ecdc6062650462e3063bd179c2a6581519\
f674a61f1d89a1fff27171ebc1b93d4dc57bceb7ae2430\
f98a6a4d83d8279ee65d71c1203d2c96d65ebbf7cce9d3\
2971c3de5084cce04a2e147821");

	for(i=0; i<11; i++) {
		sigs[i].r = BN_new();
		sigs[i].s = BN_new();
		BN_dec2bn(&(sigs[i].r), sig_r[i]);
		BN_dec2bn(&(sigs[i].s), sig_s[i]);
		identical_nonce[i] = -1;
	}

	// build array containing info about reused nonces
	for(i=0; i<10; i++) {
		for(j=i+1; j<11; j++) {
			if(!dsa_sign_nonce_cmp(&sigs[i], &sigs[j])) {
				identical_nonce[i] = j;
				break;
			}
		}
//		printf("[s6c4] id[%02d] = %02d\n", i, identical_nonce[i]);
	}

	int success = 0;

	for(i=0; i<11; i++) {
		j = identical_nonce[i];
		if(j >= 0) {
			if((success=dsa_calc_private_key_from_reused_k(&dsa_pik, k, &sigs[i], &sigs[j], msgs[i], strlen(msgs[i]), msgs[j], strlen(msgs[j]), &dsa_puk))) {
				break;
			}
		}
	}

	if(success) {
		unsigned char *dsa_pik_hex = BN_bn2hex(dsa_pik.xy);

		// convert to lower case
		for(i=0; i<strlen(dsa_pik_hex); i++) {
			dsa_pik_hex[i] = tolower(dsa_pik_hex[i]);
		}

		printf("[s6c4] k = ");
		BN_print_fp(stdout, k);
		printf("\n[s6c4] DSA private key: %s\n", dsa_pik_hex);

		unsigned char dsa_pik_hex_sha1[SHA_DIGEST_LENGTH*2+1];
		hash_sha1(dsa_pik_hex_sha1, dsa_pik_hex, strlen(dsa_pik_hex));
		printf("[s6c4] SHA1(private key): %s\n", dsa_pik_hex_sha1);

		OPENSSL_free(dsa_pik_hex);
	} else {
		printf("[s6c3] DSA private key *NOT* found!\n");
	}

	// free
	for(i=0; i<11; i++) {
		dsa_signature_free(&sigs[i]);
	}

	BN_free(k);

	dsa_key_free(&dsa_puk);
	dsa_key_free(&dsa_pik);

	return 0;
}
예제 #25
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;
}
예제 #26
0
파일: kexgexs.c 프로젝트: ChaosJohn/freebsd
void
kexgex_server(Kex *kex)
{
	BIGNUM *shared_secret = NULL, *dh_client_pub = NULL;
	Key *server_host_public, *server_host_private;
	DH *dh;
	u_char *kbuf, *hash, *signature = NULL, *server_host_key_blob = NULL;
	u_int sbloblen, klen, slen, hashlen;
	int omin = -1, min = -1, omax = -1, max = -1, onbits = -1, nbits = -1;
	int type, kout;

	if (kex->load_host_public_key == NULL ||
	    kex->load_host_private_key == NULL)
		fatal("Cannot load hostkey");
	server_host_public = kex->load_host_public_key(kex->hostkey_type);
	if (server_host_public == NULL)
		fatal("Unsupported hostkey type %d", kex->hostkey_type);
	server_host_private = kex->load_host_private_key(kex->hostkey_type);

	type = packet_read();
	switch (type) {
	case SSH2_MSG_KEX_DH_GEX_REQUEST:
		debug("SSH2_MSG_KEX_DH_GEX_REQUEST received");
		omin = min = packet_get_int();
		onbits = nbits = packet_get_int();
		omax = max = packet_get_int();
		min = MAX(DH_GRP_MIN, min);
		max = MIN(DH_GRP_MAX, max);
		nbits = MAX(DH_GRP_MIN, nbits);
		nbits = MIN(DH_GRP_MAX, nbits);
		break;
	case SSH2_MSG_KEX_DH_GEX_REQUEST_OLD:
		debug("SSH2_MSG_KEX_DH_GEX_REQUEST_OLD received");
		onbits = nbits = packet_get_int();
		/* unused for old GEX */
		omin = min = DH_GRP_MIN;
		omax = max = DH_GRP_MAX;
		break;
	default:
		fatal("protocol error during kex, no DH_GEX_REQUEST: %d", type);
	}
	packet_check_eom();

	if (omax < omin || onbits < omin || omax < onbits)
		fatal("DH_GEX_REQUEST, bad parameters: %d !< %d !< %d",
		    omin, onbits, omax);

	/* Contact privileged parent */
	dh = PRIVSEP(choose_dh(min, nbits, max));
	if (dh == NULL)
		packet_disconnect("Protocol error: no matching DH grp found");

	debug("SSH2_MSG_KEX_DH_GEX_GROUP sent");
	packet_start(SSH2_MSG_KEX_DH_GEX_GROUP);
	packet_put_bignum2(dh->p);
	packet_put_bignum2(dh->g);
	packet_send();

	/* flush */
	packet_write_wait();

	/* Compute our exchange value in parallel with the client */
	dh_gen_key(dh, kex->we_need * 8);

	debug("expecting SSH2_MSG_KEX_DH_GEX_INIT");
	packet_read_expect(SSH2_MSG_KEX_DH_GEX_INIT);

	/* key, cert */
	if ((dh_client_pub = BN_new()) == NULL)
		fatal("dh_client_pub == NULL");
	packet_get_bignum2(dh_client_pub);
	packet_check_eom();

#ifdef DEBUG_KEXDH
	fprintf(stderr, "dh_client_pub= ");
	BN_print_fp(stderr, dh_client_pub);
	fprintf(stderr, "\n");
	debug("bits %d", BN_num_bits(dh_client_pub));
#endif

#ifdef DEBUG_KEXDH
	DHparams_print_fp(stderr, dh);
	fprintf(stderr, "pub= ");
	BN_print_fp(stderr, dh->pub_key);
	fprintf(stderr, "\n");
#endif
	if (!dh_pub_is_valid(dh, dh_client_pub))
		packet_disconnect("bad client public DH value");

	klen = DH_size(dh);
	kbuf = xmalloc(klen);
	if ((kout = DH_compute_key(kbuf, dh_client_pub, dh)) < 0)
		fatal("DH_compute_key: failed");
#ifdef DEBUG_KEXDH
	dump_digest("shared secret", kbuf, kout);
#endif
	if ((shared_secret = BN_new()) == NULL)
		fatal("kexgex_server: BN_new failed");
	if (BN_bin2bn(kbuf, kout, shared_secret) == NULL)
		fatal("kexgex_server: BN_bin2bn failed");
	memset(kbuf, 0, klen);
	free(kbuf);

	key_to_blob(server_host_public, &server_host_key_blob, &sbloblen);

	if (type == SSH2_MSG_KEX_DH_GEX_REQUEST_OLD)
		omin = min = omax = max = -1;

	/* calc H */
	kexgex_hash(
	    kex->evp_md,
	    kex->client_version_string,
	    kex->server_version_string,
	    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
	    buffer_ptr(&kex->my), buffer_len(&kex->my),
	    server_host_key_blob, sbloblen,
	    omin, onbits, omax,
	    dh->p, dh->g,
	    dh_client_pub,
	    dh->pub_key,
	    shared_secret,
	    &hash, &hashlen
	);
	BN_clear_free(dh_client_pub);

	/* save session id := H */
	if (kex->session_id == NULL) {
		kex->session_id_len = hashlen;
		kex->session_id = xmalloc(kex->session_id_len);
		memcpy(kex->session_id, hash, kex->session_id_len);
	}

	/* sign H */
	kex->sign(server_host_private, server_host_public, &signature, &slen,
	    hash, hashlen);

	/* destroy_sensitive_data(); */

	/* send server hostkey, DH pubkey 'f' and singed H */
	debug("SSH2_MSG_KEX_DH_GEX_REPLY sent");
	packet_start(SSH2_MSG_KEX_DH_GEX_REPLY);
	packet_put_string(server_host_key_blob, sbloblen);
	packet_put_bignum2(dh->pub_key);	/* f */
	packet_put_string(signature, slen);
	packet_send();

	free(signature);
	free(server_host_key_blob);
	/* have keys, free DH */
	DH_free(dh);

	kex_derive_keys(kex, hash, hashlen, shared_secret);
	BN_clear_free(shared_secret);

	kex_finish(kex);
}
예제 #27
0
int main(int argc, char **argv) {
  BIGNUM *p, *q, *pmq, *n, *e, *d, *psi, *pm1, *qm1;
  int key_len;

  BN_CTX *ctx = BN_CTX_new();

  p = BN_new();
  q = BN_new();
  pmq =  BN_new();

  n = BN_new();
  e = BN_new();
  d = BN_new();
  psi = BN_new();
  pm1 = BN_new();
  qm1 = BN_new();

  if (argc != 2) {
    printf("./keygen [keylen]\n");
    return 1;
  }

  key_len = atoi(argv[1]) / 8;
  int length = atoi(argv[1]);
  
  printf("Key length: %d bits\n", length);
   uint8_t num[8], num2[8];
   primeNum(num, length);
   p = BN_bin2bn((const unsigned char *) num,length/8 , NULL);
   printf("p = %s !\n", BN_bn2dec(p)) ;
   printf("\nGenerated p...\n");

   primeNum(num2, length);
   q= BN_bin2bn((const unsigned char *) num2, length/8 , NULL);
   printf("q = %s !\n", BN_bn2dec(q)) ;
   printf("\n Generated q...\n");

  BN_mul(n, p, q, ctx);

  BN_sub(pm1, p, BN_value_one());
  BN_sub(qm1, q, BN_value_one());

  BN_mul(psi, pm1, qm1, ctx);

  BN_zero(e);
  BN_add_word(e, (BN_ULONG) (65539));

  BN_mod_inverse(d, e, psi, ctx);

  printf("N: ");
  BN_print_fp(stdout, n);
  printf("\n");

  printf("P: ");
  BN_print_fp(stdout, p);
  printf("\n");

  printf("Q: ");
  BN_print_fp(stdout, q);
  printf("\n");

  printf("E: ");
  BN_print_fp(stdout, e);
  printf("\n");

  printf("D: ");
  BN_print_fp(stdout, d);
  printf("\n");

  BN_free(p);
  BN_free(q);
  BN_free(n);
  BN_free(e);
  BN_free(d);
  BN_free(psi);
  BN_free(pm1);
  BN_free(qm1);
  BN_free(pmq);

  BN_CTX_free(ctx);

  return 0;
}
예제 #28
0
파일: kexdhs.c 프로젝트: 2asoft/freebsd
int
input_kex_dh_init(int type, u_int32_t seq, void *ctxt)
{
	struct ssh *ssh = ctxt;
	struct kex *kex = ssh->kex;
	BIGNUM *shared_secret = NULL, *dh_client_pub = NULL;
	struct sshkey *server_host_public, *server_host_private;
	u_char *kbuf = NULL, *signature = NULL, *server_host_key_blob = NULL;
	u_char hash[SSH_DIGEST_MAX_LENGTH];
	size_t sbloblen, slen;
	size_t klen = 0, hashlen;
	int kout, r;

	if (kex->load_host_public_key == NULL ||
	    kex->load_host_private_key == NULL) {
		r = SSH_ERR_INVALID_ARGUMENT;
		goto out;
	}
	server_host_public = kex->load_host_public_key(kex->hostkey_type,
	    kex->hostkey_nid, ssh);
	server_host_private = kex->load_host_private_key(kex->hostkey_type,
	    kex->hostkey_nid, ssh);
	if (server_host_public == NULL) {
		r = SSH_ERR_NO_HOSTKEY_LOADED;
		goto out;
	}

	/* key, cert */
	if ((dh_client_pub = BN_new()) == NULL) {
		r = SSH_ERR_ALLOC_FAIL;
		goto out;
	}
	if ((r = sshpkt_get_bignum2(ssh, dh_client_pub)) != 0 ||
	    (r = sshpkt_get_end(ssh)) != 0)
		goto out;

#ifdef DEBUG_KEXDH
	fprintf(stderr, "dh_client_pub= ");
	BN_print_fp(stderr, dh_client_pub);
	fprintf(stderr, "\n");
	debug("bits %d", BN_num_bits(dh_client_pub));
#endif

#ifdef DEBUG_KEXDH
	DHparams_print_fp(stderr, kex->dh);
	fprintf(stderr, "pub= ");
	BN_print_fp(stderr, kex->dh->pub_key);
	fprintf(stderr, "\n");
#endif
	if (!dh_pub_is_valid(kex->dh, dh_client_pub)) {
		sshpkt_disconnect(ssh, "bad client public DH value");
		r = SSH_ERR_MESSAGE_INCOMPLETE;
		goto out;
	}

	klen = DH_size(kex->dh);
	if ((kbuf = malloc(klen)) == NULL ||
	    (shared_secret = BN_new()) == NULL) {
		r = SSH_ERR_ALLOC_FAIL;
		goto out;
	}
	if ((kout = DH_compute_key(kbuf, dh_client_pub, kex->dh)) < 0 ||
	    BN_bin2bn(kbuf, kout, shared_secret) == NULL) {
		r = SSH_ERR_LIBCRYPTO_ERROR;
		goto out;
	}
#ifdef DEBUG_KEXDH
	dump_digest("shared secret", kbuf, kout);
#endif
	if ((r = sshkey_to_blob(server_host_public, &server_host_key_blob,
	    &sbloblen)) != 0)
		goto out;
	/* calc H */
	hashlen = sizeof(hash);
	if ((r = kex_dh_hash(
	    kex->client_version_string,
	    kex->server_version_string,
	    sshbuf_ptr(kex->peer), sshbuf_len(kex->peer),
	    sshbuf_ptr(kex->my), sshbuf_len(kex->my),
	    server_host_key_blob, sbloblen,
	    dh_client_pub,
	    kex->dh->pub_key,
	    shared_secret,
	    hash, &hashlen)) != 0)
		goto out;

	/* save session id := H */
	if (kex->session_id == NULL) {
		kex->session_id_len = hashlen;
		kex->session_id = malloc(kex->session_id_len);
		if (kex->session_id == NULL) {
			r = SSH_ERR_ALLOC_FAIL;
			goto out;
		}
		memcpy(kex->session_id, hash, kex->session_id_len);
	}

	/* sign H */
	if ((r = kex->sign(server_host_private, server_host_public, &signature,
	     &slen, hash, hashlen, kex->hostkey_alg, ssh->compat)) < 0)
		goto out;

	/* destroy_sensitive_data(); */

	/* send server hostkey, DH pubkey 'f' and singed H */
	if ((r = sshpkt_start(ssh, SSH2_MSG_KEXDH_REPLY)) != 0 ||
	    (r = sshpkt_put_string(ssh, server_host_key_blob, sbloblen)) != 0 ||
	    (r = sshpkt_put_bignum2(ssh, kex->dh->pub_key)) != 0 ||	/* f */
	    (r = sshpkt_put_string(ssh, signature, slen)) != 0 ||
	    (r = sshpkt_send(ssh)) != 0)
		goto out;

	if ((r = kex_derive_keys_bn(ssh, hash, hashlen, shared_secret)) == 0)
		r = kex_send_newkeys(ssh);
 out:
	explicit_bzero(hash, sizeof(hash));
	DH_free(kex->dh);
	kex->dh = NULL;
	if (dh_client_pub)
		BN_clear_free(dh_client_pub);
	if (kbuf) {
		explicit_bzero(kbuf, klen);
		free(kbuf);
	}
	if (shared_secret)
		BN_clear_free(shared_secret);
	free(server_host_key_blob);
	free(signature);
	return r;
}
예제 #29
0
void
kexdh_server(Kex *kex)
{
	BIGNUM *shared_secret = NULL, *dh_client_pub = NULL;
	DH *dh;
	Key *server_host_key;
	u_char *kbuf, *hash, *signature = NULL, *server_host_key_blob = NULL;
	u_int sbloblen, klen, kout, hashlen;
	u_int slen;

	/* generate server DH public key */
	switch (kex->kex_type) {
	case KEX_DH_GRP1_SHA1:
		dh = dh_new_group1();
		break;
	case KEX_DH_GRP14_SHA1:
		dh = dh_new_group14();
		break;
	default:
		fatal("%s: Unexpected KEX type %d", __func__, kex->kex_type);
	}
	dh_gen_key(dh, kex->we_need * 8);

	debug("expecting SSH2_MSG_KEXDH_INIT");
	packet_read_expect(SSH2_MSG_KEXDH_INIT);

	if (kex->load_host_key == NULL)
		fatal("Cannot load hostkey");
	server_host_key = kex->load_host_key(kex->hostkey_type);
	if (server_host_key == NULL)
		fatal("Unsupported hostkey type %d", kex->hostkey_type);

	/* key, cert */
	if ((dh_client_pub = BN_new()) == NULL)
		fatal("dh_client_pub == NULL");
	packet_get_bignum2(dh_client_pub);
	packet_check_eom();

#ifdef DEBUG_KEXDH
	fprintf(stderr, "dh_client_pub= ");
	BN_print_fp(stderr, dh_client_pub);
	fprintf(stderr, "\n");
	debug("bits %d", BN_num_bits(dh_client_pub));
#endif

#ifdef DEBUG_KEXDH
	DHparams_print_fp(stderr, dh);
	fprintf(stderr, "pub= ");
	BN_print_fp(stderr, dh->pub_key);
	fprintf(stderr, "\n");
#endif
	if (!dh_pub_is_valid(dh, dh_client_pub))
		packet_disconnect("bad client public DH value");

	klen = DH_size(dh);
	kbuf = xmalloc(klen);
	kout = DH_compute_key(kbuf, dh_client_pub, dh);
#ifdef DEBUG_KEXDH
	dump_digest("shared secret", kbuf, kout);
#endif
	if ((shared_secret = BN_new()) == NULL)
		fatal("kexdh_server: BN_new failed");
	BN_bin2bn(kbuf, kout, shared_secret);
	memset(kbuf, 0, klen);
	xfree(kbuf);

	key_to_blob(server_host_key, &server_host_key_blob, &sbloblen);

	/* calc H */
	kex_dh_hash(
	    kex->client_version_string,
	    kex->server_version_string,
	    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
	    buffer_ptr(&kex->my), buffer_len(&kex->my),
	    server_host_key_blob, sbloblen,
	    dh_client_pub,
	    dh->pub_key,
	    shared_secret,
	    &hash, &hashlen
	);
	BN_clear_free(dh_client_pub);

	/* save session id := H */
	if (kex->session_id == NULL) {
		kex->session_id_len = hashlen;
		kex->session_id = xmalloc(kex->session_id_len);
		memcpy(kex->session_id, hash, kex->session_id_len);
	}

	/* sign H */
	PRIVSEP(key_sign(server_host_key, &signature, &slen, hash, hashlen));

	/* destroy_sensitive_data(); */

	/* send server hostkey, DH pubkey 'f' and singed H */
	packet_start(SSH2_MSG_KEXDH_REPLY);
	packet_put_string(server_host_key_blob, sbloblen);
	packet_put_bignum2(dh->pub_key);	/* f */
	packet_put_string(signature, slen);
	packet_send();

	xfree(signature);
	xfree(server_host_key_blob);
	/* have keys, free DH */
	DH_free(dh);

	kex_derive_keys(kex, hash, hashlen, shared_secret);
	BN_clear_free(shared_secret);
	kex_finish(kex);
}
예제 #30
0
void ecc_pointmul(EC_GROUP const* group)
{
#define ECC_POINTMUL_TEST_VECTOR_SIZE 52
  int i;
  const char* array[ECC_POINTMUL_TEST_VECTOR_SIZE] = {
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "10",
      "11",
      "12",
      "13",
      "14",
      "15",
      "16",
      "17",
      "18",
      "19",
      "20",
      "112233445566778899",
      "112233445566778899112233445566778899",
      "176980527797516303525377593084236712909374178672537678600734933265332381"
      "265665829141343503325767757909536663252144885414127592614418729449986393"
      "3403633025023",
      "104748400337157462316262627929132596317243790506798133267698218707528750"
      "292682889221414310155907963824712114916552440160880550666043997030661040"
      "721887239",
      "670390386507834588814138165143016803949666407735096505428813312654930705"
      "874178867114819742977734393646612757593803178614740947262747970246988421"
      "4509568000",
      "167592564368239530540451716564356225188002695878089653169885673702417988"
      "034333987833638241205026343194297493964668348090643463296347825763975734"
      "1102436352",
      "127851333821494152214024952025867017986206961694467725990382357218623386"
      "921901561639515589638569590592323816028647439244274517867695151543968107"
      "06943",
      "214524875832249255872206855495734426889477529336261655255492425273322727"
      "861341825677722947375406711676372335314043071600934941615185418540320233"
      "184489636351",
      "511404862755678591311390778908355268846484618578230883486511538405082876"
      "213668545068312447465312722466202951231042695658670559493782663956047687"
      "84399",
      "665152971602520688103527995288152062784115224721278452091442503931260612"
      "019887908083964331134716901924908019823940835656341344740227044546210206"
      "8592377843",
      "322455182461323223253768007794681866015683528877808734480537039781137973"
      "163167125485384682668227367787021477846223717136514039018377022685332936"
      "3961324241919",
      "124866131284428854303808740439912850802549174883962849538151492513154126"
      "006345815390666630922976120406699780176235877528454096531672770218641326"
      "08",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005429",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005430",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005431",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005432",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005433",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005434",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005435",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005436",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005437",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005438",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005439",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005440",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005441",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005442",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005443",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005444",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005445",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005446",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005447",
      "686479766013060971498190079908139321726943530014330540939446345918554318"
      "339765539424505774633321719753296399637136332111386476861244038034037280"
      "8892707005448"};

  BN_CTX* ctx;
  BIGNUM* x;
  BIGNUM* y;
  BIGNUM* x_get;
  BIGNUM* y_get;
  BIGNUM* mul;
  EC_POINT* point;

  x = BN_new();
  y = BN_new();
  x_get = BN_new();
  y_get = BN_new();
  mul = BN_new();

  if (!x || !y || !x_get || !y_get || !mul)
    ABORT;

  ctx = BN_CTX_new();
  if (!ctx)
    ABORT;

  point = EC_POINT_new(group);

  if (!point)
    ABORT;

  for (i = 0; i < ECC_POINTMUL_TEST_VECTOR_SIZE; i++)
  {
    if (!BN_dec2bn(&mul, array[i]))
      ABORT;

    if (!EC_POINT_mul(group, point, mul, NULL, NULL, ctx))
      ABORT;

    if (!EC_POINT_get_affine_coordinates_GFp(group, point, x_get, y_get, ctx))
      ABORT;

    fprintf(stdout, "m = %s\n", array[i]);
    fprintf(stdout, "X = 0x");
    BN_print_fp(stdout, x_get);
    fprintf(stdout, "\nY = 0x");
    BN_print_fp(stdout, y_get);
    fprintf(stdout, "\n\n");
  }

  EC_POINT_free(point);
  BN_free(mul);
  BN_free(y_get);
  BN_free(x_get);
  BN_free(y);
  BN_free(x);
  BN_CTX_free(ctx);
}