1/*
2 * Copyright (c) 2011-12 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24#include "ossl-config.h"
25
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29#include <errno.h>
30
31#include "ossl-evp.h"
32#include "ossl-dsa.h"
33
34/**
35 * Same as DSA_new_method() using NULL as engine.
36 *
37 * @return a newly allocated DSA object. Free with DSA_free().
38 */
39DSA *
40DSA_new(void)
41{
42	return (DSA_new_method(NULL));
43}
44
45
46/**
47 * Allocate a new DSA object using the engine, if NULL is specified as
48 * the engine, use the default DSA engine as returned by
49 * ENGINE_get_default_DSA().
50 *
51 * @param engine Specific what ENGINE DSA provider should be used.
52 *
53 * @return a newly allocated DSA object. Free with DSA_free().
54 *
55 */
56DSA *
57DSA_new_method(ENGINE *engine)
58{
59	DSA *dsa;
60
61	dsa = calloc(1, sizeof(*dsa));
62	if (dsa == NULL) {
63		return (NULL);
64	}
65
66	dsa->write_params = 1;
67	dsa->references = 1;
68
69	if (engine) {
70		ENGINE_up_ref(engine);
71		dsa->engine = engine;
72	} else {
73		dsa->engine = ENGINE_get_default_DSA();
74	}
75
76	if (dsa->engine) {
77		dsa->meth = ENGINE_get_DSA(dsa->engine);
78		if (dsa->meth == NULL) {
79			ENGINE_finish(engine);
80			free(dsa);
81			return (0);
82		}
83	}
84
85	if (dsa->meth == NULL) {
86		dsa->meth = DSA_get_default_method();
87	}
88
89	(*dsa->meth->init)(dsa);
90
91	return (dsa);
92}
93
94
95/**
96 * Free an allocation DSA object.
97 *
98 * @param dsa the DSA object to free.
99 */
100void
101DSA_free(DSA *dsa)
102{
103	if (dsa->references <= 0) {
104		abort();
105	}
106
107	if (--dsa->references > 0) { /* XXX use atomic op */
108		return;
109	}
110
111	(*dsa->meth->finish)(dsa);
112
113	if (dsa->engine) {
114		ENGINE_finish(dsa->engine);
115	}
116
117#define free_if(f)    if (f) { BN_clear_free(f); }
118	free_if(dsa->p);
119	free_if(dsa->q);
120	free_if(dsa->g);
121	free_if(dsa->pub_key);
122	free_if(dsa->priv_key);
123	free_if(dsa->kinv);
124	free_if(dsa->r);
125#undef free_if
126
127	memset(dsa, 0, sizeof(*dsa));
128	free(dsa);
129}
130
131
132/**
133 * Add an extra reference to the DSA object. The object should be free
134 * with DSA_free() to drop the reference.
135 *
136 * @param dsa the object to add reference counting too.
137 *
138 * @return the current reference count, can't safely be used except
139 * for debug printing.
140 *
141 */
142int
143DSA_up_ref(DSA *dsa)
144{
145	return (++dsa->references); /* XXX use atomic op */
146}
147
148
149#if 0
150
151/**
152 * Return the DSA_METHOD used for this DSA object.
153 *
154 * @param dsa the object to get the method from.
155 *
156 * @return the method used for this DSA object.
157 *
158 */
159const DSA_METHOD *
160DSA_get_method(const DSA *dsa)
161{
162	return (dsa->meth);
163}
164
165
166#endif
167
168/**
169 * Set a new method for the DSA keypair.
170 *
171 * @param dsa dsa parameter.
172 * @param method the new method for the DSA parameter.
173 *
174 * @return 1 on success.
175 *
176 */
177int
178DSA_set_method(DSA *dsa, const DSA_METHOD *method)
179{
180	(*dsa->meth->finish)(dsa);
181
182	if (dsa->engine) {
183		ENGINE_finish(dsa->engine);
184		dsa->engine = NULL;
185	}
186
187	dsa->meth = method;
188	(*dsa->meth->init)(dsa);
189	return (1);
190}
191
192
193#if 0
194
195/**
196 * Set the application data for the DSA object.
197 *
198 * @param dsa the dsa object to set the parameter for
199 * @param arg the data object to store
200 *
201 * @return 1 on success.
202 *
203 */
204int
205DSA_set_app_data(DSA *dsa, void *arg)
206{
207	dsa->ex_data.sk = arg;
208	return (1);
209}
210
211
212/**
213 * Get the application data for the DSA object.
214 *
215 * @param dsa the dsa object to get the parameter for
216 *
217 * @return the data object
218 *
219 */
220void *
221DSA_get_app_data(const DSA *dsa)
222{
223	return (dsa->ex_data.sk);
224}
225
226
227#endif
228
229DSA_SIG *
230DSA_do_sign(const unsigned char *dgst, unsigned int dlen, DSA *dsa)
231{
232	if (dsa && dsa->meth && dsa->meth->dsa_do_sign) {
233		return (dsa->meth->dsa_do_sign(dgst, dlen, dsa));
234	} else{
235		return (NULL);
236	}
237}
238
239
240int
241DSA_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp)
242{
243	if (dsa && dsa->meth->dsa_sign_setup) {
244		return (dsa->meth->dsa_sign_setup(dsa, ctx_in, kinvp, rp));
245	} else{
246		return (0);
247	}
248}
249
250
251int
252DSA_do_verify(const unsigned char *dgst, int dgst_len, DSA_SIG *sig, DSA *dsa)
253{
254	if (dsa && dsa->meth && dsa->meth->dsa_do_verify) {
255		return (dsa->meth->dsa_do_verify(dgst, dgst_len, sig, dsa));
256	} else{
257		return (0);
258	}
259}
260
261
262/*
263 * default key generation
264 */
265static int
266dsa_builtin_keygen(DSA *dsa)
267{
268	int ok = 0;
269	BN_CTX *ctx = NULL;
270	BIGNUM *pub_key = NULL, *priv_key = NULL;
271
272	if ((ctx = BN_CTX_new()) == NULL) {
273		goto err;
274	}
275
276	if (dsa->priv_key == NULL) {
277		if ((priv_key = BN_new()) == NULL) {
278			goto err;
279		}
280	} else{
281		priv_key = dsa->priv_key;
282	}
283
284	do {
285		if (!BN_rand_range(priv_key, dsa->q)) {
286			goto err;
287		}
288	} while (BN_is_zero(priv_key));
289
290	if (dsa->pub_key == NULL) {
291		if ((pub_key = BN_new()) == NULL) {
292			goto err;
293		}
294	} else{
295		pub_key = dsa->pub_key;
296	}
297
298	{
299		BIGNUM local_prk;
300		BIGNUM *prk;
301
302		if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) {
303			BN_init(&local_prk);
304			prk = &local_prk;
305			BN_with_flags(prk, priv_key, BN_FLG_CONSTTIME);
306		} else{
307			prk = priv_key;
308		}
309
310		if (!BN_mod_exp(pub_key, dsa->g, prk, dsa->p, ctx)) {
311			goto err;
312		}
313	}
314
315	dsa->priv_key = priv_key;
316	dsa->pub_key = pub_key;
317	ok = 1;
318
319err:
320	if ((pub_key != NULL) && (dsa->pub_key == NULL)) {
321		BN_free(pub_key);
322	}
323	if ((priv_key != NULL) && (dsa->priv_key == NULL)) {
324		BN_free(priv_key);
325	}
326	if (ctx != NULL) {
327		BN_CTX_free(ctx);
328	}
329	return (ok);
330}
331
332
333int
334DSA_generate_key(DSA *dsa)
335{
336	if (dsa && dsa->meth && dsa->meth->dsa_keygen) {
337		return (dsa->meth->dsa_keygen(dsa));
338	} else{
339		return (dsa_builtin_keygen(dsa));
340	}
341}
342
343
344#define HASH			EVP_sha()
345#ifndef SHA_DIGEST_LENGTH
346#define SHA_DIGEST_LENGTH	20
347#endif
348#define DSS_prime_checks	50
349
350static int
351dsa_builtin_paramgen(DSA *ret, int bits,
352    unsigned char *seed_in, int seed_len,
353    int *counter_ret, unsigned long *h_ret, BN_GENCB *cb)
354{
355	int ok = 0;
356	unsigned char seed[SHA_DIGEST_LENGTH];
357	unsigned char md[SHA_DIGEST_LENGTH];
358	unsigned char buf[SHA_DIGEST_LENGTH], buf2[SHA_DIGEST_LENGTH];
359	BIGNUM *r0, *W, *X, *c, *test;
360	BIGNUM *g = NULL, *q = NULL, *p = NULL;
361	BN_MONT_CTX *mont = NULL;
362	int k, n = 0, i, m = 0;
363	int counter = 0;
364	int r = 0;
365	BN_CTX *ctx = NULL;
366	unsigned int h = 2;
367
368	if (bits < 512) {
369		bits = 512;
370	}
371	bits = (bits + 63) / 64 * 64;
372
373	/* NB: seed_len == 0 is special case: copy generated seed to
374	 * seed_in if it is not NULL.
375	 */
376	if (seed_len && (seed_len < 20)) {
377		seed_in = NULL; /* seed buffer too small -- ignore */
378	}
379	if (seed_len > 20) {
380		seed_len = 20; /* App. 2.2 of FIPS PUB 186 allows larger SEED,
381	                        * but our internal buffers are restricted to 160 bits*/
382	}
383	if ((seed_in != NULL) && (seed_len == 20)) {
384		memcpy(seed, seed_in, seed_len);
385		/* set seed_in to NULL to avoid it being copied back */
386		seed_in = NULL;
387	}
388
389	if ((ctx = BN_CTX_new()) == NULL) {
390		goto err;
391	}
392
393	if ((mont = BN_MONT_CTX_new()) == NULL) {
394		goto err;
395	}
396
397	BN_CTX_start(ctx);
398	r0 = BN_CTX_get(ctx);
399	g = BN_CTX_get(ctx);
400	W = BN_CTX_get(ctx);
401	q = BN_CTX_get(ctx);
402	X = BN_CTX_get(ctx);
403	c = BN_CTX_get(ctx);
404	p = BN_CTX_get(ctx);
405	test = BN_CTX_get(ctx);
406
407	if (!BN_lshift(test, BN_value_one(), bits - 1)) {
408		goto err;
409	}
410
411	for ( ; ; ) {
412		for ( ; ; ) {
413			/* find q */
414			int seed_is_random;
415
416			/* step 1 */
417			if (!BN_GENCB_call(cb, 0, m++)) {
418				goto err;
419			}
420
421			if (!seed_len) {
422				RAND_pseudo_bytes(seed, SHA_DIGEST_LENGTH);
423				seed_is_random = 1;
424			} else {
425				seed_is_random = 0;
426				seed_len = 0; /* use random seed if 'seed_in' turns out to be bad*/
427			}
428			memcpy(buf, seed, SHA_DIGEST_LENGTH);
429			memcpy(buf2, seed, SHA_DIGEST_LENGTH);
430			/* precompute "SEED + 1" for step 7: */
431			for (i = SHA_DIGEST_LENGTH - 1; i >= 0; i--) {
432				buf[i]++;
433				if (buf[i] != 0) {
434					break;
435				}
436			}
437
438			/* step 2 */
439			EVP_Digest(seed, SHA_DIGEST_LENGTH, md, NULL, HASH, NULL);
440			EVP_Digest(buf, SHA_DIGEST_LENGTH, buf2, NULL, HASH, NULL);
441			for (i = 0; i < SHA_DIGEST_LENGTH; i++) {
442				md[i] ^= buf2[i];
443			}
444
445			/* step 3 */
446			md[0] |= 0x80;
447			md[SHA_DIGEST_LENGTH - 1] |= 0x01;
448			if (!BN_bin2bn(md, SHA_DIGEST_LENGTH, q)) {
449				goto err;
450			}
451
452			/* step 4 */
453			r = BN_is_prime_fasttest_ex(q, DSS_prime_checks, ctx,
454				seed_is_random, cb);
455			if (r > 0) {
456				break;
457			}
458			if (r != 0) {
459				goto err;
460			}
461
462			/* do a callback call */
463			/* step 5 */
464		}
465
466		if (!BN_GENCB_call(cb, 2, 0)) {
467			goto err;
468		}
469		if (!BN_GENCB_call(cb, 3, 0)) {
470			goto err;
471		}
472
473		/* step 6 */
474		counter = 0;
475		/* "offset = 2" */
476
477		n = (bits - 1) / 160;
478
479		for ( ; ; ) {
480			if ((counter != 0) && !BN_GENCB_call(cb, 0, counter)) {
481				goto err;
482			}
483
484			/* step 7 */
485			BN_zero(W);
486			/* now 'buf' contains "SEED + offset - 1" */
487			for (k = 0; k <= n; k++) {
488				/* obtain "SEED + offset + k" by incrementing: */
489				for (i = SHA_DIGEST_LENGTH-1; i >= 0; i--) {
490					buf[i]++;
491					if (buf[i] != 0) {
492						break;
493					}
494				}
495
496				EVP_Digest(buf, SHA_DIGEST_LENGTH, md, NULL, HASH, NULL);
497
498				/* step 8 */
499				if (!BN_bin2bn(md, SHA_DIGEST_LENGTH, r0)) {
500					goto err;
501				}
502				if (!BN_lshift(r0, r0, 160*k)) {
503					goto err;
504				}
505				if (!BN_add(W, W, r0)) {
506					goto err;
507				}
508			}
509
510			/* more of step 8 */
511			if (!BN_mask_bits(W, bits-1)) {
512				goto err;
513			}
514			if (!BN_copy(X, W)) {
515				goto err;
516			}
517			if (!BN_add(X, X, test)) {
518				goto err;
519			}
520
521			/* step 9 */
522			if (!BN_lshift1(r0, q)) {
523				goto err;
524			}
525			if (!BN_mod(c, X, r0, ctx)) {
526				goto err;
527			}
528			if (!BN_sub(r0, c, BN_value_one())) {
529				goto err;
530			}
531			if (!BN_sub(p, X, r0)) {
532				goto err;
533			}
534
535			/* step 10 */
536			if (BN_cmp(p, test) >= 0) {
537				/* step 11 */
538				r = BN_is_prime_fasttest_ex(p, DSS_prime_checks,
539					ctx, 1, cb);
540				if (r > 0) {
541					goto end;         /* found it */
542				}
543				if (r != 0) {
544					goto err;
545				}
546			}
547
548			/* step 13 */
549			counter++;
550			/* "offset = offset + n + 1" */
551
552			/* step 14 */
553			if (counter >= 4096) {
554				break;
555			}
556		}
557	}
558end:
559	if (!BN_GENCB_call(cb, 2, 1)) {
560		goto err;
561	}
562
563	/* We now need to generate g */
564	/* Set r0=(p-1)/q */
565	if (!BN_sub(test, p, BN_value_one())) {
566		goto err;
567	}
568	if (!BN_div(r0, NULL, test, q, ctx)) {
569		goto err;
570	}
571
572	if (!BN_set_word(test, h)) {
573		goto err;
574	}
575	if (!BN_MONT_CTX_set(mont, p, ctx)) {
576		goto err;
577	}
578
579	for ( ; ; ) {
580		/* g=test^r0%p */
581		if (!BN_mod_exp_mont(g, test, r0, p, ctx, mont)) {
582			goto err;
583		}
584		if (!BN_is_one(g)) {
585			break;
586		}
587		if (!BN_add(test, test, BN_value_one())) {
588			goto err;
589		}
590		h++;
591	}
592
593	if (!BN_GENCB_call(cb, 3, 1)) {
594		goto err;
595	}
596
597	ok = 1;
598err:
599	if (ok) {
600		if (ret->p) {
601			BN_free(ret->p);
602		}
603		if (ret->q) {
604			BN_free(ret->q);
605		}
606		if (ret->g) {
607			BN_free(ret->g);
608		}
609		ret->p = BN_dup(p);
610		ret->q = BN_dup(q);
611		ret->g = BN_dup(g);
612		if ((ret->p == NULL) || (ret->q == NULL) || (ret->g == NULL)) {
613			ok = 0;
614			goto err;
615		}
616		if (seed_in != NULL) {
617			memcpy(seed_in, seed, 20);
618		}
619		if (counter_ret != NULL) {
620			*counter_ret = counter;
621		}
622		if (h_ret != NULL) {
623			*h_ret = h;
624		}
625	}
626	if (ctx) {
627		BN_CTX_end(ctx);
628		BN_CTX_free(ctx);
629	}
630	if (mont != NULL) {
631		BN_MONT_CTX_free(mont);
632	}
633	return (ok);
634}
635
636
637int
638DSA_generate_parameters_ex(DSA *ret, int bits,
639    unsigned char *seed_in, int seed_len,
640    int *counter_ret, unsigned long *h_ret, BN_GENCB *cb)
641{
642	if (ret && ret->meth->dsa_paramgen) {
643		return (ret->meth->dsa_paramgen(ret, bits, seed_in, seed_len,
644		       counter_ret, h_ret, cb));
645	}
646	return (dsa_builtin_paramgen(ret, bits, seed_in, seed_len,
647	       counter_ret, h_ret, cb));
648}
649
650
651/*
652 * DSA Null method
653 */
654static DSA_SIG *
655null_dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa)
656{
657	return (NULL);
658}
659
660
661static int
662null_dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp)
663{
664	return (0);
665}
666
667
668static int
669null_dsa_do_verify(const unsigned char *dgst, int dgst_len, DSA_SIG *sig, DSA *dsa)
670{
671	return (0);
672}
673
674
675static int
676null_dsa_init(DSA *dsa)
677{
678	return (0);
679}
680
681
682static int
683null_dsa_finish(DSA *dsa)
684{
685	return (0);
686}
687
688
689static int
690null_dsa_paramgen(DSA *dsa, int bits, unsigned char *seed, int seed_len,
691    int *counter_ret, unsigned long *h_ret, BN_GENCB *cb)
692{
693	return (0);
694}
695
696
697static int
698null_dsa_keygen(DSA *dsa)
699{
700	return (0);
701}
702
703
704static const DSA_METHOD dsa_null_method =
705{
706	.name		= "cryptoshim null DSA",
707	.dsa_do_sign	= null_dsa_do_sign,
708	.dsa_sign_setup = null_dsa_sign_setup,
709	.dsa_do_verify	= null_dsa_do_verify,
710	.init		= null_dsa_init,
711	.finish		= null_dsa_finish,
712	.flags		=		      0,
713	.app_data	= NULL,
714	.dsa_paramgen	= null_dsa_paramgen,
715	.dsa_keygen	= null_dsa_keygen
716};
717
718const DSA_METHOD *
719DSA_null_method(void)
720{
721	return (&dsa_null_method);
722}
723
724
725#if !defined(PR_10488503_FIXED)
726extern const DSA_METHOD _ossl_dsa_eay_method;
727static const DSA_METHOD *default_dsa_method = &_ossl_dsa_eay_method;
728#elif HAVE_CDSA
729extern const DSA_METHOD _ossl_dsa_cdsa_method;
730static const DSA_METHOD *default_dsa_method = &_ossl_dsa_cdsa_method;
731#elif defined(__APPLE_TARGET_EMBEDDED__)
732static const DSA_METHOD *default_dsa_method = &dsa_null_method;
733#elif defined(HAVE_GMP)
734extern const DSA_METHOD _ossl_dsa_gmp_method;
735static const DSA_METHOD *default_dsa_method = &_ossl_dsa_gmp_method;
736#elif defined(HEIM_HC_LTM)
737extern const DSA_METHOD _ossl_dsa_ltm_method;
738static const DSA_METHOD *default_dsa_method = &_ossl_dsa_ltm_method;
739#else
740static const DSA_METHOD *default_dsa_method = &dsa_null_method;
741#endif
742
743const DSA_METHOD *
744DSA_get_default_method(void)
745{
746	return (default_dsa_method);
747}
748
749
750void
751DSA_set_default_method(const DSA_METHOD *meth)
752{
753	default_dsa_method = meth;
754}
755
756
757DSA_SIG *
758DSA_SIG_new(void)
759{
760	DSA_SIG *sig;
761
762	sig = malloc(sizeof(DSA_SIG));
763	if (NULL == sig) {
764		return (NULL);
765	}
766	sig->r = NULL;
767	sig->s = NULL;
768
769	return (sig);
770}
771
772
773void
774DSA_SIG_free(DSA_SIG *sig)
775{
776	if (sig != NULL) {
777		if (sig->r != NULL) {
778			BN_free(sig->r);
779		}
780		if (sig->s) {
781			BN_free(sig->s);
782		}
783		free(sig);
784	}
785}
786
787
788#if defined(USE_HEIMDAL_ASN1)
789
790/*
791 * HEIMDAL ASN1
792 */
793
794#include "krb5-types.h"
795#include "rfc2459_asn1.h"
796#include "der.h"
797
798#include "ossl-common.h"
799
800int
801DSA_size(const DSA *dsa)
802{
803	DSAPublicKey data;
804	size_t size;
805
806	if (NULL == dsa) {
807		return (0);
808	}
809
810	if (_cs_BN_to_integer(dsa->q, &data)) {
811		return (0);
812	}
813
814	size = length_DSAPublicKey(&data);
815	free_DSAPublicKey(&data);
816
817	return (size);
818}
819
820
821DSA *
822d2i_DSAPrivateKey(DSA **dsa, const unsigned char **pp, long len)
823{
824	DSAPrivateKey data;
825	DSA *k = NULL;
826	size_t size;
827	int ret;
828
829	ret = decode_DSAPrivateKey(*pp, len, &data, &size);
830	if (ret) {
831		return (NULL);
832	}
833
834	*pp += size;
835
836	if (dsa != NULL) {
837		k = *dsa;
838	}
839
840	if (NULL == k) {
841		k = DSA_new();
842		if (NULL == k) {
843			free_DSAPrivateKey(&data);
844			return (NULL);
845		}
846	}
847
848	k->p = _cs_integer_to_BN(&data.p, NULL);
849	k->q = _cs_integer_to_BN(&data.q, NULL);
850	k->g = _cs_integer_to_BN(&data.g, NULL);
851	k->pub_key = _cs_integer_to_BN(&data.pub_key, NULL);
852	k->priv_key = _cs_integer_to_BN(&data.priv_key, NULL);
853	free_DSAPrivateKey(&data);
854
855	if ((NULL == k->p) || (NULL == k->q) || (NULL == k->g) ||
856	    (NULL == k->pub_key) || (NULL == k->priv_key)) {
857		DSA_free(k);
858		return (NULL);
859	}
860
861	if (dsa != NULL) {
862		*dsa = k;
863	}
864
865	return (k);
866}
867
868
869DSA *
870d2i_DSAPublicKey(DSA **dsa, const unsigned char **pp, long len)
871{
872	DSAPublicKey data;
873	DSA *k = NULL;
874	size_t size;
875	int ret;
876
877	ret = decode_DSAPublicKey(*pp, len, &data, &size);
878	if (ret) {
879		return (NULL);
880	}
881
882	*pp += size;
883
884	if (dsa != NULL) {
885		k = *dsa;
886	}
887
888	if (NULL == k) {
889		k = DSA_new();
890		if (NULL == k) {
891			free_DSAPublicKey(&data);
892			return (NULL);
893		}
894	}
895
896	k->pub_key = _cs_integer_to_BN(&data, NULL);
897	free_DSAPublicKey(&data);
898
899	if (NULL == k->pub_key) {
900		DSA_free(k);
901		return (NULL);
902	}
903
904	if (dsa != NULL) {
905		*dsa = k;
906	}
907
908	return (k);
909}
910
911
912int
913i2d_DSAPrivateKey(const DSA *dsa, unsigned char **pp)
914{
915	DSAPrivateKey data;
916	size_t size;
917	int ret;
918
919	if ((NULL == dsa->p) || (NULL == dsa->q) || (NULL == dsa->g) ||
920	    (NULL == dsa->pub_key) || (NULL == dsa->priv_key)) {
921		return (-1);
922	}
923
924	memset(&data, 0, sizeof(data));
925
926	ret = _cs_BN_to_integer(dsa->p, &data.p);
927	ret |= _cs_BN_to_integer(dsa->q, &data.q);
928	ret |= _cs_BN_to_integer(dsa->g, &data.g);
929	ret |= _cs_BN_to_integer(dsa->pub_key, &data.pub_key);
930	ret |= _cs_BN_to_integer(dsa->priv_key, &data.priv_key);
931	if (ret) {
932		free_DSAPrivateKey(&data);
933		return (-1);
934	}
935
936	if (NULL == pp) {
937		size = length_DSAPrivateKey(&data);
938		free_DSAPrivateKey(&data);
939	} else {
940		void *p;
941		size_t len;
942
943		ASN1_MALLOC_ENCODE(DSAPrivateKey, p, len, &data, &size, ret);
944		free_DSAPrivateKey(&data);
945		if (ret) {
946			return (-1);
947		}
948		if (len != size) {
949			abort();
950		}
951
952		memcpy(*pp, p, size);
953		free(p);
954
955		*pp += size;
956	}
957
958	return (size);
959}
960
961
962int
963i2d_DSAPublicKey(const DSA *dsa, unsigned char **pp)
964{
965	DSAPublicKey data;
966	size_t size;
967	int ret;
968
969	if (NULL == dsa->pub_key) {
970		return (-1);
971	}
972
973	memset(&data, 0, sizeof(data));
974	ret = _cs_BN_to_integer(dsa->pub_key, &data);
975	if (ret) {
976		free_DSAPublicKey(&data);
977		return (-1);
978	}
979
980	if (NULL == pp) {
981		size = length_DSAPublicKey(&data);
982		free_DSAPublicKey(&data);
983	} else {
984		void *p;
985		size_t len;
986
987		ASN1_MALLOC_ENCODE(DSAPublicKey, p, len, &data, &size, ret);
988		free_DSAPublicKey(&data);
989		if (ret) {
990			return (-1);
991		}
992		if (len != size) {
993			abort();
994		}
995
996		memcpy(*pp, p, size);
997		free(p);
998
999		*pp += size;
1000	}
1001
1002	return (size);
1003}
1004
1005
1006#elif defined(USE_EAY_ASN1)
1007
1008/*
1009 * ossl eay asn1
1010 */
1011
1012#include "ossl-asn1.h"
1013#include "ossl-asn1t.h"
1014
1015/* Override the default new methods */
1016static int
1017sig_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it)
1018{
1019	if (operation == ASN1_OP_NEW_PRE) {
1020		DSA_SIG *sig;
1021		sig = malloc(sizeof(DSA_SIG));
1022		sig->r = NULL;
1023		sig->s = NULL;
1024		*pval = (ASN1_VALUE *)sig;
1025		if (sig) {
1026			return (2);
1027		}
1028		/* DSAerr(DSA_F_SIG_CB, ERR_R_MALLOC_FAILURE); */
1029		return (0);
1030	}
1031	return (1);
1032}
1033
1034
1035ASN1_SEQUENCE_cb(DSA_SIG, sig_cb) =
1036{
1037	ASN1_SIMPLE(DSA_SIG, r, CBIGNUM),
1038	ASN1_SIMPLE(DSA_SIG, s, CBIGNUM)
1039}
1040
1041
1042ASN1_SEQUENCE_END_cb(DSA_SIG, DSA_SIG)
1043
1044IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(DSA_SIG, DSA_SIG, DSA_SIG)
1045
1046/* Override the default free and new methods */
1047static int
1048dsa_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it)
1049{
1050	if (operation == ASN1_OP_NEW_PRE) {
1051		*pval = (ASN1_VALUE *)DSA_new();
1052		if (*pval) {
1053			return (2);
1054		}
1055		return (0);
1056	} else if (operation == ASN1_OP_FREE_PRE) {
1057		DSA_free((DSA *)*pval);
1058		*pval = NULL;
1059		return (2);
1060	}
1061	return (1);
1062}
1063
1064
1065ASN1_SEQUENCE_cb(DSAPrivateKey, dsa_cb) =
1066{
1067	ASN1_SIMPLE(DSA, version,  LONG),
1068	ASN1_SIMPLE(DSA, p,	   BIGNUM),
1069	ASN1_SIMPLE(DSA, q,	   BIGNUM),
1070	ASN1_SIMPLE(DSA, g,	   BIGNUM),
1071	ASN1_SIMPLE(DSA, pub_key,  BIGNUM),
1072	ASN1_SIMPLE(DSA, priv_key, BIGNUM)
1073}
1074
1075
1076ASN1_SEQUENCE_END_cb(DSA, DSAPrivateKey)
1077
1078IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(DSA, DSAPrivateKey, DSAPrivateKey)
1079
1080ASN1_SEQUENCE_cb(DSAparams, dsa_cb) =
1081{
1082	ASN1_SIMPLE(DSA, p, BIGNUM),
1083	ASN1_SIMPLE(DSA, q, BIGNUM),
1084	ASN1_SIMPLE(DSA, g, BIGNUM),
1085}
1086
1087
1088ASN1_SEQUENCE_END_cb(DSA, DSAparams)
1089
1090IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(DSA, DSAparams, DSAparams)
1091
1092/* DSA public key is a bit trickier... its effectively a CHOICE type
1093 * decided by a field called write_params which can either write out
1094 * just the public key as an INTEGER or the parameters and public key
1095 * in a SEQUENCE
1096 */
1097
1098ASN1_SEQUENCE(dsa_pub_internal) =
1099{
1100	ASN1_SIMPLE(DSA, pub_key, BIGNUM),
1101	ASN1_SIMPLE(DSA, p,	  BIGNUM),
1102	ASN1_SIMPLE(DSA, q,	  BIGNUM),
1103	ASN1_SIMPLE(DSA, g,	  BIGNUM)
1104}
1105
1106
1107ASN1_SEQUENCE_END_name(DSA, dsa_pub_internal)
1108
1109ASN1_CHOICE_cb(DSAPublicKey, dsa_cb) =
1110{
1111	ASN1_SIMPLE(DSA,   pub_key, BIGNUM),
1112	ASN1_EX_COMBINE(0,	 0, dsa_pub_internal)
1113}
1114
1115
1116ASN1_CHOICE_END_cb(DSA, DSAPublicKey, write_params)
1117
1118IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(DSA, DSAPublicKey, DSAPublicKey)
1119
1120int
1121DSA_sign(int type, const unsigned char *dgst, int dlen, unsigned char *sig,
1122    unsigned int *siglen, DSA *dsa)
1123{
1124	DSA_SIG *s;
1125
1126	RAND_seed(dgst, dlen);
1127	s = DSA_do_sign(dgst, dlen, dsa);
1128	if (s == NULL) {
1129		*siglen = 0;
1130		return (0);
1131	}
1132	*siglen = i2d_DSA_SIG(s, &sig);
1133	DSA_SIG_free(s);
1134	return (1);
1135}
1136
1137
1138int
1139DSA_size(const DSA *r)
1140{
1141	int ret, i;
1142	ASN1_INTEGER bs;
1143	unsigned char buf[4];   /* 4 bytes looks really small.
1144	                         * However, i2d_ASN1_INTEGER() will not look
1145	                         * beyond the first byte, as long as the second
1146	                         * parameter is NULL. */
1147
1148	i = BN_num_bits(r->q);
1149	bs.length = (i + 7) / 8;
1150	bs.data = buf;
1151	bs.type = V_ASN1_INTEGER;
1152	/* If the top bit is set the asn1 encoding is 1 larger. */
1153	buf[0] = 0xff;
1154
1155	i = i2d_ASN1_INTEGER(&bs, NULL);
1156	i += i; /* r and s */
1157	ret = ASN1_object_size(1, i, V_ASN1_SEQUENCE);
1158	return (ret);
1159}
1160
1161
1162/* data has already been hashed (probably with SHA or SHA-1). */
1163
1164/* returns
1165 *      1: correct signature
1166 *      0: incorrect signature
1167 *     -1: error
1168 */
1169int
1170DSA_verify(int type, const unsigned char *dgst, int dgst_len,
1171    const unsigned char *sigbuf, int siglen, DSA *dsa)
1172{
1173	DSA_SIG *s;
1174
1175	int ret = -1;
1176
1177	s = DSA_SIG_new();
1178	if (s == NULL) {
1179		return (ret);
1180	}
1181	if (d2i_DSA_SIG(&s, &sigbuf, siglen) == NULL) {
1182		goto err;
1183	}
1184	ret = DSA_do_verify(dgst, dgst_len, s, dsa);
1185err:
1186	DSA_SIG_free(s);
1187	return (ret);
1188}
1189
1190
1191#else
1192
1193#error "Unknown ASN1 implementation"
1194
1195#endif /* ASN1 */
1196