/
easyrsa
executable file
·2820 lines (2432 loc) · 81.4 KB
/
easyrsa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/sh
# Easy-RSA 3 -- A Shell-based CA Utility
#
# Copyright (C) 2018 by the Open-Source OpenVPN development community.
# A full list of contributors can be found in the ChangeLog.
#
# This code released under version 2 of the GNU GPL; see COPYING and the
# Licensing/ directory of this project for full licensing details.
# Help/usage output to stdout
usage() {
# command help:
print "
Easy-RSA 3 usage and overview
USAGE: easyrsa [options] COMMAND [command-options]
A list of commands is shown below. To get detailed usage and help for a
command, run:
./easyrsa help COMMAND
For a listing of options that can be supplied before the command, use:
./easyrsa help options
Here is the list of commands available with a short syntax reminder. Use the
'help' command above to get full usage details.
init-pki
build-ca [ cmd-opts ]
gen-dh
gen-req <filename_base> [ cmd-opts ]
sign-req <type> <filename_base>
build-client-full <filename_base> [ cmd-opts ]
build-server-full <filename_base> [ cmd-opts ]
revoke <filename_base> [cmd-opts]
renew <filename_base> [cmd-opts]
build-serverClient-full <filename_base> [ cmd-opts ]
gen-crl
update-db
show-req <filename_base> [ cmd-opts ]
show-cert <filename_base> [ cmd-opts ]
show-ca [ cmd-opts ]
import-req <request_file_path> <short_basename>
export-p7 <filename_base> [ cmd-opts ]
export-p8 <filename_base> [ cmd-opts ]
export-p12 <filename_base> [ cmd-opts ]
set-rsa-pass <filename_base> [ cmd-opts ]
set-ec-pass <filename_base> [ cmd-opts ]
upgrade <type>
"
# collect/show dir status:
err_source="Not defined: vars autodetect failed and no value provided"
work_dir="${EASYRSA:-$err_source}"
pki_dir="${EASYRSA_PKI:-$err_source}"
print "\
DIRECTORY STATUS (commands would take effect on these locations)
EASYRSA: $work_dir
PKI: $pki_dir
"
} # => usage()
# Detailed command help
# When called with no args, calls usage(), otherwise shows help for a command
cmd_help() {
text=""
opts=""
case "$1" in
init-pki|clean-all) text="
init-pki [ cmd-opts ]
Removes & re-initializes the PKI dir for a clean PKI" ;;
build-ca) text="
build-ca [ cmd-opts ]
Creates a new CA"
opts="
nopass - do not encrypt the CA key (default is encrypted)
subca - create an intermediate CA keypair and request (default is a root CA)
intca - alias to the above" ;;
gen-dh) text="
gen-dh
Generates DH (Diffie-Hellman) parameters" ;;
gen-req) text="
gen-req <filename_base> [ cmd-opts ]
Generate a standalone keypair and request (CSR)
This request is suitable for sending to a remote CA for signing."
opts="
nopass - do not encrypt the private key (default is encrypted)" ;;
sign|sign-req) text="
sign-req <type> <filename_base>
Sign a certificate request of the defined type. <type> must be a known
type such as 'client', 'server', 'serverClient', or 'ca' (or a user-added type.)
This request file must exist in the reqs/ dir and have a .req file
extension. See import-req below for importing reqs from other sources." ;;
build|build-client-full|build-server-full|build-serverClient-full) text="
build-client-full <filename_base> [ cmd-opts ]
build-server-full <filename_base> [ cmd-opts ]
build-serverClient-full <filename_base> [ cmd-opts ]
Generate a keypair and sign locally for a client and/or server
This mode uses the <filename_base> as the X509 CN."
opts="
nopass - do not encrypt the private key (default is encrypted)
inline - create an inline credentials file for this node" ;;
revoke) text="
revoke <filename_base> [reason]
Revoke a certificate specified by the filename_base, with an optional
revocation reason that is one of:
unspecified
keyCompromise
CACompromise
affiliationChanged
superseded
cessationOfOperation
certificateHold";;
renew) text="
renew <filename_base> [ cmd-opts ]
Renew a certificate specified by the filename_base"
opts="
nopass - do not encrypt the private key (default is encrypted)" ;;
gen-crl) text="
gen-crl
Generate a CRL" ;;
update-db) text="
update-db
Update the index.txt database
This command will use the system time to update the status of issued
certificates." ;;
show-req|show-cert) text="
show-req <filename_base> [ cmd-opts ]
show-cert <filename_base> [ cmd-opts ]
Shows details of the req or cert referenced by filename_base
Human-readable output is shown, including any requested cert options when
showing a request."
opts="
full - show full req/cert info, including pubkey/sig data" ;;
show-ca) text="
show-ca [ cmd-opts ]
Shows details of the CA cert
Human-readable output is shown."
opts="
full - show full cert info, including pubkey/sig data" ;;
import-req) text="
import-req <request_file_path> <short_basename>
Import a certificate request from a file
This will copy the specified file into the reqs/ dir in
preparation for signing.
The <short_basename> is the filename base to create.
Example usage:
import-req /some/where/bob_request.req bob" ;;
export-p12) text="
export-p12 <filename_base> [ cmd-opts ]
Export a PKCS#12 file with the keypair specified by <filename_base>"
opts="
noca - do not include the ca.crt file in the PKCS12 output
nokey - do not include the private key in the PKCS12 output" ;;
export-p7) text="
export-p7 <filename_base> [ cmd-opts ]
Export a PKCS#7 file with the pubkey specified by <filename_base>"
opts="
noca - do not include the ca.crt file in the PKCS7 output" ;;
export-p8) text="
export-p8 <filename_base> [ cmd-opts ]
Export a PKCS#8 file with the private key specified by <filename_base>"
opts="
noca - do not include the ca.crt file in the PKCS7 output" ;;
set-rsa-pass|set-ec-pass) text="
set-rsa-pass <filename_base> [ cmd-opts ]
set-ec-pass <filename_base> [ cmd-opts ]
Set a new passphrase on an RSA or EC key for the listed <filename_base>."
opts="
nopass - use no password and leave the key unencrypted
file - (advanced) treat the file as a raw path, not a short-name" ;;
upgrade) text="
upgrade <type>
Upgrade EasyRSA PKI and/or CA. <type> must be one of:
pki - Upgrade EasyRSA v2.x PKI to EasyRSA v3.x PKI (includes CA below)
ca - Upgrade EasyRSA v3.0.5 CA or older to EasyRSA v3.0.6 CA or later." ;;
altname|subjectaltname|san) text="
--subject-alt-name=SAN_FORMAT_STRING
This global option adds a subjectAltName to the request or issued
certificate. It MUST be in a valid format accepted by openssl or
req/cert generation will fail. Note that including multiple such names
requires them to be comma-separated; further invocations of this
option will REPLACE the value.
Examples of the SAN_FORMAT_STRING shown below:
DNS:alternate.example.net
DNS:primary.example.net,DNS:alternate.example.net
IP:203.0.113.29
email:alternate@example.net" ;;
options)
opt_usage ;;
"")
usage ;;
*) text="
Unknown command: '$1' (try without commands for a list of commands)" ;;
esac
# display the help text
print "$text"
[ -n "$opts" ] && print "
cmd-opts is an optional set of command options from this list:
$opts"
} # => cmd_help()
# Options usage
opt_usage() {
print "
Easy-RSA Global Option Flags
The following options may be provided before the command. Options specified
at runtime override env-vars and any 'vars' file in use. Unless noted,
non-empty values to options are mandatory.
General options:
--batch : set automatic (no-prompts when possible) mode
--passin=ARG : set -passin ARG for openssl
--passout=ARG : set -passout ARG for openssl
--pki-dir=DIR : declares the PKI directory
--vars=FILE : define a specific 'vars' file to use for Easy-RSA config
--version : prints EasyRSA version and build information, then exits
Certificate & Request options: (these impact cert/req field values)
--days=# : sets the signing validity to the specified number of days
--digest=ALG : digest to use in the requests & certificates
--dn-mode=MODE : DN mode to use (cn_only or org)
--keysize=# : size in bits of keypair to generate
--req-cn=NAME : default CN to use
--subca-len=# : path length of signed intermediate CA certs; must be >= 0 if used
--subject-alt-name : Add a subjectAltName. For more info and syntax, see:
./easyrsa help altname
--use-algo=ALG : crypto alg to use: choose rsa (default), ec or ed
--curve=NAME : for elliptic curve, sets the named curve to use
--copy-ext : Copy included request X509 extensions (namely subjAltName
Organizational DN options: (only used with the 'org' DN mode)
(values may be blank for org DN options)
--req-c=CC : country code (2-letters)
--req-st=NAME : State/Province
--req-city=NAME : City/Locality
--req-org=NAME : Organization
--req-email=NAME : Email addresses
--req-ou=NAME : Organizational Unit
Deprecated features:
--ns-cert=YESNO : yes or no to including deprecated NS extensions
--ns-comment=COMMENT : NS comment to include (value may be blank)
"
} # => opt_usage()
# Wrapper around printf - clobber print since it's not POSIX anyway
# shellcheck disable=SC1117
print() { printf "%s\n" "$*" || exit 1; }
# Exit fatally with a message to stderr
# present even with EASYRSA_BATCH as these are fatal problems
die() {
print "
Easy-RSA error:
$1" 1>&2
exit "${2:-1}"
} # => die()
# non-fatal warning output
warn() {
[ ! "$EASYRSA_BATCH" ] && \
print "
$1" 1>&2
return 0
} # => warn()
# informational notices to stdout
notice() {
[ ! "$EASYRSA_BATCH" ] && \
print "
$1"
return 0
} # => notice()
# yes/no case-insensitive match (operates on stdin pipe)
# Returns 0 when input contains yes, 1 for no, 2 for no match
# If both strings are present, returns 1; first matching line returns.
awk_yesno() {
#shellcheck disable=SC2016
awkscript='
BEGIN {IGNORECASE=1; r=2}
{ if(match($0,"no")) {r=1; exit}
if(match($0,"yes")) {r=0; exit}
} END {exit r}'
awk "$awkscript"
} # => awk_yesno()
# intent confirmation helper func
# returns without prompting in EASYRSA_BATCH
confirm() {
[ "$EASYRSA_BATCH" ] && return
prompt="$1"
value="$2"
msg="$3"
input=""
print "
$msg
Type the word '$value' to continue, or any other input to abort."
printf %s " $prompt"
#shellcheck disable=SC2162
read input
[ "$input" = "$value" ] && return
notice "Aborting without confirmation."
exit 9
} # => confirm()
# mktemp wrapper
easyrsa_mktemp() {
[ -n "$EASYRSA_TEMP_DIR_session" ] || die "EASYRSA_TEMP_DIR_session not initialized!"
[ -d "$EASYRSA_TEMP_DIR_session" ] || mkdir -p "$EASYRSA_TEMP_DIR_session" ||
die "Could not create temporary directory '$EASYRSA_TEMP_DIR_session'. Permission or concurrency problem?"
[ -d "$EASYRSA_TEMP_DIR_session" ] || die "Temporary directory '$EASYRSA_TEMP_DIR_session' does not exist"
tempfile="$EASYRSA_TEMP_DIR_session/tmp.$($EASYRSA_OPENSSL rand -hex 3)" || return
printf "" > "$tempfile" || return
echo "$tempfile"
} # => easyrsa_mktemp
# remove temp files and do terminal cleanups
cleanup() {
[ -z "$EASYRSA_TEMP_DIR_session" ] || rm -rf "$EASYRSA_TEMP_DIR_session"
# shellcheck disable=SC2039
(stty echo 2>/dev/null) || { (set -o echo 2>/dev/null) && set -o echo; }
echo "" # just to get a clean line
} # => cleanup()
easyrsa_openssl() {
openssl_command=$1; shift
case $openssl_command in
makesafeconf) has_config=true;;
ca|req|srp|ts) has_config=true;;
*) has_config=false;;
esac
case "$osslv_major" in
3)
case $openssl_command in
genpkey) has_config=true;;
*) : ;; # ok
esac
;;
1|2) : ;; # ok - LibreSSL 2.x
'') : ;; # Unset then this is init-pki
*) die "Unsupported openssl version: $osslv_major"
esac
if ! $has_config; then
"$EASYRSA_OPENSSL" "$openssl_command" "$@"
return
fi
easyrsa_openssl_conf=$(easyrsa_mktemp) || die "Failed to create temporary file"
easyrsa_extra_exts=
if [ -n "$EASYRSA_EXTRA_EXTS" ]; then
easyrsa_extra_exts=$(easyrsa_mktemp) || die "Failed to create temporary file"
cat >"$easyrsa_extra_exts" <<-EOF
req_extensions = req_extra
[ req_extra ]
$EASYRSA_EXTRA_EXTS
EOF
fi
# Make LibreSSL safe config file from OpenSSL config file
sed \
-e "s\`ENV::EASYRSA\`EASYRSA\`g" \
-e "s\`\$dir\`$EASYRSA_PKI\`g" \
-e "s\`\$EASYRSA_PKI\`$EASYRSA_PKI\`g" \
-e "s\`\$EASYRSA_CERT_EXPIRE\`$EASYRSA_CERT_EXPIRE\`g" \
-e "s\`\$EASYRSA_CRL_DAYS\`$EASYRSA_CRL_DAYS\`g" \
-e "s\`\$EASYRSA_DIGEST\`$EASYRSA_DIGEST\`g" \
-e "s\`\$EASYRSA_KEY_SIZE\`$EASYRSA_KEY_SIZE\`g" \
-e "s\`\$EASYRSA_DIGEST\`$EASYRSA_DIGEST\`g" \
-e "s\`\$EASYRSA_DN\`$EASYRSA_DN\`g" \
-e "s\`\$EASYRSA_REQ_COUNTRY\`$EASYRSA_REQ_COUNTRY\`g" \
-e "s\`\$EASYRSA_REQ_PROVINCE\`$EASYRSA_REQ_PROVINCE\`g" \
-e "s\`\$EASYRSA_REQ_CITY\`$EASYRSA_REQ_CITY\`g" \
-e "s\`\$EASYRSA_REQ_ORG\`$EASYRSA_REQ_ORG\`g" \
-e "s\`\$EASYRSA_REQ_OU\`$EASYRSA_REQ_OU\`g" \
-e "s\`\$EASYRSA_REQ_CN\`$EASYRSA_REQ_CN\`g" \
-e "s\`\$EASYRSA_REQ_EMAIL\`$EASYRSA_REQ_EMAIL\`g" \
${EASYRSA_EXTRA_EXTS:+-e "/^#%EXTRA_EXTS%/r $easyrsa_extra_exts"} \
"$EASYRSA_SSL_CONF" > "$easyrsa_openssl_conf" ||
die "Failed to update $easyrsa_openssl_conf"
if [ "$openssl_command" = "makesafeconf" ]; then
cp "$easyrsa_openssl_conf" "$EASYRSA_SAFE_CONF"
err=$?
else
"$EASYRSA_OPENSSL" "$openssl_command" -config "$easyrsa_openssl_conf" "$@"
err=$?
fi
rm -f "$easyrsa_openssl_conf"
rm -f "$easyrsa_extra_exts"
return $err
} # => easyrsa_openssl
vars_source_check() {
# Check for defined EASYRSA_PKI
[ -n "$EASYRSA_PKI" ] || die "\
EASYRSA_PKI env-var undefined"
} # => vars_source_check()
# Verify supplied curve exists and generate curve file if needed
verify_curve_ec() {
if ! "$EASYRSA_OPENSSL" ecparam -name "$EASYRSA_CURVE" > /dev/null; then
die "\
Curve $EASYRSA_CURVE not found. Run openssl ecparam -list_curves to show a
list of supported curves."
fi
# Check that the ecparams dir exists
[ -d "$EASYRSA_EC_DIR" ] || mkdir "$EASYRSA_EC_DIR" || die "\
Failed creating ecparams dir (permissions?) at:
$EASYRSA_EC_DIR"
# Check that the required ecparams file exists
out="$EASYRSA_EC_DIR/${EASYRSA_CURVE}.pem"
[ -f "$out" ] && return 0
"$EASYRSA_OPENSSL" ecparam -name "$EASYRSA_CURVE" -out "$out" || die "\
Failed to generate ecparam file (permissions?) when writing to:
$out"
# Explicitly return success for caller
return 0
}
# Verify if Edward Curve exists
verify_curve_ed() {
easyrsa_openssl genpkey -algorithm "$EASYRSA_CURVE" > /dev/null && return 0
die "Edward Curve $EASYRSA_CURVE not found."
}
verify_ssl_lib () {
# Verify EASYRSA_OPENSSL command gives expected output
if [ -z "$EASYRSA_SSL_OK" ]; then
val="$("$EASYRSA_OPENSSL" version)"
case "${val%% *}" in
OpenSSL|LibreSSL)
osslv_major="${val#* }"
osslv_major="${osslv_major%%.*}"
case "$osslv_major" in
1) no_password='-nodes' ;;
2) no_password='-nodes' ;; # LibreSSL Only
3) no_password='-noenc' ;;
*) die "Unsupported SSL library: $osslv_major"
esac
print "\
Using SSL: $EASYRSA_OPENSSL $("$EASYRSA_OPENSSL" version)" ;;
*) die "\
Missing or invalid OpenSSL
Expected to find openssl command at: $EASYRSA_OPENSSL" ;;
esac
fi
EASYRSA_SSL_OK=1
# Verify EASYRSA_SSL_CONF file exists
[ -f "$EASYRSA_SSL_CONF" ] || die "\
The OpenSSL config file cannot be found.
Expected location: $EASYRSA_SSL_CONF"
} # => verify_ssl_lib ()
# Basic sanity-check of PKI init and complain if missing
verify_pki_init() {
help_note="Run easyrsa without commands for usage and command help."
# check that the pki dir exists
vars_source_check
[ -d "$EASYRSA_PKI" ] || die "\
EASYRSA_PKI does not exist (perhaps you need to run init-pki)?
Expected to find the EASYRSA_PKI at: $EASYRSA_PKI
$help_note"
# verify expected dirs present:
for i in private reqs; do
[ -d "$EASYRSA_PKI/$i" ] || die "\
Missing expected directory: $i (perhaps you need to run init-pki?)
$help_note"
done
# verify ssl lib
verify_ssl_lib
} # => verify_pki_init()
# Verify core CA files present
verify_ca_init() {
help_note="Run without commands for usage and command help."
# First check the PKI has been initialized
verify_pki_init
# Verify expected files are present. Allow files to be regular files
# (or symlinks), but also pipes, for flexibility with ca.key
for i in serial index.txt index.txt.attr ca.crt private/ca.key; do
if [ ! -f "$EASYRSA_PKI/$i" ] && [ ! -p "$EASYRSA_PKI/$i" ]; then
[ "$1" = "test" ] && return 1
die "\
Missing expected CA file: $i (perhaps you need to run build-ca?)
$help_note"
fi
done
# When operating in 'test' mode, return success.
# test callers don't care about CA-specific dir structure
[ "$1" = "test" ] && return 0
# verify expected CA-specific dirs:
for i in issued certs_by_serial
do
[ -d "$EASYRSA_PKI/$i" ] || die "\
Missing expected CA dir: $i (perhaps you need to run build-ca?)
$help_note"
done
# explicitly return success for callers
return 0
} # => verify_ca_init()
# init-pki backend:
init_pki() {
# If EASYRSA_PKI exists, confirm before we rm -rf (skipped with EASYRSA_BATCH)
if [ -e "$EASYRSA_PKI" ]; then
confirm "Confirm removal: " "yes" "
WARNING!!!
You are about to remove the EASYRSA_PKI at: $EASYRSA_PKI
and initialize a fresh PKI here."
# now remove it:
rm -rf "$EASYRSA_PKI" || die "Removal of PKI dir failed. Check/correct errors above"
fi
# new dirs:
for i in private reqs; do
mkdir -p "$EASYRSA_PKI/$i" || die "Failed to create PKI file structure (permissions?)"
done
# Install data-files into ALL new PKIs
install_data_to_pki || die "Failed to install required data-files to PKI."
# Verify that $EASYRSA_SAFE_CONF exists ($OPENSSL_CONF)
# Prevents bogus warnings (especially useful on win32)
if [ -n "$EASYRSA_SAFE_CONF" ] && [ -e "$EASYRSA_SAFE_CONF" ]; then
: # ok
else
die "init-pki failed to create safe SSL conf: $EASYRSA_SAFE_CONF"
fi
notice "\
init-pki complete; you may now create a CA or requests.
Your newly created PKI dir is: $EASYRSA_PKI
"
return 0
} # => init_pki()
# Copy data-files from various sources
install_data_to_pki () {
#
# This function is here to explicitly copy data-files to the PKI.
# During 'init-pki' this is the new default.
# During all other functions these requirements are tested for and
# files will be copied to the PKI, if they do not already exist there.
#
# One of the reasons for this change is to make packing EasyRSA work.
# This function searches favoured and then common 'areas' for the
# EasyRSA data-files(A):
# 'openssl-easyrsa.cnf' 'x509-types':(folder).
#
# These files MUST be found in at least one location and will be copied
# to the current PKI, if they do not already exist there.
#
#
# Other EasyRSA data-files(B): it is not crucial that these are found
# but if they are then they are also copied to the PKI.
# 'vars' 'vars.example'
#
#
# For 'vars' consideration must be given to:
# "Where the user expects to find vars!"
#
# Currently, *if* 'vars' is copied to the PKI then the PKI 'vars' will take
# priority over './vars'. But it will not be updated if './vars' is changed.
#
# Copying 'vars' to the PKI is complicated, code is included but DISABLED.
# Set required sources
vars_file='vars'
vars_file_example='vars.example'
ssl_cnf_file='openssl-easyrsa.cnf'
x509_types_dir='x509-types'
# Only use if required
# Omit 'vars' - [ -e "${EASYRSA_PKI}/${vars_file}" ] &&
if [ -e "$EASYRSA_SAFE_CONF" ] && \
[ -e "${EASYRSA_PKI}/${vars_file_example}" ] && \
[ -e "${EASYRSA_PKI}/${ssl_cnf_file}" ] && \
[ -e "${EASYRSA_PKI}/${x509_types_dir}" ]
then
return 0
fi
# PWD covers EasyRSA-Windows installed by OpenVPN, and git forks
area_pwd="$PWD"
# Old way
area_prog="${0%/*}"
# Sensible default - Includes: Arch-Linux
area_etc='/etc/easy-rsa'
# Expandable distros
area_ubuntu='/usr/share/easy-rsa'
# Add more distros here
# Find and copy data-files, in specific order
for area in \
"$area_pwd" \
"$area_prog" \
"$area_etc" \
"$area_ubuntu" \
# EOL - # Add more distros here
do
# Omitting "$vars_file"
for source in \
"$vars_file_example" \
"$ssl_cnf_file" \
# EOL - Do x509-types separately
do
# Find each item
[ -e "${area}/${source}" ] || continue
# If the item does not exist in the PKI then copy it.
if [ -e "${EASYRSA_PKI}/${source}" ]; then
continue
else
copy_data_to_pki "${area}/${source}" || return
fi
done
# Find x509-types
[ -e "${area}/${x509_types_dir}" ] || continue
# If x509-types does not exist in the PKI then copy it.
if [ -e "${EASYRSA_PKI}/${x509_types_dir}" ]; then
continue
else
copy_data_to_pki "${area}/${x509_types_dir}" recurse || return
fi
done
# Check PKI is updated - Omit 'vars' and example.
#[ -e "${EASYRSA_PKI}/${vars_file}" ] || return
#[ -e "${EASYRSA_PKI}/${vars_file_example}" ] || return
[ -e "${EASYRSA_PKI}/${ssl_cnf_file}" ] || return
[ -e "${EASYRSA_PKI}/${x509_types_dir}" ] || return
# Complete or error
[ -e "$EASYRSA_SAFE_CONF" ] || easyrsa_openssl makesafeconf
} # => install_data_to_pki ()
# Copy the source to the PKI
copy_data_to_pki () {
cp ${2:+-R} "$1" "$EASYRSA_PKI"
} # => copy_data_to_pki ()
# Disable terminal echo, if possible, otherwise warn
hide_read_pass()
{
# shellcheck disable=SC2039
if stty -echo 2>/dev/null; then
read -r "$@"
stty echo
elif (set +o echo 2>/dev/null); then
set +o echo
read -r "$@"
set -o echo
elif (echo | read -r -s 2>/dev/null) ; then
read -r -s "$@"
else
warn "Could not disable echo. Password will be shown on screen!"
read -r "$@"
fi
} # => hide_read_pass()
# build-ca backend:
build_ca() {
opts=""
sub_ca=""
nopass=""
crypto="-aes256"
while [ -n "$1" ]; do
case "$1" in
intca) sub_ca=1 ;;
subca) sub_ca=1 ;;
nopass) nopass=1 ;;
*) warn "Ignoring unknown command option: '$1'" ;;
esac
shift
done
verify_pki_init
[ "$EASYRSA_ALGO" = "ec" ] && verify_curve_ec
[ "$EASYRSA_ALGO" = "ed" ] && verify_curve_ed
# setup for the simpler intermediate CA situation and overwrite with root-CA if needed:
out_file="$EASYRSA_PKI/reqs/ca.req"
out_key="$EASYRSA_PKI/private/ca.key"
if [ ! $sub_ca ]; then
out_file="$EASYRSA_PKI/ca.crt"
opts="$opts -x509 -days $EASYRSA_CA_EXPIRE "
fi
# Test for existing CA, and complain if already present
if verify_ca_init test; then
die "\
Unable to create a CA as you already seem to have one set up.
If you intended to start a new CA, run init-pki first."
fi
# If a private key exists here, a intermediate ca was created but not signed.
# Notify the user and require a signed ca.crt or a init-pki:
[ -f "$out_key" ] && \
die "\
A CA private key exists but no ca.crt is found in your PKI dir of:
$EASYRSA_PKI
Refusing to create a new CA keypair as this operation would overwrite your
current CA keypair. If you intended to start a new CA, run init-pki first."
# create necessary files and dirs:
err_file="Unable to create necessary PKI files (permissions?)"
for i in issued certs_by_serial \
revoked/certs_by_serial revoked/private_by_serial revoked/reqs_by_serial \
renewed/certs_by_serial renewed/private_by_serial renewed/reqs_by_serial;
do
mkdir -p "$EASYRSA_PKI/$i" || die "$err_file"
done
printf "" > "$EASYRSA_PKI/index.txt" || die "$err_file"
printf "" > "$EASYRSA_PKI/index.txt.attr" || die "$err_file"
print "01" > "$EASYRSA_PKI/serial" || die "$err_file"
# Default CN only when not in global EASYRSA_BATCH mode:
# shellcheck disable=SC2015
[ "$EASYRSA_BATCH" ] && opts="$opts -batch" || export EASYRSA_REQ_CN="Easy-RSA CA"
out_key_tmp="$(easyrsa_mktemp)" || die "Failed to create temporary file"
out_file_tmp="$(easyrsa_mktemp)" || die "Failed to create temporary file"
# Get password from user if necessary
if [ ! $nopass ] && ( [ -z "$EASYRSA_PASSOUT" ] || [ -z "$EASYRSA_PASSIN" ] ); then
out_key_pass_tmp="$(easyrsa_mktemp)" || die "Failed to create temporary file"
echo
printf "Enter New CA Key Passphrase: "
hide_read_pass kpass
echo
printf "Re-Enter New CA Key Passphrase: "
hide_read_pass kpass2
echo
# shellcheck disable=2154
if [ "$kpass" = "$kpass2" ];
then
printf "%s" "$kpass" > "$out_key_pass_tmp"
else
die "Passphrases do not match."
fi
fi
# Choose SSL Library version (1 or 3) and build CA
case "$osslv_major" in # => BEGIN SSL lib version
# BEGIN SSL V3
3)
# If encrypted then create the CA key using AES256 cipher ($crypto)
# 'genpkey' requires '-pass'
crypto_opts=""
if [ ! $nopass ]; then
crypto_opts="$crypto"
if [ -z "$EASYRSA_PASSOUT" ]; then
crypto_opts="$crypto_opts -pass file:$out_key_pass_tmp"
fi
fi
# Generate CA Key - OpenSSL v3 'genpkey' is not compatible
# with easyrsa $opts and $no_password, do NOT use them here
# shellcheck disable=SC2086 # Ignore unquoted variables
case "$EASYRSA_ALGO" in
rsa)
# OpenSSL v3: 'genrsa' is deprecate, use 'genpkey'
easyrsa_openssl genpkey -algorithm "$EASYRSA_ALGO" \
-out "$out_key_tmp" ${crypto_opts} \
-pkeyopt rsa_keygen_bits:"$EASYRSA_ALGO_PARAMS" \
${EASYRSA_PASSOUT:+-pass "$EASYRSA_PASSOUT"} || \
die "Failed create CA private key"
;;
ec)
easyrsa_openssl genpkey -paramfile "$EASYRSA_ALGO_PARAMS" \
-out "$out_key_tmp" ${crypto_opts} \
${EASYRSA_PASSOUT:+-pass "$EASYRSA_PASSOUT"} || \
die "Failed create CA private key"
;;
ed)
case "$EASYRSA_CURVE" in
[eE][dD]25519|[eE][dD]448)
easyrsa_openssl genpkey -algorithm "$EASYRSA_CURVE" \
-out "$out_key_tmp" ${crypto_opts} \
${EASYRSA_PASSOUT:+-pass "$EASYRSA_PASSOUT"} || \
die "Failed create CA private key" ;;
*) die "Unknown curve: $EASYRSA_CURVE"
esac
;;
*)
die "Unknown algorithm: $EASYRSA_ALGO"
esac
# Private key encryption password or use no_password
# 'req' requires '-passin'
crypto_opts=""
if [ ! $nopass ] && [ -z "$EASYRSA_PASSIN" ]; then
crypto_opts="-passin file:$out_key_pass_tmp"
else
crypto_opts="$no_password"
fi
# create the CA keypair:
# shellcheck disable=SC2086
easyrsa_openssl req -utf8 -new -key "$out_key_tmp" \
-out "$out_file_tmp" ${opts} ${crypto_opts} \
${EASYRSA_PASSIN:+-passin "$EASYRSA_PASSIN"} || \
die "Failed to build the CA"
;;
# END SSL V3
# BEGIN SSL V1 - Includes LibreSSL 2.x
1|2)
# If encrypted then create the CA key using AES256 cipher ($crypto)
crypto_opts=""
if [ ! $nopass ]; then
crypto_opts="$crypto"
if [ -z "$EASYRSA_PASSOUT" ]; then
if [ "ed" = "$EASYRSA_ALGO" ]; then
crypto_opts="$crypto_opts -pass file:$out_key_pass_tmp"
else
crypto_opts="$crypto_opts -passout file:$out_key_pass_tmp"
fi
fi
fi
# create the CA key
#shellcheck disable=SC2086
case "$EASYRSA_ALGO" in
rsa)
"$EASYRSA_OPENSSL" genrsa -out "$out_key_tmp" $crypto_opts \
${EASYRSA_PASSOUT:+-passout "$EASYRSA_PASSOUT"} \
"$EASYRSA_ALGO_PARAMS" || \
die "Failed create CA private key"
;;
ec)
"$EASYRSA_OPENSSL" ecparam -in "$EASYRSA_ALGO_PARAMS" -genkey | \
"$EASYRSA_OPENSSL" ec -out "$out_key_tmp" $crypto_opts \
${EASYRSA_PASSOUT:+-passout "$EASYRSA_PASSOUT"} || \
die "Failed create CA private key"
;;
ed)
case "$EASYRSA_CURVE" in
[eE][dD]25519|[eE][dD]448)
"$EASYRSA_OPENSSL" genpkey -algorithm "$EASYRSA_CURVE" \
-out "$out_key_tmp" $crypto_opts \
${EASYRSA_PASSOUT:+-pass "$EASYRSA_PASSOUT"} || \
die "Failed create CA private key" ;;
*) die "Unknown curve: $EASYRSA_CURVE"
esac
;;
*) die "Unknown algorithm: $EASYRSA_ALGO"
esac
# create the CA keypair:
crypto_opts=""
if [ ! $nopass ] && [ -z "$EASYRSA_PASSIN" ]; then
crypto_opts="-passin file:$out_key_pass_tmp"
else
crypto_opts="$no_password"
fi
#shellcheck disable=SC2086
easyrsa_openssl req -utf8 -new -key "$out_key_tmp" \
-keyout "$out_key_tmp" -out "$out_file_tmp" $crypto_opts $opts \
${EASYRSA_PASSIN:+-passin "$EASYRSA_PASSIN"} || \
die "Failed to build the CA"
;;
# END SSL V1
*) die "build-ca ssl lib: $osslv_major"
esac # => END SSL lib version
mv "$out_key_tmp" "$out_key"
mv "$out_file_tmp" "$out_file"
[ -f "$out_key_pass_tmp" ] && rm "$out_key_pass_tmp"
# Success messages
if [ $sub_ca ]; then
notice "\
NOTE: Your intermediate CA request is at $out_file
and now must be sent to your parent CA for signing. Place your resulting cert
at $EASYRSA_PKI/ca.crt prior to signing operations.
"
else notice "\
CA creation complete and you may now import and sign cert requests.
Your new CA certificate file for publishing is at:
$out_file
"
fi
return 0
} # => build_ca()
# gen-dh backend:
gen_dh() {
verify_pki_init
out_file="$EASYRSA_PKI/dh.pem"
# check to see if we already have a dh parameters file
if [ -e "$EASYRSA_PKI/dh.pem" ]; then
if [ "$EASYRSA_BATCH" = "1" ]; then
# if batch is enabled, die
die "file $EASYRSA_PKI/dh.pem already exists!"
else
# warn the user, give them a chance to force overwrite
confirm "Overwrite? " "yes" "*** File $EASYRSA_PKI/dh.pem already exists! ***"
fi
fi
"$EASYRSA_OPENSSL" dhparam -out "$out_file" "$EASYRSA_KEY_SIZE" || \
die "Failed to build DH params"
notice "\
DH parameters of size $EASYRSA_KEY_SIZE created at $out_file
"
return 0
} # => gen_dh()
# gen-req backend:
gen_req() {
# pull filename base and use as default interactive CommonName:
[ -n "$1" ] || die "\
Error: gen-req must have a file base as the first argument.
Run easyrsa without commands for usage and commands."
key_out="$EASYRSA_PKI/private/$1.key"
req_out="$EASYRSA_PKI/reqs/$1.req"
[ ! "$EASYRSA_BATCH" ] && EASYRSA_REQ_CN="$1"
shift
# Require SSL Lib version for 'nopass' -> $no_password
verify_pki_init
# function opts support
opts=
while [ -n "$1" ]; do
case "$1" in
nopass) opts="$opts $no_password" ;;
# batch flag supports internal callers needing silent operation
batch) EASYRSA_BATCH=1 ;;
*) warn "Ignoring unknown command option: '$1'" ;;
esac
shift
done
[ "$EASYRSA_ALGO" = "ec" ] && verify_curve_ec
[ "$EASYRSA_ALGO" = "ed" ] && verify_curve_ed
# don't wipe out an existing private key without confirmation
[ -f "$key_out" ] && confirm "Confirm key overwrite: " "yes" "\
WARNING!!!
An existing private key was found at $key_out
Continuing with key generation will replace this key."
# When EASYRSA_EXTRA_EXTS is defined, append it to openssl's [req] section:
if [ -n "$EASYRSA_EXTRA_EXTS" ]; then
# Setup & insert the extra ext data keyed by a magic line
extra_exts="
req_extensions = req_extra