1/* $OpenBSD: t_x509.c,v 1.45 2024/04/09 13:55:02 beck Exp $ */
2/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
4 *
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
8 *
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to.  The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 *
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the copyright
27 *    notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 *    notice, this list of conditions and the following disclaimer in the
30 *    documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 *    must display the following acknowledgement:
33 *    "This product includes cryptographic software written by
34 *     Eric Young (eay@cryptsoft.com)"
35 *    The word 'cryptographic' can be left out if the rouines from the library
36 *    being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 *    the apps directory (application code) you must include an acknowledgement:
39 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 *
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * SUCH DAMAGE.
52 *
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed.  i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
57 */
58
59#include <stdio.h>
60
61#include <openssl/opensslconf.h>
62
63#include <openssl/bn.h>
64#include <openssl/buffer.h>
65#include <openssl/err.h>
66#include <openssl/objects.h>
67#include <openssl/x509.h>
68#include <openssl/x509v3.h>
69
70#ifndef OPENSSL_NO_DSA
71#include <openssl/dsa.h>
72#endif
73#ifndef OPENSSL_NO_EC
74#include <openssl/ec.h>
75#endif
76#ifndef OPENSSL_NO_RSA
77#include <openssl/rsa.h>
78#endif
79
80#include "evp_local.h"
81#include "x509_local.h"
82
83int
84X509_print_fp(FILE *fp, X509 *x)
85{
86	return X509_print_ex_fp(fp, x, XN_FLAG_COMPAT, X509_FLAG_COMPAT);
87}
88LCRYPTO_ALIAS(X509_print_fp);
89
90int
91X509_print_ex_fp(FILE *fp, X509 *x, unsigned long nmflag, unsigned long cflag)
92{
93	BIO *b;
94	int ret;
95
96	if ((b = BIO_new(BIO_s_file())) == NULL) {
97		X509error(ERR_R_BUF_LIB);
98		return (0);
99	}
100	BIO_set_fp(b, fp, BIO_NOCLOSE);
101	ret = X509_print_ex(b, x, nmflag, cflag);
102	BIO_free(b);
103	return (ret);
104}
105LCRYPTO_ALIAS(X509_print_ex_fp);
106
107int
108X509_print(BIO *bp, X509 *x)
109{
110	return X509_print_ex(bp, x, XN_FLAG_COMPAT, X509_FLAG_COMPAT);
111}
112LCRYPTO_ALIAS(X509_print);
113
114int
115X509_print_ex(BIO *bp, X509 *x, unsigned long nmflags, unsigned long cflag)
116{
117	long l;
118	int ret = 0, i;
119	char *m = NULL, mlch = ' ';
120	int nmindent = 0;
121	X509_CINF *ci;
122	ASN1_INTEGER *bs;
123	EVP_PKEY *pkey = NULL;
124
125	if ((nmflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
126		mlch = '\n';
127		nmindent = 12;
128	}
129
130	if (nmflags == X509_FLAG_COMPAT)
131		nmindent = 16;
132
133	ci = x->cert_info;
134	if (!(cflag & X509_FLAG_NO_HEADER)) {
135		if (BIO_write(bp, "Certificate:\n", 13) <= 0)
136			goto err;
137		if (BIO_write(bp, "    Data:\n", 10) <= 0)
138			goto err;
139	}
140	if (!(cflag & X509_FLAG_NO_VERSION)) {
141		l = X509_get_version(x);
142		if (l >= 0 && l <= 2) {
143			if (BIO_printf(bp, "%8sVersion: %ld (0x%lx)\n",
144			    "", l + 1, l) <= 0)
145				goto err;
146		} else {
147			if (BIO_printf(bp, "%8sVersion: unknown (%ld)\n",
148			    "", l) <= 0)
149				goto err;
150		}
151	}
152	if (!(cflag & X509_FLAG_NO_SERIAL)) {
153		if (BIO_write(bp, "        Serial Number:", 22) <= 0)
154			goto err;
155
156		bs = X509_get_serialNumber(x);
157		l = -1;
158		if (bs->length <= (int)sizeof(long))
159			l = ASN1_INTEGER_get(bs);
160		if (l >= 0) {
161			if (BIO_printf(bp, " %ld (0x%lx)\n", l, l) <= 0)
162				goto err;
163		} else {
164			const char *neg = "";
165
166			if (bs->type == V_ASN1_NEG_INTEGER)
167				neg = " (Negative)";
168
169			if (BIO_printf(bp, "\n%12s%s", "", neg) <= 0)
170				goto err;
171			for (i = 0; i < bs->length; i++) {
172				if (BIO_printf(bp, "%02x%c", bs->data[i],
173				    ((i + 1 == bs->length) ? '\n' : ':')) <= 0)
174					goto err;
175			}
176		}
177
178	}
179
180	if (!(cflag & X509_FLAG_NO_SIGNAME)) {
181		if (X509_signature_print(bp, x->sig_alg, NULL) <= 0)
182			goto err;
183	}
184
185	if (!(cflag & X509_FLAG_NO_ISSUER)) {
186		if (BIO_printf(bp, "        Issuer:%c", mlch) <= 0)
187			goto err;
188		if (X509_NAME_print_ex(bp, X509_get_issuer_name(x),
189		    nmindent, nmflags) < (nmflags == X509_FLAG_COMPAT ? 1 : 0))
190			goto err;
191		if (BIO_write(bp, "\n", 1) <= 0)
192			goto err;
193	}
194	if (!(cflag & X509_FLAG_NO_VALIDITY)) {
195		if (BIO_write(bp, "        Validity\n", 17) <= 0)
196			goto err;
197		if (BIO_write(bp, "            Not Before: ", 24) <= 0)
198			goto err;
199		if (!ASN1_TIME_print(bp, X509_get_notBefore(x)))
200			goto err;
201		if (BIO_write(bp, "\n            Not After : ", 25) <= 0)
202			goto err;
203		if (!ASN1_TIME_print(bp, X509_get_notAfter(x)))
204			goto err;
205		if (BIO_write(bp, "\n", 1) <= 0)
206			goto err;
207	}
208	if (!(cflag & X509_FLAG_NO_SUBJECT)) {
209		if (BIO_printf(bp, "        Subject:%c", mlch) <= 0)
210			goto err;
211		if (X509_NAME_print_ex(bp, X509_get_subject_name(x),
212		    nmindent, nmflags) < (nmflags == X509_FLAG_COMPAT ? 1 : 0))
213			goto err;
214		if (BIO_write(bp, "\n", 1) <= 0)
215			goto err;
216	}
217	if (!(cflag & X509_FLAG_NO_PUBKEY)) {
218		if (BIO_write(bp, "        Subject Public Key Info:\n",
219		    33) <= 0)
220			goto err;
221		if (BIO_printf(bp, "%12sPublic Key Algorithm: ", "") <= 0)
222			goto err;
223		if (i2a_ASN1_OBJECT(bp, ci->key->algor->algorithm) <= 0)
224			goto err;
225		if (BIO_puts(bp, "\n") <= 0)
226			goto err;
227
228		pkey = X509_get_pubkey(x);
229		if (pkey == NULL) {
230			BIO_printf(bp, "%12sUnable to load Public Key\n", "");
231			ERR_print_errors(bp);
232		} else {
233			EVP_PKEY_print_public(bp, pkey, 16, NULL);
234			EVP_PKEY_free(pkey);
235		}
236	}
237
238	if (!(cflag & X509_FLAG_NO_EXTENSIONS))
239		X509V3_extensions_print(bp, "X509v3 extensions",
240		    ci->extensions, cflag, 8);
241
242	if (!(cflag & X509_FLAG_NO_SIGDUMP)) {
243		if (X509_signature_print(bp, x->sig_alg, x->signature) <= 0)
244			goto err;
245	}
246	if (!(cflag & X509_FLAG_NO_AUX)) {
247		if (!X509_CERT_AUX_print(bp, x->aux, 0))
248			goto err;
249	}
250	ret = 1;
251
252 err:
253	free(m);
254	return (ret);
255}
256LCRYPTO_ALIAS(X509_print_ex);
257
258int
259X509_ocspid_print(BIO *bp, X509 *x)
260{
261	unsigned char *der = NULL;
262	unsigned char *dertmp;
263	int derlen;
264	int i;
265	unsigned char SHA1md[SHA_DIGEST_LENGTH];
266
267	/* display the hash of the subject as it would appear
268	   in OCSP requests */
269	if (BIO_printf(bp, "        Subject OCSP hash: ") <= 0)
270		goto err;
271	if ((derlen = i2d_X509_NAME(x->cert_info->subject, NULL)) <= 0)
272		goto err;
273	if ((der = dertmp = malloc(derlen)) == NULL)
274		goto err;
275	if (i2d_X509_NAME(x->cert_info->subject, &dertmp) <= 0)
276		goto err;
277
278	if (!EVP_Digest(der, derlen, SHA1md, NULL, EVP_sha1(), NULL))
279		goto err;
280	for (i = 0; i < SHA_DIGEST_LENGTH; i++) {
281		if (BIO_printf(bp, "%02X", SHA1md[i]) <= 0)
282			goto err;
283	}
284	free (der);
285	der = NULL;
286
287	/* display the hash of the public key as it would appear
288	   in OCSP requests */
289	if (BIO_printf(bp, "\n        Public key OCSP hash: ") <= 0)
290		goto err;
291
292	if (!EVP_Digest(x->cert_info->key->public_key->data,
293	    x->cert_info->key->public_key->length,
294	    SHA1md, NULL, EVP_sha1(), NULL))
295		goto err;
296	for (i = 0; i < SHA_DIGEST_LENGTH; i++) {
297		if (BIO_printf(bp, "%02X", SHA1md[i]) <= 0)
298			goto err;
299	}
300	BIO_printf(bp, "\n");
301
302	return (1);
303
304 err:
305	free(der);
306	return (0);
307}
308LCRYPTO_ALIAS(X509_ocspid_print);
309
310int
311X509_signature_dump(BIO *bp, const ASN1_STRING *sig, int indent)
312{
313	const unsigned char *s;
314	int i, n;
315
316	n = sig->length;
317	s = sig->data;
318	for (i = 0; i < n; i++) {
319		if ((i % 18) == 0) {
320			if (BIO_write(bp, "\n", 1) <= 0)
321				return 0;
322			if (BIO_indent(bp, indent, indent) <= 0)
323				return 0;
324		}
325		if (BIO_printf(bp, "%02x%s", s[i],
326		    ((i + 1) == n) ? "" : ":") <= 0)
327			return 0;
328	}
329	if (BIO_write(bp, "\n", 1) != 1)
330		return 0;
331
332	return 1;
333}
334LCRYPTO_ALIAS(X509_signature_dump);
335
336int
337X509_signature_print(BIO *bp, const X509_ALGOR *sigalg, const ASN1_STRING *sig)
338{
339	int sig_nid;
340	if (BIO_puts(bp, "    Signature Algorithm: ") <= 0)
341		return 0;
342	if (i2a_ASN1_OBJECT(bp, sigalg->algorithm) <= 0)
343		return 0;
344
345	sig_nid = OBJ_obj2nid(sigalg->algorithm);
346	if (sig_nid != NID_undef) {
347		int pkey_nid, dig_nid;
348		const EVP_PKEY_ASN1_METHOD *ameth;
349		if (OBJ_find_sigid_algs(sig_nid, &dig_nid, &pkey_nid)) {
350			ameth = EVP_PKEY_asn1_find(NULL, pkey_nid);
351			if (ameth && ameth->sig_print)
352				return ameth->sig_print(bp, sigalg, sig, 9, 0);
353		}
354	}
355	if (sig)
356		return X509_signature_dump(bp, sig, 9);
357	else if (BIO_puts(bp, "\n") <= 0)
358		return 0;
359	return 1;
360}
361LCRYPTO_ALIAS(X509_signature_print);
362
363int
364ASN1_TIME_print(BIO *bp, const ASN1_TIME *tm)
365{
366	if (tm->type == V_ASN1_UTCTIME)
367		return ASN1_UTCTIME_print(bp, tm);
368	if (tm->type == V_ASN1_GENERALIZEDTIME)
369		return ASN1_GENERALIZEDTIME_print(bp, tm);
370	BIO_write(bp, "Bad time value", 14);
371	return (0);
372}
373LCRYPTO_ALIAS(ASN1_TIME_print);
374
375static const char *mon[12] = {
376	"Jan", "Feb", "Mar", "Apr", "May", "Jun",
377	"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
378};
379
380int
381ASN1_GENERALIZEDTIME_print(BIO *bp, const ASN1_GENERALIZEDTIME *tm)
382{
383	char *v;
384	int gmt = 0;
385	int i;
386	int y = 0, M = 0, d = 0, h = 0, m = 0, s = 0;
387	char *f = "";
388	int f_len = 0;
389
390	i = tm->length;
391	v = (char *)tm->data;
392
393	if (i < 12)
394		goto err;
395	if (v[i-1] == 'Z')
396		gmt = 1;
397	for (i = 0; i < 12; i++)
398		if ((v[i] > '9') || (v[i] < '0'))
399			goto err;
400	y = (v[0] - '0') * 1000 + (v[1] - '0') * 100 +
401	    (v[2] - '0') * 10 + (v[3] - '0');
402	M = (v[4] - '0') * 10 + (v[5] - '0');
403	if ((M > 12) || (M < 1))
404		goto err;
405	d = (v[6] - '0') * 10 + (v[7] - '0');
406	h = (v[8] - '0') * 10 + (v[9] - '0');
407	m = (v[10] - '0') * 10 + (v[11] - '0');
408	if (tm->length >= 14 &&
409	    (v[12] >= '0') && (v[12] <= '9') &&
410	    (v[13] >= '0') && (v[13] <= '9')) {
411		s =  (v[12] - '0') * 10 + (v[13] - '0');
412		/* Check for fractions of seconds. */
413		if (tm->length >= 15 && v[14] == '.') {
414			int l = tm->length;
415			f = &v[14];	/* The decimal point. */
416			f_len = 1;
417			while (14 + f_len < l && f[f_len] >= '0' &&
418			    f[f_len] <= '9')
419				++f_len;
420		}
421	}
422
423	if (BIO_printf(bp, "%s %2d %02d:%02d:%02d%.*s %d%s",
424	    mon[M - 1], d, h, m, s, f_len, f, y, (gmt) ? " GMT" : "") <= 0)
425		return (0);
426	else
427		return (1);
428
429 err:
430	BIO_write(bp, "Bad time value", 14);
431	return (0);
432}
433LCRYPTO_ALIAS(ASN1_GENERALIZEDTIME_print);
434
435int
436ASN1_UTCTIME_print(BIO *bp, const ASN1_UTCTIME *tm)
437{
438	const char *v;
439	int gmt = 0;
440	int i;
441	int y = 0, M = 0, d = 0, h = 0, m = 0, s = 0;
442
443	i = tm->length;
444	v = (const char *)tm->data;
445
446	if (i < 10)
447		goto err;
448	if (v[i-1] == 'Z')
449		gmt = 1;
450	for (i = 0; i < 10; i++)
451		if ((v[i] > '9') || (v[i] < '0'))
452			goto err;
453	y = (v[0] - '0') * 10 + (v[1] - '0');
454	if (y < 50)
455		y += 100;
456	M = (v[2] - '0') * 10 + (v[3] - '0');
457	if ((M > 12) || (M < 1))
458		goto err;
459	d = (v[4] - '0') * 10 + (v[5] - '0');
460	h = (v[6] - '0') * 10 + (v[7] - '0');
461	m = (v[8] - '0') * 10 + (v[9] - '0');
462	if (tm->length >=12 &&
463	    (v[10] >= '0') && (v[10] <= '9') &&
464	    (v[11] >= '0') && (v[11] <= '9'))
465		s = (v[10] - '0') * 10 + (v[11] - '0');
466
467	if (BIO_printf(bp, "%s %2d %02d:%02d:%02d %d%s",
468	    mon[M - 1], d, h, m, s, y + 1900, (gmt) ? " GMT" : "") <= 0)
469		return (0);
470	else
471		return (1);
472
473 err:
474	BIO_write(bp, "Bad time value", 14);
475	return (0);
476}
477LCRYPTO_ALIAS(ASN1_UTCTIME_print);
478
479int
480X509_NAME_print(BIO *bp, const X509_NAME *name, int obase)
481{
482	char *s, *c, *b;
483	int i;
484	int ret = 0;
485
486	b = X509_NAME_oneline(name, NULL, 0);
487	if (b == NULL)
488		return 0;
489	if (*b == '\0') {
490		free(b);
491		return 1;
492	}
493	s = b + 1; /* skip the first slash */
494
495	c = s;
496	for (;;) {
497		if (((*s == '/') &&
498		    ((s[1] >= 'A') && (s[1] <= 'Z') &&
499		    ((s[2] == '=') || ((s[2] >= 'A') && (s[2] <= 'Z') &&
500		    (s[3] == '='))))) || (*s == '\0')) {
501			i = s - c;
502			if (BIO_write(bp, c, i) != i)
503				goto err;
504			c = s + 1;	/* skip following slash */
505			if (*s != '\0') {
506				if (BIO_write(bp, ", ", 2) != 2)
507					goto err;
508			}
509		}
510		if (*s == '\0')
511			break;
512		s++;
513	}
514
515	ret = 1;
516	if (0) {
517 err:
518		X509error(ERR_R_BUF_LIB);
519	}
520	free(b);
521	return (ret);
522}
523LCRYPTO_ALIAS(X509_NAME_print);
524