1/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
2 * project 2006.
3 */
4/* ====================================================================
5 * Copyright (c) 2006 The OpenSSL Project.  All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 *
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in
16 *    the documentation and/or other materials provided with the
17 *    distribution.
18 *
19 * 3. All advertising materials mentioning features or use of this
20 *    software must display the following acknowledgment:
21 *    "This product includes software developed by the OpenSSL Project
22 *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
23 *
24 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
25 *    endorse or promote products derived from this software without
26 *    prior written permission. For written permission, please contact
27 *    licensing@OpenSSL.org.
28 *
29 * 5. Products derived from this software may not be called "OpenSSL"
30 *    nor may "OpenSSL" appear in their names without prior written
31 *    permission of the OpenSSL Project.
32 *
33 * 6. Redistributions of any form whatsoever must retain the following
34 *    acknowledgment:
35 *    "This product includes software developed by the OpenSSL Project
36 *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
37 *
38 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
39 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
40 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
41 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
42 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
43 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
44 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
45 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
46 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
47 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
48 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
49 * OF THE POSSIBILITY OF SUCH DAMAGE.
50 * ====================================================================
51 *
52 * This product includes cryptographic software written by Eric Young
53 * (eay@cryptsoft.com).  This product includes software written by Tim
54 * Hudson (tjh@cryptsoft.com).
55 *
56 */
57
58#include <stdio.h>
59#include "cryptlib.h"
60#include <openssl/x509.h>
61#include <openssl/asn1.h>
62#include <openssl/dsa.h>
63#include <openssl/bn.h>
64#ifndef OPENSSL_NO_CMS
65#include <openssl/cms.h>
66#endif
67#include "asn1_locl.h"
68
69static int dsa_pub_decode(EVP_PKEY *pkey, X509_PUBKEY *pubkey)
70	{
71	const unsigned char *p, *pm;
72	int pklen, pmlen;
73	int ptype;
74	void *pval;
75	ASN1_STRING *pstr;
76	X509_ALGOR *palg;
77	ASN1_INTEGER *public_key = NULL;
78
79	DSA *dsa = NULL;
80
81	if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, &palg, pubkey))
82		return 0;
83	X509_ALGOR_get0(NULL, &ptype, &pval, palg);
84
85
86	if (ptype == V_ASN1_SEQUENCE)
87		{
88		pstr = pval;
89		pm = pstr->data;
90		pmlen = pstr->length;
91
92		if (!(dsa = d2i_DSAparams(NULL, &pm, pmlen)))
93			{
94			DSAerr(DSA_F_DSA_PUB_DECODE, DSA_R_DECODE_ERROR);
95			goto err;
96			}
97
98		}
99	else if ((ptype == V_ASN1_NULL) || (ptype == V_ASN1_UNDEF))
100		{
101		if (!(dsa = DSA_new()))
102			{
103			DSAerr(DSA_F_DSA_PUB_DECODE, ERR_R_MALLOC_FAILURE);
104			goto err;
105			}
106		}
107	else
108		{
109		DSAerr(DSA_F_DSA_PUB_DECODE, DSA_R_PARAMETER_ENCODING_ERROR);
110		goto err;
111		}
112
113	if (!(public_key=d2i_ASN1_INTEGER(NULL, &p, pklen)))
114		{
115		DSAerr(DSA_F_DSA_PUB_DECODE, DSA_R_DECODE_ERROR);
116		goto err;
117		}
118
119	if (!(dsa->pub_key = ASN1_INTEGER_to_BN(public_key, NULL)))
120		{
121		DSAerr(DSA_F_DSA_PUB_DECODE, DSA_R_BN_DECODE_ERROR);
122		goto err;
123		}
124
125	ASN1_INTEGER_free(public_key);
126	EVP_PKEY_assign_DSA(pkey, dsa);
127	return 1;
128
129	err:
130	if (public_key)
131		ASN1_INTEGER_free(public_key);
132	if (dsa)
133		DSA_free(dsa);
134	return 0;
135
136	}
137
138static int dsa_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey)
139	{
140	DSA *dsa;
141	void *pval = NULL;
142	int ptype;
143	unsigned char *penc = NULL;
144	int penclen;
145
146	dsa=pkey->pkey.dsa;
147	if (pkey->save_parameters && dsa->p && dsa->q && dsa->g)
148		{
149		ASN1_STRING *str;
150		str = ASN1_STRING_new();
151		str->length = i2d_DSAparams(dsa, &str->data);
152		if (str->length <= 0)
153			{
154			DSAerr(DSA_F_DSA_PUB_ENCODE, ERR_R_MALLOC_FAILURE);
155			goto err;
156			}
157		pval = str;
158		ptype = V_ASN1_SEQUENCE;
159		}
160	else
161		ptype = V_ASN1_UNDEF;
162
163	dsa->write_params=0;
164
165	penclen = i2d_DSAPublicKey(dsa, &penc);
166
167	if (penclen <= 0)
168		{
169		DSAerr(DSA_F_DSA_PUB_ENCODE, ERR_R_MALLOC_FAILURE);
170		goto err;
171		}
172
173	if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(EVP_PKEY_DSA),
174				ptype, pval, penc, penclen))
175		return 1;
176
177	err:
178	if (penc)
179		OPENSSL_free(penc);
180	if (pval)
181		ASN1_STRING_free(pval);
182
183	return 0;
184	}
185
186/* In PKCS#8 DSA: you just get a private key integer and parameters in the
187 * AlgorithmIdentifier the pubkey must be recalculated.
188 */
189
190static int dsa_priv_decode(EVP_PKEY *pkey, PKCS8_PRIV_KEY_INFO *p8)
191	{
192	const unsigned char *p, *pm;
193	int pklen, pmlen;
194	int ptype;
195	void *pval;
196	ASN1_STRING *pstr;
197	X509_ALGOR *palg;
198	ASN1_INTEGER *privkey = NULL;
199	BN_CTX *ctx = NULL;
200
201	STACK_OF(ASN1_TYPE) *ndsa = NULL;
202	DSA *dsa = NULL;
203
204	if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8))
205		return 0;
206	X509_ALGOR_get0(NULL, &ptype, &pval, palg);
207
208	/* Check for broken DSA PKCS#8, UGH! */
209	if (*p == (V_ASN1_SEQUENCE|V_ASN1_CONSTRUCTED))
210		{
211		ASN1_TYPE *t1, *t2;
212	    	if(!(ndsa = d2i_ASN1_SEQUENCE_ANY(NULL, &p, pklen)))
213			goto decerr;
214		if (sk_ASN1_TYPE_num(ndsa) != 2)
215			goto decerr;
216		/* Handle Two broken types:
217	    	 * SEQUENCE {parameters, priv_key}
218		 * SEQUENCE {pub_key, priv_key}
219		 */
220
221		t1 = sk_ASN1_TYPE_value(ndsa, 0);
222		t2 = sk_ASN1_TYPE_value(ndsa, 1);
223		if (t1->type == V_ASN1_SEQUENCE)
224			{
225			p8->broken = PKCS8_EMBEDDED_PARAM;
226			pval = t1->value.ptr;
227			}
228		else if (ptype == V_ASN1_SEQUENCE)
229			p8->broken = PKCS8_NS_DB;
230		else
231			goto decerr;
232
233		if (t2->type != V_ASN1_INTEGER)
234			goto decerr;
235
236		privkey = t2->value.integer;
237		}
238	else
239		{
240		const unsigned char *q = p;
241		if (!(privkey=d2i_ASN1_INTEGER(NULL, &p, pklen)))
242			goto decerr;
243		if (privkey->type == V_ASN1_NEG_INTEGER)
244			{
245			p8->broken = PKCS8_NEG_PRIVKEY;
246			ASN1_INTEGER_free(privkey);
247			if (!(privkey=d2i_ASN1_UINTEGER(NULL, &q, pklen)))
248				goto decerr;
249			}
250		if (ptype != V_ASN1_SEQUENCE)
251			goto decerr;
252		}
253
254	pstr = pval;
255	pm = pstr->data;
256	pmlen = pstr->length;
257	if (!(dsa = d2i_DSAparams(NULL, &pm, pmlen)))
258		goto decerr;
259	/* We have parameters now set private key */
260	if (!(dsa->priv_key = ASN1_INTEGER_to_BN(privkey, NULL)))
261		{
262		DSAerr(DSA_F_DSA_PRIV_DECODE,DSA_R_BN_ERROR);
263		goto dsaerr;
264		}
265	/* Calculate public key */
266	if (!(dsa->pub_key = BN_new()))
267		{
268		DSAerr(DSA_F_DSA_PRIV_DECODE, ERR_R_MALLOC_FAILURE);
269		goto dsaerr;
270		}
271	if (!(ctx = BN_CTX_new()))
272		{
273		DSAerr(DSA_F_DSA_PRIV_DECODE, ERR_R_MALLOC_FAILURE);
274		goto dsaerr;
275		}
276
277	if (!BN_mod_exp(dsa->pub_key, dsa->g, dsa->priv_key, dsa->p, ctx))
278		{
279		DSAerr(DSA_F_DSA_PRIV_DECODE,DSA_R_BN_ERROR);
280		goto dsaerr;
281		}
282
283	EVP_PKEY_assign_DSA(pkey, dsa);
284	BN_CTX_free (ctx);
285	if(ndsa)
286		sk_ASN1_TYPE_pop_free(ndsa, ASN1_TYPE_free);
287	else
288		ASN1_INTEGER_free(privkey);
289
290	return 1;
291
292	decerr:
293	DSAerr(DSA_F_DSA_PRIV_DECODE, EVP_R_DECODE_ERROR);
294	dsaerr:
295	BN_CTX_free (ctx);
296	if (privkey)
297		ASN1_INTEGER_free(privkey);
298	sk_ASN1_TYPE_pop_free(ndsa, ASN1_TYPE_free);
299	DSA_free(dsa);
300	return 0;
301	}
302
303static int dsa_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey)
304{
305	ASN1_STRING *params = NULL;
306	ASN1_INTEGER *prkey = NULL;
307	unsigned char *dp = NULL;
308	int dplen;
309
310	if (!pkey->pkey.dsa || !pkey->pkey.dsa->priv_key)
311		{
312		DSAerr(DSA_F_DSA_PRIV_ENCODE,DSA_R_MISSING_PARAMETERS);
313		goto err;
314		}
315
316	params = ASN1_STRING_new();
317
318	if (!params)
319		{
320		DSAerr(DSA_F_DSA_PRIV_ENCODE,ERR_R_MALLOC_FAILURE);
321		goto err;
322		}
323
324	params->length = i2d_DSAparams(pkey->pkey.dsa, &params->data);
325	if (params->length <= 0)
326		{
327		DSAerr(DSA_F_DSA_PRIV_ENCODE,ERR_R_MALLOC_FAILURE);
328		goto err;
329		}
330	params->type = V_ASN1_SEQUENCE;
331
332	/* Get private key into integer */
333	prkey = BN_to_ASN1_INTEGER(pkey->pkey.dsa->priv_key, NULL);
334
335	if (!prkey)
336		{
337		DSAerr(DSA_F_DSA_PRIV_ENCODE,DSA_R_BN_ERROR);
338		goto err;
339		}
340
341	dplen = i2d_ASN1_INTEGER(prkey, &dp);
342
343	ASN1_INTEGER_free(prkey);
344
345	if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(NID_dsa), 0,
346				V_ASN1_SEQUENCE, params, dp, dplen))
347		goto err;
348
349	return 1;
350
351err:
352	if (dp != NULL)
353		OPENSSL_free(dp);
354	if (params != NULL)
355		ASN1_STRING_free(params);
356	if (prkey != NULL)
357		ASN1_INTEGER_free(prkey);
358	return 0;
359}
360
361static int int_dsa_size(const EVP_PKEY *pkey)
362	{
363	return(DSA_size(pkey->pkey.dsa));
364	}
365
366static int dsa_bits(const EVP_PKEY *pkey)
367	{
368	return BN_num_bits(pkey->pkey.dsa->p);
369	}
370
371static int dsa_missing_parameters(const EVP_PKEY *pkey)
372	{
373	DSA *dsa;
374	dsa=pkey->pkey.dsa;
375	if ((dsa->p == NULL) || (dsa->q == NULL) || (dsa->g == NULL))
376			return 1;
377	return 0;
378	}
379
380static int dsa_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from)
381	{
382	BIGNUM *a;
383
384	if ((a=BN_dup(from->pkey.dsa->p)) == NULL)
385		return 0;
386	if (to->pkey.dsa->p != NULL)
387		BN_free(to->pkey.dsa->p);
388	to->pkey.dsa->p=a;
389
390	if ((a=BN_dup(from->pkey.dsa->q)) == NULL)
391		return 0;
392	if (to->pkey.dsa->q != NULL)
393		BN_free(to->pkey.dsa->q);
394	to->pkey.dsa->q=a;
395
396	if ((a=BN_dup(from->pkey.dsa->g)) == NULL)
397		return 0;
398	if (to->pkey.dsa->g != NULL)
399		BN_free(to->pkey.dsa->g);
400	to->pkey.dsa->g=a;
401	return 1;
402	}
403
404static int dsa_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b)
405	{
406	if (	BN_cmp(a->pkey.dsa->p,b->pkey.dsa->p) ||
407		BN_cmp(a->pkey.dsa->q,b->pkey.dsa->q) ||
408		BN_cmp(a->pkey.dsa->g,b->pkey.dsa->g))
409		return 0;
410	else
411		return 1;
412	}
413
414static int dsa_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
415	{
416	if (BN_cmp(b->pkey.dsa->pub_key,a->pkey.dsa->pub_key) != 0)
417		return 0;
418	else
419		return 1;
420	}
421
422static void int_dsa_free(EVP_PKEY *pkey)
423	{
424	DSA_free(pkey->pkey.dsa);
425	}
426
427static void update_buflen(const BIGNUM *b, size_t *pbuflen)
428	{
429	size_t i;
430	if (!b)
431		return;
432	if (*pbuflen < (i = (size_t)BN_num_bytes(b)))
433			*pbuflen = i;
434	}
435
436static int do_dsa_print(BIO *bp, const DSA *x, int off, int ptype)
437	{
438	unsigned char *m=NULL;
439	int ret=0;
440	size_t buf_len=0;
441	const char *ktype = NULL;
442
443	const BIGNUM *priv_key, *pub_key;
444
445	if (ptype == 2)
446		priv_key = x->priv_key;
447	else
448		priv_key = NULL;
449
450	if (ptype > 0)
451		pub_key = x->pub_key;
452	else
453		pub_key = NULL;
454
455	if (ptype == 2)
456		ktype = "Private-Key";
457	else if (ptype == 1)
458		ktype = "Public-Key";
459	else
460		ktype = "DSA-Parameters";
461
462	update_buflen(x->p, &buf_len);
463	update_buflen(x->q, &buf_len);
464	update_buflen(x->g, &buf_len);
465	update_buflen(priv_key, &buf_len);
466	update_buflen(pub_key, &buf_len);
467
468	m=(unsigned char *)OPENSSL_malloc(buf_len+10);
469	if (m == NULL)
470		{
471		DSAerr(DSA_F_DO_DSA_PRINT,ERR_R_MALLOC_FAILURE);
472		goto err;
473		}
474
475	if (priv_key)
476		{
477		if(!BIO_indent(bp,off,128))
478		   goto err;
479		if (BIO_printf(bp,"%s: (%d bit)\n",ktype, BN_num_bits(x->p))
480			<= 0) goto err;
481		}
482
483	if (!ASN1_bn_print(bp,"priv:",priv_key,m,off))
484		goto err;
485	if (!ASN1_bn_print(bp,"pub: ",pub_key,m,off))
486		goto err;
487	if (!ASN1_bn_print(bp,"P:   ",x->p,m,off)) goto err;
488	if (!ASN1_bn_print(bp,"Q:   ",x->q,m,off)) goto err;
489	if (!ASN1_bn_print(bp,"G:   ",x->g,m,off)) goto err;
490	ret=1;
491err:
492	if (m != NULL) OPENSSL_free(m);
493	return(ret);
494	}
495
496static int dsa_param_decode(EVP_PKEY *pkey,
497					const unsigned char **pder, int derlen)
498	{
499	DSA *dsa;
500	if (!(dsa = d2i_DSAparams(NULL, pder, derlen)))
501		{
502		DSAerr(DSA_F_DSA_PARAM_DECODE, ERR_R_DSA_LIB);
503		return 0;
504		}
505	EVP_PKEY_assign_DSA(pkey, dsa);
506	return 1;
507	}
508
509static int dsa_param_encode(const EVP_PKEY *pkey, unsigned char **pder)
510	{
511	return i2d_DSAparams(pkey->pkey.dsa, pder);
512	}
513
514static int dsa_param_print(BIO *bp, const EVP_PKEY *pkey, int indent,
515							ASN1_PCTX *ctx)
516	{
517	return do_dsa_print(bp, pkey->pkey.dsa, indent, 0);
518	}
519
520static int dsa_pub_print(BIO *bp, const EVP_PKEY *pkey, int indent,
521							ASN1_PCTX *ctx)
522	{
523	return do_dsa_print(bp, pkey->pkey.dsa, indent, 1);
524	}
525
526
527static int dsa_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent,
528							ASN1_PCTX *ctx)
529	{
530	return do_dsa_print(bp, pkey->pkey.dsa, indent, 2);
531	}
532
533static int old_dsa_priv_decode(EVP_PKEY *pkey,
534					const unsigned char **pder, int derlen)
535	{
536	DSA *dsa;
537	if (!(dsa = d2i_DSAPrivateKey (NULL, pder, derlen)))
538		{
539		DSAerr(DSA_F_OLD_DSA_PRIV_DECODE, ERR_R_DSA_LIB);
540		return 0;
541		}
542	EVP_PKEY_assign_DSA(pkey, dsa);
543	return 1;
544	}
545
546static int old_dsa_priv_encode(const EVP_PKEY *pkey, unsigned char **pder)
547	{
548	return i2d_DSAPrivateKey(pkey->pkey.dsa, pder);
549	}
550
551static int dsa_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2)
552	{
553	switch (op)
554		{
555		case ASN1_PKEY_CTRL_PKCS7_SIGN:
556		if (arg1 == 0)
557			{
558			int snid, hnid;
559			X509_ALGOR *alg1, *alg2;
560			PKCS7_SIGNER_INFO_get0_algs(arg2, NULL, &alg1, &alg2);
561			if (alg1 == NULL || alg1->algorithm == NULL)
562				return -1;
563			hnid = OBJ_obj2nid(alg1->algorithm);
564			if (hnid == NID_undef)
565				return -1;
566			if (!OBJ_find_sigid_by_algs(&snid, hnid, EVP_PKEY_id(pkey)))
567				return -1;
568			X509_ALGOR_set0(alg2, OBJ_nid2obj(snid), V_ASN1_UNDEF, 0);
569			}
570		return 1;
571#ifndef OPENSSL_NO_CMS
572		case ASN1_PKEY_CTRL_CMS_SIGN:
573		if (arg1 == 0)
574			{
575			int snid, hnid;
576			X509_ALGOR *alg1, *alg2;
577			CMS_SignerInfo_get0_algs(arg2, NULL, NULL, &alg1, &alg2);
578			if (alg1 == NULL || alg1->algorithm == NULL)
579				return -1;
580			hnid = OBJ_obj2nid(alg1->algorithm);
581			if (hnid == NID_undef)
582				return -1;
583			if (!OBJ_find_sigid_by_algs(&snid, hnid, EVP_PKEY_id(pkey)))
584				return -1;
585			X509_ALGOR_set0(alg2, OBJ_nid2obj(snid), V_ASN1_UNDEF, 0);
586			}
587		return 1;
588#endif
589
590		case ASN1_PKEY_CTRL_DEFAULT_MD_NID:
591		*(int *)arg2 = NID_sha1;
592		return 2;
593
594		default:
595		return -2;
596
597		}
598
599	}
600
601/* NB these are sorted in pkey_id order, lowest first */
602
603const EVP_PKEY_ASN1_METHOD dsa_asn1_meths[] =
604	{
605
606		{
607		EVP_PKEY_DSA2,
608		EVP_PKEY_DSA,
609		ASN1_PKEY_ALIAS
610		},
611
612		{
613		EVP_PKEY_DSA1,
614		EVP_PKEY_DSA,
615		ASN1_PKEY_ALIAS
616		},
617
618		{
619		EVP_PKEY_DSA4,
620		EVP_PKEY_DSA,
621		ASN1_PKEY_ALIAS
622		},
623
624		{
625		EVP_PKEY_DSA3,
626		EVP_PKEY_DSA,
627		ASN1_PKEY_ALIAS
628		},
629
630		{
631		EVP_PKEY_DSA,
632		EVP_PKEY_DSA,
633		0,
634
635		"DSA",
636		"OpenSSL DSA method",
637
638		dsa_pub_decode,
639		dsa_pub_encode,
640		dsa_pub_cmp,
641		dsa_pub_print,
642
643		dsa_priv_decode,
644		dsa_priv_encode,
645		dsa_priv_print,
646
647		int_dsa_size,
648		dsa_bits,
649
650		dsa_param_decode,
651		dsa_param_encode,
652		dsa_missing_parameters,
653		dsa_copy_parameters,
654		dsa_cmp_parameters,
655		dsa_param_print,
656
657		int_dsa_free,
658		dsa_pkey_ctrl,
659		old_dsa_priv_decode,
660		old_dsa_priv_encode
661		}
662	};
663