summaryrefslogtreecommitdiff
path: root/src/usr.bin/openssl
diff options
context:
space:
mode:
authorjsing <>2014-08-26 17:47:25 +0000
committerjsing <>2014-08-26 17:47:25 +0000
commitf3755acd5513f85ff734de6a822b6f804d3776ce (patch)
tree1f859a78eae941040f58599de8c0e1e56d61fdad /src/usr.bin/openssl
parent0779b9f30aa9875c290af18a4362799668829707 (diff)
downloadopenbsd-f3755acd5513f85ff734de6a822b6f804d3776ce.tar.gz
openbsd-f3755acd5513f85ff734de6a822b6f804d3776ce.tar.bz2
openbsd-f3755acd5513f85ff734de6a822b6f804d3776ce.zip
Move openssl(1) from /usr/sbin/openssl to /usr/bin/openssl, since it is not
a system/superuser binary. At the same time, move the source code from its current lib/libssl/src/apps location to a more appropriate home under usr.bin/openssl. ok deraadt@ miod@
Diffstat (limited to 'src/usr.bin/openssl')
-rw-r--r--src/usr.bin/openssl/Makefile27
-rw-r--r--src/usr.bin/openssl/apps.c2220
-rw-r--r--src/usr.bin/openssl/apps.h285
-rw-r--r--src/usr.bin/openssl/asn1pars.c406
-rw-r--r--src/usr.bin/openssl/ca.c2743
-rw-r--r--src/usr.bin/openssl/ciphers.c194
-rw-r--r--src/usr.bin/openssl/cms.c1154
-rw-r--r--src/usr.bin/openssl/crl.c415
-rw-r--r--src/usr.bin/openssl/crl2p7.c314
-rw-r--r--src/usr.bin/openssl/dgst.c547
-rw-r--r--src/usr.bin/openssl/dh.c308
-rw-r--r--src/usr.bin/openssl/dhparam.c472
-rw-r--r--src/usr.bin/openssl/dsa.c332
-rw-r--r--src/usr.bin/openssl/dsaparam.c414
-rw-r--r--src/usr.bin/openssl/ec.c341
-rw-r--r--src/usr.bin/openssl/ecparam.c613
-rw-r--r--src/usr.bin/openssl/enc.c649
-rw-r--r--src/usr.bin/openssl/engine.c494
-rw-r--r--src/usr.bin/openssl/errstr.c108
-rw-r--r--src/usr.bin/openssl/gendh.c204
-rw-r--r--src/usr.bin/openssl/gendsa.c230
-rw-r--r--src/usr.bin/openssl/genpkey.c383
-rw-r--r--src/usr.bin/openssl/genrsa.c286
-rw-r--r--src/usr.bin/openssl/nseq.c162
-rw-r--r--src/usr.bin/openssl/ocsp.c1217
-rw-r--r--src/usr.bin/openssl/openssl.110407
-rw-r--r--src/usr.bin/openssl/openssl.c639
-rw-r--r--src/usr.bin/openssl/passwd.c457
-rw-r--r--src/usr.bin/openssl/pkcs12.c913
-rw-r--r--src/usr.bin/openssl/pkcs7.c284
-rw-r--r--src/usr.bin/openssl/pkcs8.c367
-rw-r--r--src/usr.bin/openssl/pkey.c235
-rw-r--r--src/usr.bin/openssl/pkeyparam.c173
-rw-r--r--src/usr.bin/openssl/pkeyutl.c503
-rw-r--r--src/usr.bin/openssl/prime.c147
-rw-r--r--src/usr.bin/openssl/progs.h234
-rw-r--r--src/usr.bin/openssl/rand.c194
-rw-r--r--src/usr.bin/openssl/req.c1602
-rw-r--r--src/usr.bin/openssl/rsa.c392
-rw-r--r--src/usr.bin/openssl/rsautl.c341
-rw-r--r--src/usr.bin/openssl/s_apps.h147
-rw-r--r--src/usr.bin/openssl/s_cb.c854
-rw-r--r--src/usr.bin/openssl/s_client.c1507
-rw-r--r--src/usr.bin/openssl/s_server.c2154
-rw-r--r--src/usr.bin/openssl/s_socket.c351
-rw-r--r--src/usr.bin/openssl/s_time.c587
-rw-r--r--src/usr.bin/openssl/sess_id.c282
-rw-r--r--src/usr.bin/openssl/smime.c697
-rw-r--r--src/usr.bin/openssl/speed.c2170
-rw-r--r--src/usr.bin/openssl/spkac.c284
-rw-r--r--src/usr.bin/openssl/testdsa.h221
-rw-r--r--src/usr.bin/openssl/testrsa.h517
-rw-r--r--src/usr.bin/openssl/timeouts.h67
-rw-r--r--src/usr.bin/openssl/ts.c1102
-rw-r--r--src/usr.bin/openssl/verify.c339
-rw-r--r--src/usr.bin/openssl/version.c208
-rw-r--r--src/usr.bin/openssl/x509.c1160
57 files changed, 44053 insertions, 0 deletions
diff --git a/src/usr.bin/openssl/Makefile b/src/usr.bin/openssl/Makefile
new file mode 100644
index 0000000000..f4c9ed4f2b
--- /dev/null
+++ b/src/usr.bin/openssl/Makefile
@@ -0,0 +1,27 @@
1# $OpenBSD: Makefile,v 1.1 2014/08/26 17:47:24 jsing Exp $
2
3PROG= openssl
4LDADD= -lssl -lcrypto
5DPADD= ${LIBSSL} ${LIBCRYPTO}
6MAN1= openssl.1
7
8CFLAGS+= -Wall -Werror
9CFLAGS+= -Wformat
10CFLAGS+= -Wformat-security
11CFLAGS+= -Wimplicit
12CFLAGS+= -Wreturn-type
13#CFLAGS+= -Wshadow
14CFLAGS+= -Wtrigraphs
15CFLAGS+= -Wuninitialized
16CFLAGS+= -Wunused
17
18CFLAGS+= -DLIBRESSL_INTERNAL
19
20SRCS= apps.c asn1pars.c ca.c ciphers.c cms.c crl.c crl2p7.c dgst.c dh.c \
21 dhparam.c dsa.c dsaparam.c ec.c ecparam.c enc.c engine.c errstr.c \
22 gendh.c gendsa.c genpkey.c genrsa.c nseq.c ocsp.c openssl.c passwd.c \
23 pkcs12.c pkcs7.c pkcs8.c pkey.c pkeyparam.c pkeyutl.c prime.c rand.c \
24 req.c rsa.c rsautl.c s_cb.c s_client.c s_server.c s_socket.c s_time.c \
25 sess_id.c smime.c speed.c spkac.c ts.c verify.c version.c x509.c
26
27.include <bsd.prog.mk>
diff --git a/src/usr.bin/openssl/apps.c b/src/usr.bin/openssl/apps.c
new file mode 100644
index 0000000000..ac1c5107f1
--- /dev/null
+++ b/src/usr.bin/openssl/apps.c
@@ -0,0 +1,2220 @@
1/* $OpenBSD: apps.c,v 1.1 2014/08/26 17:47:24 jsing 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 * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in
70 * the documentation and/or other materials provided with the
71 * distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 * software must display the following acknowledgment:
75 * "This product includes software developed by the OpenSSL Project
76 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 * endorse or promote products derived from this software without
80 * prior written permission. For written permission, please contact
81 * openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 * nor may "OpenSSL" appear in their names without prior written
85 * permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 * acknowledgment:
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com). This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
111
112#include <sys/types.h>
113#include <sys/stat.h>
114#include <sys/times.h>
115
116#include <ctype.h>
117#include <errno.h>
118#include <stdio.h>
119#include <stdlib.h>
120#include <limits.h>
121#include <string.h>
122#include <strings.h>
123#include <unistd.h>
124
125#include "apps.h"
126
127#include <openssl/bn.h>
128#include <openssl/err.h>
129#include <openssl/pem.h>
130#include <openssl/pkcs12.h>
131#include <openssl/safestack.h>
132#include <openssl/ui.h>
133#include <openssl/x509.h>
134#include <openssl/x509v3.h>
135
136#ifndef OPENSSL_NO_ENGINE
137#include <openssl/engine.h>
138#endif
139
140#include <openssl/rsa.h>
141
142typedef struct {
143 const char *name;
144 unsigned long flag;
145 unsigned long mask;
146} NAME_EX_TBL;
147
148static UI_METHOD *ui_method = NULL;
149
150static int set_table_opts(unsigned long *flags, const char *arg,
151 const NAME_EX_TBL *in_tbl);
152static int set_multi_opts(unsigned long *flags, const char *arg,
153 const NAME_EX_TBL *in_tbl);
154
155#if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
156/* Looks like this stuff is worth moving into separate function */
157static EVP_PKEY *load_netscape_key(BIO *err, BIO *key, const char *file,
158 const char *key_descrip, int format);
159#endif
160
161int
162str2fmt(char *s)
163{
164 if (s == NULL)
165 return FORMAT_UNDEF;
166 if ((*s == 'D') || (*s == 'd'))
167 return (FORMAT_ASN1);
168 else if ((*s == 'T') || (*s == 't'))
169 return (FORMAT_TEXT);
170 else if ((*s == 'N') || (*s == 'n'))
171 return (FORMAT_NETSCAPE);
172 else if ((*s == 'S') || (*s == 's'))
173 return (FORMAT_SMIME);
174 else if ((*s == 'M') || (*s == 'm'))
175 return (FORMAT_MSBLOB);
176 else if ((*s == '1') ||
177 (strcmp(s, "PKCS12") == 0) || (strcmp(s, "pkcs12") == 0) ||
178 (strcmp(s, "P12") == 0) || (strcmp(s, "p12") == 0))
179 return (FORMAT_PKCS12);
180 else if ((*s == 'E') || (*s == 'e'))
181 return (FORMAT_ENGINE);
182 else if ((*s == 'P') || (*s == 'p')) {
183 if (s[1] == 'V' || s[1] == 'v')
184 return FORMAT_PVK;
185 else
186 return (FORMAT_PEM);
187 } else
188 return (FORMAT_UNDEF);
189}
190
191void
192program_name(char *in, char *out, int size)
193{
194 char *p;
195
196 p = strrchr(in, '/');
197 if (p != NULL)
198 p++;
199 else
200 p = in;
201 strlcpy(out, p, size);
202}
203
204int
205chopup_args(ARGS *arg, char *buf, int *argc, char **argv[])
206{
207 int num, i;
208 char *p;
209
210 *argc = 0;
211 *argv = NULL;
212
213 i = 0;
214 if (arg->count == 0) {
215 arg->count = 20;
216 arg->data = reallocarray(NULL, arg->count, sizeof(char *));
217 }
218 for (i = 0; i < arg->count; i++)
219 arg->data[i] = NULL;
220
221 num = 0;
222 p = buf;
223 for (;;) {
224 /* first scan over white space */
225 if (!*p)
226 break;
227 while (*p && ((*p == ' ') || (*p == '\t') || (*p == '\n')))
228 p++;
229 if (!*p)
230 break;
231
232 /* The start of something good :-) */
233 if (num >= arg->count) {
234 char **tmp_p;
235 int tlen = arg->count + 20;
236 tmp_p = reallocarray(arg->data, tlen, sizeof(char *));
237 if (tmp_p == NULL)
238 return 0;
239 arg->data = tmp_p;
240 arg->count = tlen;
241 /* initialize newly allocated data */
242 for (i = num; i < arg->count; i++)
243 arg->data[i] = NULL;
244 }
245 arg->data[num++] = p;
246
247 /* now look for the end of this */
248 if ((*p == '\'') || (*p == '\"')) { /* scan for closing
249 * quote */
250 i = *(p++);
251 arg->data[num - 1]++; /* jump over quote */
252 while (*p && (*p != i))
253 p++;
254 *p = '\0';
255 } else {
256 while (*p && ((*p != ' ') &&
257 (*p != '\t') && (*p != '\n')))
258 p++;
259
260 if (*p == '\0')
261 p--;
262 else
263 *p = '\0';
264 }
265 p++;
266 }
267 *argc = num;
268 *argv = arg->data;
269 return (1);
270}
271
272int
273dump_cert_text(BIO *out, X509 *x)
274{
275 char *p;
276
277 p = X509_NAME_oneline(X509_get_subject_name(x), NULL, 0);
278 BIO_puts(out, "subject=");
279 BIO_puts(out, p);
280 free(p);
281
282 p = X509_NAME_oneline(X509_get_issuer_name(x), NULL, 0);
283 BIO_puts(out, "\nissuer=");
284 BIO_puts(out, p);
285 BIO_puts(out, "\n");
286 free(p);
287
288 return 0;
289}
290
291static int
292ui_open(UI *ui)
293{
294 return UI_method_get_opener(UI_OpenSSL()) (ui);
295}
296
297static int
298ui_read(UI *ui, UI_STRING *uis)
299{
300 if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD &&
301 UI_get0_user_data(ui)) {
302 switch (UI_get_string_type(uis)) {
303 case UIT_PROMPT:
304 case UIT_VERIFY:
305 {
306 const char *password =
307 ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
308 if (password && password[0] != '\0') {
309 UI_set_result(ui, uis, password);
310 return 1;
311 }
312 }
313 break;
314 default:
315 break;
316 }
317 }
318 return UI_method_get_reader(UI_OpenSSL()) (ui, uis);
319}
320
321static int
322ui_write(UI *ui, UI_STRING *uis)
323{
324 if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD &&
325 UI_get0_user_data(ui)) {
326 switch (UI_get_string_type(uis)) {
327 case UIT_PROMPT:
328 case UIT_VERIFY:
329 {
330 const char *password =
331 ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
332 if (password && password[0] != '\0')
333 return 1;
334 }
335 break;
336 default:
337 break;
338 }
339 }
340 return UI_method_get_writer(UI_OpenSSL()) (ui, uis);
341}
342
343static int
344ui_close(UI *ui)
345{
346 return UI_method_get_closer(UI_OpenSSL()) (ui);
347}
348
349int
350setup_ui_method(void)
351{
352 ui_method = UI_create_method("OpenSSL application user interface");
353 UI_method_set_opener(ui_method, ui_open);
354 UI_method_set_reader(ui_method, ui_read);
355 UI_method_set_writer(ui_method, ui_write);
356 UI_method_set_closer(ui_method, ui_close);
357 return 0;
358}
359
360void
361destroy_ui_method(void)
362{
363 if (ui_method) {
364 UI_destroy_method(ui_method);
365 ui_method = NULL;
366 }
367}
368
369int
370password_callback(char *buf, int bufsiz, int verify, void *arg)
371{
372 PW_CB_DATA *cb_tmp = arg;
373 UI *ui = NULL;
374 int res = 0;
375 const char *prompt_info = NULL;
376 const char *password = NULL;
377 PW_CB_DATA *cb_data = (PW_CB_DATA *) cb_tmp;
378
379 if (cb_data) {
380 if (cb_data->password)
381 password = cb_data->password;
382 if (cb_data->prompt_info)
383 prompt_info = cb_data->prompt_info;
384 }
385 if (password) {
386 res = strlen(password);
387 if (res > bufsiz)
388 res = bufsiz;
389 memcpy(buf, password, res);
390 return res;
391 }
392 ui = UI_new_method(ui_method);
393 if (ui) {
394 int ok = 0;
395 char *buff = NULL;
396 int ui_flags = 0;
397 char *prompt = NULL;
398
399 prompt = UI_construct_prompt(ui, "pass phrase", prompt_info);
400
401 ui_flags |= UI_INPUT_FLAG_DEFAULT_PWD;
402 UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0);
403
404 if (ok >= 0)
405 ok = UI_add_input_string(ui, prompt, ui_flags, buf,
406 PW_MIN_LENGTH, bufsiz - 1);
407 if (ok >= 0 && verify) {
408 buff = malloc(bufsiz);
409 ok = UI_add_verify_string(ui, prompt, ui_flags, buff,
410 PW_MIN_LENGTH, bufsiz - 1, buf);
411 }
412 if (ok >= 0)
413 do {
414 ok = UI_process(ui);
415 } while (ok < 0 &&
416 UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0));
417
418 if (buff) {
419 OPENSSL_cleanse(buff, (unsigned int) bufsiz);
420 free(buff);
421 }
422 if (ok >= 0)
423 res = strlen(buf);
424 if (ok == -1) {
425 BIO_printf(bio_err, "User interface error\n");
426 ERR_print_errors(bio_err);
427 OPENSSL_cleanse(buf, (unsigned int) bufsiz);
428 res = 0;
429 }
430 if (ok == -2) {
431 BIO_printf(bio_err, "aborted!\n");
432 OPENSSL_cleanse(buf, (unsigned int) bufsiz);
433 res = 0;
434 }
435 UI_free(ui);
436 free(prompt);
437 }
438 return res;
439}
440
441static char *app_get_pass(BIO *err, char *arg, int keepbio);
442
443int
444app_passwd(BIO *err, char *arg1, char *arg2, char **pass1, char **pass2)
445{
446 int same;
447
448 if (!arg2 || !arg1 || strcmp(arg1, arg2))
449 same = 0;
450 else
451 same = 1;
452 if (arg1) {
453 *pass1 = app_get_pass(err, arg1, same);
454 if (!*pass1)
455 return 0;
456 } else if (pass1)
457 *pass1 = NULL;
458 if (arg2) {
459 *pass2 = app_get_pass(err, arg2, same ? 2 : 0);
460 if (!*pass2)
461 return 0;
462 } else if (pass2)
463 *pass2 = NULL;
464 return 1;
465}
466
467static char *
468app_get_pass(BIO *err, char *arg, int keepbio)
469{
470 char *tmp, tpass[APP_PASS_LEN];
471 static BIO *pwdbio = NULL;
472 const char *errstr = NULL;
473 int i;
474
475 if (!strncmp(arg, "pass:", 5))
476 return strdup(arg + 5);
477 if (!strncmp(arg, "env:", 4)) {
478 tmp = getenv(arg + 4);
479 if (!tmp) {
480 BIO_printf(err, "Can't read environment variable %s\n",
481 arg + 4);
482 return NULL;
483 }
484 return strdup(tmp);
485 }
486 if (!keepbio || !pwdbio) {
487 if (!strncmp(arg, "file:", 5)) {
488 pwdbio = BIO_new_file(arg + 5, "r");
489 if (!pwdbio) {
490 BIO_printf(err, "Can't open file %s\n",
491 arg + 5);
492 return NULL;
493 }
494 } else if (!strncmp(arg, "fd:", 3)) {
495 BIO *btmp;
496 i = strtonum(arg + 3, 0, INT_MAX, &errstr);
497 if (errstr) {
498 BIO_printf(err,
499 "Invalid file descriptor %s: %s\n",
500 arg, errstr);
501 return NULL;
502 }
503 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
504 if (!pwdbio) {
505 BIO_printf(err,
506 "Can't access file descriptor %s\n",
507 arg + 3);
508 return NULL;
509 }
510 /*
511 * Can't do BIO_gets on an fd BIO so add a buffering
512 * BIO
513 */
514 btmp = BIO_new(BIO_f_buffer());
515 pwdbio = BIO_push(btmp, pwdbio);
516 } else if (!strcmp(arg, "stdin")) {
517 pwdbio = BIO_new_fp(stdin, BIO_NOCLOSE);
518 if (!pwdbio) {
519 BIO_printf(err, "Can't open BIO for stdin\n");
520 return NULL;
521 }
522 } else {
523 BIO_printf(err, "Invalid password argument \"%s\"\n",
524 arg);
525 return NULL;
526 }
527 }
528 i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
529 if (keepbio != 1) {
530 BIO_free_all(pwdbio);
531 pwdbio = NULL;
532 }
533 if (i <= 0) {
534 BIO_printf(err, "Error reading password from BIO\n");
535 return NULL;
536 }
537 tmp = strchr(tpass, '\n');
538 if (tmp)
539 *tmp = 0;
540 return strdup(tpass);
541}
542
543int
544add_oid_section(BIO *err, CONF *conf)
545{
546 char *p;
547 STACK_OF(CONF_VALUE) *sktmp;
548 CONF_VALUE *cnf;
549 int i;
550
551 if (!(p = NCONF_get_string(conf, NULL, "oid_section"))) {
552 ERR_clear_error();
553 return 1;
554 }
555 if (!(sktmp = NCONF_get_section(conf, p))) {
556 BIO_printf(err, "problem loading oid section %s\n", p);
557 return 0;
558 }
559 for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
560 cnf = sk_CONF_VALUE_value(sktmp, i);
561 if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
562 BIO_printf(err, "problem creating object %s=%s\n",
563 cnf->name, cnf->value);
564 return 0;
565 }
566 }
567 return 1;
568}
569
570static int
571load_pkcs12(BIO *err, BIO *in, const char *desc, pem_password_cb *pem_cb,
572 void *cb_data, EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca)
573{
574 const char *pass;
575 char tpass[PEM_BUFSIZE];
576 int len, ret = 0;
577 PKCS12 *p12;
578
579 p12 = d2i_PKCS12_bio(in, NULL);
580 if (p12 == NULL) {
581 BIO_printf(err, "Error loading PKCS12 file for %s\n", desc);
582 goto die;
583 }
584 /* See if an empty password will do */
585 if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0))
586 pass = "";
587 else {
588 if (!pem_cb)
589 pem_cb = password_callback;
590 len = pem_cb(tpass, PEM_BUFSIZE, 0, cb_data);
591 if (len < 0) {
592 BIO_printf(err, "Passpharse callback error for %s\n",
593 desc);
594 goto die;
595 }
596 if (len < PEM_BUFSIZE)
597 tpass[len] = 0;
598 if (!PKCS12_verify_mac(p12, tpass, len)) {
599 BIO_printf(err,
600 "Mac verify error (wrong password?) in PKCS12 file for %s\n", desc);
601 goto die;
602 }
603 pass = tpass;
604 }
605 ret = PKCS12_parse(p12, pass, pkey, cert, ca);
606
607die:
608 if (p12)
609 PKCS12_free(p12);
610 return ret;
611}
612
613X509 *
614load_cert(BIO *err, const char *file, int format, const char *pass, ENGINE *e,
615 const char *cert_descrip)
616{
617 X509 *x = NULL;
618 BIO *cert;
619
620 if ((cert = BIO_new(BIO_s_file())) == NULL) {
621 ERR_print_errors(err);
622 goto end;
623 }
624 if (file == NULL) {
625 setvbuf(stdin, NULL, _IONBF, 0);
626 BIO_set_fp(cert, stdin, BIO_NOCLOSE);
627 } else {
628 if (BIO_read_filename(cert, file) <= 0) {
629 BIO_printf(err, "Error opening %s %s\n",
630 cert_descrip, file);
631 ERR_print_errors(err);
632 goto end;
633 }
634 }
635
636 if (format == FORMAT_ASN1)
637 x = d2i_X509_bio(cert, NULL);
638 else if (format == FORMAT_NETSCAPE) {
639 NETSCAPE_X509 *nx;
640 nx = ASN1_item_d2i_bio(ASN1_ITEM_rptr(NETSCAPE_X509),
641 cert, NULL);
642 if (nx == NULL)
643 goto end;
644
645 if ((strncmp(NETSCAPE_CERT_HDR, (char *) nx->header->data,
646 nx->header->length) != 0)) {
647 NETSCAPE_X509_free(nx);
648 BIO_printf(err,
649 "Error reading header on certificate\n");
650 goto end;
651 }
652 x = nx->cert;
653 nx->cert = NULL;
654 NETSCAPE_X509_free(nx);
655 } else if (format == FORMAT_PEM)
656 x = PEM_read_bio_X509_AUX(cert, NULL, password_callback, NULL);
657 else if (format == FORMAT_PKCS12) {
658 if (!load_pkcs12(err, cert, cert_descrip, NULL, NULL,
659 NULL, &x, NULL))
660 goto end;
661 } else {
662 BIO_printf(err, "bad input format specified for %s\n",
663 cert_descrip);
664 goto end;
665 }
666
667end:
668 if (x == NULL) {
669 BIO_printf(err, "unable to load certificate\n");
670 ERR_print_errors(err);
671 }
672 BIO_free(cert);
673 return (x);
674}
675
676EVP_PKEY *
677load_key(BIO *err, const char *file, int format, int maybe_stdin,
678 const char *pass, ENGINE *e, const char *key_descrip)
679{
680 BIO *key = NULL;
681 EVP_PKEY *pkey = NULL;
682 PW_CB_DATA cb_data;
683
684 cb_data.password = pass;
685 cb_data.prompt_info = file;
686
687 if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
688 BIO_printf(err, "no keyfile specified\n");
689 goto end;
690 }
691#ifndef OPENSSL_NO_ENGINE
692 if (format == FORMAT_ENGINE) {
693 if (!e)
694 BIO_printf(err, "no engine specified\n");
695 else {
696 pkey = ENGINE_load_private_key(e, file,
697 ui_method, &cb_data);
698 if (!pkey) {
699 BIO_printf(err, "cannot load %s from engine\n",
700 key_descrip);
701 ERR_print_errors(err);
702 }
703 }
704 goto end;
705 }
706#endif
707 key = BIO_new(BIO_s_file());
708 if (key == NULL) {
709 ERR_print_errors(err);
710 goto end;
711 }
712 if (file == NULL && maybe_stdin) {
713 setvbuf(stdin, NULL, _IONBF, 0);
714 BIO_set_fp(key, stdin, BIO_NOCLOSE);
715 } else if (BIO_read_filename(key, file) <= 0) {
716 BIO_printf(err, "Error opening %s %s\n",
717 key_descrip, file);
718 ERR_print_errors(err);
719 goto end;
720 }
721 if (format == FORMAT_ASN1) {
722 pkey = d2i_PrivateKey_bio(key, NULL);
723 } else if (format == FORMAT_PEM) {
724 pkey = PEM_read_bio_PrivateKey(key, NULL, password_callback, &cb_data);
725 }
726#if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
727 else if (format == FORMAT_NETSCAPE || format == FORMAT_IISSGC)
728 pkey = load_netscape_key(err, key, file, key_descrip, format);
729#endif
730 else if (format == FORMAT_PKCS12) {
731 if (!load_pkcs12(err, key, key_descrip, password_callback, &cb_data,
732 &pkey, NULL, NULL))
733 goto end;
734 }
735#if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA) && !defined (OPENSSL_NO_RC4)
736 else if (format == FORMAT_MSBLOB)
737 pkey = b2i_PrivateKey_bio(key);
738 else if (format == FORMAT_PVK)
739 pkey = b2i_PVK_bio(key, password_callback,
740 &cb_data);
741#endif
742 else {
743 BIO_printf(err, "bad input format specified for key file\n");
744 goto end;
745 }
746end:
747 BIO_free(key);
748 if (pkey == NULL) {
749 BIO_printf(err, "unable to load %s\n", key_descrip);
750 ERR_print_errors(err);
751 }
752 return (pkey);
753}
754
755EVP_PKEY *
756load_pubkey(BIO *err, const char *file, int format, int maybe_stdin,
757 const char *pass, ENGINE *e, const char *key_descrip)
758{
759 BIO *key = NULL;
760 EVP_PKEY *pkey = NULL;
761 PW_CB_DATA cb_data;
762
763 cb_data.password = pass;
764 cb_data.prompt_info = file;
765
766 if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
767 BIO_printf(err, "no keyfile specified\n");
768 goto end;
769 }
770#ifndef OPENSSL_NO_ENGINE
771 if (format == FORMAT_ENGINE) {
772 if (!e)
773 BIO_printf(bio_err, "no engine specified\n");
774 else
775 pkey = ENGINE_load_public_key(e, file,
776 ui_method, &cb_data);
777 goto end;
778 }
779#endif
780 key = BIO_new(BIO_s_file());
781 if (key == NULL) {
782 ERR_print_errors(err);
783 goto end;
784 }
785 if (file == NULL && maybe_stdin) {
786 setvbuf(stdin, NULL, _IONBF, 0);
787 BIO_set_fp(key, stdin, BIO_NOCLOSE);
788 } else if (BIO_read_filename(key, file) <= 0) {
789 BIO_printf(err, "Error opening %s %s\n", key_descrip, file);
790 ERR_print_errors(err);
791 goto end;
792 }
793 if (format == FORMAT_ASN1) {
794 pkey = d2i_PUBKEY_bio(key, NULL);
795 }
796 else if (format == FORMAT_ASN1RSA) {
797 RSA *rsa;
798 rsa = d2i_RSAPublicKey_bio(key, NULL);
799 if (rsa) {
800 pkey = EVP_PKEY_new();
801 if (pkey)
802 EVP_PKEY_set1_RSA(pkey, rsa);
803 RSA_free(rsa);
804 } else
805 pkey = NULL;
806 } else if (format == FORMAT_PEMRSA) {
807 RSA *rsa;
808 rsa = PEM_read_bio_RSAPublicKey(key, NULL, password_callback, &cb_data);
809 if (rsa) {
810 pkey = EVP_PKEY_new();
811 if (pkey)
812 EVP_PKEY_set1_RSA(pkey, rsa);
813 RSA_free(rsa);
814 } else
815 pkey = NULL;
816 }
817 else if (format == FORMAT_PEM) {
818 pkey = PEM_read_bio_PUBKEY(key, NULL, password_callback, &cb_data);
819 }
820#if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
821 else if (format == FORMAT_NETSCAPE || format == FORMAT_IISSGC)
822 pkey = load_netscape_key(err, key, file, key_descrip, format);
823#endif
824#if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA)
825 else if (format == FORMAT_MSBLOB)
826 pkey = b2i_PublicKey_bio(key);
827#endif
828 else {
829 BIO_printf(err, "bad input format specified for key file\n");
830 goto end;
831 }
832
833end:
834 BIO_free(key);
835 if (pkey == NULL)
836 BIO_printf(err, "unable to load %s\n", key_descrip);
837 return (pkey);
838}
839
840#if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
841static EVP_PKEY *
842load_netscape_key(BIO *err, BIO *key, const char *file,
843 const char *key_descrip, int format)
844{
845 EVP_PKEY *pkey;
846 BUF_MEM *buf;
847 RSA *rsa;
848 const unsigned char *p;
849 int size, i;
850
851 buf = BUF_MEM_new();
852 pkey = EVP_PKEY_new();
853 size = 0;
854 if (buf == NULL || pkey == NULL)
855 goto error;
856 for (;;) {
857 if (!BUF_MEM_grow_clean(buf, size + 1024 * 10))
858 goto error;
859 i = BIO_read(key, &(buf->data[size]), 1024 * 10);
860 size += i;
861 if (i == 0)
862 break;
863 if (i < 0) {
864 BIO_printf(err, "Error reading %s %s",
865 key_descrip, file);
866 goto error;
867 }
868 }
869 p = (unsigned char *) buf->data;
870 rsa = d2i_RSA_NET(NULL, &p, (long) size, NULL,
871 (format == FORMAT_IISSGC ? 1 : 0));
872 if (rsa == NULL)
873 goto error;
874 BUF_MEM_free(buf);
875 EVP_PKEY_set1_RSA(pkey, rsa);
876 return pkey;
877
878error:
879 BUF_MEM_free(buf);
880 EVP_PKEY_free(pkey);
881 return NULL;
882}
883#endif /* ndef OPENSSL_NO_RC4 */
884
885static int
886load_certs_crls(BIO *err, const char *file, int format, const char *pass,
887 ENGINE *e, const char *desc, STACK_OF(X509) **pcerts,
888 STACK_OF(X509_CRL) **pcrls)
889{
890 int i;
891 BIO *bio;
892 STACK_OF(X509_INFO) *xis = NULL;
893 X509_INFO *xi;
894 PW_CB_DATA cb_data;
895 int rv = 0;
896
897 cb_data.password = pass;
898 cb_data.prompt_info = file;
899
900 if (format != FORMAT_PEM) {
901 BIO_printf(err, "bad input format specified for %s\n", desc);
902 return 0;
903 }
904 if (file == NULL)
905 bio = BIO_new_fp(stdin, BIO_NOCLOSE);
906 else
907 bio = BIO_new_file(file, "r");
908
909 if (bio == NULL) {
910 BIO_printf(err, "Error opening %s %s\n",
911 desc, file ? file : "stdin");
912 ERR_print_errors(err);
913 return 0;
914 }
915 xis = PEM_X509_INFO_read_bio(bio, NULL, password_callback, &cb_data);
916
917 BIO_free(bio);
918
919 if (pcerts) {
920 *pcerts = sk_X509_new_null();
921 if (!*pcerts)
922 goto end;
923 }
924 if (pcrls) {
925 *pcrls = sk_X509_CRL_new_null();
926 if (!*pcrls)
927 goto end;
928 }
929 for (i = 0; i < sk_X509_INFO_num(xis); i++) {
930 xi = sk_X509_INFO_value(xis, i);
931 if (xi->x509 && pcerts) {
932 if (!sk_X509_push(*pcerts, xi->x509))
933 goto end;
934 xi->x509 = NULL;
935 }
936 if (xi->crl && pcrls) {
937 if (!sk_X509_CRL_push(*pcrls, xi->crl))
938 goto end;
939 xi->crl = NULL;
940 }
941 }
942
943 if (pcerts && sk_X509_num(*pcerts) > 0)
944 rv = 1;
945
946 if (pcrls && sk_X509_CRL_num(*pcrls) > 0)
947 rv = 1;
948
949end:
950 if (xis)
951 sk_X509_INFO_pop_free(xis, X509_INFO_free);
952
953 if (rv == 0) {
954 if (pcerts) {
955 sk_X509_pop_free(*pcerts, X509_free);
956 *pcerts = NULL;
957 }
958 if (pcrls) {
959 sk_X509_CRL_pop_free(*pcrls, X509_CRL_free);
960 *pcrls = NULL;
961 }
962 BIO_printf(err, "unable to load %s\n",
963 pcerts ? "certificates" : "CRLs");
964 ERR_print_errors(err);
965 }
966 return rv;
967}
968
969STACK_OF(X509) *
970load_certs(BIO *err, const char *file, int format, const char *pass,
971 ENGINE *e, const char *desc)
972{
973 STACK_OF(X509) *certs;
974
975 if (!load_certs_crls(err, file, format, pass, e, desc, &certs, NULL))
976 return NULL;
977 return certs;
978}
979
980STACK_OF(X509_CRL) *
981load_crls(BIO *err, const char *file, int format, const char *pass, ENGINE *e,
982 const char *desc)
983{
984 STACK_OF(X509_CRL) *crls;
985
986 if (!load_certs_crls(err, file, format, pass, e, desc, NULL, &crls))
987 return NULL;
988 return crls;
989}
990
991#define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
992/* Return error for unknown extensions */
993#define X509V3_EXT_DEFAULT 0
994/* Print error for unknown extensions */
995#define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
996/* ASN1 parse unknown extensions */
997#define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
998/* BIO_dump unknown extensions */
999#define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
1000
1001#define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
1002 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
1003
1004int
1005set_cert_ex(unsigned long *flags, const char *arg)
1006{
1007 static const NAME_EX_TBL cert_tbl[] = {
1008 {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
1009 {"ca_default", X509_FLAG_CA, 0xffffffffl},
1010 {"no_header", X509_FLAG_NO_HEADER, 0},
1011 {"no_version", X509_FLAG_NO_VERSION, 0},
1012 {"no_serial", X509_FLAG_NO_SERIAL, 0},
1013 {"no_signame", X509_FLAG_NO_SIGNAME, 0},
1014 {"no_validity", X509_FLAG_NO_VALIDITY, 0},
1015 {"no_subject", X509_FLAG_NO_SUBJECT, 0},
1016 {"no_issuer", X509_FLAG_NO_ISSUER, 0},
1017 {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
1018 {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
1019 {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
1020 {"no_aux", X509_FLAG_NO_AUX, 0},
1021 {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
1022 {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
1023 {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1024 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1025 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1026 {NULL, 0, 0}
1027 };
1028 return set_multi_opts(flags, arg, cert_tbl);
1029}
1030
1031int
1032set_name_ex(unsigned long *flags, const char *arg)
1033{
1034 static const NAME_EX_TBL ex_tbl[] = {
1035 {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
1036 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
1037 {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
1038 {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
1039 {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
1040 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
1041 {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
1042 {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
1043 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
1044 {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
1045 {"compat", XN_FLAG_COMPAT, 0xffffffffL},
1046 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
1047 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
1048 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
1049 {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
1050 {"dn_rev", XN_FLAG_DN_REV, 0},
1051 {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
1052 {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
1053 {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
1054 {"align", XN_FLAG_FN_ALIGN, 0},
1055 {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
1056 {"space_eq", XN_FLAG_SPC_EQ, 0},
1057 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
1058 {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
1059 {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
1060 {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
1061 {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
1062 {NULL, 0, 0}
1063 };
1064 return set_multi_opts(flags, arg, ex_tbl);
1065}
1066
1067int
1068set_ext_copy(int *copy_type, const char *arg)
1069{
1070 if (!strcasecmp(arg, "none"))
1071 *copy_type = EXT_COPY_NONE;
1072 else if (!strcasecmp(arg, "copy"))
1073 *copy_type = EXT_COPY_ADD;
1074 else if (!strcasecmp(arg, "copyall"))
1075 *copy_type = EXT_COPY_ALL;
1076 else
1077 return 0;
1078 return 1;
1079}
1080
1081int
1082copy_extensions(X509 *x, X509_REQ *req, int copy_type)
1083{
1084 STACK_OF(X509_EXTENSION) *exts = NULL;
1085 X509_EXTENSION *ext, *tmpext;
1086 ASN1_OBJECT *obj;
1087 int i, idx, ret = 0;
1088
1089 if (!x || !req || (copy_type == EXT_COPY_NONE))
1090 return 1;
1091 exts = X509_REQ_get_extensions(req);
1092
1093 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
1094 ext = sk_X509_EXTENSION_value(exts, i);
1095 obj = X509_EXTENSION_get_object(ext);
1096 idx = X509_get_ext_by_OBJ(x, obj, -1);
1097 /* Does extension exist? */
1098 if (idx != -1) {
1099 /* If normal copy don't override existing extension */
1100 if (copy_type == EXT_COPY_ADD)
1101 continue;
1102 /* Delete all extensions of same type */
1103 do {
1104 tmpext = X509_get_ext(x, idx);
1105 X509_delete_ext(x, idx);
1106 X509_EXTENSION_free(tmpext);
1107 idx = X509_get_ext_by_OBJ(x, obj, -1);
1108 } while (idx != -1);
1109 }
1110 if (!X509_add_ext(x, ext, -1))
1111 goto end;
1112 }
1113
1114 ret = 1;
1115
1116end:
1117 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1118
1119 return ret;
1120}
1121
1122static int
1123set_multi_opts(unsigned long *flags, const char *arg,
1124 const NAME_EX_TBL *in_tbl)
1125{
1126 STACK_OF(CONF_VALUE) *vals;
1127 CONF_VALUE *val;
1128 int i, ret = 1;
1129
1130 if (!arg)
1131 return 0;
1132 vals = X509V3_parse_list(arg);
1133 for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1134 val = sk_CONF_VALUE_value(vals, i);
1135 if (!set_table_opts(flags, val->name, in_tbl))
1136 ret = 0;
1137 }
1138 sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1139 return ret;
1140}
1141
1142static int
1143set_table_opts(unsigned long *flags, const char *arg,
1144 const NAME_EX_TBL *in_tbl)
1145{
1146 char c;
1147 const NAME_EX_TBL *ptbl;
1148
1149 c = arg[0];
1150 if (c == '-') {
1151 c = 0;
1152 arg++;
1153 } else if (c == '+') {
1154 c = 1;
1155 arg++;
1156 } else
1157 c = 1;
1158
1159 for (ptbl = in_tbl; ptbl->name; ptbl++) {
1160 if (!strcasecmp(arg, ptbl->name)) {
1161 *flags &= ~ptbl->mask;
1162 if (c)
1163 *flags |= ptbl->flag;
1164 else
1165 *flags &= ~ptbl->flag;
1166 return 1;
1167 }
1168 }
1169 return 0;
1170}
1171
1172void
1173print_name(BIO *out, const char *title, X509_NAME *nm, unsigned long lflags)
1174{
1175 char *buf;
1176 char mline = 0;
1177 int indent = 0;
1178
1179 if (title)
1180 BIO_puts(out, title);
1181 if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1182 mline = 1;
1183 indent = 4;
1184 }
1185 if (lflags == XN_FLAG_COMPAT) {
1186 buf = X509_NAME_oneline(nm, 0, 0);
1187 BIO_puts(out, buf);
1188 BIO_puts(out, "\n");
1189 free(buf);
1190 } else {
1191 if (mline)
1192 BIO_puts(out, "\n");
1193 X509_NAME_print_ex(out, nm, indent, lflags);
1194 BIO_puts(out, "\n");
1195 }
1196}
1197
1198X509_STORE *
1199setup_verify(BIO *bp, char *CAfile, char *CApath)
1200{
1201 X509_STORE *store;
1202 X509_LOOKUP *lookup;
1203
1204 if (!(store = X509_STORE_new()))
1205 goto end;
1206 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1207 if (lookup == NULL)
1208 goto end;
1209 if (CAfile) {
1210 if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) {
1211 BIO_printf(bp, "Error loading file %s\n", CAfile);
1212 goto end;
1213 }
1214 } else
1215 X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
1216
1217 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1218 if (lookup == NULL)
1219 goto end;
1220 if (CApath) {
1221 if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1222 BIO_printf(bp, "Error loading directory %s\n", CApath);
1223 goto end;
1224 }
1225 } else
1226 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1227
1228 ERR_clear_error();
1229 return store;
1230
1231end:
1232 X509_STORE_free(store);
1233 return NULL;
1234}
1235
1236#ifndef OPENSSL_NO_ENGINE
1237/* Try to load an engine in a shareable library */
1238static ENGINE *
1239try_load_engine(BIO *err, const char *engine, int debug)
1240{
1241 ENGINE *e = ENGINE_by_id("dynamic");
1242
1243 if (e) {
1244 if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0) ||
1245 !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
1246 ENGINE_free(e);
1247 e = NULL;
1248 }
1249 }
1250 return e;
1251}
1252
1253ENGINE *
1254setup_engine(BIO *err, const char *engine, int debug)
1255{
1256 ENGINE *e = NULL;
1257
1258 if (engine) {
1259 if (strcmp(engine, "auto") == 0) {
1260 BIO_printf(err, "enabling auto ENGINE support\n");
1261 ENGINE_register_all_complete();
1262 return NULL;
1263 }
1264 if ((e = ENGINE_by_id(engine)) == NULL &&
1265 (e = try_load_engine(err, engine, debug)) == NULL) {
1266 BIO_printf(err, "invalid engine \"%s\"\n", engine);
1267 ERR_print_errors(err);
1268 return NULL;
1269 }
1270 if (debug) {
1271 ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM,
1272 0, err, 0);
1273 }
1274 ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, ui_method, 0, 1);
1275 if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
1276 BIO_printf(err, "can't use that engine\n");
1277 ERR_print_errors(err);
1278 ENGINE_free(e);
1279 return NULL;
1280 }
1281 BIO_printf(err, "engine \"%s\" set.\n", ENGINE_get_id(e));
1282
1283 /* Free our "structural" reference. */
1284 ENGINE_free(e);
1285 }
1286 return e;
1287}
1288#endif
1289
1290int
1291load_config(BIO *err, CONF *cnf)
1292{
1293 static int load_config_called = 0;
1294
1295 if (load_config_called)
1296 return 1;
1297 load_config_called = 1;
1298 if (cnf == NULL)
1299 cnf = config;
1300 if (cnf == NULL)
1301 return 1;
1302
1303 OPENSSL_load_builtin_modules();
1304
1305 if (CONF_modules_load(cnf, NULL, 0) <= 0) {
1306 BIO_printf(err, "Error configuring OpenSSL\n");
1307 ERR_print_errors(err);
1308 return 0;
1309 }
1310 return 1;
1311}
1312
1313char *
1314make_config_name()
1315{
1316 const char *t = X509_get_default_cert_area();
1317 char *p;
1318
1319 if (asprintf(&p, "%s/openssl.cnf", t) == -1)
1320 return NULL;
1321 return p;
1322}
1323
1324static unsigned long
1325index_serial_hash(const OPENSSL_CSTRING *a)
1326{
1327 const char *n;
1328
1329 n = a[DB_serial];
1330 while (*n == '0')
1331 n++;
1332 return (lh_strhash(n));
1333}
1334
1335static int
1336index_serial_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1337{
1338 const char *aa, *bb;
1339
1340 for (aa = a[DB_serial]; *aa == '0'; aa++)
1341 ;
1342 for (bb = b[DB_serial]; *bb == '0'; bb++)
1343 ;
1344 return (strcmp(aa, bb));
1345}
1346
1347static int
1348index_name_qual(char **a)
1349{
1350 return (a[0][0] == 'V');
1351}
1352
1353static unsigned long
1354index_name_hash(const OPENSSL_CSTRING *a)
1355{
1356 return (lh_strhash(a[DB_name]));
1357}
1358
1359int
1360index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1361{
1362 return (strcmp(a[DB_name], b[DB_name]));
1363}
1364
1365static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1366static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1367static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1368static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1369
1370#define BSIZE 256
1371
1372BIGNUM *
1373load_serial(char *serialfile, int create, ASN1_INTEGER **retai)
1374{
1375 BIO *in = NULL;
1376 BIGNUM *ret = NULL;
1377 char buf[1024];
1378 ASN1_INTEGER *ai = NULL;
1379
1380 ai = ASN1_INTEGER_new();
1381 if (ai == NULL)
1382 goto err;
1383
1384 if ((in = BIO_new(BIO_s_file())) == NULL) {
1385 ERR_print_errors(bio_err);
1386 goto err;
1387 }
1388 if (BIO_read_filename(in, serialfile) <= 0) {
1389 if (!create) {
1390 perror(serialfile);
1391 goto err;
1392 } else {
1393 ret = BN_new();
1394 if (ret == NULL || !rand_serial(ret, ai))
1395 BIO_printf(bio_err, "Out of memory\n");
1396 }
1397 } else {
1398 if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1399 BIO_printf(bio_err, "unable to load number from %s\n",
1400 serialfile);
1401 goto err;
1402 }
1403 ret = ASN1_INTEGER_to_BN(ai, NULL);
1404 if (ret == NULL) {
1405 BIO_printf(bio_err,
1406 "error converting number from bin to BIGNUM\n");
1407 goto err;
1408 }
1409 }
1410
1411 if (ret && retai) {
1412 *retai = ai;
1413 ai = NULL;
1414 }
1415
1416err:
1417 if (in != NULL)
1418 BIO_free(in);
1419 if (ai != NULL)
1420 ASN1_INTEGER_free(ai);
1421 return (ret);
1422}
1423
1424int
1425save_serial(char *serialfile, char *suffix, BIGNUM *serial,
1426 ASN1_INTEGER **retai)
1427{
1428 char buf[1][BSIZE];
1429 BIO *out = NULL;
1430 int ret = 0, n;
1431 ASN1_INTEGER *ai = NULL;
1432 int j;
1433
1434 if (suffix == NULL)
1435 j = strlen(serialfile);
1436 else
1437 j = strlen(serialfile) + strlen(suffix) + 1;
1438 if (j >= BSIZE) {
1439 BIO_printf(bio_err, "file name too long\n");
1440 goto err;
1441 }
1442 if (suffix == NULL)
1443 n = strlcpy(buf[0], serialfile, BSIZE);
1444 else
1445 n = snprintf(buf[0], sizeof buf[0], "%s.%s",
1446 serialfile, suffix);
1447 if (n == -1 || n >= sizeof(buf[0])) {
1448 BIO_printf(bio_err, "serial too long\n");
1449 goto err;
1450 }
1451 out = BIO_new(BIO_s_file());
1452 if (out == NULL) {
1453 ERR_print_errors(bio_err);
1454 goto err;
1455 }
1456 if (BIO_write_filename(out, buf[0]) <= 0) {
1457 perror(serialfile);
1458 goto err;
1459 }
1460 if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1461 BIO_printf(bio_err,
1462 "error converting serial to ASN.1 format\n");
1463 goto err;
1464 }
1465 i2a_ASN1_INTEGER(out, ai);
1466 BIO_puts(out, "\n");
1467 ret = 1;
1468 if (retai) {
1469 *retai = ai;
1470 ai = NULL;
1471 }
1472
1473err:
1474 if (out != NULL)
1475 BIO_free_all(out);
1476 if (ai != NULL)
1477 ASN1_INTEGER_free(ai);
1478 return (ret);
1479}
1480
1481int
1482rotate_serial(char *serialfile, char *new_suffix, char *old_suffix)
1483{
1484 char buf[5][BSIZE];
1485 int i, j;
1486
1487 i = strlen(serialfile) + strlen(old_suffix);
1488 j = strlen(serialfile) + strlen(new_suffix);
1489 if (i > j)
1490 j = i;
1491 if (j + 1 >= BSIZE) {
1492 BIO_printf(bio_err, "file name too long\n");
1493 goto err;
1494 }
1495 snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, new_suffix);
1496 snprintf(buf[1], sizeof buf[1], "%s.%s", serialfile, old_suffix);
1497
1498
1499 if (rename(serialfile, buf[1]) < 0 &&
1500 errno != ENOENT && errno != ENOTDIR) {
1501 BIO_printf(bio_err, "unable to rename %s to %s\n",
1502 serialfile, buf[1]);
1503 perror("reason");
1504 goto err;
1505 }
1506
1507
1508 if (rename(buf[0], serialfile) < 0) {
1509 BIO_printf(bio_err, "unable to rename %s to %s\n",
1510 buf[0], serialfile);
1511 perror("reason");
1512 rename(buf[1], serialfile);
1513 goto err;
1514 }
1515 return 1;
1516
1517err:
1518 return 0;
1519}
1520
1521int
1522rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1523{
1524 BIGNUM *btmp;
1525 int ret = 0;
1526
1527 if (b)
1528 btmp = b;
1529 else
1530 btmp = BN_new();
1531
1532 if (!btmp)
1533 return 0;
1534
1535 if (!BN_pseudo_rand(btmp, SERIAL_RAND_BITS, 0, 0))
1536 goto error;
1537 if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1538 goto error;
1539
1540 ret = 1;
1541
1542error:
1543 if (!b)
1544 BN_free(btmp);
1545
1546 return ret;
1547}
1548
1549CA_DB *
1550load_index(char *dbfile, DB_ATTR *db_attr)
1551{
1552 CA_DB *retdb = NULL;
1553 TXT_DB *tmpdb = NULL;
1554 BIO *in = BIO_new(BIO_s_file());
1555 CONF *dbattr_conf = NULL;
1556 char buf[1][BSIZE];
1557 long errorline = -1;
1558
1559 if (in == NULL) {
1560 ERR_print_errors(bio_err);
1561 goto err;
1562 }
1563 if (BIO_read_filename(in, dbfile) <= 0) {
1564 perror(dbfile);
1565 BIO_printf(bio_err, "unable to open '%s'\n", dbfile);
1566 goto err;
1567 }
1568 if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1569 goto err;
1570
1571 snprintf(buf[0], sizeof buf[0], "%s.attr", dbfile);
1572 dbattr_conf = NCONF_new(NULL);
1573 if (NCONF_load(dbattr_conf, buf[0], &errorline) <= 0) {
1574 if (errorline > 0) {
1575 BIO_printf(bio_err,
1576 "error on line %ld of db attribute file '%s'\n",
1577 errorline, buf[0]);
1578 goto err;
1579 } else {
1580 NCONF_free(dbattr_conf);
1581 dbattr_conf = NULL;
1582 }
1583 }
1584 if ((retdb = malloc(sizeof(CA_DB))) == NULL) {
1585 fprintf(stderr, "Out of memory\n");
1586 goto err;
1587 }
1588 retdb->db = tmpdb;
1589 tmpdb = NULL;
1590 if (db_attr)
1591 retdb->attributes = *db_attr;
1592 else {
1593 retdb->attributes.unique_subject = 1;
1594 }
1595
1596 if (dbattr_conf) {
1597 char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1598 if (p) {
1599 retdb->attributes.unique_subject = parse_yesno(p, 1);
1600 }
1601 }
1602
1603err:
1604 if (dbattr_conf)
1605 NCONF_free(dbattr_conf);
1606 if (tmpdb)
1607 TXT_DB_free(tmpdb);
1608 if (in)
1609 BIO_free_all(in);
1610 return retdb;
1611}
1612
1613int
1614index_index(CA_DB *db)
1615{
1616 if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1617 LHASH_HASH_FN(index_serial), LHASH_COMP_FN(index_serial))) {
1618 BIO_printf(bio_err,
1619 "error creating serial number index:(%ld,%ld,%ld)\n",
1620 db->db->error, db->db->arg1, db->db->arg2);
1621 return 0;
1622 }
1623 if (db->attributes.unique_subject &&
1624 !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1625 LHASH_HASH_FN(index_name), LHASH_COMP_FN(index_name))) {
1626 BIO_printf(bio_err, "error creating name index:(%ld,%ld,%ld)\n",
1627 db->db->error, db->db->arg1, db->db->arg2);
1628 return 0;
1629 }
1630 return 1;
1631}
1632
1633int
1634save_index(const char *dbfile, const char *suffix, CA_DB *db)
1635{
1636 char buf[3][BSIZE];
1637 BIO *out = BIO_new(BIO_s_file());
1638 int j;
1639
1640 if (out == NULL) {
1641 ERR_print_errors(bio_err);
1642 goto err;
1643 }
1644 j = strlen(dbfile) + strlen(suffix);
1645 if (j + 6 >= BSIZE) {
1646 BIO_printf(bio_err, "file name too long\n");
1647 goto err;
1648 }
1649 snprintf(buf[2], sizeof buf[2], "%s.attr", dbfile);
1650 snprintf(buf[1], sizeof buf[1], "%s.attr.%s", dbfile, suffix);
1651 snprintf(buf[0], sizeof buf[0], "%s.%s", dbfile, suffix);
1652
1653
1654 if (BIO_write_filename(out, buf[0]) <= 0) {
1655 perror(dbfile);
1656 BIO_printf(bio_err, "unable to open '%s'\n", dbfile);
1657 goto err;
1658 }
1659 j = TXT_DB_write(out, db->db);
1660 if (j <= 0)
1661 goto err;
1662
1663 BIO_free(out);
1664
1665 out = BIO_new(BIO_s_file());
1666
1667
1668 if (BIO_write_filename(out, buf[1]) <= 0) {
1669 perror(buf[2]);
1670 BIO_printf(bio_err, "unable to open '%s'\n", buf[2]);
1671 goto err;
1672 }
1673 BIO_printf(out, "unique_subject = %s\n",
1674 db->attributes.unique_subject ? "yes" : "no");
1675 BIO_free(out);
1676
1677 return 1;
1678
1679err:
1680 return 0;
1681}
1682
1683int
1684rotate_index(const char *dbfile, const char *new_suffix, const char *old_suffix)
1685{
1686 char buf[5][BSIZE];
1687 int i, j;
1688
1689 i = strlen(dbfile) + strlen(old_suffix);
1690 j = strlen(dbfile) + strlen(new_suffix);
1691 if (i > j)
1692 j = i;
1693 if (j + 6 >= BSIZE) {
1694 BIO_printf(bio_err, "file name too long\n");
1695 goto err;
1696 }
1697 snprintf(buf[4], sizeof buf[4], "%s.attr", dbfile);
1698 snprintf(buf[2], sizeof buf[2], "%s.attr.%s", dbfile, new_suffix);
1699 snprintf(buf[0], sizeof buf[0], "%s.%s", dbfile, new_suffix);
1700 snprintf(buf[1], sizeof buf[1], "%s.%s", dbfile, old_suffix);
1701 snprintf(buf[3], sizeof buf[3], "%s.attr.%s", dbfile, old_suffix);
1702
1703
1704 if (rename(dbfile, buf[1]) < 0 && errno != ENOENT && errno != ENOTDIR) {
1705 BIO_printf(bio_err, "unable to rename %s to %s\n",
1706 dbfile, buf[1]);
1707 perror("reason");
1708 goto err;
1709 }
1710
1711
1712 if (rename(buf[0], dbfile) < 0) {
1713 BIO_printf(bio_err, "unable to rename %s to %s\n",
1714 buf[0], dbfile);
1715 perror("reason");
1716 rename(buf[1], dbfile);
1717 goto err;
1718 }
1719
1720
1721 if (rename(buf[4], buf[3]) < 0 && errno != ENOENT && errno != ENOTDIR) {
1722 BIO_printf(bio_err, "unable to rename %s to %s\n",
1723 buf[4], buf[3]);
1724 perror("reason");
1725 rename(dbfile, buf[0]);
1726 rename(buf[1], dbfile);
1727 goto err;
1728 }
1729
1730
1731 if (rename(buf[2], buf[4]) < 0) {
1732 BIO_printf(bio_err, "unable to rename %s to %s\n",
1733 buf[2], buf[4]);
1734 perror("reason");
1735 rename(buf[3], buf[4]);
1736 rename(dbfile, buf[0]);
1737 rename(buf[1], dbfile);
1738 goto err;
1739 }
1740 return 1;
1741
1742err:
1743 return 0;
1744}
1745
1746void
1747free_index(CA_DB *db)
1748{
1749 if (db) {
1750 if (db->db)
1751 TXT_DB_free(db->db);
1752 free(db);
1753 }
1754}
1755
1756int
1757parse_yesno(const char *str, int def)
1758{
1759 int ret = def;
1760
1761 if (str) {
1762 switch (*str) {
1763 case 'f': /* false */
1764 case 'F': /* FALSE */
1765 case 'n': /* no */
1766 case 'N': /* NO */
1767 case '0': /* 0 */
1768 ret = 0;
1769 break;
1770 case 't': /* true */
1771 case 'T': /* TRUE */
1772 case 'y': /* yes */
1773 case 'Y': /* YES */
1774 case '1': /* 1 */
1775 ret = 1;
1776 break;
1777 default:
1778 ret = def;
1779 break;
1780 }
1781 }
1782 return ret;
1783}
1784
1785/*
1786 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1787 * where characters may be escaped by \
1788 */
1789X509_NAME *
1790parse_name(char *subject, long chtype, int multirdn)
1791{
1792 X509_NAME *name = NULL;
1793 size_t buflen, max_ne;
1794 char **ne_types, **ne_values;
1795 char *buf, *bp, *sp;
1796 int i, nid, ne_num = 0;
1797 int *mval;
1798
1799 /*
1800 * Buffer to copy the types and values into. Due to escaping the
1801 * copy can only become shorter.
1802 */
1803 buflen = strlen(subject) + 1;
1804 buf = malloc(buflen);
1805
1806 /* Maximum number of name elements. */
1807 max_ne = buflen / 2 + 1;
1808 ne_types = reallocarray(NULL, max_ne, sizeof(char *));
1809 ne_values = reallocarray(NULL, max_ne, sizeof(char *));
1810 mval = reallocarray(NULL, max_ne, sizeof(int));
1811
1812 if (buf == NULL || ne_types == NULL || ne_values == NULL ||
1813 mval == NULL) {
1814 BIO_printf(bio_err, "malloc error\n");
1815 goto error;
1816 }
1817
1818 bp = buf;
1819 sp = subject;
1820
1821 if (*subject != '/') {
1822 BIO_printf(bio_err, "Subject does not start with '/'.\n");
1823 goto error;
1824 }
1825
1826 /* Skip leading '/'. */
1827 sp++;
1828
1829 /* No multivalued RDN by default. */
1830 mval[ne_num] = 0;
1831
1832 while (*sp) {
1833 /* Collect type. */
1834 ne_types[ne_num] = bp;
1835 while (*sp) {
1836 /* is there anything to escape in the type...? */
1837 if (*sp == '\\') {
1838 if (*++sp)
1839 *bp++ = *sp++;
1840 else {
1841 BIO_printf(bio_err, "escape character "
1842 "at end of string\n");
1843 goto error;
1844 }
1845 } else if (*sp == '=') {
1846 sp++;
1847 *bp++ = '\0';
1848 break;
1849 } else
1850 *bp++ = *sp++;
1851 }
1852 if (!*sp) {
1853 BIO_printf(bio_err, "end of string encountered while "
1854 "processing type of subject name element #%d\n",
1855 ne_num);
1856 goto error;
1857 }
1858 ne_values[ne_num] = bp;
1859 while (*sp) {
1860 if (*sp == '\\') {
1861 if (*++sp)
1862 *bp++ = *sp++;
1863 else {
1864 BIO_printf(bio_err, "escape character "
1865 "at end of string\n");
1866 goto error;
1867 }
1868 } else if (*sp == '/') {
1869 sp++;
1870 /* no multivalued RDN by default */
1871 mval[ne_num + 1] = 0;
1872 break;
1873 } else if (*sp == '+' && multirdn) {
1874 /* a not escaped + signals a mutlivalued RDN */
1875 sp++;
1876 mval[ne_num + 1] = -1;
1877 break;
1878 } else
1879 *bp++ = *sp++;
1880 }
1881 *bp++ = '\0';
1882 ne_num++;
1883 }
1884
1885 if ((name = X509_NAME_new()) == NULL)
1886 goto error;
1887
1888 for (i = 0; i < ne_num; i++) {
1889 if ((nid = OBJ_txt2nid(ne_types[i])) == NID_undef) {
1890 BIO_printf(bio_err,
1891 "Subject Attribute %s has no known NID, skipped\n",
1892 ne_types[i]);
1893 continue;
1894 }
1895 if (!*ne_values[i]) {
1896 BIO_printf(bio_err, "No value provided for Subject "
1897 "Attribute %s, skipped\n", ne_types[i]);
1898 continue;
1899 }
1900 if (!X509_NAME_add_entry_by_NID(name, nid, chtype,
1901 (unsigned char *) ne_values[i], -1, -1, mval[i]))
1902 goto error;
1903 }
1904 goto done;
1905
1906error:
1907 X509_NAME_free(name);
1908 name = NULL;
1909
1910done:
1911 free(ne_values);
1912 free(ne_types);
1913 free(mval);
1914 free(buf);
1915
1916 return name;
1917}
1918
1919int
1920args_verify(char ***pargs, int *pargc, int *badarg, BIO *err,
1921 X509_VERIFY_PARAM **pm)
1922{
1923 ASN1_OBJECT *otmp = NULL;
1924 unsigned long flags = 0;
1925 int i;
1926 int purpose = 0, depth = -1;
1927 char **oldargs = *pargs;
1928 char *arg = **pargs, *argn = (*pargs)[1];
1929 time_t at_time = 0;
1930 const char *errstr = NULL;
1931
1932 if (!strcmp(arg, "-policy")) {
1933 if (!argn)
1934 *badarg = 1;
1935 else {
1936 otmp = OBJ_txt2obj(argn, 0);
1937 if (!otmp) {
1938 BIO_printf(err, "Invalid Policy \"%s\"\n",
1939 argn);
1940 *badarg = 1;
1941 }
1942 }
1943 (*pargs)++;
1944 } else if (strcmp(arg, "-purpose") == 0) {
1945 X509_PURPOSE *xptmp;
1946 if (!argn)
1947 *badarg = 1;
1948 else {
1949 i = X509_PURPOSE_get_by_sname(argn);
1950 if (i < 0) {
1951 BIO_printf(err, "unrecognized purpose\n");
1952 *badarg = 1;
1953 } else {
1954 xptmp = X509_PURPOSE_get0(i);
1955 purpose = X509_PURPOSE_get_id(xptmp);
1956 }
1957 }
1958 (*pargs)++;
1959 } else if (strcmp(arg, "-verify_depth") == 0) {
1960 if (!argn)
1961 *badarg = 1;
1962 else {
1963 depth = strtonum(argn, 1, INT_MAX, &errstr);
1964 if (errstr) {
1965 BIO_printf(err, "invalid depth %s: %s\n",
1966 argn, errstr);
1967 *badarg = 1;
1968 }
1969 }
1970 (*pargs)++;
1971 } else if (strcmp(arg, "-attime") == 0) {
1972 if (!argn)
1973 *badarg = 1;
1974 else {
1975 long long timestamp;
1976 /*
1977 * interpret the -attime argument as seconds since
1978 * Epoch
1979 */
1980 if (sscanf(argn, "%lli", &timestamp) != 1) {
1981 BIO_printf(bio_err,
1982 "Error parsing timestamp %s\n",
1983 argn);
1984 *badarg = 1;
1985 }
1986 /* XXX 2038 truncation */
1987 at_time = (time_t) timestamp;
1988 }
1989 (*pargs)++;
1990 } else if (!strcmp(arg, "-ignore_critical"))
1991 flags |= X509_V_FLAG_IGNORE_CRITICAL;
1992 else if (!strcmp(arg, "-issuer_checks"))
1993 flags |= X509_V_FLAG_CB_ISSUER_CHECK;
1994 else if (!strcmp(arg, "-crl_check"))
1995 flags |= X509_V_FLAG_CRL_CHECK;
1996 else if (!strcmp(arg, "-crl_check_all"))
1997 flags |= X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL;
1998 else if (!strcmp(arg, "-policy_check"))
1999 flags |= X509_V_FLAG_POLICY_CHECK;
2000 else if (!strcmp(arg, "-explicit_policy"))
2001 flags |= X509_V_FLAG_EXPLICIT_POLICY;
2002 else if (!strcmp(arg, "-inhibit_any"))
2003 flags |= X509_V_FLAG_INHIBIT_ANY;
2004 else if (!strcmp(arg, "-inhibit_map"))
2005 flags |= X509_V_FLAG_INHIBIT_MAP;
2006 else if (!strcmp(arg, "-x509_strict"))
2007 flags |= X509_V_FLAG_X509_STRICT;
2008 else if (!strcmp(arg, "-extended_crl"))
2009 flags |= X509_V_FLAG_EXTENDED_CRL_SUPPORT;
2010 else if (!strcmp(arg, "-use_deltas"))
2011 flags |= X509_V_FLAG_USE_DELTAS;
2012 else if (!strcmp(arg, "-policy_print"))
2013 flags |= X509_V_FLAG_NOTIFY_POLICY;
2014 else if (!strcmp(arg, "-check_ss_sig"))
2015 flags |= X509_V_FLAG_CHECK_SS_SIGNATURE;
2016 else
2017 return 0;
2018
2019 if (*badarg) {
2020 if (*pm)
2021 X509_VERIFY_PARAM_free(*pm);
2022 *pm = NULL;
2023 goto end;
2024 }
2025 if (!*pm && !(*pm = X509_VERIFY_PARAM_new())) {
2026 *badarg = 1;
2027 goto end;
2028 }
2029 if (otmp)
2030 X509_VERIFY_PARAM_add0_policy(*pm, otmp);
2031 if (flags)
2032 X509_VERIFY_PARAM_set_flags(*pm, flags);
2033
2034 if (purpose)
2035 X509_VERIFY_PARAM_set_purpose(*pm, purpose);
2036
2037 if (depth >= 0)
2038 X509_VERIFY_PARAM_set_depth(*pm, depth);
2039
2040 if (at_time)
2041 X509_VERIFY_PARAM_set_time(*pm, at_time);
2042
2043end:
2044 (*pargs)++;
2045
2046 if (pargc)
2047 *pargc -= *pargs - oldargs;
2048
2049 return 1;
2050}
2051
2052/* Read whole contents of a BIO into an allocated memory buffer and
2053 * return it.
2054 */
2055
2056int
2057bio_to_mem(unsigned char **out, int maxlen, BIO *in)
2058{
2059 BIO *mem;
2060 int len, ret;
2061 unsigned char tbuf[1024];
2062
2063 mem = BIO_new(BIO_s_mem());
2064 if (!mem)
2065 return -1;
2066 for (;;) {
2067 if ((maxlen != -1) && maxlen < 1024)
2068 len = maxlen;
2069 else
2070 len = 1024;
2071 len = BIO_read(in, tbuf, len);
2072 if (len <= 0)
2073 break;
2074 if (BIO_write(mem, tbuf, len) != len) {
2075 BIO_free(mem);
2076 return -1;
2077 }
2078 maxlen -= len;
2079
2080 if (maxlen == 0)
2081 break;
2082 }
2083 ret = BIO_get_mem_data(mem, (char **) out);
2084 BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
2085 BIO_free(mem);
2086 return ret;
2087}
2088
2089int
2090pkey_ctrl_string(EVP_PKEY_CTX *ctx, char *value)
2091{
2092 int rv;
2093 char *stmp, *vtmp = NULL;
2094
2095 stmp = BUF_strdup(value);
2096 if (!stmp)
2097 return -1;
2098 vtmp = strchr(stmp, ':');
2099 if (vtmp) {
2100 *vtmp = 0;
2101 vtmp++;
2102 }
2103 rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
2104 free(stmp);
2105
2106 return rv;
2107}
2108
2109static void
2110nodes_print(BIO *out, const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
2111{
2112 X509_POLICY_NODE *node;
2113 int i;
2114
2115 BIO_printf(out, "%s Policies:", name);
2116 if (nodes) {
2117 BIO_puts(out, "\n");
2118 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
2119 node = sk_X509_POLICY_NODE_value(nodes, i);
2120 X509_POLICY_NODE_print(out, node, 2);
2121 }
2122 } else
2123 BIO_puts(out, " <empty>\n");
2124}
2125
2126void
2127policies_print(BIO *out, X509_STORE_CTX *ctx)
2128{
2129 X509_POLICY_TREE *tree;
2130 int explicit_policy;
2131 int free_out = 0;
2132
2133 if (out == NULL) {
2134 out = BIO_new_fp(stderr, BIO_NOCLOSE);
2135 free_out = 1;
2136 }
2137 tree = X509_STORE_CTX_get0_policy_tree(ctx);
2138 explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
2139
2140 BIO_printf(out, "Require explicit Policy: %s\n",
2141 explicit_policy ? "True" : "False");
2142
2143 nodes_print(out, "Authority", X509_policy_tree_get0_policies(tree));
2144 nodes_print(out, "User", X509_policy_tree_get0_user_policies(tree));
2145 if (free_out)
2146 BIO_free(out);
2147}
2148
2149#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
2150/* next_protos_parse parses a comma separated list of strings into a string
2151 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
2152 * outlen: (output) set to the length of the resulting buffer on success.
2153 * err: (maybe NULL) on failure, an error message line is written to this BIO.
2154 * in: a NUL termianted string like "abc,def,ghi"
2155 *
2156 * returns: a malloced buffer or NULL on failure.
2157 */
2158unsigned char *
2159next_protos_parse(unsigned short *outlen, const char *in)
2160{
2161 size_t len;
2162 unsigned char *out;
2163 size_t i, start = 0;
2164
2165 len = strlen(in);
2166 if (len >= 65535)
2167 return NULL;
2168
2169 out = malloc(strlen(in) + 1);
2170 if (!out)
2171 return NULL;
2172
2173 for (i = 0; i <= len; ++i) {
2174 if (i == len || in[i] == ',') {
2175 if (i - start > 255) {
2176 free(out);
2177 return NULL;
2178 }
2179 out[start] = i - start;
2180 start = i + 1;
2181 } else
2182 out[i + 1] = in[i];
2183 }
2184
2185 *outlen = len + 1;
2186 return out;
2187}
2188#endif
2189/* !OPENSSL_NO_TLSEXT && !OPENSSL_NO_NEXTPROTONEG */
2190
2191double
2192app_tminterval(int stop, int usertime)
2193{
2194 double ret = 0;
2195 struct tms rus;
2196 clock_t now = times(&rus);
2197 static clock_t tmstart;
2198
2199 if (usertime)
2200 now = rus.tms_utime;
2201
2202 if (stop == TM_START)
2203 tmstart = now;
2204 else {
2205 long int tck = sysconf(_SC_CLK_TCK);
2206 ret = (now - tmstart) / (double) tck;
2207 }
2208
2209 return (ret);
2210}
2211
2212int
2213app_isdir(const char *name)
2214{
2215 struct stat st;
2216
2217 if (stat(name, &st) == 0)
2218 return S_ISDIR(st.st_mode);
2219 return -1;
2220}
diff --git a/src/usr.bin/openssl/apps.h b/src/usr.bin/openssl/apps.h
new file mode 100644
index 0000000000..38c5f4be8c
--- /dev/null
+++ b/src/usr.bin/openssl/apps.h
@@ -0,0 +1,285 @@
1/* $OpenBSD: apps.h,v 1.1 2014/08/26 17:47:24 jsing 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 * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in
70 * the documentation and/or other materials provided with the
71 * distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 * software must display the following acknowledgment:
75 * "This product includes software developed by the OpenSSL Project
76 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 * endorse or promote products derived from this software without
80 * prior written permission. For written permission, please contact
81 * openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 * nor may "OpenSSL" appear in their names without prior written
85 * permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 * acknowledgment:
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com). This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
111
112#ifndef HEADER_APPS_H
113#define HEADER_APPS_H
114
115#include <openssl/opensslconf.h>
116
117#include <openssl/bio.h>
118#include <openssl/conf.h>
119#include <openssl/lhash.h>
120#include <openssl/ossl_typ.h>
121#include <openssl/txt_db.h>
122#include <openssl/x509.h>
123
124#ifndef OPENSSL_NO_ENGINE
125#include <openssl/engine.h>
126#endif
127
128#ifndef OPENSSL_NO_OCSP
129#include <openssl/ocsp.h>
130#endif
131
132extern CONF *config;
133extern char *default_config_file;
134extern BIO *bio_err;
135
136typedef struct args_st {
137 char **data;
138 int count;
139} ARGS;
140
141#define PW_MIN_LENGTH 4
142typedef struct pw_cb_data {
143 const void *password;
144 const char *prompt_info;
145} PW_CB_DATA;
146
147int password_callback(char *buf, int bufsiz, int verify, void *cb_data);
148
149int setup_ui_method(void);
150void destroy_ui_method(void);
151
152int should_retry(int i);
153int args_from_file(char *file, int *argc, char **argv[]);
154int str2fmt(char *s);
155void program_name(char *in, char *out, int size);
156int chopup_args(ARGS *arg, char *buf, int *argc, char **argv[]);
157#ifdef HEADER_X509_H
158int dump_cert_text(BIO *out, X509 *x);
159void print_name(BIO *out, const char *title, X509_NAME *nm,
160 unsigned long lflags);
161#endif
162int set_cert_ex(unsigned long *flags, const char *arg);
163int set_name_ex(unsigned long *flags, const char *arg);
164int set_ext_copy(int *copy_type, const char *arg);
165int copy_extensions(X509 *x, X509_REQ *req, int copy_type);
166int app_passwd(BIO *err, char *arg1, char *arg2, char **pass1, char **pass2);
167int add_oid_section(BIO *err, CONF *conf);
168X509 *load_cert(BIO *err, const char *file, int format,
169 const char *pass, ENGINE *e, const char *cert_descrip);
170EVP_PKEY *load_key(BIO *err, const char *file, int format, int maybe_stdin,
171 const char *pass, ENGINE *e, const char *key_descrip);
172EVP_PKEY *load_pubkey(BIO *err, const char *file, int format, int maybe_stdin,
173 const char *pass, ENGINE *e, const char *key_descrip);
174STACK_OF(X509) *load_certs(BIO *err, const char *file, int format,
175 const char *pass, ENGINE *e, const char *cert_descrip);
176STACK_OF(X509_CRL) *load_crls(BIO *err, const char *file, int format,
177 const char *pass, ENGINE *e, const char *cert_descrip);
178X509_STORE *setup_verify(BIO *bp, char *CAfile, char *CApath);
179#ifndef OPENSSL_NO_ENGINE
180ENGINE *setup_engine(BIO *err, const char *engine, int debug);
181#endif
182
183#ifndef OPENSSL_NO_OCSP
184OCSP_RESPONSE *process_responder(BIO *err, OCSP_REQUEST *req,
185 char *host, char *path, char *port, int use_ssl,
186 STACK_OF(CONF_VALUE) *headers, int req_timeout);
187#endif
188
189int load_config(BIO *err, CONF *cnf);
190char *make_config_name(void);
191
192/* Functions defined in ca.c and also used in ocsp.c */
193int unpack_revinfo(ASN1_TIME **prevtm, int *preason, ASN1_OBJECT **phold,
194 ASN1_GENERALIZEDTIME **pinvtm, const char *str);
195
196#define DB_type 0
197#define DB_exp_date 1
198#define DB_rev_date 2
199#define DB_serial 3 /* index - unique */
200#define DB_file 4
201#define DB_name 5 /* index - unique when active and not disabled */
202#define DB_NUMBER 6
203
204#define DB_TYPE_REV 'R'
205#define DB_TYPE_EXP 'E'
206#define DB_TYPE_VAL 'V'
207
208typedef struct db_attr_st {
209 int unique_subject;
210} DB_ATTR;
211typedef struct ca_db_st {
212 DB_ATTR attributes;
213 TXT_DB *db;
214} CA_DB;
215
216BIGNUM *load_serial(char *serialfile, int create, ASN1_INTEGER **retai);
217int save_serial(char *serialfile, char *suffix, BIGNUM *serial,
218 ASN1_INTEGER **retai);
219int rotate_serial(char *serialfile, char *new_suffix, char *old_suffix);
220int rand_serial(BIGNUM *b, ASN1_INTEGER *ai);
221CA_DB *load_index(char *dbfile, DB_ATTR *dbattr);
222int index_index(CA_DB *db);
223int save_index(const char *dbfile, const char *suffix, CA_DB *db);
224int rotate_index(const char *dbfile, const char *new_suffix,
225 const char *old_suffix);
226void free_index(CA_DB *db);
227#define index_name_cmp_noconst(a, b) \
228 index_name_cmp((const OPENSSL_CSTRING *)CHECKED_PTR_OF(OPENSSL_STRING, a), \
229 (const OPENSSL_CSTRING *)CHECKED_PTR_OF(OPENSSL_STRING, b))
230int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b);
231int parse_yesno(const char *str, int def);
232
233X509_NAME *parse_name(char *str, long chtype, int multirdn);
234int args_verify(char ***pargs, int *pargc, int *badarg, BIO *err,
235 X509_VERIFY_PARAM **pm);
236void policies_print(BIO *out, X509_STORE_CTX *ctx);
237int bio_to_mem(unsigned char **out, int maxlen, BIO *in);
238int pkey_ctrl_string(EVP_PKEY_CTX *ctx, char *value);
239int init_gen_str(BIO *err, EVP_PKEY_CTX **pctx, const char *algname, ENGINE *e,
240 int do_param);
241int do_X509_sign(BIO *err, X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
242 STACK_OF(OPENSSL_STRING) *sigopts);
243int do_X509_REQ_sign(BIO *err, X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
244 STACK_OF(OPENSSL_STRING) *sigopts);
245int do_X509_CRL_sign(BIO *err, X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
246 STACK_OF(OPENSSL_STRING) *sigopts);
247
248#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
249unsigned char *next_protos_parse(unsigned short *outlen, const char *in);
250#endif /* !OPENSSL_NO_TLSEXT && !OPENSSL_NO_NEXTPROTONEG */
251
252#define FORMAT_UNDEF 0
253#define FORMAT_ASN1 1
254#define FORMAT_TEXT 2
255#define FORMAT_PEM 3
256#define FORMAT_NETSCAPE 4
257#define FORMAT_PKCS12 5
258#define FORMAT_SMIME 6
259#define FORMAT_ENGINE 7
260#define FORMAT_IISSGC 8 /* XXX this stupid macro helps us to avoid
261 * adding yet another param to load_*key() */
262#define FORMAT_PEMRSA 9 /* PEM RSAPubicKey format */
263#define FORMAT_ASN1RSA 10 /* DER RSAPubicKey format */
264#define FORMAT_MSBLOB 11 /* MS Key blob format */
265#define FORMAT_PVK 12 /* MS PVK file format */
266
267#define EXT_COPY_NONE 0
268#define EXT_COPY_ADD 1
269#define EXT_COPY_ALL 2
270
271#define NETSCAPE_CERT_HDR "certificate"
272
273#define APP_PASS_LEN 1024
274
275#define SERIAL_RAND_BITS 64
276
277int app_isdir(const char *);
278
279#define TM_START 0
280#define TM_STOP 1
281double app_tminterval (int stop, int usertime);
282
283#define OPENSSL_NO_SSL_INTERN
284
285#endif
diff --git a/src/usr.bin/openssl/asn1pars.c b/src/usr.bin/openssl/asn1pars.c
new file mode 100644
index 0000000000..6ba43afb97
--- /dev/null
+++ b/src/usr.bin/openssl/asn1pars.c
@@ -0,0 +1,406 @@
1/* $OpenBSD: asn1pars.c,v 1.1 2014/08/26 17:47:24 jsing 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/* A nice addition from Dr Stephen Henson <steve@openssl.org> to
60 * add the -strparse option which parses nested binary structures
61 */
62
63#include <stdio.h>
64#include <stdlib.h>
65#include <limits.h>
66#include <string.h>
67
68#include "apps.h"
69
70#include <openssl/err.h>
71#include <openssl/evp.h>
72#include <openssl/pem.h>
73#include <openssl/x509.h>
74
75/* -inform arg - input format - default PEM (DER or PEM)
76 * -in arg - input file - default stdin
77 * -i - indent the details by depth
78 * -offset - where in the file to start
79 * -length - how many bytes to use
80 * -oid file - extra oid description file
81 */
82
83int asn1parse_main(int, char **);
84
85static int do_generate(BIO * bio, char *genstr, char *genconf, BUF_MEM * buf);
86
87int
88asn1parse_main(int argc, char **argv)
89{
90 int i, badops = 0, offset = 0, ret = 1, j;
91 unsigned int length = 0;
92 long num, tmplen;
93 BIO *in = NULL, *out = NULL, *b64 = NULL, *derout = NULL;
94 int informat, indent = 0, noout = 0, dump = 0;
95 char *infile = NULL, *str = NULL, *prog, *oidfile = NULL, *derfile = NULL;
96 char *genstr = NULL, *genconf = NULL;
97 const char *errstr = NULL;
98 unsigned char *tmpbuf;
99 const unsigned char *ctmpbuf;
100 BUF_MEM *buf = NULL;
101 STACK_OF(OPENSSL_STRING) * osk = NULL;
102 ASN1_TYPE *at = NULL;
103
104 informat = FORMAT_PEM;
105
106 prog = argv[0];
107 argc--;
108 argv++;
109 if ((osk = sk_OPENSSL_STRING_new_null()) == NULL) {
110 BIO_printf(bio_err, "Memory allocation failure\n");
111 goto end;
112 }
113 while (argc >= 1) {
114 if (strcmp(*argv, "-inform") == 0) {
115 if (--argc < 1)
116 goto bad;
117 informat = str2fmt(*(++argv));
118 } else if (strcmp(*argv, "-in") == 0) {
119 if (--argc < 1)
120 goto bad;
121 infile = *(++argv);
122 } else if (strcmp(*argv, "-out") == 0) {
123 if (--argc < 1)
124 goto bad;
125 derfile = *(++argv);
126 } else if (strcmp(*argv, "-i") == 0) {
127 indent = 1;
128 } else if (strcmp(*argv, "-noout") == 0)
129 noout = 1;
130 else if (strcmp(*argv, "-oid") == 0) {
131 if (--argc < 1)
132 goto bad;
133 oidfile = *(++argv);
134 } else if (strcmp(*argv, "-offset") == 0) {
135 if (--argc < 1)
136 goto bad;
137 offset = strtonum(*(++argv), 0, INT_MAX, &errstr);
138 if (errstr)
139 goto bad;
140 } else if (strcmp(*argv, "-length") == 0) {
141 if (--argc < 1)
142 goto bad;
143 length = strtonum(*(++argv), 1, UINT_MAX, &errstr);
144 if (errstr)
145 goto bad;
146 } else if (strcmp(*argv, "-dump") == 0) {
147 dump = -1;
148 } else if (strcmp(*argv, "-dlimit") == 0) {
149 if (--argc < 1)
150 goto bad;
151 dump = strtonum(*(++argv), 1, INT_MAX, &errstr);
152 if (errstr)
153 goto bad;
154 } else if (strcmp(*argv, "-strparse") == 0) {
155 if (--argc < 1)
156 goto bad;
157 sk_OPENSSL_STRING_push(osk, *(++argv));
158 } else if (strcmp(*argv, "-genstr") == 0) {
159 if (--argc < 1)
160 goto bad;
161 genstr = *(++argv);
162 } else if (strcmp(*argv, "-genconf") == 0) {
163 if (--argc < 1)
164 goto bad;
165 genconf = *(++argv);
166 } else {
167 BIO_printf(bio_err, "unknown option %s\n", *argv);
168 badops = 1;
169 break;
170 }
171 argc--;
172 argv++;
173 }
174
175 if (badops) {
176bad:
177 BIO_printf(bio_err, "%s [options] <infile\n", prog);
178 BIO_printf(bio_err, "where options are\n");
179 BIO_printf(bio_err, " -inform arg input format - one of DER PEM\n");
180 BIO_printf(bio_err, " -in arg input file\n");
181 BIO_printf(bio_err, " -out arg output file (output format is always DER\n");
182 BIO_printf(bio_err, " -noout arg don't produce any output\n");
183 BIO_printf(bio_err, " -offset arg offset into file\n");
184 BIO_printf(bio_err, " -length arg length of section in file\n");
185 BIO_printf(bio_err, " -i indent entries\n");
186 BIO_printf(bio_err, " -dump dump unknown data in hex form\n");
187 BIO_printf(bio_err, " -dlimit arg dump the first arg bytes of unknown data in hex form\n");
188 BIO_printf(bio_err, " -oid file file of extra oid definitions\n");
189 BIO_printf(bio_err, " -strparse offset\n");
190 BIO_printf(bio_err, " a series of these can be used to 'dig' into multiple\n");
191 BIO_printf(bio_err, " ASN1 blob wrappings\n");
192 BIO_printf(bio_err, " -genstr str string to generate ASN1 structure from\n");
193 BIO_printf(bio_err, " -genconf file file to generate ASN1 structure from\n");
194 goto end;
195 }
196 ERR_load_crypto_strings();
197
198 in = BIO_new(BIO_s_file());
199 out = BIO_new(BIO_s_file());
200 if ((in == NULL) || (out == NULL)) {
201 ERR_print_errors(bio_err);
202 goto end;
203 }
204 BIO_set_fp(out, stdout, BIO_NOCLOSE | BIO_FP_TEXT);
205
206 if (oidfile != NULL) {
207 if (BIO_read_filename(in, oidfile) <= 0) {
208 BIO_printf(bio_err, "problems opening %s\n", oidfile);
209 ERR_print_errors(bio_err);
210 goto end;
211 }
212 OBJ_create_objects(in);
213 }
214 if (infile == NULL)
215 BIO_set_fp(in, stdin, BIO_NOCLOSE);
216 else {
217 if (BIO_read_filename(in, infile) <= 0) {
218 perror(infile);
219 goto end;
220 }
221 }
222
223 if (derfile) {
224 if (!(derout = BIO_new_file(derfile, "wb"))) {
225 BIO_printf(bio_err, "problems opening %s\n", derfile);
226 ERR_print_errors(bio_err);
227 goto end;
228 }
229 }
230 if ((buf = BUF_MEM_new()) == NULL)
231 goto end;
232 if (!BUF_MEM_grow(buf, BUFSIZ * 8))
233 goto end; /* Pre-allocate :-) */
234
235 if (genstr || genconf) {
236 num = do_generate(bio_err, genstr, genconf, buf);
237 if (num < 0) {
238 ERR_print_errors(bio_err);
239 goto end;
240 }
241 } else {
242
243 if (informat == FORMAT_PEM) {
244 BIO *tmp;
245
246 if ((b64 = BIO_new(BIO_f_base64())) == NULL)
247 goto end;
248 BIO_push(b64, in);
249 tmp = in;
250 in = b64;
251 b64 = tmp;
252 }
253 num = 0;
254 for (;;) {
255 if (!BUF_MEM_grow(buf, (int) num + BUFSIZ))
256 goto end;
257 i = BIO_read(in, &(buf->data[num]), BUFSIZ);
258 if (i <= 0)
259 break;
260 num += i;
261 }
262 }
263 str = buf->data;
264
265 /* If any structs to parse go through in sequence */
266
267 if (sk_OPENSSL_STRING_num(osk)) {
268 tmpbuf = (unsigned char *) str;
269 tmplen = num;
270 for (i = 0; i < sk_OPENSSL_STRING_num(osk); i++) {
271 ASN1_TYPE *atmp;
272 int typ;
273 j = strtonum(sk_OPENSSL_STRING_value(osk, i),
274 1, INT_MAX, &errstr);
275 if (errstr) {
276 BIO_printf(bio_err,
277 "'%s' is an invalid number: %s\n",
278 sk_OPENSSL_STRING_value(osk, i), errstr);
279 continue;
280 }
281 tmpbuf += j;
282 tmplen -= j;
283 atmp = at;
284 ctmpbuf = tmpbuf;
285 at = d2i_ASN1_TYPE(NULL, &ctmpbuf, tmplen);
286 ASN1_TYPE_free(atmp);
287 if (!at) {
288 BIO_printf(bio_err, "Error parsing structure\n");
289 ERR_print_errors(bio_err);
290 goto end;
291 }
292 typ = ASN1_TYPE_get(at);
293 if ((typ == V_ASN1_OBJECT) ||
294 (typ == V_ASN1_NULL)) {
295 BIO_printf(bio_err, "Can't parse %s type\n",
296 typ == V_ASN1_NULL ? "NULL" : "OBJECT");
297 ERR_print_errors(bio_err);
298 goto end;
299 }
300 /* hmm... this is a little evil but it works */
301 tmpbuf = at->value.asn1_string->data;
302 tmplen = at->value.asn1_string->length;
303 }
304 str = (char *) tmpbuf;
305 num = tmplen;
306 }
307 if (offset >= num) {
308 BIO_printf(bio_err, "Error: offset too large\n");
309 goto end;
310 }
311 num -= offset;
312
313 if ((length == 0) || ((long) length > num))
314 length = (unsigned int) num;
315 if (derout) {
316 if (BIO_write(derout, str + offset, length) != (int) length) {
317 BIO_printf(bio_err, "Error writing output\n");
318 ERR_print_errors(bio_err);
319 goto end;
320 }
321 }
322 if (!noout &&
323 !ASN1_parse_dump(out, (unsigned char *) &(str[offset]), length,
324 indent, dump)) {
325 ERR_print_errors(bio_err);
326 goto end;
327 }
328 ret = 0;
329end:
330 BIO_free(derout);
331 if (in != NULL)
332 BIO_free(in);
333 if (out != NULL)
334 BIO_free_all(out);
335 if (b64 != NULL)
336 BIO_free(b64);
337 if (ret != 0)
338 ERR_print_errors(bio_err);
339 if (buf != NULL)
340 BUF_MEM_free(buf);
341 if (at != NULL)
342 ASN1_TYPE_free(at);
343 if (osk != NULL)
344 sk_OPENSSL_STRING_free(osk);
345 OBJ_cleanup();
346
347 return (ret);
348}
349
350static int
351do_generate(BIO * bio, char *genstr, char *genconf, BUF_MEM * buf)
352{
353 CONF *cnf = NULL;
354 int len;
355 long errline;
356 unsigned char *p;
357 ASN1_TYPE *atyp = NULL;
358
359 if (genconf) {
360 cnf = NCONF_new(NULL);
361 if (!NCONF_load(cnf, genconf, &errline))
362 goto conferr;
363 if (!genstr)
364 genstr = NCONF_get_string(cnf, "default", "asn1");
365 if (!genstr) {
366 BIO_printf(bio, "Can't find 'asn1' in '%s'\n", genconf);
367 goto err;
368 }
369 }
370 atyp = ASN1_generate_nconf(genstr, cnf);
371 NCONF_free(cnf);
372 cnf = NULL;
373
374 if (!atyp)
375 return -1;
376
377 len = i2d_ASN1_TYPE(atyp, NULL);
378
379 if (len <= 0)
380 goto err;
381
382 if (!BUF_MEM_grow(buf, len))
383 goto err;
384
385 p = (unsigned char *) buf->data;
386
387 i2d_ASN1_TYPE(atyp, &p);
388
389 ASN1_TYPE_free(atyp);
390 return len;
391
392conferr:
393
394 if (errline > 0)
395 BIO_printf(bio, "Error on line %ld of config file '%s'\n",
396 errline, genconf);
397 else
398 BIO_printf(bio, "Error loading config file '%s'\n", genconf);
399
400err:
401 NCONF_free(cnf);
402 ASN1_TYPE_free(atyp);
403
404 return -1;
405
406}
diff --git a/src/usr.bin/openssl/ca.c b/src/usr.bin/openssl/ca.c
new file mode 100644
index 0000000000..c19ecc6616
--- /dev/null
+++ b/src/usr.bin/openssl/ca.c
@@ -0,0 +1,2743 @@
1/* $OpenBSD: ca.c,v 1.1 2014/08/26 17:47:24 jsing 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/* The PPKI stuff has been donated by Jeff Barber <jeffb@issl.atl.hp.com> */
60
61#include <sys/types.h>
62
63#include <ctype.h>
64#include <stdio.h>
65#include <stdlib.h>
66#include <limits.h>
67#include <string.h>
68#include <unistd.h>
69
70#include "apps.h"
71
72#include <openssl/bio.h>
73#include <openssl/bn.h>
74#include <openssl/conf.h>
75#include <openssl/err.h>
76#include <openssl/evp.h>
77#include <openssl/objects.h>
78#include <openssl/ocsp.h>
79#include <openssl/pem.h>
80#include <openssl/txt_db.h>
81#include <openssl/x509.h>
82#include <openssl/x509v3.h>
83
84#define BASE_SECTION "ca"
85
86#define ENV_DEFAULT_CA "default_ca"
87
88#define STRING_MASK "string_mask"
89#define UTF8_IN "utf8"
90
91#define ENV_DIR "dir"
92#define ENV_CERTS "certs"
93#define ENV_CRL_DIR "crl_dir"
94#define ENV_CA_DB "CA_DB"
95#define ENV_NEW_CERTS_DIR "new_certs_dir"
96#define ENV_CERTIFICATE "certificate"
97#define ENV_SERIAL "serial"
98#define ENV_CRLNUMBER "crlnumber"
99#define ENV_CRL "crl"
100#define ENV_PRIVATE_KEY "private_key"
101#define ENV_DEFAULT_DAYS "default_days"
102#define ENV_DEFAULT_STARTDATE "default_startdate"
103#define ENV_DEFAULT_ENDDATE "default_enddate"
104#define ENV_DEFAULT_CRL_DAYS "default_crl_days"
105#define ENV_DEFAULT_CRL_HOURS "default_crl_hours"
106#define ENV_DEFAULT_MD "default_md"
107#define ENV_DEFAULT_EMAIL_DN "email_in_dn"
108#define ENV_PRESERVE "preserve"
109#define ENV_POLICY "policy"
110#define ENV_EXTENSIONS "x509_extensions"
111#define ENV_CRLEXT "crl_extensions"
112#define ENV_MSIE_HACK "msie_hack"
113#define ENV_NAMEOPT "name_opt"
114#define ENV_CERTOPT "cert_opt"
115#define ENV_EXTCOPY "copy_extensions"
116#define ENV_UNIQUE_SUBJECT "unique_subject"
117
118#define ENV_DATABASE "database"
119
120/* Additional revocation information types */
121
122#define REV_NONE 0 /* No addditional information */
123#define REV_CRL_REASON 1 /* Value is CRL reason code */
124#define REV_HOLD 2 /* Value is hold instruction */
125#define REV_KEY_COMPROMISE 3 /* Value is cert key compromise time */
126#define REV_CA_COMPROMISE 4 /* Value is CA key compromise time */
127
128static const char *ca_usage[] = {
129 "usage: ca args\n",
130 "\n",
131 " -verbose - Talk a lot while doing things\n",
132 " -config file - A config file\n",
133 " -name arg - The particular CA definition to use\n",
134 " -gencrl - Generate a new CRL\n",
135 " -crldays days - Days is when the next CRL is due\n",
136 " -crlhours hours - Hours is when the next CRL is due\n",
137 " -startdate YYMMDDHHMMSSZ - certificate validity notBefore\n",
138 " -enddate YYMMDDHHMMSSZ - certificate validity notAfter (overrides -days)\n",
139 " -days arg - number of days to certify the certificate for\n",
140 " -md arg - md to use, one of md2, md5, sha or sha1\n",
141 " -policy arg - The CA 'policy' to support\n",
142 " -keyfile arg - private key file\n",
143 " -keyform arg - private key file format (PEM or ENGINE)\n",
144 " -key arg - key to decode the private key if it is encrypted\n",
145 " -cert file - The CA certificate\n",
146 " -selfsign - sign a certificate with the key associated with it\n",
147 " -in file - The input PEM encoded certificate request(s)\n",
148 " -out file - Where to put the output file(s)\n",
149 " -outdir dir - Where to put output certificates\n",
150 " -infiles .... - The last argument, requests to process\n",
151 " -spkac file - File contains DN and signed public key and challenge\n",
152 " -ss_cert file - File contains a self signed cert to sign\n",
153 " -preserveDN - Don't re-order the DN\n",
154 " -noemailDN - Don't add the EMAIL field into certificate' subject\n",
155 " -batch - Don't ask questions\n",
156 " -msie_hack - msie modifications to handle all those universal strings\n",
157 " -revoke file - Revoke a certificate (given in file)\n",
158 " -subj arg - Use arg instead of request's subject\n",
159 " -utf8 - input characters are UTF8 (default ASCII)\n",
160 " -multivalue-rdn - enable support for multivalued RDNs\n",
161 " -extensions .. - Extension section (override value in config file)\n",
162 " -extfile file - Configuration file with X509v3 extentions to add\n",
163 " -crlexts .. - CRL extension section (override value in config file)\n",
164#ifndef OPENSSL_NO_ENGINE
165 " -engine e - use engine e, possibly a hardware device.\n",
166#endif
167 " -status serial - Shows certificate status given the serial number\n",
168 " -updatedb - Updates db for expired certificates\n",
169 NULL
170};
171
172static void lookup_fail(const char *name, const char *tag);
173static int certify(X509 ** xret, char *infile, EVP_PKEY * pkey, X509 * x509,
174 const EVP_MD * dgst, STACK_OF(OPENSSL_STRING) * sigopts,
175 STACK_OF(CONF_VALUE) * policy, CA_DB * db, BIGNUM * serial, char *subj,
176 unsigned long chtype, int multirdn, int email_dn, char *startdate,
177 char *enddate, long days, int batch, char *ext_sect, CONF * conf,
178 int verbose, unsigned long certopt, unsigned long nameopt,
179 int default_op, int ext_copy, int selfsign);
180static int certify_cert(X509 ** xret, char *infile, EVP_PKEY * pkey,
181 X509 * x509, const EVP_MD * dgst, STACK_OF(OPENSSL_STRING) * sigopts,
182 STACK_OF(CONF_VALUE) * policy, CA_DB * db, BIGNUM * serial, char *subj,
183 unsigned long chtype, int multirdn, int email_dn, char *startdate,
184 char *enddate, long days, int batch, char *ext_sect, CONF * conf,
185 int verbose, unsigned long certopt, unsigned long nameopt, int default_op,
186 int ext_copy, ENGINE * e);
187static int certify_spkac(X509 ** xret, char *infile, EVP_PKEY * pkey,
188 X509 * x509, const EVP_MD * dgst, STACK_OF(OPENSSL_STRING) * sigopts,
189 STACK_OF(CONF_VALUE) * policy, CA_DB * db, BIGNUM * serial, char *subj,
190 unsigned long chtype, int multirdn, int email_dn, char *startdate,
191 char *enddate, long days, char *ext_sect, CONF * conf, int verbose,
192 unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy);
193static void write_new_certificate(BIO * bp, X509 * x, int output_der,
194 int notext);
195static int do_body(X509 ** xret, EVP_PKEY * pkey, X509 * x509,
196 const EVP_MD * dgst, STACK_OF(OPENSSL_STRING) * sigopts,
197 STACK_OF(CONF_VALUE) * policy, CA_DB * db, BIGNUM * serial, char *subj,
198 unsigned long chtype, int multirdn, int email_dn, char *startdate,
199 char *enddate, long days, int batch, int verbose, X509_REQ * req,
200 char *ext_sect, CONF * conf, unsigned long certopt, unsigned long nameopt,
201 int default_op, int ext_copy, int selfsign);
202static int do_revoke(X509 * x509, CA_DB * db, int ext, char *extval);
203static int get_certificate_status(const char *ser_status, CA_DB * db);
204static int do_updatedb(CA_DB * db);
205static int check_time_format(const char *str);
206static char * bin2hex(unsigned char *, size_t);
207char *make_revocation_str(int rev_type, char *rev_arg);
208int make_revoked(X509_REVOKED * rev, const char *str);
209int old_entry_print(BIO * bp, ASN1_OBJECT * obj, ASN1_STRING * str);
210static CONF *conf = NULL;
211static CONF *extconf = NULL;
212static char *section = NULL;
213
214static int preserve = 0;
215static int msie_hack = 0;
216
217
218int ca_main(int, char **);
219
220int
221ca_main(int argc, char **argv)
222{
223 ENGINE *e = NULL;
224 char *key = NULL, *passargin = NULL;
225 int create_ser = 0;
226 int free_key = 0;
227 int total = 0;
228 int total_done = 0;
229 int badops = 0;
230 int ret = 1;
231 int email_dn = 1;
232 int req = 0;
233 int verbose = 0;
234 int gencrl = 0;
235 int dorevoke = 0;
236 int doupdatedb = 0;
237 long crldays = 0;
238 long crlhours = 0;
239 long crlsec = 0;
240 long errorline = -1;
241 char *configfile = NULL;
242 char *md = NULL;
243 char *policy = NULL;
244 char *keyfile = NULL;
245 char *certfile = NULL;
246 int keyform = FORMAT_PEM;
247 char *infile = NULL;
248 char *spkac_file = NULL;
249 char *ss_cert_file = NULL;
250 char *ser_status = NULL;
251 EVP_PKEY *pkey = NULL;
252 int output_der = 0;
253 char *outfile = NULL;
254 char *outdir = NULL;
255 char *serialfile = NULL;
256 char *crlnumberfile = NULL;
257 char *extensions = NULL;
258 char *extfile = NULL;
259 char *subj = NULL;
260 unsigned long chtype = MBSTRING_ASC;
261 int multirdn = 0;
262 char *tmp_email_dn = NULL;
263 char *crl_ext = NULL;
264 int rev_type = REV_NONE;
265 char *rev_arg = NULL;
266 BIGNUM *serial = NULL;
267 BIGNUM *crlnumber = NULL;
268 char *startdate = NULL;
269 char *enddate = NULL;
270 long days = 0;
271 int batch = 0;
272 int notext = 0;
273 unsigned long nameopt = 0, certopt = 0;
274 int default_op = 1;
275 int ext_copy = EXT_COPY_NONE;
276 int selfsign = 0;
277 X509 *x509 = NULL, *x509p = NULL;
278 X509 *x = NULL;
279 BIO *in = NULL, *out = NULL, *Sout = NULL, *Cout = NULL;
280 char *dbfile = NULL;
281 CA_DB *db = NULL;
282 X509_CRL *crl = NULL;
283 X509_REVOKED *r = NULL;
284 ASN1_TIME *tmptm;
285 ASN1_INTEGER *tmpser;
286 char *f;
287 const char *p;
288 char *const * pp;
289 int i, j;
290 const EVP_MD *dgst = NULL;
291 STACK_OF(CONF_VALUE) * attribs = NULL;
292 STACK_OF(X509) * cert_sk = NULL;
293 STACK_OF(OPENSSL_STRING) * sigopts = NULL;
294#define BSIZE 256
295 char buf[3][BSIZE];
296#ifndef OPENSSL_NO_ENGINE
297 char *engine = NULL;
298#endif
299 char *tofree = NULL;
300 const char *errstr = NULL;
301 DB_ATTR db_attr;
302
303 conf = NULL;
304 key = NULL;
305 section = NULL;
306
307 preserve = 0;
308 msie_hack = 0;
309
310 argc--;
311 argv++;
312 while (argc >= 1) {
313 if (strcmp(*argv, "-verbose") == 0)
314 verbose = 1;
315 else if (strcmp(*argv, "-config") == 0) {
316 if (--argc < 1)
317 goto bad;
318 configfile = *(++argv);
319 } else if (strcmp(*argv, "-name") == 0) {
320 if (--argc < 1)
321 goto bad;
322 section = *(++argv);
323 } else if (strcmp(*argv, "-subj") == 0) {
324 if (--argc < 1)
325 goto bad;
326 subj = *(++argv);
327 /* preserve=1; */
328 } else if (strcmp(*argv, "-utf8") == 0)
329 chtype = MBSTRING_UTF8;
330 else if (strcmp(*argv, "-create_serial") == 0)
331 create_ser = 1;
332 else if (strcmp(*argv, "-multivalue-rdn") == 0)
333 multirdn = 1;
334 else if (strcmp(*argv, "-startdate") == 0) {
335 if (--argc < 1)
336 goto bad;
337 startdate = *(++argv);
338 } else if (strcmp(*argv, "-enddate") == 0) {
339 if (--argc < 1)
340 goto bad;
341 enddate = *(++argv);
342 } else if (strcmp(*argv, "-days") == 0) {
343 if (--argc < 1)
344 goto bad;
345 days = strtonum(*(++argv), 0, LONG_MAX, &errstr);
346 if (errstr)
347 goto bad;
348 } else if (strcmp(*argv, "-md") == 0) {
349 if (--argc < 1)
350 goto bad;
351 md = *(++argv);
352 } else if (strcmp(*argv, "-policy") == 0) {
353 if (--argc < 1)
354 goto bad;
355 policy = *(++argv);
356 } else if (strcmp(*argv, "-keyfile") == 0) {
357 if (--argc < 1)
358 goto bad;
359 keyfile = *(++argv);
360 } else if (strcmp(*argv, "-keyform") == 0) {
361 if (--argc < 1)
362 goto bad;
363 keyform = str2fmt(*(++argv));
364 } else if (strcmp(*argv, "-passin") == 0) {
365 if (--argc < 1)
366 goto bad;
367 passargin = *(++argv);
368 } else if (strcmp(*argv, "-key") == 0) {
369 if (--argc < 1)
370 goto bad;
371 key = *(++argv);
372 } else if (strcmp(*argv, "-cert") == 0) {
373 if (--argc < 1)
374 goto bad;
375 certfile = *(++argv);
376 } else if (strcmp(*argv, "-selfsign") == 0)
377 selfsign = 1;
378 else if (strcmp(*argv, "-in") == 0) {
379 if (--argc < 1)
380 goto bad;
381 infile = *(++argv);
382 req = 1;
383 } else if (strcmp(*argv, "-out") == 0) {
384 if (--argc < 1)
385 goto bad;
386 outfile = *(++argv);
387 } else if (strcmp(*argv, "-outdir") == 0) {
388 if (--argc < 1)
389 goto bad;
390 outdir = *(++argv);
391 } else if (strcmp(*argv, "-sigopt") == 0) {
392 if (--argc < 1)
393 goto bad;
394 if (!sigopts)
395 sigopts = sk_OPENSSL_STRING_new_null();
396 if (!sigopts ||
397 !sk_OPENSSL_STRING_push(sigopts, *(++argv)))
398 goto bad;
399 } else if (strcmp(*argv, "-notext") == 0)
400 notext = 1;
401 else if (strcmp(*argv, "-batch") == 0)
402 batch = 1;
403 else if (strcmp(*argv, "-preserveDN") == 0)
404 preserve = 1;
405 else if (strcmp(*argv, "-noemailDN") == 0)
406 email_dn = 0;
407 else if (strcmp(*argv, "-gencrl") == 0)
408 gencrl = 1;
409 else if (strcmp(*argv, "-msie_hack") == 0)
410 msie_hack = 1;
411 else if (strcmp(*argv, "-crldays") == 0) {
412 if (--argc < 1)
413 goto bad;
414 crldays = strtonum(*(++argv), 0, LONG_MAX, &errstr);
415 if (errstr)
416 goto bad;
417 } else if (strcmp(*argv, "-crlhours") == 0) {
418 if (--argc < 1)
419 goto bad;
420 crlhours = strtonum(*(++argv), 0, LONG_MAX, &errstr);
421 if (errstr)
422 goto bad;
423 } else if (strcmp(*argv, "-crlsec") == 0) {
424 if (--argc < 1)
425 goto bad;
426 crlsec = strtonum(*(++argv), 0, LONG_MAX, &errstr);
427 if (errstr)
428 goto bad;
429 } else if (strcmp(*argv, "-infiles") == 0) {
430 argc--;
431 argv++;
432 req = 1;
433 break;
434 } else if (strcmp(*argv, "-ss_cert") == 0) {
435 if (--argc < 1)
436 goto bad;
437 ss_cert_file = *(++argv);
438 req = 1;
439 } else if (strcmp(*argv, "-spkac") == 0) {
440 if (--argc < 1)
441 goto bad;
442 spkac_file = *(++argv);
443 req = 1;
444 } else if (strcmp(*argv, "-revoke") == 0) {
445 if (--argc < 1)
446 goto bad;
447 infile = *(++argv);
448 dorevoke = 1;
449 } else if (strcmp(*argv, "-extensions") == 0) {
450 if (--argc < 1)
451 goto bad;
452 extensions = *(++argv);
453 } else if (strcmp(*argv, "-extfile") == 0) {
454 if (--argc < 1)
455 goto bad;
456 extfile = *(++argv);
457 } else if (strcmp(*argv, "-status") == 0) {
458 if (--argc < 1)
459 goto bad;
460 ser_status = *(++argv);
461 } else if (strcmp(*argv, "-updatedb") == 0) {
462 doupdatedb = 1;
463 } else if (strcmp(*argv, "-crlexts") == 0) {
464 if (--argc < 1)
465 goto bad;
466 crl_ext = *(++argv);
467 } else if (strcmp(*argv, "-crl_reason") == 0) {
468 if (--argc < 1)
469 goto bad;
470 rev_arg = *(++argv);
471 rev_type = REV_CRL_REASON;
472 } else if (strcmp(*argv, "-crl_hold") == 0) {
473 if (--argc < 1)
474 goto bad;
475 rev_arg = *(++argv);
476 rev_type = REV_HOLD;
477 } else if (strcmp(*argv, "-crl_compromise") == 0) {
478 if (--argc < 1)
479 goto bad;
480 rev_arg = *(++argv);
481 rev_type = REV_KEY_COMPROMISE;
482 } else if (strcmp(*argv, "-crl_CA_compromise") == 0) {
483 if (--argc < 1)
484 goto bad;
485 rev_arg = *(++argv);
486 rev_type = REV_CA_COMPROMISE;
487 }
488#ifndef OPENSSL_NO_ENGINE
489 else if (strcmp(*argv, "-engine") == 0) {
490 if (--argc < 1)
491 goto bad;
492 engine = *(++argv);
493 }
494#endif
495 else {
496bad:
497 if (errstr)
498 BIO_printf(bio_err, "invalid argument %s: %s\n",
499 *argv, errstr);
500 else
501 BIO_printf(bio_err, "unknown option %s\n", *argv);
502 badops = 1;
503 break;
504 }
505 argc--;
506 argv++;
507 }
508
509 if (badops) {
510 const char **pp2;
511
512 for (pp2 = ca_usage; (*pp2 != NULL); pp2++)
513 BIO_printf(bio_err, "%s", *pp2);
514 goto err;
515 }
516 ERR_load_crypto_strings();
517
518 /*****************************************************************/
519 tofree = NULL;
520 if (configfile == NULL)
521 configfile = getenv("OPENSSL_CONF");
522 if (configfile == NULL)
523 configfile = getenv("SSLEAY_CONF");
524 if (configfile == NULL) {
525 if ((tofree = make_config_name()) == NULL) {
526 BIO_printf(bio_err, "error making config file name\n");
527 goto err;
528 }
529 configfile = tofree;
530 }
531 BIO_printf(bio_err, "Using configuration from %s\n", configfile);
532 conf = NCONF_new(NULL);
533 if (NCONF_load(conf, configfile, &errorline) <= 0) {
534 if (errorline <= 0)
535 BIO_printf(bio_err,
536 "error loading the config file '%s'\n",
537 configfile);
538 else
539 BIO_printf(bio_err,
540 "error on line %ld of config file '%s'\n",
541 errorline, configfile);
542 goto err;
543 }
544 free(tofree);
545 tofree = NULL;
546
547#ifndef OPENSSL_NO_ENGINE
548 e = setup_engine(bio_err, engine, 0);
549#endif
550
551 /* Lets get the config section we are using */
552 if (section == NULL) {
553 section = NCONF_get_string(conf, BASE_SECTION, ENV_DEFAULT_CA);
554 if (section == NULL) {
555 lookup_fail(BASE_SECTION, ENV_DEFAULT_CA);
556 goto err;
557 }
558 }
559 if (conf != NULL) {
560 p = NCONF_get_string(conf, NULL, "oid_file");
561 if (p == NULL)
562 ERR_clear_error();
563 if (p != NULL) {
564 BIO *oid_bio;
565
566 oid_bio = BIO_new_file(p, "r");
567 if (oid_bio == NULL) {
568 /*
569 BIO_printf(bio_err,
570 "problems opening %s for extra oid's\n", p);
571 ERR_print_errors(bio_err);
572 */
573 ERR_clear_error();
574 } else {
575 OBJ_create_objects(oid_bio);
576 BIO_free(oid_bio);
577 }
578 }
579 if (!add_oid_section(bio_err, conf)) {
580 ERR_print_errors(bio_err);
581 goto err;
582 }
583 }
584 f = NCONF_get_string(conf, section, STRING_MASK);
585 if (!f)
586 ERR_clear_error();
587
588 if (f && !ASN1_STRING_set_default_mask_asc(f)) {
589 BIO_printf(bio_err,
590 "Invalid global string mask setting %s\n", f);
591 goto err;
592 }
593 if (chtype != MBSTRING_UTF8) {
594 f = NCONF_get_string(conf, section, UTF8_IN);
595 if (!f)
596 ERR_clear_error();
597 else if (!strcmp(f, "yes"))
598 chtype = MBSTRING_UTF8;
599 }
600 db_attr.unique_subject = 1;
601 p = NCONF_get_string(conf, section, ENV_UNIQUE_SUBJECT);
602 if (p) {
603 db_attr.unique_subject = parse_yesno(p, 1);
604 } else
605 ERR_clear_error();
606
607 in = BIO_new(BIO_s_file());
608 out = BIO_new(BIO_s_file());
609 Sout = BIO_new(BIO_s_file());
610 Cout = BIO_new(BIO_s_file());
611 if ((in == NULL) || (out == NULL) || (Sout == NULL) || (Cout == NULL)) {
612 ERR_print_errors(bio_err);
613 goto err;
614 }
615 /*****************************************************************/
616 /* report status of cert with serial number given on command line */
617 if (ser_status) {
618 if ((dbfile = NCONF_get_string(conf, section,
619 ENV_DATABASE)) == NULL) {
620 lookup_fail(section, ENV_DATABASE);
621 goto err;
622 }
623 db = load_index(dbfile, &db_attr);
624 if (db == NULL)
625 goto err;
626
627 if (!index_index(db))
628 goto err;
629
630 if (get_certificate_status(ser_status, db) != 1)
631 BIO_printf(bio_err, "Error verifying serial %s!\n",
632 ser_status);
633 goto err;
634 }
635 /*****************************************************************/
636 /* we definitely need a private key, so let's get it */
637
638 if ((keyfile == NULL) && ((keyfile = NCONF_get_string(conf,
639 section, ENV_PRIVATE_KEY)) == NULL)) {
640 lookup_fail(section, ENV_PRIVATE_KEY);
641 goto err;
642 }
643 if (!key) {
644 free_key = 1;
645 if (!app_passwd(bio_err, passargin, NULL, &key, NULL)) {
646 BIO_printf(bio_err, "Error getting password\n");
647 goto err;
648 }
649 }
650 pkey = load_key(bio_err, keyfile, keyform, 0, key, e, "CA private key");
651 if (key)
652 OPENSSL_cleanse(key, strlen(key));
653 if (pkey == NULL) {
654 /* load_key() has already printed an appropriate message */
655 goto err;
656 }
657 /*****************************************************************/
658 /* we need a certificate */
659 if (!selfsign || spkac_file || ss_cert_file || gencrl) {
660 if ((certfile == NULL) &&
661 ((certfile = NCONF_get_string(conf,
662 section, ENV_CERTIFICATE)) == NULL)) {
663 lookup_fail(section, ENV_CERTIFICATE);
664 goto err;
665 }
666 x509 = load_cert(bio_err, certfile, FORMAT_PEM, NULL, e,
667 "CA certificate");
668 if (x509 == NULL)
669 goto err;
670
671 if (!X509_check_private_key(x509, pkey)) {
672 BIO_printf(bio_err,
673 "CA certificate and CA private key do not match\n");
674 goto err;
675 }
676 }
677 if (!selfsign)
678 x509p = x509;
679
680 f = NCONF_get_string(conf, BASE_SECTION, ENV_PRESERVE);
681 if (f == NULL)
682 ERR_clear_error();
683 if ((f != NULL) && ((*f == 'y') || (*f == 'Y')))
684 preserve = 1;
685 f = NCONF_get_string(conf, BASE_SECTION, ENV_MSIE_HACK);
686 if (f == NULL)
687 ERR_clear_error();
688 if ((f != NULL) && ((*f == 'y') || (*f == 'Y')))
689 msie_hack = 1;
690
691 f = NCONF_get_string(conf, section, ENV_NAMEOPT);
692
693 if (f) {
694 if (!set_name_ex(&nameopt, f)) {
695 BIO_printf(bio_err,
696 "Invalid name options: \"%s\"\n", f);
697 goto err;
698 }
699 default_op = 0;
700 } else
701 ERR_clear_error();
702
703 f = NCONF_get_string(conf, section, ENV_CERTOPT);
704
705 if (f) {
706 if (!set_cert_ex(&certopt, f)) {
707 BIO_printf(bio_err,
708 "Invalid certificate options: \"%s\"\n", f);
709 goto err;
710 }
711 default_op = 0;
712 } else
713 ERR_clear_error();
714
715 f = NCONF_get_string(conf, section, ENV_EXTCOPY);
716
717 if (f) {
718 if (!set_ext_copy(&ext_copy, f)) {
719 BIO_printf(bio_err,
720 "Invalid extension copy option: \"%s\"\n", f);
721 goto err;
722 }
723 } else
724 ERR_clear_error();
725
726 /*****************************************************************/
727 /* lookup where to write new certificates */
728 if ((outdir == NULL) && (req)) {
729
730 if ((outdir = NCONF_get_string(conf, section,
731 ENV_NEW_CERTS_DIR)) == NULL) {
732 BIO_printf(bio_err, "there needs to be defined a directory for new certificate to be placed in\n");
733 goto err;
734 }
735 /*
736 * outdir is a directory spec, but access() for VMS demands a
737 * filename. In any case, stat(), below, will catch the
738 * problem if outdir is not a directory spec, and the fopen()
739 * or open() will catch an error if there is no write access.
740 *
741 * Presumably, this problem could also be solved by using the
742 * DEC C routines to convert the directory syntax to Unixly,
743 * and give that to access(). However, time's too short to
744 * do that just now.
745 */
746 if (access(outdir, R_OK | W_OK | X_OK) != 0) {
747 BIO_printf(bio_err,
748 "I am unable to access the %s directory\n", outdir);
749 perror(outdir);
750 goto err;
751 }
752 if (app_isdir(outdir) <= 0) {
753 BIO_printf(bio_err,
754 "%s need to be a directory\n", outdir);
755 perror(outdir);
756 goto err;
757 }
758 }
759 /*****************************************************************/
760 /* we need to load the database file */
761 if ((dbfile = NCONF_get_string(conf, section, ENV_DATABASE)) == NULL) {
762 lookup_fail(section, ENV_DATABASE);
763 goto err;
764 }
765 db = load_index(dbfile, &db_attr);
766 if (db == NULL)
767 goto err;
768
769 /* Lets check some fields */
770 for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
771 pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
772 if ((pp[DB_type][0] != DB_TYPE_REV) &&
773 (pp[DB_rev_date][0] != '\0')) {
774 BIO_printf(bio_err, "entry %d: not revoked yet, but has a revocation date\n", i + 1);
775 goto err;
776 }
777 if ((pp[DB_type][0] == DB_TYPE_REV) &&
778 !make_revoked(NULL, pp[DB_rev_date])) {
779 BIO_printf(bio_err, " in entry %d\n", i + 1);
780 goto err;
781 }
782 if (!check_time_format((char *) pp[DB_exp_date])) {
783 BIO_printf(bio_err, "entry %d: invalid expiry date\n",
784 i + 1);
785 goto err;
786 }
787 p = pp[DB_serial];
788 j = strlen(p);
789 if (*p == '-') {
790 p++;
791 j--;
792 }
793 if ((j & 1) || (j < 2)) {
794 BIO_printf(bio_err,
795 "entry %d: bad serial number length (%d)\n",
796 i + 1, j);
797 goto err;
798 }
799 while (*p) {
800 if (!(((*p >= '0') && (*p <= '9')) ||
801 ((*p >= 'A') && (*p <= 'F')) ||
802 ((*p >= 'a') && (*p <= 'f')))) {
803 BIO_printf(bio_err, "entry %d: bad serial number characters, char pos %ld, char is '%c'\n", i + 1, (long) (p - pp[DB_serial]), *p);
804 goto err;
805 }
806 p++;
807 }
808 }
809 if (verbose) {
810 BIO_set_fp(out, stdout, BIO_NOCLOSE | BIO_FP_TEXT); /* cannot fail */
811 TXT_DB_write(out, db->db);
812 BIO_printf(bio_err, "%d entries loaded from the database\n",
813 sk_OPENSSL_PSTRING_num(db->db->data));
814 BIO_printf(bio_err, "generating index\n");
815 }
816 if (!index_index(db))
817 goto err;
818
819 /*****************************************************************/
820 /* Update the db file for expired certificates */
821 if (doupdatedb) {
822 if (verbose)
823 BIO_printf(bio_err, "Updating %s ...\n", dbfile);
824
825 i = do_updatedb(db);
826 if (i == -1) {
827 BIO_printf(bio_err, "Malloc failure\n");
828 goto err;
829 } else if (i == 0) {
830 if (verbose)
831 BIO_printf(bio_err,
832 "No entries found to mark expired\n");
833 } else {
834 if (!save_index(dbfile, "new", db))
835 goto err;
836
837 if (!rotate_index(dbfile, "new", "old"))
838 goto err;
839
840 if (verbose)
841 BIO_printf(bio_err,
842 "Done. %d entries marked as expired\n", i);
843 }
844 }
845 /*****************************************************************/
846 /* Read extentions config file */
847 if (extfile) {
848 extconf = NCONF_new(NULL);
849 if (NCONF_load(extconf, extfile, &errorline) <= 0) {
850 if (errorline <= 0)
851 BIO_printf(bio_err,
852 "ERROR: loading the config file '%s'\n",
853 extfile);
854 else
855 BIO_printf(bio_err,
856 "ERROR: on line %ld of config file '%s'\n",
857 errorline, extfile);
858 ret = 1;
859 goto err;
860 }
861 if (verbose)
862 BIO_printf(bio_err,
863 "Successfully loaded extensions file %s\n",
864 extfile);
865
866 /* We can have sections in the ext file */
867 if (!extensions && !(extensions = NCONF_get_string(extconf,
868 "default", "extensions")))
869 extensions = "default";
870 }
871 /*****************************************************************/
872 if (req || gencrl) {
873 if (outfile != NULL) {
874 if (BIO_write_filename(Sout, outfile) <= 0) {
875 perror(outfile);
876 goto err;
877 }
878 } else {
879 BIO_set_fp(Sout, stdout, BIO_NOCLOSE | BIO_FP_TEXT);
880 }
881 }
882 if ((md == NULL) && ((md = NCONF_get_string(conf, section,
883 ENV_DEFAULT_MD)) == NULL)) {
884 lookup_fail(section, ENV_DEFAULT_MD);
885 goto err;
886 }
887 if (!strcmp(md, "default")) {
888 int def_nid;
889 if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) <= 0) {
890 BIO_puts(bio_err, "no default digest\n");
891 goto err;
892 }
893 md = (char *) OBJ_nid2sn(def_nid);
894 }
895 if ((dgst = EVP_get_digestbyname(md)) == NULL) {
896 BIO_printf(bio_err,
897 "%s is an unsupported message digest type\n", md);
898 goto err;
899 }
900 if (req) {
901 if ((email_dn == 1) && ((tmp_email_dn = NCONF_get_string(conf,
902 section, ENV_DEFAULT_EMAIL_DN)) != NULL)) {
903 if (strcmp(tmp_email_dn, "no") == 0)
904 email_dn = 0;
905 }
906 if (verbose)
907 BIO_printf(bio_err, "message digest is %s\n",
908 OBJ_nid2ln(dgst->type));
909 if ((policy == NULL) && ((policy = NCONF_get_string(conf,
910 section, ENV_POLICY)) == NULL)) {
911 lookup_fail(section, ENV_POLICY);
912 goto err;
913 }
914 if (verbose)
915 BIO_printf(bio_err, "policy is %s\n", policy);
916
917 if ((serialfile = NCONF_get_string(conf, section,
918 ENV_SERIAL)) == NULL) {
919 lookup_fail(section, ENV_SERIAL);
920 goto err;
921 }
922 if (!extconf) {
923 /*
924 * no '-extfile' option, so we look for extensions in
925 * the main configuration file
926 */
927 if (!extensions) {
928 extensions = NCONF_get_string(conf, section,
929 ENV_EXTENSIONS);
930 if (!extensions)
931 ERR_clear_error();
932 }
933 if (extensions) {
934 /* Check syntax of file */
935 X509V3_CTX ctx;
936 X509V3_set_ctx_test(&ctx);
937 X509V3_set_nconf(&ctx, conf);
938 if (!X509V3_EXT_add_nconf(conf, &ctx,
939 extensions, NULL)) {
940 BIO_printf(bio_err,
941 "Error Loading extension section %s\n",
942 extensions);
943 ret = 1;
944 goto err;
945 }
946 }
947 }
948 if (startdate == NULL) {
949 startdate = NCONF_get_string(conf, section,
950 ENV_DEFAULT_STARTDATE);
951 if (startdate == NULL)
952 ERR_clear_error();
953 }
954 if (startdate && !ASN1_TIME_set_string(NULL, startdate)) {
955 BIO_printf(bio_err, "start date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n");
956 goto err;
957 }
958 if (startdate == NULL)
959 startdate = "today";
960
961 if (enddate == NULL) {
962 enddate = NCONF_get_string(conf, section,
963 ENV_DEFAULT_ENDDATE);
964 if (enddate == NULL)
965 ERR_clear_error();
966 }
967 if (enddate && !ASN1_TIME_set_string(NULL, enddate)) {
968 BIO_printf(bio_err, "end date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n");
969 goto err;
970 }
971 if (days == 0) {
972 if (!NCONF_get_number(conf, section,
973 ENV_DEFAULT_DAYS, &days))
974 days = 0;
975 }
976 if (!enddate && (days == 0)) {
977 BIO_printf(bio_err,
978 "cannot lookup how many days to certify for\n");
979 goto err;
980 }
981 if ((serial = load_serial(serialfile, create_ser, NULL)) ==
982 NULL) {
983 BIO_printf(bio_err,
984 "error while loading serial number\n");
985 goto err;
986 }
987 if (verbose) {
988 if (BN_is_zero(serial))
989 BIO_printf(bio_err,
990 "next serial number is 00\n");
991 else {
992 if ((f = BN_bn2hex(serial)) == NULL)
993 goto err;
994 BIO_printf(bio_err,
995 "next serial number is %s\n", f);
996 free(f);
997 }
998 }
999 if ((attribs = NCONF_get_section(conf, policy)) == NULL) {
1000 BIO_printf(bio_err,
1001 "unable to find 'section' for %s\n", policy);
1002 goto err;
1003 }
1004 if ((cert_sk = sk_X509_new_null()) == NULL) {
1005 BIO_printf(bio_err, "Memory allocation failure\n");
1006 goto err;
1007 }
1008 if (spkac_file != NULL) {
1009 total++;
1010 j = certify_spkac(&x, spkac_file, pkey, x509, dgst,
1011 sigopts, attribs, db, serial, subj, chtype,
1012 multirdn, email_dn, startdate, enddate, days,
1013 extensions, conf, verbose, certopt, nameopt,
1014 default_op, ext_copy);
1015 if (j < 0)
1016 goto err;
1017 if (j > 0) {
1018 total_done++;
1019 BIO_printf(bio_err, "\n");
1020 if (!BN_add_word(serial, 1))
1021 goto err;
1022 if (!sk_X509_push(cert_sk, x)) {
1023 BIO_printf(bio_err,
1024 "Memory allocation failure\n");
1025 goto err;
1026 }
1027 if (outfile) {
1028 output_der = 1;
1029 batch = 1;
1030 }
1031 }
1032 }
1033 if (ss_cert_file != NULL) {
1034 total++;
1035 j = certify_cert(&x, ss_cert_file, pkey, x509, dgst,
1036 sigopts, attribs, db, serial, subj, chtype,
1037 multirdn, email_dn, startdate, enddate, days, batch,
1038 extensions, conf, verbose, certopt, nameopt,
1039 default_op, ext_copy, e);
1040 if (j < 0)
1041 goto err;
1042 if (j > 0) {
1043 total_done++;
1044 BIO_printf(bio_err, "\n");
1045 if (!BN_add_word(serial, 1))
1046 goto err;
1047 if (!sk_X509_push(cert_sk, x)) {
1048 BIO_printf(bio_err,
1049 "Memory allocation failure\n");
1050 goto err;
1051 }
1052 }
1053 }
1054 if (infile != NULL) {
1055 total++;
1056 j = certify(&x, infile, pkey, x509p, dgst, sigopts,
1057 attribs, db, serial, subj, chtype, multirdn,
1058 email_dn, startdate, enddate, days, batch,
1059 extensions, conf, verbose, certopt, nameopt,
1060 default_op, ext_copy, selfsign);
1061 if (j < 0)
1062 goto err;
1063 if (j > 0) {
1064 total_done++;
1065 BIO_printf(bio_err, "\n");
1066 if (!BN_add_word(serial, 1))
1067 goto err;
1068 if (!sk_X509_push(cert_sk, x)) {
1069 BIO_printf(bio_err,
1070 "Memory allocation failure\n");
1071 goto err;
1072 }
1073 }
1074 }
1075 for (i = 0; i < argc; i++) {
1076 total++;
1077 j = certify(&x, argv[i], pkey, x509p, dgst, sigopts,
1078 attribs, db, serial, subj, chtype, multirdn,
1079 email_dn, startdate, enddate, days, batch,
1080 extensions, conf, verbose, certopt, nameopt,
1081 default_op, ext_copy, selfsign);
1082 if (j < 0)
1083 goto err;
1084 if (j > 0) {
1085 total_done++;
1086 BIO_printf(bio_err, "\n");
1087 if (!BN_add_word(serial, 1))
1088 goto err;
1089 if (!sk_X509_push(cert_sk, x)) {
1090 BIO_printf(bio_err,
1091 "Memory allocation failure\n");
1092 goto err;
1093 }
1094 }
1095 }
1096 /*
1097 * we have a stack of newly certified certificates and a data
1098 * base and serial number that need updating
1099 */
1100
1101 if (sk_X509_num(cert_sk) > 0) {
1102 if (!batch) {
1103 BIO_printf(bio_err, "\n%d out of %d certificate requests certified, commit? [y/n]", total_done, total);
1104 (void) BIO_flush(bio_err);
1105 buf[0][0] = '\0';
1106 if (!fgets(buf[0], 10, stdin)) {
1107 BIO_printf(bio_err, "CERTIFICATION CANCELED: I/O error\n");
1108 ret = 0;
1109 goto err;
1110 }
1111 if ((buf[0][0] != 'y') && (buf[0][0] != 'Y')) {
1112 BIO_printf(bio_err, "CERTIFICATION CANCELED\n");
1113 ret = 0;
1114 goto err;
1115 }
1116 }
1117 BIO_printf(bio_err, "Write out database with %d new entries\n", sk_X509_num(cert_sk));
1118
1119 if (!save_serial(serialfile, "new", serial, NULL))
1120 goto err;
1121
1122 if (!save_index(dbfile, "new", db))
1123 goto err;
1124 }
1125 if (verbose)
1126 BIO_printf(bio_err, "writing new certificates\n");
1127 for (i = 0; i < sk_X509_num(cert_sk); i++) {
1128 int k;
1129 char *serial;
1130 unsigned char *data;
1131
1132 x = sk_X509_value(cert_sk, i);
1133
1134 j = x->cert_info->serialNumber->length;
1135 data = (unsigned char *)x->cert_info->serialNumber->data;
1136 if (j > 0)
1137 serial = bin2hex(data, j);
1138 else
1139 serial = strdup("00");
1140 if (serial) {
1141 k = snprintf(buf[2], sizeof(buf[2]),
1142 "%s/%s.pem", outdir, serial);
1143 free(serial);
1144 if (k == -1 || k >= sizeof(buf[2])) {
1145 BIO_printf(bio_err,
1146 "certificate file name too long\n");
1147 goto err;
1148 }
1149 } else {
1150 BIO_printf(bio_err,
1151 "memory allocation failed\n");
1152 goto err;
1153 }
1154 if (verbose)
1155 BIO_printf(bio_err, "writing %s\n", buf[2]);
1156
1157 if (BIO_write_filename(Cout, buf[2]) <= 0) {
1158 perror(buf[2]);
1159 goto err;
1160 }
1161 write_new_certificate(Cout, x, 0, notext);
1162 write_new_certificate(Sout, x, output_der, notext);
1163 }
1164
1165 if (sk_X509_num(cert_sk)) {
1166 /* Rename the database and the serial file */
1167 if (!rotate_serial(serialfile, "new", "old"))
1168 goto err;
1169
1170 if (!rotate_index(dbfile, "new", "old"))
1171 goto err;
1172
1173 BIO_printf(bio_err, "Data Base Updated\n");
1174 }
1175 }
1176 /*****************************************************************/
1177 if (gencrl) {
1178 int crl_v2 = 0;
1179 if (!crl_ext) {
1180 crl_ext = NCONF_get_string(conf, section, ENV_CRLEXT);
1181 if (!crl_ext)
1182 ERR_clear_error();
1183 }
1184 if (crl_ext) {
1185 /* Check syntax of file */
1186 X509V3_CTX ctx;
1187 X509V3_set_ctx_test(&ctx);
1188 X509V3_set_nconf(&ctx, conf);
1189 if (!X509V3_EXT_add_nconf(conf, &ctx, crl_ext, NULL)) {
1190 BIO_printf(bio_err,
1191 "Error Loading CRL extension section %s\n",
1192 crl_ext);
1193 ret = 1;
1194 goto err;
1195 }
1196 }
1197 if ((crlnumberfile = NCONF_get_string(conf, section,
1198 ENV_CRLNUMBER)) != NULL)
1199 if ((crlnumber = load_serial(crlnumberfile, 0,
1200 NULL)) == NULL) {
1201 BIO_printf(bio_err,
1202 "error while loading CRL number\n");
1203 goto err;
1204 }
1205 if (!crldays && !crlhours && !crlsec) {
1206 if (!NCONF_get_number(conf, section,
1207 ENV_DEFAULT_CRL_DAYS, &crldays))
1208 crldays = 0;
1209 if (!NCONF_get_number(conf, section,
1210 ENV_DEFAULT_CRL_HOURS, &crlhours))
1211 crlhours = 0;
1212 ERR_clear_error();
1213 }
1214 if ((crldays == 0) && (crlhours == 0) && (crlsec == 0)) {
1215 BIO_printf(bio_err, "cannot lookup how long until the next CRL is issued\n");
1216 goto err;
1217 }
1218 if (verbose)
1219 BIO_printf(bio_err, "making CRL\n");
1220 if ((crl = X509_CRL_new()) == NULL)
1221 goto err;
1222 if (!X509_CRL_set_issuer_name(crl, X509_get_subject_name(x509)))
1223 goto err;
1224
1225 tmptm = ASN1_TIME_new();
1226 if (!tmptm)
1227 goto err;
1228 X509_gmtime_adj(tmptm, 0);
1229 X509_CRL_set_lastUpdate(crl, tmptm);
1230 if (!X509_time_adj_ex(tmptm, crldays,
1231 crlhours * 60 * 60 + crlsec, NULL)) {
1232 BIO_puts(bio_err, "error setting CRL nextUpdate\n");
1233 goto err;
1234 }
1235 X509_CRL_set_nextUpdate(crl, tmptm);
1236
1237 ASN1_TIME_free(tmptm);
1238
1239 for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
1240 pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
1241 if (pp[DB_type][0] == DB_TYPE_REV) {
1242 if ((r = X509_REVOKED_new()) == NULL)
1243 goto err;
1244 j = make_revoked(r, pp[DB_rev_date]);
1245 if (!j)
1246 goto err;
1247 if (j == 2)
1248 crl_v2 = 1;
1249 if (!BN_hex2bn(&serial, pp[DB_serial]))
1250 goto err;
1251 tmpser = BN_to_ASN1_INTEGER(serial, NULL);
1252 BN_free(serial);
1253 serial = NULL;
1254 if (!tmpser)
1255 goto err;
1256 X509_REVOKED_set_serialNumber(r, tmpser);
1257 ASN1_INTEGER_free(tmpser);
1258 X509_CRL_add0_revoked(crl, r);
1259 }
1260 }
1261
1262 /*
1263 * sort the data so it will be written in serial number order
1264 */
1265 X509_CRL_sort(crl);
1266
1267 /* we now have a CRL */
1268 if (verbose)
1269 BIO_printf(bio_err, "signing CRL\n");
1270
1271 /* Add any extensions asked for */
1272
1273 if (crl_ext || crlnumberfile != NULL) {
1274 X509V3_CTX crlctx;
1275 X509V3_set_ctx(&crlctx, x509, NULL, NULL, crl, 0);
1276 X509V3_set_nconf(&crlctx, conf);
1277
1278 if (crl_ext)
1279 if (!X509V3_EXT_CRL_add_nconf(conf, &crlctx,
1280 crl_ext, crl))
1281 goto err;
1282 if (crlnumberfile != NULL) {
1283 tmpser = BN_to_ASN1_INTEGER(crlnumber, NULL);
1284 if (!tmpser)
1285 goto err;
1286 X509_CRL_add1_ext_i2d(crl, NID_crl_number,
1287 tmpser, 0, 0);
1288 ASN1_INTEGER_free(tmpser);
1289 crl_v2 = 1;
1290 if (!BN_add_word(crlnumber, 1))
1291 goto err;
1292 }
1293 }
1294 if (crl_ext || crl_v2) {
1295 if (!X509_CRL_set_version(crl, 1))
1296 goto err; /* version 2 CRL */
1297 }
1298 if (crlnumberfile != NULL) /* we have a CRL number that
1299 * need updating */
1300 if (!save_serial(crlnumberfile, "new", crlnumber, NULL))
1301 goto err;
1302
1303 if (crlnumber) {
1304 BN_free(crlnumber);
1305 crlnumber = NULL;
1306 }
1307 if (!do_X509_CRL_sign(bio_err, crl, pkey, dgst, sigopts))
1308 goto err;
1309
1310 PEM_write_bio_X509_CRL(Sout, crl);
1311
1312 if (crlnumberfile != NULL) /* Rename the crlnumber file */
1313 if (!rotate_serial(crlnumberfile, "new", "old"))
1314 goto err;
1315
1316 }
1317 /*****************************************************************/
1318 if (dorevoke) {
1319 if (infile == NULL) {
1320 BIO_printf(bio_err, "no input files\n");
1321 goto err;
1322 } else {
1323 X509 *revcert;
1324 revcert = load_cert(bio_err, infile, FORMAT_PEM,
1325 NULL, e, infile);
1326 if (revcert == NULL)
1327 goto err;
1328 j = do_revoke(revcert, db, rev_type, rev_arg);
1329 if (j <= 0)
1330 goto err;
1331 X509_free(revcert);
1332
1333 if (!save_index(dbfile, "new", db))
1334 goto err;
1335
1336 if (!rotate_index(dbfile, "new", "old"))
1337 goto err;
1338
1339 BIO_printf(bio_err, "Data Base Updated\n");
1340 }
1341 }
1342 /*****************************************************************/
1343 ret = 0;
1344
1345err:
1346 free(tofree);
1347
1348 BIO_free_all(Cout);
1349 BIO_free_all(Sout);
1350 BIO_free_all(out);
1351 BIO_free_all(in);
1352
1353 if (cert_sk)
1354 sk_X509_pop_free(cert_sk, X509_free);
1355
1356 if (ret)
1357 ERR_print_errors(bio_err);
1358 if (free_key && key)
1359 free(key);
1360 BN_free(serial);
1361 BN_free(crlnumber);
1362 free_index(db);
1363 if (sigopts)
1364 sk_OPENSSL_STRING_free(sigopts);
1365 EVP_PKEY_free(pkey);
1366 if (x509)
1367 X509_free(x509);
1368 X509_CRL_free(crl);
1369 NCONF_free(conf);
1370 NCONF_free(extconf);
1371 OBJ_cleanup();
1372
1373 return (ret);
1374}
1375
1376static void
1377lookup_fail(const char *name, const char *tag)
1378{
1379 BIO_printf(bio_err, "variable lookup failed for %s::%s\n", name, tag);
1380}
1381
1382static int
1383certify(X509 ** xret, char *infile, EVP_PKEY * pkey, X509 * x509,
1384 const EVP_MD * dgst, STACK_OF(OPENSSL_STRING) * sigopts,
1385 STACK_OF(CONF_VALUE) * policy, CA_DB * db, BIGNUM * serial, char *subj,
1386 unsigned long chtype, int multirdn, int email_dn, char *startdate,
1387 char *enddate, long days, int batch, char *ext_sect, CONF * lconf,
1388 int verbose, unsigned long certopt, unsigned long nameopt, int default_op,
1389 int ext_copy, int selfsign)
1390{
1391 X509_REQ *req = NULL;
1392 BIO *in = NULL;
1393 EVP_PKEY *pktmp = NULL;
1394 int ok = -1, i;
1395
1396 in = BIO_new(BIO_s_file());
1397
1398 if (BIO_read_filename(in, infile) <= 0) {
1399 perror(infile);
1400 goto err;
1401 }
1402 if ((req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL)) == NULL) {
1403 BIO_printf(bio_err, "Error reading certificate request in %s\n",
1404 infile);
1405 goto err;
1406 }
1407 if (verbose)
1408 X509_REQ_print(bio_err, req);
1409
1410 BIO_printf(bio_err, "Check that the request matches the signature\n");
1411
1412 if (selfsign && !X509_REQ_check_private_key(req, pkey)) {
1413 BIO_printf(bio_err,
1414 "Certificate request and CA private key do not match\n");
1415 ok = 0;
1416 goto err;
1417 }
1418 if ((pktmp = X509_REQ_get_pubkey(req)) == NULL) {
1419 BIO_printf(bio_err, "error unpacking public key\n");
1420 goto err;
1421 }
1422 i = X509_REQ_verify(req, pktmp);
1423 EVP_PKEY_free(pktmp);
1424 if (i < 0) {
1425 ok = 0;
1426 BIO_printf(bio_err, "Signature verification problems....\n");
1427 goto err;
1428 }
1429 if (i == 0) {
1430 ok = 0;
1431 BIO_printf(bio_err,
1432 "Signature did not match the certificate request\n");
1433 goto err;
1434 } else
1435 BIO_printf(bio_err, "Signature ok\n");
1436
1437 ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial,
1438 subj, chtype, multirdn, email_dn, startdate, enddate, days, batch,
1439 verbose, req, ext_sect, lconf, certopt, nameopt, default_op,
1440 ext_copy, selfsign);
1441
1442err:
1443 if (req != NULL)
1444 X509_REQ_free(req);
1445 if (in != NULL)
1446 BIO_free(in);
1447 return (ok);
1448}
1449
1450static int
1451certify_cert(X509 ** xret, char *infile, EVP_PKEY * pkey, X509 * x509,
1452 const EVP_MD * dgst, STACK_OF(OPENSSL_STRING) * sigopts,
1453 STACK_OF(CONF_VALUE) * policy, CA_DB * db, BIGNUM * serial, char *subj,
1454 unsigned long chtype, int multirdn, int email_dn, char *startdate,
1455 char *enddate, long days, int batch, char *ext_sect, CONF * lconf,
1456 int verbose, unsigned long certopt, unsigned long nameopt, int default_op,
1457 int ext_copy, ENGINE * e)
1458{
1459 X509 *req = NULL;
1460 X509_REQ *rreq = NULL;
1461 EVP_PKEY *pktmp = NULL;
1462 int ok = -1, i;
1463
1464 if ((req = load_cert(bio_err, infile, FORMAT_PEM, NULL, e,
1465 infile)) == NULL)
1466 goto err;
1467 if (verbose)
1468 X509_print(bio_err, req);
1469
1470 BIO_printf(bio_err, "Check that the request matches the signature\n");
1471
1472 if ((pktmp = X509_get_pubkey(req)) == NULL) {
1473 BIO_printf(bio_err, "error unpacking public key\n");
1474 goto err;
1475 }
1476 i = X509_verify(req, pktmp);
1477 EVP_PKEY_free(pktmp);
1478 if (i < 0) {
1479 ok = 0;
1480 BIO_printf(bio_err, "Signature verification problems....\n");
1481 goto err;
1482 }
1483 if (i == 0) {
1484 ok = 0;
1485 BIO_printf(bio_err,
1486 "Signature did not match the certificate\n");
1487 goto err;
1488 } else
1489 BIO_printf(bio_err, "Signature ok\n");
1490
1491 if ((rreq = X509_to_X509_REQ(req, NULL, EVP_md5())) == NULL)
1492 goto err;
1493
1494 ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial,
1495 subj, chtype, multirdn, email_dn, startdate, enddate, days, batch,
1496 verbose, rreq, ext_sect, lconf, certopt, nameopt, default_op,
1497 ext_copy, 0);
1498
1499err:
1500 if (rreq != NULL)
1501 X509_REQ_free(rreq);
1502 if (req != NULL)
1503 X509_free(req);
1504 return (ok);
1505}
1506
1507static int
1508do_body(X509 ** xret, EVP_PKEY * pkey, X509 * x509, const EVP_MD * dgst,
1509 STACK_OF(OPENSSL_STRING) * sigopts, STACK_OF(CONF_VALUE) * policy,
1510 CA_DB * db, BIGNUM * serial, char *subj, unsigned long chtype, int multirdn,
1511 int email_dn, char *startdate, char *enddate, long days, int batch,
1512 int verbose, X509_REQ * req, char *ext_sect, CONF * lconf,
1513 unsigned long certopt, unsigned long nameopt, int default_op,
1514 int ext_copy, int selfsign)
1515{
1516 X509_NAME *name = NULL, *CAname = NULL, *subject = NULL, *dn_subject = NULL;
1517 ASN1_UTCTIME *tm, *tmptm;
1518 ASN1_STRING *str, *str2;
1519 ASN1_OBJECT *obj;
1520 X509 *ret = NULL;
1521 X509_CINF *ci;
1522 X509_NAME_ENTRY *ne;
1523 X509_NAME_ENTRY *tne, *push;
1524 EVP_PKEY *pktmp;
1525 int ok = -1, i, j, last, nid;
1526 const char *p;
1527 CONF_VALUE *cv;
1528 OPENSSL_STRING row[DB_NUMBER];
1529 OPENSSL_STRING *irow = NULL;
1530 OPENSSL_STRING *rrow = NULL;
1531 char buf[25];
1532
1533 tmptm = ASN1_UTCTIME_new();
1534 if (tmptm == NULL) {
1535 BIO_printf(bio_err, "malloc error\n");
1536 return (0);
1537 }
1538 for (i = 0; i < DB_NUMBER; i++)
1539 row[i] = NULL;
1540
1541 if (subj) {
1542 X509_NAME *n = parse_name(subj, chtype, multirdn);
1543
1544 if (!n) {
1545 ERR_print_errors(bio_err);
1546 goto err;
1547 }
1548 X509_REQ_set_subject_name(req, n);
1549 req->req_info->enc.modified = 1;
1550 X509_NAME_free(n);
1551 }
1552 if (default_op)
1553 BIO_printf(bio_err,
1554 "The Subject's Distinguished Name is as follows\n");
1555
1556 name = X509_REQ_get_subject_name(req);
1557 for (i = 0; i < X509_NAME_entry_count(name); i++) {
1558 ne = X509_NAME_get_entry(name, i);
1559 str = X509_NAME_ENTRY_get_data(ne);
1560 obj = X509_NAME_ENTRY_get_object(ne);
1561
1562 if (msie_hack) {
1563 /* assume all type should be strings */
1564 nid = OBJ_obj2nid(ne->object);
1565
1566 if (str->type == V_ASN1_UNIVERSALSTRING)
1567 ASN1_UNIVERSALSTRING_to_string(str);
1568
1569 if ((str->type == V_ASN1_IA5STRING) &&
1570 (nid != NID_pkcs9_emailAddress))
1571 str->type = V_ASN1_T61STRING;
1572
1573 if ((nid == NID_pkcs9_emailAddress) &&
1574 (str->type == V_ASN1_PRINTABLESTRING))
1575 str->type = V_ASN1_IA5STRING;
1576 }
1577 /* If no EMAIL is wanted in the subject */
1578 if ((OBJ_obj2nid(obj) == NID_pkcs9_emailAddress) && (!email_dn))
1579 continue;
1580
1581 /* check some things */
1582 if ((OBJ_obj2nid(obj) == NID_pkcs9_emailAddress) &&
1583 (str->type != V_ASN1_IA5STRING)) {
1584 BIO_printf(bio_err, "\nemailAddress type needs to be of type IA5STRING\n");
1585 goto err;
1586 }
1587 if ((str->type != V_ASN1_BMPSTRING) &&
1588 (str->type != V_ASN1_UTF8STRING)) {
1589 j = ASN1_PRINTABLE_type(str->data, str->length);
1590 if (((j == V_ASN1_T61STRING) &&
1591 (str->type != V_ASN1_T61STRING)) ||
1592 ((j == V_ASN1_IA5STRING) &&
1593 (str->type == V_ASN1_PRINTABLESTRING))) {
1594 BIO_printf(bio_err, "\nThe string contains characters that are illegal for the ASN.1 type\n");
1595 goto err;
1596 }
1597 }
1598 if (default_op)
1599 old_entry_print(bio_err, obj, str);
1600 }
1601
1602 /* Ok, now we check the 'policy' stuff. */
1603 if ((subject = X509_NAME_new()) == NULL) {
1604 BIO_printf(bio_err, "Memory allocation failure\n");
1605 goto err;
1606 }
1607 /* take a copy of the issuer name before we mess with it. */
1608 if (selfsign)
1609 CAname = X509_NAME_dup(name);
1610 else
1611 CAname = X509_NAME_dup(x509->cert_info->subject);
1612 if (CAname == NULL)
1613 goto err;
1614 str = str2 = NULL;
1615
1616 for (i = 0; i < sk_CONF_VALUE_num(policy); i++) {
1617 cv = sk_CONF_VALUE_value(policy, i); /* get the object id */
1618 if ((j = OBJ_txt2nid(cv->name)) == NID_undef) {
1619 BIO_printf(bio_err, "%s:unknown object type in 'policy' configuration\n", cv->name);
1620 goto err;
1621 }
1622 obj = OBJ_nid2obj(j);
1623
1624 last = -1;
1625 for (;;) {
1626 /* lookup the object in the supplied name list */
1627 j = X509_NAME_get_index_by_OBJ(name, obj, last);
1628 if (j < 0) {
1629 if (last != -1)
1630 break;
1631 tne = NULL;
1632 } else {
1633 tne = X509_NAME_get_entry(name, j);
1634 }
1635 last = j;
1636
1637 /* depending on the 'policy', decide what to do. */
1638 push = NULL;
1639 if (strcmp(cv->value, "optional") == 0) {
1640 if (tne != NULL)
1641 push = tne;
1642 } else if (strcmp(cv->value, "supplied") == 0) {
1643 if (tne == NULL) {
1644 BIO_printf(bio_err, "The %s field needed to be supplied and was missing\n", cv->name);
1645 goto err;
1646 } else
1647 push = tne;
1648 } else if (strcmp(cv->value, "match") == 0) {
1649 int last2;
1650
1651 if (tne == NULL) {
1652 BIO_printf(bio_err, "The mandatory %s field was missing\n", cv->name);
1653 goto err;
1654 }
1655 last2 = -1;
1656
1657again2:
1658 j = X509_NAME_get_index_by_OBJ(CAname, obj, last2);
1659 if ((j < 0) && (last2 == -1)) {
1660 BIO_printf(bio_err, "The %s field does not exist in the CA certificate,\nthe 'policy' is misconfigured\n", cv->name);
1661 goto err;
1662 }
1663 if (j >= 0) {
1664 push = X509_NAME_get_entry(CAname, j);
1665 str = X509_NAME_ENTRY_get_data(tne);
1666 str2 = X509_NAME_ENTRY_get_data(push);
1667 last2 = j;
1668 if (ASN1_STRING_cmp(str, str2) != 0)
1669 goto again2;
1670 }
1671 if (j < 0) {
1672 BIO_printf(bio_err, "The %s field needed to be the same in the\nCA certificate (%s) and the request (%s)\n", cv->name, ((str2 == NULL) ? "NULL" : (char *) str2->data), ((str == NULL) ? "NULL" : (char *) str->data));
1673 goto err;
1674 }
1675 } else {
1676 BIO_printf(bio_err, "%s:invalid type in 'policy' configuration\n", cv->value);
1677 goto err;
1678 }
1679
1680 if (push != NULL) {
1681 if (!X509_NAME_add_entry(subject, push,
1682 -1, 0)) {
1683 if (push != NULL)
1684 X509_NAME_ENTRY_free(push);
1685 BIO_printf(bio_err,
1686 "Memory allocation failure\n");
1687 goto err;
1688 }
1689 }
1690 if (j < 0)
1691 break;
1692 }
1693 }
1694
1695 if (preserve) {
1696 X509_NAME_free(subject);
1697 /* subject=X509_NAME_dup(X509_REQ_get_subject_name(req)); */
1698 subject = X509_NAME_dup(name);
1699 if (subject == NULL)
1700 goto err;
1701 }
1702 if (verbose)
1703 BIO_printf(bio_err, "The subject name appears to be ok, checking data base for clashes\n");
1704
1705 /* Build the correct Subject if no e-mail is wanted in the subject */
1706 /*
1707 * and add it later on because of the method extensions are added
1708 * (altName)
1709 */
1710
1711 if (email_dn)
1712 dn_subject = subject;
1713 else {
1714 X509_NAME_ENTRY *tmpne;
1715 /*
1716 * Its best to dup the subject DN and then delete any email
1717 * addresses because this retains its structure.
1718 */
1719 if (!(dn_subject = X509_NAME_dup(subject))) {
1720 BIO_printf(bio_err, "Memory allocation failure\n");
1721 goto err;
1722 }
1723 while ((i = X509_NAME_get_index_by_NID(dn_subject,
1724 NID_pkcs9_emailAddress, -1)) >= 0) {
1725 tmpne = X509_NAME_get_entry(dn_subject, i);
1726 X509_NAME_delete_entry(dn_subject, i);
1727 X509_NAME_ENTRY_free(tmpne);
1728 }
1729 }
1730
1731 if (BN_is_zero(serial))
1732 row[DB_serial] = strdup("00");
1733 else
1734 row[DB_serial] = BN_bn2hex(serial);
1735 if (row[DB_serial] == NULL) {
1736 BIO_printf(bio_err, "Memory allocation failure\n");
1737 goto err;
1738 }
1739 if (db->attributes.unique_subject) {
1740 OPENSSL_STRING *crow = row;
1741
1742 rrow = TXT_DB_get_by_index(db->db, DB_name, crow);
1743 if (rrow != NULL) {
1744 BIO_printf(bio_err,
1745 "ERROR:There is already a certificate for %s\n",
1746 row[DB_name]);
1747 }
1748 }
1749 if (rrow == NULL) {
1750 rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
1751 if (rrow != NULL) {
1752 BIO_printf(bio_err,
1753 "ERROR:Serial number %s has already been issued,\n",
1754 row[DB_serial]);
1755 BIO_printf(bio_err, " check the database/serial_file for corruption\n");
1756 }
1757 }
1758 if (rrow != NULL) {
1759 BIO_printf(bio_err,
1760 "The matching entry has the following details\n");
1761 if (rrow[DB_type][0] == 'E')
1762 p = "Expired";
1763 else if (rrow[DB_type][0] == 'R')
1764 p = "Revoked";
1765 else if (rrow[DB_type][0] == 'V')
1766 p = "Valid";
1767 else
1768 p = "\ninvalid type, Data base error\n";
1769 BIO_printf(bio_err, "Type :%s\n", p);
1770 if (rrow[DB_type][0] == 'R') {
1771 p = rrow[DB_exp_date];
1772 if (p == NULL)
1773 p = "undef";
1774 BIO_printf(bio_err, "Was revoked on:%s\n", p);
1775 }
1776 p = rrow[DB_exp_date];
1777 if (p == NULL)
1778 p = "undef";
1779 BIO_printf(bio_err, "Expires on :%s\n", p);
1780 p = rrow[DB_serial];
1781 if (p == NULL)
1782 p = "undef";
1783 BIO_printf(bio_err, "Serial Number :%s\n", p);
1784 p = rrow[DB_file];
1785 if (p == NULL)
1786 p = "undef";
1787 BIO_printf(bio_err, "File name :%s\n", p);
1788 p = rrow[DB_name];
1789 if (p == NULL)
1790 p = "undef";
1791 BIO_printf(bio_err, "Subject Name :%s\n", p);
1792 ok = -1; /* This is now a 'bad' error. */
1793 goto err;
1794 }
1795 /* We are now totally happy, lets make and sign the certificate */
1796 if (verbose)
1797 BIO_printf(bio_err, "Everything appears to be ok, creating and signing the certificate\n");
1798
1799 if ((ret = X509_new()) == NULL)
1800 goto err;
1801 ci = ret->cert_info;
1802
1803#ifdef X509_V3
1804 /* Make it an X509 v3 certificate. */
1805 if (!X509_set_version(ret, 2))
1806 goto err;
1807#endif
1808
1809 if (BN_to_ASN1_INTEGER(serial, ci->serialNumber) == NULL)
1810 goto err;
1811 if (selfsign) {
1812 if (!X509_set_issuer_name(ret, subject))
1813 goto err;
1814 } else {
1815 if (!X509_set_issuer_name(ret, X509_get_subject_name(x509)))
1816 goto err;
1817 }
1818
1819 if (strcmp(startdate, "today") == 0)
1820 X509_gmtime_adj(X509_get_notBefore(ret), 0);
1821 else
1822 ASN1_TIME_set_string(X509_get_notBefore(ret), startdate);
1823
1824 if (enddate == NULL)
1825 X509_time_adj_ex(X509_get_notAfter(ret), days, 0, NULL);
1826 else
1827 ASN1_TIME_set_string(X509_get_notAfter(ret), enddate);
1828
1829 if (!X509_set_subject_name(ret, subject))
1830 goto err;
1831
1832 pktmp = X509_REQ_get_pubkey(req);
1833 i = X509_set_pubkey(ret, pktmp);
1834 EVP_PKEY_free(pktmp);
1835 if (!i)
1836 goto err;
1837
1838 /* Lets add the extensions, if there are any */
1839 if (ext_sect) {
1840 X509V3_CTX ctx;
1841 if (ci->version == NULL)
1842 if ((ci->version = ASN1_INTEGER_new()) == NULL)
1843 goto err;
1844 ASN1_INTEGER_set(ci->version, 2); /* version 3 certificate */
1845
1846 /*
1847 * Free the current entries if any, there should not be any I
1848 * believe
1849 */
1850 if (ci->extensions != NULL)
1851 sk_X509_EXTENSION_pop_free(ci->extensions,
1852 X509_EXTENSION_free);
1853
1854 ci->extensions = NULL;
1855
1856 /* Initialize the context structure */
1857 if (selfsign)
1858 X509V3_set_ctx(&ctx, ret, ret, req, NULL, 0);
1859 else
1860 X509V3_set_ctx(&ctx, x509, ret, req, NULL, 0);
1861
1862 if (extconf) {
1863 if (verbose)
1864 BIO_printf(bio_err,
1865 "Extra configuration file found\n");
1866
1867 /* Use the extconf configuration db LHASH */
1868 X509V3_set_nconf(&ctx, extconf);
1869
1870 /* Test the structure (needed?) */
1871 /* X509V3_set_ctx_test(&ctx); */
1872
1873 /* Adds exts contained in the configuration file */
1874 if (!X509V3_EXT_add_nconf(extconf, &ctx,
1875 ext_sect, ret)) {
1876 BIO_printf(bio_err,
1877 "ERROR: adding extensions in section %s\n",
1878 ext_sect);
1879 ERR_print_errors(bio_err);
1880 goto err;
1881 }
1882 if (verbose)
1883 BIO_printf(bio_err, "Successfully added extensions from file.\n");
1884 } else if (ext_sect) {
1885 /* We found extensions to be set from config file */
1886 X509V3_set_nconf(&ctx, lconf);
1887
1888 if (!X509V3_EXT_add_nconf(lconf, &ctx, ext_sect, ret)) {
1889 BIO_printf(bio_err,
1890 "ERROR: adding extensions in section %s\n",
1891 ext_sect);
1892 ERR_print_errors(bio_err);
1893 goto err;
1894 }
1895 if (verbose)
1896 BIO_printf(bio_err, "Successfully added extensions from config\n");
1897 }
1898 }
1899 /* Copy extensions from request (if any) */
1900
1901 if (!copy_extensions(ret, req, ext_copy)) {
1902 BIO_printf(bio_err, "ERROR: adding extensions from request\n");
1903 ERR_print_errors(bio_err);
1904 goto err;
1905 }
1906 /* Set the right value for the noemailDN option */
1907 if (email_dn == 0) {
1908 if (!X509_set_subject_name(ret, dn_subject))
1909 goto err;
1910 }
1911 if (!default_op) {
1912 BIO_printf(bio_err, "Certificate Details:\n");
1913 /*
1914 * Never print signature details because signature not
1915 * present
1916 */
1917 certopt |= X509_FLAG_NO_SIGDUMP | X509_FLAG_NO_SIGNAME;
1918 X509_print_ex(bio_err, ret, nameopt, certopt);
1919 }
1920 BIO_printf(bio_err, "Certificate is to be certified until ");
1921 ASN1_TIME_print(bio_err, X509_get_notAfter(ret));
1922 if (days)
1923 BIO_printf(bio_err, " (%ld days)", days);
1924 BIO_printf(bio_err, "\n");
1925
1926 if (!batch) {
1927
1928 BIO_printf(bio_err, "Sign the certificate? [y/n]:");
1929 (void) BIO_flush(bio_err);
1930 buf[0] = '\0';
1931 if (!fgets(buf, sizeof(buf) - 1, stdin)) {
1932 BIO_printf(bio_err,
1933 "CERTIFICATE WILL NOT BE CERTIFIED: I/O error\n");
1934 ok = 0;
1935 goto err;
1936 }
1937 if (!((buf[0] == 'y') || (buf[0] == 'Y'))) {
1938 BIO_printf(bio_err,
1939 "CERTIFICATE WILL NOT BE CERTIFIED\n");
1940 ok = 0;
1941 goto err;
1942 }
1943 }
1944 pktmp = X509_get_pubkey(ret);
1945 if (EVP_PKEY_missing_parameters(pktmp) &&
1946 !EVP_PKEY_missing_parameters(pkey))
1947 EVP_PKEY_copy_parameters(pktmp, pkey);
1948 EVP_PKEY_free(pktmp);
1949
1950 if (!do_X509_sign(bio_err, ret, pkey, dgst, sigopts))
1951 goto err;
1952
1953 /* We now just add it to the database */
1954 row[DB_type] = malloc(2);
1955
1956 tm = X509_get_notAfter(ret);
1957 row[DB_exp_date] = malloc(tm->length + 1);
1958 memcpy(row[DB_exp_date], tm->data, tm->length);
1959 row[DB_exp_date][tm->length] = '\0';
1960
1961 row[DB_rev_date] = NULL;
1962
1963 /* row[DB_serial] done already */
1964 row[DB_file] = malloc(8);
1965 row[DB_name] = X509_NAME_oneline(X509_get_subject_name(ret), NULL, 0);
1966
1967 if ((row[DB_type] == NULL) || (row[DB_exp_date] == NULL) ||
1968 (row[DB_file] == NULL) || (row[DB_name] == NULL)) {
1969 BIO_printf(bio_err, "Memory allocation failure\n");
1970 goto err;
1971 }
1972 (void) strlcpy(row[DB_file], "unknown", 8);
1973 row[DB_type][0] = 'V';
1974 row[DB_type][1] = '\0';
1975
1976 if ((irow = reallocarray(NULL, DB_NUMBER + 1, sizeof(char *))) ==
1977 NULL) {
1978 BIO_printf(bio_err, "Memory allocation failure\n");
1979 goto err;
1980 }
1981 for (i = 0; i < DB_NUMBER; i++) {
1982 irow[i] = row[i];
1983 row[i] = NULL;
1984 }
1985 irow[DB_NUMBER] = NULL;
1986
1987 if (!TXT_DB_insert(db->db, irow)) {
1988 BIO_printf(bio_err, "failed to update database\n");
1989 BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error);
1990 goto err;
1991 }
1992 ok = 1;
1993err:
1994 for (i = 0; i < DB_NUMBER; i++)
1995 free(row[i]);
1996
1997 if (CAname != NULL)
1998 X509_NAME_free(CAname);
1999 if (subject != NULL)
2000 X509_NAME_free(subject);
2001 if ((dn_subject != NULL) && !email_dn)
2002 X509_NAME_free(dn_subject);
2003 if (tmptm != NULL)
2004 ASN1_UTCTIME_free(tmptm);
2005 if (ok <= 0) {
2006 if (ret != NULL)
2007 X509_free(ret);
2008 ret = NULL;
2009 } else
2010 *xret = ret;
2011 return (ok);
2012}
2013
2014static void
2015write_new_certificate(BIO * bp, X509 * x, int output_der, int notext)
2016{
2017 if (output_der) {
2018 (void) i2d_X509_bio(bp, x);
2019 return;
2020 }
2021#if 0
2022 /* ??? Not needed since X509_print prints all this stuff anyway */
2023 f = X509_NAME_oneline(X509_get_issuer_name(x), buf, 256);
2024 BIO_printf(bp, "issuer :%s\n", f);
2025
2026 f = X509_NAME_oneline(X509_get_subject_name(x), buf, 256);
2027 BIO_printf(bp, "subject:%s\n", f);
2028
2029 BIO_puts(bp, "serial :");
2030 i2a_ASN1_INTEGER(bp, x->cert_info->serialNumber);
2031 BIO_puts(bp, "\n\n");
2032#endif
2033 if (!notext)
2034 X509_print(bp, x);
2035 PEM_write_bio_X509(bp, x);
2036}
2037
2038static int
2039certify_spkac(X509 ** xret, char *infile, EVP_PKEY * pkey, X509 * x509,
2040 const EVP_MD * dgst, STACK_OF(OPENSSL_STRING) * sigopts,
2041 STACK_OF(CONF_VALUE) * policy, CA_DB * db, BIGNUM * serial, char *subj,
2042 unsigned long chtype, int multirdn, int email_dn, char *startdate,
2043 char *enddate, long days, char *ext_sect, CONF * lconf, int verbose,
2044 unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy)
2045{
2046 STACK_OF(CONF_VALUE) * sk = NULL;
2047 LHASH_OF(CONF_VALUE) * parms = NULL;
2048 X509_REQ *req = NULL;
2049 CONF_VALUE *cv = NULL;
2050 NETSCAPE_SPKI *spki = NULL;
2051 X509_REQ_INFO *ri;
2052 char *type, *buf;
2053 EVP_PKEY *pktmp = NULL;
2054 X509_NAME *n = NULL;
2055 X509_NAME_ENTRY *ne = NULL;
2056 int ok = -1, i, j;
2057 long errline;
2058 int nid;
2059
2060 /*
2061 * Load input file into a hash table. (This is just an easy
2062 * way to read and parse the file, then put it into a convenient
2063 * STACK format).
2064 */
2065 parms = CONF_load(NULL, infile, &errline);
2066 if (parms == NULL) {
2067 BIO_printf(bio_err, "error on line %ld of %s\n",
2068 errline, infile);
2069 ERR_print_errors(bio_err);
2070 goto err;
2071 }
2072 sk = CONF_get_section(parms, "default");
2073 if (sk_CONF_VALUE_num(sk) == 0) {
2074 BIO_printf(bio_err, "no name/value pairs found in %s\n",
2075 infile);
2076 CONF_free(parms);
2077 goto err;
2078 }
2079 /*
2080 * Now create a dummy X509 request structure. We don't actually
2081 * have an X509 request, but we have many of the components
2082 * (a public key, various DN components). The idea is that we
2083 * put these components into the right X509 request structure
2084 * and we can use the same code as if you had a real X509 request.
2085 */
2086 req = X509_REQ_new();
2087 if (req == NULL) {
2088 ERR_print_errors(bio_err);
2089 goto err;
2090 }
2091 /*
2092 * Build up the subject name set.
2093 */
2094 ri = req->req_info;
2095 n = ri->subject;
2096
2097 for (i = 0;; i++) {
2098 if (sk_CONF_VALUE_num(sk) <= i)
2099 break;
2100
2101 cv = sk_CONF_VALUE_value(sk, i);
2102 type = cv->name;
2103 /*
2104 * Skip past any leading X. X: X, etc to allow for multiple
2105 * instances
2106 */
2107 for (buf = cv->name; *buf; buf++) {
2108 if ((*buf == ':') || (*buf == ',') || (*buf == '.')) {
2109 buf++;
2110 if (*buf)
2111 type = buf;
2112 break;
2113 }
2114 }
2115
2116 buf = cv->value;
2117 if ((nid = OBJ_txt2nid(type)) == NID_undef) {
2118 if (strcmp(type, "SPKAC") == 0) {
2119 spki = NETSCAPE_SPKI_b64_decode(cv->value, -1);
2120 if (spki == NULL) {
2121 BIO_printf(bio_err, "unable to load Netscape SPKAC structure\n");
2122 ERR_print_errors(bio_err);
2123 goto err;
2124 }
2125 }
2126 continue;
2127 }
2128 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
2129 (unsigned char *)buf, -1, -1, 0))
2130 goto err;
2131 }
2132 if (spki == NULL) {
2133 BIO_printf(bio_err,
2134 "Netscape SPKAC structure not found in %s\n", infile);
2135 goto err;
2136 }
2137 /*
2138 * Now extract the key from the SPKI structure.
2139 */
2140
2141 BIO_printf(bio_err,
2142 "Check that the SPKAC request matches the signature\n");
2143
2144 if ((pktmp = NETSCAPE_SPKI_get_pubkey(spki)) == NULL) {
2145 BIO_printf(bio_err, "error unpacking SPKAC public key\n");
2146 goto err;
2147 }
2148 j = NETSCAPE_SPKI_verify(spki, pktmp);
2149 if (j <= 0) {
2150 BIO_printf(bio_err,
2151 "signature verification failed on SPKAC public key\n");
2152 goto err;
2153 }
2154 BIO_printf(bio_err, "Signature ok\n");
2155
2156 X509_REQ_set_pubkey(req, pktmp);
2157 EVP_PKEY_free(pktmp);
2158 ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial,
2159 subj, chtype, multirdn, email_dn, startdate, enddate, days, 1,
2160 verbose, req, ext_sect, lconf, certopt, nameopt, default_op,
2161 ext_copy, 0);
2162
2163err:
2164 if (req != NULL)
2165 X509_REQ_free(req);
2166 if (parms != NULL)
2167 CONF_free(parms);
2168 if (spki != NULL)
2169 NETSCAPE_SPKI_free(spki);
2170 if (ne != NULL)
2171 X509_NAME_ENTRY_free(ne);
2172
2173 return (ok);
2174}
2175
2176static int
2177check_time_format(const char *str)
2178{
2179 return ASN1_TIME_set_string(NULL, str);
2180}
2181
2182static int
2183do_revoke(X509 * x509, CA_DB * db, int type, char *value)
2184{
2185 ASN1_UTCTIME *tm = NULL;
2186 char *row[DB_NUMBER], **rrow, **irow;
2187 char *rev_str = NULL;
2188 BIGNUM *bn = NULL;
2189 int ok = -1, i;
2190
2191 for (i = 0; i < DB_NUMBER; i++)
2192 row[i] = NULL;
2193 row[DB_name] = X509_NAME_oneline(X509_get_subject_name(x509), NULL, 0);
2194 bn = ASN1_INTEGER_to_BN(X509_get_serialNumber(x509), NULL);
2195 if (!bn)
2196 goto err;
2197 if (BN_is_zero(bn))
2198 row[DB_serial] = strdup("00");
2199 else
2200 row[DB_serial] = BN_bn2hex(bn);
2201 BN_free(bn);
2202 if ((row[DB_name] == NULL) || (row[DB_serial] == NULL)) {
2203 BIO_printf(bio_err, "Memory allocation failure\n");
2204 goto err;
2205 }
2206 /*
2207 * We have to lookup by serial number because name lookup skips
2208 * revoked certs
2209 */
2210 rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
2211 if (rrow == NULL) {
2212 BIO_printf(bio_err,
2213 "Adding Entry with serial number %s to DB for %s\n",
2214 row[DB_serial], row[DB_name]);
2215
2216 /* We now just add it to the database */
2217 row[DB_type] = malloc(2);
2218
2219 tm = X509_get_notAfter(x509);
2220 row[DB_exp_date] = malloc(tm->length + 1);
2221 memcpy(row[DB_exp_date], tm->data, tm->length);
2222 row[DB_exp_date][tm->length] = '\0';
2223
2224 row[DB_rev_date] = NULL;
2225
2226 /* row[DB_serial] done already */
2227 row[DB_file] = malloc(8);
2228
2229 /* row[DB_name] done already */
2230
2231 if ((row[DB_type] == NULL) || (row[DB_exp_date] == NULL) ||
2232 (row[DB_file] == NULL)) {
2233 BIO_printf(bio_err, "Memory allocation failure\n");
2234 goto err;
2235 }
2236 (void) strlcpy(row[DB_file], "unknown", 8);
2237 row[DB_type][0] = 'V';
2238 row[DB_type][1] = '\0';
2239
2240 if ((irow = reallocarray(NULL, sizeof(char *),
2241 (DB_NUMBER + 1))) == NULL) {
2242 BIO_printf(bio_err, "Memory allocation failure\n");
2243 goto err;
2244 }
2245 for (i = 0; i < DB_NUMBER; i++) {
2246 irow[i] = row[i];
2247 row[i] = NULL;
2248 }
2249 irow[DB_NUMBER] = NULL;
2250
2251 if (!TXT_DB_insert(db->db, irow)) {
2252 BIO_printf(bio_err, "failed to update database\n");
2253 BIO_printf(bio_err, "TXT_DB error number %ld\n",
2254 db->db->error);
2255 goto err;
2256 }
2257 /* Revoke Certificate */
2258 ok = do_revoke(x509, db, type, value);
2259
2260 goto err;
2261
2262 } else if (index_name_cmp_noconst(row, rrow)) {
2263 BIO_printf(bio_err, "ERROR:name does not match %s\n",
2264 row[DB_name]);
2265 goto err;
2266 } else if (rrow[DB_type][0] == 'R') {
2267 BIO_printf(bio_err, "ERROR:Already revoked, serial number %s\n",
2268 row[DB_serial]);
2269 goto err;
2270 } else {
2271 BIO_printf(bio_err, "Revoking Certificate %s.\n",
2272 rrow[DB_serial]);
2273 rev_str = make_revocation_str(type, value);
2274 if (!rev_str) {
2275 BIO_printf(bio_err, "Error in revocation arguments\n");
2276 goto err;
2277 }
2278 rrow[DB_type][0] = 'R';
2279 rrow[DB_type][1] = '\0';
2280 rrow[DB_rev_date] = rev_str;
2281 }
2282 ok = 1;
2283
2284err:
2285 for (i = 0; i < DB_NUMBER; i++)
2286 free(row[i]);
2287
2288 return (ok);
2289}
2290
2291static int
2292get_certificate_status(const char *serial, CA_DB * db)
2293{
2294 char *row[DB_NUMBER], **rrow;
2295 int ok = -1, i;
2296
2297 /* Free Resources */
2298 for (i = 0; i < DB_NUMBER; i++)
2299 row[i] = NULL;
2300
2301 /* Malloc needed char spaces */
2302 row[DB_serial] = malloc(strlen(serial) + 2);
2303 if (row[DB_serial] == NULL) {
2304 BIO_printf(bio_err, "Malloc failure\n");
2305 goto err;
2306 }
2307 if (strlen(serial) % 2) {
2308 /* Set the first char to 0 */ ;
2309 row[DB_serial][0] = '0';
2310
2311 /* Copy String from serial to row[DB_serial] */
2312 memcpy(row[DB_serial] + 1, serial, strlen(serial));
2313 row[DB_serial][strlen(serial) + 1] = '\0';
2314 } else {
2315 /* Copy String from serial to row[DB_serial] */
2316 memcpy(row[DB_serial], serial, strlen(serial));
2317 row[DB_serial][strlen(serial)] = '\0';
2318 }
2319
2320 /* Make it Upper Case */
2321 for (i = 0; row[DB_serial][i] != '\0'; i++)
2322 row[DB_serial][i] = toupper((unsigned char) row[DB_serial][i]);
2323
2324
2325 ok = 1;
2326
2327 /* Search for the certificate */
2328 rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
2329 if (rrow == NULL) {
2330 BIO_printf(bio_err, "Serial %s not present in db.\n",
2331 row[DB_serial]);
2332 ok = -1;
2333 goto err;
2334 } else if (rrow[DB_type][0] == 'V') {
2335 BIO_printf(bio_err, "%s=Valid (%c)\n",
2336 row[DB_serial], rrow[DB_type][0]);
2337 goto err;
2338 } else if (rrow[DB_type][0] == 'R') {
2339 BIO_printf(bio_err, "%s=Revoked (%c)\n",
2340 row[DB_serial], rrow[DB_type][0]);
2341 goto err;
2342 } else if (rrow[DB_type][0] == 'E') {
2343 BIO_printf(bio_err, "%s=Expired (%c)\n",
2344 row[DB_serial], rrow[DB_type][0]);
2345 goto err;
2346 } else if (rrow[DB_type][0] == 'S') {
2347 BIO_printf(bio_err, "%s=Suspended (%c)\n",
2348 row[DB_serial], rrow[DB_type][0]);
2349 goto err;
2350 } else {
2351 BIO_printf(bio_err, "%s=Unknown (%c).\n",
2352 row[DB_serial], rrow[DB_type][0]);
2353 ok = -1;
2354 }
2355
2356err:
2357 for (i = 0; i < DB_NUMBER; i++)
2358 free(row[i]);
2359
2360 return (ok);
2361}
2362
2363static int
2364do_updatedb(CA_DB * db)
2365{
2366 ASN1_UTCTIME *a_tm = NULL;
2367 int i, cnt = 0;
2368 int db_y2k, a_y2k; /* flags = 1 if y >= 2000 */
2369 char **rrow, *a_tm_s;
2370
2371 a_tm = ASN1_UTCTIME_new();
2372
2373 /* get actual time and make a string */
2374 a_tm = X509_gmtime_adj(a_tm, 0);
2375 a_tm_s = malloc(a_tm->length + 1);
2376 if (a_tm_s == NULL) {
2377 cnt = -1;
2378 goto err;
2379 }
2380 memcpy(a_tm_s, a_tm->data, a_tm->length);
2381 a_tm_s[a_tm->length] = '\0';
2382
2383 if (strncmp(a_tm_s, "49", 2) <= 0)
2384 a_y2k = 1;
2385 else
2386 a_y2k = 0;
2387
2388 for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
2389 rrow = sk_OPENSSL_PSTRING_value(db->db->data, i);
2390
2391 if (rrow[DB_type][0] == 'V') {
2392 /* ignore entries that are not valid */
2393 if (strncmp(rrow[DB_exp_date], "49", 2) <= 0)
2394 db_y2k = 1;
2395 else
2396 db_y2k = 0;
2397
2398 if (db_y2k == a_y2k) {
2399 /* all on the same y2k side */
2400 if (strcmp(rrow[DB_exp_date], a_tm_s) <= 0) {
2401 rrow[DB_type][0] = 'E';
2402 rrow[DB_type][1] = '\0';
2403 cnt++;
2404
2405 BIO_printf(bio_err, "%s=Expired\n",
2406 rrow[DB_serial]);
2407 }
2408 } else if (db_y2k < a_y2k) {
2409 rrow[DB_type][0] = 'E';
2410 rrow[DB_type][1] = '\0';
2411 cnt++;
2412
2413 BIO_printf(bio_err, "%s=Expired\n",
2414 rrow[DB_serial]);
2415 }
2416 }
2417 }
2418
2419err:
2420 ASN1_UTCTIME_free(a_tm);
2421 free(a_tm_s);
2422
2423 return (cnt);
2424}
2425
2426static const char *crl_reasons[] = {
2427 /* CRL reason strings */
2428 "unspecified",
2429 "keyCompromise",
2430 "CACompromise",
2431 "affiliationChanged",
2432 "superseded",
2433 "cessationOfOperation",
2434 "certificateHold",
2435 "removeFromCRL",
2436 /* Additional pseudo reasons */
2437 "holdInstruction",
2438 "keyTime",
2439 "CAkeyTime"
2440};
2441
2442#define NUM_REASONS (sizeof(crl_reasons) / sizeof(char *))
2443
2444/* Given revocation information convert to a DB string.
2445 * The format of the string is:
2446 * revtime[,reason,extra]. Where 'revtime' is the
2447 * revocation time (the current time). 'reason' is the
2448 * optional CRL reason and 'extra' is any additional
2449 * argument
2450 */
2451
2452char *
2453make_revocation_str(int rev_type, char *rev_arg)
2454{
2455 char *other = NULL, *str;
2456 const char *reason = NULL;
2457 ASN1_OBJECT *otmp;
2458 ASN1_UTCTIME *revtm = NULL;
2459 int i;
2460 switch (rev_type) {
2461 case REV_NONE:
2462 break;
2463
2464 case REV_CRL_REASON:
2465 for (i = 0; i < 8; i++) {
2466 if (!strcasecmp(rev_arg, crl_reasons[i])) {
2467 reason = crl_reasons[i];
2468 break;
2469 }
2470 }
2471 if (reason == NULL) {
2472 BIO_printf(bio_err, "Unknown CRL reason %s\n", rev_arg);
2473 return NULL;
2474 }
2475 break;
2476
2477 case REV_HOLD:
2478 /* Argument is an OID */
2479
2480 otmp = OBJ_txt2obj(rev_arg, 0);
2481 ASN1_OBJECT_free(otmp);
2482
2483 if (otmp == NULL) {
2484 BIO_printf(bio_err,
2485 "Invalid object identifier %s\n", rev_arg);
2486 return NULL;
2487 }
2488 reason = "holdInstruction";
2489 other = rev_arg;
2490 break;
2491
2492 case REV_KEY_COMPROMISE:
2493 case REV_CA_COMPROMISE:
2494
2495 /* Argument is the key compromise time */
2496 if (!ASN1_GENERALIZEDTIME_set_string(NULL, rev_arg)) {
2497 BIO_printf(bio_err,
2498 "Invalid time format %s. Need YYYYMMDDHHMMSSZ\n",
2499 rev_arg);
2500 return NULL;
2501 }
2502 other = rev_arg;
2503 if (rev_type == REV_KEY_COMPROMISE)
2504 reason = "keyTime";
2505 else
2506 reason = "CAkeyTime";
2507
2508 break;
2509
2510 }
2511
2512 revtm = X509_gmtime_adj(NULL, 0);
2513 if (asprintf(&str, "%s%s%s%s%s", revtm->data,
2514 reason ? "," : "", reason ? reason : "",
2515 other ? "," : "", other ? other : "") == -1)
2516 str = NULL;
2517 ASN1_UTCTIME_free(revtm);
2518 return str;
2519}
2520
2521/* Convert revocation field to X509_REVOKED entry
2522 * return code:
2523 * 0 error
2524 * 1 OK
2525 * 2 OK and some extensions added (i.e. V2 CRL)
2526 */
2527
2528int
2529make_revoked(X509_REVOKED * rev, const char *str)
2530{
2531 char *tmp = NULL;
2532 int reason_code = -1;
2533 int i, ret = 0;
2534 ASN1_OBJECT *hold = NULL;
2535 ASN1_GENERALIZEDTIME *comp_time = NULL;
2536 ASN1_ENUMERATED *rtmp = NULL;
2537
2538 ASN1_TIME *revDate = NULL;
2539
2540 i = unpack_revinfo(&revDate, &reason_code, &hold, &comp_time, str);
2541
2542 if (i == 0)
2543 goto err;
2544
2545 if (rev && !X509_REVOKED_set_revocationDate(rev, revDate))
2546 goto err;
2547
2548 if (rev && (reason_code != OCSP_REVOKED_STATUS_NOSTATUS)) {
2549 rtmp = ASN1_ENUMERATED_new();
2550 if (!rtmp || !ASN1_ENUMERATED_set(rtmp, reason_code))
2551 goto err;
2552 if (!X509_REVOKED_add1_ext_i2d(rev, NID_crl_reason, rtmp, 0, 0))
2553 goto err;
2554 }
2555 if (rev && comp_time) {
2556 if (!X509_REVOKED_add1_ext_i2d(rev, NID_invalidity_date,
2557 comp_time, 0, 0))
2558 goto err;
2559 }
2560 if (rev && hold) {
2561 if (!X509_REVOKED_add1_ext_i2d(rev, NID_hold_instruction_code,
2562 hold, 0, 0))
2563 goto err;
2564 }
2565 if (reason_code != OCSP_REVOKED_STATUS_NOSTATUS)
2566 ret = 2;
2567 else
2568 ret = 1;
2569
2570err:
2571 free(tmp);
2572
2573 ASN1_OBJECT_free(hold);
2574 ASN1_GENERALIZEDTIME_free(comp_time);
2575 ASN1_ENUMERATED_free(rtmp);
2576 ASN1_TIME_free(revDate);
2577
2578 return ret;
2579}
2580
2581int
2582old_entry_print(BIO * bp, ASN1_OBJECT * obj, ASN1_STRING * str)
2583{
2584 char buf[25], *pbuf, *p;
2585 int j;
2586
2587 j = i2a_ASN1_OBJECT(bp, obj);
2588 pbuf = buf;
2589 for (j = 22 - j; j > 0; j--)
2590 *(pbuf++) = ' ';
2591 *(pbuf++) = ':';
2592 *(pbuf++) = '\0';
2593 BIO_puts(bp, buf);
2594
2595 if (str->type == V_ASN1_PRINTABLESTRING)
2596 BIO_printf(bp, "PRINTABLE:'");
2597 else if (str->type == V_ASN1_T61STRING)
2598 BIO_printf(bp, "T61STRING:'");
2599 else if (str->type == V_ASN1_IA5STRING)
2600 BIO_printf(bp, "IA5STRING:'");
2601 else if (str->type == V_ASN1_UNIVERSALSTRING)
2602 BIO_printf(bp, "UNIVERSALSTRING:'");
2603 else
2604 BIO_printf(bp, "ASN.1 %2d:'", str->type);
2605
2606 p = (char *) str->data;
2607 for (j = str->length; j > 0; j--) {
2608 if ((*p >= ' ') && (*p <= '~'))
2609 BIO_printf(bp, "%c", *p);
2610 else if (*p & 0x80)
2611 BIO_printf(bp, "\\0x%02X", *p);
2612 else if ((unsigned char) *p == 0xf7)
2613 BIO_printf(bp, "^?");
2614 else
2615 BIO_printf(bp, "^%c", *p + '@');
2616 p++;
2617 }
2618 BIO_printf(bp, "'\n");
2619 return 1;
2620}
2621
2622int
2623unpack_revinfo(ASN1_TIME ** prevtm, int *preason, ASN1_OBJECT ** phold,
2624 ASN1_GENERALIZEDTIME ** pinvtm, const char *str)
2625{
2626 char *tmp = NULL;
2627 char *rtime_str, *reason_str = NULL, *arg_str = NULL, *p;
2628 int reason_code = -1;
2629 int ret = 0;
2630 unsigned int i;
2631 ASN1_OBJECT *hold = NULL;
2632 ASN1_GENERALIZEDTIME *comp_time = NULL;
2633
2634 if ((tmp = strdup(str)) == NULL) {
2635 BIO_printf(bio_err, "malloc failed\n");
2636 goto err;
2637 }
2638 p = strchr(tmp, ',');
2639 rtime_str = tmp;
2640
2641 if (p) {
2642 *p = '\0';
2643 p++;
2644 reason_str = p;
2645 p = strchr(p, ',');
2646 if (p) {
2647 *p = '\0';
2648 arg_str = p + 1;
2649 }
2650 }
2651 if (prevtm) {
2652 *prevtm = ASN1_UTCTIME_new();
2653 if (!ASN1_UTCTIME_set_string(*prevtm, rtime_str)) {
2654 BIO_printf(bio_err, "invalid revocation date %s\n",
2655 rtime_str);
2656 goto err;
2657 }
2658 }
2659 if (reason_str) {
2660 for (i = 0; i < NUM_REASONS; i++) {
2661 if (!strcasecmp(reason_str, crl_reasons[i])) {
2662 reason_code = i;
2663 break;
2664 }
2665 }
2666 if (reason_code == OCSP_REVOKED_STATUS_NOSTATUS) {
2667 BIO_printf(bio_err, "invalid reason code %s\n",
2668 reason_str);
2669 goto err;
2670 }
2671 if (reason_code == 7)
2672 reason_code = OCSP_REVOKED_STATUS_REMOVEFROMCRL;
2673 else if (reason_code == 8) { /* Hold instruction */
2674 if (!arg_str) {
2675 BIO_printf(bio_err,
2676 "missing hold instruction\n");
2677 goto err;
2678 }
2679 reason_code = OCSP_REVOKED_STATUS_CERTIFICATEHOLD;
2680 hold = OBJ_txt2obj(arg_str, 0);
2681
2682 if (!hold) {
2683 BIO_printf(bio_err,
2684 "invalid object identifier %s\n", arg_str);
2685 goto err;
2686 }
2687 if (phold)
2688 *phold = hold;
2689 } else if ((reason_code == 9) || (reason_code == 10)) {
2690 if (!arg_str) {
2691 BIO_printf(bio_err,
2692 "missing compromised time\n");
2693 goto err;
2694 }
2695 comp_time = ASN1_GENERALIZEDTIME_new();
2696 if (!ASN1_GENERALIZEDTIME_set_string(comp_time,
2697 arg_str)) {
2698 BIO_printf(bio_err,
2699 "invalid compromised time %s\n", arg_str);
2700 goto err;
2701 }
2702 if (reason_code == 9)
2703 reason_code = OCSP_REVOKED_STATUS_KEYCOMPROMISE;
2704 else
2705 reason_code = OCSP_REVOKED_STATUS_CACOMPROMISE;
2706 }
2707 }
2708 if (preason)
2709 *preason = reason_code;
2710 if (pinvtm)
2711 *pinvtm = comp_time;
2712 else
2713 ASN1_GENERALIZEDTIME_free(comp_time);
2714
2715 ret = 1;
2716
2717err:
2718 free(tmp);
2719
2720 if (!phold)
2721 ASN1_OBJECT_free(hold);
2722 if (!pinvtm)
2723 ASN1_GENERALIZEDTIME_free(comp_time);
2724
2725 return ret;
2726}
2727
2728static char *
2729bin2hex(unsigned char * data, size_t len)
2730{
2731 char *ret = NULL;
2732 char hex[] = "0123456789ABCDEF";
2733 int i;
2734
2735 if ((ret = malloc(len * 2 + 1))) {
2736 for (i = 0; i < len; i++) {
2737 ret[i * 2 + 0] = hex[data[i] >> 4];
2738 ret[i * 2 + 1] = hex[data[i] & 0x0F];
2739 }
2740 ret[len * 2] = '\0';
2741 }
2742 return ret;
2743}
diff --git a/src/usr.bin/openssl/ciphers.c b/src/usr.bin/openssl/ciphers.c
new file mode 100644
index 0000000000..bf17f71c06
--- /dev/null
+++ b/src/usr.bin/openssl/ciphers.c
@@ -0,0 +1,194 @@
1/* $OpenBSD: ciphers.c,v 1.1 2014/08/26 17:47:24 jsing 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#include <stdlib.h>
61#include <string.h>
62
63#include "apps.h"
64
65#include <openssl/err.h>
66#include <openssl/ssl.h>
67
68static const char *ciphers_usage[] = {
69 "usage: ciphers args\n",
70 " -v - verbose mode, a textual listing of the SSL/TLS ciphers in OpenSSL\n",
71 " -V - even more verbose\n",
72 " -ssl3 - SSL3 mode\n",
73 " -tls1 - TLS1 mode\n",
74 NULL
75};
76
77int ciphers_main(int, char **);
78
79int
80ciphers_main(int argc, char **argv)
81{
82 int ret = 1, i;
83 int verbose = 0, Verbose = 0;
84 const char **pp;
85 const char *p;
86 int badops = 0;
87 SSL_CTX *ctx = NULL;
88 SSL *ssl = NULL;
89 char *ciphers = NULL;
90 const SSL_METHOD *meth = NULL;
91 STACK_OF(SSL_CIPHER) * sk;
92 BIO *STDout = NULL;
93 char *desc;
94
95 meth = SSLv3_server_method();
96
97 STDout = BIO_new_fp(stdout, BIO_NOCLOSE);
98
99 argc--;
100 argv++;
101 while (argc >= 1) {
102 if (strcmp(*argv, "-v") == 0)
103 verbose = 1;
104 else if (strcmp(*argv, "-V") == 0)
105 verbose = Verbose = 1;
106 else if (strcmp(*argv, "-ssl3") == 0)
107 meth = SSLv3_client_method();
108 else if (strcmp(*argv, "-tls1") == 0)
109 meth = TLSv1_client_method();
110 else if ((strncmp(*argv, "-h", 2) == 0) ||
111 (strcmp(*argv, "-?") == 0)) {
112 badops = 1;
113 break;
114 } else {
115 ciphers = *argv;
116 }
117 argc--;
118 argv++;
119 }
120
121 if (badops) {
122 for (pp = ciphers_usage; (*pp != NULL); pp++)
123 BIO_printf(bio_err, "%s", *pp);
124 goto end;
125 }
126
127 ctx = SSL_CTX_new(meth);
128 if (ctx == NULL)
129 goto err;
130 if (ciphers != NULL) {
131 if (!SSL_CTX_set_cipher_list(ctx, ciphers)) {
132 BIO_printf(bio_err, "Error in cipher list\n");
133 goto err;
134 }
135 }
136 ssl = SSL_new(ctx);
137 if (ssl == NULL)
138 goto err;
139
140 if (!verbose) {
141 for (i = 0; ; i++) {
142 p = SSL_get_cipher_list(ssl, i);
143 if (p == NULL)
144 break;
145 if (i != 0)
146 BIO_printf(STDout, ":");
147 BIO_printf(STDout, "%s", p);
148 }
149 BIO_printf(STDout, "\n");
150 } else { /* verbose */
151 sk = SSL_get_ciphers(ssl);
152
153 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
154 SSL_CIPHER *c;
155
156 c = sk_SSL_CIPHER_value(sk, i);
157
158 if (Verbose) {
159 unsigned long id = SSL_CIPHER_get_id(c);
160 int id0 = (int) (id >> 24);
161 int id1 = (int) ((id >> 16) & 0xffL);
162 int id2 = (int) ((id >> 8) & 0xffL);
163 int id3 = (int) (id & 0xffL);
164
165 if ((id & 0xff000000L) == 0x02000000L)
166 BIO_printf(STDout, " 0x%02X,0x%02X,0x%02X - ", id1, id2, id3); /* SSL2 cipher */
167 else if ((id & 0xff000000L) == 0x03000000L)
168 BIO_printf(STDout, " 0x%02X,0x%02X - ", id2, id3); /* SSL3 cipher */
169 else
170 BIO_printf(STDout, "0x%02X,0x%02X,0x%02X,0x%02X - ", id0, id1, id2, id3); /* whatever */
171 }
172 desc = SSL_CIPHER_description(c, NULL, 0);
173 BIO_puts(STDout, desc);
174 if (strcmp(desc, "OPENSSL_malloc Error") != 0)
175 free(desc);
176 }
177 }
178
179 ret = 0;
180 if (0) {
181err:
182 ERR_print_errors(bio_err);
183 }
184
185end:
186 if (ctx != NULL)
187 SSL_CTX_free(ctx);
188 if (ssl != NULL)
189 SSL_free(ssl);
190 if (STDout != NULL)
191 BIO_free_all(STDout);
192
193 return (ret);
194}
diff --git a/src/usr.bin/openssl/cms.c b/src/usr.bin/openssl/cms.c
new file mode 100644
index 0000000000..21d27adad1
--- /dev/null
+++ b/src/usr.bin/openssl/cms.c
@@ -0,0 +1,1154 @@
1/* $OpenBSD: cms.c,v 1.1 2014/08/26 17:47:24 jsing Exp $ */
2/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3 * project.
4 */
5/* ====================================================================
6 * Copyright (c) 2008 The OpenSSL Project. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
19 *
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24 *
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * licensing@OpenSSL.org.
29 *
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
33 *
34 * 6. Redistributions of any form whatsoever must retain the following
35 * acknowledgment:
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
52 */
53
54/* CMS utility function */
55
56#include <stdio.h>
57#include <string.h>
58
59#include "apps.h"
60
61#ifndef OPENSSL_NO_CMS
62
63#include <openssl/cms.h>
64#include <openssl/crypto.h>
65#include <openssl/err.h>
66#include <openssl/pem.h>
67#include <openssl/x509_vfy.h>
68#include <openssl/x509v3.h>
69
70static int save_certs(char *signerfile, STACK_OF(X509) * signers);
71static int cms_cb(int ok, X509_STORE_CTX * ctx);
72static void receipt_request_print(BIO * out, CMS_ContentInfo * cms);
73static CMS_ReceiptRequest * make_receipt_request(
74 STACK_OF(OPENSSL_STRING) * rr_to, int rr_allorfirst,
75 STACK_OF(OPENSSL_STRING) * rr_from);
76
77#define SMIME_OP 0x10
78#define SMIME_IP 0x20
79#define SMIME_SIGNERS 0x40
80#define SMIME_ENCRYPT (1 | SMIME_OP)
81#define SMIME_DECRYPT (2 | SMIME_IP)
82#define SMIME_SIGN (3 | SMIME_OP | SMIME_SIGNERS)
83#define SMIME_VERIFY (4 | SMIME_IP)
84#define SMIME_CMSOUT (5 | SMIME_IP | SMIME_OP)
85#define SMIME_RESIGN (6 | SMIME_IP | SMIME_OP | SMIME_SIGNERS)
86#define SMIME_DATAOUT (7 | SMIME_IP)
87#define SMIME_DATA_CREATE (8 | SMIME_OP)
88#define SMIME_DIGEST_VERIFY (9 | SMIME_IP)
89#define SMIME_DIGEST_CREATE (10 | SMIME_OP)
90#define SMIME_UNCOMPRESS (11 | SMIME_IP)
91#define SMIME_COMPRESS (12 | SMIME_OP)
92#define SMIME_ENCRYPTED_DECRYPT (13 | SMIME_IP)
93#define SMIME_ENCRYPTED_ENCRYPT (14 | SMIME_OP)
94#define SMIME_SIGN_RECEIPT (15 | SMIME_IP | SMIME_OP)
95#define SMIME_VERIFY_RECEIPT (16 | SMIME_IP)
96
97int verify_err = 0;
98
99int cms_main(int, char **);
100
101int
102cms_main(int argc, char **argv)
103{
104 ENGINE *e = NULL;
105 int operation = 0;
106 int ret = 0;
107 char **args;
108 const char *inmode = "r", *outmode = "w";
109 char *infile = NULL, *outfile = NULL, *rctfile = NULL;
110 char *signerfile = NULL, *recipfile = NULL;
111 STACK_OF(OPENSSL_STRING) * sksigners = NULL, *skkeys = NULL;
112 char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
113 char *certsoutfile = NULL;
114 const EVP_CIPHER *cipher = NULL;
115 CMS_ContentInfo *cms = NULL, *rcms = NULL;
116 X509_STORE *store = NULL;
117 X509 *cert = NULL, *recip = NULL, *signer = NULL;
118 EVP_PKEY *key = NULL;
119 STACK_OF(X509) * encerts = NULL, *other = NULL;
120 BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL;
121 int badarg = 0;
122 int flags = CMS_DETACHED, noout = 0, print = 0;
123 int verify_retcode = 0;
124 int rr_print = 0, rr_allorfirst = -1;
125 STACK_OF(OPENSSL_STRING) * rr_to = NULL, *rr_from = NULL;
126 CMS_ReceiptRequest *rr = NULL;
127 char *to = NULL, *from = NULL, *subject = NULL;
128 char *CAfile = NULL, *CApath = NULL;
129 char *passargin = NULL, *passin = NULL;
130 const EVP_MD *sign_md = NULL;
131 int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
132 int rctformat = FORMAT_SMIME, keyform = FORMAT_PEM;
133#ifndef OPENSSL_NO_ENGINE
134 char *engine = NULL;
135#endif
136 unsigned char *secret_key = NULL, *secret_keyid = NULL;
137 unsigned char *pwri_pass = NULL, *pwri_tmp = NULL;
138 size_t secret_keylen = 0, secret_keyidlen = 0;
139
140 ASN1_OBJECT *econtent_type = NULL;
141
142 X509_VERIFY_PARAM *vpm = NULL;
143
144 args = argv + 1;
145 ret = 1;
146
147 while (!badarg && *args && *args[0] == '-') {
148 if (!strcmp(*args, "-encrypt"))
149 operation = SMIME_ENCRYPT;
150 else if (!strcmp(*args, "-decrypt"))
151 operation = SMIME_DECRYPT;
152 else if (!strcmp(*args, "-sign"))
153 operation = SMIME_SIGN;
154 else if (!strcmp(*args, "-sign_receipt"))
155 operation = SMIME_SIGN_RECEIPT;
156 else if (!strcmp(*args, "-resign"))
157 operation = SMIME_RESIGN;
158 else if (!strcmp(*args, "-verify"))
159 operation = SMIME_VERIFY;
160 else if (!strcmp(*args, "-verify_retcode"))
161 verify_retcode = 1;
162 else if (!strcmp(*args, "-verify_receipt")) {
163 operation = SMIME_VERIFY_RECEIPT;
164 if (!args[1])
165 goto argerr;
166 args++;
167 rctfile = *args;
168 } else if (!strcmp(*args, "-cmsout"))
169 operation = SMIME_CMSOUT;
170 else if (!strcmp(*args, "-data_out"))
171 operation = SMIME_DATAOUT;
172 else if (!strcmp(*args, "-data_create"))
173 operation = SMIME_DATA_CREATE;
174 else if (!strcmp(*args, "-digest_verify"))
175 operation = SMIME_DIGEST_VERIFY;
176 else if (!strcmp(*args, "-digest_create"))
177 operation = SMIME_DIGEST_CREATE;
178 else if (!strcmp(*args, "-compress"))
179 operation = SMIME_COMPRESS;
180 else if (!strcmp(*args, "-uncompress"))
181 operation = SMIME_UNCOMPRESS;
182 else if (!strcmp(*args, "-EncryptedData_decrypt"))
183 operation = SMIME_ENCRYPTED_DECRYPT;
184 else if (!strcmp(*args, "-EncryptedData_encrypt"))
185 operation = SMIME_ENCRYPTED_ENCRYPT;
186#ifndef OPENSSL_NO_DES
187 else if (!strcmp(*args, "-des3"))
188 cipher = EVP_des_ede3_cbc();
189 else if (!strcmp(*args, "-des"))
190 cipher = EVP_des_cbc();
191#endif
192#ifndef OPENSSL_NO_RC2
193 else if (!strcmp(*args, "-rc2-40"))
194 cipher = EVP_rc2_40_cbc();
195 else if (!strcmp(*args, "-rc2-128"))
196 cipher = EVP_rc2_cbc();
197 else if (!strcmp(*args, "-rc2-64"))
198 cipher = EVP_rc2_64_cbc();
199#endif
200#ifndef OPENSSL_NO_AES
201 else if (!strcmp(*args, "-aes128"))
202 cipher = EVP_aes_128_cbc();
203 else if (!strcmp(*args, "-aes192"))
204 cipher = EVP_aes_192_cbc();
205 else if (!strcmp(*args, "-aes256"))
206 cipher = EVP_aes_256_cbc();
207#endif
208#ifndef OPENSSL_NO_CAMELLIA
209 else if (!strcmp(*args, "-camellia128"))
210 cipher = EVP_camellia_128_cbc();
211 else if (!strcmp(*args, "-camellia192"))
212 cipher = EVP_camellia_192_cbc();
213 else if (!strcmp(*args, "-camellia256"))
214 cipher = EVP_camellia_256_cbc();
215#endif
216 else if (!strcmp(*args, "-debug_decrypt"))
217 flags |= CMS_DEBUG_DECRYPT;
218 else if (!strcmp(*args, "-text"))
219 flags |= CMS_TEXT;
220 else if (!strcmp(*args, "-nointern"))
221 flags |= CMS_NOINTERN;
222 else if (!strcmp(*args, "-noverify") ||
223 !strcmp(*args, "-no_signer_cert_verify"))
224 flags |= CMS_NO_SIGNER_CERT_VERIFY;
225 else if (!strcmp(*args, "-nocerts"))
226 flags |= CMS_NOCERTS;
227 else if (!strcmp(*args, "-noattr"))
228 flags |= CMS_NOATTR;
229 else if (!strcmp(*args, "-nodetach"))
230 flags &= ~CMS_DETACHED;
231 else if (!strcmp(*args, "-nosmimecap"))
232 flags |= CMS_NOSMIMECAP;
233 else if (!strcmp(*args, "-binary"))
234 flags |= CMS_BINARY;
235 else if (!strcmp(*args, "-keyid"))
236 flags |= CMS_USE_KEYID;
237 else if (!strcmp(*args, "-nosigs"))
238 flags |= CMS_NOSIGS;
239 else if (!strcmp(*args, "-no_content_verify"))
240 flags |= CMS_NO_CONTENT_VERIFY;
241 else if (!strcmp(*args, "-no_attr_verify"))
242 flags |= CMS_NO_ATTR_VERIFY;
243 else if (!strcmp(*args, "-stream"))
244 flags |= CMS_STREAM;
245 else if (!strcmp(*args, "-indef"))
246 flags |= CMS_STREAM;
247 else if (!strcmp(*args, "-noindef"))
248 flags &= ~CMS_STREAM;
249 else if (!strcmp(*args, "-nooldmime"))
250 flags |= CMS_NOOLDMIMETYPE;
251 else if (!strcmp(*args, "-crlfeol"))
252 flags |= CMS_CRLFEOL;
253 else if (!strcmp(*args, "-noout"))
254 noout = 1;
255 else if (!strcmp(*args, "-receipt_request_print"))
256 rr_print = 1;
257 else if (!strcmp(*args, "-receipt_request_all"))
258 rr_allorfirst = 0;
259 else if (!strcmp(*args, "-receipt_request_first"))
260 rr_allorfirst = 1;
261 else if (!strcmp(*args, "-receipt_request_from")) {
262 if (!args[1])
263 goto argerr;
264 args++;
265 if (!rr_from)
266 rr_from = sk_OPENSSL_STRING_new_null();
267 sk_OPENSSL_STRING_push(rr_from, *args);
268 } else if (!strcmp(*args, "-receipt_request_to")) {
269 if (!args[1])
270 goto argerr;
271 args++;
272 if (!rr_to)
273 rr_to = sk_OPENSSL_STRING_new_null();
274 sk_OPENSSL_STRING_push(rr_to, *args);
275 } else if (!strcmp(*args, "-print")) {
276 noout = 1;
277 print = 1;
278 } else if (!strcmp(*args, "-secretkey")) {
279 long ltmp;
280 if (!args[1])
281 goto argerr;
282 args++;
283 secret_key = string_to_hex(*args, &ltmp);
284 if (!secret_key) {
285 BIO_printf(bio_err, "Invalid key %s\n", *args);
286 goto argerr;
287 }
288 secret_keylen = (size_t) ltmp;
289 } else if (!strcmp(*args, "-secretkeyid")) {
290 long ltmp;
291 if (!args[1])
292 goto argerr;
293 args++;
294 secret_keyid = string_to_hex(*args, &ltmp);
295 if (!secret_keyid) {
296 BIO_printf(bio_err, "Invalid id %s\n", *args);
297 goto argerr;
298 }
299 secret_keyidlen = (size_t) ltmp;
300 } else if (!strcmp(*args, "-pwri_password")) {
301 if (!args[1])
302 goto argerr;
303 args++;
304 pwri_pass = (unsigned char *) *args;
305 } else if (!strcmp(*args, "-econtent_type")) {
306 if (!args[1])
307 goto argerr;
308 args++;
309 econtent_type = OBJ_txt2obj(*args, 0);
310 if (!econtent_type) {
311 BIO_printf(bio_err, "Invalid OID %s\n", *args);
312 goto argerr;
313 }
314 }
315#ifndef OPENSSL_NO_ENGINE
316 else if (!strcmp(*args, "-engine")) {
317 if (!args[1])
318 goto argerr;
319 engine = *++args;
320 }
321#endif
322 else if (!strcmp(*args, "-passin")) {
323 if (!args[1])
324 goto argerr;
325 passargin = *++args;
326 } else if (!strcmp(*args, "-to")) {
327 if (!args[1])
328 goto argerr;
329 to = *++args;
330 } else if (!strcmp(*args, "-from")) {
331 if (!args[1])
332 goto argerr;
333 from = *++args;
334 } else if (!strcmp(*args, "-subject")) {
335 if (!args[1])
336 goto argerr;
337 subject = *++args;
338 } else if (!strcmp(*args, "-signer")) {
339 if (!args[1])
340 goto argerr;
341 /* If previous -signer argument add signer to list */
342
343 if (signerfile) {
344 if (!sksigners)
345 sksigners =
346 sk_OPENSSL_STRING_new_null();
347 sk_OPENSSL_STRING_push(sksigners, signerfile);
348 if (!keyfile)
349 keyfile = signerfile;
350 if (!skkeys)
351 skkeys = sk_OPENSSL_STRING_new_null();
352 sk_OPENSSL_STRING_push(skkeys, keyfile);
353 keyfile = NULL;
354 }
355 signerfile = *++args;
356 } else if (!strcmp(*args, "-recip")) {
357 if (!args[1])
358 goto argerr;
359 recipfile = *++args;
360 } else if (!strcmp(*args, "-certsout")) {
361 if (!args[1])
362 goto argerr;
363 certsoutfile = *++args;
364 } else if (!strcmp(*args, "-md")) {
365 if (!args[1])
366 goto argerr;
367 sign_md = EVP_get_digestbyname(*++args);
368 if (sign_md == NULL) {
369 BIO_printf(bio_err, "Unknown digest %s\n",
370 *args);
371 goto argerr;
372 }
373 } else if (!strcmp(*args, "-inkey")) {
374 if (!args[1])
375 goto argerr;
376 /* If previous -inkey arument add signer to list */
377 if (keyfile) {
378 if (!signerfile) {
379 BIO_puts(bio_err,
380 "Illegal -inkey without -signer\n");
381 goto argerr;
382 }
383 if (!sksigners)
384 sksigners =
385 sk_OPENSSL_STRING_new_null();
386 sk_OPENSSL_STRING_push(sksigners, signerfile);
387 signerfile = NULL;
388 if (!skkeys)
389 skkeys = sk_OPENSSL_STRING_new_null();
390 sk_OPENSSL_STRING_push(skkeys, keyfile);
391 }
392 keyfile = *++args;
393 } else if (!strcmp(*args, "-keyform")) {
394 if (!args[1])
395 goto argerr;
396 keyform = str2fmt(*++args);
397 } else if (!strcmp(*args, "-rctform")) {
398 if (!args[1])
399 goto argerr;
400 rctformat = str2fmt(*++args);
401 } else if (!strcmp(*args, "-certfile")) {
402 if (!args[1])
403 goto argerr;
404 certfile = *++args;
405 } else if (!strcmp(*args, "-CAfile")) {
406 if (!args[1])
407 goto argerr;
408 CAfile = *++args;
409 } else if (!strcmp(*args, "-CApath")) {
410 if (!args[1])
411 goto argerr;
412 CApath = *++args;
413 } else if (!strcmp(*args, "-in")) {
414 if (!args[1])
415 goto argerr;
416 infile = *++args;
417 } else if (!strcmp(*args, "-inform")) {
418 if (!args[1])
419 goto argerr;
420 informat = str2fmt(*++args);
421 } else if (!strcmp(*args, "-outform")) {
422 if (!args[1])
423 goto argerr;
424 outformat = str2fmt(*++args);
425 } else if (!strcmp(*args, "-out")) {
426 if (!args[1])
427 goto argerr;
428 outfile = *++args;
429 } else if (!strcmp(*args, "-content")) {
430 if (!args[1])
431 goto argerr;
432 contfile = *++args;
433 } else if (args_verify(&args, NULL, &badarg, bio_err, &vpm))
434 continue;
435 else if ((cipher = EVP_get_cipherbyname(*args + 1)) == NULL)
436 badarg = 1;
437 args++;
438 }
439
440 if (((rr_allorfirst != -1) || rr_from) && !rr_to) {
441 BIO_puts(bio_err, "No Signed Receipts Recipients\n");
442 goto argerr;
443 }
444 if (!(operation & SMIME_SIGNERS) && (rr_to || rr_from)) {
445 BIO_puts(bio_err, "Signed receipts only allowed with -sign\n");
446 goto argerr;
447 }
448 if (!(operation & SMIME_SIGNERS) && (skkeys || sksigners)) {
449 BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
450 goto argerr;
451 }
452 if (operation & SMIME_SIGNERS) {
453 if (keyfile && !signerfile) {
454 BIO_puts(bio_err, "Illegal -inkey without -signer\n");
455 goto argerr;
456 }
457 /* Check to see if any final signer needs to be appended */
458 if (signerfile) {
459 if (!sksigners)
460 sksigners = sk_OPENSSL_STRING_new_null();
461 sk_OPENSSL_STRING_push(sksigners, signerfile);
462 if (!skkeys)
463 skkeys = sk_OPENSSL_STRING_new_null();
464 if (!keyfile)
465 keyfile = signerfile;
466 sk_OPENSSL_STRING_push(skkeys, keyfile);
467 }
468 if (!sksigners) {
469 BIO_printf(bio_err,
470 "No signer certificate specified\n");
471 badarg = 1;
472 }
473 signerfile = NULL;
474 keyfile = NULL;
475 } else if (operation == SMIME_DECRYPT) {
476 if (!recipfile && !keyfile && !secret_key && !pwri_pass) {
477 BIO_printf(bio_err,
478 "No recipient certificate or key specified\n");
479 badarg = 1;
480 }
481 } else if (operation == SMIME_ENCRYPT) {
482 if (!*args && !secret_key && !pwri_pass) {
483 BIO_printf(bio_err,
484 "No recipient(s) certificate(s) specified\n");
485 badarg = 1;
486 }
487 } else if (!operation)
488 badarg = 1;
489
490 if (badarg) {
491argerr:
492 BIO_printf(bio_err, "Usage cms [options] cert.pem ...\n");
493 BIO_printf(bio_err, "where options are\n");
494 BIO_printf(bio_err, "-encrypt encrypt message\n");
495 BIO_printf(bio_err, "-decrypt decrypt encrypted message\n");
496 BIO_printf(bio_err, "-sign sign message\n");
497 BIO_printf(bio_err, "-verify verify signed message\n");
498 BIO_printf(bio_err, "-cmsout output CMS structure\n");
499#ifndef OPENSSL_NO_DES
500 BIO_printf(bio_err, "-des3 encrypt with triple DES\n");
501 BIO_printf(bio_err, "-des encrypt with DES\n");
502#endif
503#ifndef OPENSSL_NO_RC2
504 BIO_printf(bio_err, "-rc2-40 encrypt with RC2-40 (default)\n");
505 BIO_printf(bio_err, "-rc2-64 encrypt with RC2-64\n");
506 BIO_printf(bio_err, "-rc2-128 encrypt with RC2-128\n");
507#endif
508#ifndef OPENSSL_NO_AES
509 BIO_printf(bio_err, "-aes128, -aes192, -aes256\n");
510 BIO_printf(bio_err, " encrypt PEM output with cbc aes\n");
511#endif
512#ifndef OPENSSL_NO_CAMELLIA
513 BIO_printf(bio_err, "-camellia128, -camellia192, -camellia256\n");
514 BIO_printf(bio_err, " encrypt PEM output with cbc camellia\n");
515#endif
516 BIO_printf(bio_err, "-nointern don't search certificates in message for signer\n");
517 BIO_printf(bio_err, "-nosigs don't verify message signature\n");
518 BIO_printf(bio_err, "-noverify don't verify signers certificate\n");
519 BIO_printf(bio_err, "-nocerts don't include signers certificate when signing\n");
520 BIO_printf(bio_err, "-nodetach use opaque signing\n");
521 BIO_printf(bio_err, "-noattr don't include any signed attributes\n");
522 BIO_printf(bio_err, "-binary don't translate message to text\n");
523 BIO_printf(bio_err, "-certfile file other certificates file\n");
524 BIO_printf(bio_err, "-certsout file certificate output file\n");
525 BIO_printf(bio_err, "-signer file signer certificate file\n");
526 BIO_printf(bio_err, "-recip file recipient certificate file for decryption\n");
527 BIO_printf(bio_err, "-keyid use subject key identifier\n");
528 BIO_printf(bio_err, "-in file input file\n");
529 BIO_printf(bio_err, "-inform arg input format SMIME (default), PEM or DER\n");
530 BIO_printf(bio_err, "-inkey file input private key (if not signer or recipient)\n");
531 BIO_printf(bio_err, "-keyform arg input private key format (PEM or ENGINE)\n");
532 BIO_printf(bio_err, "-out file output file\n");
533 BIO_printf(bio_err, "-outform arg output format SMIME (default), PEM or DER\n");
534 BIO_printf(bio_err, "-content file supply or override content for detached signature\n");
535 BIO_printf(bio_err, "-to addr to address\n");
536 BIO_printf(bio_err, "-from ad from address\n");
537 BIO_printf(bio_err, "-subject s subject\n");
538 BIO_printf(bio_err, "-text include or delete text MIME headers\n");
539 BIO_printf(bio_err, "-CApath dir trusted certificates directory\n");
540 BIO_printf(bio_err, "-CAfile file trusted certificates file\n");
541 BIO_printf(bio_err, "-crl_check check revocation status of signer's certificate using CRLs\n");
542 BIO_printf(bio_err, "-crl_check_all check revocation status of signer's certificate chain using CRLs\n");
543#ifndef OPENSSL_NO_ENGINE
544 BIO_printf(bio_err, "-engine e use engine e, possibly a hardware device.\n");
545#endif
546 BIO_printf(bio_err, "-passin arg input file pass phrase source\n");
547 BIO_printf(bio_err, "cert.pem recipient certificate(s) for encryption\n");
548 goto end;
549 }
550#ifndef OPENSSL_NO_ENGINE
551 e = setup_engine(bio_err, engine, 0);
552#endif
553
554 if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) {
555 BIO_printf(bio_err, "Error getting password\n");
556 goto end;
557 }
558 ret = 2;
559
560 if (!(operation & SMIME_SIGNERS))
561 flags &= ~CMS_DETACHED;
562
563 if (operation & SMIME_OP) {
564 if (outformat == FORMAT_ASN1)
565 outmode = "wb";
566 } else {
567 if (flags & CMS_BINARY)
568 outmode = "wb";
569 }
570
571 if (operation & SMIME_IP) {
572 if (informat == FORMAT_ASN1)
573 inmode = "rb";
574 } else {
575 if (flags & CMS_BINARY)
576 inmode = "rb";
577 }
578
579 if (operation == SMIME_ENCRYPT) {
580 if (!cipher) {
581#ifndef OPENSSL_NO_DES
582 cipher = EVP_des_ede3_cbc();
583#else
584 BIO_printf(bio_err, "No cipher selected\n");
585 goto end;
586#endif
587 }
588 if (secret_key && !secret_keyid) {
589 BIO_printf(bio_err, "No secret key id\n");
590 goto end;
591 }
592 if (*args)
593 encerts = sk_X509_new_null();
594 while (*args) {
595 if (!(cert = load_cert(bio_err, *args, FORMAT_PEM,
596 NULL, e, "recipient certificate file")))
597 goto end;
598 sk_X509_push(encerts, cert);
599 cert = NULL;
600 args++;
601 }
602 }
603 if (certfile) {
604 if (!(other = load_certs(bio_err, certfile, FORMAT_PEM, NULL,
605 e, "certificate file"))) {
606 ERR_print_errors(bio_err);
607 goto end;
608 }
609 }
610 if (recipfile && (operation == SMIME_DECRYPT)) {
611 if (!(recip = load_cert(bio_err, recipfile, FORMAT_PEM, NULL,
612 e, "recipient certificate file"))) {
613 ERR_print_errors(bio_err);
614 goto end;
615 }
616 }
617 if (operation == SMIME_SIGN_RECEIPT) {
618 if (!(signer = load_cert(bio_err, signerfile, FORMAT_PEM, NULL,
619 e, "receipt signer certificate file"))) {
620 ERR_print_errors(bio_err);
621 goto end;
622 }
623 }
624 if (operation == SMIME_DECRYPT) {
625 if (!keyfile)
626 keyfile = recipfile;
627 } else if ((operation == SMIME_SIGN) ||
628 (operation == SMIME_SIGN_RECEIPT)) {
629 if (!keyfile)
630 keyfile = signerfile;
631 } else
632 keyfile = NULL;
633
634 if (keyfile) {
635 key = load_key(bio_err, keyfile, keyform, 0, passin, e,
636 "signing key file");
637 if (!key)
638 goto end;
639 }
640 if (infile) {
641 if (!(in = BIO_new_file(infile, inmode))) {
642 BIO_printf(bio_err,
643 "Can't open input file %s\n", infile);
644 goto end;
645 }
646 } else
647 in = BIO_new_fp(stdin, BIO_NOCLOSE);
648
649 if (operation & SMIME_IP) {
650 if (informat == FORMAT_SMIME)
651 cms = SMIME_read_CMS(in, &indata);
652 else if (informat == FORMAT_PEM)
653 cms = PEM_read_bio_CMS(in, NULL, NULL, NULL);
654 else if (informat == FORMAT_ASN1)
655 cms = d2i_CMS_bio(in, NULL);
656 else {
657 BIO_printf(bio_err, "Bad input format for CMS file\n");
658 goto end;
659 }
660
661 if (!cms) {
662 BIO_printf(bio_err, "Error reading S/MIME message\n");
663 goto end;
664 }
665 if (contfile) {
666 BIO_free(indata);
667 if (!(indata = BIO_new_file(contfile, "rb"))) {
668 BIO_printf(bio_err,
669 "Can't read content file %s\n", contfile);
670 goto end;
671 }
672 }
673 if (certsoutfile) {
674 STACK_OF(X509) * allcerts;
675 allcerts = CMS_get1_certs(cms);
676 if (!save_certs(certsoutfile, allcerts)) {
677 BIO_printf(bio_err,
678 "Error writing certs to %s\n",
679 certsoutfile);
680 ret = 5;
681 goto end;
682 }
683 sk_X509_pop_free(allcerts, X509_free);
684 }
685 }
686 if (rctfile) {
687 char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r";
688 if (!(rctin = BIO_new_file(rctfile, rctmode))) {
689 BIO_printf(bio_err,
690 "Can't open receipt file %s\n", rctfile);
691 goto end;
692 }
693 if (rctformat == FORMAT_SMIME)
694 rcms = SMIME_read_CMS(rctin, NULL);
695 else if (rctformat == FORMAT_PEM)
696 rcms = PEM_read_bio_CMS(rctin, NULL, NULL, NULL);
697 else if (rctformat == FORMAT_ASN1)
698 rcms = d2i_CMS_bio(rctin, NULL);
699 else {
700 BIO_printf(bio_err, "Bad input format for receipt\n");
701 goto end;
702 }
703
704 if (!rcms) {
705 BIO_printf(bio_err, "Error reading receipt\n");
706 goto end;
707 }
708 }
709 if (outfile) {
710 if (!(out = BIO_new_file(outfile, outmode))) {
711 BIO_printf(bio_err,
712 "Can't open output file %s\n", outfile);
713 goto end;
714 }
715 } else {
716 out = BIO_new_fp(stdout, BIO_NOCLOSE);
717 }
718
719 if ((operation == SMIME_VERIFY) ||
720 (operation == SMIME_VERIFY_RECEIPT)) {
721 if (!(store = setup_verify(bio_err, CAfile, CApath)))
722 goto end;
723 X509_STORE_set_verify_cb(store, cms_cb);
724 if (vpm)
725 X509_STORE_set1_param(store, vpm);
726 }
727 ret = 3;
728
729 if (operation == SMIME_DATA_CREATE) {
730 cms = CMS_data_create(in, flags);
731 } else if (operation == SMIME_DIGEST_CREATE) {
732 cms = CMS_digest_create(in, sign_md, flags);
733 } else if (operation == SMIME_COMPRESS) {
734 cms = CMS_compress(in, -1, flags);
735 } else if (operation == SMIME_ENCRYPT) {
736 flags |= CMS_PARTIAL;
737 cms = CMS_encrypt(encerts, in, cipher, flags);
738 if (!cms)
739 goto end;
740 if (secret_key) {
741 if (!CMS_add0_recipient_key(cms, NID_undef, secret_key,
742 secret_keylen, secret_keyid, secret_keyidlen,
743 NULL, NULL, NULL))
744 goto end;
745 /* NULL these because call absorbs them */
746 secret_key = NULL;
747 secret_keyid = NULL;
748 }
749 if (pwri_pass) {
750 pwri_tmp = strdup(pwri_pass);
751 if (!pwri_tmp)
752 goto end;
753 if (!CMS_add0_recipient_password(cms, -1, NID_undef,
754 NID_undef, pwri_tmp, -1, NULL))
755 goto end;
756 pwri_tmp = NULL;
757 }
758 if (!(flags & CMS_STREAM)) {
759 if (!CMS_final(cms, in, NULL, flags))
760 goto end;
761 }
762 } else if (operation == SMIME_ENCRYPTED_ENCRYPT) {
763 cms = CMS_EncryptedData_encrypt(in, cipher, secret_key,
764 secret_keylen, flags);
765
766 } else if (operation == SMIME_SIGN_RECEIPT) {
767 CMS_ContentInfo *srcms = NULL;
768 STACK_OF(CMS_SignerInfo) * sis;
769 CMS_SignerInfo *si;
770 sis = CMS_get0_SignerInfos(cms);
771 if (!sis)
772 goto end;
773 si = sk_CMS_SignerInfo_value(sis, 0);
774 srcms = CMS_sign_receipt(si, signer, key, other, flags);
775 if (!srcms)
776 goto end;
777 CMS_ContentInfo_free(cms);
778 cms = srcms;
779 } else if (operation & SMIME_SIGNERS) {
780 int i;
781 /*
782 * If detached data content we enable streaming if S/MIME
783 * output format.
784 */
785 if (operation == SMIME_SIGN) {
786
787 if (flags & CMS_DETACHED) {
788 if (outformat == FORMAT_SMIME)
789 flags |= CMS_STREAM;
790 }
791 flags |= CMS_PARTIAL;
792 cms = CMS_sign(NULL, NULL, other, in, flags);
793 if (!cms)
794 goto end;
795 if (econtent_type)
796 CMS_set1_eContentType(cms, econtent_type);
797
798 if (rr_to) {
799 rr = make_receipt_request(rr_to, rr_allorfirst,
800 rr_from);
801 if (!rr) {
802 BIO_puts(bio_err,
803 "Signed Receipt Request Creation Error\n");
804 goto end;
805 }
806 }
807 } else
808 flags |= CMS_REUSE_DIGEST;
809 for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
810 CMS_SignerInfo *si;
811 signerfile = sk_OPENSSL_STRING_value(sksigners, i);
812 keyfile = sk_OPENSSL_STRING_value(skkeys, i);
813 signer = load_cert(bio_err, signerfile, FORMAT_PEM,
814 NULL, e, "signer certificate");
815 if (!signer)
816 goto end;
817 key = load_key(bio_err, keyfile, keyform, 0, passin, e,
818 "signing key file");
819 if (!key)
820 goto end;
821 si = CMS_add1_signer(cms, signer, key, sign_md, flags);
822 if (!si)
823 goto end;
824 if (rr && !CMS_add1_ReceiptRequest(si, rr))
825 goto end;
826 X509_free(signer);
827 signer = NULL;
828 EVP_PKEY_free(key);
829 key = NULL;
830 }
831 /* If not streaming or resigning finalize structure */
832 if ((operation == SMIME_SIGN) && !(flags & CMS_STREAM)) {
833 if (!CMS_final(cms, in, NULL, flags))
834 goto end;
835 }
836 }
837 if (!cms) {
838 BIO_printf(bio_err, "Error creating CMS structure\n");
839 goto end;
840 }
841 ret = 4;
842 if (operation == SMIME_DECRYPT) {
843 if (flags & CMS_DEBUG_DECRYPT)
844 CMS_decrypt(cms, NULL, NULL, NULL, NULL, flags);
845
846 if (secret_key) {
847 if (!CMS_decrypt_set1_key(cms, secret_key,
848 secret_keylen, secret_keyid, secret_keyidlen)) {
849 BIO_puts(bio_err,
850 "Error decrypting CMS using secret key\n");
851 goto end;
852 }
853 }
854 if (key) {
855 if (!CMS_decrypt_set1_pkey(cms, key, recip)) {
856 BIO_puts(bio_err,
857 "Error decrypting CMS using private key\n");
858 goto end;
859 }
860 }
861 if (pwri_pass) {
862 if (!CMS_decrypt_set1_password(cms, pwri_pass, -1)) {
863 BIO_puts(bio_err,
864 "Error decrypting CMS using password\n");
865 goto end;
866 }
867 }
868 if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags)) {
869 BIO_printf(bio_err, "Error decrypting CMS structure\n");
870 goto end;
871 }
872 } else if (operation == SMIME_DATAOUT) {
873 if (!CMS_data(cms, out, flags))
874 goto end;
875 } else if (operation == SMIME_UNCOMPRESS) {
876 if (!CMS_uncompress(cms, indata, out, flags))
877 goto end;
878 } else if (operation == SMIME_DIGEST_VERIFY) {
879 if (CMS_digest_verify(cms, indata, out, flags) > 0)
880 BIO_printf(bio_err, "Verification successful\n");
881 else {
882 BIO_printf(bio_err, "Verification failure\n");
883 goto end;
884 }
885 } else if (operation == SMIME_ENCRYPTED_DECRYPT) {
886 if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen,
887 indata, out, flags))
888 goto end;
889 } else if (operation == SMIME_VERIFY) {
890 if (CMS_verify(cms, other, store, indata, out, flags) > 0)
891 BIO_printf(bio_err, "Verification successful\n");
892 else {
893 BIO_printf(bio_err, "Verification failure\n");
894 if (verify_retcode)
895 ret = verify_err + 32;
896 goto end;
897 }
898 if (signerfile) {
899 STACK_OF(X509) * signers;
900 signers = CMS_get0_signers(cms);
901 if (!save_certs(signerfile, signers)) {
902 BIO_printf(bio_err,
903 "Error writing signers to %s\n",
904 signerfile);
905 ret = 5;
906 goto end;
907 }
908 sk_X509_free(signers);
909 }
910 if (rr_print)
911 receipt_request_print(bio_err, cms);
912
913 } else if (operation == SMIME_VERIFY_RECEIPT) {
914 if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0)
915 BIO_printf(bio_err, "Verification successful\n");
916 else {
917 BIO_printf(bio_err, "Verification failure\n");
918 goto end;
919 }
920 } else {
921 if (noout) {
922 if (print)
923 CMS_ContentInfo_print_ctx(out, cms, 0, NULL);
924 } else if (outformat == FORMAT_SMIME) {
925 if (to)
926 BIO_printf(out, "To: %s\n", to);
927 if (from)
928 BIO_printf(out, "From: %s\n", from);
929 if (subject)
930 BIO_printf(out, "Subject: %s\n", subject);
931 if (operation == SMIME_RESIGN)
932 ret = SMIME_write_CMS(out, cms, indata, flags);
933 else
934 ret = SMIME_write_CMS(out, cms, in, flags);
935 } else if (outformat == FORMAT_PEM)
936 ret = PEM_write_bio_CMS_stream(out, cms, in, flags);
937 else if (outformat == FORMAT_ASN1)
938 ret = i2d_CMS_bio_stream(out, cms, in, flags);
939 else {
940 BIO_printf(bio_err, "Bad output format for CMS file\n");
941 goto end;
942 }
943 if (ret <= 0) {
944 ret = 6;
945 goto end;
946 }
947 }
948 ret = 0;
949
950end:
951 if (ret)
952 ERR_print_errors(bio_err);
953 sk_X509_pop_free(encerts, X509_free);
954 sk_X509_pop_free(other, X509_free);
955 if (vpm)
956 X509_VERIFY_PARAM_free(vpm);
957 if (sksigners)
958 sk_OPENSSL_STRING_free(sksigners);
959 if (skkeys)
960 sk_OPENSSL_STRING_free(skkeys);
961 free(secret_key);
962 free(secret_keyid);
963 free(pwri_tmp);
964 if (econtent_type)
965 ASN1_OBJECT_free(econtent_type);
966 if (rr)
967 CMS_ReceiptRequest_free(rr);
968 if (rr_to)
969 sk_OPENSSL_STRING_free(rr_to);
970 if (rr_from)
971 sk_OPENSSL_STRING_free(rr_from);
972 X509_STORE_free(store);
973 X509_free(cert);
974 X509_free(recip);
975 X509_free(signer);
976 EVP_PKEY_free(key);
977 CMS_ContentInfo_free(cms);
978 CMS_ContentInfo_free(rcms);
979 BIO_free(rctin);
980 BIO_free(in);
981 BIO_free(indata);
982 BIO_free_all(out);
983 free(passin);
984 return (ret);
985}
986
987static int
988save_certs(char *signerfile, STACK_OF(X509) * signers)
989{
990 int i;
991 BIO *tmp;
992
993 if (!signerfile)
994 return 1;
995 tmp = BIO_new_file(signerfile, "w");
996 if (!tmp)
997 return 0;
998 for (i = 0; i < sk_X509_num(signers); i++)
999 PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
1000 BIO_free(tmp);
1001 return 1;
1002}
1003
1004/* Minimal callback just to output policy info (if any) */
1005
1006static int
1007cms_cb(int ok, X509_STORE_CTX * ctx)
1008{
1009 int error;
1010
1011 error = X509_STORE_CTX_get_error(ctx);
1012
1013 verify_err = error;
1014
1015 if ((error != X509_V_ERR_NO_EXPLICIT_POLICY) &&
1016 ((error != X509_V_OK) || (ok != 2)))
1017 return ok;
1018
1019 policies_print(NULL, ctx);
1020
1021 return ok;
1022}
1023
1024static void
1025gnames_stack_print(BIO * out, STACK_OF(GENERAL_NAMES) * gns)
1026{
1027 STACK_OF(GENERAL_NAME) * gens;
1028 GENERAL_NAME *gen;
1029 int i, j;
1030
1031 for (i = 0; i < sk_GENERAL_NAMES_num(gns); i++) {
1032 gens = sk_GENERAL_NAMES_value(gns, i);
1033 for (j = 0; j < sk_GENERAL_NAME_num(gens); j++) {
1034 gen = sk_GENERAL_NAME_value(gens, j);
1035 BIO_puts(out, " ");
1036 GENERAL_NAME_print(out, gen);
1037 BIO_puts(out, "\n");
1038 }
1039 }
1040 return;
1041}
1042
1043static void
1044receipt_request_print(BIO * out, CMS_ContentInfo * cms)
1045{
1046 STACK_OF(CMS_SignerInfo) * sis;
1047 CMS_SignerInfo *si;
1048 CMS_ReceiptRequest *rr;
1049 int allorfirst;
1050 STACK_OF(GENERAL_NAMES) * rto, *rlist;
1051 ASN1_STRING *scid;
1052 int i, rv;
1053
1054 sis = CMS_get0_SignerInfos(cms);
1055 for (i = 0; i < sk_CMS_SignerInfo_num(sis); i++) {
1056 si = sk_CMS_SignerInfo_value(sis, i);
1057 rv = CMS_get1_ReceiptRequest(si, &rr);
1058 BIO_printf(bio_err, "Signer %d:\n", i + 1);
1059 if (rv == 0)
1060 BIO_puts(bio_err, " No Receipt Request\n");
1061 else if (rv < 0) {
1062 BIO_puts(bio_err, " Receipt Request Parse Error\n");
1063 ERR_print_errors(bio_err);
1064 } else {
1065 char *id;
1066 int idlen;
1067 CMS_ReceiptRequest_get0_values(rr, &scid, &allorfirst,
1068 &rlist, &rto);
1069 BIO_puts(out, " Signed Content ID:\n");
1070 idlen = ASN1_STRING_length(scid);
1071 id = (char *) ASN1_STRING_data(scid);
1072 BIO_dump_indent(out, id, idlen, 4);
1073 BIO_puts(out, " Receipts From");
1074 if (rlist) {
1075 BIO_puts(out, " List:\n");
1076 gnames_stack_print(out, rlist);
1077 } else if (allorfirst == 1)
1078 BIO_puts(out, ": First Tier\n");
1079 else if (allorfirst == 0)
1080 BIO_puts(out, ": All\n");
1081 else
1082 BIO_printf(out, " Unknown (%d)\n", allorfirst);
1083 BIO_puts(out, " Receipts To:\n");
1084 gnames_stack_print(out, rto);
1085 }
1086 if (rr)
1087 CMS_ReceiptRequest_free(rr);
1088 }
1089}
1090
1091static STACK_OF(GENERAL_NAMES) *
1092make_names_stack(STACK_OF(OPENSSL_STRING) * ns)
1093{
1094 int i;
1095 STACK_OF(GENERAL_NAMES) * ret;
1096 GENERAL_NAMES *gens = NULL;
1097 GENERAL_NAME *gen = NULL;
1098 ret = sk_GENERAL_NAMES_new_null();
1099 if (!ret)
1100 goto err;
1101 for (i = 0; i < sk_OPENSSL_STRING_num(ns); i++) {
1102 char *str = sk_OPENSSL_STRING_value(ns, i);
1103 gen = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_EMAIL, str, 0);
1104 if (!gen)
1105 goto err;
1106 gens = GENERAL_NAMES_new();
1107 if (!gens)
1108 goto err;
1109 if (!sk_GENERAL_NAME_push(gens, gen))
1110 goto err;
1111 gen = NULL;
1112 if (!sk_GENERAL_NAMES_push(ret, gens))
1113 goto err;
1114 gens = NULL;
1115 }
1116
1117 return ret;
1118
1119err:
1120 if (ret)
1121 sk_GENERAL_NAMES_pop_free(ret, GENERAL_NAMES_free);
1122 if (gens)
1123 GENERAL_NAMES_free(gens);
1124 if (gen)
1125 GENERAL_NAME_free(gen);
1126 return NULL;
1127}
1128
1129
1130static CMS_ReceiptRequest *
1131make_receipt_request(STACK_OF(OPENSSL_STRING) * rr_to, int rr_allorfirst,
1132 STACK_OF(OPENSSL_STRING) * rr_from)
1133{
1134 STACK_OF(GENERAL_NAMES) * rct_to, *rct_from;
1135 CMS_ReceiptRequest *rr;
1136
1137 rct_to = make_names_stack(rr_to);
1138 if (!rct_to)
1139 goto err;
1140 if (rr_from) {
1141 rct_from = make_names_stack(rr_from);
1142 if (!rct_from)
1143 goto err;
1144 } else
1145 rct_from = NULL;
1146 rr = CMS_ReceiptRequest_create0(NULL, -1, rr_allorfirst, rct_from,
1147 rct_to);
1148 return rr;
1149
1150err:
1151 return NULL;
1152}
1153
1154#endif
diff --git a/src/usr.bin/openssl/crl.c b/src/usr.bin/openssl/crl.c
new file mode 100644
index 0000000000..04de5a2f12
--- /dev/null
+++ b/src/usr.bin/openssl/crl.c
@@ -0,0 +1,415 @@
1/* $OpenBSD: crl.c,v 1.1 2014/08/26 17:47:24 jsing 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#include <stdlib.h>
61#include <string.h>
62
63#include "apps.h"
64
65#include <openssl/bio.h>
66#include <openssl/err.h>
67#include <openssl/pem.h>
68#include <openssl/x509.h>
69#include <openssl/x509v3.h>
70
71#define POSTFIX ".rvk"
72
73static const char *crl_usage[] = {
74 "usage: crl args\n",
75 "\n",
76 " -inform arg - input format - default PEM (DER or PEM)\n",
77 " -outform arg - output format - default PEM\n",
78 " -text - print out a text format version\n",
79 " -in arg - input file - default stdin\n",
80 " -out arg - output file - default stdout\n",
81 " -hash - print hash value\n",
82#ifndef OPENSSL_NO_MD5
83 " -hash_old - print old-style (MD5) hash value\n",
84#endif
85 " -fingerprint - print the crl fingerprint\n",
86 " -issuer - print issuer DN\n",
87 " -lastupdate - lastUpdate field\n",
88 " -nextupdate - nextUpdate field\n",
89 " -crlnumber - print CRL number\n",
90 " -noout - no CRL output\n",
91 " -CAfile name - verify CRL using certificates in file \"name\"\n",
92 " -CApath dir - verify CRL using certificates in \"dir\"\n",
93 " -nameopt arg - various certificate name options\n",
94 NULL
95};
96
97static X509_CRL *load_crl(char *file, int format);
98static BIO *bio_out = NULL;
99
100int crl_main(int, char **);
101
102int
103crl_main(int argc, char **argv)
104{
105 unsigned long nmflag = 0;
106 X509_CRL *x = NULL;
107 char *CAfile = NULL, *CApath = NULL;
108 int ret = 1, i, num, badops = 0;
109 BIO *out = NULL;
110 int informat, outformat;
111 char *infile = NULL, *outfile = NULL;
112 int hash = 0, issuer = 0, lastupdate = 0, nextupdate = 0, noout = 0,
113 text = 0;
114#ifndef OPENSSL_NO_MD5
115 int hash_old = 0;
116#endif
117 int fingerprint = 0, crlnumber = 0;
118 const char **pp;
119 X509_STORE *store = NULL;
120 X509_STORE_CTX ctx;
121 X509_LOOKUP *lookup = NULL;
122 X509_OBJECT xobj;
123 EVP_PKEY *pkey;
124 int do_ver = 0;
125 const EVP_MD *md_alg, *digest = EVP_sha1();
126
127 if (bio_out == NULL)
128 if ((bio_out = BIO_new(BIO_s_file())) != NULL) {
129 BIO_set_fp(bio_out, stdout, BIO_NOCLOSE);
130 }
131 informat = FORMAT_PEM;
132 outformat = FORMAT_PEM;
133
134 argc--;
135 argv++;
136 num = 0;
137 while (argc >= 1) {
138#ifdef undef
139 if (strcmp(*argv, "-p") == 0) {
140 if (--argc < 1)
141 goto bad;
142 if (!args_from_file(++argv, Nargc, Nargv)) {
143 goto end;
144 }
145 }
146#endif
147 if (strcmp(*argv, "-inform") == 0) {
148 if (--argc < 1)
149 goto bad;
150 informat = str2fmt(*(++argv));
151 } else if (strcmp(*argv, "-outform") == 0) {
152 if (--argc < 1)
153 goto bad;
154 outformat = str2fmt(*(++argv));
155 } else if (strcmp(*argv, "-in") == 0) {
156 if (--argc < 1)
157 goto bad;
158 infile = *(++argv);
159 } else if (strcmp(*argv, "-out") == 0) {
160 if (--argc < 1)
161 goto bad;
162 outfile = *(++argv);
163 } else if (strcmp(*argv, "-CApath") == 0) {
164 if (--argc < 1)
165 goto bad;
166 CApath = *(++argv);
167 do_ver = 1;
168 } else if (strcmp(*argv, "-CAfile") == 0) {
169 if (--argc < 1)
170 goto bad;
171 CAfile = *(++argv);
172 do_ver = 1;
173 } else if (strcmp(*argv, "-verify") == 0)
174 do_ver = 1;
175 else if (strcmp(*argv, "-text") == 0)
176 text = 1;
177 else if (strcmp(*argv, "-hash") == 0)
178 hash = ++num;
179#ifndef OPENSSL_NO_MD5
180 else if (strcmp(*argv, "-hash_old") == 0)
181 hash_old = ++num;
182#endif
183 else if (strcmp(*argv, "-nameopt") == 0) {
184 if (--argc < 1)
185 goto bad;
186 if (!set_name_ex(&nmflag, *(++argv)))
187 goto bad;
188 } else if (strcmp(*argv, "-issuer") == 0)
189 issuer = ++num;
190 else if (strcmp(*argv, "-lastupdate") == 0)
191 lastupdate = ++num;
192 else if (strcmp(*argv, "-nextupdate") == 0)
193 nextupdate = ++num;
194 else if (strcmp(*argv, "-noout") == 0)
195 noout = ++num;
196 else if (strcmp(*argv, "-fingerprint") == 0)
197 fingerprint = ++num;
198 else if (strcmp(*argv, "-crlnumber") == 0)
199 crlnumber = ++num;
200 else if ((md_alg = EVP_get_digestbyname(*argv + 1))) {
201 /* ok */
202 digest = md_alg;
203 } else {
204 BIO_printf(bio_err, "unknown option %s\n", *argv);
205 badops = 1;
206 break;
207 }
208 argc--;
209 argv++;
210 }
211
212 if (badops) {
213bad:
214 for (pp = crl_usage; (*pp != NULL); pp++)
215 BIO_printf(bio_err, "%s", *pp);
216 goto end;
217 }
218 ERR_load_crypto_strings();
219 x = load_crl(infile, informat);
220 if (x == NULL) {
221 goto end;
222 }
223 if (do_ver) {
224 store = X509_STORE_new();
225 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
226 if (lookup == NULL)
227 goto end;
228 if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM))
229 X509_LOOKUP_load_file(lookup, NULL,
230 X509_FILETYPE_DEFAULT);
231
232 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
233 if (lookup == NULL)
234 goto end;
235 if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM))
236 X509_LOOKUP_add_dir(lookup, NULL,
237 X509_FILETYPE_DEFAULT);
238 ERR_clear_error();
239
240 if (!X509_STORE_CTX_init(&ctx, store, NULL, NULL)) {
241 BIO_printf(bio_err,
242 "Error initialising X509 store\n");
243 goto end;
244 }
245 i = X509_STORE_get_by_subject(&ctx, X509_LU_X509,
246 X509_CRL_get_issuer(x), &xobj);
247 if (i <= 0) {
248 BIO_printf(bio_err,
249 "Error getting CRL issuer certificate\n");
250 goto end;
251 }
252 pkey = X509_get_pubkey(xobj.data.x509);
253 X509_OBJECT_free_contents(&xobj);
254 if (!pkey) {
255 BIO_printf(bio_err,
256 "Error getting CRL issuer public key\n");
257 goto end;
258 }
259 i = X509_CRL_verify(x, pkey);
260 EVP_PKEY_free(pkey);
261 if (i < 0)
262 goto end;
263 if (i == 0)
264 BIO_printf(bio_err, "verify failure\n");
265 else
266 BIO_printf(bio_err, "verify OK\n");
267 }
268 if (num) {
269 for (i = 1; i <= num; i++) {
270 if (issuer == i) {
271 print_name(bio_out, "issuer=",
272 X509_CRL_get_issuer(x), nmflag);
273 }
274 if (crlnumber == i) {
275 ASN1_INTEGER *crlnum;
276 crlnum = X509_CRL_get_ext_d2i(x,
277 NID_crl_number, NULL, NULL);
278 BIO_printf(bio_out, "crlNumber=");
279 if (crlnum) {
280 i2a_ASN1_INTEGER(bio_out, crlnum);
281 ASN1_INTEGER_free(crlnum);
282 } else
283 BIO_puts(bio_out, "<NONE>");
284 BIO_printf(bio_out, "\n");
285 }
286 if (hash == i) {
287 BIO_printf(bio_out, "%08lx\n",
288 X509_NAME_hash(X509_CRL_get_issuer(x)));
289 }
290#ifndef OPENSSL_NO_MD5
291 if (hash_old == i) {
292 BIO_printf(bio_out, "%08lx\n",
293 X509_NAME_hash_old(X509_CRL_get_issuer(x)));
294 }
295#endif
296 if (lastupdate == i) {
297 BIO_printf(bio_out, "lastUpdate=");
298 ASN1_TIME_print(bio_out,
299 X509_CRL_get_lastUpdate(x));
300 BIO_printf(bio_out, "\n");
301 }
302 if (nextupdate == i) {
303 BIO_printf(bio_out, "nextUpdate=");
304 if (X509_CRL_get_nextUpdate(x))
305 ASN1_TIME_print(bio_out,
306 X509_CRL_get_nextUpdate(x));
307 else
308 BIO_printf(bio_out, "NONE");
309 BIO_printf(bio_out, "\n");
310 }
311 if (fingerprint == i) {
312 int j;
313 unsigned int n;
314 unsigned char md[EVP_MAX_MD_SIZE];
315
316 if (!X509_CRL_digest(x, digest, md, &n)) {
317 BIO_printf(bio_err, "out of memory\n");
318 goto end;
319 }
320 BIO_printf(bio_out, "%s Fingerprint=",
321 OBJ_nid2sn(EVP_MD_type(digest)));
322 for (j = 0; j < (int) n; j++) {
323 BIO_printf(bio_out, "%02X%c", md[j],
324 (j + 1 == (int)n) ? '\n' : ':');
325 }
326 }
327 }
328 }
329 out = BIO_new(BIO_s_file());
330 if (out == NULL) {
331 ERR_print_errors(bio_err);
332 goto end;
333 }
334 if (outfile == NULL) {
335 BIO_set_fp(out, stdout, BIO_NOCLOSE);
336 } else {
337 if (BIO_write_filename(out, outfile) <= 0) {
338 perror(outfile);
339 goto end;
340 }
341 }
342
343 if (text)
344 X509_CRL_print(out, x);
345
346 if (noout) {
347 ret = 0;
348 goto end;
349 }
350 if (outformat == FORMAT_ASN1)
351 i = (int) i2d_X509_CRL_bio(out, x);
352 else if (outformat == FORMAT_PEM)
353 i = PEM_write_bio_X509_CRL(out, x);
354 else {
355 BIO_printf(bio_err,
356 "bad output format specified for outfile\n");
357 goto end;
358 }
359 if (!i) {
360 BIO_printf(bio_err, "unable to write CRL\n");
361 goto end;
362 }
363 ret = 0;
364
365end:
366 BIO_free_all(out);
367 BIO_free_all(bio_out);
368 bio_out = NULL;
369 X509_CRL_free(x);
370 if (store) {
371 X509_STORE_CTX_cleanup(&ctx);
372 X509_STORE_free(store);
373 }
374
375 return (ret);
376}
377
378static X509_CRL *
379load_crl(char *infile, int format)
380{
381 X509_CRL *x = NULL;
382 BIO *in = NULL;
383
384 in = BIO_new(BIO_s_file());
385 if (in == NULL) {
386 ERR_print_errors(bio_err);
387 goto end;
388 }
389 if (infile == NULL)
390 BIO_set_fp(in, stdin, BIO_NOCLOSE);
391 else {
392 if (BIO_read_filename(in, infile) <= 0) {
393 perror(infile);
394 goto end;
395 }
396 }
397 if (format == FORMAT_ASN1)
398 x = d2i_X509_CRL_bio(in, NULL);
399 else if (format == FORMAT_PEM)
400 x = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
401 else {
402 BIO_printf(bio_err,
403 "bad input format specified for input crl\n");
404 goto end;
405 }
406 if (x == NULL) {
407 BIO_printf(bio_err, "unable to load CRL\n");
408 ERR_print_errors(bio_err);
409 goto end;
410 }
411
412end:
413 BIO_free(in);
414 return (x);
415}
diff --git a/src/usr.bin/openssl/crl2p7.c b/src/usr.bin/openssl/crl2p7.c
new file mode 100644
index 0000000000..7fdb6ccfd4
--- /dev/null
+++ b/src/usr.bin/openssl/crl2p7.c
@@ -0,0 +1,314 @@
1/* $OpenBSD: crl2p7.c,v 1.1 2014/08/26 17:47:24 jsing 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/* This was written by Gordon Chaffee <chaffee@plateau.cs.berkeley.edu>
60 * and donated 'to the cause' along with lots and lots of other fixes to
61 * the library. */
62
63#include <sys/types.h>
64
65#include <stdio.h>
66#include <string.h>
67
68#include "apps.h"
69
70#include <openssl/err.h>
71#include <openssl/evp.h>
72#include <openssl/objects.h>
73#include <openssl/pem.h>
74#include <openssl/pkcs7.h>
75#include <openssl/x509.h>
76
77static int add_certs_from_file(STACK_OF(X509) * stack, char *certfile);
78
79/* -inform arg - input format - default PEM (DER or PEM)
80 * -outform arg - output format - default PEM
81 * -in arg - input file - default stdin
82 * -out arg - output file - default stdout
83 */
84
85int crl2pkcs7_main(int, char **);
86
87int
88crl2pkcs7_main(int argc, char **argv)
89{
90 int i, badops = 0;
91 BIO *in = NULL, *out = NULL;
92 int informat, outformat;
93 char *infile, *outfile, *prog, *certfile;
94 PKCS7 *p7 = NULL;
95 PKCS7_SIGNED *p7s = NULL;
96 X509_CRL *crl = NULL;
97 STACK_OF(OPENSSL_STRING) * certflst = NULL;
98 STACK_OF(X509_CRL) * crl_stack = NULL;
99 STACK_OF(X509) * cert_stack = NULL;
100 int ret = 1, nocrl = 0;
101
102 infile = NULL;
103 outfile = NULL;
104 informat = FORMAT_PEM;
105 outformat = FORMAT_PEM;
106
107 prog = argv[0];
108 argc--;
109 argv++;
110 while (argc >= 1) {
111 if (strcmp(*argv, "-inform") == 0) {
112 if (--argc < 1)
113 goto bad;
114 informat = str2fmt(*(++argv));
115 } else if (strcmp(*argv, "-outform") == 0) {
116 if (--argc < 1)
117 goto bad;
118 outformat = str2fmt(*(++argv));
119 } else if (strcmp(*argv, "-in") == 0) {
120 if (--argc < 1)
121 goto bad;
122 infile = *(++argv);
123 } else if (strcmp(*argv, "-nocrl") == 0) {
124 nocrl = 1;
125 } else if (strcmp(*argv, "-out") == 0) {
126 if (--argc < 1)
127 goto bad;
128 outfile = *(++argv);
129 } else if (strcmp(*argv, "-certfile") == 0) {
130 if (--argc < 1)
131 goto bad;
132 if (!certflst)
133 certflst = sk_OPENSSL_STRING_new_null();
134 sk_OPENSSL_STRING_push(certflst, *(++argv));
135 } else {
136 BIO_printf(bio_err, "unknown option %s\n", *argv);
137 badops = 1;
138 break;
139 }
140 argc--;
141 argv++;
142 }
143
144 if (badops) {
145bad:
146 BIO_printf(bio_err, "%s [options] <infile >outfile\n", prog);
147 BIO_printf(bio_err, "where options are\n");
148 BIO_printf(bio_err, " -inform arg input format - DER or PEM\n");
149 BIO_printf(bio_err, " -outform arg output format - DER or PEM\n");
150 BIO_printf(bio_err, " -in arg input file\n");
151 BIO_printf(bio_err, " -out arg output file\n");
152 BIO_printf(bio_err, " -certfile arg certificates file of chain to a trusted CA\n");
153 BIO_printf(bio_err, " (can be used more than once)\n");
154 BIO_printf(bio_err, " -nocrl no crl to load, just certs from '-certfile'\n");
155 ret = 1;
156 goto end;
157 }
158 ERR_load_crypto_strings();
159
160 in = BIO_new(BIO_s_file());
161 out = BIO_new(BIO_s_file());
162 if ((in == NULL) || (out == NULL)) {
163 ERR_print_errors(bio_err);
164 goto end;
165 }
166 if (!nocrl) {
167 if (infile == NULL)
168 BIO_set_fp(in, stdin, BIO_NOCLOSE);
169 else {
170 if (BIO_read_filename(in, infile) <= 0) {
171 perror(infile);
172 goto end;
173 }
174 }
175
176 if (informat == FORMAT_ASN1)
177 crl = d2i_X509_CRL_bio(in, NULL);
178 else if (informat == FORMAT_PEM)
179 crl = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
180 else {
181 BIO_printf(bio_err,
182 "bad input format specified for input crl\n");
183 goto end;
184 }
185 if (crl == NULL) {
186 BIO_printf(bio_err, "unable to load CRL\n");
187 ERR_print_errors(bio_err);
188 goto end;
189 }
190 }
191 if ((p7 = PKCS7_new()) == NULL)
192 goto end;
193 if ((p7s = PKCS7_SIGNED_new()) == NULL)
194 goto end;
195 p7->type = OBJ_nid2obj(NID_pkcs7_signed);
196 p7->d.sign = p7s;
197 p7s->contents->type = OBJ_nid2obj(NID_pkcs7_data);
198
199 if (!ASN1_INTEGER_set(p7s->version, 1))
200 goto end;
201 if ((crl_stack = sk_X509_CRL_new_null()) == NULL)
202 goto end;
203 p7s->crl = crl_stack;
204 if (crl != NULL) {
205 sk_X509_CRL_push(crl_stack, crl);
206 crl = NULL; /* now part of p7 for freeing */
207 }
208 if ((cert_stack = sk_X509_new_null()) == NULL)
209 goto end;
210 p7s->cert = cert_stack;
211
212 if (certflst)
213 for (i = 0; i < sk_OPENSSL_STRING_num(certflst); i++) {
214 certfile = sk_OPENSSL_STRING_value(certflst, i);
215 if (add_certs_from_file(cert_stack, certfile) < 0) {
216 BIO_printf(bio_err,
217 "error loading certificates\n");
218 ERR_print_errors(bio_err);
219 goto end;
220 }
221 }
222
223 sk_OPENSSL_STRING_free(certflst);
224
225 if (outfile == NULL) {
226 BIO_set_fp(out, stdout, BIO_NOCLOSE);
227 } else {
228 if (BIO_write_filename(out, outfile) <= 0) {
229 perror(outfile);
230 goto end;
231 }
232 }
233
234 if (outformat == FORMAT_ASN1)
235 i = i2d_PKCS7_bio(out, p7);
236 else if (outformat == FORMAT_PEM)
237 i = PEM_write_bio_PKCS7(out, p7);
238 else {
239 BIO_printf(bio_err,
240 "bad output format specified for outfile\n");
241 goto end;
242 }
243 if (!i) {
244 BIO_printf(bio_err, "unable to write pkcs7 object\n");
245 ERR_print_errors(bio_err);
246 goto end;
247 }
248 ret = 0;
249
250end:
251 if (in != NULL)
252 BIO_free(in);
253 if (out != NULL)
254 BIO_free_all(out);
255 if (p7 != NULL)
256 PKCS7_free(p7);
257 if (crl != NULL)
258 X509_CRL_free(crl);
259
260
261 return (ret);
262}
263
264/*
265 *----------------------------------------------------------------------
266 * int add_certs_from_file
267 *
268 * Read a list of certificates to be checked from a file.
269 *
270 * Results:
271 * number of certs added if successful, -1 if not.
272 *----------------------------------------------------------------------
273 */
274static int
275add_certs_from_file(STACK_OF(X509) * stack, char *certfile)
276{
277 BIO *in = NULL;
278 int count = 0;
279 int ret = -1;
280 STACK_OF(X509_INFO) * sk = NULL;
281 X509_INFO *xi;
282
283 in = BIO_new(BIO_s_file());
284 if ((in == NULL) || (BIO_read_filename(in, certfile) <= 0)) {
285 BIO_printf(bio_err, "error opening the file, %s\n", certfile);
286 goto end;
287 }
288 /* This loads from a file, a stack of x509/crl/pkey sets */
289 sk = PEM_X509_INFO_read_bio(in, NULL, NULL, NULL);
290 if (sk == NULL) {
291 BIO_printf(bio_err, "error reading the file, %s\n", certfile);
292 goto end;
293 }
294 /* scan over it and pull out the CRL's */
295 while (sk_X509_INFO_num(sk)) {
296 xi = sk_X509_INFO_shift(sk);
297 if (xi->x509 != NULL) {
298 sk_X509_push(stack, xi->x509);
299 xi->x509 = NULL;
300 count++;
301 }
302 X509_INFO_free(xi);
303 }
304
305 ret = count;
306
307end:
308 /* never need to free x */
309 if (in != NULL)
310 BIO_free(in);
311 if (sk != NULL)
312 sk_X509_INFO_free(sk);
313 return (ret);
314}
diff --git a/src/usr.bin/openssl/dgst.c b/src/usr.bin/openssl/dgst.c
new file mode 100644
index 0000000000..ab64af9192
--- /dev/null
+++ b/src/usr.bin/openssl/dgst.c
@@ -0,0 +1,547 @@
1/* $OpenBSD: dgst.c,v 1.1 2014/08/26 17:47:24 jsing 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#include <stdlib.h>
61#include <string.h>
62
63#include "apps.h"
64
65#include <openssl/bio.h>
66#include <openssl/err.h>
67#include <openssl/evp.h>
68#include <openssl/hmac.h>
69#include <openssl/objects.h>
70#include <openssl/pem.h>
71#include <openssl/x509.h>
72
73#define BUFSIZE 1024*8
74
75int
76do_fp(BIO * out, unsigned char *buf, BIO * bp, int sep, int binout,
77 EVP_PKEY * key, unsigned char *sigin, int siglen,
78 const char *sig_name, const char *md_name,
79 const char *file, BIO * bmd);
80
81static void
82list_md_fn(const EVP_MD * m, const char *from, const char *to, void *arg)
83{
84 const char *mname;
85 /* Skip aliases */
86 if (!m)
87 return;
88 mname = OBJ_nid2ln(EVP_MD_type(m));
89 /* Skip shortnames */
90 if (strcmp(from, mname))
91 return;
92 /* Skip clones */
93 if (EVP_MD_flags(m) & EVP_MD_FLAG_PKEY_DIGEST)
94 return;
95 if (strchr(mname, ' '))
96 mname = EVP_MD_name(m);
97 BIO_printf(arg, "-%-14s to use the %s message digest algorithm\n",
98 mname, mname);
99}
100
101int dgst_main(int, char **);
102
103int
104dgst_main(int argc, char **argv)
105{
106 ENGINE *e = NULL;
107 unsigned char *buf = NULL;
108 int i, err = 1;
109 const EVP_MD *md = NULL, *m;
110 BIO *in = NULL, *inp;
111 BIO *bmd = NULL;
112 BIO *out = NULL;
113#define PROG_NAME_SIZE 39
114 char pname[PROG_NAME_SIZE + 1];
115 int separator = 0;
116 int debug = 0;
117 int keyform = FORMAT_PEM;
118 const char *outfile = NULL, *keyfile = NULL;
119 const char *sigfile = NULL;
120 int out_bin = -1, want_pub = 0, do_verify = 0;
121 EVP_PKEY *sigkey = NULL;
122 unsigned char *sigbuf = NULL;
123 int siglen = 0;
124 char *passargin = NULL, *passin = NULL;
125#ifndef OPENSSL_NO_ENGINE
126 char *engine = NULL;
127#endif
128 char *hmac_key = NULL;
129 char *mac_name = NULL;
130 STACK_OF(OPENSSL_STRING) * sigopts = NULL, *macopts = NULL;
131
132 if ((buf = malloc(BUFSIZE)) == NULL) {
133 BIO_printf(bio_err, "out of memory\n");
134 goto end;
135 }
136
137 /* first check the program name */
138 program_name(argv[0], pname, sizeof pname);
139
140 md = EVP_get_digestbyname(pname);
141
142 argc--;
143 argv++;
144 while (argc > 0) {
145 if ((*argv)[0] != '-')
146 break;
147 if (strcmp(*argv, "-c") == 0)
148 separator = 1;
149 else if (strcmp(*argv, "-r") == 0)
150 separator = 2;
151 else if (strcmp(*argv, "-out") == 0) {
152 if (--argc < 1)
153 break;
154 outfile = *(++argv);
155 } else if (strcmp(*argv, "-sign") == 0) {
156 if (--argc < 1)
157 break;
158 keyfile = *(++argv);
159 } else if (!strcmp(*argv, "-passin")) {
160 if (--argc < 1)
161 break;
162 passargin = *++argv;
163 } else if (strcmp(*argv, "-verify") == 0) {
164 if (--argc < 1)
165 break;
166 keyfile = *(++argv);
167 want_pub = 1;
168 do_verify = 1;
169 } else if (strcmp(*argv, "-prverify") == 0) {
170 if (--argc < 1)
171 break;
172 keyfile = *(++argv);
173 do_verify = 1;
174 } else if (strcmp(*argv, "-signature") == 0) {
175 if (--argc < 1)
176 break;
177 sigfile = *(++argv);
178 } else if (strcmp(*argv, "-keyform") == 0) {
179 if (--argc < 1)
180 break;
181 keyform = str2fmt(*(++argv));
182 }
183#ifndef OPENSSL_NO_ENGINE
184 else if (strcmp(*argv, "-engine") == 0) {
185 if (--argc < 1)
186 break;
187 engine = *(++argv);
188 e = setup_engine(bio_err, engine, 0);
189 }
190#endif
191 else if (strcmp(*argv, "-hex") == 0)
192 out_bin = 0;
193 else if (strcmp(*argv, "-binary") == 0)
194 out_bin = 1;
195 else if (strcmp(*argv, "-d") == 0)
196 debug = 1;
197 else if (!strcmp(*argv, "-hmac")) {
198 if (--argc < 1)
199 break;
200 hmac_key = *++argv;
201 } else if (!strcmp(*argv, "-mac")) {
202 if (--argc < 1)
203 break;
204 mac_name = *++argv;
205 } else if (strcmp(*argv, "-sigopt") == 0) {
206 if (--argc < 1)
207 break;
208 if (!sigopts)
209 sigopts = sk_OPENSSL_STRING_new_null();
210 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, *(++argv)))
211 break;
212 } else if (strcmp(*argv, "-macopt") == 0) {
213 if (--argc < 1)
214 break;
215 if (!macopts)
216 macopts = sk_OPENSSL_STRING_new_null();
217 if (!macopts || !sk_OPENSSL_STRING_push(macopts, *(++argv)))
218 break;
219 } else if ((m = EVP_get_digestbyname(&((*argv)[1]))) != NULL)
220 md = m;
221 else
222 break;
223 argc--;
224 argv++;
225 }
226
227
228 if (do_verify && !sigfile) {
229 BIO_printf(bio_err, "No signature to verify: use the -signature option\n");
230 goto end;
231 }
232 if ((argc > 0) && (argv[0][0] == '-')) { /* bad option */
233 BIO_printf(bio_err, "unknown option '%s'\n", *argv);
234 BIO_printf(bio_err, "options are\n");
235 BIO_printf(bio_err, "-c to output the digest with separating colons\n");
236 BIO_printf(bio_err, "-r to output the digest in coreutils format\n");
237 BIO_printf(bio_err, "-d to output debug info\n");
238 BIO_printf(bio_err, "-hex output as hex dump\n");
239 BIO_printf(bio_err, "-binary output in binary form\n");
240 BIO_printf(bio_err, "-sign file sign digest using private key in file\n");
241 BIO_printf(bio_err, "-verify file verify a signature using public key in file\n");
242 BIO_printf(bio_err, "-prverify file verify a signature using private key in file\n");
243 BIO_printf(bio_err, "-keyform arg key file format (PEM or ENGINE)\n");
244 BIO_printf(bio_err, "-out filename output to filename rather than stdout\n");
245 BIO_printf(bio_err, "-signature file signature to verify\n");
246 BIO_printf(bio_err, "-sigopt nm:v signature parameter\n");
247 BIO_printf(bio_err, "-hmac key create hashed MAC with key\n");
248 BIO_printf(bio_err, "-mac algorithm create MAC (not neccessarily HMAC)\n");
249 BIO_printf(bio_err, "-macopt nm:v MAC algorithm parameters or key\n");
250#ifndef OPENSSL_NO_ENGINE
251 BIO_printf(bio_err, "-engine e use engine e, possibly a hardware device.\n");
252#endif
253
254 EVP_MD_do_all_sorted(list_md_fn, bio_err);
255 goto end;
256 }
257 in = BIO_new(BIO_s_file());
258 bmd = BIO_new(BIO_f_md());
259 if (debug) {
260 BIO_set_callback(in, BIO_debug_callback);
261 /* needed for windows 3.1 */
262 BIO_set_callback_arg(in, (char *) bio_err);
263 }
264 if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) {
265 BIO_printf(bio_err, "Error getting password\n");
266 goto end;
267 }
268 if ((in == NULL) || (bmd == NULL)) {
269 ERR_print_errors(bio_err);
270 goto end;
271 }
272 if (out_bin == -1) {
273 if (keyfile)
274 out_bin = 1;
275 else
276 out_bin = 0;
277 }
278
279 if (outfile) {
280 if (out_bin)
281 out = BIO_new_file(outfile, "wb");
282 else
283 out = BIO_new_file(outfile, "w");
284 } else {
285 out = BIO_new_fp(stdout, BIO_NOCLOSE);
286 }
287
288 if (!out) {
289 BIO_printf(bio_err, "Error opening output file %s\n",
290 outfile ? outfile : "(stdout)");
291 ERR_print_errors(bio_err);
292 goto end;
293 }
294 if ((!!mac_name + !!keyfile + !!hmac_key) > 1) {
295 BIO_printf(bio_err, "MAC and Signing key cannot both be specified\n");
296 goto end;
297 }
298 if (keyfile) {
299 if (want_pub)
300 sigkey = load_pubkey(bio_err, keyfile, keyform, 0, NULL,
301 e, "key file");
302 else
303 sigkey = load_key(bio_err, keyfile, keyform, 0, passin,
304 e, "key file");
305 if (!sigkey) {
306 /*
307 * load_[pub]key() has already printed an appropriate
308 * message
309 */
310 goto end;
311 }
312 }
313 if (mac_name) {
314 EVP_PKEY_CTX *mac_ctx = NULL;
315 int r = 0;
316 if (!init_gen_str(bio_err, &mac_ctx, mac_name, e, 0))
317 goto mac_end;
318 if (macopts) {
319 char *macopt;
320 for (i = 0; i < sk_OPENSSL_STRING_num(macopts); i++) {
321 macopt = sk_OPENSSL_STRING_value(macopts, i);
322 if (pkey_ctrl_string(mac_ctx, macopt) <= 0) {
323 BIO_printf(bio_err,
324 "MAC parameter error \"%s\"\n",
325 macopt);
326 ERR_print_errors(bio_err);
327 goto mac_end;
328 }
329 }
330 }
331 if (EVP_PKEY_keygen(mac_ctx, &sigkey) <= 0) {
332 BIO_puts(bio_err, "Error generating key\n");
333 ERR_print_errors(bio_err);
334 goto mac_end;
335 }
336 r = 1;
337mac_end:
338 if (mac_ctx)
339 EVP_PKEY_CTX_free(mac_ctx);
340 if (r == 0)
341 goto end;
342 }
343 if (hmac_key) {
344 sigkey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, e,
345 (unsigned char *) hmac_key, -1);
346 if (!sigkey)
347 goto end;
348 }
349 if (sigkey) {
350 EVP_MD_CTX *mctx = NULL;
351 EVP_PKEY_CTX *pctx = NULL;
352 int r;
353 if (!BIO_get_md_ctx(bmd, &mctx)) {
354 BIO_printf(bio_err, "Error getting context\n");
355 ERR_print_errors(bio_err);
356 goto end;
357 }
358 if (do_verify)
359 r = EVP_DigestVerifyInit(mctx, &pctx, md, NULL, sigkey);
360 else
361 r = EVP_DigestSignInit(mctx, &pctx, md, NULL, sigkey);
362 if (!r) {
363 BIO_printf(bio_err, "Error setting context\n");
364 ERR_print_errors(bio_err);
365 goto end;
366 }
367 if (sigopts) {
368 char *sigopt;
369 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
370 sigopt = sk_OPENSSL_STRING_value(sigopts, i);
371 if (pkey_ctrl_string(pctx, sigopt) <= 0) {
372 BIO_printf(bio_err,
373 "parameter error \"%s\"\n",
374 sigopt);
375 ERR_print_errors(bio_err);
376 goto end;
377 }
378 }
379 }
380 }
381 /* we use md as a filter, reading from 'in' */
382 else {
383 if (md == NULL)
384 md = EVP_md5();
385 if (!BIO_set_md(bmd, md)) {
386 BIO_printf(bio_err, "Error setting digest %s\n", pname);
387 ERR_print_errors(bio_err);
388 goto end;
389 }
390 }
391
392 if (sigfile && sigkey) {
393 BIO *sigbio;
394 sigbio = BIO_new_file(sigfile, "rb");
395 siglen = EVP_PKEY_size(sigkey);
396 sigbuf = malloc(siglen);
397 if (!sigbio) {
398 BIO_printf(bio_err, "Error opening signature file %s\n",
399 sigfile);
400 ERR_print_errors(bio_err);
401 goto end;
402 }
403 siglen = BIO_read(sigbio, sigbuf, siglen);
404 BIO_free(sigbio);
405 if (siglen <= 0) {
406 BIO_printf(bio_err, "Error reading signature file %s\n",
407 sigfile);
408 ERR_print_errors(bio_err);
409 goto end;
410 }
411 }
412 inp = BIO_push(bmd, in);
413
414 if (md == NULL) {
415 EVP_MD_CTX *tctx;
416 BIO_get_md_ctx(bmd, &tctx);
417 md = EVP_MD_CTX_md(tctx);
418 }
419 if (argc == 0) {
420 BIO_set_fp(in, stdin, BIO_NOCLOSE);
421 err = do_fp(out, buf, inp, separator, out_bin, sigkey, sigbuf,
422 siglen, NULL, NULL, "stdin", bmd);
423 } else {
424 const char *md_name = NULL, *sig_name = NULL;
425 if (!out_bin) {
426 if (sigkey) {
427 const EVP_PKEY_ASN1_METHOD *ameth;
428 ameth = EVP_PKEY_get0_asn1(sigkey);
429 if (ameth)
430 EVP_PKEY_asn1_get0_info(NULL, NULL,
431 NULL, NULL, &sig_name, ameth);
432 }
433 md_name = EVP_MD_name(md);
434 }
435 err = 0;
436 for (i = 0; i < argc; i++) {
437 int r;
438 if (BIO_read_filename(in, argv[i]) <= 0) {
439 perror(argv[i]);
440 err++;
441 continue;
442 } else {
443 r = do_fp(out, buf, inp, separator, out_bin,
444 sigkey, sigbuf, siglen, sig_name, md_name,
445 argv[i], bmd);
446 }
447 if (r)
448 err = r;
449 (void) BIO_reset(bmd);
450 }
451 }
452
453end:
454 if (buf != NULL) {
455 OPENSSL_cleanse(buf, BUFSIZE);
456 free(buf);
457 }
458 if (in != NULL)
459 BIO_free(in);
460 free(passin);
461 BIO_free_all(out);
462 EVP_PKEY_free(sigkey);
463 if (sigopts)
464 sk_OPENSSL_STRING_free(sigopts);
465 if (macopts)
466 sk_OPENSSL_STRING_free(macopts);
467 free(sigbuf);
468 if (bmd != NULL)
469 BIO_free(bmd);
470
471 return (err);
472}
473
474int
475do_fp(BIO * out, unsigned char *buf, BIO * bp, int sep, int binout,
476 EVP_PKEY * key, unsigned char *sigin, int siglen,
477 const char *sig_name, const char *md_name,
478 const char *file, BIO * bmd)
479{
480 size_t len;
481 int i;
482
483 for (;;) {
484 i = BIO_read(bp, (char *) buf, BUFSIZE);
485 if (i < 0) {
486 BIO_printf(bio_err, "Read Error in %s\n", file);
487 ERR_print_errors(bio_err);
488 return 1;
489 }
490 if (i == 0)
491 break;
492 }
493 if (sigin) {
494 EVP_MD_CTX *ctx;
495 BIO_get_md_ctx(bp, &ctx);
496 i = EVP_DigestVerifyFinal(ctx, sigin, (unsigned int) siglen);
497 if (i > 0)
498 BIO_printf(out, "Verified OK\n");
499 else if (i == 0) {
500 BIO_printf(out, "Verification Failure\n");
501 return 1;
502 } else {
503 BIO_printf(bio_err, "Error Verifying Data\n");
504 ERR_print_errors(bio_err);
505 return 1;
506 }
507 return 0;
508 }
509 if (key) {
510 EVP_MD_CTX *ctx;
511 BIO_get_md_ctx(bp, &ctx);
512 len = BUFSIZE;
513 if (!EVP_DigestSignFinal(ctx, buf, &len)) {
514 BIO_printf(bio_err, "Error Signing Data\n");
515 ERR_print_errors(bio_err);
516 return 1;
517 }
518 } else {
519 len = BIO_gets(bp, (char *) buf, BUFSIZE);
520 if ((int) len < 0) {
521 ERR_print_errors(bio_err);
522 return 1;
523 }
524 }
525
526 if (binout)
527 BIO_write(out, buf, len);
528 else if (sep == 2) {
529 for (i = 0; i < (int) len; i++)
530 BIO_printf(out, "%02x", buf[i]);
531 BIO_printf(out, " *%s\n", file);
532 } else {
533 if (sig_name)
534 BIO_printf(out, "%s-%s(%s)= ", sig_name, md_name, file);
535 else if (md_name)
536 BIO_printf(out, "%s(%s)= ", md_name, file);
537 else
538 BIO_printf(out, "(%s)= ", file);
539 for (i = 0; i < (int) len; i++) {
540 if (sep && (i != 0))
541 BIO_printf(out, ":");
542 BIO_printf(out, "%02x", buf[i]);
543 }
544 BIO_printf(out, "\n");
545 }
546 return 0;
547}
diff --git a/src/usr.bin/openssl/dh.c b/src/usr.bin/openssl/dh.c
new file mode 100644
index 0000000000..447b4c800f
--- /dev/null
+++ b/src/usr.bin/openssl/dh.c
@@ -0,0 +1,308 @@
1/* $OpenBSD: dh.c,v 1.1 2014/08/26 17:47:24 jsing 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 <openssl/opensslconf.h> /* for OPENSSL_NO_DH */
60
61#ifndef OPENSSL_NO_DH
62
63#include <stdio.h>
64#include <stdlib.h>
65#include <string.h>
66#include <time.h>
67
68#include "apps.h"
69
70#include <openssl/bio.h>
71#include <openssl/bn.h>
72#include <openssl/err.h>
73#include <openssl/dh.h>
74#include <openssl/pem.h>
75#include <openssl/x509.h>
76
77/* -inform arg - input format - default PEM (DER or PEM)
78 * -outform arg - output format - default PEM
79 * -in arg - input file - default stdin
80 * -out arg - output file - default stdout
81 * -check - check the parameters are ok
82 * -noout
83 * -text
84 * -C
85 */
86
87int dh_main(int, char **);
88
89int
90dh_main(int argc, char **argv)
91{
92 DH *dh = NULL;
93 int i, badops = 0, text = 0;
94 BIO *in = NULL, *out = NULL;
95 int informat, outformat, check = 0, noout = 0, C = 0, ret = 1;
96 char *infile, *outfile, *prog;
97#ifndef OPENSSL_NO_ENGINE
98 char *engine;
99#endif
100
101#ifndef OPENSSL_NO_ENGINE
102 engine = NULL;
103#endif
104 infile = NULL;
105 outfile = NULL;
106 informat = FORMAT_PEM;
107 outformat = FORMAT_PEM;
108
109 prog = argv[0];
110 argc--;
111 argv++;
112 while (argc >= 1) {
113 if (strcmp(*argv, "-inform") == 0) {
114 if (--argc < 1)
115 goto bad;
116 informat = str2fmt(*(++argv));
117 } else if (strcmp(*argv, "-outform") == 0) {
118 if (--argc < 1)
119 goto bad;
120 outformat = str2fmt(*(++argv));
121 } else if (strcmp(*argv, "-in") == 0) {
122 if (--argc < 1)
123 goto bad;
124 infile = *(++argv);
125 } else if (strcmp(*argv, "-out") == 0) {
126 if (--argc < 1)
127 goto bad;
128 outfile = *(++argv);
129 }
130#ifndef OPENSSL_NO_ENGINE
131 else if (strcmp(*argv, "-engine") == 0) {
132 if (--argc < 1)
133 goto bad;
134 engine = *(++argv);
135 }
136#endif
137 else if (strcmp(*argv, "-check") == 0)
138 check = 1;
139 else if (strcmp(*argv, "-text") == 0)
140 text = 1;
141 else if (strcmp(*argv, "-C") == 0)
142 C = 1;
143 else if (strcmp(*argv, "-noout") == 0)
144 noout = 1;
145 else {
146 BIO_printf(bio_err, "unknown option %s\n", *argv);
147 badops = 1;
148 break;
149 }
150 argc--;
151 argv++;
152 }
153
154 if (badops) {
155bad:
156 BIO_printf(bio_err, "%s [options] <infile >outfile\n", prog);
157 BIO_printf(bio_err, "where options are\n");
158 BIO_printf(bio_err, " -inform arg input format - one of DER PEM\n");
159 BIO_printf(bio_err, " -outform arg output format - one of DER PEM\n");
160 BIO_printf(bio_err, " -in arg input file\n");
161 BIO_printf(bio_err, " -out arg output file\n");
162 BIO_printf(bio_err, " -check check the DH parameters\n");
163 BIO_printf(bio_err, " -text print a text form of the DH parameters\n");
164 BIO_printf(bio_err, " -C Output C code\n");
165 BIO_printf(bio_err, " -noout no output\n");
166#ifndef OPENSSL_NO_ENGINE
167 BIO_printf(bio_err, " -engine e use engine e, possibly a hardware device.\n");
168#endif
169 goto end;
170 }
171 ERR_load_crypto_strings();
172
173#ifndef OPENSSL_NO_ENGINE
174 setup_engine(bio_err, engine, 0);
175#endif
176
177 in = BIO_new(BIO_s_file());
178 out = BIO_new(BIO_s_file());
179 if ((in == NULL) || (out == NULL)) {
180 ERR_print_errors(bio_err);
181 goto end;
182 }
183 if (infile == NULL)
184 BIO_set_fp(in, stdin, BIO_NOCLOSE);
185 else {
186 if (BIO_read_filename(in, infile) <= 0) {
187 perror(infile);
188 goto end;
189 }
190 }
191 if (outfile == NULL) {
192 BIO_set_fp(out, stdout, BIO_NOCLOSE);
193 } else {
194 if (BIO_write_filename(out, outfile) <= 0) {
195 perror(outfile);
196 goto end;
197 }
198 }
199
200 if (informat == FORMAT_ASN1)
201 dh = d2i_DHparams_bio(in, NULL);
202 else if (informat == FORMAT_PEM)
203 dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
204 else {
205 BIO_printf(bio_err, "bad input format specified\n");
206 goto end;
207 }
208 if (dh == NULL) {
209 BIO_printf(bio_err, "unable to load DH parameters\n");
210 ERR_print_errors(bio_err);
211 goto end;
212 }
213 if (text) {
214 DHparams_print(out, dh);
215#ifdef undef
216 printf("p=");
217 BN_print(stdout, dh->p);
218 printf("\ng=");
219 BN_print(stdout, dh->g);
220 printf("\n");
221 if (dh->length != 0)
222 printf("recommended private length=%ld\n", dh->length);
223#endif
224 }
225 if (check) {
226 if (!DH_check(dh, &i)) {
227 ERR_print_errors(bio_err);
228 goto end;
229 }
230 if (i & DH_CHECK_P_NOT_PRIME)
231 printf("p value is not prime\n");
232 if (i & DH_CHECK_P_NOT_SAFE_PRIME)
233 printf("p value is not a safe prime\n");
234 if (i & DH_UNABLE_TO_CHECK_GENERATOR)
235 printf("unable to check the generator value\n");
236 if (i & DH_NOT_SUITABLE_GENERATOR)
237 printf("the g value is not a generator\n");
238 if (i == 0)
239 printf("DH parameters appear to be ok.\n");
240 }
241 if (C) {
242 unsigned char *data;
243 int len, l, bits;
244
245 len = BN_num_bytes(dh->p);
246 bits = BN_num_bits(dh->p);
247 data = malloc(len);
248 if (data == NULL) {
249 perror("malloc");
250 goto end;
251 }
252 l = BN_bn2bin(dh->p, data);
253 printf("static unsigned char dh%d_p[] = {", bits);
254 for (i = 0; i < l; i++) {
255 if ((i % 12) == 0)
256 printf("\n\t");
257 printf("0x%02X, ", data[i]);
258 }
259 printf("\n\t};\n");
260
261 l = BN_bn2bin(dh->g, data);
262 printf("static unsigned char dh%d_g[] = {", bits);
263 for (i = 0; i < l; i++) {
264 if ((i % 12) == 0)
265 printf("\n\t");
266 printf("0x%02X, ", data[i]);
267 }
268 printf("\n\t};\n\n");
269
270 printf("DH *get_dh%d()\n\t{\n", bits);
271 printf("\tDH *dh;\n\n");
272 printf("\tif ((dh = DH_new()) == NULL) return(NULL);\n");
273 printf("\tdh->p = BN_bin2bn(dh%d_p, sizeof(dh%d_p), NULL);\n",
274 bits, bits);
275 printf("\tdh->g = BN_bin2bn(dh%d_g, sizeof(dh%d_g), NULL);\n",
276 bits, bits);
277 printf("\tif ((dh->p == NULL) || (dh->g == NULL))\n");
278 printf("\t\treturn(NULL);\n");
279 printf("\treturn(dh);\n\t}\n");
280 free(data);
281 }
282 if (!noout) {
283 if (outformat == FORMAT_ASN1)
284 i = i2d_DHparams_bio(out, dh);
285 else if (outformat == FORMAT_PEM)
286 i = PEM_write_bio_DHparams(out, dh);
287 else {
288 BIO_printf(bio_err, "bad output format specified for outfile\n");
289 goto end;
290 }
291 if (!i) {
292 BIO_printf(bio_err, "unable to write DH parameters\n");
293 ERR_print_errors(bio_err);
294 goto end;
295 }
296 }
297 ret = 0;
298
299end:
300 BIO_free(in);
301 if (out != NULL)
302 BIO_free_all(out);
303 if (dh != NULL)
304 DH_free(dh);
305
306 return (ret);
307}
308#endif
diff --git a/src/usr.bin/openssl/dhparam.c b/src/usr.bin/openssl/dhparam.c
new file mode 100644
index 0000000000..0022f72670
--- /dev/null
+++ b/src/usr.bin/openssl/dhparam.c
@@ -0,0 +1,472 @@
1/* $OpenBSD: dhparam.c,v 1.1 2014/08/26 17:47:24 jsing 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 * Copyright (c) 1998-2000 The OpenSSL Project. All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in
70 * the documentation and/or other materials provided with the
71 * distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 * software must display the following acknowledgment:
75 * "This product includes software developed by the OpenSSL Project
76 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 * endorse or promote products derived from this software without
80 * prior written permission. For written permission, please contact
81 * openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 * nor may "OpenSSL" appear in their names without prior written
85 * permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 * acknowledgment:
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com). This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
111
112#include <openssl/opensslconf.h> /* for OPENSSL_NO_DH */
113
114#ifndef OPENSSL_NO_DH
115
116#include <stdio.h>
117#include <stdlib.h>
118#include <string.h>
119#include <time.h>
120
121#include "apps.h"
122
123#include <openssl/bio.h>
124#include <openssl/bn.h>
125#include <openssl/err.h>
126#include <openssl/dh.h>
127#include <openssl/pem.h>
128#include <openssl/x509.h>
129
130#include <openssl/dsa.h>
131
132#define DEFBITS 512
133
134/* -inform arg - input format - default PEM (DER or PEM)
135 * -outform arg - output format - default PEM
136 * -in arg - input file - default stdin
137 * -out arg - output file - default stdout
138 * -dsaparam - read or generate DSA parameters, convert to DH
139 * -check - check the parameters are ok
140 * -noout
141 * -text
142 * -C
143 */
144
145static int dh_cb(int p, int n, BN_GENCB * cb);
146
147int dhparam_main(int, char **);
148
149int
150dhparam_main(int argc, char **argv)
151{
152 DH *dh = NULL;
153 int i, badops = 0, text = 0;
154 int dsaparam = 0;
155 BIO *in = NULL, *out = NULL;
156 int informat, outformat, check = 0, noout = 0, C = 0, ret = 1;
157 char *infile, *outfile, *prog;
158#ifndef OPENSSL_NO_ENGINE
159 char *engine = NULL;
160#endif
161 int num = 0, g = 0;
162
163 infile = NULL;
164 outfile = NULL;
165 informat = FORMAT_PEM;
166 outformat = FORMAT_PEM;
167
168 prog = argv[0];
169 argc--;
170 argv++;
171 while (argc >= 1) {
172 if (strcmp(*argv, "-inform") == 0) {
173 if (--argc < 1)
174 goto bad;
175 informat = str2fmt(*(++argv));
176 } else if (strcmp(*argv, "-outform") == 0) {
177 if (--argc < 1)
178 goto bad;
179 outformat = str2fmt(*(++argv));
180 } else if (strcmp(*argv, "-in") == 0) {
181 if (--argc < 1)
182 goto bad;
183 infile = *(++argv);
184 } else if (strcmp(*argv, "-out") == 0) {
185 if (--argc < 1)
186 goto bad;
187 outfile = *(++argv);
188 }
189#ifndef OPENSSL_NO_ENGINE
190 else if (strcmp(*argv, "-engine") == 0) {
191 if (--argc < 1)
192 goto bad;
193 engine = *(++argv);
194 }
195#endif
196 else if (strcmp(*argv, "-check") == 0)
197 check = 1;
198 else if (strcmp(*argv, "-text") == 0)
199 text = 1;
200 else if (strcmp(*argv, "-dsaparam") == 0)
201 dsaparam = 1;
202 else if (strcmp(*argv, "-C") == 0)
203 C = 1;
204 else if (strcmp(*argv, "-noout") == 0)
205 noout = 1;
206 else if (strcmp(*argv, "-2") == 0)
207 g = 2;
208 else if (strcmp(*argv, "-5") == 0)
209 g = 5;
210 else if (((sscanf(*argv, "%d", &num) == 0) || (num <= 0)))
211 goto bad;
212 argv++;
213 argc--;
214 }
215
216 if (badops) {
217bad:
218 BIO_printf(bio_err, "%s [options] [numbits]\n", prog);
219 BIO_printf(bio_err, "where options are\n");
220 BIO_printf(bio_err, " -inform arg input format - one of DER PEM\n");
221 BIO_printf(bio_err, " -outform arg output format - one of DER PEM\n");
222 BIO_printf(bio_err, " -in arg input file\n");
223 BIO_printf(bio_err, " -out arg output file\n");
224 BIO_printf(bio_err, " -dsaparam read or generate DSA parameters, convert to DH\n");
225 BIO_printf(bio_err, " -check check the DH parameters\n");
226 BIO_printf(bio_err, " -text print a text form of the DH parameters\n");
227 BIO_printf(bio_err, " -C Output C code\n");
228 BIO_printf(bio_err, " -2 generate parameters using 2 as the generator value\n");
229 BIO_printf(bio_err, " -5 generate parameters using 5 as the generator value\n");
230 BIO_printf(bio_err, " numbits number of bits in to generate (default 512)\n");
231#ifndef OPENSSL_NO_ENGINE
232 BIO_printf(bio_err, " -engine e use engine e, possibly a hardware device.\n");
233#endif
234 BIO_printf(bio_err, " -noout no output\n");
235 goto end;
236 }
237 ERR_load_crypto_strings();
238
239#ifndef OPENSSL_NO_ENGINE
240 setup_engine(bio_err, engine, 0);
241#endif
242
243 if (g && !num)
244 num = DEFBITS;
245
246 if (dsaparam) {
247 if (g) {
248 BIO_printf(bio_err, "generator may not be chosen for DSA parameters\n");
249 goto end;
250 }
251 } else
252 {
253 /* DH parameters */
254 if (num && !g)
255 g = 2;
256 }
257
258 if (num) {
259
260 BN_GENCB cb;
261 BN_GENCB_set(&cb, dh_cb, bio_err);
262 if (dsaparam) {
263 DSA *dsa = DSA_new();
264
265 BIO_printf(bio_err, "Generating DSA parameters, %d bit long prime\n", num);
266 if (!dsa || !DSA_generate_parameters_ex(dsa, num,
267 NULL, 0, NULL, NULL, &cb)) {
268 if (dsa)
269 DSA_free(dsa);
270 ERR_print_errors(bio_err);
271 goto end;
272 }
273 dh = DSA_dup_DH(dsa);
274 DSA_free(dsa);
275 if (dh == NULL) {
276 ERR_print_errors(bio_err);
277 goto end;
278 }
279 } else
280 {
281 dh = DH_new();
282 BIO_printf(bio_err, "Generating DH parameters, %d bit long safe prime, generator %d\n", num, g);
283 BIO_printf(bio_err, "This is going to take a long time\n");
284 if (!dh || !DH_generate_parameters_ex(dh, num, g, &cb)) {
285 ERR_print_errors(bio_err);
286 goto end;
287 }
288 }
289 } else {
290
291 in = BIO_new(BIO_s_file());
292 if (in == NULL) {
293 ERR_print_errors(bio_err);
294 goto end;
295 }
296 if (infile == NULL)
297 BIO_set_fp(in, stdin, BIO_NOCLOSE);
298 else {
299 if (BIO_read_filename(in, infile) <= 0) {
300 perror(infile);
301 goto end;
302 }
303 }
304
305 if (informat != FORMAT_ASN1 && informat != FORMAT_PEM) {
306 BIO_printf(bio_err, "bad input format specified\n");
307 goto end;
308 }
309 if (dsaparam) {
310 DSA *dsa;
311
312 if (informat == FORMAT_ASN1)
313 dsa = d2i_DSAparams_bio(in, NULL);
314 else /* informat == FORMAT_PEM */
315 dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL);
316
317 if (dsa == NULL) {
318 BIO_printf(bio_err, "unable to load DSA parameters\n");
319 ERR_print_errors(bio_err);
320 goto end;
321 }
322 dh = DSA_dup_DH(dsa);
323 DSA_free(dsa);
324 if (dh == NULL) {
325 ERR_print_errors(bio_err);
326 goto end;
327 }
328 } else
329 {
330 if (informat == FORMAT_ASN1)
331 dh = d2i_DHparams_bio(in, NULL);
332 else /* informat == FORMAT_PEM */
333 dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
334
335 if (dh == NULL) {
336 BIO_printf(bio_err, "unable to load DH parameters\n");
337 ERR_print_errors(bio_err);
338 goto end;
339 }
340 }
341
342 /* dh != NULL */
343 }
344
345 out = BIO_new(BIO_s_file());
346 if (out == NULL) {
347 ERR_print_errors(bio_err);
348 goto end;
349 }
350 if (outfile == NULL) {
351 BIO_set_fp(out, stdout, BIO_NOCLOSE);
352 } else {
353 if (BIO_write_filename(out, outfile) <= 0) {
354 perror(outfile);
355 goto end;
356 }
357 }
358
359
360 if (text) {
361 DHparams_print(out, dh);
362 }
363 if (check) {
364 if (!DH_check(dh, &i)) {
365 ERR_print_errors(bio_err);
366 goto end;
367 }
368 if (i & DH_CHECK_P_NOT_PRIME)
369 printf("p value is not prime\n");
370 if (i & DH_CHECK_P_NOT_SAFE_PRIME)
371 printf("p value is not a safe prime\n");
372 if (i & DH_UNABLE_TO_CHECK_GENERATOR)
373 printf("unable to check the generator value\n");
374 if (i & DH_NOT_SUITABLE_GENERATOR)
375 printf("the g value is not a generator\n");
376 if (i == 0)
377 printf("DH parameters appear to be ok.\n");
378 }
379 if (C) {
380 unsigned char *data;
381 int len, l, bits;
382
383 len = BN_num_bytes(dh->p);
384 bits = BN_num_bits(dh->p);
385 data = malloc(len);
386 if (data == NULL) {
387 perror("malloc");
388 goto end;
389 }
390 printf("#ifndef HEADER_DH_H\n"
391 "#include <openssl/dh.h>\n"
392 "#endif\n");
393 printf("DH *get_dh%d()\n\t{\n", bits);
394
395 l = BN_bn2bin(dh->p, data);
396 printf("\tstatic unsigned char dh%d_p[] = {", bits);
397 for (i = 0; i < l; i++) {
398 if ((i % 12) == 0)
399 printf("\n\t\t");
400 printf("0x%02X, ", data[i]);
401 }
402 printf("\n\t\t};\n");
403
404 l = BN_bn2bin(dh->g, data);
405 printf("\tstatic unsigned char dh%d_g[] = {", bits);
406 for (i = 0; i < l; i++) {
407 if ((i % 12) == 0)
408 printf("\n\t\t");
409 printf("0x%02X, ", data[i]);
410 }
411 printf("\n\t\t};\n");
412
413 printf("\tDH *dh;\n\n");
414 printf("\tif ((dh = DH_new()) == NULL) return(NULL);\n");
415 printf("\tdh->p = BN_bin2bn(dh%d_p, sizeof(dh%d_p), NULL);\n",
416 bits, bits);
417 printf("\tdh->g = BN_bin2bn(dh%d_g, sizeof(dh%d_g), NULL);\n",
418 bits, bits);
419 printf("\tif ((dh->p == NULL) || (dh->g == NULL))\n");
420 printf("\t\t{ DH_free(dh); return(NULL); }\n");
421 if (dh->length)
422 printf("\tdh->length = %ld;\n", dh->length);
423 printf("\treturn(dh);\n\t}\n");
424 free(data);
425 }
426 if (!noout) {
427 if (outformat == FORMAT_ASN1)
428 i = i2d_DHparams_bio(out, dh);
429 else if (outformat == FORMAT_PEM)
430 i = PEM_write_bio_DHparams(out, dh);
431 else {
432 BIO_printf(bio_err, "bad output format specified for outfile\n");
433 goto end;
434 }
435 if (!i) {
436 BIO_printf(bio_err, "unable to write DH parameters\n");
437 ERR_print_errors(bio_err);
438 goto end;
439 }
440 }
441 ret = 0;
442
443end:
444 BIO_free(in);
445 if (out != NULL)
446 BIO_free_all(out);
447 if (dh != NULL)
448 DH_free(dh);
449
450 return (ret);
451}
452
453/* dh_cb is identical to dsa_cb in apps/dsaparam.c */
454static int
455dh_cb(int p, int n, BN_GENCB * cb)
456{
457 char c = '*';
458
459 if (p == 0)
460 c = '.';
461 if (p == 1)
462 c = '+';
463 if (p == 2)
464 c = '*';
465 if (p == 3)
466 c = '\n';
467 BIO_write(cb->arg, &c, 1);
468 (void) BIO_flush(cb->arg);
469 return 1;
470}
471
472#endif
diff --git a/src/usr.bin/openssl/dsa.c b/src/usr.bin/openssl/dsa.c
new file mode 100644
index 0000000000..b8ca7dd2ef
--- /dev/null
+++ b/src/usr.bin/openssl/dsa.c
@@ -0,0 +1,332 @@
1/* $OpenBSD: dsa.c,v 1.1 2014/08/26 17:47:24 jsing 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 <openssl/opensslconf.h> /* for OPENSSL_NO_DSA */
60
61
62#include <stdio.h>
63#include <stdlib.h>
64#include <time.h>
65#include <string.h>
66
67#include "apps.h"
68
69#include <openssl/bio.h>
70#include <openssl/bn.h>
71#include <openssl/dsa.h>
72#include <openssl/err.h>
73#include <openssl/evp.h>
74#include <openssl/pem.h>
75#include <openssl/x509.h>
76
77/* -inform arg - input format - default PEM (one of DER, NET or PEM)
78 * -outform arg - output format - default PEM
79 * -in arg - input file - default stdin
80 * -out arg - output file - default stdout
81 * -des - encrypt output if PEM format with DES in cbc mode
82 * -des3 - encrypt output if PEM format
83 * -idea - encrypt output if PEM format
84 * -aes128 - encrypt output if PEM format
85 * -aes192 - encrypt output if PEM format
86 * -aes256 - encrypt output if PEM format
87 * -camellia128 - encrypt output if PEM format
88 * -camellia192 - encrypt output if PEM format
89 * -camellia256 - encrypt output if PEM format
90 * -seed - encrypt output if PEM format
91 * -text - print a text version
92 * -modulus - print the DSA public key
93 */
94
95int dsa_main(int, char **);
96
97int
98dsa_main(int argc, char **argv)
99{
100 ENGINE *e = NULL;
101 int ret = 1;
102 DSA *dsa = NULL;
103 int i, badops = 0;
104 const EVP_CIPHER *enc = NULL;
105 BIO *in = NULL, *out = NULL;
106 int informat, outformat, text = 0, noout = 0;
107 int pubin = 0, pubout = 0;
108 char *infile, *outfile, *prog;
109#ifndef OPENSSL_NO_ENGINE
110 char *engine;
111#endif
112 char *passargin = NULL, *passargout = NULL;
113 char *passin = NULL, *passout = NULL;
114 int modulus = 0;
115
116 int pvk_encr = 2;
117
118#ifndef OPENSSL_NO_ENGINE
119 engine = NULL;
120#endif
121 infile = NULL;
122 outfile = NULL;
123 informat = FORMAT_PEM;
124 outformat = FORMAT_PEM;
125
126 prog = argv[0];
127 argc--;
128 argv++;
129 while (argc >= 1) {
130 if (strcmp(*argv, "-inform") == 0) {
131 if (--argc < 1)
132 goto bad;
133 informat = str2fmt(*(++argv));
134 } else if (strcmp(*argv, "-outform") == 0) {
135 if (--argc < 1)
136 goto bad;
137 outformat = str2fmt(*(++argv));
138 } else if (strcmp(*argv, "-in") == 0) {
139 if (--argc < 1)
140 goto bad;
141 infile = *(++argv);
142 } else if (strcmp(*argv, "-out") == 0) {
143 if (--argc < 1)
144 goto bad;
145 outfile = *(++argv);
146 } else if (strcmp(*argv, "-passin") == 0) {
147 if (--argc < 1)
148 goto bad;
149 passargin = *(++argv);
150 } else if (strcmp(*argv, "-passout") == 0) {
151 if (--argc < 1)
152 goto bad;
153 passargout = *(++argv);
154 }
155#ifndef OPENSSL_NO_ENGINE
156 else if (strcmp(*argv, "-engine") == 0) {
157 if (--argc < 1)
158 goto bad;
159 engine = *(++argv);
160 }
161#endif
162 else if (strcmp(*argv, "-pvk-strong") == 0)
163 pvk_encr = 2;
164 else if (strcmp(*argv, "-pvk-weak") == 0)
165 pvk_encr = 1;
166 else if (strcmp(*argv, "-pvk-none") == 0)
167 pvk_encr = 0;
168 else if (strcmp(*argv, "-noout") == 0)
169 noout = 1;
170 else if (strcmp(*argv, "-text") == 0)
171 text = 1;
172 else if (strcmp(*argv, "-modulus") == 0)
173 modulus = 1;
174 else if (strcmp(*argv, "-pubin") == 0)
175 pubin = 1;
176 else if (strcmp(*argv, "-pubout") == 0)
177 pubout = 1;
178 else if ((enc = EVP_get_cipherbyname(&(argv[0][1]))) == NULL) {
179 BIO_printf(bio_err, "unknown option %s\n", *argv);
180 badops = 1;
181 break;
182 }
183 argc--;
184 argv++;
185 }
186
187 if (badops) {
188bad:
189 BIO_printf(bio_err, "%s [options] <infile >outfile\n", prog);
190 BIO_printf(bio_err, "where options are\n");
191 BIO_printf(bio_err, " -inform arg input format - DER or PEM\n");
192 BIO_printf(bio_err, " -outform arg output format - DER or PEM\n");
193 BIO_printf(bio_err, " -in arg input file\n");
194 BIO_printf(bio_err, " -passin arg input file pass phrase source\n");
195 BIO_printf(bio_err, " -out arg output file\n");
196 BIO_printf(bio_err, " -passout arg output file pass phrase source\n");
197#ifndef OPENSSL_NO_ENGINE
198 BIO_printf(bio_err, " -engine e use engine e, possibly a hardware device.\n");
199#endif
200 BIO_printf(bio_err, " -des encrypt PEM output with cbc des\n");
201 BIO_printf(bio_err, " -des3 encrypt PEM output with ede cbc des using 168 bit key\n");
202#ifndef OPENSSL_NO_IDEA
203 BIO_printf(bio_err, " -idea encrypt PEM output with cbc idea\n");
204#endif
205#ifndef OPENSSL_NO_AES
206 BIO_printf(bio_err, " -aes128, -aes192, -aes256\n");
207 BIO_printf(bio_err, " encrypt PEM output with cbc aes\n");
208#endif
209#ifndef OPENSSL_NO_CAMELLIA
210 BIO_printf(bio_err, " -camellia128, -camellia192, -camellia256\n");
211 BIO_printf(bio_err, " encrypt PEM output with cbc camellia\n");
212#endif
213 BIO_printf(bio_err, " -text print the key in text\n");
214 BIO_printf(bio_err, " -noout don't print key out\n");
215 BIO_printf(bio_err, " -modulus print the DSA public value\n");
216 goto end;
217 }
218 ERR_load_crypto_strings();
219
220#ifndef OPENSSL_NO_ENGINE
221 e = setup_engine(bio_err, engine, 0);
222#endif
223
224 if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
225 BIO_printf(bio_err, "Error getting passwords\n");
226 goto end;
227 }
228 in = BIO_new(BIO_s_file());
229 out = BIO_new(BIO_s_file());
230 if ((in == NULL) || (out == NULL)) {
231 ERR_print_errors(bio_err);
232 goto end;
233 }
234 if (infile == NULL)
235 BIO_set_fp(in, stdin, BIO_NOCLOSE);
236 else {
237 if (BIO_read_filename(in, infile) <= 0) {
238 perror(infile);
239 goto end;
240 }
241 }
242
243 BIO_printf(bio_err, "read DSA key\n");
244
245 {
246 EVP_PKEY *pkey;
247
248 if (pubin)
249 pkey = load_pubkey(bio_err, infile, informat, 1,
250 passin, e, "Public Key");
251 else
252 pkey = load_key(bio_err, infile, informat, 1,
253 passin, e, "Private Key");
254
255 if (pkey) {
256 dsa = EVP_PKEY_get1_DSA(pkey);
257 EVP_PKEY_free(pkey);
258 }
259 }
260 if (dsa == NULL) {
261 BIO_printf(bio_err, "unable to load Key\n");
262 ERR_print_errors(bio_err);
263 goto end;
264 }
265 if (outfile == NULL) {
266 BIO_set_fp(out, stdout, BIO_NOCLOSE);
267 } else {
268 if (BIO_write_filename(out, outfile) <= 0) {
269 perror(outfile);
270 goto end;
271 }
272 }
273
274 if (text) {
275 if (!DSA_print(out, dsa, 0)) {
276 perror(outfile);
277 ERR_print_errors(bio_err);
278 goto end;
279 }
280 }
281 if (modulus) {
282 fprintf(stdout, "Public Key=");
283 BN_print(out, dsa->pub_key);
284 fprintf(stdout, "\n");
285 }
286 if (noout)
287 goto end;
288 BIO_printf(bio_err, "writing DSA key\n");
289 if (outformat == FORMAT_ASN1) {
290 if (pubin || pubout)
291 i = i2d_DSA_PUBKEY_bio(out, dsa);
292 else
293 i = i2d_DSAPrivateKey_bio(out, dsa);
294 } else if (outformat == FORMAT_PEM) {
295 if (pubin || pubout)
296 i = PEM_write_bio_DSA_PUBKEY(out, dsa);
297 else
298 i = PEM_write_bio_DSAPrivateKey(out, dsa, enc,
299 NULL, 0, NULL, passout);
300#if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_RC4)
301 } else if (outformat == FORMAT_MSBLOB || outformat == FORMAT_PVK) {
302 EVP_PKEY *pk;
303 pk = EVP_PKEY_new();
304 EVP_PKEY_set1_DSA(pk, dsa);
305 if (outformat == FORMAT_PVK)
306 i = i2b_PVK_bio(out, pk, pvk_encr, 0, passout);
307 else if (pubin || pubout)
308 i = i2b_PublicKey_bio(out, pk);
309 else
310 i = i2b_PrivateKey_bio(out, pk);
311 EVP_PKEY_free(pk);
312#endif
313 } else {
314 BIO_printf(bio_err, "bad output format specified for outfile\n");
315 goto end;
316 }
317 if (i <= 0) {
318 BIO_printf(bio_err, "unable to write private key\n");
319 ERR_print_errors(bio_err);
320 } else
321 ret = 0;
322end:
323 BIO_free(in);
324 if (out != NULL)
325 BIO_free_all(out);
326 if (dsa != NULL)
327 DSA_free(dsa);
328 free(passin);
329 free(passout);
330
331 return (ret);
332}
diff --git a/src/usr.bin/openssl/dsaparam.c b/src/usr.bin/openssl/dsaparam.c
new file mode 100644
index 0000000000..5c17a2c9ac
--- /dev/null
+++ b/src/usr.bin/openssl/dsaparam.c
@@ -0,0 +1,414 @@
1/* $OpenBSD: dsaparam.c,v 1.1 2014/08/26 17:47:24 jsing 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 <openssl/opensslconf.h> /* for OPENSSL_NO_DSA */
60
61/* Until the key-gen callbacks are modified to use newer prototypes, we allow
62 * deprecated functions for openssl-internal code */
63#ifdef OPENSSL_NO_DEPRECATED
64#undef OPENSSL_NO_DEPRECATED
65#endif
66
67
68#include <stdio.h>
69#include <stdlib.h>
70#include <string.h>
71#include <time.h>
72
73#include "apps.h"
74
75#include <openssl/bio.h>
76#include <openssl/bn.h>
77#include <openssl/err.h>
78#include <openssl/dsa.h>
79#include <openssl/pem.h>
80#include <openssl/x509.h>
81
82/* -inform arg - input format - default PEM (DER or PEM)
83 * -outform arg - output format - default PEM
84 * -in arg - input file - default stdin
85 * -out arg - output file - default stdout
86 * -noout
87 * -text
88 * -C
89 * -noout
90 * -genkey
91 * #ifdef GENCB_TEST
92 * -timebomb n - interrupt keygen after <n> seconds
93 * #endif
94 */
95
96#ifdef GENCB_TEST
97
98static int stop_keygen_flag = 0;
99
100static void
101timebomb_sigalarm(int foo)
102{
103 stop_keygen_flag = 1;
104}
105
106#endif
107
108static int dsa_cb(int p, int n, BN_GENCB * cb);
109
110int dsaparam_main(int, char **);
111
112int
113dsaparam_main(int argc, char **argv)
114{
115 DSA *dsa = NULL;
116 int i, badops = 0, text = 0;
117 BIO *in = NULL, *out = NULL;
118 int informat, outformat, noout = 0, C = 0, ret = 1;
119 char *infile, *outfile, *prog;
120 int numbits = -1, num, genkey = 0;
121#ifndef OPENSSL_NO_ENGINE
122 char *engine = NULL;
123#endif
124#ifdef GENCB_TEST
125 const char *errstr = NULL;
126 int timebomb = 0;
127#endif
128
129 infile = NULL;
130 outfile = NULL;
131 informat = FORMAT_PEM;
132 outformat = FORMAT_PEM;
133
134 prog = argv[0];
135 argc--;
136 argv++;
137 while (argc >= 1) {
138 if (strcmp(*argv, "-inform") == 0) {
139 if (--argc < 1)
140 goto bad;
141 informat = str2fmt(*(++argv));
142 } else if (strcmp(*argv, "-outform") == 0) {
143 if (--argc < 1)
144 goto bad;
145 outformat = str2fmt(*(++argv));
146 } else if (strcmp(*argv, "-in") == 0) {
147 if (--argc < 1)
148 goto bad;
149 infile = *(++argv);
150 } else if (strcmp(*argv, "-out") == 0) {
151 if (--argc < 1)
152 goto bad;
153 outfile = *(++argv);
154 }
155#ifndef OPENSSL_NO_ENGINE
156 else if (strcmp(*argv, "-engine") == 0) {
157 if (--argc < 1)
158 goto bad;
159 engine = *(++argv);
160 }
161#endif
162#ifdef GENCB_TEST
163 else if (strcmp(*argv, "-timebomb") == 0) {
164 if (--argc < 1)
165 goto bad;
166 timebomb = strtonum(*(++argv), 0, INT_MAX, &errstr);
167 if (errstr)
168 goto bad;
169 }
170#endif
171 else if (strcmp(*argv, "-text") == 0)
172 text = 1;
173 else if (strcmp(*argv, "-C") == 0)
174 C = 1;
175 else if (strcmp(*argv, "-genkey") == 0) {
176 genkey = 1;
177 } else if (strcmp(*argv, "-noout") == 0)
178 noout = 1;
179 else if (sscanf(*argv, "%d", &num) == 1) {
180 /* generate a key */
181 numbits = num;
182 } else {
183 BIO_printf(bio_err, "unknown option %s\n", *argv);
184 badops = 1;
185 break;
186 }
187 argc--;
188 argv++;
189 }
190
191 if (badops) {
192bad:
193 BIO_printf(bio_err, "%s [options] [bits] <infile >outfile\n", prog);
194 BIO_printf(bio_err, "where options are\n");
195 BIO_printf(bio_err, " -inform arg input format - DER or PEM\n");
196 BIO_printf(bio_err, " -outform arg output format - DER or PEM\n");
197 BIO_printf(bio_err, " -in arg input file\n");
198 BIO_printf(bio_err, " -out arg output file\n");
199 BIO_printf(bio_err, " -text print as text\n");
200 BIO_printf(bio_err, " -C Output C code\n");
201 BIO_printf(bio_err, " -noout no output\n");
202 BIO_printf(bio_err, " -genkey generate a DSA key\n");
203#ifndef OPENSSL_NO_ENGINE
204 BIO_printf(bio_err, " -engine e use engine e, possibly a hardware device.\n");
205#endif
206#ifdef GENCB_TEST
207 BIO_printf(bio_err, " -timebomb n interrupt keygen after <n> seconds\n");
208#endif
209 BIO_printf(bio_err, " number number of bits to use for generating private key\n");
210 goto end;
211 }
212 ERR_load_crypto_strings();
213
214 in = BIO_new(BIO_s_file());
215 out = BIO_new(BIO_s_file());
216 if ((in == NULL) || (out == NULL)) {
217 ERR_print_errors(bio_err);
218 goto end;
219 }
220 if (infile == NULL)
221 BIO_set_fp(in, stdin, BIO_NOCLOSE);
222 else {
223 if (BIO_read_filename(in, infile) <= 0) {
224 perror(infile);
225 goto end;
226 }
227 }
228 if (outfile == NULL) {
229 BIO_set_fp(out, stdout, BIO_NOCLOSE);
230 } else {
231 if (BIO_write_filename(out, outfile) <= 0) {
232 perror(outfile);
233 goto end;
234 }
235 }
236
237#ifndef OPENSSL_NO_ENGINE
238 setup_engine(bio_err, engine, 0);
239#endif
240
241 if (numbits > 0) {
242 BN_GENCB cb;
243 BN_GENCB_set(&cb, dsa_cb, bio_err);
244 dsa = DSA_new();
245 if (!dsa) {
246 BIO_printf(bio_err, "Error allocating DSA object\n");
247 goto end;
248 }
249 BIO_printf(bio_err, "Generating DSA parameters, %d bit long prime\n", num);
250 BIO_printf(bio_err, "This could take some time\n");
251#ifdef GENCB_TEST
252 if (timebomb > 0) {
253 struct sigaction act;
254 act.sa_handler = timebomb_sigalarm;
255 act.sa_flags = 0;
256 BIO_printf(bio_err, "(though I'll stop it if not done within %d secs)\n",
257 timebomb);
258 if (sigaction(SIGALRM, &act, NULL) != 0) {
259 BIO_printf(bio_err, "Error, couldn't set SIGALRM handler\n");
260 goto end;
261 }
262 alarm(timebomb);
263 }
264#endif
265 if (!DSA_generate_parameters_ex(dsa, num, NULL, 0, NULL, NULL, &cb)) {
266#ifdef GENCB_TEST
267 if (stop_keygen_flag) {
268 BIO_printf(bio_err, "DSA key generation time-stopped\n");
269 /* This is an asked-for behaviour! */
270 ret = 0;
271 goto end;
272 }
273#endif
274 ERR_print_errors(bio_err);
275 BIO_printf(bio_err, "Error, DSA key generation failed\n");
276 goto end;
277 }
278 } else if (informat == FORMAT_ASN1)
279 dsa = d2i_DSAparams_bio(in, NULL);
280 else if (informat == FORMAT_PEM)
281 dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL);
282 else {
283 BIO_printf(bio_err, "bad input format specified\n");
284 goto end;
285 }
286 if (dsa == NULL) {
287 BIO_printf(bio_err, "unable to load DSA parameters\n");
288 ERR_print_errors(bio_err);
289 goto end;
290 }
291 if (text) {
292 DSAparams_print(out, dsa);
293 }
294 if (C) {
295 unsigned char *data;
296 int l, len, bits_p;
297
298 len = BN_num_bytes(dsa->p);
299 bits_p = BN_num_bits(dsa->p);
300 data = malloc(len + 20);
301 if (data == NULL) {
302 perror("malloc");
303 goto end;
304 }
305 l = BN_bn2bin(dsa->p, data);
306 printf("static unsigned char dsa%d_p[] = {", bits_p);
307 for (i = 0; i < l; i++) {
308 if ((i % 12) == 0)
309 printf("\n\t");
310 printf("0x%02X, ", data[i]);
311 }
312 printf("\n\t};\n");
313
314 l = BN_bn2bin(dsa->q, data);
315 printf("static unsigned char dsa%d_q[] = {", bits_p);
316 for (i = 0; i < l; i++) {
317 if ((i % 12) == 0)
318 printf("\n\t");
319 printf("0x%02X, ", data[i]);
320 }
321 printf("\n\t};\n");
322
323 l = BN_bn2bin(dsa->g, data);
324 printf("static unsigned char dsa%d_g[] = {", bits_p);
325 for (i = 0; i < l; i++) {
326 if ((i % 12) == 0)
327 printf("\n\t");
328 printf("0x%02X, ", data[i]);
329 }
330 free(data);
331 printf("\n\t};\n\n");
332
333 printf("DSA *get_dsa%d()\n\t{\n", bits_p);
334 printf("\tDSA *dsa;\n\n");
335 printf("\tif ((dsa = DSA_new()) == NULL) return(NULL);\n");
336 printf("\tdsa->p = BN_bin2bn(dsa%d_p, sizeof(dsa%d_p), NULL);\n",
337 bits_p, bits_p);
338 printf("\tdsa->q = BN_bin2bn(dsa%d_q, sizeof(dsa%d_q), NULL);\n",
339 bits_p, bits_p);
340 printf("\tdsa->g = BN_bin2bn(dsa%d_g, sizeof(dsa%d_g), NULL);\n",
341 bits_p, bits_p);
342 printf("\tif ((dsa->p == NULL) || (dsa->q == NULL) || (dsa->g == NULL))\n");
343 printf("\t\t{ DSA_free(dsa); return(NULL); }\n");
344 printf("\treturn(dsa);\n\t}\n");
345 }
346 if (!noout) {
347 if (outformat == FORMAT_ASN1)
348 i = i2d_DSAparams_bio(out, dsa);
349 else if (outformat == FORMAT_PEM)
350 i = PEM_write_bio_DSAparams(out, dsa);
351 else {
352 BIO_printf(bio_err, "bad output format specified for outfile\n");
353 goto end;
354 }
355 if (!i) {
356 BIO_printf(bio_err, "unable to write DSA parameters\n");
357 ERR_print_errors(bio_err);
358 goto end;
359 }
360 }
361 if (genkey) {
362 DSA *dsakey;
363
364 if ((dsakey = DSAparams_dup(dsa)) == NULL)
365 goto end;
366 if (!DSA_generate_key(dsakey)) {
367 ERR_print_errors(bio_err);
368 DSA_free(dsakey);
369 goto end;
370 }
371 if (outformat == FORMAT_ASN1)
372 i = i2d_DSAPrivateKey_bio(out, dsakey);
373 else if (outformat == FORMAT_PEM)
374 i = PEM_write_bio_DSAPrivateKey(out, dsakey, NULL, NULL, 0, NULL, NULL);
375 else {
376 BIO_printf(bio_err, "bad output format specified for outfile\n");
377 DSA_free(dsakey);
378 goto end;
379 }
380 DSA_free(dsakey);
381 }
382 ret = 0;
383
384end:
385 BIO_free(in);
386 if (out != NULL)
387 BIO_free_all(out);
388 if (dsa != NULL)
389 DSA_free(dsa);
390
391 return (ret);
392}
393
394static int
395dsa_cb(int p, int n, BN_GENCB * cb)
396{
397 char c = '*';
398
399 if (p == 0)
400 c = '.';
401 if (p == 1)
402 c = '+';
403 if (p == 2)
404 c = '*';
405 if (p == 3)
406 c = '\n';
407 BIO_write(cb->arg, &c, 1);
408 (void) BIO_flush(cb->arg);
409#ifdef GENCB_TEST
410 if (stop_keygen_flag)
411 return 0;
412#endif
413 return 1;
414}
diff --git a/src/usr.bin/openssl/ec.c b/src/usr.bin/openssl/ec.c
new file mode 100644
index 0000000000..f1bdf55e33
--- /dev/null
+++ b/src/usr.bin/openssl/ec.c
@@ -0,0 +1,341 @@
1/* $OpenBSD: ec.c,v 1.1 2014/08/26 17:47:24 jsing Exp $ */
2/*
3 * Written by Nils Larsch for the OpenSSL project.
4 */
5/* ====================================================================
6 * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
19 *
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
24 *
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * openssl-core@openssl.org.
29 *
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
33 *
34 * 6. Redistributions of any form whatsoever must retain the following
35 * acknowledgment:
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
52 *
53 * This product includes cryptographic software written by Eric Young
54 * (eay@cryptsoft.com). This product includes software written by Tim
55 * Hudson (tjh@cryptsoft.com).
56 *
57 */
58
59#include <openssl/opensslconf.h>
60
61#ifndef OPENSSL_NO_EC
62
63#include <stdio.h>
64#include <stdlib.h>
65#include <string.h>
66
67#include "apps.h"
68
69#include <openssl/bio.h>
70#include <openssl/err.h>
71#include <openssl/evp.h>
72#include <openssl/pem.h>
73
74/* -inform arg - input format - default PEM (one of DER, NET or PEM)
75 * -outform arg - output format - default PEM
76 * -in arg - input file - default stdin
77 * -out arg - output file - default stdout
78 * -des - encrypt output if PEM format with DES in cbc mode
79 * -text - print a text version
80 * -param_out - print the elliptic curve parameters
81 * -conv_form arg - specifies the point encoding form
82 * -param_enc arg - specifies the parameter encoding
83 */
84
85int ec_main(int, char **);
86
87int
88ec_main(int argc, char **argv)
89{
90 int ret = 1;
91 EC_KEY *eckey = NULL;
92 const EC_GROUP *group;
93 int i, badops = 0;
94 const EVP_CIPHER *enc = NULL;
95 BIO *in = NULL, *out = NULL;
96 int informat, outformat, text = 0, noout = 0;
97 int pubin = 0, pubout = 0, param_out = 0;
98 char *infile, *outfile, *prog, *engine;
99 char *passargin = NULL, *passargout = NULL;
100 char *passin = NULL, *passout = NULL;
101 point_conversion_form_t form = POINT_CONVERSION_UNCOMPRESSED;
102 int new_form = 0;
103 int asn1_flag = OPENSSL_EC_NAMED_CURVE;
104 int new_asn1_flag = 0;
105
106 engine = NULL;
107 infile = NULL;
108 outfile = NULL;
109 informat = FORMAT_PEM;
110 outformat = FORMAT_PEM;
111
112 prog = argv[0];
113 argc--;
114 argv++;
115 while (argc >= 1) {
116 if (strcmp(*argv, "-inform") == 0) {
117 if (--argc < 1)
118 goto bad;
119 informat = str2fmt(*(++argv));
120 } else if (strcmp(*argv, "-outform") == 0) {
121 if (--argc < 1)
122 goto bad;
123 outformat = str2fmt(*(++argv));
124 } else if (strcmp(*argv, "-in") == 0) {
125 if (--argc < 1)
126 goto bad;
127 infile = *(++argv);
128 } else if (strcmp(*argv, "-out") == 0) {
129 if (--argc < 1)
130 goto bad;
131 outfile = *(++argv);
132 } else if (strcmp(*argv, "-passin") == 0) {
133 if (--argc < 1)
134 goto bad;
135 passargin = *(++argv);
136 } else if (strcmp(*argv, "-passout") == 0) {
137 if (--argc < 1)
138 goto bad;
139 passargout = *(++argv);
140 } else if (strcmp(*argv, "-engine") == 0) {
141 if (--argc < 1)
142 goto bad;
143 engine = *(++argv);
144 } else if (strcmp(*argv, "-noout") == 0)
145 noout = 1;
146 else if (strcmp(*argv, "-text") == 0)
147 text = 1;
148 else if (strcmp(*argv, "-conv_form") == 0) {
149 if (--argc < 1)
150 goto bad;
151 ++argv;
152 new_form = 1;
153 if (strcmp(*argv, "compressed") == 0)
154 form = POINT_CONVERSION_COMPRESSED;
155 else if (strcmp(*argv, "uncompressed") == 0)
156 form = POINT_CONVERSION_UNCOMPRESSED;
157 else if (strcmp(*argv, "hybrid") == 0)
158 form = POINT_CONVERSION_HYBRID;
159 else
160 goto bad;
161 } else if (strcmp(*argv, "-param_enc") == 0) {
162 if (--argc < 1)
163 goto bad;
164 ++argv;
165 new_asn1_flag = 1;
166 if (strcmp(*argv, "named_curve") == 0)
167 asn1_flag = OPENSSL_EC_NAMED_CURVE;
168 else if (strcmp(*argv, "explicit") == 0)
169 asn1_flag = 0;
170 else
171 goto bad;
172 } else if (strcmp(*argv, "-param_out") == 0)
173 param_out = 1;
174 else if (strcmp(*argv, "-pubin") == 0)
175 pubin = 1;
176 else if (strcmp(*argv, "-pubout") == 0)
177 pubout = 1;
178 else if ((enc = EVP_get_cipherbyname(&(argv[0][1]))) == NULL) {
179 BIO_printf(bio_err, "unknown option %s\n", *argv);
180 badops = 1;
181 break;
182 }
183 argc--;
184 argv++;
185 }
186
187 if (badops) {
188bad:
189 BIO_printf(bio_err, "%s [options] <infile >outfile\n", prog);
190 BIO_printf(bio_err, "where options are\n");
191 BIO_printf(bio_err, " -inform arg input format - "
192 "DER or PEM\n");
193 BIO_printf(bio_err, " -outform arg output format - "
194 "DER or PEM\n");
195 BIO_printf(bio_err, " -in arg input file\n");
196 BIO_printf(bio_err, " -passin arg input file pass "
197 "phrase source\n");
198 BIO_printf(bio_err, " -out arg output file\n");
199 BIO_printf(bio_err, " -passout arg output file pass "
200 "phrase source\n");
201 BIO_printf(bio_err, " -engine e use engine e, "
202 "possibly a hardware device.\n");
203 BIO_printf(bio_err, " -des encrypt PEM output, "
204 "instead of 'des' every other \n"
205 " cipher "
206 "supported by OpenSSL can be used\n");
207 BIO_printf(bio_err, " -text print the key\n");
208 BIO_printf(bio_err, " -noout don't print key out\n");
209 BIO_printf(bio_err, " -param_out print the elliptic "
210 "curve parameters\n");
211 BIO_printf(bio_err, " -conv_form arg specifies the "
212 "point conversion form \n");
213 BIO_printf(bio_err, " possible values:"
214 " compressed\n");
215 BIO_printf(bio_err, " "
216 " uncompressed (default)\n");
217 BIO_printf(bio_err, " "
218 " hybrid\n");
219 BIO_printf(bio_err, " -param_enc arg specifies the way"
220 " the ec parameters are encoded\n");
221 BIO_printf(bio_err, " in the asn1 der "
222 "encoding\n");
223 BIO_printf(bio_err, " possible values:"
224 " named_curve (default)\n");
225 BIO_printf(bio_err, " "
226 "explicit\n");
227 goto end;
228 }
229 ERR_load_crypto_strings();
230
231#ifndef OPENSSL_NO_ENGINE
232 setup_engine(bio_err, engine, 0);
233#endif
234
235 if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
236 BIO_printf(bio_err, "Error getting passwords\n");
237 goto end;
238 }
239 in = BIO_new(BIO_s_file());
240 out = BIO_new(BIO_s_file());
241 if ((in == NULL) || (out == NULL)) {
242 ERR_print_errors(bio_err);
243 goto end;
244 }
245 if (infile == NULL)
246 BIO_set_fp(in, stdin, BIO_NOCLOSE);
247 else {
248 if (BIO_read_filename(in, infile) <= 0) {
249 perror(infile);
250 goto end;
251 }
252 }
253
254 BIO_printf(bio_err, "read EC key\n");
255 if (informat == FORMAT_ASN1) {
256 if (pubin)
257 eckey = d2i_EC_PUBKEY_bio(in, NULL);
258 else
259 eckey = d2i_ECPrivateKey_bio(in, NULL);
260 } else if (informat == FORMAT_PEM) {
261 if (pubin)
262 eckey = PEM_read_bio_EC_PUBKEY(in, NULL, NULL,
263 NULL);
264 else
265 eckey = PEM_read_bio_ECPrivateKey(in, NULL, NULL,
266 passin);
267 } else {
268 BIO_printf(bio_err, "bad input format specified for key\n");
269 goto end;
270 }
271 if (eckey == NULL) {
272 BIO_printf(bio_err, "unable to load Key\n");
273 ERR_print_errors(bio_err);
274 goto end;
275 }
276 if (outfile == NULL) {
277 BIO_set_fp(out, stdout, BIO_NOCLOSE);
278 } else {
279 if (BIO_write_filename(out, outfile) <= 0) {
280 perror(outfile);
281 goto end;
282 }
283 }
284
285 group = EC_KEY_get0_group(eckey);
286
287 if (new_form)
288 EC_KEY_set_conv_form(eckey, form);
289
290 if (new_asn1_flag)
291 EC_KEY_set_asn1_flag(eckey, asn1_flag);
292
293 if (text)
294 if (!EC_KEY_print(out, eckey, 0)) {
295 perror(outfile);
296 ERR_print_errors(bio_err);
297 goto end;
298 }
299 if (noout) {
300 ret = 0;
301 goto end;
302 }
303 BIO_printf(bio_err, "writing EC key\n");
304 if (outformat == FORMAT_ASN1) {
305 if (param_out)
306 i = i2d_ECPKParameters_bio(out, group);
307 else if (pubin || pubout)
308 i = i2d_EC_PUBKEY_bio(out, eckey);
309 else
310 i = i2d_ECPrivateKey_bio(out, eckey);
311 } else if (outformat == FORMAT_PEM) {
312 if (param_out)
313 i = PEM_write_bio_ECPKParameters(out, group);
314 else if (pubin || pubout)
315 i = PEM_write_bio_EC_PUBKEY(out, eckey);
316 else
317 i = PEM_write_bio_ECPrivateKey(out, eckey, enc,
318 NULL, 0, NULL, passout);
319 } else {
320 BIO_printf(bio_err, "bad output format specified for "
321 "outfile\n");
322 goto end;
323 }
324
325 if (!i) {
326 BIO_printf(bio_err, "unable to write private key\n");
327 ERR_print_errors(bio_err);
328 } else
329 ret = 0;
330end:
331 BIO_free(in);
332 if (out)
333 BIO_free_all(out);
334 if (eckey)
335 EC_KEY_free(eckey);
336 free(passin);
337 free(passout);
338
339 return (ret);
340}
341#endif
diff --git a/src/usr.bin/openssl/ecparam.c b/src/usr.bin/openssl/ecparam.c
new file mode 100644
index 0000000000..9623cb96ce
--- /dev/null
+++ b/src/usr.bin/openssl/ecparam.c
@@ -0,0 +1,613 @@
1/* $OpenBSD: ecparam.c,v 1.1 2014/08/26 17:47:24 jsing Exp $ */
2/*
3 * Written by Nils Larsch for the OpenSSL project.
4 */
5/* ====================================================================
6 * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
19 *
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
24 *
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * openssl-core@openssl.org.
29 *
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
33 *
34 * 6. Redistributions of any form whatsoever must retain the following
35 * acknowledgment:
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
52 *
53 * This product includes cryptographic software written by Eric Young
54 * (eay@cryptsoft.com). This product includes software written by Tim
55 * Hudson (tjh@cryptsoft.com).
56 *
57 */
58/* ====================================================================
59 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
60 *
61 * Portions of the attached software ("Contribution") are developed by
62 * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
63 *
64 * The Contribution is licensed pursuant to the OpenSSL open source
65 * license provided above.
66 *
67 * The elliptic curve binary polynomial software is originally written by
68 * Sheueling Chang Shantz and Douglas Stebila of Sun Microsystems Laboratories.
69 *
70 */
71
72#include <openssl/opensslconf.h>
73
74#ifndef OPENSSL_NO_EC
75
76#include <stdio.h>
77#include <stdlib.h>
78#include <string.h>
79#include <time.h>
80
81#include "apps.h"
82
83#include <openssl/bio.h>
84#include <openssl/bn.h>
85#include <openssl/ec.h>
86#include <openssl/err.h>
87#include <openssl/pem.h>
88#include <openssl/x509.h>
89
90/* -inform arg - input format - default PEM (DER or PEM)
91 * -outform arg - output format - default PEM
92 * -in arg - input file - default stdin
93 * -out arg - output file - default stdout
94 * -noout - do not print the ec parameter
95 * -text - print the ec parameters in text form
96 * -check - validate the ec parameters
97 * -C - print a 'C' function creating the parameters
98 * -name arg - use the ec parameters with 'short name' name
99 * -list_curves - prints a list of all currently available curve 'short names'
100 * -conv_form arg - specifies the point conversion form
101 * - possible values: compressed
102 * uncompressed (default)
103 * hybrid
104 * -param_enc arg - specifies the way the ec parameters are encoded
105 * in the asn1 der encoding
106 * possible values: named_curve (default)
107 * explicit
108 * -no_seed - if 'explicit' parameters are chosen do not use the seed
109 * -genkey - generate ec key
110 * -engine e - use engine e, possibly a hardware device
111 */
112
113
114static int ecparam_print_var(BIO *, BIGNUM *, const char *, int, unsigned char *);
115
116int ecparam_main(int, char **);
117
118int
119ecparam_main(int argc, char **argv)
120{
121 EC_GROUP *group = NULL;
122 point_conversion_form_t form = POINT_CONVERSION_UNCOMPRESSED;
123 int new_form = 0;
124 int asn1_flag = OPENSSL_EC_NAMED_CURVE;
125 int new_asn1_flag = 0;
126 char *curve_name = NULL;
127 int list_curves = 0, no_seed = 0, check = 0, badops = 0, text = 0,
128 i, genkey = 0;
129 char *infile = NULL, *outfile = NULL, *prog;
130 BIO *in = NULL, *out = NULL;
131 int informat, outformat, noout = 0, C = 0, ret = 1;
132 char *engine = NULL;
133
134 BIGNUM *ec_p = NULL, *ec_a = NULL, *ec_b = NULL, *ec_gen = NULL,
135 *ec_order = NULL, *ec_cofactor = NULL;
136 unsigned char *buffer = NULL;
137
138 informat = FORMAT_PEM;
139 outformat = FORMAT_PEM;
140
141 prog = argv[0];
142 argc--;
143 argv++;
144 while (argc >= 1) {
145 if (strcmp(*argv, "-inform") == 0) {
146 if (--argc < 1)
147 goto bad;
148 informat = str2fmt(*(++argv));
149 } else if (strcmp(*argv, "-outform") == 0) {
150 if (--argc < 1)
151 goto bad;
152 outformat = str2fmt(*(++argv));
153 } else if (strcmp(*argv, "-in") == 0) {
154 if (--argc < 1)
155 goto bad;
156 infile = *(++argv);
157 } else if (strcmp(*argv, "-out") == 0) {
158 if (--argc < 1)
159 goto bad;
160 outfile = *(++argv);
161 } else if (strcmp(*argv, "-text") == 0)
162 text = 1;
163 else if (strcmp(*argv, "-C") == 0)
164 C = 1;
165 else if (strcmp(*argv, "-check") == 0)
166 check = 1;
167 else if (strcmp(*argv, "-name") == 0) {
168 if (--argc < 1)
169 goto bad;
170 curve_name = *(++argv);
171 } else if (strcmp(*argv, "-list_curves") == 0)
172 list_curves = 1;
173 else if (strcmp(*argv, "-conv_form") == 0) {
174 if (--argc < 1)
175 goto bad;
176 ++argv;
177 new_form = 1;
178 if (strcmp(*argv, "compressed") == 0)
179 form = POINT_CONVERSION_COMPRESSED;
180 else if (strcmp(*argv, "uncompressed") == 0)
181 form = POINT_CONVERSION_UNCOMPRESSED;
182 else if (strcmp(*argv, "hybrid") == 0)
183 form = POINT_CONVERSION_HYBRID;
184 else
185 goto bad;
186 } else if (strcmp(*argv, "-param_enc") == 0) {
187 if (--argc < 1)
188 goto bad;
189 ++argv;
190 new_asn1_flag = 1;
191 if (strcmp(*argv, "named_curve") == 0)
192 asn1_flag = OPENSSL_EC_NAMED_CURVE;
193 else if (strcmp(*argv, "explicit") == 0)
194 asn1_flag = 0;
195 else
196 goto bad;
197 } else if (strcmp(*argv, "-no_seed") == 0)
198 no_seed = 1;
199 else if (strcmp(*argv, "-noout") == 0)
200 noout = 1;
201 else if (strcmp(*argv, "-genkey") == 0) {
202 genkey = 1;
203 } else if (strcmp(*argv, "-engine") == 0) {
204 if (--argc < 1)
205 goto bad;
206 engine = *(++argv);
207 } else {
208 BIO_printf(bio_err, "unknown option %s\n", *argv);
209 badops = 1;
210 break;
211 }
212 argc--;
213 argv++;
214 }
215
216 if (badops) {
217bad:
218 BIO_printf(bio_err, "%s [options] <infile >outfile\n", prog);
219 BIO_printf(bio_err, "where options are\n");
220 BIO_printf(bio_err, " -inform arg input format - "
221 "default PEM (DER or PEM)\n");
222 BIO_printf(bio_err, " -outform arg output format - "
223 "default PEM\n");
224 BIO_printf(bio_err, " -in arg input file - "
225 "default stdin\n");
226 BIO_printf(bio_err, " -out arg output file - "
227 "default stdout\n");
228 BIO_printf(bio_err, " -noout do not print the "
229 "ec parameter\n");
230 BIO_printf(bio_err, " -text print the ec "
231 "parameters in text form\n");
232 BIO_printf(bio_err, " -check validate the ec "
233 "parameters\n");
234 BIO_printf(bio_err, " -C print a 'C' "
235 "function creating the parameters\n");
236 BIO_printf(bio_err, " -name arg use the "
237 "ec parameters with 'short name' name\n");
238 BIO_printf(bio_err, " -list_curves prints a list of "
239 "all currently available curve 'short names'\n");
240 BIO_printf(bio_err, " -conv_form arg specifies the "
241 "point conversion form \n");
242 BIO_printf(bio_err, " possible values:"
243 " compressed\n");
244 BIO_printf(bio_err, " "
245 " uncompressed (default)\n");
246 BIO_printf(bio_err, " "
247 " hybrid\n");
248 BIO_printf(bio_err, " -param_enc arg specifies the way"
249 " the ec parameters are encoded\n");
250 BIO_printf(bio_err, " in the asn1 der "
251 "encoding\n");
252 BIO_printf(bio_err, " possible values:"
253 " named_curve (default)\n");
254 BIO_printf(bio_err, " "
255 " explicit\n");
256 BIO_printf(bio_err, " -no_seed if 'explicit'"
257 " parameters are chosen do not"
258 " use the seed\n");
259 BIO_printf(bio_err, " -genkey generate ec"
260 " key\n");
261 BIO_printf(bio_err, " -engine e use engine e, "
262 "possibly a hardware device\n");
263 goto end;
264 }
265 ERR_load_crypto_strings();
266
267 in = BIO_new(BIO_s_file());
268 out = BIO_new(BIO_s_file());
269 if ((in == NULL) || (out == NULL)) {
270 ERR_print_errors(bio_err);
271 goto end;
272 }
273 if (infile == NULL)
274 BIO_set_fp(in, stdin, BIO_NOCLOSE);
275 else {
276 if (BIO_read_filename(in, infile) <= 0) {
277 perror(infile);
278 goto end;
279 }
280 }
281 if (outfile == NULL) {
282 BIO_set_fp(out, stdout, BIO_NOCLOSE);
283 } else {
284 if (BIO_write_filename(out, outfile) <= 0) {
285 perror(outfile);
286 goto end;
287 }
288 }
289
290#ifndef OPENSSL_NO_ENGINE
291 setup_engine(bio_err, engine, 0);
292#endif
293
294 if (list_curves) {
295 EC_builtin_curve *curves = NULL;
296 size_t crv_len = 0;
297 size_t n = 0;
298
299 crv_len = EC_get_builtin_curves(NULL, 0);
300
301 curves = reallocarray(NULL, crv_len, sizeof(EC_builtin_curve));
302
303 if (curves == NULL)
304 goto end;
305
306 if (!EC_get_builtin_curves(curves, crv_len)) {
307 free(curves);
308 goto end;
309 }
310 for (n = 0; n < crv_len; n++) {
311 const char *comment;
312 const char *sname;
313 comment = curves[n].comment;
314 sname = OBJ_nid2sn(curves[n].nid);
315 if (comment == NULL)
316 comment = "CURVE DESCRIPTION NOT AVAILABLE";
317 if (sname == NULL)
318 sname = "";
319
320 BIO_printf(out, " %-10s: ", sname);
321 BIO_printf(out, "%s\n", comment);
322 }
323
324 free(curves);
325 ret = 0;
326 goto end;
327 }
328 if (curve_name != NULL) {
329 int nid;
330
331 /*
332 * workaround for the SECG curve names secp192r1 and
333 * secp256r1 (which are the same as the curves prime192v1 and
334 * prime256v1 defined in X9.62)
335 */
336 if (!strcmp(curve_name, "secp192r1")) {
337 BIO_printf(bio_err, "using curve name prime192v1 "
338 "instead of secp192r1\n");
339 nid = NID_X9_62_prime192v1;
340 } else if (!strcmp(curve_name, "secp256r1")) {
341 BIO_printf(bio_err, "using curve name prime256v1 "
342 "instead of secp256r1\n");
343 nid = NID_X9_62_prime256v1;
344 } else
345 nid = OBJ_sn2nid(curve_name);
346
347 if (nid == 0) {
348 BIO_printf(bio_err, "unknown curve name (%s)\n",
349 curve_name);
350 goto end;
351 }
352 group = EC_GROUP_new_by_curve_name(nid);
353 if (group == NULL) {
354 BIO_printf(bio_err, "unable to create curve (%s)\n",
355 curve_name);
356 goto end;
357 }
358 EC_GROUP_set_asn1_flag(group, asn1_flag);
359 EC_GROUP_set_point_conversion_form(group, form);
360 } else if (informat == FORMAT_ASN1) {
361 group = d2i_ECPKParameters_bio(in, NULL);
362 } else if (informat == FORMAT_PEM) {
363 group = PEM_read_bio_ECPKParameters(in, NULL, NULL, NULL);
364 } else {
365 BIO_printf(bio_err, "bad input format specified\n");
366 goto end;
367 }
368
369 if (group == NULL) {
370 BIO_printf(bio_err,
371 "unable to load elliptic curve parameters\n");
372 ERR_print_errors(bio_err);
373 goto end;
374 }
375 if (new_form)
376 EC_GROUP_set_point_conversion_form(group, form);
377
378 if (new_asn1_flag)
379 EC_GROUP_set_asn1_flag(group, asn1_flag);
380
381 if (no_seed) {
382 EC_GROUP_set_seed(group, NULL, 0);
383 }
384 if (text) {
385 if (!ECPKParameters_print(out, group, 0))
386 goto end;
387 }
388 if (check) {
389 if (group == NULL)
390 BIO_printf(bio_err, "no elliptic curve parameters\n");
391 BIO_printf(bio_err, "checking elliptic curve parameters: ");
392 if (!EC_GROUP_check(group, NULL)) {
393 BIO_printf(bio_err, "failed\n");
394 ERR_print_errors(bio_err);
395 } else
396 BIO_printf(bio_err, "ok\n");
397
398 }
399 if (C) {
400 size_t buf_len = 0, tmp_len = 0;
401 const EC_POINT *point;
402 int is_prime, len = 0;
403 const EC_METHOD *meth = EC_GROUP_method_of(group);
404
405 if ((ec_p = BN_new()) == NULL || (ec_a = BN_new()) == NULL ||
406 (ec_b = BN_new()) == NULL || (ec_gen = BN_new()) == NULL ||
407 (ec_order = BN_new()) == NULL ||
408 (ec_cofactor = BN_new()) == NULL) {
409 perror("malloc");
410 goto end;
411 }
412 is_prime = (EC_METHOD_get_field_type(meth) ==
413 NID_X9_62_prime_field);
414
415 if (is_prime) {
416 if (!EC_GROUP_get_curve_GFp(group, ec_p, ec_a,
417 ec_b, NULL))
418 goto end;
419 } else {
420 /* TODO */
421 goto end;
422 }
423
424 if ((point = EC_GROUP_get0_generator(group)) == NULL)
425 goto end;
426 if (!EC_POINT_point2bn(group, point,
427 EC_GROUP_get_point_conversion_form(group), ec_gen,
428 NULL))
429 goto end;
430 if (!EC_GROUP_get_order(group, ec_order, NULL))
431 goto end;
432 if (!EC_GROUP_get_cofactor(group, ec_cofactor, NULL))
433 goto end;
434
435 if (!ec_p || !ec_a || !ec_b || !ec_gen ||
436 !ec_order || !ec_cofactor)
437 goto end;
438
439 len = BN_num_bits(ec_order);
440
441 if ((tmp_len = (size_t) BN_num_bytes(ec_p)) > buf_len)
442 buf_len = tmp_len;
443 if ((tmp_len = (size_t) BN_num_bytes(ec_a)) > buf_len)
444 buf_len = tmp_len;
445 if ((tmp_len = (size_t) BN_num_bytes(ec_b)) > buf_len)
446 buf_len = tmp_len;
447 if ((tmp_len = (size_t) BN_num_bytes(ec_gen)) > buf_len)
448 buf_len = tmp_len;
449 if ((tmp_len = (size_t) BN_num_bytes(ec_order)) > buf_len)
450 buf_len = tmp_len;
451 if ((tmp_len = (size_t) BN_num_bytes(ec_cofactor)) > buf_len)
452 buf_len = tmp_len;
453
454 buffer = malloc(buf_len);
455
456 if (buffer == NULL) {
457 perror("malloc");
458 goto end;
459 }
460 ecparam_print_var(out, ec_p, "ec_p", len, buffer);
461 ecparam_print_var(out, ec_a, "ec_a", len, buffer);
462 ecparam_print_var(out, ec_b, "ec_b", len, buffer);
463 ecparam_print_var(out, ec_gen, "ec_gen", len, buffer);
464 ecparam_print_var(out, ec_order, "ec_order", len, buffer);
465 ecparam_print_var(out, ec_cofactor, "ec_cofactor", len,
466 buffer);
467
468 BIO_printf(out, "\n\n");
469
470 BIO_printf(out, "EC_GROUP *get_ec_group_%d(void)\n\t{\n", len);
471 BIO_printf(out, "\tint ok=0;\n");
472 BIO_printf(out, "\tEC_GROUP *group = NULL;\n");
473 BIO_printf(out, "\tEC_POINT *point = NULL;\n");
474 BIO_printf(out, "\tBIGNUM *tmp_1 = NULL, *tmp_2 = NULL, "
475 "*tmp_3 = NULL;\n\n");
476 BIO_printf(out, "\tif ((tmp_1 = BN_bin2bn(ec_p_%d, "
477 "sizeof(ec_p_%d), NULL)) == NULL)\n\t\t"
478 "goto err;\n", len, len);
479 BIO_printf(out, "\tif ((tmp_2 = BN_bin2bn(ec_a_%d, "
480 "sizeof(ec_a_%d), NULL)) == NULL)\n\t\t"
481 "goto err;\n", len, len);
482 BIO_printf(out, "\tif ((tmp_3 = BN_bin2bn(ec_b_%d, "
483 "sizeof(ec_b_%d), NULL)) == NULL)\n\t\t"
484 "goto err;\n", len, len);
485 if (is_prime) {
486 BIO_printf(out, "\tif ((group = EC_GROUP_new_curve_"
487 "GFp(tmp_1, tmp_2, tmp_3, NULL)) == NULL)"
488 "\n\t\tgoto err;\n\n");
489 } else {
490 /* TODO */
491 goto end;
492 }
493 BIO_printf(out, "\t/* build generator */\n");
494 BIO_printf(out, "\tif ((tmp_1 = BN_bin2bn(ec_gen_%d, "
495 "sizeof(ec_gen_%d), tmp_1)) == NULL)"
496 "\n\t\tgoto err;\n", len, len);
497 BIO_printf(out, "\tpoint = EC_POINT_bn2point(group, tmp_1, "
498 "NULL, NULL);\n");
499 BIO_printf(out, "\tif (point == NULL)\n\t\tgoto err;\n");
500 BIO_printf(out, "\tif ((tmp_2 = BN_bin2bn(ec_order_%d, "
501 "sizeof(ec_order_%d), tmp_2)) == NULL)"
502 "\n\t\tgoto err;\n", len, len);
503 BIO_printf(out, "\tif ((tmp_3 = BN_bin2bn(ec_cofactor_%d, "
504 "sizeof(ec_cofactor_%d), tmp_3)) == NULL)"
505 "\n\t\tgoto err;\n", len, len);
506 BIO_printf(out, "\tif (!EC_GROUP_set_generator(group, point,"
507 " tmp_2, tmp_3))\n\t\tgoto err;\n");
508 BIO_printf(out, "\n\tok=1;\n");
509 BIO_printf(out, "err:\n");
510 BIO_printf(out, "\tif (tmp_1)\n\t\tBN_free(tmp_1);\n");
511 BIO_printf(out, "\tif (tmp_2)\n\t\tBN_free(tmp_2);\n");
512 BIO_printf(out, "\tif (tmp_3)\n\t\tBN_free(tmp_3);\n");
513 BIO_printf(out, "\tif (point)\n\t\tEC_POINT_free(point);\n");
514 BIO_printf(out, "\tif (!ok)\n");
515 BIO_printf(out, "\t\t{\n");
516 BIO_printf(out, "\t\tEC_GROUP_free(group);\n");
517 BIO_printf(out, "\t\tgroup = NULL;\n");
518 BIO_printf(out, "\t\t}\n");
519 BIO_printf(out, "\treturn(group);\n\t}\n");
520 }
521 if (!noout) {
522 if (outformat == FORMAT_ASN1)
523 i = i2d_ECPKParameters_bio(out, group);
524 else if (outformat == FORMAT_PEM)
525 i = PEM_write_bio_ECPKParameters(out, group);
526 else {
527 BIO_printf(bio_err, "bad output format specified for"
528 " outfile\n");
529 goto end;
530 }
531 if (!i) {
532 BIO_printf(bio_err, "unable to write elliptic "
533 "curve parameters\n");
534 ERR_print_errors(bio_err);
535 goto end;
536 }
537 }
538 if (genkey) {
539 EC_KEY *eckey = EC_KEY_new();
540
541 if (eckey == NULL)
542 goto end;
543
544 if (EC_KEY_set_group(eckey, group) == 0) {
545 EC_KEY_free(eckey);
546 goto end;
547 }
548
549 if (!EC_KEY_generate_key(eckey)) {
550 EC_KEY_free(eckey);
551 goto end;
552 }
553 if (outformat == FORMAT_ASN1)
554 i = i2d_ECPrivateKey_bio(out, eckey);
555 else if (outformat == FORMAT_PEM)
556 i = PEM_write_bio_ECPrivateKey(out, eckey, NULL,
557 NULL, 0, NULL, NULL);
558 else {
559 BIO_printf(bio_err, "bad output format specified "
560 "for outfile\n");
561 EC_KEY_free(eckey);
562 goto end;
563 }
564 EC_KEY_free(eckey);
565 }
566 ret = 0;
567end:
568 if (ec_p)
569 BN_free(ec_p);
570 if (ec_a)
571 BN_free(ec_a);
572 if (ec_b)
573 BN_free(ec_b);
574 if (ec_gen)
575 BN_free(ec_gen);
576 if (ec_order)
577 BN_free(ec_order);
578 if (ec_cofactor)
579 BN_free(ec_cofactor);
580 free(buffer);
581 BIO_free(in);
582 if (out != NULL)
583 BIO_free_all(out);
584 if (group != NULL)
585 EC_GROUP_free(group);
586
587 return (ret);
588}
589
590static int
591ecparam_print_var(BIO * out, BIGNUM * in, const char *var,
592 int len, unsigned char *buffer)
593{
594 BIO_printf(out, "static unsigned char %s_%d[] = {", var, len);
595 if (BN_is_zero(in))
596 BIO_printf(out, "\n\t0x00");
597 else {
598 int i, l;
599
600 l = BN_bn2bin(in, buffer);
601 for (i = 0; i < l - 1; i++) {
602 if ((i % 12) == 0)
603 BIO_printf(out, "\n\t");
604 BIO_printf(out, "0x%02X,", buffer[i]);
605 }
606 if ((i % 12) == 0)
607 BIO_printf(out, "\n\t");
608 BIO_printf(out, "0x%02X", buffer[i]);
609 }
610 BIO_printf(out, "\n\t};\n\n");
611 return 1;
612}
613#endif
diff --git a/src/usr.bin/openssl/enc.c b/src/usr.bin/openssl/enc.c
new file mode 100644
index 0000000000..eff49818f9
--- /dev/null
+++ b/src/usr.bin/openssl/enc.c
@@ -0,0 +1,649 @@
1/* $OpenBSD: enc.c,v 1.1 2014/08/26 17:47:24 jsing 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 <ctype.h>
60#include <stdio.h>
61#include <stdlib.h>
62#include <string.h>
63
64#include "apps.h"
65
66#include <openssl/bio.h>
67#include <openssl/comp.h>
68#include <openssl/err.h>
69#include <openssl/evp.h>
70#include <openssl/objects.h>
71#include <openssl/pem.h>
72#include <openssl/rand.h>
73#include <openssl/x509.h>
74
75int set_hex(char *in, unsigned char *out, int size);
76
77#define SIZE (512)
78#define BSIZE (8*1024)
79#define PROG enc_main
80
81static void
82show_ciphers(const OBJ_NAME * name, void *bio_)
83{
84 BIO *bio = bio_;
85 static int n;
86
87 if (!islower((unsigned char) *name->name))
88 return;
89
90 BIO_printf(bio, "-%-25s", name->name);
91 if (++n == 3) {
92 BIO_printf(bio, "\n");
93 n = 0;
94 } else
95 BIO_printf(bio, " ");
96}
97
98int enc_main(int, char **);
99
100int
101enc_main(int argc, char **argv)
102{
103 static const char magic[] = "Salted__";
104 char mbuf[sizeof magic - 1];
105 char *strbuf = NULL;
106 unsigned char *buff = NULL, *bufsize = NULL;
107 int bsize = BSIZE, verbose = 0;
108 int ret = 1, inl;
109 int nopad = 0;
110 unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH];
111 unsigned char salt[PKCS5_SALT_LEN];
112 char *str = NULL, *passarg = NULL, *pass = NULL;
113 char *hkey = NULL, *hiv = NULL, *hsalt = NULL;
114 char *md = NULL;
115 int enc = 1, printkey = 0, i, base64 = 0;
116#ifdef ZLIB
117 int do_zlib = 0;
118 BIO *bzl = NULL;
119#endif
120 int debug = 0, olb64 = 0, nosalt = 0;
121 const EVP_CIPHER *cipher = NULL, *c;
122 EVP_CIPHER_CTX *ctx = NULL;
123 char *inf = NULL, *outf = NULL;
124 BIO *in = NULL, *out = NULL, *b64 = NULL, *benc = NULL, *rbio = NULL,
125 *wbio = NULL;
126#define PROG_NAME_SIZE 39
127 char pname[PROG_NAME_SIZE + 1];
128#ifndef OPENSSL_NO_ENGINE
129 char *engine = NULL;
130#endif
131 const EVP_MD *dgst = NULL;
132
133 /* first check the program name */
134 program_name(argv[0], pname, sizeof pname);
135 if (strcmp(pname, "base64") == 0)
136 base64 = 1;
137#ifdef ZLIB
138 if (strcmp(pname, "zlib") == 0)
139 do_zlib = 1;
140#endif
141
142 cipher = EVP_get_cipherbyname(pname);
143#ifdef ZLIB
144 if (!do_zlib && !base64 && (cipher == NULL)
145 && (strcmp(pname, "enc") != 0))
146#else
147 if (!base64 && (cipher == NULL) && (strcmp(pname, "enc") != 0))
148#endif
149 {
150 BIO_printf(bio_err, "%s is an unknown cipher\n", pname);
151 goto bad;
152 }
153 argc--;
154 argv++;
155 while (argc >= 1) {
156 if (strcmp(*argv, "-e") == 0)
157 enc = 1;
158 else if (strcmp(*argv, "-in") == 0) {
159 if (--argc < 1)
160 goto bad;
161 inf = *(++argv);
162 } else if (strcmp(*argv, "-out") == 0) {
163 if (--argc < 1)
164 goto bad;
165 outf = *(++argv);
166 } else if (strcmp(*argv, "-pass") == 0) {
167 if (--argc < 1)
168 goto bad;
169 passarg = *(++argv);
170 }
171#ifndef OPENSSL_NO_ENGINE
172 else if (strcmp(*argv, "-engine") == 0) {
173 if (--argc < 1)
174 goto bad;
175 engine = *(++argv);
176 }
177#endif
178 else if (strcmp(*argv, "-d") == 0)
179 enc = 0;
180 else if (strcmp(*argv, "-p") == 0)
181 printkey = 1;
182 else if (strcmp(*argv, "-v") == 0)
183 verbose = 1;
184 else if (strcmp(*argv, "-nopad") == 0)
185 nopad = 1;
186 else if (strcmp(*argv, "-salt") == 0)
187 nosalt = 0;
188 else if (strcmp(*argv, "-nosalt") == 0)
189 nosalt = 1;
190 else if (strcmp(*argv, "-debug") == 0)
191 debug = 1;
192 else if (strcmp(*argv, "-P") == 0)
193 printkey = 2;
194 else if (strcmp(*argv, "-A") == 0)
195 olb64 = 1;
196 else if (strcmp(*argv, "-a") == 0)
197 base64 = 1;
198 else if (strcmp(*argv, "-base64") == 0)
199 base64 = 1;
200#ifdef ZLIB
201 else if (strcmp(*argv, "-z") == 0)
202 do_zlib = 1;
203#endif
204 else if (strcmp(*argv, "-bufsize") == 0) {
205 if (--argc < 1)
206 goto bad;
207 bufsize = (unsigned char *) *(++argv);
208 } else if (strcmp(*argv, "-k") == 0) {
209 if (--argc < 1)
210 goto bad;
211 str = *(++argv);
212 } else if (strcmp(*argv, "-kfile") == 0) {
213 static char buf[128];
214 FILE *infile;
215 char *file;
216
217 if (--argc < 1)
218 goto bad;
219 file = *(++argv);
220 infile = fopen(file, "r");
221 if (infile == NULL) {
222 BIO_printf(bio_err, "unable to read key from '%s'\n",
223 file);
224 goto bad;
225 }
226 buf[0] = '\0';
227 if (!fgets(buf, sizeof buf, infile)) {
228 BIO_printf(bio_err, "unable to read key from '%s'\n",
229 file);
230 fclose(infile);
231 goto bad;
232 }
233 fclose(infile);
234 i = strlen(buf);
235 if ((i > 0) &&
236 ((buf[i - 1] == '\n') || (buf[i - 1] == '\r')))
237 buf[--i] = '\0';
238 if ((i > 0) &&
239 ((buf[i - 1] == '\n') || (buf[i - 1] == '\r')))
240 buf[--i] = '\0';
241 if (i < 1) {
242 BIO_printf(bio_err, "zero length password\n");
243 goto bad;
244 }
245 str = buf;
246 } else if (strcmp(*argv, "-K") == 0) {
247 if (--argc < 1)
248 goto bad;
249 hkey = *(++argv);
250 } else if (strcmp(*argv, "-S") == 0) {
251 if (--argc < 1)
252 goto bad;
253 hsalt = *(++argv);
254 } else if (strcmp(*argv, "-iv") == 0) {
255 if (--argc < 1)
256 goto bad;
257 hiv = *(++argv);
258 } else if (strcmp(*argv, "-md") == 0) {
259 if (--argc < 1)
260 goto bad;
261 md = *(++argv);
262 } else if ((argv[0][0] == '-') &&
263 ((c = EVP_get_cipherbyname(&(argv[0][1]))) != NULL)) {
264 cipher = c;
265 } else if (strcmp(*argv, "-none") == 0)
266 cipher = NULL;
267 else {
268 BIO_printf(bio_err, "unknown option '%s'\n", *argv);
269 bad:
270 BIO_printf(bio_err, "options are\n");
271 BIO_printf(bio_err, "%-14s input file\n", "-in <file>");
272 BIO_printf(bio_err, "%-14s output file\n", "-out <file>");
273 BIO_printf(bio_err, "%-14s pass phrase source\n", "-pass <arg>");
274 BIO_printf(bio_err, "%-14s encrypt\n", "-e");
275 BIO_printf(bio_err, "%-14s decrypt\n", "-d");
276 BIO_printf(bio_err, "%-14s base64 encode/decode, depending on encryption flag\n", "-a/-base64");
277 BIO_printf(bio_err, "%-14s passphrase is the next argument\n", "-k");
278 BIO_printf(bio_err, "%-14s passphrase is the first line of the file argument\n", "-kfile");
279 BIO_printf(bio_err, "%-14s the next argument is the md to use to create a key\n", "-md");
280 BIO_printf(bio_err, "%-14s from a passphrase. One of md2, md5, sha or sha1\n", "");
281 BIO_printf(bio_err, "%-14s salt in hex is the next argument\n", "-S");
282 BIO_printf(bio_err, "%-14s key/iv in hex is the next argument\n", "-K/-iv");
283 BIO_printf(bio_err, "%-14s print the iv/key (then exit if -P)\n", "-[pP]");
284 BIO_printf(bio_err, "%-14s buffer size\n", "-bufsize <n>");
285 BIO_printf(bio_err, "%-14s disable standard block padding\n", "-nopad");
286#ifndef OPENSSL_NO_ENGINE
287 BIO_printf(bio_err, "%-14s use engine e, possibly a hardware device.\n", "-engine e");
288#endif
289
290 BIO_printf(bio_err, "Cipher Types\n");
291 OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH,
292 show_ciphers,
293 bio_err);
294 BIO_printf(bio_err, "\n");
295
296 goto end;
297 }
298 argc--;
299 argv++;
300 }
301
302#ifndef OPENSSL_NO_ENGINE
303 setup_engine(bio_err, engine, 0);
304#endif
305
306 if (md && (dgst = EVP_get_digestbyname(md)) == NULL) {
307 BIO_printf(bio_err, "%s is an unsupported message digest type\n", md);
308 goto end;
309 }
310 if (dgst == NULL) {
311 dgst = EVP_md5();
312 }
313 if (bufsize != NULL) {
314 unsigned long n;
315
316 for (n = 0; *bufsize; bufsize++) {
317 i = *bufsize;
318 if ((i <= '9') && (i >= '0'))
319 n = n * 10 + i - '0';
320 else if (i == 'k') {
321 n *= 1024;
322 bufsize++;
323 break;
324 }
325 }
326 if (*bufsize != '\0') {
327 BIO_printf(bio_err, "invalid 'bufsize' specified.\n");
328 goto end;
329 }
330 /* It must be large enough for a base64 encoded line */
331 if (base64 && n < 80)
332 n = 80;
333
334 bsize = (int) n;
335 if (verbose)
336 BIO_printf(bio_err, "bufsize=%d\n", bsize);
337 }
338 strbuf = malloc(SIZE);
339 buff = malloc(EVP_ENCODE_LENGTH(bsize));
340 if ((buff == NULL) || (strbuf == NULL)) {
341 BIO_printf(bio_err, "malloc failure %ld\n", (long) EVP_ENCODE_LENGTH(bsize));
342 goto end;
343 }
344 in = BIO_new(BIO_s_file());
345 out = BIO_new(BIO_s_file());
346 if ((in == NULL) || (out == NULL)) {
347 ERR_print_errors(bio_err);
348 goto end;
349 }
350 if (debug) {
351 BIO_set_callback(in, BIO_debug_callback);
352 BIO_set_callback(out, BIO_debug_callback);
353 BIO_set_callback_arg(in, (char *) bio_err);
354 BIO_set_callback_arg(out, (char *) bio_err);
355 }
356 if (inf == NULL) {
357 if (bufsize != NULL)
358 setvbuf(stdin, (char *) NULL, _IONBF, 0);
359 BIO_set_fp(in, stdin, BIO_NOCLOSE);
360 } else {
361 if (BIO_read_filename(in, inf) <= 0) {
362 perror(inf);
363 goto end;
364 }
365 }
366
367 if (!str && passarg) {
368 if (!app_passwd(bio_err, passarg, NULL, &pass, NULL)) {
369 BIO_printf(bio_err, "Error getting password\n");
370 goto end;
371 }
372 str = pass;
373 }
374 if ((str == NULL) && (cipher != NULL) && (hkey == NULL)) {
375 for (;;) {
376 char buf[200];
377 int ret;
378
379 ret = snprintf(buf, sizeof buf, "enter %s %s password:",
380 OBJ_nid2ln(EVP_CIPHER_nid(cipher)),
381 (enc) ? "encryption" : "decryption");
382 if (ret == -1 || ret >= sizeof buf) {
383 BIO_printf(bio_err, "Password prompt too long\n");
384 goto end;
385 }
386 strbuf[0] = '\0';
387 i = EVP_read_pw_string((char *) strbuf, SIZE, buf, enc);
388 if (i == 0) {
389 if (strbuf[0] == '\0') {
390 ret = 1;
391 goto end;
392 }
393 str = strbuf;
394 break;
395 }
396 if (i < 0) {
397 BIO_printf(bio_err, "bad password read\n");
398 goto end;
399 }
400 }
401 }
402 if (outf == NULL) {
403 BIO_set_fp(out, stdout, BIO_NOCLOSE);
404 if (bufsize != NULL)
405 setvbuf(stdout, (char *) NULL, _IONBF, 0);
406 } else {
407 if (BIO_write_filename(out, outf) <= 0) {
408 perror(outf);
409 goto end;
410 }
411 }
412
413 rbio = in;
414 wbio = out;
415
416#ifdef ZLIB
417
418 if (do_zlib) {
419 if ((bzl = BIO_new(BIO_f_zlib())) == NULL)
420 goto end;
421 if (enc)
422 wbio = BIO_push(bzl, wbio);
423 else
424 rbio = BIO_push(bzl, rbio);
425 }
426#endif
427
428 if (base64) {
429 if ((b64 = BIO_new(BIO_f_base64())) == NULL)
430 goto end;
431 if (debug) {
432 BIO_set_callback(b64, BIO_debug_callback);
433 BIO_set_callback_arg(b64, (char *) bio_err);
434 }
435 if (olb64)
436 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
437 if (enc)
438 wbio = BIO_push(b64, wbio);
439 else
440 rbio = BIO_push(b64, rbio);
441 }
442 if (cipher != NULL) {
443 /*
444 * Note that str is NULL if a key was passed on the command
445 * line, so we get no salt in that case. Is this a bug?
446 */
447 if (str != NULL) {
448 /*
449 * Salt handling: if encrypting generate a salt and
450 * write to output BIO. If decrypting read salt from
451 * input BIO.
452 */
453 unsigned char *sptr;
454 if (nosalt)
455 sptr = NULL;
456 else {
457 if (enc) {
458 if (hsalt) {
459 if (!set_hex(hsalt, salt, sizeof salt)) {
460 BIO_printf(bio_err,
461 "invalid hex salt value\n");
462 goto end;
463 }
464 } else if (RAND_pseudo_bytes(salt, sizeof salt) < 0)
465 goto end;
466 /*
467 * If -P option then don't bother
468 * writing
469 */
470 if ((printkey != 2)
471 && (BIO_write(wbio, magic,
472 sizeof magic - 1) != sizeof magic - 1
473 || BIO_write(wbio,
474 (char *) salt,
475 sizeof salt) != sizeof salt)) {
476 BIO_printf(bio_err, "error writing output file\n");
477 goto end;
478 }
479 } else if (BIO_read(rbio, mbuf, sizeof mbuf) != sizeof mbuf
480 || BIO_read(rbio,
481 (unsigned char *) salt,
482 sizeof salt) != sizeof salt) {
483 BIO_printf(bio_err, "error reading input file\n");
484 goto end;
485 } else if (memcmp(mbuf, magic, sizeof magic - 1)) {
486 BIO_printf(bio_err, "bad magic number\n");
487 goto end;
488 }
489 sptr = salt;
490 }
491
492 EVP_BytesToKey(cipher, dgst, sptr,
493 (unsigned char *) str,
494 strlen(str), 1, key, iv);
495 /*
496 * zero the complete buffer or the string passed from
497 * the command line bug picked up by Larry J. Hughes
498 * Jr. <hughes@indiana.edu>
499 */
500 if (str == strbuf)
501 OPENSSL_cleanse(str, SIZE);
502 else
503 OPENSSL_cleanse(str, strlen(str));
504 }
505 if ((hiv != NULL) && !set_hex(hiv, iv, sizeof iv)) {
506 BIO_printf(bio_err, "invalid hex iv value\n");
507 goto end;
508 }
509 if ((hiv == NULL) && (str == NULL)
510 && EVP_CIPHER_iv_length(cipher) != 0) {
511 /*
512 * No IV was explicitly set and no IV was generated
513 * during EVP_BytesToKey. Hence the IV is undefined,
514 * making correct decryption impossible.
515 */
516 BIO_printf(bio_err, "iv undefined\n");
517 goto end;
518 }
519 if ((hkey != NULL) && !set_hex(hkey, key, sizeof key)) {
520 BIO_printf(bio_err, "invalid hex key value\n");
521 goto end;
522 }
523 if ((benc = BIO_new(BIO_f_cipher())) == NULL)
524 goto end;
525
526 /*
527 * Since we may be changing parameters work on the encryption
528 * context rather than calling BIO_set_cipher().
529 */
530
531 BIO_get_cipher_ctx(benc, &ctx);
532
533 if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, enc)) {
534 BIO_printf(bio_err, "Error setting cipher %s\n",
535 EVP_CIPHER_name(cipher));
536 ERR_print_errors(bio_err);
537 goto end;
538 }
539 if (nopad)
540 EVP_CIPHER_CTX_set_padding(ctx, 0);
541
542 if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, enc)) {
543 BIO_printf(bio_err, "Error setting cipher %s\n",
544 EVP_CIPHER_name(cipher));
545 ERR_print_errors(bio_err);
546 goto end;
547 }
548 if (debug) {
549 BIO_set_callback(benc, BIO_debug_callback);
550 BIO_set_callback_arg(benc, (char *) bio_err);
551 }
552 if (printkey) {
553 if (!nosalt) {
554 printf("salt=");
555 for (i = 0; i < (int) sizeof(salt); i++)
556 printf("%02X", salt[i]);
557 printf("\n");
558 }
559 if (cipher->key_len > 0) {
560 printf("key=");
561 for (i = 0; i < cipher->key_len; i++)
562 printf("%02X", key[i]);
563 printf("\n");
564 }
565 if (cipher->iv_len > 0) {
566 printf("iv =");
567 for (i = 0; i < cipher->iv_len; i++)
568 printf("%02X", iv[i]);
569 printf("\n");
570 }
571 if (printkey == 2) {
572 ret = 0;
573 goto end;
574 }
575 }
576 }
577 /* Only encrypt/decrypt as we write the file */
578 if (benc != NULL)
579 wbio = BIO_push(benc, wbio);
580
581 for (;;) {
582 inl = BIO_read(rbio, (char *) buff, bsize);
583 if (inl <= 0)
584 break;
585 if (BIO_write(wbio, (char *) buff, inl) != inl) {
586 BIO_printf(bio_err, "error writing output file\n");
587 goto end;
588 }
589 }
590 if (!BIO_flush(wbio)) {
591 BIO_printf(bio_err, "bad decrypt\n");
592 goto end;
593 }
594 ret = 0;
595 if (verbose) {
596 BIO_printf(bio_err, "bytes read :%8ld\n", BIO_number_read(in));
597 BIO_printf(bio_err, "bytes written:%8ld\n", BIO_number_written(out));
598 }
599end:
600 ERR_print_errors(bio_err);
601 free(strbuf);
602 free(buff);
603 BIO_free(in);
604 if (out != NULL)
605 BIO_free_all(out);
606 BIO_free(benc);
607 BIO_free(b64);
608#ifdef ZLIB
609 BIO_free(bzl);
610#endif
611 free(pass);
612
613 return (ret);
614}
615
616int
617set_hex(char *in, unsigned char *out, int size)
618{
619 int i, n;
620 unsigned char j;
621
622 n = strlen(in);
623 if (n > (size * 2)) {
624 BIO_printf(bio_err, "hex string is too long\n");
625 return (0);
626 }
627 memset(out, 0, size);
628 for (i = 0; i < n; i++) {
629 j = (unsigned char) *in;
630 *(in++) = '\0';
631 if (j == 0)
632 break;
633 if ((j >= '0') && (j <= '9'))
634 j -= '0';
635 else if ((j >= 'A') && (j <= 'F'))
636 j = j - 'A' + 10;
637 else if ((j >= 'a') && (j <= 'f'))
638 j = j - 'a' + 10;
639 else {
640 BIO_printf(bio_err, "non-hex digit\n");
641 return (0);
642 }
643 if (i & 1)
644 out[i / 2] |= j;
645 else
646 out[i / 2] = (j << 4);
647 }
648 return (1);
649}
diff --git a/src/usr.bin/openssl/engine.c b/src/usr.bin/openssl/engine.c
new file mode 100644
index 0000000000..2d24e07254
--- /dev/null
+++ b/src/usr.bin/openssl/engine.c
@@ -0,0 +1,494 @@
1/* $OpenBSD: engine.c,v 1.1 2014/08/26 17:47:24 jsing Exp $ */
2/* Written by Richard Levitte <richard@levitte.org> for the OpenSSL
3 * project 2000.
4 */
5/* ====================================================================
6 * Copyright (c) 2000 The OpenSSL Project. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
19 *
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24 *
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * licensing@OpenSSL.org.
29 *
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
33 *
34 * 6. Redistributions of any form whatsoever must retain the following
35 * acknowledgment:
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
52 *
53 * This product includes cryptographic software written by Eric Young
54 * (eay@cryptsoft.com). This product includes software written by Tim
55 * Hudson (tjh@cryptsoft.com).
56 *
57 */
58
59#include <stdio.h>
60#include <stdlib.h>
61#include <string.h>
62
63#include "apps.h"
64
65#ifndef OPENSSL_NO_ENGINE
66#include <openssl/engine.h>
67#include <openssl/err.h>
68#include <openssl/ssl.h>
69
70static const char *engine_usage[] = {
71 "usage: engine opts [engine ...]\n",
72 " -v[v[v[v]]] - verbose mode, for each engine, list its 'control commands'\n",
73 " -vv will additionally display each command's description\n",
74 " -vvv will also add the input flags for each command\n",
75 " -vvvv will also show internal input flags\n",
76 " -c - for each engine, also list the capabilities\n",
77 " -t[t] - for each engine, check that they are really available\n",
78 " -tt will display error trace for unavailable engines\n",
79 " -pre <cmd> - runs command 'cmd' against the ENGINE before any attempts\n",
80 " to load it (if -t is used)\n",
81 " -post <cmd> - runs command 'cmd' against the ENGINE after loading it\n",
82 " (only used if -t is also provided)\n",
83 " NB: -pre and -post will be applied to all ENGINEs supplied on the command\n",
84 " line, or all supported ENGINEs if none are specified.\n",
85 " Eg. '-pre \"SO_PATH:/lib/libdriver.so\"' calls command \"SO_PATH\" with\n",
86 " argument \"/lib/libdriver.so\".\n",
87 NULL
88};
89
90static void
91identity(char *ptr)
92{
93 return;
94}
95
96static int
97append_buf(char **buf, const char *s, int *size, int step)
98{
99 int l = strlen(s);
100
101 if (*buf == NULL) {
102 *size = step;
103 *buf = malloc(*size);
104 if (*buf == NULL)
105 return 0;
106 **buf = '\0';
107 }
108 if (**buf != '\0')
109 l += 2; /* ", " */
110
111 if (strlen(*buf) + strlen(s) >= (unsigned int) *size) {
112 *size += step;
113 *buf = realloc(*buf, *size);
114 }
115 if (*buf == NULL)
116 return 0;
117
118 if (**buf != '\0')
119 strlcat(*buf, ", ", *size);
120 strlcat(*buf, s, *size);
121
122 return 1;
123}
124
125static int
126util_flags(BIO * bio_out, unsigned int flags, const char *indent)
127{
128 int started = 0, err = 0;
129 /* Indent before displaying input flags */
130 BIO_printf(bio_out, "%s%s(input flags): ", indent, indent);
131 if (flags == 0) {
132 BIO_printf(bio_out, "<no flags>\n");
133 return 1;
134 }
135 /*
136 * If the object is internal, mark it in a way that shows instead of
137 * having it part of all the other flags, even if it really is.
138 */
139 if (flags & ENGINE_CMD_FLAG_INTERNAL) {
140 BIO_printf(bio_out, "[Internal] ");
141 }
142 if (flags & ENGINE_CMD_FLAG_NUMERIC) {
143 BIO_printf(bio_out, "NUMERIC");
144 started = 1;
145 }
146 /*
147 * Now we check that no combinations of the mutually exclusive
148 * NUMERIC, STRING, and NO_INPUT flags have been used. Future flags
149 * that can be OR'd together with these would need to added after
150 * these to preserve the testing logic.
151 */
152 if (flags & ENGINE_CMD_FLAG_STRING) {
153 if (started) {
154 BIO_printf(bio_out, "|");
155 err = 1;
156 }
157 BIO_printf(bio_out, "STRING");
158 started = 1;
159 }
160 if (flags & ENGINE_CMD_FLAG_NO_INPUT) {
161 if (started) {
162 BIO_printf(bio_out, "|");
163 err = 1;
164 }
165 BIO_printf(bio_out, "NO_INPUT");
166 started = 1;
167 }
168 /* Check for unknown flags */
169 flags = flags & ~ENGINE_CMD_FLAG_NUMERIC &
170 ~ENGINE_CMD_FLAG_STRING &
171 ~ENGINE_CMD_FLAG_NO_INPUT &
172 ~ENGINE_CMD_FLAG_INTERNAL;
173 if (flags) {
174 if (started)
175 BIO_printf(bio_out, "|");
176 BIO_printf(bio_out, "<0x%04X>", flags);
177 }
178 if (err)
179 BIO_printf(bio_out, " <illegal flags!>");
180 BIO_printf(bio_out, "\n");
181 return 1;
182}
183
184static int
185util_verbose(ENGINE * e, int verbose, BIO * bio_out, const char *indent)
186{
187 static const int line_wrap = 78;
188 int num;
189 int ret = 0;
190 char *name = NULL;
191 char *desc = NULL;
192 int flags;
193 int xpos = 0;
194 STACK_OF(OPENSSL_STRING) * cmds = NULL;
195 if (!ENGINE_ctrl(e, ENGINE_CTRL_HAS_CTRL_FUNCTION, 0, NULL, NULL) ||
196 ((num = ENGINE_ctrl(e, ENGINE_CTRL_GET_FIRST_CMD_TYPE,
197 0, NULL, NULL)) <= 0)) {
198#if 0
199 BIO_printf(bio_out, "%s<no control commands>\n", indent);
200#endif
201 return 1;
202 }
203 cmds = sk_OPENSSL_STRING_new_null();
204
205 if (!cmds)
206 goto err;
207 do {
208 int len;
209 /* Get the command input flags */
210 if ((flags = ENGINE_ctrl(e, ENGINE_CTRL_GET_CMD_FLAGS, num,
211 NULL, NULL)) < 0)
212 goto err;
213 if (!(flags & ENGINE_CMD_FLAG_INTERNAL) || verbose >= 4) {
214 /* Get the command name */
215 if ((len = ENGINE_ctrl(e, ENGINE_CTRL_GET_NAME_LEN_FROM_CMD, num,
216 NULL, NULL)) <= 0)
217 goto err;
218 if ((name = malloc(len + 1)) == NULL)
219 goto err;
220 if (ENGINE_ctrl(e, ENGINE_CTRL_GET_NAME_FROM_CMD, num, name,
221 NULL) <= 0)
222 goto err;
223 /* Get the command description */
224 if ((len = ENGINE_ctrl(e, ENGINE_CTRL_GET_DESC_LEN_FROM_CMD, num,
225 NULL, NULL)) < 0)
226 goto err;
227 if (len > 0) {
228 if ((desc = malloc(len + 1)) == NULL)
229 goto err;
230 if (ENGINE_ctrl(e, ENGINE_CTRL_GET_DESC_FROM_CMD, num, desc,
231 NULL) <= 0)
232 goto err;
233 }
234 /* Now decide on the output */
235 if (xpos == 0)
236 /* Do an indent */
237 xpos = BIO_puts(bio_out, indent);
238 else
239 /* Otherwise prepend a ", " */
240 xpos += BIO_printf(bio_out, ", ");
241 if (verbose == 1) {
242 /* We're just listing names, comma-delimited */
243 if ((xpos > (int) strlen(indent)) &&
244 (xpos + (int) strlen(name) > line_wrap)) {
245 BIO_printf(bio_out, "\n");
246 xpos = BIO_puts(bio_out, indent);
247 }
248 xpos += BIO_printf(bio_out, "%s", name);
249 } else {
250 /* We're listing names plus descriptions */
251 BIO_printf(bio_out, "%s: %s\n", name,
252 (desc == NULL) ? "<no description>" : desc);
253 /* ... and sometimes input flags */
254 if ((verbose >= 3) && !util_flags(bio_out, flags,
255 indent))
256 goto err;
257 xpos = 0;
258 }
259 }
260 free(name);
261 name = NULL;
262 free(desc);
263 desc = NULL;
264
265 /* Move to the next command */
266 num = ENGINE_ctrl(e, ENGINE_CTRL_GET_NEXT_CMD_TYPE,
267 num, NULL, NULL);
268 } while (num > 0);
269 if (xpos > 0)
270 BIO_printf(bio_out, "\n");
271 ret = 1;
272err:
273 if (cmds)
274 sk_OPENSSL_STRING_pop_free(cmds, identity);
275 free(name);
276 free(desc);
277 return ret;
278}
279
280static void
281util_do_cmds(ENGINE * e, STACK_OF(OPENSSL_STRING) * cmds,
282 BIO * bio_out, const char *indent)
283{
284 int loop, res, num = sk_OPENSSL_STRING_num(cmds);
285
286 if (num < 0) {
287 BIO_printf(bio_out, "[Error]: internal stack error\n");
288 return;
289 }
290 for (loop = 0; loop < num; loop++) {
291 char buf[256];
292 const char *cmd, *arg;
293 cmd = sk_OPENSSL_STRING_value(cmds, loop);
294 res = 1; /* assume success */
295 /* Check if this command has no ":arg" */
296 if ((arg = strstr(cmd, ":")) == NULL) {
297 if (!ENGINE_ctrl_cmd_string(e, cmd, NULL, 0))
298 res = 0;
299 } else {
300 if ((int) (arg - cmd) > 254) {
301 BIO_printf(bio_out, "[Error]: command name too long\n");
302 return;
303 }
304 memcpy(buf, cmd, (int) (arg - cmd));
305 buf[arg - cmd] = '\0';
306 arg++; /* Move past the ":" */
307 /* Call the command with the argument */
308 if (!ENGINE_ctrl_cmd_string(e, buf, arg, 0))
309 res = 0;
310 }
311 if (res)
312 BIO_printf(bio_out, "[Success]: %s\n", cmd);
313 else {
314 BIO_printf(bio_out, "[Failure]: %s\n", cmd);
315 ERR_print_errors(bio_out);
316 }
317 }
318}
319
320int engine_main(int, char **);
321
322int
323engine_main(int argc, char **argv)
324{
325 int ret = 1, i;
326 const char **pp;
327 int verbose = 0, list_cap = 0, test_avail = 0, test_avail_noise = 0;
328 ENGINE *e;
329 STACK_OF(OPENSSL_STRING) * engines = sk_OPENSSL_STRING_new_null();
330 STACK_OF(OPENSSL_STRING) * pre_cmds = sk_OPENSSL_STRING_new_null();
331 STACK_OF(OPENSSL_STRING) * post_cmds = sk_OPENSSL_STRING_new_null();
332 int badops = 1;
333 BIO *bio_out = NULL;
334 const char *indent = " ";
335
336 bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
337
338 argc--;
339 argv++;
340 while (argc >= 1) {
341 if (strncmp(*argv, "-v", 2) == 0) {
342 if (strspn(*argv + 1, "v") < strlen(*argv + 1))
343 goto skip_arg_loop;
344 if ((verbose = strlen(*argv + 1)) > 4)
345 goto skip_arg_loop;
346 } else if (strcmp(*argv, "-c") == 0)
347 list_cap = 1;
348 else if (strncmp(*argv, "-t", 2) == 0) {
349 test_avail = 1;
350 if (strspn(*argv + 1, "t") < strlen(*argv + 1))
351 goto skip_arg_loop;
352 if ((test_avail_noise = strlen(*argv + 1) - 1) > 1)
353 goto skip_arg_loop;
354 } else if (strcmp(*argv, "-pre") == 0) {
355 argc--;
356 argv++;
357 if (argc == 0)
358 goto skip_arg_loop;
359 sk_OPENSSL_STRING_push(pre_cmds, *argv);
360 } else if (strcmp(*argv, "-post") == 0) {
361 argc--;
362 argv++;
363 if (argc == 0)
364 goto skip_arg_loop;
365 sk_OPENSSL_STRING_push(post_cmds, *argv);
366 } else if ((strncmp(*argv, "-h", 2) == 0) ||
367 (strcmp(*argv, "-?") == 0))
368 goto skip_arg_loop;
369 else
370 sk_OPENSSL_STRING_push(engines, *argv);
371 argc--;
372 argv++;
373 }
374 /* Looks like everything went OK */
375 badops = 0;
376skip_arg_loop:
377
378 if (badops) {
379 for (pp = engine_usage; (*pp != NULL); pp++)
380 BIO_printf(bio_err, "%s", *pp);
381 goto end;
382 }
383 if (sk_OPENSSL_STRING_num(engines) == 0) {
384 for (e = ENGINE_get_first(); e != NULL; e = ENGINE_get_next(e)) {
385 sk_OPENSSL_STRING_push(engines, (char *) ENGINE_get_id(e));
386 }
387 }
388 for (i = 0; i < sk_OPENSSL_STRING_num(engines); i++) {
389 const char *id = sk_OPENSSL_STRING_value(engines, i);
390 if ((e = ENGINE_by_id(id)) != NULL) {
391 const char *name = ENGINE_get_name(e);
392 /* Do "id" first, then "name". Easier to auto-parse. */
393 BIO_printf(bio_out, "(%s) %s\n", id, name);
394 util_do_cmds(e, pre_cmds, bio_out, indent);
395 if (strcmp(ENGINE_get_id(e), id) != 0) {
396 BIO_printf(bio_out, "Loaded: (%s) %s\n",
397 ENGINE_get_id(e), ENGINE_get_name(e));
398 }
399 if (list_cap) {
400 int cap_size = 256;
401 char *cap_buf = NULL;
402 int k, n;
403 const int *nids;
404 ENGINE_CIPHERS_PTR fn_c;
405 ENGINE_DIGESTS_PTR fn_d;
406 ENGINE_PKEY_METHS_PTR fn_pk;
407
408 if (ENGINE_get_RSA(e) != NULL
409 && !append_buf(&cap_buf, "RSA",
410 &cap_size, 256))
411 goto end;
412 if (ENGINE_get_DSA(e) != NULL
413 && !append_buf(&cap_buf, "DSA",
414 &cap_size, 256))
415 goto end;
416 if (ENGINE_get_DH(e) != NULL
417 && !append_buf(&cap_buf, "DH",
418 &cap_size, 256))
419 goto end;
420 if (ENGINE_get_RAND(e) != NULL
421 && !append_buf(&cap_buf, "RAND",
422 &cap_size, 256))
423 goto end;
424
425 fn_c = ENGINE_get_ciphers(e);
426 if (!fn_c)
427 goto skip_ciphers;
428 n = fn_c(e, NULL, &nids, 0);
429 for (k = 0; k < n; ++k)
430 if (!append_buf(&cap_buf,
431 OBJ_nid2sn(nids[k]),
432 &cap_size, 256))
433 goto end;
434
435 skip_ciphers:
436 fn_d = ENGINE_get_digests(e);
437 if (!fn_d)
438 goto skip_digests;
439 n = fn_d(e, NULL, &nids, 0);
440 for (k = 0; k < n; ++k)
441 if (!append_buf(&cap_buf,
442 OBJ_nid2sn(nids[k]),
443 &cap_size, 256))
444 goto end;
445
446 skip_digests:
447 fn_pk = ENGINE_get_pkey_meths(e);
448 if (!fn_pk)
449 goto skip_pmeths;
450 n = fn_pk(e, NULL, &nids, 0);
451 for (k = 0; k < n; ++k)
452 if (!append_buf(&cap_buf,
453 OBJ_nid2sn(nids[k]),
454 &cap_size, 256))
455 goto end;
456 skip_pmeths:
457 if (cap_buf && (*cap_buf != '\0'))
458 BIO_printf(bio_out, " [%s]\n", cap_buf);
459
460 free(cap_buf);
461 }
462 if (test_avail) {
463 BIO_printf(bio_out, "%s", indent);
464 if (ENGINE_init(e)) {
465 BIO_printf(bio_out, "[ available ]\n");
466 util_do_cmds(e, post_cmds, bio_out, indent);
467 ENGINE_finish(e);
468 } else {
469 BIO_printf(bio_out, "[ unavailable ]\n");
470 if (test_avail_noise)
471 ERR_print_errors_fp(stdout);
472 ERR_clear_error();
473 }
474 }
475 if ((verbose > 0) && !util_verbose(e, verbose, bio_out, indent))
476 goto end;
477 ENGINE_free(e);
478 } else
479 ERR_print_errors(bio_err);
480 }
481
482 ret = 0;
483end:
484
485 ERR_print_errors(bio_err);
486 sk_OPENSSL_STRING_pop_free(engines, identity);
487 sk_OPENSSL_STRING_pop_free(pre_cmds, identity);
488 sk_OPENSSL_STRING_pop_free(post_cmds, identity);
489 if (bio_out != NULL)
490 BIO_free_all(bio_out);
491
492 return (ret);
493}
494#endif
diff --git a/src/usr.bin/openssl/errstr.c b/src/usr.bin/openssl/errstr.c
new file mode 100644
index 0000000000..163da2e5b3
--- /dev/null
+++ b/src/usr.bin/openssl/errstr.c
@@ -0,0 +1,108 @@
1/* $OpenBSD: errstr.c,v 1.1 2014/08/26 17:47:24 jsing 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#include <stdlib.h>
61#include <string.h>
62
63#include "apps.h"
64
65#include <openssl/bio.h>
66#include <openssl/err.h>
67#include <openssl/lhash.h>
68#include <openssl/ssl.h>
69
70int errstr_main(int, char **);
71
72int
73errstr_main(int argc, char **argv)
74{
75 int i, ret = 0;
76 char buf[256];
77 unsigned long l;
78
79 if ((argc > 1) && (strcmp(argv[1], "-stats") == 0)) {
80 BIO *out = NULL;
81
82 out = BIO_new(BIO_s_file());
83 if ((out != NULL) && BIO_set_fp(out, stdout, BIO_NOCLOSE)) {
84 lh_ERR_STRING_DATA_node_stats_bio(
85 ERR_get_string_table(), out);
86 lh_ERR_STRING_DATA_stats_bio(ERR_get_string_table(),
87 out);
88 lh_ERR_STRING_DATA_node_usage_stats_bio(
89 ERR_get_string_table(), out);
90 }
91 if (out != NULL)
92 BIO_free_all(out);
93 argc--;
94 argv++;
95 }
96 for (i = 1; i < argc; i++) {
97 if (sscanf(argv[i], "%lx", &l)) {
98 ERR_error_string_n(l, buf, sizeof buf);
99 printf("%s\n", buf);
100 } else {
101 printf("%s: bad error code\n", argv[i]);
102 printf("usage: errstr [-stats] <errno> ...\n");
103 ret++;
104 }
105 }
106
107 return (ret);
108}
diff --git a/src/usr.bin/openssl/gendh.c b/src/usr.bin/openssl/gendh.c
new file mode 100644
index 0000000000..06d62c1b0d
--- /dev/null
+++ b/src/usr.bin/openssl/gendh.c
@@ -0,0 +1,204 @@
1/* $OpenBSD: gendh.c,v 1.1 2014/08/26 17:47:24 jsing 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 <openssl/opensslconf.h>
60
61/* Until the key-gen callbacks are modified to use newer prototypes, we allow
62 * deprecated functions for openssl-internal code */
63#ifdef OPENSSL_NO_DEPRECATED
64#undef OPENSSL_NO_DEPRECATED
65#endif
66
67#ifndef OPENSSL_NO_DH
68
69#include <sys/types.h>
70#include <sys/stat.h>
71
72#include <stdio.h>
73#include <string.h>
74
75#include "apps.h"
76
77#include <openssl/bio.h>
78#include <openssl/bn.h>
79#include <openssl/dh.h>
80#include <openssl/err.h>
81#include <openssl/pem.h>
82#include <openssl/rand.h>
83#include <openssl/x509.h>
84
85#define DEFBITS 512
86
87static int dh_cb(int p, int n, BN_GENCB * cb);
88
89int gendh_main(int, char **);
90
91int
92gendh_main(int argc, char **argv)
93{
94 BN_GENCB cb;
95 DH *dh = NULL;
96 int ret = 1, num = DEFBITS;
97 int g = 2;
98 char *outfile = NULL;
99#ifndef OPENSSL_NO_ENGINE
100 char *engine = NULL;
101#endif
102 BIO *out = NULL;
103
104 BN_GENCB_set(&cb, dh_cb, bio_err);
105
106 argv++;
107 argc--;
108 for (;;) {
109 if (argc <= 0)
110 break;
111 if (strcmp(*argv, "-out") == 0) {
112 if (--argc < 1)
113 goto bad;
114 outfile = *(++argv);
115 } else if (strcmp(*argv, "-2") == 0)
116 g = 2;
117 /*
118 * else if (strcmp(*argv,"-3") == 0) g=3;
119 */
120 else if (strcmp(*argv, "-5") == 0)
121 g = 5;
122#ifndef OPENSSL_NO_ENGINE
123 else if (strcmp(*argv, "-engine") == 0) {
124 if (--argc < 1)
125 goto bad;
126 engine = *(++argv);
127 }
128#endif
129 else
130 break;
131 argv++;
132 argc--;
133 }
134 if ((argc >= 1) && ((sscanf(*argv, "%d", &num) == 0) || (num < 0))) {
135bad:
136 BIO_printf(bio_err, "usage: gendh [args] [numbits]\n");
137 BIO_printf(bio_err, " -out file - output the key to 'file\n");
138 BIO_printf(bio_err, " -2 - use 2 as the generator value\n");
139 /*
140 * BIO_printf(bio_err," -3 - use 3 as the generator
141 * value\n");
142 */
143 BIO_printf(bio_err, " -5 - use 5 as the generator value\n");
144#ifndef OPENSSL_NO_ENGINE
145 BIO_printf(bio_err, " -engine e - use engine e, possibly a hardware device.\n");
146#endif
147 goto end;
148 }
149#ifndef OPENSSL_NO_ENGINE
150 setup_engine(bio_err, engine, 0);
151#endif
152
153 out = BIO_new(BIO_s_file());
154 if (out == NULL) {
155 ERR_print_errors(bio_err);
156 goto end;
157 }
158 if (outfile == NULL) {
159 BIO_set_fp(out, stdout, BIO_NOCLOSE);
160 } else {
161 if (BIO_write_filename(out, outfile) <= 0) {
162 perror(outfile);
163 goto end;
164 }
165 }
166
167 BIO_printf(bio_err, "Generating DH parameters, %d bit long safe prime, generator %d\n", num, g);
168 BIO_printf(bio_err, "This is going to take a long time\n");
169
170 if (((dh = DH_new()) == NULL) || !DH_generate_parameters_ex(dh, num, g, &cb))
171 goto end;
172
173 if (!PEM_write_bio_DHparams(out, dh))
174 goto end;
175 ret = 0;
176end:
177 if (ret != 0)
178 ERR_print_errors(bio_err);
179 if (out != NULL)
180 BIO_free_all(out);
181 if (dh != NULL)
182 DH_free(dh);
183
184 return (ret);
185}
186
187static int
188dh_cb(int p, int n, BN_GENCB * cb)
189{
190 char c = '*';
191
192 if (p == 0)
193 c = '.';
194 if (p == 1)
195 c = '+';
196 if (p == 2)
197 c = '*';
198 if (p == 3)
199 c = '\n';
200 BIO_write(cb->arg, &c, 1);
201 (void) BIO_flush(cb->arg);
202 return 1;
203}
204#endif
diff --git a/src/usr.bin/openssl/gendsa.c b/src/usr.bin/openssl/gendsa.c
new file mode 100644
index 0000000000..7c9f568830
--- /dev/null
+++ b/src/usr.bin/openssl/gendsa.c
@@ -0,0 +1,230 @@
1/* $OpenBSD: gendsa.c,v 1.1 2014/08/26 17:47:24 jsing 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 <openssl/opensslconf.h> /* for OPENSSL_NO_DSA */
60
61
62#include <sys/types.h>
63#include <sys/stat.h>
64
65#include <stdio.h>
66#include <string.h>
67
68#include "apps.h"
69
70#include <openssl/bio.h>
71#include <openssl/bn.h>
72#include <openssl/dsa.h>
73#include <openssl/err.h>
74#include <openssl/pem.h>
75#include <openssl/x509.h>
76
77#define DEFBITS 512
78
79int gendsa_main(int, char **);
80
81int
82gendsa_main(int argc, char **argv)
83{
84 DSA *dsa = NULL;
85 int ret = 1;
86 char *outfile = NULL;
87 char *dsaparams = NULL;
88 char *passargout = NULL, *passout = NULL;
89 BIO *out = NULL, *in = NULL;
90 const EVP_CIPHER *enc = NULL;
91#ifndef OPENSSL_NO_ENGINE
92 char *engine = NULL;
93#endif
94
95 argv++;
96 argc--;
97 for (;;) {
98 if (argc <= 0)
99 break;
100 if (strcmp(*argv, "-out") == 0) {
101 if (--argc < 1)
102 goto bad;
103 outfile = *(++argv);
104 } else if (strcmp(*argv, "-passout") == 0) {
105 if (--argc < 1)
106 goto bad;
107 passargout = *(++argv);
108 }
109#ifndef OPENSSL_NO_ENGINE
110 else if (strcmp(*argv, "-engine") == 0) {
111 if (--argc < 1)
112 goto bad;
113 engine = *(++argv);
114 }
115#endif
116 else if (strcmp(*argv, "-") == 0)
117 goto bad;
118#ifndef OPENSSL_NO_DES
119 else if (strcmp(*argv, "-des") == 0)
120 enc = EVP_des_cbc();
121 else if (strcmp(*argv, "-des3") == 0)
122 enc = EVP_des_ede3_cbc();
123#endif
124#ifndef OPENSSL_NO_IDEA
125 else if (strcmp(*argv, "-idea") == 0)
126 enc = EVP_idea_cbc();
127#endif
128#ifndef OPENSSL_NO_AES
129 else if (strcmp(*argv, "-aes128") == 0)
130 enc = EVP_aes_128_cbc();
131 else if (strcmp(*argv, "-aes192") == 0)
132 enc = EVP_aes_192_cbc();
133 else if (strcmp(*argv, "-aes256") == 0)
134 enc = EVP_aes_256_cbc();
135#endif
136#ifndef OPENSSL_NO_CAMELLIA
137 else if (strcmp(*argv, "-camellia128") == 0)
138 enc = EVP_camellia_128_cbc();
139 else if (strcmp(*argv, "-camellia192") == 0)
140 enc = EVP_camellia_192_cbc();
141 else if (strcmp(*argv, "-camellia256") == 0)
142 enc = EVP_camellia_256_cbc();
143#endif
144 else if (**argv != '-' && dsaparams == NULL) {
145 dsaparams = *argv;
146 } else
147 goto bad;
148 argv++;
149 argc--;
150 }
151
152 if (dsaparams == NULL) {
153bad:
154 BIO_printf(bio_err, "usage: gendsa [args] dsaparam-file\n");
155 BIO_printf(bio_err, " -out file - output the key to 'file'\n");
156#ifndef OPENSSL_NO_DES
157 BIO_printf(bio_err, " -des - encrypt the generated key with DES in cbc mode\n");
158 BIO_printf(bio_err, " -des3 - encrypt the generated key with DES in ede cbc mode (168 bit key)\n");
159#endif
160#ifndef OPENSSL_NO_IDEA
161 BIO_printf(bio_err, " -idea - encrypt the generated key with IDEA in cbc mode\n");
162#endif
163#ifndef OPENSSL_NO_AES
164 BIO_printf(bio_err, " -aes128, -aes192, -aes256\n");
165 BIO_printf(bio_err, " encrypt PEM output with cbc aes\n");
166#endif
167#ifndef OPENSSL_NO_CAMELLIA
168 BIO_printf(bio_err, " -camellia128, -camellia192, -camellia256\n");
169 BIO_printf(bio_err, " encrypt PEM output with cbc camellia\n");
170#endif
171#ifndef OPENSSL_NO_ENGINE
172 BIO_printf(bio_err, " -engine e - use engine e, possibly a hardware device.\n");
173#endif
174 BIO_printf(bio_err, " dsaparam-file\n");
175 BIO_printf(bio_err, " - a DSA parameter file as generated by the dsaparam command\n");
176 goto end;
177 }
178#ifndef OPENSSL_NO_ENGINE
179 setup_engine(bio_err, engine, 0);
180#endif
181
182 if (!app_passwd(bio_err, NULL, passargout, NULL, &passout)) {
183 BIO_printf(bio_err, "Error getting password\n");
184 goto end;
185 }
186 in = BIO_new(BIO_s_file());
187 if (!(BIO_read_filename(in, dsaparams))) {
188 perror(dsaparams);
189 goto end;
190 }
191 if ((dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL)) == NULL) {
192 BIO_printf(bio_err, "unable to load DSA parameter file\n");
193 goto end;
194 }
195 BIO_free(in);
196 in = NULL;
197
198 out = BIO_new(BIO_s_file());
199 if (out == NULL)
200 goto end;
201
202 if (outfile == NULL) {
203 BIO_set_fp(out, stdout, BIO_NOCLOSE);
204 } else {
205 if (BIO_write_filename(out, outfile) <= 0) {
206 perror(outfile);
207 goto end;
208 }
209 }
210
211 BIO_printf(bio_err, "Generating DSA key, %d bits\n",
212 BN_num_bits(dsa->p));
213 if (!DSA_generate_key(dsa))
214 goto end;
215
216 if (!PEM_write_bio_DSAPrivateKey(out, dsa, enc, NULL, 0, NULL, passout))
217 goto end;
218 ret = 0;
219end:
220 if (ret != 0)
221 ERR_print_errors(bio_err);
222 BIO_free(in);
223 if (out != NULL)
224 BIO_free_all(out);
225 if (dsa != NULL)
226 DSA_free(dsa);
227 free(passout);
228
229 return (ret);
230}
diff --git a/src/usr.bin/openssl/genpkey.c b/src/usr.bin/openssl/genpkey.c
new file mode 100644
index 0000000000..02332f6682
--- /dev/null
+++ b/src/usr.bin/openssl/genpkey.c
@@ -0,0 +1,383 @@
1/* $OpenBSD: genpkey.c,v 1.1 2014/08/26 17:47:24 jsing Exp $ */
2/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3 * project 2006
4 */
5/* ====================================================================
6 * Copyright (c) 2006 The OpenSSL Project. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
19 *
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24 *
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * licensing@OpenSSL.org.
29 *
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
33 *
34 * 6. Redistributions of any form whatsoever must retain the following
35 * acknowledgment:
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
52 *
53 * This product includes cryptographic software written by Eric Young
54 * (eay@cryptsoft.com). This product includes software written by Tim
55 * Hudson (tjh@cryptsoft.com).
56 *
57 */
58
59#include <stdio.h>
60#include <string.h>
61
62#include "apps.h"
63
64#include <openssl/err.h>
65#include <openssl/evp.h>
66#include <openssl/pem.h>
67
68#ifndef OPENSSL_NO_ENGINE
69#include <openssl/engine.h>
70#endif
71
72static int
73init_keygen_file(BIO * err, EVP_PKEY_CTX ** pctx, const char *file,
74 ENGINE * e);
75static int genpkey_cb(EVP_PKEY_CTX * ctx);
76
77
78int genpkey_main(int, char **);
79
80int
81genpkey_main(int argc, char **argv)
82{
83 ENGINE *e = NULL;
84 char **args, *outfile = NULL;
85 char *passarg = NULL;
86 BIO *in = NULL, *out = NULL;
87 const EVP_CIPHER *cipher = NULL;
88 int outformat;
89 int text = 0;
90 EVP_PKEY *pkey = NULL;
91 EVP_PKEY_CTX *ctx = NULL;
92 char *pass = NULL;
93 int badarg = 0;
94 int ret = 1, rv;
95
96 int do_param = 0;
97
98 outformat = FORMAT_PEM;
99
100 ERR_load_crypto_strings();
101 OpenSSL_add_all_algorithms();
102 args = argv + 1;
103 while (!badarg && *args && *args[0] == '-') {
104 if (!strcmp(*args, "-outform")) {
105 if (args[1]) {
106 args++;
107 outformat = str2fmt(*args);
108 } else
109 badarg = 1;
110 } else if (!strcmp(*args, "-pass")) {
111 if (!args[1])
112 goto bad;
113 passarg = *(++args);
114 }
115#ifndef OPENSSL_NO_ENGINE
116 else if (strcmp(*args, "-engine") == 0) {
117 if (!args[1])
118 goto bad;
119 e = setup_engine(bio_err, *(++args), 0);
120 }
121#endif
122 else if (!strcmp(*args, "-paramfile")) {
123 if (!args[1])
124 goto bad;
125 args++;
126 if (do_param == 1)
127 goto bad;
128 if (!init_keygen_file(bio_err, &ctx, *args, e))
129 goto end;
130 } else if (!strcmp(*args, "-out")) {
131 if (args[1]) {
132 args++;
133 outfile = *args;
134 } else
135 badarg = 1;
136 } else if (strcmp(*args, "-algorithm") == 0) {
137 if (!args[1])
138 goto bad;
139 if (!init_gen_str(bio_err, &ctx, *(++args), e, do_param))
140 goto end;
141 } else if (strcmp(*args, "-pkeyopt") == 0) {
142 if (!args[1])
143 goto bad;
144 if (!ctx) {
145 BIO_puts(bio_err, "No keytype specified\n");
146 goto bad;
147 } else if (pkey_ctrl_string(ctx, *(++args)) <= 0) {
148 BIO_puts(bio_err, "parameter setting error\n");
149 ERR_print_errors(bio_err);
150 goto end;
151 }
152 } else if (strcmp(*args, "-genparam") == 0) {
153 if (ctx)
154 goto bad;
155 do_param = 1;
156 } else if (strcmp(*args, "-text") == 0)
157 text = 1;
158 else {
159 cipher = EVP_get_cipherbyname(*args + 1);
160 if (!cipher) {
161 BIO_printf(bio_err, "Unknown cipher %s\n",
162 *args + 1);
163 badarg = 1;
164 }
165 if (do_param == 1)
166 badarg = 1;
167 }
168 args++;
169 }
170
171 if (!ctx)
172 badarg = 1;
173
174 if (badarg) {
175bad:
176 BIO_printf(bio_err, "Usage: genpkey [options]\n");
177 BIO_printf(bio_err, "where options may be\n");
178 BIO_printf(bio_err, "-out file output file\n");
179 BIO_printf(bio_err, "-outform X output format (DER or PEM)\n");
180 BIO_printf(bio_err, "-pass arg output file pass phrase source\n");
181 BIO_printf(bio_err, "-<cipher> use cipher <cipher> to encrypt the key\n");
182#ifndef OPENSSL_NO_ENGINE
183 BIO_printf(bio_err, "-engine e use engine e, possibly a hardware device.\n");
184#endif
185 BIO_printf(bio_err, "-paramfile file parameters file\n");
186 BIO_printf(bio_err, "-algorithm alg the public key algorithm\n");
187 BIO_printf(bio_err, "-pkeyopt opt:value set the public key algorithm option <opt>\n"
188 " to value <value>\n");
189 BIO_printf(bio_err, "-genparam generate parameters, not key\n");
190 BIO_printf(bio_err, "-text print the in text\n");
191 BIO_printf(bio_err, "NB: options order may be important! See the manual page.\n");
192 goto end;
193 }
194 if (!app_passwd(bio_err, passarg, NULL, &pass, NULL)) {
195 BIO_puts(bio_err, "Error getting password\n");
196 goto end;
197 }
198 if (outfile) {
199 if (!(out = BIO_new_file(outfile, "wb"))) {
200 BIO_printf(bio_err,
201 "Can't open output file %s\n", outfile);
202 goto end;
203 }
204 } else {
205 out = BIO_new_fp(stdout, BIO_NOCLOSE);
206 }
207
208 EVP_PKEY_CTX_set_cb(ctx, genpkey_cb);
209 EVP_PKEY_CTX_set_app_data(ctx, bio_err);
210
211 if (do_param) {
212 if (EVP_PKEY_paramgen(ctx, &pkey) <= 0) {
213 BIO_puts(bio_err, "Error generating parameters\n");
214 ERR_print_errors(bio_err);
215 goto end;
216 }
217 } else {
218 if (EVP_PKEY_keygen(ctx, &pkey) <= 0) {
219 BIO_puts(bio_err, "Error generating key\n");
220 ERR_print_errors(bio_err);
221 goto end;
222 }
223 }
224
225 if (do_param)
226 rv = PEM_write_bio_Parameters(out, pkey);
227 else if (outformat == FORMAT_PEM)
228 rv = PEM_write_bio_PrivateKey(out, pkey, cipher, NULL, 0,
229 NULL, pass);
230 else if (outformat == FORMAT_ASN1)
231 rv = i2d_PrivateKey_bio(out, pkey);
232 else {
233 BIO_printf(bio_err, "Bad format specified for key\n");
234 goto end;
235 }
236
237 if (rv <= 0) {
238 BIO_puts(bio_err, "Error writing key\n");
239 ERR_print_errors(bio_err);
240 }
241 if (text) {
242 if (do_param)
243 rv = EVP_PKEY_print_params(out, pkey, 0, NULL);
244 else
245 rv = EVP_PKEY_print_private(out, pkey, 0, NULL);
246
247 if (rv <= 0) {
248 BIO_puts(bio_err, "Error printing key\n");
249 ERR_print_errors(bio_err);
250 }
251 }
252 ret = 0;
253
254end:
255 if (pkey)
256 EVP_PKEY_free(pkey);
257 if (ctx)
258 EVP_PKEY_CTX_free(ctx);
259 if (out)
260 BIO_free_all(out);
261 BIO_free(in);
262 free(pass);
263
264 return ret;
265}
266
267static int
268init_keygen_file(BIO * err, EVP_PKEY_CTX ** pctx,
269 const char *file, ENGINE * e)
270{
271 BIO *pbio;
272 EVP_PKEY *pkey = NULL;
273 EVP_PKEY_CTX *ctx = NULL;
274 if (*pctx) {
275 BIO_puts(err, "Parameters already set!\n");
276 return 0;
277 }
278 pbio = BIO_new_file(file, "r");
279 if (!pbio) {
280 BIO_printf(err, "Can't open parameter file %s\n", file);
281 return 0;
282 }
283 pkey = PEM_read_bio_Parameters(pbio, NULL);
284 BIO_free(pbio);
285
286 if (!pkey) {
287 BIO_printf(bio_err, "Error reading parameter file %s\n", file);
288 return 0;
289 }
290 ctx = EVP_PKEY_CTX_new(pkey, e);
291 if (!ctx)
292 goto err;
293 if (EVP_PKEY_keygen_init(ctx) <= 0)
294 goto err;
295 EVP_PKEY_free(pkey);
296 *pctx = ctx;
297 return 1;
298
299err:
300 BIO_puts(err, "Error initializing context\n");
301 ERR_print_errors(err);
302 if (ctx)
303 EVP_PKEY_CTX_free(ctx);
304 if (pkey)
305 EVP_PKEY_free(pkey);
306 return 0;
307
308}
309
310int
311init_gen_str(BIO * err, EVP_PKEY_CTX ** pctx,
312 const char *algname, ENGINE * e, int do_param)
313{
314 EVP_PKEY_CTX *ctx = NULL;
315 const EVP_PKEY_ASN1_METHOD *ameth;
316 ENGINE *tmpeng = NULL;
317 int pkey_id;
318
319 if (*pctx) {
320 BIO_puts(err, "Algorithm already set!\n");
321 return 0;
322 }
323 ameth = EVP_PKEY_asn1_find_str(&tmpeng, algname, -1);
324
325#ifndef OPENSSL_NO_ENGINE
326 if (!ameth && e)
327 ameth = ENGINE_get_pkey_asn1_meth_str(e, algname, -1);
328#endif
329
330 if (!ameth) {
331 BIO_printf(bio_err, "Algorithm %s not found\n", algname);
332 return 0;
333 }
334 ERR_clear_error();
335
336 EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL, ameth);
337#ifndef OPENSSL_NO_ENGINE
338 if (tmpeng)
339 ENGINE_finish(tmpeng);
340#endif
341 ctx = EVP_PKEY_CTX_new_id(pkey_id, e);
342
343 if (!ctx)
344 goto err;
345 if (do_param) {
346 if (EVP_PKEY_paramgen_init(ctx) <= 0)
347 goto err;
348 } else {
349 if (EVP_PKEY_keygen_init(ctx) <= 0)
350 goto err;
351 }
352
353 *pctx = ctx;
354 return 1;
355
356err:
357 BIO_printf(err, "Error initializing %s context\n", algname);
358 ERR_print_errors(err);
359 if (ctx)
360 EVP_PKEY_CTX_free(ctx);
361 return 0;
362
363}
364
365static int
366genpkey_cb(EVP_PKEY_CTX * ctx)
367{
368 char c = '*';
369 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
370 int p;
371 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
372 if (p == 0)
373 c = '.';
374 if (p == 1)
375 c = '+';
376 if (p == 2)
377 c = '*';
378 if (p == 3)
379 c = '\n';
380 BIO_write(b, &c, 1);
381 (void) BIO_flush(b);
382 return 1;
383}
diff --git a/src/usr.bin/openssl/genrsa.c b/src/usr.bin/openssl/genrsa.c
new file mode 100644
index 0000000000..7844fb815f
--- /dev/null
+++ b/src/usr.bin/openssl/genrsa.c
@@ -0,0 +1,286 @@
1/* $OpenBSD: genrsa.c,v 1.1 2014/08/26 17:47:24 jsing 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 <openssl/opensslconf.h>
60
61/* Until the key-gen callbacks are modified to use newer prototypes, we allow
62 * deprecated functions for openssl-internal code */
63#ifdef OPENSSL_NO_DEPRECATED
64#undef OPENSSL_NO_DEPRECATED
65#endif
66
67
68#include <sys/types.h>
69#include <sys/stat.h>
70
71#include <stdio.h>
72#include <string.h>
73
74#include "apps.h"
75
76#include <openssl/bio.h>
77#include <openssl/bn.h>
78#include <openssl/err.h>
79#include <openssl/evp.h>
80#include <openssl/pem.h>
81#include <openssl/rand.h>
82#include <openssl/rsa.h>
83#include <openssl/x509.h>
84
85#define DEFBITS 2048
86
87static int genrsa_cb(int p, int n, BN_GENCB * cb);
88
89int genrsa_main(int, char **);
90
91int
92genrsa_main(int argc, char **argv)
93{
94 BN_GENCB cb;
95#ifndef OPENSSL_NO_ENGINE
96 ENGINE *e = NULL;
97#endif
98 int ret = 1;
99 int i, num = DEFBITS;
100 long l;
101 const EVP_CIPHER *enc = NULL;
102 unsigned long f4 = RSA_F4;
103 char *outfile = NULL;
104 char *passargout = NULL, *passout = NULL;
105#ifndef OPENSSL_NO_ENGINE
106 char *engine = NULL;
107#endif
108 BIO *out = NULL;
109 BIGNUM *bn = BN_new();
110 RSA *rsa = NULL;
111
112 if (!bn)
113 goto err;
114
115 BN_GENCB_set(&cb, genrsa_cb, bio_err);
116
117 if ((out = BIO_new(BIO_s_file())) == NULL) {
118 BIO_printf(bio_err, "unable to create BIO for output\n");
119 goto err;
120 }
121 argv++;
122 argc--;
123 for (;;) {
124 if (argc <= 0)
125 break;
126 if (strcmp(*argv, "-out") == 0) {
127 if (--argc < 1)
128 goto bad;
129 outfile = *(++argv);
130 } else if (strcmp(*argv, "-3") == 0)
131 f4 = 3;
132 else if (strcmp(*argv, "-F4") == 0 || strcmp(*argv, "-f4") == 0)
133 f4 = RSA_F4;
134#ifndef OPENSSL_NO_ENGINE
135 else if (strcmp(*argv, "-engine") == 0) {
136 if (--argc < 1)
137 goto bad;
138 engine = *(++argv);
139 }
140#endif
141#ifndef OPENSSL_NO_DES
142 else if (strcmp(*argv, "-des") == 0)
143 enc = EVP_des_cbc();
144 else if (strcmp(*argv, "-des3") == 0)
145 enc = EVP_des_ede3_cbc();
146#endif
147#ifndef OPENSSL_NO_IDEA
148 else if (strcmp(*argv, "-idea") == 0)
149 enc = EVP_idea_cbc();
150#endif
151#ifndef OPENSSL_NO_AES
152 else if (strcmp(*argv, "-aes128") == 0)
153 enc = EVP_aes_128_cbc();
154 else if (strcmp(*argv, "-aes192") == 0)
155 enc = EVP_aes_192_cbc();
156 else if (strcmp(*argv, "-aes256") == 0)
157 enc = EVP_aes_256_cbc();
158#endif
159#ifndef OPENSSL_NO_CAMELLIA
160 else if (strcmp(*argv, "-camellia128") == 0)
161 enc = EVP_camellia_128_cbc();
162 else if (strcmp(*argv, "-camellia192") == 0)
163 enc = EVP_camellia_192_cbc();
164 else if (strcmp(*argv, "-camellia256") == 0)
165 enc = EVP_camellia_256_cbc();
166#endif
167 else if (strcmp(*argv, "-passout") == 0) {
168 if (--argc < 1)
169 goto bad;
170 passargout = *(++argv);
171 } else
172 break;
173 argv++;
174 argc--;
175 }
176 if ((argc >= 1) && ((sscanf(*argv, "%d", &num) == 0) || (num < 0))) {
177bad:
178 BIO_printf(bio_err, "usage: genrsa [args] [numbits]\n");
179 BIO_printf(bio_err, " -des encrypt the generated key with DES in cbc mode\n");
180 BIO_printf(bio_err, " -des3 encrypt the generated key with DES in ede cbc mode (168 bit key)\n");
181#ifndef OPENSSL_NO_IDEA
182 BIO_printf(bio_err, " -idea encrypt the generated key with IDEA in cbc mode\n");
183#endif
184#ifndef OPENSSL_NO_AES
185 BIO_printf(bio_err, " -aes128, -aes192, -aes256\n");
186 BIO_printf(bio_err, " encrypt PEM output with cbc aes\n");
187#endif
188#ifndef OPENSSL_NO_CAMELLIA
189 BIO_printf(bio_err, " -camellia128, -camellia192, -camellia256\n");
190 BIO_printf(bio_err, " encrypt PEM output with cbc camellia\n");
191#endif
192 BIO_printf(bio_err, " -out file output the key to 'file\n");
193 BIO_printf(bio_err, " -passout arg output file pass phrase source\n");
194 BIO_printf(bio_err, " -f4 use F4 (0x10001) for the E value\n");
195 BIO_printf(bio_err, " -3 use 3 for the E value\n");
196#ifndef OPENSSL_NO_ENGINE
197 BIO_printf(bio_err, " -engine e use engine e, possibly a hardware device.\n");
198#endif
199 goto err;
200 }
201 ERR_load_crypto_strings();
202
203 if (!app_passwd(bio_err, NULL, passargout, NULL, &passout)) {
204 BIO_printf(bio_err, "Error getting password\n");
205 goto err;
206 }
207#ifndef OPENSSL_NO_ENGINE
208 e = setup_engine(bio_err, engine, 0);
209#endif
210
211 if (outfile == NULL) {
212 BIO_set_fp(out, stdout, BIO_NOCLOSE);
213 } else {
214 if (BIO_write_filename(out, outfile) <= 0) {
215 perror(outfile);
216 goto err;
217 }
218 }
219
220 BIO_printf(bio_err, "Generating RSA private key, %d bit long modulus\n",
221 num);
222#ifdef OPENSSL_NO_ENGINE
223 rsa = RSA_new();
224#else
225 rsa = RSA_new_method(e);
226#endif
227 if (!rsa)
228 goto err;
229
230 if (!BN_set_word(bn, f4) || !RSA_generate_key_ex(rsa, num, bn, &cb))
231 goto err;
232
233 /*
234 * We need to do the following for when the base number size is <
235 * long, esp windows 3.1 :-(.
236 */
237 l = 0L;
238 for (i = 0; i < rsa->e->top; i++) {
239#ifndef _LP64
240 l <<= BN_BITS4;
241 l <<= BN_BITS4;
242#endif
243 l += rsa->e->d[i];
244 }
245 BIO_printf(bio_err, "e is %ld (0x%lX)\n", l, l);
246 {
247 PW_CB_DATA cb_data;
248 cb_data.password = passout;
249 cb_data.prompt_info = outfile;
250 if (!PEM_write_bio_RSAPrivateKey(out, rsa, enc, NULL, 0,
251 password_callback, &cb_data))
252 goto err;
253 }
254
255 ret = 0;
256err:
257 if (bn)
258 BN_free(bn);
259 if (rsa)
260 RSA_free(rsa);
261 if (out)
262 BIO_free_all(out);
263 free(passout);
264 if (ret != 0)
265 ERR_print_errors(bio_err);
266
267 return (ret);
268}
269
270static int
271genrsa_cb(int p, int n, BN_GENCB * cb)
272{
273 char c = '*';
274
275 if (p == 0)
276 c = '.';
277 if (p == 1)
278 c = '+';
279 if (p == 2)
280 c = '*';
281 if (p == 3)
282 c = '\n';
283 BIO_write(cb->arg, &c, 1);
284 (void) BIO_flush(cb->arg);
285 return 1;
286}
diff --git a/src/usr.bin/openssl/nseq.c b/src/usr.bin/openssl/nseq.c
new file mode 100644
index 0000000000..6c32f7c4b4
--- /dev/null
+++ b/src/usr.bin/openssl/nseq.c
@@ -0,0 +1,162 @@
1/* $OpenBSD: nseq.c,v 1.1 2014/08/26 17:47:24 jsing Exp $ */
2/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3 * project 1999.
4 */
5/* ====================================================================
6 * Copyright (c) 1999 The OpenSSL Project. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
19 *
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24 *
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * licensing@OpenSSL.org.
29 *
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
33 *
34 * 6. Redistributions of any form whatsoever must retain the following
35 * acknowledgment:
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
52 *
53 * This product includes cryptographic software written by Eric Young
54 * (eay@cryptsoft.com). This product includes software written by Tim
55 * Hudson (tjh@cryptsoft.com).
56 *
57 */
58
59#include <stdio.h>
60#include <string.h>
61
62#include "apps.h"
63
64#include <openssl/err.h>
65#include <openssl/pem.h>
66
67int nseq_main(int, char **);
68
69int
70nseq_main(int argc, char **argv)
71{
72 char **args, *infile = NULL, *outfile = NULL;
73 BIO *in = NULL, *out = NULL;
74 int toseq = 0;
75 X509 *x509 = NULL;
76 NETSCAPE_CERT_SEQUENCE *seq = NULL;
77 int i, ret = 1;
78 int badarg = 0;
79
80 ERR_load_crypto_strings();
81
82 args = argv + 1;
83 while (!badarg && *args && *args[0] == '-') {
84 if (!strcmp(*args, "-toseq"))
85 toseq = 1;
86 else if (!strcmp(*args, "-in")) {
87 if (args[1]) {
88 args++;
89 infile = *args;
90 } else
91 badarg = 1;
92 } else if (!strcmp(*args, "-out")) {
93 if (args[1]) {
94 args++;
95 outfile = *args;
96 } else
97 badarg = 1;
98 } else
99 badarg = 1;
100 args++;
101 }
102
103 if (badarg) {
104 BIO_printf(bio_err, "Netscape certificate sequence utility\n");
105 BIO_printf(bio_err, "Usage nseq [options]\n");
106 BIO_printf(bio_err, "where options are\n");
107 BIO_printf(bio_err, "-in file input file\n");
108 BIO_printf(bio_err, "-out file output file\n");
109 BIO_printf(bio_err, "-toseq output NS Sequence file\n");
110 return (1);
111 }
112 if (infile) {
113 if (!(in = BIO_new_file(infile, "r"))) {
114 BIO_printf(bio_err,
115 "Can't open input file %s\n", infile);
116 goto end;
117 }
118 } else
119 in = BIO_new_fp(stdin, BIO_NOCLOSE);
120
121 if (outfile) {
122 if (!(out = BIO_new_file(outfile, "w"))) {
123 BIO_printf(bio_err,
124 "Can't open output file %s\n", outfile);
125 goto end;
126 }
127 } else {
128 out = BIO_new_fp(stdout, BIO_NOCLOSE);
129 }
130 if (toseq) {
131 seq = NETSCAPE_CERT_SEQUENCE_new();
132 seq->certs = sk_X509_new_null();
133 while ((x509 = PEM_read_bio_X509(in, NULL, NULL, NULL)))
134 sk_X509_push(seq->certs, x509);
135
136 if (!sk_X509_num(seq->certs)) {
137 BIO_printf(bio_err, "Error reading certs file %s\n", infile);
138 ERR_print_errors(bio_err);
139 goto end;
140 }
141 PEM_write_bio_NETSCAPE_CERT_SEQUENCE(out, seq);
142 ret = 0;
143 goto end;
144 }
145 if (!(seq = PEM_read_bio_NETSCAPE_CERT_SEQUENCE(in, NULL, NULL, NULL))) {
146 BIO_printf(bio_err, "Error reading sequence file %s\n", infile);
147 ERR_print_errors(bio_err);
148 goto end;
149 }
150 for (i = 0; i < sk_X509_num(seq->certs); i++) {
151 x509 = sk_X509_value(seq->certs, i);
152 dump_cert_text(out, x509);
153 PEM_write_bio_X509(out, x509);
154 }
155 ret = 0;
156end:
157 BIO_free(in);
158 BIO_free_all(out);
159 NETSCAPE_CERT_SEQUENCE_free(seq);
160
161 return (ret);
162}
diff --git a/src/usr.bin/openssl/ocsp.c b/src/usr.bin/openssl/ocsp.c
new file mode 100644
index 0000000000..bdc224d8bc
--- /dev/null
+++ b/src/usr.bin/openssl/ocsp.c
@@ -0,0 +1,1217 @@
1/* $OpenBSD: ocsp.c,v 1.1 2014/08/26 17:47:24 jsing Exp $ */
2/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3 * project 2000.
4 */
5/* ====================================================================
6 * Copyright (c) 1999 The OpenSSL Project. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
19 *
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24 *
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * licensing@OpenSSL.org.
29 *
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
33 *
34 * 6. Redistributions of any form whatsoever must retain the following
35 * acknowledgment:
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
52 *
53 * This product includes cryptographic software written by Eric Young
54 * (eay@cryptsoft.com). This product includes software written by Tim
55 * Hudson (tjh@cryptsoft.com).
56 *
57 */
58#ifndef OPENSSL_NO_OCSP
59
60#include <sys/select.h>
61
62#include <stdio.h>
63#include <stdlib.h>
64#include <limits.h>
65#include <string.h>
66#include <time.h>
67
68/* Needs to be included before the openssl headers! */
69#include "apps.h"
70
71#include <openssl/bn.h>
72#include <openssl/crypto.h>
73#include <openssl/err.h>
74#include <openssl/evp.h>
75#include <openssl/ssl.h>
76#include <openssl/x509v3.h>
77
78/* Maximum leeway in validity period: default 5 minutes */
79#define MAX_VALIDITY_PERIOD (5 * 60)
80
81static int
82add_ocsp_cert(OCSP_REQUEST ** req, X509 * cert, const EVP_MD * cert_id_md, X509 * issuer,
83 STACK_OF(OCSP_CERTID) * ids);
84static int add_ocsp_serial(OCSP_REQUEST ** req, char *serial, const EVP_MD * cert_id_md, X509 * issuer,
85 STACK_OF(OCSP_CERTID) * ids);
86static int print_ocsp_summary(BIO * out, OCSP_BASICRESP * bs, OCSP_REQUEST * req,
87 STACK_OF(OPENSSL_STRING) * names,
88 STACK_OF(OCSP_CERTID) * ids, long nsec,
89 long maxage);
90
91static int make_ocsp_response(OCSP_RESPONSE ** resp, OCSP_REQUEST * req, CA_DB * db,
92 X509 * ca, X509 * rcert, EVP_PKEY * rkey,
93 STACK_OF(X509) * rother, unsigned long flags,
94 int nmin, int ndays);
95
96static char **lookup_serial(CA_DB * db, ASN1_INTEGER * ser);
97static BIO *init_responder(char *port);
98static int do_responder(OCSP_REQUEST ** preq, BIO ** pcbio, BIO * acbio, char *port);
99static int send_ocsp_response(BIO * cbio, OCSP_RESPONSE * resp);
100static OCSP_RESPONSE *query_responder(BIO * err, BIO * cbio, char *path,
101 STACK_OF(CONF_VALUE) * headers,
102 OCSP_REQUEST * req, int req_timeout);
103
104
105int ocsp_main(int, char **);
106
107int
108ocsp_main(int argc, char **argv)
109{
110 ENGINE *e = NULL;
111 char **args;
112 char *host = NULL, *port = NULL, *path = "/";
113 char *reqin = NULL, *respin = NULL;
114 char *reqout = NULL, *respout = NULL;
115 char *signfile = NULL, *keyfile = NULL;
116 char *rsignfile = NULL, *rkeyfile = NULL;
117 char *outfile = NULL;
118 int add_nonce = 1, noverify = 0, use_ssl = -1;
119 STACK_OF(CONF_VALUE) * headers = NULL;
120 OCSP_REQUEST *req = NULL;
121 OCSP_RESPONSE *resp = NULL;
122 OCSP_BASICRESP *bs = NULL;
123 X509 *issuer = NULL, *cert = NULL;
124 X509 *signer = NULL, *rsigner = NULL;
125 EVP_PKEY *key = NULL, *rkey = NULL;
126 BIO *acbio = NULL, *cbio = NULL;
127 BIO *derbio = NULL;
128 BIO *out = NULL;
129 int req_timeout = -1;
130 int req_text = 0, resp_text = 0;
131 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
132 char *CAfile = NULL, *CApath = NULL;
133 X509_STORE *store = NULL;
134 STACK_OF(X509) * sign_other = NULL, *verify_other = NULL, *rother = NULL;
135 char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
136 unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
137 int ret = 1;
138 int accept_count = -1;
139 int badarg = 0;
140 int i;
141 int ignore_err = 0;
142 STACK_OF(OPENSSL_STRING) * reqnames = NULL;
143 STACK_OF(OCSP_CERTID) * ids = NULL;
144 X509 *rca_cert = NULL;
145 char *ridx_filename = NULL;
146 char *rca_filename = NULL;
147 CA_DB *rdb = NULL;
148 int nmin = 0, ndays = -1;
149 const EVP_MD *cert_id_md = NULL;
150 const char *errstr = NULL;
151
152 args = argv + 1;
153 reqnames = sk_OPENSSL_STRING_new_null();
154 ids = sk_OCSP_CERTID_new_null();
155 while (!badarg && *args && *args[0] == '-') {
156 if (!strcmp(*args, "-out")) {
157 if (args[1]) {
158 args++;
159 outfile = *args;
160 } else
161 badarg = 1;
162 } else if (!strcmp(*args, "-timeout")) {
163 if (args[1]) {
164 args++;
165 req_timeout = strtonum(*args, 0,
166 INT_MAX, &errstr);
167 if (errstr) {
168 BIO_printf(bio_err,
169 "Illegal timeout value %s: %s\n",
170 *args, errstr);
171 badarg = 1;
172 }
173 } else
174 badarg = 1;
175 } else if (!strcmp(*args, "-url")) {
176 if (args[1]) {
177 args++;
178 if (!OCSP_parse_url(*args, &host, &port, &path, &use_ssl)) {
179 BIO_printf(bio_err, "Error parsing URL\n");
180 badarg = 1;
181 }
182 } else
183 badarg = 1;
184 } else if (!strcmp(*args, "-host")) {
185 if (args[1]) {
186 args++;
187 host = *args;
188 } else
189 badarg = 1;
190 } else if (!strcmp(*args, "-port")) {
191 if (args[1]) {
192 args++;
193 port = *args;
194 } else
195 badarg = 1;
196 } else if (!strcmp(*args, "-header")) {
197 if (args[1] && args[2]) {
198 if (!X509V3_add_value(args[1], args[2], &headers))
199 goto end;
200 args += 2;
201 } else
202 badarg = 1;
203 } else if (!strcmp(*args, "-ignore_err"))
204 ignore_err = 1;
205 else if (!strcmp(*args, "-noverify"))
206 noverify = 1;
207 else if (!strcmp(*args, "-nonce"))
208 add_nonce = 2;
209 else if (!strcmp(*args, "-no_nonce"))
210 add_nonce = 0;
211 else if (!strcmp(*args, "-resp_no_certs"))
212 rflags |= OCSP_NOCERTS;
213 else if (!strcmp(*args, "-resp_key_id"))
214 rflags |= OCSP_RESPID_KEY;
215 else if (!strcmp(*args, "-no_certs"))
216 sign_flags |= OCSP_NOCERTS;
217 else if (!strcmp(*args, "-no_signature_verify"))
218 verify_flags |= OCSP_NOSIGS;
219 else if (!strcmp(*args, "-no_cert_verify"))
220 verify_flags |= OCSP_NOVERIFY;
221 else if (!strcmp(*args, "-no_chain"))
222 verify_flags |= OCSP_NOCHAIN;
223 else if (!strcmp(*args, "-no_cert_checks"))
224 verify_flags |= OCSP_NOCHECKS;
225 else if (!strcmp(*args, "-no_explicit"))
226 verify_flags |= OCSP_NOEXPLICIT;
227 else if (!strcmp(*args, "-trust_other"))
228 verify_flags |= OCSP_TRUSTOTHER;
229 else if (!strcmp(*args, "-no_intern"))
230 verify_flags |= OCSP_NOINTERN;
231 else if (!strcmp(*args, "-text")) {
232 req_text = 1;
233 resp_text = 1;
234 } else if (!strcmp(*args, "-req_text"))
235 req_text = 1;
236 else if (!strcmp(*args, "-resp_text"))
237 resp_text = 1;
238 else if (!strcmp(*args, "-reqin")) {
239 if (args[1]) {
240 args++;
241 reqin = *args;
242 } else
243 badarg = 1;
244 } else if (!strcmp(*args, "-respin")) {
245 if (args[1]) {
246 args++;
247 respin = *args;
248 } else
249 badarg = 1;
250 } else if (!strcmp(*args, "-signer")) {
251 if (args[1]) {
252 args++;
253 signfile = *args;
254 } else
255 badarg = 1;
256 } else if (!strcmp(*args, "-VAfile")) {
257 if (args[1]) {
258 args++;
259 verify_certfile = *args;
260 verify_flags |= OCSP_TRUSTOTHER;
261 } else
262 badarg = 1;
263 } else if (!strcmp(*args, "-sign_other")) {
264 if (args[1]) {
265 args++;
266 sign_certfile = *args;
267 } else
268 badarg = 1;
269 } else if (!strcmp(*args, "-verify_other")) {
270 if (args[1]) {
271 args++;
272 verify_certfile = *args;
273 } else
274 badarg = 1;
275 } else if (!strcmp(*args, "-CAfile")) {
276 if (args[1]) {
277 args++;
278 CAfile = *args;
279 } else
280 badarg = 1;
281 } else if (!strcmp(*args, "-CApath")) {
282 if (args[1]) {
283 args++;
284 CApath = *args;
285 } else
286 badarg = 1;
287 } else if (!strcmp(*args, "-validity_period")) {
288 if (args[1]) {
289 args++;
290 nsec = strtonum(*args, 0, LONG_MAX, &errstr);
291 if (errstr) {
292 BIO_printf(bio_err,
293 "Illegal validity period %s: %s\n",
294 *args, errstr);
295 badarg = 1;
296 }
297 } else
298 badarg = 1;
299 } else if (!strcmp(*args, "-status_age")) {
300 if (args[1]) {
301 args++;
302 maxage = strtonum(*args, 0, LONG_MAX, &errstr);
303 if (errstr) {
304 BIO_printf(bio_err,
305 "Illegal validity age %s: %s\n",
306 *args, errstr);
307 badarg = 1;
308 }
309 } else
310 badarg = 1;
311 } else if (!strcmp(*args, "-signkey")) {
312 if (args[1]) {
313 args++;
314 keyfile = *args;
315 } else
316 badarg = 1;
317 } else if (!strcmp(*args, "-reqout")) {
318 if (args[1]) {
319 args++;
320 reqout = *args;
321 } else
322 badarg = 1;
323 } else if (!strcmp(*args, "-respout")) {
324 if (args[1]) {
325 args++;
326 respout = *args;
327 } else
328 badarg = 1;
329 } else if (!strcmp(*args, "-path")) {
330 if (args[1]) {
331 args++;
332 path = *args;
333 } else
334 badarg = 1;
335 } else if (!strcmp(*args, "-issuer")) {
336 if (args[1]) {
337 args++;
338 X509_free(issuer);
339 issuer = load_cert(bio_err, *args, FORMAT_PEM,
340 NULL, e, "issuer certificate");
341 if (!issuer)
342 goto end;
343 } else
344 badarg = 1;
345 } else if (!strcmp(*args, "-cert")) {
346 if (args[1]) {
347 args++;
348 X509_free(cert);
349 cert = load_cert(bio_err, *args, FORMAT_PEM,
350 NULL, e, "certificate");
351 if (!cert)
352 goto end;
353 if (!cert_id_md)
354 cert_id_md = EVP_sha1();
355 if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
356 goto end;
357 if (!sk_OPENSSL_STRING_push(reqnames, *args))
358 goto end;
359 } else
360 badarg = 1;
361 } else if (!strcmp(*args, "-serial")) {
362 if (args[1]) {
363 args++;
364 if (!cert_id_md)
365 cert_id_md = EVP_sha1();
366 if (!add_ocsp_serial(&req, *args, cert_id_md, issuer, ids))
367 goto end;
368 if (!sk_OPENSSL_STRING_push(reqnames, *args))
369 goto end;
370 } else
371 badarg = 1;
372 } else if (!strcmp(*args, "-index")) {
373 if (args[1]) {
374 args++;
375 ridx_filename = *args;
376 } else
377 badarg = 1;
378 } else if (!strcmp(*args, "-CA")) {
379 if (args[1]) {
380 args++;
381 rca_filename = *args;
382 } else
383 badarg = 1;
384 } else if (!strcmp(*args, "-nmin")) {
385 if (args[1]) {
386 args++;
387 nmin = strtonum(*args, 0, INT_MAX, &errstr);
388 if (errstr) {
389 BIO_printf(bio_err,
390 "Illegal update period %s: %s\n",
391 *args, errstr);
392 badarg = 1;
393 }
394 }
395 if (ndays == -1)
396 ndays = 0;
397 else
398 badarg = 1;
399 } else if (!strcmp(*args, "-nrequest")) {
400 if (args[1]) {
401 args++;
402 accept_count = strtonum(*args, 0, INT_MAX, &errstr);
403 if (errstr) {
404 BIO_printf(bio_err,
405 "Illegal accept count %s: %s\n",
406 *args, errstr);
407 badarg = 1;
408 }
409 } else
410 badarg = 1;
411 } else if (!strcmp(*args, "-ndays")) {
412 if (args[1]) {
413 args++;
414 ndays = strtonum(*args, 0, INT_MAX, &errstr);
415 if (errstr) {
416 BIO_printf(bio_err,
417 "Illegal update period %s: %s\n",
418 *args, errstr);
419 badarg = 1;
420 }
421 } else
422 badarg = 1;
423 } else if (!strcmp(*args, "-rsigner")) {
424 if (args[1]) {
425 args++;
426 rsignfile = *args;
427 } else
428 badarg = 1;
429 } else if (!strcmp(*args, "-rkey")) {
430 if (args[1]) {
431 args++;
432 rkeyfile = *args;
433 } else
434 badarg = 1;
435 } else if (!strcmp(*args, "-rother")) {
436 if (args[1]) {
437 args++;
438 rcertfile = *args;
439 } else
440 badarg = 1;
441 } else if ((cert_id_md = EVP_get_digestbyname((*args) + 1)) == NULL) {
442 badarg = 1;
443 }
444 args++;
445 }
446
447 /* Have we anything to do? */
448 if (!req && !reqin && !respin && !(port && ridx_filename))
449 badarg = 1;
450
451 if (badarg) {
452 BIO_printf(bio_err, "OCSP utility\n");
453 BIO_printf(bio_err, "Usage ocsp [options]\n");
454 BIO_printf(bio_err, "where options are\n");
455 BIO_printf(bio_err, "-out file output filename\n");
456 BIO_printf(bio_err, "-issuer file issuer certificate\n");
457 BIO_printf(bio_err, "-cert file certificate to check\n");
458 BIO_printf(bio_err, "-serial n serial number to check\n");
459 BIO_printf(bio_err, "-signer file certificate to sign OCSP request with\n");
460 BIO_printf(bio_err, "-signkey file private key to sign OCSP request with\n");
461 BIO_printf(bio_err, "-sign_other file additional certificates to include in signed request\n");
462 BIO_printf(bio_err, "-no_certs don't include any certificates in signed request\n");
463 BIO_printf(bio_err, "-req_text print text form of request\n");
464 BIO_printf(bio_err, "-resp_text print text form of response\n");
465 BIO_printf(bio_err, "-text print text form of request and response\n");
466 BIO_printf(bio_err, "-reqout file write DER encoded OCSP request to \"file\"\n");
467 BIO_printf(bio_err, "-respout file write DER encoded OCSP reponse to \"file\"\n");
468 BIO_printf(bio_err, "-reqin file read DER encoded OCSP request from \"file\"\n");
469 BIO_printf(bio_err, "-respin file read DER encoded OCSP reponse from \"file\"\n");
470 BIO_printf(bio_err, "-nonce add OCSP nonce to request\n");
471 BIO_printf(bio_err, "-no_nonce don't add OCSP nonce to request\n");
472 BIO_printf(bio_err, "-url URL OCSP responder URL\n");
473 BIO_printf(bio_err, "-host host:n send OCSP request to host on port n\n");
474 BIO_printf(bio_err, "-path path to use in OCSP request\n");
475 BIO_printf(bio_err, "-CApath dir trusted certificates directory\n");
476 BIO_printf(bio_err, "-CAfile file trusted certificates file\n");
477 BIO_printf(bio_err, "-VAfile file validator certificates file\n");
478 BIO_printf(bio_err, "-validity_period n maximum validity discrepancy in seconds\n");
479 BIO_printf(bio_err, "-status_age n maximum status age in seconds\n");
480 BIO_printf(bio_err, "-noverify don't verify response at all\n");
481 BIO_printf(bio_err, "-verify_other file additional certificates to search for signer\n");
482 BIO_printf(bio_err, "-trust_other don't verify additional certificates\n");
483 BIO_printf(bio_err, "-no_intern don't search certificates contained in response for signer\n");
484 BIO_printf(bio_err, "-no_signature_verify don't check signature on response\n");
485 BIO_printf(bio_err, "-no_cert_verify don't check signing certificate\n");
486 BIO_printf(bio_err, "-no_chain don't chain verify response\n");
487 BIO_printf(bio_err, "-no_cert_checks don't do additional checks on signing certificate\n");
488 BIO_printf(bio_err, "-port num port to run responder on\n");
489 BIO_printf(bio_err, "-index file certificate status index file\n");
490 BIO_printf(bio_err, "-CA file CA certificate\n");
491 BIO_printf(bio_err, "-rsigner file responder certificate to sign responses with\n");
492 BIO_printf(bio_err, "-rkey file responder key to sign responses with\n");
493 BIO_printf(bio_err, "-rother file other certificates to include in response\n");
494 BIO_printf(bio_err, "-resp_no_certs don't include any certificates in response\n");
495 BIO_printf(bio_err, "-nmin n number of minutes before next update\n");
496 BIO_printf(bio_err, "-ndays n number of days before next update\n");
497 BIO_printf(bio_err, "-resp_key_id identify reponse by signing certificate key ID\n");
498 BIO_printf(bio_err, "-nrequest n number of requests to accept (default unlimited)\n");
499 BIO_printf(bio_err, "-<dgst alg> use specified digest in the request\n");
500 goto end;
501 }
502 if (outfile)
503 out = BIO_new_file(outfile, "w");
504 else
505 out = BIO_new_fp(stdout, BIO_NOCLOSE);
506
507 if (!out) {
508 BIO_printf(bio_err, "Error opening output file\n");
509 goto end;
510 }
511 if (!req && (add_nonce != 2))
512 add_nonce = 0;
513
514 if (!req && reqin) {
515 derbio = BIO_new_file(reqin, "rb");
516 if (!derbio) {
517 BIO_printf(bio_err, "Error Opening OCSP request file\n");
518 goto end;
519 }
520 req = d2i_OCSP_REQUEST_bio(derbio, NULL);
521 BIO_free(derbio);
522 if (!req) {
523 BIO_printf(bio_err, "Error reading OCSP request\n");
524 goto end;
525 }
526 }
527 if (!req && port) {
528 acbio = init_responder(port);
529 if (!acbio)
530 goto end;
531 }
532 if (rsignfile && !rdb) {
533 if (!rkeyfile)
534 rkeyfile = rsignfile;
535 rsigner = load_cert(bio_err, rsignfile, FORMAT_PEM,
536 NULL, e, "responder certificate");
537 if (!rsigner) {
538 BIO_printf(bio_err, "Error loading responder certificate\n");
539 goto end;
540 }
541 rca_cert = load_cert(bio_err, rca_filename, FORMAT_PEM,
542 NULL, e, "CA certificate");
543 if (rcertfile) {
544 rother = load_certs(bio_err, rcertfile, FORMAT_PEM,
545 NULL, e, "responder other certificates");
546 if (!rother)
547 goto end;
548 }
549 rkey = load_key(bio_err, rkeyfile, FORMAT_PEM, 0, NULL, NULL,
550 "responder private key");
551 if (!rkey)
552 goto end;
553 }
554 if (acbio)
555 BIO_printf(bio_err, "Waiting for OCSP client connections...\n");
556
557redo_accept:
558
559 if (acbio) {
560 if (!do_responder(&req, &cbio, acbio, port))
561 goto end;
562 if (!req) {
563 resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
564 send_ocsp_response(cbio, resp);
565 goto done_resp;
566 }
567 }
568 if (!req && (signfile || reqout || host || add_nonce || ridx_filename)) {
569 BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
570 goto end;
571 }
572 if (req && add_nonce)
573 OCSP_request_add1_nonce(req, NULL, -1);
574
575 if (signfile) {
576 if (!keyfile)
577 keyfile = signfile;
578 signer = load_cert(bio_err, signfile, FORMAT_PEM,
579 NULL, e, "signer certificate");
580 if (!signer) {
581 BIO_printf(bio_err, "Error loading signer certificate\n");
582 goto end;
583 }
584 if (sign_certfile) {
585 sign_other = load_certs(bio_err, sign_certfile, FORMAT_PEM,
586 NULL, e, "signer certificates");
587 if (!sign_other)
588 goto end;
589 }
590 key = load_key(bio_err, keyfile, FORMAT_PEM, 0, NULL, NULL,
591 "signer private key");
592 if (!key)
593 goto end;
594
595 if (!OCSP_request_sign(req, signer, key, NULL, sign_other, sign_flags)) {
596 BIO_printf(bio_err, "Error signing OCSP request\n");
597 goto end;
598 }
599 }
600 if (req_text && req)
601 OCSP_REQUEST_print(out, req, 0);
602
603 if (reqout) {
604 derbio = BIO_new_file(reqout, "wb");
605 if (!derbio) {
606 BIO_printf(bio_err, "Error opening file %s\n", reqout);
607 goto end;
608 }
609 i2d_OCSP_REQUEST_bio(derbio, req);
610 BIO_free(derbio);
611 }
612 if (ridx_filename && (!rkey || !rsigner || !rca_cert)) {
613 BIO_printf(bio_err, "Need a responder certificate, key and CA for this operation!\n");
614 goto end;
615 }
616 if (ridx_filename && !rdb) {
617 rdb = load_index(ridx_filename, NULL);
618 if (!rdb)
619 goto end;
620 if (!index_index(rdb))
621 goto end;
622 }
623 if (rdb) {
624 i = make_ocsp_response(&resp, req, rdb, rca_cert, rsigner, rkey, rother, rflags, nmin, ndays);
625 if (cbio)
626 send_ocsp_response(cbio, resp);
627 } else if (host) {
628 resp = process_responder(bio_err, req, host, path,
629 port, use_ssl, headers, req_timeout);
630 if (!resp)
631 goto end;
632 } else if (respin) {
633 derbio = BIO_new_file(respin, "rb");
634 if (!derbio) {
635 BIO_printf(bio_err, "Error Opening OCSP response file\n");
636 goto end;
637 }
638 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
639 BIO_free(derbio);
640 if (!resp) {
641 BIO_printf(bio_err, "Error reading OCSP response\n");
642 goto end;
643 }
644 } else {
645 ret = 0;
646 goto end;
647 }
648
649done_resp:
650
651 if (respout) {
652 derbio = BIO_new_file(respout, "wb");
653 if (!derbio) {
654 BIO_printf(bio_err, "Error opening file %s\n", respout);
655 goto end;
656 }
657 i2d_OCSP_RESPONSE_bio(derbio, resp);
658 BIO_free(derbio);
659 }
660 i = OCSP_response_status(resp);
661
662 if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
663 BIO_printf(out, "Responder Error: %s (%d)\n",
664 OCSP_response_status_str(i), i);
665 if (ignore_err)
666 goto redo_accept;
667 ret = 0;
668 goto end;
669 }
670 if (resp_text)
671 OCSP_RESPONSE_print(out, resp, 0);
672
673 /* If running as responder don't verify our own response */
674 if (cbio) {
675 if (accept_count > 0)
676 accept_count--;
677 /* Redo if more connections needed */
678 if (accept_count) {
679 BIO_free_all(cbio);
680 cbio = NULL;
681 OCSP_REQUEST_free(req);
682 req = NULL;
683 OCSP_RESPONSE_free(resp);
684 resp = NULL;
685 goto redo_accept;
686 }
687 goto end;
688 }
689 if (!store)
690 store = setup_verify(bio_err, CAfile, CApath);
691 if (!store)
692 goto end;
693 if (verify_certfile) {
694 verify_other = load_certs(bio_err, verify_certfile, FORMAT_PEM,
695 NULL, e, "validator certificate");
696 if (!verify_other)
697 goto end;
698 }
699 bs = OCSP_response_get1_basic(resp);
700
701 if (!bs) {
702 BIO_printf(bio_err, "Error parsing response\n");
703 goto end;
704 }
705 if (!noverify) {
706 if (req && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
707 if (i == -1)
708 BIO_printf(bio_err, "WARNING: no nonce in response\n");
709 else {
710 BIO_printf(bio_err, "Nonce Verify error\n");
711 goto end;
712 }
713 }
714 i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
715 if (i < 0)
716 i = OCSP_basic_verify(bs, NULL, store, 0);
717
718 if (i <= 0) {
719 BIO_printf(bio_err, "Response Verify Failure\n");
720 ERR_print_errors(bio_err);
721 } else
722 BIO_printf(bio_err, "Response verify OK\n");
723
724 }
725 if (!print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage))
726 goto end;
727
728 ret = 0;
729
730end:
731 ERR_print_errors(bio_err);
732 X509_free(signer);
733 X509_STORE_free(store);
734 EVP_PKEY_free(key);
735 EVP_PKEY_free(rkey);
736 X509_free(issuer);
737 X509_free(cert);
738 X509_free(rsigner);
739 X509_free(rca_cert);
740 free_index(rdb);
741 BIO_free_all(cbio);
742 BIO_free_all(acbio);
743 BIO_free(out);
744 OCSP_REQUEST_free(req);
745 OCSP_RESPONSE_free(resp);
746 OCSP_BASICRESP_free(bs);
747 sk_OPENSSL_STRING_free(reqnames);
748 sk_OCSP_CERTID_free(ids);
749 sk_X509_pop_free(sign_other, X509_free);
750 sk_X509_pop_free(verify_other, X509_free);
751 sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
752
753 if (use_ssl != -1) {
754 free(host);
755 free(port);
756 free(path);
757 }
758 return (ret);
759}
760
761static int
762add_ocsp_cert(OCSP_REQUEST ** req, X509 * cert, const EVP_MD * cert_id_md, X509 * issuer,
763 STACK_OF(OCSP_CERTID) * ids)
764{
765 OCSP_CERTID *id;
766 if (!issuer) {
767 BIO_printf(bio_err, "No issuer certificate specified\n");
768 return 0;
769 }
770 if (!*req)
771 *req = OCSP_REQUEST_new();
772 if (!*req)
773 goto err;
774 id = OCSP_cert_to_id(cert_id_md, cert, issuer);
775 if (!id || !sk_OCSP_CERTID_push(ids, id))
776 goto err;
777 if (!OCSP_request_add0_id(*req, id))
778 goto err;
779 return 1;
780
781err:
782 BIO_printf(bio_err, "Error Creating OCSP request\n");
783 return 0;
784}
785
786static int
787add_ocsp_serial(OCSP_REQUEST ** req, char *serial, const EVP_MD * cert_id_md, X509 * issuer,
788 STACK_OF(OCSP_CERTID) * ids)
789{
790 OCSP_CERTID *id;
791 X509_NAME *iname;
792 ASN1_BIT_STRING *ikey;
793 ASN1_INTEGER *sno;
794 if (!issuer) {
795 BIO_printf(bio_err, "No issuer certificate specified\n");
796 return 0;
797 }
798 if (!*req)
799 *req = OCSP_REQUEST_new();
800 if (!*req)
801 goto err;
802 iname = X509_get_subject_name(issuer);
803 ikey = X509_get0_pubkey_bitstr(issuer);
804 sno = s2i_ASN1_INTEGER(NULL, serial);
805 if (!sno) {
806 BIO_printf(bio_err, "Error converting serial number %s\n", serial);
807 return 0;
808 }
809 id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
810 ASN1_INTEGER_free(sno);
811 if (!id || !sk_OCSP_CERTID_push(ids, id))
812 goto err;
813 if (!OCSP_request_add0_id(*req, id))
814 goto err;
815 return 1;
816
817err:
818 BIO_printf(bio_err, "Error Creating OCSP request\n");
819 return 0;
820}
821
822static int
823print_ocsp_summary(BIO * out, OCSP_BASICRESP * bs, OCSP_REQUEST * req,
824 STACK_OF(OPENSSL_STRING) * names,
825 STACK_OF(OCSP_CERTID) * ids, long nsec,
826 long maxage)
827{
828 OCSP_CERTID *id;
829 char *name;
830 int i;
831
832 int status, reason;
833
834 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
835
836 if (!bs || !req || !sk_OPENSSL_STRING_num(names) || !sk_OCSP_CERTID_num(ids))
837 return 1;
838
839 for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
840 id = sk_OCSP_CERTID_value(ids, i);
841 name = sk_OPENSSL_STRING_value(names, i);
842 BIO_printf(out, "%s: ", name);
843
844 if (!OCSP_resp_find_status(bs, id, &status, &reason,
845 &rev, &thisupd, &nextupd)) {
846 BIO_puts(out, "ERROR: No Status found.\n");
847 continue;
848 }
849 /*
850 * Check validity: if invalid write to output BIO so we know
851 * which response this refers to.
852 */
853 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
854 BIO_puts(out, "WARNING: Status times invalid.\n");
855 ERR_print_errors(out);
856 }
857 BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
858
859 BIO_puts(out, "\tThis Update: ");
860 ASN1_GENERALIZEDTIME_print(out, thisupd);
861 BIO_puts(out, "\n");
862
863 if (nextupd) {
864 BIO_puts(out, "\tNext Update: ");
865 ASN1_GENERALIZEDTIME_print(out, nextupd);
866 BIO_puts(out, "\n");
867 }
868 if (status != V_OCSP_CERTSTATUS_REVOKED)
869 continue;
870
871 if (reason != -1)
872 BIO_printf(out, "\tReason: %s\n",
873 OCSP_crl_reason_str(reason));
874
875 BIO_puts(out, "\tRevocation Time: ");
876 ASN1_GENERALIZEDTIME_print(out, rev);
877 BIO_puts(out, "\n");
878 }
879
880 return 1;
881}
882
883
884static int
885make_ocsp_response(OCSP_RESPONSE ** resp, OCSP_REQUEST * req, CA_DB * db,
886 X509 * ca, X509 * rcert, EVP_PKEY * rkey,
887 STACK_OF(X509) * rother, unsigned long flags,
888 int nmin, int ndays)
889{
890 ASN1_TIME *thisupd = NULL, *nextupd = NULL;
891 OCSP_CERTID *cid, *ca_id = NULL;
892 OCSP_BASICRESP *bs = NULL;
893 int i, id_count, ret = 1;
894
895 id_count = OCSP_request_onereq_count(req);
896
897 if (id_count <= 0) {
898 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
899 goto end;
900 }
901 bs = OCSP_BASICRESP_new();
902 thisupd = X509_gmtime_adj(NULL, 0);
903 if (ndays != -1)
904 nextupd = X509_gmtime_adj(NULL, nmin * 60 + ndays * 3600 * 24);
905
906 /* Examine each certificate id in the request */
907 for (i = 0; i < id_count; i++) {
908 OCSP_ONEREQ *one;
909 ASN1_INTEGER *serial;
910 char **inf;
911 ASN1_OBJECT *cert_id_md_oid;
912 const EVP_MD *cert_id_md;
913 one = OCSP_request_onereq_get0(req, i);
914 cid = OCSP_onereq_get0_id(one);
915
916 OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
917
918 cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
919 if (!cert_id_md) {
920 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
921 NULL);
922 goto end;
923 }
924 if (ca_id)
925 OCSP_CERTID_free(ca_id);
926 ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca);
927
928 /* Is this request about our CA? */
929 if (OCSP_id_issuer_cmp(ca_id, cid)) {
930 OCSP_basic_add1_status(bs, cid,
931 V_OCSP_CERTSTATUS_UNKNOWN,
932 0, NULL,
933 thisupd, nextupd);
934 continue;
935 }
936 OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
937 inf = lookup_serial(db, serial);
938 if (!inf)
939 OCSP_basic_add1_status(bs, cid,
940 V_OCSP_CERTSTATUS_UNKNOWN,
941 0, NULL,
942 thisupd, nextupd);
943 else if (inf[DB_type][0] == DB_TYPE_VAL)
944 OCSP_basic_add1_status(bs, cid,
945 V_OCSP_CERTSTATUS_GOOD,
946 0, NULL,
947 thisupd, nextupd);
948 else if (inf[DB_type][0] == DB_TYPE_REV) {
949 ASN1_OBJECT *inst = NULL;
950 ASN1_TIME *revtm = NULL;
951 ASN1_GENERALIZEDTIME *invtm = NULL;
952 OCSP_SINGLERESP *single;
953 int reason = -1;
954 unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
955 single = OCSP_basic_add1_status(bs, cid,
956 V_OCSP_CERTSTATUS_REVOKED,
957 reason, revtm,
958 thisupd, nextupd);
959 if (invtm)
960 OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date, invtm, 0, 0);
961 else if (inst)
962 OCSP_SINGLERESP_add1_ext_i2d(single, NID_hold_instruction_code, inst, 0, 0);
963 ASN1_OBJECT_free(inst);
964 ASN1_TIME_free(revtm);
965 ASN1_GENERALIZEDTIME_free(invtm);
966 }
967 }
968
969 OCSP_copy_nonce(bs, req);
970
971 OCSP_basic_sign(bs, rcert, rkey, NULL, rother, flags);
972
973 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
974
975end:
976 ASN1_TIME_free(thisupd);
977 ASN1_TIME_free(nextupd);
978 OCSP_CERTID_free(ca_id);
979 OCSP_BASICRESP_free(bs);
980 return ret;
981
982}
983
984static char **
985lookup_serial(CA_DB * db, ASN1_INTEGER * ser)
986{
987 int i;
988 BIGNUM *bn = NULL;
989 char *itmp, *row[DB_NUMBER], **rrow;
990 for (i = 0; i < DB_NUMBER; i++)
991 row[i] = NULL;
992 bn = ASN1_INTEGER_to_BN(ser, NULL);
993 OPENSSL_assert(bn); /* FIXME: should report an error at this
994 * point and abort */
995 if (BN_is_zero(bn))
996 itmp = strdup("00");
997 else
998 itmp = BN_bn2hex(bn);
999 row[DB_serial] = itmp;
1000 BN_free(bn);
1001 rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
1002 free(itmp);
1003 return rrow;
1004}
1005
1006/* Quick and dirty OCSP server: read in and parse input request */
1007
1008static BIO *
1009init_responder(char *port)
1010{
1011 BIO *acbio = NULL, *bufbio = NULL;
1012 bufbio = BIO_new(BIO_f_buffer());
1013 if (!bufbio)
1014 goto err;
1015 acbio = BIO_new_accept(port);
1016 if (!acbio)
1017 goto err;
1018 BIO_set_accept_bios(acbio, bufbio);
1019 bufbio = NULL;
1020
1021 if (BIO_do_accept(acbio) <= 0) {
1022 BIO_printf(bio_err, "Error setting up accept BIO\n");
1023 ERR_print_errors(bio_err);
1024 goto err;
1025 }
1026 return acbio;
1027
1028err:
1029 BIO_free_all(acbio);
1030 BIO_free(bufbio);
1031 return NULL;
1032}
1033
1034static int
1035do_responder(OCSP_REQUEST ** preq, BIO ** pcbio, BIO * acbio, char *port)
1036{
1037 int have_post = 0, len;
1038 OCSP_REQUEST *req = NULL;
1039 char inbuf[1024];
1040 BIO *cbio = NULL;
1041
1042 if (BIO_do_accept(acbio) <= 0) {
1043 BIO_printf(bio_err, "Error accepting connection\n");
1044 ERR_print_errors(bio_err);
1045 return 0;
1046 }
1047 cbio = BIO_pop(acbio);
1048 *pcbio = cbio;
1049
1050 for (;;) {
1051 len = BIO_gets(cbio, inbuf, sizeof inbuf);
1052 if (len <= 0)
1053 return 1;
1054 /* Look for "POST" signalling start of query */
1055 if (!have_post) {
1056 if (strncmp(inbuf, "POST", 4)) {
1057 BIO_printf(bio_err, "Invalid request\n");
1058 return 1;
1059 }
1060 have_post = 1;
1061 }
1062 /* Look for end of headers */
1063 if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
1064 break;
1065 }
1066
1067 /* Try to read OCSP request */
1068
1069 req = d2i_OCSP_REQUEST_bio(cbio, NULL);
1070
1071 if (!req) {
1072 BIO_printf(bio_err, "Error parsing OCSP request\n");
1073 ERR_print_errors(bio_err);
1074 }
1075 *preq = req;
1076
1077 return 1;
1078
1079}
1080
1081static int
1082send_ocsp_response(BIO * cbio, OCSP_RESPONSE * resp)
1083{
1084 static const char http_resp[] =
1085 "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1086 "Content-Length: %d\r\n\r\n";
1087 if (!cbio)
1088 return 0;
1089 BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
1090 i2d_OCSP_RESPONSE_bio(cbio, resp);
1091 (void) BIO_flush(cbio);
1092 return 1;
1093}
1094
1095static OCSP_RESPONSE *
1096query_responder(BIO * err, BIO * cbio, char *path,
1097 STACK_OF(CONF_VALUE) * headers,
1098 OCSP_REQUEST * req, int req_timeout)
1099{
1100 int fd;
1101 int rv;
1102 int i;
1103 OCSP_REQ_CTX *ctx = NULL;
1104 OCSP_RESPONSE *rsp = NULL;
1105 fd_set confds;
1106 struct timeval tv;
1107
1108 if (req_timeout != -1)
1109 BIO_set_nbio(cbio, 1);
1110
1111 rv = BIO_do_connect(cbio);
1112
1113 if ((rv <= 0) && ((req_timeout == -1) || !BIO_should_retry(cbio))) {
1114 BIO_puts(err, "Error connecting BIO\n");
1115 return NULL;
1116 }
1117 if (BIO_get_fd(cbio, &fd) <= 0) {
1118 BIO_puts(err, "Can't get connection fd\n");
1119 goto err;
1120 }
1121 if (req_timeout != -1 && rv <= 0) {
1122 FD_ZERO(&confds);
1123 FD_SET(fd, &confds);
1124 tv.tv_usec = 0;
1125 tv.tv_sec = req_timeout;
1126 rv = select(fd + 1, NULL, &confds, NULL, &tv);
1127 if (rv == 0) {
1128 BIO_puts(err, "Timeout on connect\n");
1129 return NULL;
1130 }
1131 }
1132 ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
1133 if (!ctx)
1134 return NULL;
1135
1136 for (i = 0; i < sk_CONF_VALUE_num(headers); i++) {
1137 CONF_VALUE *hdr = sk_CONF_VALUE_value(headers, i);
1138 if (!OCSP_REQ_CTX_add1_header(ctx, hdr->name, hdr->value))
1139 goto err;
1140 }
1141
1142 if (!OCSP_REQ_CTX_set1_req(ctx, req))
1143 goto err;
1144
1145 for (;;) {
1146 rv = OCSP_sendreq_nbio(&rsp, ctx);
1147 if (rv != -1)
1148 break;
1149 if (req_timeout == -1)
1150 continue;
1151 FD_ZERO(&confds);
1152 FD_SET(fd, &confds);
1153 tv.tv_usec = 0;
1154 tv.tv_sec = req_timeout;
1155 if (BIO_should_read(cbio))
1156 rv = select(fd + 1, &confds, NULL, NULL, &tv);
1157 else if (BIO_should_write(cbio))
1158 rv = select(fd + 1, NULL, &confds, NULL, &tv);
1159 else {
1160 BIO_puts(err, "Unexpected retry condition\n");
1161 goto err;
1162 }
1163 if (rv == 0) {
1164 BIO_puts(err, "Timeout on request\n");
1165 break;
1166 }
1167 if (rv == -1) {
1168 BIO_puts(err, "Select error\n");
1169 break;
1170 }
1171 }
1172err:
1173 if (ctx)
1174 OCSP_REQ_CTX_free(ctx);
1175
1176 return rsp;
1177}
1178
1179OCSP_RESPONSE *
1180process_responder(BIO * err, OCSP_REQUEST * req,
1181 char *host, char *path, char *port, int use_ssl,
1182 STACK_OF(CONF_VALUE) * headers,
1183 int req_timeout)
1184{
1185 BIO *cbio = NULL;
1186 SSL_CTX *ctx = NULL;
1187 OCSP_RESPONSE *resp = NULL;
1188 cbio = BIO_new_connect(host);
1189 if (!cbio) {
1190 BIO_printf(err, "Error creating connect BIO\n");
1191 goto end;
1192 }
1193 if (port)
1194 BIO_set_conn_port(cbio, port);
1195 if (use_ssl == 1) {
1196 BIO *sbio;
1197 ctx = SSL_CTX_new(SSLv23_client_method());
1198 if (ctx == NULL) {
1199 BIO_printf(err, "Error creating SSL context.\n");
1200 goto end;
1201 }
1202 SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
1203 sbio = BIO_new_ssl(ctx, 1);
1204 cbio = BIO_push(sbio, cbio);
1205 }
1206 resp = query_responder(err, cbio, path, headers, req, req_timeout);
1207 if (!resp)
1208 BIO_printf(bio_err, "Error querying OCSP responder\n");
1209end:
1210 if (cbio)
1211 BIO_free_all(cbio);
1212 if (ctx)
1213 SSL_CTX_free(ctx);
1214 return resp;
1215}
1216
1217#endif
diff --git a/src/usr.bin/openssl/openssl.1 b/src/usr.bin/openssl/openssl.1
new file mode 100644
index 0000000000..b374728ba9
--- /dev/null
+++ b/src/usr.bin/openssl/openssl.1
@@ -0,0 +1,10407 @@
1.\" $OpenBSD: openssl.1,v 1.1 2014/08/26 17:47:24 jsing Exp $
2.\" ====================================================================
3.\" Copyright (c) 1998-2002 The OpenSSL Project. All rights reserved.
4.\"
5.\" Redistribution and use in source and binary forms, with or without
6.\" modification, are permitted provided that the following conditions
7.\" are met:
8.\"
9.\" 1. Redistributions of source code must retain the above copyright
10.\" notice, this list of conditions and the following disclaimer.
11.\"
12.\" 2. Redistributions in binary form must reproduce the above copyright
13.\" notice, this list of conditions and the following disclaimer in
14.\" the documentation and/or other materials provided with the
15.\" distribution.
16.\"
17.\" 3. All advertising materials mentioning features or use of this
18.\" software must display the following acknowledgment:
19.\" "This product includes software developed by the OpenSSL Project
20.\" for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
21.\"
22.\" 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
23.\" endorse or promote products derived from this software without
24.\" prior written permission. For written permission, please contact
25.\" openssl-core@openssl.org.
26.\"
27.\" 5. Products derived from this software may not be called "OpenSSL"
28.\" nor may "OpenSSL" appear in their names without prior written
29.\" permission of the OpenSSL Project.
30.\"
31.\" 6. Redistributions of any form whatsoever must retain the following
32.\" acknowledgment:
33.\" "This product includes software developed by the OpenSSL Project
34.\" for use in the OpenSSL Toolkit (http://www.openssl.org/)"
35.\"
36.\" THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
37.\" EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
39.\" PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
40.\" ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41.\" SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
42.\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43.\" LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
45.\" STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
47.\" OF THE POSSIBILITY OF SUCH DAMAGE.
48.\" ====================================================================
49.\"
50.\" This product includes cryptographic software written by Eric Young
51.\" (eay@cryptsoft.com). This product includes software written by Tim
52.\" Hudson (tjh@cryptsoft.com).
53.\"
54.\"
55.\" Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
56.\" All rights reserved.
57.\"
58.\" This package is an SSL implementation written
59.\" by Eric Young (eay@cryptsoft.com).
60.\" The implementation was written so as to conform with Netscapes SSL.
61.\"
62.\" This library is free for commercial and non-commercial use as long as
63.\" the following conditions are aheared to. The following conditions
64.\" apply to all code found in this distribution, be it the RC4, RSA,
65.\" lhash, DES, etc., code; not just the SSL code. The SSL documentation
66.\" included with this distribution is covered by the same copyright terms
67.\" except that the holder is Tim Hudson (tjh@cryptsoft.com).
68.\"
69.\" Copyright remains Eric Young's, and as such any Copyright notices in
70.\" the code are not to be removed.
71.\" If this package is used in a product, Eric Young should be given attribution
72.\" as the author of the parts of the library used.
73.\" This can be in the form of a textual message at program startup or
74.\" in documentation (online or textual) provided with the package.
75.\"
76.\" Redistribution and use in source and binary forms, with or without
77.\" modification, are permitted provided that the following conditions
78.\" are met:
79.\" 1. Redistributions of source code must retain the copyright
80.\" notice, this list of conditions and the following disclaimer.
81.\" 2. Redistributions in binary form must reproduce the above copyright
82.\" notice, this list of conditions and the following disclaimer in the
83.\" documentation and/or other materials provided with the distribution.
84.\" 3. All advertising materials mentioning features or use of this software
85.\" must display the following acknowledgement:
86.\" "This product includes cryptographic software written by
87.\" Eric Young (eay@cryptsoft.com)"
88.\" The word 'cryptographic' can be left out if the rouines from the library
89.\" being used are not cryptographic related :-).
90.\" 4. If you include any Windows specific code (or a derivative thereof) from
91.\" the apps directory (application code) you must include an
92.\" acknowledgement:
93.\" "This product includes software written by Tim Hudson
94.\" (tjh@cryptsoft.com)"
95.\"
96.\" THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
97.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
98.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
99.\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
100.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
101.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
102.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
103.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
104.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
105.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
106.\" SUCH DAMAGE.
107.\"
108.\" The licence and distribution terms for any publically available version or
109.\" derivative of this code cannot be changed. i.e. this code cannot simply be
110.\" copied and put under another distribution licence
111.\" [including the GNU Public Licence.]
112.\"
113.\" OPENSSL
114.\"
115.Dd $Mdocdate: August 26 2014 $
116.Dt OPENSSL 1
117.Os
118.Sh NAME
119.Nm openssl
120.Nd OpenSSL command line tool
121.Sh SYNOPSIS
122.Nm
123.Cm command
124.Op Ar command_opts
125.Op Ar command_args
126.Pp
127.Nm
128.Cm list-standard-commands \*(Ba
129.Cm list-message-digest-commands \*(Ba
130.Cm list-cipher-commands \*(Ba
131.Cm list-cipher-algorithms \*(Ba
132.Cm list-message-digest-algorithms \*(Ba
133.Cm list-public-key-algorithms
134.Pp
135.Nm
136.Cm no- Ns Ar XXX
137.Op Ar arbitrary options
138.Sh DESCRIPTION
139.Nm OpenSSL
140is a cryptography toolkit implementing the Secure Sockets Layer
141.Pq SSL v3
142and Transport Layer Security
143.Pq TLS v1
144network protocols and related cryptography standards required by them.
145.Pp
146The
147.Nm
148program is a command line tool for using the various
149cryptography functions of
150.Nm OpenSSL Ns Li 's
151.Em crypto
152library from the shell.
153It can be used for
154.Pp
155.Bl -bullet -offset indent -compact
156.It
157Creation and management of private keys, public keys, and parameters
158.It
159Public key cryptographic operations
160.It
161Creation of X.509 certificates, CSRs and CRLs
162.It
163Calculation of Message Digests
164.It
165Encryption and Decryption with Ciphers
166.It
167SSL/TLS Client and Server Tests
168.It
169Handling of S/MIME signed or encrypted mail
170.It
171Time stamp requests, generation, and verification
172.El
173.Sh COMMAND SUMMARY
174The
175.Nm
176program provides a rich variety of commands
177.Pf ( Cm command
178in the
179.Sx SYNOPSIS
180above),
181each of which often has a wealth of options and arguments
182.Pf ( Ar command_opts
183and
184.Ar command_args
185in the
186.Sx SYNOPSIS ) .
187.Pp
188The pseudo-commands
189.Cm list-standard-commands , list-message-digest-commands ,
190and
191.Cm list-cipher-commands
192output a list
193.Pq one entry per line
194of the names of all standard commands, message digest commands,
195or cipher commands, respectively, that are available in the present
196.Nm
197utility.
198.Pp
199The pseudo-commands
200.Cm list-cipher-algorithms
201and
202.Cm list-message-digest-algorithms
203list all cipher and message digest names,
204one entry per line.
205Aliases are listed as:
206.Pp
207.D1 from =\*(Gt to
208.Pp
209The pseudo-command
210.Cm list-public-key-algorithms
211lists all supported public key algorithms.
212.Pp
213The pseudo-command
214.Cm no- Ns Ar XXX
215tests whether a command of the
216specified name is available.
217If no command named
218.Ar XXX
219exists,
220it returns 0
221.Pq success
222and prints
223.Cm no- Ns Ar XXX ;
224otherwise it returns 1 and prints
225.Ar XXX .
226In both cases, the output goes to
227.Em stdout
228and nothing is printed to
229.Em stderr .
230Additional command line arguments are always ignored.
231Since for each cipher there is a command of the same name,
232this provides an easy way for shell scripts to test for the
233availability of ciphers in the
234.Nm
235program.
236.Pp
237.Sy Note :
238.Cm no- Ns Ar XXX
239is not able to detect pseudo-commands such as
240.Cm quit ,
241.Cm list- Ns Ar ... Ns Cm -commands ,
242or
243.Cm no- Ns Ar XXX
244itself.
245.Sh STANDARD COMMANDS
246.Bl -tag -width "asn1parse"
247.It Cm asn1parse
248Parse an ASN.1 sequence.
249.It Cm ca
250Certificate Authority
251.Pq CA
252management.
253.It Cm ciphers
254Cipher suite description determination.
255.It Cm crl
256Certificate Revocation List
257.Pq CRL
258management.
259.It Cm crl2pkcs7
260CRL to PKCS#7 conversion.
261.It Cm dgst
262Message digest calculation.
263.It Cm dh
264Diffie-Hellman parameter management.
265Obsoleted by
266.Cm dhparam .
267.It Cm dhparam
268Generation and management of Diffie-Hellman parameters.
269Superseded by
270.Cm genpkey
271and
272.Cm pkeyparam .
273.It Cm dsa
274DSA data management.
275.It Cm dsaparam
276DSA parameter generation and management.
277Superseded by
278.Cm genpkey
279and
280.Cm pkeyparam .
281.It Cm ec
282Elliptic curve (EC) key processing.
283.It Cm ecparam
284EC parameter manipulation and generation.
285.It Cm enc
286Encoding with ciphers.
287.It Cm engine
288Engine (loadable module) information and manipulation.
289.It Cm errstr
290Error number to error string conversion.
291.It Cm gendh
292Generation of Diffie-Hellman parameters.
293Obsoleted by
294.Cm dhparam .
295.It Cm gendsa
296Generation of DSA private key from parameters.
297Superseded by
298.Cm genpkey
299and
300.Cm pkey .
301.It Cm genpkey
302Generation of private keys or parameters.
303.It Cm genrsa
304Generation of RSA private key.
305Superseded by
306.Cm genpkey .
307.It Cm nseq
308Create or examine a Netscape certificate sequence.
309.It Cm ocsp
310Online Certificate Status Protocol utility.
311.It Cm passwd
312Generation of hashed passwords.
313.It Cm pkcs7
314PKCS#7 data management.
315.It Cm pkcs8
316PKCS#8 data management.
317.It Cm pkcs12
318PKCS#12 data management.
319.It Cm pkey
320Public and private key management.
321.It Cm pkeyparam
322Public key algorithm parameter management.
323.It Cm pkeyutl
324Public key algorithm cryptographic operation utility.
325.It Cm prime
326Generate prime numbers or test numbers for primality.
327.It Cm rand
328Generate pseudo-random bytes.
329.It Cm req
330PKCS#10 X.509 Certificate Signing Request
331.Pq CSR
332management.
333.It Cm rsa
334RSA key management.
335.It Cm rsautl
336RSA utility for signing, verification, encryption, and decryption.
337Superseded by
338.Cm pkeyutl .
339.It Cm s_client
340This implements a generic SSL/TLS client which can establish a transparent
341connection to a remote server speaking SSL/TLS.
342It's intended for testing purposes only and provides only rudimentary
343interface functionality but internally uses mostly all functionality of the
344.Nm OpenSSL
345.Em ssl
346library.
347.It Cm s_server
348This implements a generic SSL/TLS server which accepts connections from remote
349clients speaking SSL/TLS.
350It's intended for testing purposes only and provides only rudimentary
351interface functionality but internally uses mostly all functionality of the
352.Nm OpenSSL
353.Em ssl
354library.
355It provides both an own command line oriented protocol for testing
356SSL functions and a simple HTTP response
357facility to emulate an SSL/TLS-aware webserver.
358.It Cm s_time
359SSL connection timer.
360.It Cm sess_id
361SSL session data management.
362.It Cm smime
363S/MIME mail processing.
364.It Cm speed
365Algorithm speed measurement.
366.It Cm spkac
367SPKAC printing and generating utility.
368.It Cm ts
369Time stamping authority tool (client/server).
370.It Cm verify
371X.509 certificate verification.
372.It Cm version
373.Nm OpenSSL
374version information.
375.It Cm x509
376X.509 certificate data management.
377.El
378.Sh MESSAGE DIGEST COMMANDS
379.Bl -tag -width "asn1parse"
380.It Cm md2
381MD2 digest.
382.It Cm md4
383MD4 digest.
384.It Cm md5
385MD5 digest.
386.It Cm ripemd160
387RIPEMD-160 digest.
388.It Cm sha
389SHA digest.
390.It Cm sha1
391SHA-1 digest.
392.El
393.Sh ENCODING AND CIPHER COMMANDS
394.Bl -tag -width Ds -compact
395.It Cm aes-128-cbc | aes-128-ecb | aes-192-cbc | aes-192-ecb
396.It Cm aes-256-cbc | aes-256-ecb
397AES cipher.
398.Pp
399.It Cm base64
400Base64 encoding.
401.Pp
402.It Xo
403.Cm bf | bf-cbc | bf-cfb |
404.Cm bf-ecb | bf-ofb
405.Xc
406Blowfish cipher.
407.Pp
408.It Cm cast | cast-cbc
409CAST cipher.
410.Pp
411.It Cm cast5-cbc | cast5-cfb | cast5-ecb | cast5-ofb
412CAST5 cipher.
413.Pp
414.It Xo
415.Cm des | des-cbc | des-cfb | des-ecb |
416.Cm des-ede | des-ede-cbc
417.Xc
418.It Cm des-ede-cfb | des-ede-ofb | des-ofb
419DES cipher.
420.Pp
421.It Xo
422.Cm des3 | desx | des-ede3 |
423.Cm des-ede3-cbc | des-ede3-cfb | des-ede3-ofb
424.Xc
425Triple DES cipher.
426.Pp
427.It Xo
428.Cm rc2 | rc2-40-cbc | rc2-64-cbc | rc2-cbc |
429.Cm rc2-cfb | rc2-ecb | rc2-ofb
430.Xc
431RC2 cipher.
432.Pp
433.It Cm rc4 | rc4-40
434RC4 cipher.
435.El
436.Sh PASS PHRASE ARGUMENTS
437Several commands accept password arguments, typically using
438.Fl passin
439and
440.Fl passout
441for input and output passwords, respectively.
442These allow the password to be obtained from a variety of sources.
443Both of these options take a single argument whose format is described below.
444If no password argument is given and a password is required,
445then the user is prompted to enter one:
446this will typically be read from the current terminal with echoing turned off.
447.Bl -tag -width "fd:number"
448.It Ar pass : Ns Ar password
449The actual password is
450.Ar password .
451Since the password is visible to utilities
452(like
453.Xr ps 1
454under
455.Ux )
456this form should only be used where security is not important.
457.It Ar env : Ns Ar var
458Obtain the password from the environment variable
459.Ar var .
460Since the environment of other processes is visible on certain platforms
461(e.g.\&
462.Xr ps 1
463under certain
464.Ux
465OSes) this option should be used with caution.
466.It Ar file : Ns Ar path
467The first line of
468.Ar path
469is the password.
470If the same
471.Ar path
472argument is supplied to
473.Fl passin
474and
475.Fl passout ,
476then the first line will be used for the input password and the next line
477for the output password.
478.Ar path
479need not refer to a regular file:
480it could, for example, refer to a device or named pipe.
481.It Ar fd : Ns Ar number
482Read the password from the file descriptor
483.Ar number .
484This can be used to send the data via a pipe for example.
485.It Ar stdin
486Read the password from standard input.
487.El
488.\"
489.\" ASN1PARSE
490.\"
491.Sh ASN1PARSE
492.nr nS 1
493.Nm "openssl asn1parse"
494.Bk -words
495.Op Fl i
496.Op Fl dlimit Ar number
497.Op Fl dump
498.Op Fl genconf Ar file
499.Op Fl genstr Ar str
500.Op Fl in Ar file
501.Op Fl inform Ar DER | PEM | TXT
502.Op Fl length Ar number
503.Op Fl noout
504.Op Fl offset Ar number
505.Op Fl oid Ar file
506.Op Fl out Ar file
507.Op Fl strparse Ar offset
508.Ek
509.nr nS 0
510.Pp
511The
512.Nm asn1parse
513command is a diagnostic utility that can parse ASN.1 structures.
514It can also be used to extract data from ASN.1 formatted data.
515.Pp
516The options are as follows:
517.Bl -tag -width Ds
518.It Fl dlimit Ar number
519Dump the first
520.Ar number
521bytes of unknown data in hex form.
522.It Fl dump
523Dump unknown data in hex form.
524.It Fl genconf Ar file , Fl genstr Ar str
525Generate encoded data based on string
526.Ar str ,
527file
528.Ar file ,
529or both using
530.Xr ASN1_generate_nconf 3
531format.
532If only
533.Ar file
534is present then the string is obtained from the default section
535using the name
536.Dq asn1 .
537The encoded data is passed through the ASN1 parser and printed out as
538though it came from a file;
539the contents can thus be examined and written to a file using the
540.Fl out
541option.
542.It Fl i
543Indents the output according to the
544.Qq depth
545of the structures.
546.It Fl in Ar file
547The input file; default is standard input.
548.It Fl inform Ar DER | PEM | TXT
549The input format.
550.Ar DER
551.Pq Distinguished Encoding Rules
552is binary format and
553.Ar PEM
554.Pq Privacy Enhanced Mail ,
555the default, is base64-encoded.
556.Ar TXT
557is plain text.
558.It Fl length Ar number
559Number of bytes to parse; default is until end of file.
560.It Fl noout
561Don't output the parsed version of the input file.
562.It Fl offset Ar number
563Starting offset to begin parsing; default is start of file.
564.It Fl oid Ar file
565A file containing additional object identifiers
566.Pq OIDs .
567The format of this file is described in the
568.Sx ASN1PARSE NOTES
569section below.
570.It Fl out Ar file
571Output file to place the DER-encoded data into.
572If this option is not present, no encoded data will be output.
573This is most useful when combined with the
574.Fl strparse
575option.
576.It Fl strparse Ar offset
577Parse the content octets of the ASN.1 object starting at
578.Ar offset .
579This option can be used multiple times to
580.Qq drill down
581into a nested structure.
582.El
583.Sh ASN1PARSE OUTPUT
584The output will typically contain lines like this:
585.Bd -literal -offset 2n
5860:d=0 hl=4 l= 681 cons: SEQUENCE
587
588\&.....
589
590229:d=3 hl=3 l= 141 prim: BIT STRING
591373:d=2 hl=3 l= 162 cons: cont [ 3 ]
592376:d=3 hl=3 l= 159 cons: SEQUENCE
593379:d=4 hl=2 l= 29 cons: SEQUENCE
594381:d=5 hl=2 l= 3 prim: OBJECT :X509v3 Subject Key Identifier
595386:d=5 hl=2 l= 22 prim: OCTET STRING
596410:d=4 hl=2 l= 112 cons: SEQUENCE
597412:d=5 hl=2 l= 3 prim: OBJECT :X509v3 Authority Key Identifier
598417:d=5 hl=2 l= 105 prim: OCTET STRING
599524:d=4 hl=2 l= 12 cons: SEQUENCE
600
601\&.....
602.Ed
603.Pp
604This example is part of a self-signed certificate.
605Each line starts with the offset in decimal.
606.Cm d=XX
607specifies the current depth.
608The depth is increased within the scope of any SET or SEQUENCE.
609.Cm hl=XX
610gives the header length
611.Pq tag and length octets
612of the current type.
613.Cm l=XX
614gives the length of the content octets.
615.Pp
616The
617.Fl i
618option can be used to make the output more readable.
619.Pp
620Some knowledge of the ASN.1 structure is needed to interpret the output.
621.Pp
622In this example, the BIT STRING at offset 229 is the certificate public key.
623The content octets of this will contain the public key information.
624This can be examined using the option
625.Fl strparse Cm 229
626to yield:
627.Bd -literal
628 0:d=0 hl=3 l= 137 cons: SEQUENCE
629 3:d=1 hl=3 l= 129 prim: INTEGER :E5D21E1F5C8D208EA7A2166C7FA
630F9F6BDF2059669C60876DDB70840F1A5AAFA59699FE471F379F1DD6A487E7D5409AB6A88D4A
6319746E24B91D8CF55DB3521015460C8EDE44EE8A4189F7A7BE77D6CD3A9AF2696F486855CF58
632BF0EDF2B4068058C7A947F52548DDF7E15E96B385F86422BEA9064A3EE9
633 135:d=1 hl=2 l= 3 prim: INTEGER :010001
634.Ed
635.Sh ASN1PARSE NOTES
636If an OID
637.Pq object identifier
638is not part of
639.Nm OpenSSL Ns Li 's
640internal table it will be represented in
641numerical form
642.Pq for example 1.2.3.4 .
643The file passed to the
644.Fl oid
645option allows additional OIDs to be included.
646Each line consists of three columns:
647the first column is the OID in numerical format and should be followed by
648whitespace.
649The second column is the
650.Qq short name
651which is a single word followed by whitespace.
652The final column is the rest of the line and is the
653.Qq long name .
654.Nm asn1parse
655displays the long name.
656Example:
657.Pp
658.Dl \&"1.2.3.4 shortname A long name\&"
659.Sh ASN1 EXAMPLES
660Parse a file:
661.Pp
662.Dl $ openssl asn1parse -in file.pem
663.Pp
664Parse a DER file:
665.Pp
666.Dl $ openssl asn1parse -inform DER -in file.der
667.Sh ASN1PARSE BUGS
668There should be options to change the format of output lines.
669The output of some ASN.1 types is not well handled
670.Pq if at all .
671.\"
672.\" CA
673.\"
674.Sh CA
675.nr nS 1
676.Nm "openssl ca"
677.Bk -words
678.Op Fl batch
679.Op Fl cert Ar file
680.Op Fl config Ar file
681.Op Fl crl_CA_compromise Ar time
682.Op Fl crl_compromise Ar time
683.Op Fl crl_hold Ar instruction
684.Op Fl crl_reason Ar reason
685.Op Fl crldays Ar days
686.Op Fl crlexts Ar section
687.Op Fl crlhours Ar hours
688.Op Fl days Ar arg
689.Op Fl enddate Ar date
690.Op Fl engine Ar id
691.Op Fl extensions Ar section
692.Op Fl extfile Ar section
693.Op Fl gencrl
694.Op Fl in Ar file
695.Op Fl infiles
696.Op Fl key Ar keyfile
697.Op Fl keyfile Ar arg
698.Op Fl keyform Ar ENGINE | PEM
699.Op Fl md Ar arg
700.Op Fl msie_hack
701.Op Fl name Ar section
702.Op Fl noemailDN
703.Op Fl notext
704.Op Fl out Ar file
705.Op Fl outdir Ar dir
706.Op Fl passin Ar arg
707.Op Fl policy Ar arg
708.Op Fl preserveDN
709.Op Fl revoke Ar file
710.Op Fl spkac Ar file
711.Op Fl ss_cert Ar file
712.Op Fl startdate Ar date
713.Op Fl status Ar serial
714.Op Fl subj Ar arg
715.Op Fl updatedb
716.Op Fl verbose
717.Ek
718.nr nS 0
719.Pp
720The
721.Nm ca
722command is a minimal CA application.
723It can be used to sign certificate requests in a variety of forms
724and generate CRLs.
725It also maintains a text database of issued certificates and their status.
726.Pp
727The options descriptions will be divided into each purpose.
728.Sh CA OPTIONS
729.Bl -tag -width "XXXX"
730.It Fl batch
731This sets the batch mode.
732In this mode no questions will be asked
733and all certificates will be certified automatically.
734.It Fl cert Ar file
735The CA certificate file.
736.It Fl config Ar file
737Specifies the configuration file to use.
738.It Fl days Ar arg
739The number of days to certify the certificate for.
740.It Fl enddate Ar date
741This allows the expiry date to be explicitly set.
742The format of the date is YYMMDDHHMMSSZ
743.Pq the same as an ASN1 UTCTime structure .
744.It Fl engine Ar id
745Specifying an engine (by its unique
746.Ar id
747string) will cause
748.Nm ca
749to attempt to obtain a functional reference to the specified engine,
750thus initialising it if needed.
751The engine will then be set as the default for all available algorithms.
752.It Fl extensions Ar section
753The section of the configuration file containing certificate extensions
754to be added when a certificate is issued (defaults to
755.Em x509_extensions
756unless the
757.Fl extfile
758option is used).
759If no extension section is present, a V1 certificate is created.
760If the extension section is present
761.Pq even if it is empty ,
762then a V3 certificate is created.
763.It Fl extfile Ar file
764An additional configuration
765.Ar file
766to read certificate extensions from
767(using the default section unless the
768.Fl extensions
769option is also used).
770.It Fl in Ar file
771An input
772.Ar file
773containing a single certificate request to be signed by the CA.
774.It Fl infiles
775If present, this should be the last option; all subsequent arguments
776are assumed to be the names of files containing certificate requests.
777.It Fl key Ar keyfile
778The password used to encrypt the private key.
779Since on some systems the command line arguments are visible
780(e.g.\&
781.Ux
782with the
783.Xr ps 1
784utility) this option should be used with caution.
785.It Fl keyfile Ar file
786The private key to sign requests with.
787.It Fl keyform Ar ENGINE | PEM
788Private key file format.
789.It Fl md Ar alg
790The message digest to use.
791Possible values include
792.Ar md5
793and
794.Ar sha1 .
795This option also applies to CRLs.
796.It Fl msie_hack
797This is a legacy option to make
798.Nm ca
799work with very old versions of the IE certificate enrollment control
800.Qq certenr3 .
801It used UniversalStrings for almost everything.
802Since the old control has various security bugs,
803its use is strongly discouraged.
804The newer control
805.Qq Xenroll
806does not need this option.
807.It Fl name Ar section
808Specifies the configuration file
809.Ar section
810to use (overrides
811.Cm default_ca
812in the
813.Cm ca
814section).
815.It Fl noemailDN
816The DN of a certificate can contain the EMAIL field if present in the
817request DN, however it is good policy just having the e-mail set into
818the
819.Em altName
820extension of the certificate.
821When this option is set, the EMAIL field is removed from the certificate's
822subject and set only in the, eventually present, extensions.
823The
824.Ar email_in_dn
825keyword can be used in the configuration file to enable this behaviour.
826.It Fl notext
827Don't output the text form of a certificate to the output file.
828.It Fl out Ar file
829The output file to output certificates to.
830The default is standard output.
831The certificate details will also be printed out to this file.
832.It Fl outdir Ar directory
833The
834.Ar directory
835to output certificates to.
836The certificate will be written to a file consisting of the
837serial number in hex with
838.Qq .pem
839appended.
840.It Fl passin Ar arg
841The key password source.
842For more information about the format of
843.Ar arg ,
844see the
845.Sx PASS PHRASE ARGUMENTS
846section above.
847.It Fl policy Ar arg
848This option defines the CA
849.Qq policy
850to use.
851This is a section in the configuration file which decides which fields
852should be mandatory or match the CA certificate.
853Check out the
854.Sx CA POLICY FORMAT
855section for more information.
856.It Fl preserveDN
857Normally, the DN order of a certificate is the same as the order of the
858fields in the relevant policy section.
859When this option is set, the order is the same as the request.
860This is largely for compatibility with the older IE enrollment control
861which would only accept certificates if their DNs matched the order of the
862request.
863This is not needed for Xenroll.
864.It Fl spkac Ar file
865A file containing a single Netscape signed public key and challenge,
866and additional field values to be signed by the CA.
867See the
868.Sx SPKAC FORMAT
869section for information on the required format.
870.It Fl ss_cert Ar file
871A single self-signed certificate to be signed by the CA.
872.It Fl startdate Ar date
873This allows the start date to be explicitly set.
874The format of the date is YYMMDDHHMMSSZ
875.Pq the same as an ASN1 UTCTime structure .
876.It Fl status Ar serial
877Show status of certificate with serial number
878.Ar serial .
879.It Fl updatedb
880Update database for expired certificates.
881.It Fl verbose
882This prints extra details about the operations being performed.
883.El
884.Sh CRL OPTIONS
885.Bl -tag -width "XXXX"
886.It Fl crl_CA_compromise Ar time
887This is the same as
888.Fl crl_compromise ,
889except the revocation reason is set to CACompromise.
890.It Fl crl_compromise Ar time
891This sets the revocation reason to keyCompromise and the compromise time to
892.Ar time .
893.Ar time
894should be in GeneralizedTime format, i.e. YYYYMMDDHHMMSSZ.
895.It Fl crl_hold Ar instruction
896This sets the CRL revocation reason code to certificateHold and the hold
897instruction to
898.Ar instruction
899which must be an OID.
900Although any OID can be used, only holdInstructionNone
901(the use of which is discouraged by RFC 2459), holdInstructionCallIssuer or
902holdInstructionReject will normally be used.
903.It Fl crl_reason Ar reason
904Revocation reason, where
905.Ar reason
906is one of:
907unspecified, keyCompromise, CACompromise, affiliationChanged, superseded,
908cessationOfOperation, certificateHold or removeFromCRL.
909The matching of
910.Ar reason
911is case insensitive.
912Setting any revocation reason will make the CRL v2.
913In practice, removeFromCRL is not particularly useful because it is only used
914in delta CRLs which are not currently implemented.
915.It Fl crldays Ar num
916The number of days before the next CRL is due.
917This is the days from now to place in the CRL
918.Em nextUpdate
919field.
920.It Fl crlexts Ar section
921The
922.Ar section
923of the configuration file containing CRL extensions to include.
924If no CRL extension section is present then a V1 CRL is created;
925if the CRL extension section is present
926.Pq even if it is empty
927then a V2 CRL is created.
928The CRL extensions specified are CRL extensions and
929.Em not
930CRL entry extensions.
931It should be noted that some software
932.Pq for example Netscape
933can't handle V2 CRLs.
934.It Fl crlhours Ar num
935The number of hours before the next CRL is due.
936.It Fl gencrl
937This option generates a CRL based on information in the index file.
938.It Fl revoke Ar file
939A
940.Ar file
941containing a certificate to revoke.
942.It Fl subj Ar arg
943Supersedes the subject name given in the request.
944The
945.Ar arg
946must be formatted as
947.Ar /type0=value0/type1=value1/type2=... ;
948characters may be escaped by
949.Sq \e
950.Pq backslash ,
951no spaces are skipped.
952.El
953.Sh CA CONFIGURATION FILE OPTIONS
954The section of the configuration file containing options for
955.Nm ca
956is found as follows:
957If the
958.Fl name
959command line option is used, then it names the section to be used.
960Otherwise the section to be used must be named in the
961.Em default_ca
962option of the
963.Em ca
964section of the configuration file (or in the default section of the
965configuration file).
966Besides
967.Em default_ca ,
968the following options are read directly from the
969.Em ca
970section:
971.Pp
972.Bl -tag -width Ds -offset indent -compact
973.It preserve
974.It msie_hack
975.El
976.Pp
977This is probably a bug and may change in future releases.
978.Pp
979Many of the configuration file options are identical to command line
980options.
981Where the option is present in the configuration file and the command line,
982the command line value is used.
983Where an option is described as mandatory, then it must be present in
984the configuration file or the command line equivalent
985.Pq if any
986used.
987.Bl -tag -width "XXXX"
988.It Ar certificate
989The same as
990.Fl cert .
991It gives the file containing the CA certificate.
992Mandatory.
993.It Ar copy_extensions
994Determines how extensions in certificate requests should be handled.
995If set to
996.Ar none
997or this option is not present, then extensions are
998ignored and not copied to the certificate.
999If set to
1000.Ar copy ,
1001then any extensions present in the request that are not already present
1002are copied to the certificate.
1003If set to
1004.Ar copyall ,
1005then all extensions in the request are copied to the certificate:
1006if the extension is already present in the certificate it is deleted first.
1007See the
1008.Sx CA WARNINGS
1009section before using this option.
1010.Pp
1011The main use of this option is to allow a certificate request to supply
1012values for certain extensions such as
1013.Em subjectAltName .
1014.It Ar crl_extensions
1015The same as
1016.Fl crlexts .
1017.It Ar crlnumber
1018A text file containing the next CRL number to use in hex.
1019The CRL number will be inserted in the CRLs only if this file exists.
1020If this file is present, it must contain a valid CRL number.
1021.It Ar database
1022The text database file to use.
1023Mandatory.
1024This file must be present, though initially it will be empty.
1025.It Ar default_crl_hours , default_crl_days
1026The same as the
1027.Fl crlhours
1028and
1029.Fl crldays
1030options.
1031These will only be used if neither command line option is present.
1032At least one of these must be present to generate a CRL.
1033.It Ar default_days
1034The same as the
1035.Fl days
1036option.
1037The number of days to certify a certificate for.
1038.It Ar default_enddate
1039The same as the
1040.Fl enddate
1041option.
1042Either this option or
1043.Ar default_days
1044.Pq or the command line equivalents
1045must be present.
1046.It Ar default_md
1047The same as the
1048.Fl md
1049option.
1050The message digest to use.
1051Mandatory.
1052.It Ar default_startdate
1053The same as the
1054.Fl startdate
1055option.
1056The start date to certify a certificate for.
1057If not set, the current time is used.
1058.It Ar email_in_dn
1059The same as
1060.Fl noemailDN .
1061If the EMAIL field is to be removed from the DN of the certificate,
1062simply set this to
1063.Qq no .
1064If not present, the default is to allow for the EMAIL field in the
1065certificate's DN.
1066.It Ar msie_hack
1067The same as
1068.Fl msie_hack .
1069.It Ar name_opt , cert_opt
1070These options allow the format used to display the certificate details
1071when asking the user to confirm signing.
1072All the options supported by the
1073.Nm x509
1074utilities'
1075.Fl nameopt
1076and
1077.Fl certopt
1078switches can be used here, except that
1079.Ar no_signame
1080and
1081.Ar no_sigdump
1082are permanently set and cannot be disabled
1083(this is because the certificate signature cannot be displayed because
1084the certificate has not been signed at this point).
1085.Pp
1086For convenience, the value
1087.Em ca_default
1088is accepted by both to produce a reasonable output.
1089.Pp
1090If neither option is present, the format used in earlier versions of
1091.Nm OpenSSL
1092is used.
1093Use of the old format is
1094.Em strongly
1095discouraged because it only displays fields mentioned in the
1096.Ar policy
1097section,
1098mishandles multicharacter string types and does not display extensions.
1099.It Ar new_certs_dir
1100The same as the
1101.Fl outdir
1102command line option.
1103It specifies the directory where new certificates will be placed.
1104Mandatory.
1105.It Ar oid_file
1106This specifies a file containing additional object identifiers.
1107Each line of the file should consist of the numerical form of the
1108object identifier followed by whitespace, then the short name followed
1109by whitespace and finally the long name.
1110.It Ar oid_section
1111This specifies a section in the configuration file containing extra
1112object identifiers.
1113Each line should consist of the short name of the object identifier
1114followed by
1115.Sq =
1116and the numerical form.
1117The short and long names are the same when this option is used.
1118.It Ar policy
1119The same as
1120.Fl policy .
1121Mandatory.
1122See the
1123.Sx CA POLICY FORMAT
1124section for more information.
1125.It Ar preserve
1126The same as
1127.Fl preserveDN .
1128.It Ar private_key
1129Same as the
1130.Fl keyfile
1131option.
1132The file containing the CA private key.
1133Mandatory.
1134.It Ar serial
1135A text file containing the next serial number to use in hex.
1136Mandatory.
1137This file must be present and contain a valid serial number.
1138.It Ar unique_subject
1139If the value
1140.Ar yes
1141is given, the valid certificate entries in the
1142database must have unique subjects.
1143If the value
1144.Ar no
1145is given,
1146several valid certificate entries may have the exact same subject.
1147The default value is
1148.Ar yes .
1149.It Ar x509_extensions
1150The same as
1151.Fl extensions .
1152.El
1153.Sh CA POLICY FORMAT
1154The policy section consists of a set of variables corresponding to
1155certificate DN fields.
1156If the value is
1157.Qq match ,
1158then the field value must match the same field in the CA certificate.
1159If the value is
1160.Qq supplied ,
1161then it must be present.
1162If the value is
1163.Qq optional ,
1164then it may be present.
1165Any fields not mentioned in the policy section
1166are silently deleted, unless the
1167.Fl preserveDN
1168option is set,
1169but this can be regarded more of a quirk than intended behaviour.
1170.Sh SPKAC FORMAT
1171The input to the
1172.Fl spkac
1173command line option is a Netscape signed public key and challenge.
1174This will usually come from the
1175.Em KEYGEN
1176tag in an HTML form to create a new private key.
1177It is, however, possible to create SPKACs using the
1178.Nm spkac
1179utility.
1180.Pp
1181The file should contain the variable SPKAC set to the value of
1182the SPKAC and also the required DN components as name value pairs.
1183If it's necessary to include the same component twice,
1184then it can be preceded by a number and a
1185.Sq \&. .
1186.Sh CA EXAMPLES
1187.Sy Note :
1188these examples assume that the
1189.Nm ca
1190directory structure is already set up and the relevant files already exist.
1191This usually involves creating a CA certificate and private key with
1192.Cm req ,
1193a serial number file and an empty index file and placing them in
1194the relevant directories.
1195.Pp
1196To use the sample configuration file below, the directories
1197.Pa demoCA ,
1198.Pa demoCA/private
1199and
1200.Pa demoCA/newcerts
1201would be created.
1202The CA certificate would be copied to
1203.Pa demoCA/cacert.pem
1204and its private key to
1205.Pa demoCA/private/cakey.pem .
1206A file
1207.Pa demoCA/serial
1208would be created containing, for example,
1209.Qq 01
1210and the empty index file
1211.Pa demoCA/index.txt .
1212.Pp
1213Sign a certificate request:
1214.Pp
1215.Dl $ openssl ca -in req.pem -out newcert.pem
1216.Pp
1217Sign a certificate request, using CA extensions:
1218.Pp
1219.Dl $ openssl ca -in req.pem -extensions v3_ca -out newcert.pem
1220.Pp
1221Generate a CRL:
1222.Pp
1223.Dl $ openssl ca -gencrl -out crl.pem
1224.Pp
1225Sign several requests:
1226.Pp
1227.Dl $ openssl ca -infiles req1.pem req2.pem req3.pem
1228.Pp
1229Certify a Netscape SPKAC:
1230.Pp
1231.Dl $ openssl ca -spkac spkac.txt
1232.Pp
1233A sample SPKAC file
1234.Pq the SPKAC line has been truncated for clarity :
1235.Bd -literal -offset indent
1236SPKAC=MIG0MGAwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAn7PDhCeV/xIxUg8V70YRxK
1237CN=Steve Test
1238emailAddress=steve@openssl.org
12390.OU=OpenSSL Group
12401.OU=Another Group
1241.Ed
1242.Pp
1243A sample configuration file with the relevant sections for
1244.Nm ca :
1245.Bd -literal
1246\& [ ca ]
1247\& default_ca = CA_default # The default ca section
1248
1249\& [ CA_default ]
1250
1251\& dir = ./demoCA # top dir
1252\& database = $dir/index.txt # index file
1253\& new_certs_dir = $dir/newcerts # new certs dir
1254
1255\& certificate = $dir/cacert.pem # The CA cert
1256\& serial = $dir/serial # serial no file
1257\& private_key = $dir/private/cakey.pem# CA private key
1258
1259\& default_days = 365 # how long to certify for
1260\& default_crl_days= 30 # how long before next CRL
1261\& default_md = md5 # md to use
1262
1263\& policy = policy_any # default policy
1264\& email_in_dn = no # Don't add the email into cert DN
1265
1266\& name_opt = ca_default # Subject name display option
1267\& cert_opt = ca_default # Certificate display option
1268\& copy_extensions = none #Don't copy extensions from request
1269
1270\& [ policy_any ]
1271\& countryName = supplied
1272\& stateOrProvinceName = optional
1273\& organizationName = optional
1274\& organizationalUnitName = optional
1275\& commonName = supplied
1276\& emailAddress = optional
1277.Ed
1278.Sh CA FILES
1279.Sy Note :
1280the location of all files can change either by compile time options,
1281configuration file entries, environment variables, or command line options.
1282The values below reflect the default values.
1283.Bd -literal -offset indent
1284/etc/ssl/openssl.cnf - master configuration file
1285\&./demoCA - main CA directory
1286\&./demoCA/cacert.pem - CA certificate
1287\&./demoCA/private/cakey.pem - CA private key
1288\&./demoCA/serial - CA serial number file
1289\&./demoCA/serial.old - CA serial number backup file
1290\&./demoCA/index.txt - CA text database file
1291\&./demoCA/index.txt.old - CA text database backup file
1292\&./demoCA/certs - certificate output file
1293\&./demoCA/.rnd - CA random seed information
1294.Ed
1295.Sh CA ENVIRONMENT VARIABLES
1296.Ev OPENSSL_CONF
1297reflects the location of the master configuration file;
1298it can be overridden by the
1299.Fl config
1300command line option.
1301.Sh CA RESTRICTIONS
1302The text database index file is a critical part of the process,
1303and if corrupted it can be difficult to fix.
1304It is theoretically possible to rebuild the index file from all the
1305issued certificates and a current CRL; however there is no option to do this.
1306.Pp
1307V2 CRL features like delta CRLs are not currently supported.
1308.Pp
1309Although several requests can be input and handled at once, it is only
1310possible to include one SPKAC or self-signed certificate.
1311.Sh CA BUGS
1312The use of an in-memory text database can cause problems when large
1313numbers of certificates are present because, as the name implies,
1314the database has to be kept in memory.
1315.Pp
1316It is not possible to certify two certificates with the same DN; this
1317is a side effect of how the text database is indexed and it cannot easily
1318be fixed without introducing other problems.
1319Some S/MIME clients can use two certificates with the same DN for separate
1320signing and encryption keys.
1321.Pp
1322The
1323.Nm ca
1324command really needs rewriting or the required functionality
1325exposed at either a command or interface level so a more friendly utility
1326.Pq perl script or GUI
1327can handle things properly.
1328The scripts
1329.Nm CA.sh
1330and
1331.Nm CA.pl
1332help a little but not very much.
1333.Pp
1334Any fields in a request that are not present in a policy are silently
1335deleted.
1336This does not happen if the
1337.Fl preserveDN
1338option is used.
1339To enforce the absence of the EMAIL field within the DN, as suggested
1340by RFCs, regardless of the contents of the request's subject the
1341.Fl noemailDN
1342option can be used.
1343The behaviour should be more friendly and configurable.
1344.Pp
1345Cancelling some commands by refusing to certify a certificate can
1346create an empty file.
1347.Sh CA WARNINGS
1348The
1349.Nm ca
1350command is quirky and at times downright unfriendly.
1351.Pp
1352The
1353.Nm ca
1354utility was originally meant as an example of how to do things in a CA.
1355It was not supposed to be used as a full blown CA itself:
1356nevertheless some people are using it for this purpose.
1357.Pp
1358The
1359.Nm ca
1360command is effectively a single user command: no locking is done on the
1361various files, and attempts to run more than one
1362.Nm ca
1363command on the same database can have unpredictable results.
1364.Pp
1365The
1366.Ar copy_extensions
1367option should be used with caution.
1368If care is not taken, it can be a security risk.
1369For example, if a certificate request contains a
1370.Em basicConstraints
1371extension with CA:TRUE and the
1372.Ar copy_extensions
1373value is set to
1374.Ar copyall
1375and the user does not spot
1376this when the certificate is displayed, then this will hand the requestor
1377a valid CA certificate.
1378.Pp
1379This situation can be avoided by setting
1380.Ar copy_extensions
1381to
1382.Ar copy
1383and including
1384.Em basicConstraints
1385with CA:FALSE in the configuration file.
1386Then if the request contains a
1387.Em basicConstraints
1388extension, it will be ignored.
1389.Pp
1390It is advisable to also include values for other extensions such
1391as
1392.Ar keyUsage
1393to prevent a request supplying its own values.
1394.Pp
1395Additional restrictions can be placed on the CA certificate itself.
1396For example if the CA certificate has:
1397.Pp
1398.D1 basicConstraints = CA:TRUE, pathlen:0
1399.Pp
1400then even if a certificate is issued with CA:TRUE it will not be valid.
1401.\"
1402.\" CIPHERS
1403.\"
1404.Sh CIPHERS
1405.Nm openssl ciphers
1406.Op Fl hVv
1407.Op Fl ssl3 | tls1
1408.Op Ar cipherlist
1409.Pp
1410The
1411.Nm ciphers
1412command converts
1413.Nm OpenSSL
1414cipher lists into ordered SSL cipher preference lists.
1415It can be used as a test tool to determine the appropriate cipherlist.
1416.Pp
1417The options are as follows:
1418.Bl -tag -width Ds
1419.It Fl h , \&?
1420Print a brief usage message.
1421.It Fl ssl3
1422Only include SSL v3 ciphers.
1423.It Fl tls1
1424Only include TLS v1 ciphers.
1425.It Fl V
1426Like
1427.Fl v ,
1428but include cipher suite codes in output (hex format).
1429.It Fl v
1430Verbose option.
1431List ciphers with a complete description of protocol version
1432.Pq SSLv3, which includes TLS ,
1433key exchange, authentication, encryption and mac algorithms used along with
1434any key size restrictions and whether the algorithm is classed as an
1435.Em export
1436cipher.
1437Note that without the
1438.Fl v
1439option, ciphers may seem to appear twice in a cipher list;
1440this is when similar ciphers are available for SSL v3/TLS v1.
1441.It Ar cipherlist
1442A cipher list to convert to a cipher preference list.
1443If it is not included, the default cipher list will be used.
1444The format is described below.
1445.El
1446.Sh CIPHERS LIST FORMAT
1447The cipher list consists of one or more
1448.Em cipher strings
1449separated by colons.
1450Commas or spaces are also acceptable separators, but colons are normally used.
1451.Pp
1452The actual
1453.Em cipher string
1454can take several different forms:
1455.Pp
1456It can consist of a single cipher suite such as
1457.Em RC4-SHA .
1458.Pp
1459It can represent a list of cipher suites containing a certain algorithm,
1460or cipher suites of a certain type.
1461For example
1462.Em SHA1
1463represents all cipher suites using the digest algorithm SHA1, and
1464.Em SSLv3
1465represents all SSL v3 algorithms.
1466.Pp
1467Lists of cipher suites can be combined in a single
1468.Em cipher string
1469using the
1470.Sq +
1471character.
1472This is used as a logical
1473.Em and
1474operation.
1475For example,
1476.Em SHA1+DES
1477represents all cipher suites containing the SHA1 and the DES algorithms.
1478.Pp
1479Each cipher string can be optionally preceded by the characters
1480.Sq \&! ,
1481.Sq - ,
1482or
1483.Sq + .
1484.Pp
1485If
1486.Sq !\&
1487is used, then the ciphers are permanently deleted from the list.
1488The ciphers deleted can never reappear in the list even if they are
1489explicitly stated.
1490.Pp
1491If
1492.Sq -
1493is used, then the ciphers are deleted from the list, but some or
1494all of the ciphers can be added again by later options.
1495.Pp
1496If
1497.Sq +
1498is used, then the ciphers are moved to the end of the list.
1499This option doesn't add any new ciphers, it just moves matching existing ones.
1500.Pp
1501If none of these characters is present, the string is just interpreted
1502as a list of ciphers to be appended to the current preference list.
1503If the list includes any ciphers already present, they will be ignored;
1504that is, they will not be moved to the end of the list.
1505.Pp
1506Additionally, the cipher string
1507.Em @STRENGTH
1508can be used at any point to sort the current cipher list in order of
1509encryption algorithm key length.
1510.Sh CIPHERS STRINGS
1511The following is a list of all permitted cipher strings and their meanings.
1512.Bl -tag -width "XXXX"
1513.It Ar DEFAULT
1514The default cipher list.
1515This is determined at compile time and is currently
1516.Ar ALL:!aNULL:!eNULL:!SSLv2 .
1517This must be the first
1518.Ar cipher string
1519specified.
1520.It Ar COMPLEMENTOFDEFAULT
1521The ciphers included in
1522.Ar ALL ,
1523but not enabled by default.
1524Currently this is
1525.Ar ADH .
1526Note that this rule does not cover
1527.Ar eNULL ,
1528which is not included by
1529.Ar ALL
1530(use
1531.Ar COMPLEMENTOFALL
1532if necessary).
1533.It Ar ALL
1534All cipher suites except the
1535.Ar eNULL
1536ciphers which must be explicitly enabled.
1537.It Ar COMPLEMENTOFALL
1538The cipher suites not enabled by
1539.Ar ALL ,
1540currently being
1541.Ar eNULL .
1542.It Ar HIGH
1543.Qq High
1544encryption cipher suites.
1545This currently means those with key lengths larger than 128 bits.
1546.It Ar MEDIUM
1547.Qq Medium
1548encryption cipher suites, currently those using 128-bit encryption.
1549.It Ar LOW
1550.Qq Low
1551encryption cipher suites, currently those using 64- or 56-bit encryption
1552algorithms, but excluding export cipher suites.
1553.It Ar EXP , EXPORT
1554Export encryption algorithms.
1555Including 40- and 56-bit algorithms.
1556.It Ar EXPORT40
155740-bit export encryption algorithms.
1558.It Ar eNULL , NULL
1559The
1560.Qq NULL
1561ciphers; that is, those offering no encryption.
1562Because these offer no encryption at all and are a security risk,
1563they are disabled unless explicitly included.
1564.It Ar aNULL
1565The cipher suites offering no authentication.
1566This is currently the anonymous DH algorithms.
1567These cipher suites are vulnerable to a
1568.Qq man in the middle
1569attack, so their use is normally discouraged.
1570.It Ar kRSA , RSA
1571Cipher suites using RSA key exchange.
1572.It Ar kEDH
1573Cipher suites using ephemeral DH key agreement.
1574.It Ar aRSA
1575Cipher suites using RSA authentication, i.e. the certificates carry RSA keys.
1576.It Ar aDSS , DSS
1577Cipher suites using DSS authentication, i.e. the certificates carry DSS keys.
1578.It Ar TLSv1 , SSLv3
1579TLS v1.0 or SSL v3.0 cipher suites, respectively.
1580.It Ar DH
1581Cipher suites using DH, including anonymous DH.
1582.It Ar ADH
1583Anonymous DH cipher suites.
1584.It Ar AES
1585Cipher suites using AES.
1586.It Ar 3DES
1587Cipher suites using triple DES.
1588.It Ar DES
1589Cipher suites using DES
1590.Pq not triple DES .
1591.It Ar RC4
1592Cipher suites using RC4.
1593.It Ar RC2
1594Cipher suites using RC2.
1595.It Ar MD5
1596Cipher suites using MD5.
1597.It Ar SHA1 , SHA
1598Cipher suites using SHA1.
1599.El
1600.Sh CIPHERS SUITE NAMES
1601The following lists give the SSL or TLS cipher suites names from the
1602relevant specification and their
1603.Nm OpenSSL
1604equivalents.
1605It should be noted that several cipher suite names do not include the
1606authentication used, e.g. DES-CBC3-SHA.
1607In these cases, RSA authentication is used.
1608.Ss SSL v3.0 cipher suites
1609.Bd -unfilled -offset indent
1610SSL_RSA_WITH_NULL_MD5 NULL-MD5
1611SSL_RSA_WITH_NULL_SHA NULL-SHA
1612SSL_RSA_EXPORT_WITH_RC4_40_MD5 EXP-RC4-MD5
1613SSL_RSA_WITH_RC4_128_MD5 RC4-MD5
1614SSL_RSA_WITH_RC4_128_SHA RC4-SHA
1615SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5 EXP-RC2-CBC-MD5
1616SSL_RSA_WITH_IDEA_CBC_SHA IDEA-CBC-SHA
1617SSL_RSA_EXPORT_WITH_DES40_CBC_SHA EXP-DES-CBC-SHA
1618SSL_RSA_WITH_DES_CBC_SHA DES-CBC-SHA
1619SSL_RSA_WITH_3DES_EDE_CBC_SHA DES-CBC3-SHA
1620
1621SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA Not implemented.
1622SSL_DH_DSS_WITH_DES_CBC_SHA Not implemented.
1623SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA Not implemented.
1624SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA Not implemented.
1625SSL_DH_RSA_WITH_DES_CBC_SHA Not implemented.
1626SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA Not implemented.
1627SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA EXP-EDH-DSS-DES-CBC-SHA
1628SSL_DHE_DSS_WITH_DES_CBC_SHA EDH-DSS-CBC-SHA
1629SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA EDH-DSS-DES-CBC3-SHA
1630SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA EXP-EDH-RSA-DES-CBC-SHA
1631SSL_DHE_RSA_WITH_DES_CBC_SHA EDH-RSA-DES-CBC-SHA
1632SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA EDH-RSA-DES-CBC3-SHA
1633
1634SSL_DH_anon_EXPORT_WITH_RC4_40_MD5 EXP-ADH-RC4-MD5
1635SSL_DH_anon_WITH_RC4_128_MD5 ADH-RC4-MD5
1636SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA EXP-ADH-DES-CBC-SHA
1637SSL_DH_anon_WITH_DES_CBC_SHA ADH-DES-CBC-SHA
1638SSL_DH_anon_WITH_3DES_EDE_CBC_SHA ADH-DES-CBC3-SHA
1639
1640SSL_FORTEZZA_KEA_WITH_NULL_SHA Not implemented.
1641SSL_FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA Not implemented.
1642SSL_FORTEZZA_KEA_WITH_RC4_128_SHA Not implemented.
1643.Ed
1644.Ss TLS v1.0 cipher suites
1645.Bd -unfilled -offset indent
1646TLS_RSA_WITH_NULL_MD5 NULL-MD5
1647TLS_RSA_WITH_NULL_SHA NULL-SHA
1648TLS_RSA_EXPORT_WITH_RC4_40_MD5 EXP-RC4-MD5
1649TLS_RSA_WITH_RC4_128_MD5 RC4-MD5
1650TLS_RSA_WITH_RC4_128_SHA RC4-SHA
1651TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 EXP-RC2-CBC-MD5
1652TLS_RSA_WITH_IDEA_CBC_SHA IDEA-CBC-SHA
1653TLS_RSA_EXPORT_WITH_DES40_CBC_SHA EXP-DES-CBC-SHA
1654TLS_RSA_WITH_DES_CBC_SHA DES-CBC-SHA
1655TLS_RSA_WITH_3DES_EDE_CBC_SHA DES-CBC3-SHA
1656
1657TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA Not implemented.
1658TLS_DH_DSS_WITH_DES_CBC_SHA Not implemented.
1659TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA Not implemented.
1660TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA Not implemented.
1661TLS_DH_RSA_WITH_DES_CBC_SHA Not implemented.
1662TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA Not implemented.
1663TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA EXP-EDH-DSS-DES-CBC-SHA
1664TLS_DHE_DSS_WITH_DES_CBC_SHA EDH-DSS-CBC-SHA
1665TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA EDH-DSS-DES-CBC3-SHA
1666TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA EXP-EDH-RSA-DES-CBC-SHA
1667TLS_DHE_RSA_WITH_DES_CBC_SHA EDH-RSA-DES-CBC-SHA
1668TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA EDH-RSA-DES-CBC3-SHA
1669
1670TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 EXP-ADH-RC4-MD5
1671TLS_DH_anon_WITH_RC4_128_MD5 ADH-RC4-MD5
1672TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA EXP-ADH-DES-CBC-SHA
1673TLS_DH_anon_WITH_DES_CBC_SHA ADH-DES-CBC-SHA
1674TLS_DH_anon_WITH_3DES_EDE_CBC_SHA ADH-DES-CBC3-SHA
1675.Ed
1676.Ss AES ciphersuites from RFC 3268, extending TLS v1.0
1677.Bd -unfilled -offset indent
1678TLS_RSA_WITH_AES_128_CBC_SHA AES128-SHA
1679TLS_RSA_WITH_AES_256_CBC_SHA AES256-SHA
1680
1681TLS_DH_DSS_WITH_AES_128_CBC_SHA Not implemented.
1682TLS_DH_DSS_WITH_AES_256_CBC_SHA Not implemented.
1683TLS_DH_RSA_WITH_AES_128_CBC_SHA Not implemented.
1684TLS_DH_RSA_WITH_AES_256_CBC_SHA Not implemented.
1685
1686TLS_DHE_DSS_WITH_AES_128_CBC_SHA DHE-DSS-AES128-SHA
1687TLS_DHE_DSS_WITH_AES_256_CBC_SHA DHE-DSS-AES256-SHA
1688TLS_DHE_RSA_WITH_AES_128_CBC_SHA DHE-RSA-AES128-SHA
1689TLS_DHE_RSA_WITH_AES_256_CBC_SHA DHE-RSA-AES256-SHA
1690
1691TLS_DH_anon_WITH_AES_128_CBC_SHA ADH-AES128-SHA
1692TLS_DH_anon_WITH_AES_256_CBC_SHA ADH-AES256-SHA
1693.Ed
1694.Ss GOST ciphersuites from draft-chudov-cryptopro-cptls, extending TLS v1.0
1695.Sy Note :
1696These ciphers require an engine which includes GOST cryptographic
1697algorithms, such as the
1698.Dq ccgost
1699engine, included in the OpenSSL distribution.
1700.Bd -unfilled -offset indent
1701TLS_GOSTR341094_WITH_28147_CNT_IMIT GOST94-GOST89-GOST89
1702TLS_GOSTR341001_WITH_28147_CNT_IMIT GOST2001-GOST89-GOST89
1703TLS_GOSTR341094_WITH_NULL_GOSTR3411 GOST94-NULL-GOST94
1704TLS_GOSTR341001_WITH_NULL_GOSTR3411 GOST2001-NULL-GOST94
1705.Ed
1706.Ss Additional Export 1024 and other cipher suites
1707.Sy Note :
1708These ciphers can also be used in SSL v3.
1709.Bd -unfilled -offset indent
1710TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA EXP1024-DES-CBC-SHA
1711TLS_RSA_EXPORT1024_WITH_RC4_56_SHA EXP1024-RC4-SHA
1712TLS_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA EXP1024-DHE-DSS-DES-CBC-SHA
1713TLS_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA EXP1024-DHE-DSS-RC4-SHA
1714TLS_DHE_DSS_WITH_RC4_128_SHA DHE-DSS-RC4-SHA
1715.Ed
1716.Sh CIPHERS NOTES
1717The non-ephemeral DH modes are currently unimplemented in
1718.Nm OpenSSL
1719because there is no support for DH certificates.
1720.Pp
1721Some compiled versions of
1722.Nm OpenSSL
1723may not include all the ciphers
1724listed here because some ciphers were excluded at compile time.
1725.Sh CIPHERS EXAMPLES
1726Verbose listing of all
1727.Nm OpenSSL
1728ciphers including NULL ciphers:
1729.Pp
1730.Dl $ openssl ciphers -v 'ALL:eNULL'
1731.Pp
1732Include all ciphers except NULL and anonymous DH then sort by
1733strength:
1734.Pp
1735.Dl $ openssl ciphers -v 'ALL:!ADH:@STRENGTH'
1736.Pp
1737Include only 3DES ciphers and then place RSA ciphers last:
1738.Pp
1739.Dl $ openssl ciphers -v '3DES:+RSA'
1740.Pp
1741Include all RC4 ciphers but leave out those without authentication:
1742.Pp
1743.Dl $ openssl ciphers -v 'RC4:!COMPLEMENTOFDEFAULT'
1744.Pp
1745Include all ciphers with RSA authentication but leave out ciphers without
1746encryption:
1747.Pp
1748.Dl $ openssl ciphers -v 'RSA:!COMPLEMENTOFALL'
1749.Sh CIPHERS HISTORY
1750The
1751.Ar COMPLEMENTOFALL
1752and
1753.Ar COMPLEMENTOFDEFAULT
1754selection options were added in
1755.Nm OpenSSL
17560.9.7.
1757.Pp
1758The
1759.Fl V
1760option of the
1761.Nm ciphers
1762command was added in
1763.Nm OpenSSL
17641.0.0.
1765.\"
1766.\" CRL
1767.\"
1768.Sh CRL
1769.nr nS 1
1770.Nm "openssl crl"
1771.Bk -words
1772.Op Fl CAfile Ar file
1773.Op Fl CApath Ar dir
1774.Op Fl fingerprint
1775.Op Fl hash
1776.Op Fl in Ar file
1777.Op Fl inform Ar DER | PEM
1778.Op Fl issuer
1779.Op Fl lastupdate
1780.Op Fl nextupdate
1781.Op Fl noout
1782.Op Fl out Ar file
1783.Op Fl outform Ar DER | PEM
1784.Op Fl text
1785.Ek
1786.nr nS 0
1787.Pp
1788The
1789.Nm crl
1790command processes CRL files in DER or PEM format.
1791.Pp
1792The options are as follows:
1793.Bl -tag -width Ds
1794.It Fl CAfile Ar file
1795Verify the signature on a CRL by looking up the issuing certificate in
1796.Ar file .
1797.It Fl CApath Ar directory
1798Verify the signature on a CRL by looking up the issuing certificate in
1799.Ar dir .
1800This directory must be a standard certificate directory,
1801i.e. a hash of each subject name (using
1802.Cm x509 Fl hash )
1803should be linked to each certificate.
1804.It Fl fingerprint
1805Print the CRL fingerprint.
1806.It Fl hash
1807Output a hash of the issuer name.
1808This can be used to look up CRLs in a directory by issuer name.
1809.It Fl in Ar file
1810This specifies the input file to read from, or standard input if this
1811option is not specified.
1812.It Fl inform Ar DER | PEM
1813This specifies the input format.
1814.Ar DER
1815format is a DER-encoded CRL structure.
1816.Ar PEM
1817.Pq the default
1818is a base64-encoded version of the DER form with header and footer lines.
1819.It Fl issuer
1820Output the issuer name.
1821.It Fl lastupdate
1822Output the
1823.Ar lastUpdate
1824field.
1825.It Fl nextupdate
1826Output the
1827.Ar nextUpdate
1828field.
1829.It Fl noout
1830Don't output the encoded version of the CRL.
1831.It Fl out Ar file
1832Specifies the output file to write to, or standard output by
1833default.
1834.It Fl outform Ar DER | PEM
1835This specifies the output format; the options have the same meaning as the
1836.Fl inform
1837option.
1838.It Fl text
1839Print out the CRL in text form.
1840.El
1841.Sh CRL NOTES
1842The PEM CRL format uses the header and footer lines:
1843.Bd -unfilled -offset indent
1844-----BEGIN X509 CRL-----
1845-----END X509 CRL-----
1846.Ed
1847.Sh CRL EXAMPLES
1848Convert a CRL file from PEM to DER:
1849.Pp
1850.Dl $ openssl crl -in crl.pem -outform DER -out crl.der
1851.Pp
1852Output the text form of a DER-encoded certificate:
1853.Pp
1854.Dl $ openssl crl -in crl.der -inform DER -text -noout
1855.Sh CRL BUGS
1856Ideally, it should be possible to create a CRL using appropriate options
1857and files too.
1858.\"
1859.\" CRL2PKCS7
1860.\"
1861.Sh CRL2PKCS7
1862.nr nS 1
1863.Nm "openssl crl2pkcs7"
1864.Bk -words
1865.Op Fl certfile Ar file
1866.Op Fl in Ar file
1867.Op Fl inform Ar DER | PEM
1868.Op Fl nocrl
1869.Op Fl out Ar file
1870.Op Fl outform Ar DER | PEM
1871.Ek
1872.nr nS 0
1873.Pp
1874The
1875.Nm crl2pkcs7
1876command takes an optional CRL and one or more
1877certificates and converts them into a PKCS#7 degenerate
1878.Qq certificates only
1879structure.
1880.Pp
1881The options are as follows:
1882.Bl -tag -width Ds
1883.It Fl certfile Ar file
1884Specifies a
1885.Ar file
1886containing one or more certificates in PEM format.
1887All certificates in the file will be added to the PKCS#7 structure.
1888This option can be used more than once to read certificates from multiple
1889files.
1890.It Fl in Ar file
1891This specifies the input
1892.Ar file
1893to read a CRL from, or standard input if this option is not specified.
1894.It Fl inform Ar DER | PEM
1895This specifies the CRL input format.
1896.Ar DER
1897format is a DER-encoded CRL structure.
1898.Ar PEM
1899.Pq the default
1900is a base64-encoded version of the DER form with header and footer lines.
1901.It Fl nocrl
1902Normally, a CRL is included in the output file.
1903With this option, no CRL is
1904included in the output file and a CRL is not read from the input file.
1905.It Fl out Ar file
1906Specifies the output
1907.Ar file
1908to write the PKCS#7 structure to, or standard output by default.
1909.It Fl outform Ar DER | PEM
1910This specifies the PKCS#7 structure output format.
1911.Ar DER
1912format is a DER-encoded PKCS#7 structure.
1913.Ar PEM
1914.Pq the default
1915is a base64-encoded version of the DER form with header and footer lines.
1916.El
1917.Sh CRL2PKCS7 EXAMPLES
1918Create a PKCS#7 structure from a certificate and CRL:
1919.Pp
1920.Dl $ openssl crl2pkcs7 -in crl.pem -certfile cert.pem -out p7.pem
1921.Pp
1922Create a PKCS#7 structure in DER format with no CRL from several
1923different certificates:
1924.Bd -literal -offset indent
1925$ openssl crl2pkcs7 -nocrl -certfile newcert.pem \e
1926 -certfile demoCA/cacert.pem -outform DER -out p7.der
1927.Ed
1928.Sh CRL2PKCS7 NOTES
1929The output file is a PKCS#7 signed data structure containing no signers and
1930just certificates and an optional CRL.
1931.Pp
1932This utility can be used to send certificates and CAs to Netscape as part of
1933the certificate enrollment process.
1934This involves sending the DER-encoded output
1935as MIME type
1936.Em application/x-x509-user-cert .
1937.Pp
1938The PEM-encoded form with the header and footer lines removed can be used to
1939install user certificates and CAs in MSIE using the Xenroll control.
1940.\"
1941.\" DGST
1942.\"
1943.Sh DGST
1944.nr nS 1
1945.Nm "openssl dgst"
1946.Bk -words
1947.Oo
1948.Fl dss1 | md2 | md4 | md5 |
1949.Fl ripemd160 | sha | sha1
1950.Oc
1951.Op Fl binary
1952.Op Fl cd
1953.Op Fl engine Ar id
1954.Op Fl hex
1955.Op Fl hmac Ar key
1956.Op Fl keyform Ar ENGINE | PEM
1957.Op Fl mac Ar algorithm
1958.Op Fl macopt Ar nm : Ns Ar v
1959.Op Fl out Ar file
1960.Op Fl passin Ar arg
1961.Op Fl prverify Ar file
1962.Op Fl sign Ar file
1963.Op Fl signature Ar file
1964.Op Fl sigopt Ar nm : Ns Ar v
1965.Op Fl verify Ar file
1966.Op Ar
1967.Ek
1968.nr nS 0
1969.Pp
1970.Nm openssl
1971.Cm md2 | md4 | md5 |
1972.Cm ripemd160 | sha | sha1
1973.Op Fl c
1974.Op Fl d
1975.Op Ar
1976.Pp
1977The digest functions output the message digest of a supplied
1978.Ar file
1979or
1980.Ar files
1981in hexadecimal form.
1982They can also be used for digital signing and verification.
1983.Pp
1984The options are as follows:
1985.Bl -tag -width Ds
1986.It Fl binary
1987Output the digest or signature in binary form.
1988.It Fl c
1989Print out the digest in two-digit groups separated by colons; only relevant if
1990.Em hex
1991format output is used.
1992.It Fl d
1993Print out BIO debugging information.
1994.It Fl engine Ar id
1995Specifying an engine (by its unique
1996.Ar id
1997string) will cause
1998.Nm dgst
1999to attempt to obtain a functional reference to the specified engine,
2000thus initialising it if needed.
2001The engine will then be set as the default for all available algorithms.
2002This engine is not used as a source for digest algorithms
2003unless it is also specified in the configuration file.
2004.It Fl hex
2005Digest is to be output as a hex dump.
2006This is the default case for a
2007.Qq normal
2008digest as opposed to a digital signature.
2009.It Fl hmac Ar key
2010Create a hashed MAC using
2011.Ar key .
2012.It Fl keyform Ar ENGINE | PEM
2013Specifies the key format to sign the digest with.
2014.It Fl mac Ar algorithm
2015Create a keyed Message Authentication Code (MAC).
2016The most popular MAC algorithm is HMAC (hash-based MAC),
2017but there are other MAC algorithms which are not based on hash.
2018MAC keys and other options should be set via the
2019.Fl macopt
2020parameter.
2021.It Fl macopt Ar nm : Ns Ar v
2022Passes options to the MAC algorithm, specified by
2023.Fl mac .
2024The following options are supported by HMAC:
2025.Bl -tag -width Ds
2026.It Ar key : Ns Ar string
2027Specifies the MAC key as an alphanumeric string
2028(use if the key contain printable characters only).
2029String length must conform to any restrictions of the MAC algorithm.
2030.It Ar hexkey : Ns Ar string
2031Specifies the MAC key in hexadecimal form (two hex digits per byte).
2032Key length must conform to any restrictions of the MAC algorithm.
2033.El
2034.It Fl out Ar file
2035The file to output to, or standard output by default.
2036.It Fl passin Ar arg
2037The key password source.
2038For more information about the format of
2039.Ar arg ,
2040see the
2041.Sx PASS PHRASE ARGUMENTS
2042section above.
2043.It Fl prverify Ar file
2044Verify the signature using the private key in
2045.Ar file .
2046The output is either
2047.Qq Verification OK
2048or
2049.Qq Verification Failure .
2050.It Fl sign Ar file
2051Digitally sign the digest using the private key in
2052.Ar file .
2053.It Fl signature Ar file
2054The actual signature to verify.
2055.It Fl sigopt Ar nm : Ns Ar v
2056Pass options to the signature algorithm during sign or verify operations.
2057The names and values of these options are algorithm-specific.
2058.It Fl verify Ar file
2059Verify the signature using the public key in
2060.Ar file .
2061The output is either
2062.Qq Verification OK
2063or
2064.Qq Verification Failure .
2065.It Ar
2066File or files to digest.
2067If no files are specified then standard input is used.
2068.El
2069.Sh DGST NOTES
2070The digest of choice for all new applications is SHA1.
2071Other digests are, however, still widely used.
2072.Pp
2073If you wish to sign or verify data using the DSA algorithm, the dss1
2074digest must be used.
2075.Pp
2076A source of random numbers is required for certain signing algorithms, in
2077particular DSA.
2078.Pp
2079The signing and verify options should only be used if a single file is
2080being signed or verified.
2081.\"
2082.\" DH
2083.\"
2084.Sh DH
2085Diffie-Hellman Parameter Management.
2086The
2087.Nm dh
2088command has been replaced by
2089.Nm dhparam .
2090See
2091.Sx DHPARAM
2092below.
2093.\"
2094.\" DHPARAM
2095.\"
2096.Sh DHPARAM
2097.nr nS 1
2098.Nm "openssl dhparam"
2099.Bk -words
2100.Op Fl 2 | 5
2101.Op Fl C
2102.Op Fl check
2103.Op Fl dsaparam
2104.Op Fl engine Ar id
2105.Op Fl in Ar file
2106.Op Fl inform Ar DER | PEM
2107.Op Fl noout
2108.Op Fl out Ar file
2109.Op Fl outform Ar DER | PEM
2110.Op Fl text
2111.Op Ar numbits
2112.Ek
2113.nr nS 0
2114.Pp
2115The
2116.Nm dhparam
2117command is used to manipulate DH parameter files.
2118.Pp
2119The options are as follows:
2120.Bl -tag -width Ds
2121.It Fl 2 , 5
2122The generator to use, either 2 or 5.
21232 is the default.
2124If present, the input file is ignored and parameters are generated instead.
2125.It Fl C
2126This option converts the parameters into C code.
2127The parameters can then be loaded by calling the
2128.Cm get_dh Ns Ar numbits Ns Li ()
2129function.
2130.It Fl check
2131Check the DH parameters.
2132.It Fl dsaparam
2133If this option is used, DSA rather than DH parameters are read or created;
2134they are converted to DH format.
2135Otherwise,
2136.Qq strong
2137primes
2138.Pq such that (p-1)/2 is also prime
2139will be used for DH parameter generation.
2140.Pp
2141DH parameter generation with the
2142.Fl dsaparam
2143option is much faster,
2144and the recommended exponent length is shorter,
2145which makes DH key exchange more efficient.
2146Beware that with such DSA-style DH parameters,
2147a fresh DH key should be created for each use to
2148avoid small-subgroup attacks that may be possible otherwise.
2149.It Fl engine Ar id
2150Specifying an engine (by its unique
2151.Ar id
2152string) will cause
2153.Nm dhparam
2154to attempt to obtain a functional reference to the specified engine,
2155thus initialising it if needed.
2156The engine will then be set as the default for all available algorithms.
2157.It Fl in Ar file
2158This specifies the input
2159.Ar file
2160to read parameters from, or standard input if this option is not specified.
2161.It Fl inform Ar DER | PEM
2162This specifies the input format.
2163The argument
2164.Ar DER
2165uses an ASN1 DER-encoded form compatible with the PKCS#3 DHparameter
2166structure.
2167The
2168.Ar PEM
2169form is the default format:
2170it consists of the DER format base64-encoded with
2171additional header and footer lines.
2172.It Fl noout
2173This option inhibits the output of the encoded version of the parameters.
2174.It Ar numbits
2175This argument specifies that a parameter set should be generated of size
2176.Ar numbits .
2177It must be the last option.
2178If not present, a value of 512 is used.
2179If this value is present, the input file is ignored and
2180parameters are generated instead.
2181.It Fl out Ar file
2182This specifies the output
2183.Ar file
2184to write parameters to.
2185Standard output is used if this option is not present.
2186The output filename should
2187.Em not
2188be the same as the input filename.
2189.It Fl outform Ar DER | PEM
2190This specifies the output format; the options have the same meaning as the
2191.Fl inform
2192option.
2193.It Fl text
2194This option prints out the DH parameters in human readable form.
2195.El
2196.Sh DHPARAM WARNINGS
2197The program
2198.Nm dhparam
2199combines the functionality of the programs
2200.Nm dh
2201and
2202.Nm gendh
2203in previous versions of
2204.Nm OpenSSL
2205and
2206.Nm SSLeay .
2207The
2208.Nm dh
2209and
2210.Nm gendh
2211programs are retained for now, but may have different purposes in future
2212versions of
2213.Nm OpenSSL .
2214.Sh DHPARAM NOTES
2215PEM format DH parameters use the header and footer lines:
2216.Bd -unfilled -offset indent
2217-----BEGIN DH PARAMETERS-----
2218-----END DH PARAMETERS-----
2219.Ed
2220.Pp
2221.Nm OpenSSL
2222currently only supports the older PKCS#3 DH,
2223not the newer X9.42 DH.
2224.Pp
2225This program manipulates DH parameters not keys.
2226.Sh DHPARAM BUGS
2227There should be a way to generate and manipulate DH keys.
2228.Sh DHPARAM HISTORY
2229The
2230.Nm dhparam
2231command was added in
2232.Nm OpenSSL
22330.9.5.
2234The
2235.Fl dsaparam
2236option was added in
2237.Nm OpenSSL
22380.9.6.
2239.\"
2240.\" DSA
2241.\"
2242.Sh DSA
2243.nr nS 1
2244.Nm "openssl dsa"
2245.Bk -words
2246.Oo
2247.Fl aes128 | aes192 | aes256 |
2248.Fl des | des3
2249.Oc
2250.Op Fl engine Ar id
2251.Op Fl in Ar file
2252.Op Fl inform Ar DER | PEM
2253.Op Fl modulus
2254.Op Fl noout
2255.Op Fl out Ar file
2256.Op Fl outform Ar DER | PEM
2257.Op Fl passin Ar arg
2258.Op Fl passout Ar arg
2259.Op Fl pubin
2260.Op Fl pubout
2261.Op Fl text
2262.Ek
2263.nr nS 0
2264.Pp
2265The
2266.Nm dsa
2267command processes DSA keys.
2268They can be converted between various forms and their components printed out.
2269.Pp
2270.Sy Note :
2271This command uses the traditional
2272.Nm SSLeay
2273compatible format for private key encryption:
2274newer applications should use the more secure PKCS#8 format using the
2275.Nm pkcs8
2276command.
2277.Pp
2278The options are as follows:
2279.Bl -tag -width Ds
2280.It Xo
2281.Fl aes128 | aes192 | aes256 |
2282.Fl des | des3
2283.Xc
2284These options encrypt the private key with the AES, DES, or the triple DES
2285ciphers, respectively, before outputting it.
2286A pass phrase is prompted for.
2287If none of these options is specified, the key is written in plain text.
2288This means that using the
2289.Nm dsa
2290utility to read in an encrypted key with no encryption option can be used to
2291remove the pass phrase from a key,
2292or by setting the encryption options it can be use to add or change
2293the pass phrase.
2294These options can only be used with PEM format output files.
2295.It Fl engine Ar id
2296Specifying an engine (by its unique
2297.Ar id
2298string) will cause
2299.Nm dsa
2300to attempt to obtain a functional reference to the specified engine,
2301thus initialising it if needed.
2302The engine will then be set as the default for all available algorithms.
2303.It Fl in Ar file
2304This specifies the input
2305.Ar file
2306to read a key from, or standard input if this option is not specified.
2307If the key is encrypted, a pass phrase will be prompted for.
2308.It Fl inform Ar DER | PEM
2309This specifies the input format.
2310The
2311.Ar DER
2312argument with a private key uses an ASN1 DER-encoded form of an ASN.1
2313SEQUENCE consisting of the values of version
2314.Pq currently zero ,
2315P, Q, G,
2316and the public and private key components, respectively, as ASN.1 INTEGERs.
2317When used with a public key it uses a
2318.Em SubjectPublicKeyInfo
2319structure: it is an error if the key is not DSA.
2320.Pp
2321The
2322.Ar PEM
2323form is the default format:
2324it consists of the DER format base64-encoded with additional header and footer
2325lines.
2326In the case of a private key, PKCS#8 format is also accepted.
2327.It Fl modulus
2328This option prints out the value of the public key component of the key.
2329.It Fl noout
2330This option prevents output of the encoded version of the key.
2331.It Fl out Ar file
2332This specifies the output
2333.Ar file
2334to write a key to, or standard output if not specified.
2335If any encryption options are set then a pass phrase will be
2336prompted for.
2337The output filename should
2338.Em not
2339be the same as the input filename.
2340.It Fl outform Ar DER | PEM
2341This specifies the output format; the options have the same meaning as the
2342.Fl inform
2343option.
2344.It Fl passin Ar arg
2345The key password source.
2346For more information about the format of
2347.Ar arg ,
2348see the
2349.Sx PASS PHRASE ARGUMENTS
2350section above.
2351.It Fl passout Ar arg
2352The output file password source.
2353For more information about the format of
2354.Ar arg ,
2355see the
2356.Sx PASS PHRASE ARGUMENTS
2357section above.
2358.It Fl pubin
2359By default, a private key is read from the input file.
2360With this option a public key is read instead.
2361.It Fl pubout
2362By default, a private key is output.
2363With this option a public key will be output instead.
2364This option is automatically set if the input is a public key.
2365.It Fl text
2366Prints out the public/private key components and parameters.
2367.El
2368.Sh DSA NOTES
2369The PEM private key format uses the header and footer lines:
2370.Bd -unfilled -offset indent
2371-----BEGIN DSA PRIVATE KEY-----
2372-----END DSA PRIVATE KEY-----
2373.Ed
2374.Pp
2375The PEM public key format uses the header and footer lines:
2376.Bd -unfilled -offset indent
2377-----BEGIN PUBLIC KEY-----
2378-----END PUBLIC KEY-----
2379.Ed
2380.Sh DSA EXAMPLES
2381To remove the pass phrase on a DSA private key:
2382.Pp
2383.Dl $ openssl dsa -in key.pem -out keyout.pem
2384.Pp
2385To encrypt a private key using triple DES:
2386.Pp
2387.Dl $ openssl dsa -in key.pem -des3 -out keyout.pem
2388.Pp
2389To convert a private key from PEM to DER format:
2390.Pp
2391.Dl $ openssl dsa -in key.pem -outform DER -out keyout.der
2392.Pp
2393To print out the components of a private key to standard output:
2394.Pp
2395.Dl $ openssl dsa -in key.pem -text -noout
2396.Pp
2397To just output the public part of a private key:
2398.Pp
2399.Dl $ openssl dsa -in key.pem -pubout -out pubkey.pem
2400.\"
2401.\" DSAPARAM
2402.\"
2403.Sh DSAPARAM
2404.nr nS 1
2405.Nm "openssl dsaparam"
2406.Bk -words
2407.Op Fl C
2408.Op Fl engine Ar id
2409.Op Fl genkey
2410.Op Fl in Ar file
2411.Op Fl inform Ar DER | PEM
2412.Op Fl noout
2413.Op Fl out Ar file
2414.Op Fl outform Ar DER | PEM
2415.Op Fl text
2416.Op Ar numbits
2417.Ek
2418.nr nS 0
2419.Pp
2420The
2421.Nm dsaparam
2422command is used to manipulate or generate DSA parameter files.
2423.Pp
2424The options are as follows:
2425.Bl -tag -width Ds
2426.It Fl C
2427This option converts the parameters into C code.
2428The parameters can then be loaded by calling the
2429.Cm get_dsa Ns Ar XXX Ns Li ()
2430function.
2431.It Fl engine Ar id
2432Specifying an engine (by its unique
2433.Ar id
2434string) will cause
2435.Nm dsaparam
2436to attempt to obtain a functional reference to the specified engine,
2437thus initialising it if needed.
2438The engine will then be set as the default for all available algorithms.
2439.It Fl genkey
2440This option will generate a DSA either using the specified or generated
2441parameters.
2442.It Fl in Ar file
2443This specifies the input
2444.Ar file
2445to read parameters from, or standard input if this option is not specified.
2446If the
2447.Ar numbits
2448parameter is included, then this option will be ignored.
2449.It Fl inform Ar DER | PEM
2450This specifies the input format.
2451The
2452.Ar DER
2453argument uses an ASN1 DER-encoded form compatible with RFC 2459
2454.Pq PKIX
2455DSS-Parms that is a SEQUENCE consisting of p, q and g, respectively.
2456The
2457.Ar PEM
2458form is the default format:
2459it consists of the DER format base64-encoded with additional header
2460and footer lines.
2461.It Fl noout
2462This option inhibits the output of the encoded version of the parameters.
2463.It Ar numbits
2464This option specifies that a parameter set should be generated of size
2465.Ar numbits .
2466If this option is included, the input file
2467.Pq if any
2468is ignored.
2469.It Fl out Ar file
2470This specifies the output
2471.Ar file
2472to write parameters to.
2473Standard output is used if this option is not present.
2474The output filename should
2475.Em not
2476be the same as the input filename.
2477.It Fl outform Ar DER | PEM
2478This specifies the output format; the options have the same meaning as the
2479.Fl inform
2480option.
2481.It Fl text
2482This option prints out the DSA parameters in human readable form.
2483.El
2484.Sh DSAPARAM NOTES
2485PEM format DSA parameters use the header and footer lines:
2486.Bd -unfilled -offset indent
2487-----BEGIN DSA PARAMETERS-----
2488-----END DSA PARAMETERS-----
2489.Ed
2490.Pp
2491DSA parameter generation is a slow process and as a result the same set of
2492DSA parameters is often used to generate several distinct keys.
2493.\"
2494.\" EC
2495.\"
2496.Sh EC
2497.nr nS 1
2498.Nm "openssl ec"
2499.Bk -words
2500.Op Fl conv_form Ar arg
2501.Op Fl des
2502.Op Fl des3
2503.Op Fl engine Ar id
2504.Op Fl in Ar file
2505.Op Fl inform Ar DER | PEM
2506.Op Fl noout
2507.Op Fl out Ar file
2508.Op Fl outform Ar DER | PEM
2509.Op Fl param_enc Ar arg
2510.Op Fl param_out
2511.Op Fl passin Ar arg
2512.Op Fl passout Ar arg
2513.Op Fl pubin
2514.Op Fl pubout
2515.Op Fl text
2516.Ek
2517.nr nS 0
2518.Pp
2519The
2520.Nm ec
2521command processes EC keys.
2522They can be converted between various
2523forms and their components printed out.
2524Note:
2525.Nm OpenSSL
2526uses the private key format specified in
2527.Dq SEC 1: Elliptic Curve Cryptography
2528.Pq Lk http://www.secg.org/ .
2529To convert an
2530.Nm OpenSSL
2531EC private key into the PKCS#8 private key format use the
2532.Nm pkcs8
2533command.
2534.Pp
2535The options are as follows:
2536.Bl -tag -width Ds
2537.It Fl conv_form Ar arg
2538This specifies how the points on the elliptic curve are converted
2539into octet strings.
2540Possible values are:
2541.Cm compressed
2542(the default value),
2543.Cm uncompressed ,
2544and
2545.Cm hybrid .
2546For more information regarding
2547the point conversion forms please read the X9.62 standard.
2548Note:
2549Due to patent issues the
2550.Cm compressed
2551option is disabled by default for binary curves
2552and can be enabled by defining the preprocessor macro
2553.Ar OPENSSL_EC_BIN_PT_COMP
2554at compile time.
2555.It Fl des | des3
2556These options encrypt the private key with the DES, triple DES, or
2557any other cipher supported by
2558.Nm OpenSSL
2559before outputting it.
2560A pass phrase is prompted for.
2561If none of these options is specified the key is written in plain text.
2562This means that using the
2563.Nm ec
2564utility to read in an encrypted key with no
2565encryption option can be used to remove the pass phrase from a key,
2566or by setting the encryption options
2567it can be use to add or change the pass phrase.
2568These options can only be used with PEM format output files.
2569.It Fl engine Ar id
2570Specifying an engine (by its unique
2571.Ar id
2572string) will cause
2573.Nm ec
2574to attempt to obtain a functional reference to the specified engine,
2575thus initialising it if needed.
2576The engine will then be set as the default for all available algorithms.
2577.It Fl in Ar file
2578This specifies the input filename to read a key from,
2579or standard input if this option is not specified.
2580If the key is encrypted a pass phrase will be prompted for.
2581.It Fl inform Ar DER | PEM
2582This specifies the input format.
2583DER with a private key uses
2584an ASN.1 DER-encoded SEC1 private key.
2585When used with a public key it
2586uses the SubjectPublicKeyInfo structure as specified in RFC 3280.
2587PEM is the default format:
2588it consists of the DER format base64
2589encoded with additional header and footer lines.
2590In the case of a private key
2591PKCS#8 format is also accepted.
2592.It Fl noout
2593Prevents output of the encoded version of the key.
2594.It Fl out Ar file
2595Specifies the output filename to write a key to,
2596or standard output if none is specified.
2597If any encryption options are set then a pass phrase will be prompted for.
2598The output filename should
2599.Em not
2600be the same as the input filename.
2601.It Fl outform Ar DER | PEM
2602This specifies the output format.
2603The options have the same meaning as the
2604.Fl inform
2605option.
2606.It Fl param_enc Ar arg
2607This specifies how the elliptic curve parameters are encoded.
2608Possible value are:
2609.Cm named_curve ,
2610i.e. the EC parameters are specified by an OID; or
2611.Cm explicit ,
2612where the EC parameters are explicitly given
2613(see RFC 3279 for the definition of the EC parameter structures).
2614The default value is
2615.Cm named_curve .
2616Note: the
2617.Cm implicitlyCA
2618alternative,
2619as specified in RFC 3279,
2620is currently not implemented in
2621.Nm OpenSSL .
2622.It Fl passin Ar arg
2623The key password source.
2624For more information about the format of
2625.Ar arg ,
2626see the
2627.Sx PASS PHRASE ARGUMENTS
2628section above.
2629.It Fl passout Ar arg
2630The output file password source.
2631For more information about the format of
2632.Ar arg ,
2633see the
2634.Sx PASS PHRASE ARGUMENTS
2635section above.
2636.It Fl pubin
2637By default a private key is read from the input file;
2638with this option a public key is read instead.
2639.It Fl pubout
2640By default a private key is output;
2641with this option a public key is output instead.
2642This option is automatically set if the input is a public key.
2643.It Fl text
2644Prints out the public/private key components and parameters.
2645.El
2646.Sh EC NOTES
2647The PEM private key format uses the header and footer lines:
2648.Bd -literal -offset indent
2649-----BEGIN EC PRIVATE KEY-----
2650-----END EC PRIVATE KEY-----
2651.Ed
2652.Pp
2653The PEM public key format uses the header and footer lines:
2654.Bd -literal -offset indent
2655-----BEGIN PUBLIC KEY-----
2656-----END PUBLIC KEY-----
2657.Ed
2658.Sh EC EXAMPLES
2659To encrypt a private key using triple DES:
2660.Bd -literal -offset indent
2661$ openssl ec -in key.pem -des3 -out keyout.pem
2662.Ed
2663.Pp
2664To convert a private key from PEM to DER format:
2665.Bd -literal -offset indent
2666$ openssl ec -in key.pem -outform DER -out keyout.der
2667.Ed
2668.Pp
2669To print out the components of a private key to standard output:
2670.Bd -literal -offset indent
2671$ openssl ec -in key.pem -text -noout
2672.Ed
2673.Pp
2674To just output the public part of a private key:
2675.Bd -literal -offset indent
2676$ openssl ec -in key.pem -pubout -out pubkey.pem
2677.Ed
2678.Pp
2679To change the parameter encoding to
2680.Cm explicit :
2681.Bd -literal -offset indent
2682$ openssl ec -in key.pem -param_enc explicit -out keyout.pem
2683.Ed
2684.Pp
2685To change the point conversion form to
2686.Cm compressed :
2687.Bd -literal -offset indent
2688$ openssl ec -in key.pem -conv_form compressed -out keyout.pem
2689.Ed
2690.Sh EC HISTORY
2691The
2692.Nm ec
2693command was first introduced in
2694.Nm OpenSSL
26950.9.8.
2696.Sh EC AUTHORS
2697.An Nils Larsch .
2698.\"
2699.\" ECPARAM
2700.\"
2701.Sh ECPARAM
2702.nr nS 1
2703.Nm "openssl ecparam"
2704.Bk -words
2705.Op Fl C
2706.Op Fl check
2707.Op Fl conv_form Ar arg
2708.Op Fl engine Ar id
2709.Op Fl genkey
2710.Op Fl in Ar file
2711.Op Fl inform Ar DER | PEM
2712.Op Fl list_curves
2713.Op Fl name Ar arg
2714.Op Fl no_seed
2715.Op Fl noout
2716.Op Fl out Ar file
2717.Op Fl outform Ar DER | PEM
2718.Op Fl param_enc Ar arg
2719.Op Fl text
2720.Ek
2721.nr nS 0
2722.Pp
2723This command is used to manipulate or generate EC parameter files.
2724.Pp
2725The options are as follows:
2726.Bl -tag -width Ds
2727.It Fl C
2728Convert the EC parameters into C code.
2729The parameters can then be loaded by calling the
2730.Fn get_ec_group_XXX
2731function.
2732.It Fl check
2733Validate the elliptic curve parameters.
2734.It Fl conv_form Ar arg
2735Specify how the points on the elliptic curve are converted
2736into octet strings.
2737Possible values are:
2738.Cm compressed
2739(the default value),
2740.Cm uncompressed ,
2741and
2742.Cm hybrid .
2743For more information regarding
2744the point conversion forms please read the X9.62 standard.
2745Note:
2746Due to patent issues the
2747.Cm compressed
2748option is disabled by default for binary curves
2749and can be enabled by defining the preprocessor macro
2750.Ar OPENSSL_EC_BIN_PT_COMP
2751at compile time.
2752.It Fl engine Ar id
2753Specifying an engine (by its unique
2754.Ar id
2755string) will cause
2756.Nm ecparam
2757to attempt to obtain a functional reference to the specified engine,
2758thus initialising it if needed.
2759The engine will then be set as the default for all available algorithms.
2760.It Fl genkey
2761Generate an EC private key using the specified parameters.
2762.It Fl in Ar file
2763Specify the input filename to read parameters from or standard input if
2764this option is not specified.
2765.It Fl inform Ar DER | PEM
2766Specify the input format.
2767DER uses an ASN.1 DER-encoded
2768form compatible with RFC 3279 EcpkParameters.
2769PEM is the default format:
2770it consists of the DER format base64 encoded with additional
2771header and footer lines.
2772.It Fl list_curves
2773Print out a list of all
2774currently implemented EC parameter names and exit.
2775.It Fl name Ar arg
2776Use the EC parameters with the specified 'short' name.
2777Use
2778.Fl list_curves
2779to get a list of all currently implemented EC parameters.
2780.It Fl no_seed
2781Inhibit that the 'seed' for the parameter generation
2782is included in the ECParameters structure (see RFC 3279).
2783.It Fl noout
2784Inhibit the output of the encoded version of the parameters.
2785.It Fl out Ar file
2786Specify the output filename parameters are written to.
2787Standard output is used if this option is not present.
2788The output filename should
2789.Em not
2790be the same as the input filename.
2791.It Fl outform Ar DER | PEM
2792Specify the output format;
2793the parameters have the same meaning as the
2794.Fl inform
2795option.
2796.It Fl param_enc Ar arg
2797This specifies how the elliptic curve parameters are encoded.
2798Possible value are:
2799.Cm named_curve ,
2800i.e. the EC parameters are specified by an OID, or
2801.Cm explicit ,
2802where the EC parameters are explicitly given
2803(see RFC 3279 for the definition of the EC parameter structures).
2804The default value is
2805.Cm named_curve .
2806Note: the
2807.Cm implicitlyCA
2808alternative, as specified in RFC 3279,
2809is currently not implemented in
2810.Nm OpenSSL .
2811.It Fl text
2812Print out the EC parameters in human readable form.
2813.El
2814.Sh ECPARAM NOTES
2815PEM format EC parameters use the header and footer lines:
2816.Bd -literal -offset indent
2817-----BEGIN EC PARAMETERS-----
2818-----END EC PARAMETERS-----
2819.Ed
2820.Pp
2821.Nm OpenSSL
2822is currently not able to generate new groups and therefore
2823.Nm ecparam
2824can only create EC parameters from known (named) curves.
2825.Sh ECPARAM EXAMPLES
2826To create EC parameters with the group 'prime192v1':
2827.Bd -literal -offset indent
2828$ openssl ecparam -out ec_param.pem -name prime192v1
2829.Ed
2830.Pp
2831To create EC parameters with explicit parameters:
2832.Bd -literal -offset indent
2833$ openssl ecparam -out ec_param.pem -name prime192v1 \e
2834 -param_enc explicit
2835.Ed
2836.Pp
2837To validate given EC parameters:
2838.Bd -literal -offset indent
2839$ openssl ecparam -in ec_param.pem -check
2840.Ed
2841.Pp
2842To create EC parameters and a private key:
2843.Bd -literal -offset indent
2844$ openssl ecparam -out ec_key.pem -name prime192v1 -genkey
2845.Ed
2846.Pp
2847To change the point encoding to 'compressed':
2848.Bd -literal -offset indent
2849$ openssl ecparam -in ec_in.pem -out ec_out.pem \e
2850 -conv_form compressed
2851.Ed
2852.Pp
2853To print out the EC parameters to standard output:
2854.Bd -literal -offset indent
2855$ openssl ecparam -in ec_param.pem -noout -text
2856.Ed
2857.Sh ECPARAM HISTORY
2858The
2859.Nm ecparam
2860command was first introduced in
2861.Nm OpenSSL
28620.9.8.
2863.Sh ECPARAM AUTHORS
2864.An Nils Larsch .
2865.\"
2866.\" ENC
2867.\"
2868.Sh ENC
2869.nr nS 1
2870.Nm "openssl enc"
2871.Bk -words
2872.Fl ciphername
2873.Op Fl AadePp
2874.Op Fl base64
2875.Op Fl bufsize Ar number
2876.Op Fl debug
2877.Op Fl engine Ar id
2878.Op Fl in Ar file
2879.Op Fl iv Ar IV
2880.Op Fl K Ar key
2881.Op Fl k Ar password
2882.Op Fl kfile Ar file
2883.Op Fl md Ar digest
2884.Op Fl none
2885.Op Fl nopad
2886.Op Fl nosalt
2887.Op Fl out Ar file
2888.Op Fl pass Ar arg
2889.Op Fl S Ar salt
2890.Op Fl salt
2891.Ek
2892.nr nS 0
2893.Pp
2894The symmetric cipher commands allow data to be encrypted or decrypted
2895using various block and stream ciphers using keys based on passwords
2896or explicitly provided.
2897Base64 encoding or decoding can also be performed either by itself
2898or in addition to the encryption or decryption.
2899.Pp
2900The options are as follows:
2901.Bl -tag -width Ds
2902.It Fl A
2903If the
2904.Fl a
2905option is set, then base64 process the data on one line.
2906.It Fl a , base64
2907Base64 process the data.
2908This means that if encryption is taking place, the data is base64-encoded
2909after encryption.
2910If decryption is set, the input data is base64 decoded before
2911being decrypted.
2912.It Fl bufsize Ar number
2913Set the buffer size for I/O.
2914.It Fl d
2915Decrypt the input data.
2916.It Fl debug
2917Debug the BIOs used for I/O.
2918.It Fl e
2919Encrypt the input data: this is the default.
2920.It Fl engine Ar id
2921Specifying an engine (by its unique
2922.Ar id
2923string) will cause
2924.Nm enc
2925to attempt to obtain a functional reference to the specified engine,
2926thus initialising it if needed.
2927The engine will then be set as the default for all available algorithms.
2928.It Fl in Ar file
2929The input
2930.Ar file ;
2931standard input by default.
2932.It Fl iv Ar IV
2933The actual
2934.Ar IV
2935.Pq initialisation vector
2936to use:
2937this must be represented as a string comprised only of hex digits.
2938When only the
2939.Ar key
2940is specified using the
2941.Fl K
2942option, the
2943.Ar IV
2944must explicitly be defined.
2945When a password is being specified using one of the other options,
2946the
2947.Ar IV
2948is generated from this password.
2949.It Fl K Ar key
2950The actual
2951.Ar key
2952to use:
2953this must be represented as a string comprised only of hex digits.
2954If only the key is specified, the
2955.Ar IV
2956must be additionally specified using the
2957.Fl iv
2958option.
2959When both a
2960.Ar key
2961and a
2962.Ar password
2963are specified, the
2964.Ar key
2965given with the
2966.Fl K
2967option will be used and the
2968.Ar IV
2969generated from the password will be taken.
2970It probably does not make much sense to specify both
2971.Ar key
2972and
2973.Ar password .
2974.It Fl k Ar password
2975The
2976.Ar password
2977to derive the key from.
2978This is for compatibility with previous versions of
2979.Nm OpenSSL .
2980Superseded by the
2981.Fl pass
2982option.
2983.It Fl kfile Ar file
2984Read the password to derive the key from the first line of
2985.Ar file .
2986This is for compatibility with previous versions of
2987.Nm OpenSSL .
2988Superseded by the
2989.Fl pass
2990option.
2991.It Fl md Ar digest
2992Use
2993.Ar digest
2994to create a key from a pass phrase.
2995.Ar digest
2996may be one of
2997.Dq md2 ,
2998.Dq md5 ,
2999.Dq sha ,
3000or
3001.Dq sha1 .
3002.It Fl none
3003Use NULL cipher (no encryption or decryption of input).
3004.It Fl nopad
3005Disable standard block padding.
3006.It Fl nosalt
3007Don't use a
3008.Ar salt
3009in the key derivation routines.
3010This option should
3011.Em NEVER
3012be used unless compatibility with previous versions of
3013.Nm OpenSSL
3014or
3015.Nm SSLeay
3016is required.
3017.It Fl out Ar file
3018The output
3019.Ar file ,
3020standard output by default.
3021.It Fl P
3022Print out the
3023.Ar salt ,
3024.Ar key ,
3025and
3026.Ar IV
3027used, then immediately exit;
3028don't do any encryption or decryption.
3029.It Fl p
3030Print out the
3031.Ar salt ,
3032.Ar key ,
3033and
3034.Ar IV
3035used.
3036.It Fl pass Ar arg
3037The password source.
3038For more information about the format of
3039.Ar arg ,
3040see the
3041.Sx PASS PHRASE ARGUMENTS
3042section above.
3043.It Fl S Ar salt
3044The actual
3045.Ar salt
3046to use:
3047this must be represented as a string comprised only of hex digits.
3048.It Fl salt
3049Use a
3050.Ar salt
3051in the key derivation routines.
3052This is the default.
3053.El
3054.Sh ENC NOTES
3055The program can be called either as
3056.Nm openssl ciphername
3057or
3058.Nm openssl enc -ciphername .
3059But the first form doesn't work with engine-provided ciphers,
3060because this form is processed before the
3061configuration file is read and any engines loaded.
3062.Pp
3063Engines which provide entirely new encryption algorithms
3064should be configured in the configuration file.
3065Engines, specified on the command line using the
3066.Fl engine
3067option,
3068can only be used for hardware-assisted implementations of ciphers,
3069supported by
3070.Nm OpenSSL
3071core, or by other engines specified in the configuration file.
3072.Pp
3073When
3074.Nm enc
3075lists supported ciphers,
3076ciphers provided by engines specified in the configuration files
3077are listed too.
3078.Pp
3079A password will be prompted for to derive the
3080.Ar key
3081and
3082.Ar IV
3083if necessary.
3084.Pp
3085The
3086.Fl nosalt
3087option should
3088.Em NEVER
3089be used unless compatibility with previous versions of
3090.Nm OpenSSL
3091or
3092.Nm SSLeay
3093is required.
3094.Pp
3095With the
3096.Fl nosalt
3097option it is possible to perform efficient dictionary
3098attacks on the password and to attack stream cipher encrypted data.
3099The reason for this is that without the salt
3100the same password always generates the same encryption key.
3101When the salt
3102is being used the first eight bytes of the encrypted data are reserved
3103for the salt:
3104it is generated at random when encrypting a file and read from the
3105encrypted file when it is decrypted.
3106.Pp
3107Some of the ciphers do not have large keys and others have security
3108implications if not used correctly.
3109A beginner is advised to just use a strong block cipher in CBC mode
3110such as bf or des3.
3111.Pp
3112All the block ciphers normally use PKCS#5 padding also known as standard block
3113padding:
3114this allows a rudimentary integrity or password check to be performed.
3115However, since the chance of random data passing the test is
3116better than 1 in 256, it isn't a very good test.
3117.Pp
3118If padding is disabled, the input data must be a multiple of the cipher
3119block length.
3120.Pp
3121All RC2 ciphers have the same key and effective key length.
3122.Pp
3123Blowfish and RC5 algorithms use a 128-bit key.
3124.Sh ENC SUPPORTED CIPHERS
3125.Bd -unfilled -offset indent
3126aes-[128|192|256]-cbc 128/192/256 bit AES in CBC mode
3127aes-[128|192|256] Alias for aes-[128|192|256]-cbc
3128aes-[128|192|256]-cfb 128/192/256 bit AES in 128 bit CFB mode
3129aes-[128|192|256]-cfb1 128/192/256 bit AES in 1 bit CFB mode
3130aes-[128|192|256]-cfb8 128/192/256 bit AES in 8 bit CFB mode
3131aes-[128|192|256]-ecb 128/192/256 bit AES in ECB mode
3132aes-[128|192|256]-ofb 128/192/256 bit AES in OFB mode
3133
3134base64 Base 64
3135
3136bf Alias for bf-cbc
3137bf-cbc Blowfish in CBC mode
3138bf-cfb Blowfish in CFB mode
3139bf-ecb Blowfish in ECB mode
3140bf-ofb Blowfish in OFB mode
3141
3142cast Alias for cast-cbc
3143cast-cbc CAST in CBC mode
3144cast5-cbc CAST5 in CBC mode
3145cast5-cfb CAST5 in CFB mode
3146cast5-ecb CAST5 in ECB mode
3147cast5-ofb CAST5 in OFB mode
3148
3149des Alias for des-cbc
3150des-cbc DES in CBC mode
3151des-cfb DES in CBC mode
3152des-ecb DES in ECB mode
3153des-ofb DES in OFB mode
3154
3155des-ede Two key triple DES EDE in ECB mode
3156des-ede-cbc Two key triple DES EDE in CBC mode
3157des-ede-cfb Two key triple DES EDE in CFB mode
3158des-ede-ofb Two key triple DES EDE in OFB mode
3159
3160des3 Alias for des-ede3-cbc
3161des-ede3 Three key triple DES EDE in ECB mode
3162des-ede3-cbc Three key triple DES EDE in CBC mode
3163des-ede3-cfb Three key triple DES EDE CFB mode
3164des-ede3-ofb Three key triple DES EDE in OFB mode
3165
3166desx DESX algorithm
3167
3168rc2 Alias for rc2-cbc
3169rc2-cbc 128-bit RC2 in CBC mode
3170rc2-cfb 128-bit RC2 in CFB mode
3171rc2-ecb 128-bit RC2 in ECB mode
3172rc2-ofb 128-bit RC2 in OFB mode
3173rc2-64-cbc 64-bit RC2 in CBC mode
3174rc2-40-cbc 40-bit RC2 in CBC mode
3175
3176rc4 128-bit RC4
3177rc4-40 40-bit RC4
3178.Ed
3179.Sh ENC EXAMPLES
3180Just base64 encode a binary file:
3181.Pp
3182.Dl $ openssl base64 -in file.bin -out file.b64
3183.Pp
3184Decode the same file:
3185.Pp
3186.Dl $ openssl base64 -d -in file.b64 -out file.bin
3187.Pp
3188Encrypt a file using triple DES in CBC mode using a prompted password:
3189.Pp
3190.Dl $ openssl des3 -salt -in file.txt -out file.des3
3191.Pp
3192Decrypt a file using a supplied password:
3193.Pp
3194.Dl "$ openssl des3 -d -in file.des3 -out file.txt -k mypassword"
3195.Pp
3196Encrypt a file then base64 encode it
3197(so it can be sent via mail for example)
3198using Blowfish in CBC mode:
3199.Pp
3200.Dl $ openssl bf -a -salt -in file.txt -out file.bf
3201.Pp
3202Base64 decode a file then decrypt it:
3203.Pp
3204.Dl "$ openssl bf -d -a -in file.bf -out file.txt"
3205.Sh ENC BUGS
3206The
3207.Fl A
3208option when used with large files doesn't work properly.
3209.Pp
3210There should be an option to allow an iteration count to be included.
3211.Pp
3212The
3213.Nm enc
3214program only supports a fixed number of algorithms with certain parameters.
3215Therefore it is not possible to use RC2 with a 76-bit key
3216or RC4 with an 84-bit key with this program.
3217.\"
3218.\" ENGINE
3219.\"
3220.Sh ENGINE
3221.Nm openssl engine
3222.Op Fl ctv
3223.Op Fl post Ar cmd
3224.Op Fl pre Ar cmd
3225.Op Ar engine ...
3226.Pp
3227The
3228.Nm engine
3229command provides loadable module information and manipulation
3230of various engines.
3231Any options are applied to all engines supplied on the command line,
3232or all supported engines if none are specified.
3233.Pp
3234The options are as follows:
3235.Bl -tag -width Ds
3236.It Fl c
3237For each engine, also list the capabilities.
3238.It Fl post Ar cmd
3239Run command
3240.Ar cmd
3241against the engine after loading it
3242(only used if
3243.Fl t
3244is also provided).
3245.It Fl pre Ar cmd
3246Run command
3247.Ar cmd
3248against the engine before any attempts
3249to load it
3250(only used if
3251.Fl t
3252is also provided).
3253.It Fl t
3254For each engine, check that they are really available.
3255.Fl tt
3256will display an error trace for unavailable engines.
3257.It Fl v
3258Verbose mode.
3259For each engine, list its 'control commands'.
3260.Fl vv
3261will additionally display each command's description.
3262.Fl vvv
3263will also add the input flags for each command.
3264.Fl vvvv
3265will also show internal input flags.
3266.El
3267.\"
3268.\" ERRSTR
3269.\"
3270.Sh ERRSTR
3271.Nm openssl errstr
3272.Op Fl stats
3273.Ar errno ...
3274.Pp
3275The
3276.Nm errstr
3277command performs error number to error string conversion,
3278generating a human-readable string representing the error code
3279.Ar errno .
3280The string is obtained through the
3281.Xr ERR_error_string_n 3
3282function and has the following format:
3283.Pp
3284.Dl error:[error code]:[library name]:[function name]:[reason string]
3285.Pp
3286.Bq error code
3287is an 8-digit hexadecimal number.
3288The remaining fields
3289.Bq library name ,
3290.Bq function name ,
3291and
3292.Bq reason string
3293are all ASCII text.
3294.Pp
3295The options are as follows:
3296.Bl -tag -width Ds
3297.It Fl stats
3298Print debugging statistics about various aspects of the hash table.
3299.El
3300.Sh ERRSTR EXAMPLES
3301The following error code:
3302.Pp
3303.Dl 27594:error:2006D080:lib(32):func(109):reason(128):bss_file.c:107:
3304.Pp
3305\&...can be displayed with:
3306.Pp
3307.Dl $ openssl errstr 2006D080
3308.Pp
3309\&...to produce the error message:
3310.Pp
3311.Dl error:2006D080:BIO routines:BIO_new_file:no such file
3312.\"
3313.\" GENDH
3314.\"
3315.Sh GENDH
3316Generation of Diffie-Hellman Parameters.
3317Replaced by
3318.Nm dhparam .
3319See
3320.Sx DHPARAM
3321above.
3322.\"
3323.\" GENDSA
3324.\"
3325.Sh GENDSA
3326.nr nS 1
3327.Nm "openssl gendsa"
3328.Bk -words
3329.Oo
3330.Fl aes128 | aes192 | aes256 |
3331.Fl des | des3
3332.Oc
3333.Op Fl engine Ar id
3334.Op Fl out Ar file
3335.Op Ar paramfile
3336.Ek
3337.nr nS 0
3338.Pp
3339The
3340.Nm gendsa
3341command generates a DSA private key from a DSA parameter file
3342(which will typically be generated by the
3343.Nm openssl dsaparam
3344command).
3345.Pp
3346The options are as follows:
3347.Bl -tag -width Ds
3348.It Xo
3349.Fl aes128 | aes192 | aes256 |
3350.Fl des | des3
3351.Xc
3352These options encrypt the private key with the AES, DES,
3353or the triple DES ciphers, respectively, before outputting it.
3354A pass phrase is prompted for.
3355If none of these options are specified, no encryption is used.
3356.It Fl engine Ar id
3357Specifying an engine (by its unique
3358.Ar id
3359string) will cause
3360.Nm gendsa
3361to attempt to obtain a functional reference to the specified engine,
3362thus initialising it if needed.
3363The engine will then be set as the default for all available algorithms.
3364.It Fl out Ar file
3365The output
3366.Ar file .
3367If this argument is not specified, standard output is used.
3368.It Ar paramfile
3369This option specifies the DSA parameter file to use.
3370The parameters in this file determine the size of the private key.
3371DSA parameters can be generated and examined using the
3372.Nm openssl dsaparam
3373command.
3374.El
3375.Sh GENDSA NOTES
3376DSA key generation is little more than random number generation so it is
3377much quicker than RSA key generation, for example.
3378.\"
3379.\" GENPKEY
3380.\"
3381.Sh GENPKEY
3382.nr nS 1
3383.Nm "openssl genpkey"
3384.Bk -words
3385.Op Fl algorithm Ar alg
3386.Op Ar cipher
3387.Op Fl engine Ar id
3388.Op Fl genparam
3389.Op Fl out Ar file
3390.Op Fl outform Ar DER | PEM
3391.Op Fl paramfile Ar file
3392.Op Fl pass Ar arg
3393.Op Fl pkeyopt Ar opt : Ns Ar value
3394.Op Fl text
3395.Ek
3396.nr nS 0
3397.Pp
3398The
3399.Nm genpkey
3400command generates private keys.
3401The use of this
3402program is encouraged over the algorithm specific utilities
3403because additional algorithm options
3404and engine-provided algorithms can be used.
3405.Pp
3406The options are as follows:
3407.Bl -tag -width Ds
3408.It Fl algorithm Ar alg
3409The public key algorithm to use,
3410such as RSA, DSA, or DH.
3411If used this option must precede any
3412.Fl pkeyopt
3413options.
3414The options
3415.Fl paramfile
3416and
3417.Fl algorithm
3418are mutually exclusive.
3419.It Ar cipher
3420Encrypt the private key with the supplied cipher.
3421Any algorithm name accepted by
3422.Fn EVP_get_cipherbyname
3423is acceptable, such as
3424.Cm des3 .
3425.It Fl engine Ar id
3426Specifying an engine (by its unique
3427.Ar id
3428string) will cause
3429.Nm genpkey
3430to attempt to obtain a functional reference to the specified engine,
3431thus initialising it if needed.
3432The engine will then be set as the default for all available algorithms.
3433.It Fl genparam
3434Generate a set of parameters instead of a private key.
3435If used this option must precede any
3436.Fl algorithm ,
3437.Fl paramfile ,
3438or
3439.Fl pkeyopt
3440options.
3441.It Fl out Ar file
3442The output filename.
3443If this argument is not specified then standard output is used.
3444.It Fl outform Ar DER | PEM
3445This specifies the output format, DER or PEM.
3446.It Fl paramfile Ar file
3447Some public key algorithms generate a private key based on a set of parameters.
3448They can be supplied using this option.
3449If this option is used the public key
3450algorithm used is determined by the parameters.
3451If used this option must precede any
3452.Fl pkeyopt
3453options.
3454The options
3455.Fl paramfile
3456and
3457.Fl algorithm
3458are mutually exclusive.
3459.It Fl pass Ar arg
3460The output file password source.
3461For more information about the format of
3462.Ar arg ,
3463see the
3464.Sx PASS PHRASE ARGUMENTS
3465section above.
3466.It Fl pkeyopt Ar opt : Ns Ar value
3467Set the public key algorithm option
3468.Ar opt
3469to
3470.Ar value .
3471The precise set of options supported
3472depends on the public key algorithm used and its implementation.
3473See
3474.Sx GENPKEY KEY GENERATION OPTIONS
3475below for more details.
3476.It Fl text
3477Print an (unencrypted) text representation of private and public keys and
3478parameters along with the DER or PEM structure.
3479.El
3480.Sh GENPKEY KEY GENERATION OPTIONS
3481The options supported by each algorithm
3482and indeed each implementation of an algorithm can vary.
3483The options for the
3484.Nm OpenSSL
3485implementations are detailed below.
3486.Bl -tag -width Ds -offset indent
3487.It rsa_keygen_bits : Ns Ar numbits
3488(RSA)
3489The number of bits in the generated key.
3490If not specified 2048 is used.
3491.It rsa_keygen_pubexp : Ns Ar value
3492(RSA)
3493The RSA public exponent value.
3494This can be a large decimal or hexadecimal value if preceded by 0x.
3495The default value is 65537.
3496.It dsa_paramgen_bits : Ns Ar numbits
3497(DSA)
3498The number of bits in the generated parameters.
3499If not specified 1024 is used.
3500.It dh_paramgen_prime_len : Ns Ar numbits
3501(DH)
3502The number of bits in the prime parameter
3503.Ar p .
3504.It dh_paramgen_generator : Ns Ar value
3505(DH)
3506The value to use for the generator
3507.Ar g .
3508.It ec_paramgen_curve : Ns Ar curve
3509(EC)
3510The EC curve to use.
3511.El
3512.Sh GENPKEY EXAMPLES
3513Generate an RSA private key using default parameters:
3514.Bd -literal -offset indent
3515$ openssl genpkey -algorithm RSA -out key.pem
3516.Ed
3517.Pp
3518Encrypt and output a private key using 128-bit AES and the passphrase "hello":
3519.Bd -literal -offset indent
3520$ openssl genpkey -algorithm RSA -out key.pem \e
3521 -aes-128-cbc -pass pass:hello
3522.Ed
3523.Pp
3524Generate a 2048-bit RSA key using 3 as the public exponent:
3525.Bd -literal -offset indent
3526$ openssl genpkey -algorithm RSA -out key.pem \e
3527 -pkeyopt rsa_keygen_bits:2048 -pkeyopt rsa_keygen_pubexp:3
3528.Ed
3529.Pp
3530Generate 1024-bit DSA parameters:
3531.Bd -literal -offset indent
3532$ openssl genpkey -genparam -algorithm DSA \e
3533 -out dsap.pem -pkeyopt dsa_paramgen_bits:1024
3534.Ed
3535.Pp
3536Generate a DSA key from parameters:
3537.Bd -literal -offset indent
3538$ openssl genpkey -paramfile dsap.pem -out dsakey.pem
3539.Ed
3540.Pp
3541Generate 1024-bit DH parameters:
3542.Bd -literal -offset indent
3543$ openssl genpkey -genparam -algorithm DH \e
3544 -out dhp.pem -pkeyopt dh_paramgen_prime_len:1024
3545.Ed
3546.Pp
3547Generate a DH key from parameters:
3548.Bd -literal -offset indent
3549$ openssl genpkey -paramfile dhp.pem -out dhkey.pem
3550.Ed
3551.\"
3552.\" GENRSA
3553.\"
3554.Sh GENRSA
3555.nr nS 1
3556.Nm "openssl genrsa"
3557.Bk -words
3558.Op Fl 3 | f4
3559.Oo
3560.Fl aes128 | aes192 | aes256 |
3561.Fl des | des3
3562.Oc
3563.Op Fl engine Ar id
3564.Op Fl out Ar file
3565.Op Fl passout Ar arg
3566.Op Ar numbits
3567.Ek
3568.nr nS 0
3569.Pp
3570The
3571.Nm genrsa
3572command generates an RSA private key.
3573.Pp
3574The options are as follows:
3575.Bl -tag -width Ds
3576.It Fl 3 | f4
3577The public exponent to use, either 3 or 65537.
3578The default is 65537.
3579.It Xo
3580.Fl aes128 | aes192 | aes256 |
3581.Fl des | des3
3582.Xc
3583These options encrypt the private key with the AES, DES,
3584or the triple DES ciphers, respectively, before outputting it.
3585If none of these options are specified, no encryption is used.
3586If encryption is used, a pass phrase is prompted for,
3587if it is not supplied via the
3588.Fl passout
3589option.
3590.It Fl engine Ar id
3591Specifying an engine (by its unique
3592.Ar id
3593string) will cause
3594.Nm genrsa
3595to attempt to obtain a functional reference to the specified engine,
3596thus initialising it if needed.
3597The engine will then be set as the default for all available algorithms.
3598.It Fl out Ar file
3599The output
3600.Ar file .
3601If this argument is not specified, standard output is used.
3602.It Fl passout Ar arg
3603The output file password source.
3604For more information about the format of
3605.Ar arg ,
3606see the
3607.Sx PASS PHRASE ARGUMENTS
3608section above.
3609.It Ar numbits
3610The size of the private key to generate in bits.
3611This must be the last option specified.
3612The default is 2048.
3613.El
3614.Sh GENRSA NOTES
3615RSA private key generation essentially involves the generation of two prime
3616numbers.
3617When generating a private key, various symbols will be output to
3618indicate the progress of the generation.
3619A
3620.Sq \&.
3621represents each number which has passed an initial sieve test;
3622.Sq +
3623means a number has passed a single round of the Miller-Rabin primality test.
3624A newline means that the number has passed all the prime tests
3625.Pq the actual number depends on the key size .
3626.Pp
3627Because key generation is a random process,
3628the time taken to generate a key may vary somewhat.
3629.Sh GENRSA BUGS
3630A quirk of the prime generation algorithm is that it cannot generate small
3631primes.
3632Therefore the number of bits should not be less that 64.
3633For typical private keys this will not matter because for security reasons
3634they will be much larger
3635.Pq typically 2048 bits .
3636.\"
3637.\" NSEQ
3638.\"
3639.Sh NSEQ
3640.Nm openssl nseq
3641.Op Fl in Ar file
3642.Op Fl out Ar file
3643.Op Fl toseq
3644.Pp
3645The
3646.Nm nseq
3647command takes a file containing a Netscape certificate
3648sequence and prints out the certificates contained in it or takes a
3649file of certificates and converts it into a Netscape certificate
3650sequence.
3651.Pp
3652The options are as follows:
3653.Bl -tag -width Ds
3654.It Fl in Ar file
3655This specifies the input
3656.Ar file
3657to read, or standard input if this option is not specified.
3658.It Fl out Ar file
3659Specifies the output
3660.Ar file ,
3661or standard output by default.
3662.It Fl toseq
3663Normally, a Netscape certificate sequence will be input and the output
3664is the certificates contained in it.
3665With the
3666.Fl toseq
3667option the situation is reversed:
3668a Netscape certificate sequence is created from a file of certificates.
3669.El
3670.Sh NSEQ EXAMPLES
3671Output the certificates in a Netscape certificate sequence:
3672.Bd -literal -offset indent
3673$ openssl nseq -in nseq.pem -out certs.pem
3674.Ed
3675.Pp
3676Create a Netscape certificate sequence:
3677.Bd -literal -offset indent
3678$ openssl nseq -in certs.pem -toseq -out nseq.pem
3679.Ed
3680.Sh NSEQ NOTES
3681The PEM-encoded form uses the same headers and footers as a certificate:
3682.Bd -unfilled -offset indent
3683-----BEGIN CERTIFICATE-----
3684-----END CERTIFICATE-----
3685.Ed
3686.Pp
3687A Netscape certificate sequence is a Netscape specific form that can be sent
3688to browsers as an alternative to the standard PKCS#7 format when several
3689certificates are sent to the browser:
3690for example during certificate enrollment.
3691It is used by the Netscape certificate server, for example.
3692.Sh NSEQ BUGS
3693This program needs a few more options,
3694like allowing DER or PEM input and output files
3695and allowing multiple certificate files to be used.
3696.\"
3697.\" OCSP
3698.\"
3699.Sh OCSP
3700.nr nS 1
3701.Nm "openssl ocsp"
3702.Bk -words
3703.Op Fl CA Ar file
3704.Op Fl CAfile Ar file
3705.Op Fl CApath Ar directory
3706.Op Fl cert Ar file
3707.Op Fl dgst Ar alg
3708.Oo
3709.Fl host
3710.Ar hostname : Ns Ar port
3711.Oc
3712.Op Fl index Ar indexfile
3713.Op Fl issuer Ar file
3714.Op Fl ndays Ar days
3715.Op Fl nmin Ar minutes
3716.Op Fl no_cert_checks
3717.Op Fl no_cert_verify
3718.Op Fl no_certs
3719.Op Fl no_chain
3720.Op Fl no_intern
3721.Op Fl no_nonce
3722.Op Fl no_signature_verify
3723.Op Fl nonce
3724.Op Fl noverify
3725.Op Fl nrequest Ar number
3726.Op Fl out Ar file
3727.Op Fl path Ar path
3728.Op Fl port Ar portnum
3729.Op Fl req_text
3730.Op Fl reqin Ar file
3731.Op Fl reqout Ar file
3732.Op Fl resp_key_id
3733.Op Fl resp_no_certs
3734.Op Fl resp_text
3735.Op Fl respin Ar file
3736.Op Fl respout Ar file
3737.Op Fl rkey Ar file
3738.Op Fl rother Ar file
3739.Op Fl rsigner Ar file
3740.Op Fl serial Ar number
3741.Op Fl sign_other Ar file
3742.Op Fl signer Ar file
3743.Op Fl signkey Ar file
3744.Op Fl status_age Ar age
3745.Op Fl text
3746.Op Fl trust_other
3747.Op Fl url Ar responder_url
3748.Op Fl VAfile Ar file
3749.Op Fl validity_period Ar nsec
3750.Op Fl verify_other Ar file
3751.Ek
3752.nr nS 0
3753.Pp
3754The Online Certificate Status Protocol
3755.Pq OCSP
3756enables applications to determine the
3757.Pq revocation
3758state of an identified certificate
3759.Pq RFC 2560 .
3760.Pp
3761The
3762.Nm ocsp
3763command performs many common OCSP tasks.
3764It can be used to print out requests and responses,
3765create requests and send queries to an OCSP responder,
3766and behave like a mini OCSP server itself.
3767.Pp
3768The options are as follows:
3769.Bl -tag -width Ds
3770.It Fl CAfile Ar file , Fl CApath Ar directory
3771.Ar file
3772or
3773.Ar path
3774containing trusted CA certificates.
3775These are used to verify the signature on the OCSP response.
3776.It Fl cert Ar file
3777Add the certificate
3778.Ar file
3779to the request.
3780The issuer certificate is taken from the previous
3781.Fl issuer
3782option, or an error occurs if no issuer certificate is specified.
3783.It Fl dgst Ar alg
3784Sets the digest algorithm to use for certificate identification
3785in the OCSP request.
3786By default SHA-1 is used.
3787.It Xo
3788.Fl host Ar hostname : Ns Ar port ,
3789.Fl path Ar path
3790.Xc
3791If the
3792.Fl host
3793option is present, then the OCSP request is sent to the host
3794.Ar hostname
3795on port
3796.Ar port .
3797.Fl path
3798specifies the HTTP path name to use, or
3799.Sq /
3800by default.
3801.It Fl issuer Ar file
3802This specifies the current issuer certificate.
3803This option can be used multiple times.
3804The certificate specified in
3805.Ar file
3806must be in PEM format.
3807This option
3808.Em must
3809come before any
3810.Fl cert
3811options.
3812.It Fl no_cert_checks
3813Don't perform any additional checks on the OCSP response signer's certificate.
3814That is, do not make any checks to see if the signer's certificate is
3815authorised to provide the necessary status information:
3816as a result this option should only be used for testing purposes.
3817.It Fl no_cert_verify
3818Don't verify the OCSP response signer's certificate at all.
3819Since this option allows the OCSP response to be signed by any certificate,
3820it should only be used for testing purposes.
3821.It Fl no_certs
3822Don't include any certificates in signed request.
3823.It Fl no_chain
3824Do not use certificates in the response as additional untrusted CA
3825certificates.
3826.It Fl no_intern
3827Ignore certificates contained in the OCSP response
3828when searching for the signer's certificate.
3829With this option, the signer's certificate must be specified with either the
3830.Fl verify_other
3831or
3832.Fl VAfile
3833options.
3834.It Fl no_signature_verify
3835Don't check the signature on the OCSP response.
3836Since this option tolerates invalid signatures on OCSP responses,
3837it will normally only be used for testing purposes.
3838.It Fl nonce , no_nonce
3839Add an OCSP
3840.Em nonce
3841extension to a request or disable an OCSP
3842.Em nonce
3843addition.
3844Normally, if an OCSP request is input using the
3845.Fl respin
3846option no
3847.Em nonce
3848is added:
3849using the
3850.Fl nonce
3851option will force addition of a
3852.Em nonce .
3853If an OCSP request is being created (using the
3854.Fl cert
3855and
3856.Fl serial
3857options)
3858a
3859.Em nonce
3860is automatically added; specifying
3861.Fl no_nonce
3862overrides this.
3863.It Fl noverify
3864Don't attempt to verify the OCSP response signature or the
3865.Em nonce
3866values.
3867This option will normally only be used for debugging
3868since it disables all verification of the responder's certificate.
3869.It Fl out Ar file
3870Specify output
3871.Ar file ;
3872default is standard output.
3873.It Fl req_text , resp_text , text
3874Print out the text form of the OCSP request, response, or both, respectively.
3875.It Fl reqin Ar file , Fl respin Ar file
3876Read an OCSP request or response file from
3877.Ar file .
3878These options are ignored
3879if an OCSP request or response creation is implied by other options
3880(for example with the
3881.Fl serial , cert ,
3882and
3883.Fl host
3884options).
3885.It Fl reqout Ar file , Fl respout Ar file
3886Write out the DER-encoded certificate request or response to
3887.Ar file .
3888.It Fl serial Ar num
3889Same as the
3890.Fl cert
3891option except the certificate with serial number
3892.Ar num
3893is added to the request.
3894The serial number is interpreted as a decimal integer unless preceded by
3895.Sq 0x .
3896Negative integers can also be specified by preceding the value with a
3897.Sq -
3898sign.
3899.It Fl sign_other Ar file
3900Additional certificates to include in the signed request.
3901.It Fl signer Ar file , Fl signkey Ar file
3902Sign the OCSP request using the certificate specified in the
3903.Fl signer
3904option and the private key specified by the
3905.Fl signkey
3906option.
3907If the
3908.Fl signkey
3909option is not present, then the private key is read from the same file
3910as the certificate.
3911If neither option is specified, the OCSP request is not signed.
3912.It Fl trust_other
3913The certificates specified by the
3914.Fl verify_other
3915option should be explicitly trusted and no additional checks will be
3916performed on them.
3917This is useful when the complete responder certificate chain is not available
3918or trusting a root CA is not appropriate.
3919.It Fl url Ar responder_url
3920Specify the responder URL.
3921Both HTTP and HTTPS
3922.Pq SSL/TLS
3923URLs can be specified.
3924.It Fl VAfile Ar file
3925.Ar file
3926containing explicitly trusted responder certificates.
3927Equivalent to the
3928.Fl verify_other
3929and
3930.Fl trust_other
3931options.
3932.It Fl validity_period Ar nsec , Fl status_age Ar age
3933These options specify the range of times, in seconds, which will be tolerated
3934in an OCSP response.
3935Each certificate status response includes a
3936.Em notBefore
3937time and an optional
3938.Em notAfter
3939time.
3940The current time should fall between these two values,
3941but the interval between the two times may be only a few seconds.
3942In practice the OCSP responder and clients' clocks may not be precisely
3943synchronised and so such a check may fail.
3944To avoid this the
3945.Fl validity_period
3946option can be used to specify an acceptable error range in seconds,
3947the default value is 5 minutes.
3948.Pp
3949If the
3950.Em notAfter
3951time is omitted from a response, then this means that new status
3952information is immediately available.
3953In this case the age of the
3954.Em notBefore
3955field is checked to see it is not older than
3956.Ar age
3957seconds old.
3958By default, this additional check is not performed.
3959.It Fl verify_other Ar file
3960.Ar file
3961containing additional certificates to search when attempting to locate
3962the OCSP response signing certificate.
3963Some responders omit the actual signer's certificate from the response;
3964this option can be used to supply the necessary certificate in such cases.
3965.El
3966.Sh OCSP SERVER OPTIONS
3967.Bl -tag -width "XXXX"
3968.It Fl CA Ar file
3969CA certificate corresponding to the revocation information in
3970.Ar indexfile .
3971.It Fl index Ar indexfile
3972.Ar indexfile
3973is a text index file in
3974.Nm ca
3975format containing certificate revocation information.
3976.Pp
3977If the
3978.Fl index
3979option is specified, the
3980.Nm ocsp
3981utility is in
3982.Em responder
3983mode, otherwise it is in
3984.Em client
3985mode.
3986The request(s) the responder processes can be either specified on
3987the command line (using the
3988.Fl issuer
3989and
3990.Fl serial
3991options), supplied in a file (using the
3992.Fl respin
3993option) or via external OCSP clients (if
3994.Ar port
3995or
3996.Ar url
3997is specified).
3998.Pp
3999If the
4000.Fl index
4001option is present, then the
4002.Fl CA
4003and
4004.Fl rsigner
4005options must also be present.
4006.It Fl nmin Ar minutes , Fl ndays Ar days
4007Number of
4008.Ar minutes
4009or
4010.Ar days
4011when fresh revocation information is available: used in the
4012.Ar nextUpdate
4013field.
4014If neither option is present, the
4015.Em nextUpdate
4016field is omitted, meaning fresh revocation information is immediately available.
4017.It Fl nrequest Ar number
4018The OCSP server will exit after receiving
4019.Ar number
4020requests, default unlimited.
4021.It Fl port Ar portnum
4022Port to listen for OCSP requests on.
4023The port may also be specified using the
4024.Fl url
4025option.
4026.It Fl resp_key_id
4027Identify the signer certificate using the key ID;
4028default is to use the subject name.
4029.It Fl resp_no_certs
4030Don't include any certificates in the OCSP response.
4031.It Fl rkey Ar file
4032The private key to sign OCSP responses with;
4033if not present, the file specified in the
4034.Fl rsigner
4035option is used.
4036.It Fl rother Ar file
4037Additional certificates to include in the OCSP response.
4038.It Fl rsigner Ar file
4039The certificate to sign OCSP responses with.
4040.El
4041.Sh OCSP RESPONSE VERIFICATION
4042OCSP Response follows the rules specified in RFC 2560.
4043.Pp
4044Initially the OCSP responder certificate is located and the signature on
4045the OCSP request checked using the responder certificate's public key.
4046.Pp
4047Then a normal certificate verify is performed on the OCSP responder certificate
4048building up a certificate chain in the process.
4049The locations of the trusted certificates used to build the chain can be
4050specified by the
4051.Fl CAfile
4052and
4053.Fl CApath
4054options or they will be looked for in the standard
4055.Nm OpenSSL
4056certificates
4057directory.
4058.Pp
4059If the initial verify fails, the OCSP verify process halts with an
4060error.
4061.Pp
4062Otherwise the issuing CA certificate in the request is compared to the OCSP
4063responder certificate: if there is a match then the OCSP verify succeeds.
4064.Pp
4065Otherwise the OCSP responder certificate's CA is checked against the issuing
4066CA certificate in the request.
4067If there is a match and the OCSPSigning extended key usage is present
4068in the OCSP responder certificate, then the OCSP verify succeeds.
4069.Pp
4070Otherwise the root CA of the OCSP responder's CA is checked to see if it
4071is trusted for OCSP signing.
4072If it is, the OCSP verify succeeds.
4073.Pp
4074If none of these checks is successful, the OCSP verify fails.
4075.Pp
4076What this effectively means is that if the OCSP responder certificate is
4077authorised directly by the CA it is issuing revocation information about
4078.Pq and it is correctly configured ,
4079then verification will succeed.
4080.Pp
4081If the OCSP responder is a
4082.Em global responder
4083which can give details about multiple CAs and has its own separate
4084certificate chain, then its root CA can be trusted for OCSP signing.
4085For example:
4086.Bd -literal -offset indent
4087$ openssl x509 -in ocspCA.pem -addtrust OCSPSigning \e
4088 -out trustedCA.pem
4089.Ed
4090.Pp
4091Alternatively, the responder certificate itself can be explicitly trusted
4092with the
4093.Fl VAfile
4094option.
4095.Sh OCSP NOTES
4096As noted, most of the verify options are for testing or debugging purposes.
4097Normally, only the
4098.Fl CApath , CAfile
4099and
4100.Pq if the responder is a `global VA'
4101.Fl VAfile
4102options need to be used.
4103.Pp
4104The OCSP server is only useful for test and demonstration purposes:
4105it is not really usable as a full OCSP responder.
4106It contains only a very simple HTTP request handling and can only handle
4107the POST form of OCSP queries.
4108It also handles requests serially, meaning it cannot respond to
4109new requests until it has processed the current one.
4110The text index file format of revocation is also inefficient for large
4111quantities of revocation data.
4112.Pp
4113It is possible to run the
4114.Nm ocsp
4115application in
4116.Em responder
4117mode via a CGI script using the
4118.Fl respin
4119and
4120.Fl respout
4121options.
4122.Sh OCSP EXAMPLES
4123Create an OCSP request and write it to a file:
4124.Bd -literal -offset indent
4125$ openssl ocsp -issuer issuer.pem -cert c1.pem -cert c2.pem \e
4126 -reqout req.der
4127.Ed
4128.Pp
4129Send a query to an OCSP responder with URL
4130.Pa http://ocsp.myhost.com/ ,
4131save the response to a file and print it out in text form:
4132.Bd -literal -offset indent
4133$ openssl ocsp -issuer issuer.pem -cert c1.pem -cert c2.pem \e
4134 -url http://ocsp.myhost.com/ -resp_text -respout resp.der
4135.Ed
4136.Pp
4137Read in an OCSP response and print out in text form:
4138.Pp
4139.Dl $ openssl ocsp -respin resp.der -text
4140.Pp
4141OCSP server on port 8888 using a standard
4142.Nm ca
4143configuration, and a separate responder certificate.
4144All requests and responses are printed to a file:
4145.Bd -literal -offset indent
4146$ openssl ocsp -index demoCA/index.txt -port 8888 -rsigner \e
4147 rcert.pem -CA demoCA/cacert.pem -text -out log.txt
4148.Ed
4149.Pp
4150As above, but exit after processing one request:
4151.Bd -literal -offset indent
4152$ openssl ocsp -index demoCA/index.txt -port 8888 -rsigner \e
4153 rcert.pem -CA demoCA/cacert.pem -nrequest 1
4154.Ed
4155.Pp
4156Query status information using internally generated request:
4157.Bd -literal -offset indent
4158$ openssl ocsp -index demoCA/index.txt -rsigner rcert.pem -CA \e
4159 demoCA/cacert.pem -issuer demoCA/cacert.pem -serial 1
4160.Ed
4161.Pp
4162Query status information using request read from a file and write
4163the response to a second file:
4164.Bd -literal -offset indent
4165$ openssl ocsp -index demoCA/index.txt -rsigner rcert.pem -CA \e
4166 demoCA/cacert.pem -reqin req.der -respout resp.der
4167.Ed
4168.\"
4169.\" PASSWD
4170.\"
4171.Sh PASSWD
4172.nr nS 1
4173.Nm "openssl passwd"
4174.Op Fl 1 | apr1 | crypt
4175.Op Fl in Ar file
4176.Op Fl noverify
4177.Op Fl quiet
4178.Op Fl reverse
4179.Op Fl salt Ar string
4180.Op Fl stdin
4181.Op Fl table
4182.Op Ar password
4183.nr nS 0
4184.Pp
4185The
4186.Nm passwd
4187command computes the hash of a password typed at run-time
4188or the hash of each password in a list.
4189The password list is taken from the named
4190.Ar file
4191for option
4192.Fl in ,
4193from stdin for option
4194.Fl stdin ,
4195or from the command line, or from the terminal otherwise.
4196The
4197.Ux
4198standard algorithm
4199.Em crypt
4200and the MD5-based
4201.Bx
4202password algorithm
4203.Em 1
4204and its Apache variant
4205.Em apr1
4206are available.
4207.Pp
4208The options are as follows:
4209.Bl -tag -width Ds
4210.It Fl 1
4211Use the MD5 based
4212.Bx
4213password algorithm
4214.Em 1 .
4215.It Fl apr1
4216Use the
4217.Em apr1
4218algorithm
4219.Pq Apache variant of the
4220.Bx
4221algorithm.
4222.It Fl crypt
4223Use the
4224.Em crypt
4225algorithm
4226.Pq default .
4227.It Fl in Ar file
4228Read passwords from
4229.Ar file .
4230.It Fl noverify
4231Don't verify when reading a password from the terminal.
4232.It Fl quiet
4233Don't output warnings when passwords given on the command line are truncated.
4234.It Fl reverse
4235Switch table columns.
4236This only makes sense in conjunction with the
4237.Fl table
4238option.
4239.It Fl salt Ar string
4240Use the specified
4241.Ar salt .
4242When reading a password from the terminal, this implies
4243.Fl noverify .
4244.It Fl stdin
4245Read passwords from
4246.Em stdin .
4247.It Fl table
4248In the output list, prepend the cleartext password and a TAB character
4249to each password hash.
4250.El
4251.Sh PASSWD EXAMPLES
4252.Dl $ openssl passwd -crypt -salt xx password
4253prints
4254.Qq xxj31ZMTZzkVA .
4255.Pp
4256.Dl $ openssl passwd -1 -salt xxxxxxxx password
4257prints
4258.Qq $1$xxxxxxxx$UYCIxa628.9qXjpQCjM4a. .
4259.Pp
4260.Dl $ openssl passwd -apr1 -salt xxxxxxxx password
4261prints
4262.Qq $apr1$xxxxxxxx$dxHfLAsjHkDRmG83UXe8K0 .
4263.\"
4264.\" PKCS7
4265.\"
4266.Sh PKCS7
4267.nr nS 1
4268.Nm "openssl pkcs7"
4269.Bk -words
4270.Op Fl engine Ar id
4271.Op Fl in Ar file
4272.Op Fl inform Ar DER | PEM
4273.Op Fl noout
4274.Op Fl out Ar file
4275.Op Fl outform Ar DER | PEM
4276.Op Fl print_certs
4277.Op Fl text
4278.Ek
4279.nr nS 0
4280.Pp
4281The
4282.Nm pkcs7
4283command processes PKCS#7 files in DER or PEM format.
4284.Pp
4285The options are as follows:
4286.Bl -tag -width Ds
4287.It Fl engine Ar id
4288Specifying an engine (by its unique
4289.Ar id
4290string) will cause
4291.Nm pkcs7
4292to attempt to obtain a functional reference to the specified engine,
4293thus initialising it if needed.
4294The engine will then be set as the default for all available algorithms.
4295.It Fl in Ar file
4296This specifies the input
4297.Ar file
4298to read from, or standard input if this option is not specified.
4299.It Fl inform Ar DER | PEM
4300This specifies the input format.
4301.Ar DER
4302format is a DER-encoded PKCS#7 v1.5 structure.
4303.Ar PEM
4304.Pq the default
4305is a base64-encoded version of the DER form with header and footer lines.
4306.It Fl noout
4307Don't output the encoded version of the PKCS#7 structure
4308(or certificates if
4309.Fl print_certs
4310is set).
4311.It Fl out Ar file
4312Specifies the output
4313.Ar file
4314to write to, or standard output by default.
4315.It Fl outform Ar DER | PEM
4316This specifies the output format; the options have the same meaning as the
4317.Fl inform
4318option.
4319.It Fl print_certs
4320Prints out any certificates or CRLs contained in the file.
4321They are preceded by their subject and issuer names in a one-line format.
4322.It Fl text
4323Prints out certificate details in full rather than just subject and
4324issuer names.
4325.El
4326.Sh PKCS7 EXAMPLES
4327Convert a PKCS#7 file from PEM to DER:
4328.Pp
4329.Dl $ openssl pkcs7 -in file.pem -outform DER -out file.der
4330.Pp
4331Output all certificates in a file:
4332.Pp
4333.Dl $ openssl pkcs7 -in file.pem -print_certs -out certs.pem
4334.Sh PKCS7 NOTES
4335The PEM PKCS#7 format uses the header and footer lines:
4336.Bd -unfilled -offset indent
4337-----BEGIN PKCS7-----
4338-----END PKCS7-----
4339.Ed
4340.Pp
4341For compatibility with some CAs it will also accept:
4342.Bd -unfilled -offset indent
4343-----BEGIN CERTIFICATE-----
4344-----END CERTIFICATE-----
4345.Ed
4346.Sh PKCS7 RESTRICTIONS
4347There is no option to print out all the fields of a PKCS#7 file.
4348.Pp
4349The PKCS#7 routines only understand PKCS#7 v 1.5 as specified in RFC 2315.
4350They cannot currently parse, for example, the new CMS as described in RFC 2630.
4351.\"
4352.\" PKCS8
4353.\"
4354.Sh PKCS8
4355.nr nS 1
4356.Nm "openssl pkcs8"
4357.Bk -words
4358.Op Fl embed
4359.Op Fl engine Ar id
4360.Op Fl in Ar file
4361.Op Fl inform Ar DER | PEM
4362.Op Fl nocrypt
4363.Op Fl noiter
4364.Op Fl nooct
4365.Op Fl nsdb
4366.Op Fl out Ar file
4367.Op Fl outform Ar DER | PEM
4368.Op Fl passin Ar arg
4369.Op Fl passout Ar arg
4370.Op Fl topk8
4371.Op Fl v1 Ar alg
4372.Op Fl v2 Ar alg
4373.Ek
4374.nr nS 0
4375.Pp
4376The
4377.Nm pkcs8
4378command processes private keys in PKCS#8 format.
4379It can handle both unencrypted PKCS#8 PrivateKeyInfo format
4380and EncryptedPrivateKeyInfo format with a variety of PKCS#5
4381.Pq v1.5 and v2.0
4382and PKCS#12 algorithms.
4383.Pp
4384The options are as follows:
4385.Bl -tag -width Ds
4386.It Fl embed
4387This option generates DSA keys in a broken format.
4388The DSA parameters are embedded inside the
4389.Em PrivateKey
4390structure.
4391In this form the OCTET STRING contains an ASN1 SEQUENCE consisting of
4392two structures:
4393a SEQUENCE containing the parameters and an ASN1 INTEGER containing
4394the private key.
4395.It Fl engine Ar id
4396Specifying an engine (by its unique
4397.Ar id
4398string) will cause
4399.Nm pkcs8
4400to attempt to obtain a functional reference to the specified engine,
4401thus initialising it if needed.
4402The engine will then be set as the default for all available algorithms.
4403.It Fl in Ar file
4404This specifies the input
4405.Ar file
4406to read a key from, or standard input if this option is not specified.
4407If the key is encrypted, a pass phrase will be prompted for.
4408.It Fl inform Ar DER | PEM
4409This specifies the input format.
4410If a PKCS#8 format key is expected on input,
4411then either a
4412DER- or PEM-encoded version of a PKCS#8 key will be expected.
4413Otherwise the DER or PEM format of the traditional format private key is used.
4414.It Fl nocrypt
4415PKCS#8 keys generated or input are normally PKCS#8
4416.Em EncryptedPrivateKeyInfo
4417structures using an appropriate password-based encryption algorithm.
4418With this option, an unencrypted
4419.Em PrivateKeyInfo
4420structure is expected or output.
4421This option does not encrypt private keys at all and should only be used
4422when absolutely necessary.
4423Certain software such as some versions of Java code signing software use
4424unencrypted private keys.
4425.It Fl noiter
4426Use an iteration count of 1.
4427See the
4428.Sx PKCS12
4429section below for a detailed explanation of this option.
4430.It Fl nooct
4431This option generates RSA private keys in a broken format that some software
4432uses.
4433Specifically the private key should be enclosed in an OCTET STRING,
4434but some software just includes the structure itself without the
4435surrounding OCTET STRING.
4436.It Fl nsdb
4437This option generates DSA keys in a broken format compatible with Netscape
4438private key databases.
4439The
4440.Em PrivateKey
4441contains a SEQUENCE consisting of the public and private keys, respectively.
4442.It Fl out Ar file
4443This specifies the output
4444.Ar file
4445to write a key to, or standard output by default.
4446If any encryption options are set, a pass phrase will be prompted for.
4447The output filename should
4448.Em not
4449be the same as the input filename.
4450.It Fl outform Ar DER | PEM
4451This specifies the output format; the options have the same meaning as the
4452.Fl inform
4453option.
4454.It Fl passin Ar arg
4455The key password source.
4456For more information about the format of
4457.Ar arg ,
4458see the
4459.Sx PASS PHRASE ARGUMENTS
4460section above.
4461.It Fl passout Ar arg
4462The output file password source.
4463For more information about the format of
4464.Ar arg ,
4465see the
4466.Sx PASS PHRASE ARGUMENTS
4467section above.
4468.It Fl topk8
4469Normally, a PKCS#8 private key is expected on input and a traditional format
4470private key will be written.
4471With the
4472.Fl topk8
4473option the situation is reversed:
4474it reads a traditional format private key and writes a PKCS#8 format key.
4475.It Fl v1 Ar alg
4476This option specifies a PKCS#5 v1.5 or PKCS#12 algorithm to use.
4477A complete list of possible algorithms is included below.
4478.It Fl v2 Ar alg
4479This option enables the use of PKCS#5 v2.0 algorithms.
4480Normally, PKCS#8 private keys are encrypted with the password-based
4481encryption algorithm called
4482.Em pbeWithMD5AndDES-CBC ;
4483this uses 56-bit DES encryption but it was the strongest encryption
4484algorithm supported in PKCS#5 v1.5.
4485Using the
4486.Fl v2
4487option PKCS#5 v2.0 algorithms are used which can use any
4488encryption algorithm such as 168-bit triple DES or 128-bit RC2, however
4489not many implementations support PKCS#5 v2.0 yet.
4490If using private keys with
4491.Nm OpenSSL
4492then this doesn't matter.
4493.Pp
4494The
4495.Ar alg
4496argument is the encryption algorithm to use; valid values include
4497.Ar des , des3 ,
4498and
4499.Ar rc2 .
4500It is recommended that
4501.Ar des3
4502is used.
4503.El
4504.Sh PKCS8 NOTES
4505The encrypted form of a PEM-encoded PKCS#8 file uses the following
4506headers and footers:
4507.Bd -unfilled -offset indent
4508-----BEGIN ENCRYPTED PRIVATE KEY-----
4509-----END ENCRYPTED PRIVATE KEY-----
4510.Ed
4511.Pp
4512The unencrypted form uses:
4513.Bd -unfilled -offset indent
4514-----BEGIN PRIVATE KEY-----
4515-----END PRIVATE KEY-----
4516.Ed
4517.Pp
4518Private keys encrypted using PKCS#5 v2.0 algorithms and high iteration
4519counts are more secure than those encrypted using the traditional
4520.Nm SSLeay
4521compatible formats.
4522So if additional security is considered important, the keys should be converted.
4523.Pp
4524The default encryption is only 56 bits because this is the encryption
4525that most current implementations of PKCS#8 support.
4526.Pp
4527Some software may use PKCS#12 password-based encryption algorithms
4528with PKCS#8 format private keys: these are handled automatically
4529but there is no option to produce them.
4530.Pp
4531It is possible to write out
4532DER-encoded encrypted private keys in PKCS#8 format because the encryption
4533details are included at an ASN1
4534level whereas the traditional format includes them at a PEM level.
4535.Sh PKCS#5 V1.5 AND PKCS#12 ALGORITHMS
4536Various algorithms can be used with the
4537.Fl v1
4538command line option, including PKCS#5 v1.5 and PKCS#12.
4539These are described in more detail below.
4540.Pp
4541.Bl -tag -width "XXXX" -compact
4542.It Ar PBE-MD2-DES | PBE-MD5-DES
4543These algorithms were included in the original PKCS#5 v1.5 specification.
4544They only offer 56 bits of protection since they both use DES.
4545.Pp
4546.It Ar PBE-SHA1-RC2-64 | PBE-MD2-RC2-64 | PBE-MD5-RC2-64 | PBE-SHA1-DES
4547These algorithms are not mentioned in the original PKCS#5 v1.5 specification
4548but they use the same key derivation algorithm and are supported by some
4549software.
4550They are mentioned in PKCS#5 v2.0.
4551They use either 64-bit RC2 or 56-bit DES.
4552.Pp
4553.It Ar PBE-SHA1-RC4-128 | PBE-SHA1-RC4-40 | PBE-SHA1-3DES | PBE-SHA1-2DES
4554.It Ar PBE-SHA1-RC2-128 | PBE-SHA1-RC2-40
4555These algorithms use the PKCS#12 password-based encryption algorithm and
4556allow strong encryption algorithms like triple DES or 128-bit RC2 to be used.
4557.El
4558.Sh PKCS8 EXAMPLES
4559Convert a private key from traditional to PKCS#5 v2.0 format using triple DES:
4560.Pp
4561.Dl "$ openssl pkcs8 -in key.pem -topk8 -v2 des3 -out enckey.pem"
4562.Pp
4563Convert a private key to PKCS#8 using a PKCS#5 1.5 compatible algorithm
4564.Pq DES :
4565.Pp
4566.Dl $ openssl pkcs8 -in key.pem -topk8 -out enckey.pem
4567.Pp
4568Convert a private key to PKCS#8 using a PKCS#12 compatible algorithm
4569.Pq 3DES :
4570.Bd -literal -offset indent
4571$ openssl pkcs8 -in key.pem -topk8 -out enckey.pem \e
4572 -v1 PBE-SHA1-3DES
4573.Ed
4574.Pp
4575Read a DER-unencrypted PKCS#8 format private key:
4576.Pp
4577.Dl "$ openssl pkcs8 -inform DER -nocrypt -in key.der -out key.pem"
4578.Pp
4579Convert a private key from any PKCS#8 format to traditional format:
4580.Pp
4581.Dl $ openssl pkcs8 -in pk8.pem -out key.pem
4582.Sh PKCS8 STANDARDS
4583Test vectors from this PKCS#5 v2.0 implementation were posted to the
4584pkcs-tng mailing list using triple DES, DES and RC2 with high iteration counts;
4585several people confirmed that they could decrypt the private
4586keys produced and therefore it can be assumed that the PKCS#5 v2.0
4587implementation is reasonably accurate at least as far as these
4588algorithms are concerned.
4589.Pp
4590The format of PKCS#8 DSA
4591.Pq and other
4592private keys is not well documented:
4593it is hidden away in PKCS#11 v2.01, section 11.9;
4594.Nm OpenSSL Ns Li 's
4595default DSA PKCS#8 private key format complies with this standard.
4596.Sh PKCS8 BUGS
4597There should be an option that prints out the encryption algorithm
4598in use and other details such as the iteration count.
4599.Pp
4600PKCS#8 using triple DES and PKCS#5 v2.0 should be the default private
4601key format; for
4602.Nm OpenSSL
4603compatibility, several of the utilities use the old format at present.
4604.\"
4605.\" PKCS12
4606.\"
4607.Sh PKCS12
4608.nr nS 1
4609.Nm "openssl pkcs12"
4610.Bk -words
4611.Oo
4612.Fl aes128 | aes192 | aes256 |
4613.Fl des | des3
4614.Oc
4615.Op Fl cacerts
4616.Op Fl CAfile Ar file
4617.Op Fl caname Ar name
4618.Op Fl CApath Ar directory
4619.Op Fl certfile Ar file
4620.Op Fl certpbe Ar alg
4621.Op Fl chain
4622.Op Fl clcerts
4623.Op Fl CSP Ar name
4624.Op Fl descert
4625.Op Fl engine Ar id
4626.Op Fl export
4627.Op Fl in Ar file
4628.Op Fl info
4629.Op Fl inkey Ar file
4630.Op Fl keyex
4631.Op Fl keypbe Ar alg
4632.Op Fl keysig
4633.Op Fl macalg Ar alg
4634.Op Fl maciter
4635.Op Fl name Ar name
4636.Op Fl nocerts
4637.Op Fl nodes
4638.Op Fl noiter
4639.Op Fl nokeys
4640.Op Fl nomac
4641.Op Fl nomaciter
4642.Op Fl nomacver
4643.Op Fl noout
4644.Op Fl out Ar file
4645.Op Fl passin Ar arg
4646.Op Fl passout Ar arg
4647.Op Fl twopass
4648.Ek
4649.nr nS 0
4650.Pp
4651The
4652.Nm pkcs12
4653command allows PKCS#12 files
4654.Pq sometimes referred to as PFX files
4655to be created and parsed.
4656PKCS#12 files are used by several programs including Netscape, MSIE
4657and MS Outlook.
4658.Pp
4659There are a lot of options; the meaning of some depends on whether a
4660PKCS#12 file is being created or parsed.
4661By default, a PKCS#12 file is parsed;
4662a PKCS#12 file can be created by using the
4663.Fl export
4664option
4665.Pq see below .
4666.Sh PKCS12 PARSING OPTIONS
4667.Bl -tag -width "XXXX"
4668.It Xo
4669.Fl aes128 | aes192 | aes256 |
4670.Fl des | des3
4671.Xc
4672Use AES, DES, or triple DES, respectively,
4673to encrypt private keys before outputting.
4674The default is triple DES.
4675.It Fl cacerts
4676Only output CA certificates
4677.Pq not client certificates .
4678.It Fl clcerts
4679Only output client certificates
4680.Pq not CA certificates .
4681.It Fl in Ar file
4682This specifies the
4683.Ar file
4684of the PKCS#12 file to be parsed.
4685Standard input is used by default.
4686.It Fl info
4687Output additional information about the PKCS#12 file structure,
4688algorithms used, and iteration counts.
4689.It Fl nocerts
4690No certificates at all will be output.
4691.It Fl nodes
4692Don't encrypt the private keys at all.
4693.It Fl nokeys
4694No private keys will be output.
4695.It Fl nomacver
4696Don't attempt to verify the integrity MAC before reading the file.
4697.It Fl noout
4698This option inhibits output of the keys and certificates to the output file
4699version of the PKCS#12 file.
4700.It Fl out Ar file
4701The
4702.Ar file
4703to write certificates and private keys to, standard output by default.
4704They are all written in PEM format.
4705.It Fl passin Ar arg
4706The key password source.
4707For more information about the format of
4708.Ar arg ,
4709see the
4710.Sx PASS PHRASE ARGUMENTS
4711section above.
4712.It Fl passout Ar arg
4713The output file password source.
4714For more information about the format of
4715.Ar arg ,
4716see the
4717.Sx PASS PHRASE ARGUMENTS
4718section above.
4719.It Fl twopass
4720Prompt for separate integrity and encryption passwords: most software
4721always assumes these are the same so this option will render such
4722PKCS#12 files unreadable.
4723.El
4724.Sh PKCS12 FILE CREATION OPTIONS
4725.Bl -tag -width "XXXX"
4726.It Fl CAfile Ar file
4727CA storage as a file.
4728.It Fl CApath Ar directory
4729CA storage as a directory.
4730This directory must be a standard certificate directory:
4731that is, a hash of each subject name (using
4732.Cm x509 -hash )
4733should be linked to each certificate.
4734.It Fl caname Ar name
4735This specifies the
4736.Qq friendly name
4737for other certificates.
4738This option may be used multiple times to specify names for all certificates
4739in the order they appear.
4740Netscape ignores friendly names on other certificates,
4741whereas MSIE displays them.
4742.It Fl certfile Ar file
4743A file to read additional certificates from.
4744.It Fl certpbe Ar alg , Fl keypbe Ar alg
4745These options allow the algorithm used to encrypt the private key and
4746certificates to be selected.
4747Any PKCS#5 v1.5 or PKCS#12 PBE algorithm name can be used (see the
4748.Sx PKCS12 NOTES
4749section for more information).
4750If a cipher name
4751(as output by the
4752.Cm list-cipher-algorithms
4753command) is specified then it
4754is used with PKCS#5 v2.0.
4755For interoperability reasons it is advisable to only use PKCS#12 algorithms.
4756.It Fl chain
4757If this option is present, an attempt is made to include the entire
4758certificate chain of the user certificate.
4759The standard CA store is used for this search.
4760If the search fails, it is considered a fatal error.
4761.It Fl CSP Ar name
4762Write
4763.Ar name
4764as a Microsoft CSP name.
4765.It Fl descert
4766Encrypt the certificate using triple DES; this may render the PKCS#12
4767file unreadable by some
4768.Qq export grade
4769software.
4770By default, the private key is encrypted using triple DES and the
4771certificate using 40-bit RC2.
4772.It Fl engine Ar id
4773Specifying an engine (by its unique
4774.Ar id
4775string) will cause
4776.Nm pkcs12
4777to attempt to obtain a functional reference to the specified engine,
4778thus initialising it if needed.
4779The engine will then be set as the default for all available algorithms.
4780.It Fl export
4781This option specifies that a PKCS#12 file will be created rather than
4782parsed.
4783.It Fl in Ar file
4784The
4785.Ar file
4786to read certificates and private keys from, standard input by default.
4787They must all be in PEM format.
4788The order doesn't matter but one private key and its corresponding
4789certificate should be present.
4790If additional certificates are present, they will also be included
4791in the PKCS#12 file.
4792.It Fl inkey Ar file
4793File to read private key from.
4794If not present, a private key must be present in the input file.
4795.It Fl keyex | keysig
4796Specifies that the private key is to be used for key exchange or just signing.
4797This option is only interpreted by MSIE and similar MS software.
4798Normally,
4799.Qq export grade
4800software will only allow 512-bit RSA keys to be
4801used for encryption purposes, but arbitrary length keys for signing.
4802The
4803.Fl keysig
4804option marks the key for signing only.
4805Signing only keys can be used for S/MIME signing, authenticode
4806.Pq ActiveX control signing
4807and SSL client authentication;
4808however, due to a bug only MSIE 5.0 and later support
4809the use of signing only keys for SSL client authentication.
4810.It Fl macalg Ar alg
4811Specify the MAC digest algorithm.
4812If not included then SHA1 is used.
4813.It Fl maciter
4814This option is included for compatibility with previous versions; it used
4815to be needed to use MAC iterations counts but they are now used by default.
4816.It Fl name Ar name
4817This specifies the
4818.Qq friendly name
4819for the certificate and private key.
4820This name is typically displayed in list boxes by software importing the file.
4821.It Fl nomac
4822Don't attempt to provide the MAC integrity.
4823.It Fl nomaciter , noiter
4824These options affect the iteration counts on the MAC and key algorithms.
4825Unless you wish to produce files compatible with MSIE 4.0, you should leave
4826these options alone.
4827.Pp
4828To discourage attacks by using large dictionaries of common passwords,
4829the algorithm that derives keys from passwords can have an iteration count
4830applied to it: this causes a certain part of the algorithm to be repeated
4831and slows it down.
4832The MAC is used to check the file integrity but since it will normally
4833have the same password as the keys and certificates it could also be attacked.
4834By default, both MAC and encryption iteration counts are set to 2048;
4835using these options the MAC and encryption iteration counts can be set to 1.
4836Since this reduces the file security you should not use these options
4837unless you really have to.
4838Most software supports both MAC and key iteration counts.
4839MSIE 4.0 doesn't support MAC iteration counts, so it needs the
4840.Fl nomaciter
4841option.
4842.It Fl out Ar file
4843This specifies
4844.Ar file
4845to write the PKCS#12 file to.
4846Standard output is used by default.
4847.It Fl passin Ar arg
4848The key password source.
4849For more information about the format of
4850.Ar arg ,
4851see the
4852.Sx PASS PHRASE ARGUMENTS
4853section above.
4854.It Fl passout Ar arg
4855The output file password source.
4856For more information about the format of
4857.Ar arg ,
4858see the
4859.Sx PASS PHRASE ARGUMENTS
4860section above.
4861.El
4862.Sh PKCS12 NOTES
4863Although there are a large number of options,
4864most of them are very rarely used.
4865For PKCS#12 file parsing, only
4866.Fl in
4867and
4868.Fl out
4869need to be used for PKCS#12 file creation.
4870.Fl export
4871and
4872.Fl name
4873are also used.
4874.Pp
4875If none of the
4876.Fl clcerts , cacerts ,
4877or
4878.Fl nocerts
4879options are present, then all certificates will be output in the order
4880they appear in the input PKCS#12 files.
4881There is no guarantee that the first certificate present is
4882the one corresponding to the private key.
4883Certain software which requires a private key and certificate and assumes
4884the first certificate in the file is the one corresponding to the private key:
4885this may not always be the case.
4886Using the
4887.Fl clcerts
4888option will solve this problem by only outputting the certificate
4889corresponding to the private key.
4890If the CA certificates are required, they can be output to a separate
4891file using the
4892.Fl nokeys
4893and
4894.Fl cacerts
4895options to just output CA certificates.
4896.Pp
4897The
4898.Fl keypbe
4899and
4900.Fl certpbe
4901algorithms allow the precise encryption algorithms for private keys
4902and certificates to be specified.
4903Normally, the defaults are fine but occasionally software can't handle
4904triple DES encrypted private keys;
4905then the option
4906.Fl keypbe Ar PBE-SHA1-RC2-40
4907can be used to reduce the private key encryption to 40-bit RC2.
4908A complete description of all algorithms is contained in the
4909.Sx PKCS8
4910section above.
4911.Sh PKCS12 EXAMPLES
4912Parse a PKCS#12 file and output it to a file:
4913.Pp
4914.Dl $ openssl pkcs12 -in file.p12 -out file.pem
4915.Pp
4916Output only client certificates to a file:
4917.Pp
4918.Dl $ openssl pkcs12 -in file.p12 -clcerts -out file.pem
4919.Pp
4920Don't encrypt the private key:
4921.Pp
4922.Dl $ openssl pkcs12 -in file.p12 -out file.pem -nodes
4923.Pp
4924Print some info about a PKCS#12 file:
4925.Pp
4926.Dl $ openssl pkcs12 -in file.p12 -info -noout
4927.Pp
4928Create a PKCS#12 file:
4929.Bd -literal -offset indent
4930$ openssl pkcs12 -export -in file.pem -out file.p12 \e
4931 -name "My Certificate"
4932.Ed
4933.Pp
4934Include some extra certificates:
4935.Bd -literal -offset indent
4936$ openssl pkcs12 -export -in file.pem -out file.p12 \e
4937 -name "My Certificate" -certfile othercerts.pem
4938.Ed
4939.Sh PKCS12 BUGS
4940Some would argue that the PKCS#12 standard is one big bug :\-)
4941.Pp
4942Versions of
4943.Nm OpenSSL
4944before 0.9.6a had a bug in the PKCS#12 key generation routines.
4945Under rare circumstances this could produce a PKCS#12 file encrypted
4946with an invalid key.
4947As a result some PKCS#12 files which triggered this bug
4948from other implementations
4949.Pq MSIE or Netscape
4950could not be decrypted by
4951.Nm OpenSSL
4952and similarly
4953.Nm OpenSSL
4954could produce PKCS#12 files which could not be decrypted by other
4955implementations.
4956The chances of producing such a file are relatively small: less than 1 in 256.
4957.Pp
4958A side effect of fixing this bug is that any old invalidly encrypted PKCS#12
4959files can no longer be parsed by the fixed version.
4960Under such circumstances the
4961.Nm pkcs12
4962utility will report that the MAC is OK but fail with a decryption
4963error when extracting private keys.
4964.Pp
4965This problem can be resolved by extracting the private keys and certificates
4966from the PKCS#12 file using an older version of
4967.Nm OpenSSL
4968and recreating
4969the PKCS#12 file from the keys and certificates using a newer version of
4970.Nm OpenSSL .
4971For example:
4972.Bd -literal -offset indent
4973$ old-openssl -in bad.p12 -out keycerts.pem
4974$ openssl -in keycerts.pem -export -name "My PKCS#12 file" \e
4975 -out fixed.p12
4976.Ed
4977.\"
4978.\" PKEY
4979.\"
4980.Sh PKEY
4981.nr nS 1
4982.Nm "openssl pkey"
4983.Bk -words
4984.Op Ar cipher
4985.Op Fl engine Ar id
4986.Op Fl in Ar file
4987.Op Fl inform Ar DER | PEM
4988.Op Fl noout
4989.Op Fl out Ar file
4990.Op Fl outform Ar DER | PEM
4991.Op Fl passin Ar arg
4992.Op Fl passout Ar arg
4993.Op Fl pubin
4994.Op Fl pubout
4995.Op Fl text
4996.Op Fl text_pub
4997.Ek
4998.nr nS 0
4999.Pp
5000The
5001.Nm pkey
5002command processes public or private keys.
5003They can be converted between various forms
5004and their components printed out.
5005.Pp
5006The options are as follows:
5007.Bl -tag -width Ds
5008.It Ar cipher
5009These options encrypt the private key with the supplied cipher.
5010Any algorithm name accepted by
5011.Fn EVP_get_cipherbyname
5012is acceptable, such as
5013.Cm des3 .
5014.It Fl engine Ar id
5015Specifying an engine (by its unique
5016.Ar id
5017string) will cause
5018.Nm pkey
5019to attempt to obtain a functional reference to the specified engine,
5020thus initialising it if needed.
5021The engine will then be set as the default for all available algorithms.
5022.It Fl in Ar file
5023This specifies the input filename to read a key from,
5024or standard input if this option is not specified.
5025If the key is encrypted a pass phrase will be prompted for.
5026.It Fl inform Ar DER | PEM
5027This specifies the input format, DER or PEM.
5028.It Fl noout
5029Do not output the encoded version of the key.
5030.It Fl out Ar file
5031This specifies the output filename to write a key to,
5032or standard output if this option is not specified.
5033If any encryption options are set then a pass phrase
5034will be prompted for.
5035The output filename should
5036.Em not
5037be the same as the input filename.
5038.It Fl outform Ar DER | PEM
5039This specifies the output format;
5040the options have the same meaning as the
5041.Fl inform
5042option.
5043.It Fl passin Ar arg
5044The key password source.
5045For more information about the format of
5046.Ar arg ,
5047see the
5048.Sx PASS PHRASE ARGUMENTS
5049section above.
5050.It Fl passout Ar arg
5051The output file password source.
5052For more information about the format of
5053.Ar arg
5054see the
5055.Sx PASS PHRASE ARGUMENTS
5056section above.
5057.It Fl pubin
5058By default a private key is read from the input file:
5059with this option a public key is read instead.
5060.It Fl pubout
5061By default a private key is output:
5062with this option a public key will be output instead.
5063This option is automatically set if
5064the input is a public key.
5065.It Fl text
5066Print out the various public or private key components in
5067plain text in addition to the encoded version.
5068.It Fl text_pub
5069Print out only public key components
5070even if a private key is being processed.
5071.El
5072.Sh PKEY EXAMPLES
5073To remove the pass phrase on an RSA private key:
5074.Bd -literal -offset indent
5075$ openssl pkey -in key.pem -out keyout.pem
5076.Ed
5077.Pp
5078To encrypt a private key using triple DES:
5079.Bd -literal -offset indent
5080$ openssl pkey -in key.pem -des3 -out keyout.pem
5081.Ed
5082.Pp
5083To convert a private key from PEM to DER format:
5084.Bd -literal -offset indent
5085$ openssl pkey -in key.pem -outform DER -out keyout.der
5086.Ed
5087.Pp
5088To print the components of a private key to standard output:
5089.Bd -literal -offset indent
5090$ openssl pkey -in key.pem -text -noout
5091.Ed
5092.Pp
5093To print the public components of a private key to standard output:
5094.Bd -literal -offset indent
5095$ openssl pkey -in key.pem -text_pub -noout
5096.Ed
5097.Pp
5098To just output the public part of a private key:
5099.Bd -literal -offset indent
5100$ openssl pkey -in key.pem -pubout -out pubkey.pem
5101.Ed
5102.\"
5103.\" PKEYPARAM
5104.\"
5105.Sh PKEYPARAM
5106.Cm openssl pkeyparam
5107.Op Fl engine Ar id
5108.Op Fl in Ar file
5109.Op Fl noout
5110.Op Fl out Ar file
5111.Op Fl text
5112.Pp
5113The
5114.Nm pkey
5115command processes public or private keys.
5116They can be converted between various forms and their components printed out.
5117.Pp
5118The options are as follows:
5119.Bl -tag -width Ds
5120.It Fl engine Ar id
5121Specifying an engine (by its unique
5122.Ar id
5123string) will cause
5124.Nm pkeyparam
5125to attempt to obtain a functional reference to the specified engine,
5126thus initialising it if needed.
5127The engine will then be set as the default for all available algorithms.
5128.It Fl in Ar file
5129This specifies the input filename to read parameters from,
5130or standard input if this option is not specified.
5131.It Fl noout
5132Do not output the encoded version of the parameters.
5133.It Fl out Ar file
5134This specifies the output filename to write parameters to,
5135or standard output if this option is not specified.
5136.It Fl text
5137Prints out the parameters in plain text in addition to the encoded version.
5138.El
5139.Sh PKEYPARAM EXAMPLES
5140Print out text version of parameters:
5141.Bd -literal -offset indent
5142$ openssl pkeyparam -in param.pem -text
5143.Ed
5144.Sh PKEYPARAM NOTES
5145There are no
5146.Fl inform
5147or
5148.Fl outform
5149options for this command because only PEM format is supported
5150because the key type is determined by the PEM headers.
5151.\"
5152.\" PKEYUTL
5153.\"
5154.Sh PKEYUTL
5155.nr nS 1
5156.Nm "openssl pkeyutl"
5157.Bk -words
5158.Op Fl asn1parse
5159.Op Fl certin
5160.Op Fl decrypt
5161.Op Fl derive
5162.Op Fl encrypt
5163.Op Fl engine Ar id
5164.Op Fl hexdump
5165.Op Fl in Ar file
5166.Op Fl inkey Ar file
5167.Op Fl keyform Ar DER | ENGINE | PEM
5168.Op Fl out Ar file
5169.Op Fl passin Ar arg
5170.Op Fl peerform Ar DER | ENGINE | PEM
5171.Op Fl peerkey Ar file
5172.Op Fl pkeyopt Ar opt : Ns Ar value
5173.Op Fl pubin
5174.Op Fl rev
5175.Op Fl sigfile Ar file
5176.Op Fl sign
5177.Op Fl verify
5178.Op Fl verifyrecover
5179.Ek
5180.nr nS 0
5181.Pp
5182The
5183.Nm pkeyutl
5184command can be used to perform public key operations using
5185any supported algorithm.
5186.Pp
5187The options are as follows:
5188.Bl -tag -width Ds
5189.It Fl asn1parse
5190ASN1parse the output data.
5191This is useful when combined with the
5192.Fl verifyrecover
5193option when an ASN1 structure is signed.
5194.It Fl certin
5195The input is a certificate containing a public key.
5196.It Fl decrypt
5197Decrypt the input data using a private key.
5198.It Fl derive
5199Derive a shared secret using the peer key.
5200.It Fl encrypt
5201Encrypt the input data using a public key.
5202.It Fl engine Ar id
5203Specifying an engine (by its unique
5204.Ar id
5205string) will cause
5206.Nm pkeyutl
5207to attempt to obtain a functional reference to the specified engine,
5208thus initialising it if needed.
5209The engine will then be set as the default for all available algorithms.
5210.It Fl hexdump
5211Hex dump the output data.
5212.It Fl in Ar file
5213Specify the input filename to read data from,
5214or standard input if this option is not specified.
5215.It Fl inkey Ar file
5216The input key file.
5217By default it should be a private key.
5218.It Fl keyform Ar DER | ENGINE | PEM
5219The key format DER, ENGINE, or PEM.
5220.It Fl out Ar file
5221Specify the output filename to write to,
5222or standard output by default.
5223.It Fl passin Ar arg
5224The key password source.
5225For more information about the format of
5226.Ar arg ,
5227see the
5228.Sx PASS PHRASE ARGUMENTS
5229section above.
5230.It Fl peerform Ar DER | ENGINE | PEM
5231The peer key format DER, ENGINE, or PEM.
5232.It Fl peerkey Ar file
5233The peer key file, used by key derivation (agreement) operations.
5234.It Fl pkeyopt Ar opt : Ns Ar value
5235Public key options.
5236.It Fl pubin
5237The input file is a public key.
5238.It Fl rev
5239Reverse the order of the input buffer.
5240This is useful for some libraries (such as CryptoAPI)
5241which represent the buffer in little endian format.
5242.It Fl sigfile Ar file
5243Signature file (verify operation only).
5244.It Fl sign
5245Sign the input data and output the signed result.
5246This requires a private key.
5247.It Fl verify
5248Verify the input data against the signature file and indicate if the
5249verification succeeded or failed.
5250.It Fl verifyrecover
5251Verify the input data and output the recovered data.
5252.El
5253.Sh PKEYUTL NOTES
5254The operations and options supported vary according to the key algorithm
5255and its implementation.
5256The
5257.Nm OpenSSL
5258operations and options are indicated below.
5259.Pp
5260Unless otherwise mentioned all algorithms support the
5261.Ar digest : Ns Ar alg
5262option which specifies the digest in use
5263for sign, verify, and verifyrecover operations.
5264The value
5265.Ar alg
5266should represent a digest name as used in the
5267.Fn EVP_get_digestbyname
5268function, for example
5269.Cm sha1 .
5270.Ss RSA algorithm
5271The RSA algorithm supports the
5272encrypt, decrypt, sign, verify, and verifyrecover operations in general.
5273Some padding modes only support some of these
5274operations however.
5275.Bl -tag -width Ds
5276.It rsa_padding_mode : Ns Ar mode
5277This sets the RSA padding mode.
5278Acceptable values for
5279.Ar mode
5280are
5281.Cm pkcs1
5282for PKCS#1 padding;
5283.Cm sslv3
5284for SSLv3 padding;
5285.Cm none
5286for no padding;
5287.Cm oaep
5288for OAEP mode;
5289.Cm x931
5290for X9.31 mode;
5291and
5292.Cm pss
5293for PSS.
5294.Pp
5295In PKCS#1 padding if the message digest is not set then the supplied data is
5296signed or verified directly instead of using a DigestInfo structure.
5297If a digest is set then a DigestInfo
5298structure is used and its length
5299must correspond to the digest type.
5300.Pp
5301For oeap mode only encryption and decryption is supported.
5302.Pp
5303For x931 if the digest type is set it is used to format the block data;
5304otherwise the first byte is used to specify the X9.31 digest ID.
5305Sign, verify, and verifyrecover can be performed in this mode.
5306.Pp
5307For pss mode only sign and verify are supported and the digest type must be
5308specified.
5309.It rsa_pss_saltlen : Ns Ar len
5310For pss
5311mode only this option specifies the salt length.
5312Two special values are supported:
5313-1 sets the salt length to the digest length.
5314When signing -2 sets the salt length to the maximum permissible value.
5315When verifying -2 causes the salt length to be automatically determined
5316based on the PSS block structure.
5317.El
5318.Ss DSA algorithm
5319The DSA algorithm supports the sign and verify operations.
5320Currently there are no additional options other than
5321.Ar digest .
5322Only the SHA1 digest can be used and this digest is assumed by default.
5323.Ss DH algorithm
5324The DH algorithm supports the derive operation
5325and no additional options.
5326.Ss EC algorithm
5327The EC algorithm supports the sign, verify, and derive operations.
5328The sign and verify operations use ECDSA and derive uses ECDH.
5329Currently there are no additional options other than
5330.Ar digest .
5331Only the SHA1 digest can be used and this digest is assumed by default.
5332.Sh PKEYUTL EXAMPLES
5333Sign some data using a private key:
5334.Bd -literal -offset indent
5335$ openssl pkeyutl -sign -in file -inkey key.pem -out sig
5336.Ed
5337.Pp
5338Recover the signed data (e.g. if an RSA key is used):
5339.Bd -literal -offset indent
5340$ openssl pkeyutl -verifyrecover -in sig -inkey key.pem
5341.Ed
5342.Pp
5343Verify the signature (e.g. a DSA key):
5344.Bd -literal -offset indent
5345$ openssl pkeyutl -verify -in file -sigfile sig \e
5346 -inkey key.pem
5347.Ed
5348.Pp
5349Sign data using a message digest value (this is currently only valid for RSA):
5350.Bd -literal -offset indent
5351$ openssl pkeyutl -sign -in file -inkey key.pem \e
5352 -out sig -pkeyopt digest:sha256
5353.Ed
5354.Pp
5355Derive a shared secret value:
5356.Bd -literal -offset indent
5357$ openssl pkeyutl -derive -inkey key.pem \e
5358 -peerkey pubkey.pem -out secret
5359.Ed
5360.\"
5361.\" PRIME
5362.\"
5363.Sh PRIME
5364.Cm openssl prime
5365.Op Fl bits Ar n
5366.Op Fl checks Ar n
5367.Op Fl generate
5368.Op Fl hex
5369.Op Fl safe
5370.Ar p
5371.Pp
5372The
5373.Nm prime
5374command is used to generate prime numbers,
5375or to check numbers for primality.
5376Results are probabilistic:
5377they have an exceedingly high likelihood of being correct,
5378but are not guaranteed.
5379.Pp
5380The options are as follows:
5381.Bl -tag -width Ds
5382.It Fl bits Ar n
5383Specify the number of bits in the generated prime number.
5384Must be used in conjunction with
5385.Fl generate .
5386.It Fl checks Ar n
5387Perform a Miller-Rabin probabilistic primality test with
5388.Ar n
5389iterations.
5390The default is 20.
5391.It Fl generate
5392Generate a pseudo-random prime number.
5393Must be used in conjunction with
5394.Fl bits .
5395.It Fl hex
5396Output in hex format.
5397.It Fl safe
5398Generate only
5399.Qq safe
5400prime numbers
5401(i.e. a prime p so that (p-1)/2 is also prime).
5402.It Ar p
5403Test if number
5404.Ar p
5405is prime.
5406.El
5407.\"
5408.\" RAND
5409.\"
5410.Sh RAND
5411.nr nS 1
5412.Nm "openssl rand"
5413.Op Fl base64
5414.Op Fl engine Ar id
5415.Op Fl hex
5416.Op Fl out Ar file
5417.Ar num
5418.nr nS 0
5419.Pp
5420The
5421.Nm rand
5422command outputs
5423.Ar num
5424pseudo-random bytes.
5425.Pp
5426The options are as follows:
5427.Bl -tag -width Ds
5428.It Fl base64
5429Perform
5430.Em base64
5431encoding on the output.
5432.It Fl engine Ar id
5433Specifying an engine (by its unique
5434.Ar id
5435string) will cause
5436.Nm rand
5437to attempt to obtain a functional reference to the specified engine,
5438thus initialising it if needed.
5439The engine will then be set as the default for all available algorithms.
5440.It Fl hex
5441Specify hexadecimal output.
5442.It Fl out Ar file
5443Write to
5444.Ar file
5445instead of standard output.
5446.El
5447.\"
5448.\" REQ
5449.\"
5450.Sh REQ
5451.nr nS 1
5452.Nm "openssl req"
5453.Bk -words
5454.Op Fl asn1-kludge
5455.Op Fl batch
5456.Op Fl config Ar file
5457.Op Fl days Ar n
5458.Op Fl engine Ar id
5459.Op Fl extensions Ar section
5460.Op Fl in Ar file
5461.Op Fl inform Ar DER | PEM
5462.Op Fl key Ar keyfile
5463.Op Fl keyform Ar DER | PEM
5464.Op Fl keyout Ar file
5465.Op Fl md4 | md5 | sha1
5466.Op Fl modulus
5467.Op Fl nameopt Ar option
5468.Op Fl new
5469.Op Fl newhdr
5470.Op Fl newkey Ar arg
5471.Op Fl no-asn1-kludge
5472.Op Fl nodes
5473.Op Fl noout
5474.Op Fl out Ar file
5475.Op Fl outform Ar DER | PEM
5476.Op Fl passin Ar arg
5477.Op Fl passout Ar arg
5478.Op Fl pubkey
5479.Op Fl reqexts Ar section
5480.Op Fl reqopt Ar option
5481.Op Fl set_serial Ar n
5482.Op Fl subj Ar arg
5483.Op Fl subject
5484.Op Fl text
5485.Op Fl utf8
5486.Op Fl verbose
5487.Op Fl verify
5488.Op Fl x509
5489.Ek
5490.nr nS 0
5491.Pp
5492The
5493.Nm req
5494command primarily creates and processes certificate requests
5495in PKCS#10 format.
5496It can additionally create self-signed certificates,
5497for use as root CAs, for example.
5498.Pp
5499The options are as follows:
5500.Bl -tag -width Ds
5501.It Fl asn1-kludge
5502By default, the
5503.Nm req
5504command outputs certificate requests containing
5505no attributes in the correct PKCS#10 format.
5506However certain CAs will only
5507accept requests containing no attributes in an invalid form: this
5508option produces this invalid format.
5509.Pp
5510More precisely, the
5511.Em Attributes
5512in a PKCS#10 certificate request are defined as a SET OF Attribute.
5513They are
5514.Em not
5515optional, so if no attributes are present then they should be encoded as an
5516empty SET OF.
5517The invalid form does not include the empty
5518SET OF, whereas the correct form does.
5519.Pp
5520It should be noted that very few CAs still require the use of this option.
5521.It Fl batch
5522Non-interactive mode.
5523.It Fl config Ar file
5524This allows an alternative configuration file to be specified;
5525this overrides the compile time filename or any specified in
5526the
5527.Ev OPENSSL_CONF
5528environment variable.
5529.It Fl days Ar n
5530When the
5531.Fl x509
5532option is being used, this specifies the number of
5533days to certify the certificate for.
5534The default is 30 days.
5535.It Fl engine Ar id
5536Specifying an engine (by its unique
5537.Ar id
5538string) will cause
5539.Nm req
5540to attempt to obtain a functional reference to the specified engine,
5541thus initialising it if needed.
5542The engine will then be set as the default for all available algorithms.
5543.It Fl extensions Ar section , Fl reqexts Ar section
5544These options specify alternative sections to include certificate
5545extensions (if the
5546.Fl x509
5547option is present) or certificate request extensions.
5548This allows several different sections to
5549be used in the same configuration file to specify requests for
5550a variety of purposes.
5551.It Fl in Ar file
5552This specifies the input
5553.Ar file
5554to read a request from, or standard input
5555if this option is not specified.
5556A request is only read if the creation options
5557.Fl new
5558and
5559.Fl newkey
5560are not specified.
5561.It Fl inform Ar DER | PEM
5562This specifies the input format.
5563The
5564.Ar DER
5565argument uses an ASN1 DER-encoded form compatible with the PKCS#10.
5566The
5567.Ar PEM
5568form is the default format:
5569it consists of the DER format base64-encoded with additional header and
5570footer lines.
5571.It Fl key Ar keyfile
5572This specifies the file to read the private key from.
5573It also accepts PKCS#8 format private keys for PEM format files.
5574.It Fl keyform Ar DER | PEM
5575The format of the private key file specified in the
5576.Fl key
5577argument.
5578.Ar PEM
5579is the default.
5580.It Fl keyout Ar file
5581This gives the
5582.Ar file
5583to write the newly created private key to.
5584If this option is not specified, the filename present in the
5585configuration file is used.
5586.It Fl md4 | md5 | sha1
5587This specifies the message digest to sign the request with.
5588This overrides the digest algorithm specified in the configuration file.
5589.Pp
5590Some public key algorithms may override this choice.
5591For instance, DSA signatures always use SHA1.
5592.It Fl modulus
5593This option prints out the value of the modulus of the public key
5594contained in the request.
5595.It Fl nameopt Ar option , Fl reqopt Ar option
5596These options determine how the subject or issuer names are displayed.
5597The
5598.Ar option
5599argument can be a single option or multiple options separated by commas.
5600Alternatively, these options may be used more than once to set multiple options.
5601See the
5602.Sx X509
5603section below for details.
5604.It Fl new
5605This option generates a new certificate request.
5606It will prompt the user for the relevant field values.
5607The actual fields prompted for and their maximum and minimum sizes
5608are specified in the configuration file and any requested extensions.
5609.Pp
5610If the
5611.Fl key
5612option is not used, it will generate a new RSA private
5613key using information specified in the configuration file.
5614.It Fl newhdr
5615Adds the word NEW to the PEM file header and footer lines
5616on the outputed request.
5617Some software
5618.Pq Netscape certificate server
5619and some CAs need this.
5620.It Fl newkey Ar arg
5621This option creates a new certificate request and a new private key.
5622The argument takes one of several forms.
5623.Ar rsa : Ns Ar nbits ,
5624where
5625.Ar nbits
5626is the number of bits, generates an RSA key
5627.Ar nbits
5628in size.
5629If
5630.Ar nbits
5631is omitted, i.e.\&
5632.Cm -newkey rsa
5633specified,
5634the default key size, specified in the configuration file, is used.
5635.Pp
5636All other algorithms support the
5637.Ar alg : Ns Ar file
5638form,
5639where file may be an algorithm parameter file,
5640created by the
5641.Cm genpkey -genparam
5642command or an X.509 certificate for a key with approriate algorithm.
5643.Pp
5644.Ar param : Ns Ar file
5645generates a key using the parameter file or certificate
5646.Ar file ;
5647the algorithm is determined by the parameters.
5648.Ar algname : Ns Ar file
5649use algorithm
5650.Ar algname
5651and parameter file
5652.Ar file :
5653the two algorithms must match or an error occurs.
5654.Ar algname
5655just uses algorithm
5656.Ar algname ,
5657and parameters, if necessary,
5658should be specified via the
5659.Fl pkeyopt
5660option.
5661.Pp
5662.Ar dsa : Ns Ar file
5663generates a DSA key using the parameters in the file
5664.Ar file .
5665.It Fl no-asn1-kludge
5666Reverses the effect of
5667.Fl asn1-kludge .
5668.It Fl nodes
5669If this option is specified and a private key is created, it
5670will not be encrypted.
5671.It Fl noout
5672This option prevents output of the encoded version of the request.
5673.It Fl out Ar file
5674This specifies the output
5675.Ar file
5676to write to, or standard output by default.
5677.It Fl outform Ar DER | PEM
5678This specifies the output format; the options have the same meaning as the
5679.Fl inform
5680option.
5681.It Fl passin Ar arg
5682The key password source.
5683For more information about the format of
5684.Ar arg ,
5685see the
5686.Sx PASS PHRASE ARGUMENTS
5687section above.
5688.It Fl passout Ar arg
5689The output file password source.
5690For more information about the format of
5691.Ar arg ,
5692see the
5693.Sx PASS PHRASE ARGUMENTS
5694section above.
5695.It Fl pubkey
5696Outputs the public key.
5697.It Fl reqopt Ar option
5698Customise the output format used with
5699.Fl text .
5700The
5701.Ar option
5702argument can be a single option or multiple options separated by commas.
5703.Pp
5704See the discussion of the
5705.Fl certopt
5706option in the
5707.Nm x509
5708command.
5709.It Fl set_serial Ar n
5710Serial number to use when outputting a self-signed certificate.
5711This may be specified as a decimal value or a hex value if preceded by
5712.Sq 0x .
5713It is possible to use negative serial numbers but this is not recommended.
5714.It Fl subj Ar arg
5715Replaces subject field of input request with specified data and outputs
5716modified request.
5717The arg must be formatted as
5718.Em /type0=value0/type1=value1/type2=... ;
5719characters may be escaped by
5720.Sq \e
5721.Pq backslash ;
5722no spaces are skipped.
5723.It Fl subject
5724Prints out the request subject (or certificate subject if
5725.Fl x509
5726is specified.
5727.It Fl text
5728Prints out the certificate request in text form.
5729.It Fl utf8
5730This option causes field values to be interpreted as UTF8 strings;
5731by default they are interpreted as ASCII.
5732This means that the field values, whether prompted from a terminal or
5733obtained from a configuration file, must be valid UTF8 strings.
5734.It Fl verbose
5735Print extra details about the operations being performed.
5736.It Fl verify
5737Verifies the signature on the request.
5738.It Fl x509
5739This option outputs a self-signed certificate instead of a certificate
5740request.
5741This is typically used to generate a test certificate or
5742a self-signed root CA.
5743The extensions added to the certificate
5744.Pq if any
5745are specified in the configuration file.
5746Unless specified using the
5747.Fl set_serial
5748option, 0 will be used for the serial number.
5749.El
5750.Sh REQ CONFIGURATION FILE FORMAT
5751The configuration options are specified in the
5752.Em req
5753section of the configuration file.
5754As with all configuration files, if no value is specified in the specific
5755section (i.e.\&
5756.Em req )
5757then the initial unnamed or
5758.Em default
5759section is searched too.
5760.Pp
5761The options available are described in detail below.
5762.Bl -tag -width "XXXX"
5763.It Ar attributes
5764This specifies the section containing any request attributes: its format
5765is the same as
5766.Ar distinguished_name .
5767Typically these may contain the
5768.Em challengePassword
5769or
5770.Em unstructuredName
5771types.
5772They are currently ignored by
5773.Nm OpenSSL Ns Li 's
5774request signing utilities, but some CAs might want them.
5775.It Ar default_bits
5776This specifies the default key size in bits.
5777If not specified, 512 is used.
5778It is used if the
5779.Fl new
5780option is used.
5781It can be overridden by using the
5782.Fl newkey
5783option.
5784.It Ar default_keyfile
5785This is the default file to write a private key to.
5786If not specified, the key is written to standard output.
5787This can be overridden by the
5788.Fl keyout
5789option.
5790.It Ar default_md
5791This option specifies the digest algorithm to use.
5792Possible values include
5793.Ar md5
5794and
5795.Ar sha1 .
5796If not present, MD5 is used.
5797This option can be overridden on the command line.
5798.It Ar distinguished_name
5799This specifies the section containing the distinguished name fields to
5800prompt for when generating a certificate or certificate request.
5801The format is described in the next section.
5802.It Ar encrypt_key
5803If this is set to
5804.Em no
5805and a private key is generated, it is
5806.Em not
5807encrypted.
5808This is equivalent to the
5809.Fl nodes
5810command line option.
5811For compatibility,
5812.Ar encrypt_rsa_key
5813is an equivalent option.
5814.It Ar input_password | output_password
5815The passwords for the input private key file
5816.Pq if present
5817and the output private key file
5818.Pq if one will be created .
5819The command line options
5820.Fl passin
5821and
5822.Fl passout
5823override the configuration file values.
5824.It Ar oid_file
5825This specifies a file containing additional OBJECT IDENTIFIERS.
5826Each line of the file should consist of the numerical form of the
5827object identifier, followed by whitespace, then the short name followed
5828by whitespace and finally the long name.
5829.It Ar oid_section
5830This specifies a section in the configuration file containing extra
5831object identifiers.
5832Each line should consist of the short name of the
5833object identifier followed by
5834.Sq =
5835and the numerical form.
5836The short and long names are the same when this option is used.
5837.It Ar prompt
5838If set to the value
5839.Em no ,
5840this disables prompting of certificate fields
5841and just takes values from the config file directly.
5842It also changes the expected format of the
5843.Em distinguished_name
5844and
5845.Em attributes
5846sections.
5847.It Ar req_extensions
5848This specifies the configuration file section containing a list of
5849extensions to add to the certificate request.
5850It can be overridden by the
5851.Fl reqexts
5852command line switch.
5853.It Ar string_mask
5854This option limits the string types for encoding certain
5855fields.
5856The following values may be used, limiting strings to the indicated types:
5857.Bl -tag -width "MASK:number"
5858.It Ar utf8only
5859.Em UTF8String.
5860This is the default, as recommended by PKIX in RFC 2459.
5861.It Ar default
5862.Em PrintableString , IA5String , T61String , BMPString , UTF8String .
5863.It Ar pkix
5864.Em PrintableString , IA5String , BMPString , UTF8String .
5865This was inspired by the PKIX recommendation in RFC 2459 for certificates
5866generated before 2004, but differs by also permitting
5867.Em IA5String .
5868.It Ar nombstr
5869.Em PrintableString , IA5String , T61String , UniversalString .
5870This was a workaround for some ancient software that had problems
5871with the variable-sized
5872.Em BMPString
5873and
5874.Em UTF8String
5875types.
5876.It Cm MASK : Ns Ar number
5877This is an explicit bitmask of permitted types, where
5878.Ar number
5879is a C-style hex, decimal, or octal number that's a bit-wise OR of
5880.Dv B_ASN1_*
5881values from
5882.In openssl/asn1.h .
5883.El
5884.It Ar utf8
5885If set to the value
5886.Em yes ,
5887then field values are interpreted as UTF8 strings;
5888by default they are interpreted as ASCII.
5889This means that the field values, whether prompted from a terminal or
5890obtained from a configuration file, must be valid UTF8 strings.
5891.It Ar x509_extensions
5892This specifies the configuration file section containing a list of
5893extensions to add to a certificate generated when the
5894.Fl x509
5895switch is used.
5896It can be overridden by the
5897.Fl extensions
5898command line switch.
5899.El
5900.Sh REQ DISTINGUISHED NAME AND ATTRIBUTE SECTION FORMAT
5901There are two separate formats for the distinguished name and attribute
5902sections.
5903If the
5904.Fl prompt
5905option is set to
5906.Em no ,
5907then these sections just consist of field names and values: for example,
5908.Bd -unfilled -offset indent
5909CN=My Name
5910OU=My Organization
5911emailAddress=someone@somewhere.org
5912.Ed
5913.Pp
5914This allows external programs
5915.Pq e.g. GUI based
5916to generate a template file with all the field names and values
5917and just pass it to
5918.Nm req .
5919An example of this kind of configuration file is contained in the
5920.Sx REQ EXAMPLES
5921section.
5922.Pp
5923Alternatively if the
5924.Fl prompt
5925option is absent or not set to
5926.Em no ,
5927then the file contains field prompting information.
5928It consists of lines of the form:
5929.Bd -unfilled -offset indent
5930fieldName="prompt"
5931fieldName_default="default field value"
5932fieldName_min= 2
5933fieldName_max= 4
5934.Ed
5935.Pp
5936.Qq fieldName
5937is the field name being used, for example
5938.Em commonName
5939.Pq or CN .
5940The
5941.Qq prompt
5942string is used to ask the user to enter the relevant details.
5943If the user enters nothing, the default value is used;
5944if no default value is present, the field is omitted.
5945A field can still be omitted if a default value is present,
5946if the user just enters the
5947.Sq \&.
5948character.
5949.Pp
5950The number of characters entered must be between the
5951.Em fieldName_min
5952and
5953.Em fieldName_max
5954limits:
5955there may be additional restrictions based on the field being used
5956(for example
5957.Em countryName
5958can only ever be two characters long and must fit in a
5959.Em PrintableString ) .
5960.Pp
5961Some fields (such as
5962.Em organizationName )
5963can be used more than once in a DN.
5964This presents a problem because configuration files will
5965not recognize the same name occurring twice.
5966To avoid this problem, if the
5967.Em fieldName
5968contains some characters followed by a full stop, they will be ignored.
5969So, for example, a second
5970.Em organizationName
5971can be input by calling it
5972.Qq 1.organizationName .
5973.Pp
5974The actual permitted field names are any object identifier short or
5975long names.
5976These are compiled into
5977.Nm OpenSSL
5978and include the usual values such as
5979.Em commonName , countryName , localityName , organizationName ,
5980.Em organizationUnitName , stateOrProvinceName .
5981Additionally,
5982.Em emailAddress
5983is included as well as
5984.Em name , surname , givenName initials
5985and
5986.Em dnQualifier .
5987.Pp
5988Additional object identifiers can be defined with the
5989.Ar oid_file
5990or
5991.Ar oid_section
5992options in the configuration file.
5993Any additional fields will be treated as though they were a
5994.Em DirectoryString .
5995.Sh REQ EXAMPLES
5996Examine and verify a certificate request:
5997.Pp
5998.Dl $ openssl req -in req.pem -text -verify -noout
5999.Pp
6000Create a private key and then generate a certificate request from it:
6001.Bd -literal -offset indent
6002$ openssl genrsa -out key.pem 2048
6003$ openssl req -new -key key.pem -out req.pem
6004.Ed
6005.Pp
6006The same but just using req:
6007.Pp
6008.Dl $ openssl req -newkey rsa:2048 -keyout key.pem -out req.pem
6009.Pp
6010Generate a self-signed root certificate:
6011.Pp
6012.Dl "$ openssl req -x509 -newkey rsa:2048 -keyout key.pem -out req.pem"
6013.Pp
6014Example of a file pointed to by the
6015.Ar oid_file
6016option:
6017.Bd -unfilled -offset indent
60181.2.3.4 shortName A longer Name
60191.2.3.6 otherName Other longer Name
6020.Ed
6021.Pp
6022Example of a section pointed to by
6023.Ar oid_section
6024making use of variable expansion:
6025.Bd -unfilled -offset indent
6026testoid1=1.2.3.5
6027testoid2=${testoid1}.6
6028.Ed
6029.Pp
6030Sample configuration file prompting for field values:
6031.Bd -literal
6032\& [ req ]
6033\& default_bits = 1024
6034\& default_keyfile = privkey.pem
6035\& distinguished_name = req_distinguished_name
6036\& attributes = req_attributes
6037\& x509_extensions = v3_ca
6038
6039\& dirstring_type = nobmp
6040
6041\& [ req_distinguished_name ]
6042\& countryName = Country Name (2 letter code)
6043\& countryName_default = AU
6044\& countryName_min = 2
6045\& countryName_max = 2
6046
6047\& localityName = Locality Name (eg, city)
6048
6049\& organizationalUnitName = Organizational Unit Name (eg, section)
6050
6051\& commonName = Common Name (eg, YOUR name)
6052\& commonName_max = 64
6053
6054\& emailAddress = Email Address
6055\& emailAddress_max = 40
6056
6057\& [ req_attributes ]
6058\& challengePassword = A challenge password
6059\& challengePassword_min = 4
6060\& challengePassword_max = 20
6061
6062\& [ v3_ca ]
6063
6064\& subjectKeyIdentifier=hash
6065\& authorityKeyIdentifier=keyid:always,issuer:always
6066\& basicConstraints = CA:true
6067.Ed
6068.Pp
6069Sample configuration containing all field values:
6070.Bd -literal
6071
6072\& [ req ]
6073\& default_bits = 1024
6074\& default_keyfile = keyfile.pem
6075\& distinguished_name = req_distinguished_name
6076\& attributes = req_attributes
6077\& prompt = no
6078\& output_password = mypass
6079
6080\& [ req_distinguished_name ]
6081\& C = GB
6082\& ST = Test State or Province
6083\& L = Test Locality
6084\& O = Organization Name
6085\& OU = Organizational Unit Name
6086\& CN = Common Name
6087\& emailAddress = test@email.address
6088
6089\& [ req_attributes ]
6090\& challengePassword = A challenge password
6091.Ed
6092.Sh REQ NOTES
6093The header and footer lines in the PEM format are normally:
6094.Bd -unfilled -offset indent
6095-----BEGIN CERTIFICATE REQUEST-----
6096-----END CERTIFICATE REQUEST-----
6097.Ed
6098.Pp
6099Some software
6100.Pq some versions of Netscape certificate server
6101instead needs:
6102.Bd -unfilled -offset indent
6103-----BEGIN NEW CERTIFICATE REQUEST-----
6104-----END NEW CERTIFICATE REQUEST-----
6105.Ed
6106.Pp
6107which is produced with the
6108.Fl newhdr
6109option but is otherwise compatible.
6110Either form is accepted transparently on input.
6111.Pp
6112The certificate requests generated by Xenroll with MSIE have extensions added.
6113It includes the
6114.Em keyUsage
6115extension which determines the type of key
6116.Pq signature only or general purpose
6117and any additional OIDs entered by the script in an
6118.Em extendedKeyUsage
6119extension.
6120.Sh REQ DIAGNOSTICS
6121The following messages are frequently asked about:
6122.Bd -unfilled -offset indent
6123Using configuration from /some/path/openssl.cnf
6124Unable to load config info
6125.Ed
6126.Pp
6127This is followed some time later by...
6128.Bd -unfilled -offset indent
6129unable to find 'distinguished_name' in config
6130problems making Certificate Request
6131.Ed
6132.Pp
6133The first error message is the clue: it can't find the configuration
6134file!
6135Certain operations
6136.Pq like examining a certificate request
6137don't need a configuration file so its use isn't enforced.
6138Generation of certificates or requests, however, do need a configuration file.
6139This could be regarded as a bug.
6140.Pp
6141Another puzzling message is this:
6142.Bd -unfilled -offset indent
6143Attributes:
6144 a0:00
6145.Ed
6146.Pp
6147This is displayed when no attributes are present and the request includes
6148the correct empty SET OF structure
6149.Pq the DER encoding of which is 0xa0 0x00 .
6150If you just see:
6151.Pp
6152.D1 Attributes:
6153.Pp
6154then the SET OF is missing and the encoding is technically invalid
6155.Pq but it is tolerated .
6156See the description of the command line option
6157.Fl asn1-kludge
6158for more information.
6159.Sh REQ ENVIRONMENT VARIABLES
6160The variable
6161.Ev OPENSSL_CONF ,
6162if defined, allows an alternative configuration
6163file location to be specified; it will be overridden by the
6164.Fl config
6165command line switch if it is present.
6166For compatibility reasons the
6167.Ev SSLEAY_CONF
6168environment variable serves the same purpose but its use is discouraged.
6169.Sh REQ BUGS
6170.Nm OpenSSL Ns Li 's
6171handling of T61Strings
6172.Pq aka TeletexStrings
6173is broken: it effectively treats them as ISO 8859-1
6174.Pq Latin 1 ;
6175Netscape and MSIE have similar behaviour.
6176This can cause problems if you need characters that aren't available in
6177.Em PrintableStrings
6178and you don't want to or can't use
6179.Em BMPStrings .
6180.Pp
6181As a consequence of the T61String handling, the only correct way to represent
6182accented characters in
6183.Nm OpenSSL
6184is to use a
6185.Em BMPString :
6186unfortunately Netscape currently chokes on these.
6187If you have to use accented characters with Netscape
6188and MSIE then you currently need to use the invalid T61String form.
6189.Pp
6190The current prompting is not very friendly.
6191It doesn't allow you to confirm what you've just entered.
6192Other things, like extensions in certificate requests, are
6193statically defined in the configuration file.
6194Some of these, like an email address in
6195.Em subjectAltName ,
6196should be input by the user.
6197.\"
6198.\" RSA
6199.\"
6200.Sh RSA
6201.nr nS 1
6202.Nm "openssl rsa"
6203.Bk -words
6204.Oo
6205.Fl aes128 | aes192 | aes256 |
6206.Fl des | des3
6207.Oc
6208.Op Fl check
6209.Op Fl engine Ar id
6210.Op Fl in Ar file
6211.Op Fl inform Ar DER | NET | PEM
6212.Op Fl modulus
6213.Op Fl noout
6214.Op Fl out Ar file
6215.Op Fl outform Ar DER | NET | PEM
6216.Op Fl passin Ar arg
6217.Op Fl passout Ar arg
6218.Op Fl pubin
6219.Op Fl pubout
6220.Op Fl sgckey
6221.Op Fl text
6222.nr nS 0
6223.Ek
6224.Pp
6225The
6226.Nm rsa
6227command processes RSA keys.
6228They can be converted between various forms and their components printed out.
6229.Pp
6230.Sy Note :
6231this command uses the traditional
6232.Nm SSLeay
6233compatible format for private key encryption:
6234newer applications should use the more secure PKCS#8 format using the
6235.Nm pkcs8
6236utility.
6237.Pp
6238The options are as follows:
6239.Bl -tag -width Ds
6240.It Xo
6241.Fl aes128 | aes192 | aes256 |
6242.Fl des | des3
6243.Xc
6244These options encrypt the private key with the AES, DES,
6245or the triple DES ciphers, respectively, before outputting it.
6246A pass phrase is prompted for.
6247If none of these options are specified, the key is written in plain text.
6248This means that using the
6249.Nm rsa
6250utility to read in an encrypted key with no encryption option can be used
6251to remove the pass phrase from a key, or by setting the encryption options
6252it can be used to add or change the pass phrase.
6253These options can only be used with PEM format output files.
6254.It Fl check
6255This option checks the consistency of an RSA private key.
6256.It Fl engine Ar id
6257Specifying an engine (by its unique
6258.Ar id
6259string) will cause
6260.Nm rsa
6261to attempt to obtain a functional reference to the specified engine,
6262thus initialising it if needed.
6263The engine will then be set as the default for all available algorithms.
6264.It Fl in Ar file
6265This specifies the input
6266.Ar file
6267to read a key from, or standard input if this
6268option is not specified.
6269If the key is encrypted, a pass phrase will be prompted for.
6270.It Fl inform Ar DER | NET | PEM
6271This specifies the input format.
6272The
6273.Ar DER
6274argument
6275uses an ASN1 DER-encoded form compatible with the PKCS#1
6276RSAPrivateKey or SubjectPublicKeyInfo format.
6277The
6278.Ar PEM
6279form is the default format: it consists of the DER format base64-encoded with
6280additional header and footer lines.
6281On input PKCS#8 format private keys are also accepted.
6282The
6283.Ar NET
6284form is a format described in the
6285.Sx RSA NOTES
6286section.
6287.It Fl noout
6288This option prevents output of the encoded version of the key.
6289.It Fl modulus
6290This option prints out the value of the modulus of the key.
6291.It Fl out Ar file
6292This specifies the output
6293.Ar file
6294to write a key to, or standard output if this option is not specified.
6295If any encryption options are set, a pass phrase will be prompted for.
6296The output filename should
6297.Em not
6298be the same as the input filename.
6299.It Fl outform Ar DER | NET | PEM
6300This specifies the output format; the options have the same meaning as the
6301.Fl inform
6302option.
6303.It Fl passin Ar arg
6304The key password source.
6305For more information about the format of
6306.Ar arg ,
6307see the
6308.Sx PASS PHRASE ARGUMENTS
6309section above.
6310.It Fl passout Ar arg
6311The output file password source.
6312For more information about the format of
6313.Ar arg ,
6314see the
6315.Sx PASS PHRASE ARGUMENTS
6316section above.
6317.It Fl pubin
6318By default, a private key is read from the input file; with this
6319option a public key is read instead.
6320.It Fl pubout
6321By default, a private key is output;
6322with this option a public key will be output instead.
6323This option is automatically set if the input is a public key.
6324.It Fl sgckey
6325Use the modified
6326.Em NET
6327algorithm used with some versions of Microsoft IIS and SGC keys.
6328.It Fl text
6329Prints out the various public or private key components in
6330plain text, in addition to the encoded version.
6331.El
6332.Sh RSA NOTES
6333The PEM private key format uses the header and footer lines:
6334.Bd -unfilled -offset indent
6335-----BEGIN RSA PRIVATE KEY-----
6336-----END RSA PRIVATE KEY-----
6337.Ed
6338.Pp
6339The PEM public key format uses the header and footer lines:
6340.Bd -unfilled -offset indent
6341-----BEGIN PUBLIC KEY-----
6342-----END PUBLIC KEY-----
6343.Ed
6344.Pp
6345The
6346.Em NET
6347form is a format compatible with older Netscape servers
6348and Microsoft IIS .key files; this uses unsalted RC4 for its encryption.
6349It is not very secure and so should only be used when necessary.
6350.Pp
6351Some newer version of IIS have additional data in the exported .key files.
6352To use these with the
6353.Nm rsa
6354utility, view the file with a binary editor
6355and look for the string
6356.Qq private-key ,
6357then trace back to the byte sequence 0x30, 0x82
6358.Pq this is an ASN1 SEQUENCE .
6359Copy all the data from this point onwards to another file and use that as
6360the input to the
6361.Nm rsa
6362utility with the
6363.Fl inform Ar NET
6364option.
6365If there is an error after entering the password, try the
6366.Fl sgckey
6367option.
6368.Sh RSA EXAMPLES
6369To remove the pass phrase on an RSA private key:
6370.Pp
6371.Dl $ openssl rsa -in key.pem -out keyout.pem
6372.Pp
6373To encrypt a private key using triple DES:
6374.Pp
6375.Dl $ openssl rsa -in key.pem -des3 -out keyout.pem
6376.Pp
6377To convert a private key from PEM to DER format:
6378.Pp
6379.Dl $ openssl rsa -in key.pem -outform DER -out keyout.der
6380.Pp
6381To print out the components of a private key to standard output:
6382.Pp
6383.Dl $ openssl rsa -in key.pem -text -noout
6384.Pp
6385To just output the public part of a private key:
6386.Pp
6387.Dl $ openssl rsa -in key.pem -pubout -out pubkey.pem
6388.Sh RSA BUGS
6389The command line password arguments don't currently work with
6390.Em NET
6391format.
6392.Pp
6393There should be an option that automatically handles .key files,
6394without having to manually edit them.
6395.\"
6396.\" RSAUTL
6397.\"
6398.Sh RSAUTL
6399.nr nS 1
6400.Nm "openssl rsautl"
6401.Bk -words
6402.Op Fl asn1parse
6403.Op Fl certin
6404.Op Fl decrypt
6405.Op Fl encrypt
6406.Op Fl engine Ar id
6407.Op Fl hexdump
6408.Op Fl in Ar file
6409.Op Fl inkey Ar file
6410.Op Fl keyform Ar DER | PEM
6411.Op Fl oaep | pkcs | raw | ssl
6412.Op Fl out Ar file
6413.Op Fl pubin
6414.Op Fl sign
6415.Op Fl verify
6416.Ek
6417.nr nS 0
6418.Pp
6419The
6420.Nm rsautl
6421command can be used to sign, verify, encrypt and decrypt
6422data using the RSA algorithm.
6423.Pp
6424The options are as follows:
6425.Bl -tag -width Ds
6426.It Fl asn1parse
6427Asn1parse the output data; this is useful when combined with the
6428.Fl verify
6429option.
6430.It Fl certin
6431The input is a certificate containing an RSA public key.
6432.It Fl decrypt
6433Decrypt the input data using an RSA private key.
6434.It Fl encrypt
6435Encrypt the input data using an RSA public key.
6436.It Fl engine Ar id
6437Specifying an engine (by its unique
6438.Ar id
6439string) will cause
6440.Nm rsautl
6441to attempt to obtain a functional reference to the specified engine,
6442thus initialising it if needed.
6443The engine will then be set as the default for all available algorithms.
6444.It Fl hexdump
6445Hex dump the output data.
6446.It Fl in Ar file
6447This specifies the input
6448.Ar file
6449to read data from, or standard input
6450if this option is not specified.
6451.It Fl inkey Ar file
6452The input key file, by default it should be an RSA private key.
6453.It Fl keyform Ar DER | PEM
6454Private ket format.
6455Default is
6456.Ar PEM .
6457.It Fl oaep | pkcs | raw | ssl
6458The padding to use:
6459PKCS#1 OAEP, PKCS#1 v1.5
6460.Pq the default ,
6461or no padding, respectively.
6462For signatures, only
6463.Fl pkcs
6464and
6465.Fl raw
6466can be used.
6467.It Fl out Ar file
6468Specifies the output
6469.Ar file
6470to write to, or standard output by
6471default.
6472.It Fl pubin
6473The input file is an RSA public key.
6474.It Fl sign
6475Sign the input data and output the signed result.
6476This requires an RSA private key.
6477.It Fl verify
6478Verify the input data and output the recovered data.
6479.El
6480.Sh RSAUTL NOTES
6481.Nm rsautl ,
6482because it uses the RSA algorithm directly, can only be
6483used to sign or verify small pieces of data.
6484.Sh RSAUTL EXAMPLES
6485Sign some data using a private key:
6486.Pp
6487.Dl "$ openssl rsautl -sign -in file -inkey key.pem -out sig"
6488.Pp
6489Recover the signed data:
6490.Pp
6491.Dl $ openssl rsautl -verify -in sig -inkey key.pem
6492.Pp
6493Examine the raw signed data:
6494.Pp
6495.Li "\ \&$ openssl rsautl -verify -in file -inkey key.pem -raw -hexdump"
6496.Bd -unfilled
6497\& 0000 - 00 01 ff ff ff ff ff ff-ff ff ff ff ff ff ff ff ................
6498\& 0010 - ff ff ff ff ff ff ff ff-ff ff ff ff ff ff ff ff ................
6499\& 0020 - ff ff ff ff ff ff ff ff-ff ff ff ff ff ff ff ff ................
6500\& 0030 - ff ff ff ff ff ff ff ff-ff ff ff ff ff ff ff ff ................
6501\& 0040 - ff ff ff ff ff ff ff ff-ff ff ff ff ff ff ff ff ................
6502\& 0050 - ff ff ff ff ff ff ff ff-ff ff ff ff ff ff ff ff ................
6503\& 0060 - ff ff ff ff ff ff ff ff-ff ff ff ff ff ff ff ff ................
6504\& 0070 - ff ff ff ff 00 68 65 6c-6c 6f 20 77 6f 72 6c 64 .....hello world
6505.Ed
6506.Pp
6507The PKCS#1 block formatting is evident from this.
6508If this was done using encrypt and decrypt, the block would have been of type 2
6509.Pq the second byte
6510and random padding data visible instead of the 0xff bytes.
6511.Pp
6512It is possible to analyse the signature of certificates using this
6513utility in conjunction with
6514.Nm asn1parse .
6515Consider the self-signed example in
6516.Pa certs/pca-cert.pem :
6517running
6518.Nm asn1parse
6519as follows yields:
6520.Pp
6521.Li "\ \&$ openssl asn1parse -in pca-cert.pem"
6522.Bd -unfilled
6523\& 0:d=0 hl=4 l= 742 cons: SEQUENCE
6524\& 4:d=1 hl=4 l= 591 cons: SEQUENCE
6525\& 8:d=2 hl=2 l= 3 cons: cont [ 0 ]
6526\& 10:d=3 hl=2 l= 1 prim: INTEGER :02
6527\& 13:d=2 hl=2 l= 1 prim: INTEGER :00
6528\& 16:d=2 hl=2 l= 13 cons: SEQUENCE
6529\& 18:d=3 hl=2 l= 9 prim: OBJECT :md5WithRSAEncryption
6530\& 29:d=3 hl=2 l= 0 prim: NULL
6531\& 31:d=2 hl=2 l= 92 cons: SEQUENCE
6532\& 33:d=3 hl=2 l= 11 cons: SET
6533\& 35:d=4 hl=2 l= 9 cons: SEQUENCE
6534\& 37:d=5 hl=2 l= 3 prim: OBJECT :countryName
6535\& 42:d=5 hl=2 l= 2 prim: PRINTABLESTRING :AU
6536\& ....
6537\& 599:d=1 hl=2 l= 13 cons: SEQUENCE
6538\& 601:d=2 hl=2 l= 9 prim: OBJECT :md5WithRSAEncryption
6539\& 612:d=2 hl=2 l= 0 prim: NULL
6540\& 614:d=1 hl=3 l= 129 prim: BIT STRING
6541.Ed
6542.Pp
6543The final BIT STRING contains the actual signature.
6544It can be extracted with:
6545.Pp
6546.Dl "$ openssl asn1parse -in pca-cert.pem -out sig -noout -strparse 614"
6547.Pp
6548The certificate public key can be extracted with:
6549.Pp
6550.Dl $ openssl x509 -in test/testx509.pem -pubkey -noout \*(Gtpubkey.pem
6551.Pp
6552The signature can be analysed with:
6553.Pp
6554.Li "\ \&$ openssl rsautl -in sig -verify -asn1parse -inkey pubkey.pem -pubin"
6555.Bd -unfilled
6556\& 0:d=0 hl=2 l= 32 cons: SEQUENCE
6557\& 2:d=1 hl=2 l= 12 cons: SEQUENCE
6558\& 4:d=2 hl=2 l= 8 prim: OBJECT :md5
6559\& 14:d=2 hl=2 l= 0 prim: NULL
6560\& 16:d=1 hl=2 l= 16 prim: OCTET STRING
6561\& 0000 - f3 46 9e aa 1a 4a 73 c9-37 ea 93 00 48 25 08 b5 .F...Js.7...H%..
6562.Ed
6563.Pp
6564This is the parsed version of an ASN1
6565.Em DigestInfo
6566structure.
6567It can be seen that the digest used was MD5.
6568The actual part of the certificate that was signed can be extracted with:
6569.Pp
6570.Dl "$ openssl asn1parse -in pca-cert.pem -out tbs -noout -strparse 4"
6571.Pp
6572and its digest computed with:
6573.Pp
6574.Dl $ openssl md5 -c tbs
6575.D1 MD5(tbs)= f3:46:9e:aa:1a:4a:73:c9:37:ea:93:00:48:25:08:b5
6576.Pp
6577which it can be seen agrees with the recovered value above.
6578.\"
6579.\" S_CLIENT
6580.\"
6581.Sh S_CLIENT
6582.nr nS 1
6583.Nm "openssl s_client"
6584.Bk -words
6585.Op Fl 4 | 6
6586.Op Fl bugs
6587.Op Fl CAfile Ar file
6588.Op Fl CApath Ar directory
6589.Op Fl cert Ar file
6590.Op Fl check_ss_sig
6591.Op Fl cipher Ar cipherlist
6592.Oo
6593.Fl connect Ar host : Ns Ar port |
6594.Ar host Ns / Ns Ar port
6595.Oc
6596.Op Fl crl_check
6597.Op Fl crl_check_all
6598.Op Fl crlf
6599.Op Fl debug
6600.Op Fl engine Ar id
6601.Op Fl extended_crl
6602.Op Fl ign_eof
6603.Op Fl ignore_critical
6604.Op Fl issuer_checks
6605.Op Fl key Ar keyfile
6606.Op Fl msg
6607.Op Fl nbio
6608.Op Fl nbio_test
6609.Op Fl no_ssl3
6610.Op Fl no_ticket
6611.Op Fl no_tls1
6612.Op Fl pause
6613.Op Fl policy_check
6614.Op Fl prexit
6615.Op Fl psk Ar key
6616.Op Fl psk_identity Ar identity
6617.Op Fl quiet
6618.Op Fl reconnect
6619.Op Fl showcerts
6620.Op Fl ssl3
6621.Op Fl starttls Ar protocol
6622.Op Fl state
6623.Op Fl tls1
6624.Op Fl tlsextdebug
6625.Op Fl verify Ar depth
6626.Op Fl x509_strict
6627.Ek
6628.nr nS 0
6629.Pp
6630The
6631.Nm s_client
6632command implements a generic SSL/TLS client which connects
6633to a remote host using SSL/TLS.
6634It is a
6635.Em very
6636useful diagnostic tool for SSL servers.
6637.Pp
6638The options are as follows:
6639.Bl -tag -width Ds
6640.It Fl 4
6641Specify that
6642.Nm s_client
6643should attempt connections using IPv4 only.
6644.It Fl 6
6645Specify that
6646.Nm s_client
6647should attempt connections using IPv6 only.
6648.It Fl bugs
6649There are several known bugs in SSL and TLS implementations.
6650Adding this option enables various workarounds.
6651.It Fl CAfile Ar file
6652A
6653.Ar file
6654containing trusted certificates to use during server authentication
6655and to use when attempting to build the client certificate chain.
6656.It Fl CApath Ar directory
6657The
6658.Ar directory
6659to use for server certificate verification.
6660This directory must be in
6661.Qq hash format ;
6662see
6663.Fl verify
6664for more information.
6665These are also used when building the client certificate chain.
6666.It Fl cert Ar file
6667The certificate to use, if one is requested by the server.
6668The default is not to use a certificate.
6669.It Xo
6670.Fl check_ss_sig ,
6671.Fl crl_check ,
6672.Fl crl_check_all ,
6673.Fl extended_crl ,
6674.Fl ignore_critical ,
6675.Fl issuer_checks ,
6676.Fl policy_check ,
6677.Fl x509_strict
6678.Xc
6679Set various certificate chain validation options.
6680See the
6681.Nm VERIFY
6682command for details.
6683.It Fl cipher Ar cipherlist
6684This allows the cipher list sent by the client to be modified.
6685Although the server determines which cipher suite is used, it should take
6686the first supported cipher in the list sent by the client.
6687See the
6688.Sx CIPHERS
6689section above for more information.
6690.It Xo
6691.Fl connect Ar host : Ns Ar port |
6692.Ar host Ns / Ns Ar port
6693.Xc
6694This specifies the
6695.Ar host
6696and optional
6697.Ar port
6698to connect to.
6699If not specified, an attempt is made to connect to the local host
6700on port 4433.
6701Alternatively, the host and port pair may be separated using a forward-slash
6702character.
6703This form is useful for numeric IPv6 addresses.
6704.It Fl crlf
6705This option translates a line feed from the terminal into CR+LF as required
6706by some servers.
6707.It Fl debug
6708Print extensive debugging information including a hex dump of all traffic.
6709.It Fl engine Ar id
6710Specifying an engine (by its unique
6711.Ar id
6712string) will cause
6713.Nm s_client
6714to attempt to obtain a functional reference to the specified engine,
6715thus initialising it if needed.
6716The engine will then be set as the default for all available algorithms.
6717.It Fl ign_eof
6718Inhibit shutting down the connection when end of file is reached in the
6719input.
6720.It Fl key Ar keyfile
6721The private key to use.
6722If not specified, the certificate file will be used.
6723.It Fl msg
6724Show all protocol messages with hex dump.
6725.It Fl nbio
6726Turns on non-blocking I/O.
6727.It Fl nbio_test
6728Tests non-blocking I/O.
6729.It Xo
6730.Fl no_ssl3 | no_tls1 |
6731.Fl ssl3 | tls1
6732.Xc
6733These options disable the use of certain SSL or TLS protocols.
6734By default, the initial handshake uses a method which should be compatible
6735with all servers and permit them to use SSL v3 or TLS as appropriate.
6736.Pp
6737Unfortunately there are a lot of ancient and broken servers in use which
6738cannot handle this technique and will fail to connect.
6739Some servers only work if TLS is turned off with the
6740.Fl no_tls
6741option.
6742.It Fl no_ticket
6743Disable RFC 4507 session ticket support.
6744.It Fl pause
6745Pauses 1 second between each read and write call.
6746.It Fl prexit
6747Print session information when the program exits.
6748This will always attempt
6749to print out information even if the connection fails.
6750Normally, information will only be printed out once if the connection succeeds.
6751This option is useful because the cipher in use may be renegotiated
6752or the connection may fail because a client certificate is required or is
6753requested only after an attempt is made to access a certain URL.
6754.Sy Note :
6755the output produced by this option is not always accurate because a
6756connection might never have been established.
6757.It Fl psk Ar key
6758Use the PSK key
6759.Ar key
6760when using a PSK cipher suite.
6761The key is given as a hexadecimal number without the leading 0x,
6762for example -psk 1a2b3c4d.
6763.It Fl psk_identity Ar identity
6764Use the PSK identity
6765.Ar identity
6766when using a PSK cipher suite.
6767.It Fl quiet
6768Inhibit printing of session and certificate information.
6769This implicitly turns on
6770.Fl ign_eof
6771as well.
6772.It Fl reconnect
6773Reconnects to the same server 5 times using the same session ID; this can
6774be used as a test that session caching is working.
6775.It Fl showcerts
6776Display the whole server certificate chain: normally only the server
6777certificate itself is displayed.
6778.It Fl starttls Ar protocol
6779Send the protocol-specific message(s) to switch to TLS for communication.
6780.Ar protocol
6781is a keyword for the intended protocol.
6782Currently, the supported keywords are
6783.Qq ftp ,
6784.Qq imap ,
6785.Qq smtp ,
6786.Qq pop3 ,
6787and
6788.Qq xmpp .
6789.It Fl state
6790Prints out the SSL session states.
6791.It Fl tlsextdebug
6792Print out a hex dump of any TLS extensions received from the server.
6793.It Fl verify Ar depth
6794The verify
6795.Ar depth
6796to use.
6797This specifies the maximum length of the
6798server certificate chain and turns on server certificate verification.
6799Currently the verify operation continues after errors so all the problems
6800with a certificate chain can be seen.
6801As a side effect the connection will never fail due to a server
6802certificate verify failure.
6803.El
6804.Sh S_CLIENT CONNECTED COMMANDS
6805If a connection is established with an SSL server, any data received
6806from the server is displayed and any key presses will be sent to the
6807server.
6808When used interactively (which means neither
6809.Fl quiet
6810nor
6811.Fl ign_eof
6812have been given), the session will be renegotiated if the line begins with an
6813.Em R ;
6814if the line begins with a
6815.Em Q
6816or if end of file is reached, the connection will be closed down.
6817.Sh S_CLIENT NOTES
6818.Nm s_client
6819can be used to debug SSL servers.
6820To connect to an SSL HTTP server the command:
6821.Pp
6822.Dl $ openssl s_client -connect servername:443
6823.Pp
6824would typically be used
6825.Pq HTTPS uses port 443 .
6826If the connection succeeds, an HTTP command can be given such as
6827.Qq GET
6828to retrieve a web page.
6829.Pp
6830If the handshake fails, there are several possible causes; if it is
6831nothing obvious like no client certificate, then the
6832.Fl bugs , ssl3 , tls1 , no_ssl3 ,
6833and
6834.Fl no_tls1
6835options can be tried in case it is a buggy server.
6836In particular these options should be tried
6837.Em before
6838submitting a bug report to an
6839.Nm OpenSSL
6840mailing list.
6841.Pp
6842A frequent problem when attempting to get client certificates working
6843is that a web client complains it has no certificates or gives an empty
6844list to choose from.
6845This is normally because the server is not sending the client's certificate
6846authority in its
6847.Qq acceptable CA list
6848when it requests a certificate.
6849By using
6850.Nm s_client
6851the CA list can be viewed and checked.
6852However some servers only request client authentication
6853after a specific URL is requested.
6854To obtain the list in this case it is necessary to use the
6855.Fl prexit
6856option and send an HTTP request for an appropriate page.
6857.Pp
6858If a certificate is specified on the command line using the
6859.Fl cert
6860option, it will not be used unless the server specifically requests
6861a client certificate.
6862Therefore merely including a client certificate
6863on the command line is no guarantee that the certificate works.
6864.Pp
6865If there are problems verifying a server certificate, the
6866.Fl showcerts
6867option can be used to show the whole chain.
6868.Pp
6869Compression methods are only supported for
6870.Fl tls1 .
6871.Sh S_CLIENT BUGS
6872Because this program has a lot of options and also because some of
6873the techniques used are rather old, the C source of
6874.Nm s_client
6875is rather hard to read and not a model of how things should be done.
6876A typical SSL client program would be much simpler.
6877.Pp
6878The
6879.Fl verify
6880option should really exit if the server verification fails.
6881.Pp
6882The
6883.Fl prexit
6884option is a bit of a hack.
6885We should really report information whenever a session is renegotiated.
6886.\"
6887.\" S_SERVER
6888.\"
6889.Sh S_SERVER
6890.nr nS 1
6891.Nm "openssl s_server"
6892.Bk -words
6893.Op Fl accept Ar port
6894.Op Fl bugs
6895.Op Fl CAfile Ar file
6896.Op Fl CApath Ar directory
6897.Op Fl cert Ar file
6898.Op Fl cipher Ar cipherlist
6899.Op Fl context Ar id
6900.Op Fl crl_check
6901.Op Fl crl_check_all
6902.Op Fl crlf
6903.Op Fl dcert Ar file
6904.Op Fl debug
6905.Op Fl dhparam Ar file
6906.Op Fl dkey Ar file
6907.Op Fl engine Ar id
6908.Op Fl hack
6909.Op Fl HTTP
6910.Op Fl id_prefix Ar arg
6911.Op Fl key Ar keyfile
6912.Op Fl msg
6913.Op Fl nbio
6914.Op Fl nbio_test
6915.Op Fl no_dhe
6916.Op Fl no_ssl3
6917.Op Fl no_tls1
6918.Op Fl no_tmp_rsa
6919.Op Fl nocert
6920.Op Fl psk Ar key
6921.Op Fl psk_hint Ar hint
6922.Op Fl quiet
6923.Op Fl serverpref
6924.Op Fl ssl3
6925.Op Fl state
6926.Op Fl tls1
6927.Op Fl Verify Ar depth
6928.Op Fl verify Ar depth
6929.Op Fl WWW
6930.Op Fl www
6931.Ek
6932.nr nS 0
6933.Pp
6934The
6935.Nm s_server
6936command implements a generic SSL/TLS server which listens
6937for connections on a given port using SSL/TLS.
6938.Pp
6939The options are as follows:
6940.Bl -tag -width Ds
6941.It Fl accept Ar port
6942The TCP
6943.Ar port
6944to listen on for connections.
6945If not specified, 4433 is used.
6946.It Fl bugs
6947There are several known bugs in SSL and TLS implementations.
6948Adding this option enables various workarounds.
6949.It Fl CAfile Ar file
6950A file containing trusted certificates to use during client authentication
6951and to use when attempting to build the server certificate chain.
6952The list is also used in the list of acceptable client CAs passed to the
6953client when a certificate is requested.
6954.It Fl CApath Ar directory
6955The
6956.Ar directory
6957to use for client certificate verification.
6958This directory must be in
6959.Qq hash format ;
6960see
6961.Fl verify
6962for more information.
6963These are also used when building the server certificate chain.
6964.It Fl cert Ar file
6965The certificate to use; most server's cipher suites require the use of a
6966certificate and some require a certificate with a certain public key type:
6967for example the DSS cipher suites require a certificate containing a DSS
6968.Pq DSA
6969key.
6970If not specified, the file
6971.Pa server.pem
6972will be used.
6973.It Fl cipher Ar cipherlist
6974This allows the cipher list used by the server to be modified.
6975When the client sends a list of supported ciphers, the first client cipher
6976also included in the server list is used.
6977Because the client specifies the preference order, the order of the server
6978cipherlist is irrelevant.
6979See the
6980.Sx CIPHERS
6981section for more information.
6982.It Fl context Ar id
6983Sets the SSL context ID.
6984It can be given any string value.
6985If this option is not present, a default value will be used.
6986.It Fl crl_check , crl_check_all
6987Check the peer certificate has not been revoked by its CA.
6988The CRLs are appended to the certificate file.
6989With the
6990.Fl crl_check_all
6991option, all CRLs of all CAs in the chain are checked.
6992.It Fl crlf
6993This option translates a line feed from the terminal into CR+LF.
6994.It Fl dcert Ar file , Fl dkey Ar file
6995Specify an additional certificate and private key; these behave in the
6996same manner as the
6997.Fl cert
6998and
6999.Fl key
7000options except there is no default if they are not specified
7001.Pq no additional certificate or key is used .
7002As noted above some cipher suites require a certificate containing a key of
7003a certain type.
7004Some cipher suites need a certificate carrying an RSA key
7005and some a DSS
7006.Pq DSA
7007key.
7008By using RSA and DSS certificates and keys,
7009a server can support clients which only support RSA or DSS cipher suites
7010by using an appropriate certificate.
7011.It Fl debug
7012Print extensive debugging information including a hex dump of all traffic.
7013.It Fl dhparam Ar file
7014The DH parameter file to use.
7015The ephemeral DH cipher suites generate keys
7016using a set of DH parameters.
7017If not specified, an attempt is made to
7018load the parameters from the server certificate file.
7019If this fails, a static set of parameters hard coded into the
7020.Nm s_server
7021program will be used.
7022.It Fl engine Ar id
7023Specifying an engine (by its unique
7024.Ar id
7025string) will cause
7026.Nm s_server
7027to attempt to obtain a functional reference to the specified engine,
7028thus initialising it if needed.
7029The engine will then be set as the default for all available algorithms.
7030.It Fl hack
7031This option enables a further workaround for some early Netscape
7032SSL code
7033.Pq \&? .
7034.It Fl HTTP
7035Emulates a simple web server.
7036Pages will be resolved relative to the current directory;
7037for example if the URL
7038.Pa https://myhost/page.html
7039is requested, the file
7040.Pa ./page.html
7041will be loaded.
7042The files loaded are assumed to contain a complete and correct HTTP
7043response (lines that are part of the HTTP response line and headers
7044must end with CRLF).
7045.It Fl id_prefix Ar arg
7046Generate SSL/TLS session IDs prefixed by
7047.Ar arg .
7048This is mostly useful for testing any SSL/TLS code
7049.Pq e.g. proxies
7050that wish to deal with multiple servers, when each of which might be
7051generating a unique range of session IDs
7052.Pq e.g. with a certain prefix .
7053.It Fl key Ar keyfile
7054The private key to use.
7055If not specified, the certificate file will be used.
7056.It Fl msg
7057Show all protocol messages with hex dump.
7058.It Fl nbio
7059Turns on non-blocking I/O.
7060.It Fl nbio_test
7061Tests non-blocking I/O.
7062.It Fl no_dhe
7063If this option is set, no DH parameters will be loaded, effectively
7064disabling the ephemeral DH cipher suites.
7065.It Xo
7066.Fl no_ssl3 | no_tls1 |
7067.Fl ssl3 | tls1
7068.Xc
7069These options disable the use of certain SSL or TLS protocols.
7070By default, the initial handshake uses a method which should be compatible
7071with all servers and permit them to use SSL v3 or TLS as appropriate.
7072.It Fl no_tmp_rsa
7073Certain export cipher suites sometimes use a temporary RSA key; this option
7074disables temporary RSA key generation.
7075.It Fl nocert
7076If this option is set, no certificate is used.
7077This restricts the cipher suites available to the anonymous ones
7078.Pq currently just anonymous DH .
7079.It Fl psk Ar key
7080Use the PSK key
7081.Ar key
7082when using a PSK cipher suite.
7083The key is given as a hexadecimal number without the leading 0x,
7084for example -psk 1a2b3c4d.
7085.It Fl psk_hint Ar hint
7086Use the PSK identity hint
7087.Ar hint
7088when using a PSK cipher suite.
7089.It Fl quiet
7090Inhibit printing of session and certificate information.
7091.It Fl serverpref
7092Use server's cipher preferences.
7093.It Fl state
7094Prints out the SSL session states.
7095.It Fl WWW
7096Emulates a simple web server.
7097Pages will be resolved relative to the current directory;
7098for example if the URL
7099.Pa https://myhost/page.html
7100is requested, the file
7101.Pa ./page.html
7102will be loaded.
7103.It Fl www
7104Sends a status message back to the client when it connects.
7105This includes lots of information about the ciphers used and various
7106session parameters.
7107The output is in HTML format so this option will normally be used with a
7108web browser.
7109.It Fl Verify Ar depth , Fl verify Ar depth
7110The verify
7111.Ar depth
7112to use.
7113This specifies the maximum length of the client certificate chain
7114and makes the server request a certificate from the client.
7115With the
7116.Fl Verify
7117option, the client must supply a certificate or an error occurs.
7118With the
7119.Fl verify
7120option, a certificate is requested but the client does not have to send one.
7121.El
7122.Sh S_SERVER CONNECTED COMMANDS
7123If a connection request is established with an SSL client and neither the
7124.Fl www
7125nor the
7126.Fl WWW
7127option has been used, then normally any data received
7128from the client is displayed and any key presses will be sent to the client.
7129.Pp
7130Certain single letter commands are also recognized which perform special
7131operations: these are listed below.
7132.Bl -tag -width "XXXX"
7133.It Ar P
7134Send some plain text down the underlying TCP connection: this should
7135cause the client to disconnect due to a protocol violation.
7136.It Ar Q
7137End the current SSL connection and exit.
7138.It Ar q
7139End the current SSL connection, but still accept new connections.
7140.It Ar R
7141Renegotiate the SSL session and request a client certificate.
7142.It Ar r
7143Renegotiate the SSL session.
7144.It Ar S
7145Print out some session cache status information.
7146.El
7147.Sh S_SERVER NOTES
7148.Nm s_server
7149can be used to debug SSL clients.
7150To accept connections from a web browser the command:
7151.Pp
7152.Dl $ openssl s_server -accept 443 -www
7153.Pp
7154can be used, for example.
7155.Pp
7156Most web browsers
7157.Pq in particular Netscape and MSIE
7158only support RSA cipher suites, so they cannot connect to servers
7159which don't use a certificate carrying an RSA key or a version of
7160.Nm OpenSSL
7161with RSA disabled.
7162.Pp
7163Although specifying an empty list of CAs when requesting a client certificate
7164is strictly speaking a protocol violation, some SSL
7165clients interpret this to mean any CA is acceptable.
7166This is useful for debugging purposes.
7167.Pp
7168The session parameters can printed out using the
7169.Nm sess_id
7170program.
7171.Sh S_SERVER BUGS
7172Because this program has a lot of options and also because some of
7173the techniques used are rather old, the C source of
7174.Nm s_server
7175is rather hard to read and not a model of how things should be done.
7176A typical SSL server program would be much simpler.
7177.Pp
7178The output of common ciphers is wrong: it just gives the list of ciphers that
7179.Nm OpenSSL
7180recognizes and the client supports.
7181.Pp
7182There should be a way for the
7183.Nm s_server
7184program to print out details of any
7185unknown cipher suites a client says it supports.
7186.\"
7187.\" S_TIME
7188.\"
7189.Sh S_TIME
7190.nr nS 1
7191.Nm "openssl s_time"
7192.Bk -words
7193.Op Fl bugs
7194.Op Fl CAfile Ar file
7195.Op Fl CApath Ar directory
7196.Op Fl cert Ar file
7197.Op Fl cipher Ar cipherlist
7198.Op Fl connect Ar host : Ns Ar port
7199.Op Fl key Ar keyfile
7200.Op Fl nbio
7201.Op Fl new
7202.Op Fl reuse
7203.Op Fl ssl3
7204.Op Fl time Ar seconds
7205.Op Fl verify Ar depth
7206.Op Fl www Ar page
7207.Ek
7208.nr nS 0
7209.Pp
7210The
7211.Nm s_client
7212command implements a generic SSL/TLS client which connects to a
7213remote host using SSL/TLS.
7214It can request a page from the server and includes
7215the time to transfer the payload data in its timing measurements.
7216It measures the number of connections within a given timeframe,
7217the amount of data transferred
7218.Pq if any ,
7219and calculates the average time spent for one connection.
7220.Pp
7221The options are as follows:
7222.Bl -tag -width Ds
7223.It Fl bugs
7224There are several known bugs in SSL and TLS implementations.
7225Adding this option enables various workarounds.
7226.It Fl CAfile Ar file
7227A file containing trusted certificates to use during server authentication
7228and to use when attempting to build the client certificate chain.
7229.It Fl CApath Ar directory
7230The directory to use for server certificate verification.
7231This directory must be in
7232.Qq hash format ;
7233see
7234.Nm verify
7235for more information.
7236These are also used when building the client certificate chain.
7237.It Fl cert Ar file
7238The certificate to use, if one is requested by the server.
7239The default is not to use a certificate.
7240The file is in PEM format.
7241.It Fl cipher Ar cipherlist
7242This allows the cipher list sent by the client to be modified.
7243Although the server determines which cipher suite is used,
7244it should take the first supported cipher in the list sent by the client.
7245See the
7246.Nm ciphers
7247command for more information.
7248.It Fl connect Ar host : Ns Ar port
7249This specifies the host and optional port to connect to.
7250.It Fl key Ar keyfile
7251The private key to use.
7252If not specified, the certificate file will be used.
7253The file is in PEM format.
7254.It Fl nbio
7255Turns on non-blocking I/O.
7256.It Fl new
7257Performs the timing test using a new session ID for each connection.
7258If neither
7259.Fl new
7260nor
7261.Fl reuse
7262are specified,
7263they are both on by default and executed in sequence.
7264.It Fl reuse
7265Performs the timing test using the same session ID;
7266this can be used as a test that session caching is working.
7267If neither
7268.Fl new
7269nor
7270.Fl reuse
7271are specified,
7272they are both on by default and executed in sequence.
7273.It Fl ssl3
7274This option disables the use of certain SSL or TLS protocols.
7275By default, the initial handshake uses a method
7276which should be compatible with all servers and permit them to use
7277SSL v3 or TLS as appropriate.
7278The timing program is not as rich in options to turn protocols on and off as
7279the
7280.Nm s_client
7281program and may not connect to all servers.
7282.Pp
7283Unfortunately there are a lot of ancient and broken servers in use which
7284cannot handle this technique and will fail to connect.
7285Some servers only work if TLS is turned off with the
7286.Fl ssl3
7287option.
7288.It Fl time Ar seconds
7289Specifies how long
7290.Pq in seconds
7291.Nm s_time
7292should establish connections and
7293optionally transfer payload data from a server.
7294The default is 30 seconds.
7295Server and client performance and the link speed
7296determine how many connections
7297.Nm s_time
7298can establish.
7299.It Fl verify Ar depth
7300The verify depth to use.
7301This specifies the maximum length of the server certificate chain
7302and turns on server certificate verification.
7303Currently the verify operation continues after errors, so all the problems
7304with a certificate chain can be seen.
7305As a side effect,
7306the connection will never fail due to a server certificate verify failure.
7307.It Fl www Ar page
7308This specifies the page to GET from the server.
7309A value of
7310.Sq /
7311gets the index.htm[l] page.
7312If this parameter is not specified,
7313.Nm s_time
7314will only perform the handshake to establish SSL connections
7315but not transfer any payload data.
7316.El
7317.Sh S_TIME NOTES
7318.Nm s_client
7319can be used to measure the performance of an SSL connection.
7320To connect to an SSL HTTP server and get the default page the command
7321.Bd -literal -offset indent
7322$ openssl s_time -connect servername:443 -www / -CApath yourdir \e
7323 -CAfile yourfile.pem -cipher commoncipher [-ssl3]
7324.Ed
7325.Pp
7326would typically be used
7327.Pq HTTPS uses port 443 .
7328.Dq commoncipher
7329is a cipher to which both client and server can agree;
7330see the
7331.Nm ciphers
7332command for details.
7333.Pp
7334If the handshake fails, there are several possible causes:
7335if it is nothing obvious like no client certificate, the
7336.Fl bugs
7337and
7338.Fl ssl3
7339options can be tried in case it is a buggy server.
7340In particular you should play with these options
7341.Em before
7342submitting a bug report to an OpenSSL mailing list.
7343.Pp
7344A frequent problem when attempting to get client certificates working
7345is that a web client complains it has no certificates or gives an empty
7346list to choose from.
7347This is normally because the server is not sending
7348the clients certificate authority in its
7349.Qq acceptable CA list
7350when it requests a certificate.
7351By using
7352.Nm s_client ,
7353the CA list can be viewed and checked.
7354However some servers only request client authentication
7355after a specific URL is requested.
7356To obtain the list in this case, it is necessary to use the
7357.Fl prexit
7358option of
7359.Nm s_client
7360and send an HTTP request for an appropriate page.
7361.Pp
7362If a certificate is specified on the command line using the
7363.Fl cert
7364option,
7365it will not be used unless the server specifically requests
7366a client certificate.
7367Therefore merely including a client certificate
7368on the command line is no guarantee that the certificate works.
7369.Sh S_TIME BUGS
7370Because this program does not have all the options of the
7371.Nm s_client
7372program to turn protocols on and off,
7373you may not be able to measure the performance
7374of all protocols with all servers.
7375.Pp
7376The
7377.Fl verify
7378option should really exit if the server verification fails.
7379.\"
7380.\" SESS_ID
7381.\"
7382.Sh SESS_ID
7383.nr nS 1
7384.Nm "openssl sess_id"
7385.Bk -words
7386.Op Fl cert
7387.Op Fl context Ar ID
7388.Op Fl in Ar file
7389.Op Fl inform Ar DER | PEM
7390.Op Fl noout
7391.Op Fl out Ar file
7392.Op Fl outform Ar DER | PEM
7393.Op Fl text
7394.Ek
7395.nr nS 0
7396.Pp
7397The
7398.Nm sess_id
7399program processes the encoded version of the SSL session structure and
7400optionally prints out SSL session details
7401.Pq for example the SSL session master key
7402in human readable format.
7403Since this is a diagnostic tool that needs some knowledge of the SSL
7404protocol to use properly, most users will not need to use it.
7405.Pp
7406The options are as follows:
7407.Bl -tag -width Ds
7408.It Fl cert
7409If a certificate is present in the session,
7410it will be output using this option;
7411if the
7412.Fl text
7413option is also present, then it will be printed out in text form.
7414.It Fl context Ar ID
7415This option can set the session ID so the output session information uses the
7416supplied
7417.Ar ID .
7418The
7419.Ar ID
7420can be any string of characters.
7421This option won't normally be used.
7422.It Fl in Ar file
7423This specifies the input
7424.Ar file
7425to read session information from, or standard input by default.
7426.It Fl inform Ar DER | PEM
7427This specifies the input format.
7428The
7429.Ar DER
7430argument uses an ASN1 DER-encoded
7431format containing session details.
7432The precise format can vary from one version to the next.
7433The
7434.Ar PEM
7435form is the default format: it consists of the DER
7436format base64-encoded with additional header and footer lines.
7437.It Fl noout
7438This option prevents output of the encoded version of the session.
7439.It Fl out Ar file
7440This specifies the output
7441.Ar file
7442to write session information to, or standard
7443output if this option is not specified.
7444.It Fl outform Ar DER | PEM
7445This specifies the output format; the options have the same meaning as the
7446.Fl inform
7447option.
7448.It Fl text
7449Prints out the various public or private key components in
7450plain text in addition to the encoded version.
7451.El
7452.Sh SESS_ID OUTPUT
7453Typical output:
7454.Bd -literal
7455SSL-Session:
7456 Protocol : TLSv1
7457 Cipher : 0016
7458 Session-ID: 871E62626C554CE95488823752CBD5F3673A3EF3DCE9C67BD916C809914B40ED
7459 Session-ID-ctx: 01000000
7460 Master-Key: A7CEFC571974BE02CAC305269DC59F76EA9F0B180CB6642697A68251F2D2BB57E51DBBB4C7885573192AE9AEE220FACD
7461 Key-Arg : None
7462 Start Time: 948459261
7463 Timeout : 300 (sec)
7464 Verify return code 0 (ok)
7465.Ed
7466.Pp
7467These are described below in more detail.
7468.Pp
7469.Bl -tag -width "Verify return code " -compact
7470.It Ar Protocol
7471This is the protocol in use: TLSv1 or SSLv3.
7472.It Ar Cipher
7473The cipher used is the actual raw SSL or TLS cipher code;
7474see the SSL or TLS specifications for more information.
7475.It Ar Session-ID
7476The SSL session ID in hex format.
7477.It Ar Session-ID-ctx
7478The session ID context in hex format.
7479.It Ar Master-Key
7480This is the SSL session master key.
7481.It Ar Key-Arg
7482The key argument; this is only used in SSL v2.
7483.It Ar Start Time
7484This is the session start time, represented as an integer in standard
7485.Ux
7486format.
7487.It Ar Timeout
7488The timeout in seconds.
7489.It Ar Verify return code
7490This is the return code when an SSL client certificate is verified.
7491.El
7492.Sh SESS_ID NOTES
7493The PEM-encoded session format uses the header and footer lines:
7494.Bd -unfilled -offset indent
7495-----BEGIN SSL SESSION PARAMETERS-----
7496-----END SSL SESSION PARAMETERS-----
7497.Ed
7498.Pp
7499Since the SSL session output contains the master key, it is possible to read
7500the contents of an encrypted session using this information.
7501Therefore appropriate security precautions
7502should be taken if the information is being output by a
7503.Qq real
7504application.
7505This is, however, strongly discouraged and should only be used for
7506debugging purposes.
7507.Sh SESS_ID BUGS
7508The cipher and start time should be printed out in human readable form.
7509.\"
7510.\" SMIME
7511.\"
7512.Sh SMIME
7513.nr nS 1
7514.Nm "openssl smime"
7515.Bk -words
7516.Oo
7517.Fl aes128 | aes192 | aes256 | des |
7518.Fl des3 | rc2-40 | rc2-64 | rc2-128
7519.Oc
7520.Op Fl binary
7521.Op Fl CAfile Ar file
7522.Op Fl CApath Ar directory
7523.Op Fl certfile Ar file
7524.Op Fl check_ss_sig
7525.Op Fl content Ar file
7526.Op Fl crl_check
7527.Op Fl crl_check_all
7528.Op Fl decrypt
7529.Op Fl encrypt
7530.Op Fl engine Ar id
7531.Op Fl extended_crl
7532.Op Fl from Ar addr
7533.Op Fl ignore_critical
7534.Op Fl in Ar file
7535.Op Fl indef
7536.Op Fl inform Ar DER | PEM | SMIME
7537.Op Fl inkey Ar file
7538.Op Fl issuer_checks
7539.Op Fl keyform Ar ENGINE | PEM
7540.Op Fl md Ar digest
7541.Op Fl noattr
7542.Op Fl nocerts
7543.Op Fl nochain
7544.Op Fl nodetach
7545.Op Fl noindef
7546.Op Fl nointern
7547.Op Fl nosigs
7548.Op Fl noverify
7549.Op Fl out Ar file
7550.Op Fl outform Ar DER | PEM | SMIME
7551.Op Fl passin Ar arg
7552.Op Fl pk7out
7553.Op Fl policy_check
7554.Op Fl recip Ar file
7555.Op Fl resign
7556.Op Fl sign
7557.Op Fl signer Ar file
7558.Op Fl stream
7559.Op Fl subject Ar s
7560.Op Fl text
7561.Op Fl to Ar addr
7562.Op Fl verify
7563.Op Fl x509_strict
7564.Op Ar cert.pem ...
7565.Ek
7566.nr nS 0
7567.Pp
7568The
7569.Nm smime
7570command handles
7571.Em S/MIME
7572mail.
7573It can encrypt, decrypt, sign, and verify
7574.Em S/MIME
7575messages.
7576.Pp
7577There are six operation options that set the type of operation to be performed.
7578The meaning of the other options varies according to the operation type.
7579.Pp
7580The six operation options are as follows:
7581.Bl -tag -width "XXXX"
7582.It Fl decrypt
7583Decrypt mail using the supplied certificate and private key.
7584Expects an encrypted mail message in
7585.Em MIME
7586format for the input file.
7587The decrypted mail is written to the output file.
7588.It Fl encrypt
7589Encrypt mail for the given recipient certificates.
7590Input file is the message to be encrypted.
7591The output file is the encrypted mail in
7592.Em MIME
7593format.
7594.It Fl pk7out
7595Takes an input message and writes out a PEM-encoded PKCS#7 structure.
7596.It Fl resign
7597Resign a message: take an existing message and one or more new signers.
7598.It Fl sign
7599Sign mail using the supplied certificate and private key.
7600Input file is the message to be signed.
7601The signed message in
7602.Em MIME
7603format is written to the output file.
7604.It Fl verify
7605Verify signed mail.
7606Expects a signed mail message on input and outputs the signed data.
7607Both clear text and opaque signing is supported.
7608.El
7609.Pp
7610The reamaining options are as follows:
7611.Bl -tag -width "XXXX"
7612.It Xo
7613.Fl aes128 | aes192 | aes256 | des |
7614.Fl des3 | rc2-40 | rc2-64 | rc2-128
7615.Xc
7616The encryption algorithm to use.
7617128-, 192-, or 256-bit AES,
7618DES
7619.Pq 56 bits ,
7620triple DES
7621.Pq 168 bits ,
7622or 40-, 64-, or 128-bit RC2, respectively;
7623if not specified, 40-bit RC2 is
7624used.
7625Only used with
7626.Fl encrypt .
7627.It Fl binary
7628Normally, the input message is converted to
7629.Qq canonical
7630format which is effectively using CR and LF as end of line \-
7631as required by the
7632.Em S/MIME
7633specification.
7634When this option is present no translation occurs.
7635This is useful when handling binary data which may not be in
7636.Em MIME
7637format.
7638.It Fl CAfile Ar file
7639A
7640.Ar file
7641containing trusted CA certificates; only used with
7642.Fl verify .
7643.It Fl CApath Ar directory
7644A
7645.Ar directory
7646containing trusted CA certificates; only used with
7647.Fl verify .
7648This directory must be a standard certificate directory:
7649that is, a hash of each subject name (using
7650.Nm x509 -hash )
7651should be linked to each certificate.
7652.It Ar cert.pem ...
7653One or more certificates of message recipients: used when encrypting
7654a message.
7655.It Fl certfile Ar file
7656Allows additional certificates to be specified.
7657When signing, these will be included with the message.
7658When verifying, these will be searched for the signers' certificates.
7659The certificates should be in PEM format.
7660.It Xo
7661.Fl check_ss_sig ,
7662.Fl crl_check ,
7663.Fl crl_check_all ,
7664.Fl extended_crl ,
7665.Fl ignore_critical ,
7666.Fl issuer_checks ,
7667.Fl policy_check ,
7668.Fl x509_strict
7669.Xc
7670Set various certificate chain validation options.
7671See the
7672.Nm VERIFY
7673command for details.
7674.It Fl content Ar file
7675This specifies a file containing the detached content.
7676This is only useful with the
7677.Fl verify
7678command.
7679This is only usable if the PKCS#7 structure is using the detached
7680signature form where the content is not included.
7681This option will override any content if the input format is
7682.Em S/MIME
7683and it uses the multipart/signed
7684.Em MIME
7685content type.
7686.It Fl engine Ar id
7687Specifying an engine (by its unique
7688.Ar id
7689string) will cause
7690.Nm smime
7691to attempt to obtain a functional reference to the specified engine,
7692thus initialising it if needed.
7693The engine will then be set as the default for all available algorithms.
7694.It Xo
7695.Fl from Ar addr ,
7696.Fl subject Ar s ,
7697.Fl to Ar addr
7698.Xc
7699The relevant mail headers.
7700These are included outside the signed
7701portion of a message so they may be included manually.
7702When signing, many
7703.Em S/MIME
7704mail clients check that the signer's certificate email
7705address matches the From: address.
7706.It Fl in Ar file
7707The input message to be encrypted or signed or the
7708.Em MIME
7709message to
7710be decrypted or verified.
7711.It Fl indef
7712Enable streaming I/O for encoding operations.
7713This permits single pass processing of data without
7714the need to hold the entire contents in memory,
7715potentially supporting very large files.
7716Streaming is automatically set for S/MIME signing with detached
7717data if the output format is SMIME;
7718it is currently off by default for all other operations.
7719.It Fl inform Ar DER | PEM | SMIME
7720This specifies the input format for the PKCS#7 structure.
7721The default is
7722.Em SMIME ,
7723which reads an
7724.Em S/MIME
7725format message.
7726.Ar PEM
7727and
7728.Ar DER
7729format change this to expect PEM and DER format PKCS#7 structures
7730instead.
7731This currently only affects the input format of the PKCS#7
7732structure; if no PKCS#7 structure is being input (for example with
7733.Fl encrypt
7734or
7735.Fl sign ) ,
7736this option has no effect.
7737.It Fl inkey Ar file
7738The private key to use when signing or decrypting.
7739This must match the corresponding certificate.
7740If this option is not specified, the private key must be included
7741in the certificate file specified with
7742the
7743.Fl recip
7744or
7745.Fl signer
7746file.
7747When signing,
7748this option can be used multiple times to specify successive keys.
7749.It Fl keyform Ar ENGINE | PEM
7750Input private key format.
7751.It Fl md Ar digest
7752The digest algorithm to use when signing or resigning.
7753If not present then the default digest algorithm for the signing key is used
7754(usually SHA1).
7755.It Fl noattr
7756Normally, when a message is signed a set of attributes are included which
7757include the signing time and supported symmetric algorithms.
7758With this option they are not included.
7759.It Fl nocerts
7760When signing a message, the signer's certificate is normally included;
7761with this option it is excluded.
7762This will reduce the size of the signed message but the verifier must
7763have a copy of the signer's certificate available locally (passed using the
7764.Fl certfile
7765option, for example).
7766.It Fl nochain
7767Do not do chain verification of signers' certificates: that is,
7768don't use the certificates in the signed message as untrusted CAs.
7769.It Fl nodetach
7770When signing a message use opaque signing: this form is more resistant
7771to translation by mail relays but it cannot be read by mail agents that
7772do not support
7773.Em S/MIME .
7774Without this option cleartext signing with the
7775.Em MIME
7776type multipart/signed is used.
7777.It Fl noindef
7778Disable streaming I/O where it would produce an encoding of indefinite length.
7779This option currently has no effect.
7780In future streaming will be enabled by default on all relevant operations
7781and this option will disable it.
7782.It Fl nointern
7783When verifying a message, normally certificates
7784.Pq if any
7785included in the message are searched for the signing certificate.
7786With this option, only the certificates specified in the
7787.Fl certfile
7788option are used.
7789The supplied certificates can still be used as untrusted CAs however.
7790.It Fl nosigs
7791Don't try to verify the signatures on the message.
7792.It Fl noverify
7793Do not verify the signer's certificate of a signed message.
7794.It Fl out Ar file
7795The message text that has been decrypted or verified, or the output
7796.Em MIME
7797format message that has been signed or verified.
7798.It Fl outform Ar DER | PEM | SMIME
7799This specifies the output format for the PKCS#7 structure.
7800The default is
7801.Em SMIME ,
7802which writes an
7803.Em S/MIME
7804format message.
7805.Ar PEM
7806and
7807.Ar DER
7808format change this to write PEM and DER format PKCS#7 structures
7809instead.
7810This currently only affects the output format of the PKCS#7
7811structure; if no PKCS#7 structure is being output (for example with
7812.Fl verify
7813or
7814.Fl decrypt )
7815this option has no effect.
7816.It Fl passin Ar arg
7817The key password source.
7818For more information about the format of
7819.Ar arg ,
7820see the
7821.Sx PASS PHRASE ARGUMENTS
7822section above.
7823.It Fl recip Ar file
7824The recipients certificate when decrypting a message.
7825This certificate
7826must match one of the recipients of the message or an error occurs.
7827.It Fl signer Ar file
7828A signing certificate when signing or resigning a message;
7829this option can be used multiple times if more than one signer is required.
7830If a message is being verified, the signer's certificates will be
7831written to this file if the verification was successful.
7832.It Fl stream
7833The same as
7834.Fl indef .
7835.It Fl text
7836This option adds plain text
7837.Pq text/plain
7838.Em MIME
7839headers to the supplied message if encrypting or signing.
7840If decrypting or verifying, it strips off text headers:
7841if the decrypted or verified message is not of
7842.Em MIME
7843type text/plain then an error occurs.
7844.El
7845.Sh SMIME NOTES
7846The
7847.Em MIME
7848message must be sent without any blank lines between the
7849headers and the output.
7850Some mail programs will automatically add a blank line.
7851Piping the mail directly to sendmail is one way to
7852achieve the correct format.
7853.Pp
7854The supplied message to be signed or encrypted must include the
7855necessary
7856.Em MIME
7857headers or many
7858.Em S/MIME
7859clients won't display it properly
7860.Pq if at all .
7861You can use the
7862.Fl text
7863option to automatically add plain text headers.
7864.Pp
7865A
7866.Qq signed and encrypted
7867message is one where a signed message is then encrypted.
7868This can be produced by encrypting an already signed message:
7869see the
7870.Sx SMIME EXAMPLES
7871section.
7872.Pp
7873This version of the program only allows one signer per message, but it
7874will verify multiple signers on received messages.
7875Some
7876.Em S/MIME
7877clients choke if a message contains multiple signers.
7878It is possible to sign messages
7879.Qq in parallel
7880by signing an already signed message.
7881.Pp
7882The options
7883.Fl encrypt
7884and
7885.Fl decrypt
7886reflect common usage in
7887.Em S/MIME
7888clients.
7889Strictly speaking these process PKCS#7 enveloped data: PKCS#7
7890encrypted data is used for other purposes.
7891.Pp
7892The
7893.Fl resign
7894option uses an existing message digest when adding a new signer.
7895This means that attributes must be present in at least one existing
7896signer using the same message digest or this operation will fail.
7897.Pp
7898The
7899.Fl stream
7900and
7901.Fl indef
7902options enable experimental streaming I/O support.
7903As a result the encoding is BER using indefinite length constructed encoding
7904and no longer DER.
7905Streaming is supported for the
7906.Fl encrypt
7907and
7908.Fl sign
7909operations if the content is not detached.
7910.Pp
7911Streaming is always used for the
7912.Fl sign
7913operation with detached data
7914but since the content is no longer part of the PKCS#7 structure
7915the encoding remains DER.
7916.Sh SMIME EXIT CODES
7917.Bl -tag -width "XXXX"
7918.It Ar 0
7919The operation was completely successful.
7920.It Ar 1
7921An error occurred parsing the command options.
7922.It Ar 2
7923One of the input files could not be read.
7924.It Ar 3
7925An error occurred creating the PKCS#7 file or when reading the
7926.Em MIME
7927message.
7928.It Ar 4
7929An error occurred decrypting or verifying the message.
7930.It Ar 5
7931The message was verified correctly, but an error occurred writing out
7932the signer's certificates.
7933.El
7934.Sh SMIME EXAMPLES
7935Create a cleartext signed message:
7936.Bd -literal -offset indent
7937$ openssl smime -sign -in message.txt -text -out mail.msg \e
7938 -signer mycert.pem
7939.Ed
7940.Pp
7941Create an opaque signed message:
7942.Bd -literal -offset indent
7943$ openssl smime -sign -in message.txt -text -out mail.msg \e
7944 -nodetach -signer mycert.pem
7945.Ed
7946.Pp
7947Create a signed message, include some additional certificates and
7948read the private key from another file:
7949.Bd -literal -offset indent
7950$ openssl smime -sign -in in.txt -text -out mail.msg \e
7951 -signer mycert.pem -inkey mykey.pem -certfile mycerts.pem
7952.Ed
7953.Pp
7954Create a signed message with two signers:
7955.Bd -literal -offset indent
7956openssl smime -sign -in message.txt -text -out mail.msg \e
7957 -signer mycert.pem -signer othercert.pem
7958.Ed
7959.Pp
7960Send a signed message under
7961.Ux
7962directly to
7963.Xr sendmail 8 ,
7964including headers:
7965.Bd -literal -offset indent
7966$ openssl smime -sign -in in.txt -text -signer mycert.pem \e
7967 -from steve@openssl.org -to someone@somewhere \e
7968 -subject "Signed message" | sendmail someone@somewhere
7969.Ed
7970.Pp
7971Verify a message and extract the signer's certificate if successful:
7972.Bd -literal -offset indent
7973$ openssl smime -verify -in mail.msg -signer user.pem \e
7974 -out signedtext.txt
7975.Ed
7976.Pp
7977Send encrypted mail using triple DES:
7978.Bd -literal -offset indent
7979$ openssl smime -encrypt -in in.txt -from steve@openssl.org \e
7980 -to someone@somewhere -subject "Encrypted message" \e
7981 -des3 -out mail.msg user.pem
7982.Ed
7983.Pp
7984Sign and encrypt mail:
7985.Bd -literal -offset indent
7986$ openssl smime -sign -in ml.txt -signer my.pem -text | \e
7987 openssl smime -encrypt -out mail.msg \e
7988 -from steve@openssl.org -to someone@somewhere \e
7989 -subject "Signed and Encrypted message" -des3 user.pem
7990.Ed
7991.Pp
7992.Sy Note :
7993The encryption command does not include the
7994.Fl text
7995option because the message being encrypted already has
7996.Em MIME
7997headers.
7998.Pp
7999Decrypt mail:
8000.Bd -literal -offset indent
8001$ openssl smime -decrypt -in mail.msg -recip mycert.pem \e
8002 -inkey key.pem"
8003.Ed
8004.Pp
8005The output from Netscape form signing is a PKCS#7 structure with the
8006detached signature format.
8007You can use this program to verify the signature by line wrapping the
8008base64-encoded structure and surrounding it with:
8009.Bd -unfilled -offset indent
8010-----BEGIN PKCS7-----
8011-----END PKCS7-----
8012.Ed
8013.Pp
8014and using the command:
8015.Bd -literal -offset indent
8016$ openssl smime -verify -inform PEM -in signature.pem \e
8017 -content content.txt
8018.Ed
8019.Pp
8020Alternatively, you can base64 decode the signature and use:
8021.Bd -literal -offset indent
8022$ openssl smime -verify -inform DER -in signature.der \e
8023 -content content.txt
8024.Ed
8025.Pp
8026Create an encrypted message using 128-bit AES:
8027.Bd -literal -offset indent
8028openssl smime -encrypt -in plain.txt -aes128 \e
8029 -out mail.msg cert.pem
8030.Ed
8031.Pp
8032Add a signer to an existing message:
8033.Bd -literal -offset indent
8034openssl smime -resign -in mail.msg -signer newsign.pem \e
8035 -out mail2.msg
8036.Ed
8037.Sh SMIME BUGS
8038The
8039.Em MIME
8040parser isn't very clever: it seems to handle most messages that I've thrown
8041at it, but it may choke on others.
8042.Pp
8043The code currently will only write out the signer's certificate to a file:
8044if the signer has a separate encryption certificate this must be manually
8045extracted.
8046There should be some heuristic that determines the correct encryption
8047certificate.
8048.Pp
8049Ideally, a database should be maintained of a certificate for each email
8050address.
8051.Pp
8052The code doesn't currently take note of the permitted symmetric encryption
8053algorithms as supplied in the
8054.Em SMIMECapabilities
8055signed attribute.
8056This means the user has to manually include the correct encryption algorithm.
8057It should store the list of permitted ciphers in a database and only use those.
8058.Pp
8059No revocation checking is done on the signer's certificate.
8060.Pp
8061The current code can only handle
8062.Em S/MIME
8063v2 messages; the more complex
8064.Em S/MIME
8065v3 structures may cause parsing errors.
8066.Sh SMIME HISTORY
8067The use of multiple
8068.Fl signer
8069options and the
8070.Fl resign
8071command were first added in
8072.Nm OpenSSL
80731.0.0.
8074.\"
8075.\" SPEED
8076.\"
8077.Sh SPEED
8078.nr nS 1
8079.Nm "openssl speed"
8080.Bk -words
8081.Op Cm aes
8082.Op Cm aes-128-cbc
8083.Op Cm aes-192-cbc
8084.Op Cm aes-256-cbc
8085.Op Cm blowfish
8086.Op Cm bf-cbc
8087.Op Cm cast
8088.Op Cm cast-cbc
8089.Op Cm des
8090.Op Cm des-cbc
8091.Op Cm des-ede3
8092.Op Cm dsa
8093.Op Cm dsa512
8094.Op Cm dsa1024
8095.Op Cm dsa2048
8096.Op Cm hmac
8097.Op Cm md2
8098.Op Cm md4
8099.Op Cm md5
8100.Op Cm rc2
8101.Op Cm rc2-cbc
8102.Op Cm rc4
8103.Op Cm rmd160
8104.Op Cm rsa
8105.Op Cm rsa512
8106.Op Cm rsa1024
8107.Op Cm rsa2048
8108.Op Cm rsa4096
8109.Op Cm sha1
8110.Op Fl decrypt
8111.Op Fl elapsed
8112.Op Fl engine Ar id
8113.Op Fl evp Ar e
8114.Op Fl mr
8115.Op Fl multi Ar number
8116.Ek
8117.nr nS 0
8118.Pp
8119The
8120.Nm speed
8121command is used to test the performance of cryptographic algorithms.
8122.Bl -tag -width "XXXX"
8123.It Bq Cm zero or more test algorithms
8124If any options are given,
8125.Nm speed
8126tests those algorithms, otherwise all of the above are tested.
8127.It Fl decrypt
8128Time decryption instead of encryption
8129.Pq only EVP .
8130.It Fl engine Ar id
8131Specifying an engine (by its unique
8132.Ar id
8133string) will cause
8134.Nm speed
8135to attempt to obtain a functional reference to the specified engine,
8136thus initialising it if needed.
8137The engine will then be set as the default for all available algorithms.
8138.It Fl elapsed
8139Measure time in real time instead of CPU user time.
8140.It Fl evp Ar e
8141Use EVP
8142.Ar e .
8143.It Fl mr
8144Produce machine readable output.
8145.It Fl multi Ar number
8146Run
8147.Ar number
8148benchmarks in parallel.
8149.El
8150.\"
8151.\" TS
8152.\"
8153.Sh TS
8154.nr nS 1
8155.Nm "openssl ts"
8156.Bk -words
8157.Fl query
8158.Op Fl md4 | md5 | ripemd160 | sha | sha1
8159.Op Fl cert
8160.Op Fl config Ar configfile
8161.Op Fl data Ar file_to_hash
8162.Op Fl digest Ar digest_bytes
8163.Op Fl in Ar request.tsq
8164.Op Fl no_nonce
8165.Op Fl out Ar request.tsq
8166.Op Fl policy Ar object_id
8167.Op Fl text
8168.Ek
8169.nr nS 0
8170.Pp
8171.nr nS 1
8172.Nm "openssl ts"
8173.Bk -words
8174.Fl reply
8175.Op Fl chain Ar certs_file.pem
8176.Op Fl config Ar configfile
8177.Op Fl engine Ar id
8178.Op Fl in Ar response.tsr
8179.Op Fl inkey Ar private.pem
8180.Op Fl out Ar response.tsr
8181.Op Fl passin Ar arg
8182.Op Fl policy Ar object_id
8183.Op Fl queryfile Ar request.tsq
8184.Op Fl section Ar tsa_section
8185.Op Fl signer Ar tsa_cert.pem
8186.Op Fl text
8187.Op Fl token_in
8188.Op Fl token_out
8189.Ek
8190.nr nS 0
8191.Pp
8192.nr nS 1
8193.Nm "openssl ts"
8194.Bk -words
8195.Fl verify
8196.Op Fl CAfile Ar trusted_certs.pem
8197.Op Fl CApath Ar trusted_cert_path
8198.Op Fl data Ar file_to_hash
8199.Op Fl digest Ar digest_bytes
8200.Op Fl in Ar response.tsr
8201.Op Fl queryfile Ar request.tsq
8202.Op Fl token_in
8203.Op Fl untrusted Ar cert_file.pem
8204.Ek
8205.nr nS 0
8206.Pp
8207The
8208.Nm ts
8209command is a basic Time Stamping Authority (TSA) client and server
8210application as specified in RFC 3161 (Time-Stamp Protocol, TSP).
8211A TSA can be part of a PKI deployment and its role is to provide long
8212term proof of the existence of a certain datum before a particular time.
8213Here is a brief description of the protocol:
8214.Bl -enum
8215.It
8216The TSA client computes a one-way hash value for a data file and sends
8217the hash to the TSA.
8218.It
8219The TSA attaches the current date and time to the received hash value,
8220signs them and sends the time stamp token back to the client.
8221By creating this token the TSA certifies the existence of the original
8222data file at the time of response generation.
8223.It
8224The TSA client receives the time stamp token and verifies the
8225signature on it.
8226It also checks if the token contains the same hash
8227value that it had sent to the TSA.
8228.El
8229.Pp
8230There is one DER-encoded protocol data unit defined for transporting a time
8231stamp request to the TSA and one for sending the time stamp response
8232back to the client.
8233The
8234.Nm ts
8235command has three main functions:
8236creating a time stamp request based on a data file;
8237creating a time stamp response based on a request;
8238and verifying if a response corresponds
8239to a particular request or a data file.
8240.Pp
8241There is no support for sending the requests/responses automatically
8242over HTTP or TCP yet as suggested in RFC 3161.
8243Users must send the requests either by FTP or email.
8244.Pp
8245The
8246.Fl query
8247switch can be used for creating and printing a time stamp
8248request with the following options:
8249.Bl -tag -width Ds
8250.It Fl cert
8251The TSA is expected to include its signing certificate in the
8252response.
8253.It Fl config Ar configfile
8254The configuration file to use.
8255This option overrides the
8256.Ev OPENSSL_CONF
8257environment variable.
8258Only the OID section of the config file is used with the
8259.Fl query
8260command.
8261.It Fl data Ar file_to_hash
8262The data file for which the time stamp request needs to be created.
8263stdin is the default if neither the
8264.Fl data
8265nor the
8266.Fl digest
8267option is specified.
8268.It Fl digest Ar digest_bytes
8269It is possible to specify the message imprint explicitly without the data
8270file.
8271The imprint must be specified in a hexadecimal format,
8272two characters per byte,
8273the bytes optionally separated by colons (e.g. 1A:F6:01:... or 1AF601...).
8274The number of bytes must match the message digest algorithm in use.
8275.It Fl in Ar request.tsq
8276This option specifies a previously created time stamp request in DER
8277format that will be printed into the output file.
8278Useful when you need to examine the content of a request in human-readable
8279format.
8280.It Fl md4|md5|ripemd160|sha|sha1
8281The message digest to apply to the data file.
8282It supports all the message digest algorithms that are supported by the
8283.Nm dgst
8284command.
8285The default is SHA-1.
8286.It Fl no_nonce
8287No nonce is specified in the request if this option is given.
8288Otherwise a 64-bit long pseudo-random none is
8289included in the request.
8290It is recommended to use nonce to protect against replay-attacks.
8291.It Fl out Ar request.tsq
8292Name of the output file to which the request will be written.
8293The default is stdout.
8294.It Fl policy Ar object_id
8295The policy that the client expects the TSA to use for creating the
8296time stamp token.
8297Either the dotted OID notation or OID names defined
8298in the config file can be used.
8299If no policy is requested the TSA will
8300use its own default policy.
8301.It Fl text
8302If this option is specified the output is in human-readable text format
8303instead of DER.
8304.El
8305.Pp
8306A time stamp response (TimeStampResp) consists of a response status
8307and the time stamp token itself (ContentInfo),
8308if the token generation was successful.
8309The
8310.Fl reply
8311command is for creating a time stamp
8312response or time stamp token based on a request and printing the
8313response/token in human-readable format.
8314If
8315.Fl token_out
8316is not specified the output is always a time stamp response (TimeStampResp),
8317otherwise it is a time stamp token (ContentInfo).
8318.Bl -tag -width Ds
8319.It Fl chain Ar certs_file.pem
8320The collection of certificates, in PEM format,
8321that will be included in the response
8322in addition to the signer certificate if the
8323.Fl cert
8324option was used for the request.
8325This file is supposed to contain the certificate chain
8326for the signer certificate from its issuer upwards.
8327The
8328.Fl reply
8329command does not build a certificate chain automatically.
8330.It Fl config Ar configfile
8331The configuration file to use.
8332This option overrides the
8333.Ev OPENSSL_CONF
8334environment variable.
8335See
8336.Sx TS CONFIGURATION FILE OPTIONS
8337for configurable variables.
8338.It Fl engine Ar id
8339Specifying an engine (by its unique
8340.Ar id
8341string) will cause
8342.Nm ts
8343to attempt to obtain a functional reference to the specified engine,
8344thus initialising it if needed.
8345The engine will then be set as the default for all available algorithms.
8346.It Fl in Ar response.tsr
8347Specifies a previously created time stamp response or time stamp token, if
8348.Fl token_in
8349is also specified,
8350in DER format that will be written to the output file.
8351This option does not require a request;
8352it is useful, for example,
8353when you need to examine the content of a response or token
8354or you want to extract the time stamp token from a response.
8355If the input is a token and the output is a time stamp response a default
8356.Dq granted
8357status info is added to the token.
8358.It Fl inkey Ar private.pem
8359The signer private key of the TSA in PEM format.
8360Overrides the
8361.Cm signer_key
8362config file option.
8363.It Fl out Ar response.tsr
8364The response is written to this file.
8365The format and content of the file depends on other options (see
8366.Fl text
8367and
8368.Fl token_out ) .
8369The default is stdout.
8370.It Fl passin Ar arg
8371The key password source.
8372For more information about the format of
8373.Ar arg ,
8374see the
8375.Sx PASS PHRASE ARGUMENTS
8376section above.
8377.It Fl policy Ar object_id
8378The default policy to use for the response unless the client
8379explicitly requires a particular TSA policy.
8380The OID can be specified either in dotted notation or with its name.
8381Overrides the
8382.Cm default_policy
8383config file option.
8384.It Fl queryfile Ar request.tsq
8385The name of the file containing a DER-encoded time stamp request.
8386.It Fl section Ar tsa_section
8387The name of the config file section containing the settings for the
8388response generation.
8389If not specified the default TSA section is used; see
8390.Sx TS CONFIGURATION FILE OPTIONS
8391for details.
8392.It Fl signer Ar tsa_cert.pem
8393The signer certificate of the TSA in PEM format.
8394The TSA signing certificate must have exactly one extended key usage
8395assigned to it: timeStamping.
8396The extended key usage must also be critical,
8397otherwise the certificate is going to be refused.
8398Overrides the
8399.Cm signer_cert
8400variable of the config file.
8401.It Fl text
8402If this option is specified the output is human-readable text format
8403instead of DER.
8404.It Fl token_in
8405This flag can be used together with the
8406.Fl in
8407option and indicates that the input is a DER-encoded time stamp token
8408(ContentInfo) instead of a time stamp response (TimeStampResp).
8409.It Fl token_out
8410The output is a time stamp token (ContentInfo) instead of time stamp
8411response (TimeStampResp).
8412.El
8413.Pp
8414The
8415.Fl verify
8416command is for verifying if a time stamp response or time stamp token
8417is valid and matches a particular time stamp request or data file.
8418The
8419.Fl verify
8420command does not use the configuration file.
8421.Bl -tag -width Ds
8422.It Fl CAfile Ar trusted_certs.pem
8423The name of the file containing a set of trusted self-signed CA
8424certificates in PEM format.
8425See the similar option of
8426.Nm verify
8427for additional details.
8428Either this option or
8429.Fl CApath
8430must be specified.
8431.It Fl CApath Ar trusted_cert_path
8432The name of the directory containing the trused CA certificates of the
8433client.
8434See the similar option of
8435.Nm verify
8436for additional details.
8437Either this option or
8438.Fl CAfile
8439must be specified.
8440.It Fl data Ar file_to_hash
8441The response or token must be verified against
8442.Ar file_to_hash .
8443The file is hashed with the message digest algorithm specified in the token.
8444The
8445.Fl digest
8446and
8447.Fl queryfile
8448options must not be specified with this one.
8449.It Fl digest Ar digest_bytes
8450The response or token must be verified against the message digest specified
8451with this option.
8452The number of bytes must match the message digest algorithm
8453specified in the token.
8454The
8455.Fl data
8456and
8457.Fl queryfile
8458options must not be specified with this one.
8459.It Fl in Ar response.tsr
8460The time stamp response that needs to be verified, in DER format.
8461This option in mandatory.
8462.It Fl queryfile Ar request.tsq
8463The original time stamp request, in DER format.
8464The
8465.Fl data
8466and
8467.Fl digest
8468options must not be specified with this one.
8469.It Fl token_in
8470This flag can be used together with the
8471.Fl in
8472option and indicates that the input is a DER-encoded time stamp token
8473(ContentInfo) instead of a time stamp response (TimeStampResp).
8474.It Fl untrusted Ar cert_file.pem
8475Set of additional untrusted certificates in PEM format which may be
8476needed when building the certificate chain for the TSA's signing
8477certificate.
8478This file must contain the TSA signing certificate and
8479all intermediate CA certificates unless the response includes them.
8480.El
8481.Sh TS CONFIGURATION FILE OPTIONS
8482The
8483.Fl query
8484and
8485.Fl reply
8486options make use of a configuration file defined by the
8487.Ev OPENSSL_CONF
8488environment variable.
8489The
8490.Fl query
8491option uses only the symbolic OID names section
8492and it can work without it.
8493However, the
8494.Fl reply
8495option needs the config file for its operation.
8496.Pp
8497When there is a command line switch equivalent of a variable the
8498switch always overrides the settings in the config file.
8499.Bl -tag -width Ds
8500.It Cm tsa Ar section , Cm default_tsa
8501This is the main section and it specifies the name of another section
8502that contains all the options for the
8503.Fl reply
8504option.
8505This default section can be overridden with the
8506.Fl section
8507command line switch.
8508.It Cm oid_file
8509See
8510.Nm ca
8511for a description.
8512.It Cm oid_section
8513See
8514.Nm ca
8515for a description.
8516.It Cm serial
8517The name of the file containing the hexadecimal serial number of the
8518last time stamp response created.
8519This number is incremented by 1 for each response.
8520If the file does not exist at the time of response
8521generation a new file is created with serial number 1.
8522This parameter is mandatory.
8523.It Cm crypto_device
8524Specifies the
8525.Nm OpenSSL
8526engine that will be set as the default for
8527all available algorithms.
8528.It Cm signer_cert
8529TSA signing certificate, in PEM format.
8530The same as the
8531.Fl signer
8532command line option.
8533.It Cm certs
8534A file containing a set of PEM-encoded certificates that need to be
8535included in the response.
8536The same as the
8537.Fl chain
8538command line option.
8539.It Cm signer_key
8540The private key of the TSA, in PEM format.
8541The same as the
8542.Fl inkey
8543command line option.
8544.It Cm default_policy
8545The default policy to use when the request does not mandate any policy.
8546The same as the
8547.Fl policy
8548command line option.
8549.It Cm other_policies
8550Comma separated list of policies that are also acceptable by the TSA
8551and used only if the request explicitly specifies one of them.
8552.It Cm digests
8553The list of message digest algorithms that the TSA accepts.
8554At least one algorithm must be specified.
8555This parameter is mandatory.
8556.It Cm accuracy
8557The accuracy of the time source of the TSA in seconds, milliseconds
8558and microseconds.
8559For example, secs:1, millisecs:500, microsecs:100.
8560If any of the components is missing,
8561zero is assumed for that field.
8562.It Cm clock_precision_digits
8563Specifies the maximum number of digits, which represent the fraction of
8564seconds, that need to be included in the time field.
8565The trailing zeroes must be removed from the time,
8566so there might actually be fewer digits,
8567or no fraction of seconds at all.
8568The maximum value is 6;
8569the default is 0.
8570.It Cm ordering
8571If this option is yes,
8572the responses generated by this TSA can always be ordered,
8573even if the time difference between two responses is less
8574than the sum of their accuracies.
8575The default is no.
8576.It Cm tsa_name
8577Set this option to yes if the subject name of the TSA must be included in
8578the TSA name field of the response.
8579The default is no.
8580.It Cm ess_cert_id_chain
8581The SignedData objects created by the TSA always contain the
8582certificate identifier of the signing certificate in a signed
8583attribute (see RFC 2634, Enhanced Security Services).
8584If this option is set to yes and either the
8585.Cm certs
8586variable or the
8587.Fl chain
8588option is specified then the certificate identifiers of the chain will also
8589be included in the SigningCertificate signed attribute.
8590If this variable is set to no,
8591only the signing certificate identifier is included.
8592The default is no.
8593.El
8594.Sh TS ENVIRONMENT VARIABLES
8595.Ev OPENSSL_CONF
8596contains the path of the configuration file and can be
8597overridden by the
8598.Fl config
8599command line option.
8600.Sh TS EXAMPLES
8601All the examples below presume that
8602.Ev OPENSSL_CONF
8603is set to a proper configuration file,
8604e.g. the example configuration file
8605.Pa openssl/apps/openssl.cnf
8606will do.
8607.Pp
8608To create a time stamp request for design1.txt with SHA-1
8609without nonce and policy and no certificate is required in the response:
8610.Bd -literal -offset indent
8611$ openssl ts -query -data design1.txt -no_nonce \e
8612 -out design1.tsq
8613.Ed
8614.Pp
8615To create a similar time stamp request but specifying the message imprint
8616explicitly:
8617.Bd -literal -offset indent
8618$ openssl ts -query \e
8619 -digest b7e5d3f93198b38379852f2c04e78d73abdd0f4b \e
8620 -no_nonce -out design1.tsq
8621.Ed
8622.Pp
8623To print the content of the previous request in human readable format:
8624.Bd -literal -offset indent
8625$ openssl ts -query -in design1.tsq -text
8626.Ed
8627.Pp
8628To create a time stamp request which includes the MD5 digest
8629of design2.txt, requests the signer certificate and nonce,
8630specifies a policy ID
8631(assuming the tsa_policy1 name is defined in the
8632OID section of the config file):
8633.Bd -literal -offset indent
8634$ openssl ts -query -data design2.txt -md5 \e
8635 -policy tsa_policy1 -cert -out design2.tsq
8636.Ed
8637.Pp
8638Before generating a response,
8639a signing certificate must be created for the TSA that contains the
8640.Cm timeStamping
8641critical extended key usage extension
8642without any other key usage extensions.
8643You can add the
8644.Dq extendedKeyUsage = critical,timeStamping
8645line to the user certificate section
8646of the config file to generate a proper certificate.
8647See the
8648.Nm req ,
8649.Nm ca ,
8650and
8651.Nm x509
8652commands for instructions.
8653The examples below assume that cacert.pem contains the certificate of the CA,
8654tsacert.pem is the signing certificate issued by cacert.pem and
8655tsakey.pem is the private key of the TSA.
8656.Pp
8657To create a time stamp response for a request:
8658.Bd -literal -offset indent
8659$ openssl ts -reply -queryfile design1.tsq -inkey tsakey.pem \e
8660 -signer tsacert.pem -out design1.tsr
8661.Ed
8662.Pp
8663If you want to use the settings in the config file you could just write:
8664.Bd -literal -offset indent
8665$ openssl ts -reply -queryfile design1.tsq -out design1.tsr
8666.Ed
8667.Pp
8668To print a time stamp reply to stdout in human readable format:
8669.Bd -literal -offset indent
8670$ openssl ts -reply -in design1.tsr -text
8671.Ed
8672.Pp
8673To create a time stamp token instead of time stamp response:
8674.Bd -literal -offset indent
8675$ openssl ts -reply -queryfile design1.tsq \e
8676 -out design1_token.der -token_out
8677.Ed
8678.Pp
8679To print a time stamp token to stdout in human readable format:
8680.Bd -literal -offset indent
8681$ openssl ts -reply -in design1_token.der -token_in \e
8682 -text -token_out
8683.Ed
8684.Pp
8685To extract the time stamp token from a response:
8686.Bd -literal -offset indent
8687$ openssl ts -reply -in design1.tsr -out design1_token.der \e
8688 -token_out
8689.Ed
8690.Pp
8691To add
8692.Dq granted
8693status info to a time stamp token thereby creating a valid response:
8694.Bd -literal -offset indent
8695$ openssl ts -reply -in design1_token.der \e
8696 -token_in -out design1.tsr
8697.Ed
8698.Pp
8699To verify a time stamp reply against a request:
8700.Bd -literal -offset indent
8701$ openssl ts -verify -queryfile design1.tsq -in design1.tsr \e
8702 -CAfile cacert.pem -untrusted tsacert.pem
8703.Ed
8704.Pp
8705To verify a time stamp reply that includes the certificate chain:
8706.Bd -literal -offset indent
8707$ openssl ts -verify -queryfile design2.tsq -in design2.tsr \e
8708 -CAfile cacert.pem
8709.Ed
8710.Pp
8711To verify a time stamp token against the original data file:
8712.Bd -literal -offset indent
8713$ openssl ts -verify -data design2.txt -in design2.tsr \e
8714 -CAfile cacert.pem
8715.Ed
8716.Pp
8717To verify a time stamp token against a message imprint:
8718.Bd -literal -offset indent
8719$ openssl ts -verify \e
8720 -digest b7e5d3f93198b38379852f2c04e78d73abdd0f4b \e
8721 -in design2.tsr -CAfile cacert.pem
8722.Ed
8723.Sh TS BUGS
8724No support for time stamps over SMTP, though it is quite easy
8725to implement an automatic email-based TSA with
8726.Xr procmail
8727and
8728.Xr perl 1 .
8729Pure TCP/IP is not supported.
8730.Pp
8731The file containing the last serial number of the TSA is not
8732locked when being read or written.
8733This is a problem if more than one instance of
8734.Nm OpenSSL
8735is trying to create a time stamp
8736response at the same time.
8737.Pp
8738Look for the FIXME word in the source files.
8739.Pp
8740The source code should really be reviewed by somebody else, too.
8741.Pp
8742More testing is needed.
8743.Sh TS AUTHORS
8744.An Zoltan Glozik Aq Mt zglozik@opentsa.org ,
8745OpenTSA project
8746.Pq Lk http://www.opentsa.org .
8747.\"
8748.\" SPKAC
8749.\"
8750.Sh SPKAC
8751.nr nS 1
8752.Nm "openssl spkac"
8753.Bk -words
8754.Op Fl challenge Ar string
8755.Op Fl engine Ar id
8756.Op Fl in Ar file
8757.Op Fl key Ar keyfile
8758.Op Fl noout
8759.Op Fl out Ar file
8760.Op Fl passin Ar arg
8761.Op Fl pubkey
8762.Op Fl spkac Ar spkacname
8763.Op Fl spksect Ar section
8764.Op Fl verify
8765.Ek
8766.nr nS 0
8767.Pp
8768The
8769.Nm spkac
8770command processes Netscape signed public key and challenge
8771.Pq SPKAC
8772files.
8773It can print out their contents, verify the signature,
8774and produce its own SPKACs from a supplied private key.
8775.Pp
8776The options are as follows:
8777.Bl -tag -width Ds
8778.It Fl challenge Ar string
8779Specifies the challenge string if an SPKAC is being created.
8780.It Fl engine Ar id
8781Specifying an engine (by its unique
8782.Ar id
8783string) will cause
8784.Nm spkac
8785to attempt to obtain a functional reference to the specified engine,
8786thus initialising it if needed.
8787The engine will then be set as the default for all available algorithms.
8788.It Fl in Ar file
8789This specifies the input
8790.Ar file
8791to read from, or standard input if this option is not specified.
8792Ignored if the
8793.Fl key
8794option is used.
8795.It Fl key Ar keyfile
8796Create an SPKAC file using the private key in
8797.Ar keyfile .
8798The
8799.Fl in , noout , spksect ,
8800and
8801.Fl verify
8802options are ignored if present.
8803.It Fl noout
8804Don't output the text version of the SPKAC
8805.Pq not used if an SPKAC is being created .
8806.It Fl out Ar file
8807Specifies the output
8808.Ar file
8809to write to, or standard output by default.
8810.It Fl passin Ar arg
8811The key password source.
8812For more information about the format of
8813.Ar arg ,
8814see the
8815.Sx PASS PHRASE ARGUMENTS
8816section above.
8817.It Fl pubkey
8818Output the public key of an SPKAC
8819.Pq not used if an SPKAC is being created .
8820.It Fl spkac Ar spkacname
8821Allows an alternative name for the variable containing the SPKAC.
8822The default is "SPKAC".
8823This option affects both generated and input SPKAC files.
8824.It Fl spksect Ar section
8825Allows an alternative name for the
8826.Ar section
8827containing the SPKAC.
8828The default is the default section.
8829.It Fl verify
8830Verifies the digital signature on the supplied SPKAC.
8831.El
8832.Sh SPKAC EXAMPLES
8833Print out the contents of an SPKAC:
8834.Pp
8835.Dl $ openssl spkac -in spkac.cnf
8836.Pp
8837Verify the signature of an SPKAC:
8838.Pp
8839.Dl $ openssl spkac -in spkac.cnf -noout -verify
8840.Pp
8841Create an SPKAC using the challenge string
8842.Qq hello :
8843.Pp
8844.Dl $ openssl spkac -key key.pem -challenge hello -out spkac.cnf
8845.Pp
8846Example of an SPKAC,
8847.Pq long lines split up for clarity :
8848.Bd -unfilled -offset indent
8849SPKAC=MIG5MGUwXDANBgkqhkiG9w0BAQEFAANLADBIAkEA1cCoq2Wa3Ixs47uI7F\e
8850PVwHVIPDx5yso105Y6zpozam135a8R0CpoRvkkigIyXfcCjiVi5oWk+6FfPaD03u\e
8851PFoQIDAQABFgVoZWxsbzANBgkqhkiG9w0BAQQFAANBAFpQtY/FojdwkJh1bEIYuc\e
88522EeM2KHTWPEepWYeawvHD0gQ3DngSC75YCWnnDdq+NQ3F+X4deMx9AaEglZtULwV\e
88534=
8854.Ed
8855.Sh SPKAC NOTES
8856A created SPKAC with suitable DN components appended can be fed into
8857the
8858.Nm ca
8859utility.
8860.Pp
8861SPKACs are typically generated by Netscape when a form is submitted
8862containing the
8863.Em KEYGEN
8864tag as part of the certificate enrollment process.
8865.Pp
8866The challenge string permits a primitive form of proof of possession
8867of private key.
8868By checking the SPKAC signature and a random challenge
8869string, some guarantee is given that the user knows the private key
8870corresponding to the public key being certified.
8871This is important in some applications.
8872Without this it is possible for a previous SPKAC
8873to be used in a
8874.Qq replay attack .
8875.\"
8876.\" VERIFY
8877.\"
8878.Sh VERIFY
8879.nr nS 1
8880.Nm "openssl verify"
8881.Bk -words
8882.Op Fl CAfile Ar file
8883.Op Fl CApath Ar directory
8884.Op Fl check_ss_sig
8885.Op Fl crl_check
8886.Op Fl crl_check_all
8887.Op Fl engine Ar id
8888.Op Fl explicit_policy
8889.Op Fl extended_crl
8890.Op Fl help
8891.Op Fl ignore_critical
8892.Op Fl inhibit_any
8893.Op Fl inhibit_map
8894.Op Fl issuer_checks
8895.Op Fl policy_check
8896.Op Fl purpose Ar purpose
8897.Op Fl untrusted Ar file
8898.Op Fl verbose
8899.Op Fl x509_strict
8900.Op Fl
8901.Op Ar certificates
8902.Ek
8903.nr nS 0
8904.Pp
8905The
8906.Nm verify
8907command verifies certificate chains.
8908.Pp
8909The options are as follows:
8910.Bl -tag -width Ds
8911.It Fl check_ss_sig
8912Verify the signature on the self-signed root CA.
8913This is disabled by default
8914because it doesn't add any security.
8915.It Fl CAfile Ar file
8916A
8917.Ar file
8918of trusted certificates.
8919The
8920.Ar file
8921should contain multiple certificates in PEM format, concatenated together.
8922.It Fl CApath Ar directory
8923A
8924.Ar directory
8925of trusted certificates.
8926The certificates should have names of the form
8927.Em hash.0 ,
8928or have symbolic links to them of this form
8929("hash" is the hashed certificate subject name: see the
8930.Fl hash
8931option of the
8932.Nm x509
8933utility).
8934The
8935.Nm c_rehash
8936script distributed with OpenSSL
8937will automatically create symbolic links to a directory of certificates.
8938.It Fl crl_check
8939Checks end entity certificate validity by attempting to look up a valid CRL.
8940If a valid CRL cannot be found an error occurs.
8941.It Fl crl_check_all
8942Checks the validity of all certificates in the chain by attempting
8943to look up valid CRLs.
8944.It Fl engine Ar id
8945Specifying an engine (by its unique
8946.Ar id
8947string) will cause
8948.Nm verify
8949to attempt to obtain a functional reference to the specified engine,
8950thus initialising it if needed.
8951The engine will then be set as the default for all available algorithms.
8952.It Fl explicit_policy
8953Set policy variable require-explicit-policy (see RFC 3280 et al).
8954.It Fl extended_crl
8955Enable extended CRL features such as indirect CRLs and alternate CRL
8956signing keys.
8957.It Fl help
8958Prints out a usage message.
8959.It Fl ignore_critical
8960Normally if an unhandled critical extension is present which is not
8961supported by
8962.Nm OpenSSL ,
8963the certificate is rejected (as required by RFC 3280 et al).
8964If this option is set, critical extensions are ignored.
8965.It Fl inhibit_any
8966Set policy variable inhibit-any-policy (see RFC 3280 et al).
8967.It Fl inhibit_map
8968Set policy variable inhibit-policy-mapping (see RFC 3280 et al).
8969.It Fl issuer_checks
8970Print out diagnostics relating to searches for the issuer certificate
8971of the current certificate.
8972This shows why each candidate issuer certificate was rejected.
8973However the presence of rejection messages
8974does not itself imply that anything is wrong: during the normal
8975verify process several rejections may take place.
8976.It Fl policy_check
8977Enables certificate policy processing.
8978.It Fl purpose Ar purpose
8979The intended use for the certificate.
8980Without this option no chain verification will be done.
8981Currently accepted uses are
8982.Ar sslclient , sslserver ,
8983.Ar nssslserver , smimesign ,
8984.Ar smimeencrypt , crlsign ,
8985.Ar any ,
8986and
8987.Ar ocsphelper .
8988See the
8989.Sx VERIFY OPERATION
8990section for more information.
8991.It Fl untrusted Ar file
8992A
8993.Ar file
8994of untrusted certificates.
8995The
8996.Ar file
8997should contain multiple certificates.
8998.It Fl verbose
8999Print extra information about the operations being performed.
9000.It Fl x509_strict
9001Disable workarounds for broken certificates which have to be disabled
9002for strict X.509 compliance.
9003.It Fl
9004Marks the last option.
9005All arguments following this are assumed to be certificate files.
9006This is useful if the first certificate filename begins with a
9007.Sq - .
9008.It Ar certificates
9009One or more
9010.Ar certificates
9011to verify.
9012If no certificate files are included, an attempt is made to read
9013a certificate from standard input.
9014They should all be in PEM format.
9015.El
9016.Sh VERIFY OPERATION
9017The
9018.Nm verify
9019program uses the same functions as the internal SSL and S/MIME verification,
9020therefore this description applies to these verify operations too.
9021.Pp
9022There is one crucial difference between the verify operations performed
9023by the
9024.Nm verify
9025program: wherever possible an attempt is made to continue
9026after an error, whereas normally the verify operation would halt on the
9027first error.
9028This allows all the problems with a certificate chain to be determined.
9029.Pp
9030The verify operation consists of a number of separate steps:
9031.Pp
9032Firstly a certificate chain is built up starting from the supplied certificate
9033and ending in the root CA.
9034It is an error if the whole chain cannot be built up.
9035The chain is built up by looking up the issuer's certificate of the current
9036certificate.
9037If a certificate is found which is its own issuer, it is assumed
9038to be the root CA.
9039.Pp
9040The process of
9041.Qq looking up the issuer's certificate
9042itself involves a number of steps.
9043In versions of
9044.Nm OpenSSL
9045before 0.9.5a the first certificate whose subject name matched the issuer
9046of the current certificate was assumed to be the issuer's certificate.
9047In
9048.Nm OpenSSL
90490.9.6 and later all certificates whose subject name matches the issuer name
9050of the current certificate are subject to further tests.
9051The relevant authority key identifier components of the current certificate
9052.Pq if present
9053must match the subject key identifier
9054.Pq if present
9055and issuer and serial number of the candidate issuer; in addition the
9056.Em keyUsage
9057extension of the candidate issuer
9058.Pq if present
9059must permit certificate signing.
9060.Pp
9061The lookup first looks in the list of untrusted certificates and if no match
9062is found the remaining lookups are from the trusted certificates.
9063The root CA is always looked up in the trusted certificate list: if the
9064certificate to verify is a root certificate, then an exact match must be
9065found in the trusted list.
9066.Pp
9067The second operation is to check every untrusted certificate's extensions for
9068consistency with the supplied purpose.
9069If the
9070.Fl purpose
9071option is not included, then no checks are done.
9072The supplied or
9073.Qq leaf
9074certificate must have extensions compatible with the supplied purpose
9075and all other certificates must also be valid CA certificates.
9076The precise extensions required are described in more detail in
9077the
9078.Sx X.509 CERTIFICATE EXTENSIONS
9079section below.
9080.Pp
9081The third operation is to check the trust settings on the root CA.
9082The root CA should be trusted for the supplied purpose.
9083For compatibility with previous versions of
9084.Nm SSLeay
9085and
9086.Nm OpenSSL ,
9087a certificate with no trust settings is considered to be valid for
9088all purposes.
9089.Pp
9090The final operation is to check the validity of the certificate chain.
9091The validity period is checked against the current system time and the
9092.Em notBefore
9093and
9094.Em notAfter
9095dates in the certificate.
9096The certificate signatures are also checked at this point.
9097.Pp
9098If all operations complete successfully, the certificate is considered
9099valid.
9100If any operation fails then the certificate is not valid.
9101.Sh VERIFY DIAGNOSTICS
9102When a verify operation fails, the output messages can be somewhat cryptic.
9103The general form of the error message is:
9104.Bd -unfilled
9105\& server.pem: /C=AU/ST=Queensland/O=CryptSoft Pty Ltd/CN=Test CA (1024-bit)
9106\& error 24 at 1 depth lookup:invalid CA certificate
9107.Ed
9108.Pp
9109The first line contains the name of the certificate being verified, followed by
9110the subject name of the certificate.
9111The second line contains the error number and the depth.
9112The depth is the number of the certificate being verified when a
9113problem was detected starting with zero for the certificate being verified
9114itself, then 1 for the CA that signed the certificate and so on.
9115Finally a text version of the error number is presented.
9116.Pp
9117An exhaustive list of the error codes and messages is shown below; this also
9118includes the name of the error code as defined in the header file
9119.Aq Pa openssl/x509_vfy.h .
9120Some of the error codes are defined but never returned: these are described
9121as
9122.Qq unused .
9123.Bl -tag -width "XXXX"
9124.It Ar "0 X509_V_OK: ok"
9125The operation was successful.
9126.It Ar 2 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: unable to get issuer certificate
9127The issuer certificate could not be found: this occurs if the issuer certificate
9128of an untrusted certificate cannot be found.
9129.It Ar 3 X509_V_ERR_UNABLE_TO_GET_CRL: unable to get certificate CRL
9130The CRL of a certificate could not be found.
9131.It Ar 4 X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE: unable to decrypt certificate's signature
9132The certificate signature could not be decrypted.
9133This means that the actual signature value could not be determined rather
9134than it not matching the expected value.
9135This is only meaningful for RSA keys.
9136.It Ar 5 X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: unable to decrypt CRL's signature
9137The CRL signature could not be decrypted: this means that the actual
9138signature value could not be determined rather than it not matching the
9139expected value.
9140Unused.
9141.It Ar 6 X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: unable to decode issuer public key
9142The public key in the certificate
9143.Em SubjectPublicKeyInfo
9144could not be read.
9145.It Ar 7 X509_V_ERR_CERT_SIGNATURE_FAILURE: certificate signature failure
9146The signature of the certificate is invalid.
9147.It Ar 8 X509_V_ERR_CRL_SIGNATURE_FAILURE: CRL signature failure
9148The signature of the certificate is invalid.
9149.It Ar 9 X509_V_ERR_CERT_NOT_YET_VALID: certificate is not yet valid
9150The certificate is not yet valid: the
9151.Em notBefore
9152date is after the current time.
9153.It Ar 10 X509_V_ERR_CERT_HAS_EXPIRED: certificate has expired
9154The certificate has expired; that is, the
9155.Em notAfter
9156date is before the current time.
9157.It Ar 11 X509_V_ERR_CRL_NOT_YET_VALID: CRL is not yet valid
9158The CRL is not yet valid.
9159.It Ar 12 X509_V_ERR_CRL_HAS_EXPIRED: CRL has expired
9160The CRL has expired.
9161.It Ar 13 X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: format error in certificate's notBefore field
9162The certificate
9163.Em notBefore
9164field contains an invalid time.
9165.It Ar 14 X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: format error in certificate's notAfter field
9166The certificate
9167.Em notAfter
9168field contains an invalid time.
9169.It Ar 15 X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: format error in CRL's lastUpdate field
9170The CRL
9171.Em lastUpdate
9172field contains an invalid time.
9173.It Ar 16 X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: format error in CRL's nextUpdate field
9174The CRL
9175.Em nextUpdate
9176field contains an invalid time.
9177.It Ar 17 X509_V_ERR_OUT_OF_MEM: out of memory
9178An error occurred trying to allocate memory.
9179This should never happen.
9180.It Ar 18 X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: self signed certificate
9181The passed certificate is self-signed and the same certificate cannot be
9182found in the list of trusted certificates.
9183.It Ar 19 X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: self signed certificate in certificate chain
9184The certificate chain could be built up using the untrusted certificates but
9185the root could not be found locally.
9186.It Ar 20 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: unable to get local issuer certificate
9187The issuer certificate of a locally looked up certificate could not be found.
9188This normally means the list of trusted certificates is not complete.
9189.It Ar 21 X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: unable to verify the first certificate
9190No signatures could be verified because the chain contains only one
9191certificate and it is not self-signed.
9192.It Ar 22 X509_V_ERR_CERT_CHAIN_TOO_LONG: certificate chain too long
9193The certificate chain length is greater than the supplied maximum depth.
9194Unused.
9195.It Ar 23 X509_V_ERR_CERT_REVOKED: certificate revoked
9196The certificate has been revoked.
9197.It Ar 24 X509_V_ERR_INVALID_CA: invalid CA certificate
9198A CA certificate is invalid.
9199Either it is not a CA or its extensions are not consistent
9200with the supplied purpose.
9201.It Ar 25 X509_V_ERR_PATH_LENGTH_EXCEEDED: path length constraint exceeded
9202The
9203.Em basicConstraints
9204pathlength parameter has been exceeded.
9205.It Ar 26 X509_V_ERR_INVALID_PURPOSE: unsupported certificate purpose
9206The supplied certificate cannot be used for the specified purpose.
9207.It Ar 27 X509_V_ERR_CERT_UNTRUSTED: certificate not trusted
9208The root CA is not marked as trusted for the specified purpose.
9209.It Ar 28 X509_V_ERR_CERT_REJECTED: certificate rejected
9210The root CA is marked to reject the specified purpose.
9211.It Ar 29 X509_V_ERR_SUBJECT_ISSUER_MISMATCH: subject issuer mismatch
9212The current candidate issuer certificate was rejected because its subject name
9213did not match the issuer name of the current certificate.
9214Only displayed when the
9215.Fl issuer_checks
9216option is set.
9217.It Ar 30 X509_V_ERR_AKID_SKID_MISMATCH: authority and subject key identifier mismatch
9218The current candidate issuer certificate was rejected because its subject key
9219identifier was present and did not match the authority key identifier current
9220certificate.
9221Only displayed when the
9222.Fl issuer_checks
9223option is set.
9224.It Ar 31 X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH: authority and issuer serial number mismatch
9225The current candidate issuer certificate was rejected because its issuer name
9226and serial number were present and did not match the authority key identifier
9227of the current certificate.
9228Only displayed when the
9229.Fl issuer_checks
9230option is set.
9231.It Ar 32 X509_V_ERR_KEYUSAGE_NO_CERTSIGN:key usage does not include certificate signing
9232The current candidate issuer certificate was rejected because its
9233.Em keyUsage
9234extension does not permit certificate signing.
9235.It Ar 50 X509_V_ERR_APPLICATION_VERIFICATION: application verification failure
9236An application specific error.
9237Unused.
9238.El
9239.Sh VERIFY BUGS
9240Although the issuer checks are a considerable improvement over the old
9241technique, they still suffer from limitations in the underlying
9242X509_LOOKUP API.
9243One consequence of this is that trusted certificates with matching subject
9244name must either appear in a file (as specified by the
9245.Fl CAfile
9246option) or a directory (as specified by
9247.Fl CApath ) .
9248If they occur in both, only the certificates in the file will
9249be recognised.
9250.Pp
9251Previous versions of
9252.Nm OpenSSL
9253assumed certificates with matching subject name were identical and
9254mishandled them.
9255.\"
9256.\" VERSION
9257.\"
9258.Sh VERSION
9259.Nm openssl version
9260.Op Fl abdfopv
9261.Pp
9262The
9263.Nm version
9264command is used to print out version information about
9265.Nm OpenSSL .
9266.Pp
9267The options are as follows:
9268.Bl -tag -width Ds
9269.It Fl a
9270All information: this is the same as setting all the other flags.
9271.It Fl b
9272The date the current version of
9273.Nm OpenSSL
9274was built.
9275.It Fl d
9276.Ev OPENSSLDIR
9277setting.
9278.It Fl f
9279Compilation flags.
9280.It Fl o
9281Option information: various options set when the library was built.
9282.It Fl p
9283Platform setting.
9284.It Fl v
9285The current
9286.Nm OpenSSL
9287version.
9288.El
9289.Sh VERSION NOTES
9290The output of
9291.Nm openssl version -a
9292would typically be used when sending in a bug report.
9293.Sh VERSION HISTORY
9294The
9295.Fl d
9296option was added in
9297.Nm OpenSSL
92980.9.7.
9299.\"
9300.\" X509
9301.\"
9302.Sh X509
9303.nr nS 1
9304.Nm "openssl x509"
9305.Bk -words
9306.Op Fl C
9307.Op Fl addreject Ar arg
9308.Op Fl addtrust Ar arg
9309.Op Fl alias
9310.Op Fl CA Ar file
9311.Op Fl CAcreateserial
9312.Op Fl CAform Ar DER | PEM
9313.Op Fl CAkey Ar file
9314.Op Fl CAkeyform Ar DER | PEM
9315.Op Fl CAserial Ar file
9316.Op Fl certopt Ar option
9317.Op Fl checkend Ar arg
9318.Op Fl clrext
9319.Op Fl clrreject
9320.Op Fl clrtrust
9321.Op Fl dates
9322.Op Fl days Ar arg
9323.Op Fl email
9324.Op Fl enddate
9325.Op Fl engine Ar id
9326.Op Fl extensions Ar section
9327.Op Fl extfile Ar file
9328.Op Fl fingerprint
9329.Op Fl hash
9330.Op Fl in Ar file
9331.Op Fl inform Ar DER | NET | PEM
9332.Op Fl issuer
9333.Op Fl issuer_hash
9334.Op Fl issuer_hash_old
9335.Op Fl keyform Ar DER | PEM
9336.Op Fl md2 | md5 | sha1
9337.Op Fl modulus
9338.Op Fl nameopt Ar option
9339.Op Fl noout
9340.Op Fl ocsp_uri
9341.Op Fl ocspid
9342.Op Fl out Ar file
9343.Op Fl outform Ar DER | NET | PEM
9344.Op Fl passin Ar arg
9345.Op Fl pubkey
9346.Op Fl purpose
9347.Op Fl req
9348.Op Fl serial
9349.Op Fl set_serial Ar n
9350.Op Fl setalias Ar arg
9351.Op Fl signkey Ar file
9352.Op Fl startdate
9353.Op Fl subject
9354.Op Fl subject_hash
9355.Op Fl subject_hash_old
9356.Op Fl text
9357.Op Fl trustout
9358.Op Fl x509toreq
9359.Ek
9360.nr nS 0
9361.Pp
9362The
9363.Nm x509
9364command is a multi-purpose certificate utility.
9365It can be used to display certificate information, convert certificates to
9366various forms, sign certificate requests like a
9367.Qq mini CA ,
9368or edit certificate trust settings.
9369.Pp
9370Since there are a large number of options, they are split up into
9371various sections.
9372.Sh X509 INPUT, OUTPUT, AND GENERAL PURPOSE OPTIONS
9373.Bl -tag -width "XXXX"
9374.It Fl engine Ar id
9375Specifying an engine (by its unique
9376.Ar id
9377string) will cause
9378.Nm x509
9379to attempt to obtain a functional reference to the specified engine,
9380thus initialising it if needed.
9381The engine will then be set as the default for all available algorithms.
9382.It Fl in Ar file
9383This specifies the input
9384.Ar file
9385to read a certificate from, or standard input if this option is not specified.
9386.It Fl inform Ar DER | NET | PEM
9387This specifies the input format.
9388Normally, the command will expect an X.509 certificate,
9389but this can change if other options such as
9390.Fl req
9391are present.
9392The
9393.Ar DER
9394format is the DER encoding of the certificate and
9395.Ar PEM
9396is the base64 encoding of the DER encoding with header and footer lines added.
9397The
9398.Ar NET
9399option is an obscure Netscape server format that is now
9400obsolete.
9401.It Fl md2 | md5 | sha1
9402The digest to use.
9403This affects any signing or display option that uses a message digest,
9404such as the
9405.Fl fingerprint , signkey ,
9406and
9407.Fl CA
9408options.
9409If not specified, MD5 is used.
9410If the key being used to sign with is a DSA key,
9411this option has no effect: SHA1 is always used with DSA keys.
9412.It Fl out Ar file
9413This specifies the output
9414.Ar file
9415to write to, or standard output by default.
9416.It Fl outform Ar DER | NET | PEM
9417This specifies the output format; the options have the same meaning as the
9418.Fl inform
9419option.
9420.It Fl passin Ar arg
9421The key password source.
9422For more information about the format of
9423.Ar arg ,
9424see the
9425.Sx PASS PHRASE ARGUMENTS
9426section above.
9427.El
9428.Sh X509 DISPLAY OPTIONS
9429.Sy Note :
9430The
9431.Fl alias
9432and
9433.Fl purpose
9434options are also display options but are described in the
9435.Sx X509 TRUST SETTINGS
9436section.
9437.Bl -tag -width "XXXX"
9438.It Fl C
9439This outputs the certificate in the form of a C source file.
9440.It Fl certopt Ar option
9441Customise the output format used with
9442.Fl text .
9443The
9444.Ar option
9445argument can be a single option or multiple options separated by commas.
9446The
9447.Fl certopt
9448switch may also be used more than once to set multiple options.
9449See the
9450.Sx X509 TEXT OPTIONS
9451section for more information.
9452.It Fl dates
9453Prints out the start and expiry dates of a certificate.
9454.It Fl email
9455Outputs the email address(es), if any.
9456.It Fl enddate
9457Prints out the expiry date of the certificate; that is, the
9458.Em notAfter
9459date.
9460.It Fl fingerprint
9461Prints out the digest of the DER-encoded version of the whole certificate
9462(see
9463.Sx DIGEST OPTIONS ) .
9464.It Fl hash
9465A synonym for
9466.Fl subject_hash ,
9467for backwards compatibility.
9468.It Fl issuer
9469Outputs the issuer name.
9470.It Fl issuer_hash
9471Outputs the
9472.Qq hash
9473of the certificate issuer name.
9474.It Fl issuer_hash_old
9475Outputs the
9476.Qq hash
9477of the certificate issuer name using the older algorithm
9478as used by
9479.Nm OpenSSL
9480versions before 1.0.0.
9481.It Fl modulus
9482This option prints out the value of the modulus of the public key
9483contained in the certificate.
9484.It Fl nameopt Ar option
9485Option which determines how the subject or issuer names are displayed.
9486The
9487.Ar option
9488argument can be a single option or multiple options separated by commas.
9489Alternatively, the
9490.Fl nameopt
9491switch may be used more than once to set multiple options.
9492See the
9493.Sx X509 NAME OPTIONS
9494section for more information.
9495.It Fl noout
9496This option prevents output of the encoded version of the request.
9497.It Fl ocsp_uri
9498Outputs the OCSP responder addresses, if any.
9499.It Fl ocspid
9500Print OCSP hash values for the subject name and public key.
9501.It Fl pubkey
9502Output the public key.
9503.It Fl serial
9504Outputs the certificate serial number.
9505.It Fl startdate
9506Prints out the start date of the certificate; that is, the
9507.Em notBefore
9508date.
9509.It Fl subject
9510Outputs the subject name.
9511.It Fl subject_hash
9512Outputs the
9513.Qq hash
9514of the certificate subject name.
9515This is used in
9516.Nm OpenSSL
9517to form an index to allow certificates in a directory to be looked up
9518by subject name.
9519.It Fl subject_hash_old
9520Outputs the
9521.Qq hash
9522of the certificate subject name using the older algorithm
9523as used by
9524.Nm OpenSSL
9525versions before 1.0.0.
9526.It Fl text
9527Prints out the certificate in text form.
9528Full details are output including the public key, signature algorithms,
9529issuer and subject names, serial number, any extensions present,
9530and any trust settings.
9531.El
9532.Sh X509 TRUST SETTINGS
9533Please note these options are currently experimental and may well change.
9534.Pp
9535A
9536.Em trusted certificate
9537is an ordinary certificate which has several
9538additional pieces of information attached to it such as the permitted
9539and prohibited uses of the certificate and an
9540.Qq alias .
9541.Pp
9542Normally, when a certificate is being verified at least one certificate
9543must be
9544.Qq trusted .
9545By default, a trusted certificate must be stored
9546locally and must be a root CA: any certificate chain ending in this CA
9547is then usable for any purpose.
9548.Pp
9549Trust settings currently are only used with a root CA.
9550They allow a finer control over the purposes the root CA can be used for.
9551For example, a CA may be trusted for an SSL client but not for
9552SSL server use.
9553.Pp
9554See the description of the
9555.Nm verify
9556utility for more information on the meaning of trust settings.
9557.Pp
9558Future versions of
9559.Nm OpenSSL
9560will recognize trust settings on any certificate: not just root CAs.
9561.Bl -tag -width "XXXX"
9562.It Fl addreject Ar arg
9563Adds a prohibited use.
9564It accepts the same values as the
9565.Fl addtrust
9566option.
9567.It Fl addtrust Ar arg
9568Adds a trusted certificate use.
9569Any object name can be used here, but currently only
9570.Ar clientAuth
9571.Pq SSL client use ,
9572.Ar serverAuth
9573.Pq SSL server use ,
9574and
9575.Ar emailProtection
9576.Pq S/MIME email
9577are used.
9578Other
9579.Nm OpenSSL
9580applications may define additional uses.
9581.It Fl alias
9582Outputs the certificate alias, if any.
9583.It Fl clrreject
9584Clears all the prohibited or rejected uses of the certificate.
9585.It Fl clrtrust
9586Clears all the permitted or trusted uses of the certificate.
9587.It Fl purpose
9588This option performs tests on the certificate extensions and outputs
9589the results.
9590For a more complete description, see the
9591.Sx X.509 CERTIFICATE EXTENSIONS
9592section.
9593.It Fl setalias Ar arg
9594Sets the alias of the certificate.
9595This will allow the certificate to be referred to using a nickname,
9596for example
9597.Qq Steve's Certificate .
9598.It Fl trustout
9599This causes
9600.Nm x509
9601to output a
9602.Em trusted certificate .
9603An ordinary or trusted certificate can be input, but by default an ordinary
9604certificate is output and any trust settings are discarded.
9605With the
9606.Fl trustout
9607option a trusted certificate is output.
9608A trusted certificate is automatically output if any trust settings
9609are modified.
9610.El
9611.Sh X509 SIGNING OPTIONS
9612The
9613.Nm x509
9614utility can be used to sign certificates and requests: it
9615can thus behave like a
9616.Qq mini CA .
9617.Bl -tag -width "XXXX"
9618.It Fl CA Ar file
9619Specifies the CA certificate to be used for signing.
9620When this option is present,
9621.Nm x509
9622behaves like a
9623.Qq mini CA .
9624The input file is signed by the CA using this option;
9625that is, its issuer name is set to the subject name of the CA and it is
9626digitally signed using the CA's private key.
9627.Pp
9628This option is normally combined with the
9629.Fl req
9630option.
9631Without the
9632.Fl req
9633option, the input is a certificate which must be self-signed.
9634.It Fl CAcreateserial
9635With this option the CA serial number file is created if it does not exist:
9636it will contain the serial number
9637.Sq 02
9638and the certificate being signed will have
9639.Sq 1
9640as its serial number.
9641Normally, if the
9642.Fl CA
9643option is specified and the serial number file does not exist, it is an error.
9644.It Fl CAform Ar DER | PEM
9645The format of the CA certificate file.
9646The default is
9647.Ar PEM .
9648.It Fl CAkey Ar file
9649Sets the CA private key to sign a certificate with.
9650If this option is not specified, it is assumed that the CA private key
9651is present in the CA certificate file.
9652.It Fl CAkeyform Ar DER | PEM
9653The format of the CA private key.
9654The default is
9655.Ar PEM .
9656.It Fl CAserial Ar file
9657Sets the CA serial number file to use.
9658.Pp
9659When the
9660.Fl CA
9661option is used to sign a certificate,
9662it uses a serial number specified in a file.
9663This file consists of one line containing an even number of hex digits
9664with the serial number to use.
9665After each use the serial number is incremented and written out
9666to the file again.
9667.Pp
9668The default filename consists of the CA certificate file base name with
9669.Pa .srl
9670appended.
9671For example, if the CA certificate file is called
9672.Pa mycacert.pem ,
9673it expects to find a serial number file called
9674.Pa mycacert.srl .
9675.It Fl checkend Ar arg
9676Check whether the certificate expires in the next
9677.Ar arg
9678seconds.
9679If so, exit with return value 1;
9680otherwise exit with return value 0.
9681.It Fl clrext
9682Delete any extensions from a certificate.
9683This option is used when a certificate is being created from another
9684certificate (for example with the
9685.Fl signkey
9686or the
9687.Fl CA
9688options).
9689Normally, all extensions are retained.
9690.It Fl days Ar arg
9691Specifies the number of days to make a certificate valid for.
9692The default is 30 days.
9693.It Fl extensions Ar section
9694The section to add certificate extensions from.
9695If this option is not specified, the extensions should either be
9696contained in the unnamed
9697.Pq default
9698section or the default section should contain a variable called
9699.Qq extensions
9700which contains the section to use.
9701.It Fl extfile Ar file
9702File containing certificate extensions to use.
9703If not specified, no extensions are added to the certificate.
9704.It Fl keyform Ar DER | PEM
9705Specifies the format
9706.Pq DER or PEM
9707of the private key file used in the
9708.Fl signkey
9709option.
9710.It Fl req
9711By default, a certificate is expected on input.
9712With this option a certificate request is expected instead.
9713.It Fl set_serial Ar n
9714Specifies the serial number to use.
9715This option can be used with either the
9716.Fl signkey
9717or
9718.Fl CA
9719options.
9720If used in conjunction with the
9721.Fl CA
9722option, the serial number file (as specified by the
9723.Fl CAserial
9724or
9725.Fl CAcreateserial
9726options) is not used.
9727.Pp
9728The serial number can be decimal or hex (if preceded by
9729.Sq 0x ) .
9730Negative serial numbers can also be specified but their use is not recommended.
9731.It Fl signkey Ar file
9732This option causes the input file to be self-signed using the supplied
9733private key.
9734.Pp
9735If the input file is a certificate, it sets the issuer name to the
9736subject name
9737.Pq i.e. makes it self-signed ,
9738changes the public key to the supplied value,
9739and changes the start and end dates.
9740The start date is set to the current time and the end date is set to
9741a value determined by the
9742.Fl days
9743option.
9744Any certificate extensions are retained unless the
9745.Fl clrext
9746option is supplied.
9747.Pp
9748If the input is a certificate request, a self-signed certificate
9749is created using the supplied private key using the subject name in
9750the request.
9751.It Fl x509toreq
9752Converts a certificate into a certificate request.
9753The
9754.Fl signkey
9755option is used to pass the required private key.
9756.El
9757.Sh X509 NAME OPTIONS
9758The
9759.Fl nameopt
9760command line switch determines how the subject and issuer
9761names are displayed.
9762If no
9763.Fl nameopt
9764switch is present, the default
9765.Qq oneline
9766format is used which is compatible with previous versions of
9767.Nm OpenSSL .
9768Each option is described in detail below; all options can be preceded by a
9769.Sq -
9770to turn the option off.
9771Only
9772.Ar compat ,
9773.Ar RFC2253 ,
9774.Ar oneline ,
9775and
9776.Ar multiline
9777will normally be used.
9778.Bl -tag -width "XXXX"
9779.It Ar align
9780Align field values for a more readable output.
9781Only usable with
9782.Ar sep_multiline .
9783.It Ar compat
9784Use the old format.
9785This is equivalent to specifying no name options at all.
9786.It Ar dn_rev
9787Reverse the fields of the DN.
9788This is required by RFC 2253.
9789As a side effect, this also reverses the order of multiple AVAs but this is
9790permissible.
9791.It Ar dump_all
9792Dump all fields.
9793This option, when used with
9794.Ar dump_der ,
9795allows the DER encoding of the structure to be unambiguously determined.
9796.It Ar dump_der
9797When this option is set, any fields that need to be hexdumped will
9798be dumped using the DER encoding of the field.
9799Otherwise just the content octets will be displayed.
9800Both options use the RFC 2253 #XXXX... format.
9801.It Ar dump_nostr
9802Dump non-character string types
9803.Pq for example OCTET STRING ;
9804if this option is not set, non-character string types will be displayed
9805as though each content octet represents a single character.
9806.It Ar dump_unknown
9807Dump any field whose OID is not recognised by
9808.Nm OpenSSL .
9809.It Ar esc_2253
9810Escape the
9811.Qq special
9812characters required by RFC 2253 in a field that is
9813.Dq \& ,+"\*(Lt\*(Gt; .
9814Additionally,
9815.Sq #
9816is escaped at the beginning of a string
9817and a space character at the beginning or end of a string.
9818.It Ar esc_ctrl
9819Escape control characters.
9820That is, those with ASCII values less than 0x20
9821.Pq space
9822and the delete
9823.Pq 0x7f
9824character.
9825They are escaped using the RFC 2253 \eXX notation (where XX are two hex
9826digits representing the character value).
9827.It Ar esc_msb
9828Escape characters with the MSB set; that is, with ASCII values larger than
9829127.
9830.It Ar multiline
9831A multiline format.
9832It is equivalent to
9833.Ar esc_ctrl , esc_msb , sep_multiline ,
9834.Ar space_eq , lname ,
9835and
9836.Ar align .
9837.It Ar no_type
9838This option does not attempt to interpret multibyte characters in any
9839way.
9840That is, their content octets are merely dumped as though one octet
9841represents each character.
9842This is useful for diagnostic purposes but will result in rather odd
9843looking output.
9844.It Ar nofname , sname , lname , oid
9845These options alter how the field name is displayed.
9846.Ar nofname
9847does not display the field at all.
9848.Ar sname
9849uses the
9850.Qq short name
9851form (CN for
9852.Ar commonName ,
9853for example).
9854.Ar lname
9855uses the long form.
9856.Ar oid
9857represents the OID in numerical form and is useful for diagnostic purpose.
9858.It Ar oneline
9859A oneline format which is more readable than
9860.Ar RFC2253 .
9861It is equivalent to specifying the
9862.Ar esc_2253 , esc_ctrl , esc_msb , utf8 ,
9863.Ar dump_nostr , dump_der , use_quote , sep_comma_plus_spc ,
9864.Ar space_eq ,
9865and
9866.Ar sname
9867options.
9868.It Ar RFC2253
9869Displays names compatible with RFC 2253; equivalent to
9870.Ar esc_2253 , esc_ctrl ,
9871.Ar esc_msb , utf8 , dump_nostr , dump_unknown ,
9872.Ar dump_der , sep_comma_plus , dn_rev ,
9873and
9874.Ar sname .
9875.It Ar sep_comma_plus , sep_comma_plus_space , sep_semi_plus_space , sep_multiline
9876These options determine the field separators.
9877The first character is between RDNs and the second between multiple AVAs
9878(multiple AVAs are very rare and their use is discouraged).
9879The options ending in
9880.Qq space
9881additionally place a space after the separator to make it more readable.
9882The
9883.Ar sep_multiline
9884uses a linefeed character for the RDN separator and a spaced
9885.Sq +
9886for the AVA separator.
9887It also indents the fields by four characters.
9888.It Ar show_type
9889Show the type of the ASN1 character string.
9890The type precedes the field contents.
9891For example
9892.Qq BMPSTRING: Hello World .
9893.It Ar space_eq
9894Places spaces round the
9895.Sq =
9896character which follows the field name.
9897.It Ar use_quote
9898Escapes some characters by surrounding the whole string with
9899.Sq \&"
9900characters.
9901Without the option, all escaping is done with the
9902.Sq \e
9903character.
9904.It Ar utf8
9905Convert all strings to UTF8 format first.
9906This is required by RFC 2253.
9907If you are lucky enough to have a UTF8 compatible terminal,
9908the use of this option (and
9909.Em not
9910setting
9911.Ar esc_msb )
9912may result in the correct display of multibyte
9913.Pq international
9914characters.
9915If this option is not present, multibyte characters larger than 0xff
9916will be represented using the format \eUXXXX for 16 bits and \eWXXXXXXXX
9917for 32 bits.
9918Also, if this option is off, any UTF8Strings will be converted to their
9919character form first.
9920.El
9921.Sh X509 TEXT OPTIONS
9922As well as customising the name output format, it is also possible to
9923customise the actual fields printed using the
9924.Fl certopt
9925options when the
9926.Fl text
9927option is present.
9928The default behaviour is to print all fields.
9929.Bl -tag -width "XXXX"
9930.It Ar ca_default
9931The value used by the
9932.Nm ca
9933utility; equivalent to
9934.Ar no_issuer , no_pubkey , no_header ,
9935.Ar no_version , no_sigdump ,
9936and
9937.Ar no_signame .
9938.It Ar compatible
9939Use the old format.
9940This is equivalent to specifying no output options at all.
9941.It Ar ext_default
9942Retain default extension behaviour: attempt to print out unsupported
9943certificate extensions.
9944.It Ar ext_dump
9945Hex dump unsupported extensions.
9946.It Ar ext_error
9947Print an error message for unsupported certificate extensions.
9948.It Ar ext_parse
9949ASN1 parse unsupported extensions.
9950.It Ar no_aux
9951Don't print out certificate trust information.
9952.It Ar no_extensions
9953Don't print out any X509V3 extensions.
9954.It Ar no_header
9955Don't print header information: that is, the lines saying
9956.Qq Certificate
9957and
9958.Qq Data .
9959.It Ar no_issuer
9960Don't print out the issuer name.
9961.It Ar no_pubkey
9962Don't print out the public key.
9963.It Ar no_serial
9964Don't print out the serial number.
9965.It Ar no_sigdump
9966Don't give a hexadecimal dump of the certificate signature.
9967.It Ar no_signame
9968Don't print out the signature algorithm used.
9969.It Ar no_subject
9970Don't print out the subject name.
9971.It Ar no_validity
9972Don't print the validity; that is, the
9973.Em notBefore
9974and
9975.Em notAfter
9976fields.
9977.It Ar no_version
9978Don't print out the version number.
9979.El
9980.Sh X509 EXAMPLES
9981Display the contents of a certificate:
9982.Pp
9983.Dl $ openssl x509 -in cert.pem -noout -text
9984.Pp
9985Display the certificate serial number:
9986.Pp
9987.Dl $ openssl x509 -in cert.pem -noout -serial
9988.Pp
9989Display the certificate subject name:
9990.Pp
9991.Dl $ openssl x509 -in cert.pem -noout -subject
9992.Pp
9993Display the certificate subject name in RFC 2253 form:
9994.Pp
9995.Dl $ openssl x509 -in cert.pem -noout -subject -nameopt RFC2253
9996.Pp
9997Display the certificate subject name in oneline form on a terminal
9998supporting UTF8:
9999.Bd -literal -offset indent
10000$ openssl x509 -in cert.pem -noout -subject \e
10001 -nameopt oneline,-esc_msb
10002.Ed
10003.Pp
10004Display the certificate MD5 fingerprint:
10005.Pp
10006.Dl $ openssl x509 -in cert.pem -noout -fingerprint
10007.Pp
10008Display the certificate SHA1 fingerprint:
10009.Pp
10010.Dl $ openssl x509 -sha1 -in cert.pem -noout -fingerprint
10011.Pp
10012Convert a certificate from PEM to DER format:
10013.Pp
10014.Dl "$ openssl x509 -in cert.pem -inform PEM -out cert.der -outform DER"
10015.Pp
10016Convert a certificate to a certificate request:
10017.Bd -literal -offset indent
10018$ openssl x509 -x509toreq -in cert.pem -out req.pem \e
10019 -signkey key.pem
10020.Ed
10021.Pp
10022Convert a certificate request into a self-signed certificate using
10023extensions for a CA:
10024.Bd -literal -offset indent
10025$ openssl x509 -req -in careq.pem -extfile openssl.cnf -extensions \e
10026 v3_ca -signkey key.pem -out cacert.pem
10027.Ed
10028.Pp
10029Sign a certificate request using the CA certificate above and add user
10030certificate extensions:
10031.Bd -literal -offset indent
10032$ openssl x509 -req -in req.pem -extfile openssl.cnf -extensions \e
10033 v3_usr -CA cacert.pem -CAkey key.pem -CAcreateserial
10034.Ed
10035.Pp
10036Set a certificate to be trusted for SSL
10037client use and set its alias to
10038.Qq Steve's Class 1 CA :
10039.Bd -literal -offset indent
10040$ openssl x509 -in cert.pem -addtrust clientAuth \e
10041 -setalias "Steve's Class 1 CA" -out trust.pem
10042.Ed
10043.Sh X509 NOTES
10044The PEM format uses the header and footer lines:
10045.Bd -unfilled -offset indent
10046-----BEGIN CERTIFICATE-----
10047-----END CERTIFICATE-----
10048.Ed
10049.Pp
10050It will also handle files containing:
10051.Bd -unfilled -offset indent
10052-----BEGIN X509 CERTIFICATE-----
10053-----END X509 CERTIFICATE-----
10054.Ed
10055.Pp
10056Trusted certificates have the lines:
10057.Bd -unfilled -offset indent
10058-----BEGIN TRUSTED CERTIFICATE-----
10059-----END TRUSTED CERTIFICATE-----
10060.Ed
10061.Pp
10062The conversion to UTF8 format used with the name options assumes that
10063T61Strings use the ISO 8859-1 character set.
10064This is wrong, but Netscape and MSIE do this, as do many certificates.
10065So although this is incorrect
10066it is more likely to display the majority of certificates correctly.
10067.Pp
10068The
10069.Fl fingerprint
10070option takes the digest of the DER-encoded certificate.
10071This is commonly called a
10072.Qq fingerprint .
10073Because of the nature of message digests, the fingerprint of a certificate
10074is unique to that certificate and two certificates with the same fingerprint
10075can be considered to be the same.
10076.Pp
10077The Netscape fingerprint uses MD5, whereas MSIE uses SHA1.
10078.Pp
10079The
10080.Fl email
10081option searches the subject name and the subject alternative
10082name extension.
10083Only unique email addresses will be printed out: it will
10084not print the same address more than once.
10085.Sh X.509 CERTIFICATE EXTENSIONS
10086The
10087.Fl purpose
10088option checks the certificate extensions and determines
10089what the certificate can be used for.
10090The actual checks done are rather
10091complex and include various hacks and workarounds to handle broken
10092certificates and software.
10093.Pp
10094The same code is used when verifying untrusted certificates in chains,
10095so this section is useful if a chain is rejected by the verify code.
10096.Pp
10097The
10098.Em basicConstraints
10099extension CA flag is used to determine whether the
10100certificate can be used as a CA.
10101If the CA flag is true, it is a CA;
10102if the CA flag is false, it is not a CA.
10103.Em All
10104CAs should have the CA flag set to true.
10105.Pp
10106If the
10107.Em basicConstraints
10108extension is absent, then the certificate is
10109considered to be a
10110.Qq possible CA ;
10111other extensions are checked according to the intended use of the certificate.
10112A warning is given in this case because the certificate should really not
10113be regarded as a CA: however,
10114it is allowed to be a CA to work around some broken software.
10115.Pp
10116If the certificate is a V1 certificate
10117.Pq and thus has no extensions
10118and it is self-signed, it is also assumed to be a CA but a warning is again
10119given: this is to work around the problem of Verisign roots which are V1
10120self-signed certificates.
10121.Pp
10122If the
10123.Em keyUsage
10124extension is present, then additional restraints are
10125made on the uses of the certificate.
10126A CA certificate
10127.Em must
10128have the
10129.Em keyCertSign
10130bit set if the
10131.Em keyUsage
10132extension is present.
10133.Pp
10134The extended key usage extension places additional restrictions on the
10135certificate uses.
10136If this extension is present
10137.Pq whether critical or not ,
10138the key can only be used for the purposes specified.
10139.Pp
10140A complete description of each test is given below.
10141The comments about
10142.Em basicConstraints
10143and
10144.Em keyUsage
10145and V1 certificates above apply to
10146.Em all
10147CA certificates.
10148.Bl -tag -width "XXXX"
10149.It Ar SSL Client
10150The extended key usage extension must be absent or include the
10151.Qq web client authentication
10152OID.
10153.Ar keyUsage
10154must be absent or it must have the
10155.Em digitalSignature
10156bit set.
10157Netscape certificate type must be absent or it must have the SSL
10158client bit set.
10159.It Ar SSL Client CA
10160The extended key usage extension must be absent or include the
10161.Qq web client authentication
10162OID.
10163Netscape certificate type must be absent or it must have the SSL CA
10164bit set: this is used as a work around if the
10165.Em basicConstraints
10166extension is absent.
10167.It Ar SSL Server
10168The extended key usage extension must be absent or include the
10169.Qq web server authentication
10170and/or one of the SGC OIDs.
10171.Em keyUsage
10172must be absent or it must have the
10173.Em digitalSignature
10174set, the
10175.Em keyEncipherment
10176set, or both bits set.
10177Netscape certificate type must be absent or have the SSL server bit set.
10178.It Ar SSL Server CA
10179The extended key usage extension must be absent or include the
10180.Qq web server authentication
10181and/or one of the SGC OIDs.
10182Netscape certificate type must be absent or the SSL CA
10183bit must be set: this is used as a work around if the
10184.Em basicConstraints
10185extension is absent.
10186.It Ar Netscape SSL Server
10187For Netscape SSL clients to connect to an SSL server; it must have the
10188.Em keyEncipherment
10189bit set if the
10190.Em keyUsage
10191extension is present.
10192This isn't always valid because some cipher suites use the key for
10193digital signing.
10194Otherwise it is the same as a normal SSL server.
10195.It Ar Common S/MIME Client Tests
10196The extended key usage extension must be absent or include the
10197.Qq email protection
10198OID.
10199Netscape certificate type must be absent or should have the
10200.Em S/MIME
10201bit set.
10202If the
10203.Em S/MIME
10204bit is not set in Netscape certificate type, then the SSL
10205client bit is tolerated as an alternative but a warning is shown:
10206this is because some Verisign certificates don't set the
10207.Em S/MIME
10208bit.
10209.It Ar S/MIME Signing
10210In addition to the common
10211.Em S/MIME
10212client tests, the
10213.Em digitalSignature
10214bit must be set if the
10215.Em keyUsage
10216extension is present.
10217.It Ar S/MIME Encryption
10218In addition to the common
10219.Em S/MIME
10220tests, the
10221.Em keyEncipherment
10222bit must be set if the
10223.Em keyUsage
10224extension is present.
10225.It Ar S/MIME CA
10226The extended key usage extension must be absent or include the
10227.Qq email protection
10228OID.
10229Netscape certificate type must be absent or must have the
10230.Em S/MIME CA
10231bit set: this is used as a work around if the
10232.Em basicConstraints
10233extension is absent.
10234.It Ar CRL Signing
10235The
10236.Em keyUsage
10237extension must be absent or it must have the
10238.Em CRL
10239signing bit set.
10240.It Ar CRL Signing CA
10241The normal CA tests apply.
10242Except in this case the
10243.Em basicConstraints
10244extension must be present.
10245.El
10246.Sh X509 BUGS
10247Extensions in certificates are not transferred to certificate requests and
10248vice versa.
10249.Pp
10250It is possible to produce invalid certificates or requests by specifying the
10251wrong private key or using inconsistent options in some cases: these should
10252be checked.
10253.Pp
10254There should be options to explicitly set such things as start and end dates,
10255rather than an offset from the current time.
10256.Pp
10257The code to implement the verify behaviour described in the
10258.Sx X509 TRUST SETTINGS
10259is currently being developed.
10260It thus describes the intended behaviour rather than the current behaviour.
10261It is hoped that it will represent reality in
10262.Nm OpenSSL
102630.9.5 and later.
10264.Sh X509 HISTORY
10265Before
10266.Nm OpenSSL
102670.9.8,
10268the default digest for RSA keys was MD5.
10269.Pp
10270The hash algorithm used in the
10271.Fl subject_hash
10272and
10273.Fl issuer_hash
10274options before
10275.Nm OpenSSL
102761.0.0 was based on the deprecated MD5 algorithm and the encoding
10277of the distinguished name.
10278In
10279.Nm OpenSSL
102801.0.0 and later it is based on a canonical version of the DN using SHA1.
10281This means that any directories using the old form
10282must have their links rebuilt using
10283.Ar c_rehash
10284or similar.
10285.\"
10286.\" FILES
10287.\"
10288.Sh FILES
10289.Bl -tag -width "/etc/ssl/openssl.cnf" -compact
10290.It /etc/ssl/
10291Default config directory for
10292.Nm openssl .
10293.It /etc/ssl/lib/
10294Unused.
10295.It /etc/ssl/private/
10296Default private key directory.
10297.It /etc/ssl/openssl.cnf
10298Default configuration file for
10299.Nm openssl .
10300.It /etc/ssl/x509v3.cnf
10301Default configuration file for
10302.Nm x509
10303certificates.
10304.El
10305.\"
10306.\" SEE ALSO
10307.\"
10308.Sh SEE ALSO
10309.Xr nginx 8 ,
10310.Xr sendmail 8 ,
10311.Xr ssl 8 ,
10312.Xr starttls 8
10313.Sh STANDARDS
10314.Rs
10315.%D February 1995
10316.%Q Netscape Communications Corp.
10317.%T The SSL Protocol
10318.Re
10319.Pp
10320.Rs
10321.%D November 1996
10322.%Q Netscape Communications Corp.
10323.%T The SSL 3.0 Protocol
10324.Re
10325.Pp
10326.Rs
10327.%A T. Dierks
10328.%A C. Allen
10329.%D January 1999
10330.%R RFC 2246
10331.%T The TLS Protocol Version 1.0
10332.Re
10333.Pp
10334.Rs
10335.%A M. Wahl
10336.%A S. Killie
10337.%A T. Howes
10338.%D December 1997
10339.%R RFC 2253
10340.%T Lightweight Directory Access Protocol (v3): UTF-8 String Representation of Distinguished Names
10341.Re
10342.Pp
10343.Rs
10344.%A B. Kaliski
10345.%D March 1998
10346.%R RFC 2315
10347.%T PKCS #7: Cryptographic Message Syntax Version 1.5
10348.Re
10349.Pp
10350.Rs
10351.%A R. Housley
10352.%A W. Ford
10353.%A W. Polk
10354.%A D. Solo
10355.%D January 1999
10356.%R RFC 2459
10357.%T Internet X.509 Public Key Infrastructure Certificate and CRL Profile
10358.Re
10359.Pp
10360.Rs
10361.%A M. Myers
10362.%A R. Ankney
10363.%A A. Malpani
10364.%A S. Galperin
10365.%A C. Adams
10366.%D June 1999
10367.%R RFC 2560
10368.%T X.509 Internet Public Key Infrastructure Online Certificate Status Protocol \(en OCSP
10369.Re
10370.Pp
10371.Rs
10372.%A R. Housley
10373.%D June 1999
10374.%R RFC 2630
10375.%T Cryptographic Message Syntax
10376.Re
10377.Pp
10378.Rs
10379.%A P. Chown
10380.%D June 2002
10381.%R RFC 3268
10382.%T Advanced Encryption Standard (AES) Ciphersuites for Transport Layer Security(TLS)
10383.Re
10384.\"
10385.\" OPENSSL HISTORY
10386.\"
10387.Sh HISTORY
10388The
10389.Xr openssl 1
10390document appeared in
10391.Nm OpenSSL
103920.9.2.
10393The
10394.Cm list- Ns XXX Ns Cm -commands
10395pseudo-commands were added in
10396.Nm OpenSSL
103970.9.3;
10398the
10399.Cm no- Ns XXX
10400pseudo-commands were added in
10401.Nm OpenSSL
104020.9.5a;
10403the
10404.Cm list- Ns XXX Ns Cm -algorithms
10405pseudo-commands were added in
10406.Nm OpenSSL
104071.0.0.
diff --git a/src/usr.bin/openssl/openssl.c b/src/usr.bin/openssl/openssl.c
new file mode 100644
index 0000000000..bcb9b56b74
--- /dev/null
+++ b/src/usr.bin/openssl/openssl.c
@@ -0,0 +1,639 @@
1/* $OpenBSD: openssl.c,v 1.1 2014/08/26 17:47:25 jsing 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 * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in
70 * the documentation and/or other materials provided with the
71 * distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 * software must display the following acknowledgment:
75 * "This product includes software developed by the OpenSSL Project
76 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 * endorse or promote products derived from this software without
80 * prior written permission. For written permission, please contact
81 * openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 * nor may "OpenSSL" appear in their names without prior written
85 * permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 * acknowledgment:
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com). This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
111
112#include <err.h>
113#include <signal.h>
114#include <stdio.h>
115#include <string.h>
116#include <stdlib.h>
117
118#include "apps.h"
119
120#include <openssl/bio.h>
121#include <openssl/conf.h>
122#include <openssl/crypto.h>
123#include <openssl/err.h>
124#include <openssl/lhash.h>
125#include <openssl/pem.h>
126#include <openssl/rand.h>
127#include <openssl/ssl.h>
128#include <openssl/x509.h>
129
130#ifndef OPENSSL_NO_ENGINE
131#include <openssl/engine.h>
132#endif
133
134#include "progs.h"
135#include "s_apps.h"
136
137static void openssl_startup(void);
138static void openssl_shutdown(void);
139
140/* The LHASH callbacks ("hash" & "cmp") have been replaced by functions with the
141 * base prototypes (we cast each variable inside the function to the required
142 * type of "FUNCTION*"). This removes the necessity for macro-generated wrapper
143 * functions. */
144
145static LHASH_OF(FUNCTION) *prog_init(void);
146static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]);
147static void list_pkey(BIO * out);
148static void list_cipher(BIO * out);
149static void list_md(BIO * out);
150char *default_config_file = NULL;
151
152CONF *config = NULL;
153BIO *bio_err = NULL;
154
155static void
156lock_dbg_cb(int mode, int type, const char *file, int line)
157{
158 static int modes[CRYPTO_NUM_LOCKS]; /* = {0, 0, ... } */
159 const char *errstr = NULL;
160 int rw;
161
162 rw = mode & (CRYPTO_READ | CRYPTO_WRITE);
163 if (!((rw == CRYPTO_READ) || (rw == CRYPTO_WRITE))) {
164 errstr = "invalid mode";
165 goto err;
166 }
167 if (type < 0 || type >= CRYPTO_NUM_LOCKS) {
168 errstr = "type out of bounds";
169 goto err;
170 }
171 if (mode & CRYPTO_LOCK) {
172 if (modes[type]) {
173 errstr = "already locked";
174 /*
175 * must not happen in a single-threaded program
176 * (would deadlock)
177 */
178 goto err;
179 }
180 modes[type] = rw;
181 } else if (mode & CRYPTO_UNLOCK) {
182 if (!modes[type]) {
183 errstr = "not locked";
184 goto err;
185 }
186 if (modes[type] != rw) {
187 errstr = (rw == CRYPTO_READ) ?
188 "CRYPTO_r_unlock on write lock" :
189 "CRYPTO_w_unlock on read lock";
190 }
191 modes[type] = 0;
192 } else {
193 errstr = "invalid mode";
194 goto err;
195 }
196
197err:
198 if (errstr) {
199 /* we cannot use bio_err here */
200 fprintf(stderr, "openssl (lock_dbg_cb): %s (mode=%d, type=%d) at %s:%d\n",
201 errstr, mode, type, file, line);
202 }
203}
204
205static void
206openssl_startup(void)
207{
208 signal(SIGPIPE, SIG_IGN);
209
210 CRYPTO_malloc_init();
211 OpenSSL_add_all_algorithms();
212 SSL_library_init();
213 SSL_load_error_strings();
214
215#ifndef OPENSSL_NO_ENGINE
216 ENGINE_load_builtin_engines();
217#endif
218
219 setup_ui_method();
220}
221
222static void
223openssl_shutdown(void)
224{
225 CONF_modules_unload(1);
226 destroy_ui_method();
227 OBJ_cleanup();
228 EVP_cleanup();
229
230#ifndef OPENSSL_NO_ENGINE
231 ENGINE_cleanup();
232#endif
233
234 CRYPTO_cleanup_all_ex_data();
235 ERR_remove_thread_state(NULL);
236 RAND_cleanup();
237 ERR_free_strings();
238}
239
240int
241main(int argc, char **argv)
242{
243 ARGS arg;
244#define PROG_NAME_SIZE 39
245 char pname[PROG_NAME_SIZE + 1];
246 FUNCTION f, *fp;
247 const char *prompt;
248 char buf[1024];
249 char *to_free = NULL;
250 int n, i, ret = 0;
251 char *p;
252 LHASH_OF(FUNCTION) * prog = NULL;
253 long errline;
254
255 arg.data = NULL;
256 arg.count = 0;
257
258 bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
259 if (bio_err == NULL) {
260 fprintf(stderr, "openssl: failed to initialise bio_err\n");
261 exit(1);
262 }
263
264 CRYPTO_set_locking_callback(lock_dbg_cb);
265
266 openssl_startup();
267
268 /* Lets load up our environment a little */
269 p = getenv("OPENSSL_CONF");
270 if (p == NULL)
271 p = getenv("SSLEAY_CONF");
272 if (p == NULL) {
273 p = to_free = make_config_name();
274 if (p == NULL) {
275 BIO_printf(bio_err, "error making config file name\n");
276 goto end;
277 }
278 }
279
280 default_config_file = p;
281
282 config = NCONF_new(NULL);
283 i = NCONF_load(config, p, &errline);
284 if (i == 0) {
285 if (ERR_GET_REASON(ERR_peek_last_error()) ==
286 CONF_R_NO_SUCH_FILE) {
287 BIO_printf(bio_err,
288 "WARNING: can't open config file: %s\n", p);
289 ERR_clear_error();
290 NCONF_free(config);
291 config = NULL;
292 } else {
293 ERR_print_errors(bio_err);
294 NCONF_free(config);
295 exit(1);
296 }
297 }
298
299 if (!load_config(bio_err, NULL)) {
300 BIO_printf(bio_err, "failed to load configuration\n");
301 goto end;
302 }
303
304 prog = prog_init();
305
306 /* first check the program name */
307 program_name(argv[0], pname, sizeof pname);
308
309 f.name = pname;
310 fp = lh_FUNCTION_retrieve(prog, &f);
311 if (fp != NULL) {
312 argv[0] = pname;
313 ret = fp->func(argc, argv);
314 goto end;
315 }
316 /*
317 * ok, now check that there are not arguments, if there are, run with
318 * them, shifting the ssleay off the front
319 */
320 if (argc != 1) {
321 argc--;
322 argv++;
323 ret = do_cmd(prog, argc, argv);
324 if (ret < 0)
325 ret = 0;
326 goto end;
327 }
328 /* ok, lets enter the old 'OpenSSL>' mode */
329
330 for (;;) {
331 ret = 0;
332 p = buf;
333 n = sizeof buf;
334 i = 0;
335 for (;;) {
336 p[0] = '\0';
337 if (i++)
338 prompt = ">";
339 else
340 prompt = "OpenSSL> ";
341 fputs(prompt, stdout);
342 fflush(stdout);
343 if (!fgets(p, n, stdin))
344 goto end;
345 if (p[0] == '\0')
346 goto end;
347 i = strlen(p);
348 if (i <= 1)
349 break;
350 if (p[i - 2] != '\\')
351 break;
352 i -= 2;
353 p += i;
354 n -= i;
355 }
356 if (!chopup_args(&arg, buf, &argc, &argv))
357 break;
358
359 ret = do_cmd(prog, argc, argv);
360 if (ret < 0) {
361 ret = 0;
362 goto end;
363 }
364 if (ret != 0)
365 BIO_printf(bio_err, "error in %s\n", argv[0]);
366 (void) BIO_flush(bio_err);
367 }
368 BIO_printf(bio_err, "bad exit\n");
369 ret = 1;
370
371end:
372 free(to_free);
373
374 if (config != NULL) {
375 NCONF_free(config);
376 config = NULL;
377 }
378 if (prog != NULL)
379 lh_FUNCTION_free(prog);
380 free(arg.data);
381
382 openssl_shutdown();
383
384 if (bio_err != NULL) {
385 BIO_free(bio_err);
386 bio_err = NULL;
387 }
388 return (ret);
389}
390
391#define LIST_STANDARD_COMMANDS "list-standard-commands"
392#define LIST_MESSAGE_DIGEST_COMMANDS "list-message-digest-commands"
393#define LIST_MESSAGE_DIGEST_ALGORITHMS "list-message-digest-algorithms"
394#define LIST_CIPHER_COMMANDS "list-cipher-commands"
395#define LIST_CIPHER_ALGORITHMS "list-cipher-algorithms"
396#define LIST_PUBLIC_KEY_ALGORITHMS "list-public-key-algorithms"
397
398
399static int
400do_cmd(LHASH_OF(FUNCTION) * prog, int argc, char *argv[])
401{
402 FUNCTION f, *fp;
403 int i, ret = 1, tp, nl;
404
405 if ((argc <= 0) || (argv[0] == NULL)) {
406 ret = 0;
407 goto end;
408 }
409 f.name = argv[0];
410 fp = lh_FUNCTION_retrieve(prog, &f);
411 if (fp == NULL) {
412 if (EVP_get_digestbyname(argv[0])) {
413 f.type = FUNC_TYPE_MD;
414 f.func = dgst_main;
415 fp = &f;
416 } else if (EVP_get_cipherbyname(argv[0])) {
417 f.type = FUNC_TYPE_CIPHER;
418 f.func = enc_main;
419 fp = &f;
420 }
421 }
422 if (fp != NULL) {
423 ret = fp->func(argc, argv);
424 } else if ((strncmp(argv[0], "no-", 3)) == 0) {
425 BIO *bio_stdout = BIO_new_fp(stdout, BIO_NOCLOSE);
426 f.name = argv[0] + 3;
427 ret = (lh_FUNCTION_retrieve(prog, &f) != NULL);
428 if (!ret)
429 BIO_printf(bio_stdout, "%s\n", argv[0]);
430 else
431 BIO_printf(bio_stdout, "%s\n", argv[0] + 3);
432 BIO_free_all(bio_stdout);
433 goto end;
434 } else if ((strcmp(argv[0], "quit") == 0) ||
435 (strcmp(argv[0], "q") == 0) ||
436 (strcmp(argv[0], "exit") == 0) ||
437 (strcmp(argv[0], "bye") == 0)) {
438 ret = -1;
439 goto end;
440 } else if ((strcmp(argv[0], LIST_STANDARD_COMMANDS) == 0) ||
441 (strcmp(argv[0], LIST_MESSAGE_DIGEST_COMMANDS) == 0) ||
442 (strcmp(argv[0], LIST_MESSAGE_DIGEST_ALGORITHMS) == 0) ||
443 (strcmp(argv[0], LIST_CIPHER_COMMANDS) == 0) ||
444 (strcmp(argv[0], LIST_CIPHER_ALGORITHMS) == 0) ||
445 (strcmp(argv[0], LIST_PUBLIC_KEY_ALGORITHMS) == 0)) {
446 int list_type;
447 BIO *bio_stdout;
448
449 if (strcmp(argv[0], LIST_STANDARD_COMMANDS) == 0)
450 list_type = FUNC_TYPE_GENERAL;
451 else if (strcmp(argv[0], LIST_MESSAGE_DIGEST_COMMANDS) == 0)
452 list_type = FUNC_TYPE_MD;
453 else if (strcmp(argv[0], LIST_MESSAGE_DIGEST_ALGORITHMS) == 0)
454 list_type = FUNC_TYPE_MD_ALG;
455 else if (strcmp(argv[0], LIST_PUBLIC_KEY_ALGORITHMS) == 0)
456 list_type = FUNC_TYPE_PKEY;
457 else if (strcmp(argv[0], LIST_CIPHER_ALGORITHMS) == 0)
458 list_type = FUNC_TYPE_CIPHER_ALG;
459 else /* strcmp(argv[0],LIST_CIPHER_COMMANDS) == 0 */
460 list_type = FUNC_TYPE_CIPHER;
461 bio_stdout = BIO_new_fp(stdout, BIO_NOCLOSE);
462
463 if (list_type == FUNC_TYPE_PKEY)
464 list_pkey(bio_stdout);
465 if (list_type == FUNC_TYPE_MD_ALG)
466 list_md(bio_stdout);
467 if (list_type == FUNC_TYPE_CIPHER_ALG)
468 list_cipher(bio_stdout);
469 else {
470 for (fp = functions; fp->name != NULL; fp++)
471 if (fp->type == list_type)
472 BIO_printf(bio_stdout, "%s\n",
473 fp->name);
474 }
475 BIO_free_all(bio_stdout);
476 ret = 0;
477 goto end;
478 } else {
479 BIO_printf(bio_err,
480 "openssl:Error: '%s' is an invalid command.\n",
481 argv[0]);
482 BIO_printf(bio_err, "\nStandard commands");
483 i = 0;
484 tp = 0;
485 for (fp = functions; fp->name != NULL; fp++) {
486 nl = 0;
487#ifdef OPENSSL_NO_CAMELLIA
488 if (((i++) % 5) == 0)
489#else
490 if (((i++) % 4) == 0)
491#endif
492 {
493 BIO_printf(bio_err, "\n");
494 nl = 1;
495 }
496 if (fp->type != tp) {
497 tp = fp->type;
498 if (!nl)
499 BIO_printf(bio_err, "\n");
500 if (tp == FUNC_TYPE_MD) {
501 i = 1;
502 BIO_printf(bio_err,
503 "\nMessage Digest commands (see the `dgst' command for more details)\n");
504 } else if (tp == FUNC_TYPE_CIPHER) {
505 i = 1;
506 BIO_printf(bio_err, "\nCipher commands (see the `enc' command for more details)\n");
507 }
508 }
509#ifdef OPENSSL_NO_CAMELLIA
510 BIO_printf(bio_err, "%-15s", fp->name);
511#else
512 BIO_printf(bio_err, "%-18s", fp->name);
513#endif
514 }
515 BIO_printf(bio_err, "\n\n");
516 ret = 0;
517 }
518end:
519 return (ret);
520}
521
522static int
523SortFnByName(const void *_f1, const void *_f2)
524{
525 const FUNCTION *f1 = _f1;
526 const FUNCTION *f2 = _f2;
527
528 if (f1->type != f2->type)
529 return f1->type - f2->type;
530 return strcmp(f1->name, f2->name);
531}
532
533static void
534list_pkey(BIO * out)
535{
536 int i;
537
538 for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
539 const EVP_PKEY_ASN1_METHOD *ameth;
540 int pkey_id, pkey_base_id, pkey_flags;
541 const char *pinfo, *pem_str;
542 ameth = EVP_PKEY_asn1_get0(i);
543 EVP_PKEY_asn1_get0_info(&pkey_id, &pkey_base_id, &pkey_flags,
544 &pinfo, &pem_str, ameth);
545 if (pkey_flags & ASN1_PKEY_ALIAS) {
546 BIO_printf(out, "Name: %s\n",
547 OBJ_nid2ln(pkey_id));
548 BIO_printf(out, "\tType: Alias to %s\n",
549 OBJ_nid2ln(pkey_base_id));
550 } else {
551 BIO_printf(out, "Name: %s\n", pinfo);
552 BIO_printf(out, "\tType: %s Algorithm\n",
553 pkey_flags & ASN1_PKEY_DYNAMIC ?
554 "External" : "Builtin");
555 BIO_printf(out, "\tOID: %s\n", OBJ_nid2ln(pkey_id));
556 if (pem_str == NULL)
557 pem_str = "(none)";
558 BIO_printf(out, "\tPEM string: %s\n", pem_str);
559 }
560
561 }
562}
563
564static void
565list_cipher_fn(const EVP_CIPHER * c, const char *from, const char *to,
566 void *arg)
567{
568 if (c)
569 BIO_printf(arg, "%s\n", EVP_CIPHER_name(c));
570 else {
571 if (!from)
572 from = "<undefined>";
573 if (!to)
574 to = "<undefined>";
575 BIO_printf(arg, "%s => %s\n", from, to);
576 }
577}
578
579static void
580list_cipher(BIO * out)
581{
582 EVP_CIPHER_do_all_sorted(list_cipher_fn, out);
583}
584
585static void
586list_md_fn(const EVP_MD * m, const char *from, const char *to, void *arg)
587{
588 if (m)
589 BIO_printf(arg, "%s\n", EVP_MD_name(m));
590 else {
591 if (!from)
592 from = "<undefined>";
593 if (!to)
594 to = "<undefined>";
595 BIO_printf(arg, "%s => %s\n", from, to);
596 }
597}
598
599static void
600list_md(BIO * out)
601{
602 EVP_MD_do_all_sorted(list_md_fn, out);
603}
604
605static int
606function_cmp(const FUNCTION * a, const FUNCTION * b)
607{
608 return strncmp(a->name, b->name, 8);
609}
610
611static IMPLEMENT_LHASH_COMP_FN(function, FUNCTION)
612
613static unsigned long
614function_hash(const FUNCTION * a)
615{
616 return lh_strhash(a->name);
617}
618
619static IMPLEMENT_LHASH_HASH_FN(function, FUNCTION)
620
621static LHASH_OF(FUNCTION) *
622prog_init(void)
623{
624 LHASH_OF(FUNCTION) * ret;
625 FUNCTION *f;
626 size_t i;
627
628 /* Purely so it looks nice when the user hits ? */
629 for (i = 0, f = functions; f->name != NULL; ++f, ++i)
630 ;
631 qsort(functions, i, sizeof *functions, SortFnByName);
632
633 if ((ret = lh_FUNCTION_new()) == NULL)
634 return (NULL);
635
636 for (f = functions; f->name != NULL; f++)
637 (void) lh_FUNCTION_insert(ret, f);
638 return (ret);
639}
diff --git a/src/usr.bin/openssl/passwd.c b/src/usr.bin/openssl/passwd.c
new file mode 100644
index 0000000000..fd5d062f57
--- /dev/null
+++ b/src/usr.bin/openssl/passwd.c
@@ -0,0 +1,457 @@
1/* $OpenBSD: passwd.c,v 1.1 2014/08/26 17:47:25 jsing Exp $ */
2
3#if defined OPENSSL_NO_MD5
4#define NO_MD5CRYPT_1
5#endif
6
7#if !defined(OPENSSL_NO_DES) || !defined(NO_MD5CRYPT_1)
8
9#include <assert.h>
10#include <string.h>
11
12#include "apps.h"
13
14#include <openssl/bio.h>
15#include <openssl/err.h>
16#include <openssl/evp.h>
17#include <openssl/rand.h>
18
19#ifndef OPENSSL_NO_DES
20#include <openssl/des.h>
21#endif
22
23#ifndef NO_MD5CRYPT_1
24#include <openssl/md5.h>
25#endif
26
27static unsigned const char cov_2char[64] = {
28 /* from crypto/des/fcrypt.c */
29 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
30 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44,
31 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C,
32 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54,
33 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x61, 0x62,
34 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A,
35 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72,
36 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A
37};
38
39static int
40do_passwd(int passed_salt, char **salt_p, char **salt_malloc_p,
41 char *passwd, BIO * out, int quiet, int table, int reverse,
42 size_t pw_maxlen, int usecrypt, int use1, int useapr1);
43
44/* -crypt - standard Unix password algorithm (default)
45 * -1 - MD5-based password algorithm
46 * -apr1 - MD5-based password algorithm, Apache variant
47 * -salt string - salt
48 * -in file - read passwords from file
49 * -stdin - read passwords from stdin
50 * -noverify - never verify when reading password from terminal
51 * -quiet - no warnings
52 * -table - format output as table
53 * -reverse - switch table columns
54 */
55
56int passwd_main(int, char **);
57
58int
59passwd_main(int argc, char **argv)
60{
61 int ret = 1;
62 char *infile = NULL;
63 int in_stdin = 0;
64 int in_noverify = 0;
65 char *salt = NULL, *passwd = NULL, **passwds = NULL;
66 char *salt_malloc = NULL, *passwd_malloc = NULL;
67 size_t passwd_malloc_size = 0;
68 int pw_source_defined = 0;
69 BIO *in = NULL, *out = NULL;
70 int i, badopt, opt_done;
71 int passed_salt = 0, quiet = 0, table = 0, reverse = 0;
72 int usecrypt = 0, use1 = 0, useapr1 = 0;
73 size_t pw_maxlen = 0;
74
75 out = BIO_new(BIO_s_file());
76 if (out == NULL)
77 goto err;
78 BIO_set_fp(out, stdout, BIO_NOCLOSE | BIO_FP_TEXT);
79
80 badopt = 0, opt_done = 0;
81 i = 0;
82 while (!badopt && !opt_done && argv[++i] != NULL) {
83 if (strcmp(argv[i], "-crypt") == 0)
84 usecrypt = 1;
85 else if (strcmp(argv[i], "-1") == 0)
86 use1 = 1;
87 else if (strcmp(argv[i], "-apr1") == 0)
88 useapr1 = 1;
89 else if (strcmp(argv[i], "-salt") == 0) {
90 if ((argv[i + 1] != NULL) && (salt == NULL)) {
91 passed_salt = 1;
92 salt = argv[++i];
93 } else
94 badopt = 1;
95 } else if (strcmp(argv[i], "-in") == 0) {
96 if ((argv[i + 1] != NULL) && !pw_source_defined) {
97 pw_source_defined = 1;
98 infile = argv[++i];
99 } else
100 badopt = 1;
101 } else if (strcmp(argv[i], "-stdin") == 0) {
102 if (!pw_source_defined) {
103 pw_source_defined = 1;
104 in_stdin = 1;
105 } else
106 badopt = 1;
107 } else if (strcmp(argv[i], "-noverify") == 0)
108 in_noverify = 1;
109 else if (strcmp(argv[i], "-quiet") == 0)
110 quiet = 1;
111 else if (strcmp(argv[i], "-table") == 0)
112 table = 1;
113 else if (strcmp(argv[i], "-reverse") == 0)
114 reverse = 1;
115 else if (argv[i][0] == '-')
116 badopt = 1;
117 else if (!pw_source_defined)
118 /* non-option arguments, use as passwords */
119 {
120 pw_source_defined = 1;
121 passwds = &argv[i];
122 opt_done = 1;
123 } else
124 badopt = 1;
125 }
126
127 if (!usecrypt && !use1 && !useapr1) /* use default */
128 usecrypt = 1;
129 if (usecrypt + use1 + useapr1 > 1) /* conflict */
130 badopt = 1;
131
132 /* reject unsupported algorithms */
133#ifdef OPENSSL_NO_DES
134 if (usecrypt)
135 badopt = 1;
136#endif
137#ifdef NO_MD5CRYPT_1
138 if (use1 || useapr1)
139 badopt = 1;
140#endif
141
142 if (badopt) {
143 BIO_printf(bio_err, "Usage: passwd [options] [passwords]\n");
144 BIO_printf(bio_err, "where options are\n");
145#ifndef OPENSSL_NO_DES
146 BIO_printf(bio_err, "-crypt standard Unix password algorithm (default)\n");
147#endif
148#ifndef NO_MD5CRYPT_1
149 BIO_printf(bio_err, "-1 MD5-based password algorithm\n");
150 BIO_printf(bio_err, "-apr1 MD5-based password algorithm, Apache variant\n");
151#endif
152 BIO_printf(bio_err, "-salt string use provided salt\n");
153 BIO_printf(bio_err, "-in file read passwords from file\n");
154 BIO_printf(bio_err, "-stdin read passwords from stdin\n");
155 BIO_printf(bio_err, "-noverify never verify when reading password from terminal\n");
156 BIO_printf(bio_err, "-quiet no warnings\n");
157 BIO_printf(bio_err, "-table format output as table\n");
158 BIO_printf(bio_err, "-reverse switch table columns\n");
159
160 goto err;
161 }
162 if ((infile != NULL) || in_stdin) {
163 in = BIO_new(BIO_s_file());
164 if (in == NULL)
165 goto err;
166 if (infile != NULL) {
167 assert(in_stdin == 0);
168 if (BIO_read_filename(in, infile) <= 0)
169 goto err;
170 } else {
171 assert(in_stdin);
172 BIO_set_fp(in, stdin, BIO_NOCLOSE);
173 }
174 }
175 if (usecrypt)
176 pw_maxlen = 8;
177 else if (use1 || useapr1)
178 pw_maxlen = 256;/* arbitrary limit, should be enough for most
179 * passwords */
180
181 if (passwds == NULL) {
182 /* no passwords on the command line */
183
184 passwd_malloc_size = pw_maxlen + 2;
185 /* longer than necessary so that we can warn about truncation */
186 passwd = passwd_malloc = malloc(passwd_malloc_size);
187 if (passwd_malloc == NULL)
188 goto err;
189 }
190 if ((in == NULL) && (passwds == NULL)) {
191 /* build a null-terminated list */
192 static char *passwds_static[2] = {NULL, NULL};
193
194 passwds = passwds_static;
195 if (in == NULL)
196 if (EVP_read_pw_string(passwd_malloc, passwd_malloc_size, "Password: ", !(passed_salt || in_noverify)) != 0)
197 goto err;
198 passwds[0] = passwd_malloc;
199 }
200 if (in == NULL) {
201 assert(passwds != NULL);
202 assert(*passwds != NULL);
203
204 do { /* loop over list of passwords */
205 passwd = *passwds++;
206 if (!do_passwd(passed_salt, &salt, &salt_malloc, passwd, out,
207 quiet, table, reverse, pw_maxlen, usecrypt, use1, useapr1))
208 goto err;
209 }
210 while (*passwds != NULL);
211 } else
212 /* in != NULL */
213 {
214 int done;
215
216 assert(passwd != NULL);
217 do {
218 int r = BIO_gets(in, passwd, pw_maxlen + 1);
219 if (r > 0) {
220 char *c = (strchr(passwd, '\n'));
221 if (c != NULL)
222 *c = 0; /* truncate at newline */
223 else {
224 /* ignore rest of line */
225 char trash[BUFSIZ];
226 do
227 r = BIO_gets(in, trash, sizeof trash);
228 while ((r > 0) && (!strchr(trash, '\n')));
229 }
230
231 if (!do_passwd(passed_salt, &salt, &salt_malloc, passwd, out,
232 quiet, table, reverse, pw_maxlen, usecrypt, use1, useapr1))
233 goto err;
234 }
235 done = (r <= 0);
236 }
237 while (!done);
238 }
239 ret = 0;
240
241err:
242 ERR_print_errors(bio_err);
243 free(salt_malloc);
244 free(passwd_malloc);
245 BIO_free(in);
246 if (out)
247 BIO_free_all(out);
248
249 return (ret);
250}
251
252
253#ifndef NO_MD5CRYPT_1
254/* MD5-based password algorithm (should probably be available as a library
255 * function; then the static buffer would not be acceptable).
256 * For magic string "1", this should be compatible to the MD5-based BSD
257 * password algorithm.
258 * For 'magic' string "apr1", this is compatible to the MD5-based Apache
259 * password algorithm.
260 * (Apparently, the Apache password algorithm is identical except that the
261 * 'magic' string was changed -- the laziest application of the NIH principle
262 * I've ever encountered.)
263 */
264static char *
265md5crypt(const char *passwd, const char *magic, const char *salt)
266{
267 static char out_buf[6 + 9 + 24 + 2]; /* "$apr1$..salt..$.......md5h
268 * ash..........\0" */
269 unsigned char buf[MD5_DIGEST_LENGTH];
270 char *salt_out;
271 int n;
272 unsigned int i;
273 EVP_MD_CTX md, md2;
274 size_t passwd_len, salt_len;
275
276 passwd_len = strlen(passwd);
277 out_buf[0] = '$';
278 out_buf[1] = 0;
279 assert(strlen(magic) <= 4); /* "1" or "apr1" */
280 strlcat(out_buf, magic, sizeof(out_buf));
281 strlcat(out_buf, "$", sizeof(out_buf));
282 strlcat(out_buf, salt, sizeof(out_buf));
283 assert(strlen(out_buf) <= 6 + 8); /* "$apr1$..salt.." */
284 salt_out = out_buf + 2 + strlen(magic);
285 salt_len = strlen(salt_out);
286 assert(salt_len <= 8);
287
288 EVP_MD_CTX_init(&md);
289 EVP_DigestInit_ex(&md, EVP_md5(), NULL);
290 EVP_DigestUpdate(&md, passwd, passwd_len);
291 EVP_DigestUpdate(&md, "$", 1);
292 EVP_DigestUpdate(&md, magic, strlen(magic));
293 EVP_DigestUpdate(&md, "$", 1);
294 EVP_DigestUpdate(&md, salt_out, salt_len);
295
296 EVP_MD_CTX_init(&md2);
297 EVP_DigestInit_ex(&md2, EVP_md5(), NULL);
298 EVP_DigestUpdate(&md2, passwd, passwd_len);
299 EVP_DigestUpdate(&md2, salt_out, salt_len);
300 EVP_DigestUpdate(&md2, passwd, passwd_len);
301 EVP_DigestFinal_ex(&md2, buf, NULL);
302
303 for (i = passwd_len; i > sizeof buf; i -= sizeof buf)
304 EVP_DigestUpdate(&md, buf, sizeof buf);
305 EVP_DigestUpdate(&md, buf, i);
306
307 n = passwd_len;
308 while (n) {
309 EVP_DigestUpdate(&md, (n & 1) ? "\0" : passwd, 1);
310 n >>= 1;
311 }
312 EVP_DigestFinal_ex(&md, buf, NULL);
313
314 for (i = 0; i < 1000; i++) {
315 EVP_DigestInit_ex(&md2, EVP_md5(), NULL);
316 EVP_DigestUpdate(&md2, (i & 1) ? (unsigned const char *) passwd : buf,
317 (i & 1) ? passwd_len : sizeof buf);
318 if (i % 3)
319 EVP_DigestUpdate(&md2, salt_out, salt_len);
320 if (i % 7)
321 EVP_DigestUpdate(&md2, passwd, passwd_len);
322 EVP_DigestUpdate(&md2, (i & 1) ? buf : (unsigned const char *) passwd,
323 (i & 1) ? sizeof buf : passwd_len);
324 EVP_DigestFinal_ex(&md2, buf, NULL);
325 }
326 EVP_MD_CTX_cleanup(&md2);
327
328 {
329 /* transform buf into output string */
330
331 unsigned char buf_perm[sizeof buf];
332 int dest, source;
333 char *output;
334
335 /* silly output permutation */
336 for (dest = 0, source = 0; dest < 14; dest++, source = (source + 6) % 17)
337 buf_perm[dest] = buf[source];
338 buf_perm[14] = buf[5];
339 buf_perm[15] = buf[11];
340 assert(16 == sizeof buf_perm);
341
342 output = salt_out + salt_len;
343 assert(output == out_buf + strlen(out_buf));
344
345 *output++ = '$';
346
347 for (i = 0; i < 15; i += 3) {
348 *output++ = cov_2char[buf_perm[i + 2] & 0x3f];
349 *output++ = cov_2char[((buf_perm[i + 1] & 0xf) << 2) |
350 (buf_perm[i + 2] >> 6)];
351 *output++ = cov_2char[((buf_perm[i] & 3) << 4) |
352 (buf_perm[i + 1] >> 4)];
353 *output++ = cov_2char[buf_perm[i] >> 2];
354 }
355 assert(i == 15);
356 *output++ = cov_2char[buf_perm[i] & 0x3f];
357 *output++ = cov_2char[buf_perm[i] >> 6];
358 *output = 0;
359 assert(strlen(out_buf) < sizeof(out_buf));
360 }
361 EVP_MD_CTX_cleanup(&md);
362
363 return out_buf;
364}
365#endif
366
367
368static int
369do_passwd(int passed_salt, char **salt_p, char **salt_malloc_p,
370 char *passwd, BIO * out, int quiet, int table, int reverse,
371 size_t pw_maxlen, int usecrypt, int use1, int useapr1)
372{
373 char *hash = NULL;
374
375 assert(salt_p != NULL);
376 assert(salt_malloc_p != NULL);
377
378 /* first make sure we have a salt */
379 if (!passed_salt) {
380#ifndef OPENSSL_NO_DES
381 if (usecrypt) {
382 if (*salt_malloc_p == NULL) {
383 *salt_p = *salt_malloc_p = malloc(3);
384 if (*salt_malloc_p == NULL)
385 goto err;
386 }
387 if (RAND_pseudo_bytes((unsigned char *) *salt_p, 2) < 0)
388 goto err;
389 (*salt_p)[0] = cov_2char[(*salt_p)[0] & 0x3f]; /* 6 bits */
390 (*salt_p)[1] = cov_2char[(*salt_p)[1] & 0x3f]; /* 6 bits */
391 (*salt_p)[2] = 0;
392 }
393#endif /* !OPENSSL_NO_DES */
394
395#ifndef NO_MD5CRYPT_1
396 if (use1 || useapr1) {
397 int i;
398
399 if (*salt_malloc_p == NULL) {
400 *salt_p = *salt_malloc_p = malloc(9);
401 if (*salt_malloc_p == NULL)
402 goto err;
403 }
404 if (RAND_pseudo_bytes((unsigned char *) *salt_p, 8) < 0)
405 goto err;
406
407 for (i = 0; i < 8; i++)
408 (*salt_p)[i] = cov_2char[(*salt_p)[i] & 0x3f]; /* 6 bits */
409 (*salt_p)[8] = 0;
410 }
411#endif /* !NO_MD5CRYPT_1 */
412 }
413 assert(*salt_p != NULL);
414
415 /* truncate password if necessary */
416 if ((strlen(passwd) > pw_maxlen)) {
417 if (!quiet)
418 /*
419 * XXX: really we should know how to print a size_t,
420 * not cast it
421 */
422 BIO_printf(bio_err, "Warning: truncating password to %u characters\n", (unsigned) pw_maxlen);
423 passwd[pw_maxlen] = 0;
424 }
425 assert(strlen(passwd) <= pw_maxlen);
426
427 /* now compute password hash */
428#ifndef OPENSSL_NO_DES
429 if (usecrypt)
430 hash = DES_crypt(passwd, *salt_p);
431#endif
432#ifndef NO_MD5CRYPT_1
433 if (use1 || useapr1)
434 hash = md5crypt(passwd, (use1 ? "1" : "apr1"), *salt_p);
435#endif
436 assert(hash != NULL);
437
438 if (table && !reverse)
439 BIO_printf(out, "%s\t%s\n", passwd, hash);
440 else if (table && reverse)
441 BIO_printf(out, "%s\t%s\n", hash, passwd);
442 else
443 BIO_printf(out, "%s\n", hash);
444 return 1;
445
446err:
447 return 0;
448}
449#else
450
451int
452passwd_main(int argc, char **argv)
453{
454 fputs("Program not available.\n", stderr)
455 return (1);
456}
457#endif
diff --git a/src/usr.bin/openssl/pkcs12.c b/src/usr.bin/openssl/pkcs12.c
new file mode 100644
index 0000000000..77b7c31d01
--- /dev/null
+++ b/src/usr.bin/openssl/pkcs12.c
@@ -0,0 +1,913 @@
1/* $OpenBSD: pkcs12.c,v 1.1 2014/08/26 17:47:25 jsing Exp $ */
2/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3 * project.
4 */
5/* ====================================================================
6 * Copyright (c) 1999-2006 The OpenSSL Project. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
19 *
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24 *
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * licensing@OpenSSL.org.
29 *
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
33 *
34 * 6. Redistributions of any form whatsoever must retain the following
35 * acknowledgment:
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
52 *
53 * This product includes cryptographic software written by Eric Young
54 * (eay@cryptsoft.com). This product includes software written by Tim
55 * Hudson (tjh@cryptsoft.com).
56 *
57 */
58
59#include <openssl/opensslconf.h>
60
61#if !defined(OPENSSL_NO_DES) && !defined(OPENSSL_NO_SHA1)
62
63#include <stdio.h>
64#include <stdlib.h>
65#include <string.h>
66
67#include "apps.h"
68
69#include <openssl/crypto.h>
70#include <openssl/err.h>
71#include <openssl/pem.h>
72#include <openssl/pkcs12.h>
73
74const EVP_CIPHER *enc;
75
76#define NOKEYS 0x1
77#define NOCERTS 0x2
78#define INFO 0x4
79#define CLCERTS 0x8
80#define CACERTS 0x10
81
82int get_cert_chain(X509 * cert, X509_STORE * store, STACK_OF(X509) ** chain);
83int dump_certs_keys_p12(BIO * out, PKCS12 * p12, char *pass, int passlen,
84 int options, char *pempass);
85int dump_certs_pkeys_bags(BIO * out, STACK_OF(PKCS12_SAFEBAG) * bags, char *pass,
86 int passlen, int options, char *pempass);
87int dump_certs_pkeys_bag(BIO * out, PKCS12_SAFEBAG * bags, char *pass, int passlen,
88 int options, char *pempass);
89int print_attribs(BIO * out, STACK_OF(X509_ATTRIBUTE) * attrlst, const char *name);
90void hex_prin(BIO * out, unsigned char *buf, int len);
91int alg_print(BIO * x, X509_ALGOR * alg);
92int cert_load(BIO * in, STACK_OF(X509) * sk);
93static int set_pbe(BIO * err, int *ppbe, const char *str);
94
95int pkcs12_main(int, char **);
96
97int
98pkcs12_main(int argc, char **argv)
99{
100 ENGINE *e = NULL;
101 char *infile = NULL, *outfile = NULL, *keyname = NULL;
102 char *certfile = NULL;
103 BIO *in = NULL, *out = NULL;
104 char **args;
105 char *name = NULL;
106 char *csp_name = NULL;
107 int add_lmk = 0;
108 PKCS12 *p12 = NULL;
109 char pass[50], macpass[50];
110 int export_cert = 0;
111 int options = 0;
112 int chain = 0;
113 int badarg = 0;
114 int iter = PKCS12_DEFAULT_ITER;
115 int maciter = PKCS12_DEFAULT_ITER;
116 int twopass = 0;
117 int keytype = 0;
118 int cert_pbe;
119 int key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
120 int ret = 1;
121 int macver = 1;
122 int noprompt = 0;
123 STACK_OF(OPENSSL_STRING) * canames = NULL;
124 char *cpass = NULL, *mpass = NULL;
125 char *passargin = NULL, *passargout = NULL, *passarg = NULL;
126 char *passin = NULL, *passout = NULL;
127 char *macalg = NULL;
128 char *CApath = NULL, *CAfile = NULL;
129#ifndef OPENSSL_NO_ENGINE
130 char *engine = NULL;
131#endif
132
133 cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
134
135 enc = EVP_des_ede3_cbc();
136
137 args = argv + 1;
138
139 while (*args) {
140 if (*args[0] == '-') {
141 if (!strcmp(*args, "-nokeys"))
142 options |= NOKEYS;
143 else if (!strcmp(*args, "-keyex"))
144 keytype = KEY_EX;
145 else if (!strcmp(*args, "-keysig"))
146 keytype = KEY_SIG;
147 else if (!strcmp(*args, "-nocerts"))
148 options |= NOCERTS;
149 else if (!strcmp(*args, "-clcerts"))
150 options |= CLCERTS;
151 else if (!strcmp(*args, "-cacerts"))
152 options |= CACERTS;
153 else if (!strcmp(*args, "-noout"))
154 options |= (NOKEYS | NOCERTS);
155 else if (!strcmp(*args, "-info"))
156 options |= INFO;
157 else if (!strcmp(*args, "-chain"))
158 chain = 1;
159 else if (!strcmp(*args, "-twopass"))
160 twopass = 1;
161 else if (!strcmp(*args, "-nomacver"))
162 macver = 0;
163 else if (!strcmp(*args, "-descert"))
164 cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
165 else if (!strcmp(*args, "-export"))
166 export_cert = 1;
167 else if (!strcmp(*args, "-des"))
168 enc = EVP_des_cbc();
169 else if (!strcmp(*args, "-des3"))
170 enc = EVP_des_ede3_cbc();
171#ifndef OPENSSL_NO_IDEA
172 else if (!strcmp(*args, "-idea"))
173 enc = EVP_idea_cbc();
174#endif
175#ifndef OPENSSL_NO_AES
176 else if (!strcmp(*args, "-aes128"))
177 enc = EVP_aes_128_cbc();
178 else if (!strcmp(*args, "-aes192"))
179 enc = EVP_aes_192_cbc();
180 else if (!strcmp(*args, "-aes256"))
181 enc = EVP_aes_256_cbc();
182#endif
183#ifndef OPENSSL_NO_CAMELLIA
184 else if (!strcmp(*args, "-camellia128"))
185 enc = EVP_camellia_128_cbc();
186 else if (!strcmp(*args, "-camellia192"))
187 enc = EVP_camellia_192_cbc();
188 else if (!strcmp(*args, "-camellia256"))
189 enc = EVP_camellia_256_cbc();
190#endif
191 else if (!strcmp(*args, "-noiter"))
192 iter = 1;
193 else if (!strcmp(*args, "-maciter"))
194 maciter = PKCS12_DEFAULT_ITER;
195 else if (!strcmp(*args, "-nomaciter"))
196 maciter = 1;
197 else if (!strcmp(*args, "-nomac"))
198 maciter = -1;
199 else if (!strcmp(*args, "-macalg"))
200 if (args[1]) {
201 args++;
202 macalg = *args;
203 } else
204 badarg = 1;
205 else if (!strcmp(*args, "-nodes"))
206 enc = NULL;
207 else if (!strcmp(*args, "-certpbe")) {
208 if (!set_pbe(bio_err, &cert_pbe, *++args))
209 badarg = 1;
210 } else if (!strcmp(*args, "-keypbe")) {
211 if (!set_pbe(bio_err, &key_pbe, *++args))
212 badarg = 1;
213 } else if (!strcmp(*args, "-inkey")) {
214 if (args[1]) {
215 args++;
216 keyname = *args;
217 } else
218 badarg = 1;
219 } else if (!strcmp(*args, "-certfile")) {
220 if (args[1]) {
221 args++;
222 certfile = *args;
223 } else
224 badarg = 1;
225 } else if (!strcmp(*args, "-name")) {
226 if (args[1]) {
227 args++;
228 name = *args;
229 } else
230 badarg = 1;
231 } else if (!strcmp(*args, "-LMK"))
232 add_lmk = 1;
233 else if (!strcmp(*args, "-CSP")) {
234 if (args[1]) {
235 args++;
236 csp_name = *args;
237 } else
238 badarg = 1;
239 } else if (!strcmp(*args, "-caname")) {
240 if (args[1]) {
241 args++;
242 if (!canames)
243 canames = sk_OPENSSL_STRING_new_null();
244 sk_OPENSSL_STRING_push(canames, *args);
245 } else
246 badarg = 1;
247 } else if (!strcmp(*args, "-in")) {
248 if (args[1]) {
249 args++;
250 infile = *args;
251 } else
252 badarg = 1;
253 } else if (!strcmp(*args, "-out")) {
254 if (args[1]) {
255 args++;
256 outfile = *args;
257 } else
258 badarg = 1;
259 } else if (!strcmp(*args, "-passin")) {
260 if (args[1]) {
261 args++;
262 passargin = *args;
263 } else
264 badarg = 1;
265 } else if (!strcmp(*args, "-passout")) {
266 if (args[1]) {
267 args++;
268 passargout = *args;
269 } else
270 badarg = 1;
271 } else if (!strcmp(*args, "-password")) {
272 if (args[1]) {
273 args++;
274 passarg = *args;
275 noprompt = 1;
276 } else
277 badarg = 1;
278 } else if (!strcmp(*args, "-CApath")) {
279 if (args[1]) {
280 args++;
281 CApath = *args;
282 } else
283 badarg = 1;
284 } else if (!strcmp(*args, "-CAfile")) {
285 if (args[1]) {
286 args++;
287 CAfile = *args;
288 } else
289 badarg = 1;
290#ifndef OPENSSL_NO_ENGINE
291 } else if (!strcmp(*args, "-engine")) {
292 if (args[1]) {
293 args++;
294 engine = *args;
295 } else
296 badarg = 1;
297#endif
298 } else
299 badarg = 1;
300
301 } else
302 badarg = 1;
303 args++;
304 }
305
306 if (badarg) {
307 BIO_printf(bio_err, "Usage: pkcs12 [options]\n");
308 BIO_printf(bio_err, "where options are\n");
309 BIO_printf(bio_err, "-export output PKCS12 file\n");
310 BIO_printf(bio_err, "-chain add certificate chain\n");
311 BIO_printf(bio_err, "-inkey file private key if not infile\n");
312 BIO_printf(bio_err, "-certfile f add all certs in f\n");
313 BIO_printf(bio_err, "-CApath arg - PEM format directory of CA's\n");
314 BIO_printf(bio_err, "-CAfile arg - PEM format file of CA's\n");
315 BIO_printf(bio_err, "-name \"name\" use name as friendly name\n");
316 BIO_printf(bio_err, "-caname \"nm\" use nm as CA friendly name (can be used more than once).\n");
317 BIO_printf(bio_err, "-in infile input filename\n");
318 BIO_printf(bio_err, "-out outfile output filename\n");
319 BIO_printf(bio_err, "-noout don't output anything, just verify.\n");
320 BIO_printf(bio_err, "-nomacver don't verify MAC.\n");
321 BIO_printf(bio_err, "-nocerts don't output certificates.\n");
322 BIO_printf(bio_err, "-clcerts only output client certificates.\n");
323 BIO_printf(bio_err, "-cacerts only output CA certificates.\n");
324 BIO_printf(bio_err, "-nokeys don't output private keys.\n");
325 BIO_printf(bio_err, "-info give info about PKCS#12 structure.\n");
326 BIO_printf(bio_err, "-des encrypt private keys with DES\n");
327 BIO_printf(bio_err, "-des3 encrypt private keys with triple DES (default)\n");
328#ifndef OPENSSL_NO_IDEA
329 BIO_printf(bio_err, "-idea encrypt private keys with idea\n");
330#endif
331#ifndef OPENSSL_NO_AES
332 BIO_printf(bio_err, "-aes128, -aes192, -aes256\n");
333 BIO_printf(bio_err, " encrypt PEM output with cbc aes\n");
334#endif
335#ifndef OPENSSL_NO_CAMELLIA
336 BIO_printf(bio_err, "-camellia128, -camellia192, -camellia256\n");
337 BIO_printf(bio_err, " encrypt PEM output with cbc camellia\n");
338#endif
339 BIO_printf(bio_err, "-nodes don't encrypt private keys\n");
340 BIO_printf(bio_err, "-noiter don't use encryption iteration\n");
341 BIO_printf(bio_err, "-nomaciter don't use MAC iteration\n");
342 BIO_printf(bio_err, "-maciter use MAC iteration\n");
343 BIO_printf(bio_err, "-nomac don't generate MAC\n");
344 BIO_printf(bio_err, "-twopass separate MAC, encryption passwords\n");
345 BIO_printf(bio_err, "-descert encrypt PKCS#12 certificates with triple DES (default RC2-40)\n");
346 BIO_printf(bio_err, "-certpbe alg specify certificate PBE algorithm (default RC2-40)\n");
347 BIO_printf(bio_err, "-keypbe alg specify private key PBE algorithm (default 3DES)\n");
348 BIO_printf(bio_err, "-macalg alg digest algorithm used in MAC (default SHA1)\n");
349 BIO_printf(bio_err, "-keyex set MS key exchange type\n");
350 BIO_printf(bio_err, "-keysig set MS key signature type\n");
351 BIO_printf(bio_err, "-password p set import/export password source\n");
352 BIO_printf(bio_err, "-passin p input file pass phrase source\n");
353 BIO_printf(bio_err, "-passout p output file pass phrase source\n");
354#ifndef OPENSSL_NO_ENGINE
355 BIO_printf(bio_err, "-engine e use engine e, possibly a hardware device.\n");
356#endif
357 BIO_printf(bio_err, "-CSP name Microsoft CSP name\n");
358 BIO_printf(bio_err, "-LMK Add local machine keyset attribute to private key\n");
359 goto end;
360 }
361#ifndef OPENSSL_NO_ENGINE
362 e = setup_engine(bio_err, engine, 0);
363#endif
364
365 if (passarg) {
366 if (export_cert)
367 passargout = passarg;
368 else
369 passargin = passarg;
370 }
371 if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
372 BIO_printf(bio_err, "Error getting passwords\n");
373 goto end;
374 }
375 if (!cpass) {
376 if (export_cert)
377 cpass = passout;
378 else
379 cpass = passin;
380 }
381 if (cpass) {
382 mpass = cpass;
383 noprompt = 1;
384 } else {
385 cpass = pass;
386 mpass = macpass;
387 }
388
389 ERR_load_crypto_strings();
390
391
392 if (!infile)
393 in = BIO_new_fp(stdin, BIO_NOCLOSE);
394 else
395 in = BIO_new_file(infile, "rb");
396 if (!in) {
397 BIO_printf(bio_err, "Error opening input file %s\n",
398 infile ? infile : "<stdin>");
399 perror(infile);
400 goto end;
401 }
402
403 if (!outfile) {
404 out = BIO_new_fp(stdout, BIO_NOCLOSE);
405 } else
406 out = BIO_new_file(outfile, "wb");
407 if (!out) {
408 BIO_printf(bio_err, "Error opening output file %s\n",
409 outfile ? outfile : "<stdout>");
410 perror(outfile);
411 goto end;
412 }
413 if (twopass) {
414 if (EVP_read_pw_string(macpass, sizeof macpass, "Enter MAC Password:", export_cert)) {
415 BIO_printf(bio_err, "Can't read Password\n");
416 goto end;
417 }
418 }
419 if (export_cert) {
420 EVP_PKEY *key = NULL;
421 X509 *ucert = NULL, *x = NULL;
422 STACK_OF(X509) * certs = NULL;
423 const EVP_MD *macmd = NULL;
424 unsigned char *catmp = NULL;
425 int i;
426
427 if ((options & (NOCERTS | NOKEYS)) == (NOCERTS | NOKEYS)) {
428 BIO_printf(bio_err, "Nothing to do!\n");
429 goto export_end;
430 }
431 if (options & NOCERTS)
432 chain = 0;
433
434 if (!(options & NOKEYS)) {
435 key = load_key(bio_err, keyname ? keyname : infile,
436 FORMAT_PEM, 1, passin, e, "private key");
437 if (!key)
438 goto export_end;
439 }
440
441 /* Load in all certs in input file */
442 if (!(options & NOCERTS)) {
443 certs = load_certs(bio_err, infile, FORMAT_PEM, NULL, e,
444 "certificates");
445 if (!certs)
446 goto export_end;
447
448 if (key) {
449 /* Look for matching private key */
450 for (i = 0; i < sk_X509_num(certs); i++) {
451 x = sk_X509_value(certs, i);
452 if (X509_check_private_key(x, key)) {
453 ucert = x;
454 /* Zero keyid and alias */
455 X509_keyid_set1(ucert, NULL, 0);
456 X509_alias_set1(ucert, NULL, 0);
457 /* Remove from list */
458 (void) sk_X509_delete(certs, i);
459 break;
460 }
461 }
462 if (!ucert) {
463 BIO_printf(bio_err, "No certificate matches private key\n");
464 goto export_end;
465 }
466 }
467 }
468
469 /* Add any more certificates asked for */
470 if (certfile) {
471 STACK_OF(X509) * morecerts = NULL;
472 if (!(morecerts = load_certs(bio_err, certfile, FORMAT_PEM,
473 NULL, e,
474 "certificates from certfile")))
475 goto export_end;
476 while (sk_X509_num(morecerts) > 0)
477 sk_X509_push(certs, sk_X509_shift(morecerts));
478 sk_X509_free(morecerts);
479 }
480
481
482 /* If chaining get chain from user cert */
483 if (chain) {
484 int vret;
485 STACK_OF(X509) * chain2;
486 X509_STORE *store = X509_STORE_new();
487 if (!store) {
488 BIO_printf(bio_err, "Memory allocation error\n");
489 goto export_end;
490 }
491 if (!X509_STORE_load_locations(store, CAfile, CApath))
492 X509_STORE_set_default_paths(store);
493
494 vret = get_cert_chain(ucert, store, &chain2);
495 X509_STORE_free(store);
496
497 if (!vret) {
498 /* Exclude verified certificate */
499 for (i = 1; i < sk_X509_num(chain2); i++)
500 sk_X509_push(certs, sk_X509_value(chain2, i));
501 /* Free first certificate */
502 X509_free(sk_X509_value(chain2, 0));
503 sk_X509_free(chain2);
504 } else {
505 if (vret >= 0)
506 BIO_printf(bio_err, "Error %s getting chain.\n",
507 X509_verify_cert_error_string(vret));
508 else
509 ERR_print_errors(bio_err);
510 goto export_end;
511 }
512 }
513 /* Add any CA names */
514
515 for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++) {
516 catmp = (unsigned char *) sk_OPENSSL_STRING_value(canames, i);
517 X509_alias_set1(sk_X509_value(certs, i), catmp, -1);
518 }
519
520 if (csp_name && key)
521 EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name,
522 MBSTRING_ASC, (unsigned char *) csp_name, -1);
523
524 if (add_lmk && key)
525 EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1);
526
527
528 if (!noprompt &&
529 EVP_read_pw_string(pass, sizeof pass, "Enter Export Password:", 1)) {
530 BIO_printf(bio_err, "Can't read Password\n");
531 goto export_end;
532 }
533 if (!twopass)
534 strlcpy(macpass, pass, sizeof macpass);
535
536
537 p12 = PKCS12_create(cpass, name, key, ucert, certs,
538 key_pbe, cert_pbe, iter, -1, keytype);
539
540 if (!p12) {
541 ERR_print_errors(bio_err);
542 goto export_end;
543 }
544 if (macalg) {
545 macmd = EVP_get_digestbyname(macalg);
546 if (!macmd) {
547 BIO_printf(bio_err, "Unknown digest algorithm %s\n",
548 macalg);
549 }
550 }
551 if (maciter != -1)
552 PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, macmd);
553
554
555 i2d_PKCS12_bio(out, p12);
556
557 ret = 0;
558
559export_end:
560
561 if (key)
562 EVP_PKEY_free(key);
563 if (certs)
564 sk_X509_pop_free(certs, X509_free);
565 if (ucert)
566 X509_free(ucert);
567
568 goto end;
569
570 }
571 if (!(p12 = d2i_PKCS12_bio(in, NULL))) {
572 ERR_print_errors(bio_err);
573 goto end;
574 }
575 if (!noprompt && EVP_read_pw_string(pass, sizeof pass, "Enter Import Password:", 0)) {
576 BIO_printf(bio_err, "Can't read Password\n");
577 goto end;
578 }
579
580 if (!twopass)
581 strlcpy(macpass, pass, sizeof macpass);
582
583 if ((options & INFO) && p12->mac)
584 BIO_printf(bio_err, "MAC Iteration %ld\n", p12->mac->iter ? ASN1_INTEGER_get(p12->mac->iter) : 1);
585 if (macver) {
586 /* If we enter empty password try no password first */
587 if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
588 /* If mac and crypto pass the same set it to NULL too */
589 if (!twopass)
590 cpass = NULL;
591 } else if (!PKCS12_verify_mac(p12, mpass, -1)) {
592 BIO_printf(bio_err, "Mac verify error: invalid password?\n");
593 ERR_print_errors(bio_err);
594 goto end;
595 }
596 BIO_printf(bio_err, "MAC verified OK\n");
597 }
598 if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout)) {
599 BIO_printf(bio_err, "Error outputting keys and certificates\n");
600 ERR_print_errors(bio_err);
601 goto end;
602 }
603 ret = 0;
604end:
605 if (p12)
606 PKCS12_free(p12);
607 BIO_free(in);
608 BIO_free_all(out);
609 if (canames)
610 sk_OPENSSL_STRING_free(canames);
611 free(passin);
612 free(passout);
613
614 return (ret);
615}
616
617int
618dump_certs_keys_p12(BIO * out, PKCS12 * p12, char *pass,
619 int passlen, int options, char *pempass)
620{
621 STACK_OF(PKCS7) * asafes = NULL;
622 STACK_OF(PKCS12_SAFEBAG) * bags;
623 int i, bagnid;
624 int ret = 0;
625 PKCS7 *p7;
626
627 if (!(asafes = PKCS12_unpack_authsafes(p12)))
628 return 0;
629 for (i = 0; i < sk_PKCS7_num(asafes); i++) {
630 p7 = sk_PKCS7_value(asafes, i);
631 bagnid = OBJ_obj2nid(p7->type);
632 if (bagnid == NID_pkcs7_data) {
633 bags = PKCS12_unpack_p7data(p7);
634 if (options & INFO)
635 BIO_printf(bio_err, "PKCS7 Data\n");
636 } else if (bagnid == NID_pkcs7_encrypted) {
637 if (options & INFO) {
638 BIO_printf(bio_err, "PKCS7 Encrypted data: ");
639 alg_print(bio_err,
640 p7->d.encrypted->enc_data->algorithm);
641 }
642 bags = PKCS12_unpack_p7encdata(p7, pass, passlen);
643 } else
644 continue;
645 if (!bags)
646 goto err;
647 if (!dump_certs_pkeys_bags(out, bags, pass, passlen,
648 options, pempass)) {
649 sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
650 goto err;
651 }
652 sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
653 bags = NULL;
654 }
655 ret = 1;
656
657err:
658
659 if (asafes)
660 sk_PKCS7_pop_free(asafes, PKCS7_free);
661 return ret;
662}
663
664int
665dump_certs_pkeys_bags(BIO * out, STACK_OF(PKCS12_SAFEBAG) * bags,
666 char *pass, int passlen, int options, char *pempass)
667{
668 int i;
669 for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) {
670 if (!dump_certs_pkeys_bag(out,
671 sk_PKCS12_SAFEBAG_value(bags, i),
672 pass, passlen,
673 options, pempass))
674 return 0;
675 }
676 return 1;
677}
678
679int
680dump_certs_pkeys_bag(BIO * out, PKCS12_SAFEBAG * bag, char *pass,
681 int passlen, int options, char *pempass)
682{
683 EVP_PKEY *pkey;
684 PKCS8_PRIV_KEY_INFO *p8;
685 X509 *x509;
686
687 switch (M_PKCS12_bag_type(bag)) {
688 case NID_keyBag:
689 if (options & INFO)
690 BIO_printf(bio_err, "Key bag\n");
691 if (options & NOKEYS)
692 return 1;
693 print_attribs(out, bag->attrib, "Bag Attributes");
694 p8 = bag->value.keybag;
695 if (!(pkey = EVP_PKCS82PKEY(p8)))
696 return 0;
697 print_attribs(out, p8->attributes, "Key Attributes");
698 PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
699 EVP_PKEY_free(pkey);
700 break;
701
702 case NID_pkcs8ShroudedKeyBag:
703 if (options & INFO) {
704 BIO_printf(bio_err, "Shrouded Keybag: ");
705 alg_print(bio_err, bag->value.shkeybag->algor);
706 }
707 if (options & NOKEYS)
708 return 1;
709 print_attribs(out, bag->attrib, "Bag Attributes");
710 if (!(p8 = PKCS12_decrypt_skey(bag, pass, passlen)))
711 return 0;
712 if (!(pkey = EVP_PKCS82PKEY(p8))) {
713 PKCS8_PRIV_KEY_INFO_free(p8);
714 return 0;
715 }
716 print_attribs(out, p8->attributes, "Key Attributes");
717 PKCS8_PRIV_KEY_INFO_free(p8);
718 PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
719 EVP_PKEY_free(pkey);
720 break;
721
722 case NID_certBag:
723 if (options & INFO)
724 BIO_printf(bio_err, "Certificate bag\n");
725 if (options & NOCERTS)
726 return 1;
727 if (PKCS12_get_attr(bag, NID_localKeyID)) {
728 if (options & CACERTS)
729 return 1;
730 } else if (options & CLCERTS)
731 return 1;
732 print_attribs(out, bag->attrib, "Bag Attributes");
733 if (M_PKCS12_cert_bag_type(bag) != NID_x509Certificate)
734 return 1;
735 if (!(x509 = PKCS12_certbag2x509(bag)))
736 return 0;
737 dump_cert_text(out, x509);
738 PEM_write_bio_X509(out, x509);
739 X509_free(x509);
740 break;
741
742 case NID_safeContentsBag:
743 if (options & INFO)
744 BIO_printf(bio_err, "Safe Contents bag\n");
745 print_attribs(out, bag->attrib, "Bag Attributes");
746 return dump_certs_pkeys_bags(out, bag->value.safes, pass,
747 passlen, options, pempass);
748
749 default:
750 BIO_printf(bio_err, "Warning unsupported bag type: ");
751 i2a_ASN1_OBJECT(bio_err, bag->type);
752 BIO_printf(bio_err, "\n");
753 return 1;
754 break;
755 }
756 return 1;
757}
758
759/* Given a single certificate return a verified chain or NULL if error */
760
761/* Hope this is OK .... */
762
763int
764get_cert_chain(X509 * cert, X509_STORE * store, STACK_OF(X509) ** chain)
765{
766 X509_STORE_CTX store_ctx;
767 STACK_OF(X509) * chn;
768 int i = 0;
769
770 /*
771 * FIXME: Should really check the return status of
772 * X509_STORE_CTX_init for an error, but how that fits into the
773 * return value of this function is less obvious.
774 */
775 X509_STORE_CTX_init(&store_ctx, store, cert, NULL);
776 if (X509_verify_cert(&store_ctx) <= 0) {
777 i = X509_STORE_CTX_get_error(&store_ctx);
778 if (i == 0)
779 /*
780 * avoid returning 0 if X509_verify_cert() did not
781 * set an appropriate error value in the context
782 */
783 i = -1;
784 chn = NULL;
785 goto err;
786 } else
787 chn = X509_STORE_CTX_get1_chain(&store_ctx);
788err:
789 X509_STORE_CTX_cleanup(&store_ctx);
790 *chain = chn;
791
792 return i;
793}
794
795int
796alg_print(BIO * x, X509_ALGOR * alg)
797{
798 PBEPARAM *pbe;
799 const unsigned char *p;
800 p = alg->parameter->value.sequence->data;
801 pbe = d2i_PBEPARAM(NULL, &p, alg->parameter->value.sequence->length);
802 if (!pbe)
803 return 1;
804 BIO_printf(bio_err, "%s, Iteration %ld\n",
805 OBJ_nid2ln(OBJ_obj2nid(alg->algorithm)),
806 ASN1_INTEGER_get(pbe->iter));
807 PBEPARAM_free(pbe);
808 return 1;
809}
810
811/* Load all certificates from a given file */
812
813int
814cert_load(BIO * in, STACK_OF(X509) * sk)
815{
816 int ret;
817 X509 *cert;
818 ret = 0;
819 while ((cert = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
820 ret = 1;
821 sk_X509_push(sk, cert);
822 }
823 if (ret)
824 ERR_clear_error();
825 return ret;
826}
827
828/* Generalised attribute print: handle PKCS#8 and bag attributes */
829
830int
831print_attribs(BIO * out, STACK_OF(X509_ATTRIBUTE) * attrlst, const char *name)
832{
833 X509_ATTRIBUTE *attr;
834 ASN1_TYPE *av;
835 char *value;
836 int i, attr_nid;
837 if (!attrlst) {
838 BIO_printf(out, "%s: <No Attributes>\n", name);
839 return 1;
840 }
841 if (!sk_X509_ATTRIBUTE_num(attrlst)) {
842 BIO_printf(out, "%s: <Empty Attributes>\n", name);
843 return 1;
844 }
845 BIO_printf(out, "%s\n", name);
846 for (i = 0; i < sk_X509_ATTRIBUTE_num(attrlst); i++) {
847 attr = sk_X509_ATTRIBUTE_value(attrlst, i);
848 attr_nid = OBJ_obj2nid(attr->object);
849 BIO_printf(out, " ");
850 if (attr_nid == NID_undef) {
851 i2a_ASN1_OBJECT(out, attr->object);
852 BIO_printf(out, ": ");
853 } else
854 BIO_printf(out, "%s: ", OBJ_nid2ln(attr_nid));
855
856 if (sk_ASN1_TYPE_num(attr->value.set)) {
857 av = sk_ASN1_TYPE_value(attr->value.set, 0);
858 switch (av->type) {
859 case V_ASN1_BMPSTRING:
860 value = OPENSSL_uni2asc(av->value.bmpstring->data,
861 av->value.bmpstring->length);
862 BIO_printf(out, "%s\n", value);
863 free(value);
864 break;
865
866 case V_ASN1_OCTET_STRING:
867 hex_prin(out, av->value.octet_string->data,
868 av->value.octet_string->length);
869 BIO_printf(out, "\n");
870 break;
871
872 case V_ASN1_BIT_STRING:
873 hex_prin(out, av->value.bit_string->data,
874 av->value.bit_string->length);
875 BIO_printf(out, "\n");
876 break;
877
878 default:
879 BIO_printf(out, "<Unsupported tag %d>\n", av->type);
880 break;
881 }
882 } else
883 BIO_printf(out, "<No Values>\n");
884 }
885 return 1;
886}
887
888void
889hex_prin(BIO * out, unsigned char *buf, int len)
890{
891 int i;
892 for (i = 0; i < len; i++)
893 BIO_printf(out, "%02X ", buf[i]);
894}
895
896static int
897set_pbe(BIO * err, int *ppbe, const char *str)
898{
899 if (!str)
900 return 0;
901 if (!strcmp(str, "NONE")) {
902 *ppbe = -1;
903 return 1;
904 }
905 *ppbe = OBJ_txt2nid(str);
906 if (*ppbe == NID_undef) {
907 BIO_printf(bio_err, "Unknown PBE algorithm %s\n", str);
908 return 0;
909 }
910 return 1;
911}
912
913#endif
diff --git a/src/usr.bin/openssl/pkcs7.c b/src/usr.bin/openssl/pkcs7.c
new file mode 100644
index 0000000000..2c2af168a9
--- /dev/null
+++ b/src/usr.bin/openssl/pkcs7.c
@@ -0,0 +1,284 @@
1/* $OpenBSD: pkcs7.c,v 1.1 2014/08/26 17:47:25 jsing 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#include <stdlib.h>
61#include <string.h>
62#include <time.h>
63
64#include "apps.h"
65
66#include <openssl/err.h>
67#include <openssl/evp.h>
68#include <openssl/objects.h>
69#include <openssl/pem.h>
70#include <openssl/pkcs7.h>
71#include <openssl/x509.h>
72
73/* -inform arg - input format - default PEM (DER or PEM)
74 * -outform arg - output format - default PEM
75 * -in arg - input file - default stdin
76 * -out arg - output file - default stdout
77 * -print_certs
78 */
79
80int pkcs7_main(int, char **);
81
82int
83pkcs7_main(int argc, char **argv)
84{
85 PKCS7 *p7 = NULL;
86 int i, badops = 0;
87 BIO *in = NULL, *out = NULL;
88 int informat, outformat;
89 char *infile, *outfile, *prog;
90 int print_certs = 0, text = 0, noout = 0, p7_print = 0;
91 int ret = 1;
92#ifndef OPENSSL_NO_ENGINE
93 char *engine = NULL;
94#endif
95
96 infile = NULL;
97 outfile = NULL;
98 informat = FORMAT_PEM;
99 outformat = FORMAT_PEM;
100
101 prog = argv[0];
102 argc--;
103 argv++;
104 while (argc >= 1) {
105 if (strcmp(*argv, "-inform") == 0) {
106 if (--argc < 1)
107 goto bad;
108 informat = str2fmt(*(++argv));
109 } else if (strcmp(*argv, "-outform") == 0) {
110 if (--argc < 1)
111 goto bad;
112 outformat = str2fmt(*(++argv));
113 } else if (strcmp(*argv, "-in") == 0) {
114 if (--argc < 1)
115 goto bad;
116 infile = *(++argv);
117 } else if (strcmp(*argv, "-out") == 0) {
118 if (--argc < 1)
119 goto bad;
120 outfile = *(++argv);
121 } else if (strcmp(*argv, "-noout") == 0)
122 noout = 1;
123 else if (strcmp(*argv, "-text") == 0)
124 text = 1;
125 else if (strcmp(*argv, "-print") == 0)
126 p7_print = 1;
127 else if (strcmp(*argv, "-print_certs") == 0)
128 print_certs = 1;
129#ifndef OPENSSL_NO_ENGINE
130 else if (strcmp(*argv, "-engine") == 0) {
131 if (--argc < 1)
132 goto bad;
133 engine = *(++argv);
134 }
135#endif
136 else {
137 BIO_printf(bio_err, "unknown option %s\n", *argv);
138 badops = 1;
139 break;
140 }
141 argc--;
142 argv++;
143 }
144
145 if (badops) {
146bad:
147 BIO_printf(bio_err, "%s [options] <infile >outfile\n", prog);
148 BIO_printf(bio_err, "where options are\n");
149 BIO_printf(bio_err, " -inform arg input format - DER or PEM\n");
150 BIO_printf(bio_err, " -outform arg output format - DER or PEM\n");
151 BIO_printf(bio_err, " -in arg input file\n");
152 BIO_printf(bio_err, " -out arg output file\n");
153 BIO_printf(bio_err, " -print_certs print any certs or crl in the input\n");
154 BIO_printf(bio_err, " -text print full details of certificates\n");
155 BIO_printf(bio_err, " -noout don't output encoded data\n");
156#ifndef OPENSSL_NO_ENGINE
157 BIO_printf(bio_err, " -engine e use engine e, possibly a hardware device.\n");
158#endif
159 ret = 1;
160 goto end;
161 }
162 ERR_load_crypto_strings();
163
164#ifndef OPENSSL_NO_ENGINE
165 setup_engine(bio_err, engine, 0);
166#endif
167
168 in = BIO_new(BIO_s_file());
169 out = BIO_new(BIO_s_file());
170 if ((in == NULL) || (out == NULL)) {
171 ERR_print_errors(bio_err);
172 goto end;
173 }
174 if (infile == NULL)
175 BIO_set_fp(in, stdin, BIO_NOCLOSE);
176 else {
177 if (BIO_read_filename(in, infile) <= 0)
178 if (in == NULL) {
179 perror(infile);
180 goto end;
181 }
182 }
183
184 if (informat == FORMAT_ASN1)
185 p7 = d2i_PKCS7_bio(in, NULL);
186 else if (informat == FORMAT_PEM)
187 p7 = PEM_read_bio_PKCS7(in, NULL, NULL, NULL);
188 else {
189 BIO_printf(bio_err, "bad input format specified for pkcs7 object\n");
190 goto end;
191 }
192 if (p7 == NULL) {
193 BIO_printf(bio_err, "unable to load PKCS7 object\n");
194 ERR_print_errors(bio_err);
195 goto end;
196 }
197 if (outfile == NULL) {
198 BIO_set_fp(out, stdout, BIO_NOCLOSE);
199 } else {
200 if (BIO_write_filename(out, outfile) <= 0) {
201 perror(outfile);
202 goto end;
203 }
204 }
205
206 if (p7_print)
207 PKCS7_print_ctx(out, p7, 0, NULL);
208
209 if (print_certs) {
210 STACK_OF(X509) * certs = NULL;
211 STACK_OF(X509_CRL) * crls = NULL;
212
213 i = OBJ_obj2nid(p7->type);
214 switch (i) {
215 case NID_pkcs7_signed:
216 certs = p7->d.sign->cert;
217 crls = p7->d.sign->crl;
218 break;
219 case NID_pkcs7_signedAndEnveloped:
220 certs = p7->d.signed_and_enveloped->cert;
221 crls = p7->d.signed_and_enveloped->crl;
222 break;
223 default:
224 break;
225 }
226
227 if (certs != NULL) {
228 X509 *x;
229
230 for (i = 0; i < sk_X509_num(certs); i++) {
231 x = sk_X509_value(certs, i);
232 if (text)
233 X509_print(out, x);
234 else
235 dump_cert_text(out, x);
236
237 if (!noout)
238 PEM_write_bio_X509(out, x);
239 BIO_puts(out, "\n");
240 }
241 }
242 if (crls != NULL) {
243 X509_CRL *crl;
244
245 for (i = 0; i < sk_X509_CRL_num(crls); i++) {
246 crl = sk_X509_CRL_value(crls, i);
247
248 X509_CRL_print(out, crl);
249
250 if (!noout)
251 PEM_write_bio_X509_CRL(out, crl);
252 BIO_puts(out, "\n");
253 }
254 }
255 ret = 0;
256 goto end;
257 }
258 if (!noout) {
259 if (outformat == FORMAT_ASN1)
260 i = i2d_PKCS7_bio(out, p7);
261 else if (outformat == FORMAT_PEM)
262 i = PEM_write_bio_PKCS7(out, p7);
263 else {
264 BIO_printf(bio_err, "bad output format specified for outfile\n");
265 goto end;
266 }
267
268 if (!i) {
269 BIO_printf(bio_err, "unable to write pkcs7 object\n");
270 ERR_print_errors(bio_err);
271 goto end;
272 }
273 }
274 ret = 0;
275end:
276 if (p7 != NULL)
277 PKCS7_free(p7);
278 if (in != NULL)
279 BIO_free(in);
280 if (out != NULL)
281 BIO_free_all(out);
282
283 return (ret);
284}
diff --git a/src/usr.bin/openssl/pkcs8.c b/src/usr.bin/openssl/pkcs8.c
new file mode 100644
index 0000000000..1715fe1d6b
--- /dev/null
+++ b/src/usr.bin/openssl/pkcs8.c
@@ -0,0 +1,367 @@
1/* $OpenBSD: pkcs8.c,v 1.1 2014/08/26 17:47:25 jsing Exp $ */
2/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3 * project 1999-2004.
4 */
5/* ====================================================================
6 * Copyright (c) 1999 The OpenSSL Project. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
19 *
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24 *
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * licensing@OpenSSL.org.
29 *
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
33 *
34 * 6. Redistributions of any form whatsoever must retain the following
35 * acknowledgment:
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
52 *
53 * This product includes cryptographic software written by Eric Young
54 * (eay@cryptsoft.com). This product includes software written by Tim
55 * Hudson (tjh@cryptsoft.com).
56 *
57 */
58
59#include <stdio.h>
60#include <string.h>
61
62#include "apps.h"
63
64#include <openssl/err.h>
65#include <openssl/evp.h>
66#include <openssl/pem.h>
67#include <openssl/pkcs12.h>
68
69int pkcs8_main(int, char **);
70
71int
72pkcs8_main(int argc, char **argv)
73{
74 ENGINE *e = NULL;
75 char **args, *infile = NULL, *outfile = NULL;
76 char *passargin = NULL, *passargout = NULL;
77 BIO *in = NULL, *out = NULL;
78 int topk8 = 0;
79 int pbe_nid = -1;
80 const EVP_CIPHER *cipher = NULL;
81 int iter = PKCS12_DEFAULT_ITER;
82 int informat, outformat;
83 int p8_broken = PKCS8_OK;
84 int nocrypt = 0;
85 X509_SIG *p8 = NULL;
86 PKCS8_PRIV_KEY_INFO *p8inf = NULL;
87 EVP_PKEY *pkey = NULL;
88 char pass[50], *passin = NULL, *passout = NULL, *p8pass = NULL;
89 int badarg = 0;
90 int ret = 1;
91#ifndef OPENSSL_NO_ENGINE
92 char *engine = NULL;
93#endif
94
95 informat = FORMAT_PEM;
96 outformat = FORMAT_PEM;
97
98 ERR_load_crypto_strings();
99 OpenSSL_add_all_algorithms();
100 args = argv + 1;
101 while (!badarg && *args && *args[0] == '-') {
102 if (!strcmp(*args, "-v2")) {
103 if (args[1]) {
104 args++;
105 cipher = EVP_get_cipherbyname(*args);
106 if (!cipher) {
107 BIO_printf(bio_err,
108 "Unknown cipher %s\n", *args);
109 badarg = 1;
110 }
111 } else
112 badarg = 1;
113 } else if (!strcmp(*args, "-v1")) {
114 if (args[1]) {
115 args++;
116 pbe_nid = OBJ_txt2nid(*args);
117 if (pbe_nid == NID_undef) {
118 BIO_printf(bio_err,
119 "Unknown PBE algorithm %s\n", *args);
120 badarg = 1;
121 }
122 } else
123 badarg = 1;
124 } else if (!strcmp(*args, "-inform")) {
125 if (args[1]) {
126 args++;
127 informat = str2fmt(*args);
128 } else
129 badarg = 1;
130 } else if (!strcmp(*args, "-outform")) {
131 if (args[1]) {
132 args++;
133 outformat = str2fmt(*args);
134 } else
135 badarg = 1;
136 } else if (!strcmp(*args, "-topk8"))
137 topk8 = 1;
138 else if (!strcmp(*args, "-noiter"))
139 iter = 1;
140 else if (!strcmp(*args, "-nocrypt"))
141 nocrypt = 1;
142 else if (!strcmp(*args, "-nooct"))
143 p8_broken = PKCS8_NO_OCTET;
144 else if (!strcmp(*args, "-nsdb"))
145 p8_broken = PKCS8_NS_DB;
146 else if (!strcmp(*args, "-embed"))
147 p8_broken = PKCS8_EMBEDDED_PARAM;
148 else if (!strcmp(*args, "-passin")) {
149 if (!args[1])
150 goto bad;
151 passargin = *(++args);
152 } else if (!strcmp(*args, "-passout")) {
153 if (!args[1])
154 goto bad;
155 passargout = *(++args);
156 }
157#ifndef OPENSSL_NO_ENGINE
158 else if (strcmp(*args, "-engine") == 0) {
159 if (!args[1])
160 goto bad;
161 engine = *(++args);
162 }
163#endif
164 else if (!strcmp(*args, "-in")) {
165 if (args[1]) {
166 args++;
167 infile = *args;
168 } else
169 badarg = 1;
170 } else if (!strcmp(*args, "-out")) {
171 if (args[1]) {
172 args++;
173 outfile = *args;
174 } else
175 badarg = 1;
176 } else
177 badarg = 1;
178 args++;
179 }
180
181 if (badarg) {
182bad:
183 BIO_printf(bio_err, "Usage pkcs8 [options]\n");
184 BIO_printf(bio_err, "where options are\n");
185 BIO_printf(bio_err, "-in file input file\n");
186 BIO_printf(bio_err, "-inform X input format (DER or PEM)\n");
187 BIO_printf(bio_err, "-passin arg input file pass phrase source\n");
188 BIO_printf(bio_err, "-outform X output format (DER or PEM)\n");
189 BIO_printf(bio_err, "-out file output file\n");
190 BIO_printf(bio_err, "-passout arg output file pass phrase source\n");
191 BIO_printf(bio_err, "-topk8 output PKCS8 file\n");
192 BIO_printf(bio_err, "-nooct use (nonstandard) no octet format\n");
193 BIO_printf(bio_err, "-embed use (nonstandard) embedded DSA parameters format\n");
194 BIO_printf(bio_err, "-nsdb use (nonstandard) DSA Netscape DB format\n");
195 BIO_printf(bio_err, "-noiter use 1 as iteration count\n");
196 BIO_printf(bio_err, "-nocrypt use or expect unencrypted private key\n");
197 BIO_printf(bio_err, "-v2 alg use PKCS#5 v2.0 and cipher \"alg\"\n");
198 BIO_printf(bio_err, "-v1 obj use PKCS#5 v1.5 and cipher \"alg\"\n");
199#ifndef OPENSSL_NO_ENGINE
200 BIO_printf(bio_err, " -engine e use engine e, possibly a hardware device.\n");
201#endif
202 goto end;
203 }
204#ifndef OPENSSL_NO_ENGINE
205 e = setup_engine(bio_err, engine, 0);
206#endif
207
208 if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
209 BIO_printf(bio_err, "Error getting passwords\n");
210 goto end;
211 }
212 if ((pbe_nid == -1) && !cipher)
213 pbe_nid = NID_pbeWithMD5AndDES_CBC;
214
215 if (infile) {
216 if (!(in = BIO_new_file(infile, "rb"))) {
217 BIO_printf(bio_err,
218 "Can't open input file %s\n", infile);
219 goto end;
220 }
221 } else
222 in = BIO_new_fp(stdin, BIO_NOCLOSE);
223
224 if (outfile) {
225 if (!(out = BIO_new_file(outfile, "wb"))) {
226 BIO_printf(bio_err,
227 "Can't open output file %s\n", outfile);
228 goto end;
229 }
230 } else {
231 out = BIO_new_fp(stdout, BIO_NOCLOSE);
232 }
233 if (topk8) {
234 pkey = load_key(bio_err, infile, informat, 1,
235 passin, e, "key");
236 if (!pkey)
237 goto end;
238 if (!(p8inf = EVP_PKEY2PKCS8_broken(pkey, p8_broken))) {
239 BIO_printf(bio_err, "Error converting key\n");
240 ERR_print_errors(bio_err);
241 goto end;
242 }
243 if (nocrypt) {
244 if (outformat == FORMAT_PEM)
245 PEM_write_bio_PKCS8_PRIV_KEY_INFO(out, p8inf);
246 else if (outformat == FORMAT_ASN1)
247 i2d_PKCS8_PRIV_KEY_INFO_bio(out, p8inf);
248 else {
249 BIO_printf(bio_err, "Bad format specified for key\n");
250 goto end;
251 }
252 } else {
253 if (passout)
254 p8pass = passout;
255 else {
256 p8pass = pass;
257 if (EVP_read_pw_string(pass, sizeof pass, "Enter Encryption Password:", 1))
258 goto end;
259 }
260 if (!(p8 = PKCS8_encrypt(pbe_nid, cipher,
261 p8pass, strlen(p8pass),
262 NULL, 0, iter, p8inf))) {
263 BIO_printf(bio_err, "Error encrypting key\n");
264 ERR_print_errors(bio_err);
265 goto end;
266 }
267 if (outformat == FORMAT_PEM)
268 PEM_write_bio_PKCS8(out, p8);
269 else if (outformat == FORMAT_ASN1)
270 i2d_PKCS8_bio(out, p8);
271 else {
272 BIO_printf(bio_err, "Bad format specified for key\n");
273 goto end;
274 }
275 }
276
277 ret = 0;
278 goto end;
279 }
280 if (nocrypt) {
281 if (informat == FORMAT_PEM)
282 p8inf = PEM_read_bio_PKCS8_PRIV_KEY_INFO(in, NULL, NULL, NULL);
283 else if (informat == FORMAT_ASN1)
284 p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(in, NULL);
285 else {
286 BIO_printf(bio_err, "Bad format specified for key\n");
287 goto end;
288 }
289 } else {
290 if (informat == FORMAT_PEM)
291 p8 = PEM_read_bio_PKCS8(in, NULL, NULL, NULL);
292 else if (informat == FORMAT_ASN1)
293 p8 = d2i_PKCS8_bio(in, NULL);
294 else {
295 BIO_printf(bio_err, "Bad format specified for key\n");
296 goto end;
297 }
298
299 if (!p8) {
300 BIO_printf(bio_err, "Error reading key\n");
301 ERR_print_errors(bio_err);
302 goto end;
303 }
304 if (passin)
305 p8pass = passin;
306 else {
307 p8pass = pass;
308 EVP_read_pw_string(pass, sizeof pass, "Enter Password:", 0);
309 }
310 p8inf = PKCS8_decrypt(p8, p8pass, strlen(p8pass));
311 }
312
313 if (!p8inf) {
314 BIO_printf(bio_err, "Error decrypting key\n");
315 ERR_print_errors(bio_err);
316 goto end;
317 }
318 if (!(pkey = EVP_PKCS82PKEY(p8inf))) {
319 BIO_printf(bio_err, "Error converting key\n");
320 ERR_print_errors(bio_err);
321 goto end;
322 }
323 if (p8inf->broken) {
324 BIO_printf(bio_err, "Warning: broken key encoding: ");
325 switch (p8inf->broken) {
326 case PKCS8_NO_OCTET:
327 BIO_printf(bio_err, "No Octet String in PrivateKey\n");
328 break;
329
330 case PKCS8_EMBEDDED_PARAM:
331 BIO_printf(bio_err, "DSA parameters included in PrivateKey\n");
332 break;
333
334 case PKCS8_NS_DB:
335 BIO_printf(bio_err, "DSA public key include in PrivateKey\n");
336 break;
337
338 case PKCS8_NEG_PRIVKEY:
339 BIO_printf(bio_err, "DSA private key value is negative\n");
340 break;
341
342 default:
343 BIO_printf(bio_err, "Unknown broken type\n");
344 break;
345 }
346 }
347 if (outformat == FORMAT_PEM)
348 PEM_write_bio_PrivateKey(out, pkey, NULL, NULL, 0, NULL, passout);
349 else if (outformat == FORMAT_ASN1)
350 i2d_PrivateKey_bio(out, pkey);
351 else {
352 BIO_printf(bio_err, "Bad format specified for key\n");
353 goto end;
354 }
355 ret = 0;
356
357end:
358 X509_SIG_free(p8);
359 PKCS8_PRIV_KEY_INFO_free(p8inf);
360 EVP_PKEY_free(pkey);
361 BIO_free_all(out);
362 BIO_free(in);
363 free(passin);
364 free(passout);
365
366 return ret;
367}
diff --git a/src/usr.bin/openssl/pkey.c b/src/usr.bin/openssl/pkey.c
new file mode 100644
index 0000000000..7f13bbbf62
--- /dev/null
+++ b/src/usr.bin/openssl/pkey.c
@@ -0,0 +1,235 @@
1/* $OpenBSD: pkey.c,v 1.1 2014/08/26 17:47:25 jsing Exp $ */
2/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3 * project 2006
4 */
5/* ====================================================================
6 * Copyright (c) 2006 The OpenSSL Project. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
19 *
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24 *
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * licensing@OpenSSL.org.
29 *
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
33 *
34 * 6. Redistributions of any form whatsoever must retain the following
35 * acknowledgment:
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
52 *
53 * This product includes cryptographic software written by Eric Young
54 * (eay@cryptsoft.com). This product includes software written by Tim
55 * Hudson (tjh@cryptsoft.com).
56 *
57 */
58
59#include <stdio.h>
60#include <string.h>
61
62#include "apps.h"
63
64#include <openssl/err.h>
65#include <openssl/evp.h>
66#include <openssl/pem.h>
67
68int pkey_main(int, char **);
69
70int
71pkey_main(int argc, char **argv)
72{
73 ENGINE *e = NULL;
74 char **args, *infile = NULL, *outfile = NULL;
75 char *passargin = NULL, *passargout = NULL;
76 BIO *in = NULL, *out = NULL;
77 const EVP_CIPHER *cipher = NULL;
78 int informat, outformat;
79 int pubin = 0, pubout = 0, pubtext = 0, text = 0, noout = 0;
80 EVP_PKEY *pkey = NULL;
81 char *passin = NULL, *passout = NULL;
82 int badarg = 0;
83#ifndef OPENSSL_NO_ENGINE
84 char *engine = NULL;
85#endif
86 int ret = 1;
87
88 informat = FORMAT_PEM;
89 outformat = FORMAT_PEM;
90
91 ERR_load_crypto_strings();
92 OpenSSL_add_all_algorithms();
93 args = argv + 1;
94 while (!badarg && *args && *args[0] == '-') {
95 if (!strcmp(*args, "-inform")) {
96 if (args[1]) {
97 args++;
98 informat = str2fmt(*args);
99 } else
100 badarg = 1;
101 } else if (!strcmp(*args, "-outform")) {
102 if (args[1]) {
103 args++;
104 outformat = str2fmt(*args);
105 } else
106 badarg = 1;
107 } else if (!strcmp(*args, "-passin")) {
108 if (!args[1])
109 goto bad;
110 passargin = *(++args);
111 } else if (!strcmp(*args, "-passout")) {
112 if (!args[1])
113 goto bad;
114 passargout = *(++args);
115 }
116#ifndef OPENSSL_NO_ENGINE
117 else if (strcmp(*args, "-engine") == 0) {
118 if (!args[1])
119 goto bad;
120 engine = *(++args);
121 }
122#endif
123 else if (!strcmp(*args, "-in")) {
124 if (args[1]) {
125 args++;
126 infile = *args;
127 } else
128 badarg = 1;
129 } else if (!strcmp(*args, "-out")) {
130 if (args[1]) {
131 args++;
132 outfile = *args;
133 } else
134 badarg = 1;
135 } else if (strcmp(*args, "-pubin") == 0) {
136 pubin = 1;
137 pubout = 1;
138 pubtext = 1;
139 } else if (strcmp(*args, "-pubout") == 0)
140 pubout = 1;
141 else if (strcmp(*args, "-text_pub") == 0) {
142 pubtext = 1;
143 text = 1;
144 } else if (strcmp(*args, "-text") == 0)
145 text = 1;
146 else if (strcmp(*args, "-noout") == 0)
147 noout = 1;
148 else {
149 cipher = EVP_get_cipherbyname(*args + 1);
150 if (!cipher) {
151 BIO_printf(bio_err, "Unknown cipher %s\n",
152 *args + 1);
153 badarg = 1;
154 }
155 }
156 args++;
157 }
158
159 if (badarg) {
160bad:
161 BIO_printf(bio_err, "Usage pkey [options]\n");
162 BIO_printf(bio_err, "where options are\n");
163 BIO_printf(bio_err, "-in file input file\n");
164 BIO_printf(bio_err, "-inform X input format (DER or PEM)\n");
165 BIO_printf(bio_err, "-passin arg input file pass phrase source\n");
166 BIO_printf(bio_err, "-outform X output format (DER or PEM)\n");
167 BIO_printf(bio_err, "-out file output file\n");
168 BIO_printf(bio_err, "-passout arg output file pass phrase source\n");
169#ifndef OPENSSL_NO_ENGINE
170 BIO_printf(bio_err, "-engine e use engine e, possibly a hardware device.\n");
171#endif
172 return 1;
173 }
174#ifndef OPENSSL_NO_ENGINE
175 e = setup_engine(bio_err, engine, 0);
176#endif
177
178 if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
179 BIO_printf(bio_err, "Error getting passwords\n");
180 goto end;
181 }
182 if (outfile) {
183 if (!(out = BIO_new_file(outfile, "wb"))) {
184 BIO_printf(bio_err,
185 "Can't open output file %s\n", outfile);
186 goto end;
187 }
188 } else {
189 out = BIO_new_fp(stdout, BIO_NOCLOSE);
190 }
191
192 if (pubin)
193 pkey = load_pubkey(bio_err, infile, informat, 1,
194 passin, e, "Public Key");
195 else
196 pkey = load_key(bio_err, infile, informat, 1,
197 passin, e, "key");
198 if (!pkey)
199 goto end;
200
201 if (!noout) {
202 if (outformat == FORMAT_PEM) {
203 if (pubout)
204 PEM_write_bio_PUBKEY(out, pkey);
205 else
206 PEM_write_bio_PrivateKey(out, pkey, cipher,
207 NULL, 0, NULL, passout);
208 } else if (outformat == FORMAT_ASN1) {
209 if (pubout)
210 i2d_PUBKEY_bio(out, pkey);
211 else
212 i2d_PrivateKey_bio(out, pkey);
213 } else {
214 BIO_printf(bio_err, "Bad format specified for key\n");
215 goto end;
216 }
217
218 }
219 if (text) {
220 if (pubtext)
221 EVP_PKEY_print_public(out, pkey, 0, NULL);
222 else
223 EVP_PKEY_print_private(out, pkey, 0, NULL);
224 }
225 ret = 0;
226
227end:
228 EVP_PKEY_free(pkey);
229 BIO_free_all(out);
230 BIO_free(in);
231 free(passin);
232 free(passout);
233
234 return ret;
235}
diff --git a/src/usr.bin/openssl/pkeyparam.c b/src/usr.bin/openssl/pkeyparam.c
new file mode 100644
index 0000000000..c48f1a95dd
--- /dev/null
+++ b/src/usr.bin/openssl/pkeyparam.c
@@ -0,0 +1,173 @@
1/* $OpenBSD: pkeyparam.c,v 1.1 2014/08/26 17:47:25 jsing Exp $ */
2/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3 * project 2006
4 */
5/* ====================================================================
6 * Copyright (c) 2006 The OpenSSL Project. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
19 *
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24 *
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * licensing@OpenSSL.org.
29 *
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
33 *
34 * 6. Redistributions of any form whatsoever must retain the following
35 * acknowledgment:
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
52 *
53 * This product includes cryptographic software written by Eric Young
54 * (eay@cryptsoft.com). This product includes software written by Tim
55 * Hudson (tjh@cryptsoft.com).
56 *
57 */
58
59#include <stdio.h>
60#include <string.h>
61
62#include "apps.h"
63
64#include <openssl/err.h>
65#include <openssl/evp.h>
66#include <openssl/pem.h>
67
68int pkeyparam_main(int, char **);
69
70int
71pkeyparam_main(int argc, char **argv)
72{
73 char **args, *infile = NULL, *outfile = NULL;
74 BIO *in = NULL, *out = NULL;
75 int text = 0, noout = 0;
76 EVP_PKEY *pkey = NULL;
77 int badarg = 0;
78#ifndef OPENSSL_NO_ENGINE
79 char *engine = NULL;
80#endif
81 int ret = 1;
82
83 ERR_load_crypto_strings();
84 OpenSSL_add_all_algorithms();
85 args = argv + 1;
86 while (!badarg && *args && *args[0] == '-') {
87 if (!strcmp(*args, "-in")) {
88 if (args[1]) {
89 args++;
90 infile = *args;
91 } else
92 badarg = 1;
93 } else if (!strcmp(*args, "-out")) {
94 if (args[1]) {
95 args++;
96 outfile = *args;
97 } else
98 badarg = 1;
99 }
100#ifndef OPENSSL_NO_ENGINE
101 else if (strcmp(*args, "-engine") == 0) {
102 if (!args[1])
103 goto bad;
104 engine = *(++args);
105 }
106#endif
107
108 else if (strcmp(*args, "-text") == 0)
109 text = 1;
110 else if (strcmp(*args, "-noout") == 0)
111 noout = 1;
112 args++;
113 }
114
115 if (badarg) {
116#ifndef OPENSSL_NO_ENGINE
117bad:
118#endif
119 BIO_printf(bio_err, "Usage pkeyparam [options]\n");
120 BIO_printf(bio_err, "where options are\n");
121 BIO_printf(bio_err, "-in file input file\n");
122 BIO_printf(bio_err, "-out file output file\n");
123 BIO_printf(bio_err, "-text print parameters as text\n");
124 BIO_printf(bio_err, "-noout don't output encoded parameters\n");
125#ifndef OPENSSL_NO_ENGINE
126 BIO_printf(bio_err, "-engine e use engine e, possibly a hardware device.\n");
127#endif
128 return 1;
129 }
130#ifndef OPENSSL_NO_ENGINE
131 setup_engine(bio_err, engine, 0);
132#endif
133
134 if (infile) {
135 if (!(in = BIO_new_file(infile, "r"))) {
136 BIO_printf(bio_err,
137 "Can't open input file %s\n", infile);
138 goto end;
139 }
140 } else
141 in = BIO_new_fp(stdin, BIO_NOCLOSE);
142
143 if (outfile) {
144 if (!(out = BIO_new_file(outfile, "w"))) {
145 BIO_printf(bio_err,
146 "Can't open output file %s\n", outfile);
147 goto end;
148 }
149 } else {
150 out = BIO_new_fp(stdout, BIO_NOCLOSE);
151 }
152
153 pkey = PEM_read_bio_Parameters(in, NULL);
154 if (!pkey) {
155 BIO_printf(bio_err, "Error reading parameters\n");
156 ERR_print_errors(bio_err);
157 goto end;
158 }
159 if (!noout)
160 PEM_write_bio_Parameters(out, pkey);
161
162 if (text)
163 EVP_PKEY_print_params(out, pkey, 0, NULL);
164
165 ret = 0;
166
167end:
168 EVP_PKEY_free(pkey);
169 BIO_free_all(out);
170 BIO_free(in);
171
172 return ret;
173}
diff --git a/src/usr.bin/openssl/pkeyutl.c b/src/usr.bin/openssl/pkeyutl.c
new file mode 100644
index 0000000000..5fff008db6
--- /dev/null
+++ b/src/usr.bin/openssl/pkeyutl.c
@@ -0,0 +1,503 @@
1/* $OpenBSD: pkeyutl.c,v 1.1 2014/08/26 17:47:25 jsing Exp $ */
2/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3 * project 2006.
4 */
5/* ====================================================================
6 * Copyright (c) 2006 The OpenSSL Project. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
19 *
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24 *
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * licensing@OpenSSL.org.
29 *
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
33 *
34 * 6. Redistributions of any form whatsoever must retain the following
35 * acknowledgment:
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
52 *
53 * This product includes cryptographic software written by Eric Young
54 * (eay@cryptsoft.com). This product includes software written by Tim
55 * Hudson (tjh@cryptsoft.com).
56 *
57 */
58
59#include <string.h>
60
61#include "apps.h"
62
63#include <openssl/err.h>
64#include <openssl/evp.h>
65#include <openssl/pem.h>
66
67#define KEY_PRIVKEY 1
68#define KEY_PUBKEY 2
69#define KEY_CERT 3
70
71static void usage(void);
72
73static EVP_PKEY_CTX *init_ctx(int *pkeysize,
74 char *keyfile, int keyform, int key_type,
75 char *passargin, int pkey_op, ENGINE * e);
76
77static int setup_peer(BIO * err, EVP_PKEY_CTX * ctx, int peerform,
78 const char *file);
79
80static int do_keyop(EVP_PKEY_CTX * ctx, int pkey_op,
81 unsigned char *out, size_t * poutlen,
82 unsigned char *in, size_t inlen);
83
84int pkeyutl_main(int argc, char **);
85
86int
87pkeyutl_main(int argc, char **argv)
88{
89 BIO *in = NULL, *out = NULL;
90 char *infile = NULL, *outfile = NULL, *sigfile = NULL;
91 ENGINE *e = NULL;
92 int pkey_op = EVP_PKEY_OP_SIGN, key_type = KEY_PRIVKEY;
93 int keyform = FORMAT_PEM, peerform = FORMAT_PEM;
94 char badarg = 0, rev = 0;
95 char hexdump = 0, asn1parse = 0;
96 EVP_PKEY_CTX *ctx = NULL;
97 char *passargin = NULL;
98 int keysize = -1;
99
100 unsigned char *buf_in = NULL, *buf_out = NULL, *sig = NULL;
101 size_t buf_outlen;
102 int buf_inlen = 0, siglen = -1;
103
104 int ret = 1, rv = -1;
105
106 argc--;
107 argv++;
108
109 ERR_load_crypto_strings();
110 OpenSSL_add_all_algorithms();
111
112 while (argc >= 1) {
113 if (!strcmp(*argv, "-in")) {
114 if (--argc < 1)
115 badarg = 1;
116 else
117 infile = *(++argv);
118 } else if (!strcmp(*argv, "-out")) {
119 if (--argc < 1)
120 badarg = 1;
121 else
122 outfile = *(++argv);
123 } else if (!strcmp(*argv, "-sigfile")) {
124 if (--argc < 1)
125 badarg = 1;
126 else
127 sigfile = *(++argv);
128 } else if (!strcmp(*argv, "-inkey")) {
129 if (--argc < 1)
130 badarg = 1;
131 else {
132 ctx = init_ctx(&keysize,
133 *(++argv), keyform, key_type,
134 passargin, pkey_op, e);
135 if (!ctx) {
136 BIO_puts(bio_err,
137 "Error initializing context\n");
138 ERR_print_errors(bio_err);
139 badarg = 1;
140 }
141 }
142 } else if (!strcmp(*argv, "-peerkey")) {
143 if (--argc < 1)
144 badarg = 1;
145 else if (!setup_peer(bio_err, ctx, peerform, *(++argv)))
146 badarg = 1;
147 } else if (!strcmp(*argv, "-passin")) {
148 if (--argc < 1)
149 badarg = 1;
150 else
151 passargin = *(++argv);
152 } else if (strcmp(*argv, "-peerform") == 0) {
153 if (--argc < 1)
154 badarg = 1;
155 else
156 peerform = str2fmt(*(++argv));
157 } else if (strcmp(*argv, "-keyform") == 0) {
158 if (--argc < 1)
159 badarg = 1;
160 else
161 keyform = str2fmt(*(++argv));
162 }
163#ifndef OPENSSL_NO_ENGINE
164 else if (!strcmp(*argv, "-engine")) {
165 if (--argc < 1)
166 badarg = 1;
167 else
168 e = setup_engine(bio_err, *(++argv), 0);
169 }
170#endif
171 else if (!strcmp(*argv, "-pubin"))
172 key_type = KEY_PUBKEY;
173 else if (!strcmp(*argv, "-certin"))
174 key_type = KEY_CERT;
175 else if (!strcmp(*argv, "-asn1parse"))
176 asn1parse = 1;
177 else if (!strcmp(*argv, "-hexdump"))
178 hexdump = 1;
179 else if (!strcmp(*argv, "-sign"))
180 pkey_op = EVP_PKEY_OP_SIGN;
181 else if (!strcmp(*argv, "-verify"))
182 pkey_op = EVP_PKEY_OP_VERIFY;
183 else if (!strcmp(*argv, "-verifyrecover"))
184 pkey_op = EVP_PKEY_OP_VERIFYRECOVER;
185 else if (!strcmp(*argv, "-rev"))
186 rev = 1;
187 else if (!strcmp(*argv, "-encrypt"))
188 pkey_op = EVP_PKEY_OP_ENCRYPT;
189 else if (!strcmp(*argv, "-decrypt"))
190 pkey_op = EVP_PKEY_OP_DECRYPT;
191 else if (!strcmp(*argv, "-derive"))
192 pkey_op = EVP_PKEY_OP_DERIVE;
193 else if (strcmp(*argv, "-pkeyopt") == 0) {
194 if (--argc < 1)
195 badarg = 1;
196 else if (!ctx) {
197 BIO_puts(bio_err,
198 "-pkeyopt command before -inkey\n");
199 badarg = 1;
200 } else if (pkey_ctrl_string(ctx, *(++argv)) <= 0) {
201 BIO_puts(bio_err, "parameter setting error\n");
202 ERR_print_errors(bio_err);
203 goto end;
204 }
205 } else
206 badarg = 1;
207 if (badarg) {
208 usage();
209 goto end;
210 }
211 argc--;
212 argv++;
213 }
214
215 if (!ctx) {
216 usage();
217 goto end;
218 }
219 if (sigfile && (pkey_op != EVP_PKEY_OP_VERIFY)) {
220 BIO_puts(bio_err, "Signature file specified for non verify\n");
221 goto end;
222 }
223 if (!sigfile && (pkey_op == EVP_PKEY_OP_VERIFY)) {
224 BIO_puts(bio_err, "No signature file specified for verify\n");
225 goto end;
226 }
227
228 if (pkey_op != EVP_PKEY_OP_DERIVE) {
229 if (infile) {
230 if (!(in = BIO_new_file(infile, "rb"))) {
231 BIO_puts(bio_err,
232 "Error Opening Input File\n");
233 ERR_print_errors(bio_err);
234 goto end;
235 }
236 } else
237 in = BIO_new_fp(stdin, BIO_NOCLOSE);
238 }
239 if (outfile) {
240 if (!(out = BIO_new_file(outfile, "wb"))) {
241 BIO_printf(bio_err, "Error Creating Output File\n");
242 ERR_print_errors(bio_err);
243 goto end;
244 }
245 } else {
246 out = BIO_new_fp(stdout, BIO_NOCLOSE);
247 }
248
249 if (sigfile) {
250 BIO *sigbio = BIO_new_file(sigfile, "rb");
251 if (!sigbio) {
252 BIO_printf(bio_err, "Can't open signature file %s\n",
253 sigfile);
254 goto end;
255 }
256 siglen = bio_to_mem(&sig, keysize * 10, sigbio);
257 BIO_free(sigbio);
258 if (siglen <= 0) {
259 BIO_printf(bio_err, "Error reading signature data\n");
260 goto end;
261 }
262 }
263 if (in) {
264 /* Read the input data */
265 buf_inlen = bio_to_mem(&buf_in, keysize * 10, in);
266 if (buf_inlen <= 0) {
267 BIO_printf(bio_err, "Error reading input Data\n");
268 exit(1);
269 }
270 if (rev) {
271 size_t i;
272 unsigned char ctmp;
273 size_t l = (size_t) buf_inlen;
274 for (i = 0; i < l / 2; i++) {
275 ctmp = buf_in[i];
276 buf_in[i] = buf_in[l - 1 - i];
277 buf_in[l - 1 - i] = ctmp;
278 }
279 }
280 }
281 if (pkey_op == EVP_PKEY_OP_VERIFY) {
282 rv = EVP_PKEY_verify(ctx, sig, (size_t) siglen,
283 buf_in, (size_t) buf_inlen);
284 if (rv == 0)
285 BIO_puts(out, "Signature Verification Failure\n");
286 else if (rv == 1)
287 BIO_puts(out, "Signature Verified Successfully\n");
288 if (rv >= 0)
289 goto end;
290 } else {
291 rv = do_keyop(ctx, pkey_op, NULL, (size_t *) & buf_outlen,
292 buf_in, (size_t) buf_inlen);
293 if (rv > 0) {
294 buf_out = malloc(buf_outlen);
295 if (!buf_out)
296 rv = -1;
297 else
298 rv = do_keyop(ctx, pkey_op,
299 buf_out, (size_t *) & buf_outlen,
300 buf_in, (size_t) buf_inlen);
301 }
302 }
303
304 if (rv <= 0) {
305 BIO_printf(bio_err, "Public Key operation error\n");
306 ERR_print_errors(bio_err);
307 goto end;
308 }
309 ret = 0;
310 if (asn1parse) {
311 if (!ASN1_parse_dump(out, buf_out, buf_outlen, 1, -1))
312 ERR_print_errors(bio_err);
313 } else if (hexdump)
314 BIO_dump(out, (char *) buf_out, buf_outlen);
315 else
316 BIO_write(out, buf_out, buf_outlen);
317
318end:
319 if (ctx)
320 EVP_PKEY_CTX_free(ctx);
321 BIO_free(in);
322 BIO_free_all(out);
323 free(buf_in);
324 free(buf_out);
325 free(sig);
326
327 return ret;
328}
329
330static void
331usage()
332{
333 BIO_printf(bio_err, "Usage: pkeyutl [options]\n");
334 BIO_printf(bio_err, "-in file input file\n");
335 BIO_printf(bio_err, "-out file output file\n");
336 BIO_printf(bio_err, "-sigfile file signature file (verify operation only)\n");
337 BIO_printf(bio_err, "-inkey file input key\n");
338 BIO_printf(bio_err, "-keyform arg private key format - default PEM\n");
339 BIO_printf(bio_err, "-pubin input is a public key\n");
340 BIO_printf(bio_err, "-certin input is a certificate carrying a public key\n");
341 BIO_printf(bio_err, "-pkeyopt X:Y public key options\n");
342 BIO_printf(bio_err, "-sign sign with private key\n");
343 BIO_printf(bio_err, "-verify verify with public key\n");
344 BIO_printf(bio_err, "-verifyrecover verify with public key, recover original data\n");
345 BIO_printf(bio_err, "-encrypt encrypt with public key\n");
346 BIO_printf(bio_err, "-decrypt decrypt with private key\n");
347 BIO_printf(bio_err, "-derive derive shared secret\n");
348 BIO_printf(bio_err, "-hexdump hex dump output\n");
349#ifndef OPENSSL_NO_ENGINE
350 BIO_printf(bio_err, "-engine e use engine e, possibly a hardware device.\n");
351#endif
352 BIO_printf(bio_err, "-passin arg pass phrase source\n");
353
354}
355
356static EVP_PKEY_CTX *
357init_ctx(int *pkeysize,
358 char *keyfile, int keyform, int key_type,
359 char *passargin, int pkey_op, ENGINE * e)
360{
361 EVP_PKEY *pkey = NULL;
362 EVP_PKEY_CTX *ctx = NULL;
363 char *passin = NULL;
364 int rv = -1;
365 X509 *x;
366 if (((pkey_op == EVP_PKEY_OP_SIGN) || (pkey_op == EVP_PKEY_OP_DECRYPT)
367 || (pkey_op == EVP_PKEY_OP_DERIVE))
368 && (key_type != KEY_PRIVKEY)) {
369 BIO_printf(bio_err, "A private key is needed for this operation\n");
370 goto end;
371 }
372 if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) {
373 BIO_printf(bio_err, "Error getting password\n");
374 goto end;
375 }
376 switch (key_type) {
377 case KEY_PRIVKEY:
378 pkey = load_key(bio_err, keyfile, keyform, 0,
379 passin, e, "Private Key");
380 break;
381
382 case KEY_PUBKEY:
383 pkey = load_pubkey(bio_err, keyfile, keyform, 0,
384 NULL, e, "Public Key");
385 break;
386
387 case KEY_CERT:
388 x = load_cert(bio_err, keyfile, keyform,
389 NULL, e, "Certificate");
390 if (x) {
391 pkey = X509_get_pubkey(x);
392 X509_free(x);
393 }
394 break;
395
396 }
397
398 *pkeysize = EVP_PKEY_size(pkey);
399
400 if (!pkey)
401 goto end;
402
403 ctx = EVP_PKEY_CTX_new(pkey, e);
404
405 EVP_PKEY_free(pkey);
406
407 if (!ctx)
408 goto end;
409
410 switch (pkey_op) {
411 case EVP_PKEY_OP_SIGN:
412 rv = EVP_PKEY_sign_init(ctx);
413 break;
414
415 case EVP_PKEY_OP_VERIFY:
416 rv = EVP_PKEY_verify_init(ctx);
417 break;
418
419 case EVP_PKEY_OP_VERIFYRECOVER:
420 rv = EVP_PKEY_verify_recover_init(ctx);
421 break;
422
423 case EVP_PKEY_OP_ENCRYPT:
424 rv = EVP_PKEY_encrypt_init(ctx);
425 break;
426
427 case EVP_PKEY_OP_DECRYPT:
428 rv = EVP_PKEY_decrypt_init(ctx);
429 break;
430
431 case EVP_PKEY_OP_DERIVE:
432 rv = EVP_PKEY_derive_init(ctx);
433 break;
434 }
435
436 if (rv <= 0) {
437 EVP_PKEY_CTX_free(ctx);
438 ctx = NULL;
439 }
440end:
441
442 free(passin);
443
444 return ctx;
445
446
447}
448
449static int
450setup_peer(BIO * err, EVP_PKEY_CTX * ctx, int peerform,
451 const char *file)
452{
453 EVP_PKEY *peer = NULL;
454 int ret;
455 if (!ctx) {
456 BIO_puts(err, "-peerkey command before -inkey\n");
457 return 0;
458 }
459 peer = load_pubkey(bio_err, file, peerform, 0, NULL, NULL, "Peer Key");
460
461 if (!peer) {
462 BIO_printf(bio_err, "Error reading peer key %s\n", file);
463 ERR_print_errors(err);
464 return 0;
465 }
466 ret = EVP_PKEY_derive_set_peer(ctx, peer);
467
468 EVP_PKEY_free(peer);
469 if (ret <= 0)
470 ERR_print_errors(err);
471 return ret;
472}
473
474static int
475do_keyop(EVP_PKEY_CTX * ctx, int pkey_op,
476 unsigned char *out, size_t * poutlen,
477 unsigned char *in, size_t inlen)
478{
479 int rv = 0;
480 switch (pkey_op) {
481 case EVP_PKEY_OP_VERIFYRECOVER:
482 rv = EVP_PKEY_verify_recover(ctx, out, poutlen, in, inlen);
483 break;
484
485 case EVP_PKEY_OP_SIGN:
486 rv = EVP_PKEY_sign(ctx, out, poutlen, in, inlen);
487 break;
488
489 case EVP_PKEY_OP_ENCRYPT:
490 rv = EVP_PKEY_encrypt(ctx, out, poutlen, in, inlen);
491 break;
492
493 case EVP_PKEY_OP_DECRYPT:
494 rv = EVP_PKEY_decrypt(ctx, out, poutlen, in, inlen);
495 break;
496
497 case EVP_PKEY_OP_DERIVE:
498 rv = EVP_PKEY_derive(ctx, out, poutlen);
499 break;
500
501 }
502 return rv;
503}
diff --git a/src/usr.bin/openssl/prime.c b/src/usr.bin/openssl/prime.c
new file mode 100644
index 0000000000..e7fb3257d8
--- /dev/null
+++ b/src/usr.bin/openssl/prime.c
@@ -0,0 +1,147 @@
1/* $OpenBSD: prime.c,v 1.1 2014/08/26 17:47:25 jsing Exp $ */
2/* ====================================================================
3 * Copyright (c) 2004 The OpenSSL Project. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 *
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in
14 * the documentation and/or other materials provided with the
15 * distribution.
16 *
17 * 3. All advertising materials mentioning features or use of this
18 * software must display the following acknowledgment:
19 * "This product includes software developed by the OpenSSL Project
20 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
21 *
22 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
23 * endorse or promote products derived from this software without
24 * prior written permission. For written permission, please contact
25 * openssl-core@openssl.org.
26 *
27 * 5. Products derived from this software may not be called "OpenSSL"
28 * nor may "OpenSSL" appear in their names without prior written
29 * permission of the OpenSSL Project.
30 *
31 * 6. Redistributions of any form whatsoever must retain the following
32 * acknowledgment:
33 * "This product includes software developed by the OpenSSL Project
34 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
35 *
36 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
37 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
39 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
40 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
42 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
45 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
47 * OF THE POSSIBILITY OF SUCH DAMAGE.
48 *
49 */
50
51#include <string.h>
52#include <limits.h>
53
54#include "apps.h"
55
56#include <openssl/bn.h>
57
58int prime_main(int, char **);
59
60int
61prime_main(int argc, char **argv)
62{
63 int hex = 0;
64 int checks = 20;
65 int generate = 0;
66 int bits = 0;
67 int safe = 0;
68 BIGNUM *bn = NULL;
69 const char *errstr = NULL;
70 BIO *bio_out;
71
72 --argc;
73 ++argv;
74 while (argc >= 1 && **argv == '-') {
75 if (!strcmp(*argv, "-hex"))
76 hex = 1;
77 else if (!strcmp(*argv, "-generate"))
78 generate = 1;
79 else if (!strcmp(*argv, "-bits")) {
80 if (--argc < 1)
81 goto bad;
82 else
83 bits = strtonum(*(++argv), 0, INT_MAX, &errstr);
84 if (errstr)
85 goto bad;
86 } else if (!strcmp(*argv, "-safe"))
87 safe = 1;
88 else if (!strcmp(*argv, "-checks")) {
89 if (--argc < 1)
90 goto bad;
91 else
92 checks = strtonum(*(++argv), 0, INT_MAX, &errstr);
93 if (errstr)
94 goto bad;
95 } else {
96 BIO_printf(bio_err, "Unknown option '%s'\n", *argv);
97 goto bad;
98 }
99 --argc;
100 ++argv;
101 }
102
103 if (argv[0] == NULL && !generate) {
104 BIO_printf(bio_err, "No prime specified\n");
105 goto bad;
106 }
107 if ((bio_out = BIO_new(BIO_s_file())) != NULL) {
108 BIO_set_fp(bio_out, stdout, BIO_NOCLOSE);
109 }
110 if (generate) {
111 char *s;
112
113 if (!bits) {
114 BIO_printf(bio_err, "Specifiy the number of bits.\n");
115 return 1;
116 }
117 bn = BN_new();
118 BN_generate_prime_ex(bn, bits, safe, NULL, NULL, NULL);
119 s = hex ? BN_bn2hex(bn) : BN_bn2dec(bn);
120 BIO_printf(bio_out, "%s\n", s);
121 free(s);
122 } else {
123 if (hex)
124 BN_hex2bn(&bn, argv[0]);
125 else
126 BN_dec2bn(&bn, argv[0]);
127
128 BN_print(bio_out, bn);
129 BIO_printf(bio_out, " is %sprime\n",
130 BN_is_prime_ex(bn, checks, NULL, NULL) ? "" : "not ");
131 }
132
133 BN_free(bn);
134 BIO_free_all(bio_out);
135
136 return 0;
137
138bad:
139 if (errstr)
140 BIO_printf(bio_err, "invalid argument %s: %s\n", *argv, errstr);
141 else {
142 BIO_printf(bio_err, "options are\n");
143 BIO_printf(bio_err, "%-14s hex\n", "-hex");
144 BIO_printf(bio_err, "%-14s number of checks\n", "-checks <n>");
145 }
146 return 1;
147}
diff --git a/src/usr.bin/openssl/progs.h b/src/usr.bin/openssl/progs.h
new file mode 100644
index 0000000000..6f957c6f7c
--- /dev/null
+++ b/src/usr.bin/openssl/progs.h
@@ -0,0 +1,234 @@
1/* $OpenBSD: progs.h,v 1.1 2014/08/26 17:47:25 jsing Exp $ */
2/* Public domain */
3
4extern int asn1parse_main(int argc, char *argv[]);
5extern int ca_main(int argc, char *argv[]);
6extern int ciphers_main(int argc, char *argv[]);
7extern int cms_main(int argc, char *argv[]);
8extern int crl2pkcs7_main(int argc, char *argv[]);
9extern int crl_main(int argc, char *argv[]);
10extern int dgst_main(int argc, char *argv[]);
11extern int dh_main(int argc, char *argv[]);
12extern int dhparam_main(int argc, char *argv[]);
13extern int dsa_main(int argc, char *argv[]);
14extern int dsaparam_main(int argc, char *argv[]);
15extern int ec_main(int argc, char *argv[]);
16extern int ecparam_main(int argc, char *argv[]);
17extern int enc_main(int argc, char *argv[]);
18extern int engine_main(int argc, char *argv[]);
19extern int errstr_main(int argc, char *argv[]);
20extern int gendh_main(int argc, char *argv[]);
21extern int gendsa_main(int argc, char *argv[]);
22extern int genpkey_main(int argc, char *argv[]);
23extern int genrsa_main(int argc, char *argv[]);
24extern int nseq_main(int argc, char *argv[]);
25extern int ocsp_main(int argc, char *argv[]);
26extern int passwd_main(int argc, char *argv[]);
27extern int pkcs7_main(int argc, char *argv[]);
28extern int pkcs8_main(int argc, char *argv[]);
29extern int pkcs12_main(int argc, char *argv[]);
30extern int pkey_main(int argc, char *argv[]);
31extern int pkeyparam_main(int argc, char *argv[]);
32extern int pkeyutl_main(int argc, char *argv[]);
33extern int prime_main(int argc, char *argv[]);
34extern int rand_main(int argc, char *argv[]);
35extern int req_main(int argc, char *argv[]);
36extern int rsa_main(int argc, char *argv[]);
37extern int rsautl_main(int argc, char *argv[]);
38extern int s_client_main(int argc, char *argv[]);
39extern int s_server_main(int argc, char *argv[]);
40extern int s_time_main(int argc, char *argv[]);
41extern int sess_id_main(int argc, char *argv[]);
42extern int smime_main(int argc, char *argv[]);
43extern int speed_main(int argc, char *argv[]);
44extern int spkac_main(int argc, char *argv[]);
45extern int ts_main(int argc, char *argv[]);
46extern int verify_main(int argc, char *argv[]);
47extern int version_main(int argc, char *argv[]);
48extern int x509_main(int argc, char *argv[]);
49
50#define FUNC_TYPE_GENERAL 1
51#define FUNC_TYPE_MD 2
52#define FUNC_TYPE_CIPHER 3
53#define FUNC_TYPE_PKEY 4
54#define FUNC_TYPE_MD_ALG 5
55#define FUNC_TYPE_CIPHER_ALG 6
56
57typedef struct {
58 int type;
59 const char *name;
60 int (*func)(int argc, char *argv[]);
61} FUNCTION;
62DECLARE_LHASH_OF(FUNCTION);
63
64FUNCTION functions[] = {
65
66 /* General functions. */
67 { FUNC_TYPE_GENERAL, "asn1parse", asn1parse_main },
68 { FUNC_TYPE_GENERAL, "ca", ca_main },
69 { FUNC_TYPE_GENERAL, "ciphers", ciphers_main },
70#ifndef OPENSSL_NO_CMS
71 { FUNC_TYPE_GENERAL, "cms", cms_main },
72#endif
73 { FUNC_TYPE_GENERAL, "crl2pkcs7", crl2pkcs7_main },
74 { FUNC_TYPE_GENERAL, "crl", crl_main },
75 { FUNC_TYPE_GENERAL, "dgst", dgst_main },
76 { FUNC_TYPE_GENERAL, "enc", enc_main },
77#ifndef OPENSSL_NO_ENGINE
78 { FUNC_TYPE_GENERAL, "engine", engine_main },
79#endif
80 { FUNC_TYPE_GENERAL, "errstr", errstr_main },
81 { FUNC_TYPE_GENERAL, "genpkey", genpkey_main },
82 { FUNC_TYPE_GENERAL, "nseq", nseq_main },
83#ifndef OPENSSL_NO_OCSP
84 { FUNC_TYPE_GENERAL, "ocsp", ocsp_main },
85#endif
86 { FUNC_TYPE_GENERAL, "passwd", passwd_main },
87 { FUNC_TYPE_GENERAL, "pkcs7", pkcs7_main },
88 { FUNC_TYPE_GENERAL, "pkcs8", pkcs8_main },
89#if !defined(OPENSSL_NO_DES) && !defined(OPENSSL_NO_SHA1)
90 { FUNC_TYPE_GENERAL, "pkcs12", pkcs12_main },
91#endif
92 { FUNC_TYPE_GENERAL, "pkey", pkey_main },
93 { FUNC_TYPE_GENERAL, "pkeyparam", pkeyparam_main },
94 { FUNC_TYPE_GENERAL, "pkeyutl", pkeyutl_main },
95 { FUNC_TYPE_GENERAL, "prime", prime_main },
96 { FUNC_TYPE_GENERAL, "rand", rand_main },
97 { FUNC_TYPE_GENERAL, "req", req_main },
98 { FUNC_TYPE_GENERAL, "s_client", s_client_main },
99 { FUNC_TYPE_GENERAL, "s_server", s_server_main },
100 { FUNC_TYPE_GENERAL, "s_time", s_time_main },
101 { FUNC_TYPE_GENERAL, "sess_id", sess_id_main },
102 { FUNC_TYPE_GENERAL, "smime", smime_main },
103#ifndef OPENSSL_NO_SPEED
104 { FUNC_TYPE_GENERAL, "speed", speed_main },
105#endif
106 { FUNC_TYPE_GENERAL, "spkac", spkac_main },
107 { FUNC_TYPE_GENERAL, "ts", ts_main },
108 { FUNC_TYPE_GENERAL, "verify", verify_main },
109 { FUNC_TYPE_GENERAL, "version", version_main },
110 { FUNC_TYPE_GENERAL, "x509", x509_main },
111
112#ifndef OPENSSL_NO_DH
113 { FUNC_TYPE_GENERAL, "dh", dh_main },
114 { FUNC_TYPE_GENERAL, "dhparam", dhparam_main },
115 { FUNC_TYPE_GENERAL, "gendh", gendh_main },
116#endif
117#ifndef OPENSSL_NO_DSA
118 { FUNC_TYPE_GENERAL, "dsa", dsa_main },
119 { FUNC_TYPE_GENERAL, "dsaparam", dsaparam_main },
120 { FUNC_TYPE_GENERAL, "gendsa", gendsa_main },
121#endif
122#ifndef OPENSSL_NO_EC
123 { FUNC_TYPE_GENERAL, "ec", ec_main },
124 { FUNC_TYPE_GENERAL, "ecparam", ecparam_main },
125#endif
126#ifndef OPENSSL_NO_RSA
127 { FUNC_TYPE_GENERAL, "genrsa", genrsa_main },
128 { FUNC_TYPE_GENERAL, "rsa", rsa_main },
129 { FUNC_TYPE_GENERAL, "rsautl", rsautl_main },
130#endif
131
132 /* Message Digests. */
133#ifndef OPENSSL_NO_MD4
134 { FUNC_TYPE_MD, "md4", dgst_main },
135#endif
136#ifndef OPENSSL_NO_MD5
137 { FUNC_TYPE_MD, "md5", dgst_main },
138#endif
139#ifndef OPENSSL_NO_RMD160
140 { FUNC_TYPE_MD, "rmd160", dgst_main },
141#endif
142#ifndef OPENSSL_NO_SHA
143 { FUNC_TYPE_MD, "sha", dgst_main },
144#endif
145#ifndef OPENSSL_NO_SHA1
146 { FUNC_TYPE_MD, "sha1", dgst_main },
147#endif
148
149 /* Ciphers. */
150 { FUNC_TYPE_CIPHER, "base64", enc_main },
151#ifndef OPENSSL_NO_AES
152 { FUNC_TYPE_CIPHER, "aes-128-cbc", enc_main },
153 { FUNC_TYPE_CIPHER, "aes-128-ecb", enc_main },
154 { FUNC_TYPE_CIPHER, "aes-192-cbc", enc_main },
155 { FUNC_TYPE_CIPHER, "aes-192-ecb", enc_main },
156 { FUNC_TYPE_CIPHER, "aes-256-cbc", enc_main },
157 { FUNC_TYPE_CIPHER, "aes-256-ecb", enc_main },
158#endif
159#ifndef OPENSSL_NO_BF
160 { FUNC_TYPE_CIPHER, "bf", enc_main },
161 { FUNC_TYPE_CIPHER, "bf-cbc", enc_main },
162 { FUNC_TYPE_CIPHER, "bf-ecb", enc_main },
163 { FUNC_TYPE_CIPHER, "bf-cfb", enc_main },
164 { FUNC_TYPE_CIPHER, "bf-ofb", enc_main },
165#endif
166#ifndef OPENSSL_NO_CAMELLIA
167 { FUNC_TYPE_CIPHER, "camellia-128-cbc", enc_main },
168 { FUNC_TYPE_CIPHER, "camellia-128-ecb", enc_main },
169 { FUNC_TYPE_CIPHER, "camellia-192-cbc", enc_main },
170 { FUNC_TYPE_CIPHER, "camellia-192-ecb", enc_main },
171 { FUNC_TYPE_CIPHER, "camellia-256-cbc", enc_main },
172 { FUNC_TYPE_CIPHER, "camellia-256-ecb", enc_main },
173#endif
174#ifndef OPENSSL_NO_CAST
175 { FUNC_TYPE_CIPHER, "cast", enc_main },
176 { FUNC_TYPE_CIPHER, "cast5-cbc", enc_main },
177 { FUNC_TYPE_CIPHER, "cast5-ecb", enc_main },
178 { FUNC_TYPE_CIPHER, "cast5-cfb", enc_main },
179 { FUNC_TYPE_CIPHER, "cast5-ofb", enc_main },
180 { FUNC_TYPE_CIPHER, "cast-cbc", enc_main },
181#endif
182#ifndef OPENSSL_NO_CHACHA
183 { FUNC_TYPE_CIPHER, "chacha", enc_main },
184#endif
185#ifndef OPENSSL_NO_DES
186 { FUNC_TYPE_CIPHER, "des", enc_main },
187 { FUNC_TYPE_CIPHER, "des3", enc_main },
188 { FUNC_TYPE_CIPHER, "desx", enc_main },
189 { FUNC_TYPE_CIPHER, "des-ecb", enc_main },
190 { FUNC_TYPE_CIPHER, "des-ede", enc_main },
191 { FUNC_TYPE_CIPHER, "des-ede3", enc_main },
192 { FUNC_TYPE_CIPHER, "des-cbc", enc_main },
193 { FUNC_TYPE_CIPHER, "des-ede-cbc", enc_main },
194 { FUNC_TYPE_CIPHER, "des-ede3-cbc", enc_main },
195 { FUNC_TYPE_CIPHER, "des-cfb", enc_main },
196 { FUNC_TYPE_CIPHER, "des-ede-cfb", enc_main },
197 { FUNC_TYPE_CIPHER, "des-ede3-cfb", enc_main },
198 { FUNC_TYPE_CIPHER, "des-ofb", enc_main },
199 { FUNC_TYPE_CIPHER, "des-ede-ofb", enc_main },
200 { FUNC_TYPE_CIPHER, "des-ede3-ofb", enc_main },
201#endif
202#ifndef OPENSSL_NO_IDEA
203 { FUNC_TYPE_CIPHER, "idea", enc_main },
204 { FUNC_TYPE_CIPHER, "idea-cbc", enc_main },
205 { FUNC_TYPE_CIPHER, "idea-ecb", enc_main },
206 { FUNC_TYPE_CIPHER, "idea-cfb", enc_main },
207 { FUNC_TYPE_CIPHER, "idea-ofb", enc_main },
208#endif
209#ifndef OPENSSL_NO_RC2
210 { FUNC_TYPE_CIPHER, "rc2", enc_main },
211 { FUNC_TYPE_CIPHER, "rc2-cbc", enc_main },
212 { FUNC_TYPE_CIPHER, "rc2-ecb", enc_main },
213 { FUNC_TYPE_CIPHER, "rc2-cfb", enc_main },
214 { FUNC_TYPE_CIPHER, "rc2-ofb", enc_main },
215 { FUNC_TYPE_CIPHER, "rc2-64-cbc", enc_main },
216 { FUNC_TYPE_CIPHER, "rc2-40-cbc", enc_main },
217#endif
218#ifndef OPENSSL_NO_RC4
219 { FUNC_TYPE_CIPHER, "rc4", enc_main },
220 { FUNC_TYPE_CIPHER, "rc4-40", enc_main },
221#endif
222#ifndef OPENSSL_NO_RC5
223 { FUNC_TYPE_CIPHER, "rc5", enc_main },
224 { FUNC_TYPE_CIPHER, "rc5-cbc", enc_main },
225 { FUNC_TYPE_CIPHER, "rc5-ecb", enc_main },
226 { FUNC_TYPE_CIPHER, "rc5-cfb", enc_main },
227 { FUNC_TYPE_CIPHER, "rc5-ofb", enc_main },
228#endif
229#ifdef ZLIB
230 { FUNC_TYPE_CIPHER, "zlib", enc_main },
231#endif
232
233 { 0, NULL, NULL }
234};
diff --git a/src/usr.bin/openssl/rand.c b/src/usr.bin/openssl/rand.c
new file mode 100644
index 0000000000..0800157a35
--- /dev/null
+++ b/src/usr.bin/openssl/rand.c
@@ -0,0 +1,194 @@
1/* $OpenBSD: rand.c,v 1.1 2014/08/26 17:47:25 jsing Exp $ */
2/* ====================================================================
3 * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 *
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in
14 * the documentation and/or other materials provided with the
15 * distribution.
16 *
17 * 3. All advertising materials mentioning features or use of this
18 * software must display the following acknowledgment:
19 * "This product includes software developed by the OpenSSL Project
20 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
21 *
22 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
23 * endorse or promote products derived from this software without
24 * prior written permission. For written permission, please contact
25 * openssl-core@openssl.org.
26 *
27 * 5. Products derived from this software may not be called "OpenSSL"
28 * nor may "OpenSSL" appear in their names without prior written
29 * permission of the OpenSSL Project.
30 *
31 * 6. Redistributions of any form whatsoever must retain the following
32 * acknowledgment:
33 * "This product includes software developed by the OpenSSL Project
34 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
35 *
36 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
37 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
39 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
40 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
42 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
45 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
47 * OF THE POSSIBILITY OF SUCH DAMAGE.
48 * ====================================================================
49 *
50 * This product includes cryptographic software written by Eric Young
51 * (eay@cryptsoft.com). This product includes software written by Tim
52 * Hudson (tjh@cryptsoft.com).
53 *
54 */
55
56#include <ctype.h>
57#include <stdio.h>
58#include <string.h>
59
60#include "apps.h"
61
62#include <openssl/bio.h>
63#include <openssl/err.h>
64#include <openssl/rand.h>
65
66/* -out file - write to file
67 * -base64 - base64 encode output
68 * -hex - hex encode output
69 * num - write 'num' bytes
70 */
71
72int rand_main(int, char **);
73
74int
75rand_main(int argc, char **argv)
76{
77 int i, r, ret = 1;
78 int badopt;
79 char *outfile = NULL;
80 int base64 = 0;
81 int hex = 0;
82 BIO *out = NULL;
83 int num = -1;
84#ifndef OPENSSL_NO_ENGINE
85 char *engine = NULL;
86#endif
87
88 badopt = 0;
89 i = 0;
90 while (!badopt && argv[++i] != NULL) {
91 if (strcmp(argv[i], "-out") == 0) {
92 if ((argv[i + 1] != NULL) && (outfile == NULL))
93 outfile = argv[++i];
94 else
95 badopt = 1;
96 }
97#ifndef OPENSSL_NO_ENGINE
98 else if (strcmp(argv[i], "-engine") == 0) {
99 if ((argv[i + 1] != NULL) && (engine == NULL))
100 engine = argv[++i];
101 else
102 badopt = 1;
103 }
104#endif
105 else if (strcmp(argv[i], "-base64") == 0) {
106 if (!base64)
107 base64 = 1;
108 else
109 badopt = 1;
110 } else if (strcmp(argv[i], "-hex") == 0) {
111 if (!hex)
112 hex = 1;
113 else
114 badopt = 1;
115 } else if (isdigit((unsigned char) argv[i][0])) {
116 if (num < 0) {
117 r = sscanf(argv[i], "%d", &num);
118 if (r == 0 || num < 0)
119 badopt = 1;
120 } else
121 badopt = 1;
122 } else
123 badopt = 1;
124 }
125
126 if (hex && base64)
127 badopt = 1;
128
129 if (num < 0)
130 badopt = 1;
131
132 if (badopt) {
133 BIO_printf(bio_err, "Usage: rand [options] num\n");
134 BIO_printf(bio_err, "where options are\n");
135 BIO_printf(bio_err, "-out file - write to file\n");
136#ifndef OPENSSL_NO_ENGINE
137 BIO_printf(bio_err, "-engine e - use engine e, possibly a hardware device.\n");
138#endif
139 BIO_printf(bio_err, "-base64 - base64 encode output\n");
140 BIO_printf(bio_err, "-hex - hex encode output\n");
141 goto err;
142 }
143#ifndef OPENSSL_NO_ENGINE
144 setup_engine(bio_err, engine, 0);
145#endif
146
147 out = BIO_new(BIO_s_file());
148 if (out == NULL)
149 goto err;
150 if (outfile != NULL)
151 r = BIO_write_filename(out, outfile);
152 else {
153 r = BIO_set_fp(out, stdout, BIO_NOCLOSE | BIO_FP_TEXT);
154 }
155 if (r <= 0)
156 goto err;
157
158 if (base64) {
159 BIO *b64 = BIO_new(BIO_f_base64());
160 if (b64 == NULL)
161 goto err;
162 out = BIO_push(b64, out);
163 }
164 while (num > 0) {
165 unsigned char buf[4096];
166 int chunk;
167
168 chunk = num;
169 if (chunk > (int) sizeof(buf))
170 chunk = sizeof buf;
171 r = RAND_bytes(buf, chunk);
172 if (r <= 0)
173 goto err;
174 if (!hex)
175 BIO_write(out, buf, chunk);
176 else {
177 for (i = 0; i < chunk; i++)
178 BIO_printf(out, "%02x", buf[i]);
179 }
180 num -= chunk;
181 }
182 if (hex)
183 BIO_puts(out, "\n");
184 (void) BIO_flush(out);
185
186 ret = 0;
187
188err:
189 ERR_print_errors(bio_err);
190 if (out)
191 BIO_free_all(out);
192
193 return (ret);
194}
diff --git a/src/usr.bin/openssl/req.c b/src/usr.bin/openssl/req.c
new file mode 100644
index 0000000000..87599b35e1
--- /dev/null
+++ b/src/usr.bin/openssl/req.c
@@ -0,0 +1,1602 @@
1/* $OpenBSD: req.c,v 1.1 2014/08/26 17:47:25 jsing 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/* Until the key-gen callbacks are modified to use newer prototypes, we allow
60 * deprecated functions for openssl-internal code */
61#ifdef OPENSSL_NO_DEPRECATED
62#undef OPENSSL_NO_DEPRECATED
63#endif
64
65#include <stdio.h>
66#include <stdlib.h>
67#include <limits.h>
68#include <string.h>
69#include <time.h>
70
71#include "apps.h"
72
73#include <openssl/asn1.h>
74#include <openssl/bio.h>
75#include <openssl/bn.h>
76#include <openssl/conf.h>
77#include <openssl/err.h>
78#include <openssl/evp.h>
79#include <openssl/objects.h>
80#include <openssl/pem.h>
81#include <openssl/x509.h>
82#include <openssl/x509v3.h>
83
84#include <openssl/dsa.h>
85
86#include <openssl/rsa.h>
87
88#define SECTION "req"
89
90#define BITS "default_bits"
91#define KEYFILE "default_keyfile"
92#define PROMPT "prompt"
93#define DISTINGUISHED_NAME "distinguished_name"
94#define ATTRIBUTES "attributes"
95#define V3_EXTENSIONS "x509_extensions"
96#define REQ_EXTENSIONS "req_extensions"
97#define STRING_MASK "string_mask"
98#define UTF8_IN "utf8"
99
100#define DEFAULT_KEY_LENGTH 512
101#define MIN_KEY_LENGTH 384
102
103
104/* -inform arg - input format - default PEM (DER or PEM)
105 * -outform arg - output format - default PEM
106 * -in arg - input file - default stdin
107 * -out arg - output file - default stdout
108 * -verify - check request signature
109 * -noout - don't print stuff out.
110 * -text - print out human readable text.
111 * -nodes - no des encryption
112 * -config file - Load configuration file.
113 * -key file - make a request using key in file (or use it for verification).
114 * -keyform arg - key file format.
115 * -newkey - make a key and a request.
116 * -modulus - print RSA modulus.
117 * -pubkey - output Public Key.
118 * -x509 - output a self signed X509 structure instead.
119 * -asn1-kludge - output new certificate request in a format that some CA's
120 * require. This format is wrong
121 */
122
123static int make_REQ(X509_REQ * req, EVP_PKEY * pkey, char *dn, int mutlirdn,
124 int attribs, unsigned long chtype);
125static int build_subject(X509_REQ * req, char *subj, unsigned long chtype,
126 int multirdn);
127static int prompt_info(X509_REQ * req,
128 STACK_OF(CONF_VALUE) * dn_sk, char *dn_sect,
129 STACK_OF(CONF_VALUE) * attr_sk, char *attr_sect, int attribs,
130 unsigned long chtype);
131static int auto_info(X509_REQ * req, STACK_OF(CONF_VALUE) * sk,
132 STACK_OF(CONF_VALUE) * attr, int attribs,
133 unsigned long chtype);
134static int add_attribute_object(X509_REQ * req, char *text, const char *def,
135 char *value, int nid, int n_min,
136 int n_max, unsigned long chtype);
137static int add_DN_object(X509_NAME * n, char *text, const char *def, char *value,
138 int nid, int n_min, int n_max, unsigned long chtype, int mval);
139static int genpkey_cb(EVP_PKEY_CTX * ctx);
140static int req_check_len(int len, int n_min, int n_max);
141static int check_end(const char *str, const char *end);
142static EVP_PKEY_CTX *set_keygen_ctx(BIO * err, const char *gstr, int *pkey_type,
143 long *pkeylen, char **palgnam,
144 ENGINE * keygen_engine);
145static CONF *req_conf = NULL;
146static int batch = 0;
147
148int req_main(int, char **);
149
150int
151req_main(int argc, char **argv)
152{
153 ENGINE *e = NULL, *gen_eng = NULL;
154 unsigned long nmflag = 0, reqflag = 0;
155 int ex = 1, x509 = 0, days = 30;
156 X509 *x509ss = NULL;
157 X509_REQ *req = NULL;
158 EVP_PKEY_CTX *genctx = NULL;
159 const char *keyalg = NULL;
160 char *keyalgstr = NULL;
161 STACK_OF(OPENSSL_STRING) * pkeyopts = NULL, *sigopts = NULL;
162 EVP_PKEY *pkey = NULL;
163 int i = 0, badops = 0, newreq = 0, verbose = 0, pkey_type = -1;
164 long newkey = -1;
165 BIO *in = NULL, *out = NULL;
166 int informat, outformat, verify = 0, noout = 0, text = 0, keyform = FORMAT_PEM;
167 int nodes = 0, kludge = 0, newhdr = 0, subject = 0, pubkey = 0;
168 char *infile, *outfile, *prog, *keyfile = NULL, *template = NULL,
169 *keyout = NULL;
170#ifndef OPENSSL_NO_ENGINE
171 char *engine = NULL;
172#endif
173 char *extensions = NULL;
174 char *req_exts = NULL;
175 const EVP_CIPHER *cipher = NULL;
176 ASN1_INTEGER *serial = NULL;
177 int modulus = 0;
178 char *passargin = NULL, *passargout = NULL;
179 char *passin = NULL, *passout = NULL;
180 char *p;
181 char *subj = NULL;
182 int multirdn = 0;
183 const EVP_MD *md_alg = NULL, *digest = NULL;
184 unsigned long chtype = MBSTRING_ASC;
185
186 req_conf = NULL;
187#ifndef OPENSSL_NO_DES
188 cipher = EVP_des_ede3_cbc();
189#endif
190
191 infile = NULL;
192 outfile = NULL;
193 informat = FORMAT_PEM;
194 outformat = FORMAT_PEM;
195
196 prog = argv[0];
197 argc--;
198 argv++;
199 while (argc >= 1) {
200 if (strcmp(*argv, "-inform") == 0) {
201 if (--argc < 1)
202 goto bad;
203 informat = str2fmt(*(++argv));
204 } else if (strcmp(*argv, "-outform") == 0) {
205 if (--argc < 1)
206 goto bad;
207 outformat = str2fmt(*(++argv));
208 }
209#ifndef OPENSSL_NO_ENGINE
210 else if (strcmp(*argv, "-engine") == 0) {
211 if (--argc < 1)
212 goto bad;
213 engine = *(++argv);
214 } else if (strcmp(*argv, "-keygen_engine") == 0) {
215 if (--argc < 1)
216 goto bad;
217 gen_eng = ENGINE_by_id(*(++argv));
218 if (gen_eng == NULL) {
219 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
220 goto end;
221 }
222 }
223#endif
224 else if (strcmp(*argv, "-key") == 0) {
225 if (--argc < 1)
226 goto bad;
227 keyfile = *(++argv);
228 } else if (strcmp(*argv, "-pubkey") == 0) {
229 pubkey = 1;
230 } else if (strcmp(*argv, "-new") == 0) {
231 newreq = 1;
232 } else if (strcmp(*argv, "-config") == 0) {
233 if (--argc < 1)
234 goto bad;
235 template = *(++argv);
236 } else if (strcmp(*argv, "-keyform") == 0) {
237 if (--argc < 1)
238 goto bad;
239 keyform = str2fmt(*(++argv));
240 } else if (strcmp(*argv, "-in") == 0) {
241 if (--argc < 1)
242 goto bad;
243 infile = *(++argv);
244 } else if (strcmp(*argv, "-out") == 0) {
245 if (--argc < 1)
246 goto bad;
247 outfile = *(++argv);
248 } else if (strcmp(*argv, "-keyout") == 0) {
249 if (--argc < 1)
250 goto bad;
251 keyout = *(++argv);
252 } else if (strcmp(*argv, "-passin") == 0) {
253 if (--argc < 1)
254 goto bad;
255 passargin = *(++argv);
256 } else if (strcmp(*argv, "-passout") == 0) {
257 if (--argc < 1)
258 goto bad;
259 passargout = *(++argv);
260 } else if (strcmp(*argv, "-newkey") == 0) {
261 if (--argc < 1)
262 goto bad;
263 keyalg = *(++argv);
264 newreq = 1;
265 } else if (strcmp(*argv, "-pkeyopt") == 0) {
266 if (--argc < 1)
267 goto bad;
268 if (!pkeyopts)
269 pkeyopts = sk_OPENSSL_STRING_new_null();
270 if (!pkeyopts || !sk_OPENSSL_STRING_push(pkeyopts, *(++argv)))
271 goto bad;
272 } else if (strcmp(*argv, "-sigopt") == 0) {
273 if (--argc < 1)
274 goto bad;
275 if (!sigopts)
276 sigopts = sk_OPENSSL_STRING_new_null();
277 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, *(++argv)))
278 goto bad;
279 } else if (strcmp(*argv, "-batch") == 0)
280 batch = 1;
281 else if (strcmp(*argv, "-newhdr") == 0)
282 newhdr = 1;
283 else if (strcmp(*argv, "-modulus") == 0)
284 modulus = 1;
285 else if (strcmp(*argv, "-verify") == 0)
286 verify = 1;
287 else if (strcmp(*argv, "-nodes") == 0)
288 nodes = 1;
289 else if (strcmp(*argv, "-noout") == 0)
290 noout = 1;
291 else if (strcmp(*argv, "-verbose") == 0)
292 verbose = 1;
293 else if (strcmp(*argv, "-utf8") == 0)
294 chtype = MBSTRING_UTF8;
295 else if (strcmp(*argv, "-nameopt") == 0) {
296 if (--argc < 1)
297 goto bad;
298 if (!set_name_ex(&nmflag, *(++argv)))
299 goto bad;
300 } else if (strcmp(*argv, "-reqopt") == 0) {
301 if (--argc < 1)
302 goto bad;
303 if (!set_cert_ex(&reqflag, *(++argv)))
304 goto bad;
305 } else if (strcmp(*argv, "-subject") == 0)
306 subject = 1;
307 else if (strcmp(*argv, "-text") == 0)
308 text = 1;
309 else if (strcmp(*argv, "-x509") == 0)
310 x509 = 1;
311 else if (strcmp(*argv, "-asn1-kludge") == 0)
312 kludge = 1;
313 else if (strcmp(*argv, "-no-asn1-kludge") == 0)
314 kludge = 0;
315 else if (strcmp(*argv, "-subj") == 0) {
316 if (--argc < 1)
317 goto bad;
318 subj = *(++argv);
319 } else if (strcmp(*argv, "-multivalue-rdn") == 0)
320 multirdn = 1;
321 else if (strcmp(*argv, "-days") == 0) {
322 const char *errstr;
323
324 if (--argc < 1)
325 goto bad;
326 days = strtonum(*(++argv), 1, INT_MAX, &errstr);
327 if (errstr) {
328 BIO_printf(bio_err, "bad -days %s, using 0: %s\n",
329 *argv, errstr);
330 days = 30;
331 }
332 } else if (strcmp(*argv, "-set_serial") == 0) {
333 if (--argc < 1)
334 goto bad;
335 serial = s2i_ASN1_INTEGER(NULL, *(++argv));
336 if (!serial)
337 goto bad;
338 } else if (strcmp(*argv, "-extensions") == 0) {
339 if (--argc < 1)
340 goto bad;
341 extensions = *(++argv);
342 } else if (strcmp(*argv, "-reqexts") == 0) {
343 if (--argc < 1)
344 goto bad;
345 req_exts = *(++argv);
346 } else if ((md_alg = EVP_get_digestbyname(&((*argv)[1]))) != NULL) {
347 /* ok */
348 digest = md_alg;
349 } else {
350 BIO_printf(bio_err, "unknown option %s\n", *argv);
351 badops = 1;
352 break;
353 }
354 argc--;
355 argv++;
356 }
357
358 if (badops) {
359bad:
360 BIO_printf(bio_err, "%s [options] <infile >outfile\n", prog);
361 BIO_printf(bio_err, "where options are\n");
362 BIO_printf(bio_err, " -inform arg input format - DER or PEM\n");
363 BIO_printf(bio_err, " -outform arg output format - DER or PEM\n");
364 BIO_printf(bio_err, " -in arg input file\n");
365 BIO_printf(bio_err, " -out arg output file\n");
366 BIO_printf(bio_err, " -text text form of request\n");
367 BIO_printf(bio_err, " -pubkey output public key\n");
368 BIO_printf(bio_err, " -noout do not output REQ\n");
369 BIO_printf(bio_err, " -verify verify signature on REQ\n");
370 BIO_printf(bio_err, " -modulus RSA modulus\n");
371 BIO_printf(bio_err, " -nodes don't encrypt the output key\n");
372#ifndef OPENSSL_NO_ENGINE
373 BIO_printf(bio_err, " -engine e use engine e, possibly a hardware device\n");
374#endif
375 BIO_printf(bio_err, " -subject output the request's subject\n");
376 BIO_printf(bio_err, " -passin private key password source\n");
377 BIO_printf(bio_err, " -key file use the private key contained in file\n");
378 BIO_printf(bio_err, " -keyform arg key file format\n");
379 BIO_printf(bio_err, " -keyout arg file to send the key to\n");
380 BIO_printf(bio_err, " -newkey rsa:bits generate a new RSA key of 'bits' in size\n");
381 BIO_printf(bio_err, " -newkey dsa:file generate a new DSA key, parameters taken from CA in 'file'\n");
382 BIO_printf(bio_err, " -newkey ec:file generate a new EC key, parameters taken from CA in 'file'\n");
383 BIO_printf(bio_err, " -[digest] Digest to sign with (md5, sha1, md2, mdc2, md4)\n");
384 BIO_printf(bio_err, " -config file request template file.\n");
385 BIO_printf(bio_err, " -subj arg set or modify request subject\n");
386 BIO_printf(bio_err, " -multivalue-rdn enable support for multivalued RDNs\n");
387 BIO_printf(bio_err, " -new new request.\n");
388 BIO_printf(bio_err, " -batch do not ask anything during request generation\n");
389 BIO_printf(bio_err, " -x509 output a x509 structure instead of a cert. req.\n");
390 BIO_printf(bio_err, " -days number of days a certificate generated by -x509 is valid for.\n");
391 BIO_printf(bio_err, " -set_serial serial number to use for a certificate generated by -x509.\n");
392 BIO_printf(bio_err, " -newhdr output \"NEW\" in the header lines\n");
393 BIO_printf(bio_err, " -asn1-kludge Output the 'request' in a format that is wrong but some CA's\n");
394 BIO_printf(bio_err, " have been reported as requiring\n");
395 BIO_printf(bio_err, " -extensions .. specify certificate extension section (override value in config file)\n");
396 BIO_printf(bio_err, " -reqexts .. specify request extension section (override value in config file)\n");
397 BIO_printf(bio_err, " -utf8 input characters are UTF8 (default ASCII)\n");
398 BIO_printf(bio_err, " -nameopt arg - various certificate name options\n");
399 BIO_printf(bio_err, " -reqopt arg - various request text options\n\n");
400 goto end;
401 }
402 ERR_load_crypto_strings();
403 if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
404 BIO_printf(bio_err, "Error getting passwords\n");
405 goto end;
406 }
407 if (template != NULL) {
408 long errline = -1;
409
410 if (verbose)
411 BIO_printf(bio_err, "Using configuration from %s\n", template);
412 req_conf = NCONF_new(NULL);
413 i = NCONF_load(req_conf, template, &errline);
414 if (i == 0) {
415 BIO_printf(bio_err, "error on line %ld of %s\n", errline, template);
416 goto end;
417 }
418 } else {
419 req_conf = config;
420
421 if (req_conf == NULL) {
422 BIO_printf(bio_err, "Unable to load config info from %s\n", default_config_file);
423 if (newreq)
424 goto end;
425 } else if (verbose)
426 BIO_printf(bio_err, "Using configuration from %s\n",
427 default_config_file);
428 }
429
430 if (req_conf != NULL) {
431 if (!load_config(bio_err, req_conf))
432 goto end;
433 p = NCONF_get_string(req_conf, NULL, "oid_file");
434 if (p == NULL)
435 ERR_clear_error();
436 if (p != NULL) {
437 BIO *oid_bio;
438
439 oid_bio = BIO_new_file(p, "r");
440 if (oid_bio == NULL) {
441 /*
442 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
443 ERR_print_errors(bio_err);
444 */
445 } else {
446 OBJ_create_objects(oid_bio);
447 BIO_free(oid_bio);
448 }
449 }
450 }
451 if (!add_oid_section(bio_err, req_conf))
452 goto end;
453
454 if (md_alg == NULL) {
455 p = NCONF_get_string(req_conf, SECTION, "default_md");
456 if (p == NULL)
457 ERR_clear_error();
458 if (p != NULL) {
459 if ((md_alg = EVP_get_digestbyname(p)) != NULL)
460 digest = md_alg;
461 }
462 }
463 if (!extensions) {
464 extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
465 if (!extensions)
466 ERR_clear_error();
467 }
468 if (extensions) {
469 /* Check syntax of file */
470 X509V3_CTX ctx;
471 X509V3_set_ctx_test(&ctx);
472 X509V3_set_nconf(&ctx, req_conf);
473 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
474 BIO_printf(bio_err,
475 "Error Loading extension section %s\n", extensions);
476 goto end;
477 }
478 }
479 if (!passin) {
480 passin = NCONF_get_string(req_conf, SECTION, "input_password");
481 if (!passin)
482 ERR_clear_error();
483 }
484 if (!passout) {
485 passout = NCONF_get_string(req_conf, SECTION, "output_password");
486 if (!passout)
487 ERR_clear_error();
488 }
489 p = NCONF_get_string(req_conf, SECTION, STRING_MASK);
490 if (!p)
491 ERR_clear_error();
492
493 if (p && !ASN1_STRING_set_default_mask_asc(p)) {
494 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
495 goto end;
496 }
497 if (chtype != MBSTRING_UTF8) {
498 p = NCONF_get_string(req_conf, SECTION, UTF8_IN);
499 if (!p)
500 ERR_clear_error();
501 else if (!strcmp(p, "yes"))
502 chtype = MBSTRING_UTF8;
503 }
504 if (!req_exts) {
505 req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
506 if (!req_exts)
507 ERR_clear_error();
508 }
509 if (req_exts) {
510 /* Check syntax of file */
511 X509V3_CTX ctx;
512 X509V3_set_ctx_test(&ctx);
513 X509V3_set_nconf(&ctx, req_conf);
514 if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
515 BIO_printf(bio_err,
516 "Error Loading request extension section %s\n",
517 req_exts);
518 goto end;
519 }
520 }
521 in = BIO_new(BIO_s_file());
522 out = BIO_new(BIO_s_file());
523 if ((in == NULL) || (out == NULL))
524 goto end;
525
526#ifndef OPENSSL_NO_ENGINE
527 e = setup_engine(bio_err, engine, 0);
528#endif
529
530 if (keyfile != NULL) {
531 pkey = load_key(bio_err, keyfile, keyform, 0, passin, e,
532 "Private Key");
533 if (!pkey) {
534 /*
535 * load_key() has already printed an appropriate
536 * message
537 */
538 goto end;
539 }
540 }
541 if (newreq && (pkey == NULL)) {
542 if (!NCONF_get_number(req_conf, SECTION, BITS, &newkey)) {
543 newkey = DEFAULT_KEY_LENGTH;
544 }
545 if (keyalg) {
546 genctx = set_keygen_ctx(bio_err, keyalg, &pkey_type, &newkey,
547 &keyalgstr, gen_eng);
548 if (!genctx)
549 goto end;
550 }
551 if (newkey < MIN_KEY_LENGTH && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
552 BIO_printf(bio_err, "private key length is too short,\n");
553 BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n", MIN_KEY_LENGTH, newkey);
554 goto end;
555 }
556 if (!genctx) {
557 genctx = set_keygen_ctx(bio_err, NULL, &pkey_type, &newkey,
558 &keyalgstr, gen_eng);
559 if (!genctx)
560 goto end;
561 }
562 if (pkeyopts) {
563 char *genopt;
564 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
565 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
566 if (pkey_ctrl_string(genctx, genopt) <= 0) {
567 BIO_printf(bio_err,
568 "parameter error \"%s\"\n",
569 genopt);
570 ERR_print_errors(bio_err);
571 goto end;
572 }
573 }
574 }
575 BIO_printf(bio_err, "Generating a %ld bit %s private key\n",
576 newkey, keyalgstr);
577
578 EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
579 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
580
581 if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
582 BIO_puts(bio_err, "Error Generating Key\n");
583 goto end;
584 }
585 EVP_PKEY_CTX_free(genctx);
586 genctx = NULL;
587
588 if (keyout == NULL) {
589 keyout = NCONF_get_string(req_conf, SECTION, KEYFILE);
590 if (keyout == NULL)
591 ERR_clear_error();
592 }
593 if (keyout == NULL) {
594 BIO_printf(bio_err, "writing new private key to stdout\n");
595 BIO_set_fp(out, stdout, BIO_NOCLOSE);
596 } else {
597 BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
598 if (BIO_write_filename(out, keyout) <= 0) {
599 perror(keyout);
600 goto end;
601 }
602 }
603
604 p = NCONF_get_string(req_conf, SECTION, "encrypt_rsa_key");
605 if (p == NULL) {
606 ERR_clear_error();
607 p = NCONF_get_string(req_conf, SECTION, "encrypt_key");
608 if (p == NULL)
609 ERR_clear_error();
610 }
611 if ((p != NULL) && (strcmp(p, "no") == 0))
612 cipher = NULL;
613 if (nodes)
614 cipher = NULL;
615
616 i = 0;
617loop:
618 if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
619 NULL, 0, NULL, passout)) {
620 if ((ERR_GET_REASON(ERR_peek_error()) ==
621 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
622 ERR_clear_error();
623 i++;
624 goto loop;
625 }
626 goto end;
627 }
628 BIO_printf(bio_err, "-----\n");
629 }
630 if (!newreq) {
631 /*
632 * Since we are using a pre-existing certificate request, the
633 * kludge 'format' info should not be changed.
634 */
635 kludge = -1;
636 if (infile == NULL)
637 BIO_set_fp(in, stdin, BIO_NOCLOSE);
638 else {
639 if (BIO_read_filename(in, infile) <= 0) {
640 perror(infile);
641 goto end;
642 }
643 }
644
645 if (informat == FORMAT_ASN1)
646 req = d2i_X509_REQ_bio(in, NULL);
647 else if (informat == FORMAT_PEM)
648 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
649 else {
650 BIO_printf(bio_err, "bad input format specified for X509 request\n");
651 goto end;
652 }
653 if (req == NULL) {
654 BIO_printf(bio_err, "unable to load X509 request\n");
655 goto end;
656 }
657 }
658 if (newreq || x509) {
659 if (pkey == NULL) {
660 BIO_printf(bio_err, "you need to specify a private key\n");
661 goto end;
662 }
663 if (req == NULL) {
664 req = X509_REQ_new();
665 if (req == NULL) {
666 goto end;
667 }
668 i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
669 subj = NULL; /* done processing '-subj' option */
670 if ((kludge > 0) && !sk_X509_ATTRIBUTE_num(req->req_info->attributes)) {
671 sk_X509_ATTRIBUTE_free(req->req_info->attributes);
672 req->req_info->attributes = NULL;
673 }
674 if (!i) {
675 BIO_printf(bio_err, "problems making Certificate Request\n");
676 goto end;
677 }
678 }
679 if (x509) {
680 EVP_PKEY *tmppkey;
681 X509V3_CTX ext_ctx;
682 if ((x509ss = X509_new()) == NULL)
683 goto end;
684
685 /* Set version to V3 */
686 if (extensions && !X509_set_version(x509ss, 2))
687 goto end;
688 if (serial) {
689 if (!X509_set_serialNumber(x509ss, serial))
690 goto end;
691 } else {
692 if (!rand_serial(NULL,
693 X509_get_serialNumber(x509ss)))
694 goto end;
695 }
696
697 if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
698 goto end;
699 if (!X509_gmtime_adj(X509_get_notBefore(x509ss), 0))
700 goto end;
701 if (!X509_time_adj_ex(X509_get_notAfter(x509ss), days, 0, NULL))
702 goto end;
703 if (!X509_set_subject_name(x509ss, X509_REQ_get_subject_name(req)))
704 goto end;
705 tmppkey = X509_REQ_get_pubkey(req);
706 if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
707 goto end;
708 EVP_PKEY_free(tmppkey);
709
710 /* Set up V3 context struct */
711
712 X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
713 X509V3_set_nconf(&ext_ctx, req_conf);
714
715 /* Add extensions */
716 if (extensions && !X509V3_EXT_add_nconf(req_conf,
717 &ext_ctx, extensions, x509ss)) {
718 BIO_printf(bio_err,
719 "Error Loading extension section %s\n",
720 extensions);
721 goto end;
722 }
723 i = do_X509_sign(bio_err, x509ss, pkey, digest, sigopts);
724 if (!i) {
725 ERR_print_errors(bio_err);
726 goto end;
727 }
728 } else {
729 X509V3_CTX ext_ctx;
730
731 /* Set up V3 context struct */
732
733 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
734 X509V3_set_nconf(&ext_ctx, req_conf);
735
736 /* Add extensions */
737 if (req_exts && !X509V3_EXT_REQ_add_nconf(req_conf,
738 &ext_ctx, req_exts, req)) {
739 BIO_printf(bio_err,
740 "Error Loading extension section %s\n",
741 req_exts);
742 goto end;
743 }
744 i = do_X509_REQ_sign(bio_err, req, pkey, digest, sigopts);
745 if (!i) {
746 ERR_print_errors(bio_err);
747 goto end;
748 }
749 }
750 }
751 if (subj && x509) {
752 BIO_printf(bio_err, "Cannot modifiy certificate subject\n");
753 goto end;
754 }
755 if (subj && !x509) {
756 if (verbose) {
757 BIO_printf(bio_err, "Modifying Request's Subject\n");
758 print_name(bio_err, "old subject=", X509_REQ_get_subject_name(req), nmflag);
759 }
760 if (build_subject(req, subj, chtype, multirdn) == 0) {
761 BIO_printf(bio_err, "ERROR: cannot modify subject\n");
762 ex = 1;
763 goto end;
764 }
765 req->req_info->enc.modified = 1;
766
767 if (verbose) {
768 print_name(bio_err, "new subject=", X509_REQ_get_subject_name(req), nmflag);
769 }
770 }
771 if (verify && !x509) {
772 int tmp = 0;
773
774 if (pkey == NULL) {
775 pkey = X509_REQ_get_pubkey(req);
776 tmp = 1;
777 if (pkey == NULL)
778 goto end;
779 }
780 i = X509_REQ_verify(req, pkey);
781 if (tmp) {
782 EVP_PKEY_free(pkey);
783 pkey = NULL;
784 }
785 if (i < 0) {
786 goto end;
787 } else if (i == 0) {
788 BIO_printf(bio_err, "verify failure\n");
789 ERR_print_errors(bio_err);
790 } else /* if (i > 0) */
791 BIO_printf(bio_err, "verify OK\n");
792 }
793 if (noout && !text && !modulus && !subject && !pubkey) {
794 ex = 0;
795 goto end;
796 }
797 if (outfile == NULL) {
798 BIO_set_fp(out, stdout, BIO_NOCLOSE);
799 } else {
800 if ((keyout != NULL) && (strcmp(outfile, keyout) == 0))
801 i = (int) BIO_append_filename(out, outfile);
802 else
803 i = (int) BIO_write_filename(out, outfile);
804 if (!i) {
805 perror(outfile);
806 goto end;
807 }
808 }
809
810 if (pubkey) {
811 EVP_PKEY *tpubkey;
812 tpubkey = X509_REQ_get_pubkey(req);
813 if (tpubkey == NULL) {
814 BIO_printf(bio_err, "Error getting public key\n");
815 ERR_print_errors(bio_err);
816 goto end;
817 }
818 PEM_write_bio_PUBKEY(out, tpubkey);
819 EVP_PKEY_free(tpubkey);
820 }
821 if (text) {
822 if (x509)
823 X509_print_ex(out, x509ss, nmflag, reqflag);
824 else
825 X509_REQ_print_ex(out, req, nmflag, reqflag);
826 }
827 if (subject) {
828 if (x509)
829 print_name(out, "subject=", X509_get_subject_name(x509ss), nmflag);
830 else
831 print_name(out, "subject=", X509_REQ_get_subject_name(req), nmflag);
832 }
833 if (modulus) {
834 EVP_PKEY *tpubkey;
835
836 if (x509)
837 tpubkey = X509_get_pubkey(x509ss);
838 else
839 tpubkey = X509_REQ_get_pubkey(req);
840 if (tpubkey == NULL) {
841 fprintf(stdout, "Modulus=unavailable\n");
842 goto end;
843 }
844 fprintf(stdout, "Modulus=");
845 if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA)
846 BN_print(out, tpubkey->pkey.rsa->n);
847 else
848 fprintf(stdout, "Wrong Algorithm type");
849 EVP_PKEY_free(tpubkey);
850 fprintf(stdout, "\n");
851 }
852 if (!noout && !x509) {
853 if (outformat == FORMAT_ASN1)
854 i = i2d_X509_REQ_bio(out, req);
855 else if (outformat == FORMAT_PEM) {
856 if (newhdr)
857 i = PEM_write_bio_X509_REQ_NEW(out, req);
858 else
859 i = PEM_write_bio_X509_REQ(out, req);
860 } else {
861 BIO_printf(bio_err, "bad output format specified for outfile\n");
862 goto end;
863 }
864 if (!i) {
865 BIO_printf(bio_err, "unable to write X509 request\n");
866 goto end;
867 }
868 }
869 if (!noout && x509 && (x509ss != NULL)) {
870 if (outformat == FORMAT_ASN1)
871 i = i2d_X509_bio(out, x509ss);
872 else if (outformat == FORMAT_PEM)
873 i = PEM_write_bio_X509(out, x509ss);
874 else {
875 BIO_printf(bio_err, "bad output format specified for outfile\n");
876 goto end;
877 }
878 if (!i) {
879 BIO_printf(bio_err, "unable to write X509 certificate\n");
880 goto end;
881 }
882 }
883 ex = 0;
884end:
885 if (ex) {
886 ERR_print_errors(bio_err);
887 }
888 if ((req_conf != NULL) && (req_conf != config))
889 NCONF_free(req_conf);
890 BIO_free(in);
891 BIO_free_all(out);
892 EVP_PKEY_free(pkey);
893 if (genctx)
894 EVP_PKEY_CTX_free(genctx);
895 if (pkeyopts)
896 sk_OPENSSL_STRING_free(pkeyopts);
897 if (sigopts)
898 sk_OPENSSL_STRING_free(sigopts);
899#ifndef OPENSSL_NO_ENGINE
900 if (gen_eng)
901 ENGINE_free(gen_eng);
902#endif
903 free(keyalgstr);
904 X509_REQ_free(req);
905 X509_free(x509ss);
906 ASN1_INTEGER_free(serial);
907 if (passargin && passin)
908 free(passin);
909 if (passargout && passout)
910 free(passout);
911 OBJ_cleanup();
912
913 return (ex);
914}
915
916static int
917make_REQ(X509_REQ * req, EVP_PKEY * pkey, char *subj, int multirdn,
918 int attribs, unsigned long chtype)
919{
920 int ret = 0, i;
921 char no_prompt = 0;
922 STACK_OF(CONF_VALUE) * dn_sk, *attr_sk = NULL;
923 char *tmp, *dn_sect, *attr_sect;
924
925 tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
926 if (tmp == NULL)
927 ERR_clear_error();
928 if ((tmp != NULL) && !strcmp(tmp, "no"))
929 no_prompt = 1;
930
931 dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
932 if (dn_sect == NULL) {
933 BIO_printf(bio_err, "unable to find '%s' in config\n",
934 DISTINGUISHED_NAME);
935 goto err;
936 }
937 dn_sk = NCONF_get_section(req_conf, dn_sect);
938 if (dn_sk == NULL) {
939 BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
940 goto err;
941 }
942 attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
943 if (attr_sect == NULL) {
944 ERR_clear_error();
945 attr_sk = NULL;
946 } else {
947 attr_sk = NCONF_get_section(req_conf, attr_sect);
948 if (attr_sk == NULL) {
949 BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
950 goto err;
951 }
952 }
953
954 /* setup version number */
955 if (!X509_REQ_set_version(req, 0L))
956 goto err; /* version 1 */
957
958 if (no_prompt)
959 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
960 else {
961 if (subj)
962 i = build_subject(req, subj, chtype, multirdn);
963 else
964 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs, chtype);
965 }
966 if (!i)
967 goto err;
968
969 if (!X509_REQ_set_pubkey(req, pkey))
970 goto err;
971
972 ret = 1;
973err:
974 return (ret);
975}
976
977/*
978 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
979 * where characters may be escaped by \
980 */
981static int
982build_subject(X509_REQ * req, char *subject, unsigned long chtype, int multirdn)
983{
984 X509_NAME *n;
985
986 if (!(n = parse_name(subject, chtype, multirdn)))
987 return 0;
988
989 if (!X509_REQ_set_subject_name(req, n)) {
990 X509_NAME_free(n);
991 return 0;
992 }
993 X509_NAME_free(n);
994 return 1;
995}
996
997
998static int
999prompt_info(X509_REQ * req,
1000 STACK_OF(CONF_VALUE) * dn_sk, char *dn_sect,
1001 STACK_OF(CONF_VALUE) * attr_sk, char *attr_sect, int attribs,
1002 unsigned long chtype)
1003{
1004 int i;
1005 char *p, *q;
1006 char buf[100];
1007 int nid, mval;
1008 long n_min, n_max;
1009 char *type, *value;
1010 const char *def;
1011 CONF_VALUE *v;
1012 X509_NAME *subj;
1013 subj = X509_REQ_get_subject_name(req);
1014
1015 if (!batch) {
1016 BIO_printf(bio_err, "You are about to be asked to enter information that will be incorporated\n");
1017 BIO_printf(bio_err, "into your certificate request.\n");
1018 BIO_printf(bio_err, "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1019 BIO_printf(bio_err, "There are quite a few fields but you can leave some blank\n");
1020 BIO_printf(bio_err, "For some fields there will be a default value,\n");
1021 BIO_printf(bio_err, "If you enter '.', the field will be left blank.\n");
1022 BIO_printf(bio_err, "-----\n");
1023 }
1024 if (sk_CONF_VALUE_num(dn_sk)) {
1025 i = -1;
1026start: for (;;) {
1027 int ret;
1028 i++;
1029 if (sk_CONF_VALUE_num(dn_sk) <= i)
1030 break;
1031
1032 v = sk_CONF_VALUE_value(dn_sk, i);
1033 p = q = NULL;
1034 type = v->name;
1035 if (!check_end(type, "_min") || !check_end(type, "_max") ||
1036 !check_end(type, "_default") ||
1037 !check_end(type, "_value"))
1038 continue;
1039 /*
1040 * Skip past any leading X. X: X, etc to allow for
1041 * multiple instances
1042 */
1043 for (p = v->name; *p; p++)
1044 if ((*p == ':') || (*p == ',') ||
1045 (*p == '.')) {
1046 p++;
1047 if (*p)
1048 type = p;
1049 break;
1050 }
1051 if (*type == '+') {
1052 mval = -1;
1053 type++;
1054 } else
1055 mval = 0;
1056 /* If OBJ not recognised ignore it */
1057 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1058 goto start;
1059 ret = snprintf(buf, sizeof buf, "%s_default", v->name);
1060 if (ret == -1 || ret >= sizeof(buf)) {
1061 BIO_printf(bio_err, "Name '%s' too long for default\n",
1062 v->name);
1063 return 0;
1064 }
1065 if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1066 ERR_clear_error();
1067 def = "";
1068 }
1069 ret = snprintf(buf, sizeof buf, "%s_value", v->name);
1070 if (ret == -1 || ret >= sizeof(buf)) {
1071 BIO_printf(bio_err, "Name '%s' too long for value\n",
1072 v->name);
1073 return 0;
1074 }
1075 if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1076 ERR_clear_error();
1077 value = NULL;
1078 }
1079 ret = snprintf(buf, sizeof buf, "%s_min", v->name);
1080 if (ret == -1 || ret >= sizeof(buf)) {
1081 BIO_printf(bio_err, "Name '%s' too long for min\n",
1082 v->name);
1083 return 0;
1084 }
1085 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1086 ERR_clear_error();
1087 n_min = -1;
1088 }
1089 ret = snprintf(buf, sizeof buf, "%s_max", v->name);
1090 if (ret == -1 || ret >= sizeof(buf)) {
1091 BIO_printf(bio_err, "Name '%s' too long for max\n",
1092 v->name);
1093 return 0;
1094 }
1095 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1096 ERR_clear_error();
1097 n_max = -1;
1098 }
1099 if (!add_DN_object(subj, v->value, def, value, nid,
1100 n_min, n_max, chtype, mval))
1101 return 0;
1102 }
1103 if (X509_NAME_entry_count(subj) == 0) {
1104 BIO_printf(bio_err, "error, no objects specified in config file\n");
1105 return 0;
1106 }
1107 if (attribs) {
1108 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0) &&
1109 (!batch)) {
1110 BIO_printf(bio_err,
1111 "\nPlease enter the following 'extra' attributes\n");
1112 BIO_printf(bio_err,
1113 "to be sent with your certificate request\n");
1114 }
1115 i = -1;
1116start2: for (;;) {
1117 int ret;
1118 i++;
1119 if ((attr_sk == NULL) ||
1120 (sk_CONF_VALUE_num(attr_sk) <= i))
1121 break;
1122
1123 v = sk_CONF_VALUE_value(attr_sk, i);
1124 type = v->name;
1125 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1126 goto start2;
1127 ret = snprintf(buf, sizeof buf, "%s_default", type);
1128 if (ret == -1 || ret >= sizeof(buf)) {
1129 BIO_printf(bio_err, "Name '%s' too long for default\n",
1130 v->name);
1131 return 0;
1132 }
1133 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1134 == NULL) {
1135 ERR_clear_error();
1136 def = "";
1137 }
1138 ret = snprintf(buf, sizeof buf, "%s_value", type);
1139 if (ret == -1 || ret >= sizeof(buf)) {
1140 BIO_printf(bio_err, "Name '%s' too long for value\n",
1141 v->name);
1142 return 0;
1143 }
1144 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1145 == NULL) {
1146 ERR_clear_error();
1147 value = NULL;
1148 }
1149 ret = snprintf(buf, sizeof buf, "%s_min", type);
1150 if (ret == -1 || ret >= sizeof(buf)) {
1151 BIO_printf(bio_err, "Name '%s' too long for min\n",
1152 v->name);
1153 return 0;
1154 }
1155 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1156 ERR_clear_error();
1157 n_min = -1;
1158 }
1159 ret = snprintf(buf, sizeof buf, "%s_max", type);
1160 if (ret == -1 || ret >= sizeof(buf)) {
1161 BIO_printf(bio_err, "Name '%s' too long for max\n",
1162 v->name);
1163 return 0;
1164 }
1165 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1166 ERR_clear_error();
1167 n_max = -1;
1168 }
1169 if (!add_attribute_object(req,
1170 v->value, def, value, nid, n_min, n_max, chtype))
1171 return 0;
1172 }
1173 }
1174 } else {
1175 BIO_printf(bio_err, "No template, please set one up.\n");
1176 return 0;
1177 }
1178
1179 return 1;
1180
1181}
1182
1183static int
1184auto_info(X509_REQ * req, STACK_OF(CONF_VALUE) * dn_sk,
1185 STACK_OF(CONF_VALUE) * attr_sk, int attribs, unsigned long chtype)
1186{
1187 int i;
1188 char *p, *q;
1189 char *type;
1190 CONF_VALUE *v;
1191 X509_NAME *subj;
1192
1193 subj = X509_REQ_get_subject_name(req);
1194
1195 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1196 int mval;
1197 v = sk_CONF_VALUE_value(dn_sk, i);
1198 p = q = NULL;
1199 type = v->name;
1200 /*
1201 * Skip past any leading X. X: X, etc to allow for multiple
1202 * instances
1203 */
1204 for (p = v->name; *p; p++)
1205 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1206 p++;
1207 if (*p)
1208 type = p;
1209 break;
1210 }
1211 if (*p == '+') {
1212 p++;
1213 mval = -1;
1214 } else
1215 mval = 0;
1216 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1217 (unsigned char *) v->value, -1, -1, mval))
1218 return 0;
1219
1220 }
1221
1222 if (!X509_NAME_entry_count(subj)) {
1223 BIO_printf(bio_err, "error, no objects specified in config file\n");
1224 return 0;
1225 }
1226 if (attribs) {
1227 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1228 v = sk_CONF_VALUE_value(attr_sk, i);
1229 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1230 (unsigned char *) v->value, -1))
1231 return 0;
1232 }
1233 }
1234 return 1;
1235}
1236
1237
1238static int
1239add_DN_object(X509_NAME * n, char *text, const char *def, char *value,
1240 int nid, int n_min, int n_max, unsigned long chtype, int mval)
1241{
1242 int i, ret = 0;
1243 char buf[1024];
1244start:
1245 if (!batch)
1246 BIO_printf(bio_err, "%s [%s]:", text, def);
1247 (void) BIO_flush(bio_err);
1248 if (value != NULL) {
1249 strlcpy(buf, value, sizeof buf);
1250 strlcat(buf, "\n", sizeof buf);
1251 BIO_printf(bio_err, "%s\n", value);
1252 } else {
1253 buf[0] = '\0';
1254 if (!batch) {
1255 if (!fgets(buf, sizeof buf, stdin))
1256 return 0;
1257 } else {
1258 buf[0] = '\n';
1259 buf[1] = '\0';
1260 }
1261 }
1262
1263 if (buf[0] == '\0')
1264 return (0);
1265 else if (buf[0] == '\n') {
1266 if ((def == NULL) || (def[0] == '\0'))
1267 return (1);
1268 strlcpy(buf, def, sizeof buf);
1269 strlcat(buf, "\n", sizeof buf);
1270 } else if ((buf[0] == '.') && (buf[1] == '\n'))
1271 return (1);
1272
1273 i = strlen(buf);
1274 if (buf[i - 1] != '\n') {
1275 BIO_printf(bio_err, "weird input :-(\n");
1276 return (0);
1277 }
1278 buf[--i] = '\0';
1279 if (!req_check_len(i, n_min, n_max))
1280 goto start;
1281 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1282 (unsigned char *) buf, -1, -1, mval))
1283 goto err;
1284 ret = 1;
1285err:
1286 return (ret);
1287}
1288
1289static int
1290add_attribute_object(X509_REQ * req, char *text, const char *def,
1291 char *value, int nid, int n_min,
1292 int n_max, unsigned long chtype)
1293{
1294 int i;
1295 static char buf[1024];
1296
1297start:
1298 if (!batch)
1299 BIO_printf(bio_err, "%s [%s]:", text, def);
1300 (void) BIO_flush(bio_err);
1301 if (value != NULL) {
1302 strlcpy(buf, value, sizeof buf);
1303 strlcat(buf, "\n", sizeof buf);
1304 BIO_printf(bio_err, "%s\n", value);
1305 } else {
1306 buf[0] = '\0';
1307 if (!batch) {
1308 if (!fgets(buf, sizeof buf, stdin))
1309 return 0;
1310 } else {
1311 buf[0] = '\n';
1312 buf[1] = '\0';
1313 }
1314 }
1315
1316 if (buf[0] == '\0')
1317 return (0);
1318 else if (buf[0] == '\n') {
1319 if ((def == NULL) || (def[0] == '\0'))
1320 return (1);
1321 strlcpy(buf, def, sizeof buf);
1322 strlcat(buf, "\n", sizeof buf);
1323 } else if ((buf[0] == '.') && (buf[1] == '\n'))
1324 return (1);
1325
1326 i = strlen(buf);
1327 if (buf[i - 1] != '\n') {
1328 BIO_printf(bio_err, "weird input :-(\n");
1329 return (0);
1330 }
1331 buf[--i] = '\0';
1332 if (!req_check_len(i, n_min, n_max))
1333 goto start;
1334
1335 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1336 (unsigned char *) buf, -1)) {
1337 BIO_printf(bio_err, "Error adding attribute\n");
1338 ERR_print_errors(bio_err);
1339 goto err;
1340 }
1341 return (1);
1342err:
1343 return (0);
1344}
1345
1346static int
1347req_check_len(int len, int n_min, int n_max)
1348{
1349 if ((n_min > 0) && (len < n_min)) {
1350 BIO_printf(bio_err, "string is too short, it needs to be at least %d bytes long\n", n_min);
1351 return (0);
1352 }
1353 if ((n_max >= 0) && (len > n_max)) {
1354 BIO_printf(bio_err, "string is too long, it needs to be less than %d bytes long\n", n_max);
1355 return (0);
1356 }
1357 return (1);
1358}
1359
1360/* Check if the end of a string matches 'end' */
1361static int
1362check_end(const char *str, const char *end)
1363{
1364 int elen, slen;
1365 const char *tmp;
1366 elen = strlen(end);
1367 slen = strlen(str);
1368 if (elen > slen)
1369 return 1;
1370 tmp = str + slen - elen;
1371 return strcmp(tmp, end);
1372}
1373
1374static EVP_PKEY_CTX *
1375set_keygen_ctx(BIO * err, const char *gstr, int *pkey_type,
1376 long *pkeylen, char **palgnam,
1377 ENGINE * keygen_engine)
1378{
1379 EVP_PKEY_CTX *gctx = NULL;
1380 EVP_PKEY *param = NULL;
1381 long keylen = -1;
1382 BIO *pbio = NULL;
1383 const char *paramfile = NULL;
1384 const char *errstr;
1385
1386 if (gstr == NULL) {
1387 *pkey_type = EVP_PKEY_RSA;
1388 keylen = *pkeylen;
1389 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1390 *pkey_type = EVP_PKEY_RSA;
1391 keylen = strtonum(gstr, 0, LONG_MAX, &errstr);
1392 if (errstr) {
1393 BIO_printf(err, "bad algorithm %s: %s\n", gstr, errstr);
1394 return NULL;
1395 }
1396 *pkeylen = keylen;
1397 } else if (!strncmp(gstr, "param:", 6))
1398 paramfile = gstr + 6;
1399 else {
1400 const char *p = strchr(gstr, ':');
1401 int len;
1402 ENGINE *tmpeng;
1403 const EVP_PKEY_ASN1_METHOD *ameth;
1404
1405 if (p)
1406 len = p - gstr;
1407 else
1408 len = strlen(gstr);
1409 /*
1410 * The lookup of a the string will cover all engines so keep
1411 * a note of the implementation.
1412 */
1413
1414 ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1415
1416 if (!ameth) {
1417 BIO_printf(err, "Unknown algorithm %.*s\n", len, gstr);
1418 return NULL;
1419 }
1420 EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL,
1421 ameth);
1422#ifndef OPENSSL_NO_ENGINE
1423 if (tmpeng)
1424 ENGINE_finish(tmpeng);
1425#endif
1426 if (*pkey_type == EVP_PKEY_RSA) {
1427 if (p) {
1428 keylen = strtonum(p + 1, 0, LONG_MAX, &errstr);
1429 if (errstr) {
1430 BIO_printf(err, "bad algorithm %s: %s\n",
1431 p + 1, errstr);
1432 return NULL;
1433 }
1434 *pkeylen = keylen;
1435 } else
1436 keylen = *pkeylen;
1437 } else if (p)
1438 paramfile = p + 1;
1439 }
1440
1441 if (paramfile) {
1442 pbio = BIO_new_file(paramfile, "r");
1443 if (!pbio) {
1444 BIO_printf(err, "Can't open parameter file %s\n",
1445 paramfile);
1446 return NULL;
1447 }
1448 param = PEM_read_bio_Parameters(pbio, NULL);
1449
1450 if (!param) {
1451 X509 *x;
1452 (void) BIO_reset(pbio);
1453 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1454 if (x) {
1455 param = X509_get_pubkey(x);
1456 X509_free(x);
1457 }
1458 }
1459 BIO_free(pbio);
1460
1461 if (!param) {
1462 BIO_printf(err, "Error reading parameter file %s\n",
1463 paramfile);
1464 return NULL;
1465 }
1466 if (*pkey_type == -1)
1467 *pkey_type = EVP_PKEY_id(param);
1468 else if (*pkey_type != EVP_PKEY_base_id(param)) {
1469 BIO_printf(err, "Key Type does not match parameters\n");
1470 EVP_PKEY_free(param);
1471 return NULL;
1472 }
1473 }
1474 if (palgnam) {
1475 const EVP_PKEY_ASN1_METHOD *ameth;
1476 ENGINE *tmpeng;
1477 const char *anam;
1478 ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1479 if (!ameth) {
1480 BIO_puts(err, "Internal error: can't find key algorithm\n");
1481 return NULL;
1482 }
1483 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1484 *palgnam = BUF_strdup(anam);
1485#ifndef OPENSSL_NO_ENGINE
1486 if (tmpeng)
1487 ENGINE_finish(tmpeng);
1488#endif
1489 }
1490 if (param) {
1491 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1492 *pkeylen = EVP_PKEY_bits(param);
1493 EVP_PKEY_free(param);
1494 } else
1495 gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1496
1497 if (!gctx) {
1498 BIO_puts(err, "Error allocating keygen context\n");
1499 ERR_print_errors(err);
1500 return NULL;
1501 }
1502 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1503 BIO_puts(err, "Error initializing keygen context\n");
1504 ERR_print_errors(err);
1505 return NULL;
1506 }
1507 if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1508 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1509 BIO_puts(err, "Error setting RSA keysize\n");
1510 ERR_print_errors(err);
1511 EVP_PKEY_CTX_free(gctx);
1512 return NULL;
1513 }
1514 }
1515
1516 return gctx;
1517}
1518
1519static int
1520genpkey_cb(EVP_PKEY_CTX * ctx)
1521{
1522 char c = '*';
1523 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1524 int p;
1525 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1526 if (p == 0)
1527 c = '.';
1528 if (p == 1)
1529 c = '+';
1530 if (p == 2)
1531 c = '*';
1532 if (p == 3)
1533 c = '\n';
1534 BIO_write(b, &c, 1);
1535 (void) BIO_flush(b);
1536 return 1;
1537}
1538
1539static int
1540do_sign_init(BIO * err, EVP_MD_CTX * ctx, EVP_PKEY * pkey,
1541 const EVP_MD * md, STACK_OF(OPENSSL_STRING) * sigopts)
1542{
1543 EVP_PKEY_CTX *pkctx = NULL;
1544 int i;
1545 EVP_MD_CTX_init(ctx);
1546 if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1547 return 0;
1548 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1549 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1550 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1551 BIO_printf(err, "parameter error \"%s\"\n", sigopt);
1552 ERR_print_errors(bio_err);
1553 return 0;
1554 }
1555 }
1556 return 1;
1557}
1558
1559int
1560do_X509_sign(BIO * err, X509 * x, EVP_PKEY * pkey, const EVP_MD * md,
1561 STACK_OF(OPENSSL_STRING) * sigopts)
1562{
1563 int rv;
1564 EVP_MD_CTX mctx;
1565 EVP_MD_CTX_init(&mctx);
1566 rv = do_sign_init(err, &mctx, pkey, md, sigopts);
1567 if (rv > 0)
1568 rv = X509_sign_ctx(x, &mctx);
1569 EVP_MD_CTX_cleanup(&mctx);
1570 return rv > 0 ? 1 : 0;
1571}
1572
1573
1574int
1575do_X509_REQ_sign(BIO * err, X509_REQ * x, EVP_PKEY * pkey, const EVP_MD * md,
1576 STACK_OF(OPENSSL_STRING) * sigopts)
1577{
1578 int rv;
1579 EVP_MD_CTX mctx;
1580 EVP_MD_CTX_init(&mctx);
1581 rv = do_sign_init(err, &mctx, pkey, md, sigopts);
1582 if (rv > 0)
1583 rv = X509_REQ_sign_ctx(x, &mctx);
1584 EVP_MD_CTX_cleanup(&mctx);
1585 return rv > 0 ? 1 : 0;
1586}
1587
1588
1589
1590int
1591do_X509_CRL_sign(BIO * err, X509_CRL * x, EVP_PKEY * pkey, const EVP_MD * md,
1592 STACK_OF(OPENSSL_STRING) * sigopts)
1593{
1594 int rv;
1595 EVP_MD_CTX mctx;
1596 EVP_MD_CTX_init(&mctx);
1597 rv = do_sign_init(err, &mctx, pkey, md, sigopts);
1598 if (rv > 0)
1599 rv = X509_CRL_sign_ctx(x, &mctx);
1600 EVP_MD_CTX_cleanup(&mctx);
1601 return rv > 0 ? 1 : 0;
1602}
diff --git a/src/usr.bin/openssl/rsa.c b/src/usr.bin/openssl/rsa.c
new file mode 100644
index 0000000000..677e35f859
--- /dev/null
+++ b/src/usr.bin/openssl/rsa.c
@@ -0,0 +1,392 @@
1/* $OpenBSD: rsa.c,v 1.1 2014/08/26 17:47:25 jsing 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 <openssl/opensslconf.h>
60
61
62#include <stdio.h>
63#include <stdlib.h>
64#include <string.h>
65#include <time.h>
66
67#include "apps.h"
68
69#include <openssl/bio.h>
70#include <openssl/bn.h>
71#include <openssl/err.h>
72#include <openssl/evp.h>
73#include <openssl/pem.h>
74#include <openssl/rsa.h>
75#include <openssl/x509.h>
76
77/* -inform arg - input format - default PEM (one of DER, NET or PEM)
78 * -outform arg - output format - default PEM
79 * -in arg - input file - default stdin
80 * -out arg - output file - default stdout
81 * -des - encrypt output if PEM format with DES in cbc mode
82 * -des3 - encrypt output if PEM format
83 * -idea - encrypt output if PEM format
84 * -seed - encrypt output if PEM format
85 * -aes128 - encrypt output if PEM format
86 * -aes192 - encrypt output if PEM format
87 * -aes256 - encrypt output if PEM format
88 * -camellia128 - encrypt output if PEM format
89 * -camellia192 - encrypt output if PEM format
90 * -camellia256 - encrypt output if PEM format
91 * -text - print a text version
92 * -modulus - print the RSA key modulus
93 * -check - verify key consistency
94 * -pubin - Expect a public key in input file.
95 * -pubout - Output a public key.
96 */
97
98int rsa_main(int, char **);
99
100int
101rsa_main(int argc, char **argv)
102{
103 ENGINE *e = NULL;
104 int ret = 1;
105 RSA *rsa = NULL;
106 int i, badops = 0, sgckey = 0;
107 const EVP_CIPHER *enc = NULL;
108 BIO *out = NULL;
109 int informat, outformat, text = 0, check = 0, noout = 0;
110 int pubin = 0, pubout = 0;
111 char *infile, *outfile, *prog;
112 char *passargin = NULL, *passargout = NULL;
113 char *passin = NULL, *passout = NULL;
114#ifndef OPENSSL_NO_ENGINE
115 char *engine = NULL;
116#endif
117 int modulus = 0;
118
119 int pvk_encr = 2;
120
121 infile = NULL;
122 outfile = NULL;
123 informat = FORMAT_PEM;
124 outformat = FORMAT_PEM;
125
126 prog = argv[0];
127 argc--;
128 argv++;
129 while (argc >= 1) {
130 if (strcmp(*argv, "-inform") == 0) {
131 if (--argc < 1)
132 goto bad;
133 informat = str2fmt(*(++argv));
134 } else if (strcmp(*argv, "-outform") == 0) {
135 if (--argc < 1)
136 goto bad;
137 outformat = str2fmt(*(++argv));
138 } else if (strcmp(*argv, "-in") == 0) {
139 if (--argc < 1)
140 goto bad;
141 infile = *(++argv);
142 } else if (strcmp(*argv, "-out") == 0) {
143 if (--argc < 1)
144 goto bad;
145 outfile = *(++argv);
146 } else if (strcmp(*argv, "-passin") == 0) {
147 if (--argc < 1)
148 goto bad;
149 passargin = *(++argv);
150 } else if (strcmp(*argv, "-passout") == 0) {
151 if (--argc < 1)
152 goto bad;
153 passargout = *(++argv);
154 }
155#ifndef OPENSSL_NO_ENGINE
156 else if (strcmp(*argv, "-engine") == 0) {
157 if (--argc < 1)
158 goto bad;
159 engine = *(++argv);
160 }
161#endif
162 else if (strcmp(*argv, "-sgckey") == 0)
163 sgckey = 1;
164 else if (strcmp(*argv, "-pubin") == 0)
165 pubin = 1;
166 else if (strcmp(*argv, "-pubout") == 0)
167 pubout = 1;
168 else if (strcmp(*argv, "-RSAPublicKey_in") == 0)
169 pubin = 2;
170 else if (strcmp(*argv, "-RSAPublicKey_out") == 0)
171 pubout = 2;
172 else if (strcmp(*argv, "-pvk-strong") == 0)
173 pvk_encr = 2;
174 else if (strcmp(*argv, "-pvk-weak") == 0)
175 pvk_encr = 1;
176 else if (strcmp(*argv, "-pvk-none") == 0)
177 pvk_encr = 0;
178 else if (strcmp(*argv, "-noout") == 0)
179 noout = 1;
180 else if (strcmp(*argv, "-text") == 0)
181 text = 1;
182 else if (strcmp(*argv, "-modulus") == 0)
183 modulus = 1;
184 else if (strcmp(*argv, "-check") == 0)
185 check = 1;
186 else if ((enc = EVP_get_cipherbyname(&(argv[0][1]))) == NULL) {
187 BIO_printf(bio_err, "unknown option %s\n", *argv);
188 badops = 1;
189 break;
190 }
191 argc--;
192 argv++;
193 }
194
195 if (badops) {
196bad:
197 BIO_printf(bio_err, "%s [options] <infile >outfile\n", prog);
198 BIO_printf(bio_err, "where options are\n");
199 BIO_printf(bio_err, " -inform arg input format - one of DER NET PEM\n");
200 BIO_printf(bio_err, " -outform arg output format - one of DER NET PEM\n");
201 BIO_printf(bio_err, " -in arg input file\n");
202 BIO_printf(bio_err, " -sgckey Use IIS SGC key format\n");
203 BIO_printf(bio_err, " -passin arg input file pass phrase source\n");
204 BIO_printf(bio_err, " -out arg output file\n");
205 BIO_printf(bio_err, " -passout arg output file pass phrase source\n");
206 BIO_printf(bio_err, " -des encrypt PEM output with cbc des\n");
207 BIO_printf(bio_err, " -des3 encrypt PEM output with ede cbc des using 168 bit key\n");
208#ifndef OPENSSL_NO_IDEA
209 BIO_printf(bio_err, " -idea encrypt PEM output with cbc idea\n");
210#endif
211#ifndef OPENSSL_NO_AES
212 BIO_printf(bio_err, " -aes128, -aes192, -aes256\n");
213 BIO_printf(bio_err, " encrypt PEM output with cbc aes\n");
214#endif
215#ifndef OPENSSL_NO_CAMELLIA
216 BIO_printf(bio_err, " -camellia128, -camellia192, -camellia256\n");
217 BIO_printf(bio_err, " encrypt PEM output with cbc camellia\n");
218#endif
219 BIO_printf(bio_err, " -text print the key in text\n");
220 BIO_printf(bio_err, " -noout don't print key out\n");
221 BIO_printf(bio_err, " -modulus print the RSA key modulus\n");
222 BIO_printf(bio_err, " -check verify key consistency\n");
223 BIO_printf(bio_err, " -pubin expect a public key in input file\n");
224 BIO_printf(bio_err, " -pubout output a public key\n");
225#ifndef OPENSSL_NO_ENGINE
226 BIO_printf(bio_err, " -engine e use engine e, possibly a hardware device.\n");
227#endif
228 goto end;
229 }
230 ERR_load_crypto_strings();
231
232#ifndef OPENSSL_NO_ENGINE
233 e = setup_engine(bio_err, engine, 0);
234#endif
235
236 if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
237 BIO_printf(bio_err, "Error getting passwords\n");
238 goto end;
239 }
240 if (check && pubin) {
241 BIO_printf(bio_err, "Only private keys can be checked\n");
242 goto end;
243 }
244 out = BIO_new(BIO_s_file());
245
246 {
247 EVP_PKEY *pkey;
248
249 if (pubin) {
250 int tmpformat = -1;
251 if (pubin == 2) {
252 if (informat == FORMAT_PEM)
253 tmpformat = FORMAT_PEMRSA;
254 else if (informat == FORMAT_ASN1)
255 tmpformat = FORMAT_ASN1RSA;
256 } else if (informat == FORMAT_NETSCAPE && sgckey)
257 tmpformat = FORMAT_IISSGC;
258 else
259 tmpformat = informat;
260
261 pkey = load_pubkey(bio_err, infile, tmpformat, 1,
262 passin, e, "Public Key");
263 } else
264 pkey = load_key(bio_err, infile,
265 (informat == FORMAT_NETSCAPE && sgckey ?
266 FORMAT_IISSGC : informat), 1,
267 passin, e, "Private Key");
268
269 if (pkey != NULL)
270 rsa = EVP_PKEY_get1_RSA(pkey);
271 EVP_PKEY_free(pkey);
272 }
273
274 if (rsa == NULL) {
275 ERR_print_errors(bio_err);
276 goto end;
277 }
278 if (outfile == NULL) {
279 BIO_set_fp(out, stdout, BIO_NOCLOSE);
280 } else {
281 if (BIO_write_filename(out, outfile) <= 0) {
282 perror(outfile);
283 goto end;
284 }
285 }
286
287 if (text)
288 if (!RSA_print(out, rsa, 0)) {
289 perror(outfile);
290 ERR_print_errors(bio_err);
291 goto end;
292 }
293 if (modulus) {
294 BIO_printf(out, "Modulus=");
295 BN_print(out, rsa->n);
296 BIO_printf(out, "\n");
297 }
298 if (check) {
299 int r = RSA_check_key(rsa);
300
301 if (r == 1)
302 BIO_printf(out, "RSA key ok\n");
303 else if (r == 0) {
304 unsigned long err;
305
306 while ((err = ERR_peek_error()) != 0 &&
307 ERR_GET_LIB(err) == ERR_LIB_RSA &&
308 ERR_GET_FUNC(err) == RSA_F_RSA_CHECK_KEY &&
309 ERR_GET_REASON(err) != ERR_R_MALLOC_FAILURE) {
310 BIO_printf(out, "RSA key error: %s\n", ERR_reason_error_string(err));
311 ERR_get_error(); /* remove e from error
312 * stack */
313 }
314 }
315 if (r == -1 || ERR_peek_error() != 0) { /* should happen only if
316 * r == -1 */
317 ERR_print_errors(bio_err);
318 goto end;
319 }
320 }
321 if (noout) {
322 ret = 0;
323 goto end;
324 }
325 BIO_printf(bio_err, "writing RSA key\n");
326 if (outformat == FORMAT_ASN1) {
327 if (pubout || pubin) {
328 if (pubout == 2)
329 i = i2d_RSAPublicKey_bio(out, rsa);
330 else
331 i = i2d_RSA_PUBKEY_bio(out, rsa);
332 } else
333 i = i2d_RSAPrivateKey_bio(out, rsa);
334 }
335#ifndef OPENSSL_NO_RC4
336 else if (outformat == FORMAT_NETSCAPE) {
337 unsigned char *p, *pp;
338 int size;
339
340 i = 1;
341 size = i2d_RSA_NET(rsa, NULL, NULL, sgckey);
342 if ((p = malloc(size)) == NULL) {
343 BIO_printf(bio_err, "Memory allocation failure\n");
344 goto end;
345 }
346 pp = p;
347 i2d_RSA_NET(rsa, &p, NULL, sgckey);
348 BIO_write(out, (char *) pp, size);
349 free(pp);
350 }
351#endif
352 else if (outformat == FORMAT_PEM) {
353 if (pubout || pubin) {
354 if (pubout == 2)
355 i = PEM_write_bio_RSAPublicKey(out, rsa);
356 else
357 i = PEM_write_bio_RSA_PUBKEY(out, rsa);
358 } else
359 i = PEM_write_bio_RSAPrivateKey(out, rsa,
360 enc, NULL, 0, NULL, passout);
361#if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_RC4)
362 } else if (outformat == FORMAT_MSBLOB || outformat == FORMAT_PVK) {
363 EVP_PKEY *pk;
364 pk = EVP_PKEY_new();
365 EVP_PKEY_set1_RSA(pk, rsa);
366 if (outformat == FORMAT_PVK)
367 i = i2b_PVK_bio(out, pk, pvk_encr, 0, passout);
368 else if (pubin || pubout)
369 i = i2b_PublicKey_bio(out, pk);
370 else
371 i = i2b_PrivateKey_bio(out, pk);
372 EVP_PKEY_free(pk);
373#endif
374 } else {
375 BIO_printf(bio_err, "bad output format specified for outfile\n");
376 goto end;
377 }
378 if (i <= 0) {
379 BIO_printf(bio_err, "unable to write key\n");
380 ERR_print_errors(bio_err);
381 } else
382 ret = 0;
383end:
384 if (out != NULL)
385 BIO_free_all(out);
386 if (rsa != NULL)
387 RSA_free(rsa);
388 free(passin);
389 free(passout);
390
391 return (ret);
392}
diff --git a/src/usr.bin/openssl/rsautl.c b/src/usr.bin/openssl/rsautl.c
new file mode 100644
index 0000000000..7c83f1a82c
--- /dev/null
+++ b/src/usr.bin/openssl/rsautl.c
@@ -0,0 +1,341 @@
1/* $OpenBSD: rsautl.c,v 1.1 2014/08/26 17:47:25 jsing Exp $ */
2/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3 * project 2000.
4 */
5/* ====================================================================
6 * Copyright (c) 2000 The OpenSSL Project. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
19 *
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24 *
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * licensing@OpenSSL.org.
29 *
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
33 *
34 * 6. Redistributions of any form whatsoever must retain the following
35 * acknowledgment:
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
52 *
53 * This product includes cryptographic software written by Eric Young
54 * (eay@cryptsoft.com). This product includes software written by Tim
55 * Hudson (tjh@cryptsoft.com).
56 *
57 */
58
59#include <openssl/opensslconf.h>
60
61
62#include <string.h>
63
64#include "apps.h"
65
66#include <openssl/err.h>
67#include <openssl/pem.h>
68#include <openssl/rsa.h>
69
70#define RSA_SIGN 1
71#define RSA_VERIFY 2
72#define RSA_ENCRYPT 3
73#define RSA_DECRYPT 4
74
75#define KEY_PRIVKEY 1
76#define KEY_PUBKEY 2
77#define KEY_CERT 3
78
79static void usage(void);
80
81int rsautl_main(int argc, char **);
82
83int
84rsautl_main(int argc, char **argv)
85{
86 ENGINE *e = NULL;
87 BIO *in = NULL, *out = NULL;
88 char *infile = NULL, *outfile = NULL;
89#ifndef OPENSSL_NO_ENGINE
90 char *engine = NULL;
91#endif
92 char *keyfile = NULL;
93 char rsa_mode = RSA_VERIFY, key_type = KEY_PRIVKEY;
94 int keyform = FORMAT_PEM;
95 char need_priv = 0, badarg = 0, rev = 0;
96 char hexdump = 0, asn1parse = 0;
97 X509 *x;
98 EVP_PKEY *pkey = NULL;
99 RSA *rsa = NULL;
100 unsigned char *rsa_in = NULL, *rsa_out = NULL, pad;
101 char *passargin = NULL, *passin = NULL;
102 int rsa_inlen, rsa_outlen = 0;
103 int keysize;
104
105 int ret = 1;
106
107 argc--;
108 argv++;
109
110 ERR_load_crypto_strings();
111 OpenSSL_add_all_algorithms();
112 pad = RSA_PKCS1_PADDING;
113
114 while (argc >= 1) {
115 if (!strcmp(*argv, "-in")) {
116 if (--argc < 1)
117 badarg = 1;
118 else
119 infile = *(++argv);
120 } else if (!strcmp(*argv, "-out")) {
121 if (--argc < 1)
122 badarg = 1;
123 else
124 outfile = *(++argv);
125 } else if (!strcmp(*argv, "-inkey")) {
126 if (--argc < 1)
127 badarg = 1;
128 else
129 keyfile = *(++argv);
130 } else if (!strcmp(*argv, "-passin")) {
131 if (--argc < 1)
132 badarg = 1;
133 else
134 passargin = *(++argv);
135 } else if (strcmp(*argv, "-keyform") == 0) {
136 if (--argc < 1)
137 badarg = 1;
138 else
139 keyform = str2fmt(*(++argv));
140#ifndef OPENSSL_NO_ENGINE
141 } else if (!strcmp(*argv, "-engine")) {
142 if (--argc < 1)
143 badarg = 1;
144 else
145 engine = *(++argv);
146#endif
147 } else if (!strcmp(*argv, "-pubin")) {
148 key_type = KEY_PUBKEY;
149 } else if (!strcmp(*argv, "-certin")) {
150 key_type = KEY_CERT;
151 } else if (!strcmp(*argv, "-asn1parse"))
152 asn1parse = 1;
153 else if (!strcmp(*argv, "-hexdump"))
154 hexdump = 1;
155 else if (!strcmp(*argv, "-raw"))
156 pad = RSA_NO_PADDING;
157 else if (!strcmp(*argv, "-oaep"))
158 pad = RSA_PKCS1_OAEP_PADDING;
159 else if (!strcmp(*argv, "-ssl"))
160 pad = RSA_SSLV23_PADDING;
161 else if (!strcmp(*argv, "-pkcs"))
162 pad = RSA_PKCS1_PADDING;
163 else if (!strcmp(*argv, "-x931"))
164 pad = RSA_X931_PADDING;
165 else if (!strcmp(*argv, "-sign")) {
166 rsa_mode = RSA_SIGN;
167 need_priv = 1;
168 } else if (!strcmp(*argv, "-verify"))
169 rsa_mode = RSA_VERIFY;
170 else if (!strcmp(*argv, "-rev"))
171 rev = 1;
172 else if (!strcmp(*argv, "-encrypt"))
173 rsa_mode = RSA_ENCRYPT;
174 else if (!strcmp(*argv, "-decrypt")) {
175 rsa_mode = RSA_DECRYPT;
176 need_priv = 1;
177 } else
178 badarg = 1;
179 if (badarg) {
180 usage();
181 goto end;
182 }
183 argc--;
184 argv++;
185 }
186
187 if (need_priv && (key_type != KEY_PRIVKEY)) {
188 BIO_printf(bio_err, "A private key is needed for this operation\n");
189 goto end;
190 }
191#ifndef OPENSSL_NO_ENGINE
192 e = setup_engine(bio_err, engine, 0);
193#endif
194 if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) {
195 BIO_printf(bio_err, "Error getting password\n");
196 goto end;
197 }
198
199 switch (key_type) {
200 case KEY_PRIVKEY:
201 pkey = load_key(bio_err, keyfile, keyform, 0,
202 passin, e, "Private Key");
203 break;
204
205 case KEY_PUBKEY:
206 pkey = load_pubkey(bio_err, keyfile, keyform, 0,
207 NULL, e, "Public Key");
208 break;
209
210 case KEY_CERT:
211 x = load_cert(bio_err, keyfile, keyform,
212 NULL, e, "Certificate");
213 if (x) {
214 pkey = X509_get_pubkey(x);
215 X509_free(x);
216 }
217 break;
218 }
219
220 if (!pkey) {
221 return 1;
222 }
223 rsa = EVP_PKEY_get1_RSA(pkey);
224 EVP_PKEY_free(pkey);
225
226 if (!rsa) {
227 BIO_printf(bio_err, "Error getting RSA key\n");
228 ERR_print_errors(bio_err);
229 goto end;
230 }
231 if (infile) {
232 if (!(in = BIO_new_file(infile, "rb"))) {
233 BIO_printf(bio_err, "Error Reading Input File\n");
234 ERR_print_errors(bio_err);
235 goto end;
236 }
237 } else
238 in = BIO_new_fp(stdin, BIO_NOCLOSE);
239
240 if (outfile) {
241 if (!(out = BIO_new_file(outfile, "wb"))) {
242 BIO_printf(bio_err, "Error Reading Output File\n");
243 ERR_print_errors(bio_err);
244 goto end;
245 }
246 } else {
247 out = BIO_new_fp(stdout, BIO_NOCLOSE);
248 }
249
250 keysize = RSA_size(rsa);
251
252 rsa_in = reallocarray(NULL, keysize, 2);
253 rsa_out = malloc(keysize);
254
255 /* Read the input data */
256 rsa_inlen = BIO_read(in, rsa_in, keysize * 2);
257 if (rsa_inlen <= 0) {
258 BIO_printf(bio_err, "Error reading input Data\n");
259 exit(1);
260 }
261 if (rev) {
262 int i;
263 unsigned char ctmp;
264 for (i = 0; i < rsa_inlen / 2; i++) {
265 ctmp = rsa_in[i];
266 rsa_in[i] = rsa_in[rsa_inlen - 1 - i];
267 rsa_in[rsa_inlen - 1 - i] = ctmp;
268 }
269 }
270 switch (rsa_mode) {
271
272 case RSA_VERIFY:
273 rsa_outlen = RSA_public_decrypt(rsa_inlen, rsa_in, rsa_out, rsa, pad);
274 break;
275
276 case RSA_SIGN:
277 rsa_outlen = RSA_private_encrypt(rsa_inlen, rsa_in, rsa_out, rsa, pad);
278 break;
279
280 case RSA_ENCRYPT:
281 rsa_outlen = RSA_public_encrypt(rsa_inlen, rsa_in, rsa_out, rsa, pad);
282 break;
283
284 case RSA_DECRYPT:
285 rsa_outlen = RSA_private_decrypt(rsa_inlen, rsa_in, rsa_out, rsa, pad);
286 break;
287
288 }
289
290 if (rsa_outlen <= 0) {
291 BIO_printf(bio_err, "RSA operation error\n");
292 ERR_print_errors(bio_err);
293 goto end;
294 }
295 ret = 0;
296 if (asn1parse) {
297 if (!ASN1_parse_dump(out, rsa_out, rsa_outlen, 1, -1)) {
298 ERR_print_errors(bio_err);
299 }
300 } else if (hexdump)
301 BIO_dump(out, (char *) rsa_out, rsa_outlen);
302 else
303 BIO_write(out, rsa_out, rsa_outlen);
304
305end:
306 RSA_free(rsa);
307 BIO_free(in);
308 BIO_free_all(out);
309 free(rsa_in);
310 free(rsa_out);
311 free(passin);
312
313 return ret;
314}
315
316static void
317usage()
318{
319 BIO_printf(bio_err, "Usage: rsautl [options]\n");
320 BIO_printf(bio_err, "-in file input file\n");
321 BIO_printf(bio_err, "-out file output file\n");
322 BIO_printf(bio_err, "-inkey file input key\n");
323 BIO_printf(bio_err, "-keyform arg private key format - default PEM\n");
324 BIO_printf(bio_err, "-pubin input is an RSA public\n");
325 BIO_printf(bio_err, "-certin input is a certificate carrying an RSA public key\n");
326 BIO_printf(bio_err, "-ssl use SSL v2 padding\n");
327 BIO_printf(bio_err, "-raw use no padding\n");
328 BIO_printf(bio_err, "-pkcs use PKCS#1 v1.5 padding (default)\n");
329 BIO_printf(bio_err, "-oaep use PKCS#1 OAEP\n");
330 BIO_printf(bio_err, "-sign sign with private key\n");
331 BIO_printf(bio_err, "-verify verify with public key\n");
332 BIO_printf(bio_err, "-encrypt encrypt with public key\n");
333 BIO_printf(bio_err, "-decrypt decrypt with private key\n");
334 BIO_printf(bio_err, "-hexdump hex dump output\n");
335#ifndef OPENSSL_NO_ENGINE
336 BIO_printf(bio_err, "-engine e use engine e, possibly a hardware device.\n");
337 BIO_printf(bio_err, "-passin arg pass phrase source\n");
338#endif
339
340}
341
diff --git a/src/usr.bin/openssl/s_apps.h b/src/usr.bin/openssl/s_apps.h
new file mode 100644
index 0000000000..dd4b733afb
--- /dev/null
+++ b/src/usr.bin/openssl/s_apps.h
@@ -0,0 +1,147 @@
1/* $OpenBSD: s_apps.h,v 1.1 2014/08/26 17:47:25 jsing 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 * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in
70 * the documentation and/or other materials provided with the
71 * distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 * software must display the following acknowledgment:
75 * "This product includes software developed by the OpenSSL Project
76 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 * endorse or promote products derived from this software without
80 * prior written permission. For written permission, please contact
81 * openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 * nor may "OpenSSL" appear in their names without prior written
85 * permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 * acknowledgment:
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com). This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
111#include <sys/types.h>
112#include <openssl/opensslconf.h>
113
114#define PORT 4433
115#define PORT_STR "4433"
116#define PROTOCOL "tcp"
117
118int do_server(int port, int type, int *ret,
119 int (*cb)(char *hostname, int s, unsigned char *context),
120 unsigned char *context);
121#ifdef HEADER_X509_H
122int verify_callback(int ok, X509_STORE_CTX *ctx);
123#endif
124#ifdef HEADER_SSL_H
125int set_cert_stuff(SSL_CTX *ctx, char *cert_file, char *key_file);
126int set_cert_key_stuff(SSL_CTX *ctx, X509 *cert, EVP_PKEY *key);
127#endif
128int init_client(int *sock, char *server, char *port, int type, int af);
129int should_retry(int i);
130int extract_port(char *str, short *port_ptr);
131int extract_host_port(char *str, char **host_ptr, unsigned char *ip, char **p);
132
133long bio_dump_callback(BIO *bio, int cmd, const char *argp, int argi,
134 long argl, long ret);
135
136#ifdef HEADER_SSL_H
137void apps_ssl_info_callback(const SSL *s, int where, int ret);
138void msg_cb(int write_p, int version, int content_type, const void *buf,
139 size_t len, SSL *ssl, void *arg);
140void tlsext_cb(SSL *s, int client_server, int type, unsigned char *data,
141 int len, void *arg);
142#endif
143
144int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
145 unsigned int *cookie_len);
146int verify_cookie_callback(SSL *ssl, unsigned char *cookie,
147 unsigned int cookie_len);
diff --git a/src/usr.bin/openssl/s_cb.c b/src/usr.bin/openssl/s_cb.c
new file mode 100644
index 0000000000..2e00abe7f1
--- /dev/null
+++ b/src/usr.bin/openssl/s_cb.c
@@ -0,0 +1,854 @@
1/* $OpenBSD: s_cb.c,v 1.1 2014/08/26 17:47:25 jsing 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 * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in
70 * the documentation and/or other materials provided with the
71 * distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 * software must display the following acknowledgment:
75 * "This product includes software developed by the OpenSSL Project
76 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 * endorse or promote products derived from this software without
80 * prior written permission. For written permission, please contact
81 * openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 * nor may "OpenSSL" appear in their names without prior written
85 * permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 * acknowledgment:
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com). This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
111
112#include <sys/socket.h>
113
114#include <netinet/in.h>
115
116#include <netdb.h>
117#include <stdio.h>
118#include <stdlib.h>
119#include <string.h>
120
121#include "apps.h"
122
123#include <openssl/err.h>
124#include <openssl/rand.h>
125#include <openssl/ssl.h>
126#include <openssl/x509.h>
127
128#include "s_apps.h"
129
130#define COOKIE_SECRET_LENGTH 16
131
132int verify_depth = 0;
133int verify_error = X509_V_OK;
134int verify_return_error = 0;
135unsigned char cookie_secret[COOKIE_SECRET_LENGTH];
136int cookie_initialized = 0;
137
138int
139verify_callback(int ok, X509_STORE_CTX * ctx)
140{
141 X509 *err_cert;
142 int err, depth;
143
144 err_cert = X509_STORE_CTX_get_current_cert(ctx);
145 err = X509_STORE_CTX_get_error(ctx);
146 depth = X509_STORE_CTX_get_error_depth(ctx);
147
148 BIO_printf(bio_err, "depth=%d ", depth);
149 if (err_cert) {
150 X509_NAME_print_ex(bio_err, X509_get_subject_name(err_cert),
151 0, XN_FLAG_ONELINE);
152 BIO_puts(bio_err, "\n");
153 } else
154 BIO_puts(bio_err, "<no cert>\n");
155 if (!ok) {
156 BIO_printf(bio_err, "verify error:num=%d:%s\n", err,
157 X509_verify_cert_error_string(err));
158 if (verify_depth >= depth) {
159 if (!verify_return_error)
160 ok = 1;
161 verify_error = X509_V_OK;
162 } else {
163 ok = 0;
164 verify_error = X509_V_ERR_CERT_CHAIN_TOO_LONG;
165 }
166 }
167 switch (err) {
168 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
169 BIO_puts(bio_err, "issuer= ");
170 X509_NAME_print_ex(bio_err, X509_get_issuer_name(err_cert),
171 0, XN_FLAG_ONELINE);
172 BIO_puts(bio_err, "\n");
173 break;
174 case X509_V_ERR_CERT_NOT_YET_VALID:
175 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
176 BIO_printf(bio_err, "notBefore=");
177 ASN1_TIME_print(bio_err, X509_get_notBefore(err_cert));
178 BIO_printf(bio_err, "\n");
179 break;
180 case X509_V_ERR_CERT_HAS_EXPIRED:
181 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
182 BIO_printf(bio_err, "notAfter=");
183 ASN1_TIME_print(bio_err, X509_get_notAfter(err_cert));
184 BIO_printf(bio_err, "\n");
185 break;
186 case X509_V_ERR_NO_EXPLICIT_POLICY:
187 policies_print(bio_err, ctx);
188 break;
189 }
190 if (err == X509_V_OK && ok == 2)
191 policies_print(bio_err, ctx);
192
193 BIO_printf(bio_err, "verify return:%d\n", ok);
194 return (ok);
195}
196
197int
198set_cert_stuff(SSL_CTX * ctx, char *cert_file, char *key_file)
199{
200 if (cert_file != NULL) {
201 /*
202 SSL *ssl;
203 X509 *x509;
204 */
205
206 if (SSL_CTX_use_certificate_file(ctx, cert_file,
207 SSL_FILETYPE_PEM) <= 0) {
208 BIO_printf(bio_err,
209 "unable to get certificate from '%s'\n", cert_file);
210 ERR_print_errors(bio_err);
211 return (0);
212 }
213 if (key_file == NULL)
214 key_file = cert_file;
215 if (SSL_CTX_use_PrivateKey_file(ctx, key_file,
216 SSL_FILETYPE_PEM) <= 0) {
217 BIO_printf(bio_err,
218 "unable to get private key from '%s'\n", key_file);
219 ERR_print_errors(bio_err);
220 return (0);
221 }
222 /*
223 In theory this is no longer needed
224 ssl=SSL_new(ctx);
225 x509=SSL_get_certificate(ssl);
226
227 if (x509 != NULL) {
228 EVP_PKEY *pktmp;
229 pktmp = X509_get_pubkey(x509);
230 EVP_PKEY_copy_parameters(pktmp,
231 SSL_get_privatekey(ssl));
232 EVP_PKEY_free(pktmp);
233 }
234 SSL_free(ssl);
235 */
236
237 /*
238 * If we are using DSA, we can copy the parameters from the
239 * private key
240 */
241
242
243 /*
244 * Now we know that a key and cert have been set against the
245 * SSL context
246 */
247 if (!SSL_CTX_check_private_key(ctx)) {
248 BIO_printf(bio_err,
249 "Private key does not match the certificate public key\n");
250 return (0);
251 }
252 }
253 return (1);
254}
255
256int
257set_cert_key_stuff(SSL_CTX * ctx, X509 * cert, EVP_PKEY * key)
258{
259 if (cert == NULL)
260 return 1;
261 if (SSL_CTX_use_certificate(ctx, cert) <= 0) {
262 BIO_printf(bio_err, "error setting certificate\n");
263 ERR_print_errors(bio_err);
264 return 0;
265 }
266 if (SSL_CTX_use_PrivateKey(ctx, key) <= 0) {
267 BIO_printf(bio_err, "error setting private key\n");
268 ERR_print_errors(bio_err);
269 return 0;
270 }
271 /*
272 * Now we know that a key and cert have been set against the SSL
273 * context
274 */
275 if (!SSL_CTX_check_private_key(ctx)) {
276 BIO_printf(bio_err,
277 "Private key does not match the certificate public key\n");
278 return 0;
279 }
280 return 1;
281}
282
283long
284bio_dump_callback(BIO * bio, int cmd, const char *argp,
285 int argi, long argl, long ret)
286{
287 BIO *out;
288
289 out = (BIO *) BIO_get_callback_arg(bio);
290 if (out == NULL)
291 return (ret);
292
293 if (cmd == (BIO_CB_READ | BIO_CB_RETURN)) {
294 BIO_printf(out,
295 "read from %p [%p] (%lu bytes => %ld (0x%lX))\n",
296 (void *) bio, argp, (unsigned long) argi, ret, ret);
297 BIO_dump(out, argp, (int) ret);
298 return (ret);
299 } else if (cmd == (BIO_CB_WRITE | BIO_CB_RETURN)) {
300 BIO_printf(out,
301 "write to %p [%p] (%lu bytes => %ld (0x%lX))\n",
302 (void *) bio, argp, (unsigned long) argi, ret, ret);
303 BIO_dump(out, argp, (int) ret);
304 }
305 return (ret);
306}
307
308void
309apps_ssl_info_callback(const SSL * s, int where, int ret)
310{
311 const char *str;
312 int w;
313
314 w = where & ~SSL_ST_MASK;
315
316 if (w & SSL_ST_CONNECT)
317 str = "SSL_connect";
318 else if (w & SSL_ST_ACCEPT)
319 str = "SSL_accept";
320 else
321 str = "undefined";
322
323 if (where & SSL_CB_LOOP) {
324 BIO_printf(bio_err, "%s:%s\n", str, SSL_state_string_long(s));
325 } else if (where & SSL_CB_ALERT) {
326 str = (where & SSL_CB_READ) ? "read" : "write";
327 BIO_printf(bio_err, "SSL3 alert %s:%s:%s\n", str,
328 SSL_alert_type_string_long(ret),
329 SSL_alert_desc_string_long(ret));
330 } else if (where & SSL_CB_EXIT) {
331 if (ret == 0)
332 BIO_printf(bio_err, "%s:failed in %s\n",
333 str, SSL_state_string_long(s));
334 else if (ret < 0) {
335 BIO_printf(bio_err, "%s:error in %s\n",
336 str, SSL_state_string_long(s));
337 }
338 }
339}
340
341
342void
343msg_cb(int write_p, int version, int content_type, const void *buf, size_t len, SSL * ssl, void *arg)
344{
345 BIO *bio = arg;
346 const char *str_write_p, *str_version, *str_content_type = "",
347 *str_details1 = "", *str_details2 = "";
348
349 str_write_p = write_p ? ">>>" : "<<<";
350
351 switch (version) {
352 case SSL2_VERSION:
353 str_version = "SSL 2.0";
354 break;
355 case SSL3_VERSION:
356 str_version = "SSL 3.0 ";
357 break;
358 case TLS1_VERSION:
359 str_version = "TLS 1.0 ";
360 break;
361 case TLS1_1_VERSION:
362 str_version = "TLS 1.1 ";
363 break;
364 case TLS1_2_VERSION:
365 str_version = "TLS 1.2 ";
366 break;
367 case DTLS1_VERSION:
368 str_version = "DTLS 1.0 ";
369 break;
370 case DTLS1_BAD_VER:
371 str_version = "DTLS 1.0 (bad) ";
372 break;
373 default:
374 str_version = "???";
375 }
376
377 if (version == SSL2_VERSION) {
378 str_details1 = "???";
379
380 if (len > 0) {
381 switch (((const unsigned char *) buf)[0]) {
382 case 0:
383 str_details1 = ", ERROR:";
384 str_details2 = " ???";
385 if (len >= 3) {
386 unsigned err = (((const unsigned char *) buf)[1] << 8) + ((const unsigned char *) buf)[2];
387
388 switch (err) {
389 case 0x0001:
390 str_details2 = " NO-CIPHER-ERROR";
391 break;
392 case 0x0002:
393 str_details2 = " NO-CERTIFICATE-ERROR";
394 break;
395 case 0x0004:
396 str_details2 = " BAD-CERTIFICATE-ERROR";
397 break;
398 case 0x0006:
399 str_details2 = " UNSUPPORTED-CERTIFICATE-TYPE-ERROR";
400 break;
401 }
402 }
403 break;
404 case 1:
405 str_details1 = ", CLIENT-HELLO";
406 break;
407 case 2:
408 str_details1 = ", CLIENT-MASTER-KEY";
409 break;
410 case 3:
411 str_details1 = ", CLIENT-FINISHED";
412 break;
413 case 4:
414 str_details1 = ", SERVER-HELLO";
415 break;
416 case 5:
417 str_details1 = ", SERVER-VERIFY";
418 break;
419 case 6:
420 str_details1 = ", SERVER-FINISHED";
421 break;
422 case 7:
423 str_details1 = ", REQUEST-CERTIFICATE";
424 break;
425 case 8:
426 str_details1 = ", CLIENT-CERTIFICATE";
427 break;
428 }
429 }
430 }
431 if (version == SSL3_VERSION || version == TLS1_VERSION ||
432 version == TLS1_1_VERSION || version == TLS1_2_VERSION ||
433 version == DTLS1_VERSION || version == DTLS1_BAD_VER) {
434 switch (content_type) {
435 case 20:
436 str_content_type = "ChangeCipherSpec";
437 break;
438 case 21:
439 str_content_type = "Alert";
440 break;
441 case 22:
442 str_content_type = "Handshake";
443 break;
444 }
445
446 if (content_type == 21) { /* Alert */
447 str_details1 = ", ???";
448
449 if (len == 2) {
450 switch (((const unsigned char *) buf)[0]) {
451 case 1:
452 str_details1 = ", warning";
453 break;
454 case 2:
455 str_details1 = ", fatal";
456 break;
457 }
458
459 str_details2 = " ???";
460 switch (((const unsigned char *) buf)[1]) {
461 case 0:
462 str_details2 = " close_notify";
463 break;
464 case 10:
465 str_details2 = " unexpected_message";
466 break;
467 case 20:
468 str_details2 = " bad_record_mac";
469 break;
470 case 21:
471 str_details2 = " decryption_failed";
472 break;
473 case 22:
474 str_details2 = " record_overflow";
475 break;
476 case 30:
477 str_details2 = " decompression_failure";
478 break;
479 case 40:
480 str_details2 = " handshake_failure";
481 break;
482 case 42:
483 str_details2 = " bad_certificate";
484 break;
485 case 43:
486 str_details2 = " unsupported_certificate";
487 break;
488 case 44:
489 str_details2 = " certificate_revoked";
490 break;
491 case 45:
492 str_details2 = " certificate_expired";
493 break;
494 case 46:
495 str_details2 = " certificate_unknown";
496 break;
497 case 47:
498 str_details2 = " illegal_parameter";
499 break;
500 case 48:
501 str_details2 = " unknown_ca";
502 break;
503 case 49:
504 str_details2 = " access_denied";
505 break;
506 case 50:
507 str_details2 = " decode_error";
508 break;
509 case 51:
510 str_details2 = " decrypt_error";
511 break;
512 case 60:
513 str_details2 = " export_restriction";
514 break;
515 case 70:
516 str_details2 = " protocol_version";
517 break;
518 case 71:
519 str_details2 = " insufficient_security";
520 break;
521 case 80:
522 str_details2 = " internal_error";
523 break;
524 case 90:
525 str_details2 = " user_canceled";
526 break;
527 case 100:
528 str_details2 = " no_renegotiation";
529 break;
530 case 110:
531 str_details2 = " unsupported_extension";
532 break;
533 case 111:
534 str_details2 = " certificate_unobtainable";
535 break;
536 case 112:
537 str_details2 = " unrecognized_name";
538 break;
539 case 113:
540 str_details2 = " bad_certificate_status_response";
541 break;
542 case 114:
543 str_details2 = " bad_certificate_hash_value";
544 break;
545 case 115:
546 str_details2 = " unknown_psk_identity";
547 break;
548 }
549 }
550 }
551 if (content_type == 22) { /* Handshake */
552 str_details1 = "???";
553
554 if (len > 0) {
555 switch (((const unsigned char *) buf)[0]) {
556 case 0:
557 str_details1 = ", HelloRequest";
558 break;
559 case 1:
560 str_details1 = ", ClientHello";
561 break;
562 case 2:
563 str_details1 = ", ServerHello";
564 break;
565 case 3:
566 str_details1 = ", HelloVerifyRequest";
567 break;
568 case 11:
569 str_details1 = ", Certificate";
570 break;
571 case 12:
572 str_details1 = ", ServerKeyExchange";
573 break;
574 case 13:
575 str_details1 = ", CertificateRequest";
576 break;
577 case 14:
578 str_details1 = ", ServerHelloDone";
579 break;
580 case 15:
581 str_details1 = ", CertificateVerify";
582 break;
583 case 16:
584 str_details1 = ", ClientKeyExchange";
585 break;
586 case 20:
587 str_details1 = ", Finished";
588 break;
589 }
590 }
591 }
592 }
593 BIO_printf(bio, "%s %s%s [length %04lx]%s%s\n", str_write_p,
594 str_version, str_content_type, (unsigned long) len,
595 str_details1, str_details2);
596
597 if (len > 0) {
598 size_t num, i;
599
600 BIO_printf(bio, " ");
601 num = len;
602#if 0
603 if (num > 16)
604 num = 16;
605#endif
606 for (i = 0; i < num; i++) {
607 if (i % 16 == 0 && i > 0)
608 BIO_printf(bio, "\n ");
609 BIO_printf(bio, " %02x",
610 ((const unsigned char *) buf)[i]);
611 }
612 if (i < len)
613 BIO_printf(bio, " ...");
614 BIO_printf(bio, "\n");
615 }
616 (void) BIO_flush(bio);
617}
618
619void
620tlsext_cb(SSL * s, int client_server, int type, unsigned char *data, int len,
621 void *arg)
622{
623 BIO *bio = arg;
624 char *extname;
625
626 switch (type) {
627 case TLSEXT_TYPE_server_name:
628 extname = "server name";
629 break;
630
631 case TLSEXT_TYPE_max_fragment_length:
632 extname = "max fragment length";
633 break;
634
635 case TLSEXT_TYPE_client_certificate_url:
636 extname = "client certificate URL";
637 break;
638
639 case TLSEXT_TYPE_trusted_ca_keys:
640 extname = "trusted CA keys";
641 break;
642
643 case TLSEXT_TYPE_truncated_hmac:
644 extname = "truncated HMAC";
645 break;
646
647 case TLSEXT_TYPE_status_request:
648 extname = "status request";
649 break;
650
651 case TLSEXT_TYPE_user_mapping:
652 extname = "user mapping";
653 break;
654
655 case TLSEXT_TYPE_client_authz:
656 extname = "client authz";
657 break;
658
659 case TLSEXT_TYPE_server_authz:
660 extname = "server authz";
661 break;
662
663 case TLSEXT_TYPE_cert_type:
664 extname = "cert type";
665 break;
666
667 case TLSEXT_TYPE_elliptic_curves:
668 extname = "elliptic curves";
669 break;
670
671 case TLSEXT_TYPE_ec_point_formats:
672 extname = "EC point formats";
673 break;
674
675 case TLSEXT_TYPE_srp:
676 extname = "SRP";
677 break;
678
679 case TLSEXT_TYPE_signature_algorithms:
680 extname = "signature algorithms";
681 break;
682
683 case TLSEXT_TYPE_use_srtp:
684 extname = "use SRTP";
685 break;
686
687 case TLSEXT_TYPE_heartbeat:
688 extname = "heartbeat";
689 break;
690
691 case TLSEXT_TYPE_session_ticket:
692 extname = "session ticket";
693 break;
694
695 case TLSEXT_TYPE_renegotiate:
696 extname = "renegotiation info";
697 break;
698
699#ifdef TLSEXT_TYPE_next_proto_neg
700 case TLSEXT_TYPE_next_proto_neg:
701 extname = "next protocol";
702 break;
703#endif
704
705 default:
706 extname = "unknown";
707 break;
708
709 }
710
711 BIO_printf(bio, "TLS %s extension \"%s\" (id=%d), len=%d\n",
712 client_server ? "server" : "client", extname, type, len);
713 BIO_dump(bio, (char *) data, len);
714 (void) BIO_flush(bio);
715}
716
717int
718generate_cookie_callback(SSL * ssl, unsigned char *cookie,
719 unsigned int *cookie_len)
720{
721 unsigned char *buffer, result[EVP_MAX_MD_SIZE];
722 unsigned int length, resultlength;
723 union {
724 struct sockaddr sa;
725 struct sockaddr_in s4;
726 struct sockaddr_in6 s6;
727 } peer;
728
729 /* Initialize a random secret */
730 if (!cookie_initialized) {
731 if (!RAND_bytes(cookie_secret, COOKIE_SECRET_LENGTH)) {
732 BIO_printf(bio_err,
733 "error setting random cookie secret\n");
734 return 0;
735 }
736 cookie_initialized = 1;
737 }
738 /* Read peer information */
739 (void) BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer);
740
741 /* Create buffer with peer's address and port */
742 length = 0;
743 switch (peer.sa.sa_family) {
744 case AF_INET:
745 length += sizeof(struct in_addr);
746 length += sizeof(peer.s4.sin_port);
747 break;
748 case AF_INET6:
749 length += sizeof(struct in6_addr);
750 length += sizeof(peer.s6.sin6_port);
751 break;
752 default:
753 OPENSSL_assert(0);
754 break;
755 }
756 buffer = malloc(length);
757
758 if (buffer == NULL) {
759 BIO_printf(bio_err, "out of memory\n");
760 return 0;
761 }
762 switch (peer.sa.sa_family) {
763 case AF_INET:
764 memcpy(buffer, &peer.s4.sin_port, sizeof(peer.s4.sin_port));
765 memcpy(buffer + sizeof(peer.s4.sin_port),
766 &peer.s4.sin_addr, sizeof(struct in_addr));
767 break;
768 case AF_INET6:
769 memcpy(buffer, &peer.s6.sin6_port, sizeof(peer.s6.sin6_port));
770 memcpy(buffer + sizeof(peer.s6.sin6_port),
771 &peer.s6.sin6_addr, sizeof(struct in6_addr));
772 break;
773 default:
774 OPENSSL_assert(0);
775 break;
776 }
777
778 /* Calculate HMAC of buffer using the secret */
779 HMAC(EVP_sha1(), cookie_secret, COOKIE_SECRET_LENGTH,
780 buffer, length, result, &resultlength);
781 free(buffer);
782
783 memcpy(cookie, result, resultlength);
784 *cookie_len = resultlength;
785
786 return 1;
787}
788
789int
790verify_cookie_callback(SSL * ssl, unsigned char *cookie, unsigned int cookie_len)
791{
792 unsigned char *buffer, result[EVP_MAX_MD_SIZE];
793 unsigned int length, resultlength;
794 union {
795 struct sockaddr sa;
796 struct sockaddr_in s4;
797 struct sockaddr_in6 s6;
798 } peer;
799
800 /* If secret isn't initialized yet, the cookie can't be valid */
801 if (!cookie_initialized)
802 return 0;
803
804 /* Read peer information */
805 (void) BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer);
806
807 /* Create buffer with peer's address and port */
808 length = 0;
809 switch (peer.sa.sa_family) {
810 case AF_INET:
811 length += sizeof(struct in_addr);
812 length += sizeof(peer.s4.sin_port);
813 break;
814 case AF_INET6:
815 length += sizeof(struct in6_addr);
816 length += sizeof(peer.s6.sin6_port);
817 break;
818 default:
819 OPENSSL_assert(0);
820 break;
821 }
822 buffer = malloc(length);
823
824 if (buffer == NULL) {
825 BIO_printf(bio_err, "out of memory\n");
826 return 0;
827 }
828 switch (peer.sa.sa_family) {
829 case AF_INET:
830 memcpy(buffer, &peer.s4.sin_port, sizeof(peer.s4.sin_port));
831 memcpy(buffer + sizeof(peer.s4.sin_port),
832 &peer.s4.sin_addr, sizeof(struct in_addr));
833 break;
834 case AF_INET6:
835 memcpy(buffer, &peer.s6.sin6_port, sizeof(peer.s6.sin6_port));
836 memcpy(buffer + sizeof(peer.s6.sin6_port),
837 &peer.s6.sin6_addr, sizeof(struct in6_addr));
838 break;
839 default:
840 OPENSSL_assert(0);
841 break;
842 }
843
844 /* Calculate HMAC of buffer using the secret */
845 HMAC(EVP_sha1(), cookie_secret, COOKIE_SECRET_LENGTH,
846 buffer, length, result, &resultlength);
847 free(buffer);
848
849 if (cookie_len == resultlength &&
850 memcmp(result, cookie, resultlength) == 0)
851 return 1;
852
853 return 0;
854}
diff --git a/src/usr.bin/openssl/s_client.c b/src/usr.bin/openssl/s_client.c
new file mode 100644
index 0000000000..f35624baca
--- /dev/null
+++ b/src/usr.bin/openssl/s_client.c
@@ -0,0 +1,1507 @@
1/* $OpenBSD: s_client.c,v 1.1 2014/08/26 17:47:25 jsing 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 * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in
70 * the documentation and/or other materials provided with the
71 * distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 * software must display the following acknowledgment:
75 * "This product includes software developed by the OpenSSL Project
76 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 * endorse or promote products derived from this software without
80 * prior written permission. For written permission, please contact
81 * openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 * nor may "OpenSSL" appear in their names without prior written
85 * permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 * acknowledgment:
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com). This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
111/* ====================================================================
112 * Copyright 2005 Nokia. All rights reserved.
113 *
114 * The portions of the attached software ("Contribution") is developed by
115 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
116 * license.
117 *
118 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
119 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
120 * support (see RFC 4279) to OpenSSL.
121 *
122 * No patent licenses or other rights except those expressly stated in
123 * the OpenSSL open source license shall be deemed granted or received
124 * expressly, by implication, estoppel, or otherwise.
125 *
126 * No assurances are provided by Nokia that the Contribution does not
127 * infringe the patent or other intellectual property rights of any third
128 * party or that the license provides you with all the necessary rights
129 * to make use of the Contribution.
130 *
131 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
132 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
133 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
134 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
135 * OTHERWISE.
136 */
137
138#include <sys/types.h>
139#include <sys/ioctl.h>
140#include <sys/select.h>
141#include <sys/socket.h>
142
143#include <netinet/in.h>
144
145#include <assert.h>
146#include <ctype.h>
147#include <limits.h>
148#include <netdb.h>
149#include <stdio.h>
150#include <stdlib.h>
151#include <limits.h>
152#include <string.h>
153#include <unistd.h>
154
155#include "apps.h"
156
157#include <openssl/bn.h>
158#include <openssl/err.h>
159#include <openssl/ocsp.h>
160#include <openssl/pem.h>
161#include <openssl/rand.h>
162#include <openssl/ssl.h>
163#include <openssl/x509.h>
164
165#include "s_apps.h"
166#include "timeouts.h"
167
168/*#define SSL_HOST_NAME "www.netscape.com" */
169/*#define SSL_HOST_NAME "193.118.187.102" */
170#define SSL_HOST_NAME "localhost"
171
172 /*#define TEST_CERT "client.pem" *//* no default cert. */
173
174#define BUFSIZZ 1024*8
175
176extern int verify_depth;
177extern int verify_error;
178extern int verify_return_error;
179
180static int c_nbio = 0;
181static int c_Pause = 0;
182static int c_debug = 0;
183#ifndef OPENSSL_NO_TLSEXT
184static int c_tlsextdebug = 0;
185static int c_status_req = 0;
186#endif
187static int c_msg = 0;
188static int c_showcerts = 0;
189
190static char *keymatexportlabel = NULL;
191static int keymatexportlen = 20;
192
193static void sc_usage(void);
194static void print_stuff(BIO * berr, SSL * con, int full);
195#ifndef OPENSSL_NO_TLSEXT
196static int ocsp_resp_cb(SSL * s, void *arg);
197#endif
198static BIO *bio_c_out = NULL;
199static int c_quiet = 0;
200static int c_ign_eof = 0;
201
202
203static void
204sc_usage(void)
205{
206 BIO_printf(bio_err, "usage: s_client args\n");
207 BIO_printf(bio_err, "\n");
208 BIO_printf(bio_err, " -4 - Force IPv4\n");
209 BIO_printf(bio_err, " -6 - Force IPv6\n");
210 BIO_printf(bio_err, " -host host - use -connect instead\n");
211 BIO_printf(bio_err, " -port port - use -connect instead\n");
212 BIO_printf(bio_err, " -connect host:port - who to connect to (default is %s:%s)\n", SSL_HOST_NAME, PORT_STR);
213
214 BIO_printf(bio_err, " -verify arg - turn on peer certificate verification\n");
215 BIO_printf(bio_err, " -cert arg - certificate file to use, PEM format assumed\n");
216 BIO_printf(bio_err, " -certform arg - certificate format (PEM or DER) PEM default\n");
217 BIO_printf(bio_err, " -key arg - Private key file to use, in cert file if\n");
218 BIO_printf(bio_err, " not specified but cert file is.\n");
219 BIO_printf(bio_err, " -keyform arg - key format (PEM or DER) PEM default\n");
220 BIO_printf(bio_err, " -pass arg - private key file pass phrase source\n");
221 BIO_printf(bio_err, " -CApath arg - PEM format directory of CA's\n");
222 BIO_printf(bio_err, " -CAfile arg - PEM format file of CA's\n");
223 BIO_printf(bio_err, " -reconnect - Drop and re-make the connection with the same Session-ID\n");
224 BIO_printf(bio_err, " -pause - sleep(1) after each read(2) and write(2) system call\n");
225 BIO_printf(bio_err, " -showcerts - show all certificates in the chain\n");
226 BIO_printf(bio_err, " -debug - extra output\n");
227 BIO_printf(bio_err, " -msg - Show protocol messages\n");
228 BIO_printf(bio_err, " -nbio_test - more ssl protocol testing\n");
229 BIO_printf(bio_err, " -state - print the 'ssl' states\n");
230 BIO_printf(bio_err, " -nbio - Run with non-blocking IO\n");
231 BIO_printf(bio_err, " -crlf - convert LF from terminal into CRLF\n");
232 BIO_printf(bio_err, " -quiet - no s_client output\n");
233 BIO_printf(bio_err, " -ign_eof - ignore input eof (default when -quiet)\n");
234 BIO_printf(bio_err, " -no_ign_eof - don't ignore input eof\n");
235 BIO_printf(bio_err, " -ssl3 - just use SSLv3\n");
236 BIO_printf(bio_err, " -tls1_2 - just use TLSv1.2\n");
237 BIO_printf(bio_err, " -tls1_1 - just use TLSv1.1\n");
238 BIO_printf(bio_err, " -tls1 - just use TLSv1\n");
239 BIO_printf(bio_err, " -dtls1 - just use DTLSv1\n");
240 BIO_printf(bio_err, " -mtu - set the link layer MTU\n");
241 BIO_printf(bio_err, " -no_tls1_2/-no_tls1_1/-no_tls1/-no_ssl3/-no_ssl2 - turn off that protocol\n");
242 BIO_printf(bio_err, " -bugs - Switch on all SSL implementation bug workarounds\n");
243 BIO_printf(bio_err, " -cipher - preferred cipher to use, use the 'openssl ciphers'\n");
244 BIO_printf(bio_err, " command to see what is available\n");
245 BIO_printf(bio_err, " -starttls prot - use the STARTTLS command before starting TLS\n");
246 BIO_printf(bio_err, " for those protocols that support it, where\n");
247 BIO_printf(bio_err, " 'prot' defines which one to assume. Currently,\n");
248 BIO_printf(bio_err, " only \"smtp\", \"lmtp\", \"pop3\", \"imap\", \"ftp\" and \"xmpp\"\n");
249 BIO_printf(bio_err, " are supported.\n");
250#ifndef OPENSSL_NO_ENGINE
251 BIO_printf(bio_err, " -engine id - Initialise and use the specified engine\n");
252#endif
253 BIO_printf(bio_err, " -sess_out arg - file to write SSL session to\n");
254 BIO_printf(bio_err, " -sess_in arg - file to read SSL session from\n");
255#ifndef OPENSSL_NO_TLSEXT
256 BIO_printf(bio_err, " -servername host - Set TLS extension servername in ClientHello\n");
257 BIO_printf(bio_err, " -tlsextdebug - hex dump of all TLS extensions received\n");
258 BIO_printf(bio_err, " -status - request certificate status from server\n");
259 BIO_printf(bio_err, " -no_ticket - disable use of RFC4507bis session tickets\n");
260#ifndef OPENSSL_NO_NEXTPROTONEG
261 BIO_printf(bio_err, " -nextprotoneg arg - enable NPN extension, considering named protocols supported (comma-separated list)\n");
262#endif
263#endif
264#ifndef OPENSSL_NO_SRTP
265 BIO_printf(bio_err, " -use_srtp profiles - Offer SRTP key management with a colon-separated profile list\n");
266#endif
267 BIO_printf(bio_err, " -keymatexport label - Export keying material using label\n");
268 BIO_printf(bio_err, " -keymatexportlen len - Export len bytes of keying material (default 20)\n");
269}
270
271#ifndef OPENSSL_NO_TLSEXT
272
273/* This is a context that we pass to callbacks */
274typedef struct tlsextctx_st {
275 BIO *biodebug;
276 int ack;
277} tlsextctx;
278
279
280static int
281ssl_servername_cb(SSL * s, int *ad, void *arg)
282{
283 tlsextctx *p = (tlsextctx *) arg;
284 const char *hn = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
285 if (SSL_get_servername_type(s) != -1)
286 p->ack = !SSL_session_reused(s) && hn != NULL;
287 else
288 BIO_printf(bio_err, "Can't use SSL_get_servername\n");
289
290 return SSL_TLSEXT_ERR_OK;
291}
292
293#ifndef OPENSSL_NO_SRTP
294char *srtp_profiles = NULL;
295#endif
296
297#ifndef OPENSSL_NO_NEXTPROTONEG
298/* This the context that we pass to next_proto_cb */
299typedef struct tlsextnextprotoctx_st {
300 unsigned char *data;
301 unsigned short len;
302 int status;
303} tlsextnextprotoctx;
304
305static tlsextnextprotoctx next_proto;
306
307static int
308next_proto_cb(SSL * s, unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg)
309{
310 tlsextnextprotoctx *ctx = arg;
311
312 if (!c_quiet) {
313 /* We can assume that |in| is syntactically valid. */
314 unsigned i;
315 BIO_printf(bio_c_out, "Protocols advertised by server: ");
316 for (i = 0; i < inlen;) {
317 if (i)
318 BIO_write(bio_c_out, ", ", 2);
319 BIO_write(bio_c_out, &in[i + 1], in[i]);
320 i += in[i] + 1;
321 }
322 BIO_write(bio_c_out, "\n", 1);
323 }
324 ctx->status = SSL_select_next_proto(out, outlen, in, inlen, ctx->data, ctx->len);
325 return SSL_TLSEXT_ERR_OK;
326}
327#endif /* ndef OPENSSL_NO_NEXTPROTONEG */
328#endif
329
330enum {
331 PROTO_OFF = 0,
332 PROTO_SMTP,
333 PROTO_LMTP,
334 PROTO_POP3,
335 PROTO_IMAP,
336 PROTO_FTP,
337 PROTO_XMPP
338};
339
340int s_client_main(int, char **);
341
342int
343s_client_main(int argc, char **argv)
344{
345 unsigned int off = 0, clr = 0;
346 SSL *con = NULL;
347 int s, k, width, state = 0, af = AF_UNSPEC;
348 char *cbuf = NULL, *sbuf = NULL, *mbuf = NULL;
349 int cbuf_len, cbuf_off;
350 int sbuf_len, sbuf_off;
351 fd_set readfds, writefds;
352 char *port = PORT_STR;
353 int full_log = 1;
354 char *host = SSL_HOST_NAME;
355 char *cert_file = NULL, *key_file = NULL;
356 int cert_format = FORMAT_PEM, key_format = FORMAT_PEM;
357 char *passarg = NULL, *pass = NULL;
358 X509 *cert = NULL;
359 EVP_PKEY *key = NULL;
360 char *CApath = NULL, *CAfile = NULL, *cipher = NULL;
361 int reconnect = 0, badop = 0, verify = SSL_VERIFY_NONE, bugs = 0;
362 int crlf = 0;
363 int write_tty, read_tty, write_ssl, read_ssl, tty_on, ssl_pending;
364 SSL_CTX *ctx = NULL;
365 int ret = 1, in_init = 1, i, nbio_test = 0;
366 int starttls_proto = PROTO_OFF;
367 int prexit = 0;
368 X509_VERIFY_PARAM *vpm = NULL;
369 int badarg = 0;
370 const SSL_METHOD *meth = NULL;
371 int socket_type = SOCK_STREAM;
372 BIO *sbio;
373 int mbuf_len = 0;
374 struct timeval timeout, *timeoutp;
375 const char *errstr = NULL;
376#ifndef OPENSSL_NO_ENGINE
377 char *engine_id = NULL;
378 char *ssl_client_engine_id = NULL;
379 ENGINE *ssl_client_engine = NULL;
380#endif
381 ENGINE *e = NULL;
382#ifndef OPENSSL_NO_TLSEXT
383 char *servername = NULL;
384 tlsextctx tlsextcbp =
385 {NULL, 0};
386#ifndef OPENSSL_NO_NEXTPROTONEG
387 const char *next_proto_neg_in = NULL;
388#endif
389#endif
390 char *sess_in = NULL;
391 char *sess_out = NULL;
392 struct sockaddr peer;
393 int peerlen = sizeof(peer);
394 int enable_timeouts = 0;
395 long socket_mtu = 0;
396
397 meth = SSLv23_client_method();
398
399 c_Pause = 0;
400 c_quiet = 0;
401 c_ign_eof = 0;
402 c_debug = 0;
403 c_msg = 0;
404 c_showcerts = 0;
405
406 if (((cbuf = malloc(BUFSIZZ)) == NULL) ||
407 ((sbuf = malloc(BUFSIZZ)) == NULL) ||
408 ((mbuf = malloc(BUFSIZZ + 1)) == NULL)) { /* NUL byte */
409 BIO_printf(bio_err, "out of memory\n");
410 goto end;
411 }
412 verify_depth = 0;
413 verify_error = X509_V_OK;
414 c_nbio = 0;
415
416 argc--;
417 argv++;
418 while (argc >= 1) {
419 if (strcmp(*argv, "-host") == 0) {
420 if (--argc < 1)
421 goto bad;
422 host = *(++argv);
423 } else if (strcmp(*argv, "-port") == 0) {
424 if (--argc < 1)
425 goto bad;
426 port = *(++argv);
427 if (port == NULL || *port == '\0')
428 goto bad;
429 } else if (strcmp(*argv, "-connect") == 0) {
430 if (--argc < 1)
431 goto bad;
432 if (!extract_host_port(*(++argv), &host, NULL, &port))
433 goto bad;
434 } else if (strcmp(*argv, "-verify") == 0) {
435 verify = SSL_VERIFY_PEER;
436 if (--argc < 1)
437 goto bad;
438 verify_depth = strtonum(*(++argv), 0, INT_MAX, &errstr);
439 if (errstr)
440 goto bad;
441 BIO_printf(bio_err, "verify depth is %d\n", verify_depth);
442 } else if (strcmp(*argv, "-cert") == 0) {
443 if (--argc < 1)
444 goto bad;
445 cert_file = *(++argv);
446 } else if (strcmp(*argv, "-sess_out") == 0) {
447 if (--argc < 1)
448 goto bad;
449 sess_out = *(++argv);
450 } else if (strcmp(*argv, "-sess_in") == 0) {
451 if (--argc < 1)
452 goto bad;
453 sess_in = *(++argv);
454 } else if (strcmp(*argv, "-certform") == 0) {
455 if (--argc < 1)
456 goto bad;
457 cert_format = str2fmt(*(++argv));
458 } else if (args_verify(&argv, &argc, &badarg, bio_err, &vpm)) {
459 if (badarg)
460 goto bad;
461 continue;
462 } else if (strcmp(*argv, "-verify_return_error") == 0)
463 verify_return_error = 1;
464 else if (strcmp(*argv, "-prexit") == 0)
465 prexit = 1;
466 else if (strcmp(*argv, "-crlf") == 0)
467 crlf = 1;
468 else if (strcmp(*argv, "-quiet") == 0) {
469 c_quiet = 1;
470 c_ign_eof = 1;
471 } else if (strcmp(*argv, "-ign_eof") == 0)
472 c_ign_eof = 1;
473 else if (strcmp(*argv, "-no_ign_eof") == 0)
474 c_ign_eof = 0;
475 else if (strcmp(*argv, "-pause") == 0)
476 c_Pause = 1;
477 else if (strcmp(*argv, "-debug") == 0)
478 c_debug = 1;
479#ifndef OPENSSL_NO_TLSEXT
480 else if (strcmp(*argv, "-tlsextdebug") == 0)
481 c_tlsextdebug = 1;
482 else if (strcmp(*argv, "-status") == 0)
483 c_status_req = 1;
484#endif
485 else if (strcmp(*argv, "-msg") == 0)
486 c_msg = 1;
487 else if (strcmp(*argv, "-showcerts") == 0)
488 c_showcerts = 1;
489 else if (strcmp(*argv, "-nbio_test") == 0)
490 nbio_test = 1;
491 else if (strcmp(*argv, "-state") == 0)
492 state = 1;
493 else if (strcmp(*argv, "-ssl3") == 0)
494 meth = SSLv3_client_method();
495 else if (strcmp(*argv, "-tls1_2") == 0)
496 meth = TLSv1_2_client_method();
497 else if (strcmp(*argv, "-tls1_1") == 0)
498 meth = TLSv1_1_client_method();
499 else if (strcmp(*argv, "-tls1") == 0)
500 meth = TLSv1_client_method();
501#ifndef OPENSSL_NO_DTLS1
502 else if (strcmp(*argv, "-dtls1") == 0) {
503 meth = DTLSv1_client_method();
504 socket_type = SOCK_DGRAM;
505 } else if (strcmp(*argv, "-timeout") == 0)
506 enable_timeouts = 1;
507 else if (strcmp(*argv, "-mtu") == 0) {
508 if (--argc < 1)
509 goto bad;
510 socket_mtu = strtonum(*(++argv), 0, LONG_MAX, &errstr);
511 if (errstr)
512 goto bad;
513 }
514#endif
515 else if (strcmp(*argv, "-bugs") == 0)
516 bugs = 1;
517 else if (strcmp(*argv, "-keyform") == 0) {
518 if (--argc < 1)
519 goto bad;
520 key_format = str2fmt(*(++argv));
521 } else if (strcmp(*argv, "-pass") == 0) {
522 if (--argc < 1)
523 goto bad;
524 passarg = *(++argv);
525 } else if (strcmp(*argv, "-key") == 0) {
526 if (--argc < 1)
527 goto bad;
528 key_file = *(++argv);
529 } else if (strcmp(*argv, "-reconnect") == 0) {
530 reconnect = 5;
531 } else if (strcmp(*argv, "-CApath") == 0) {
532 if (--argc < 1)
533 goto bad;
534 CApath = *(++argv);
535 } else if (strcmp(*argv, "-CAfile") == 0) {
536 if (--argc < 1)
537 goto bad;
538 CAfile = *(++argv);
539 } else if (strcmp(*argv, "-no_tls1_2") == 0)
540 off |= SSL_OP_NO_TLSv1_2;
541 else if (strcmp(*argv, "-no_tls1_1") == 0)
542 off |= SSL_OP_NO_TLSv1_1;
543 else if (strcmp(*argv, "-no_tls1") == 0)
544 off |= SSL_OP_NO_TLSv1;
545 else if (strcmp(*argv, "-no_ssl3") == 0)
546 off |= SSL_OP_NO_SSLv3;
547 else if (strcmp(*argv, "-no_ssl2") == 0)
548 off |= SSL_OP_NO_SSLv2;
549 else if (strcmp(*argv, "-no_comp") == 0) {
550 off |= SSL_OP_NO_COMPRESSION;
551 }
552#ifndef OPENSSL_NO_TLSEXT
553 else if (strcmp(*argv, "-no_ticket") == 0) {
554 off |= SSL_OP_NO_TICKET;
555 }
556#ifndef OPENSSL_NO_NEXTPROTONEG
557 else if (strcmp(*argv, "-nextprotoneg") == 0) {
558 if (--argc < 1)
559 goto bad;
560 next_proto_neg_in = *(++argv);
561 }
562#endif
563#endif
564 else if (strcmp(*argv, "-serverpref") == 0)
565 off |= SSL_OP_CIPHER_SERVER_PREFERENCE;
566 else if (strcmp(*argv, "-legacy_renegotiation") == 0)
567 ; /* no-op */
568 else if (strcmp(*argv, "-legacy_server_connect") == 0) {
569 off |= SSL_OP_LEGACY_SERVER_CONNECT;
570 } else if (strcmp(*argv, "-no_legacy_server_connect") == 0) {
571 clr |= SSL_OP_LEGACY_SERVER_CONNECT;
572 } else if (strcmp(*argv, "-cipher") == 0) {
573 if (--argc < 1)
574 goto bad;
575 cipher = *(++argv);
576 }
577 else if (strcmp(*argv, "-nbio") == 0) {
578 c_nbio = 1;
579 }
580 else if (strcmp(*argv, "-starttls") == 0) {
581 if (--argc < 1)
582 goto bad;
583 ++argv;
584 if (strcmp(*argv, "smtp") == 0)
585 starttls_proto = PROTO_SMTP;
586 else if (strcmp(*argv, "lmtp") == 0)
587 starttls_proto = PROTO_LMTP;
588 else if (strcmp(*argv, "pop3") == 0)
589 starttls_proto = PROTO_POP3;
590 else if (strcmp(*argv, "imap") == 0)
591 starttls_proto = PROTO_IMAP;
592 else if (strcmp(*argv, "ftp") == 0)
593 starttls_proto = PROTO_FTP;
594 else if (strcmp(*argv, "xmpp") == 0)
595 starttls_proto = PROTO_XMPP;
596 else
597 goto bad;
598 }
599#ifndef OPENSSL_NO_ENGINE
600 else if (strcmp(*argv, "-engine") == 0) {
601 if (--argc < 1)
602 goto bad;
603 engine_id = *(++argv);
604 } else if (strcmp(*argv, "-ssl_client_engine") == 0) {
605 if (--argc < 1)
606 goto bad;
607 ssl_client_engine_id = *(++argv);
608 }
609#endif
610 else if (strcmp(*argv, "-4") == 0) {
611 af = AF_INET;
612 } else if (strcmp(*argv, "-6") == 0) {
613 af = AF_INET6;
614 }
615#ifndef OPENSSL_NO_TLSEXT
616 else if (strcmp(*argv, "-servername") == 0) {
617 if (--argc < 1)
618 goto bad;
619 servername = *(++argv);
620 /* meth=TLSv1_client_method(); */
621 }
622#endif
623#ifndef OPENSSL_NO_SRTP
624 else if (strcmp(*argv, "-use_srtp") == 0) {
625 if (--argc < 1)
626 goto bad;
627 srtp_profiles = *(++argv);
628 }
629#endif
630 else if (strcmp(*argv, "-keymatexport") == 0) {
631 if (--argc < 1)
632 goto bad;
633 keymatexportlabel = *(++argv);
634 } else if (strcmp(*argv, "-keymatexportlen") == 0) {
635 const char *errstr;
636
637 if (--argc < 1)
638 goto bad;
639 keymatexportlen = strtonum(*(++argv), 1, INT_MAX, &errstr);
640 if (errstr)
641 goto bad;
642 } else {
643 BIO_printf(bio_err, "unknown option %s\n", *argv);
644 badop = 1;
645 break;
646 }
647 argc--;
648 argv++;
649 }
650 if (badop) {
651bad:
652 if (errstr)
653 BIO_printf(bio_err, "invalid argument %s: %s\n",
654 *argv, errstr);
655 else
656 sc_usage();
657 goto end;
658 }
659
660#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
661 next_proto.status = -1;
662 if (next_proto_neg_in) {
663 next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in);
664 if (next_proto.data == NULL) {
665 BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n");
666 goto end;
667 }
668 } else
669 next_proto.data = NULL;
670#endif
671
672#ifndef OPENSSL_NO_ENGINE
673 e = setup_engine(bio_err, engine_id, 1);
674 if (ssl_client_engine_id) {
675 ssl_client_engine = ENGINE_by_id(ssl_client_engine_id);
676 if (!ssl_client_engine) {
677 BIO_printf(bio_err,
678 "Error getting client auth engine\n");
679 goto end;
680 }
681 }
682#endif
683 if (!app_passwd(bio_err, passarg, NULL, &pass, NULL)) {
684 BIO_printf(bio_err, "Error getting password\n");
685 goto end;
686 }
687 if (key_file == NULL)
688 key_file = cert_file;
689
690
691 if (key_file) {
692
693 key = load_key(bio_err, key_file, key_format, 0, pass, e,
694 "client certificate private key file");
695 if (!key) {
696 ERR_print_errors(bio_err);
697 goto end;
698 }
699 }
700 if (cert_file) {
701 cert = load_cert(bio_err, cert_file, cert_format,
702 NULL, e, "client certificate file");
703
704 if (!cert) {
705 ERR_print_errors(bio_err);
706 goto end;
707 }
708 }
709 if (bio_c_out == NULL) {
710 if (c_quiet && !c_debug && !c_msg) {
711 bio_c_out = BIO_new(BIO_s_null());
712 } else {
713 if (bio_c_out == NULL)
714 bio_c_out = BIO_new_fp(stdout, BIO_NOCLOSE);
715 }
716 }
717
718 ctx = SSL_CTX_new(meth);
719 if (ctx == NULL) {
720 ERR_print_errors(bio_err);
721 goto end;
722 }
723 if (vpm)
724 SSL_CTX_set1_param(ctx, vpm);
725
726#ifndef OPENSSL_NO_ENGINE
727 if (ssl_client_engine) {
728 if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) {
729 BIO_puts(bio_err, "Error setting client auth engine\n");
730 ERR_print_errors(bio_err);
731 ENGINE_free(ssl_client_engine);
732 goto end;
733 }
734 ENGINE_free(ssl_client_engine);
735 }
736#endif
737
738#ifndef OPENSSL_NO_SRTP
739 if (srtp_profiles != NULL)
740 SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles);
741#endif
742 if (bugs)
743 SSL_CTX_set_options(ctx, SSL_OP_ALL | off);
744 else
745 SSL_CTX_set_options(ctx, off);
746
747 if (clr)
748 SSL_CTX_clear_options(ctx, clr);
749 /*
750 * DTLS: partial reads end up discarding unread UDP bytes :-( Setting
751 * read ahead solves this problem.
752 */
753 if (socket_type == SOCK_DGRAM)
754 SSL_CTX_set_read_ahead(ctx, 1);
755
756#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
757 if (next_proto.data)
758 SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto);
759#endif
760
761 if (state)
762 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
763 if (cipher != NULL)
764 if (!SSL_CTX_set_cipher_list(ctx, cipher)) {
765 BIO_printf(bio_err, "error setting cipher list\n");
766 ERR_print_errors(bio_err);
767 goto end;
768 }
769
770 SSL_CTX_set_verify(ctx, verify, verify_callback);
771 if (!set_cert_key_stuff(ctx, cert, key))
772 goto end;
773
774 if ((!SSL_CTX_load_verify_locations(ctx, CAfile, CApath)) ||
775 (!SSL_CTX_set_default_verify_paths(ctx))) {
776 /*
777 * BIO_printf(bio_err,"error setting default verify
778 * locations\n");
779 */
780 ERR_print_errors(bio_err);
781 /* goto end; */
782 }
783#ifndef OPENSSL_NO_TLSEXT
784 if (servername != NULL) {
785 tlsextcbp.biodebug = bio_err;
786 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
787 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
788 }
789#endif
790
791 con = SSL_new(ctx);
792 if (sess_in) {
793 SSL_SESSION *sess;
794 BIO *stmp = BIO_new_file(sess_in, "r");
795 if (!stmp) {
796 BIO_printf(bio_err, "Can't open session file %s\n",
797 sess_in);
798 ERR_print_errors(bio_err);
799 goto end;
800 }
801 sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
802 BIO_free(stmp);
803 if (!sess) {
804 BIO_printf(bio_err, "Can't open session file %s\n",
805 sess_in);
806 ERR_print_errors(bio_err);
807 goto end;
808 }
809 SSL_set_session(con, sess);
810 SSL_SESSION_free(sess);
811 }
812#ifndef OPENSSL_NO_TLSEXT
813 if (servername != NULL) {
814 if (!SSL_set_tlsext_host_name(con, servername)) {
815 BIO_printf(bio_err, "Unable to set TLS servername extension.\n");
816 ERR_print_errors(bio_err);
817 goto end;
818 }
819 }
820#endif
821/* SSL_set_cipher_list(con,"RC4-MD5"); */
822
823re_start:
824
825 if (init_client(&s, host, port, socket_type, af) == 0) {
826 BIO_printf(bio_err, "connect:errno=%d\n", errno);
827 shutdown(s, SHUT_RD);
828 close(s);
829 goto end;
830 }
831 BIO_printf(bio_c_out, "CONNECTED(%08X)\n", s);
832
833 if (c_nbio) {
834 unsigned long l = 1;
835 BIO_printf(bio_c_out, "turning on non blocking io\n");
836 if (BIO_socket_ioctl(s, FIONBIO, &l) < 0) {
837 ERR_print_errors(bio_err);
838 goto end;
839 }
840 }
841 if (c_Pause & 0x01)
842 SSL_set_debug(con, 1);
843
844 if (SSL_version(con) == DTLS1_VERSION) {
845
846 sbio = BIO_new_dgram(s, BIO_NOCLOSE);
847 if (getsockname(s, &peer, (void *) &peerlen) < 0) {
848 BIO_printf(bio_err, "getsockname:errno=%d\n",
849 errno);
850 shutdown(s, SHUT_RD);
851 close(s);
852 goto end;
853 }
854 (void) BIO_ctrl_set_connected(sbio, 1, &peer);
855
856 if (enable_timeouts) {
857 timeout.tv_sec = 0;
858 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
859 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
860
861 timeout.tv_sec = 0;
862 timeout.tv_usec = DGRAM_SND_TIMEOUT;
863 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
864 }
865 if (socket_mtu > 28) {
866 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
867 SSL_set_mtu(con, socket_mtu - 28);
868 } else
869 /* want to do MTU discovery */
870 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
871 } else
872 sbio = BIO_new_socket(s, BIO_NOCLOSE);
873
874 if (nbio_test) {
875 BIO *test;
876
877 test = BIO_new(BIO_f_nbio_test());
878 sbio = BIO_push(test, sbio);
879 }
880 if (c_debug) {
881 SSL_set_debug(con, 1);
882 BIO_set_callback(sbio, bio_dump_callback);
883 BIO_set_callback_arg(sbio, (char *) bio_c_out);
884 }
885 if (c_msg) {
886 SSL_set_msg_callback(con, msg_cb);
887 SSL_set_msg_callback_arg(con, bio_c_out);
888 }
889#ifndef OPENSSL_NO_TLSEXT
890 if (c_tlsextdebug) {
891 SSL_set_tlsext_debug_callback(con, tlsext_cb);
892 SSL_set_tlsext_debug_arg(con, bio_c_out);
893 }
894 if (c_status_req) {
895 SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp);
896 SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb);
897 SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out);
898 }
899#endif
900
901 SSL_set_bio(con, sbio, sbio);
902 SSL_set_connect_state(con);
903
904 /* ok, lets connect */
905 width = SSL_get_fd(con) + 1;
906
907 read_tty = 1;
908 write_tty = 0;
909 tty_on = 0;
910 read_ssl = 1;
911 write_ssl = 1;
912
913 cbuf_len = 0;
914 cbuf_off = 0;
915 sbuf_len = 0;
916 sbuf_off = 0;
917
918 /* This is an ugly hack that does a lot of assumptions */
919 /*
920 * We do have to handle multi-line responses which may come in a
921 * single packet or not. We therefore have to use BIO_gets() which
922 * does need a buffering BIO. So during the initial chitchat we do
923 * push a buffering BIO into the chain that is removed again later on
924 * to not disturb the rest of the s_client operation.
925 */
926 if (starttls_proto == PROTO_SMTP || starttls_proto == PROTO_LMTP) {
927 int foundit = 0;
928 BIO *fbio = BIO_new(BIO_f_buffer());
929 BIO_push(fbio, sbio);
930 /* wait for multi-line response to end from SMTP */
931 do {
932 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
933 }
934 while (mbuf_len > 3 && mbuf[3] == '-');
935 /* STARTTLS command requires EHLO... */
936 BIO_printf(fbio, "%cHLO openssl.client.net\r\n",
937 starttls_proto == PROTO_SMTP ? 'E' : 'L');
938 (void) BIO_flush(fbio);
939 /* wait for multi-line response to end EHLO SMTP response */
940 do {
941 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
942 if (strstr(mbuf, "STARTTLS"))
943 foundit = 1;
944 }
945 while (mbuf_len > 3 && mbuf[3] == '-');
946 (void) BIO_flush(fbio);
947 BIO_pop(fbio);
948 BIO_free(fbio);
949 if (!foundit)
950 BIO_printf(bio_err,
951 "didn't found starttls in server response,"
952 " try anyway...\n");
953 BIO_printf(sbio, "STARTTLS\r\n");
954 BIO_read(sbio, sbuf, BUFSIZZ);
955 } else if (starttls_proto == PROTO_POP3) {
956 mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
957 if (mbuf_len == -1) {
958 BIO_printf(bio_err, "BIO_read failed\n");
959 goto end;
960 }
961 BIO_printf(sbio, "STLS\r\n");
962 BIO_read(sbio, sbuf, BUFSIZZ);
963 } else if (starttls_proto == PROTO_IMAP) {
964 int foundit = 0;
965 BIO *fbio = BIO_new(BIO_f_buffer());
966 BIO_push(fbio, sbio);
967 BIO_gets(fbio, mbuf, BUFSIZZ);
968 /* STARTTLS command requires CAPABILITY... */
969 BIO_printf(fbio, ". CAPABILITY\r\n");
970 (void) BIO_flush(fbio);
971 /* wait for multi-line CAPABILITY response */
972 do {
973 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
974 if (strstr(mbuf, "STARTTLS"))
975 foundit = 1;
976 }
977 while (mbuf_len > 3 && mbuf[0] != '.');
978 (void) BIO_flush(fbio);
979 BIO_pop(fbio);
980 BIO_free(fbio);
981 if (!foundit)
982 BIO_printf(bio_err,
983 "didn't found STARTTLS in server response,"
984 " try anyway...\n");
985 BIO_printf(sbio, ". STARTTLS\r\n");
986 BIO_read(sbio, sbuf, BUFSIZZ);
987 } else if (starttls_proto == PROTO_FTP) {
988 BIO *fbio = BIO_new(BIO_f_buffer());
989 BIO_push(fbio, sbio);
990 /* wait for multi-line response to end from FTP */
991 do {
992 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
993 }
994 while (mbuf_len > 3 && mbuf[3] == '-');
995 (void) BIO_flush(fbio);
996 BIO_pop(fbio);
997 BIO_free(fbio);
998 BIO_printf(sbio, "AUTH TLS\r\n");
999 BIO_read(sbio, sbuf, BUFSIZZ);
1000 }
1001 if (starttls_proto == PROTO_XMPP) {
1002 int seen = 0;
1003 BIO_printf(sbio, "<stream:stream "
1004 "xmlns:stream='http://etherx.jabber.org/streams' "
1005 "xmlns='jabber:client' to='%s' version='1.0'>", host);
1006 seen = BIO_read(sbio, mbuf, BUFSIZZ);
1007 mbuf[seen] = 0;
1008 while (!strstr(mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'")) {
1009 if (strstr(mbuf, "/stream:features>"))
1010 goto shut;
1011 seen = BIO_read(sbio, mbuf, BUFSIZZ);
1012 mbuf[seen] = 0;
1013 }
1014 BIO_printf(sbio, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
1015 seen = BIO_read(sbio, sbuf, BUFSIZZ);
1016 sbuf[seen] = 0;
1017 if (!strstr(sbuf, "<proceed"))
1018 goto shut;
1019 mbuf[0] = 0;
1020 }
1021 for (;;) {
1022 FD_ZERO(&readfds);
1023 FD_ZERO(&writefds);
1024
1025 if ((SSL_version(con) == DTLS1_VERSION) &&
1026 DTLSv1_get_timeout(con, &timeout))
1027 timeoutp = &timeout;
1028 else
1029 timeoutp = NULL;
1030
1031 if (SSL_in_init(con) && !SSL_total_renegotiations(con)) {
1032 in_init = 1;
1033 tty_on = 0;
1034 } else {
1035 tty_on = 1;
1036 if (in_init) {
1037 in_init = 0;
1038 if (sess_out) {
1039 BIO *stmp = BIO_new_file(sess_out, "w");
1040 if (stmp) {
1041 PEM_write_bio_SSL_SESSION(stmp, SSL_get_session(con));
1042 BIO_free(stmp);
1043 } else
1044 BIO_printf(bio_err, "Error writing session file %s\n", sess_out);
1045 }
1046 print_stuff(bio_c_out, con, full_log);
1047 if (full_log > 0)
1048 full_log--;
1049
1050 if (starttls_proto) {
1051 BIO_write(bio_err, mbuf, mbuf_len);
1052 /* We don't need to know any more */
1053 starttls_proto = PROTO_OFF;
1054 }
1055 if (reconnect) {
1056 reconnect--;
1057 BIO_printf(bio_c_out, "drop connection and then reconnect\n");
1058 SSL_shutdown(con);
1059 SSL_set_connect_state(con);
1060 shutdown(SSL_get_fd(con), SHUT_RD);
1061 close(SSL_get_fd(con));
1062 goto re_start;
1063 }
1064 }
1065 }
1066
1067 ssl_pending = read_ssl && SSL_pending(con);
1068
1069 /* XXX should add tests for fd_set overflow */
1070
1071 if (!ssl_pending) {
1072 if (tty_on) {
1073 if (read_tty)
1074 FD_SET(fileno(stdin), &readfds);
1075 if (write_tty)
1076 FD_SET(fileno(stdout), &writefds);
1077 }
1078 if (read_ssl)
1079 FD_SET(SSL_get_fd(con), &readfds);
1080 if (write_ssl)
1081 FD_SET(SSL_get_fd(con), &writefds);
1082/* printf("mode tty(%d %d%d) ssl(%d%d)\n",
1083 tty_on,read_tty,write_tty,read_ssl,write_ssl);*/
1084
1085 i = select(width, &readfds, &writefds,
1086 NULL, timeoutp);
1087 if (i < 0) {
1088 BIO_printf(bio_err, "bad select %d\n",
1089 errno);
1090 goto shut;
1091 /* goto end; */
1092 }
1093 }
1094 if ((SSL_version(con) == DTLS1_VERSION) && DTLSv1_handle_timeout(con) > 0) {
1095 BIO_printf(bio_err, "TIMEOUT occured\n");
1096 }
1097 if (!ssl_pending && FD_ISSET(SSL_get_fd(con), &writefds)) {
1098 k = SSL_write(con, &(cbuf[cbuf_off]),
1099 (unsigned int) cbuf_len);
1100 switch (SSL_get_error(con, k)) {
1101 case SSL_ERROR_NONE:
1102 cbuf_off += k;
1103 cbuf_len -= k;
1104 if (k <= 0)
1105 goto end;
1106 /* we have done a write(con,NULL,0); */
1107 if (cbuf_len <= 0) {
1108 read_tty = 1;
1109 write_ssl = 0;
1110 } else { /* if (cbuf_len > 0) */
1111 read_tty = 0;
1112 write_ssl = 1;
1113 }
1114 break;
1115 case SSL_ERROR_WANT_WRITE:
1116 BIO_printf(bio_c_out, "write W BLOCK\n");
1117 write_ssl = 1;
1118 read_tty = 0;
1119 break;
1120 case SSL_ERROR_WANT_READ:
1121 BIO_printf(bio_c_out, "write R BLOCK\n");
1122 write_tty = 0;
1123 read_ssl = 1;
1124 write_ssl = 0;
1125 break;
1126 case SSL_ERROR_WANT_X509_LOOKUP:
1127 BIO_printf(bio_c_out, "write X BLOCK\n");
1128 break;
1129 case SSL_ERROR_ZERO_RETURN:
1130 if (cbuf_len != 0) {
1131 BIO_printf(bio_c_out, "shutdown\n");
1132 ret = 0;
1133 goto shut;
1134 } else {
1135 read_tty = 1;
1136 write_ssl = 0;
1137 break;
1138 }
1139
1140 case SSL_ERROR_SYSCALL:
1141 if ((k != 0) || (cbuf_len != 0)) {
1142 BIO_printf(bio_err, "write:errno=%d\n",
1143 errno);
1144 goto shut;
1145 } else {
1146 read_tty = 1;
1147 write_ssl = 0;
1148 }
1149 break;
1150 case SSL_ERROR_SSL:
1151 ERR_print_errors(bio_err);
1152 goto shut;
1153 }
1154 } else if (!ssl_pending && FD_ISSET(fileno(stdout), &writefds)) {
1155 i = write(fileno(stdout), &(sbuf[sbuf_off]), sbuf_len);
1156
1157 if (i <= 0) {
1158 BIO_printf(bio_c_out, "DONE\n");
1159 ret = 0;
1160 goto shut;
1161 /* goto end; */
1162 }
1163 sbuf_len -= i;
1164 sbuf_off += i;
1165 if (sbuf_len <= 0) {
1166 read_ssl = 1;
1167 write_tty = 0;
1168 }
1169 } else if (ssl_pending || FD_ISSET(SSL_get_fd(con), &readfds)) {
1170#ifdef RENEG
1171 {
1172 static int iiii;
1173 if (++iiii == 52) {
1174 SSL_renegotiate(con);
1175 iiii = 0;
1176 }
1177 }
1178#endif
1179 k = SSL_read(con, sbuf, 1024 /* BUFSIZZ */ );
1180
1181 switch (SSL_get_error(con, k)) {
1182 case SSL_ERROR_NONE:
1183 if (k <= 0)
1184 goto end;
1185 sbuf_off = 0;
1186 sbuf_len = k;
1187
1188 read_ssl = 0;
1189 write_tty = 1;
1190 break;
1191 case SSL_ERROR_WANT_WRITE:
1192 BIO_printf(bio_c_out, "read W BLOCK\n");
1193 write_ssl = 1;
1194 read_tty = 0;
1195 break;
1196 case SSL_ERROR_WANT_READ:
1197 BIO_printf(bio_c_out, "read R BLOCK\n");
1198 write_tty = 0;
1199 read_ssl = 1;
1200 if ((read_tty == 0) && (write_ssl == 0))
1201 write_ssl = 1;
1202 break;
1203 case SSL_ERROR_WANT_X509_LOOKUP:
1204 BIO_printf(bio_c_out, "read X BLOCK\n");
1205 break;
1206 case SSL_ERROR_SYSCALL:
1207 ret = errno;
1208 BIO_printf(bio_err, "read:errno=%d\n", ret);
1209 goto shut;
1210 case SSL_ERROR_ZERO_RETURN:
1211 BIO_printf(bio_c_out, "closed\n");
1212 ret = 0;
1213 goto shut;
1214 case SSL_ERROR_SSL:
1215 ERR_print_errors(bio_err);
1216 goto shut;
1217 /* break; */
1218 }
1219 } else if (FD_ISSET(fileno(stdin), &readfds)) {
1220 if (crlf) {
1221 int j, lf_num;
1222
1223 i = read(fileno(stdin), cbuf, BUFSIZZ / 2);
1224 lf_num = 0;
1225 /* both loops are skipped when i <= 0 */
1226 for (j = 0; j < i; j++)
1227 if (cbuf[j] == '\n')
1228 lf_num++;
1229 for (j = i - 1; j >= 0; j--) {
1230 cbuf[j + lf_num] = cbuf[j];
1231 if (cbuf[j] == '\n') {
1232 lf_num--;
1233 i++;
1234 cbuf[j + lf_num] = '\r';
1235 }
1236 }
1237 assert(lf_num == 0);
1238 } else
1239 i = read(fileno(stdin), cbuf, BUFSIZZ);
1240
1241 if ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'Q'))) {
1242 BIO_printf(bio_err, "DONE\n");
1243 ret = 0;
1244 goto shut;
1245 }
1246 if ((!c_ign_eof) && (cbuf[0] == 'R')) {
1247 BIO_printf(bio_err, "RENEGOTIATING\n");
1248 SSL_renegotiate(con);
1249 cbuf_len = 0;
1250 } else {
1251 cbuf_len = i;
1252 cbuf_off = 0;
1253 }
1254
1255 write_ssl = 1;
1256 read_tty = 0;
1257 }
1258 }
1259
1260 ret = 0;
1261shut:
1262 if (in_init)
1263 print_stuff(bio_c_out, con, full_log);
1264 SSL_shutdown(con);
1265 shutdown(SSL_get_fd(con), SHUT_RD);
1266 close(SSL_get_fd(con));
1267end:
1268 if (con != NULL) {
1269 if (prexit != 0)
1270 print_stuff(bio_c_out, con, 1);
1271 SSL_free(con);
1272 }
1273#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
1274 free(next_proto.data);
1275#endif
1276 if (ctx != NULL)
1277 SSL_CTX_free(ctx);
1278 if (cert)
1279 X509_free(cert);
1280 if (key)
1281 EVP_PKEY_free(key);
1282 free(pass);
1283 if (vpm)
1284 X509_VERIFY_PARAM_free(vpm);
1285 if (cbuf != NULL) {
1286 OPENSSL_cleanse(cbuf, BUFSIZZ);
1287 free(cbuf);
1288 }
1289 if (sbuf != NULL) {
1290 OPENSSL_cleanse(sbuf, BUFSIZZ);
1291 free(sbuf);
1292 }
1293 if (mbuf != NULL) {
1294 OPENSSL_cleanse(mbuf, BUFSIZZ);
1295 free(mbuf);
1296 }
1297 if (bio_c_out != NULL) {
1298 BIO_free(bio_c_out);
1299 bio_c_out = NULL;
1300 }
1301
1302 return (ret);
1303}
1304
1305
1306static void
1307print_stuff(BIO * bio, SSL * s, int full)
1308{
1309 X509 *peer = NULL;
1310 char *p;
1311 static const char *space = " ";
1312 char buf[BUFSIZ];
1313 STACK_OF(X509) * sk;
1314 STACK_OF(X509_NAME) * sk2;
1315 const SSL_CIPHER *c;
1316 X509_NAME *xn;
1317 int j, i;
1318 unsigned char *exportedkeymat;
1319
1320 if (full) {
1321 int got_a_chain = 0;
1322
1323 sk = SSL_get_peer_cert_chain(s);
1324 if (sk != NULL) {
1325 got_a_chain = 1; /* we don't have it for SSL2
1326 * (yet) */
1327
1328 BIO_printf(bio, "---\nCertificate chain\n");
1329 for (i = 0; i < sk_X509_num(sk); i++) {
1330 X509_NAME_oneline(X509_get_subject_name(
1331 sk_X509_value(sk, i)), buf, sizeof buf);
1332 BIO_printf(bio, "%2d s:%s\n", i, buf);
1333 X509_NAME_oneline(X509_get_issuer_name(
1334 sk_X509_value(sk, i)), buf, sizeof buf);
1335 BIO_printf(bio, " i:%s\n", buf);
1336 if (c_showcerts)
1337 PEM_write_bio_X509(bio, sk_X509_value(sk, i));
1338 }
1339 }
1340 BIO_printf(bio, "---\n");
1341 peer = SSL_get_peer_certificate(s);
1342 if (peer != NULL) {
1343 BIO_printf(bio, "Server certificate\n");
1344 if (!(c_showcerts && got_a_chain)) /* Redundant if we
1345 * showed the whole
1346 * chain */
1347 PEM_write_bio_X509(bio, peer);
1348 X509_NAME_oneline(X509_get_subject_name(peer),
1349 buf, sizeof buf);
1350 BIO_printf(bio, "subject=%s\n", buf);
1351 X509_NAME_oneline(X509_get_issuer_name(peer),
1352 buf, sizeof buf);
1353 BIO_printf(bio, "issuer=%s\n", buf);
1354 } else
1355 BIO_printf(bio, "no peer certificate available\n");
1356
1357 sk2 = SSL_get_client_CA_list(s);
1358 if ((sk2 != NULL) && (sk_X509_NAME_num(sk2) > 0)) {
1359 BIO_printf(bio, "---\nAcceptable client certificate CA names\n");
1360 for (i = 0; i < sk_X509_NAME_num(sk2); i++) {
1361 xn = sk_X509_NAME_value(sk2, i);
1362 X509_NAME_oneline(xn, buf, sizeof(buf));
1363 BIO_write(bio, buf, strlen(buf));
1364 BIO_write(bio, "\n", 1);
1365 }
1366 } else {
1367 BIO_printf(bio, "---\nNo client certificate CA names sent\n");
1368 }
1369 p = SSL_get_shared_ciphers(s, buf, sizeof buf);
1370 if (p != NULL) {
1371 /*
1372 * This works only for SSL 2. In later protocol
1373 * versions, the client does not know what other
1374 * ciphers (in addition to the one to be used in the
1375 * current connection) the server supports.
1376 */
1377
1378 BIO_printf(bio, "---\nCiphers common between both SSL endpoints:\n");
1379 j = i = 0;
1380 while (*p) {
1381 if (*p == ':') {
1382 BIO_write(bio, space, 15 - j % 25);
1383 i++;
1384 j = 0;
1385 BIO_write(bio, ((i % 3) ? " " : "\n"), 1);
1386 } else {
1387 BIO_write(bio, p, 1);
1388 j++;
1389 }
1390 p++;
1391 }
1392 BIO_write(bio, "\n", 1);
1393 }
1394 BIO_printf(bio, "---\nSSL handshake has read %ld bytes and written %ld bytes\n",
1395 BIO_number_read(SSL_get_rbio(s)),
1396 BIO_number_written(SSL_get_wbio(s)));
1397 }
1398 BIO_printf(bio, (SSL_cache_hit(s) ? "---\nReused, " : "---\nNew, "));
1399 c = SSL_get_current_cipher(s);
1400 BIO_printf(bio, "%s, Cipher is %s\n",
1401 SSL_CIPHER_get_version(c),
1402 SSL_CIPHER_get_name(c));
1403 if (peer != NULL) {
1404 EVP_PKEY *pktmp;
1405 pktmp = X509_get_pubkey(peer);
1406 BIO_printf(bio, "Server public key is %d bit\n",
1407 EVP_PKEY_bits(pktmp));
1408 EVP_PKEY_free(pktmp);
1409 }
1410 BIO_printf(bio, "Secure Renegotiation IS%s supported\n",
1411 SSL_get_secure_renegotiation_support(s) ? "" : " NOT");
1412
1413 /* Compression is not supported and will always be none. */
1414 BIO_printf(bio, "Compression: NONE\n");
1415 BIO_printf(bio, "Expansion: NONE\n");
1416
1417#ifdef SSL_DEBUG
1418 {
1419 /* Print out local port of connection: useful for debugging */
1420 int sock;
1421 struct sockaddr_in ladd;
1422 socklen_t ladd_size = sizeof(ladd);
1423 sock = SSL_get_fd(s);
1424 getsockname(sock, (struct sockaddr *) & ladd, &ladd_size);
1425 BIO_printf(bio_c_out, "LOCAL PORT is %u\n", ntohs(ladd.sin_port));
1426 }
1427#endif
1428
1429#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
1430 if (next_proto.status != -1) {
1431 const unsigned char *proto;
1432 unsigned int proto_len;
1433 SSL_get0_next_proto_negotiated(s, &proto, &proto_len);
1434 BIO_printf(bio, "Next protocol: (%d) ", next_proto.status);
1435 BIO_write(bio, proto, proto_len);
1436 BIO_write(bio, "\n", 1);
1437 }
1438#endif
1439
1440#ifndef OPENSSL_NO_SRTP
1441 {
1442 SRTP_PROTECTION_PROFILE *srtp_profile = SSL_get_selected_srtp_profile(s);
1443
1444 if (srtp_profile)
1445 BIO_printf(bio, "SRTP Extension negotiated, profile=%s\n",
1446 srtp_profile->name);
1447 }
1448#endif
1449
1450 SSL_SESSION_print(bio, SSL_get_session(s));
1451 if (keymatexportlabel != NULL) {
1452 BIO_printf(bio, "Keying material exporter:\n");
1453 BIO_printf(bio, " Label: '%s'\n", keymatexportlabel);
1454 BIO_printf(bio, " Length: %i bytes\n", keymatexportlen);
1455 exportedkeymat = malloc(keymatexportlen);
1456 if (exportedkeymat != NULL) {
1457 if (!SSL_export_keying_material(s, exportedkeymat,
1458 keymatexportlen,
1459 keymatexportlabel,
1460 strlen(keymatexportlabel),
1461 NULL, 0, 0)) {
1462 BIO_printf(bio, " Error\n");
1463 } else {
1464 BIO_printf(bio, " Keying material: ");
1465 for (i = 0; i < keymatexportlen; i++)
1466 BIO_printf(bio, "%02X",
1467 exportedkeymat[i]);
1468 BIO_printf(bio, "\n");
1469 }
1470 free(exportedkeymat);
1471 }
1472 }
1473 BIO_printf(bio, "---\n");
1474 if (peer != NULL)
1475 X509_free(peer);
1476 /* flush, or debugging output gets mixed with http response */
1477 (void) BIO_flush(bio);
1478}
1479
1480#ifndef OPENSSL_NO_TLSEXT
1481
1482static int
1483ocsp_resp_cb(SSL * s, void *arg)
1484{
1485 const unsigned char *p;
1486 int len;
1487 OCSP_RESPONSE *rsp;
1488 len = SSL_get_tlsext_status_ocsp_resp(s, &p);
1489 BIO_puts(arg, "OCSP response: ");
1490 if (!p) {
1491 BIO_puts(arg, "no response sent\n");
1492 return 1;
1493 }
1494 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
1495 if (!rsp) {
1496 BIO_puts(arg, "response parse error\n");
1497 BIO_dump_indent(arg, (char *) p, len, 4);
1498 return 0;
1499 }
1500 BIO_puts(arg, "\n======================================\n");
1501 OCSP_RESPONSE_print(arg, rsp, 0);
1502 BIO_puts(arg, "======================================\n");
1503 OCSP_RESPONSE_free(rsp);
1504 return 1;
1505}
1506
1507#endif
diff --git a/src/usr.bin/openssl/s_server.c b/src/usr.bin/openssl/s_server.c
new file mode 100644
index 0000000000..7fa875c661
--- /dev/null
+++ b/src/usr.bin/openssl/s_server.c
@@ -0,0 +1,2154 @@
1/* $OpenBSD: s_server.c,v 1.1 2014/08/26 17:47:25 jsing 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 * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in
70 * the documentation and/or other materials provided with the
71 * distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 * software must display the following acknowledgment:
75 * "This product includes software developed by the OpenSSL Project
76 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 * endorse or promote products derived from this software without
80 * prior written permission. For written permission, please contact
81 * openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 * nor may "OpenSSL" appear in their names without prior written
85 * permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 * acknowledgment:
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com). This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
111/* ====================================================================
112 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113 * ECC cipher suite support in OpenSSL originally developed by
114 * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
115 */
116/* ====================================================================
117 * Copyright 2005 Nokia. All rights reserved.
118 *
119 * The portions of the attached software ("Contribution") is developed by
120 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
121 * license.
122 *
123 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
124 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
125 * support (see RFC 4279) to OpenSSL.
126 *
127 * No patent licenses or other rights except those expressly stated in
128 * the OpenSSL open source license shall be deemed granted or received
129 * expressly, by implication, estoppel, or otherwise.
130 *
131 * No assurances are provided by Nokia that the Contribution does not
132 * infringe the patent or other intellectual property rights of any third
133 * party or that the license provides you with all the necessary rights
134 * to make use of the Contribution.
135 *
136 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
137 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
138 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
139 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
140 * OTHERWISE.
141 */
142
143/* Until the key-gen callbacks are modified to use newer prototypes, we allow
144 * deprecated functions for openssl-internal code */
145#ifdef OPENSSL_NO_DEPRECATED
146#undef OPENSSL_NO_DEPRECATED
147#endif
148
149#include <sys/types.h>
150#include <sys/ioctl.h>
151#include <sys/select.h>
152#include <sys/socket.h>
153
154#include <assert.h>
155#include <ctype.h>
156#include <stdio.h>
157#include <stdlib.h>
158#include <limits.h>
159#include <string.h>
160#include <unistd.h>
161
162#include "apps.h"
163
164#include <openssl/bn.h>
165#include <openssl/err.h>
166#include <openssl/lhash.h>
167#include <openssl/ocsp.h>
168#include <openssl/pem.h>
169#include <openssl/rand.h>
170#include <openssl/ssl.h>
171#include <openssl/x509.h>
172
173#ifndef OPENSSL_NO_DH
174#include <openssl/dh.h>
175#endif
176
177#include <openssl/rsa.h>
178
179#include "s_apps.h"
180#include "timeouts.h"
181
182static RSA *tmp_rsa_cb(SSL * s, int is_export, int keylength);
183static int sv_body(char *hostname, int s, unsigned char *context);
184static int www_body(char *hostname, int s, unsigned char *context);
185static void close_accept_socket(void);
186static void sv_usage(void);
187static int init_ssl_connection(SSL * s);
188static void print_stats(BIO * bp, SSL_CTX * ctx);
189static int
190generate_session_id(const SSL * ssl, unsigned char *id,
191 unsigned int *id_len);
192#ifndef OPENSSL_NO_DH
193static DH *load_dh_param(const char *dhfile);
194static DH *get_dh512(void);
195#endif
196
197static void s_server_init(void);
198
199#ifndef OPENSSL_NO_DH
200static unsigned char dh512_p[] = {
201 0xDA, 0x58, 0x3C, 0x16, 0xD9, 0x85, 0x22, 0x89, 0xD0, 0xE4, 0xAF, 0x75,
202 0x6F, 0x4C, 0xCA, 0x92, 0xDD, 0x4B, 0xE5, 0x33, 0xB8, 0x04, 0xFB, 0x0F,
203 0xED, 0x94, 0xEF, 0x9C, 0x8A, 0x44, 0x03, 0xED, 0x57, 0x46, 0x50, 0xD3,
204 0x69, 0x99, 0xDB, 0x29, 0xD7, 0x76, 0x27, 0x6B, 0xA2, 0xD3, 0xD4, 0x12,
205 0xE2, 0x18, 0xF4, 0xDD, 0x1E, 0x08, 0x4C, 0xF6, 0xD8, 0x00, 0x3E, 0x7C,
206 0x47, 0x74, 0xE8, 0x33,
207};
208static unsigned char dh512_g[] = {
209 0x02,
210};
211
212static DH *
213get_dh512(void)
214{
215 DH *dh = NULL;
216
217 if ((dh = DH_new()) == NULL)
218 return (NULL);
219 dh->p = BN_bin2bn(dh512_p, sizeof(dh512_p), NULL);
220 dh->g = BN_bin2bn(dh512_g, sizeof(dh512_g), NULL);
221 if ((dh->p == NULL) || (dh->g == NULL))
222 return (NULL);
223 return (dh);
224}
225#endif
226
227
228/* static int load_CA(SSL_CTX *ctx, char *file);*/
229
230#define BUFSIZZ 16*1024
231static int bufsize = BUFSIZZ;
232static int accept_socket = -1;
233
234#define TEST_CERT "server.pem"
235#ifndef OPENSSL_NO_TLSEXT
236#define TEST_CERT2 "server2.pem"
237#endif
238
239extern int verify_depth, verify_return_error;
240
241static char *cipher = NULL;
242static int s_server_verify = SSL_VERIFY_NONE;
243static int s_server_session_id_context = 1; /* anything will do */
244static const char *s_cert_file = TEST_CERT, *s_key_file = NULL;
245#ifndef OPENSSL_NO_TLSEXT
246static const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL;
247#endif
248static char *s_dcert_file = NULL, *s_dkey_file = NULL;
249static int s_nbio = 0;
250static int s_nbio_test = 0;
251int s_crlf = 0;
252static SSL_CTX *ctx = NULL;
253#ifndef OPENSSL_NO_TLSEXT
254static SSL_CTX *ctx2 = NULL;
255#endif
256static int www = 0;
257
258static BIO *bio_s_out = NULL;
259static int s_debug = 0;
260#ifndef OPENSSL_NO_TLSEXT
261static int s_tlsextdebug = 0;
262static int s_tlsextstatus = 0;
263static int cert_status_cb(SSL * s, void *arg);
264#endif
265static int s_msg = 0;
266static int s_quiet = 0;
267
268static char *keymatexportlabel = NULL;
269static int keymatexportlen = 20;
270
271static int hack = 0;
272#ifndef OPENSSL_NO_ENGINE
273static char *engine_id = NULL;
274#endif
275static const char *session_id_prefix = NULL;
276
277static int enable_timeouts = 0;
278static long socket_mtu;
279#ifndef OPENSSL_NO_DTLS1
280static int cert_chain = 0;
281#endif
282
283
284
285
286static void
287s_server_init(void)
288{
289 accept_socket = -1;
290 cipher = NULL;
291 s_server_verify = SSL_VERIFY_NONE;
292 s_dcert_file = NULL;
293 s_dkey_file = NULL;
294 s_cert_file = TEST_CERT;
295 s_key_file = NULL;
296#ifndef OPENSSL_NO_TLSEXT
297 s_cert_file2 = TEST_CERT2;
298 s_key_file2 = NULL;
299 ctx2 = NULL;
300#endif
301 s_nbio = 0;
302 s_nbio_test = 0;
303 ctx = NULL;
304 www = 0;
305
306 bio_s_out = NULL;
307 s_debug = 0;
308 s_msg = 0;
309 s_quiet = 0;
310 hack = 0;
311#ifndef OPENSSL_NO_ENGINE
312 engine_id = NULL;
313#endif
314}
315
316static void
317sv_usage(void)
318{
319 BIO_printf(bio_err, "usage: s_server [args ...]\n");
320 BIO_printf(bio_err, "\n");
321 BIO_printf(bio_err, " -accept arg - port to accept on (default is %d)\n", PORT);
322 BIO_printf(bio_err, " -context arg - set session ID context\n");
323 BIO_printf(bio_err, " -verify arg - turn on peer certificate verification\n");
324 BIO_printf(bio_err, " -Verify arg - turn on peer certificate verification, must have a cert.\n");
325 BIO_printf(bio_err, " -cert arg - certificate file to use\n");
326 BIO_printf(bio_err, " (default is %s)\n", TEST_CERT);
327 BIO_printf(bio_err, " -crl_check - check the peer certificate has not been revoked by its CA.\n" \
328 " The CRL(s) are appended to the certificate file\n");
329 BIO_printf(bio_err, " -crl_check_all - check the peer certificate has not been revoked by its CA\n" \
330 " or any other CRL in the CA chain. CRL(s) are appended to the\n" \
331 " the certificate file.\n");
332 BIO_printf(bio_err, " -certform arg - certificate format (PEM or DER) PEM default\n");
333 BIO_printf(bio_err, " -key arg - Private Key file to use, in cert file if\n");
334 BIO_printf(bio_err, " not specified (default is %s)\n", TEST_CERT);
335 BIO_printf(bio_err, " -keyform arg - key format (PEM, DER or ENGINE) PEM default\n");
336 BIO_printf(bio_err, " -pass arg - private key file pass phrase source\n");
337 BIO_printf(bio_err, " -dcert arg - second certificate file to use (usually for DSA)\n");
338 BIO_printf(bio_err, " -dcertform x - second certificate format (PEM or DER) PEM default\n");
339 BIO_printf(bio_err, " -dkey arg - second private key file to use (usually for DSA)\n");
340 BIO_printf(bio_err, " -dkeyform arg - second key format (PEM, DER or ENGINE) PEM default\n");
341 BIO_printf(bio_err, " -dpass arg - second private key file pass phrase source\n");
342 BIO_printf(bio_err, " -dhparam arg - DH parameter file to use, in cert file if not specified\n");
343 BIO_printf(bio_err, " or a default set of parameters is used\n");
344 BIO_printf(bio_err, " -named_curve arg - Elliptic curve name to use for ephemeral ECDH keys.\n" \
345 " Use \"openssl ecparam -list_curves\" for all names\n" \
346 " (default is nistp256).\n");
347 BIO_printf(bio_err, " -nbio - Run with non-blocking IO\n");
348 BIO_printf(bio_err, " -nbio_test - test with the non-blocking test bio\n");
349 BIO_printf(bio_err, " -crlf - convert LF from terminal into CRLF\n");
350 BIO_printf(bio_err, " -debug - Print more output\n");
351 BIO_printf(bio_err, " -msg - Show protocol messages\n");
352 BIO_printf(bio_err, " -state - Print the SSL states\n");
353 BIO_printf(bio_err, " -CApath arg - PEM format directory of CA's\n");
354 BIO_printf(bio_err, " -CAfile arg - PEM format file of CA's\n");
355 BIO_printf(bio_err, " -nocert - Don't use any certificates (Anon-DH)\n");
356 BIO_printf(bio_err, " -cipher arg - play with 'openssl ciphers' to see what goes here\n");
357 BIO_printf(bio_err, " -serverpref - Use server's cipher preferences\n");
358 BIO_printf(bio_err, " -quiet - Inhibit printing of session and certificate information\n");
359 BIO_printf(bio_err, " -no_tmp_rsa - Do not generate a tmp RSA key\n");
360 BIO_printf(bio_err, " -ssl3 - Just talk SSLv3\n");
361 BIO_printf(bio_err, " -tls1_2 - Just talk TLSv1.2\n");
362 BIO_printf(bio_err, " -tls1_1 - Just talk TLSv1.1\n");
363 BIO_printf(bio_err, " -tls1 - Just talk TLSv1\n");
364 BIO_printf(bio_err, " -dtls1 - Just talk DTLSv1\n");
365 BIO_printf(bio_err, " -timeout - Enable timeouts\n");
366 BIO_printf(bio_err, " -mtu - Set link layer MTU\n");
367 BIO_printf(bio_err, " -chain - Read a certificate chain\n");
368 BIO_printf(bio_err, " -no_ssl2 - Just disable SSLv2\n");
369 BIO_printf(bio_err, " -no_ssl3 - Just disable SSLv3\n");
370 BIO_printf(bio_err, " -no_tls1 - Just disable TLSv1\n");
371 BIO_printf(bio_err, " -no_tls1_1 - Just disable TLSv1.1\n");
372 BIO_printf(bio_err, " -no_tls1_2 - Just disable TLSv1.2\n");
373#ifndef OPENSSL_NO_DH
374 BIO_printf(bio_err, " -no_dhe - Disable ephemeral DH\n");
375#endif
376 BIO_printf(bio_err, " -no_ecdhe - Disable ephemeral ECDH\n");
377 BIO_printf(bio_err, " -bugs - Turn on SSL bug compatibility\n");
378 BIO_printf(bio_err, " -www - Respond to a 'GET /' with a status page\n");
379 BIO_printf(bio_err, " -WWW - Respond to a 'GET /<path> HTTP/1.0' with file ./<path>\n");
380 BIO_printf(bio_err, " -HTTP - Respond to a 'GET /<path> HTTP/1.0' with file ./<path>\n");
381 BIO_printf(bio_err, " with the assumption it contains a complete HTTP response.\n");
382#ifndef OPENSSL_NO_ENGINE
383 BIO_printf(bio_err, " -engine id - Initialise and use the specified engine\n");
384#endif
385 BIO_printf(bio_err, " -id_prefix arg - Generate SSL/TLS session IDs prefixed by 'arg'\n");
386#ifndef OPENSSL_NO_TLSEXT
387 BIO_printf(bio_err, " -servername host - servername for HostName TLS extension\n");
388 BIO_printf(bio_err, " -servername_fatal - on mismatch send fatal alert (default warning alert)\n");
389 BIO_printf(bio_err, " -cert2 arg - certificate file to use for servername\n");
390 BIO_printf(bio_err, " (default is %s)\n", TEST_CERT2);
391 BIO_printf(bio_err, " -key2 arg - Private Key file to use for servername, in cert file if\n");
392 BIO_printf(bio_err, " not specified (default is %s)\n", TEST_CERT2);
393 BIO_printf(bio_err, " -tlsextdebug - hex dump of all TLS extensions received\n");
394 BIO_printf(bio_err, " -no_ticket - disable use of RFC4507bis session tickets\n");
395#ifndef OPENSSL_NO_NEXTPROTONEG
396 BIO_printf(bio_err, " -nextprotoneg arg - set the advertised protocols for the NPN extension (comma-separated list)\n");
397#endif
398#ifndef OPENSSL_NO_SRTP
399 BIO_printf(bio_err, " -use_srtp profiles - Offer SRTP key management with a colon-separated profile list\n");
400#endif
401#endif
402 BIO_printf(bio_err, " -keymatexport label - Export keying material using label\n");
403 BIO_printf(bio_err, " -keymatexportlen len - Export len bytes of keying material (default 20)\n");
404}
405
406static int local_argc = 0;
407static char **local_argv;
408
409#ifndef OPENSSL_NO_TLSEXT
410
411/* This is a context that we pass to callbacks */
412typedef struct tlsextctx_st {
413 char *servername;
414 BIO *biodebug;
415 int extension_error;
416} tlsextctx;
417
418
419static int
420ssl_servername_cb(SSL * s, int *ad, void *arg)
421{
422 tlsextctx *p = (tlsextctx *) arg;
423 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
424 if (servername && p->biodebug)
425 BIO_printf(p->biodebug, "Hostname in TLS extension: \"%s\"\n", servername);
426
427 if (!p->servername)
428 return SSL_TLSEXT_ERR_NOACK;
429
430 if (servername) {
431 if (strcmp(servername, p->servername))
432 return p->extension_error;
433 if (ctx2) {
434 BIO_printf(p->biodebug, "Switching server context.\n");
435 SSL_set_SSL_CTX(s, ctx2);
436 }
437 }
438 return SSL_TLSEXT_ERR_OK;
439}
440
441/* Structure passed to cert status callback */
442
443typedef struct tlsextstatusctx_st {
444 /* Default responder to use */
445 char *host, *path, *port;
446 int use_ssl;
447 int timeout;
448 BIO *err;
449 int verbose;
450} tlsextstatusctx;
451
452static tlsextstatusctx tlscstatp = {NULL, NULL, NULL, 0, -1, NULL, 0};
453
454/* Certificate Status callback. This is called when a client includes a
455 * certificate status request extension.
456 *
457 * This is a simplified version. It examines certificates each time and
458 * makes one OCSP responder query for each request.
459 *
460 * A full version would store details such as the OCSP certificate IDs and
461 * minimise the number of OCSP responses by caching them until they were
462 * considered "expired".
463 */
464
465static int
466cert_status_cb(SSL * s, void *arg)
467{
468 tlsextstatusctx *srctx = arg;
469 BIO *err = srctx->err;
470 char *host, *port, *path;
471 int use_ssl;
472 unsigned char *rspder = NULL;
473 int rspderlen;
474 STACK_OF(OPENSSL_STRING) * aia = NULL;
475 X509 *x = NULL;
476 X509_STORE_CTX inctx;
477 X509_OBJECT obj;
478 OCSP_REQUEST *req = NULL;
479 OCSP_RESPONSE *resp = NULL;
480 OCSP_CERTID *id = NULL;
481 STACK_OF(X509_EXTENSION) * exts;
482 int ret = SSL_TLSEXT_ERR_NOACK;
483 int i;
484
485 if (srctx->verbose)
486 BIO_puts(err, "cert_status: callback called\n");
487 /* Build up OCSP query from server certificate */
488 x = SSL_get_certificate(s);
489 aia = X509_get1_ocsp(x);
490 if (aia) {
491 if (!OCSP_parse_url(sk_OPENSSL_STRING_value(aia, 0),
492 &host, &port, &path, &use_ssl)) {
493 BIO_puts(err, "cert_status: can't parse AIA URL\n");
494 goto err;
495 }
496 if (srctx->verbose)
497 BIO_printf(err, "cert_status: AIA URL: %s\n",
498 sk_OPENSSL_STRING_value(aia, 0));
499 } else {
500 if (!srctx->host) {
501 BIO_puts(srctx->err, "cert_status: no AIA and no default responder URL\n");
502 goto done;
503 }
504 host = srctx->host;
505 path = srctx->path;
506 port = srctx->port;
507 use_ssl = srctx->use_ssl;
508 }
509
510 if (!X509_STORE_CTX_init(&inctx,
511 SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)),
512 NULL, NULL))
513 goto err;
514 if (X509_STORE_get_by_subject(&inctx, X509_LU_X509,
515 X509_get_issuer_name(x), &obj) <= 0) {
516 BIO_puts(err, "cert_status: Can't retrieve issuer certificate.\n");
517 X509_STORE_CTX_cleanup(&inctx);
518 goto done;
519 }
520 req = OCSP_REQUEST_new();
521 if (!req)
522 goto err;
523 id = OCSP_cert_to_id(NULL, x, obj.data.x509);
524 X509_free(obj.data.x509);
525 X509_STORE_CTX_cleanup(&inctx);
526 if (!id)
527 goto err;
528 if (!OCSP_request_add0_id(req, id))
529 goto err;
530 id = NULL;
531 /* Add any extensions to the request */
532 SSL_get_tlsext_status_exts(s, &exts);
533 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
534 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
535 if (!OCSP_REQUEST_add_ext(req, ext, -1))
536 goto err;
537 }
538 resp = process_responder(err, req, host, path, port, use_ssl, NULL,
539 srctx->timeout);
540 if (!resp) {
541 BIO_puts(err, "cert_status: error querying responder\n");
542 goto done;
543 }
544 rspderlen = i2d_OCSP_RESPONSE(resp, &rspder);
545 if (rspderlen <= 0)
546 goto err;
547 SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen);
548 if (srctx->verbose) {
549 BIO_puts(err, "cert_status: ocsp response sent:\n");
550 OCSP_RESPONSE_print(err, resp, 2);
551 }
552 ret = SSL_TLSEXT_ERR_OK;
553done:
554 if (ret != SSL_TLSEXT_ERR_OK)
555 ERR_print_errors(err);
556 if (aia) {
557 free(host);
558 free(path);
559 free(port);
560 X509_email_free(aia);
561 }
562 if (id)
563 OCSP_CERTID_free(id);
564 if (req)
565 OCSP_REQUEST_free(req);
566 if (resp)
567 OCSP_RESPONSE_free(resp);
568 return ret;
569err:
570 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
571 goto done;
572}
573
574#ifndef OPENSSL_NO_NEXTPROTONEG
575/* This is the context that we pass to next_proto_cb */
576typedef struct tlsextnextprotoctx_st {
577 unsigned char *data;
578 unsigned int len;
579} tlsextnextprotoctx;
580
581static int
582next_proto_cb(SSL * s, const unsigned char **data, unsigned int *len, void *arg)
583{
584 tlsextnextprotoctx *next_proto = arg;
585
586 *data = next_proto->data;
587 *len = next_proto->len;
588
589 return SSL_TLSEXT_ERR_OK;
590}
591#endif /* ndef OPENSSL_NO_NEXTPROTONEG */
592
593
594#endif
595
596int s_server_main(int, char **);
597
598#ifndef OPENSSL_NO_SRTP
599static char *srtp_profiles = NULL;
600#endif
601
602int
603s_server_main(int argc, char *argv[])
604{
605 X509_VERIFY_PARAM *vpm = NULL;
606 int badarg = 0;
607 short port = PORT;
608 char *CApath = NULL, *CAfile = NULL;
609 unsigned char *context = NULL;
610 char *dhfile = NULL;
611 char *named_curve = NULL;
612 int badop = 0, bugs = 0;
613 int ret = 1;
614 int off = 0;
615 int no_tmp_rsa = 0, no_dhe = 0, no_ecdhe = 0, nocert = 0;
616 int state = 0;
617 const SSL_METHOD *meth = NULL;
618 int socket_type = SOCK_STREAM;
619 ENGINE *e = NULL;
620 int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM;
621 char *passarg = NULL, *pass = NULL;
622 char *dpassarg = NULL, *dpass = NULL;
623 int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM;
624 X509 *s_cert = NULL, *s_dcert = NULL;
625 EVP_PKEY *s_key = NULL, *s_dkey = NULL;
626 int no_cache = 0;
627 const char *errstr = NULL;
628#ifndef OPENSSL_NO_TLSEXT
629 EVP_PKEY *s_key2 = NULL;
630 X509 *s_cert2 = NULL;
631 tlsextctx tlsextcbp = {NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING};
632#ifndef OPENSSL_NO_NEXTPROTONEG
633 const char *next_proto_neg_in = NULL;
634 tlsextnextprotoctx next_proto;
635#endif
636#endif
637 meth = SSLv23_server_method();
638
639 local_argc = argc;
640 local_argv = argv;
641
642 s_server_init();
643
644 verify_depth = 0;
645 s_nbio = 0;
646 s_nbio_test = 0;
647
648 argc--;
649 argv++;
650
651 while (argc >= 1) {
652 if ((strcmp(*argv, "-port") == 0) ||
653 (strcmp(*argv, "-accept") == 0)) {
654 if (--argc < 1)
655 goto bad;
656 if (!extract_port(*(++argv), &port))
657 goto bad;
658 } else if (strcmp(*argv, "-verify") == 0) {
659 s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
660 if (--argc < 1)
661 goto bad;
662 verify_depth = strtonum(*(++argv), 0, INT_MAX, &errstr);
663 if (errstr)
664 goto bad;
665 BIO_printf(bio_err, "verify depth is %d\n", verify_depth);
666 } else if (strcmp(*argv, "-Verify") == 0) {
667 s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
668 SSL_VERIFY_CLIENT_ONCE;
669 if (--argc < 1)
670 goto bad;
671 verify_depth = strtonum(*(++argv), 0, INT_MAX, &errstr);
672 if (errstr)
673 goto bad;
674 BIO_printf(bio_err, "verify depth is %d, must return a certificate\n", verify_depth);
675 } else if (strcmp(*argv, "-context") == 0) {
676 if (--argc < 1)
677 goto bad;
678 context = (unsigned char *) *(++argv);
679 } else if (strcmp(*argv, "-cert") == 0) {
680 if (--argc < 1)
681 goto bad;
682 s_cert_file = *(++argv);
683 } else if (strcmp(*argv, "-certform") == 0) {
684 if (--argc < 1)
685 goto bad;
686 s_cert_format = str2fmt(*(++argv));
687 } else if (strcmp(*argv, "-key") == 0) {
688 if (--argc < 1)
689 goto bad;
690 s_key_file = *(++argv);
691 } else if (strcmp(*argv, "-keyform") == 0) {
692 if (--argc < 1)
693 goto bad;
694 s_key_format = str2fmt(*(++argv));
695 } else if (strcmp(*argv, "-pass") == 0) {
696 if (--argc < 1)
697 goto bad;
698 passarg = *(++argv);
699 } else if (strcmp(*argv, "-dhparam") == 0) {
700 if (--argc < 1)
701 goto bad;
702 dhfile = *(++argv);
703 }
704 else if (strcmp(*argv, "-named_curve") == 0) {
705 if (--argc < 1)
706 goto bad;
707 named_curve = *(++argv);
708 }
709 else if (strcmp(*argv, "-dcertform") == 0) {
710 if (--argc < 1)
711 goto bad;
712 s_dcert_format = str2fmt(*(++argv));
713 } else if (strcmp(*argv, "-dcert") == 0) {
714 if (--argc < 1)
715 goto bad;
716 s_dcert_file = *(++argv);
717 } else if (strcmp(*argv, "-dkeyform") == 0) {
718 if (--argc < 1)
719 goto bad;
720 s_dkey_format = str2fmt(*(++argv));
721 } else if (strcmp(*argv, "-dpass") == 0) {
722 if (--argc < 1)
723 goto bad;
724 dpassarg = *(++argv);
725 } else if (strcmp(*argv, "-dkey") == 0) {
726 if (--argc < 1)
727 goto bad;
728 s_dkey_file = *(++argv);
729 } else if (strcmp(*argv, "-nocert") == 0) {
730 nocert = 1;
731 } else if (strcmp(*argv, "-CApath") == 0) {
732 if (--argc < 1)
733 goto bad;
734 CApath = *(++argv);
735 } else if (strcmp(*argv, "-no_cache") == 0)
736 no_cache = 1;
737 else if (args_verify(&argv, &argc, &badarg, bio_err, &vpm)) {
738 if (badarg)
739 goto bad;
740 continue;
741 } else if (strcmp(*argv, "-verify_return_error") == 0)
742 verify_return_error = 1;
743 else if (strcmp(*argv, "-serverpref") == 0) {
744 off |= SSL_OP_CIPHER_SERVER_PREFERENCE;
745 } else if (strcmp(*argv, "-legacy_renegotiation") == 0)
746 ; /* no-op */
747 else if (strcmp(*argv, "-cipher") == 0) {
748 if (--argc < 1)
749 goto bad;
750 cipher = *(++argv);
751 } else if (strcmp(*argv, "-CAfile") == 0) {
752 if (--argc < 1)
753 goto bad;
754 CAfile = *(++argv);
755 }
756 else if (strcmp(*argv, "-nbio") == 0) {
757 s_nbio = 1;
758 }
759 else if (strcmp(*argv, "-nbio_test") == 0) {
760 s_nbio = 1;
761 s_nbio_test = 1;
762 } else if (strcmp(*argv, "-debug") == 0) {
763 s_debug = 1;
764 }
765#ifndef OPENSSL_NO_TLSEXT
766 else if (strcmp(*argv, "-tlsextdebug") == 0)
767 s_tlsextdebug = 1;
768 else if (strcmp(*argv, "-status") == 0)
769 s_tlsextstatus = 1;
770 else if (strcmp(*argv, "-status_verbose") == 0) {
771 s_tlsextstatus = 1;
772 tlscstatp.verbose = 1;
773 } else if (!strcmp(*argv, "-status_timeout")) {
774 s_tlsextstatus = 1;
775 if (--argc < 1)
776 goto bad;
777 tlscstatp.timeout = strtonum(*(++argv), 0, INT_MAX, &errstr);
778 if (errstr)
779 goto bad;
780 } else if (!strcmp(*argv, "-status_url")) {
781 s_tlsextstatus = 1;
782 if (--argc < 1)
783 goto bad;
784 if (!OCSP_parse_url(*(++argv),
785 &tlscstatp.host,
786 &tlscstatp.port,
787 &tlscstatp.path,
788 &tlscstatp.use_ssl)) {
789 BIO_printf(bio_err, "Error parsing URL\n");
790 goto bad;
791 }
792 }
793#endif
794 else if (strcmp(*argv, "-msg") == 0) {
795 s_msg = 1;
796 } else if (strcmp(*argv, "-hack") == 0) {
797 hack = 1;
798 } else if (strcmp(*argv, "-state") == 0) {
799 state = 1;
800 } else if (strcmp(*argv, "-crlf") == 0) {
801 s_crlf = 1;
802 } else if (strcmp(*argv, "-quiet") == 0) {
803 s_quiet = 1;
804 } else if (strcmp(*argv, "-bugs") == 0) {
805 bugs = 1;
806 } else if (strcmp(*argv, "-no_tmp_rsa") == 0) {
807 no_tmp_rsa = 1;
808 } else if (strcmp(*argv, "-no_dhe") == 0) {
809 no_dhe = 1;
810 } else if (strcmp(*argv, "-no_ecdhe") == 0) {
811 no_ecdhe = 1;
812 }
813 else if (strcmp(*argv, "-www") == 0) {
814 www = 1;
815 } else if (strcmp(*argv, "-WWW") == 0) {
816 www = 2;
817 } else if (strcmp(*argv, "-HTTP") == 0) {
818 www = 3;
819 } else if (strcmp(*argv, "-no_ssl2") == 0) {
820 off |= SSL_OP_NO_SSLv2;
821 } else if (strcmp(*argv, "-no_ssl3") == 0) {
822 off |= SSL_OP_NO_SSLv3;
823 } else if (strcmp(*argv, "-no_tls1") == 0) {
824 off |= SSL_OP_NO_TLSv1;
825 } else if (strcmp(*argv, "-no_tls1_1") == 0) {
826 off |= SSL_OP_NO_TLSv1_1;
827 } else if (strcmp(*argv, "-no_tls1_2") == 0) {
828 off |= SSL_OP_NO_TLSv1_2;
829 } else if (strcmp(*argv, "-no_comp") == 0) {
830 off |= SSL_OP_NO_COMPRESSION;
831 }
832#ifndef OPENSSL_NO_TLSEXT
833 else if (strcmp(*argv, "-no_ticket") == 0) {
834 off |= SSL_OP_NO_TICKET;
835 }
836#endif
837 else if (strcmp(*argv, "-ssl3") == 0) {
838 meth = SSLv3_server_method();
839 } else if (strcmp(*argv, "-tls1") == 0) {
840 meth = TLSv1_server_method();
841 } else if (strcmp(*argv, "-tls1_1") == 0) {
842 meth = TLSv1_1_server_method();
843 } else if (strcmp(*argv, "-tls1_2") == 0) {
844 meth = TLSv1_2_server_method();
845 }
846#ifndef OPENSSL_NO_DTLS1
847 else if (strcmp(*argv, "-dtls1") == 0) {
848 meth = DTLSv1_server_method();
849 socket_type = SOCK_DGRAM;
850 } else if (strcmp(*argv, "-timeout") == 0)
851 enable_timeouts = 1;
852 else if (strcmp(*argv, "-mtu") == 0) {
853 if (--argc < 1)
854 goto bad;
855 socket_mtu = strtonum(*(++argv), 0, LONG_MAX, &errstr);
856 if (errstr)
857 goto bad;
858 } else if (strcmp(*argv, "-chain") == 0)
859 cert_chain = 1;
860#endif
861 else if (strcmp(*argv, "-id_prefix") == 0) {
862 if (--argc < 1)
863 goto bad;
864 session_id_prefix = *(++argv);
865 }
866#ifndef OPENSSL_NO_ENGINE
867 else if (strcmp(*argv, "-engine") == 0) {
868 if (--argc < 1)
869 goto bad;
870 engine_id = *(++argv);
871 }
872#endif
873#ifndef OPENSSL_NO_TLSEXT
874 else if (strcmp(*argv, "-servername") == 0) {
875 if (--argc < 1)
876 goto bad;
877 tlsextcbp.servername = *(++argv);
878 } else if (strcmp(*argv, "-servername_fatal") == 0) {
879 tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL;
880 } else if (strcmp(*argv, "-cert2") == 0) {
881 if (--argc < 1)
882 goto bad;
883 s_cert_file2 = *(++argv);
884 } else if (strcmp(*argv, "-key2") == 0) {
885 if (--argc < 1)
886 goto bad;
887 s_key_file2 = *(++argv);
888 }
889#ifndef OPENSSL_NO_NEXTPROTONEG
890 else if (strcmp(*argv, "-nextprotoneg") == 0) {
891 if (--argc < 1)
892 goto bad;
893 next_proto_neg_in = *(++argv);
894 }
895#endif
896#endif
897#ifndef OPENSSL_NO_SRTP
898 else if (strcmp(*argv, "-use_srtp") == 0) {
899 if (--argc < 1)
900 goto bad;
901 srtp_profiles = *(++argv);
902 }
903#endif
904 else if (strcmp(*argv, "-keymatexport") == 0) {
905 if (--argc < 1)
906 goto bad;
907 keymatexportlabel = *(++argv);
908 } else if (strcmp(*argv, "-keymatexportlen") == 0) {
909 if (--argc < 1)
910 goto bad;
911 keymatexportlen = strtonum(*(++argv), 1, INT_MAX, &errstr);
912 if (errstr)
913 goto bad;
914 } else {
915 BIO_printf(bio_err, "unknown option %s\n", *argv);
916 badop = 1;
917 break;
918 }
919 argc--;
920 argv++;
921 }
922 if (badop) {
923bad:
924 if (errstr)
925 BIO_printf(bio_err, "invalid argument %s: %s\n",
926 *argv, errstr);
927 else
928 sv_usage();
929 goto end;
930 }
931
932#ifndef OPENSSL_NO_ENGINE
933 e = setup_engine(bio_err, engine_id, 1);
934#endif
935
936 if (!app_passwd(bio_err, passarg, dpassarg, &pass, &dpass)) {
937 BIO_printf(bio_err, "Error getting password\n");
938 goto end;
939 }
940 if (s_key_file == NULL)
941 s_key_file = s_cert_file;
942#ifndef OPENSSL_NO_TLSEXT
943 if (s_key_file2 == NULL)
944 s_key_file2 = s_cert_file2;
945#endif
946
947 if (nocert == 0) {
948 s_key = load_key(bio_err, s_key_file, s_key_format, 0, pass, e,
949 "server certificate private key file");
950 if (!s_key) {
951 ERR_print_errors(bio_err);
952 goto end;
953 }
954 s_cert = load_cert(bio_err, s_cert_file, s_cert_format,
955 NULL, e, "server certificate file");
956
957 if (!s_cert) {
958 ERR_print_errors(bio_err);
959 goto end;
960 }
961#ifndef OPENSSL_NO_TLSEXT
962 if (tlsextcbp.servername) {
963 s_key2 = load_key(bio_err, s_key_file2, s_key_format, 0, pass, e,
964 "second server certificate private key file");
965 if (!s_key2) {
966 ERR_print_errors(bio_err);
967 goto end;
968 }
969 s_cert2 = load_cert(bio_err, s_cert_file2, s_cert_format,
970 NULL, e, "second server certificate file");
971
972 if (!s_cert2) {
973 ERR_print_errors(bio_err);
974 goto end;
975 }
976 }
977#endif
978 }
979#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
980 if (next_proto_neg_in) {
981 unsigned short len;
982 next_proto.data = next_protos_parse(&len, next_proto_neg_in);
983 if (next_proto.data == NULL)
984 goto end;
985 next_proto.len = len;
986 } else {
987 next_proto.data = NULL;
988 }
989#endif
990
991
992 if (s_dcert_file) {
993
994 if (s_dkey_file == NULL)
995 s_dkey_file = s_dcert_file;
996
997 s_dkey = load_key(bio_err, s_dkey_file, s_dkey_format,
998 0, dpass, e,
999 "second certificate private key file");
1000 if (!s_dkey) {
1001 ERR_print_errors(bio_err);
1002 goto end;
1003 }
1004 s_dcert = load_cert(bio_err, s_dcert_file, s_dcert_format,
1005 NULL, e, "second server certificate file");
1006
1007 if (!s_dcert) {
1008 ERR_print_errors(bio_err);
1009 goto end;
1010 }
1011 }
1012 if (bio_s_out == NULL) {
1013 if (s_quiet && !s_debug && !s_msg) {
1014 bio_s_out = BIO_new(BIO_s_null());
1015 } else {
1016 if (bio_s_out == NULL)
1017 bio_s_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1018 }
1019 }
1020 if (nocert)
1021 {
1022 s_cert_file = NULL;
1023 s_key_file = NULL;
1024 s_dcert_file = NULL;
1025 s_dkey_file = NULL;
1026#ifndef OPENSSL_NO_TLSEXT
1027 s_cert_file2 = NULL;
1028 s_key_file2 = NULL;
1029#endif
1030 }
1031 ctx = SSL_CTX_new(meth);
1032 if (ctx == NULL) {
1033 ERR_print_errors(bio_err);
1034 goto end;
1035 }
1036 if (session_id_prefix) {
1037 if (strlen(session_id_prefix) >= 32)
1038 BIO_printf(bio_err,
1039 "warning: id_prefix is too long, only one new session will be possible\n");
1040 else if (strlen(session_id_prefix) >= 16)
1041 BIO_printf(bio_err,
1042 "warning: id_prefix is too long if you use SSLv2\n");
1043 if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) {
1044 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1045 ERR_print_errors(bio_err);
1046 goto end;
1047 }
1048 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1049 }
1050 SSL_CTX_set_quiet_shutdown(ctx, 1);
1051 if (bugs)
1052 SSL_CTX_set_options(ctx, SSL_OP_ALL);
1053 if (hack)
1054 SSL_CTX_set_options(ctx, SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG);
1055 SSL_CTX_set_options(ctx, off);
1056 /*
1057 * DTLS: partial reads end up discarding unread UDP bytes :-( Setting
1058 * read ahead solves this problem.
1059 */
1060 if (socket_type == SOCK_DGRAM)
1061 SSL_CTX_set_read_ahead(ctx, 1);
1062
1063 if (state)
1064 SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1065 if (no_cache)
1066 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1067 else
1068 SSL_CTX_sess_set_cache_size(ctx, 128);
1069
1070#ifndef OPENSSL_NO_SRTP
1071 if (srtp_profiles != NULL)
1072 SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles);
1073#endif
1074
1075
1076 if ((!SSL_CTX_load_verify_locations(ctx, CAfile, CApath)) ||
1077 (!SSL_CTX_set_default_verify_paths(ctx))) {
1078 /* BIO_printf(bio_err,"X509_load_verify_locations\n"); */
1079 ERR_print_errors(bio_err);
1080 /* goto end; */
1081 }
1082 if (vpm)
1083 SSL_CTX_set1_param(ctx, vpm);
1084
1085#ifndef OPENSSL_NO_TLSEXT
1086 if (s_cert2) {
1087 ctx2 = SSL_CTX_new(meth);
1088 if (ctx2 == NULL) {
1089 ERR_print_errors(bio_err);
1090 goto end;
1091 }
1092 }
1093 if (ctx2) {
1094 BIO_printf(bio_s_out, "Setting secondary ctx parameters\n");
1095
1096 if (session_id_prefix) {
1097 if (strlen(session_id_prefix) >= 32)
1098 BIO_printf(bio_err,
1099 "warning: id_prefix is too long, only one new session will be possible\n");
1100 else if (strlen(session_id_prefix) >= 16)
1101 BIO_printf(bio_err,
1102 "warning: id_prefix is too long if you use SSLv2\n");
1103 if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) {
1104 BIO_printf(bio_err, "error setting 'id_prefix'\n");
1105 ERR_print_errors(bio_err);
1106 goto end;
1107 }
1108 BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix);
1109 }
1110 SSL_CTX_set_quiet_shutdown(ctx2, 1);
1111 if (bugs)
1112 SSL_CTX_set_options(ctx2, SSL_OP_ALL);
1113 if (hack)
1114 SSL_CTX_set_options(ctx2, SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG);
1115 SSL_CTX_set_options(ctx2, off);
1116 /*
1117 * DTLS: partial reads end up discarding unread UDP bytes :-(
1118 * Setting read ahead solves this problem.
1119 */
1120 if (socket_type == SOCK_DGRAM)
1121 SSL_CTX_set_read_ahead(ctx2, 1);
1122
1123 if (state)
1124 SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback);
1125
1126 if (no_cache)
1127 SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF);
1128 else
1129 SSL_CTX_sess_set_cache_size(ctx2, 128);
1130
1131 if ((!SSL_CTX_load_verify_locations(ctx2, CAfile, CApath)) ||
1132 (!SSL_CTX_set_default_verify_paths(ctx2))) {
1133 ERR_print_errors(bio_err);
1134 }
1135 if (vpm)
1136 SSL_CTX_set1_param(ctx2, vpm);
1137 }
1138#ifndef OPENSSL_NO_NEXTPROTONEG
1139 if (next_proto.data)
1140 SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb, &next_proto);
1141#endif
1142#endif
1143
1144#ifndef OPENSSL_NO_DH
1145 if (!no_dhe) {
1146 DH *dh = NULL;
1147
1148 if (dhfile)
1149 dh = load_dh_param(dhfile);
1150 else if (s_cert_file)
1151 dh = load_dh_param(s_cert_file);
1152
1153 if (dh != NULL) {
1154 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1155 } else {
1156 BIO_printf(bio_s_out, "Using default temp DH parameters\n");
1157 dh = get_dh512();
1158 }
1159 (void) BIO_flush(bio_s_out);
1160
1161 SSL_CTX_set_tmp_dh(ctx, dh);
1162#ifndef OPENSSL_NO_TLSEXT
1163 if (ctx2) {
1164 if (!dhfile) {
1165 DH *dh2 = load_dh_param(s_cert_file2);
1166 if (dh2 != NULL) {
1167 BIO_printf(bio_s_out, "Setting temp DH parameters\n");
1168 (void) BIO_flush(bio_s_out);
1169
1170 DH_free(dh);
1171 dh = dh2;
1172 }
1173 }
1174 SSL_CTX_set_tmp_dh(ctx2, dh);
1175 }
1176#endif
1177 DH_free(dh);
1178 }
1179#endif
1180
1181 if (!no_ecdhe) {
1182 EC_KEY *ecdh = NULL;
1183
1184 if (named_curve) {
1185 int nid = OBJ_sn2nid(named_curve);
1186
1187 if (nid == 0) {
1188 BIO_printf(bio_err, "unknown curve name (%s)\n",
1189 named_curve);
1190 goto end;
1191 }
1192 ecdh = EC_KEY_new_by_curve_name(nid);
1193 if (ecdh == NULL) {
1194 BIO_printf(bio_err, "unable to create curve (%s)\n",
1195 named_curve);
1196 goto end;
1197 }
1198 }
1199 if (ecdh != NULL) {
1200 BIO_printf(bio_s_out, "Setting temp ECDH parameters\n");
1201 } else {
1202 BIO_printf(bio_s_out, "Using default temp ECDH parameters\n");
1203 ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
1204 if (ecdh == NULL) {
1205 BIO_printf(bio_err, "unable to create curve (nistp256)\n");
1206 goto end;
1207 }
1208 }
1209 (void) BIO_flush(bio_s_out);
1210
1211 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
1212#ifndef OPENSSL_NO_TLSEXT
1213 if (ctx2)
1214 SSL_CTX_set_tmp_ecdh(ctx2, ecdh);
1215#endif
1216 EC_KEY_free(ecdh);
1217 }
1218
1219 if (!set_cert_key_stuff(ctx, s_cert, s_key))
1220 goto end;
1221#ifndef OPENSSL_NO_TLSEXT
1222 if (ctx2 && !set_cert_key_stuff(ctx2, s_cert2, s_key2))
1223 goto end;
1224#endif
1225 if (s_dcert != NULL) {
1226 if (!set_cert_key_stuff(ctx, s_dcert, s_dkey))
1227 goto end;
1228 }
1229 if (!no_tmp_rsa) {
1230 SSL_CTX_set_tmp_rsa_callback(ctx, tmp_rsa_cb);
1231#ifndef OPENSSL_NO_TLSEXT
1232 if (ctx2)
1233 SSL_CTX_set_tmp_rsa_callback(ctx2, tmp_rsa_cb);
1234#endif
1235 }
1236
1237
1238 if (cipher != NULL) {
1239 if (!SSL_CTX_set_cipher_list(ctx, cipher)) {
1240 BIO_printf(bio_err, "error setting cipher list\n");
1241 ERR_print_errors(bio_err);
1242 goto end;
1243 }
1244#ifndef OPENSSL_NO_TLSEXT
1245 if (ctx2 && !SSL_CTX_set_cipher_list(ctx2, cipher)) {
1246 BIO_printf(bio_err, "error setting cipher list\n");
1247 ERR_print_errors(bio_err);
1248 goto end;
1249 }
1250#endif
1251 }
1252 SSL_CTX_set_verify(ctx, s_server_verify, verify_callback);
1253 SSL_CTX_set_session_id_context(ctx, (void *) &s_server_session_id_context,
1254 sizeof s_server_session_id_context);
1255
1256 /* Set DTLS cookie generation and verification callbacks */
1257 SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback);
1258 SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback);
1259
1260#ifndef OPENSSL_NO_TLSEXT
1261 if (ctx2) {
1262 SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback);
1263 SSL_CTX_set_session_id_context(ctx2, (void *) &s_server_session_id_context,
1264 sizeof s_server_session_id_context);
1265
1266 tlsextcbp.biodebug = bio_s_out;
1267 SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb);
1268 SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp);
1269 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1270 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1271 }
1272#endif
1273
1274 if (CAfile != NULL) {
1275 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile));
1276#ifndef OPENSSL_NO_TLSEXT
1277 if (ctx2)
1278 SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile));
1279#endif
1280 }
1281 BIO_printf(bio_s_out, "ACCEPT\n");
1282 (void) BIO_flush(bio_s_out);
1283 if (www)
1284 do_server(port, socket_type, &accept_socket, www_body, context);
1285 else
1286 do_server(port, socket_type, &accept_socket, sv_body, context);
1287 print_stats(bio_s_out, ctx);
1288 ret = 0;
1289end:
1290 if (ctx != NULL)
1291 SSL_CTX_free(ctx);
1292 if (s_cert)
1293 X509_free(s_cert);
1294 if (s_dcert)
1295 X509_free(s_dcert);
1296 if (s_key)
1297 EVP_PKEY_free(s_key);
1298 if (s_dkey)
1299 EVP_PKEY_free(s_dkey);
1300 free(pass);
1301 free(dpass);
1302 if (vpm)
1303 X509_VERIFY_PARAM_free(vpm);
1304#ifndef OPENSSL_NO_TLSEXT
1305 free(tlscstatp.host);
1306 free(tlscstatp.port);
1307 free(tlscstatp.path);
1308 if (ctx2 != NULL)
1309 SSL_CTX_free(ctx2);
1310 if (s_cert2)
1311 X509_free(s_cert2);
1312 if (s_key2)
1313 EVP_PKEY_free(s_key2);
1314#endif
1315 if (bio_s_out != NULL) {
1316 BIO_free(bio_s_out);
1317 bio_s_out = NULL;
1318 }
1319
1320 return (ret);
1321}
1322
1323static void
1324print_stats(BIO * bio, SSL_CTX * ssl_ctx)
1325{
1326 BIO_printf(bio, "%4ld items in the session cache\n",
1327 SSL_CTX_sess_number(ssl_ctx));
1328 BIO_printf(bio, "%4ld client connects (SSL_connect())\n",
1329 SSL_CTX_sess_connect(ssl_ctx));
1330 BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n",
1331 SSL_CTX_sess_connect_renegotiate(ssl_ctx));
1332 BIO_printf(bio, "%4ld client connects that finished\n",
1333 SSL_CTX_sess_connect_good(ssl_ctx));
1334 BIO_printf(bio, "%4ld server accepts (SSL_accept())\n",
1335 SSL_CTX_sess_accept(ssl_ctx));
1336 BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n",
1337 SSL_CTX_sess_accept_renegotiate(ssl_ctx));
1338 BIO_printf(bio, "%4ld server accepts that finished\n",
1339 SSL_CTX_sess_accept_good(ssl_ctx));
1340 BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx));
1341 BIO_printf(bio, "%4ld session cache misses\n", SSL_CTX_sess_misses(ssl_ctx));
1342 BIO_printf(bio, "%4ld session cache timeouts\n", SSL_CTX_sess_timeouts(ssl_ctx));
1343 BIO_printf(bio, "%4ld callback cache hits\n", SSL_CTX_sess_cb_hits(ssl_ctx));
1344 BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n",
1345 SSL_CTX_sess_cache_full(ssl_ctx),
1346 SSL_CTX_sess_get_cache_size(ssl_ctx));
1347}
1348
1349static int
1350sv_body(char *hostname, int s, unsigned char *context)
1351{
1352 char *buf = NULL;
1353 fd_set readfds;
1354 int ret = 1, width;
1355 int k, i;
1356 unsigned long l;
1357 SSL *con = NULL;
1358 BIO *sbio;
1359 struct timeval timeout;
1360 struct timeval *timeoutp;
1361
1362 if ((buf = malloc(bufsize)) == NULL) {
1363 BIO_printf(bio_err, "out of memory\n");
1364 goto err;
1365 }
1366 if (s_nbio) {
1367 unsigned long sl = 1;
1368
1369 if (!s_quiet)
1370 BIO_printf(bio_err, "turning on non blocking io\n");
1371 if (BIO_socket_ioctl(s, FIONBIO, &sl) < 0)
1372 ERR_print_errors(bio_err);
1373 }
1374
1375 if (con == NULL) {
1376 con = SSL_new(ctx);
1377#ifndef OPENSSL_NO_TLSEXT
1378 if (s_tlsextdebug) {
1379 SSL_set_tlsext_debug_callback(con, tlsext_cb);
1380 SSL_set_tlsext_debug_arg(con, bio_s_out);
1381 }
1382 if (s_tlsextstatus) {
1383 SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb);
1384 tlscstatp.err = bio_err;
1385 SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp);
1386 }
1387#endif
1388 if (context)
1389 SSL_set_session_id_context(con, context,
1390 strlen((char *) context));
1391 }
1392 SSL_clear(con);
1393
1394 if (SSL_version(con) == DTLS1_VERSION) {
1395
1396 sbio = BIO_new_dgram(s, BIO_NOCLOSE);
1397
1398 if (enable_timeouts) {
1399 timeout.tv_sec = 0;
1400 timeout.tv_usec = DGRAM_RCV_TIMEOUT;
1401 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
1402
1403 timeout.tv_sec = 0;
1404 timeout.tv_usec = DGRAM_SND_TIMEOUT;
1405 BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
1406 }
1407 if (socket_mtu > 28) {
1408 SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
1409 SSL_set_mtu(con, socket_mtu - 28);
1410 } else
1411 /* want to do MTU discovery */
1412 BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
1413
1414 /* turn on cookie exchange */
1415 SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE);
1416 } else
1417 sbio = BIO_new_socket(s, BIO_NOCLOSE);
1418
1419 if (s_nbio_test) {
1420 BIO *test;
1421
1422 test = BIO_new(BIO_f_nbio_test());
1423 sbio = BIO_push(test, sbio);
1424 }
1425
1426 SSL_set_bio(con, sbio, sbio);
1427 SSL_set_accept_state(con);
1428 /* SSL_set_fd(con,s); */
1429
1430 if (s_debug) {
1431 SSL_set_debug(con, 1);
1432 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
1433 BIO_set_callback_arg(SSL_get_rbio(con), (char *) bio_s_out);
1434 }
1435 if (s_msg) {
1436 SSL_set_msg_callback(con, msg_cb);
1437 SSL_set_msg_callback_arg(con, bio_s_out);
1438 }
1439#ifndef OPENSSL_NO_TLSEXT
1440 if (s_tlsextdebug) {
1441 SSL_set_tlsext_debug_callback(con, tlsext_cb);
1442 SSL_set_tlsext_debug_arg(con, bio_s_out);
1443 }
1444#endif
1445
1446 width = s + 1;
1447 for (;;) {
1448 int read_from_terminal;
1449 int read_from_sslcon;
1450
1451 read_from_terminal = 0;
1452 read_from_sslcon = SSL_pending(con);
1453
1454 if (!read_from_sslcon) {
1455 FD_ZERO(&readfds);
1456 FD_SET(fileno(stdin), &readfds);
1457 FD_SET(s, &readfds);
1458 if ((SSL_version(con) == DTLS1_VERSION) &&
1459 DTLSv1_get_timeout(con, &timeout))
1460 timeoutp = &timeout;
1461 else
1462 timeoutp = NULL;
1463
1464 i = select(width, &readfds, NULL, NULL, timeoutp);
1465
1466 if ((SSL_version(con) == DTLS1_VERSION) && DTLSv1_handle_timeout(con) > 0) {
1467 BIO_printf(bio_err, "TIMEOUT occured\n");
1468 }
1469 if (i <= 0)
1470 continue;
1471 if (FD_ISSET(fileno(stdin), &readfds))
1472 read_from_terminal = 1;
1473 if (FD_ISSET(s, &readfds))
1474 read_from_sslcon = 1;
1475 }
1476 if (read_from_terminal) {
1477 if (s_crlf) {
1478 int j, lf_num;
1479
1480 i = read(fileno(stdin), buf, bufsize / 2);
1481 lf_num = 0;
1482 /* both loops are skipped when i <= 0 */
1483 for (j = 0; j < i; j++)
1484 if (buf[j] == '\n')
1485 lf_num++;
1486 for (j = i - 1; j >= 0; j--) {
1487 buf[j + lf_num] = buf[j];
1488 if (buf[j] == '\n') {
1489 lf_num--;
1490 i++;
1491 buf[j + lf_num] = '\r';
1492 }
1493 }
1494 assert(lf_num == 0);
1495 } else
1496 i = read(fileno(stdin), buf, bufsize);
1497 if (!s_quiet) {
1498 if ((i <= 0) || (buf[0] == 'Q')) {
1499 BIO_printf(bio_s_out, "DONE\n");
1500 shutdown(s, SHUT_RD);
1501 close(s);
1502 close_accept_socket();
1503 ret = -11;
1504 goto err;
1505 }
1506 if ((i <= 0) || (buf[0] == 'q')) {
1507 BIO_printf(bio_s_out, "DONE\n");
1508 if (SSL_version(con) != DTLS1_VERSION) {
1509 shutdown(s, SHUT_RD);
1510 close(s);
1511 }
1512 /*
1513 * close_accept_socket(); ret= -11;
1514 */
1515 goto err;
1516 }
1517 if ((buf[0] == 'r') &&
1518 ((buf[1] == '\n') || (buf[1] == '\r'))) {
1519 SSL_renegotiate(con);
1520 i = SSL_do_handshake(con);
1521 printf("SSL_do_handshake -> %d\n", i);
1522 i = 0; /* 13; */
1523 continue;
1524 /*
1525 * strcpy(buf,"server side
1526 * RE-NEGOTIATE\n");
1527 */
1528 }
1529 if ((buf[0] == 'R') &&
1530 ((buf[1] == '\n') || (buf[1] == '\r'))) {
1531 SSL_set_verify(con,
1532 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, NULL);
1533 SSL_renegotiate(con);
1534 i = SSL_do_handshake(con);
1535 printf("SSL_do_handshake -> %d\n", i);
1536 i = 0; /* 13; */
1537 continue;
1538 /*
1539 * strcpy(buf,"server side
1540 * RE-NEGOTIATE asking for client
1541 * cert\n");
1542 */
1543 }
1544 if (buf[0] == 'P') {
1545 static const char *str = "Lets print some clear text\n";
1546 BIO_write(SSL_get_wbio(con), str, strlen(str));
1547 }
1548 if (buf[0] == 'S') {
1549 print_stats(bio_s_out, SSL_get_SSL_CTX(con));
1550 }
1551 }
1552 l = k = 0;
1553 for (;;) {
1554 /* should do a select for the write */
1555#ifdef RENEG
1556 {
1557 static count = 0;
1558 if (++count == 100) {
1559 count = 0;
1560 SSL_renegotiate(con);
1561 }
1562 }
1563#endif
1564 k = SSL_write(con, &(buf[l]), (unsigned int) i);
1565 switch (SSL_get_error(con, k)) {
1566 case SSL_ERROR_NONE:
1567 break;
1568 case SSL_ERROR_WANT_WRITE:
1569 case SSL_ERROR_WANT_READ:
1570 case SSL_ERROR_WANT_X509_LOOKUP:
1571 BIO_printf(bio_s_out, "Write BLOCK\n");
1572 break;
1573 case SSL_ERROR_SYSCALL:
1574 case SSL_ERROR_SSL:
1575 BIO_printf(bio_s_out, "ERROR\n");
1576 ERR_print_errors(bio_err);
1577 ret = 1;
1578 goto err;
1579 /* break; */
1580 case SSL_ERROR_ZERO_RETURN:
1581 BIO_printf(bio_s_out, "DONE\n");
1582 ret = 1;
1583 goto err;
1584 }
1585 l += k;
1586 i -= k;
1587 if (i <= 0)
1588 break;
1589 }
1590 }
1591 if (read_from_sslcon) {
1592 if (!SSL_is_init_finished(con)) {
1593 i = init_ssl_connection(con);
1594
1595 if (i < 0) {
1596 ret = 0;
1597 goto err;
1598 } else if (i == 0) {
1599 ret = 1;
1600 goto err;
1601 }
1602 } else {
1603 again:
1604 i = SSL_read(con, (char *) buf, bufsize);
1605 switch (SSL_get_error(con, i)) {
1606 case SSL_ERROR_NONE: {
1607 int len, n;
1608 for (len = 0; len < i;) {
1609 do {
1610 n = write(fileno(stdout), buf + len, i - len);
1611 } while (n == -1 && errno == EINTR);
1612
1613 if (n < 0) {
1614 BIO_printf(bio_s_out, "ERROR\n");
1615 goto err;
1616 }
1617 len += n;
1618 }
1619 }
1620 if (SSL_pending(con))
1621 goto again;
1622 break;
1623 case SSL_ERROR_WANT_WRITE:
1624 case SSL_ERROR_WANT_READ:
1625 BIO_printf(bio_s_out, "Read BLOCK\n");
1626 break;
1627 case SSL_ERROR_SYSCALL:
1628 case SSL_ERROR_SSL:
1629 BIO_printf(bio_s_out, "ERROR\n");
1630 ERR_print_errors(bio_err);
1631 ret = 1;
1632 goto err;
1633 case SSL_ERROR_ZERO_RETURN:
1634 BIO_printf(bio_s_out, "DONE\n");
1635 ret = 1;
1636 goto err;
1637 }
1638 }
1639 }
1640 }
1641err:
1642 if (con != NULL) {
1643 BIO_printf(bio_s_out, "shutting down SSL\n");
1644 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
1645 SSL_free(con);
1646 }
1647 BIO_printf(bio_s_out, "CONNECTION CLOSED\n");
1648 if (buf != NULL) {
1649 OPENSSL_cleanse(buf, bufsize);
1650 free(buf);
1651 }
1652 if (ret >= 0)
1653 BIO_printf(bio_s_out, "ACCEPT\n");
1654 return (ret);
1655}
1656
1657static void
1658close_accept_socket(void)
1659{
1660 BIO_printf(bio_err, "shutdown accept socket\n");
1661 if (accept_socket >= 0) {
1662 shutdown(accept_socket, SHUT_RDWR);
1663 close(accept_socket);
1664 }
1665}
1666
1667static int
1668init_ssl_connection(SSL * con)
1669{
1670 int i;
1671 const char *str;
1672 X509 *peer;
1673 long verify_error;
1674 char buf[BUFSIZ];
1675#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
1676 const unsigned char *next_proto_neg;
1677 unsigned next_proto_neg_len;
1678#endif
1679 unsigned char *exportedkeymat;
1680
1681
1682 i = SSL_accept(con);
1683 if (i <= 0) {
1684 if (BIO_sock_should_retry(i)) {
1685 BIO_printf(bio_s_out, "DELAY\n");
1686 return (1);
1687 }
1688 BIO_printf(bio_err, "ERROR\n");
1689 verify_error = SSL_get_verify_result(con);
1690 if (verify_error != X509_V_OK) {
1691 BIO_printf(bio_err, "verify error:%s\n",
1692 X509_verify_cert_error_string(verify_error));
1693 } else
1694 ERR_print_errors(bio_err);
1695 return (0);
1696 }
1697 PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
1698
1699 peer = SSL_get_peer_certificate(con);
1700 if (peer != NULL) {
1701 BIO_printf(bio_s_out, "Client certificate\n");
1702 PEM_write_bio_X509(bio_s_out, peer);
1703 X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf);
1704 BIO_printf(bio_s_out, "subject=%s\n", buf);
1705 X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf);
1706 BIO_printf(bio_s_out, "issuer=%s\n", buf);
1707 X509_free(peer);
1708 }
1709 if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL)
1710 BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
1711 str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
1712 BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
1713
1714#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
1715 SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
1716 if (next_proto_neg) {
1717 BIO_printf(bio_s_out, "NEXTPROTO is ");
1718 BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
1719 BIO_printf(bio_s_out, "\n");
1720 }
1721#endif
1722#ifndef OPENSSL_NO_SRTP
1723 {
1724 SRTP_PROTECTION_PROFILE *srtp_profile
1725 = SSL_get_selected_srtp_profile(con);
1726
1727 if (srtp_profile)
1728 BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
1729 srtp_profile->name);
1730 }
1731#endif
1732 if (SSL_cache_hit(con))
1733 BIO_printf(bio_s_out, "Reused session-id\n");
1734 if (SSL_ctrl(con, SSL_CTRL_GET_FLAGS, 0, NULL) &
1735 TLS1_FLAGS_TLS_PADDING_BUG)
1736 BIO_printf(bio_s_out,
1737 "Peer has incorrect TLSv1 block padding\n");
1738 BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
1739 SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
1740 if (keymatexportlabel != NULL) {
1741 BIO_printf(bio_s_out, "Keying material exporter:\n");
1742 BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
1743 BIO_printf(bio_s_out, " Length: %i bytes\n",
1744 keymatexportlen);
1745 exportedkeymat = malloc(keymatexportlen);
1746 if (exportedkeymat != NULL) {
1747 if (!SSL_export_keying_material(con, exportedkeymat,
1748 keymatexportlen,
1749 keymatexportlabel,
1750 strlen(keymatexportlabel),
1751 NULL, 0, 0)) {
1752 BIO_printf(bio_s_out, " Error\n");
1753 } else {
1754 BIO_printf(bio_s_out, " Keying material: ");
1755 for (i = 0; i < keymatexportlen; i++)
1756 BIO_printf(bio_s_out, "%02X",
1757 exportedkeymat[i]);
1758 BIO_printf(bio_s_out, "\n");
1759 }
1760 free(exportedkeymat);
1761 }
1762 }
1763 return (1);
1764}
1765
1766#ifndef OPENSSL_NO_DH
1767static DH *
1768load_dh_param(const char *dhfile)
1769{
1770 DH *ret = NULL;
1771 BIO *bio;
1772
1773 if ((bio = BIO_new_file(dhfile, "r")) == NULL)
1774 goto err;
1775 ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1776err:
1777 BIO_free(bio);
1778 return (ret);
1779}
1780#endif
1781
1782static int
1783www_body(char *hostname, int s, unsigned char *context)
1784{
1785 char *buf = NULL;
1786 int ret = 1;
1787 int i, j, k, dot;
1788 SSL *con;
1789 const SSL_CIPHER *c;
1790 BIO *io, *ssl_bio, *sbio;
1791
1792 buf = malloc(bufsize);
1793 if (buf == NULL)
1794 return (0);
1795 io = BIO_new(BIO_f_buffer());
1796 ssl_bio = BIO_new(BIO_f_ssl());
1797 if ((io == NULL) || (ssl_bio == NULL))
1798 goto err;
1799
1800 if (s_nbio) {
1801 unsigned long sl = 1;
1802
1803 if (!s_quiet)
1804 BIO_printf(bio_err, "turning on non blocking io\n");
1805 if (BIO_socket_ioctl(s, FIONBIO, &sl) < 0)
1806 ERR_print_errors(bio_err);
1807 }
1808
1809 /* lets make the output buffer a reasonable size */
1810 if (!BIO_set_write_buffer_size(io, bufsize))
1811 goto err;
1812
1813 if ((con = SSL_new(ctx)) == NULL)
1814 goto err;
1815#ifndef OPENSSL_NO_TLSEXT
1816 if (s_tlsextdebug) {
1817 SSL_set_tlsext_debug_callback(con, tlsext_cb);
1818 SSL_set_tlsext_debug_arg(con, bio_s_out);
1819 }
1820#endif
1821 if (context)
1822 SSL_set_session_id_context(con, context,
1823 strlen((char *) context));
1824
1825 sbio = BIO_new_socket(s, BIO_NOCLOSE);
1826 if (s_nbio_test) {
1827 BIO *test;
1828
1829 test = BIO_new(BIO_f_nbio_test());
1830 sbio = BIO_push(test, sbio);
1831 }
1832 SSL_set_bio(con, sbio, sbio);
1833 SSL_set_accept_state(con);
1834
1835 /* SSL_set_fd(con,s); */
1836 BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
1837 BIO_push(io, ssl_bio);
1838
1839 if (s_debug) {
1840 SSL_set_debug(con, 1);
1841 BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
1842 BIO_set_callback_arg(SSL_get_rbio(con), (char *) bio_s_out);
1843 }
1844 if (s_msg) {
1845 SSL_set_msg_callback(con, msg_cb);
1846 SSL_set_msg_callback_arg(con, bio_s_out);
1847 }
1848 for (;;) {
1849 if (hack) {
1850 i = SSL_accept(con);
1851 switch (SSL_get_error(con, i)) {
1852 case SSL_ERROR_NONE:
1853 break;
1854 case SSL_ERROR_WANT_WRITE:
1855 case SSL_ERROR_WANT_READ:
1856 case SSL_ERROR_WANT_X509_LOOKUP:
1857 continue;
1858 case SSL_ERROR_SYSCALL:
1859 case SSL_ERROR_SSL:
1860 case SSL_ERROR_ZERO_RETURN:
1861 ret = 1;
1862 goto err;
1863 /* break; */
1864 }
1865
1866 SSL_renegotiate(con);
1867 SSL_write(con, NULL, 0);
1868 }
1869 i = BIO_gets(io, buf, bufsize - 1);
1870 if (i < 0) { /* error */
1871 if (!BIO_should_retry(io)) {
1872 if (!s_quiet)
1873 ERR_print_errors(bio_err);
1874 goto err;
1875 } else {
1876 BIO_printf(bio_s_out, "read R BLOCK\n");
1877 sleep(1);
1878 continue;
1879 }
1880 } else if (i == 0) { /* end of input */
1881 ret = 1;
1882 goto end;
1883 }
1884 /* else we have data */
1885 if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) ||
1886 ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) {
1887 char *p;
1888 X509 *peer;
1889 STACK_OF(SSL_CIPHER) * sk;
1890 static const char *space = " ";
1891
1892 BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
1893 BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n");
1894 BIO_puts(io, "<pre>\n");
1895/* BIO_puts(io,SSLeay_version(SSLEAY_VERSION));*/
1896 BIO_puts(io, "\n");
1897 for (i = 0; i < local_argc; i++) {
1898 BIO_puts(io, local_argv[i]);
1899 BIO_write(io, " ", 1);
1900 }
1901 BIO_puts(io, "\n");
1902
1903 BIO_printf(io,
1904 "Secure Renegotiation IS%s supported\n",
1905 SSL_get_secure_renegotiation_support(con) ?
1906 "" : " NOT");
1907
1908 /*
1909 * The following is evil and should not really be
1910 * done
1911 */
1912 BIO_printf(io, "Ciphers supported in s_server binary\n");
1913 sk = SSL_get_ciphers(con);
1914 j = sk_SSL_CIPHER_num(sk);
1915 for (i = 0; i < j; i++) {
1916 c = sk_SSL_CIPHER_value(sk, i);
1917 BIO_printf(io, "%-11s:%-25s",
1918 SSL_CIPHER_get_version(c),
1919 SSL_CIPHER_get_name(c));
1920 if ((((i + 1) % 2) == 0) && (i + 1 != j))
1921 BIO_puts(io, "\n");
1922 }
1923 BIO_puts(io, "\n");
1924 p = SSL_get_shared_ciphers(con, buf, bufsize);
1925 if (p != NULL) {
1926 BIO_printf(io, "---\nCiphers common between both SSL end points:\n");
1927 j = i = 0;
1928 while (*p) {
1929 if (*p == ':') {
1930 BIO_write(io, space, 26 - j);
1931 i++;
1932 j = 0;
1933 BIO_write(io, ((i % 3) ? " " : "\n"), 1);
1934 } else {
1935 BIO_write(io, p, 1);
1936 j++;
1937 }
1938 p++;
1939 }
1940 BIO_puts(io, "\n");
1941 }
1942 BIO_printf(io, (SSL_cache_hit(con)
1943 ? "---\nReused, "
1944 : "---\nNew, "));
1945 c = SSL_get_current_cipher(con);
1946 BIO_printf(io, "%s, Cipher is %s\n",
1947 SSL_CIPHER_get_version(c),
1948 SSL_CIPHER_get_name(c));
1949 SSL_SESSION_print(io, SSL_get_session(con));
1950 BIO_printf(io, "---\n");
1951 print_stats(io, SSL_get_SSL_CTX(con));
1952 BIO_printf(io, "---\n");
1953 peer = SSL_get_peer_certificate(con);
1954 if (peer != NULL) {
1955 BIO_printf(io, "Client certificate\n");
1956 X509_print(io, peer);
1957 PEM_write_bio_X509(io, peer);
1958 } else
1959 BIO_puts(io, "no client certificate available\n");
1960 BIO_puts(io, "</BODY></HTML>\r\n\r\n");
1961 break;
1962 } else if ((www == 2 || www == 3)
1963 && (strncmp("GET /", buf, 5) == 0)) {
1964 BIO *file;
1965 char *p, *e;
1966 static const char *text = "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
1967
1968 /* skip the '/' */
1969 p = &(buf[5]);
1970
1971 dot = 1;
1972 for (e = p; *e != '\0'; e++) {
1973 if (e[0] == ' ')
1974 break;
1975
1976 switch (dot) {
1977 case 1:
1978 dot = (e[0] == '.') ? 2 : 0;
1979 break;
1980 case 2:
1981 dot = (e[0] == '.') ? 3 : 0;
1982 break;
1983 case 3:
1984 dot = (e[0] == '/') ? -1 : 0;
1985 break;
1986 }
1987 if (dot == 0)
1988 dot = (e[0] == '/') ? 1 : 0;
1989 }
1990 dot = (dot == 3) || (dot == -1); /* filename contains
1991 * ".." component */
1992
1993 if (*e == '\0') {
1994 BIO_puts(io, text);
1995 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
1996 break;
1997 }
1998 *e = '\0';
1999
2000 if (dot) {
2001 BIO_puts(io, text);
2002 BIO_printf(io, "'%s' contains '..' reference\r\n", p);
2003 break;
2004 }
2005 if (*p == '/') {
2006 BIO_puts(io, text);
2007 BIO_printf(io, "'%s' is an invalid path\r\n", p);
2008 break;
2009 }
2010 /* if a directory, do the index thang */
2011 if (app_isdir(p) > 0) {
2012 BIO_puts(io, text);
2013 BIO_printf(io, "'%s' is a directory\r\n", p);
2014 break;
2015 }
2016 if ((file = BIO_new_file(p, "r")) == NULL) {
2017 BIO_puts(io, text);
2018 BIO_printf(io, "Error opening '%s'\r\n", p);
2019 ERR_print_errors(io);
2020 break;
2021 }
2022 if (!s_quiet)
2023 BIO_printf(bio_err, "FILE:%s\n", p);
2024
2025 if (www == 2) {
2026 i = strlen(p);
2027 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
2028 ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
2029 ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
2030 BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
2031 else
2032 BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
2033 }
2034 /* send the file */
2035 for (;;) {
2036 i = BIO_read(file, buf, bufsize);
2037 if (i <= 0)
2038 break;
2039
2040#ifdef RENEG
2041 total_bytes += i;
2042 fprintf(stderr, "%d\n", i);
2043 if (total_bytes > 3 * 1024) {
2044 total_bytes = 0;
2045 fprintf(stderr, "RENEGOTIATE\n");
2046 SSL_renegotiate(con);
2047 }
2048#endif
2049
2050 for (j = 0; j < i;) {
2051#ifdef RENEG
2052 {
2053 static count = 0;
2054 if (++count == 13) {
2055 SSL_renegotiate(con);
2056 }
2057 }
2058#endif
2059 k = BIO_write(io, &(buf[j]), i - j);
2060 if (k <= 0) {
2061 if (!BIO_should_retry(io))
2062 goto write_error;
2063 else {
2064 BIO_printf(bio_s_out, "rwrite W BLOCK\n");
2065 }
2066 } else {
2067 j += k;
2068 }
2069 }
2070 }
2071 write_error:
2072 BIO_free(file);
2073 break;
2074 }
2075 }
2076
2077 for (;;) {
2078 i = (int) BIO_flush(io);
2079 if (i <= 0) {
2080 if (!BIO_should_retry(io))
2081 break;
2082 } else
2083 break;
2084 }
2085end:
2086 /* make sure we re-use sessions */
2087 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
2088
2089err:
2090
2091 if (ret >= 0)
2092 BIO_printf(bio_s_out, "ACCEPT\n");
2093
2094 if (buf != NULL)
2095 free(buf);
2096 if (io != NULL)
2097 BIO_free_all(io);
2098/* if (ssl_bio != NULL) BIO_free(ssl_bio);*/
2099 return (ret);
2100}
2101
2102static RSA *
2103tmp_rsa_cb(SSL * s, int is_export, int keylength)
2104{
2105 BIGNUM *bn = NULL;
2106 static RSA *rsa_tmp = NULL;
2107
2108 if (!rsa_tmp && ((bn = BN_new()) == NULL))
2109 BIO_printf(bio_err, "Allocation error in generating RSA key\n");
2110 if (!rsa_tmp && bn) {
2111 if (!s_quiet) {
2112 BIO_printf(bio_err, "Generating temp (%d bit) RSA key...", keylength);
2113 (void) BIO_flush(bio_err);
2114 }
2115 if (!BN_set_word(bn, RSA_F4) || ((rsa_tmp = RSA_new()) == NULL) ||
2116 !RSA_generate_key_ex(rsa_tmp, keylength, bn, NULL)) {
2117 if (rsa_tmp)
2118 RSA_free(rsa_tmp);
2119 rsa_tmp = NULL;
2120 }
2121 if (!s_quiet) {
2122 BIO_printf(bio_err, "\n");
2123 (void) BIO_flush(bio_err);
2124 }
2125 BN_free(bn);
2126 }
2127 return (rsa_tmp);
2128}
2129
2130#define MAX_SESSION_ID_ATTEMPTS 10
2131static int
2132generate_session_id(const SSL * ssl, unsigned char *id,
2133 unsigned int *id_len)
2134{
2135 unsigned int count = 0;
2136 do {
2137 RAND_pseudo_bytes(id, *id_len);
2138 /*
2139 * Prefix the session_id with the required prefix. NB: If our
2140 * prefix is too long, clip it - but there will be worse
2141 * effects anyway, eg. the server could only possibly create
2142 * 1 session ID (ie. the prefix!) so all future session
2143 * negotiations will fail due to conflicts.
2144 */
2145 memcpy(id, session_id_prefix,
2146 (strlen(session_id_prefix) < *id_len) ?
2147 strlen(session_id_prefix) : *id_len);
2148 }
2149 while (SSL_has_matching_session_id(ssl, id, *id_len) &&
2150 (++count < MAX_SESSION_ID_ATTEMPTS));
2151 if (count >= MAX_SESSION_ID_ATTEMPTS)
2152 return 0;
2153 return 1;
2154}
diff --git a/src/usr.bin/openssl/s_socket.c b/src/usr.bin/openssl/s_socket.c
new file mode 100644
index 0000000000..48af178a23
--- /dev/null
+++ b/src/usr.bin/openssl/s_socket.c
@@ -0,0 +1,351 @@
1/* $OpenBSD: s_socket.c,v 1.1 2014/08/26 17:47:25 jsing 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 <sys/socket.h>
60
61#include <netinet/in.h>
62
63#include <errno.h>
64#include <netdb.h>
65#include <stdio.h>
66#include <stdlib.h>
67#include <string.h>
68#include <unistd.h>
69
70#include "apps.h"
71
72#include <openssl/ssl.h>
73
74#include "s_apps.h"
75
76static int ssl_sock_init(void);
77static int init_server(int *sock, int port, int type);
78static int init_server_long(int *sock, int port, char *ip, int type);
79static int do_accept(int acc_sock, int *sock, char **host);
80
81#define SOCKET_PROTOCOL IPPROTO_TCP
82
83static int
84ssl_sock_init(void)
85{
86 return (1);
87}
88
89int
90init_client(int *sock, char *host, char *port, int type, int af)
91{
92 struct addrinfo hints, *ai_top, *ai;
93 int i, s;
94
95 if (!ssl_sock_init())
96 return (0);
97
98 memset(&hints, '\0', sizeof(hints));
99 hints.ai_family = af;
100 hints.ai_socktype = type;
101
102 if ((i = getaddrinfo(host, port, &hints, &ai_top)) != 0) {
103 BIO_printf(bio_err, "getaddrinfo: %s\n", gai_strerror(i));
104 return (0);
105 }
106 if (ai_top == NULL || ai_top->ai_addr == NULL) {
107 BIO_printf(bio_err, "getaddrinfo returned no addresses\n");
108 if (ai_top != NULL) {
109 freeaddrinfo(ai_top);
110 }
111 return (0);
112 }
113 for (ai = ai_top; ai != NULL; ai = ai->ai_next) {
114 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
115 if (s == -1) {
116 continue;
117 }
118 if (type == SOCK_STREAM) {
119 i = 0;
120 i = setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
121 (char *) &i, sizeof(i));
122 if (i < 0) {
123 perror("keepalive");
124 close(s);
125 return (0);
126 }
127 }
128 if ((i = connect(s, ai->ai_addr, ai->ai_addrlen)) == 0) {
129 *sock = s;
130 freeaddrinfo(ai_top);
131 return (1);
132 }
133 close(s);
134 }
135
136 perror("connect");
137 close(s);
138 freeaddrinfo(ai_top);
139 return (0);
140}
141
142int
143do_server(int port, int type, int *ret,
144 int (*cb) (char *hostname, int s, unsigned char *context),
145 unsigned char *context)
146{
147 int sock;
148 char *name = NULL;
149 int accept_socket = 0;
150 int i;
151
152 if (!init_server(&accept_socket, port, type))
153 return (0);
154
155 if (ret != NULL) {
156 *ret = accept_socket;
157 /* return(1); */
158 }
159 for (;;) {
160 if (type == SOCK_STREAM) {
161 if (do_accept(accept_socket, &sock, &name) == 0) {
162 shutdown(accept_socket, SHUT_RD);
163 close(accept_socket);
164 return (0);
165 }
166 } else
167 sock = accept_socket;
168 i = (*cb) (name, sock, context);
169 free(name);
170 if (type == SOCK_STREAM) {
171 shutdown(sock, SHUT_RDWR);
172 close(sock);
173 }
174 if (i < 0) {
175 shutdown(accept_socket, SHUT_RDWR);
176 close(accept_socket);
177 return (i);
178 }
179 }
180}
181
182static int
183init_server_long(int *sock, int port, char *ip, int type)
184{
185 int ret = 0;
186 struct sockaddr_in server;
187 int s = -1;
188
189 if (!ssl_sock_init())
190 return (0);
191
192 memset((char *) &server, 0, sizeof(server));
193 server.sin_family = AF_INET;
194 server.sin_port = htons((unsigned short) port);
195 if (ip == NULL)
196 server.sin_addr.s_addr = INADDR_ANY;
197 else
198 memcpy(&server.sin_addr.s_addr, ip, 4);
199
200 if (type == SOCK_STREAM)
201 s = socket(AF_INET, SOCK_STREAM, SOCKET_PROTOCOL);
202 else /* type == SOCK_DGRAM */
203 s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
204
205 if (s == -1)
206 goto err;
207#if defined SOL_SOCKET && defined SO_REUSEADDR
208 {
209 int j = 1;
210 setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
211 (void *) &j, sizeof j);
212 }
213#endif
214 if (bind(s, (struct sockaddr *) & server, sizeof(server)) == -1) {
215 perror("bind");
216 goto err;
217 }
218 /* Make it 128 for linux */
219 if (type == SOCK_STREAM && listen(s, 128) == -1)
220 goto err;
221 *sock = s;
222 ret = 1;
223err:
224 if ((ret == 0) && (s != -1)) {
225 shutdown(s, SHUT_RD);
226 close(s);
227 }
228 return (ret);
229}
230
231static int
232init_server(int *sock, int port, int type)
233{
234 return (init_server_long(sock, port, NULL, type));
235}
236
237static int
238do_accept(int acc_sock, int *sock, char **host)
239{
240 int ret;
241 struct hostent *h1, *h2;
242 static struct sockaddr_in from;
243 socklen_t len;
244/* struct linger ling; */
245
246 if (!ssl_sock_init())
247 return (0);
248
249redoit:
250
251 memset((char *) &from, 0, sizeof(from));
252 len = sizeof(from);
253 ret = accept(acc_sock, (struct sockaddr *) & from, &len);
254 if (ret == -1) {
255 if (errno == EINTR) {
256 /* check_timeout(); */
257 goto redoit;
258 }
259 fprintf(stderr, "errno=%d ", errno);
260 perror("accept");
261 return (0);
262 }
263/*
264 ling.l_onoff=1;
265 ling.l_linger=0;
266 i=setsockopt(ret,SOL_SOCKET,SO_LINGER,(char *)&ling,sizeof(ling));
267 if (i < 0) { perror("linger"); return(0); }
268 i=0;
269 i=setsockopt(ret,SOL_SOCKET,SO_KEEPALIVE,(char *)&i,sizeof(i));
270 if (i < 0) { perror("keepalive"); return(0); }
271*/
272
273 if (host == NULL)
274 goto end;
275 h1 = gethostbyaddr((char *) &from.sin_addr.s_addr,
276 sizeof(from.sin_addr.s_addr), AF_INET);
277 if (h1 == NULL) {
278 BIO_printf(bio_err, "bad gethostbyaddr\n");
279 *host = NULL;
280 /* return(0); */
281 } else {
282 if ((*host = strdup(h1->h_name)) == NULL) {
283 perror("strdup");
284 close(ret);
285 return (0);
286 }
287
288 h2 = gethostbyname(*host);
289 if (h2 == NULL) {
290 BIO_printf(bio_err, "gethostbyname failure\n");
291 close(ret);
292 return (0);
293 }
294 if (h2->h_addrtype != AF_INET) {
295 BIO_printf(bio_err, "gethostbyname addr is not AF_INET\n");
296 close(ret);
297 return (0);
298 }
299 }
300
301end:
302 *sock = ret;
303 return (1);
304}
305
306int
307extract_host_port(char *str, char **host_ptr, unsigned char *ip,
308 char **port_ptr)
309{
310 char *h, *p;
311
312 h = str;
313 p = strrchr(str, '/'); /* IPv6 host/port */
314 if (p == NULL) {
315 p = strrchr(str, ':');
316 }
317 if (p == NULL) {
318 BIO_printf(bio_err, "no port defined\n");
319 return (0);
320 }
321 *(p++) = '\0';
322
323 if (host_ptr != NULL)
324 *host_ptr = h;
325
326 if (port_ptr != NULL && p != NULL && *p != '\0')
327 *port_ptr = p;
328
329 return (1);
330}
331
332int
333extract_port(char *str, short *port_ptr)
334{
335 int i;
336 const char *errstr;
337 struct servent *s;
338
339 i = strtonum(str, 1, 65535, &errstr);
340 if (!errstr) {
341 *port_ptr = (unsigned short) i;
342 } else {
343 s = getservbyname(str, "tcp");
344 if (s == NULL) {
345 BIO_printf(bio_err, "getservbyname failure for %s\n", str);
346 return (0);
347 }
348 *port_ptr = ntohs((unsigned short) s->s_port);
349 }
350 return (1);
351}
diff --git a/src/usr.bin/openssl/s_time.c b/src/usr.bin/openssl/s_time.c
new file mode 100644
index 0000000000..f8c104b7d7
--- /dev/null
+++ b/src/usr.bin/openssl/s_time.c
@@ -0,0 +1,587 @@
1/* $OpenBSD: s_time.c,v 1.1 2014/08/26 17:47:25 jsing 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#define NO_SHUTDOWN
60
61/*-----------------------------------------
62 s_time - SSL client connection timer program
63 Written and donated by Larry Streepy <streepy@healthcare.com>
64 -----------------------------------------*/
65
66#include <sys/select.h>
67#include <sys/socket.h>
68
69#include <stdio.h>
70#include <stdlib.h>
71#include <limits.h>
72#include <string.h>
73#include <unistd.h>
74
75#include "apps.h"
76
77#include <openssl/err.h>
78#include <openssl/pem.h>
79#include <openssl/ssl.h>
80#include <openssl/x509.h>
81
82#include "s_apps.h"
83
84#define SSL_CONNECT_NAME "localhost:4433"
85
86 /*#define TEST_CERT "client.pem" *//* no default cert. */
87
88#define BUFSIZZ 1024*10
89
90#define MYBUFSIZ 1024*8
91
92#undef min
93#undef max
94#define min(a,b) (((a) < (b)) ? (a) : (b))
95#define max(a,b) (((a) > (b)) ? (a) : (b))
96
97#define SECONDS 30
98extern int verify_depth;
99extern int verify_error;
100
101static void s_time_usage(void);
102static int parseArgs(int argc, char **argv);
103static SSL *doConnection(SSL * scon);
104static void s_time_init(void);
105
106/***********************************************************************
107 * Static data declarations
108 */
109
110/* static char *port=PORT_STR;*/
111static char *host = SSL_CONNECT_NAME;
112static char *t_cert_file = NULL;
113static char *t_key_file = NULL;
114static char *CApath = NULL;
115static char *CAfile = NULL;
116static char *tm_cipher = NULL;
117static int tm_verify = SSL_VERIFY_NONE;
118static int maxTime = SECONDS;
119static SSL_CTX *tm_ctx = NULL;
120static const SSL_METHOD *s_time_meth = NULL;
121static char *s_www_path = NULL;
122static long bytes_read = 0;
123static int st_bugs = 0;
124static int perform = 0;
125static int t_nbio = 0;
126
127static void
128s_time_init(void)
129{
130 host = SSL_CONNECT_NAME;
131 t_cert_file = NULL;
132 t_key_file = NULL;
133 CApath = NULL;
134 CAfile = NULL;
135 tm_cipher = NULL;
136 tm_verify = SSL_VERIFY_NONE;
137 maxTime = SECONDS;
138 tm_ctx = NULL;
139 s_time_meth = NULL;
140 s_www_path = NULL;
141 bytes_read = 0;
142 st_bugs = 0;
143 perform = 0;
144
145 t_nbio = 0;
146}
147
148/***********************************************************************
149 * usage - display usage message
150 */
151static void
152s_time_usage(void)
153{
154 static const char umsg[] = "\
155-time arg - max number of seconds to collect data, default %d\n\
156-verify arg - turn on peer certificate verification, arg == depth\n\
157-cert arg - certificate file to use, PEM format assumed\n\
158-key arg - RSA file to use, PEM format assumed, key is in cert file\n\
159 file if not specified by this option\n\
160-CApath arg - PEM format directory of CA's\n\
161-CAfile arg - PEM format file of CA's\n\
162-cipher - preferred cipher to use, play with 'openssl ciphers'\n\n";
163
164 printf("usage: s_time <args>\n\n");
165
166 printf("-connect host:port - host:port to connect to (default is %s)\n", SSL_CONNECT_NAME);
167 printf("-nbio - Run with non-blocking IO\n");
168 printf("-ssl2 - Just use SSLv2\n");
169 printf("-ssl3 - Just use SSLv3\n");
170 printf("-bugs - Turn on SSL bug compatibility\n");
171 printf("-new - Just time new connections\n");
172 printf("-reuse - Just time connection reuse\n");
173 printf("-www page - Retrieve 'page' from the site\n");
174 printf(umsg, SECONDS);
175}
176
177/***********************************************************************
178 * parseArgs - Parse command line arguments and initialize data
179 *
180 * Returns 0 if ok, -1 on bad args
181 */
182static int
183parseArgs(int argc, char **argv)
184{
185 int badop = 0;
186 const char *errstr;
187
188 verify_depth = 0;
189 verify_error = X509_V_OK;
190
191 argc--;
192 argv++;
193
194 while (argc >= 1) {
195 if (strcmp(*argv, "-connect") == 0) {
196 if (--argc < 1)
197 goto bad;
198 host = *(++argv);
199 }
200#if 0
201 else if (strcmp(*argv, "-host") == 0) {
202 if (--argc < 1)
203 goto bad;
204 host = *(++argv);
205 } else if (strcmp(*argv, "-port") == 0) {
206 if (--argc < 1)
207 goto bad;
208 port = *(++argv);
209 }
210#endif
211 else if (strcmp(*argv, "-reuse") == 0)
212 perform = 2;
213 else if (strcmp(*argv, "-new") == 0)
214 perform = 1;
215 else if (strcmp(*argv, "-verify") == 0) {
216 const char *errstr;
217
218 tm_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
219 if (--argc < 1)
220 goto bad;
221 verify_depth = strtonum(*(++argv), 0, INT_MAX, &errstr);
222 if (errstr)
223 goto bad;
224 BIO_printf(bio_err, "verify depth is %d\n", verify_depth);
225
226 } else if (strcmp(*argv, "-cert") == 0) {
227
228 if (--argc < 1)
229 goto bad;
230 t_cert_file = *(++argv);
231
232 } else if (strcmp(*argv, "-key") == 0) {
233
234 if (--argc < 1)
235 goto bad;
236 t_key_file = *(++argv);
237
238 } else if (strcmp(*argv, "-CApath") == 0) {
239
240 if (--argc < 1)
241 goto bad;
242 CApath = *(++argv);
243
244 } else if (strcmp(*argv, "-CAfile") == 0) {
245
246 if (--argc < 1)
247 goto bad;
248 CAfile = *(++argv);
249
250 } else if (strcmp(*argv, "-cipher") == 0) {
251
252 if (--argc < 1)
253 goto bad;
254 tm_cipher = *(++argv);
255 }
256 else if (strcmp(*argv, "-nbio") == 0) {
257 t_nbio = 1;
258 }
259 else if (strcmp(*argv, "-www") == 0) {
260 if (--argc < 1)
261 goto bad;
262 s_www_path = *(++argv);
263 if (strlen(s_www_path) > MYBUFSIZ - 100) {
264 BIO_printf(bio_err, "-www option too long\n");
265 badop = 1;
266 }
267 } else if (strcmp(*argv, "-bugs") == 0)
268 st_bugs = 1;
269 else if (strcmp(*argv, "-ssl3") == 0)
270 s_time_meth = SSLv3_client_method();
271 else if (strcmp(*argv, "-time") == 0) {
272
273 if (--argc < 1)
274 goto bad;
275 maxTime = strtonum(*(++argv), 0, INT_MAX, &errstr);
276 if (errstr)
277 goto bad;
278 } else {
279 BIO_printf(bio_err, "unknown option %s\n", *argv);
280 badop = 1;
281 break;
282 }
283
284 argc--;
285 argv++;
286 }
287
288 if (perform == 0)
289 perform = 3;
290
291 if (badop) {
292bad:
293 s_time_usage();
294 return -1;
295 }
296 return 0; /* Valid args */
297}
298
299/***********************************************************************
300 * TIME - time functions
301 */
302#define START 0
303#define STOP 1
304
305static double
306tm_Time_F(int s)
307{
308 return app_tminterval(s, 1);
309}
310
311/***********************************************************************
312 * MAIN - main processing area for client
313 * real name depends on MONOLITH
314 */
315int s_time_main(int, char **);
316
317int
318s_time_main(int argc, char **argv)
319{
320 double totalTime = 0.0;
321 int nConn = 0;
322 SSL *scon = NULL;
323 long finishtime = 0;
324 int ret = 1, i;
325 char buf[1024 * 8];
326 int ver;
327
328 s_time_init();
329
330 s_time_meth = SSLv23_client_method();
331
332 /* parse the command line arguments */
333 if (parseArgs(argc, argv) < 0)
334 goto end;
335
336 if ((tm_ctx = SSL_CTX_new(s_time_meth)) == NULL)
337 return (1);
338
339 SSL_CTX_set_quiet_shutdown(tm_ctx, 1);
340
341 if (st_bugs)
342 SSL_CTX_set_options(tm_ctx, SSL_OP_ALL);
343 SSL_CTX_set_cipher_list(tm_ctx, tm_cipher);
344 if (!set_cert_stuff(tm_ctx, t_cert_file, t_key_file))
345 goto end;
346
347 if ((!SSL_CTX_load_verify_locations(tm_ctx, CAfile, CApath)) ||
348 (!SSL_CTX_set_default_verify_paths(tm_ctx))) {
349 /*
350 * BIO_printf(bio_err,"error setting default verify
351 * locations\n");
352 */
353 ERR_print_errors(bio_err);
354 /* goto end; */
355 }
356 if (tm_cipher == NULL)
357 tm_cipher = getenv("SSL_CIPHER");
358
359 if (tm_cipher == NULL) {
360 fprintf(stderr, "No CIPHER specified\n");
361 }
362 if (!(perform & 1))
363 goto next;
364 printf("Collecting connection statistics for %d seconds\n", maxTime);
365
366 /* Loop and time how long it takes to make connections */
367
368 bytes_read = 0;
369 finishtime = (long) time(NULL) + maxTime;
370 tm_Time_F(START);
371 for (;;) {
372 if (finishtime < (long) time(NULL))
373 break;
374 if ((scon = doConnection(NULL)) == NULL)
375 goto end;
376
377 if (s_www_path != NULL) {
378 int ret = snprintf(buf, sizeof buf,
379 "GET %s HTTP/1.0\r\n\r\n", s_www_path);
380 if (ret == -1 || ret >= sizeof buf) {
381 fprintf(stderr, "URL too long\n");
382 goto end;
383 }
384 SSL_write(scon, buf, strlen(buf));
385 while ((i = SSL_read(scon, buf, sizeof(buf))) > 0)
386 bytes_read += i;
387 }
388#ifdef NO_SHUTDOWN
389 SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
390#else
391 SSL_shutdown(scon);
392#endif
393 shutdown(SSL_get_fd(scon), SHUT_RDWR);
394 close(SSL_get_fd(scon));
395
396 nConn += 1;
397 if (SSL_session_reused(scon))
398 ver = 'r';
399 else {
400 ver = SSL_version(scon);
401 if (ver == TLS1_VERSION)
402 ver = 't';
403 else if (ver == SSL3_VERSION)
404 ver = '3';
405 else if (ver == SSL2_VERSION)
406 ver = '2';
407 else
408 ver = '*';
409 }
410 fputc(ver, stdout);
411 fflush(stdout);
412
413 SSL_free(scon);
414 scon = NULL;
415 }
416 totalTime += tm_Time_F(STOP); /* Add the time for this iteration */
417
418 i = (int) ((long) time(NULL) - finishtime + maxTime);
419 printf("\n\n%d connections in %.2fs; %.2f connections/user sec, bytes read %ld\n", nConn, totalTime, ((double) nConn / totalTime), bytes_read);
420 printf("%d connections in %ld real seconds, %ld bytes read per connection\n", nConn, (long) time(NULL) - finishtime + maxTime, bytes_read / nConn);
421
422 /*
423 * Now loop and time connections using the same session id over and
424 * over
425 */
426
427next:
428 if (!(perform & 2))
429 goto end;
430 printf("\n\nNow timing with session id reuse.\n");
431
432 /* Get an SSL object so we can reuse the session id */
433 if ((scon = doConnection(NULL)) == NULL) {
434 fprintf(stderr, "Unable to get connection\n");
435 goto end;
436 }
437 if (s_www_path != NULL) {
438 int ret = snprintf(buf, sizeof buf,
439 "GET %s HTTP/1.0\r\n\r\n", s_www_path);
440 if (ret == -1 || ret >= sizeof buf) {
441 fprintf(stderr, "URL too long\n");
442 goto end;
443 }
444 SSL_write(scon, buf, strlen(buf));
445 while (SSL_read(scon, buf, sizeof(buf)) > 0);
446 }
447#ifdef NO_SHUTDOWN
448 SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
449#else
450 SSL_shutdown(scon);
451#endif
452 shutdown(SSL_get_fd(scon), SHUT_RDWR);
453 close(SSL_get_fd(scon));
454
455 nConn = 0;
456 totalTime = 0.0;
457
458 finishtime = (long) time(NULL) + maxTime;
459
460 printf("starting\n");
461 bytes_read = 0;
462 tm_Time_F(START);
463
464 for (;;) {
465 if (finishtime < (long) time(NULL))
466 break;
467 if ((doConnection(scon)) == NULL)
468 goto end;
469
470 if (s_www_path) {
471 int ret = snprintf(buf, sizeof buf,
472 "GET %s HTTP/1.0\r\n\r\n", s_www_path);
473 if (ret == -1 || ret >= sizeof buf) {
474 fprintf(stderr, "URL too long\n");
475 goto end;
476 }
477 SSL_write(scon, buf, strlen(buf));
478 while ((i = SSL_read(scon, buf, sizeof(buf))) > 0)
479 bytes_read += i;
480 }
481#ifdef NO_SHUTDOWN
482 SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
483#else
484 SSL_shutdown(scon);
485#endif
486 shutdown(SSL_get_fd(scon), SHUT_RDWR);
487 close(SSL_get_fd(scon));
488
489 nConn += 1;
490 if (SSL_session_reused(scon))
491 ver = 'r';
492 else {
493 ver = SSL_version(scon);
494 if (ver == TLS1_VERSION)
495 ver = 't';
496 else if (ver == SSL3_VERSION)
497 ver = '3';
498 else if (ver == SSL2_VERSION)
499 ver = '2';
500 else
501 ver = '*';
502 }
503 fputc(ver, stdout);
504 fflush(stdout);
505 }
506 totalTime += tm_Time_F(STOP); /* Add the time for this iteration */
507
508
509 printf("\n\n%d connections in %.2fs; %.2f connections/user sec, bytes read %ld\n", nConn, totalTime, ((double) nConn / totalTime), bytes_read);
510 printf("%d connections in %ld real seconds, %ld bytes read per connection\n", nConn, (long) time(NULL) - finishtime + maxTime, bytes_read / nConn);
511
512 ret = 0;
513end:
514 if (scon != NULL)
515 SSL_free(scon);
516
517 if (tm_ctx != NULL) {
518 SSL_CTX_free(tm_ctx);
519 tm_ctx = NULL;
520 }
521
522 return (ret);
523}
524
525/***********************************************************************
526 * doConnection - make a connection
527 * Args:
528 * scon = earlier ssl connection for session id, or NULL
529 * Returns:
530 * SSL * = the connection pointer.
531 */
532static SSL *
533doConnection(SSL * scon)
534{
535 BIO *conn;
536 SSL *serverCon;
537 int width, i;
538 fd_set readfds;
539
540 if ((conn = BIO_new(BIO_s_connect())) == NULL)
541 return (NULL);
542
543/* BIO_set_conn_port(conn,port);*/
544 BIO_set_conn_hostname(conn, host);
545
546 if (scon == NULL)
547 serverCon = SSL_new(tm_ctx);
548 else {
549 serverCon = scon;
550 SSL_set_connect_state(serverCon);
551 }
552
553 SSL_set_bio(serverCon, conn, conn);
554
555#if 0
556 if (scon != NULL)
557 SSL_set_session(serverCon, SSL_get_session(scon));
558#endif
559
560 /* ok, lets connect */
561 for (;;) {
562 i = SSL_connect(serverCon);
563 if (BIO_sock_should_retry(i)) {
564 BIO_printf(bio_err, "DELAY\n");
565
566 i = SSL_get_fd(serverCon);
567 width = i + 1;
568 FD_ZERO(&readfds);
569 FD_SET(i, &readfds);
570 select(width, &readfds, NULL, NULL, NULL);
571 continue;
572 }
573 break;
574 }
575 if (i <= 0) {
576 BIO_printf(bio_err, "ERROR\n");
577 if (verify_error != X509_V_OK)
578 BIO_printf(bio_err, "verify error:%s\n",
579 X509_verify_cert_error_string(verify_error));
580 else
581 ERR_print_errors(bio_err);
582 if (scon == NULL)
583 SSL_free(serverCon);
584 return NULL;
585 }
586 return serverCon;
587}
diff --git a/src/usr.bin/openssl/sess_id.c b/src/usr.bin/openssl/sess_id.c
new file mode 100644
index 0000000000..23df0301b3
--- /dev/null
+++ b/src/usr.bin/openssl/sess_id.c
@@ -0,0 +1,282 @@
1/* $OpenBSD: sess_id.c,v 1.1 2014/08/26 17:47:25 jsing 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#include <stdlib.h>
61#include <string.h>
62
63#include "apps.h"
64
65#include <openssl/bio.h>
66#include <openssl/err.h>
67#include <openssl/pem.h>
68#include <openssl/ssl.h>
69#include <openssl/x509.h>
70
71static const char *sess_id_usage[] = {
72 "usage: sess_id args\n",
73 "\n",
74 " -inform arg - input format - default PEM (DER or PEM)\n",
75 " -outform arg - output format - default PEM\n",
76 " -in arg - input file - default stdin\n",
77 " -out arg - output file - default stdout\n",
78 " -text - print ssl session id details\n",
79 " -cert - output certificate \n",
80 " -noout - no output of encoded session info\n",
81 " -context arg - set the session ID context\n",
82 NULL
83};
84
85static SSL_SESSION *load_sess_id(char *file, int format);
86
87int sess_id_main(int, char **);
88
89int
90sess_id_main(int argc, char **argv)
91{
92 SSL_SESSION *x = NULL;
93 X509 *peer = NULL;
94 int ret = 1, i, num, badops = 0;
95 BIO *out = NULL;
96 int informat, outformat;
97 char *infile = NULL, *outfile = NULL, *context = NULL;
98 int cert = 0, noout = 0, text = 0;
99 const char **pp;
100
101 informat = FORMAT_PEM;
102 outformat = FORMAT_PEM;
103
104 argc--;
105 argv++;
106 num = 0;
107 while (argc >= 1) {
108 if (strcmp(*argv, "-inform") == 0) {
109 if (--argc < 1)
110 goto bad;
111 informat = str2fmt(*(++argv));
112 } else if (strcmp(*argv, "-outform") == 0) {
113 if (--argc < 1)
114 goto bad;
115 outformat = str2fmt(*(++argv));
116 } else if (strcmp(*argv, "-in") == 0) {
117 if (--argc < 1)
118 goto bad;
119 infile = *(++argv);
120 } else if (strcmp(*argv, "-out") == 0) {
121 if (--argc < 1)
122 goto bad;
123 outfile = *(++argv);
124 } else if (strcmp(*argv, "-text") == 0)
125 text = ++num;
126 else if (strcmp(*argv, "-cert") == 0)
127 cert = ++num;
128 else if (strcmp(*argv, "-noout") == 0)
129 noout = ++num;
130 else if (strcmp(*argv, "-context") == 0) {
131 if (--argc < 1)
132 goto bad;
133 context = *++argv;
134 } else {
135 BIO_printf(bio_err, "unknown option %s\n", *argv);
136 badops = 1;
137 break;
138 }
139 argc--;
140 argv++;
141 }
142
143 if (badops) {
144bad:
145 for (pp = sess_id_usage; (*pp != NULL); pp++)
146 BIO_printf(bio_err, "%s", *pp);
147 goto end;
148 }
149 ERR_load_crypto_strings();
150 x = load_sess_id(infile, informat);
151 if (x == NULL) {
152 goto end;
153 }
154 peer = SSL_SESSION_get0_peer(x);
155
156 if (context) {
157 size_t ctx_len = strlen(context);
158 if (ctx_len > SSL_MAX_SID_CTX_LENGTH) {
159 BIO_printf(bio_err, "Context too long\n");
160 goto end;
161 }
162 SSL_SESSION_set1_id_context(x, (unsigned char *) context, ctx_len);
163 }
164#ifdef undef
165 /* just testing for memory leaks :-) */
166 {
167 SSL_SESSION *s;
168 char buf[1024 * 10], *p;
169 int i;
170
171 s = SSL_SESSION_new();
172
173 p = &buf;
174 i = i2d_SSL_SESSION(x, &p);
175 p = &buf;
176 d2i_SSL_SESSION(&s, &p, (long) i);
177 p = &buf;
178 d2i_SSL_SESSION(&s, &p, (long) i);
179 p = &buf;
180 d2i_SSL_SESSION(&s, &p, (long) i);
181 SSL_SESSION_free(s);
182 }
183#endif
184
185 if (!noout || text) {
186 out = BIO_new(BIO_s_file());
187 if (out == NULL) {
188 ERR_print_errors(bio_err);
189 goto end;
190 }
191 if (outfile == NULL) {
192 BIO_set_fp(out, stdout, BIO_NOCLOSE);
193 } else {
194 if (BIO_write_filename(out, outfile) <= 0) {
195 perror(outfile);
196 goto end;
197 }
198 }
199 }
200 if (text) {
201 SSL_SESSION_print(out, x);
202
203 if (cert) {
204 if (peer == NULL)
205 BIO_puts(out, "No certificate present\n");
206 else
207 X509_print(out, peer);
208 }
209 }
210 if (!noout && !cert) {
211 if (outformat == FORMAT_ASN1)
212 i = i2d_SSL_SESSION_bio(out, x);
213 else if (outformat == FORMAT_PEM)
214 i = PEM_write_bio_SSL_SESSION(out, x);
215 else {
216 BIO_printf(bio_err, "bad output format specified for outfile\n");
217 goto end;
218 }
219 if (!i) {
220 BIO_printf(bio_err, "unable to write SSL_SESSION\n");
221 goto end;
222 }
223 } else if (!noout && (peer != NULL)) { /* just print the certificate */
224 if (outformat == FORMAT_ASN1)
225 i = (int) i2d_X509_bio(out, peer);
226 else if (outformat == FORMAT_PEM)
227 i = PEM_write_bio_X509(out, peer);
228 else {
229 BIO_printf(bio_err, "bad output format specified for outfile\n");
230 goto end;
231 }
232 if (!i) {
233 BIO_printf(bio_err, "unable to write X509\n");
234 goto end;
235 }
236 }
237 ret = 0;
238end:
239 if (out != NULL)
240 BIO_free_all(out);
241 if (x != NULL)
242 SSL_SESSION_free(x);
243
244 return (ret);
245}
246
247static SSL_SESSION *
248load_sess_id(char *infile, int format)
249{
250 SSL_SESSION *x = NULL;
251 BIO *in = NULL;
252
253 in = BIO_new(BIO_s_file());
254 if (in == NULL) {
255 ERR_print_errors(bio_err);
256 goto end;
257 }
258 if (infile == NULL)
259 BIO_set_fp(in, stdin, BIO_NOCLOSE);
260 else {
261 if (BIO_read_filename(in, infile) <= 0) {
262 perror(infile);
263 goto end;
264 }
265 }
266 if (format == FORMAT_ASN1)
267 x = d2i_SSL_SESSION_bio(in, NULL);
268 else if (format == FORMAT_PEM)
269 x = PEM_read_bio_SSL_SESSION(in, NULL, NULL, NULL);
270 else {
271 BIO_printf(bio_err, "bad input format specified for input crl\n");
272 goto end;
273 }
274 if (x == NULL) {
275 BIO_printf(bio_err, "unable to load SSL_SESSION\n");
276 ERR_print_errors(bio_err);
277 goto end;
278 }
279end:
280 BIO_free(in);
281 return (x);
282}
diff --git a/src/usr.bin/openssl/smime.c b/src/usr.bin/openssl/smime.c
new file mode 100644
index 0000000000..155bb8b03d
--- /dev/null
+++ b/src/usr.bin/openssl/smime.c
@@ -0,0 +1,697 @@
1/* $OpenBSD: smime.c,v 1.1 2014/08/26 17:47:25 jsing Exp $ */
2/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3 * project.
4 */
5/* ====================================================================
6 * Copyright (c) 1999-2004 The OpenSSL Project. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
19 *
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24 *
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * licensing@OpenSSL.org.
29 *
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
33 *
34 * 6. Redistributions of any form whatsoever must retain the following
35 * acknowledgment:
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
52 *
53 * This product includes cryptographic software written by Eric Young
54 * (eay@cryptsoft.com). This product includes software written by Tim
55 * Hudson (tjh@cryptsoft.com).
56 *
57 */
58
59/* S/MIME utility function */
60
61#include <stdio.h>
62#include <string.h>
63
64#include "apps.h"
65
66#include <openssl/crypto.h>
67#include <openssl/err.h>
68#include <openssl/pem.h>
69#include <openssl/x509_vfy.h>
70#include <openssl/x509v3.h>
71
72static int save_certs(char *signerfile, STACK_OF(X509) * signers);
73static int smime_cb(int ok, X509_STORE_CTX * ctx);
74
75#define SMIME_OP 0x10
76#define SMIME_IP 0x20
77#define SMIME_SIGNERS 0x40
78#define SMIME_ENCRYPT (1 | SMIME_OP)
79#define SMIME_DECRYPT (2 | SMIME_IP)
80#define SMIME_SIGN (3 | SMIME_OP | SMIME_SIGNERS)
81#define SMIME_VERIFY (4 | SMIME_IP)
82#define SMIME_PK7OUT (5 | SMIME_IP | SMIME_OP)
83#define SMIME_RESIGN (6 | SMIME_IP | SMIME_OP | SMIME_SIGNERS)
84
85int smime_main(int, char **);
86
87int
88smime_main(int argc, char **argv)
89{
90 ENGINE *e = NULL;
91 int operation = 0;
92 int ret = 0;
93 char **args;
94 const char *inmode = "r", *outmode = "w";
95 char *infile = NULL, *outfile = NULL;
96 char *signerfile = NULL, *recipfile = NULL;
97 STACK_OF(OPENSSL_STRING) * sksigners = NULL, *skkeys = NULL;
98 char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
99 const EVP_CIPHER *cipher = NULL;
100 PKCS7 *p7 = NULL;
101 X509_STORE *store = NULL;
102 X509 *cert = NULL, *recip = NULL, *signer = NULL;
103 EVP_PKEY *key = NULL;
104 STACK_OF(X509) * encerts = NULL, *other = NULL;
105 BIO *in = NULL, *out = NULL, *indata = NULL;
106 int badarg = 0;
107 int flags = PKCS7_DETACHED;
108 char *to = NULL, *from = NULL, *subject = NULL;
109 char *CAfile = NULL, *CApath = NULL;
110 char *passargin = NULL, *passin = NULL;
111 int indef = 0;
112 const EVP_MD *sign_md = NULL;
113 int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
114 int keyform = FORMAT_PEM;
115#ifndef OPENSSL_NO_ENGINE
116 char *engine = NULL;
117#endif
118
119 X509_VERIFY_PARAM *vpm = NULL;
120
121 args = argv + 1;
122 ret = 1;
123
124 while (!badarg && *args && *args[0] == '-') {
125 if (!strcmp(*args, "-encrypt"))
126 operation = SMIME_ENCRYPT;
127 else if (!strcmp(*args, "-decrypt"))
128 operation = SMIME_DECRYPT;
129 else if (!strcmp(*args, "-sign"))
130 operation = SMIME_SIGN;
131 else if (!strcmp(*args, "-resign"))
132 operation = SMIME_RESIGN;
133 else if (!strcmp(*args, "-verify"))
134 operation = SMIME_VERIFY;
135 else if (!strcmp(*args, "-pk7out"))
136 operation = SMIME_PK7OUT;
137#ifndef OPENSSL_NO_DES
138 else if (!strcmp(*args, "-des3"))
139 cipher = EVP_des_ede3_cbc();
140 else if (!strcmp(*args, "-des"))
141 cipher = EVP_des_cbc();
142#endif
143#ifndef OPENSSL_NO_RC2
144 else if (!strcmp(*args, "-rc2-40"))
145 cipher = EVP_rc2_40_cbc();
146 else if (!strcmp(*args, "-rc2-128"))
147 cipher = EVP_rc2_cbc();
148 else if (!strcmp(*args, "-rc2-64"))
149 cipher = EVP_rc2_64_cbc();
150#endif
151#ifndef OPENSSL_NO_AES
152 else if (!strcmp(*args, "-aes128"))
153 cipher = EVP_aes_128_cbc();
154 else if (!strcmp(*args, "-aes192"))
155 cipher = EVP_aes_192_cbc();
156 else if (!strcmp(*args, "-aes256"))
157 cipher = EVP_aes_256_cbc();
158#endif
159#ifndef OPENSSL_NO_CAMELLIA
160 else if (!strcmp(*args, "-camellia128"))
161 cipher = EVP_camellia_128_cbc();
162 else if (!strcmp(*args, "-camellia192"))
163 cipher = EVP_camellia_192_cbc();
164 else if (!strcmp(*args, "-camellia256"))
165 cipher = EVP_camellia_256_cbc();
166#endif
167 else if (!strcmp(*args, "-text"))
168 flags |= PKCS7_TEXT;
169 else if (!strcmp(*args, "-nointern"))
170 flags |= PKCS7_NOINTERN;
171 else if (!strcmp(*args, "-noverify"))
172 flags |= PKCS7_NOVERIFY;
173 else if (!strcmp(*args, "-nochain"))
174 flags |= PKCS7_NOCHAIN;
175 else if (!strcmp(*args, "-nocerts"))
176 flags |= PKCS7_NOCERTS;
177 else if (!strcmp(*args, "-noattr"))
178 flags |= PKCS7_NOATTR;
179 else if (!strcmp(*args, "-nodetach"))
180 flags &= ~PKCS7_DETACHED;
181 else if (!strcmp(*args, "-nosmimecap"))
182 flags |= PKCS7_NOSMIMECAP;
183 else if (!strcmp(*args, "-binary"))
184 flags |= PKCS7_BINARY;
185 else if (!strcmp(*args, "-nosigs"))
186 flags |= PKCS7_NOSIGS;
187 else if (!strcmp(*args, "-stream"))
188 indef = 1;
189 else if (!strcmp(*args, "-indef"))
190 indef = 1;
191 else if (!strcmp(*args, "-noindef"))
192 indef = 0;
193 else if (!strcmp(*args, "-nooldmime"))
194 flags |= PKCS7_NOOLDMIMETYPE;
195 else if (!strcmp(*args, "-crlfeol"))
196 flags |= PKCS7_CRLFEOL;
197#ifndef OPENSSL_NO_ENGINE
198 else if (!strcmp(*args, "-engine")) {
199 if (!args[1])
200 goto argerr;
201 engine = *++args;
202 }
203#endif
204 else if (!strcmp(*args, "-passin")) {
205 if (!args[1])
206 goto argerr;
207 passargin = *++args;
208 } else if (!strcmp(*args, "-to")) {
209 if (!args[1])
210 goto argerr;
211 to = *++args;
212 } else if (!strcmp(*args, "-from")) {
213 if (!args[1])
214 goto argerr;
215 from = *++args;
216 } else if (!strcmp(*args, "-subject")) {
217 if (!args[1])
218 goto argerr;
219 subject = *++args;
220 } else if (!strcmp(*args, "-signer")) {
221 if (!args[1])
222 goto argerr;
223 /* If previous -signer argument add signer to list */
224
225 if (signerfile) {
226 if (!sksigners)
227 sksigners = sk_OPENSSL_STRING_new_null();
228 sk_OPENSSL_STRING_push(sksigners, signerfile);
229 if (!keyfile)
230 keyfile = signerfile;
231 if (!skkeys)
232 skkeys = sk_OPENSSL_STRING_new_null();
233 sk_OPENSSL_STRING_push(skkeys, keyfile);
234 keyfile = NULL;
235 }
236 signerfile = *++args;
237 } else if (!strcmp(*args, "-recip")) {
238 if (!args[1])
239 goto argerr;
240 recipfile = *++args;
241 } else if (!strcmp(*args, "-md")) {
242 if (!args[1])
243 goto argerr;
244 sign_md = EVP_get_digestbyname(*++args);
245 if (sign_md == NULL) {
246 BIO_printf(bio_err, "Unknown digest %s\n",
247 *args);
248 goto argerr;
249 }
250 } else if (!strcmp(*args, "-inkey")) {
251 if (!args[1])
252 goto argerr;
253 /* If previous -inkey arument add signer to list */
254 if (keyfile) {
255 if (!signerfile) {
256 BIO_puts(bio_err, "Illegal -inkey without -signer\n");
257 goto argerr;
258 }
259 if (!sksigners)
260 sksigners = sk_OPENSSL_STRING_new_null();
261 sk_OPENSSL_STRING_push(sksigners, signerfile);
262 signerfile = NULL;
263 if (!skkeys)
264 skkeys = sk_OPENSSL_STRING_new_null();
265 sk_OPENSSL_STRING_push(skkeys, keyfile);
266 }
267 keyfile = *++args;
268 } else if (!strcmp(*args, "-keyform")) {
269 if (!args[1])
270 goto argerr;
271 keyform = str2fmt(*++args);
272 } else if (!strcmp(*args, "-certfile")) {
273 if (!args[1])
274 goto argerr;
275 certfile = *++args;
276 } else if (!strcmp(*args, "-CAfile")) {
277 if (!args[1])
278 goto argerr;
279 CAfile = *++args;
280 } else if (!strcmp(*args, "-CApath")) {
281 if (!args[1])
282 goto argerr;
283 CApath = *++args;
284 } else if (!strcmp(*args, "-in")) {
285 if (!args[1])
286 goto argerr;
287 infile = *++args;
288 } else if (!strcmp(*args, "-inform")) {
289 if (!args[1])
290 goto argerr;
291 informat = str2fmt(*++args);
292 } else if (!strcmp(*args, "-outform")) {
293 if (!args[1])
294 goto argerr;
295 outformat = str2fmt(*++args);
296 } else if (!strcmp(*args, "-out")) {
297 if (!args[1])
298 goto argerr;
299 outfile = *++args;
300 } else if (!strcmp(*args, "-content")) {
301 if (!args[1])
302 goto argerr;
303 contfile = *++args;
304 } else if (args_verify(&args, NULL, &badarg, bio_err, &vpm))
305 continue;
306 else if ((cipher = EVP_get_cipherbyname(*args + 1)) == NULL)
307 badarg = 1;
308 args++;
309 }
310
311 if (!(operation & SMIME_SIGNERS) && (skkeys || sksigners)) {
312 BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
313 goto argerr;
314 }
315 if (operation & SMIME_SIGNERS) {
316 /* Check to see if any final signer needs to be appended */
317 if (keyfile && !signerfile) {
318 BIO_puts(bio_err, "Illegal -inkey without -signer\n");
319 goto argerr;
320 }
321 if (signerfile) {
322 if (!sksigners)
323 sksigners = sk_OPENSSL_STRING_new_null();
324 sk_OPENSSL_STRING_push(sksigners, signerfile);
325 if (!skkeys)
326 skkeys = sk_OPENSSL_STRING_new_null();
327 if (!keyfile)
328 keyfile = signerfile;
329 sk_OPENSSL_STRING_push(skkeys, keyfile);
330 }
331 if (!sksigners) {
332 BIO_printf(bio_err, "No signer certificate specified\n");
333 badarg = 1;
334 }
335 signerfile = NULL;
336 keyfile = NULL;
337 } else if (operation == SMIME_DECRYPT) {
338 if (!recipfile && !keyfile) {
339 BIO_printf(bio_err, "No recipient certificate or key specified\n");
340 badarg = 1;
341 }
342 } else if (operation == SMIME_ENCRYPT) {
343 if (!*args) {
344 BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
345 badarg = 1;
346 }
347 } else if (!operation)
348 badarg = 1;
349
350 if (badarg) {
351argerr:
352 BIO_printf(bio_err, "Usage smime [options] cert.pem ...\n");
353 BIO_printf(bio_err, "where options are\n");
354 BIO_printf(bio_err, "-encrypt encrypt message\n");
355 BIO_printf(bio_err, "-decrypt decrypt encrypted message\n");
356 BIO_printf(bio_err, "-sign sign message\n");
357 BIO_printf(bio_err, "-verify verify signed message\n");
358 BIO_printf(bio_err, "-pk7out output PKCS#7 structure\n");
359#ifndef OPENSSL_NO_DES
360 BIO_printf(bio_err, "-des3 encrypt with triple DES\n");
361 BIO_printf(bio_err, "-des encrypt with DES\n");
362#endif
363#ifndef OPENSSL_NO_RC2
364 BIO_printf(bio_err, "-rc2-40 encrypt with RC2-40 (default)\n");
365 BIO_printf(bio_err, "-rc2-64 encrypt with RC2-64\n");
366 BIO_printf(bio_err, "-rc2-128 encrypt with RC2-128\n");
367#endif
368#ifndef OPENSSL_NO_AES
369 BIO_printf(bio_err, "-aes128, -aes192, -aes256\n");
370 BIO_printf(bio_err, " encrypt PEM output with cbc aes\n");
371#endif
372#ifndef OPENSSL_NO_CAMELLIA
373 BIO_printf(bio_err, "-camellia128, -camellia192, -camellia256\n");
374 BIO_printf(bio_err, " encrypt PEM output with cbc camellia\n");
375#endif
376 BIO_printf(bio_err, "-nointern don't search certificates in message for signer\n");
377 BIO_printf(bio_err, "-nosigs don't verify message signature\n");
378 BIO_printf(bio_err, "-noverify don't verify signers certificate\n");
379 BIO_printf(bio_err, "-nocerts don't include signers certificate when signing\n");
380 BIO_printf(bio_err, "-nodetach use opaque signing\n");
381 BIO_printf(bio_err, "-noattr don't include any signed attributes\n");
382 BIO_printf(bio_err, "-binary don't translate message to text\n");
383 BIO_printf(bio_err, "-certfile file other certificates file\n");
384 BIO_printf(bio_err, "-signer file signer certificate file\n");
385 BIO_printf(bio_err, "-recip file recipient certificate file for decryption\n");
386 BIO_printf(bio_err, "-in file input file\n");
387 BIO_printf(bio_err, "-inform arg input format SMIME (default), PEM or DER\n");
388 BIO_printf(bio_err, "-inkey file input private key (if not signer or recipient)\n");
389 BIO_printf(bio_err, "-keyform arg input private key format (PEM or ENGINE)\n");
390 BIO_printf(bio_err, "-out file output file\n");
391 BIO_printf(bio_err, "-outform arg output format SMIME (default), PEM or DER\n");
392 BIO_printf(bio_err, "-content file supply or override content for detached signature\n");
393 BIO_printf(bio_err, "-to addr to address\n");
394 BIO_printf(bio_err, "-from ad from address\n");
395 BIO_printf(bio_err, "-subject s subject\n");
396 BIO_printf(bio_err, "-text include or delete text MIME headers\n");
397 BIO_printf(bio_err, "-CApath dir trusted certificates directory\n");
398 BIO_printf(bio_err, "-CAfile file trusted certificates file\n");
399 BIO_printf(bio_err, "-crl_check check revocation status of signer's certificate using CRLs\n");
400 BIO_printf(bio_err, "-crl_check_all check revocation status of signer's certificate chain using CRLs\n");
401#ifndef OPENSSL_NO_ENGINE
402 BIO_printf(bio_err, "-engine e use engine e, possibly a hardware device.\n");
403#endif
404 BIO_printf(bio_err, "-passin arg input file pass phrase source\n");
405 BIO_printf(bio_err, "cert.pem recipient certificate(s) for encryption\n");
406 goto end;
407 }
408#ifndef OPENSSL_NO_ENGINE
409 e = setup_engine(bio_err, engine, 0);
410#endif
411
412 if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) {
413 BIO_printf(bio_err, "Error getting password\n");
414 goto end;
415 }
416 ret = 2;
417
418 if (!(operation & SMIME_SIGNERS))
419 flags &= ~PKCS7_DETACHED;
420
421 if (operation & SMIME_OP) {
422 if (outformat == FORMAT_ASN1)
423 outmode = "wb";
424 } else {
425 if (flags & PKCS7_BINARY)
426 outmode = "wb";
427 }
428
429 if (operation & SMIME_IP) {
430 if (informat == FORMAT_ASN1)
431 inmode = "rb";
432 } else {
433 if (flags & PKCS7_BINARY)
434 inmode = "rb";
435 }
436
437 if (operation == SMIME_ENCRYPT) {
438 if (!cipher) {
439#ifndef OPENSSL_NO_RC2
440 cipher = EVP_rc2_40_cbc();
441#else
442 BIO_printf(bio_err, "No cipher selected\n");
443 goto end;
444#endif
445 }
446 encerts = sk_X509_new_null();
447 while (*args) {
448 if (!(cert = load_cert(bio_err, *args, FORMAT_PEM,
449 NULL, e, "recipient certificate file"))) {
450#if 0 /* An appropriate message is already printed */
451 BIO_printf(bio_err, "Can't read recipient certificate file %s\n", *args);
452#endif
453 goto end;
454 }
455 sk_X509_push(encerts, cert);
456 cert = NULL;
457 args++;
458 }
459 }
460 if (certfile) {
461 if (!(other = load_certs(bio_err, certfile, FORMAT_PEM, NULL,
462 e, "certificate file"))) {
463 ERR_print_errors(bio_err);
464 goto end;
465 }
466 }
467 if (recipfile && (operation == SMIME_DECRYPT)) {
468 if (!(recip = load_cert(bio_err, recipfile, FORMAT_PEM, NULL,
469 e, "recipient certificate file"))) {
470 ERR_print_errors(bio_err);
471 goto end;
472 }
473 }
474 if (operation == SMIME_DECRYPT) {
475 if (!keyfile)
476 keyfile = recipfile;
477 } else if (operation == SMIME_SIGN) {
478 if (!keyfile)
479 keyfile = signerfile;
480 } else
481 keyfile = NULL;
482
483 if (keyfile) {
484 key = load_key(bio_err, keyfile, keyform, 0, passin, e,
485 "signing key file");
486 if (!key)
487 goto end;
488 }
489 if (infile) {
490 if (!(in = BIO_new_file(infile, inmode))) {
491 BIO_printf(bio_err,
492 "Can't open input file %s\n", infile);
493 goto end;
494 }
495 } else
496 in = BIO_new_fp(stdin, BIO_NOCLOSE);
497
498 if (operation & SMIME_IP) {
499 if (informat == FORMAT_SMIME)
500 p7 = SMIME_read_PKCS7(in, &indata);
501 else if (informat == FORMAT_PEM)
502 p7 = PEM_read_bio_PKCS7(in, NULL, NULL, NULL);
503 else if (informat == FORMAT_ASN1)
504 p7 = d2i_PKCS7_bio(in, NULL);
505 else {
506 BIO_printf(bio_err, "Bad input format for PKCS#7 file\n");
507 goto end;
508 }
509
510 if (!p7) {
511 BIO_printf(bio_err, "Error reading S/MIME message\n");
512 goto end;
513 }
514 if (contfile) {
515 BIO_free(indata);
516 if (!(indata = BIO_new_file(contfile, "rb"))) {
517 BIO_printf(bio_err, "Can't read content file %s\n", contfile);
518 goto end;
519 }
520 }
521 }
522 if (outfile) {
523 if (!(out = BIO_new_file(outfile, outmode))) {
524 BIO_printf(bio_err,
525 "Can't open output file %s\n", outfile);
526 goto end;
527 }
528 } else {
529 out = BIO_new_fp(stdout, BIO_NOCLOSE);
530 }
531
532 if (operation == SMIME_VERIFY) {
533 if (!(store = setup_verify(bio_err, CAfile, CApath)))
534 goto end;
535 X509_STORE_set_verify_cb(store, smime_cb);
536 if (vpm)
537 X509_STORE_set1_param(store, vpm);
538 }
539 ret = 3;
540
541 if (operation == SMIME_ENCRYPT) {
542 if (indef)
543 flags |= PKCS7_STREAM;
544 p7 = PKCS7_encrypt(encerts, in, cipher, flags);
545 } else if (operation & SMIME_SIGNERS) {
546 int i;
547 /*
548 * If detached data content we only enable streaming if
549 * S/MIME output format.
550 */
551 if (operation == SMIME_SIGN) {
552 if (flags & PKCS7_DETACHED) {
553 if (outformat == FORMAT_SMIME)
554 flags |= PKCS7_STREAM;
555 } else if (indef)
556 flags |= PKCS7_STREAM;
557 flags |= PKCS7_PARTIAL;
558 p7 = PKCS7_sign(NULL, NULL, other, in, flags);
559 if (!p7)
560 goto end;
561 } else
562 flags |= PKCS7_REUSE_DIGEST;
563 for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
564 signerfile = sk_OPENSSL_STRING_value(sksigners, i);
565 keyfile = sk_OPENSSL_STRING_value(skkeys, i);
566 signer = load_cert(bio_err, signerfile, FORMAT_PEM, NULL,
567 e, "signer certificate");
568 if (!signer)
569 goto end;
570 key = load_key(bio_err, keyfile, keyform, 0, passin, e,
571 "signing key file");
572 if (!key)
573 goto end;
574 if (!PKCS7_sign_add_signer(p7, signer, key,
575 sign_md, flags))
576 goto end;
577 X509_free(signer);
578 signer = NULL;
579 EVP_PKEY_free(key);
580 key = NULL;
581 }
582 /* If not streaming or resigning finalize structure */
583 if ((operation == SMIME_SIGN) && !(flags & PKCS7_STREAM)) {
584 if (!PKCS7_final(p7, in, flags))
585 goto end;
586 }
587 }
588 if (!p7) {
589 BIO_printf(bio_err, "Error creating PKCS#7 structure\n");
590 goto end;
591 }
592 ret = 4;
593 if (operation == SMIME_DECRYPT) {
594 if (!PKCS7_decrypt(p7, key, recip, out, flags)) {
595 BIO_printf(bio_err, "Error decrypting PKCS#7 structure\n");
596 goto end;
597 }
598 } else if (operation == SMIME_VERIFY) {
599 STACK_OF(X509) * signers;
600 if (PKCS7_verify(p7, other, store, indata, out, flags))
601 BIO_printf(bio_err, "Verification successful\n");
602 else {
603 BIO_printf(bio_err, "Verification failure\n");
604 goto end;
605 }
606 signers = PKCS7_get0_signers(p7, other, flags);
607 if (!save_certs(signerfile, signers)) {
608 BIO_printf(bio_err, "Error writing signers to %s\n",
609 signerfile);
610 ret = 5;
611 goto end;
612 }
613 sk_X509_free(signers);
614 } else if (operation == SMIME_PK7OUT)
615 PEM_write_bio_PKCS7(out, p7);
616 else {
617 if (to)
618 BIO_printf(out, "To: %s\n", to);
619 if (from)
620 BIO_printf(out, "From: %s\n", from);
621 if (subject)
622 BIO_printf(out, "Subject: %s\n", subject);
623 if (outformat == FORMAT_SMIME) {
624 if (operation == SMIME_RESIGN)
625 SMIME_write_PKCS7(out, p7, indata, flags);
626 else
627 SMIME_write_PKCS7(out, p7, in, flags);
628 } else if (outformat == FORMAT_PEM)
629 PEM_write_bio_PKCS7_stream(out, p7, in, flags);
630 else if (outformat == FORMAT_ASN1)
631 i2d_PKCS7_bio_stream(out, p7, in, flags);
632 else {
633 BIO_printf(bio_err, "Bad output format for PKCS#7 file\n");
634 goto end;
635 }
636 }
637 ret = 0;
638end:
639 if (ret)
640 ERR_print_errors(bio_err);
641 sk_X509_pop_free(encerts, X509_free);
642 sk_X509_pop_free(other, X509_free);
643 if (vpm)
644 X509_VERIFY_PARAM_free(vpm);
645 if (sksigners)
646 sk_OPENSSL_STRING_free(sksigners);
647 if (skkeys)
648 sk_OPENSSL_STRING_free(skkeys);
649 X509_STORE_free(store);
650 X509_free(cert);
651 X509_free(recip);
652 X509_free(signer);
653 EVP_PKEY_free(key);
654 PKCS7_free(p7);
655 BIO_free(in);
656 BIO_free(indata);
657 BIO_free_all(out);
658 free(passin);
659
660 return (ret);
661}
662
663static int
664save_certs(char *signerfile, STACK_OF(X509) * signers)
665{
666 int i;
667 BIO *tmp;
668 if (!signerfile)
669 return 1;
670 tmp = BIO_new_file(signerfile, "w");
671 if (!tmp)
672 return 0;
673 for (i = 0; i < sk_X509_num(signers); i++)
674 PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
675 BIO_free(tmp);
676 return 1;
677}
678
679
680/* Minimal callback just to output policy info (if any) */
681
682static int
683smime_cb(int ok, X509_STORE_CTX * ctx)
684{
685 int error;
686
687 error = X509_STORE_CTX_get_error(ctx);
688
689 if ((error != X509_V_ERR_NO_EXPLICIT_POLICY)
690 && ((error != X509_V_OK) || (ok != 2)))
691 return ok;
692
693 policies_print(NULL, ctx);
694
695 return ok;
696
697}
diff --git a/src/usr.bin/openssl/speed.c b/src/usr.bin/openssl/speed.c
new file mode 100644
index 0000000000..82a0f90f05
--- /dev/null
+++ b/src/usr.bin/openssl/speed.c
@@ -0,0 +1,2170 @@
1/* $OpenBSD: speed.c,v 1.1 2014/08/26 17:47:25 jsing 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 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
60 *
61 * Portions of the attached software ("Contribution") are developed by
62 * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
63 *
64 * The Contribution is licensed pursuant to the OpenSSL open source
65 * license provided above.
66 *
67 * The ECDH and ECDSA speed test software is originally written by
68 * Sumit Gupta of Sun Microsystems Laboratories.
69 *
70 */
71
72/* most of this code has been pilfered from my libdes speed.c program */
73
74#ifndef OPENSSL_NO_SPEED
75
76#define SECONDS 3
77#define RSA_SECONDS 10
78#define DSA_SECONDS 10
79#define ECDSA_SECONDS 10
80#define ECDH_SECONDS 10
81
82/* 11-Sep-92 Andrew Daviel Support for Silicon Graphics IRIX added */
83/* 06-Apr-92 Luke Brennan Support for VMS and add extra signal calls */
84
85#include <math.h>
86#include <signal.h>
87#include <stdio.h>
88#include <stdlib.h>
89#include <limits.h>
90#include <string.h>
91#include <unistd.h>
92
93#include "apps.h"
94
95#include <openssl/bn.h>
96#include <openssl/crypto.h>
97#include <openssl/err.h>
98#include <openssl/evp.h>
99#include <openssl/modes.h>
100#include <openssl/objects.h>
101#include <openssl/rand.h>
102#include <openssl/x509.h>
103
104#ifndef OPENSSL_NO_AES
105#include <openssl/aes.h>
106#endif
107#ifndef OPENSSL_NO_BF
108#include <openssl/blowfish.h>
109#endif
110#ifndef OPENSSL_NO_CAST
111#include <openssl/cast.h>
112#endif
113#ifndef OPENSSL_NO_CAMELLIA
114#include <openssl/camellia.h>
115#endif
116#ifndef OPENSSL_NO_DES
117#include <openssl/des.h>
118#endif
119#include <openssl/dsa.h>
120#include <openssl/ecdh.h>
121#include <openssl/ecdsa.h>
122#ifndef OPENSSL_NO_HMAC
123#include <openssl/hmac.h>
124#endif
125#ifndef OPENSSL_NO_IDEA
126#include <openssl/idea.h>
127#endif
128#ifndef OPENSSL_NO_MDC2
129#include <openssl/mdc2.h>
130#endif
131#ifndef OPENSSL_NO_MD4
132#include <openssl/md4.h>
133#endif
134#ifndef OPENSSL_NO_MD5
135#include <openssl/md5.h>
136#endif
137#ifndef OPENSSL_NO_RC2
138#include <openssl/rc2.h>
139#endif
140#ifndef OPENSSL_NO_RC4
141#include <openssl/rc4.h>
142#endif
143#ifndef OPENSSL_NO_RC5
144#include <openssl/rc5.h>
145#endif
146#include <openssl/rsa.h>
147#ifndef OPENSSL_NO_RIPEMD
148#include <openssl/ripemd.h>
149#endif
150#ifndef OPENSSL_NO_SHA
151#include <openssl/sha.h>
152#endif
153#ifndef OPENSSL_NO_WHIRLPOOL
154#include <openssl/whrlpool.h>
155#endif
156
157#include "./testdsa.h"
158#include "./testrsa.h"
159
160#define BUFSIZE ((long)1024*8+1)
161int run = 0;
162
163static int mr = 0;
164static int usertime = 1;
165
166static double Time_F(int s);
167static void print_message(const char *s, long num, int length);
168static void
169pkey_print_message(const char *str, const char *str2,
170 long num, int bits, int sec);
171static void print_result(int alg, int run_no, int count, double time_used);
172static int do_multi(int multi);
173
174#define ALGOR_NUM 30
175#define SIZE_NUM 5
176#define RSA_NUM 4
177#define DSA_NUM 3
178
179#define EC_NUM 16
180#define MAX_ECDH_SIZE 256
181
182static const char *names[ALGOR_NUM] = {
183 "md2", "mdc2", "md4", "md5", "hmac(md5)", "sha1", "rmd160", "rc4",
184 "des cbc", "des ede3", "idea cbc", "seed cbc",
185 "rc2 cbc", "rc5-32/12 cbc", "blowfish cbc", "cast cbc",
186 "aes-128 cbc", "aes-192 cbc", "aes-256 cbc",
187 "camellia-128 cbc", "camellia-192 cbc", "camellia-256 cbc",
188 "evp", "sha256", "sha512", "whirlpool",
189"aes-128 ige", "aes-192 ige", "aes-256 ige", "ghash"};
190static double results[ALGOR_NUM][SIZE_NUM];
191static int lengths[SIZE_NUM] = {16, 64, 256, 1024, 8 * 1024};
192static double rsa_results[RSA_NUM][2];
193static double dsa_results[DSA_NUM][2];
194static double ecdsa_results[EC_NUM][2];
195static double ecdh_results[EC_NUM][1];
196
197static void sig_done(int sig);
198
199static void
200sig_done(int sig)
201{
202 signal(SIGALRM, sig_done);
203 run = 0;
204}
205
206#define START 0
207#define STOP 1
208
209
210static double
211Time_F(int s)
212{
213 return app_tminterval(s, usertime);
214}
215
216
217static const int KDF1_SHA1_len = 20;
218static void *
219KDF1_SHA1(const void *in, size_t inlen, void *out, size_t * outlen)
220{
221#ifndef OPENSSL_NO_SHA
222 if (*outlen < SHA_DIGEST_LENGTH)
223 return NULL;
224 else
225 *outlen = SHA_DIGEST_LENGTH;
226 return SHA1(in, inlen, out);
227#else
228 return NULL;
229#endif /* OPENSSL_NO_SHA */
230}
231
232
233int speed_main(int, char **);
234
235int
236speed_main(int argc, char **argv)
237{
238 unsigned char *buf = NULL, *buf2 = NULL;
239 int mret = 1;
240 long count = 0, save_count = 0;
241 int i, j, k;
242 long rsa_count;
243 unsigned rsa_num;
244 unsigned char md[EVP_MAX_MD_SIZE];
245#ifndef OPENSSL_NO_MDC2
246 unsigned char mdc2[MDC2_DIGEST_LENGTH];
247#endif
248#ifndef OPENSSL_NO_MD4
249 unsigned char md4[MD4_DIGEST_LENGTH];
250#endif
251#ifndef OPENSSL_NO_MD5
252 unsigned char md5[MD5_DIGEST_LENGTH];
253 unsigned char hmac[MD5_DIGEST_LENGTH];
254#endif
255#ifndef OPENSSL_NO_SHA
256 unsigned char sha[SHA_DIGEST_LENGTH];
257#ifndef OPENSSL_NO_SHA256
258 unsigned char sha256[SHA256_DIGEST_LENGTH];
259#endif
260#ifndef OPENSSL_NO_SHA512
261 unsigned char sha512[SHA512_DIGEST_LENGTH];
262#endif
263#endif
264#ifndef OPENSSL_NO_WHIRLPOOL
265 unsigned char whirlpool[WHIRLPOOL_DIGEST_LENGTH];
266#endif
267#ifndef OPENSSL_NO_RIPEMD
268 unsigned char rmd160[RIPEMD160_DIGEST_LENGTH];
269#endif
270#ifndef OPENSSL_NO_RC4
271 RC4_KEY rc4_ks;
272#endif
273#ifndef OPENSSL_NO_RC5
274 RC5_32_KEY rc5_ks;
275#endif
276#ifndef OPENSSL_NO_RC2
277 RC2_KEY rc2_ks;
278#endif
279#ifndef OPENSSL_NO_IDEA
280 IDEA_KEY_SCHEDULE idea_ks;
281#endif
282#ifndef OPENSSL_NO_BF
283 BF_KEY bf_ks;
284#endif
285#ifndef OPENSSL_NO_CAST
286 CAST_KEY cast_ks;
287#endif
288 static const unsigned char key16[16] =
289 {0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,
290 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12};
291#ifndef OPENSSL_NO_AES
292 static const unsigned char key24[24] =
293 {0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,
294 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12,
295 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34};
296 static const unsigned char key32[32] =
297 {0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,
298 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12,
299 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34,
300 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56};
301#endif
302#ifndef OPENSSL_NO_CAMELLIA
303 static const unsigned char ckey24[24] =
304 {0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,
305 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12,
306 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34};
307 static const unsigned char ckey32[32] =
308 {0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,
309 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12,
310 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34,
311 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56};
312#endif
313#ifndef OPENSSL_NO_AES
314#define MAX_BLOCK_SIZE 128
315#else
316#define MAX_BLOCK_SIZE 64
317#endif
318 unsigned char DES_iv[8];
319 unsigned char iv[2 * MAX_BLOCK_SIZE / 8];
320#ifndef OPENSSL_NO_DES
321 static DES_cblock key = {0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0};
322 static DES_cblock key2 = {0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12};
323 static DES_cblock key3 = {0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34};
324 DES_key_schedule sch;
325 DES_key_schedule sch2;
326 DES_key_schedule sch3;
327#endif
328#ifndef OPENSSL_NO_AES
329 AES_KEY aes_ks1, aes_ks2, aes_ks3;
330#endif
331#ifndef OPENSSL_NO_CAMELLIA
332 CAMELLIA_KEY camellia_ks1, camellia_ks2, camellia_ks3;
333#endif
334#define D_MD2 0
335#define D_MDC2 1
336#define D_MD4 2
337#define D_MD5 3
338#define D_HMAC 4
339#define D_SHA1 5
340#define D_RMD160 6
341#define D_RC4 7
342#define D_CBC_DES 8
343#define D_EDE3_DES 9
344#define D_CBC_IDEA 10
345#define D_CBC_SEED 11
346#define D_CBC_RC2 12
347#define D_CBC_RC5 13
348#define D_CBC_BF 14
349#define D_CBC_CAST 15
350#define D_CBC_128_AES 16
351#define D_CBC_192_AES 17
352#define D_CBC_256_AES 18
353#define D_CBC_128_CML 19
354#define D_CBC_192_CML 20
355#define D_CBC_256_CML 21
356#define D_EVP 22
357#define D_SHA256 23
358#define D_SHA512 24
359#define D_WHIRLPOOL 25
360#define D_IGE_128_AES 26
361#define D_IGE_192_AES 27
362#define D_IGE_256_AES 28
363#define D_GHASH 29
364 double d = 0.0;
365 long c[ALGOR_NUM][SIZE_NUM];
366#define R_DSA_512 0
367#define R_DSA_1024 1
368#define R_DSA_2048 2
369#define R_RSA_512 0
370#define R_RSA_1024 1
371#define R_RSA_2048 2
372#define R_RSA_4096 3
373
374#define R_EC_P160 0
375#define R_EC_P192 1
376#define R_EC_P224 2
377#define R_EC_P256 3
378#define R_EC_P384 4
379#define R_EC_P521 5
380#define R_EC_K163 6
381#define R_EC_K233 7
382#define R_EC_K283 8
383#define R_EC_K409 9
384#define R_EC_K571 10
385#define R_EC_B163 11
386#define R_EC_B233 12
387#define R_EC_B283 13
388#define R_EC_B409 14
389#define R_EC_B571 15
390
391 RSA *rsa_key[RSA_NUM];
392 long rsa_c[RSA_NUM][2];
393 static unsigned int rsa_bits[RSA_NUM] = {512, 1024, 2048, 4096};
394 static unsigned char *rsa_data[RSA_NUM] =
395 {test512, test1024, test2048, test4096};
396 static int rsa_data_length[RSA_NUM] = {
397 sizeof(test512), sizeof(test1024),
398 sizeof(test2048), sizeof(test4096)};
399 DSA *dsa_key[DSA_NUM];
400 long dsa_c[DSA_NUM][2];
401 static unsigned int dsa_bits[DSA_NUM] = {512, 1024, 2048};
402#ifndef OPENSSL_NO_EC
403 /*
404 * We only test over the following curves as they are representative,
405 * To add tests over more curves, simply add the curve NID and curve
406 * name to the following arrays and increase the EC_NUM value
407 * accordingly.
408 */
409 static unsigned int test_curves[EC_NUM] =
410 {
411 /* Prime Curves */
412 NID_secp160r1,
413 NID_X9_62_prime192v1,
414 NID_secp224r1,
415 NID_X9_62_prime256v1,
416 NID_secp384r1,
417 NID_secp521r1,
418 /* Binary Curves */
419 NID_sect163k1,
420 NID_sect233k1,
421 NID_sect283k1,
422 NID_sect409k1,
423 NID_sect571k1,
424 NID_sect163r2,
425 NID_sect233r1,
426 NID_sect283r1,
427 NID_sect409r1,
428 NID_sect571r1
429 };
430 static const char *test_curves_names[EC_NUM] =
431 {
432 /* Prime Curves */
433 "secp160r1",
434 "nistp192",
435 "nistp224",
436 "nistp256",
437 "nistp384",
438 "nistp521",
439 /* Binary Curves */
440 "nistk163",
441 "nistk233",
442 "nistk283",
443 "nistk409",
444 "nistk571",
445 "nistb163",
446 "nistb233",
447 "nistb283",
448 "nistb409",
449 "nistb571"
450 };
451 static int test_curves_bits[EC_NUM] =
452 {
453 160, 192, 224, 256, 384, 521,
454 163, 233, 283, 409, 571,
455 163, 233, 283, 409, 571
456 };
457
458#endif
459
460 unsigned char ecdsasig[256];
461 unsigned int ecdsasiglen;
462 EC_KEY *ecdsa[EC_NUM];
463 long ecdsa_c[EC_NUM][2];
464
465 EC_KEY *ecdh_a[EC_NUM], *ecdh_b[EC_NUM];
466 unsigned char secret_a[MAX_ECDH_SIZE], secret_b[MAX_ECDH_SIZE];
467 int secret_size_a, secret_size_b;
468 int ecdh_checks = 0;
469 int secret_idx = 0;
470 long ecdh_c[EC_NUM][2];
471
472 int rsa_doit[RSA_NUM];
473 int dsa_doit[DSA_NUM];
474 int ecdsa_doit[EC_NUM];
475 int ecdh_doit[EC_NUM];
476 int doit[ALGOR_NUM];
477 int pr_header = 0;
478 const EVP_CIPHER *evp_cipher = NULL;
479 const EVP_MD *evp_md = NULL;
480 int decrypt = 0;
481 int multi = 0;
482 const char *errstr = NULL;
483
484#ifndef TIMES
485 usertime = -1;
486#endif
487
488 memset(results, 0, sizeof(results));
489 memset(dsa_key, 0, sizeof(dsa_key));
490 for (i = 0; i < EC_NUM; i++)
491 ecdsa[i] = NULL;
492 for (i = 0; i < EC_NUM; i++) {
493 ecdh_a[i] = NULL;
494 ecdh_b[i] = NULL;
495 }
496
497 memset(rsa_key, 0, sizeof(rsa_key));
498 for (i = 0; i < RSA_NUM; i++)
499 rsa_key[i] = NULL;
500
501 if ((buf = malloc((int) BUFSIZE)) == NULL) {
502 BIO_printf(bio_err, "out of memory\n");
503 goto end;
504 }
505 if ((buf2 = malloc((int) BUFSIZE)) == NULL) {
506 BIO_printf(bio_err, "out of memory\n");
507 goto end;
508 }
509 memset(c, 0, sizeof(c));
510 memset(DES_iv, 0, sizeof(DES_iv));
511 memset(iv, 0, sizeof(iv));
512
513 for (i = 0; i < ALGOR_NUM; i++)
514 doit[i] = 0;
515 for (i = 0; i < RSA_NUM; i++)
516 rsa_doit[i] = 0;
517 for (i = 0; i < DSA_NUM; i++)
518 dsa_doit[i] = 0;
519 for (i = 0; i < EC_NUM; i++)
520 ecdsa_doit[i] = 0;
521 for (i = 0; i < EC_NUM; i++)
522 ecdh_doit[i] = 0;
523
524
525 j = 0;
526 argc--;
527 argv++;
528 while (argc) {
529 if ((argc > 0) && (strcmp(*argv, "-elapsed") == 0)) {
530 usertime = 0;
531 j--; /* Otherwise, -elapsed gets confused with an
532 * algorithm. */
533 } else if ((argc > 0) && (strcmp(*argv, "-evp") == 0)) {
534 argc--;
535 argv++;
536 if (argc == 0) {
537 BIO_printf(bio_err, "no EVP given\n");
538 goto end;
539 }
540 evp_cipher = EVP_get_cipherbyname(*argv);
541 if (!evp_cipher) {
542 evp_md = EVP_get_digestbyname(*argv);
543 }
544 if (!evp_cipher && !evp_md) {
545 BIO_printf(bio_err, "%s is an unknown cipher or digest\n", *argv);
546 goto end;
547 }
548 doit[D_EVP] = 1;
549 } else if (argc > 0 && !strcmp(*argv, "-decrypt")) {
550 decrypt = 1;
551 j--; /* Otherwise, -elapsed gets confused with an
552 * algorithm. */
553 }
554#ifndef OPENSSL_NO_ENGINE
555 else if ((argc > 0) && (strcmp(*argv, "-engine") == 0)) {
556 argc--;
557 argv++;
558 if (argc == 0) {
559 BIO_printf(bio_err, "no engine given\n");
560 goto end;
561 }
562 setup_engine(bio_err, *argv, 0);
563 /*
564 * j will be increased again further down. We just
565 * don't want speed to confuse an engine with an
566 * algorithm, especially when none is given (which
567 * means all of them should be run)
568 */
569 j--;
570 }
571#endif
572 else if ((argc > 0) && (strcmp(*argv, "-multi") == 0)) {
573 argc--;
574 argv++;
575 if (argc == 0) {
576 BIO_printf(bio_err, "no multi count given\n");
577 goto end;
578 }
579 multi = strtonum(argv[0], 1, INT_MAX, &errstr);
580 if (errstr) {
581 BIO_printf(bio_err, "bad multi count: %s", errstr);
582 goto end;
583 }
584 j--; /* Otherwise, -mr gets confused with an
585 * algorithm. */
586 }
587 else if (argc > 0 && !strcmp(*argv, "-mr")) {
588 mr = 1;
589 j--; /* Otherwise, -mr gets confused with an
590 * algorithm. */
591 } else
592#ifndef OPENSSL_NO_MDC2
593 if (strcmp(*argv, "mdc2") == 0)
594 doit[D_MDC2] = 1;
595 else
596#endif
597#ifndef OPENSSL_NO_MD4
598 if (strcmp(*argv, "md4") == 0)
599 doit[D_MD4] = 1;
600 else
601#endif
602#ifndef OPENSSL_NO_MD5
603 if (strcmp(*argv, "md5") == 0)
604 doit[D_MD5] = 1;
605 else
606#endif
607#ifndef OPENSSL_NO_MD5
608 if (strcmp(*argv, "hmac") == 0)
609 doit[D_HMAC] = 1;
610 else
611#endif
612#ifndef OPENSSL_NO_SHA
613 if (strcmp(*argv, "sha1") == 0)
614 doit[D_SHA1] = 1;
615 else if (strcmp(*argv, "sha") == 0)
616 doit[D_SHA1] = 1,
617 doit[D_SHA256] = 1,
618 doit[D_SHA512] = 1;
619 else
620#ifndef OPENSSL_NO_SHA256
621 if (strcmp(*argv, "sha256") == 0)
622 doit[D_SHA256] = 1;
623 else
624#endif
625#ifndef OPENSSL_NO_SHA512
626 if (strcmp(*argv, "sha512") == 0)
627 doit[D_SHA512] = 1;
628 else
629#endif
630#endif
631#ifndef OPENSSL_NO_WHIRLPOOL
632 if (strcmp(*argv, "whirlpool") == 0)
633 doit[D_WHIRLPOOL] = 1;
634 else
635#endif
636#ifndef OPENSSL_NO_RIPEMD
637 if (strcmp(*argv, "ripemd") == 0)
638 doit[D_RMD160] = 1;
639 else if (strcmp(*argv, "rmd160") == 0)
640 doit[D_RMD160] = 1;
641 else if (strcmp(*argv, "ripemd160") == 0)
642 doit[D_RMD160] = 1;
643 else
644#endif
645#ifndef OPENSSL_NO_RC4
646 if (strcmp(*argv, "rc4") == 0)
647 doit[D_RC4] = 1;
648 else
649#endif
650#ifndef OPENSSL_NO_DES
651 if (strcmp(*argv, "des-cbc") == 0)
652 doit[D_CBC_DES] = 1;
653 else if (strcmp(*argv, "des-ede3") == 0)
654 doit[D_EDE3_DES] = 1;
655 else
656#endif
657#ifndef OPENSSL_NO_AES
658 if (strcmp(*argv, "aes-128-cbc") == 0)
659 doit[D_CBC_128_AES] = 1;
660 else if (strcmp(*argv, "aes-192-cbc") == 0)
661 doit[D_CBC_192_AES] = 1;
662 else if (strcmp(*argv, "aes-256-cbc") == 0)
663 doit[D_CBC_256_AES] = 1;
664 else if (strcmp(*argv, "aes-128-ige") == 0)
665 doit[D_IGE_128_AES] = 1;
666 else if (strcmp(*argv, "aes-192-ige") == 0)
667 doit[D_IGE_192_AES] = 1;
668 else if (strcmp(*argv, "aes-256-ige") == 0)
669 doit[D_IGE_256_AES] = 1;
670 else
671#endif
672#ifndef OPENSSL_NO_CAMELLIA
673 if (strcmp(*argv, "camellia-128-cbc") == 0)
674 doit[D_CBC_128_CML] = 1;
675 else if (strcmp(*argv, "camellia-192-cbc") == 0)
676 doit[D_CBC_192_CML] = 1;
677 else if (strcmp(*argv, "camellia-256-cbc") == 0)
678 doit[D_CBC_256_CML] = 1;
679 else
680#endif
681#if 0 /* was: #ifdef RSAref */
682 if (strcmp(*argv, "rsaref") == 0) {
683 RSA_set_default_openssl_method(RSA_PKCS1_RSAref());
684 j--;
685 } else
686#endif
687#ifndef RSA_NULL
688 if (strcmp(*argv, "openssl") == 0) {
689 RSA_set_default_method(RSA_PKCS1_SSLeay());
690 j--;
691 } else
692#endif
693 if (strcmp(*argv, "dsa512") == 0)
694 dsa_doit[R_DSA_512] = 2;
695 else if (strcmp(*argv, "dsa1024") == 0)
696 dsa_doit[R_DSA_1024] = 2;
697 else if (strcmp(*argv, "dsa2048") == 0)
698 dsa_doit[R_DSA_2048] = 2;
699 else if (strcmp(*argv, "rsa512") == 0)
700 rsa_doit[R_RSA_512] = 2;
701 else if (strcmp(*argv, "rsa1024") == 0)
702 rsa_doit[R_RSA_1024] = 2;
703 else if (strcmp(*argv, "rsa2048") == 0)
704 rsa_doit[R_RSA_2048] = 2;
705 else if (strcmp(*argv, "rsa4096") == 0)
706 rsa_doit[R_RSA_4096] = 2;
707 else
708#ifndef OPENSSL_NO_RC2
709 if (strcmp(*argv, "rc2-cbc") == 0)
710 doit[D_CBC_RC2] = 1;
711 else if (strcmp(*argv, "rc2") == 0)
712 doit[D_CBC_RC2] = 1;
713 else
714#endif
715#ifndef OPENSSL_NO_RC5
716 if (strcmp(*argv, "rc5-cbc") == 0)
717 doit[D_CBC_RC5] = 1;
718 else if (strcmp(*argv, "rc5") == 0)
719 doit[D_CBC_RC5] = 1;
720 else
721#endif
722#ifndef OPENSSL_NO_IDEA
723 if (strcmp(*argv, "idea-cbc") == 0)
724 doit[D_CBC_IDEA] = 1;
725 else if (strcmp(*argv, "idea") == 0)
726 doit[D_CBC_IDEA] = 1;
727 else
728#endif
729#ifndef OPENSSL_NO_BF
730 if (strcmp(*argv, "bf-cbc") == 0)
731 doit[D_CBC_BF] = 1;
732 else if (strcmp(*argv, "blowfish") == 0)
733 doit[D_CBC_BF] = 1;
734 else if (strcmp(*argv, "bf") == 0)
735 doit[D_CBC_BF] = 1;
736 else
737#endif
738#ifndef OPENSSL_NO_CAST
739 if (strcmp(*argv, "cast-cbc") == 0)
740 doit[D_CBC_CAST] = 1;
741 else if (strcmp(*argv, "cast") == 0)
742 doit[D_CBC_CAST] = 1;
743 else if (strcmp(*argv, "cast5") == 0)
744 doit[D_CBC_CAST] = 1;
745 else
746#endif
747#ifndef OPENSSL_NO_DES
748 if (strcmp(*argv, "des") == 0) {
749 doit[D_CBC_DES] = 1;
750 doit[D_EDE3_DES] = 1;
751 } else
752#endif
753#ifndef OPENSSL_NO_AES
754 if (strcmp(*argv, "aes") == 0) {
755 doit[D_CBC_128_AES] = 1;
756 doit[D_CBC_192_AES] = 1;
757 doit[D_CBC_256_AES] = 1;
758 } else if (strcmp(*argv, "ghash") == 0) {
759 doit[D_GHASH] = 1;
760 } else
761#endif
762#ifndef OPENSSL_NO_CAMELLIA
763 if (strcmp(*argv, "camellia") == 0) {
764 doit[D_CBC_128_CML] = 1;
765 doit[D_CBC_192_CML] = 1;
766 doit[D_CBC_256_CML] = 1;
767 } else
768#endif
769 if (strcmp(*argv, "rsa") == 0) {
770 rsa_doit[R_RSA_512] = 1;
771 rsa_doit[R_RSA_1024] = 1;
772 rsa_doit[R_RSA_2048] = 1;
773 rsa_doit[R_RSA_4096] = 1;
774 } else
775 if (strcmp(*argv, "dsa") == 0) {
776 dsa_doit[R_DSA_512] = 1;
777 dsa_doit[R_DSA_1024] = 1;
778 dsa_doit[R_DSA_2048] = 1;
779 } else
780 if (strcmp(*argv, "ecdsap160") == 0)
781 ecdsa_doit[R_EC_P160] = 2;
782 else if (strcmp(*argv, "ecdsap192") == 0)
783 ecdsa_doit[R_EC_P192] = 2;
784 else if (strcmp(*argv, "ecdsap224") == 0)
785 ecdsa_doit[R_EC_P224] = 2;
786 else if (strcmp(*argv, "ecdsap256") == 0)
787 ecdsa_doit[R_EC_P256] = 2;
788 else if (strcmp(*argv, "ecdsap384") == 0)
789 ecdsa_doit[R_EC_P384] = 2;
790 else if (strcmp(*argv, "ecdsap521") == 0)
791 ecdsa_doit[R_EC_P521] = 2;
792 else if (strcmp(*argv, "ecdsak163") == 0)
793 ecdsa_doit[R_EC_K163] = 2;
794 else if (strcmp(*argv, "ecdsak233") == 0)
795 ecdsa_doit[R_EC_K233] = 2;
796 else if (strcmp(*argv, "ecdsak283") == 0)
797 ecdsa_doit[R_EC_K283] = 2;
798 else if (strcmp(*argv, "ecdsak409") == 0)
799 ecdsa_doit[R_EC_K409] = 2;
800 else if (strcmp(*argv, "ecdsak571") == 0)
801 ecdsa_doit[R_EC_K571] = 2;
802 else if (strcmp(*argv, "ecdsab163") == 0)
803 ecdsa_doit[R_EC_B163] = 2;
804 else if (strcmp(*argv, "ecdsab233") == 0)
805 ecdsa_doit[R_EC_B233] = 2;
806 else if (strcmp(*argv, "ecdsab283") == 0)
807 ecdsa_doit[R_EC_B283] = 2;
808 else if (strcmp(*argv, "ecdsab409") == 0)
809 ecdsa_doit[R_EC_B409] = 2;
810 else if (strcmp(*argv, "ecdsab571") == 0)
811 ecdsa_doit[R_EC_B571] = 2;
812 else if (strcmp(*argv, "ecdsa") == 0) {
813 for (i = 0; i < EC_NUM; i++)
814 ecdsa_doit[i] = 1;
815 } else
816 if (strcmp(*argv, "ecdhp160") == 0)
817 ecdh_doit[R_EC_P160] = 2;
818 else if (strcmp(*argv, "ecdhp192") == 0)
819 ecdh_doit[R_EC_P192] = 2;
820 else if (strcmp(*argv, "ecdhp224") == 0)
821 ecdh_doit[R_EC_P224] = 2;
822 else if (strcmp(*argv, "ecdhp256") == 0)
823 ecdh_doit[R_EC_P256] = 2;
824 else if (strcmp(*argv, "ecdhp384") == 0)
825 ecdh_doit[R_EC_P384] = 2;
826 else if (strcmp(*argv, "ecdhp521") == 0)
827 ecdh_doit[R_EC_P521] = 2;
828 else if (strcmp(*argv, "ecdhk163") == 0)
829 ecdh_doit[R_EC_K163] = 2;
830 else if (strcmp(*argv, "ecdhk233") == 0)
831 ecdh_doit[R_EC_K233] = 2;
832 else if (strcmp(*argv, "ecdhk283") == 0)
833 ecdh_doit[R_EC_K283] = 2;
834 else if (strcmp(*argv, "ecdhk409") == 0)
835 ecdh_doit[R_EC_K409] = 2;
836 else if (strcmp(*argv, "ecdhk571") == 0)
837 ecdh_doit[R_EC_K571] = 2;
838 else if (strcmp(*argv, "ecdhb163") == 0)
839 ecdh_doit[R_EC_B163] = 2;
840 else if (strcmp(*argv, "ecdhb233") == 0)
841 ecdh_doit[R_EC_B233] = 2;
842 else if (strcmp(*argv, "ecdhb283") == 0)
843 ecdh_doit[R_EC_B283] = 2;
844 else if (strcmp(*argv, "ecdhb409") == 0)
845 ecdh_doit[R_EC_B409] = 2;
846 else if (strcmp(*argv, "ecdhb571") == 0)
847 ecdh_doit[R_EC_B571] = 2;
848 else if (strcmp(*argv, "ecdh") == 0) {
849 for (i = 0; i < EC_NUM; i++)
850 ecdh_doit[i] = 1;
851 } else
852 {
853 BIO_printf(bio_err, "Error: bad option or value\n");
854 BIO_printf(bio_err, "\n");
855 BIO_printf(bio_err, "Available values:\n");
856#ifndef OPENSSL_NO_MDC2
857 BIO_printf(bio_err, "mdc2 ");
858#endif
859#ifndef OPENSSL_NO_MD4
860 BIO_printf(bio_err, "md4 ");
861#endif
862#ifndef OPENSSL_NO_MD5
863 BIO_printf(bio_err, "md5 ");
864#ifndef OPENSSL_NO_HMAC
865 BIO_printf(bio_err, "hmac ");
866#endif
867#endif
868#ifndef OPENSSL_NO_SHA1
869 BIO_printf(bio_err, "sha1 ");
870#endif
871#ifndef OPENSSL_NO_SHA256
872 BIO_printf(bio_err, "sha256 ");
873#endif
874#ifndef OPENSSL_NO_SHA512
875 BIO_printf(bio_err, "sha512 ");
876#endif
877#ifndef OPENSSL_NO_WHIRLPOOL
878 BIO_printf(bio_err, "whirlpool");
879#endif
880#ifndef OPENSSL_NO_RIPEMD160
881 BIO_printf(bio_err, "rmd160");
882#endif
883#if !defined(OPENSSL_NO_MD2) || !defined(OPENSSL_NO_MDC2) || \
884 !defined(OPENSSL_NO_MD4) || !defined(OPENSSL_NO_MD5) || \
885 !defined(OPENSSL_NO_SHA1) || !defined(OPENSSL_NO_RIPEMD160) || \
886 !defined(OPENSSL_NO_WHIRLPOOL)
887 BIO_printf(bio_err, "\n");
888#endif
889
890#ifndef OPENSSL_NO_IDEA
891 BIO_printf(bio_err, "idea-cbc ");
892#endif
893#ifndef OPENSSL_NO_RC2
894 BIO_printf(bio_err, "rc2-cbc ");
895#endif
896#ifndef OPENSSL_NO_RC5
897 BIO_printf(bio_err, "rc5-cbc ");
898#endif
899#ifndef OPENSSL_NO_BF
900 BIO_printf(bio_err, "bf-cbc");
901#endif
902#if !defined(OPENSSL_NO_IDEA) || !defined(OPENSSL_NO_SEED) || !defined(OPENSSL_NO_RC2) || \
903 !defined(OPENSSL_NO_BF) || !defined(OPENSSL_NO_RC5)
904 BIO_printf(bio_err, "\n");
905#endif
906#ifndef OPENSSL_NO_DES
907 BIO_printf(bio_err, "des-cbc des-ede3 ");
908#endif
909#ifndef OPENSSL_NO_AES
910 BIO_printf(bio_err, "aes-128-cbc aes-192-cbc aes-256-cbc ");
911 BIO_printf(bio_err, "aes-128-ige aes-192-ige aes-256-ige ");
912#endif
913#ifndef OPENSSL_NO_CAMELLIA
914 BIO_printf(bio_err, "\n");
915 BIO_printf(bio_err, "camellia-128-cbc camellia-192-cbc camellia-256-cbc ");
916#endif
917#ifndef OPENSSL_NO_RC4
918 BIO_printf(bio_err, "rc4");
919#endif
920 BIO_printf(bio_err, "\n");
921
922 BIO_printf(bio_err, "rsa512 rsa1024 rsa2048 rsa4096\n");
923
924 BIO_printf(bio_err, "dsa512 dsa1024 dsa2048\n");
925 BIO_printf(bio_err, "ecdsap160 ecdsap192 ecdsap224 ecdsap256 ecdsap384 ecdsap521\n");
926 BIO_printf(bio_err, "ecdsak163 ecdsak233 ecdsak283 ecdsak409 ecdsak571\n");
927 BIO_printf(bio_err, "ecdsab163 ecdsab233 ecdsab283 ecdsab409 ecdsab571\n");
928 BIO_printf(bio_err, "ecdsa\n");
929 BIO_printf(bio_err, "ecdhp160 ecdhp192 ecdhp224 ecdhp256 ecdhp384 ecdhp521\n");
930 BIO_printf(bio_err, "ecdhk163 ecdhk233 ecdhk283 ecdhk409 ecdhk571\n");
931 BIO_printf(bio_err, "ecdhb163 ecdhb233 ecdhb283 ecdhb409 ecdhb571\n");
932 BIO_printf(bio_err, "ecdh\n");
933
934#ifndef OPENSSL_NO_IDEA
935 BIO_printf(bio_err, "idea ");
936#endif
937#ifndef OPENSSL_NO_RC2
938 BIO_printf(bio_err, "rc2 ");
939#endif
940#ifndef OPENSSL_NO_DES
941 BIO_printf(bio_err, "des ");
942#endif
943#ifndef OPENSSL_NO_AES
944 BIO_printf(bio_err, "aes ");
945#endif
946#ifndef OPENSSL_NO_CAMELLIA
947 BIO_printf(bio_err, "camellia ");
948#endif
949 BIO_printf(bio_err, "rsa ");
950#ifndef OPENSSL_NO_BF
951 BIO_printf(bio_err, "blowfish");
952#endif
953#if !defined(OPENSSL_NO_IDEA) || !defined(OPENSSL_NO_SEED) || \
954 !defined(OPENSSL_NO_RC2) || !defined(OPENSSL_NO_DES) || \
955 !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_BF) || \
956 !defined(OPENSSL_NO_AES) || !defined(OPENSSL_NO_CAMELLIA)
957 BIO_printf(bio_err, "\n");
958#endif
959
960 BIO_printf(bio_err, "\n");
961 BIO_printf(bio_err, "Available options:\n");
962#if defined(TIMES) || defined(USE_TOD)
963 BIO_printf(bio_err, "-elapsed measure time in real time instead of CPU user time.\n");
964#endif
965#ifndef OPENSSL_NO_ENGINE
966 BIO_printf(bio_err, "-engine e use engine e, possibly a hardware device.\n");
967#endif
968 BIO_printf(bio_err, "-evp e use EVP e.\n");
969 BIO_printf(bio_err, "-decrypt time decryption instead of encryption (only EVP).\n");
970 BIO_printf(bio_err, "-mr produce machine readable output.\n");
971 BIO_printf(bio_err, "-multi n run n benchmarks in parallel.\n");
972 goto end;
973 }
974 argc--;
975 argv++;
976 j++;
977 }
978
979 if (multi && do_multi(multi))
980 goto show_res;
981
982 if (j == 0) {
983 for (i = 0; i < ALGOR_NUM; i++) {
984 if (i != D_EVP)
985 doit[i] = 1;
986 }
987 for (i = 0; i < RSA_NUM; i++)
988 rsa_doit[i] = 1;
989 for (i = 0; i < DSA_NUM; i++)
990 dsa_doit[i] = 1;
991 for (i = 0; i < EC_NUM; i++)
992 ecdsa_doit[i] = 1;
993 for (i = 0; i < EC_NUM; i++)
994 ecdh_doit[i] = 1;
995 }
996 for (i = 0; i < ALGOR_NUM; i++)
997 if (doit[i])
998 pr_header++;
999
1000 if (usertime == 0 && !mr)
1001 BIO_printf(bio_err, "You have chosen to measure elapsed time instead of user CPU time.\n");
1002
1003 for (i = 0; i < RSA_NUM; i++) {
1004 const unsigned char *p;
1005
1006 p = rsa_data[i];
1007 rsa_key[i] = d2i_RSAPrivateKey(NULL, &p, rsa_data_length[i]);
1008 if (rsa_key[i] == NULL) {
1009 BIO_printf(bio_err, "internal error loading RSA key number %d\n", i);
1010 goto end;
1011 }
1012#if 0
1013 else {
1014 BIO_printf(bio_err, mr ? "+RK:%d:"
1015 : "Loaded RSA key, %d bit modulus and e= 0x",
1016 BN_num_bits(rsa_key[i]->n));
1017 BN_print(bio_err, rsa_key[i]->e);
1018 BIO_printf(bio_err, "\n");
1019 }
1020#endif
1021 }
1022
1023 dsa_key[0] = get_dsa512();
1024 dsa_key[1] = get_dsa1024();
1025 dsa_key[2] = get_dsa2048();
1026
1027#ifndef OPENSSL_NO_DES
1028 DES_set_key_unchecked(&key, &sch);
1029 DES_set_key_unchecked(&key2, &sch2);
1030 DES_set_key_unchecked(&key3, &sch3);
1031#endif
1032#ifndef OPENSSL_NO_AES
1033 AES_set_encrypt_key(key16, 128, &aes_ks1);
1034 AES_set_encrypt_key(key24, 192, &aes_ks2);
1035 AES_set_encrypt_key(key32, 256, &aes_ks3);
1036#endif
1037#ifndef OPENSSL_NO_CAMELLIA
1038 Camellia_set_key(key16, 128, &camellia_ks1);
1039 Camellia_set_key(ckey24, 192, &camellia_ks2);
1040 Camellia_set_key(ckey32, 256, &camellia_ks3);
1041#endif
1042#ifndef OPENSSL_NO_IDEA
1043 idea_set_encrypt_key(key16, &idea_ks);
1044#endif
1045#ifndef OPENSSL_NO_RC4
1046 RC4_set_key(&rc4_ks, 16, key16);
1047#endif
1048#ifndef OPENSSL_NO_RC2
1049 RC2_set_key(&rc2_ks, 16, key16, 128);
1050#endif
1051#ifndef OPENSSL_NO_RC5
1052 RC5_32_set_key(&rc5_ks, 16, key16, 12);
1053#endif
1054#ifndef OPENSSL_NO_BF
1055 BF_set_key(&bf_ks, 16, key16);
1056#endif
1057#ifndef OPENSSL_NO_CAST
1058 CAST_set_key(&cast_ks, 16, key16);
1059#endif
1060 memset(rsa_c, 0, sizeof(rsa_c));
1061#define COND(c) (run && count<0x7fffffff)
1062#define COUNT(d) (count)
1063 signal(SIGALRM, sig_done);
1064
1065#ifndef OPENSSL_NO_MDC2
1066 if (doit[D_MDC2]) {
1067 for (j = 0; j < SIZE_NUM; j++) {
1068 print_message(names[D_MDC2], c[D_MDC2][j], lengths[j]);
1069 Time_F(START);
1070 for (count = 0, run = 1; COND(c[D_MDC2][j]); count++)
1071 EVP_Digest(buf, (unsigned long) lengths[j], &(mdc2[0]), NULL, EVP_mdc2(), NULL);
1072 d = Time_F(STOP);
1073 print_result(D_MDC2, j, count, d);
1074 }
1075 }
1076#endif
1077
1078#ifndef OPENSSL_NO_MD4
1079 if (doit[D_MD4]) {
1080 for (j = 0; j < SIZE_NUM; j++) {
1081 print_message(names[D_MD4], c[D_MD4][j], lengths[j]);
1082 Time_F(START);
1083 for (count = 0, run = 1; COND(c[D_MD4][j]); count++)
1084 EVP_Digest(&(buf[0]), (unsigned long) lengths[j], &(md4[0]), NULL, EVP_md4(), NULL);
1085 d = Time_F(STOP);
1086 print_result(D_MD4, j, count, d);
1087 }
1088 }
1089#endif
1090
1091#ifndef OPENSSL_NO_MD5
1092 if (doit[D_MD5]) {
1093 for (j = 0; j < SIZE_NUM; j++) {
1094 print_message(names[D_MD5], c[D_MD5][j], lengths[j]);
1095 Time_F(START);
1096 for (count = 0, run = 1; COND(c[D_MD5][j]); count++)
1097 EVP_Digest(&(buf[0]), (unsigned long) lengths[j], &(md5[0]), NULL, EVP_get_digestbyname("md5"), NULL);
1098 d = Time_F(STOP);
1099 print_result(D_MD5, j, count, d);
1100 }
1101 }
1102#endif
1103
1104#if !defined(OPENSSL_NO_MD5) && !defined(OPENSSL_NO_HMAC)
1105 if (doit[D_HMAC]) {
1106 HMAC_CTX hctx;
1107
1108 HMAC_CTX_init(&hctx);
1109 HMAC_Init_ex(&hctx, (unsigned char *) "This is a key...",
1110 16, EVP_md5(), NULL);
1111
1112 for (j = 0; j < SIZE_NUM; j++) {
1113 print_message(names[D_HMAC], c[D_HMAC][j], lengths[j]);
1114 Time_F(START);
1115 for (count = 0, run = 1; COND(c[D_HMAC][j]); count++) {
1116 HMAC_Init_ex(&hctx, NULL, 0, NULL, NULL);
1117 HMAC_Update(&hctx, buf, lengths[j]);
1118 HMAC_Final(&hctx, &(hmac[0]), NULL);
1119 }
1120 d = Time_F(STOP);
1121 print_result(D_HMAC, j, count, d);
1122 }
1123 HMAC_CTX_cleanup(&hctx);
1124 }
1125#endif
1126#ifndef OPENSSL_NO_SHA
1127 if (doit[D_SHA1]) {
1128 for (j = 0; j < SIZE_NUM; j++) {
1129 print_message(names[D_SHA1], c[D_SHA1][j], lengths[j]);
1130 Time_F(START);
1131 for (count = 0, run = 1; COND(c[D_SHA1][j]); count++)
1132 EVP_Digest(buf, (unsigned long) lengths[j], &(sha[0]), NULL, EVP_sha1(), NULL);
1133 d = Time_F(STOP);
1134 print_result(D_SHA1, j, count, d);
1135 }
1136 }
1137#ifndef OPENSSL_NO_SHA256
1138 if (doit[D_SHA256]) {
1139 for (j = 0; j < SIZE_NUM; j++) {
1140 print_message(names[D_SHA256], c[D_SHA256][j], lengths[j]);
1141 Time_F(START);
1142 for (count = 0, run = 1; COND(c[D_SHA256][j]); count++)
1143 SHA256(buf, lengths[j], sha256);
1144 d = Time_F(STOP);
1145 print_result(D_SHA256, j, count, d);
1146 }
1147 }
1148#endif
1149
1150#ifndef OPENSSL_NO_SHA512
1151 if (doit[D_SHA512]) {
1152 for (j = 0; j < SIZE_NUM; j++) {
1153 print_message(names[D_SHA512], c[D_SHA512][j], lengths[j]);
1154 Time_F(START);
1155 for (count = 0, run = 1; COND(c[D_SHA512][j]); count++)
1156 SHA512(buf, lengths[j], sha512);
1157 d = Time_F(STOP);
1158 print_result(D_SHA512, j, count, d);
1159 }
1160 }
1161#endif
1162#endif
1163
1164#ifndef OPENSSL_NO_WHIRLPOOL
1165 if (doit[D_WHIRLPOOL]) {
1166 for (j = 0; j < SIZE_NUM; j++) {
1167 print_message(names[D_WHIRLPOOL], c[D_WHIRLPOOL][j], lengths[j]);
1168 Time_F(START);
1169 for (count = 0, run = 1; COND(c[D_WHIRLPOOL][j]); count++)
1170 WHIRLPOOL(buf, lengths[j], whirlpool);
1171 d = Time_F(STOP);
1172 print_result(D_WHIRLPOOL, j, count, d);
1173 }
1174 }
1175#endif
1176
1177#ifndef OPENSSL_NO_RIPEMD
1178 if (doit[D_RMD160]) {
1179 for (j = 0; j < SIZE_NUM; j++) {
1180 print_message(names[D_RMD160], c[D_RMD160][j], lengths[j]);
1181 Time_F(START);
1182 for (count = 0, run = 1; COND(c[D_RMD160][j]); count++)
1183 EVP_Digest(buf, (unsigned long) lengths[j], &(rmd160[0]), NULL, EVP_ripemd160(), NULL);
1184 d = Time_F(STOP);
1185 print_result(D_RMD160, j, count, d);
1186 }
1187 }
1188#endif
1189#ifndef OPENSSL_NO_RC4
1190 if (doit[D_RC4]) {
1191 for (j = 0; j < SIZE_NUM; j++) {
1192 print_message(names[D_RC4], c[D_RC4][j], lengths[j]);
1193 Time_F(START);
1194 for (count = 0, run = 1; COND(c[D_RC4][j]); count++)
1195 RC4(&rc4_ks, (unsigned int) lengths[j],
1196 buf, buf);
1197 d = Time_F(STOP);
1198 print_result(D_RC4, j, count, d);
1199 }
1200 }
1201#endif
1202#ifndef OPENSSL_NO_DES
1203 if (doit[D_CBC_DES]) {
1204 for (j = 0; j < SIZE_NUM; j++) {
1205 print_message(names[D_CBC_DES], c[D_CBC_DES][j], lengths[j]);
1206 Time_F(START);
1207 for (count = 0, run = 1; COND(c[D_CBC_DES][j]); count++)
1208 DES_ncbc_encrypt(buf, buf, lengths[j], &sch,
1209 &DES_iv, DES_ENCRYPT);
1210 d = Time_F(STOP);
1211 print_result(D_CBC_DES, j, count, d);
1212 }
1213 }
1214 if (doit[D_EDE3_DES]) {
1215 for (j = 0; j < SIZE_NUM; j++) {
1216 print_message(names[D_EDE3_DES], c[D_EDE3_DES][j], lengths[j]);
1217 Time_F(START);
1218 for (count = 0, run = 1; COND(c[D_EDE3_DES][j]); count++)
1219 DES_ede3_cbc_encrypt(buf, buf, lengths[j],
1220 &sch, &sch2, &sch3,
1221 &DES_iv, DES_ENCRYPT);
1222 d = Time_F(STOP);
1223 print_result(D_EDE3_DES, j, count, d);
1224 }
1225 }
1226#endif
1227#ifndef OPENSSL_NO_AES
1228 if (doit[D_CBC_128_AES]) {
1229 for (j = 0; j < SIZE_NUM; j++) {
1230 print_message(names[D_CBC_128_AES], c[D_CBC_128_AES][j], lengths[j]);
1231 Time_F(START);
1232 for (count = 0, run = 1; COND(c[D_CBC_128_AES][j]); count++)
1233 AES_cbc_encrypt(buf, buf,
1234 (unsigned long) lengths[j], &aes_ks1,
1235 iv, AES_ENCRYPT);
1236 d = Time_F(STOP);
1237 print_result(D_CBC_128_AES, j, count, d);
1238 }
1239 }
1240 if (doit[D_CBC_192_AES]) {
1241 for (j = 0; j < SIZE_NUM; j++) {
1242 print_message(names[D_CBC_192_AES], c[D_CBC_192_AES][j], lengths[j]);
1243 Time_F(START);
1244 for (count = 0, run = 1; COND(c[D_CBC_192_AES][j]); count++)
1245 AES_cbc_encrypt(buf, buf,
1246 (unsigned long) lengths[j], &aes_ks2,
1247 iv, AES_ENCRYPT);
1248 d = Time_F(STOP);
1249 print_result(D_CBC_192_AES, j, count, d);
1250 }
1251 }
1252 if (doit[D_CBC_256_AES]) {
1253 for (j = 0; j < SIZE_NUM; j++) {
1254 print_message(names[D_CBC_256_AES], c[D_CBC_256_AES][j], lengths[j]);
1255 Time_F(START);
1256 for (count = 0, run = 1; COND(c[D_CBC_256_AES][j]); count++)
1257 AES_cbc_encrypt(buf, buf,
1258 (unsigned long) lengths[j], &aes_ks3,
1259 iv, AES_ENCRYPT);
1260 d = Time_F(STOP);
1261 print_result(D_CBC_256_AES, j, count, d);
1262 }
1263 }
1264 if (doit[D_IGE_128_AES]) {
1265 for (j = 0; j < SIZE_NUM; j++) {
1266 print_message(names[D_IGE_128_AES], c[D_IGE_128_AES][j], lengths[j]);
1267 Time_F(START);
1268 for (count = 0, run = 1; COND(c[D_IGE_128_AES][j]); count++)
1269 AES_ige_encrypt(buf, buf2,
1270 (unsigned long) lengths[j], &aes_ks1,
1271 iv, AES_ENCRYPT);
1272 d = Time_F(STOP);
1273 print_result(D_IGE_128_AES, j, count, d);
1274 }
1275 }
1276 if (doit[D_IGE_192_AES]) {
1277 for (j = 0; j < SIZE_NUM; j++) {
1278 print_message(names[D_IGE_192_AES], c[D_IGE_192_AES][j], lengths[j]);
1279 Time_F(START);
1280 for (count = 0, run = 1; COND(c[D_IGE_192_AES][j]); count++)
1281 AES_ige_encrypt(buf, buf2,
1282 (unsigned long) lengths[j], &aes_ks2,
1283 iv, AES_ENCRYPT);
1284 d = Time_F(STOP);
1285 print_result(D_IGE_192_AES, j, count, d);
1286 }
1287 }
1288 if (doit[D_IGE_256_AES]) {
1289 for (j = 0; j < SIZE_NUM; j++) {
1290 print_message(names[D_IGE_256_AES], c[D_IGE_256_AES][j], lengths[j]);
1291 Time_F(START);
1292 for (count = 0, run = 1; COND(c[D_IGE_256_AES][j]); count++)
1293 AES_ige_encrypt(buf, buf2,
1294 (unsigned long) lengths[j], &aes_ks3,
1295 iv, AES_ENCRYPT);
1296 d = Time_F(STOP);
1297 print_result(D_IGE_256_AES, j, count, d);
1298 }
1299 }
1300 if (doit[D_GHASH]) {
1301 GCM128_CONTEXT *ctx = CRYPTO_gcm128_new(&aes_ks1, (block128_f) AES_encrypt);
1302 CRYPTO_gcm128_setiv(ctx, (unsigned char *) "0123456789ab", 12);
1303
1304 for (j = 0; j < SIZE_NUM; j++) {
1305 print_message(names[D_GHASH], c[D_GHASH][j], lengths[j]);
1306 Time_F(START);
1307 for (count = 0, run = 1; COND(c[D_GHASH][j]); count++)
1308 CRYPTO_gcm128_aad(ctx, buf, lengths[j]);
1309 d = Time_F(STOP);
1310 print_result(D_GHASH, j, count, d);
1311 }
1312 CRYPTO_gcm128_release(ctx);
1313 }
1314#endif
1315#ifndef OPENSSL_NO_CAMELLIA
1316 if (doit[D_CBC_128_CML]) {
1317 for (j = 0; j < SIZE_NUM; j++) {
1318 print_message(names[D_CBC_128_CML], c[D_CBC_128_CML][j], lengths[j]);
1319 Time_F(START);
1320 for (count = 0, run = 1; COND(c[D_CBC_128_CML][j]); count++)
1321 Camellia_cbc_encrypt(buf, buf,
1322 (unsigned long) lengths[j], &camellia_ks1,
1323 iv, CAMELLIA_ENCRYPT);
1324 d = Time_F(STOP);
1325 print_result(D_CBC_128_CML, j, count, d);
1326 }
1327 }
1328 if (doit[D_CBC_192_CML]) {
1329 for (j = 0; j < SIZE_NUM; j++) {
1330 print_message(names[D_CBC_192_CML], c[D_CBC_192_CML][j], lengths[j]);
1331 Time_F(START);
1332 for (count = 0, run = 1; COND(c[D_CBC_192_CML][j]); count++)
1333 Camellia_cbc_encrypt(buf, buf,
1334 (unsigned long) lengths[j], &camellia_ks2,
1335 iv, CAMELLIA_ENCRYPT);
1336 d = Time_F(STOP);
1337 print_result(D_CBC_192_CML, j, count, d);
1338 }
1339 }
1340 if (doit[D_CBC_256_CML]) {
1341 for (j = 0; j < SIZE_NUM; j++) {
1342 print_message(names[D_CBC_256_CML], c[D_CBC_256_CML][j], lengths[j]);
1343 Time_F(START);
1344 for (count = 0, run = 1; COND(c[D_CBC_256_CML][j]); count++)
1345 Camellia_cbc_encrypt(buf, buf,
1346 (unsigned long) lengths[j], &camellia_ks3,
1347 iv, CAMELLIA_ENCRYPT);
1348 d = Time_F(STOP);
1349 print_result(D_CBC_256_CML, j, count, d);
1350 }
1351 }
1352#endif
1353#ifndef OPENSSL_NO_IDEA
1354 if (doit[D_CBC_IDEA]) {
1355 for (j = 0; j < SIZE_NUM; j++) {
1356 print_message(names[D_CBC_IDEA], c[D_CBC_IDEA][j], lengths[j]);
1357 Time_F(START);
1358 for (count = 0, run = 1; COND(c[D_CBC_IDEA][j]); count++)
1359 idea_cbc_encrypt(buf, buf,
1360 (unsigned long) lengths[j], &idea_ks,
1361 iv, IDEA_ENCRYPT);
1362 d = Time_F(STOP);
1363 print_result(D_CBC_IDEA, j, count, d);
1364 }
1365 }
1366#endif
1367#ifndef OPENSSL_NO_RC2
1368 if (doit[D_CBC_RC2]) {
1369 for (j = 0; j < SIZE_NUM; j++) {
1370 print_message(names[D_CBC_RC2], c[D_CBC_RC2][j], lengths[j]);
1371 Time_F(START);
1372 for (count = 0, run = 1; COND(c[D_CBC_RC2][j]); count++)
1373 RC2_cbc_encrypt(buf, buf,
1374 (unsigned long) lengths[j], &rc2_ks,
1375 iv, RC2_ENCRYPT);
1376 d = Time_F(STOP);
1377 print_result(D_CBC_RC2, j, count, d);
1378 }
1379 }
1380#endif
1381#ifndef OPENSSL_NO_RC5
1382 if (doit[D_CBC_RC5]) {
1383 for (j = 0; j < SIZE_NUM; j++) {
1384 print_message(names[D_CBC_RC5], c[D_CBC_RC5][j], lengths[j]);
1385 Time_F(START);
1386 for (count = 0, run = 1; COND(c[D_CBC_RC5][j]); count++)
1387 RC5_32_cbc_encrypt(buf, buf,
1388 (unsigned long) lengths[j], &rc5_ks,
1389 iv, RC5_ENCRYPT);
1390 d = Time_F(STOP);
1391 print_result(D_CBC_RC5, j, count, d);
1392 }
1393 }
1394#endif
1395#ifndef OPENSSL_NO_BF
1396 if (doit[D_CBC_BF]) {
1397 for (j = 0; j < SIZE_NUM; j++) {
1398 print_message(names[D_CBC_BF], c[D_CBC_BF][j], lengths[j]);
1399 Time_F(START);
1400 for (count = 0, run = 1; COND(c[D_CBC_BF][j]); count++)
1401 BF_cbc_encrypt(buf, buf,
1402 (unsigned long) lengths[j], &bf_ks,
1403 iv, BF_ENCRYPT);
1404 d = Time_F(STOP);
1405 print_result(D_CBC_BF, j, count, d);
1406 }
1407 }
1408#endif
1409#ifndef OPENSSL_NO_CAST
1410 if (doit[D_CBC_CAST]) {
1411 for (j = 0; j < SIZE_NUM; j++) {
1412 print_message(names[D_CBC_CAST], c[D_CBC_CAST][j], lengths[j]);
1413 Time_F(START);
1414 for (count = 0, run = 1; COND(c[D_CBC_CAST][j]); count++)
1415 CAST_cbc_encrypt(buf, buf,
1416 (unsigned long) lengths[j], &cast_ks,
1417 iv, CAST_ENCRYPT);
1418 d = Time_F(STOP);
1419 print_result(D_CBC_CAST, j, count, d);
1420 }
1421 }
1422#endif
1423
1424 if (doit[D_EVP]) {
1425 for (j = 0; j < SIZE_NUM; j++) {
1426 if (evp_cipher) {
1427 EVP_CIPHER_CTX ctx;
1428 int outl;
1429
1430 names[D_EVP] = OBJ_nid2ln(evp_cipher->nid);
1431 /*
1432 * -O3 -fschedule-insns messes up an
1433 * optimization here! names[D_EVP] somehow
1434 * becomes NULL
1435 */
1436 print_message(names[D_EVP], save_count,
1437 lengths[j]);
1438
1439 EVP_CIPHER_CTX_init(&ctx);
1440 if (decrypt)
1441 EVP_DecryptInit_ex(&ctx, evp_cipher, NULL, key16, iv);
1442 else
1443 EVP_EncryptInit_ex(&ctx, evp_cipher, NULL, key16, iv);
1444 EVP_CIPHER_CTX_set_padding(&ctx, 0);
1445
1446 Time_F(START);
1447 if (decrypt)
1448 for (count = 0, run = 1; COND(save_count * 4 * lengths[0] / lengths[j]); count++)
1449 EVP_DecryptUpdate(&ctx, buf, &outl, buf, lengths[j]);
1450 else
1451 for (count = 0, run = 1; COND(save_count * 4 * lengths[0] / lengths[j]); count++)
1452 EVP_EncryptUpdate(&ctx, buf, &outl, buf, lengths[j]);
1453 if (decrypt)
1454 EVP_DecryptFinal_ex(&ctx, buf, &outl);
1455 else
1456 EVP_EncryptFinal_ex(&ctx, buf, &outl);
1457 d = Time_F(STOP);
1458 EVP_CIPHER_CTX_cleanup(&ctx);
1459 }
1460 if (evp_md) {
1461 names[D_EVP] = OBJ_nid2ln(evp_md->type);
1462 print_message(names[D_EVP], save_count,
1463 lengths[j]);
1464
1465 Time_F(START);
1466 for (count = 0, run = 1; COND(save_count * 4 * lengths[0] / lengths[j]); count++)
1467 EVP_Digest(buf, lengths[j], &(md[0]), NULL, evp_md, NULL);
1468
1469 d = Time_F(STOP);
1470 }
1471 print_result(D_EVP, j, count, d);
1472 }
1473 }
1474 RAND_pseudo_bytes(buf, 36);
1475 for (j = 0; j < RSA_NUM; j++) {
1476 int ret;
1477 if (!rsa_doit[j])
1478 continue;
1479 ret = RSA_sign(NID_md5_sha1, buf, 36, buf2, &rsa_num, rsa_key[j]);
1480 if (ret == 0) {
1481 BIO_printf(bio_err, "RSA sign failure. No RSA sign will be done.\n");
1482 ERR_print_errors(bio_err);
1483 rsa_count = 1;
1484 } else {
1485 pkey_print_message("private", "rsa",
1486 rsa_c[j][0], rsa_bits[j],
1487 RSA_SECONDS);
1488/* RSA_blinding_on(rsa_key[j],NULL); */
1489 Time_F(START);
1490 for (count = 0, run = 1; COND(rsa_c[j][0]); count++) {
1491 ret = RSA_sign(NID_md5_sha1, buf, 36, buf2,
1492 &rsa_num, rsa_key[j]);
1493 if (ret == 0) {
1494 BIO_printf(bio_err,
1495 "RSA sign failure\n");
1496 ERR_print_errors(bio_err);
1497 count = 1;
1498 break;
1499 }
1500 }
1501 d = Time_F(STOP);
1502 BIO_printf(bio_err, mr ? "+R1:%ld:%d:%.2f\n"
1503 : "%ld %d bit private RSA's in %.2fs\n",
1504 count, rsa_bits[j], d);
1505 rsa_results[j][0] = d / (double) count;
1506 rsa_count = count;
1507 }
1508
1509#if 1
1510 ret = RSA_verify(NID_md5_sha1, buf, 36, buf2, rsa_num, rsa_key[j]);
1511 if (ret <= 0) {
1512 BIO_printf(bio_err, "RSA verify failure. No RSA verify will be done.\n");
1513 ERR_print_errors(bio_err);
1514 rsa_doit[j] = 0;
1515 } else {
1516 pkey_print_message("public", "rsa",
1517 rsa_c[j][1], rsa_bits[j],
1518 RSA_SECONDS);
1519 Time_F(START);
1520 for (count = 0, run = 1; COND(rsa_c[j][1]); count++) {
1521 ret = RSA_verify(NID_md5_sha1, buf, 36, buf2,
1522 rsa_num, rsa_key[j]);
1523 if (ret <= 0) {
1524 BIO_printf(bio_err,
1525 "RSA verify failure\n");
1526 ERR_print_errors(bio_err);
1527 count = 1;
1528 break;
1529 }
1530 }
1531 d = Time_F(STOP);
1532 BIO_printf(bio_err, mr ? "+R2:%ld:%d:%.2f\n"
1533 : "%ld %d bit public RSA's in %.2fs\n",
1534 count, rsa_bits[j], d);
1535 rsa_results[j][1] = d / (double) count;
1536 }
1537#endif
1538
1539 if (rsa_count <= 1) {
1540 /* if longer than 10s, don't do any more */
1541 for (j++; j < RSA_NUM; j++)
1542 rsa_doit[j] = 0;
1543 }
1544 }
1545
1546 RAND_pseudo_bytes(buf, 20);
1547 for (j = 0; j < DSA_NUM; j++) {
1548 unsigned int kk;
1549 int ret;
1550
1551 if (!dsa_doit[j])
1552 continue;
1553/* DSA_generate_key(dsa_key[j]); */
1554/* DSA_sign_setup(dsa_key[j],NULL); */
1555 ret = DSA_sign(EVP_PKEY_DSA, buf, 20, buf2,
1556 &kk, dsa_key[j]);
1557 if (ret == 0) {
1558 BIO_printf(bio_err, "DSA sign failure. No DSA sign will be done.\n");
1559 ERR_print_errors(bio_err);
1560 rsa_count = 1;
1561 } else {
1562 pkey_print_message("sign", "dsa",
1563 dsa_c[j][0], dsa_bits[j],
1564 DSA_SECONDS);
1565 Time_F(START);
1566 for (count = 0, run = 1; COND(dsa_c[j][0]); count++) {
1567 ret = DSA_sign(EVP_PKEY_DSA, buf, 20, buf2,
1568 &kk, dsa_key[j]);
1569 if (ret == 0) {
1570 BIO_printf(bio_err,
1571 "DSA sign failure\n");
1572 ERR_print_errors(bio_err);
1573 count = 1;
1574 break;
1575 }
1576 }
1577 d = Time_F(STOP);
1578 BIO_printf(bio_err, mr ? "+R3:%ld:%d:%.2f\n"
1579 : "%ld %d bit DSA signs in %.2fs\n",
1580 count, dsa_bits[j], d);
1581 dsa_results[j][0] = d / (double) count;
1582 rsa_count = count;
1583 }
1584
1585 ret = DSA_verify(EVP_PKEY_DSA, buf, 20, buf2,
1586 kk, dsa_key[j]);
1587 if (ret <= 0) {
1588 BIO_printf(bio_err, "DSA verify failure. No DSA verify will be done.\n");
1589 ERR_print_errors(bio_err);
1590 dsa_doit[j] = 0;
1591 } else {
1592 pkey_print_message("verify", "dsa",
1593 dsa_c[j][1], dsa_bits[j],
1594 DSA_SECONDS);
1595 Time_F(START);
1596 for (count = 0, run = 1; COND(dsa_c[j][1]); count++) {
1597 ret = DSA_verify(EVP_PKEY_DSA, buf, 20, buf2,
1598 kk, dsa_key[j]);
1599 if (ret <= 0) {
1600 BIO_printf(bio_err,
1601 "DSA verify failure\n");
1602 ERR_print_errors(bio_err);
1603 count = 1;
1604 break;
1605 }
1606 }
1607 d = Time_F(STOP);
1608 BIO_printf(bio_err, mr ? "+R4:%ld:%d:%.2f\n"
1609 : "%ld %d bit DSA verify in %.2fs\n",
1610 count, dsa_bits[j], d);
1611 dsa_results[j][1] = d / (double) count;
1612 }
1613
1614 if (rsa_count <= 1) {
1615 /* if longer than 10s, don't do any more */
1616 for (j++; j < DSA_NUM; j++)
1617 dsa_doit[j] = 0;
1618 }
1619 }
1620
1621 for (j = 0; j < EC_NUM; j++) {
1622 int ret;
1623
1624 if (!ecdsa_doit[j])
1625 continue; /* Ignore Curve */
1626 ecdsa[j] = EC_KEY_new_by_curve_name(test_curves[j]);
1627 if (ecdsa[j] == NULL) {
1628 BIO_printf(bio_err, "ECDSA failure.\n");
1629 ERR_print_errors(bio_err);
1630 rsa_count = 1;
1631 } else {
1632#if 1
1633 EC_KEY_precompute_mult(ecdsa[j], NULL);
1634#endif
1635 /* Perform ECDSA signature test */
1636 EC_KEY_generate_key(ecdsa[j]);
1637 ret = ECDSA_sign(0, buf, 20, ecdsasig,
1638 &ecdsasiglen, ecdsa[j]);
1639 if (ret == 0) {
1640 BIO_printf(bio_err, "ECDSA sign failure. No ECDSA sign will be done.\n");
1641 ERR_print_errors(bio_err);
1642 rsa_count = 1;
1643 } else {
1644 pkey_print_message("sign", "ecdsa",
1645 ecdsa_c[j][0],
1646 test_curves_bits[j],
1647 ECDSA_SECONDS);
1648
1649 Time_F(START);
1650 for (count = 0, run = 1; COND(ecdsa_c[j][0]);
1651 count++) {
1652 ret = ECDSA_sign(0, buf, 20,
1653 ecdsasig, &ecdsasiglen,
1654 ecdsa[j]);
1655 if (ret == 0) {
1656 BIO_printf(bio_err, "ECDSA sign failure\n");
1657 ERR_print_errors(bio_err);
1658 count = 1;
1659 break;
1660 }
1661 }
1662 d = Time_F(STOP);
1663
1664 BIO_printf(bio_err, mr ? "+R5:%ld:%d:%.2f\n" :
1665 "%ld %d bit ECDSA signs in %.2fs \n",
1666 count, test_curves_bits[j], d);
1667 ecdsa_results[j][0] = d / (double) count;
1668 rsa_count = count;
1669 }
1670
1671 /* Perform ECDSA verification test */
1672 ret = ECDSA_verify(0, buf, 20, ecdsasig,
1673 ecdsasiglen, ecdsa[j]);
1674 if (ret != 1) {
1675 BIO_printf(bio_err, "ECDSA verify failure. No ECDSA verify will be done.\n");
1676 ERR_print_errors(bio_err);
1677 ecdsa_doit[j] = 0;
1678 } else {
1679 pkey_print_message("verify", "ecdsa",
1680 ecdsa_c[j][1],
1681 test_curves_bits[j],
1682 ECDSA_SECONDS);
1683 Time_F(START);
1684 for (count = 0, run = 1; COND(ecdsa_c[j][1]); count++) {
1685 ret = ECDSA_verify(0, buf, 20, ecdsasig, ecdsasiglen, ecdsa[j]);
1686 if (ret != 1) {
1687 BIO_printf(bio_err, "ECDSA verify failure\n");
1688 ERR_print_errors(bio_err);
1689 count = 1;
1690 break;
1691 }
1692 }
1693 d = Time_F(STOP);
1694 BIO_printf(bio_err, mr ? "+R6:%ld:%d:%.2f\n"
1695 : "%ld %d bit ECDSA verify in %.2fs\n",
1696 count, test_curves_bits[j], d);
1697 ecdsa_results[j][1] = d / (double) count;
1698 }
1699
1700 if (rsa_count <= 1) {
1701 /* if longer than 10s, don't do any more */
1702 for (j++; j < EC_NUM; j++)
1703 ecdsa_doit[j] = 0;
1704 }
1705 }
1706 }
1707
1708 for (j = 0; j < EC_NUM; j++) {
1709 if (!ecdh_doit[j])
1710 continue;
1711 ecdh_a[j] = EC_KEY_new_by_curve_name(test_curves[j]);
1712 ecdh_b[j] = EC_KEY_new_by_curve_name(test_curves[j]);
1713 if ((ecdh_a[j] == NULL) || (ecdh_b[j] == NULL)) {
1714 BIO_printf(bio_err, "ECDH failure.\n");
1715 ERR_print_errors(bio_err);
1716 rsa_count = 1;
1717 } else {
1718 /* generate two ECDH key pairs */
1719 if (!EC_KEY_generate_key(ecdh_a[j]) ||
1720 !EC_KEY_generate_key(ecdh_b[j])) {
1721 BIO_printf(bio_err, "ECDH key generation failure.\n");
1722 ERR_print_errors(bio_err);
1723 rsa_count = 1;
1724 } else {
1725 /*
1726 * If field size is not more than 24 octets,
1727 * then use SHA-1 hash of result; otherwise,
1728 * use result (see section 4.8 of
1729 * draft-ietf-tls-ecc-03.txt).
1730 */
1731 int field_size, outlen;
1732 void *(*kdf) (const void *in, size_t inlen, void *out, size_t * xoutlen);
1733 field_size = EC_GROUP_get_degree(EC_KEY_get0_group(ecdh_a[j]));
1734 if (field_size <= 24 * 8) {
1735 outlen = KDF1_SHA1_len;
1736 kdf = KDF1_SHA1;
1737 } else {
1738 outlen = (field_size + 7) / 8;
1739 kdf = NULL;
1740 }
1741 secret_size_a = ECDH_compute_key(secret_a, outlen,
1742 EC_KEY_get0_public_key(ecdh_b[j]),
1743 ecdh_a[j], kdf);
1744 secret_size_b = ECDH_compute_key(secret_b, outlen,
1745 EC_KEY_get0_public_key(ecdh_a[j]),
1746 ecdh_b[j], kdf);
1747 if (secret_size_a != secret_size_b)
1748 ecdh_checks = 0;
1749 else
1750 ecdh_checks = 1;
1751
1752 for (secret_idx = 0;
1753 (secret_idx < secret_size_a)
1754 && (ecdh_checks == 1);
1755 secret_idx++) {
1756 if (secret_a[secret_idx] != secret_b[secret_idx])
1757 ecdh_checks = 0;
1758 }
1759
1760 if (ecdh_checks == 0) {
1761 BIO_printf(bio_err, "ECDH computations don't match.\n");
1762 ERR_print_errors(bio_err);
1763 rsa_count = 1;
1764 }
1765 pkey_print_message("", "ecdh",
1766 ecdh_c[j][0],
1767 test_curves_bits[j],
1768 ECDH_SECONDS);
1769 Time_F(START);
1770 for (count = 0, run = 1; COND(ecdh_c[j][0]); count++) {
1771 ECDH_compute_key(secret_a, outlen,
1772 EC_KEY_get0_public_key(ecdh_b[j]),
1773 ecdh_a[j], kdf);
1774 }
1775 d = Time_F(STOP);
1776 BIO_printf(bio_err, mr ? "+R7:%ld:%d:%.2f\n" : "%ld %d-bit ECDH ops in %.2fs\n",
1777 count, test_curves_bits[j], d);
1778 ecdh_results[j][0] = d / (double) count;
1779 rsa_count = count;
1780 }
1781 }
1782
1783
1784 if (rsa_count <= 1) {
1785 /* if longer than 10s, don't do any more */
1786 for (j++; j < EC_NUM; j++)
1787 ecdh_doit[j] = 0;
1788 }
1789 }
1790show_res:
1791 if (!mr) {
1792 fprintf(stdout, "%s\n", SSLeay_version(SSLEAY_VERSION));
1793 fprintf(stdout, "%s\n", SSLeay_version(SSLEAY_BUILT_ON));
1794 printf("options:");
1795 printf("%s ", BN_options());
1796#ifndef OPENSSL_NO_RC4
1797 printf("%s ", RC4_options());
1798#endif
1799#ifndef OPENSSL_NO_DES
1800 printf("%s ", DES_options());
1801#endif
1802#ifndef OPENSSL_NO_AES
1803 printf("%s ", AES_options());
1804#endif
1805#ifndef OPENSSL_NO_IDEA
1806 printf("%s ", idea_options());
1807#endif
1808#ifndef OPENSSL_NO_BF
1809 printf("%s ", BF_options());
1810#endif
1811 fprintf(stdout, "\n%s\n", SSLeay_version(SSLEAY_CFLAGS));
1812 }
1813 if (pr_header) {
1814 if (mr)
1815 fprintf(stdout, "+H");
1816 else {
1817 fprintf(stdout, "The 'numbers' are in 1000s of bytes per second processed.\n");
1818 fprintf(stdout, "type ");
1819 }
1820 for (j = 0; j < SIZE_NUM; j++)
1821 fprintf(stdout, mr ? ":%d" : "%7d bytes", lengths[j]);
1822 fprintf(stdout, "\n");
1823 }
1824 for (k = 0; k < ALGOR_NUM; k++) {
1825 if (!doit[k])
1826 continue;
1827 if (mr)
1828 fprintf(stdout, "+F:%d:%s", k, names[k]);
1829 else
1830 fprintf(stdout, "%-13s", names[k]);
1831 for (j = 0; j < SIZE_NUM; j++) {
1832 if (results[k][j] > 10000 && !mr)
1833 fprintf(stdout, " %11.2fk", results[k][j] / 1e3);
1834 else
1835 fprintf(stdout, mr ? ":%.2f" : " %11.2f ", results[k][j]);
1836 }
1837 fprintf(stdout, "\n");
1838 }
1839 j = 1;
1840 for (k = 0; k < RSA_NUM; k++) {
1841 if (!rsa_doit[k])
1842 continue;
1843 if (j && !mr) {
1844 printf("%18ssign verify sign/s verify/s\n", " ");
1845 j = 0;
1846 }
1847 if (mr)
1848 fprintf(stdout, "+F2:%u:%u:%f:%f\n",
1849 k, rsa_bits[k], rsa_results[k][0],
1850 rsa_results[k][1]);
1851 else
1852 fprintf(stdout, "rsa %4u bits %8.6fs %8.6fs %8.1f %8.1f\n",
1853 rsa_bits[k], rsa_results[k][0], rsa_results[k][1],
1854 1.0 / rsa_results[k][0], 1.0 / rsa_results[k][1]);
1855 }
1856 j = 1;
1857 for (k = 0; k < DSA_NUM; k++) {
1858 if (!dsa_doit[k])
1859 continue;
1860 if (j && !mr) {
1861 printf("%18ssign verify sign/s verify/s\n", " ");
1862 j = 0;
1863 }
1864 if (mr)
1865 fprintf(stdout, "+F3:%u:%u:%f:%f\n",
1866 k, dsa_bits[k], dsa_results[k][0], dsa_results[k][1]);
1867 else
1868 fprintf(stdout, "dsa %4u bits %8.6fs %8.6fs %8.1f %8.1f\n",
1869 dsa_bits[k], dsa_results[k][0], dsa_results[k][1],
1870 1.0 / dsa_results[k][0], 1.0 / dsa_results[k][1]);
1871 }
1872 j = 1;
1873 for (k = 0; k < EC_NUM; k++) {
1874 if (!ecdsa_doit[k])
1875 continue;
1876 if (j && !mr) {
1877 printf("%30ssign verify sign/s verify/s\n", " ");
1878 j = 0;
1879 }
1880 if (mr)
1881 fprintf(stdout, "+F4:%u:%u:%f:%f\n",
1882 k, test_curves_bits[k],
1883 ecdsa_results[k][0], ecdsa_results[k][1]);
1884 else
1885 fprintf(stdout,
1886 "%4u bit ecdsa (%s) %8.4fs %8.4fs %8.1f %8.1f\n",
1887 test_curves_bits[k],
1888 test_curves_names[k],
1889 ecdsa_results[k][0], ecdsa_results[k][1],
1890 1.0 / ecdsa_results[k][0], 1.0 / ecdsa_results[k][1]);
1891 }
1892
1893
1894 j = 1;
1895 for (k = 0; k < EC_NUM; k++) {
1896 if (!ecdh_doit[k])
1897 continue;
1898 if (j && !mr) {
1899 printf("%30sop op/s\n", " ");
1900 j = 0;
1901 }
1902 if (mr)
1903 fprintf(stdout, "+F5:%u:%u:%f:%f\n",
1904 k, test_curves_bits[k],
1905 ecdh_results[k][0], 1.0 / ecdh_results[k][0]);
1906
1907 else
1908 fprintf(stdout, "%4u bit ecdh (%s) %8.4fs %8.1f\n",
1909 test_curves_bits[k],
1910 test_curves_names[k],
1911 ecdh_results[k][0], 1.0 / ecdh_results[k][0]);
1912 }
1913
1914 mret = 0;
1915
1916end:
1917 ERR_print_errors(bio_err);
1918 free(buf);
1919 free(buf2);
1920 for (i = 0; i < RSA_NUM; i++)
1921 if (rsa_key[i] != NULL)
1922 RSA_free(rsa_key[i]);
1923 for (i = 0; i < DSA_NUM; i++)
1924 if (dsa_key[i] != NULL)
1925 DSA_free(dsa_key[i]);
1926
1927 for (i = 0; i < EC_NUM; i++)
1928 if (ecdsa[i] != NULL)
1929 EC_KEY_free(ecdsa[i]);
1930 for (i = 0; i < EC_NUM; i++) {
1931 if (ecdh_a[i] != NULL)
1932 EC_KEY_free(ecdh_a[i]);
1933 if (ecdh_b[i] != NULL)
1934 EC_KEY_free(ecdh_b[i]);
1935 }
1936
1937
1938 return (mret);
1939}
1940
1941static void
1942print_message(const char *s, long num, int length)
1943{
1944 BIO_printf(bio_err, mr ? "+DT:%s:%d:%d\n"
1945 : "Doing %s for %ds on %d size blocks: ", s, SECONDS, length);
1946 (void) BIO_flush(bio_err);
1947 alarm(SECONDS);
1948}
1949
1950static void
1951pkey_print_message(const char *str, const char *str2, long num,
1952 int bits, int tm)
1953{
1954 BIO_printf(bio_err, mr ? "+DTP:%d:%s:%s:%d\n"
1955 : "Doing %d bit %s %s's for %ds: ", bits, str, str2, tm);
1956 (void) BIO_flush(bio_err);
1957 alarm(tm);
1958}
1959
1960static void
1961print_result(int alg, int run_no, int count, double time_used)
1962{
1963 BIO_printf(bio_err, mr ? "+R:%d:%s:%f\n"
1964 : "%d %s's in %.2fs\n", count, names[alg], time_used);
1965 results[alg][run_no] = ((double) count) / time_used * lengths[run_no];
1966}
1967
1968static char *
1969sstrsep(char **string, const char *delim)
1970{
1971 char isdelim[256];
1972 char *token = *string;
1973
1974 if (**string == 0)
1975 return NULL;
1976
1977 memset(isdelim, 0, sizeof isdelim);
1978 isdelim[0] = 1;
1979
1980 while (*delim) {
1981 isdelim[(unsigned char) (*delim)] = 1;
1982 delim++;
1983 }
1984
1985 while (!isdelim[(unsigned char) (**string)]) {
1986 (*string)++;
1987 }
1988
1989 if (**string) {
1990 **string = 0;
1991 (*string)++;
1992 }
1993 return token;
1994}
1995
1996static int
1997do_multi(int multi)
1998{
1999 int n;
2000 int fd[2];
2001 int *fds;
2002 static char sep[] = ":";
2003 const char *errstr = NULL;
2004
2005 fds = reallocarray(NULL, multi, sizeof *fds);
2006 for (n = 0; n < multi; ++n) {
2007 if (pipe(fd) == -1) {
2008 fprintf(stderr, "pipe failure\n");
2009 exit(1);
2010 }
2011 fflush(stdout);
2012 fflush(stderr);
2013 if (fork()) {
2014 close(fd[1]);
2015 fds[n] = fd[0];
2016 } else {
2017 close(fd[0]);
2018 close(1);
2019 if (dup(fd[1]) == -1) {
2020 fprintf(stderr, "dup failed\n");
2021 exit(1);
2022 }
2023 close(fd[1]);
2024 mr = 1;
2025 usertime = 0;
2026 free(fds);
2027 return 0;
2028 }
2029 printf("Forked child %d\n", n);
2030 }
2031
2032 /* for now, assume the pipe is long enough to take all the output */
2033 for (n = 0; n < multi; ++n) {
2034 FILE *f;
2035 char buf[1024];
2036 char *p;
2037
2038 f = fdopen(fds[n], "r");
2039 while (fgets(buf, sizeof buf, f)) {
2040 p = strchr(buf, '\n');
2041 if (p)
2042 *p = '\0';
2043 if (buf[0] != '+') {
2044 fprintf(stderr, "Don't understand line '%s' from child %d\n",
2045 buf, n);
2046 continue;
2047 }
2048 printf("Got: %s from %d\n", buf, n);
2049 if (!strncmp(buf, "+F:", 3)) {
2050 int alg;
2051 int j;
2052
2053 p = buf + 3;
2054 alg = strtonum(sstrsep(&p, sep),
2055 0, ALGOR_NUM - 1, &errstr);
2056 sstrsep(&p, sep);
2057 for (j = 0; j < SIZE_NUM; ++j)
2058 results[alg][j] += atof(sstrsep(&p, sep));
2059 } else if (!strncmp(buf, "+F2:", 4)) {
2060 int k;
2061 double d;
2062
2063 p = buf + 4;
2064 k = strtonum(sstrsep(&p, sep),
2065 0, ALGOR_NUM - 1, &errstr);
2066 sstrsep(&p, sep);
2067
2068 d = atof(sstrsep(&p, sep));
2069 if (n)
2070 rsa_results[k][0] = 1 / (1 / rsa_results[k][0] + 1 / d);
2071 else
2072 rsa_results[k][0] = d;
2073
2074 d = atof(sstrsep(&p, sep));
2075 if (n)
2076 rsa_results[k][1] = 1 / (1 / rsa_results[k][1] + 1 / d);
2077 else
2078 rsa_results[k][1] = d;
2079 } else if (!strncmp(buf, "+F2:", 4)) {
2080 int k;
2081 double d;
2082
2083 p = buf + 4;
2084 k = strtonum(sstrsep(&p, sep),
2085 0, ALGOR_NUM - 1, &errstr);
2086 sstrsep(&p, sep);
2087
2088 d = atof(sstrsep(&p, sep));
2089 if (n)
2090 rsa_results[k][0] = 1 / (1 / rsa_results[k][0] + 1 / d);
2091 else
2092 rsa_results[k][0] = d;
2093
2094 d = atof(sstrsep(&p, sep));
2095 if (n)
2096 rsa_results[k][1] = 1 / (1 / rsa_results[k][1] + 1 / d);
2097 else
2098 rsa_results[k][1] = d;
2099 }
2100 else if (!strncmp(buf, "+F3:", 4)) {
2101 int k;
2102 double d;
2103
2104 p = buf + 4;
2105 k = strtonum(sstrsep(&p, sep),
2106 0, ALGOR_NUM - 1, &errstr);
2107 sstrsep(&p, sep);
2108
2109 d = atof(sstrsep(&p, sep));
2110 if (n)
2111 dsa_results[k][0] = 1 / (1 / dsa_results[k][0] + 1 / d);
2112 else
2113 dsa_results[k][0] = d;
2114
2115 d = atof(sstrsep(&p, sep));
2116 if (n)
2117 dsa_results[k][1] = 1 / (1 / dsa_results[k][1] + 1 / d);
2118 else
2119 dsa_results[k][1] = d;
2120 }
2121 else if (!strncmp(buf, "+F4:", 4)) {
2122 int k;
2123 double d;
2124
2125 p = buf + 4;
2126 k = strtonum(sstrsep(&p, sep),
2127 0, ALGOR_NUM - 1, &errstr);
2128 sstrsep(&p, sep);
2129
2130 d = atof(sstrsep(&p, sep));
2131 if (n)
2132 ecdsa_results[k][0] = 1 / (1 / ecdsa_results[k][0] + 1 / d);
2133 else
2134 ecdsa_results[k][0] = d;
2135
2136 d = atof(sstrsep(&p, sep));
2137 if (n)
2138 ecdsa_results[k][1] = 1 / (1 / ecdsa_results[k][1] + 1 / d);
2139 else
2140 ecdsa_results[k][1] = d;
2141 }
2142
2143 else if (!strncmp(buf, "+F5:", 4)) {
2144 int k;
2145 double d;
2146
2147 p = buf + 4;
2148 k = strtonum(sstrsep(&p, sep),
2149 0, ALGOR_NUM - 1, &errstr);
2150 sstrsep(&p, sep);
2151
2152 d = atof(sstrsep(&p, sep));
2153 if (n)
2154 ecdh_results[k][0] = 1 / (1 / ecdh_results[k][0] + 1 / d);
2155 else
2156 ecdh_results[k][0] = d;
2157
2158 }
2159
2160 else if (!strncmp(buf, "+H:", 3)) {
2161 } else
2162 fprintf(stderr, "Unknown type '%s' from child %d\n", buf, n);
2163 }
2164
2165 fclose(f);
2166 }
2167 free(fds);
2168 return 1;
2169}
2170#endif
diff --git a/src/usr.bin/openssl/spkac.c b/src/usr.bin/openssl/spkac.c
new file mode 100644
index 0000000000..266ed57662
--- /dev/null
+++ b/src/usr.bin/openssl/spkac.c
@@ -0,0 +1,284 @@
1/* $OpenBSD: spkac.c,v 1.1 2014/08/26 17:47:25 jsing Exp $ */
2/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3 * project 1999. Based on an original idea by Massimiliano Pala
4 * (madwolf@openca.org).
5 */
6/* ====================================================================
7 * Copyright (c) 1999 The OpenSSL Project. All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 *
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 *
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in
18 * the documentation and/or other materials provided with the
19 * distribution.
20 *
21 * 3. All advertising materials mentioning features or use of this
22 * software must display the following acknowledgment:
23 * "This product includes software developed by the OpenSSL Project
24 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25 *
26 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27 * endorse or promote products derived from this software without
28 * prior written permission. For written permission, please contact
29 * licensing@OpenSSL.org.
30 *
31 * 5. Products derived from this software may not be called "OpenSSL"
32 * nor may "OpenSSL" appear in their names without prior written
33 * permission of the OpenSSL Project.
34 *
35 * 6. Redistributions of any form whatsoever must retain the following
36 * acknowledgment:
37 * "This product includes software developed by the OpenSSL Project
38 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39 *
40 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
44 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51 * OF THE POSSIBILITY OF SUCH DAMAGE.
52 * ====================================================================
53 *
54 * This product includes cryptographic software written by Eric Young
55 * (eay@cryptsoft.com). This product includes software written by Tim
56 * Hudson (tjh@cryptsoft.com).
57 *
58 */
59
60#include <stdio.h>
61#include <stdlib.h>
62#include <string.h>
63#include <time.h>
64
65#include "apps.h"
66
67#include <openssl/bio.h>
68#include <openssl/conf.h>
69#include <openssl/err.h>
70#include <openssl/evp.h>
71#include <openssl/lhash.h>
72#include <openssl/pem.h>
73#include <openssl/x509.h>
74
75/* -in arg - input file - default stdin
76 * -out arg - output file - default stdout
77 */
78
79int spkac_main(int, char **);
80
81int
82spkac_main(int argc, char **argv)
83{
84 ENGINE *e = NULL;
85 int i, badops = 0, ret = 1;
86 BIO *in = NULL, *out = NULL;
87 int verify = 0, noout = 0, pubkey = 0;
88 char *infile = NULL, *outfile = NULL, *prog;
89 char *passargin = NULL, *passin = NULL;
90 const char *spkac = "SPKAC", *spksect = "default";
91 char *spkstr = NULL;
92 char *challenge = NULL, *keyfile = NULL;
93 CONF *conf = NULL;
94 NETSCAPE_SPKI *spki = NULL;
95 EVP_PKEY *pkey = NULL;
96#ifndef OPENSSL_NO_ENGINE
97 char *engine = NULL;
98#endif
99
100 prog = argv[0];
101 argc--;
102 argv++;
103 while (argc >= 1) {
104 if (strcmp(*argv, "-in") == 0) {
105 if (--argc < 1)
106 goto bad;
107 infile = *(++argv);
108 } else if (strcmp(*argv, "-out") == 0) {
109 if (--argc < 1)
110 goto bad;
111 outfile = *(++argv);
112 } else if (strcmp(*argv, "-passin") == 0) {
113 if (--argc < 1)
114 goto bad;
115 passargin = *(++argv);
116 } else if (strcmp(*argv, "-key") == 0) {
117 if (--argc < 1)
118 goto bad;
119 keyfile = *(++argv);
120 } else if (strcmp(*argv, "-challenge") == 0) {
121 if (--argc < 1)
122 goto bad;
123 challenge = *(++argv);
124 } else if (strcmp(*argv, "-spkac") == 0) {
125 if (--argc < 1)
126 goto bad;
127 spkac = *(++argv);
128 } else if (strcmp(*argv, "-spksect") == 0) {
129 if (--argc < 1)
130 goto bad;
131 spksect = *(++argv);
132 }
133#ifndef OPENSSL_NO_ENGINE
134 else if (strcmp(*argv, "-engine") == 0) {
135 if (--argc < 1)
136 goto bad;
137 engine = *(++argv);
138 }
139#endif
140 else if (strcmp(*argv, "-noout") == 0)
141 noout = 1;
142 else if (strcmp(*argv, "-pubkey") == 0)
143 pubkey = 1;
144 else if (strcmp(*argv, "-verify") == 0)
145 verify = 1;
146 else
147 badops = 1;
148 argc--;
149 argv++;
150 }
151
152 if (badops) {
153bad:
154 BIO_printf(bio_err, "%s [options]\n", prog);
155 BIO_printf(bio_err, "where options are\n");
156 BIO_printf(bio_err, " -in arg input file\n");
157 BIO_printf(bio_err, " -out arg output file\n");
158 BIO_printf(bio_err, " -key arg create SPKAC using private key\n");
159 BIO_printf(bio_err, " -passin arg input file pass phrase source\n");
160 BIO_printf(bio_err, " -challenge arg challenge string\n");
161 BIO_printf(bio_err, " -spkac arg alternative SPKAC name\n");
162 BIO_printf(bio_err, " -noout don't print SPKAC\n");
163 BIO_printf(bio_err, " -pubkey output public key\n");
164 BIO_printf(bio_err, " -verify verify SPKAC signature\n");
165#ifndef OPENSSL_NO_ENGINE
166 BIO_printf(bio_err, " -engine e use engine e, possibly a hardware device.\n");
167#endif
168 goto end;
169 }
170 ERR_load_crypto_strings();
171 if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) {
172 BIO_printf(bio_err, "Error getting password\n");
173 goto end;
174 }
175#ifndef OPENSSL_NO_ENGINE
176 e = setup_engine(bio_err, engine, 0);
177#endif
178
179 if (keyfile) {
180 pkey = load_key(bio_err,
181 strcmp(keyfile, "-") ? keyfile : NULL,
182 FORMAT_PEM, 1, passin, e, "private key");
183 if (!pkey) {
184 goto end;
185 }
186 spki = NETSCAPE_SPKI_new();
187 if (challenge)
188 ASN1_STRING_set(spki->spkac->challenge,
189 challenge, (int) strlen(challenge));
190 NETSCAPE_SPKI_set_pubkey(spki, pkey);
191 NETSCAPE_SPKI_sign(spki, pkey, EVP_md5());
192 spkstr = NETSCAPE_SPKI_b64_encode(spki);
193 if (spkstr == NULL) {
194 BIO_printf(bio_err, "Error encoding SPKAC\n");
195 ERR_print_errors(bio_err);
196 goto end;
197 }
198
199 if (outfile)
200 out = BIO_new_file(outfile, "w");
201 else
202 out = BIO_new_fp(stdout, BIO_NOCLOSE);
203
204 if (!out) {
205 BIO_printf(bio_err, "Error opening output file\n");
206 ERR_print_errors(bio_err);
207 } else {
208 BIO_printf(out, "SPKAC=%s\n", spkstr);
209 ret = 0;
210 }
211 free(spkstr);
212 goto end;
213 }
214 if (infile)
215 in = BIO_new_file(infile, "r");
216 else
217 in = BIO_new_fp(stdin, BIO_NOCLOSE);
218
219 if (!in) {
220 BIO_printf(bio_err, "Error opening input file\n");
221 ERR_print_errors(bio_err);
222 goto end;
223 }
224 conf = NCONF_new(NULL);
225 i = NCONF_load_bio(conf, in, NULL);
226
227 if (!i) {
228 BIO_printf(bio_err, "Error parsing config file\n");
229 ERR_print_errors(bio_err);
230 goto end;
231 }
232 spkstr = NCONF_get_string(conf, spksect, spkac);
233
234 if (!spkstr) {
235 BIO_printf(bio_err, "Can't find SPKAC called \"%s\"\n", spkac);
236 ERR_print_errors(bio_err);
237 goto end;
238 }
239 spki = NETSCAPE_SPKI_b64_decode(spkstr, -1);
240
241 if (!spki) {
242 BIO_printf(bio_err, "Error loading SPKAC\n");
243 ERR_print_errors(bio_err);
244 goto end;
245 }
246 if (outfile)
247 out = BIO_new_file(outfile, "w");
248 else {
249 out = BIO_new_fp(stdout, BIO_NOCLOSE);
250 }
251
252 if (!out) {
253 BIO_printf(bio_err, "Error opening output file\n");
254 ERR_print_errors(bio_err);
255 goto end;
256 }
257 if (!noout)
258 NETSCAPE_SPKI_print(out, spki);
259 pkey = NETSCAPE_SPKI_get_pubkey(spki);
260 if (verify) {
261 i = NETSCAPE_SPKI_verify(spki, pkey);
262 if (i > 0)
263 BIO_printf(bio_err, "Signature OK\n");
264 else {
265 BIO_printf(bio_err, "Signature Failure\n");
266 ERR_print_errors(bio_err);
267 goto end;
268 }
269 }
270 if (pubkey)
271 PEM_write_bio_PUBKEY(out, pkey);
272
273 ret = 0;
274
275end:
276 NCONF_free(conf);
277 NETSCAPE_SPKI_free(spki);
278 BIO_free(in);
279 BIO_free_all(out);
280 EVP_PKEY_free(pkey);
281 free(passin);
282
283 return (ret);
284}
diff --git a/src/usr.bin/openssl/testdsa.h b/src/usr.bin/openssl/testdsa.h
new file mode 100644
index 0000000000..1bbb09ca70
--- /dev/null
+++ b/src/usr.bin/openssl/testdsa.h
@@ -0,0 +1,221 @@
1/* $OpenBSD: testdsa.h,v 1.1 2014/08/26 17:47:25 jsing Exp $ */
2
3DSA *get_dsa512(void);
4DSA *get_dsa1024(void);
5DSA *get_dsa2048(void);
6
7static unsigned char dsa512_priv[] = {
8 0x65, 0xe5, 0xc7, 0x38, 0x60, 0x24, 0xb5, 0x89, 0xd4, 0x9c, 0xeb, 0x4c,
9 0x9c, 0x1d, 0x7a, 0x22, 0xbd, 0xd1, 0xc2, 0xd2,
10};
11static unsigned char dsa512_pub[] = {
12 0x00, 0x95, 0xa7, 0x0d, 0xec, 0x93, 0x68, 0xba, 0x5f, 0xf7, 0x5f, 0x07,
13 0xf2, 0x3b, 0xad, 0x6b, 0x01, 0xdc, 0xbe, 0xec, 0xde, 0x04, 0x7a, 0x3a,
14 0x27, 0xb3, 0xec, 0x49, 0xfd, 0x08, 0x43, 0x3d, 0x7e, 0xa8, 0x2c, 0x5e,
15 0x7b, 0xbb, 0xfc, 0xf4, 0x6e, 0xeb, 0x6c, 0xb0, 0x6e, 0xf8, 0x02, 0x12,
16 0x8c, 0x38, 0x5d, 0x83, 0x56, 0x7d, 0xee, 0x53, 0x05, 0x3e, 0x24, 0x84,
17 0xbe, 0xba, 0x0a, 0x6b, 0xc8,
18};
19static unsigned char dsa512_p[] = {
20 0x9D, 0x1B, 0x69, 0x8E, 0x26, 0xDB, 0xF2, 0x2B, 0x11, 0x70, 0x19, 0x86,
21 0xF6, 0x19, 0xC8, 0xF8, 0x19, 0xF2, 0x18, 0x53, 0x94, 0x46, 0x06, 0xD0,
22 0x62, 0x50, 0x33, 0x4B, 0x02, 0x3C, 0x52, 0x30, 0x03, 0x8B, 0x3B, 0xF9,
23 0x5F, 0xD1, 0x24, 0x06, 0x4F, 0x7B, 0x4C, 0xBA, 0xAA, 0x40, 0x9B, 0xFD,
24 0x96, 0xE4, 0x37, 0x33, 0xBB, 0x2D, 0x5A, 0xD7, 0x5A, 0x11, 0x40, 0x66,
25 0xA2, 0x76, 0x7D, 0x31,
26};
27static unsigned char dsa512_q[] = {
28 0xFB, 0x53, 0xEF, 0x50, 0xB4, 0x40, 0x92, 0x31, 0x56, 0x86, 0x53, 0x7A,
29 0xE8, 0x8B, 0x22, 0x9A, 0x49, 0xFB, 0x71, 0x8F,
30};
31static unsigned char dsa512_g[] = {
32 0x83, 0x3E, 0x88, 0xE5, 0xC5, 0x89, 0x73, 0xCE, 0x3B, 0x6C, 0x01, 0x49,
33 0xBF, 0xB3, 0xC7, 0x9F, 0x0A, 0xEA, 0x44, 0x91, 0xE5, 0x30, 0xAA, 0xD9,
34 0xBE, 0x5B, 0x5F, 0xB7, 0x10, 0xD7, 0x89, 0xB7, 0x8E, 0x74, 0xFB, 0xCF,
35 0x29, 0x1E, 0xEB, 0xA8, 0x2C, 0x54, 0x51, 0xB8, 0x10, 0xDE, 0xA0, 0xCE,
36 0x2F, 0xCC, 0x24, 0x6B, 0x90, 0x77, 0xDE, 0xA2, 0x68, 0xA6, 0x52, 0x12,
37 0xA2, 0x03, 0x9D, 0x20,
38};
39
40DSA *
41get_dsa512()
42{
43 DSA *dsa;
44
45 if ((dsa = DSA_new()) == NULL)
46 return (NULL);
47 dsa->priv_key = BN_bin2bn(dsa512_priv, sizeof(dsa512_priv), NULL);
48 dsa->pub_key = BN_bin2bn(dsa512_pub, sizeof(dsa512_pub), NULL);
49 dsa->p = BN_bin2bn(dsa512_p, sizeof(dsa512_p), NULL);
50 dsa->q = BN_bin2bn(dsa512_q, sizeof(dsa512_q), NULL);
51 dsa->g = BN_bin2bn(dsa512_g, sizeof(dsa512_g), NULL);
52 if ((dsa->priv_key == NULL) || (dsa->pub_key == NULL) ||
53 (dsa->p == NULL) || (dsa->q == NULL) || (dsa->g == NULL))
54 return (NULL);
55 return (dsa);
56}
57
58static unsigned char dsa1024_priv[] = {
59 0x7d, 0x21, 0xda, 0xbb, 0x62, 0x15, 0x47, 0x36, 0x07, 0x67, 0x12, 0xe8,
60 0x8c, 0xaa, 0x1c, 0xcd, 0x38, 0x12, 0x61, 0x18,
61};
62static unsigned char dsa1024_pub[] = {
63 0x3c, 0x4e, 0x9c, 0x2a, 0x7f, 0x16, 0xc1, 0x25, 0xeb, 0xac, 0x78, 0x63,
64 0x90, 0x14, 0x8c, 0x8b, 0xf4, 0x68, 0x43, 0x3c, 0x2d, 0xee, 0x65, 0x50,
65 0x7d, 0x9c, 0x8f, 0x8c, 0x8a, 0x51, 0xd6, 0x11, 0x2b, 0x99, 0xaf, 0x1e,
66 0x90, 0x97, 0xb5, 0xd3, 0xa6, 0x20, 0x25, 0xd6, 0xfe, 0x43, 0x02, 0xd5,
67 0x91, 0x7d, 0xa7, 0x8c, 0xdb, 0xc9, 0x85, 0xa3, 0x36, 0x48, 0xf7, 0x68,
68 0xaa, 0x60, 0xb1, 0xf7, 0x05, 0x68, 0x3a, 0xa3, 0x3f, 0xd3, 0x19, 0x82,
69 0xd8, 0x82, 0x7a, 0x77, 0xfb, 0xef, 0xf4, 0x15, 0x0a, 0xeb, 0x06, 0x04,
70 0x7f, 0x53, 0x07, 0x0c, 0xbc, 0xcb, 0x2d, 0x83, 0xdb, 0x3e, 0xd1, 0x28,
71 0xa5, 0xa1, 0x31, 0xe0, 0x67, 0xfa, 0x50, 0xde, 0x9b, 0x07, 0x83, 0x7e,
72 0x2c, 0x0b, 0xc3, 0x13, 0x50, 0x61, 0xe5, 0xad, 0xbd, 0x36, 0xb8, 0x97,
73 0x4e, 0x40, 0x7d, 0xe8, 0x83, 0x0d, 0xbc, 0x4b
74};
75static unsigned char dsa1024_p[] = {
76 0xA7, 0x3F, 0x6E, 0x85, 0xBF, 0x41, 0x6A, 0x29, 0x7D, 0xF0, 0x9F, 0x47,
77 0x19, 0x30, 0x90, 0x9A, 0x09, 0x1D, 0xDA, 0x6A, 0x33, 0x1E, 0xC5, 0x3D,
78 0x86, 0x96, 0xB3, 0x15, 0xE0, 0x53, 0x2E, 0x8F, 0xE0, 0x59, 0x82, 0x73,
79 0x90, 0x3E, 0x75, 0x31, 0x99, 0x47, 0x7A, 0x52, 0xFB, 0x85, 0xE4, 0xD9,
80 0xA6, 0x7B, 0x38, 0x9B, 0x68, 0x8A, 0x84, 0x9B, 0x87, 0xC6, 0x1E, 0xB5,
81 0x7E, 0x86, 0x4B, 0x53, 0x5B, 0x59, 0xCF, 0x71, 0x65, 0x19, 0x88, 0x6E,
82 0xCE, 0x66, 0xAE, 0x6B, 0x88, 0x36, 0xFB, 0xEC, 0x28, 0xDC, 0xC2, 0xD7,
83 0xA5, 0xBB, 0xE5, 0x2C, 0x39, 0x26, 0x4B, 0xDA, 0x9A, 0x70, 0x18, 0x95,
84 0x37, 0x95, 0x10, 0x56, 0x23, 0xF6, 0x15, 0xED, 0xBA, 0x04, 0x5E, 0xDE,
85 0x39, 0x4F, 0xFD, 0xB7, 0x43, 0x1F, 0xB5, 0xA4, 0x65, 0x6F, 0xCD, 0x80,
86 0x11, 0xE4, 0x70, 0x95, 0x5B, 0x50, 0xCD, 0x49,
87};
88static unsigned char dsa1024_q[] = {
89 0xF7, 0x07, 0x31, 0xED, 0xFA, 0x6C, 0x06, 0x03, 0xD5, 0x85, 0x8A, 0x1C,
90 0xAC, 0x9C, 0x65, 0xE7, 0x50, 0x66, 0x65, 0x6F,
91};
92static unsigned char dsa1024_g[] = {
93 0x4D, 0xDF, 0x4C, 0x03, 0xA6, 0x91, 0x8A, 0xF5, 0x19, 0x6F, 0x50, 0x46,
94 0x25, 0x99, 0xE5, 0x68, 0x6F, 0x30, 0xE3, 0x69, 0xE1, 0xE5, 0xB3, 0x5D,
95 0x98, 0xBB, 0x28, 0x86, 0x48, 0xFC, 0xDE, 0x99, 0x04, 0x3F, 0x5F, 0x88,
96 0x0C, 0x9C, 0x73, 0x24, 0x0D, 0x20, 0x5D, 0xB9, 0x2A, 0x9A, 0x3F, 0x18,
97 0x96, 0x27, 0xE4, 0x62, 0x87, 0xC1, 0x7B, 0x74, 0x62, 0x53, 0xFC, 0x61,
98 0x27, 0xA8, 0x7A, 0x91, 0x09, 0x9D, 0xB6, 0xF1, 0x4D, 0x9C, 0x54, 0x0F,
99 0x58, 0x06, 0xEE, 0x49, 0x74, 0x07, 0xCE, 0x55, 0x7E, 0x23, 0xCE, 0x16,
100 0xF6, 0xCA, 0xDC, 0x5A, 0x61, 0x01, 0x7E, 0xC9, 0x71, 0xB5, 0x4D, 0xF6,
101 0xDC, 0x34, 0x29, 0x87, 0x68, 0xF6, 0x5E, 0x20, 0x93, 0xB3, 0xDB, 0xF5,
102 0xE4, 0x09, 0x6C, 0x41, 0x17, 0x95, 0x92, 0xEB, 0x01, 0xB5, 0x73, 0xA5,
103 0x6A, 0x7E, 0xD8, 0x32, 0xED, 0x0E, 0x02, 0xB8,
104};
105
106DSA *
107get_dsa1024()
108{
109 DSA *dsa;
110
111 if ((dsa = DSA_new()) == NULL)
112 return (NULL);
113 dsa->priv_key = BN_bin2bn(dsa1024_priv, sizeof(dsa1024_priv), NULL);
114 dsa->pub_key = BN_bin2bn(dsa1024_pub, sizeof(dsa1024_pub), NULL);
115 dsa->p = BN_bin2bn(dsa1024_p, sizeof(dsa1024_p), NULL);
116 dsa->q = BN_bin2bn(dsa1024_q, sizeof(dsa1024_q), NULL);
117 dsa->g = BN_bin2bn(dsa1024_g, sizeof(dsa1024_g), NULL);
118 if ((dsa->priv_key == NULL) || (dsa->pub_key == NULL) ||
119 (dsa->p == NULL) || (dsa->q == NULL) || (dsa->g == NULL))
120 return (NULL);
121 return (dsa);
122}
123
124static unsigned char dsa2048_priv[] = {
125 0x32, 0x67, 0x92, 0xf6, 0xc4, 0xe2, 0xe2, 0xe8, 0xa0, 0x8b, 0x6b, 0x45,
126 0x0c, 0x8a, 0x76, 0xb0, 0xee, 0xcf, 0x91, 0xa7,
127};
128static unsigned char dsa2048_pub[] = {
129 0x17, 0x8f, 0xa8, 0x11, 0x84, 0x92, 0xec, 0x83, 0x47, 0xc7, 0x6a, 0xb0,
130 0x92, 0xaf, 0x5a, 0x20, 0x37, 0xa3, 0x64, 0x79, 0xd2, 0xd0, 0x3d, 0xcd,
131 0xe0, 0x61, 0x88, 0x88, 0x21, 0xcc, 0x74, 0x5d, 0xce, 0x4c, 0x51, 0x47,
132 0xf0, 0xc5, 0x5c, 0x4c, 0x82, 0x7a, 0xaf, 0x72, 0xad, 0xb9, 0xe0, 0x53,
133 0xf2, 0x78, 0xb7, 0xf0, 0xb5, 0x48, 0x7f, 0x8a, 0x3a, 0x18, 0xd1, 0x9f,
134 0x8b, 0x7d, 0xa5, 0x47, 0xb7, 0x95, 0xab, 0x98, 0xf8, 0x7b, 0x74, 0x50,
135 0x56, 0x8e, 0x57, 0xf0, 0xee, 0xf5, 0xb7, 0xba, 0xab, 0x85, 0x86, 0xf9,
136 0x2b, 0xef, 0x41, 0x56, 0xa0, 0xa4, 0x9f, 0xb7, 0x38, 0x00, 0x46, 0x0a,
137 0xa6, 0xf1, 0xfc, 0x1f, 0xd8, 0x4e, 0x85, 0x44, 0x92, 0x43, 0x21, 0x5d,
138 0x6e, 0xcc, 0xc2, 0xcb, 0x26, 0x31, 0x0d, 0x21, 0xc4, 0xbd, 0x8d, 0x24,
139 0xbc, 0xd9, 0x18, 0x19, 0xd7, 0xdc, 0xf1, 0xe7, 0x93, 0x50, 0x48, 0x03,
140 0x2c, 0xae, 0x2e, 0xe7, 0x49, 0x88, 0x5f, 0x93, 0x57, 0x27, 0x99, 0x36,
141 0xb4, 0x20, 0xab, 0xfc, 0xa7, 0x2b, 0xf2, 0xd9, 0x98, 0xd7, 0xd4, 0x34,
142 0x9d, 0x96, 0x50, 0x58, 0x9a, 0xea, 0x54, 0xf3, 0xee, 0xf5, 0x63, 0x14,
143 0xee, 0x85, 0x83, 0x74, 0x76, 0xe1, 0x52, 0x95, 0xc3, 0xf7, 0xeb, 0x04,
144 0x04, 0x7b, 0xa7, 0x28, 0x1b, 0xcc, 0xea, 0x4a, 0x4e, 0x84, 0xda, 0xd8,
145 0x9c, 0x79, 0xd8, 0x9b, 0x66, 0x89, 0x2f, 0xcf, 0xac, 0xd7, 0x79, 0xf9,
146 0xa9, 0xd8, 0x45, 0x13, 0x78, 0xb9, 0x00, 0x14, 0xc9, 0x7e, 0x22, 0x51,
147 0x86, 0x67, 0xb0, 0x9f, 0x26, 0x11, 0x23, 0xc8, 0x38, 0xd7, 0x70, 0x1d,
148 0x15, 0x8e, 0x4d, 0x4f, 0x95, 0x97, 0x40, 0xa1, 0xc2, 0x7e, 0x01, 0x18,
149 0x72, 0xf4, 0x10, 0xe6, 0x8d, 0x52, 0x16, 0x7f, 0xf2, 0xc9, 0xf8, 0x33,
150 0x8b, 0x33, 0xb7, 0xce,
151};
152static unsigned char dsa2048_p[] = {
153 0xA0, 0x25, 0xFA, 0xAD, 0xF4, 0x8E, 0xB9, 0xE5, 0x99, 0xF3, 0x5D, 0x6F,
154 0x4F, 0x83, 0x34, 0xE2, 0x7E, 0xCF, 0x6F, 0xBF, 0x30, 0xAF, 0x6F, 0x81,
155 0xEB, 0xF8, 0xC4, 0x13, 0xD9, 0xA0, 0x5D, 0x8B, 0x5C, 0x8E, 0xDC, 0xC2,
156 0x1D, 0x0B, 0x41, 0x32, 0xB0, 0x1F, 0xFE, 0xEF, 0x0C, 0xC2, 0xA2, 0x7E,
157 0x68, 0x5C, 0x28, 0x21, 0xE9, 0xF5, 0xB1, 0x58, 0x12, 0x63, 0x4C, 0x19,
158 0x4E, 0xFF, 0x02, 0x4B, 0x92, 0xED, 0xD2, 0x07, 0x11, 0x4D, 0x8C, 0x58,
159 0x16, 0x5C, 0x55, 0x8E, 0xAD, 0xA3, 0x67, 0x7D, 0xB9, 0x86, 0x6E, 0x0B,
160 0xE6, 0x54, 0x6F, 0x40, 0xAE, 0x0E, 0x67, 0x4C, 0xF9, 0x12, 0x5B, 0x3C,
161 0x08, 0x7A, 0xF7, 0xFC, 0x67, 0x86, 0x69, 0xE7, 0x0A, 0x94, 0x40, 0xBF,
162 0x8B, 0x76, 0xFE, 0x26, 0xD1, 0xF2, 0xA1, 0x1A, 0x84, 0xA1, 0x43, 0x56,
163 0x28, 0xBC, 0x9A, 0x5F, 0xD7, 0x3B, 0x69, 0x89, 0x8A, 0x36, 0x2C, 0x51,
164 0xDF, 0x12, 0x77, 0x2F, 0x57, 0x7B, 0xA0, 0xAA, 0xDD, 0x7F, 0xA1, 0x62,
165 0x3B, 0x40, 0x7B, 0x68, 0x1A, 0x8F, 0x0D, 0x38, 0xBB, 0x21, 0x5D, 0x18,
166 0xFC, 0x0F, 0x46, 0xF7, 0xA3, 0xB0, 0x1D, 0x23, 0xC3, 0xD2, 0xC7, 0x72,
167 0x51, 0x18, 0xDF, 0x46, 0x95, 0x79, 0xD9, 0xBD, 0xB5, 0x19, 0x02, 0x2C,
168 0x87, 0xDC, 0xE7, 0x57, 0x82, 0x7E, 0xF1, 0x8B, 0x06, 0x3D, 0x00, 0xA5,
169 0x7B, 0x6B, 0x26, 0x27, 0x91, 0x0F, 0x6A, 0x77, 0xE4, 0xD5, 0x04, 0xE4,
170 0x12, 0x2C, 0x42, 0xFF, 0xD2, 0x88, 0xBB, 0xD3, 0x92, 0xA0, 0xF9, 0xC8,
171 0x51, 0x64, 0x14, 0x5C, 0xD8, 0xF9, 0x6C, 0x47, 0x82, 0xB4, 0x1C, 0x7F,
172 0x09, 0xB8, 0xF0, 0x25, 0x83, 0x1D, 0x3F, 0x3F, 0x05, 0xB3, 0x21, 0x0A,
173 0x5D, 0xA7, 0xD8, 0x54, 0xC3, 0x65, 0x7D, 0xC3, 0xB0, 0x1D, 0xBF, 0xAE,
174 0xF8, 0x68, 0xCF, 0x9B,
175};
176static unsigned char dsa2048_q[] = {
177 0x97, 0xE7, 0x33, 0x4D, 0xD3, 0x94, 0x3E, 0x0B, 0xDB, 0x62, 0x74, 0xC6,
178 0xA1, 0x08, 0xDD, 0x19, 0xA3, 0x75, 0x17, 0x1B,
179};
180static unsigned char dsa2048_g[] = {
181 0x2C, 0x78, 0x16, 0x59, 0x34, 0x63, 0xF4, 0xF3, 0x92, 0xFC, 0xB5, 0xA5,
182 0x4F, 0x13, 0xDE, 0x2F, 0x1C, 0xA4, 0x3C, 0xAE, 0xAD, 0x38, 0x3F, 0x7E,
183 0x90, 0xBF, 0x96, 0xA6, 0xAE, 0x25, 0x90, 0x72, 0xF5, 0x8E, 0x80, 0x0C,
184 0x39, 0x1C, 0xD9, 0xEC, 0xBA, 0x90, 0x5B, 0x3A, 0xE8, 0x58, 0x6C, 0x9E,
185 0x30, 0x42, 0x37, 0x02, 0x31, 0x82, 0xBC, 0x6A, 0xDF, 0x6A, 0x09, 0x29,
186 0xE3, 0xC0, 0x46, 0xD1, 0xCB, 0x85, 0xEC, 0x0C, 0x30, 0x5E, 0xEA, 0xC8,
187 0x39, 0x8E, 0x22, 0x9F, 0x22, 0x10, 0xD2, 0x34, 0x61, 0x68, 0x37, 0x3D,
188 0x2E, 0x4A, 0x5B, 0x9A, 0xF5, 0xC1, 0x48, 0xC6, 0xF6, 0xDC, 0x63, 0x1A,
189 0xD3, 0x96, 0x64, 0xBA, 0x34, 0xC9, 0xD1, 0xA0, 0xD1, 0xAE, 0x6C, 0x2F,
190 0x48, 0x17, 0x93, 0x14, 0x43, 0xED, 0xF0, 0x21, 0x30, 0x19, 0xC3, 0x1B,
191 0x5F, 0xDE, 0xA3, 0xF0, 0x70, 0x78, 0x18, 0xE1, 0xA8, 0xE4, 0xEE, 0x2E,
192 0x00, 0xA5, 0xE4, 0xB3, 0x17, 0xC8, 0x0C, 0x7D, 0x6E, 0x42, 0xDC, 0xB7,
193 0x46, 0x00, 0x36, 0x4D, 0xD4, 0x46, 0xAA, 0x3D, 0x3C, 0x46, 0x89, 0x40,
194 0xBF, 0x1D, 0x84, 0x77, 0x0A, 0x75, 0xF3, 0x87, 0x1D, 0x08, 0x4C, 0xA6,
195 0xD1, 0xA9, 0x1C, 0x1E, 0x12, 0x1E, 0xE1, 0xC7, 0x30, 0x28, 0x76, 0xA5,
196 0x7F, 0x6C, 0x85, 0x96, 0x2B, 0x6F, 0xDB, 0x80, 0x66, 0x26, 0xAE, 0xF5,
197 0x93, 0xC7, 0x8E, 0xAE, 0x9A, 0xED, 0xE4, 0xCA, 0x04, 0xEA, 0x3B, 0x72,
198 0xEF, 0xDC, 0x87, 0xED, 0x0D, 0xA5, 0x4C, 0x4A, 0xDD, 0x71, 0x22, 0x64,
199 0x59, 0x69, 0x4E, 0x8E, 0xBF, 0x43, 0xDC, 0xAB, 0x8E, 0x66, 0xBB, 0x01,
200 0xB6, 0xF4, 0xE7, 0xFD, 0xD2, 0xAD, 0x9F, 0x36, 0xC1, 0xA0, 0x29, 0x99,
201 0xD1, 0x96, 0x70, 0x59, 0x06, 0x78, 0x35, 0xBD, 0x65, 0x55, 0x52, 0x9E,
202 0xF8, 0xB2, 0xE5, 0x38,
203};
204
205DSA *
206get_dsa2048()
207{
208 DSA *dsa;
209
210 if ((dsa = DSA_new()) == NULL)
211 return (NULL);
212 dsa->priv_key = BN_bin2bn(dsa2048_priv, sizeof(dsa2048_priv), NULL);
213 dsa->pub_key = BN_bin2bn(dsa2048_pub, sizeof(dsa2048_pub), NULL);
214 dsa->p = BN_bin2bn(dsa2048_p, sizeof(dsa2048_p), NULL);
215 dsa->q = BN_bin2bn(dsa2048_q, sizeof(dsa2048_q), NULL);
216 dsa->g = BN_bin2bn(dsa2048_g, sizeof(dsa2048_g), NULL);
217 if ((dsa->priv_key == NULL) || (dsa->pub_key == NULL) ||
218 (dsa->p == NULL) || (dsa->q == NULL) || (dsa->g == NULL))
219 return (NULL);
220 return (dsa);
221}
diff --git a/src/usr.bin/openssl/testrsa.h b/src/usr.bin/openssl/testrsa.h
new file mode 100644
index 0000000000..789afa9621
--- /dev/null
+++ b/src/usr.bin/openssl/testrsa.h
@@ -0,0 +1,517 @@
1/* $OpenBSD: testrsa.h,v 1.1 2014/08/26 17:47:25 jsing 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
59static unsigned char test512[] = {
60 0x30, 0x82, 0x01, 0x3a, 0x02, 0x01, 0x00, 0x02, 0x41, 0x00,
61 0xd6, 0x33, 0xb9, 0xc8, 0xfb, 0x4f, 0x3c, 0x7d, 0xc0, 0x01,
62 0x86, 0xd0, 0xe7, 0xa0, 0x55, 0xf2, 0x95, 0x93, 0xcc, 0x4f,
63 0xb7, 0x5b, 0x67, 0x5b, 0x94, 0x68, 0xc9, 0x34, 0x15, 0xde,
64 0xa5, 0x2e, 0x1c, 0x33, 0xc2, 0x6e, 0xfc, 0x34, 0x5e, 0x71,
65 0x13, 0xb7, 0xd6, 0xee, 0xd8, 0xa5, 0x65, 0x05, 0x72, 0x87,
66 0xa8, 0xb0, 0x77, 0xfe, 0x57, 0xf5, 0xfc, 0x5f, 0x55, 0x83,
67 0x87, 0xdd, 0x57, 0x49, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02,
68 0x41, 0x00, 0xa7, 0xf7, 0x91, 0xc5, 0x0f, 0x84, 0x57, 0xdc,
69 0x07, 0xf7, 0x6a, 0x7f, 0x60, 0x52, 0xb3, 0x72, 0xf1, 0x66,
70 0x1f, 0x7d, 0x97, 0x3b, 0x9e, 0xb6, 0x0a, 0x8f, 0x8c, 0xcf,
71 0x42, 0x23, 0x00, 0x04, 0xd4, 0x28, 0x0e, 0x1c, 0x90, 0xc4,
72 0x11, 0x25, 0x25, 0xa5, 0x93, 0xa5, 0x2f, 0x70, 0x02, 0xdf,
73 0x81, 0x9c, 0x49, 0x03, 0xa0, 0xf8, 0x6d, 0x54, 0x2e, 0x26,
74 0xde, 0xaa, 0x85, 0x59, 0xa8, 0x31, 0x02, 0x21, 0x00, 0xeb,
75 0x47, 0xd7, 0x3b, 0xf6, 0xc3, 0xdd, 0x5a, 0x46, 0xc5, 0xb9,
76 0x2b, 0x9a, 0xa0, 0x09, 0x8f, 0xa6, 0xfb, 0xf3, 0x78, 0x7a,
77 0x33, 0x70, 0x9d, 0x0f, 0x42, 0x6b, 0x13, 0x68, 0x24, 0xd3,
78 0x15, 0x02, 0x21, 0x00, 0xe9, 0x10, 0xb0, 0xb3, 0x0d, 0xe2,
79 0x82, 0x68, 0x77, 0x8a, 0x6e, 0x7c, 0xda, 0xbc, 0x3e, 0x53,
80 0x83, 0xfb, 0xd6, 0x22, 0xe7, 0xb5, 0xae, 0x6e, 0x80, 0xda,
81 0x00, 0x55, 0x97, 0xc1, 0xd0, 0x65, 0x02, 0x20, 0x4c, 0xf8,
82 0x73, 0xb1, 0x6a, 0x49, 0x29, 0x61, 0x1f, 0x46, 0x10, 0x0d,
83 0xf3, 0xc7, 0xe7, 0x58, 0xd7, 0x88, 0x15, 0x5e, 0x94, 0x9b,
84 0xbf, 0x7b, 0xa2, 0x42, 0x58, 0x45, 0x41, 0x0c, 0xcb, 0x01,
85 0x02, 0x20, 0x12, 0x11, 0xba, 0x31, 0x57, 0x9d, 0x3d, 0x11,
86 0x0e, 0x5b, 0x8c, 0x2f, 0x5f, 0xe2, 0x02, 0x4f, 0x05, 0x47,
87 0x8c, 0x15, 0x8e, 0xb3, 0x56, 0x3f, 0xb8, 0xfb, 0xad, 0xd4,
88 0xf4, 0xfc, 0x10, 0xc5, 0x02, 0x20, 0x18, 0xa1, 0x29, 0x99,
89 0x5b, 0xd9, 0xc8, 0xd4, 0xfc, 0x49, 0x7a, 0x2a, 0x21, 0x2c,
90 0x49, 0xe4, 0x4f, 0xeb, 0xef, 0x51, 0xf1, 0xab, 0x6d, 0xfb,
91 0x4b, 0x14, 0xe9, 0x4b, 0x52, 0xb5, 0x82, 0x2c,
92};
93
94static unsigned char test1024[] = {
95 0x30, 0x82, 0x02, 0x5c, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81,
96 0x00, 0xdc, 0x98, 0x43, 0xe8, 0x3d, 0x43, 0x5b, 0xe4, 0x05,
97 0xcd, 0xd0, 0xa9, 0x3e, 0xcb, 0x83, 0x75, 0xf6, 0xb5, 0xa5,
98 0x9f, 0x6b, 0xe9, 0x34, 0x41, 0x29, 0x18, 0xfa, 0x6a, 0x55,
99 0x4d, 0x70, 0xfc, 0xec, 0xae, 0x87, 0x38, 0x0a, 0x20, 0xa9,
100 0xc0, 0x45, 0x77, 0x6e, 0x57, 0x60, 0x57, 0xf4, 0xed, 0x96,
101 0x22, 0xcb, 0x8f, 0xe1, 0x33, 0x3a, 0x17, 0x1f, 0xed, 0x37,
102 0xa5, 0x6f, 0xeb, 0xa6, 0xbc, 0x12, 0x80, 0x1d, 0x53, 0xbd,
103 0x70, 0xeb, 0x21, 0x76, 0x3e, 0xc9, 0x2f, 0x1a, 0x45, 0x24,
104 0x82, 0xff, 0xcd, 0x59, 0x32, 0x06, 0x2e, 0x12, 0x3b, 0x23,
105 0x78, 0xed, 0x12, 0x3d, 0xe0, 0x8d, 0xf9, 0x67, 0x4f, 0x37,
106 0x4e, 0x47, 0x02, 0x4c, 0x2d, 0xc0, 0x4f, 0x1f, 0xb3, 0x94,
107 0xe1, 0x41, 0x2e, 0x2d, 0x90, 0x10, 0xfc, 0x82, 0x91, 0x8b,
108 0x0f, 0x22, 0xd4, 0xf2, 0xfc, 0x2c, 0xab, 0x53, 0x55, 0x02,
109 0x03, 0x01, 0x00, 0x01, 0x02, 0x81, 0x80, 0x2b, 0xcc, 0x3f,
110 0x8f, 0x58, 0xba, 0x8b, 0x00, 0x16, 0xf6, 0xea, 0x3a, 0xf0,
111 0x30, 0xd0, 0x05, 0x17, 0xda, 0xb0, 0xeb, 0x9a, 0x2d, 0x4f,
112 0x26, 0xb0, 0xd6, 0x38, 0xc1, 0xeb, 0xf5, 0xd8, 0x3d, 0x1f,
113 0x70, 0xf7, 0x7f, 0xf4, 0xe2, 0xcf, 0x51, 0x51, 0x79, 0x88,
114 0xfa, 0xe8, 0x32, 0x0e, 0x7b, 0x2d, 0x97, 0xf2, 0xfa, 0xba,
115 0x27, 0xc5, 0x9c, 0xd9, 0xc5, 0xeb, 0x8a, 0x79, 0x52, 0x3c,
116 0x64, 0x34, 0x7d, 0xc2, 0xcf, 0x28, 0xc7, 0x4e, 0xd5, 0x43,
117 0x0b, 0xd1, 0xa6, 0xca, 0x6d, 0x03, 0x2d, 0x72, 0x23, 0xbc,
118 0x6d, 0x05, 0xfa, 0x16, 0x09, 0x2f, 0x2e, 0x5c, 0xb6, 0xee,
119 0x74, 0xdd, 0xd2, 0x48, 0x8e, 0x36, 0x0c, 0x06, 0x3d, 0x4d,
120 0xe5, 0x10, 0x82, 0xeb, 0x6a, 0xf3, 0x4b, 0x9f, 0xd6, 0xed,
121 0x11, 0xb1, 0x6e, 0xec, 0xf4, 0xfe, 0x8e, 0x75, 0x94, 0x20,
122 0x2f, 0xcb, 0xac, 0x46, 0xf1, 0x02, 0x41, 0x00, 0xf9, 0x8c,
123 0xa3, 0x85, 0xb1, 0xdd, 0x29, 0xaf, 0x65, 0xc1, 0x33, 0xf3,
124 0x95, 0xc5, 0x52, 0x68, 0x0b, 0xd4, 0xf1, 0xe5, 0x0e, 0x02,
125 0x9f, 0x4f, 0xfa, 0x77, 0xdc, 0x46, 0x9e, 0xc7, 0xa6, 0xe4,
126 0x16, 0x29, 0xda, 0xb0, 0x07, 0xcf, 0x5b, 0xa9, 0x12, 0x8a,
127 0xdd, 0x63, 0x0a, 0xde, 0x2e, 0x8c, 0x66, 0x8b, 0x8c, 0xdc,
128 0x19, 0xa3, 0x7e, 0xf4, 0x3b, 0xd0, 0x1a, 0x8c, 0xa4, 0xc2,
129 0xe1, 0xd3, 0x02, 0x41, 0x00, 0xe2, 0x4c, 0x05, 0xf2, 0x04,
130 0x86, 0x4e, 0x61, 0x43, 0xdb, 0xb0, 0xb9, 0x96, 0x86, 0x52,
131 0x2c, 0xca, 0x8d, 0x7b, 0xab, 0x0b, 0x13, 0x0d, 0x7e, 0x38,
132 0x5b, 0xe2, 0x2e, 0x7b, 0x0e, 0xe7, 0x19, 0x99, 0x38, 0xe7,
133 0xf2, 0x21, 0xbd, 0x85, 0x85, 0xe3, 0xfd, 0x28, 0x77, 0x20,
134 0x31, 0x71, 0x2c, 0xd0, 0xff, 0xfb, 0x2e, 0xaf, 0x85, 0xb4,
135 0x86, 0xca, 0xf3, 0xbb, 0xca, 0xaa, 0x0f, 0x95, 0x37, 0x02,
136 0x40, 0x0e, 0x41, 0x9a, 0x95, 0xe8, 0xb3, 0x59, 0xce, 0x4b,
137 0x61, 0xde, 0x35, 0xec, 0x38, 0x79, 0x9c, 0xb8, 0x10, 0x52,
138 0x41, 0x63, 0xab, 0x82, 0xae, 0x6f, 0x00, 0xa9, 0xf4, 0xde,
139 0xdd, 0x49, 0x0b, 0x7e, 0xb8, 0xa5, 0x65, 0xa9, 0x0c, 0x8f,
140 0x8f, 0xf9, 0x1f, 0x35, 0xc6, 0x92, 0xb8, 0x5e, 0xb0, 0x66,
141 0xab, 0x52, 0x40, 0xc0, 0xb6, 0x36, 0x6a, 0x7d, 0x80, 0x46,
142 0x04, 0x02, 0xe5, 0x9f, 0x41, 0x02, 0x41, 0x00, 0xc0, 0xad,
143 0xcc, 0x4e, 0x21, 0xee, 0x1d, 0x24, 0x91, 0xfb, 0xa7, 0x80,
144 0x8d, 0x9a, 0xb6, 0xb3, 0x2e, 0x8f, 0xc2, 0xe1, 0x82, 0xdf,
145 0x69, 0x18, 0xb4, 0x71, 0xff, 0xa6, 0x65, 0xde, 0xed, 0x84,
146 0x8d, 0x42, 0xb7, 0xb3, 0x21, 0x69, 0x56, 0x1c, 0x07, 0x60,
147 0x51, 0x29, 0x04, 0xff, 0x34, 0x06, 0xdd, 0xb9, 0x67, 0x2c,
148 0x7c, 0x04, 0x93, 0x0e, 0x46, 0x15, 0xbb, 0x2a, 0xb7, 0x1b,
149 0xe7, 0x87, 0x02, 0x40, 0x78, 0xda, 0x5d, 0x07, 0x51, 0x0c,
150 0x16, 0x7a, 0x9f, 0x29, 0x20, 0x84, 0x0d, 0x42, 0xfa, 0xd7,
151 0x00, 0xd8, 0x77, 0x7e, 0xb0, 0xb0, 0x6b, 0xd6, 0x5b, 0x53,
152 0xb8, 0x9b, 0x7a, 0xcd, 0xc7, 0x2b, 0xb8, 0x6a, 0x63, 0xa9,
153 0xfb, 0x6f, 0xa4, 0x72, 0xbf, 0x4c, 0x5d, 0x00, 0x14, 0xba,
154 0xfa, 0x59, 0x88, 0xed, 0xe4, 0xe0, 0x8c, 0xa2, 0xec, 0x14,
155 0x7e, 0x2d, 0xe2, 0xf0, 0x46, 0x49, 0x95, 0x45,
156};
157
158static unsigned char test2048[] = {
159 0x30, 0x82, 0x04, 0xa3, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01,
160 0x01, 0x00, 0xc0, 0xc0, 0xce, 0x3e, 0x3c, 0x53, 0x67, 0x3f,
161 0x4f, 0xc5, 0x2f, 0xa4, 0xc2, 0x5a, 0x2f, 0x58, 0xfd, 0x27,
162 0x52, 0x6a, 0xe8, 0xcf, 0x4a, 0x73, 0x47, 0x8d, 0x25, 0x0f,
163 0x5f, 0x03, 0x26, 0x78, 0xef, 0xf0, 0x22, 0x12, 0xd3, 0xde,
164 0x47, 0xb2, 0x1c, 0x0b, 0x38, 0x63, 0x1a, 0x6c, 0x85, 0x7a,
165 0x80, 0xc6, 0x8f, 0xa0, 0x41, 0xaf, 0x62, 0xc4, 0x67, 0x32,
166 0x88, 0xf8, 0xa6, 0x9c, 0xf5, 0x23, 0x1d, 0xe4, 0xac, 0x3f,
167 0x29, 0xf9, 0xec, 0xe1, 0x8b, 0x26, 0x03, 0x2c, 0xb2, 0xab,
168 0xf3, 0x7d, 0xb5, 0xca, 0x49, 0xc0, 0x8f, 0x1c, 0xdf, 0x33,
169 0x3a, 0x60, 0xda, 0x3c, 0xb0, 0x16, 0xf8, 0xa9, 0x12, 0x8f,
170 0x64, 0xac, 0x23, 0x0c, 0x69, 0x64, 0x97, 0x5d, 0x99, 0xd4,
171 0x09, 0x83, 0x9b, 0x61, 0xd3, 0xac, 0xf0, 0xde, 0xdd, 0x5e,
172 0x9f, 0x44, 0x94, 0xdb, 0x3a, 0x4d, 0x97, 0xe8, 0x52, 0x29,
173 0xf7, 0xdb, 0x94, 0x07, 0x45, 0x90, 0x78, 0x1e, 0x31, 0x0b,
174 0x80, 0xf7, 0x57, 0xad, 0x1c, 0x79, 0xc5, 0xcb, 0x32, 0xb0,
175 0xce, 0xcd, 0x74, 0xb3, 0xe2, 0x94, 0xc5, 0x78, 0x2f, 0x34,
176 0x1a, 0x45, 0xf7, 0x8c, 0x52, 0xa5, 0xbc, 0x8d, 0xec, 0xd1,
177 0x2f, 0x31, 0x3b, 0xf0, 0x49, 0x59, 0x5e, 0x88, 0x9d, 0x15,
178 0x92, 0x35, 0x32, 0xc1, 0xe7, 0x61, 0xec, 0x50, 0x48, 0x7c,
179 0xba, 0x05, 0xf9, 0xf8, 0xf8, 0xa7, 0x8c, 0x83, 0xe8, 0x66,
180 0x5b, 0xeb, 0xfe, 0xd8, 0x4f, 0xdd, 0x6d, 0x36, 0xc0, 0xb2,
181 0x90, 0x0f, 0xb8, 0x52, 0xf9, 0x04, 0x9b, 0x40, 0x2c, 0x27,
182 0xd6, 0x36, 0x8e, 0xc2, 0x1b, 0x44, 0xf3, 0x92, 0xd5, 0x15,
183 0x9e, 0x9a, 0xbc, 0xf3, 0x7d, 0x03, 0xd7, 0x02, 0x14, 0x20,
184 0xe9, 0x10, 0x92, 0xfd, 0xf9, 0xfc, 0x8f, 0xe5, 0x18, 0xe1,
185 0x95, 0xcc, 0x9e, 0x60, 0xa6, 0xfa, 0x38, 0x4d, 0x02, 0x03,
186 0x01, 0x00, 0x01, 0x02, 0x82, 0x01, 0x00, 0x00, 0xc3, 0xc3,
187 0x0d, 0xb4, 0x27, 0x90, 0x8d, 0x4b, 0xbf, 0xb8, 0x84, 0xaa,
188 0xd0, 0xb8, 0xc7, 0x5d, 0x99, 0xbe, 0x55, 0xf6, 0x3e, 0x7c,
189 0x49, 0x20, 0xcb, 0x8a, 0x8e, 0x19, 0x0e, 0x66, 0x24, 0xac,
190 0xaf, 0x03, 0x33, 0x97, 0xeb, 0x95, 0xd5, 0x3b, 0x0f, 0x40,
191 0x56, 0x04, 0x50, 0xd1, 0xe6, 0xbe, 0x84, 0x0b, 0x25, 0xd3,
192 0x9c, 0xe2, 0x83, 0x6c, 0xf5, 0x62, 0x5d, 0xba, 0x2b, 0x7d,
193 0x3d, 0x7a, 0x6c, 0xe1, 0xd2, 0x0e, 0x54, 0x93, 0x80, 0x01,
194 0x91, 0x51, 0x09, 0xe8, 0x5b, 0x8e, 0x47, 0xbd, 0x64, 0xe4,
195 0x0e, 0x03, 0x83, 0x55, 0xcf, 0x5a, 0x37, 0xf0, 0x25, 0xb5,
196 0x7d, 0x21, 0xd7, 0x69, 0xdf, 0x6f, 0xc2, 0xcf, 0x10, 0xc9,
197 0x8a, 0x40, 0x9f, 0x7a, 0x70, 0xc0, 0xe8, 0xe8, 0xc0, 0xe6,
198 0x9a, 0x15, 0x0a, 0x8d, 0x4e, 0x46, 0xcb, 0x7a, 0xdb, 0xb3,
199 0xcb, 0x83, 0x02, 0xc4, 0xf0, 0xab, 0xeb, 0x02, 0x01, 0x0e,
200 0x23, 0xfc, 0x1d, 0xc4, 0xbd, 0xd4, 0xaa, 0x5d, 0x31, 0x46,
201 0x99, 0xce, 0x9e, 0xf8, 0x04, 0x75, 0x10, 0x67, 0xc4, 0x53,
202 0x47, 0x44, 0xfa, 0xc2, 0x25, 0x73, 0x7e, 0xd0, 0x8e, 0x59,
203 0xd1, 0xb2, 0x5a, 0xf4, 0xc7, 0x18, 0x92, 0x2f, 0x39, 0xab,
204 0xcd, 0xa3, 0xb5, 0xc2, 0xb9, 0xc7, 0xb9, 0x1b, 0x9f, 0x48,
205 0xfa, 0x13, 0xc6, 0x98, 0x4d, 0xca, 0x84, 0x9c, 0x06, 0xca,
206 0xe7, 0x89, 0x01, 0x04, 0xc4, 0x6c, 0xfd, 0x29, 0x59, 0x35,
207 0xe7, 0xf3, 0xdd, 0xce, 0x64, 0x59, 0xbf, 0x21, 0x13, 0xa9,
208 0x9f, 0x0e, 0xc5, 0xff, 0xbd, 0x33, 0x00, 0xec, 0xac, 0x6b,
209 0x11, 0xef, 0x51, 0x5e, 0xad, 0x07, 0x15, 0xde, 0xb8, 0x5f,
210 0xc6, 0xb9, 0xa3, 0x22, 0x65, 0x46, 0x83, 0x14, 0xdf, 0xd0,
211 0xf1, 0x44, 0x8a, 0xe1, 0x9c, 0x23, 0x33, 0xb4, 0x97, 0x33,
212 0xe6, 0x6b, 0x81, 0x02, 0x81, 0x81, 0x00, 0xec, 0x12, 0xa7,
213 0x59, 0x74, 0x6a, 0xde, 0x3e, 0xad, 0xd8, 0x36, 0x80, 0x50,
214 0xa2, 0xd5, 0x21, 0x81, 0x07, 0xf1, 0xd0, 0x91, 0xf2, 0x6c,
215 0x12, 0x2f, 0x9d, 0x1a, 0x26, 0xf8, 0x30, 0x65, 0xdf, 0xe8,
216 0xc0, 0x9b, 0x6a, 0x30, 0x98, 0x82, 0x87, 0xec, 0xa2, 0x56,
217 0x87, 0x62, 0x6f, 0xe7, 0x9f, 0xf6, 0x56, 0xe6, 0x71, 0x8f,
218 0x49, 0x86, 0x93, 0x5a, 0x4d, 0x34, 0x58, 0xfe, 0xd9, 0x04,
219 0x13, 0xaf, 0x79, 0xb7, 0xad, 0x11, 0xd1, 0x30, 0x9a, 0x14,
220 0x06, 0xa0, 0xfa, 0xb7, 0x55, 0xdc, 0x6c, 0x5a, 0x4c, 0x2c,
221 0x59, 0x56, 0xf6, 0xe8, 0x9d, 0xaf, 0x0a, 0x78, 0x99, 0x06,
222 0x06, 0x9e, 0xe7, 0x9c, 0x51, 0x55, 0x43, 0xfc, 0x3b, 0x6c,
223 0x0b, 0xbf, 0x2d, 0x41, 0xa7, 0xaf, 0xb7, 0xe0, 0xe8, 0x28,
224 0x18, 0xb4, 0x13, 0xd1, 0xe6, 0x97, 0xd0, 0x9f, 0x6a, 0x80,
225 0xca, 0xdd, 0x1a, 0x7e, 0x15, 0x02, 0x81, 0x81, 0x00, 0xd1,
226 0x06, 0x0c, 0x1f, 0xe3, 0xd0, 0xab, 0xd6, 0xca, 0x7c, 0xbc,
227 0x7d, 0x13, 0x35, 0xce, 0x27, 0xcd, 0xd8, 0x49, 0x51, 0x63,
228 0x64, 0x0f, 0xca, 0x06, 0x12, 0xfc, 0x07, 0x3e, 0xaf, 0x61,
229 0x6d, 0xe2, 0x53, 0x39, 0x27, 0xae, 0xc3, 0x11, 0x9e, 0x94,
230 0x01, 0x4f, 0xe3, 0xf3, 0x67, 0xf9, 0x77, 0xf9, 0xe7, 0x95,
231 0x3a, 0x6f, 0xe2, 0x20, 0x73, 0x3e, 0xa4, 0x7a, 0x28, 0xd4,
232 0x61, 0x97, 0xf6, 0x17, 0xa0, 0x23, 0x10, 0x2b, 0xce, 0x84,
233 0x57, 0x7e, 0x25, 0x1f, 0xf4, 0xa8, 0x54, 0xd2, 0x65, 0x94,
234 0xcc, 0x95, 0x0a, 0xab, 0x30, 0xc1, 0x59, 0x1f, 0x61, 0x8e,
235 0xb9, 0x6b, 0xd7, 0x4e, 0xb9, 0x83, 0x43, 0x79, 0x85, 0x11,
236 0xbc, 0x0f, 0xae, 0x25, 0x20, 0x05, 0xbc, 0xd2, 0x48, 0xa1,
237 0x68, 0x09, 0x84, 0xf6, 0x12, 0x9a, 0x66, 0xb9, 0x2b, 0xbb,
238 0x76, 0x03, 0x17, 0x46, 0x4e, 0x97, 0x59, 0x02, 0x81, 0x80,
239 0x09, 0x4c, 0xfa, 0xd6, 0xe5, 0x65, 0x48, 0x78, 0x43, 0xb5,
240 0x1f, 0x00, 0x93, 0x2c, 0xb7, 0x24, 0xe8, 0xc6, 0x7d, 0x5a,
241 0x70, 0x45, 0x92, 0xc8, 0x6c, 0xa3, 0xcd, 0xe1, 0xf7, 0x29,
242 0x40, 0xfa, 0x3f, 0x5b, 0x47, 0x44, 0x39, 0xc1, 0xe8, 0x72,
243 0x9e, 0x7a, 0x0e, 0xda, 0xaa, 0xa0, 0x2a, 0x09, 0xfd, 0x54,
244 0x93, 0x23, 0xaa, 0x37, 0x85, 0x5b, 0xcc, 0xd4, 0xf9, 0xd8,
245 0xff, 0xc1, 0x61, 0x0d, 0xbd, 0x7e, 0x18, 0x24, 0x73, 0x6d,
246 0x40, 0x72, 0xf1, 0x93, 0x09, 0x48, 0x97, 0x6c, 0x84, 0x90,
247 0xa8, 0x46, 0x14, 0x01, 0x39, 0x11, 0xe5, 0x3c, 0x41, 0x27,
248 0x32, 0x75, 0x24, 0xed, 0xa1, 0xd9, 0x12, 0x29, 0x8a, 0x28,
249 0x71, 0x89, 0x8d, 0xca, 0x30, 0xb0, 0x01, 0xc4, 0x2f, 0x82,
250 0x19, 0x14, 0x4c, 0x70, 0x1c, 0xb8, 0x23, 0x2e, 0xe8, 0x90,
251 0x49, 0x97, 0x92, 0x97, 0x6b, 0x7a, 0x9d, 0xb9, 0x02, 0x81,
252 0x80, 0x0f, 0x0e, 0xa1, 0x76, 0xf6, 0xa1, 0x44, 0x8f, 0xaf,
253 0x7c, 0x76, 0xd3, 0x87, 0xbb, 0xbb, 0x83, 0x10, 0x88, 0x01,
254 0x18, 0x14, 0xd1, 0xd3, 0x75, 0x59, 0x24, 0xaa, 0xf5, 0x16,
255 0xa5, 0xe9, 0x9d, 0xd1, 0xcc, 0xee, 0xf4, 0x15, 0xd9, 0xc5,
256 0x7e, 0x27, 0xe9, 0x44, 0x49, 0x06, 0x72, 0xb9, 0xfc, 0xd3,
257 0x8a, 0xc4, 0x2c, 0x36, 0x7d, 0x12, 0x9b, 0x5a, 0xaa, 0xdc,
258 0x85, 0xee, 0x6e, 0xad, 0x54, 0xb3, 0xf4, 0xfc, 0x31, 0xa1,
259 0x06, 0x3a, 0x70, 0x57, 0x0c, 0xf3, 0x95, 0x5b, 0x3e, 0xe8,
260 0xfd, 0x1a, 0x4f, 0xf6, 0x78, 0x93, 0x46, 0x6a, 0xd7, 0x31,
261 0xb4, 0x84, 0x64, 0x85, 0x09, 0x38, 0x89, 0x92, 0x94, 0x1c,
262 0xbf, 0xe2, 0x3c, 0x2a, 0xe0, 0xff, 0x99, 0xa3, 0xf0, 0x2b,
263 0x31, 0xc2, 0x36, 0xcd, 0x60, 0xbf, 0x9d, 0x2d, 0x74, 0x32,
264 0xe8, 0x9c, 0x93, 0x6e, 0xbb, 0x91, 0x7b, 0xfd, 0xd9, 0x02,
265 0x81, 0x81, 0x00, 0xa2, 0x71, 0x25, 0x38, 0xeb, 0x2a, 0xe9,
266 0x37, 0xcd, 0xfe, 0x44, 0xce, 0x90, 0x3f, 0x52, 0x87, 0x84,
267 0x52, 0x1b, 0xae, 0x8d, 0x22, 0x94, 0xce, 0x38, 0xe6, 0x04,
268 0x88, 0x76, 0x85, 0x9a, 0xd3, 0x14, 0x09, 0xe5, 0x69, 0x9a,
269 0xff, 0x58, 0x92, 0x02, 0x6a, 0x7d, 0x7c, 0x1e, 0x2c, 0xfd,
270 0xa8, 0xca, 0x32, 0x14, 0x4f, 0x0d, 0x84, 0x0d, 0x37, 0x43,
271 0xbf, 0xe4, 0x5d, 0x12, 0xc8, 0x24, 0x91, 0x27, 0x8d, 0x46,
272 0xd9, 0x54, 0x53, 0xe7, 0x62, 0x71, 0xa8, 0x2b, 0x71, 0x41,
273 0x8d, 0x75, 0xf8, 0x3a, 0xa0, 0x61, 0x29, 0x46, 0xa6, 0xe5,
274 0x82, 0xfa, 0x3a, 0xd9, 0x08, 0xfa, 0xfc, 0x63, 0xfd, 0x6b,
275 0x30, 0xbc, 0xf4, 0x4e, 0x9e, 0x8c, 0x25, 0x0c, 0xb6, 0x55,
276 0xe7, 0x3c, 0xd4, 0x4e, 0x0b, 0xfd, 0x8b, 0xc3, 0x0e, 0x1d,
277 0x9c, 0x44, 0x57, 0x8f, 0x1f, 0x86, 0xf7, 0xd5, 0x1b, 0xe4,
278 0x95,
279};
280
281static unsigned char test4096[] = {
282 0x30, 0x82, 0x09, 0x29, 0x02, 0x01, 0x00, 0x02, 0x82, 0x02,
283 0x01, 0x00, 0xc0, 0x71, 0xac, 0x1a, 0x13, 0x88, 0x82, 0x43,
284 0x3b, 0x51, 0x57, 0x71, 0x8d, 0xb6, 0x2b, 0x82, 0x65, 0x21,
285 0x53, 0x5f, 0x28, 0x29, 0x4f, 0x8d, 0x7c, 0x8a, 0xb9, 0x44,
286 0xb3, 0x28, 0x41, 0x4f, 0xd3, 0xfa, 0x6a, 0xf8, 0xb9, 0x28,
287 0x50, 0x39, 0x67, 0x53, 0x2c, 0x3c, 0xd7, 0xcb, 0x96, 0x41,
288 0x40, 0x32, 0xbb, 0xeb, 0x70, 0xae, 0x1f, 0xb0, 0x65, 0xf7,
289 0x3a, 0xd9, 0x22, 0xfd, 0x10, 0xae, 0xbd, 0x02, 0xe2, 0xdd,
290 0xf3, 0xc2, 0x79, 0x3c, 0xc6, 0xfc, 0x75, 0xbb, 0xaf, 0x4e,
291 0x3a, 0x36, 0xc2, 0x4f, 0xea, 0x25, 0xdf, 0x13, 0x16, 0x4b,
292 0x20, 0xfe, 0x4b, 0x69, 0x16, 0xc4, 0x7f, 0x1a, 0x43, 0xa6,
293 0x17, 0x1b, 0xb9, 0x0a, 0xf3, 0x09, 0x86, 0x28, 0x89, 0xcf,
294 0x2c, 0xd0, 0xd4, 0x81, 0xaf, 0xc6, 0x6d, 0xe6, 0x21, 0x8d,
295 0xee, 0xef, 0xea, 0xdc, 0xb7, 0xc6, 0x3b, 0x63, 0x9f, 0x0e,
296 0xad, 0x89, 0x78, 0x23, 0x18, 0xbf, 0x70, 0x7e, 0x84, 0xe0,
297 0x37, 0xec, 0xdb, 0x8e, 0x9c, 0x3e, 0x6a, 0x19, 0xcc, 0x99,
298 0x72, 0xe6, 0xb5, 0x7d, 0x6d, 0xfa, 0xe5, 0xd3, 0xe4, 0x90,
299 0xb5, 0xb2, 0xb2, 0x12, 0x70, 0x4e, 0xca, 0xf8, 0x10, 0xf8,
300 0xa3, 0x14, 0xc2, 0x48, 0x19, 0xeb, 0x60, 0x99, 0xbb, 0x2a,
301 0x1f, 0xb1, 0x7a, 0xb1, 0x3d, 0x24, 0xfb, 0xa0, 0x29, 0xda,
302 0xbd, 0x1b, 0xd7, 0xa4, 0xbf, 0xef, 0x60, 0x2d, 0x22, 0xca,
303 0x65, 0x98, 0xf1, 0xc4, 0xe1, 0xc9, 0x02, 0x6b, 0x16, 0x28,
304 0x2f, 0xa1, 0xaa, 0x79, 0x00, 0xda, 0xdc, 0x7c, 0x43, 0xf7,
305 0x42, 0x3c, 0xa0, 0xef, 0x68, 0xf7, 0xdf, 0xb9, 0x69, 0xfb,
306 0x8e, 0x01, 0xed, 0x01, 0x42, 0xb5, 0x4e, 0x57, 0xa6, 0x26,
307 0xb8, 0xd0, 0x7b, 0x56, 0x6d, 0x03, 0xc6, 0x40, 0x8c, 0x8c,
308 0x2a, 0x55, 0xd7, 0x9c, 0x35, 0x00, 0x94, 0x93, 0xec, 0x03,
309 0xeb, 0x22, 0xef, 0x77, 0xbb, 0x79, 0x13, 0x3f, 0x15, 0xa1,
310 0x8f, 0xca, 0xdf, 0xfd, 0xd3, 0xb8, 0xe1, 0xd4, 0xcc, 0x09,
311 0x3f, 0x3c, 0x2c, 0xdb, 0xd1, 0x49, 0x7f, 0x38, 0x07, 0x83,
312 0x6d, 0xeb, 0x08, 0x66, 0xe9, 0x06, 0x44, 0x12, 0xac, 0x95,
313 0x22, 0x90, 0x23, 0x67, 0xd4, 0x08, 0xcc, 0xf4, 0xb7, 0xdc,
314 0xcc, 0x87, 0xd4, 0xac, 0x69, 0x35, 0x4c, 0xb5, 0x39, 0x36,
315 0xcd, 0xa4, 0xd2, 0x95, 0xca, 0x0d, 0xc5, 0xda, 0xc2, 0xc5,
316 0x22, 0x32, 0x28, 0x08, 0xe3, 0xd2, 0x8b, 0x38, 0x30, 0xdc,
317 0x8c, 0x75, 0x4f, 0x6a, 0xec, 0x7a, 0xac, 0x16, 0x3e, 0xa8,
318 0xd4, 0x6a, 0x45, 0xe1, 0xa8, 0x4f, 0x2e, 0x80, 0x34, 0xaa,
319 0x54, 0x1b, 0x02, 0x95, 0x7d, 0x8a, 0x6d, 0xcc, 0x79, 0xca,
320 0xf2, 0xa4, 0x2e, 0x8d, 0xfb, 0xfe, 0x15, 0x51, 0x10, 0x0e,
321 0x4d, 0x88, 0xb1, 0xc7, 0xf4, 0x79, 0xdb, 0xf0, 0xb4, 0x56,
322 0x44, 0x37, 0xca, 0x5a, 0xc1, 0x8c, 0x48, 0xac, 0xae, 0x48,
323 0x80, 0x83, 0x01, 0x3f, 0xde, 0xd9, 0xd3, 0x2c, 0x51, 0x46,
324 0xb1, 0x41, 0xb6, 0xc6, 0x91, 0x72, 0xf9, 0x83, 0x55, 0x1b,
325 0x8c, 0xba, 0xf3, 0x73, 0xe5, 0x2c, 0x74, 0x50, 0x3a, 0xbe,
326 0xc5, 0x2f, 0xa7, 0xb2, 0x6d, 0x8c, 0x9e, 0x13, 0x77, 0xa3,
327 0x13, 0xcd, 0x6d, 0x8c, 0x45, 0xe1, 0xfc, 0x0b, 0xb7, 0x69,
328 0xe9, 0x27, 0xbc, 0x65, 0xc3, 0xfa, 0x9b, 0xd0, 0xef, 0xfe,
329 0xe8, 0x1f, 0xb3, 0x5e, 0x34, 0xf4, 0x8c, 0xea, 0xfc, 0xd3,
330 0x81, 0xbf, 0x3d, 0x30, 0xb2, 0xb4, 0x01, 0xe8, 0x43, 0x0f,
331 0xba, 0x02, 0x23, 0x42, 0x76, 0x82, 0x31, 0x73, 0x91, 0xed,
332 0x07, 0x46, 0x61, 0x0d, 0x39, 0x83, 0x40, 0xce, 0x7a, 0xd4,
333 0xdb, 0x80, 0x2c, 0x1f, 0x0d, 0xd1, 0x34, 0xd4, 0x92, 0xe3,
334 0xd4, 0xf1, 0xc2, 0x01, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02,
335 0x82, 0x02, 0x01, 0x00, 0x97, 0x6c, 0xda, 0x6e, 0xea, 0x4f,
336 0xcf, 0xaf, 0xf7, 0x4c, 0xd9, 0xf1, 0x90, 0x00, 0x77, 0xdb,
337 0xf2, 0x97, 0x76, 0x72, 0xb9, 0xb7, 0x47, 0xd1, 0x9c, 0xdd,
338 0xcb, 0x4a, 0x33, 0x6e, 0xc9, 0x75, 0x76, 0xe6, 0xe4, 0xa5,
339 0x31, 0x8c, 0x77, 0x13, 0xb4, 0x29, 0xcd, 0xf5, 0x52, 0x17,
340 0xef, 0xf3, 0x08, 0x00, 0xe3, 0xbd, 0x2e, 0xbc, 0xd4, 0x52,
341 0x88, 0xe9, 0x30, 0x75, 0x0b, 0x02, 0xf5, 0xcd, 0x89, 0x0c,
342 0x6c, 0x57, 0x19, 0x27, 0x3d, 0x1e, 0x85, 0xb4, 0xc1, 0x2f,
343 0x1d, 0x92, 0x00, 0x5c, 0x76, 0x29, 0x4b, 0xa4, 0xe1, 0x12,
344 0xb3, 0xc8, 0x09, 0xfe, 0x0e, 0x78, 0x72, 0x61, 0xcb, 0x61,
345 0x6f, 0x39, 0x91, 0x95, 0x4e, 0xd5, 0x3e, 0xc7, 0x8f, 0xb8,
346 0xf6, 0x36, 0xfe, 0x9c, 0x93, 0x9a, 0x38, 0x25, 0x7a, 0xf4,
347 0x4a, 0x12, 0xd4, 0xa0, 0x13, 0xbd, 0xf9, 0x1d, 0x12, 0x3e,
348 0x21, 0x39, 0xfb, 0x72, 0xe0, 0x05, 0x3d, 0xc3, 0xe5, 0x50,
349 0xa8, 0x5d, 0x85, 0xa3, 0xea, 0x5f, 0x1c, 0xb2, 0x3f, 0xea,
350 0x6d, 0x03, 0x91, 0x55, 0xd8, 0x19, 0x0a, 0x21, 0x12, 0x16,
351 0xd9, 0x12, 0xc4, 0xe6, 0x07, 0x18, 0x5b, 0x26, 0xa4, 0xae,
352 0xed, 0x2b, 0xb7, 0xa6, 0xed, 0xf8, 0xad, 0xec, 0x77, 0xe6,
353 0x7f, 0x4f, 0x76, 0x00, 0xc0, 0xfa, 0x15, 0x92, 0xb4, 0x2c,
354 0x22, 0xc2, 0xeb, 0x6a, 0xad, 0x14, 0x05, 0xb2, 0xe5, 0x8a,
355 0x9e, 0x85, 0x83, 0xcc, 0x04, 0xf1, 0x56, 0x78, 0x44, 0x5e,
356 0xde, 0xe0, 0x60, 0x1a, 0x65, 0x79, 0x31, 0x23, 0x05, 0xbb,
357 0x01, 0xff, 0xdd, 0x2e, 0xb7, 0xb3, 0xaa, 0x74, 0xe0, 0xa5,
358 0x94, 0xaf, 0x4b, 0xde, 0x58, 0x0f, 0x55, 0xde, 0x33, 0xf6,
359 0xe3, 0xd6, 0x34, 0x36, 0x57, 0xd6, 0x79, 0x91, 0x2e, 0xbe,
360 0x3b, 0xd9, 0x4e, 0xb6, 0x9d, 0x21, 0x5c, 0xd3, 0x48, 0x14,
361 0x7f, 0x4a, 0xc4, 0x60, 0xa9, 0x29, 0xf8, 0x53, 0x7f, 0x88,
362 0x11, 0x2d, 0xb5, 0xc5, 0x2d, 0x6f, 0xee, 0x85, 0x0b, 0xf7,
363 0x8d, 0x9a, 0xbe, 0xb0, 0x42, 0xf2, 0x2e, 0x71, 0xaf, 0x19,
364 0x31, 0x6d, 0xec, 0xcd, 0x6f, 0x2b, 0x23, 0xdf, 0xb4, 0x40,
365 0xaf, 0x2c, 0x0a, 0xc3, 0x1b, 0x7d, 0x7d, 0x03, 0x1d, 0x4b,
366 0xf3, 0xb5, 0xe0, 0x85, 0xd8, 0xdf, 0x91, 0x6b, 0x0a, 0x69,
367 0xf7, 0xf2, 0x69, 0x66, 0x5b, 0xf1, 0xcf, 0x46, 0x7d, 0xe9,
368 0x70, 0xfa, 0x6d, 0x7e, 0x75, 0x4e, 0xa9, 0x77, 0xe6, 0x8c,
369 0x02, 0xf7, 0x14, 0x4d, 0xa5, 0x41, 0x8f, 0x3f, 0xc1, 0x62,
370 0x1e, 0x71, 0x5e, 0x38, 0xb4, 0xd6, 0xe6, 0xe1, 0x4b, 0xc2,
371 0x2c, 0x30, 0x83, 0x81, 0x6f, 0x49, 0x2e, 0x96, 0xe6, 0xc9,
372 0x9a, 0xf7, 0x5d, 0x09, 0xa0, 0x55, 0x02, 0xa5, 0x3a, 0x25,
373 0x23, 0xd0, 0x92, 0xc3, 0xa3, 0xe3, 0x0e, 0x12, 0x2f, 0x4d,
374 0xef, 0xf3, 0x55, 0x5a, 0xbe, 0xe6, 0x19, 0x86, 0x31, 0xab,
375 0x75, 0x9a, 0xd3, 0xf0, 0x2c, 0xc5, 0x41, 0x92, 0xd9, 0x1f,
376 0x5f, 0x11, 0x8c, 0x75, 0x1c, 0x63, 0xd0, 0x02, 0x80, 0x2c,
377 0x68, 0xcb, 0x93, 0xfb, 0x51, 0x73, 0x49, 0xb4, 0x60, 0xda,
378 0xe2, 0x26, 0xaf, 0xa9, 0x46, 0x12, 0xb8, 0xec, 0x50, 0xdd,
379 0x12, 0x06, 0x5f, 0xce, 0x59, 0xe6, 0xf6, 0x1c, 0xe0, 0x54,
380 0x10, 0xad, 0xf6, 0xcd, 0x98, 0xcc, 0x0f, 0xfb, 0xcb, 0x41,
381 0x14, 0x9d, 0xed, 0xe4, 0xb4, 0x74, 0x5f, 0x09, 0x60, 0xc7,
382 0x12, 0xf6, 0x7b, 0x3c, 0x8f, 0xa7, 0x20, 0xbc, 0xe4, 0xb1,
383 0xef, 0xeb, 0xa4, 0x93, 0xc5, 0x06, 0xca, 0x9a, 0x27, 0x9d,
384 0x87, 0xf3, 0xde, 0xca, 0xe5, 0xe7, 0xf6, 0x1c, 0x01, 0x65,
385 0x5b, 0xfb, 0x19, 0x79, 0x6e, 0x08, 0x26, 0xc5, 0xc8, 0x28,
386 0x0e, 0xb6, 0x3b, 0x07, 0x08, 0xc1, 0x02, 0x82, 0x01, 0x01,
387 0x00, 0xe8, 0x1c, 0x73, 0xa6, 0xb8, 0xe0, 0x0e, 0x6d, 0x8d,
388 0x1b, 0xb9, 0x53, 0xed, 0x58, 0x94, 0xe6, 0x1d, 0x60, 0x14,
389 0x5c, 0x76, 0x43, 0xc4, 0x58, 0x19, 0xc4, 0x24, 0xe8, 0xbc,
390 0x1b, 0x3b, 0x0b, 0x13, 0x24, 0x45, 0x54, 0x0e, 0xcc, 0x37,
391 0xf0, 0xe0, 0x63, 0x7d, 0xc3, 0xf7, 0xfb, 0x81, 0x74, 0x81,
392 0xc4, 0x0f, 0x1a, 0x21, 0x48, 0xaf, 0xce, 0xc1, 0xc4, 0x94,
393 0x18, 0x06, 0x44, 0x8d, 0xd3, 0xd2, 0x22, 0x2d, 0x2d, 0x3e,
394 0x5a, 0x31, 0xdc, 0x95, 0x8e, 0xf4, 0x41, 0xfc, 0x58, 0xc9,
395 0x40, 0x92, 0x17, 0x5f, 0xe3, 0xda, 0xac, 0x9e, 0x3f, 0x1c,
396 0x2a, 0x6b, 0x58, 0x5f, 0x48, 0x78, 0x20, 0xb1, 0xaf, 0x24,
397 0x9b, 0x3c, 0x20, 0x8b, 0x93, 0x25, 0x9e, 0xe6, 0x6b, 0xbc,
398 0x13, 0x42, 0x14, 0x6c, 0x36, 0x31, 0xff, 0x7a, 0xd1, 0xc1,
399 0x1a, 0x26, 0x14, 0x7f, 0xa9, 0x76, 0xa7, 0x0c, 0xf8, 0xcc,
400 0xed, 0x07, 0x6a, 0xd2, 0xdf, 0x62, 0xee, 0x0a, 0x7c, 0x84,
401 0xcb, 0x49, 0x90, 0xb2, 0x03, 0x0d, 0xa2, 0x82, 0x06, 0x77,
402 0xf1, 0xcd, 0x67, 0xf2, 0x47, 0x21, 0x02, 0x3f, 0x43, 0x21,
403 0xf0, 0x46, 0x30, 0x62, 0x51, 0x72, 0xb1, 0xe7, 0x48, 0xc6,
404 0x67, 0x12, 0xcd, 0x9e, 0xd6, 0x15, 0xe5, 0x21, 0xed, 0xfa,
405 0x8f, 0x30, 0xa6, 0x41, 0xfe, 0xb6, 0xfa, 0x8f, 0x34, 0x14,
406 0x19, 0xe8, 0x11, 0xf7, 0xa5, 0x77, 0x3e, 0xb7, 0xf9, 0x39,
407 0x07, 0x8c, 0x67, 0x2a, 0xab, 0x7b, 0x08, 0xf8, 0xb0, 0x06,
408 0xa8, 0xea, 0x2f, 0x8f, 0xfa, 0xcc, 0xcc, 0x40, 0xce, 0xf3,
409 0x70, 0x4f, 0x3f, 0x7f, 0xe2, 0x0c, 0xea, 0x76, 0x4a, 0x35,
410 0x4e, 0x47, 0xad, 0x2b, 0xa7, 0x97, 0x5d, 0x74, 0x43, 0x97,
411 0x90, 0xd2, 0xfb, 0xd9, 0xf9, 0x96, 0x01, 0x33, 0x05, 0xed,
412 0x7b, 0x03, 0x05, 0xad, 0xf8, 0x49, 0x03, 0x02, 0x82, 0x01,
413 0x01, 0x00, 0xd4, 0x40, 0x17, 0x66, 0x10, 0x92, 0x95, 0xc8,
414 0xec, 0x62, 0xa9, 0x7a, 0xcb, 0x93, 0x8e, 0xe6, 0x53, 0xd4,
415 0x80, 0x48, 0x27, 0x4b, 0x41, 0xce, 0x61, 0xdf, 0xbf, 0x94,
416 0xa4, 0x3d, 0x71, 0x03, 0x0b, 0xed, 0x25, 0x71, 0x98, 0xa4,
417 0xd6, 0xd5, 0x4a, 0x57, 0xf5, 0x6c, 0x1b, 0xda, 0x21, 0x7d,
418 0x35, 0x45, 0xb3, 0xf3, 0x6a, 0xd9, 0xd3, 0x43, 0xe8, 0x5c,
419 0x54, 0x1c, 0x83, 0x1b, 0xb4, 0x5f, 0xf2, 0x97, 0x24, 0x2e,
420 0xdc, 0x40, 0xde, 0x92, 0x23, 0x59, 0x8e, 0xbc, 0xd2, 0xa1,
421 0xf2, 0xe0, 0x4c, 0xdd, 0x0b, 0xd1, 0xe7, 0xae, 0x65, 0xbc,
422 0xb5, 0xf5, 0x5b, 0x98, 0xe9, 0xd7, 0xc2, 0xb7, 0x0e, 0x55,
423 0x71, 0x0e, 0x3c, 0x0a, 0x24, 0x6b, 0xa6, 0xe6, 0x14, 0x61,
424 0x11, 0xfd, 0x33, 0x42, 0x99, 0x2b, 0x84, 0x77, 0x74, 0x92,
425 0x91, 0xf5, 0x79, 0x79, 0xcf, 0xad, 0x8e, 0x04, 0xef, 0x80,
426 0x1e, 0x57, 0xf4, 0x14, 0xf5, 0x35, 0x09, 0x74, 0xb2, 0x13,
427 0x71, 0x58, 0x6b, 0xea, 0x32, 0x5d, 0xf3, 0xd3, 0x76, 0x48,
428 0x39, 0x10, 0x23, 0x84, 0x9d, 0xbe, 0x92, 0x77, 0x4a, 0xed,
429 0x70, 0x3e, 0x1a, 0xa2, 0x6c, 0xb3, 0x81, 0x00, 0xc3, 0xc9,
430 0xe4, 0x52, 0xc8, 0x24, 0x88, 0x0c, 0x41, 0xad, 0x87, 0x5a,
431 0xea, 0xa3, 0x7a, 0x85, 0x1c, 0x5e, 0x31, 0x7f, 0xc3, 0x35,
432 0xc6, 0xfa, 0x10, 0xc8, 0x75, 0x10, 0xc4, 0x96, 0x99, 0xe7,
433 0xfe, 0x01, 0xb4, 0x74, 0xdb, 0xb4, 0x11, 0xc3, 0xc8, 0x8c,
434 0xf6, 0xf7, 0x3b, 0x66, 0x50, 0xfc, 0xdb, 0xeb, 0xca, 0x47,
435 0x85, 0x89, 0xe1, 0x65, 0xd9, 0x62, 0x34, 0x3c, 0x70, 0xd8,
436 0x2e, 0xb4, 0x2f, 0x65, 0x3c, 0x4a, 0xa6, 0x2a, 0xe7, 0xc7,
437 0xd8, 0x41, 0x8f, 0x8a, 0x43, 0xbf, 0x42, 0xf2, 0x4d, 0xbc,
438 0xfc, 0x9e, 0x27, 0x95, 0xfb, 0x75, 0xff, 0xab, 0x02, 0x82,
439 0x01, 0x00, 0x41, 0x2f, 0x44, 0x57, 0x6d, 0x12, 0x17, 0x5b,
440 0x32, 0xc6, 0xb7, 0x6c, 0x57, 0x7a, 0x8a, 0x0e, 0x79, 0xef,
441 0x72, 0xa8, 0x68, 0xda, 0x2d, 0x38, 0xe4, 0xbb, 0x8d, 0xf6,
442 0x02, 0x65, 0xcf, 0x56, 0x13, 0xe1, 0x1a, 0xcb, 0x39, 0x80,
443 0xa6, 0xb1, 0x32, 0x03, 0x1e, 0xdd, 0xbb, 0x35, 0xd9, 0xac,
444 0x43, 0x89, 0x31, 0x08, 0x90, 0x92, 0x5e, 0x35, 0x3d, 0x7b,
445 0x9c, 0x6f, 0x86, 0xcb, 0x17, 0xdd, 0x85, 0xe4, 0xed, 0x35,
446 0x08, 0x8e, 0xc1, 0xf4, 0x05, 0xd8, 0x68, 0xc6, 0x63, 0x3c,
447 0xf7, 0xff, 0xf7, 0x47, 0x33, 0x39, 0xc5, 0x3e, 0xb7, 0x0e,
448 0x58, 0x35, 0x9d, 0x81, 0xea, 0xf8, 0x6a, 0x2c, 0x1c, 0x5a,
449 0x68, 0x78, 0x64, 0x11, 0x6b, 0xc1, 0x3e, 0x4e, 0x7a, 0xbd,
450 0x84, 0xcb, 0x0f, 0xc2, 0xb6, 0x85, 0x1d, 0xd3, 0x76, 0xc5,
451 0x93, 0x6a, 0x69, 0x89, 0x56, 0x34, 0xdc, 0x4a, 0x9b, 0xbc,
452 0xff, 0xa8, 0x0d, 0x6e, 0x35, 0x9c, 0x60, 0xa7, 0x23, 0x30,
453 0xc7, 0x06, 0x64, 0x39, 0x8b, 0x94, 0x89, 0xee, 0xba, 0x7f,
454 0x60, 0x8d, 0xfa, 0xb6, 0x97, 0x76, 0xdc, 0x51, 0x4a, 0x3c,
455 0xeb, 0x3a, 0x14, 0x2c, 0x20, 0x60, 0x69, 0x4a, 0x86, 0xfe,
456 0x8c, 0x21, 0x84, 0x49, 0x54, 0xb3, 0x20, 0xe1, 0x01, 0x7f,
457 0x58, 0xdf, 0x7f, 0xb5, 0x21, 0x51, 0x8c, 0x47, 0x9f, 0x91,
458 0xeb, 0x97, 0x3e, 0xf2, 0x54, 0xcf, 0x16, 0x46, 0xf9, 0xd9,
459 0xb6, 0xe7, 0x64, 0xc9, 0xd0, 0x54, 0xea, 0x2f, 0xa1, 0xcf,
460 0xa5, 0x7f, 0x28, 0x8d, 0x84, 0xec, 0xd5, 0x39, 0x03, 0x76,
461 0x5b, 0x2d, 0x8e, 0x43, 0xf2, 0x01, 0x24, 0xc9, 0x6f, 0xc0,
462 0xf5, 0x69, 0x6f, 0x7d, 0xb5, 0x85, 0xd2, 0x5f, 0x7f, 0x78,
463 0x40, 0x07, 0x7f, 0x09, 0x15, 0xb5, 0x1f, 0x28, 0x65, 0x10,
464 0xe4, 0x19, 0xa8, 0xc6, 0x9e, 0x8d, 0xdc, 0xcb, 0x02, 0x82,
465 0x01, 0x00, 0x13, 0x01, 0xee, 0x56, 0x80, 0x93, 0x70, 0x00,
466 0x7f, 0x52, 0xd2, 0x94, 0xa1, 0x98, 0x84, 0x4a, 0x92, 0x25,
467 0x4c, 0x9b, 0xa9, 0x91, 0x2e, 0xc2, 0x79, 0xb7, 0x5c, 0xe3,
468 0xc5, 0xd5, 0x8e, 0xc2, 0x54, 0x16, 0x17, 0xad, 0x55, 0x9b,
469 0x25, 0x76, 0x12, 0x63, 0x50, 0x22, 0x2f, 0x58, 0x58, 0x79,
470 0x6b, 0x04, 0xe3, 0xf9, 0x9f, 0x8f, 0x04, 0x41, 0x67, 0x94,
471 0xa5, 0x1f, 0xac, 0x8a, 0x15, 0x9c, 0x26, 0x10, 0x6c, 0xf8,
472 0x19, 0x57, 0x61, 0xd7, 0x3a, 0x7d, 0x31, 0xb0, 0x2d, 0x38,
473 0xbd, 0x94, 0x62, 0xad, 0xc4, 0xfa, 0x36, 0x42, 0x42, 0xf0,
474 0x24, 0x67, 0x65, 0x9d, 0x8b, 0x0b, 0x7c, 0x6f, 0x82, 0x44,
475 0x1a, 0x8c, 0xc8, 0xc9, 0xab, 0xbb, 0x4c, 0x45, 0xfc, 0x7b,
476 0x38, 0xee, 0x30, 0xe1, 0xfc, 0xef, 0x8d, 0xbc, 0x58, 0xdf,
477 0x2b, 0x5d, 0x0d, 0x54, 0xe0, 0x49, 0x4d, 0x97, 0x99, 0x8f,
478 0x22, 0xa8, 0x83, 0xbe, 0x40, 0xbb, 0x50, 0x2e, 0x78, 0x28,
479 0x0f, 0x95, 0x78, 0x8c, 0x8f, 0x98, 0x24, 0x56, 0xc2, 0x97,
480 0xf3, 0x2c, 0x43, 0xd2, 0x03, 0x82, 0x66, 0x81, 0x72, 0x5f,
481 0x53, 0x16, 0xec, 0xb1, 0xb1, 0x04, 0x5e, 0x40, 0x20, 0x48,
482 0x7b, 0x3f, 0x02, 0x97, 0x6a, 0xeb, 0x96, 0x12, 0x21, 0x35,
483 0xfe, 0x1f, 0x47, 0xc0, 0x95, 0xea, 0xc5, 0x8a, 0x08, 0x84,
484 0x4f, 0x5e, 0x63, 0x94, 0x60, 0x0f, 0x71, 0x5b, 0x7f, 0x4a,
485 0xec, 0x4f, 0x60, 0xc6, 0xba, 0x4a, 0x24, 0xf1, 0x20, 0x8b,
486 0xa7, 0x2e, 0x3a, 0xce, 0x8d, 0xe0, 0x27, 0x1d, 0xb5, 0x8e,
487 0xb4, 0x21, 0xc5, 0xe2, 0xa6, 0x16, 0x0a, 0x51, 0x83, 0x55,
488 0x88, 0xd1, 0x30, 0x11, 0x63, 0xd5, 0xd7, 0x8d, 0xae, 0x16,
489 0x12, 0x82, 0xc4, 0x85, 0x00, 0x4e, 0x27, 0x83, 0xa5, 0x7c,
490 0x90, 0x2e, 0xe5, 0xa2, 0xa3, 0xd3, 0x4c, 0x63, 0x02, 0x82,
491 0x01, 0x01, 0x00, 0x86, 0x08, 0x98, 0x98, 0xa5, 0x00, 0x05,
492 0x39, 0x77, 0xd9, 0x66, 0xb3, 0xcf, 0xca, 0xa0, 0x71, 0xb3,
493 0x50, 0xce, 0x3d, 0xb1, 0x93, 0x95, 0x35, 0xc4, 0xd4, 0x2e,
494 0x90, 0xdf, 0x0f, 0xfc, 0x60, 0xc1, 0x94, 0x68, 0x61, 0x43,
495 0xca, 0x9a, 0x23, 0x4a, 0x1e, 0x45, 0x72, 0x99, 0xb5, 0x1e,
496 0x61, 0x8d, 0x77, 0x0f, 0xa0, 0xbb, 0xd7, 0x77, 0xb4, 0x2a,
497 0x15, 0x11, 0x88, 0x2d, 0xb3, 0x56, 0x61, 0x5e, 0x6a, 0xed,
498 0xa4, 0x46, 0x4a, 0x3f, 0x50, 0x11, 0xd6, 0xba, 0xb6, 0xd7,
499 0x95, 0x65, 0x53, 0xc3, 0xa1, 0x8f, 0xe0, 0xa3, 0xf5, 0x1c,
500 0xfd, 0xaf, 0x6e, 0x43, 0xd7, 0x17, 0xa7, 0xd3, 0x81, 0x1b,
501 0xa4, 0xdf, 0xe0, 0x97, 0x8a, 0x46, 0x03, 0xd3, 0x46, 0x0e,
502 0x83, 0x48, 0x4e, 0xd2, 0x02, 0xcb, 0xc0, 0xad, 0x79, 0x95,
503 0x8c, 0x96, 0xba, 0x40, 0x34, 0x11, 0x71, 0x5e, 0xe9, 0x11,
504 0xf9, 0xc5, 0x4a, 0x5e, 0x91, 0x9d, 0xf5, 0x92, 0x4f, 0xeb,
505 0xc6, 0x70, 0x02, 0x2d, 0x3d, 0x04, 0xaa, 0xe9, 0x3a, 0x8e,
506 0xd5, 0xa8, 0xad, 0xf7, 0xce, 0x0d, 0x16, 0xb2, 0xec, 0x0a,
507 0x9c, 0xf5, 0x94, 0x39, 0xb9, 0x8a, 0xfc, 0x1e, 0xf9, 0xcc,
508 0xf2, 0x5f, 0x21, 0x31, 0x74, 0x72, 0x6b, 0x64, 0xae, 0x35,
509 0x61, 0x8d, 0x0d, 0xcb, 0xe7, 0xda, 0x39, 0xca, 0xf3, 0x21,
510 0x66, 0x0b, 0x95, 0xd7, 0x0a, 0x7c, 0xca, 0xa1, 0xa9, 0x5a,
511 0xe8, 0xac, 0xe0, 0x71, 0x54, 0xaf, 0x28, 0xcf, 0xd5, 0x70,
512 0x89, 0xe0, 0xf3, 0x9e, 0x43, 0x6c, 0x8d, 0x7b, 0x99, 0x01,
513 0x68, 0x4d, 0xa1, 0x45, 0x46, 0x0c, 0x43, 0xbc, 0xcc, 0x2c,
514 0xdd, 0xc5, 0x46, 0xc8, 0x4e, 0x0e, 0xbe, 0xed, 0xb9, 0x26,
515 0xab, 0x2e, 0xdb, 0xeb, 0x8f, 0xff, 0xdb, 0xb0, 0xc6, 0x55,
516 0xaf, 0xf8, 0x2a, 0x91, 0x9d, 0x50, 0x44, 0x21, 0x17,
517};
diff --git a/src/usr.bin/openssl/timeouts.h b/src/usr.bin/openssl/timeouts.h
new file mode 100644
index 0000000000..dd2f85028d
--- /dev/null
+++ b/src/usr.bin/openssl/timeouts.h
@@ -0,0 +1,67 @@
1/* $OpenBSD: timeouts.h,v 1.1 2014/08/26 17:47:25 jsing Exp $ */
2/*
3 * DTLS implementation written by Nagendra Modadugu
4 * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.
5 */
6/* ====================================================================
7 * Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 *
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 *
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in
18 * the documentation and/or other materials provided with the
19 * distribution.
20 *
21 * 3. All advertising materials mentioning features or use of this
22 * software must display the following acknowledgment:
23 * "This product includes software developed by the OpenSSL Project
24 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25 *
26 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27 * endorse or promote products derived from this software without
28 * prior written permission. For written permission, please contact
29 * openssl-core@OpenSSL.org.
30 *
31 * 5. Products derived from this software may not be called "OpenSSL"
32 * nor may "OpenSSL" appear in their names without prior written
33 * permission of the OpenSSL Project.
34 *
35 * 6. Redistributions of any form whatsoever must retain the following
36 * acknowledgment:
37 * "This product includes software developed by the OpenSSL Project
38 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39 *
40 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
44 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51 * OF THE POSSIBILITY OF SUCH DAMAGE.
52 * ====================================================================
53 *
54 * This product includes cryptographic software written by Eric Young
55 * (eay@cryptsoft.com). This product includes software written by Tim
56 * Hudson (tjh@cryptsoft.com).
57 *
58 */
59
60#ifndef INCLUDED_TIMEOUTS_H
61#define INCLUDED_TIMEOUTS_H
62
63/* numbers in us */
64#define DGRAM_RCV_TIMEOUT 250000
65#define DGRAM_SND_TIMEOUT 250000
66
67#endif /* ! INCLUDED_TIMEOUTS_H */
diff --git a/src/usr.bin/openssl/ts.c b/src/usr.bin/openssl/ts.c
new file mode 100644
index 0000000000..fab79b9cee
--- /dev/null
+++ b/src/usr.bin/openssl/ts.c
@@ -0,0 +1,1102 @@
1/* $OpenBSD: ts.c,v 1.1 2014/08/26 17:47:25 jsing Exp $ */
2/* Written by Zoltan Glozik (zglozik@stones.com) for the OpenSSL
3 * project 2002.
4 */
5/* ====================================================================
6 * Copyright (c) 2001 The OpenSSL Project. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
19 *
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24 *
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * licensing@OpenSSL.org.
29 *
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
33 *
34 * 6. Redistributions of any form whatsoever must retain the following
35 * acknowledgment:
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
52 *
53 * This product includes cryptographic software written by Eric Young
54 * (eay@cryptsoft.com). This product includes software written by Tim
55 * Hudson (tjh@cryptsoft.com).
56 *
57 */
58
59#include <stdio.h>
60#include <stdlib.h>
61#include <string.h>
62
63#include "apps.h"
64
65#include <openssl/bio.h>
66#include <openssl/bn.h>
67#include <openssl/err.h>
68#include <openssl/pem.h>
69#include <openssl/rand.h>
70#include <openssl/ts.h>
71
72/* Length of the nonce of the request in bits (must be a multiple of 8). */
73#define NONCE_LENGTH 64
74
75/* Macro definitions for the configuration file. */
76#define ENV_OID_FILE "oid_file"
77
78/* Local function declarations. */
79
80static ASN1_OBJECT *txt2obj(const char *oid);
81static CONF *load_config_file(const char *configfile);
82
83/* Query related functions. */
84static int query_command(const char *data, char *digest,
85 const EVP_MD * md, const char *policy, int no_nonce,
86 int cert, const char *in, const char *out, int text);
87static BIO *BIO_open_with_default(const char *file, const char *mode,
88 FILE * default_fp);
89static TS_REQ *create_query(BIO * data_bio, char *digest, const EVP_MD * md,
90 const char *policy, int no_nonce, int cert);
91static int create_digest(BIO * input, char *digest,
92 const EVP_MD * md, unsigned char **md_value);
93static ASN1_INTEGER *create_nonce(int bits);
94
95/* Reply related functions. */
96static int reply_command(CONF * conf, char *section, char *engine,
97 char *queryfile, char *passin, char *inkey,
98 char *signer, char *chain, const char *policy,
99 char *in, int token_in, char *out, int token_out,
100 int text);
101static TS_RESP *read_PKCS7(BIO * in_bio);
102static TS_RESP *create_response(CONF * conf, const char *section, char *engine,
103 char *queryfile, char *passin, char *inkey,
104 char *signer, char *chain, const char *policy);
105static ASN1_INTEGER *serial_cb(TS_RESP_CTX * ctx, void *data);
106static ASN1_INTEGER *next_serial(const char *serialfile);
107static int save_ts_serial(const char *serialfile, ASN1_INTEGER * serial);
108
109/* Verify related functions. */
110static int verify_command(char *data, char *digest, char *queryfile,
111 char *in, int token_in,
112 char *ca_path, char *ca_file, char *untrusted);
113static TS_VERIFY_CTX *create_verify_ctx(char *data, char *digest,
114 char *queryfile,
115 char *ca_path, char *ca_file,
116 char *untrusted);
117static X509_STORE *create_cert_store(char *ca_path, char *ca_file);
118static int verify_cb(int ok, X509_STORE_CTX * ctx);
119
120/* Main function definition. */
121int ts_main(int, char **);
122
123int
124ts_main(int argc, char **argv)
125{
126 int ret = 1;
127 char *configfile = NULL;
128 char *section = NULL;
129 CONF *conf = NULL;
130 enum mode {
131 CMD_NONE, CMD_QUERY, CMD_REPLY, CMD_VERIFY
132 } mode = CMD_NONE;
133 char *data = NULL;
134 char *digest = NULL;
135 const EVP_MD *md = NULL;
136 char *policy = NULL;
137 int no_nonce = 0;
138 int cert = 0;
139 char *in = NULL;
140 char *out = NULL;
141 int text = 0;
142 char *queryfile = NULL;
143 char *passin = NULL; /* Password source. */
144 char *password = NULL; /* Password itself. */
145 char *inkey = NULL;
146 char *signer = NULL;
147 char *chain = NULL;
148 char *ca_path = NULL;
149 char *ca_file = NULL;
150 char *untrusted = NULL;
151 char *engine = NULL;
152 /* Input is ContentInfo instead of TimeStampResp. */
153 int token_in = 0;
154 /* Output is ContentInfo instead of TimeStampResp. */
155 int token_out = 0;
156
157 ERR_load_crypto_strings();
158
159 for (argc--, argv++; argc > 0; argc--, argv++) {
160 if (strcmp(*argv, "-config") == 0) {
161 if (argc-- < 1)
162 goto usage;
163 configfile = *++argv;
164 } else if (strcmp(*argv, "-section") == 0) {
165 if (argc-- < 1)
166 goto usage;
167 section = *++argv;
168 } else if (strcmp(*argv, "-query") == 0) {
169 if (mode != CMD_NONE)
170 goto usage;
171 mode = CMD_QUERY;
172 } else if (strcmp(*argv, "-data") == 0) {
173 if (argc-- < 1)
174 goto usage;
175 data = *++argv;
176 } else if (strcmp(*argv, "-digest") == 0) {
177 if (argc-- < 1)
178 goto usage;
179 digest = *++argv;
180 } else if (strcmp(*argv, "-policy") == 0) {
181 if (argc-- < 1)
182 goto usage;
183 policy = *++argv;
184 } else if (strcmp(*argv, "-no_nonce") == 0) {
185 no_nonce = 1;
186 } else if (strcmp(*argv, "-cert") == 0) {
187 cert = 1;
188 } else if (strcmp(*argv, "-in") == 0) {
189 if (argc-- < 1)
190 goto usage;
191 in = *++argv;
192 } else if (strcmp(*argv, "-token_in") == 0) {
193 token_in = 1;
194 } else if (strcmp(*argv, "-out") == 0) {
195 if (argc-- < 1)
196 goto usage;
197 out = *++argv;
198 } else if (strcmp(*argv, "-token_out") == 0) {
199 token_out = 1;
200 } else if (strcmp(*argv, "-text") == 0) {
201 text = 1;
202 } else if (strcmp(*argv, "-reply") == 0) {
203 if (mode != CMD_NONE)
204 goto usage;
205 mode = CMD_REPLY;
206 } else if (strcmp(*argv, "-queryfile") == 0) {
207 if (argc-- < 1)
208 goto usage;
209 queryfile = *++argv;
210 } else if (strcmp(*argv, "-passin") == 0) {
211 if (argc-- < 1)
212 goto usage;
213 passin = *++argv;
214 } else if (strcmp(*argv, "-inkey") == 0) {
215 if (argc-- < 1)
216 goto usage;
217 inkey = *++argv;
218 } else if (strcmp(*argv, "-signer") == 0) {
219 if (argc-- < 1)
220 goto usage;
221 signer = *++argv;
222 } else if (strcmp(*argv, "-chain") == 0) {
223 if (argc-- < 1)
224 goto usage;
225 chain = *++argv;
226 } else if (strcmp(*argv, "-verify") == 0) {
227 if (mode != CMD_NONE)
228 goto usage;
229 mode = CMD_VERIFY;
230 } else if (strcmp(*argv, "-CApath") == 0) {
231 if (argc-- < 1)
232 goto usage;
233 ca_path = *++argv;
234 } else if (strcmp(*argv, "-CAfile") == 0) {
235 if (argc-- < 1)
236 goto usage;
237 ca_file = *++argv;
238 } else if (strcmp(*argv, "-untrusted") == 0) {
239 if (argc-- < 1)
240 goto usage;
241 untrusted = *++argv;
242 } else if (strcmp(*argv, "-engine") == 0) {
243 if (argc-- < 1)
244 goto usage;
245 engine = *++argv;
246 } else if ((md = EVP_get_digestbyname(*argv + 1)) != NULL) {
247 /* empty. */
248 } else
249 goto usage;
250 }
251
252 /* Get the password if required. */
253 if (mode == CMD_REPLY && passin &&
254 !app_passwd(bio_err, passin, NULL, &password, NULL)) {
255 BIO_printf(bio_err, "Error getting password.\n");
256 goto cleanup;
257 }
258 /*
259 * Check consistency of parameters and execute the appropriate
260 * function.
261 */
262 switch (mode) {
263 case CMD_NONE:
264 goto usage;
265 case CMD_QUERY:
266 /*
267 * Data file and message imprint cannot be specified at the
268 * same time.
269 */
270 ret = data != NULL && digest != NULL;
271 if (ret)
272 goto usage;
273 /* Load the config file for possible policy OIDs. */
274 conf = load_config_file(configfile);
275 ret = !query_command(data, digest, md, policy, no_nonce, cert,
276 in, out, text);
277 break;
278 case CMD_REPLY:
279 conf = load_config_file(configfile);
280 if (in == NULL) {
281 ret = !(queryfile != NULL && conf != NULL && !token_in);
282 if (ret)
283 goto usage;
284 } else {
285 /* 'in' and 'queryfile' are exclusive. */
286 ret = !(queryfile == NULL);
287 if (ret)
288 goto usage;
289 }
290
291 ret = !reply_command(conf, section, engine, queryfile,
292 password, inkey, signer, chain, policy,
293 in, token_in, out, token_out, text);
294 break;
295 case CMD_VERIFY:
296 ret = !(((queryfile && !data && !digest) ||
297 (!queryfile && data && !digest) ||
298 (!queryfile && !data && digest)) && in != NULL);
299 if (ret)
300 goto usage;
301
302 ret = !verify_command(data, digest, queryfile, in, token_in,
303 ca_path, ca_file, untrusted);
304 }
305
306 goto cleanup;
307
308usage:
309 BIO_printf(bio_err, "usage:\n"
310 "ts -query [-config configfile] "
311 "[-data file_to_hash] [-digest digest_bytes]"
312 "[-md2|-md4|-md5|-sha|-sha1|-mdc2|-ripemd160] "
313 "[-policy object_id] [-no_nonce] [-cert] "
314 "[-in request.tsq] [-out request.tsq] [-text]\n");
315 BIO_printf(bio_err, "or\n"
316 "ts -reply [-config configfile] [-section tsa_section] "
317 "[-queryfile request.tsq] [-passin password] "
318 "[-signer tsa_cert.pem] [-inkey private_key.pem] "
319 "[-chain certs_file.pem] [-policy object_id] "
320 "[-in response.tsr] [-token_in] "
321 "[-out response.tsr] [-token_out] [-text] [-engine id]\n");
322 BIO_printf(bio_err, "or\n"
323 "ts -verify [-data file_to_hash] [-digest digest_bytes] "
324 "[-queryfile request.tsq] "
325 "-in response.tsr [-token_in] "
326 "-CApath ca_path -CAfile ca_file.pem "
327 "-untrusted cert_file.pem\n");
328
329cleanup:
330 /* Clean up. */
331 NCONF_free(conf);
332 free(password);
333 OBJ_cleanup();
334
335 return (ret);
336}
337
338/*
339 * Configuration file-related function definitions.
340 */
341
342static ASN1_OBJECT *
343txt2obj(const char *oid)
344{
345 ASN1_OBJECT *oid_obj = NULL;
346
347 if (!(oid_obj = OBJ_txt2obj(oid, 0)))
348 BIO_printf(bio_err, "cannot convert %s to OID\n", oid);
349
350 return oid_obj;
351}
352
353static CONF *
354load_config_file(const char *configfile)
355{
356 CONF *conf = NULL;
357 long errorline = -1;
358
359 if (!configfile)
360 configfile = getenv("OPENSSL_CONF");
361 if (!configfile)
362 configfile = getenv("SSLEAY_CONF");
363
364 if (configfile &&
365 (!(conf = NCONF_new(NULL)) ||
366 NCONF_load(conf, configfile, &errorline) <= 0)) {
367 if (errorline <= 0)
368 BIO_printf(bio_err, "error loading the config file "
369 "'%s'\n", configfile);
370 else
371 BIO_printf(bio_err, "error on line %ld of config file "
372 "'%s'\n", errorline, configfile);
373 }
374 if (conf != NULL) {
375 const char *p;
376
377 BIO_printf(bio_err, "Using configuration from %s\n",
378 configfile);
379 p = NCONF_get_string(conf, NULL, ENV_OID_FILE);
380 if (p != NULL) {
381 BIO *oid_bio = BIO_new_file(p, "r");
382 if (!oid_bio)
383 ERR_print_errors(bio_err);
384 else {
385 OBJ_create_objects(oid_bio);
386 BIO_free_all(oid_bio);
387 }
388 } else
389 ERR_clear_error();
390 if (!add_oid_section(bio_err, conf))
391 ERR_print_errors(bio_err);
392 }
393 return conf;
394}
395
396/*
397 * Query-related method definitions.
398 */
399
400static int
401query_command(const char *data, char *digest, const EVP_MD * md,
402 const char *policy, int no_nonce, int cert, const char *in,
403 const char *out, int text)
404{
405 int ret = 0;
406 TS_REQ *query = NULL;
407 BIO *in_bio = NULL;
408 BIO *data_bio = NULL;
409 BIO *out_bio = NULL;
410
411 /* Build query object either from file or from scratch. */
412 if (in != NULL) {
413 if ((in_bio = BIO_new_file(in, "rb")) == NULL)
414 goto end;
415 query = d2i_TS_REQ_bio(in_bio, NULL);
416 } else {
417 /* Open the file if no explicit digest bytes were specified. */
418 if (!digest &&
419 !(data_bio = BIO_open_with_default(data, "rb", stdin)))
420 goto end;
421 /* Creating the query object. */
422 query = create_query(data_bio, digest, md,
423 policy, no_nonce, cert);
424 /* Saving the random number generator state. */
425 }
426 if (query == NULL)
427 goto end;
428
429 /* Write query either in ASN.1 or in text format. */
430 if ((out_bio = BIO_open_with_default(out, "wb", stdout)) == NULL)
431 goto end;
432 if (text) {
433 /* Text output. */
434 if (!TS_REQ_print_bio(out_bio, query))
435 goto end;
436 } else {
437 /* ASN.1 output. */
438 if (!i2d_TS_REQ_bio(out_bio, query))
439 goto end;
440 }
441
442 ret = 1;
443
444end:
445 ERR_print_errors(bio_err);
446
447 /* Clean up. */
448 BIO_free_all(in_bio);
449 BIO_free_all(data_bio);
450 BIO_free_all(out_bio);
451 TS_REQ_free(query);
452
453 return ret;
454}
455
456static BIO *
457BIO_open_with_default(const char *file, const char *mode, FILE * default_fp)
458{
459 return file == NULL ? BIO_new_fp(default_fp, BIO_NOCLOSE) :
460 BIO_new_file(file, mode);
461}
462
463static TS_REQ *
464create_query(BIO * data_bio, char *digest, const EVP_MD * md,
465 const char *policy, int no_nonce, int cert)
466{
467 int ret = 0;
468 TS_REQ *ts_req = NULL;
469 int len;
470 TS_MSG_IMPRINT *msg_imprint = NULL;
471 X509_ALGOR *algo = NULL;
472 unsigned char *data = NULL;
473 ASN1_OBJECT *policy_obj = NULL;
474 ASN1_INTEGER *nonce_asn1 = NULL;
475
476 /* Setting default message digest. */
477 if (!md && !(md = EVP_get_digestbyname("sha1")))
478 goto err;
479
480 /* Creating request object. */
481 if (!(ts_req = TS_REQ_new()))
482 goto err;
483
484 /* Setting version. */
485 if (!TS_REQ_set_version(ts_req, 1))
486 goto err;
487
488 /* Creating and adding MSG_IMPRINT object. */
489 if (!(msg_imprint = TS_MSG_IMPRINT_new()))
490 goto err;
491
492 /* Adding algorithm. */
493 if (!(algo = X509_ALGOR_new()))
494 goto err;
495 if (!(algo->algorithm = OBJ_nid2obj(EVP_MD_type(md))))
496 goto err;
497 if (!(algo->parameter = ASN1_TYPE_new()))
498 goto err;
499 algo->parameter->type = V_ASN1_NULL;
500 if (!TS_MSG_IMPRINT_set_algo(msg_imprint, algo))
501 goto err;
502
503 /* Adding message digest. */
504 if ((len = create_digest(data_bio, digest, md, &data)) == 0)
505 goto err;
506 if (!TS_MSG_IMPRINT_set_msg(msg_imprint, data, len))
507 goto err;
508
509 if (!TS_REQ_set_msg_imprint(ts_req, msg_imprint))
510 goto err;
511
512 /* Setting policy if requested. */
513 if (policy && !(policy_obj = txt2obj(policy)))
514 goto err;
515 if (policy_obj && !TS_REQ_set_policy_id(ts_req, policy_obj))
516 goto err;
517
518 /* Setting nonce if requested. */
519 if (!no_nonce && !(nonce_asn1 = create_nonce(NONCE_LENGTH)))
520 goto err;
521 if (nonce_asn1 && !TS_REQ_set_nonce(ts_req, nonce_asn1))
522 goto err;
523
524 /* Setting certificate request flag if requested. */
525 if (!TS_REQ_set_cert_req(ts_req, cert))
526 goto err;
527
528 ret = 1;
529
530err:
531 if (!ret) {
532 TS_REQ_free(ts_req);
533 ts_req = NULL;
534 BIO_printf(bio_err, "could not create query\n");
535 }
536 TS_MSG_IMPRINT_free(msg_imprint);
537 X509_ALGOR_free(algo);
538 free(data);
539 ASN1_OBJECT_free(policy_obj);
540 ASN1_INTEGER_free(nonce_asn1);
541
542 return ts_req;
543}
544
545static int
546create_digest(BIO * input, char *digest, const EVP_MD * md,
547 unsigned char **md_value)
548{
549 int md_value_len;
550
551 md_value_len = EVP_MD_size(md);
552 if (md_value_len < 0)
553 goto err;
554 if (input) {
555 /* Digest must be computed from an input file. */
556 EVP_MD_CTX md_ctx;
557 unsigned char buffer[4096];
558 int length;
559
560 *md_value = malloc(md_value_len);
561 if (*md_value == 0)
562 goto err;
563
564 EVP_DigestInit(&md_ctx, md);
565 while ((length = BIO_read(input, buffer, sizeof(buffer))) > 0) {
566 EVP_DigestUpdate(&md_ctx, buffer, length);
567 }
568 EVP_DigestFinal(&md_ctx, *md_value, NULL);
569 } else {
570 /* Digest bytes are specified with digest. */
571 long digest_len;
572 *md_value = string_to_hex(digest, &digest_len);
573 if (!*md_value || md_value_len != digest_len) {
574 free(*md_value);
575 *md_value = NULL;
576 BIO_printf(bio_err, "bad digest, %d bytes "
577 "must be specified\n", md_value_len);
578 goto err;
579 }
580 }
581
582 return md_value_len;
583err:
584 return 0;
585}
586
587static ASN1_INTEGER *
588create_nonce(int bits)
589{
590 unsigned char buf[20];
591 ASN1_INTEGER *nonce = NULL;
592 int len = (bits - 1) / 8 + 1;
593 int i;
594
595 /* Generating random byte sequence. */
596 if (len > (int) sizeof(buf))
597 goto err;
598 if (RAND_bytes(buf, len) <= 0)
599 goto err;
600
601 /* Find the first non-zero byte and creating ASN1_INTEGER object. */
602 for (i = 0; i < len && !buf[i]; ++i)
603 ;
604 if (!(nonce = ASN1_INTEGER_new()))
605 goto err;
606 free(nonce->data);
607 /* Allocate at least one byte. */
608 nonce->length = len - i;
609 if (!(nonce->data = malloc(nonce->length + 1)))
610 goto err;
611 memcpy(nonce->data, buf + i, nonce->length);
612
613 return nonce;
614
615err:
616 BIO_printf(bio_err, "could not create nonce\n");
617 ASN1_INTEGER_free(nonce);
618 return NULL;
619}
620/*
621 * Reply-related method definitions.
622 */
623
624static int
625reply_command(CONF * conf, char *section, char *engine, char *queryfile,
626 char *passin, char *inkey, char *signer, char *chain, const char *policy,
627 char *in, int token_in, char *out, int token_out, int text)
628{
629 int ret = 0;
630 TS_RESP *response = NULL;
631 BIO *in_bio = NULL;
632 BIO *query_bio = NULL;
633 BIO *inkey_bio = NULL;
634 BIO *signer_bio = NULL;
635 BIO *out_bio = NULL;
636
637 /* Build response object either from response or query. */
638 if (in != NULL) {
639 if ((in_bio = BIO_new_file(in, "rb")) == NULL)
640 goto end;
641 if (token_in) {
642 /*
643 * We have a ContentInfo (PKCS7) object, add
644 * 'granted' status info around it.
645 */
646 response = read_PKCS7(in_bio);
647 } else {
648 /* We have a ready-made TS_RESP object. */
649 response = d2i_TS_RESP_bio(in_bio, NULL);
650 }
651 } else {
652 response = create_response(conf, section, engine, queryfile,
653 passin, inkey, signer, chain,
654 policy);
655 if (response)
656 BIO_printf(bio_err, "Response has been generated.\n");
657 else
658 BIO_printf(bio_err, "Response is not generated.\n");
659 }
660 if (response == NULL)
661 goto end;
662
663 /* Write response either in ASN.1 or text format. */
664 if ((out_bio = BIO_open_with_default(out, "wb", stdout)) == NULL)
665 goto end;
666 if (text) {
667 /* Text output. */
668 if (token_out) {
669 TS_TST_INFO *tst_info = TS_RESP_get_tst_info(response);
670 if (!TS_TST_INFO_print_bio(out_bio, tst_info))
671 goto end;
672 } else {
673 if (!TS_RESP_print_bio(out_bio, response))
674 goto end;
675 }
676 } else {
677 /* ASN.1 DER output. */
678 if (token_out) {
679 PKCS7 *token = TS_RESP_get_token(response);
680 if (!i2d_PKCS7_bio(out_bio, token))
681 goto end;
682 } else {
683 if (!i2d_TS_RESP_bio(out_bio, response))
684 goto end;
685 }
686 }
687
688 ret = 1;
689
690end:
691 ERR_print_errors(bio_err);
692
693 /* Clean up. */
694 BIO_free_all(in_bio);
695 BIO_free_all(query_bio);
696 BIO_free_all(inkey_bio);
697 BIO_free_all(signer_bio);
698 BIO_free_all(out_bio);
699 TS_RESP_free(response);
700
701 return ret;
702}
703
704/* Reads a PKCS7 token and adds default 'granted' status info to it. */
705static TS_RESP *
706read_PKCS7(BIO * in_bio)
707{
708 int ret = 0;
709 PKCS7 *token = NULL;
710 TS_TST_INFO *tst_info = NULL;
711 TS_RESP *resp = NULL;
712 TS_STATUS_INFO *si = NULL;
713
714 /* Read PKCS7 object and extract the signed time stamp info. */
715 if (!(token = d2i_PKCS7_bio(in_bio, NULL)))
716 goto end;
717 if (!(tst_info = PKCS7_to_TS_TST_INFO(token)))
718 goto end;
719
720 /* Creating response object. */
721 if (!(resp = TS_RESP_new()))
722 goto end;
723
724 /* Create granted status info. */
725 if (!(si = TS_STATUS_INFO_new()))
726 goto end;
727 if (!(ASN1_INTEGER_set(si->status, TS_STATUS_GRANTED)))
728 goto end;
729 if (!TS_RESP_set_status_info(resp, si))
730 goto end;
731
732 /* Setting encapsulated token. */
733 TS_RESP_set_tst_info(resp, token, tst_info);
734 token = NULL; /* Ownership is lost. */
735 tst_info = NULL; /* Ownership is lost. */
736
737 ret = 1;
738end:
739 PKCS7_free(token);
740 TS_TST_INFO_free(tst_info);
741 if (!ret) {
742 TS_RESP_free(resp);
743 resp = NULL;
744 }
745 TS_STATUS_INFO_free(si);
746 return resp;
747}
748
749static TS_RESP *
750create_response(CONF * conf, const char *section, char *engine,
751 char *queryfile, char *passin, char *inkey,
752 char *signer, char *chain, const char *policy)
753{
754 int ret = 0;
755 TS_RESP *response = NULL;
756 BIO *query_bio = NULL;
757 TS_RESP_CTX *resp_ctx = NULL;
758
759 if (!(query_bio = BIO_new_file(queryfile, "rb")))
760 goto end;
761
762 /* Getting TSA configuration section. */
763 if (!(section = TS_CONF_get_tsa_section(conf, section)))
764 goto end;
765
766 /* Setting up response generation context. */
767 if (!(resp_ctx = TS_RESP_CTX_new()))
768 goto end;
769
770 /* Setting serial number provider callback. */
771 if (!TS_CONF_set_serial(conf, section, serial_cb, resp_ctx))
772 goto end;
773#ifndef OPENSSL_NO_ENGINE
774 /* Setting default OpenSSL engine. */
775 if (!TS_CONF_set_crypto_device(conf, section, engine))
776 goto end;
777#endif
778
779 /* Setting TSA signer certificate. */
780 if (!TS_CONF_set_signer_cert(conf, section, signer, resp_ctx))
781 goto end;
782
783 /* Setting TSA signer certificate chain. */
784 if (!TS_CONF_set_certs(conf, section, chain, resp_ctx))
785 goto end;
786
787 /* Setting TSA signer private key. */
788 if (!TS_CONF_set_signer_key(conf, section, inkey, passin, resp_ctx))
789 goto end;
790
791 /* Setting default policy OID. */
792 if (!TS_CONF_set_def_policy(conf, section, policy, resp_ctx))
793 goto end;
794
795 /* Setting acceptable policy OIDs. */
796 if (!TS_CONF_set_policies(conf, section, resp_ctx))
797 goto end;
798
799 /* Setting the acceptable one-way hash algorithms. */
800 if (!TS_CONF_set_digests(conf, section, resp_ctx))
801 goto end;
802
803 /* Setting guaranteed time stamp accuracy. */
804 if (!TS_CONF_set_accuracy(conf, section, resp_ctx))
805 goto end;
806
807 /* Setting the precision of the time. */
808 if (!TS_CONF_set_clock_precision_digits(conf, section, resp_ctx))
809 goto end;
810
811 /* Setting the ordering flaf if requested. */
812 if (!TS_CONF_set_ordering(conf, section, resp_ctx))
813 goto end;
814
815 /* Setting the TSA name required flag if requested. */
816 if (!TS_CONF_set_tsa_name(conf, section, resp_ctx))
817 goto end;
818
819 /* Setting the ESS cert id chain flag if requested. */
820 if (!TS_CONF_set_ess_cert_id_chain(conf, section, resp_ctx))
821 goto end;
822
823 /* Creating the response. */
824 if (!(response = TS_RESP_create_response(resp_ctx, query_bio)))
825 goto end;
826
827 ret = 1;
828end:
829 if (!ret) {
830 TS_RESP_free(response);
831 response = NULL;
832 }
833 TS_RESP_CTX_free(resp_ctx);
834 BIO_free_all(query_bio);
835
836 return response;
837}
838
839static ASN1_INTEGER *
840serial_cb(TS_RESP_CTX * ctx, void *data)
841{
842 const char *serial_file = (const char *) data;
843 ASN1_INTEGER *serial = next_serial(serial_file);
844
845 if (!serial) {
846 TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
847 "Error during serial number "
848 "generation.");
849 TS_RESP_CTX_add_failure_info(ctx,
850 TS_INFO_ADD_INFO_NOT_AVAILABLE);
851 } else
852 save_ts_serial(serial_file, serial);
853
854 return serial;
855}
856
857static ASN1_INTEGER *
858next_serial(const char *serialfile)
859{
860 int ret = 0;
861 BIO *in = NULL;
862 ASN1_INTEGER *serial = NULL;
863 BIGNUM *bn = NULL;
864
865 if (!(serial = ASN1_INTEGER_new()))
866 goto err;
867
868 if (!(in = BIO_new_file(serialfile, "r"))) {
869 ERR_clear_error();
870 BIO_printf(bio_err, "Warning: could not open file %s for "
871 "reading, using serial number: 1\n", serialfile);
872 if (!ASN1_INTEGER_set(serial, 1))
873 goto err;
874 } else {
875 char buf[1024];
876 if (!a2i_ASN1_INTEGER(in, serial, buf, sizeof(buf))) {
877 BIO_printf(bio_err, "unable to load number from %s\n",
878 serialfile);
879 goto err;
880 }
881 if (!(bn = ASN1_INTEGER_to_BN(serial, NULL)))
882 goto err;
883 ASN1_INTEGER_free(serial);
884 serial = NULL;
885 if (!BN_add_word(bn, 1))
886 goto err;
887 if (!(serial = BN_to_ASN1_INTEGER(bn, NULL)))
888 goto err;
889 }
890 ret = 1;
891err:
892 if (!ret) {
893 ASN1_INTEGER_free(serial);
894 serial = NULL;
895 }
896 BIO_free_all(in);
897 BN_free(bn);
898 return serial;
899}
900
901static int
902save_ts_serial(const char *serialfile, ASN1_INTEGER * serial)
903{
904 int ret = 0;
905 BIO *out = NULL;
906
907 if (!(out = BIO_new_file(serialfile, "w")))
908 goto err;
909 if (i2a_ASN1_INTEGER(out, serial) <= 0)
910 goto err;
911 if (BIO_puts(out, "\n") <= 0)
912 goto err;
913 ret = 1;
914err:
915 if (!ret)
916 BIO_printf(bio_err, "could not save serial number to %s\n",
917 serialfile);
918 BIO_free_all(out);
919 return ret;
920}
921
922/*
923 * Verify-related method definitions.
924 */
925
926static int
927verify_command(char *data, char *digest, char *queryfile, char *in,
928 int token_in, char *ca_path, char *ca_file, char *untrusted)
929{
930 BIO *in_bio = NULL;
931 PKCS7 *token = NULL;
932 TS_RESP *response = NULL;
933 TS_VERIFY_CTX *verify_ctx = NULL;
934 int ret = 0;
935
936 /* Decode the token (PKCS7) or response (TS_RESP) files. */
937 if (!(in_bio = BIO_new_file(in, "rb")))
938 goto end;
939 if (token_in) {
940 if (!(token = d2i_PKCS7_bio(in_bio, NULL)))
941 goto end;
942 } else {
943 if (!(response = d2i_TS_RESP_bio(in_bio, NULL)))
944 goto end;
945 }
946
947 if (!(verify_ctx = create_verify_ctx(data, digest, queryfile,
948 ca_path, ca_file, untrusted)))
949 goto end;
950
951 /* Checking the token or response against the request. */
952 ret = token_in ?
953 TS_RESP_verify_token(verify_ctx, token) :
954 TS_RESP_verify_response(verify_ctx, response);
955
956end:
957 printf("Verification: ");
958 if (ret)
959 printf("OK\n");
960 else {
961 printf("FAILED\n");
962 /* Print errors, if there are any. */
963 ERR_print_errors(bio_err);
964 }
965
966 /* Clean up. */
967 BIO_free_all(in_bio);
968 PKCS7_free(token);
969 TS_RESP_free(response);
970 TS_VERIFY_CTX_free(verify_ctx);
971 return ret;
972}
973
974static TS_VERIFY_CTX *
975create_verify_ctx(char *data, char *digest, char *queryfile, char *ca_path,
976 char *ca_file, char *untrusted)
977{
978 TS_VERIFY_CTX *ctx = NULL;
979 BIO *input = NULL;
980 TS_REQ *request = NULL;
981 int ret = 0;
982
983 if (data != NULL || digest != NULL) {
984 if (!(ctx = TS_VERIFY_CTX_new()))
985 goto err;
986 ctx->flags = TS_VFY_VERSION | TS_VFY_SIGNER;
987 if (data != NULL) {
988 ctx->flags |= TS_VFY_DATA;
989 if (!(ctx->data = BIO_new_file(data, "rb")))
990 goto err;
991 } else if (digest != NULL) {
992 long imprint_len;
993 ctx->flags |= TS_VFY_IMPRINT;
994 if (!(ctx->imprint = string_to_hex(digest,
995 &imprint_len))) {
996 BIO_printf(bio_err, "invalid digest string\n");
997 goto err;
998 }
999 ctx->imprint_len = imprint_len;
1000 }
1001 } else if (queryfile != NULL) {
1002 /*
1003 * The request has just to be read, decoded and converted to
1004 * a verify context object.
1005 */
1006 if (!(input = BIO_new_file(queryfile, "rb")))
1007 goto err;
1008 if (!(request = d2i_TS_REQ_bio(input, NULL)))
1009 goto err;
1010 if (!(ctx = TS_REQ_to_TS_VERIFY_CTX(request, NULL)))
1011 goto err;
1012 } else
1013 return NULL;
1014
1015 /* Add the signature verification flag and arguments. */
1016 ctx->flags |= TS_VFY_SIGNATURE;
1017
1018 /* Initialising the X509_STORE object. */
1019 if (!(ctx->store = create_cert_store(ca_path, ca_file)))
1020 goto err;
1021
1022 /* Loading untrusted certificates. */
1023 if (untrusted && !(ctx->certs = TS_CONF_load_certs(untrusted)))
1024 goto err;
1025
1026 ret = 1;
1027err:
1028 if (!ret) {
1029 TS_VERIFY_CTX_free(ctx);
1030 ctx = NULL;
1031 }
1032 BIO_free_all(input);
1033 TS_REQ_free(request);
1034 return ctx;
1035}
1036
1037static X509_STORE *
1038create_cert_store(char *ca_path, char *ca_file)
1039{
1040 X509_STORE *cert_ctx = NULL;
1041 X509_LOOKUP *lookup = NULL;
1042 int i;
1043
1044 /* Creating the X509_STORE object. */
1045 cert_ctx = X509_STORE_new();
1046
1047 /* Setting the callback for certificate chain verification. */
1048 X509_STORE_set_verify_cb(cert_ctx, verify_cb);
1049
1050 /* Adding a trusted certificate directory source. */
1051 if (ca_path) {
1052 lookup = X509_STORE_add_lookup(cert_ctx,
1053 X509_LOOKUP_hash_dir());
1054 if (lookup == NULL) {
1055 BIO_printf(bio_err, "memory allocation failure\n");
1056 goto err;
1057 }
1058 i = X509_LOOKUP_add_dir(lookup, ca_path, X509_FILETYPE_PEM);
1059 if (!i) {
1060 BIO_printf(bio_err, "Error loading directory %s\n",
1061 ca_path);
1062 goto err;
1063 }
1064 }
1065 /* Adding a trusted certificate file source. */
1066 if (ca_file) {
1067 lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file());
1068 if (lookup == NULL) {
1069 BIO_printf(bio_err, "memory allocation failure\n");
1070 goto err;
1071 }
1072 i = X509_LOOKUP_load_file(lookup, ca_file, X509_FILETYPE_PEM);
1073 if (!i) {
1074 BIO_printf(bio_err, "Error loading file %s\n", ca_file);
1075 goto err;
1076 }
1077 }
1078 return cert_ctx;
1079err:
1080 X509_STORE_free(cert_ctx);
1081 return NULL;
1082}
1083
1084static int
1085verify_cb(int ok, X509_STORE_CTX * ctx)
1086{
1087 /*
1088 char buf[256];
1089
1090 if (!ok)
1091 {
1092 X509_NAME_oneline(X509_get_subject_name(ctx->current_cert),
1093 buf, sizeof(buf));
1094 printf("%s\n", buf);
1095 printf("error %d at %d depth lookup: %s\n",
1096 ctx->error, ctx->error_depth,
1097 X509_verify_cert_error_string(ctx->error));
1098 }
1099 */
1100
1101 return ok;
1102}
diff --git a/src/usr.bin/openssl/verify.c b/src/usr.bin/openssl/verify.c
new file mode 100644
index 0000000000..057c467372
--- /dev/null
+++ b/src/usr.bin/openssl/verify.c
@@ -0,0 +1,339 @@
1/* $OpenBSD: verify.c,v 1.1 2014/08/26 17:47:25 jsing 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#include <stdlib.h>
61#include <string.h>
62
63#include "apps.h"
64
65#include <openssl/bio.h>
66#include <openssl/err.h>
67#include <openssl/pem.h>
68#include <openssl/x509.h>
69#include <openssl/x509v3.h>
70
71static int cb(int ok, X509_STORE_CTX * ctx);
72static int check(X509_STORE * ctx, char *file, STACK_OF(X509) * uchain,
73 STACK_OF(X509) * tchain, STACK_OF(X509_CRL) * crls, ENGINE * e);
74static int v_verbose = 0, vflags = 0;
75
76int verify_main(int, char **);
77
78int
79verify_main(int argc, char **argv)
80{
81 ENGINE *e = NULL;
82 int i, ret = 1, badarg = 0;
83 char *CApath = NULL, *CAfile = NULL;
84 char *untfile = NULL, *trustfile = NULL, *crlfile = NULL;
85 STACK_OF(X509) * untrusted = NULL, *trusted = NULL;
86 STACK_OF(X509_CRL) * crls = NULL;
87 X509_STORE *cert_ctx = NULL;
88 X509_LOOKUP *lookup = NULL;
89 X509_VERIFY_PARAM *vpm = NULL;
90#ifndef OPENSSL_NO_ENGINE
91 char *engine = NULL;
92#endif
93
94 cert_ctx = X509_STORE_new();
95 if (cert_ctx == NULL)
96 goto end;
97 X509_STORE_set_verify_cb(cert_ctx, cb);
98
99 ERR_load_crypto_strings();
100
101 argc--;
102 argv++;
103 for (;;) {
104 if (argc >= 1) {
105 if (strcmp(*argv, "-CApath") == 0) {
106 if (argc-- < 1)
107 goto end;
108 CApath = *(++argv);
109 } else if (strcmp(*argv, "-CAfile") == 0) {
110 if (argc-- < 1)
111 goto end;
112 CAfile = *(++argv);
113 } else if (args_verify(&argv, &argc, &badarg, bio_err,
114 &vpm)) {
115 if (badarg)
116 goto end;
117 continue;
118 } else if (strcmp(*argv, "-untrusted") == 0) {
119 if (argc-- < 1)
120 goto end;
121 untfile = *(++argv);
122 } else if (strcmp(*argv, "-trusted") == 0) {
123 if (argc-- < 1)
124 goto end;
125 trustfile = *(++argv);
126 } else if (strcmp(*argv, "-CRLfile") == 0) {
127 if (argc-- < 1)
128 goto end;
129 crlfile = *(++argv);
130 }
131#ifndef OPENSSL_NO_ENGINE
132 else if (strcmp(*argv, "-engine") == 0) {
133 if (--argc < 1)
134 goto end;
135 engine = *(++argv);
136 }
137#endif
138 else if (strcmp(*argv, "-help") == 0)
139 goto end;
140 else if (strcmp(*argv, "-verbose") == 0)
141 v_verbose = 1;
142 else if (argv[0][0] == '-')
143 goto end;
144 else
145 break;
146 argc--;
147 argv++;
148 } else
149 break;
150 }
151
152#ifndef OPENSSL_NO_ENGINE
153 e = setup_engine(bio_err, engine, 0);
154#endif
155
156 if (vpm)
157 X509_STORE_set1_param(cert_ctx, vpm);
158
159 lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file());
160 if (lookup == NULL)
161 abort();
162 if (CAfile) {
163 i = X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM);
164 if (!i) {
165 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
166 ERR_print_errors(bio_err);
167 goto end;
168 }
169 } else
170 X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
171
172 lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir());
173 if (lookup == NULL)
174 abort();
175 if (CApath) {
176 i = X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM);
177 if (!i) {
178 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
179 ERR_print_errors(bio_err);
180 goto end;
181 }
182 } else
183 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
184
185 ERR_clear_error();
186
187 if (untfile) {
188 untrusted = load_certs(bio_err, untfile, FORMAT_PEM,
189 NULL, e, "untrusted certificates");
190 if (!untrusted)
191 goto end;
192 }
193 if (trustfile) {
194 trusted = load_certs(bio_err, trustfile, FORMAT_PEM,
195 NULL, e, "trusted certificates");
196 if (!trusted)
197 goto end;
198 }
199 if (crlfile) {
200 crls = load_crls(bio_err, crlfile, FORMAT_PEM,
201 NULL, e, "other CRLs");
202 if (!crls)
203 goto end;
204 }
205 ret = 0;
206 if (argc < 1) {
207 if (1 != check(cert_ctx, NULL, untrusted, trusted, crls, e))
208 ret = -1;
209 } else {
210 for (i = 0; i < argc; i++)
211 if (1 != check(cert_ctx, argv[i], untrusted, trusted,
212 crls, e))
213 ret = -1;
214 }
215
216end:
217 if (ret == 1) {
218 BIO_printf(bio_err, "usage: verify [-verbose] [-CApath path] [-CAfile file] [-purpose purpose] [-crl_check]");
219 BIO_printf(bio_err, " [-attime timestamp]");
220#ifndef OPENSSL_NO_ENGINE
221 BIO_printf(bio_err, " [-engine e]");
222#endif
223 BIO_printf(bio_err, " cert1 cert2 ...\n");
224
225 BIO_printf(bio_err, "recognized usages:\n");
226 for (i = 0; i < X509_PURPOSE_get_count(); i++) {
227 X509_PURPOSE *ptmp;
228 ptmp = X509_PURPOSE_get0(i);
229 BIO_printf(bio_err, "\t%-10s\t%s\n",
230 X509_PURPOSE_get0_sname(ptmp),
231 X509_PURPOSE_get0_name(ptmp));
232 }
233 }
234 if (vpm)
235 X509_VERIFY_PARAM_free(vpm);
236 if (cert_ctx != NULL)
237 X509_STORE_free(cert_ctx);
238 sk_X509_pop_free(untrusted, X509_free);
239 sk_X509_pop_free(trusted, X509_free);
240 sk_X509_CRL_pop_free(crls, X509_CRL_free);
241
242 return (ret < 0 ? 2 : ret);
243}
244
245static int
246check(X509_STORE * ctx, char *file, STACK_OF(X509) * uchain,
247 STACK_OF(X509) * tchain, STACK_OF(X509_CRL) * crls, ENGINE * e)
248{
249 X509 *x = NULL;
250 int i = 0, ret = 0;
251 X509_STORE_CTX *csc;
252
253 x = load_cert(bio_err, file, FORMAT_PEM, NULL, e, "certificate file");
254 if (x == NULL)
255 goto end;
256 fprintf(stdout, "%s: ", (file == NULL) ? "stdin" : file);
257
258 csc = X509_STORE_CTX_new();
259 if (csc == NULL) {
260 ERR_print_errors(bio_err);
261 goto end;
262 }
263 X509_STORE_set_flags(ctx, vflags);
264 if (!X509_STORE_CTX_init(csc, ctx, x, uchain)) {
265 ERR_print_errors(bio_err);
266 goto end;
267 }
268 if (tchain)
269 X509_STORE_CTX_trusted_stack(csc, tchain);
270 if (crls)
271 X509_STORE_CTX_set0_crls(csc, crls);
272 i = X509_verify_cert(csc);
273 X509_STORE_CTX_free(csc);
274
275 ret = 0;
276
277end:
278 if (i > 0) {
279 fprintf(stdout, "OK\n");
280 ret = 1;
281 } else
282 ERR_print_errors(bio_err);
283 if (x != NULL)
284 X509_free(x);
285
286 return (ret);
287}
288
289static int
290cb(int ok, X509_STORE_CTX * ctx)
291{
292 int cert_error = X509_STORE_CTX_get_error(ctx);
293 X509 *current_cert = X509_STORE_CTX_get_current_cert(ctx);
294
295 if (!ok) {
296 if (current_cert) {
297 X509_NAME_print_ex_fp(stdout,
298 X509_get_subject_name(current_cert),
299 0, XN_FLAG_ONELINE);
300 printf("\n");
301 }
302 printf("%serror %d at %d depth lookup:%s\n",
303 X509_STORE_CTX_get0_parent_ctx(ctx) ? "[CRL path]" : "",
304 cert_error,
305 X509_STORE_CTX_get_error_depth(ctx),
306 X509_verify_cert_error_string(cert_error));
307 switch (cert_error) {
308 case X509_V_ERR_NO_EXPLICIT_POLICY:
309 policies_print(NULL, ctx);
310 case X509_V_ERR_CERT_HAS_EXPIRED:
311
312 /*
313 * since we are just checking the certificates, it is
314 * ok if they are self signed. But we should still
315 * warn the user.
316 */
317
318 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
319 /* Continue after extension errors too */
320 case X509_V_ERR_INVALID_CA:
321 case X509_V_ERR_INVALID_NON_CA:
322 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
323 case X509_V_ERR_INVALID_PURPOSE:
324 case X509_V_ERR_CRL_HAS_EXPIRED:
325 case X509_V_ERR_CRL_NOT_YET_VALID:
326 case X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION:
327 ok = 1;
328
329 }
330
331 return ok;
332
333 }
334 if (cert_error == X509_V_OK && ok == 2)
335 policies_print(NULL, ctx);
336 if (!v_verbose)
337 ERR_clear_error();
338 return (ok);
339}
diff --git a/src/usr.bin/openssl/version.c b/src/usr.bin/openssl/version.c
new file mode 100644
index 0000000000..afad0c3e11
--- /dev/null
+++ b/src/usr.bin/openssl/version.c
@@ -0,0 +1,208 @@
1/* $OpenBSD: version.c,v 1.1 2014/08/26 17:47:25 jsing 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 * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in
70 * the documentation and/or other materials provided with the
71 * distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 * software must display the following acknowledgment:
75 * "This product includes software developed by the OpenSSL Project
76 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 * endorse or promote products derived from this software without
80 * prior written permission. For written permission, please contact
81 * openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 * nor may "OpenSSL" appear in their names without prior written
85 * permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 * acknowledgment:
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com). This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
111
112#include <stdio.h>
113#include <stdlib.h>
114#include <string.h>
115
116#include "apps.h"
117
118#include <openssl/bn.h>
119#include <openssl/crypto.h>
120#include <openssl/evp.h>
121
122#ifndef OPENSSL_NO_BF
123#include <openssl/blowfish.h>
124#endif
125
126#ifndef OPENSSL_NO_DES
127#include <openssl/des.h>
128#endif
129
130#ifndef OPENSSL_NO_IDEA
131#include <openssl/idea.h>
132#endif
133
134#ifndef OPENSSL_NO_RC4
135#include <openssl/rc4.h>
136#endif
137
138int version_main(int, char **);
139
140int
141version_main(int argc, char **argv)
142{
143 int i, ret = 0;
144 int cflags = 0, version = 0, date = 0, options = 0, platform = 0,
145 dir = 0;
146
147 if (argc == 1)
148 version = 1;
149 for (i = 1; i < argc; i++) {
150 if (strcmp(argv[i], "-v") == 0)
151 version = 1;
152 else if (strcmp(argv[i], "-b") == 0)
153 date = 1;
154 else if (strcmp(argv[i], "-f") == 0)
155 cflags = 1;
156 else if (strcmp(argv[i], "-o") == 0)
157 options = 1;
158 else if (strcmp(argv[i], "-p") == 0)
159 platform = 1;
160 else if (strcmp(argv[i], "-d") == 0)
161 dir = 1;
162 else if (strcmp(argv[i], "-a") == 0)
163 date = version = cflags = options = platform = dir = 1;
164 else {
165 BIO_printf(bio_err, "usage:version -[avbofpd]\n");
166 ret = 1;
167 goto end;
168 }
169 }
170
171 if (version) {
172 if (SSLeay() == SSLEAY_VERSION_NUMBER) {
173 printf("%s\n", SSLeay_version(SSLEAY_VERSION));
174 } else {
175 printf("%s (Library: %s)\n",
176 OPENSSL_VERSION_TEXT,
177 SSLeay_version(SSLEAY_VERSION));
178 }
179 }
180 if (date)
181 printf("%s\n", SSLeay_version(SSLEAY_BUILT_ON));
182 if (platform)
183 printf("%s\n", SSLeay_version(SSLEAY_PLATFORM));
184 if (options) {
185 printf("options: ");
186 printf("%s ", BN_options());
187#ifndef OPENSSL_NO_RC4
188 printf("%s ", RC4_options());
189#endif
190#ifndef OPENSSL_NO_DES
191 printf("%s ", DES_options());
192#endif
193#ifndef OPENSSL_NO_IDEA
194 printf("%s ", idea_options());
195#endif
196#ifndef OPENSSL_NO_BF
197 printf("%s ", BF_options());
198#endif
199 printf("\n");
200 }
201 if (cflags)
202 printf("%s\n", SSLeay_version(SSLEAY_CFLAGS));
203 if (dir)
204 printf("%s\n", SSLeay_version(SSLEAY_DIR));
205end:
206
207 return (ret);
208}
diff --git a/src/usr.bin/openssl/x509.c b/src/usr.bin/openssl/x509.c
new file mode 100644
index 0000000000..afbccc00d6
--- /dev/null
+++ b/src/usr.bin/openssl/x509.c
@@ -0,0 +1,1160 @@
1/* $OpenBSD: x509.c,v 1.1 2014/08/26 17:47:25 jsing 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 <assert.h>
60#include <stdio.h>
61#include <stdlib.h>
62#include <limits.h>
63#include <string.h>
64
65#include "apps.h"
66
67#include <openssl/asn1.h>
68#include <openssl/bio.h>
69#include <openssl/bn.h>
70#include <openssl/err.h>
71#include <openssl/evp.h>
72#include <openssl/objects.h>
73#include <openssl/pem.h>
74#include <openssl/x509.h>
75#include <openssl/x509v3.h>
76
77#include <openssl/dsa.h>
78
79#include <openssl/rsa.h>
80
81#define POSTFIX ".srl"
82#define DEF_DAYS 30
83
84static const char *x509_usage[] = {
85 "usage: x509 args\n",
86 " -inform arg - input format - default PEM (one of DER, NET or PEM)\n",
87 " -outform arg - output format - default PEM (one of DER, NET or PEM)\n",
88 " -keyform arg - private key format - default PEM\n",
89 " -CAform arg - CA format - default PEM\n",
90 " -CAkeyform arg - CA key format - default PEM\n",
91 " -in arg - input file - default stdin\n",
92 " -out arg - output file - default stdout\n",
93 " -passin arg - private key password source\n",
94 " -serial - print serial number value\n",
95 " -subject_hash - print subject hash value\n",
96#ifndef OPENSSL_NO_MD5
97 " -subject_hash_old - print old-style (MD5) subject hash value\n",
98#endif
99 " -issuer_hash - print issuer hash value\n",
100#ifndef OPENSSL_NO_MD5
101 " -issuer_hash_old - print old-style (MD5) issuer hash value\n",
102#endif
103 " -hash - synonym for -subject_hash\n",
104 " -subject - print subject DN\n",
105 " -issuer - print issuer DN\n",
106 " -email - print email address(es)\n",
107 " -startdate - notBefore field\n",
108 " -enddate - notAfter field\n",
109 " -purpose - print out certificate purposes\n",
110 " -dates - both Before and After dates\n",
111 " -modulus - print the RSA key modulus\n",
112 " -pubkey - output the public key\n",
113 " -fingerprint - print the certificate fingerprint\n",
114 " -alias - output certificate alias\n",
115 " -noout - no certificate output\n",
116 " -ocspid - print OCSP hash values for the subject name and public key\n",
117 " -ocsp_uri - print OCSP Responder URL(s)\n",
118 " -trustout - output a \"trusted\" certificate\n",
119 " -clrtrust - clear all trusted purposes\n",
120 " -clrreject - clear all rejected purposes\n",
121 " -addtrust arg - trust certificate for a given purpose\n",
122 " -addreject arg - reject certificate for a given purpose\n",
123 " -setalias arg - set certificate alias\n",
124 " -days arg - How long till expiry of a signed certificate - def 30 days\n",
125 " -checkend arg - check whether the cert expires in the next arg seconds\n",
126 " exit 1 if so, 0 if not\n",
127 " -signkey arg - self sign cert with arg\n",
128 " -x509toreq - output a certification request object\n",
129 " -req - input is a certificate request, sign and output.\n",
130 " -CA arg - set the CA certificate, must be PEM format.\n",
131 " -CAkey arg - set the CA key, must be PEM format\n",
132 " missing, it is assumed to be in the CA file.\n",
133 " -CAcreateserial - create serial number file if it does not exist\n",
134 " -CAserial arg - serial file\n",
135 " -set_serial - serial number to use\n",
136 " -text - print the certificate in text form\n",
137 " -C - print out C code forms\n",
138 " -md2/-md5/-sha1/-mdc2 - digest to use\n",
139 " -extfile - configuration file with X509V3 extensions to add\n",
140 " -extensions - section from config file with X509V3 extensions to add\n",
141 " -clrext - delete extensions before signing and input certificate\n",
142 " -nameopt arg - various certificate name options\n",
143#ifndef OPENSSL_NO_ENGINE
144 " -engine e - use engine e, possibly a hardware device.\n",
145#endif
146 " -certopt arg - various certificate text options\n",
147 NULL
148};
149
150static int callb(int ok, X509_STORE_CTX *ctx);
151static int sign(X509 *x, EVP_PKEY *pkey, int days, int clrext,
152 const EVP_MD *digest, CONF *conf, char *section);
153static int x509_certify(X509_STORE *ctx, char *CAfile, const EVP_MD *digest,
154 X509 *x, X509 *xca, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *sigopts,
155 char *serial, int create, int days, int clrext, CONF *conf, char *section,
156 ASN1_INTEGER *sno);
157static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt);
158static int reqfile = 0;
159
160int x509_main(int, char **);
161
162int
163x509_main(int argc, char **argv)
164{
165 ENGINE *e = NULL;
166 int ret = 1;
167 X509_REQ *req = NULL;
168 X509 *x = NULL, *xca = NULL;
169 ASN1_OBJECT *objtmp;
170 STACK_OF(OPENSSL_STRING) *sigopts = NULL;
171 EVP_PKEY *Upkey = NULL, *CApkey = NULL;
172 ASN1_INTEGER *sno = NULL;
173 int i, num, badops = 0;
174 BIO *out = NULL;
175 BIO *STDout = NULL;
176 STACK_OF(ASN1_OBJECT) *trust = NULL, *reject = NULL;
177 int informat, outformat, keyformat, CAformat, CAkeyformat;
178 char *infile = NULL, *outfile = NULL, *keyfile = NULL, *CAfile = NULL;
179 char *CAkeyfile = NULL, *CAserial = NULL;
180 char *alias = NULL;
181 int text = 0, serial = 0, subject = 0, issuer = 0, startdate = 0,
182 enddate = 0;
183 int next_serial = 0;
184 int subject_hash = 0, issuer_hash = 0, ocspid = 0;
185#ifndef OPENSSL_NO_MD5
186 int subject_hash_old = 0, issuer_hash_old = 0;
187#endif
188 int noout = 0, sign_flag = 0, CA_flag = 0, CA_createserial = 0,
189 email = 0;
190 int ocsp_uri = 0;
191 int trustout = 0, clrtrust = 0, clrreject = 0, aliasout = 0, clrext = 0;
192 int C = 0;
193 int x509req = 0, days = DEF_DAYS, modulus = 0, pubkey = 0;
194 int pprint = 0;
195 const char **pp;
196 X509_STORE *ctx = NULL;
197 X509_REQ *rq = NULL;
198 int fingerprint = 0;
199 char buf[256];
200 const EVP_MD *md_alg, *digest = NULL;
201 CONF *extconf = NULL;
202 char *extsect = NULL, *extfile = NULL, *passin = NULL, *passargin = NULL;
203 int checkend = 0, checkoffset = 0;
204 unsigned long nmflag = 0, certflag = 0;
205#ifndef OPENSSL_NO_ENGINE
206 char *engine = NULL;
207#endif
208 const char *errstr = NULL;
209
210 reqfile = 0;
211
212 STDout = BIO_new_fp(stdout, BIO_NOCLOSE);
213
214 informat = FORMAT_PEM;
215 outformat = FORMAT_PEM;
216 keyformat = FORMAT_PEM;
217 CAformat = FORMAT_PEM;
218 CAkeyformat = FORMAT_PEM;
219
220 ctx = X509_STORE_new();
221 if (ctx == NULL)
222 goto end;
223 X509_STORE_set_verify_cb(ctx, callb);
224
225 argc--;
226 argv++;
227 num = 0;
228 while (argc >= 1) {
229 if (strcmp(*argv, "-inform") == 0) {
230 if (--argc < 1)
231 goto bad;
232 informat = str2fmt(*(++argv));
233 } else if (strcmp(*argv, "-outform") == 0) {
234 if (--argc < 1)
235 goto bad;
236 outformat = str2fmt(*(++argv));
237 } else if (strcmp(*argv, "-keyform") == 0) {
238 if (--argc < 1)
239 goto bad;
240 keyformat = str2fmt(*(++argv));
241 } else if (strcmp(*argv, "-req") == 0) {
242 reqfile = 1;
243 } else if (strcmp(*argv, "-CAform") == 0) {
244 if (--argc < 1)
245 goto bad;
246 CAformat = str2fmt(*(++argv));
247 } else if (strcmp(*argv, "-CAkeyform") == 0) {
248 if (--argc < 1)
249 goto bad;
250 CAkeyformat = str2fmt(*(++argv));
251 } else if (strcmp(*argv, "-sigopt") == 0) {
252 if (--argc < 1)
253 goto bad;
254 if (!sigopts)
255 sigopts = sk_OPENSSL_STRING_new_null();
256 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, *(++argv)))
257 goto bad;
258 } else if (strcmp(*argv, "-days") == 0) {
259 if (--argc < 1)
260 goto bad;
261 days = strtonum(*(++argv), 1, INT_MAX, &errstr);
262 if (errstr) {
263 BIO_printf(bio_err, "bad number of days: %s\n", errstr);
264 goto bad;
265 }
266 } else if (strcmp(*argv, "-passin") == 0) {
267 if (--argc < 1)
268 goto bad;
269 passargin = *(++argv);
270 } else if (strcmp(*argv, "-extfile") == 0) {
271 if (--argc < 1)
272 goto bad;
273 extfile = *(++argv);
274 } else if (strcmp(*argv, "-extensions") == 0) {
275 if (--argc < 1)
276 goto bad;
277 extsect = *(++argv);
278 } else if (strcmp(*argv, "-in") == 0) {
279 if (--argc < 1)
280 goto bad;
281 infile = *(++argv);
282 } else if (strcmp(*argv, "-out") == 0) {
283 if (--argc < 1)
284 goto bad;
285 outfile = *(++argv);
286 } else if (strcmp(*argv, "-signkey") == 0) {
287 if (--argc < 1)
288 goto bad;
289 keyfile = *(++argv);
290 sign_flag = ++num;
291 } else if (strcmp(*argv, "-CA") == 0) {
292 if (--argc < 1)
293 goto bad;
294 CAfile = *(++argv);
295 CA_flag = ++num;
296 } else if (strcmp(*argv, "-CAkey") == 0) {
297 if (--argc < 1)
298 goto bad;
299 CAkeyfile = *(++argv);
300 } else if (strcmp(*argv, "-CAserial") == 0) {
301 if (--argc < 1)
302 goto bad;
303 CAserial = *(++argv);
304 } else if (strcmp(*argv, "-set_serial") == 0) {
305 if (--argc < 1)
306 goto bad;
307 if (!(sno = s2i_ASN1_INTEGER(NULL, *(++argv))))
308 goto bad;
309 } else if (strcmp(*argv, "-addtrust") == 0) {
310 if (--argc < 1)
311 goto bad;
312 if (!(objtmp = OBJ_txt2obj(*(++argv), 0))) {
313 BIO_printf(bio_err,
314 "Invalid trust object value %s\n", *argv);
315 goto bad;
316 }
317 if (!trust)
318 trust = sk_ASN1_OBJECT_new_null();
319 sk_ASN1_OBJECT_push(trust, objtmp);
320 trustout = 1;
321 } else if (strcmp(*argv, "-addreject") == 0) {
322 if (--argc < 1)
323 goto bad;
324 if (!(objtmp = OBJ_txt2obj(*(++argv), 0))) {
325 BIO_printf(bio_err,
326 "Invalid reject object value %s\n", *argv);
327 goto bad;
328 }
329 if (!reject)
330 reject = sk_ASN1_OBJECT_new_null();
331 sk_ASN1_OBJECT_push(reject, objtmp);
332 trustout = 1;
333 } else if (strcmp(*argv, "-setalias") == 0) {
334 if (--argc < 1)
335 goto bad;
336 alias = *(++argv);
337 trustout = 1;
338 } else if (strcmp(*argv, "-certopt") == 0) {
339 if (--argc < 1)
340 goto bad;
341 if (!set_cert_ex(&certflag, *(++argv)))
342 goto bad;
343 } else if (strcmp(*argv, "-nameopt") == 0) {
344 if (--argc < 1)
345 goto bad;
346 if (!set_name_ex(&nmflag, *(++argv)))
347 goto bad;
348 }
349#ifndef OPENSSL_NO_ENGINE
350 else if (strcmp(*argv, "-engine") == 0) {
351 if (--argc < 1)
352 goto bad;
353 engine = *(++argv);
354 }
355#endif
356 else if (strcmp(*argv, "-C") == 0)
357 C = ++num;
358 else if (strcmp(*argv, "-email") == 0)
359 email = ++num;
360 else if (strcmp(*argv, "-ocsp_uri") == 0)
361 ocsp_uri = ++num;
362 else if (strcmp(*argv, "-serial") == 0)
363 serial = ++num;
364 else if (strcmp(*argv, "-next_serial") == 0)
365 next_serial = ++num;
366 else if (strcmp(*argv, "-modulus") == 0)
367 modulus = ++num;
368 else if (strcmp(*argv, "-pubkey") == 0)
369 pubkey = ++num;
370 else if (strcmp(*argv, "-x509toreq") == 0)
371 x509req = ++num;
372 else if (strcmp(*argv, "-text") == 0)
373 text = ++num;
374 else if (strcmp(*argv, "-hash") == 0 ||
375 strcmp(*argv, "-subject_hash") == 0)
376 subject_hash = ++num;
377#ifndef OPENSSL_NO_MD5
378 else if (strcmp(*argv, "-subject_hash_old") == 0)
379 subject_hash_old = ++num;
380#endif
381 else if (strcmp(*argv, "-issuer_hash") == 0)
382 issuer_hash = ++num;
383#ifndef OPENSSL_NO_MD5
384 else if (strcmp(*argv, "-issuer_hash_old") == 0)
385 issuer_hash_old = ++num;
386#endif
387 else if (strcmp(*argv, "-subject") == 0)
388 subject = ++num;
389 else if (strcmp(*argv, "-issuer") == 0)
390 issuer = ++num;
391 else if (strcmp(*argv, "-fingerprint") == 0)
392 fingerprint = ++num;
393 else if (strcmp(*argv, "-dates") == 0) {
394 startdate = ++num;
395 enddate = ++num;
396 } else if (strcmp(*argv, "-purpose") == 0)
397 pprint = ++num;
398 else if (strcmp(*argv, "-startdate") == 0)
399 startdate = ++num;
400 else if (strcmp(*argv, "-enddate") == 0)
401 enddate = ++num;
402 else if (strcmp(*argv, "-checkend") == 0) {
403 if (--argc < 1)
404 goto bad;
405 checkoffset = strtonum(*(++argv), 0, INT_MAX, &errstr);
406 if (errstr) {
407 BIO_printf(bio_err, "checkend unusable: %s\n", errstr);
408 goto bad;
409 }
410 checkend = 1;
411 } else if (strcmp(*argv, "-noout") == 0)
412 noout = ++num;
413 else if (strcmp(*argv, "-trustout") == 0)
414 trustout = 1;
415 else if (strcmp(*argv, "-clrtrust") == 0)
416 clrtrust = ++num;
417 else if (strcmp(*argv, "-clrreject") == 0)
418 clrreject = ++num;
419 else if (strcmp(*argv, "-alias") == 0)
420 aliasout = ++num;
421 else if (strcmp(*argv, "-CAcreateserial") == 0)
422 CA_createserial = ++num;
423 else if (strcmp(*argv, "-clrext") == 0)
424 clrext = 1;
425 else if (strcmp(*argv, "-ocspid") == 0)
426 ocspid = ++num;
427 else if ((md_alg = EVP_get_digestbyname(*argv + 1))) {
428 /* ok */
429 digest = md_alg;
430 } else {
431 BIO_printf(bio_err, "unknown option %s\n", *argv);
432 badops = 1;
433 break;
434 }
435 argc--;
436 argv++;
437 }
438
439 if (badops) {
440bad:
441 for (pp = x509_usage; (*pp != NULL); pp++)
442 BIO_printf(bio_err, "%s", *pp);
443 goto end;
444 }
445#ifndef OPENSSL_NO_ENGINE
446 e = setup_engine(bio_err, engine, 0);
447#endif
448
449 ERR_load_crypto_strings();
450
451 if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) {
452 BIO_printf(bio_err, "Error getting password\n");
453 goto end;
454 }
455 if (!X509_STORE_set_default_paths(ctx)) {
456 ERR_print_errors(bio_err);
457 goto end;
458 }
459 if ((CAkeyfile == NULL) && (CA_flag) && (CAformat == FORMAT_PEM)) {
460 CAkeyfile = CAfile;
461 } else if ((CA_flag) && (CAkeyfile == NULL)) {
462 BIO_printf(bio_err,
463 "need to specify a CAkey if using the CA command\n");
464 goto end;
465 }
466 if (extfile) {
467 long errorline = -1;
468 X509V3_CTX ctx2;
469 extconf = NCONF_new(NULL);
470 if (!NCONF_load(extconf, extfile, &errorline)) {
471 if (errorline <= 0)
472 BIO_printf(bio_err,
473 "error loading the config file '%s'\n",
474 extfile);
475 else
476 BIO_printf(bio_err,
477 "error on line %ld of config file '%s'\n",
478 errorline, extfile);
479 goto end;
480 }
481 if (!extsect) {
482 extsect = NCONF_get_string(extconf, "default",
483 "extensions");
484 if (!extsect) {
485 ERR_clear_error();
486 extsect = "default";
487 }
488 }
489 X509V3_set_ctx_test(&ctx2);
490 X509V3_set_nconf(&ctx2, extconf);
491 if (!X509V3_EXT_add_nconf(extconf, &ctx2, extsect, NULL)) {
492 BIO_printf(bio_err,
493 "Error Loading extension section %s\n",
494 extsect);
495 ERR_print_errors(bio_err);
496 goto end;
497 }
498 }
499 if (reqfile) {
500 EVP_PKEY *pkey;
501 BIO *in;
502
503 if (!sign_flag && !CA_flag) {
504 BIO_printf(bio_err, "We need a private key to sign with\n");
505 goto end;
506 }
507 in = BIO_new(BIO_s_file());
508 if (in == NULL) {
509 ERR_print_errors(bio_err);
510 goto end;
511 }
512 if (infile == NULL)
513 BIO_set_fp(in, stdin, BIO_NOCLOSE | BIO_FP_TEXT);
514 else {
515 if (BIO_read_filename(in, infile) <= 0) {
516 perror(infile);
517 BIO_free(in);
518 goto end;
519 }
520 }
521 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
522 BIO_free(in);
523
524 if (req == NULL) {
525 ERR_print_errors(bio_err);
526 goto end;
527 }
528 if ((req->req_info == NULL) ||
529 (req->req_info->pubkey == NULL) ||
530 (req->req_info->pubkey->public_key == NULL) ||
531 (req->req_info->pubkey->public_key->data == NULL)) {
532 BIO_printf(bio_err, "The certificate request appears to corrupted\n");
533 BIO_printf(bio_err, "It does not contain a public key\n");
534 goto end;
535 }
536 if ((pkey = X509_REQ_get_pubkey(req)) == NULL) {
537 BIO_printf(bio_err, "error unpacking public key\n");
538 goto end;
539 }
540 i = X509_REQ_verify(req, pkey);
541 EVP_PKEY_free(pkey);
542 if (i < 0) {
543 BIO_printf(bio_err, "Signature verification error\n");
544 ERR_print_errors(bio_err);
545 goto end;
546 }
547 if (i == 0) {
548 BIO_printf(bio_err, "Signature did not match the certificate request\n");
549 goto end;
550 } else
551 BIO_printf(bio_err, "Signature ok\n");
552
553 print_name(bio_err, "subject=", X509_REQ_get_subject_name(req), nmflag);
554
555 if ((x = X509_new()) == NULL)
556 goto end;
557
558 if (sno == NULL) {
559 sno = ASN1_INTEGER_new();
560 if (!sno || !rand_serial(NULL, sno))
561 goto end;
562 if (!X509_set_serialNumber(x, sno))
563 goto end;
564 ASN1_INTEGER_free(sno);
565 sno = NULL;
566 } else if (!X509_set_serialNumber(x, sno))
567 goto end;
568
569 if (!X509_set_issuer_name(x, req->req_info->subject))
570 goto end;
571 if (!X509_set_subject_name(x, req->req_info->subject))
572 goto end;
573
574 X509_gmtime_adj(X509_get_notBefore(x), 0);
575 X509_time_adj_ex(X509_get_notAfter(x), days, 0, NULL);
576
577 pkey = X509_REQ_get_pubkey(req);
578 X509_set_pubkey(x, pkey);
579 EVP_PKEY_free(pkey);
580 } else
581 x = load_cert(bio_err, infile, informat, NULL, e, "Certificate");
582
583 if (x == NULL)
584 goto end;
585 if (CA_flag) {
586 xca = load_cert(bio_err, CAfile, CAformat, NULL, e, "CA Certificate");
587 if (xca == NULL)
588 goto end;
589 }
590 if (!noout || text || next_serial) {
591 OBJ_create("2.99999.3",
592 "SET.ex3", "SET x509v3 extension 3");
593
594 out = BIO_new(BIO_s_file());
595 if (out == NULL) {
596 ERR_print_errors(bio_err);
597 goto end;
598 }
599 if (outfile == NULL) {
600 BIO_set_fp(out, stdout, BIO_NOCLOSE);
601 } else {
602 if (BIO_write_filename(out, outfile) <= 0) {
603 perror(outfile);
604 goto end;
605 }
606 }
607 }
608 if (alias)
609 X509_alias_set1(x, (unsigned char *) alias, -1);
610
611 if (clrtrust)
612 X509_trust_clear(x);
613 if (clrreject)
614 X509_reject_clear(x);
615
616 if (trust) {
617 for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++) {
618 objtmp = sk_ASN1_OBJECT_value(trust, i);
619 X509_add1_trust_object(x, objtmp);
620 }
621 }
622 if (reject) {
623 for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++) {
624 objtmp = sk_ASN1_OBJECT_value(reject, i);
625 X509_add1_reject_object(x, objtmp);
626 }
627 }
628 if (num) {
629 for (i = 1; i <= num; i++) {
630 if (issuer == i) {
631 print_name(STDout, "issuer= ",
632 X509_get_issuer_name(x), nmflag);
633 } else if (subject == i) {
634 print_name(STDout, "subject= ",
635 X509_get_subject_name(x), nmflag);
636 } else if (serial == i) {
637 BIO_printf(STDout, "serial=");
638 i2a_ASN1_INTEGER(STDout,
639 X509_get_serialNumber(x));
640 BIO_printf(STDout, "\n");
641 } else if (next_serial == i) {
642 BIGNUM *bnser;
643 ASN1_INTEGER *ser;
644 ser = X509_get_serialNumber(x);
645 bnser = ASN1_INTEGER_to_BN(ser, NULL);
646 if (!bnser)
647 goto end;
648 if (!BN_add_word(bnser, 1))
649 goto end;
650 ser = BN_to_ASN1_INTEGER(bnser, NULL);
651 if (!ser)
652 goto end;
653 BN_free(bnser);
654 i2a_ASN1_INTEGER(out, ser);
655 ASN1_INTEGER_free(ser);
656 BIO_puts(out, "\n");
657 } else if ((email == i) || (ocsp_uri == i)) {
658 int j;
659 STACK_OF(OPENSSL_STRING) *emlst;
660 if (email == i)
661 emlst = X509_get1_email(x);
662 else
663 emlst = X509_get1_ocsp(x);
664 for (j = 0; j < sk_OPENSSL_STRING_num(emlst); j++)
665 BIO_printf(STDout, "%s\n",
666 sk_OPENSSL_STRING_value(emlst, j));
667 X509_email_free(emlst);
668 } else if (aliasout == i) {
669 unsigned char *alstr;
670 alstr = X509_alias_get0(x, NULL);
671 if (alstr)
672 BIO_printf(STDout, "%s\n", alstr);
673 else
674 BIO_puts(STDout, "<No Alias>\n");
675 } else if (subject_hash == i) {
676 BIO_printf(STDout, "%08lx\n", X509_subject_name_hash(x));
677 }
678#ifndef OPENSSL_NO_MD5
679 else if (subject_hash_old == i) {
680 BIO_printf(STDout, "%08lx\n", X509_subject_name_hash_old(x));
681 }
682#endif
683 else if (issuer_hash == i) {
684 BIO_printf(STDout, "%08lx\n", X509_issuer_name_hash(x));
685 }
686#ifndef OPENSSL_NO_MD5
687 else if (issuer_hash_old == i) {
688 BIO_printf(STDout, "%08lx\n", X509_issuer_name_hash_old(x));
689 }
690#endif
691 else if (pprint == i) {
692 X509_PURPOSE *ptmp;
693 int j;
694 BIO_printf(STDout, "Certificate purposes:\n");
695 for (j = 0; j < X509_PURPOSE_get_count(); j++) {
696 ptmp = X509_PURPOSE_get0(j);
697 purpose_print(STDout, x, ptmp);
698 }
699 } else if (modulus == i) {
700 EVP_PKEY *pkey;
701
702 pkey = X509_get_pubkey(x);
703 if (pkey == NULL) {
704 BIO_printf(bio_err, "Modulus=unavailable\n");
705 ERR_print_errors(bio_err);
706 goto end;
707 }
708 BIO_printf(STDout, "Modulus=");
709 if (pkey->type == EVP_PKEY_RSA)
710 BN_print(STDout, pkey->pkey.rsa->n);
711 else
712 if (pkey->type == EVP_PKEY_DSA)
713 BN_print(STDout, pkey->pkey.dsa->pub_key);
714 else
715 BIO_printf(STDout, "Wrong Algorithm type");
716 BIO_printf(STDout, "\n");
717 EVP_PKEY_free(pkey);
718 } else if (pubkey == i) {
719 EVP_PKEY *pkey;
720
721 pkey = X509_get_pubkey(x);
722 if (pkey == NULL) {
723 BIO_printf(bio_err, "Error getting public key\n");
724 ERR_print_errors(bio_err);
725 goto end;
726 }
727 PEM_write_bio_PUBKEY(STDout, pkey);
728 EVP_PKEY_free(pkey);
729 } else if (C == i) {
730 unsigned char *d;
731 char *m;
732 int y, z;
733
734 X509_NAME_oneline(X509_get_subject_name(x),
735 buf, sizeof buf);
736 BIO_printf(STDout, "/* subject:%s */\n", buf);
737 m = X509_NAME_oneline(
738 X509_get_issuer_name(x), buf,
739 sizeof buf);
740 BIO_printf(STDout, "/* issuer :%s */\n", buf);
741
742 z = i2d_X509(x, NULL);
743 m = malloc(z);
744
745 d = (unsigned char *) m;
746 z = i2d_X509_NAME(X509_get_subject_name(x), &d);
747 BIO_printf(STDout, "unsigned char XXX_subject_name[%d]={\n", z);
748 d = (unsigned char *) m;
749 for (y = 0; y < z; y++) {
750 BIO_printf(STDout, "0x%02X,", d[y]);
751 if ((y & 0x0f) == 0x0f)
752 BIO_printf(STDout, "\n");
753 }
754 if (y % 16 != 0)
755 BIO_printf(STDout, "\n");
756 BIO_printf(STDout, "};\n");
757
758 z = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x), &d);
759 BIO_printf(STDout, "unsigned char XXX_public_key[%d]={\n", z);
760 d = (unsigned char *) m;
761 for (y = 0; y < z; y++) {
762 BIO_printf(STDout, "0x%02X,", d[y]);
763 if ((y & 0x0f) == 0x0f)
764 BIO_printf(STDout, "\n");
765 }
766 if (y % 16 != 0)
767 BIO_printf(STDout, "\n");
768 BIO_printf(STDout, "};\n");
769
770 z = i2d_X509(x, &d);
771 BIO_printf(STDout, "unsigned char XXX_certificate[%d]={\n", z);
772 d = (unsigned char *) m;
773 for (y = 0; y < z; y++) {
774 BIO_printf(STDout, "0x%02X,", d[y]);
775 if ((y & 0x0f) == 0x0f)
776 BIO_printf(STDout, "\n");
777 }
778 if (y % 16 != 0)
779 BIO_printf(STDout, "\n");
780 BIO_printf(STDout, "};\n");
781
782 free(m);
783 } else if (text == i) {
784 X509_print_ex(STDout, x, nmflag, certflag);
785 } else if (startdate == i) {
786 BIO_puts(STDout, "notBefore=");
787 ASN1_TIME_print(STDout, X509_get_notBefore(x));
788 BIO_puts(STDout, "\n");
789 } else if (enddate == i) {
790 BIO_puts(STDout, "notAfter=");
791 ASN1_TIME_print(STDout, X509_get_notAfter(x));
792 BIO_puts(STDout, "\n");
793 } else if (fingerprint == i) {
794 int j;
795 unsigned int n;
796 unsigned char md[EVP_MAX_MD_SIZE];
797 const EVP_MD *fdig = digest;
798
799 if (!fdig)
800 fdig = EVP_sha1();
801
802 if (!X509_digest(x, fdig, md, &n)) {
803 BIO_printf(bio_err, "out of memory\n");
804 goto end;
805 }
806 BIO_printf(STDout, "%s Fingerprint=",
807 OBJ_nid2sn(EVP_MD_type(fdig)));
808 for (j = 0; j < (int) n; j++) {
809 BIO_printf(STDout, "%02X%c", md[j],
810 (j + 1 == (int)n) ? '\n' : ':');
811 }
812 }
813 /* should be in the library */
814 else if ((sign_flag == i) && (x509req == 0)) {
815 BIO_printf(bio_err, "Getting Private key\n");
816 if (Upkey == NULL) {
817 Upkey = load_key(bio_err,
818 keyfile, keyformat, 0,
819 passin, e, "Private key");
820 if (Upkey == NULL)
821 goto end;
822 }
823 if (!sign(x, Upkey, days, clrext, digest,
824 extconf, extsect))
825 goto end;
826 } else if (CA_flag == i) {
827 BIO_printf(bio_err, "Getting CA Private Key\n");
828 if (CAkeyfile != NULL) {
829 CApkey = load_key(bio_err,
830 CAkeyfile, CAkeyformat,
831 0, passin, e,
832 "CA Private Key");
833 if (CApkey == NULL)
834 goto end;
835 }
836 if (!x509_certify(ctx, CAfile, digest, x, xca,
837 CApkey, sigopts,
838 CAserial, CA_createserial, days, clrext,
839 extconf, extsect, sno))
840 goto end;
841 } else if (x509req == i) {
842 EVP_PKEY *pk;
843
844 BIO_printf(bio_err, "Getting request Private Key\n");
845 if (keyfile == NULL) {
846 BIO_printf(bio_err, "no request key file specified\n");
847 goto end;
848 } else {
849 pk = load_key(bio_err,
850 keyfile, keyformat, 0,
851 passin, e, "request key");
852 if (pk == NULL)
853 goto end;
854 }
855
856 BIO_printf(bio_err, "Generating certificate request\n");
857
858 rq = X509_to_X509_REQ(x, pk, digest);
859 EVP_PKEY_free(pk);
860 if (rq == NULL) {
861 ERR_print_errors(bio_err);
862 goto end;
863 }
864 if (!noout) {
865 X509_REQ_print(out, rq);
866 PEM_write_bio_X509_REQ(out, rq);
867 }
868 noout = 1;
869 } else if (ocspid == i) {
870 X509_ocspid_print(out, x);
871 }
872 }
873 }
874 if (checkend) {
875 time_t tcheck = time(NULL) + checkoffset;
876
877 if (X509_cmp_time(X509_get_notAfter(x), &tcheck) < 0) {
878 BIO_printf(out, "Certificate will expire\n");
879 ret = 1;
880 } else {
881 BIO_printf(out, "Certificate will not expire\n");
882 ret = 0;
883 }
884 goto end;
885 }
886 if (noout) {
887 ret = 0;
888 goto end;
889 }
890 if (outformat == FORMAT_ASN1)
891 i = i2d_X509_bio(out, x);
892 else if (outformat == FORMAT_PEM) {
893 if (trustout)
894 i = PEM_write_bio_X509_AUX(out, x);
895 else
896 i = PEM_write_bio_X509(out, x);
897 } else if (outformat == FORMAT_NETSCAPE) {
898 NETSCAPE_X509 nx;
899 ASN1_OCTET_STRING hdr;
900
901 hdr.data = (unsigned char *) NETSCAPE_CERT_HDR;
902 hdr.length = strlen(NETSCAPE_CERT_HDR);
903 nx.header = &hdr;
904 nx.cert = x;
905
906 i = ASN1_item_i2d_bio(ASN1_ITEM_rptr(NETSCAPE_X509), out, &nx);
907 } else {
908 BIO_printf(bio_err, "bad output format specified for outfile\n");
909 goto end;
910 }
911 if (!i) {
912 BIO_printf(bio_err, "unable to write certificate\n");
913 ERR_print_errors(bio_err);
914 goto end;
915 }
916 ret = 0;
917
918end:
919 OBJ_cleanup();
920 NCONF_free(extconf);
921 BIO_free_all(out);
922 BIO_free_all(STDout);
923 X509_STORE_free(ctx);
924 X509_REQ_free(req);
925 X509_free(x);
926 X509_free(xca);
927 EVP_PKEY_free(Upkey);
928 EVP_PKEY_free(CApkey);
929 if (sigopts)
930 sk_OPENSSL_STRING_free(sigopts);
931 X509_REQ_free(rq);
932 ASN1_INTEGER_free(sno);
933 sk_ASN1_OBJECT_pop_free(trust, ASN1_OBJECT_free);
934 sk_ASN1_OBJECT_pop_free(reject, ASN1_OBJECT_free);
935 free(passin);
936
937 return (ret);
938}
939
940static ASN1_INTEGER *
941x509_load_serial(char *CAfile, char *serialfile, int create)
942{
943 char *buf = NULL, *p;
944 ASN1_INTEGER *bs = NULL;
945 BIGNUM *serial = NULL;
946 size_t len;
947
948 len = ((serialfile == NULL) ? (strlen(CAfile) + strlen(POSTFIX) + 1) :
949 (strlen(serialfile))) + 1;
950 buf = malloc(len);
951 if (buf == NULL) {
952 BIO_printf(bio_err, "out of mem\n");
953 goto end;
954 }
955 if (serialfile == NULL) {
956 strlcpy(buf, CAfile, len);
957 for (p = buf; *p; p++)
958 if (*p == '.') {
959 *p = '\0';
960 break;
961 }
962 strlcat(buf, POSTFIX, len);
963 } else
964 strlcpy(buf, serialfile, len);
965
966 serial = load_serial(buf, create, NULL);
967 if (serial == NULL)
968 goto end;
969
970 if (!BN_add_word(serial, 1)) {
971 BIO_printf(bio_err, "add_word failure\n");
972 goto end;
973 }
974 if (!save_serial(buf, NULL, serial, &bs))
975 goto end;
976
977end:
978 free(buf);
979 BN_free(serial);
980
981 return bs;
982}
983
984static int
985x509_certify(X509_STORE *ctx, char *CAfile, const EVP_MD *digest, X509 *x,
986 X509 *xca, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *sigopts,
987 char *serialfile, int create, int days, int clrext, CONF *conf,
988 char *section, ASN1_INTEGER *sno)
989{
990 int ret = 0;
991 ASN1_INTEGER *bs = NULL;
992 X509_STORE_CTX xsc;
993 EVP_PKEY *upkey;
994
995 upkey = X509_get_pubkey(xca);
996 EVP_PKEY_copy_parameters(upkey, pkey);
997 EVP_PKEY_free(upkey);
998
999 if (!X509_STORE_CTX_init(&xsc, ctx, x, NULL)) {
1000 BIO_printf(bio_err, "Error initialising X509 store\n");
1001 goto end;
1002 }
1003 if (sno)
1004 bs = sno;
1005 else if (!(bs = x509_load_serial(CAfile, serialfile, create)))
1006 goto end;
1007
1008/* if (!X509_STORE_add_cert(ctx,x)) goto end;*/
1009
1010 /*
1011 * NOTE: this certificate can/should be self signed, unless it was a
1012 * certificate request in which case it is not.
1013 */
1014 X509_STORE_CTX_set_cert(&xsc, x);
1015 X509_STORE_CTX_set_flags(&xsc, X509_V_FLAG_CHECK_SS_SIGNATURE);
1016 if (!reqfile && X509_verify_cert(&xsc) <= 0)
1017 goto end;
1018
1019 if (!X509_check_private_key(xca, pkey)) {
1020 BIO_printf(bio_err, "CA certificate and CA private key do not match\n");
1021 goto end;
1022 }
1023 if (!X509_set_issuer_name(x, X509_get_subject_name(xca)))
1024 goto end;
1025 if (!X509_set_serialNumber(x, bs))
1026 goto end;
1027
1028 if (X509_gmtime_adj(X509_get_notBefore(x), 0L) == NULL)
1029 goto end;
1030
1031 /* hardwired expired */
1032 if (X509_time_adj_ex(X509_get_notAfter(x), days, 0, NULL) == NULL)
1033 goto end;
1034
1035 if (clrext) {
1036 while (X509_get_ext_count(x) > 0)
1037 X509_delete_ext(x, 0);
1038 }
1039 if (conf) {
1040 X509V3_CTX ctx2;
1041 X509_set_version(x, 2); /* version 3 certificate */
1042 X509V3_set_ctx(&ctx2, xca, x, NULL, NULL, 0);
1043 X509V3_set_nconf(&ctx2, conf);
1044 if (!X509V3_EXT_add_nconf(conf, &ctx2, section, x))
1045 goto end;
1046 }
1047 if (!do_X509_sign(bio_err, x, pkey, digest, sigopts))
1048 goto end;
1049 ret = 1;
1050end:
1051 X509_STORE_CTX_cleanup(&xsc);
1052 if (!ret)
1053 ERR_print_errors(bio_err);
1054 if (!sno)
1055 ASN1_INTEGER_free(bs);
1056 return ret;
1057}
1058
1059static int
1060callb(int ok, X509_STORE_CTX *ctx)
1061{
1062 int err;
1063 X509 *err_cert;
1064
1065 /*
1066 * it is ok to use a self signed certificate This case will catch
1067 * both the initial ok == 0 and the final ok == 1 calls to this
1068 * function
1069 */
1070 err = X509_STORE_CTX_get_error(ctx);
1071 if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT)
1072 return 1;
1073
1074 /*
1075 * BAD we should have gotten an error. Normally if everything worked
1076 * X509_STORE_CTX_get_error(ctx) will still be set to
1077 * DEPTH_ZERO_SELF_....
1078 */
1079 if (ok) {
1080 BIO_printf(bio_err, "error with certificate to be certified - should be self signed\n");
1081 return 0;
1082 } else {
1083 err_cert = X509_STORE_CTX_get_current_cert(ctx);
1084 print_name(bio_err, NULL, X509_get_subject_name(err_cert), 0);
1085 BIO_printf(bio_err, "error with certificate - error %d at depth %d\n%s\n",
1086 err, X509_STORE_CTX_get_error_depth(ctx),
1087 X509_verify_cert_error_string(err));
1088 return 1;
1089 }
1090}
1091
1092/* self sign */
1093static int
1094sign(X509 *x, EVP_PKEY *pkey, int days, int clrext, const EVP_MD *digest,
1095 CONF *conf, char *section)
1096{
1097
1098 EVP_PKEY *pktmp;
1099
1100 pktmp = X509_get_pubkey(x);
1101 EVP_PKEY_copy_parameters(pktmp, pkey);
1102 EVP_PKEY_save_parameters(pktmp, 1);
1103 EVP_PKEY_free(pktmp);
1104
1105 if (!X509_set_issuer_name(x, X509_get_subject_name(x)))
1106 goto err;
1107 if (X509_gmtime_adj(X509_get_notBefore(x), 0) == NULL)
1108 goto err;
1109
1110 /* Lets just make it 12:00am GMT, Jan 1 1970 */
1111 /* memcpy(x->cert_info->validity->notBefore,"700101120000Z",13); */
1112 /* 28 days to be certified */
1113
1114 if (X509_gmtime_adj(X509_get_notAfter(x),
1115 (long) 60 * 60 * 24 * days) == NULL)
1116 goto err;
1117
1118 if (!X509_set_pubkey(x, pkey))
1119 goto err;
1120 if (clrext) {
1121 while (X509_get_ext_count(x) > 0)
1122 X509_delete_ext(x, 0);
1123 }
1124 if (conf) {
1125 X509V3_CTX ctx;
1126 X509_set_version(x, 2); /* version 3 certificate */
1127 X509V3_set_ctx(&ctx, x, x, NULL, NULL, 0);
1128 X509V3_set_nconf(&ctx, conf);
1129 if (!X509V3_EXT_add_nconf(conf, &ctx, section, x))
1130 goto err;
1131 }
1132 if (!X509_sign(x, pkey, digest))
1133 goto err;
1134 return 1;
1135
1136err:
1137 ERR_print_errors(bio_err);
1138 return 0;
1139}
1140
1141static int
1142purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt)
1143{
1144 int id, i, idret;
1145 char *pname;
1146
1147 id = X509_PURPOSE_get_id(pt);
1148 pname = X509_PURPOSE_get0_name(pt);
1149 for (i = 0; i < 2; i++) {
1150 idret = X509_check_purpose(cert, id, i);
1151 BIO_printf(bio, "%s%s : ", pname, i ? " CA" : "");
1152 if (idret == 1)
1153 BIO_printf(bio, "Yes\n");
1154 else if (idret == 0)
1155 BIO_printf(bio, "No\n");
1156 else
1157 BIO_printf(bio, "Yes (WARNING code=%d)\n", idret);
1158 }
1159 return 1;
1160}