forked from bpstahlman/cac-enabled-git-setup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild-cac-enabled-git
executable file
·952 lines (917 loc) · 33 KB
/
build-cac-enabled-git
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
#! /bin/bash
# Synopsis: Automate the creation of a version of Git that can load PKCS11 engines to use a CAC card for authentication.
# Author: Brett Pershing Stahlman
# Sources:
# -The following document by Jerry Quassar, entitled "Using Native git with CAC":
# https://rite.sd.spawar.navy.mil/confluence/display/RITE/Using+git+with+CAC
# -Lots of trial-and-error/debugging.
# Date: 09 March 2015
# --TODO--
VERSION=0.9.7
# Starting cwd is base of operations.
# TODO: Check to be sure it seems to contain the package.
Basedir=$PWD
# Make sure we have an unmodified git we can use to clone source repos.
# TODO: This should probably be obtained more reliably...
Sys_git=/usr/bin/git
# This will be detected and set in detect_cac_card.
# Possible TODO: This can also be set by option now. Perhaps put in Opts[]
Card_id=
# Facilitate skipping install step when --no-install specified
Make_install="make install"
# System type: cygwin32 | cygwin64 | linux
System_type=
declare -i Step_idx=0
# Container for steps specified with --skip-step
declare -A Skip_steps=()
# Container for steps specified with --only-steps
declare -A Only_steps=()
# These are tied to the --start-step / --end-step options
Start_step=
End_step=
# Rules:
# --start-step and/or --end-step puts us in range mode
# --only-step puts us in only mode
# max 1 mode transition permitted
Step_mode=normal # normal | range | only
# Note: A missing boolean option is considered unset.
declare -A Opts=(
[ca-bundle-in]=http://curl.haxx.se/ca/cacert.pem
[ca-bundle-out]=~/ca-bundle-plus-dod-root.pem
[openssl-conf]=~/pkcs11-openssl.cnf
[env-script]=~/cac-enabled-git-env.sh
)
declare -a Steps=(
download_source
build_opensc
detect_cac_card
create_certs
patch_curl
build_curl
configure_openssl_conf
patch_git
build_git
install_env_script
)
# TODO: Consider making this an on_err (using ERR signal instead of EXIT).
on_exit() {
if (($? == 0)); then
log --ts "Success! You may need to open a new terminal before changes take effect."
else
cat <<-eof >&2
Setup aborted with error! Check stdout for details.
After resolving any issues, you can resume setup at the failed step with the
following option: --start-step ${Steps[$Step_idx]}"
eof
fi
cd "$Basedir"
}
# Run all steps not excluded by options.
run() {
local started=no
if [[ $Step_mode == normal || ($Step_mode == range && -z $Start_step) ]]; then
started=yes
fi
for step in "${Steps[@]}"; do
local skip=no
# Process started and skip logic.
if [[ $Step_mode == only ]]; then
if [[ -z ${Only_steps[$step]} ]]; then
skip=yes
fi
else # normal | range
if [[ $started == no && $step == $Start_step ]]; then
started=yes
fi
if [[ $started == no || -n ${Skip_steps[$step]} ]]; then
skip=yes
fi
fi
# If we're not skipping...
if [[ $skip == no ]]; then
log --ts "Starting step #$((Step_idx + 1)): $step"
${Opts[no-execute]:+echo Simulating step} $step
log --ts "Finished step #$((Step_idx + 1)): $step"
fi
# Check for termination condition.
if [[ $Step_mode == range && -n $End_step && $step == $End_step ]]; then
log "Exiting after specified end step: $End_step"
return 0
fi
((++Step_idx))
done
}
# TODO: Colorize?
log() {
if [[ $1 == --ts ]]; then
ts="$(date +%T): "
shift
fi
echo >&2 "$ts$@"
}
# Display usage message on stderr
usage() {
# TODO: Path or not?
local prog=$(basename "$0")
cat >&2 <<-eof
Usage: sudo $prog [OPTION]...
Caveat: Must be run as root (e.g., using sudo) in non-Cygwin environments.
Try '$prog --help' for more information.
eof
}
# Display help on stdout
show_help() {
local prog=$(basename $0)
# TODO: Finish converting this...
cat <<-eof
Usage: $prog [OPTION]...
Build a PKCS#11-enabled Git that supports authentication with a DoD CAC card.
-s, --start-step=STEP start with STEP
--skip-steps=STEP[,STEP]... skip specified step(s)
--only-steps=STEP[,STEP]... run *only* specified step(s)
--end-step=STEP end with STEP
--card-id=XX 2-digit smart card id
Note: Can be detected by script if CAC card
is inserted.
--ca-bundle-in=PATH|URL where to obtain ca-bundle (preferably
Mozilla's cert bundle in .pem format)
Default: ${Opts[ca-bundle-in]}
--ca-bundle-out=PATH where to put generated ca-bundle
Default: ${Opts[ca-bundle-out]}
--openssl-conf=PATH full path for generated openssl conf file
CAVEAT: Directory must exist.
Default: /usr/ssl/pkcs11-openssl.cnf
--skip-cygwin-x if you don't want Cygwin X server installed
(e.g., you don't plan to run graphical git)
NOTE: Option ignored on non-Windows systems
--no-install build without installing
--no-execute a sort of "dry run" - steps not executed
--list-steps list the steps (with short desc) and exit
--help display this help and exit
--version output version information and exit
Examples:
sudo $prog --ca-bundle-out=~/my-certs/my-ca-bundle.pem
sudo $prog --openssl-conf=~/my-conf/openssl.conf
$prog --skip-cygwin-x
sudo $prog --start-step create_certs
Prerequisites: (Before running...)
Windows users:
This script assumes you have the default Cygwin "Base" package installed.
It also assumes a working \`wget' in your path (may be obtained from the
Cygwin "Web" package).
Linux users:
This script assumes you have a standard Linux build toolchain, as well as
the following libraries or suitable equivalents:
Note: Exact package names may vary from one distribution to the next.
openssl libnss libssl-dev
git autoconf automake m4 libtool
gettext libexpat1-dev
libpcsclite-dev
Running the script:
1. Open a shell with access to Bash.
2. Create an empty directory anywhere you like.
3. cd to the directory created in step 2, and run this script.
Note: The terminal's buffer may not be sufficiently large to hold all of
the output generated by the script. If you wish to monitor the script's
progress real-time, but capture all output in a logfile, you could do
something like this...
sudo ./$prog [OPTIONS] |& tee ./setup.log
Alternatively, if you wish to see only stderr, redirecting stdout to a
file for inspection at a later time...
sudo ./$prog [OPTIONS] > ./setup.log
Note: \`sudo' applies only to non-Cygwin environments.
Output:
Upon successful termination of this script, you should have a CAC-aware Git
in your path (/usr/local/bin). Additionally, this script will attempt to
add \`source' commands to several of your startup scripts to ensure that
the environment variables needed to use the CAC-aware Git are set in both
login and non-login interactive shells.
Note: If you wish to inhibit loading the PKCS#11 engine temporarily, you
have several options:
1. Set environment variable INHIBIT_CAC_ENABLED_GIT=1 to prevent the env
vars from being defined each time you start a shell.
2. Run disable_cac_aware_git from within your current shell.
Note: There's a matching enable_cac_aware_git should you wish to
re-enable.
Note: This script leaves the default (non-CAC-aware) Git in its default
location (typically /usr/bin); thus, a more definitive way to disable the
CAC customizations is to adjust your PATH to ensure that the default Git is
is found first. Additionally, the aforementioned startup script creates...
ncgit
...(non-CAC git) as an alias to /usr/bin/git.
eof
}
error() {
local usage=no
if [[ $1 == --usage ]]; then
usage=yes
shift
fi
echo >&2 "$@"
if [[ $usage == yes ]]; then
usage
fi
exit 1
}
warn() {
echo >&2 "Warning: $@"
}
list_steps() {
cat <<-eof
download_source
Download source code for several OpenSC libraries and tools, as well as
the source for cURL and Git (both of which we'll be patching and
building).
build_opensc
Build the OpenSC libraries/tools.
detect_cac_card
Simultaneously verify opensc tool installation and determine the CAC slot
id to be used to build various GIT_SSL_<...> environment vars.
create_certs
Download 3 separate DOD root CA cert bundles, convert to .pem format, and
combine with the default CA bundles provided with openssl to create a
single cert bundle that can be used with Git's sslCAInfo config option.
patch_curl
Modify the cURL source code to support dynamic loading of the PKCS11
engine built in an earlier step.
build_curl
Build the modified cURL (both standalone and dynamic library)
configure_openssl_conf
Create an OpenSSL configuration file that will enable the PKCS11 engine to
be loaded dynamically by the cURL library.
patch_git
Modify the Git source to do the following:
-Add support for several SSL-related options that are needed to configure
the cURL lib to use PKCS11.
-Add support for an environment variable (GIT_INHIBIT_ASKPASS), which can
be set to prevent Git from trying to use the default Tk GUI prompt (which
can fail on non-X11 systems) for collecting passwords.
build_git
Build the modified Git
install_env_script
Install an env var script (and if possible, links thereto in several
startup scripts), to ensure the environment needed to run CAC-enabled Git
in your shells.
eof
}
# Processes a ~ (alone) or a ~/ at head of input path, replacing with `$HOME/'.
# Rationale: Bash's tilde expansion is inhibited by quoting a path, but quotes may be necessary to protect spaces.
# TODO: Perhaps remove this if I end up not using (on grounds that user shouldn't quote if he wants it expanded).
expand_path() {
if [[ $1 == "~" ]]; then
echo "$HOME"
else
echo "${1/#~\//$HOME/}"
fi
}
# TODO: Refactor (parameterize) to avoid code duplication across these 4 functions.
set_start_step() {
if [[ $Step_mode == only ]]; then
error --usage "Illegal attempt to use --start-step: mutually-exclusive options specified"
fi
if ! check_step "$1"; then
error --usage "Unknown or invalid step specified with --start-step: $1"
fi
Start_step=$1
Step_mode=range
}
set_end_step() {
if [[ $Step_mode == only ]]; then
error --usage "Illegal attempt to use --end-step: mutually-exclusive options specified"
fi
if ! check_step "$1"; then
error --usage "Unknown or invalid step specified with --end-step: $1"
fi
End_step=$1
Step_mode=range
}
add_skip_steps() {
if [[ $Step_mode == only ]]; then
error --usage "Illegal attempt to use --skip-steps: mutually-exclusive options specified"
fi
# Update hash of steps to skip.
for s in ${1//,/ }; do
if ! check_step "$s"; then
error --usage "Unknown or invalid step specified with --skip-steps: $s"
fi
Skip_steps[$s]=yes
done
}
add_only_steps() {
if [[ $Step_mode == range ]]; then
error --usage "Illegal attempt to use --only-steps: mutually-exclusive options specified"
fi
# Update hash of steps to run
for s in ${1//,/ }; do
if ! check_step "$s"; then
error --usage "Unknown or invalid step specified with --only-steps: $s"
fi
Only_steps[$s]=yes
done
Step_mode=only
}
set_card_id() {
if [[ $1 != [0-9][0-9] ]]; then
error --usage "Invalid id format for card-id: $1"
fi
Card_id=$1
}
# TODO: Remove if obsolete...
confirm_cygwin64() {
echo >&2 "Warning! This script has not been tested on 64-bit versions of Cygwin."
echo >&2 "Do you wish to proceed? (y/[n])"
read ans
if [[ $ans != [yY] ]]; then
return 1
fi
}
detect_system() {
local -l system=$(uname -s)
local -l machine=$(uname -m)
local -l version=$(uname -v)
# Default to generic Linux.
System_type=linux
# Check system (kernel)
# Note: -o would be more convenient, but it's an illegal option on some systems (e.g., OS X);
# -s is valid on *all* systems, -m is valid on Cygwin.
case $system in
*cygwin*)
# Check machine type (32/64-bit)
case $machine in
x86_64)
System_type=cygwin64;;
*)
# Default to safest choice.
System_type=cygwin32;;
esac;;
*linux*)
case $version in
*ubuntu*)
# Don't really care about machine type (confirm)
System_type=ubuntu;;
esac;;
esac
}
# Assumption: errexit option has not yet been enabled.
process_opt() {
# TODO: Consider a different way, which would handle defaults.
local -a longs=(
"help" version list-steps
start-step: end-step: skip-steps: only-steps:
card-id: ca-bundle-in: ca-bundle-out: openssl-conf: env-script:
skip-cygwin-x no-install no-execute)
local shorts='s:e:'
# getopt idiosyncrasy: 1st arg specified to a long opt intended to be used to build an array can lose the 1st arg if
# there no short opts are specified (e.g., with -o).
# Getopt workaround: To facilitate proper error reporting, I'm calling getopt up to twice: once to validate, and
# then, only if valid, to get the actual parsed options. Note that if validation fails, the stderr redirection
# ensures that I have the error text for reporting via error(); in the second call, the -q option ensures there can
# be no error text, so the redirection is harmless.
cmd='getopt 2>&1 $quiet -o$shorts -l$(IFS=, ; echo "${longs[*]}") -- "$@"'
for mode in check real; do
if [[ $mode == check ]]; then
quiet=-Q
# Caveat: Doing this way because the local assignment discards any error; eval doesn't.
eval $cmd
else
quiet=-q
local opts=$(eval $cmd)
fi
if (( $? )); then
error --usage "$opts"
fi
done
eval set -- "$opts"
while (($#)); do
local v=$1
shift
case $v in
--help)
show_help
exit 0;;
--version)
echo "$(basename "$0"): A script to automate creation of a CAC-aware Git: Version $VERSION"
exit 0;;
--list-steps)
list_steps
exit 0;;
-s | --start-step)
set_start_step $1
shift;;
-e | --end-step)
set_end_step $1
shift;;
--skip-steps)
add_skip_steps $1
shift;;
--only-steps)
add_only_steps $1
shift;;
--card-id)
set_card_id $1
shift;;
--ca-bundle-in) Opts[ca-bundle-in]=$1; shift;;
--ca-bundle-out) Opts[ca-bundle-out]=$1; shift;;
--openssl-conf) Opts[openssl-conf]=$1; shift;;
--env-script)
# Silently convert - to /dev/null
Opts[env-script]=${Opts[env-script]/-/'/dev/null'}
shift;;
--skip-cygwin-x)
Opts[skip-cygwin-x]=yes;;
--no-install)
Opts[no-install]=yes
Make_install="echo Skipping install...";;
--no-execute)
Opts[no-execute]=yes;;
esac
done
}
# React to values of certain options, now that all have been set and detection is complete.
post_process_opt() {
# Abort early if we can't write the env script and user hasn't disabled this.
if [[ ${Opts[env-script]} != /dev/null && -e ${Opts[env-script]} ]]; then
error "Refusing to overwrite env script file \`${Opts[env-script]}'. Either remove the file before running this" \
"script, or specify a different path with the --env-script option. (Note that you can prevent the script from" \
"being written with --env-script=- or --env-script=/dev/null.)"
fi
}
detect_cac_card() {
if [[ -n $Card_id ]]; then
# No need for detection: user specified with option.
return 0
fi
while [[ -z $Card_id ]]; do
# Note: Extract the desired id using pkcs15-tool (installed in earlier step).
# Using reader with a card: Broadcom Corp Contacted SmartCard 0
# X.509 Certificate [Certificate for PIV Authentication]
# Object Flags : [0x0]
# Authority : no
# Path :
# ID : 01
Card_id=$(pkcs15-tool -c |
sed -n -e '/PIV/,/ID/p' |
sed -n '$s/[[:space:]]*ID[[:space:]]*:[[:space:]]*\([0-9]\+\)[[:space:]]*/\1/p')
# TODO: Allow user to insert and retry.
if [[ -z $Card_id ]]; then
echo >&2 "Warning: Unable to detect CAC card. Insert now if you wish to continue."
echo >&2 "Continue? (y/[n])"
read ans
if [[ $ans != [yY] ]]; then
return 1
#error "Aborting setup"
fi
fi
done
}
# Return success if and only if input step is valid
check_step() {
if ! grep -q "\\<$1\\>" <<<"${Steps[@]}"; then
# Unknown step
return 1
fi
# Assumption: All cygwin options have cygwin in the name.
if [[ $System_type != cygwin* && $1 == *cygwin* ]]; then
# Inapplicable step.
return 2
fi
}
do_prereq() {
# Invoke the system-dependent prerequisite function.
do_prereq_${System_type} "$@"
}
# Return success if and only if we can positively verify successful package installation.
# Note: A false positive is preferred over a false negative.
check_cygwin_package() {
grep -q "$1[[:space:]].*[[:space:]]\\+OK" <<<$(cygcheck -c $1);
}
# Caveat: Running cygwin setup program standalone fails if the install-info
# utility is not in the path. Appears to be a cygwin bug/oversight.
# Note: Using setup -P for an already-installed package appears to re-install harmlessly.
# Important Note: If unattended setup causes problems on user's machine, he can install the packages
# himself through the setup gui, in which case, cygcheck should prevent any actual installs.
do_prereq_cygwin() {
# Make sure latest setup program can be downloaded.
if ! which wget &>/dev/null; then
error "Prerequisite not met: Cannot proceed without a working \`wget'." \
"Suggested remedy: Install \`wget' from the Web category using Cygwin installer," \
"then re-run."
fi
log --ts "Starting installation of Cygwin prerequisites..."
# TODO: Document purpose of all these...
# Caveat: Make sure info pkg is installed first.
# Rationale: I've run into issues attempting to install packages when install-info (in info package) didn't exist.
# Note: libexpat-devel and gettext-devel appear to be hidden dependencies of various configure/make scripts.
local -a pkgs=(
info make binutils gcc-g++ libiconv-devel
git dos2unix patch
libnss3 openssl openssl-devel libopenssl100
chkconfig pkg-config automake autoconf libtool cygwin-devel
libexpat-devel gettext-devel
)
if [[ -z ${Opts[skip-cygwin-x]} ]]; then
pkgs+=(xorg-server xinit)
fi
# Obtain latest copy of appropriate setup program and make executable.
local url=https://cygwin.com/setup-x86$([[ $System_type == cygwin64 ]] && echo "_64").exe
local opt="-q -N -d -W -B"
local setup=./${url##*/}
wget -O $setup $url
chmod a+x $setup
# Install packages one at a time (though -P supports multiple).
# Rationale: Cygwin setup "quiet" mode doesn't handle dependencies well at all.
# Cygwin setup tends to generate spurious (but apparently harmless) errors, so temporarily turn off errexit.
set +e
# Note: Cygwin Base is a prereq, so we could probably dispense with its installation, but just
# to be safe, we'll install Base if system looks strange...
if ! which cygcheck &>/dev/null; then
$setup $opt -C base
fi
for p in "${pkgs[@]}"; do
# Skip already-installed packages.
if ! check_cygwin_package "$p"; then
$setup $opt -P "$p"
fi
done
set -e
log --ts "Finished installation of Cygwin prerequisites..."
}
do_prereq_cygwin32() {
do_prereq_cygwin "$@"
}
do_prereq_cygwin64() {
do_prereq_cygwin "$@"
}
do_prereq_ubuntu() {
# Notes:
# git needed to obtain source
# libssl-dev needed so that OpenSSL can be found
# libpcsclite-dev needed because of OpenSC build dependency on winscard.h
# Note: nss is needed, but it appears to be part of ubuntu by default.
# TODO: Add libiconv-dev
# TODO: Consider adding gcc, make, etc..., but should already be there...
local -a pkgs=(
openssl libssl-dev
git autoconf automake m4 libtool
gettext libexpat1-dev
libpcsclite-dev
)
log --ts "Installing ubuntu prerequisite packages: ${pkgs[@]}..."
# Assumption: Script is running with root privileges (e.g., sudo).
# Note: Suppress tty prompt.
apt-get install -y "${pkgs[@]}"
log --ts "Finished installing ubuntu prerequisite packages..."
}
do_prereq_linux() {
# Generic Linux
# TODO: Inform user of what packages are needed, and present him with options: e.g.,
# 1) I have them. Proceed.
# 2) I don't have them. Abort.
# TODO: Remove stuff below...
# Design Decision: For now, just check the easy stuff: things that can be checked without
# autoconf, etc...
local -a exes=(git make patch)
for exe in "${exes[@]}"; do
if ! which "$exe" &>/dev/null; then
error "Prerequisite not met: Cannot proceed without a working \`$exe'. Use your" \
"package manager to install, then re-run."
fi
done
}
# Make sure there's nothing in the environment (e.g., from a previous run), that could mess us up (e.g., GIT_SSL_<...>
# vars that could cause the vanilla git to attempt to use the CAC card).
clean_env() {
for v in $(env | grep '^[[:space:]]*GIT_SSL_'); do
unset ${v%%=*};
done
# These 2 shouldn't have any impact, but just in case...
unset OPENSSL_CONF
unset GIT_INHIBIT_ASKPASS
}
download_source() {
# TODO: Perhaps separate OpenSC from the others, possibly even having a single build_opensc...
local repos=(
https://github.com/bagder/curl.git
https://github.com/git/git.git
https://github.com/OpenSC/engine_pkcs11
https://github.com/OpenSC/libp11
https://github.com/OpenSC/OpenSC
)
for repo in "${repos[@]}"; do
rm -rf "$(basename $repo .git)"
# Note: Setting core.autocrlf=input obviates need for dos2unix post-processing.
# TODO: How to ensure we always use unmodified versions of things like git. Make this configurable somehow?
$Sys_git clone --config core.autocrlf=input $repo
done
}
build_opensc() {
if [[ $System_type == cygwin* ]]; then
# Caveat: If we don't set PKG_CONFIG_PATH, the libp11 we're about to build won't be found in subsequent build steps.
export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig
fi
local libs=(libp11 engine_pkcs11 OpenSC)
for d in "${libs[@]}"; do
pushd "$d"
# TODO: Make sure error handled as desired (with effective popd).
# simulate error somehow to test...
# TEMP DEBUG - Don't really install...
./bootstrap && ./configure && make && $Make_install
popd
done
# Caveat: Not all linux systems have ldconfig: e.g., OS X apparently does not.
if [[ $System_type != cygwin* ]] && which ldconfig >/dev/null 2>&1; then
# Workaround for issue (at least in Ubuntu) whereby ldconfig cache is not rebuilt properly.
# Explanation: opensc build script invokes `ldconfig -n /usr/local/lib', which doesn't add the libopensc shared
# lib (apparently because of the -n option - not sure why it's used).
# Assumption: Script is running with root privileges (e.g., sudo).
ldconfig /usr/local/lib
fi
}
create_certs() {
# Make sure file has a valid extension.
if [[ ${Opts[ca-bundle-out]} != *.pem && ${Opts[ca-bundle-out]} != *.crt ]]; then
warn "Adding .pem extension to ca-bundle ${Opts[ca-bundle-out]}"
Opts[ca-bundle-out]+=.pem
fi
# Create the dir if necessary.
local dir=${Opts[ca-bundle-out]/%$(basename "${Opts[ca-bundle-out]}")/}
if [[ ! -d "$dir" ]]; then
mkdir -p "$dir"
fi
# Seed the file with a daily build of Mozilla's CA bundles (provided by cURL)
# Note: Could also use the bundle(s) supplied with openssl (e.g., in /usr/ssl/certs), but the location is too
# unpredictable...
# Use cat or wget as appropriate to get the ca bundle.
$([[ ${Opts[ca-bundle-in]} == http* ]] && echo wget -O- || echo cat) ${Opts[ca-bundle-in]} >"${Opts[ca-bundle-out]}"
# Append the DOD root certs (after converting from .p7b to .pem format)
local certs=(rel3_dodroot_2048 dodeca dodeca2)
local url=http://dodpki.c3pki.chamb.disa.mil
for cert in "${certs[@]}"; do
wget -O- $url/$cert.p7b | openssl pkcs7 -inform DER -outform PEM -print_certs
done >>"${Opts[ca-bundle-out]}"
}
# TODO: Decide whether these patches should be part of a package or here-docs.
patch_curl() {
patch -u -p0 <<-'eof'
--- curl/lib/easy.c.orig 2015-02-25 10:25:12.505452200 -0600
+++ curl/lib/easy.c 2015-02-25 10:26:35.904222300 -0600
@@ -947,6 +947,18 @@
data->state.resolver))
goto fail;
+ /* If set, clone the handle to the engine being used. */
+#ifdef HAVE_OPENSSL_ENGINE_H
+ if (data->state.engine) {
+ /* state.engine existing means curl_ossl_set_engine was
+ * previously successful. Because curl_ossl_set_engine worked,
+ * we can query the already-set engine for that handle and use
+ * that to increment a reference:
+ */
+ Curl_ssl_set_engine(outcurl, ENGINE_get_id(data->state.engine));
+ }
+#endif /* HAVE_OPENSSL_ENGINE_H */
+
Curl_convert_setup(outcurl);
outcurl->magic = CURLEASY_MAGIC_NUMBER;
--- curl/lib/vtls/openssl.c.orig 2015-02-25 10:22:35.120450300 -0600
+++ curl/lib/vtls/openssl.c 2015-02-25 10:23:47.825608800 -0600
@@ -761,6 +761,11 @@
/* Lets get nice error messages */
SSL_load_error_strings();
+ /* Load config file */
+ OPENSSL_load_builtin_modules();
+ if (CONF_modules_load_file(getenv("OPENSSL_CONF"), NULL, 0) <= 0)
+ return 0;
+
/* Init the global ciphers and digests */
if(!SSLeay_add_ssl_algorithms())
return 0;
eof
}
build_curl() {
pushd curl
# Note: curl from github doesn't come with a configure script.
./buildconf && ./configure --enable-threaded_resolver --with-ca-bundle="${Opts[ca-bundle-out]}" && make && $Make_install
popd
}
configure_openssl_conf() {
# Note: Account for difference in shared library extensions between Cygwin/Linux.
local ext=$([[ $System_type == cygwin* ]] && echo dll || echo so)
# Important Note: install_env_script will add the env var curl uses to find and load this.
cat <<-eof > "${Opts[openssl-conf]}"
openssl_conf = openssl_def
[openssl_def]
engines = engine_section
[engine_section]
pkcs11 = pkcs11_section
[pkcs11_section]
engine_id = pkcs11
dynamic_path = /usr/local/lib/engines/engine_pkcs11.$ext
MODULE_PATH = /usr/local/lib/opensc-pkcs11.$ext
init = 0
[req]
distinguished_name = req_distinguished_name
[req_distinguished_name]
eof
}
patch_git() {
# Caveat: Leading tabs will be stripped, but need to ensure that patch lines without + or - preserve the leading
# Space (to avoid "malformed patch at line..." errors).
patch -u -p0 <<-'eof'
--- git/http.c.orig 2015-02-26 08:09:14.879850700 -0600
+++ git/http.c 2015-02-26 16:47:18.067707400 -0600
@@ -51,6 +51,9 @@
struct credential http_auth = CREDENTIAL_INIT;
static int http_proactive_auth;
static const char *user_agent;
+static const char *ssl_keytype;
+static const char *ssl_certtype;
+static const char *ssl_engine;
#if LIBCURL_VERSION_NUM >= 0x071700
/* Use CURLOPT_KEYPASSWD as is */
@@ -252,6 +255,12 @@
if (!strcmp("http.useragent", var))
return git_config_string(&user_agent, var, value);
+ if (!strcmp("http.sslkeytype", var))
+ return git_config_string(&ssl_keytype, var, value);
+ if (!strcmp("http.sslcerttype", var))
+ return git_config_string(&ssl_certtype, var, value);
+ if (!strcmp("http.sslengine", var))
+ return git_config_string(&ssl_engine, var, value);
/* Fall back on the default ones */
return git_default_config(var, value, cb);
@@ -408,6 +417,17 @@
curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
}
+ /* Adding setting of engine-related curl SSL options. */
+ if (ssl_engine != NULL) {
+ curl_easy_setopt(result, CURLOPT_SSLENGINE, ssl_engine);
+ curl_easy_setopt(result, CURLOPT_SSLENGINE_DEFAULT, 1L);
+ }
+
+ if (ssl_keytype != NULL)
+ curl_easy_setopt(result, CURLOPT_SSLKEYTYPE, ssl_keytype);
+ if (ssl_certtype != NULL)
+ curl_easy_setopt(result, CURLOPT_SSLCERTTYPE, ssl_certtype);
+
set_curl_keepalive(result);
return result;
@@ -502,7 +522,10 @@
starts_with(url, "https://"))
ssl_cert_password_required = 1;
}
-
+ /* Added environment variables for expanded engine-related options. */
+ set_from_env(&ssl_keytype, "GIT_SSL_KEYTYPE");
+ set_from_env(&ssl_certtype, "GIT_SSL_CERTTYPE");
+ set_from_env(&ssl_engine, "GIT_SSL_ENGINE");
#ifndef NO_CURL_EASY_DUPHANDLE
curl_default = get_curl_handle();
#endif
--- git/prompt.c.orig 2015-02-26 16:39:49.891073200 -0600
+++ git/prompt.c 2015-02-26 16:39:55.933418800 -0600
@@ -45,7 +45,7 @@
{
char *r = NULL;
- if (flags & PROMPT_ASKPASS) {
+ if (!git_env_bool("GIT_INHIBIT_ASKPASS", 0) && flags & PROMPT_ASKPASS) {
const char *askpass;
askpass = getenv("GIT_ASKPASS");
eof
}
build_git() {
# Note: Git has no configure script.
NO_R_TO_GCC_LINKER=1 CURLDIR=/usr/local make -C git prefix=/usr/local all ${Opts[no-install]:-install}
}
# Does input file contain a command that would dot-source the env script?
file_contains_env_link() {
# Note: Permit (but don't require) quotes around the name.
# Possible TODO: When head of env-script is expanded `~', perhaps ensure that it's written to file unexpanded. For
# now, assuming always expanded.
grep -q '^[[:space:]]*\(\.\|source\)[[:space:]]\+'"[\"']\\?${Opts[env-script]}[\"']\\?"'\>' < "$1"
}
# Append to the input file a command to dot-source the env script.
add_env_link_to_file() {
echo ". '${Opts[env-script]}'" >> "$1"
}
# Taking into account Bash startup logic... Add links (. <env-script>) to startup scripts to ensure that the env vars
# are created in both login and non-login interactive shells.
# Logic: If none of the shell startup files in a group exist, create the highest priority one.
# Rationale: If we picked one other than 1st, things would stop working when user subsequently created a file
# with higher precedence.
# Possible TODO: Adding the link to all 3 scripts might be a bit more robust, and wouldn't really be harmful,
# given that only one of the 3 is ever sourced (unless user sources one from the other). Hmm...
# Assumption: User will be using bash (not sh).
add_env_script_links() {
local problem=
# prioritized lists of files in the 2 groups (login, non-login interactive)
local -a login=(~/.bash_profile ~/.bash_login ~/.profile)
local -a inter=(~/.bashrc)
local ary
for ary in login inter; do
# A bit of kludgery to emulate multi-dim arrays.
local idx="$ary[@]"
local added=
local -i pass
for pass in 1 2; do
local f
for f in "${!idx}"; do
# Stop after 1st one found...
if ((pass == 1)); then
# pass 1 - consider only existing files
if [[ -r $f ]]; then
if file_contains_env_link "$f"; then
added=yes
elif [[ -w $f ]]; then
add_env_link_to_file "$f"
added=yes
fi
fi
else
# pass 2 - create highest priority file we can
if [[ ! -e $f || -w $f ]]; then
add_env_link_to_file "$f"
added=yes
fi
fi
if [[ -n $added ]]; then break 2; fi
done
done
if [[ -z $added ]]; then
warn "Unable to add env script link for $([[ $ary == login ]] && echo "login" || echo "interactive") shells."
problem=yes
fi
done
if [[ -n $problem ]]; then
cat >&2 <<-eof
Warning: Env settings have been added to...
${Opts[env-script]}
...but I could not add a command to source it to one or more startup file(s).
Either add the commands manually: e.g.,
. ${Opts[env-script]}
...or re-run this script with option --start-step=install_env_script after
ensuring that at least 1 startup script in each of the following groups is
modifiable:
1) ${login[@]}
2) ${inter[@]}
eof
fi
}
write_env_script() {
if [[ ${Opts[env-script]} == /dev/null ]]; then
return 0
fi
# TODO: Consider putting the cac id detection there also (in case slot id moves)...
cat <<eof >"${Opts[env-script]}"
#! /bin/bash
enable_cac_aware_git() {
# Add environment vars needed for CAC-enabled Git
export GIT_SSL_CERT=slot_01-id_$Card_id
export GIT_SSL_KEY=slot_01-id_$Card_id
export GIT_SSL_CAINFO="${Opts[ca-bundle-out]}"
export GIT_SSL_ENGINE=pkcs11
export GIT_SSL_KEYTYPE=ENG
export GIT_SSL_CERTTYPE=ENG
# Make sure curl can load the pkcs11 openssl engine.
export OPENSSL_CONF="${Opts[openssl-conf]}"
# Keep Git from using the Tk-based askpass gui (which has an X11 dependency that may not be satisfied) before
# defaulting to the console-based prompt.
# Note: The inhibit could also be accomplished by setting GIT_ASKPASS to empty string, but that would impact
# non-CAC Git(s) as well, and there may be reasons we want it inhibited only for the CAC-aware Git (e.g, you're
# going to have to enter PKCS#11 pin at tty anyways).
export GIT_INHIBIT_ASKPASS=yes
}
disable_cac_aware_git() {
for v in \$(env|grep GIT_SSL_); do
unset \${v%%=*};
done
unset OPENSSL_CONF
unset GIT_INHIBIT_ASKPASS
}
# Note: User can disable automatic CAC setup at shell startup simply by defining a non-empty INHIBIT_CAC_ENABLED_GIT env
# var. To disable/re-enable in a running shell, he can use the following functions:
# enable_cac_aware_git
# disable_cac_aware_git
[ -z \$INHIBIT_CAC_ENABLED_GIT ] && enable_cac_aware_git
# As a convenience, provide an alias to "non-CAC-aware" git.
alias ncgit=/usr/bin/git
eof
}
install_env_script() {
# Don't try to install if user explicitly disabled.
if [[ ${Opts[env-script]} != /dev/null ]]; then
write_env_script
add_env_script_links
fi
}
detect_system
process_opt "$@"
post_process_opt
clean_env
do_prereq
# Default mode from here on is to fail on error with indication of last step completed.
# Note: Step functions with a need (e.g., install_cygwin) may *temporarily* unset.
# Caveat: Take care not to generate spurious errors: e.g., do ((++var)) instead of ((var++) when var could be 0.
set -e
trap on_exit EXIT
run
# vim: ts=4:sw=4:tw=120