-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
easyrsa
executable file
·3635 lines (3114 loc) · 104 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 on Github at:
# https://github.com/OpenVPN/easy-rsa/graphs/contributors
#
# 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 [ cmd-opts ]
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]
revoke-renewed <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 ]
show-crl
import-req <request_file_path> <short_basename>
export-p1 <filename_base> [ cmd-opts ]
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"
opts="
hard-reset - Recursively deletes the PKI directory if it exists.
soft-reset - Keeps the vars file and the PKI directory itself intact." ;;
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="
text - Include certificate text in request
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";;
revoke-renewed) text="
revoke-renewed <filename_base> [reason]
Revoke a renewed 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" ;;
show-crl) text="
show-crl
Shows details of the current certificate revocation list (CRL)
Human-readable output is shown." ;;
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="
nopass - use no password and leave the key unencrypted
noca - do not include the ca.crt file in the PKCS12 output
nokey - do not include the private key in the PKCS12 output
usefn - use <filename_base> as friendly name" ;;
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="
nopass - do not encrypt the private key (default is encrypted)" ;;
export-p1) text="
export-p1 <filename_base> [ cmd-opts ]
Export a PKCS#1 (RSA format) file with the pubkey specified by <filename_base>"
opts="
nopass - do not encrypt the private key (default is encrypted)" ;;
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
--silent : Disable all Warnings and Notices
--sbatch : Combined --silent and --batch operating mode
--passin=ARG : set -passin ARG for openssl
--passout=ARG : set -passout ARG for openssl
--pki-dir=DIR : declare the PKI directory
--tmp-dir=DIR : declare the temporary directory
--ssl-conf=FILE : define a specific OpenSSL config file for Easy-RSA to use
--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
--fix-offset=# : Generate certificate with fixed start and end dates.
: Range 1 to 365
: start date: 01 January 00:00:00 of the current year
: end date: off-set days 01:00:00 of the final year
: Final year is configured via --days (Default: 825 days, 2 years)
--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
--san : 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=YES/NO : 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
# print() is used internally, so MUST NOT be silenced.
# 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
print "
Host: $host_out
${EASYRSA_DEBUG+
*** Disable EASYRSA_DEBUG mode ***}"
exit "${2:-1}"
} # => die()
# non-fatal warning output
warn() {
[ "$EASYRSA_SILENT" ] && return
print "* WARNING:
$1
" 1>&2
} # => warn()
# informational notices to stdout
notice() {
[ "$EASYRSA_SILENT" ] && return
[ "$EASYRSA_BATCH" ] && return
print "* Notice:
$1
"
} # => 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 # vars don't expand in single quotes
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 without -r will mangle backslashes
read input
printf '\n'
[ "$input" = "$value" ] && return
notice "Aborting without confirmation."
exit 9
} # => confirm()
# Create session directory atomically or fail
secure_session() {
# Session is already defined
[ "$EASYRSA_TEMP_DIR_session" ] && die "session overload"
# temporary directory must exist
[ -n "$EASYRSA_TEMP_DIR" ] || return
[ -d "$EASYRSA_TEMP_DIR" ] || die "\
Non-existant temporary directory: $EASYRSA_TEMP_DIR"
for i in 1 2 3; do
# Always use openssl directly for rand
rand="$("$EASYRSA_OPENSSL" rand -hex 4)" \
|| die "secure_session - rand '$rand'"
mkdir "${EASYRSA_TEMP_DIR}/${rand}" || continue
EASYRSA_TEMP_DIR_session="${EASYRSA_TEMP_DIR}/${rand}"
return
done
return 1
} # => secure_session()
# Create tempfile atomically or fail
easyrsa_mktemp() {
# session directory must exist
[ -n "$EASYRSA_TEMP_DIR_session" ] || return
[ -d "$EASYRSA_TEMP_DIR_session" ] || return
for i in 1 2 3; do
# Always use openssl directly for rand
rand="$("$EASYRSA_OPENSSL" rand -hex 4)" \
|| die "easyrsa_mktemp - rand '$rand'"
shotfile="${EASYRSA_TEMP_DIR_session}/shot.$rand"
if [ -e "$shotfile" ]; then
continue
else
printf "" > "$shotfile" || continue
fi
tempfile="${EASYRSA_TEMP_DIR_session}/temp.$rand"
mv "$shotfile" "$tempfile" || continue
printf '%s\n' "$tempfile" || die "easyrsa_mktemp - write temp"
return
done
return 1
} # => easyrsa_mktemp()
# remove temp files and do terminal cleanups
cleanup() {
[ -z "$EASYRSA_TEMP_DIR_session" ] || rm -rf "$EASYRSA_TEMP_DIR_session"
[ -n "${EASYRSA_EC_DIR%/*}" ] && [ -d "$EASYRSA_EC_DIR" ] && \
rm -rf "$EASYRSA_EC_DIR"
# shellcheck disable=SC3040 # In POSIX sh, set option [name] is undefined
case "$easyrsa_host_os" in
nix) stty echo ;;
win) set -o echo ;;
*) warn "Host OS undefined."
esac
[ "$EASYRSA_SILENT" ] || echo "" # just to get a clean line
} # => cleanup()
# Easy-RSA meta-wrapper for SSL
easyrsa_openssl() {
openssl_command="$1"; shift
# Do not allow 'rand' here because it interferes with EASYRSA_DEBUG
case "$openssl_command" in
rand) die "easyrsa_openssl: Illegal SSL command: rand" ;;
makesafeconf) has_config=1 ;;
ca|req|srp|ts) has_config=1 ;;
*) unset -v has_config
esac
# OpenSSL 1x genpkey does not support -config - Not as documented:
# https://www.openssl.org/docs/manmaster/man1/openssl-genpkey.html
if [ "$osslv_major" = 3 ] && [ "$openssl_command" = genpkey ]; then
has_config=1
fi
if [ "$has_config" ]; then
# Make LibreSSL safe config file from OpenSSL config file
# Do not use easyrsa_mktemp() for init-pki
if [ "$no_pki_required" ]; then
# for init-pki $EASYRSA_SAFE_CONF is always set in the PKI, use it.
easyrsa_openssl_conf="${EASYRSA_SAFE_CONF}.init-tmp"
else
easyrsa_openssl_conf="$(easyrsa_mktemp)" || \
die "easyrsa_openssl - Failed to create temporary file"
fi
# OpenSSL does not require a safe config, so skip to the copy
if [ "$require_safe_ssl_conf" ]; then
# Make a safe SSL 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_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_SSL_CONF" > "$easyrsa_openssl_conf" || \
die "easyrsa_openssl - Failed to make temporary config"
else
# Do NOT Make a safe SSL config file
cp -f "$EASYRSA_SSL_CONF" "$easyrsa_openssl_conf" || \
die "easyrsa_openssl - Failed to copy temporary config"
fi
if [ "$openssl_command" = "makesafeconf" ]; then
# move temp file to safessl-easyrsa.cnf
mv -f "$easyrsa_openssl_conf" "$EASYRSA_SAFE_CONF" || \
die "easyrsa_openssl - makesafeconf failed"
else
# !!!
# this debug CANNOT be used in automated testing
# to function correctly easyrsa_openssl()
# must ONLY output SSL layer output
# debug log on
if [ "$EASYRSA_DEBUG" ]; then set -x; fi
# Exec SSL with -config temp-file
"$EASYRSA_OPENSSL" "$openssl_command" \
-config "$easyrsa_openssl_conf" "$@" || return
# debug log off
if [ "$EASYRSA_DEBUG" ]; then set +x; fi
fi
else
# !!!
# this debug CANNOT be used in automated testing
# to function correctly easyrsa_openssl()
# must ONLY output SSL layer output
# debug log on
if [ "$EASYRSA_DEBUG" ]; then set -x; fi
# Exec SSL without -config temp-file
"$EASYRSA_OPENSSL" "$openssl_command" "$@" || return
# debug log off
if [ "$EASYRSA_DEBUG" ]; then set +x; fi
fi
} # => easyrsa_openssl()
# Verify supplied curve exists and Always generate curve file
verify_curve_ec() {
# 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
if easyrsa_openssl ecparam -name "$EASYRSA_CURVE" \
-out "$EASYRSA_ALGO_PARAMS" 1>/dev/null
then
return 0
fi
# Clean up failure
rm -rf "$EASYRSA_EC_DIR"
die "\
Failed to generate ecparam file (permissions?) when writing to:
$EASYRSA_ALGO_PARAMS"
} # => verify_curve_ec()
# Verify if Edwards Curve exists
verify_curve_ed() {
easyrsa_openssl genpkey -algorithm "$EASYRSA_CURVE" > /dev/null \
|| die "Edwards Curve $EASYRSA_CURVE not found."
} # => verify_curve_ed()
# Verify the SSL library is functional and establish version dependencies
verify_ssl_lib() {
if [ -z "$EASYRSA_SSL_OK" ]; then
val="$("$EASYRSA_OPENSSL" version)"
case "${val%% *}" in
# OpenSSL does not require a safe config-file
OpenSSL) unset -v require_safe_ssl_conf ;;
LibreSSL) require_safe_ssl_conf=1 ;;
*) die "\
Missing or invalid OpenSSL
Expected to find openssl command at: $EASYRSA_OPENSSL"
esac
# Set SSL version dependent $no_password option
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
notice "Using SSL: $EASYRSA_OPENSSL $val"
EASYRSA_SSL_OK=1
fi
# 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 for defined EASYRSA_PKI
[ -n "$EASYRSA_PKI" ] || die "\
EASYRSA_PKI env-var undefined"
# check that the pki dir exists
[ -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
unset -v help_note
} # => verify_pki_init()
# Verify core CA files present
verify_ca_init() {
# First check the PKI has been initialized
verify_pki_init
help_note="Run without commands for usage and command help."
# 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
unset -v help_note
return 0
} # => verify_ca_init()
# init-pki backend:
init_pki() {
# Process command options
reset="hard"
while [ -n "$1" ]; do
case "$1" in
hard-reset|hard) reset="hard" ;;
soft-reset|soft) reset="soft" ;;
*) warn "Ignoring unknown command option: '$1'"
esac
shift
done
# 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:
case "$reset" in
hard)
rm -rf "$EASYRSA_PKI" || \
die "Removal of PKI dir failed. Check/correct errors above"
;;
soft)
for i in ca.crt certs_by_serial ecparams index.txt index.txt.attr \
index.txt.old issued private reqs serial serial.old; do
rm -rf "${EASYRSA_PKI:?}/$i" || \
die "Removal of PKI dir failed. Check/correct errors above"
done
;;
# More modes could be added here, e.g. only remove
# issued certs (and clean database), but keep CA intact.
*)
die "Removal of PKI dir failed. Unknown reset type: $reset"
esac
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 init-pki || \
warn "Failed to install required data-files to PKI. (init)"
# 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
IMPORTANT: Easy-RSA 'vars' file has now been moved to your PKI above."
} # => init_pki()
# Copy data-files from various sources
install_data_to_pki () {
#
# This function will explicitly find and optionally 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 packaging EasyRSA work.
#
# First: search favoured and then common 'areas' for the EasyRSA data-files(A):
# * 'openssl-easyrsa.cnf' and 'x509-types' (folder).
#
# These files MUST be found in at least one location.
# * 'openssl-easyrsa.cnf' will be copied to the PKI.
# A warning will be issued if this file cannot be found.
#
# * 'x509-types' will set EASYRSA_EXT_DIR to the found location.
# If x509-types cannot be found then that is a FATAL error.
#
# Other EasyRSA data-files(B): it is not crucial that these are found
# but if they are then they are copied to the PKI. (Note: 1)
# * 'vars' and 'vars.example'
#
# Note 1: 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.
context="$1"
shift
# Set required sources
vars_file='vars'
vars_file_example='vars.example'
ssl_cnf_file='openssl-easyrsa.cnf'
x509_types_dir='x509-types'
# PWD - Covers EasyRSA-Windows installed by OpenVPN, and git forks
# "prog_dir" - Old way (Who installs data files in /usr/bin ?)
# /etc/easy-rsa - possible default
# /usr/share/easy-rsa - usr
# /usr/local/share/easy-rsa - usr/local
# Find and copy data-files, in specific order
for area in \
"$PWD" \
"${0%/*}" \
'/etc/easy-rsa' \
'/usr/share/easy-rsa' \
'/usr/local/share/easy-rsa' \
# 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
cp "${area}/${source}" "$EASYRSA_PKI" || return
fi
done
# Find x509-types
[ -e "${area}/${x509_types_dir}" ] || continue
# Declare in preferred order, first wins, beaten by command line.
# Only set if not in PKI; Same condition made in vars_setup()
if [ ! -d "$EASYRSA_PKI/x509-types" ]; then
set_var EASYRSA_EXT_DIR "${area}/${x509_types_dir}"
fi
done
# if PKI/x509-types exists then it wins, except command line
# Same condition made in vars_setup()
if [ -d "$EASYRSA_PKI/x509-types" ]; then
set_var EASYRSA_EXT_DIR "$EASYRSA_PKI/x509-types"
fi
# If this is init-pki then create PKI/vars from PKI/example
case "$context" in
init-pki)
if [ -e "${EASYRSA_PKI}/${vars_file_example}" ]; then
[ -e "${EASYRSA_PKI}/${vars_file}" ] || \
cp "${EASYRSA_PKI}/${vars_file_example}" \
"${EASYRSA_PKI}/${vars_file}" || :
fi
;;
vars-setup)
if [ "$found_vars" ]; then
: # ok - Do not make a PKI/vars if another vars exists
else
if [ -e "${EASYRSA_PKI}/${vars_file_example}" ]; then
[ -e "${EASYRSA_PKI}/${vars_file}" ] || \
cp "${EASYRSA_PKI}/${vars_file_example}" \
"${EASYRSA_PKI}/${vars_file}" || :
fi
fi
;;
'')
die "install_data_to_pki - unspecified context" ;;
*)
die "install_data_to_pki - unknown context: $context"
esac
# Check PKI is updated - Omit unnecessary checks
#[ -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
# EASYRSA_EXT_DIR must be found! No exceptions!
# The shellcheck warning 2015 is valid, however, this code works correctly.
# Note that A && B || C is not if-then-else. C may run when A is true
# shellcheck disable=SC2015
[ -n "$EASYRSA_EXT_DIR" ] && [ -e "$EASYRSA_EXT_DIR" ] || \
die "x509-types folder cannot be found: $EASYRSA_EXT_DIR"
# Complete or error
[ -e "$EASYRSA_SAFE_CONF" ] || easyrsa_openssl makesafeconf
} # => install_data_to_pki ()
# Disable terminal echo, if possible, otherwise warn
hide_read_pass()
{
# 3040 - In POSIX sh, set option [name] is undefined
# 3045 - In POSIX sh, some-command-with-flag is undefined
# shellcheck disable=SC3040,SC3045
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() {
cipher="-aes256"
unset -v nopass sub_ca ssl_batch date_stamp x509
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
out_key="$EASYRSA_PKI/private/ca.key"
# setup for an intermediate CA
if [ "$sub_ca" ]; then
# Gerate a CSR
out_file="$EASYRSA_PKI/reqs/ca.req"
else
# Gerate a certificate
out_file="$EASYRSA_PKI/ca.crt"
date_stamp=1
x509=1
fi
# If encrypted then create the CA key using AES256 cipher
if [ "$nopass" ]; then
unset -v cipher
else
unset -v no_password
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;
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"
printf '%s\n' "01" > "$EASYRSA_PKI/serial" || die "$err_file"
# Default CN only when not in global EASYRSA_BATCH mode:
[ "$EASYRSA_BATCH" ] && ssl_batch=1
[ "$EASYRSA_REQ_CN" = ChangeMe ] && export EASYRSA_REQ_CN="Easy-RSA CA"
out_key_tmp="$(easyrsa_mktemp)" || die "Failed to create temp-key file"
out_file_tmp="$(easyrsa_mktemp)" || die "Failed to create temp-cert file"
# Get password from user if necessary
if [ -z "$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 # var is referenced but not assigned
if [ "$kpass" = "$kpass2" ]; then
printf "%s" "$kpass" > "$out_key_pass_tmp"
else
die "Passphrases do not match."
fi
fi
# Insert x509-types COMMON and 'ca' and EASYRSA_EXTRA_EXTS, if defined.
# shellcheck disable=SC2016 # vars don't expand in single quote
awkscript='
{if ( match($0, "^#%CA_X509_TYPES_EXTRA_EXTS%") )
{ while ( getline<"/dev/stdin" ) {print} next }
{print}
}'
conf_tmp="$(easyrsa_mktemp)" || die "Failed to create temporary file"
{
cat "$EASYRSA_EXT_DIR/ca" "$EASYRSA_EXT_DIR/COMMON"
[ "$EASYRSA_EXTRA_EXTS" ] && print "$EASYRSA_EXTRA_EXTS"
} | \
awk "$awkscript" "$EASYRSA_SSL_CONF" \
> "$conf_tmp" \
|| die "Copying X509_TYPES to config file failed"
# Use this new SSL config for the rest of this function
EASYRSA_SSL_CONF="$conf_tmp"
# Choose SSL Library version (1, 2(LibreSSL) or 3) and build CA
case "$osslv_major" in
# Version agnostic CA generation
# The only remaining option which is version dependent is -nodes/-noenc
1|2|3)
# Generate CA Key
case "$EASYRSA_ALGO" in
rsa)
easyrsa_openssl genpkey -algorithm "$EASYRSA_ALGO" \
-pkeyopt rsa_keygen_bits:"$EASYRSA_ALGO_PARAMS" \
-out "$out_key_tmp" \
${cipher+ "$cipher"} \
${EASYRSA_PASSOUT:+ -pass "$EASYRSA_PASSOUT"} \