From 78d5eafc9a379e9b4dbd9c74e910c634aeb8fa7b Mon Sep 17 00:00:00 2001 From: shimunn Date: Fri, 20 Sep 2019 15:54:47 +0200 Subject: [PATCH] structopt --- Cargo.lock | 136 ++++++++++----- Cargo.toml | 7 +- README.md | 7 +- dracut/96luks-2fa/luks-2fa-generator.sh | 2 +- dracut/96luks-2fa/module-setup.sh | 1 - src/cli.rs | 222 ++++++++++++++++-------- src/config.rs | 125 +++++-------- src/error.rs | 27 +-- src/main.rs | 184 +------------------- 9 files changed, 301 insertions(+), 410 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c2126fb..5244b86 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,5 +1,22 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. +[[package]] +name = "ansi_term" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "atty" +version = "0.2.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "autocfg" version = "0.1.6" @@ -63,6 +80,20 @@ name = "cfg-if" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "clap" +version = "2.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", + "atty 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)", + "bitflags 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "strsim 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", + "textwrap 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-width 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "cloudabi" version = "0.0.3" @@ -101,14 +132,6 @@ dependencies = [ "untrusted 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "envy" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "serde 1.0.100 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "errno" version = "0.2.4" @@ -154,15 +177,12 @@ version = "0.1.0" dependencies = [ "cryptsetup-rs 0.2.0 (git+https://github.com/shimunn/cryptsetup-rs.git?branch=destroy)", "ctap 0.1.0 (git+https://github.com/shimunn/ctap.git?branch=hmac_ext)", - "envy 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", "hex 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", "libcryptsetup-sys 0.1.1 (git+https://github.com/shimunn/cryptsetup-rs.git?branch=destroy)", "rpassword 4.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.100 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_derive 1.0.100 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.40 (registry+https://github.com/rust-lang/crates.io-index)", + "structopt 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -176,13 +196,16 @@ version = "0.3.55" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] -name = "hex" -version = "0.3.2" +name = "heck" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-segmentation 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", +] [[package]] -name = "itoa" -version = "0.4.4" +name = "hex" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -235,6 +258,16 @@ name = "pkg-config" version = "0.3.16" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "proc-macro-error" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "proc-macro2" version = "0.4.30" @@ -440,33 +473,29 @@ version = "0.3.24" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] -name = "ryu" -version = "1.0.0" +name = "strsim" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] -name = "serde" -version = "1.0.100" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "serde_derive" -version = "1.0.100" +name = "structopt" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "proc-macro2 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", + "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", + "structopt-derive 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] -name = "serde_json" -version = "1.0.40" +name = "structopt-derive" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "itoa 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)", - "ryu 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.100 (registry+https://github.com/rust-lang/crates.io-index)", + "heck 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro-error 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -500,6 +529,14 @@ dependencies = [ "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "textwrap" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-width 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "time" version = "0.1.42" @@ -510,6 +547,16 @@ dependencies = [ "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "unicode-segmentation" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "unicode-width" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "unicode-xid" version = "0.1.0" @@ -534,6 +581,11 @@ dependencies = [ "rand 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "vec_map" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "winapi" version = "0.3.8" @@ -554,6 +606,8 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" [metadata] +"checksum ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" +"checksum atty 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)" = "1803c647a3ec87095e7ae7acfca019e98de5ec9a7d01343f611cf3152ed71a90" "checksum autocfg 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "b671c8fb71b457dd4ae18c4ba1e59aa81793daacc361d82fcd410cef0d491875" "checksum backtrace 0.3.37 (registry+https://github.com/rust-lang/crates.io-index)" = "5180c5a20655b14a819b652fd2378fa5f1697b6c9ddad3e695c2f9cedf6df4e2" "checksum backtrace-sys 0.1.31 (registry+https://github.com/rust-lang/crates.io-index)" = "82a830b4ef2d1124a711c71d263c5abdc710ef8e907bd508c88be475cebc422b" @@ -563,18 +617,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" "checksum cbor-codec 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "e083a023562b37c52837e850131a51b1154cceb9d149f41ee3d386737b140f46" "checksum cc 1.0.45 (registry+https://github.com/rust-lang/crates.io-index)" = "4fc9a35e1f4290eb9e5fc54ba6cf40671ed2a2514c3eeb2b2a908dda2ea5a1be" "checksum cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "b486ce3ccf7ffd79fdeb678eac06a9e6c09fc88d33836340becb8fffe87c5e33" +"checksum clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5067f5bb2d80ef5d68b4c87db81601f0b75bca627bc2ef76b141d7b846a3c6d9" "checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" "checksum cryptsetup-rs 0.2.0 (git+https://github.com/shimunn/cryptsetup-rs.git?branch=destroy)" = "" "checksum ctap 0.1.0 (git+https://github.com/shimunn/ctap.git?branch=hmac_ext)" = "" -"checksum envy 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "261b836bcf13f42a01c70351f56bd7b66db6e6fb58352bd214cb77e9269a34b4" "checksum errno 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "c2a071601ed01b988f896ab14b95e67335d1eeb50190932a1320f7fe3cadc84e" "checksum errno-dragonfly 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "14ca354e36190500e1e1fb267c647932382b54053c50b14970856c0b00a35067" "checksum failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "795bd83d3abeb9220f257e597aa0080a508b27533824adf336529648f6abf7e2" "checksum failure_derive 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "ea1063915fd7ef4309e222a5a07cf9c319fb9c7836b1f89b85458672dbb127e1" "checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" "checksum gcc 0.3.55 (registry+https://github.com/rust-lang/crates.io-index)" = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2" +"checksum heck 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "20564e78d53d2bb135c343b3f47714a56af2061f1c928fdb541dc7b9fdd94205" "checksum hex 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "805026a5d0141ffc30abb3be3173848ad46a1b1664fe632428479619a3644d77" -"checksum itoa 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "501266b7edd0174f8530248f87f99c88fbe60ca4ef3dd486835b8d8d53136f7f" "checksum lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" "checksum libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)" = "34fcd2c08d2f832f376f4173a231990fa5aef4e99fb569867318a227ef4c06ba" "checksum libcryptsetup-sys 0.1.1 (git+https://github.com/shimunn/cryptsetup-rs.git?branch=destroy)" = "" @@ -582,6 +636,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" "checksum num-derive 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "eafd0b45c5537c3ba526f79d3e75120036502bebacbb3f3220914067ce39dbf2" "checksum num-traits 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "6ba9a427cfca2be13aa6f6403b0b7e7368fe982bfa16fccc450ce74c46cd9b32" "checksum pkg-config 0.3.16 (registry+https://github.com/rust-lang/crates.io-index)" = "72d5370d90f49f70bd033c3d75e87fc529fbfff9d6f7cccef07d6170079d91ea" +"checksum proc-macro-error 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "aeccfe4d5d8ea175d5f0e4a2ad0637e0f4121d63bd99d356fb1f39ab2e7c6097" "checksum proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)" = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" "checksum proc-macro2 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "e98a83a9f9b331f54b924e68a66acb1bb35cb01fb0a23645139967abefb697e8" "checksum quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)" = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1" @@ -605,18 +660,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" "checksum rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)" = "f76d05d3993fd5f4af9434e8e436db163a12a9d40e1a58a726f27a01dfd12a2a" "checksum rustc-demangle 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)" = "4c691c0e608126e00913e33f0ccf3727d5fc84573623b8d65b2df340b5201783" "checksum rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)" = "dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda" -"checksum ryu 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c92464b447c0ee8c4fb3824ecc8383b81717b9f1e74ba2e72540aef7b9f82997" -"checksum serde 1.0.100 (registry+https://github.com/rust-lang/crates.io-index)" = "f4473e8506b213730ff2061073b48fa51dcc66349219e2e7c5608f0296a1d95a" -"checksum serde_derive 1.0.100 (registry+https://github.com/rust-lang/crates.io-index)" = "11e410fde43e157d789fc290d26bc940778ad0fdd47836426fbac36573710dbb" -"checksum serde_json 1.0.40 (registry+https://github.com/rust-lang/crates.io-index)" = "051c49229f282f7c6f3813f8286cc1e3323e8051823fce42c7ea80fe13521704" +"checksum strsim 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" +"checksum structopt 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "3fe8d3289b63ef2f196d89e7701f986583c0895e764b78f052a55b9b5d34d84a" +"checksum structopt-derive 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f3add731f5b4fb85931d362a3c92deb1ad7113649a8d51701fb257673705f122" "checksum syn 0.15.44 (registry+https://github.com/rust-lang/crates.io-index)" = "9ca4b3b69a77cbe1ffc9e198781b7acb0c7365a883670e8f1c1bc66fba79a5c5" "checksum syn 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "66850e97125af79138385e9b88339cbcd037e3f28ceab8c5ad98e64f0f1f80bf" "checksum synstructure 0.10.2 (registry+https://github.com/rust-lang/crates.io-index)" = "02353edf96d6e4dc81aea2d8490a7e9db177bf8acb0e951c24940bf866cb313f" +"checksum textwrap 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" "checksum time 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)" = "db8dcfca086c1143c9270ac42a2bbd8a7ee477b78ac8e45b19abfb0cbede4b6f" +"checksum unicode-segmentation 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1967f4cdfc355b37fd76d2a954fb2ed3871034eb4f26d60537d88795cfc332a9" +"checksum unicode-width 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "7007dbd421b92cc6e28410fe7362e2e0a2503394908f417b68ec8d1c364c4e20" "checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" "checksum unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" "checksum untrusted 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "55cd1f4b4e96b46aeb8d4855db4a7a9bd96eeeb5c6a1ab54593328761642ce2f" "checksum uuid 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)" = "e1436e58182935dcd9ce0add9ea0b558e8a87befe01c1a301e6020aeb0876363" +"checksum vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "05c78687fb1a80548ae3250346c3db86a80a7cdd77bda190189f2d0a0987c81a" "checksum winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" "checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" "checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/Cargo.toml b/Cargo.toml index eee27c1..50719e3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,13 +13,12 @@ libcryptsetup-sys = { git = "https://github.com/shimunn/cryptsetup-rs.git", bran hex = "0.3.2" rust-crypto = "0.2.36" failure = "0.1.5" -serde_derive = "1.0.100" -serde = "1.0.100" -serde_json = "1.0.40" rpassword = "4.0.1" -envy = "0.4.0" +structopt = "0.3.2" [profile.release] lto = true opt-level = 'z' panic = 'abort' +incremental = false +overflow-checks = false diff --git a/README.md b/README.md index 9890ed4..447c424 100644 --- a/README.md +++ b/README.md @@ -26,10 +26,10 @@ set -a . fido2luks.conf #Repeat for each luks volume -FIDO2LUKS_PASSWORD_HELPER=stdin sudo -E fido2luks addkey /dev/disk/by-uuid/ +sudo -E fido2luks -i addkey /dev/disk/by-uuid/ #Test(only works if the luks container isn't active) -FIDO2LUKS_PASSWORD_HELPER=stdin sudo -E fido2luks open /dev/disk/by-uuid/ luks- +sudo -E fido2luks -i open /dev/disk/by-uuid/ luks- ``` @@ -58,7 +58,6 @@ Just reboot and see if it works, if thats the case you should remove your old le ``` #Recommend in case you lose your authenticator, store this backupfile somewhere safe cryptsetup luksHeaderBackup /dev/disk/by-uuid/ --header-backup-file luks_backup_ -#Slot should be 0 if you only had one previous password otherwise consult cryptsetup luksDump #There is no turning back if you mess this up, make sure you made a backup -FIDO2LUKS_PASSWORD_HELPER=stdin fido2luks print-secret | xxd -r -p - | cryptsetup luksKillSlot /dev/disk/by-uuid/ +fido2luks -i add-key --exclusive /dev/disk/by-uuid/ ``` diff --git a/dracut/96luks-2fa/luks-2fa-generator.sh b/dracut/96luks-2fa/luks-2fa-generator.sh index 442362d..7ea465c 100755 --- a/dracut/96luks-2fa/luks-2fa-generator.sh +++ b/dracut/96luks-2fa/luks-2fa-generator.sh @@ -38,7 +38,7 @@ generate_service () { printf -- "\nKeyringMode=%s" "shared" #printf -- "\nExecStart=${CRYPTSETUP} attach 'luks-%s' '/dev/disk/by-uuid/%s' 'none'" "$keyfile_uuid" "$keyfile_uuid" #LUKS on USB #printf -- "\nExecStart=${MOUNT} '/dev/mapper/luks-%s' %s" "$keyfile_uuid" "$keyfile_mountpoint" #Mount keyfile - printf -- "\nExecStart=/bin/bash -c \"${FIDO2LUKS} print-secret | ${XXD} -r -p - | ${CRYPTSETUP} attach 'luks-%s' '/dev/disk/by-uuid/%s' '/dev/stdin'\"" "$target_uuid" "$target_uuid" + printf -- "\nExecStart=/bin/bash -c \"${FIDO2LUKS} print-secret --bin | ${CRYPTSETUP} attach 'luks-%s' '/dev/disk/by-uuid/%s' '/dev/stdin'\"" "$target_uuid" "$target_uuid" #printf -- "\nExecStart=${UMOUNT} '%s'" "$keyfile_mountpoint" #printf -- "\nExecStart=${CRYPTSETUP} detach 'luks-%s'" "$keyfile_uuid" printf -- "\nExecStop=${CRYPTSETUP} detach 'luks-%s'" "$target_uuid" diff --git a/dracut/96luks-2fa/module-setup.sh b/dracut/96luks-2fa/module-setup.sh index 7423cb5..e957be6 100755 --- a/dracut/96luks-2fa/module-setup.sh +++ b/dracut/96luks-2fa/module-setup.sh @@ -17,7 +17,6 @@ depends () { install () { inst "$moddir/luks-2fa-generator.sh" "/etc/systemd/system-generators/luks-2fa-generator.sh" - inst_simple "/usr/bin/xxd" "/usr/bin/xxd" inst_simple "/usr/bin/fido2luks" "/usr/bin/fido2luks" inst "$systemdutildir/systemd-cryptsetup" mkdir -p "$initdir/luks-2fa" diff --git a/src/cli.rs b/src/cli.rs index 123e529..d6c22ab 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -3,81 +3,14 @@ use crate::*; use cryptsetup_rs as luks; use cryptsetup_rs::api::{CryptDeviceHandle, CryptDeviceOpenBuilder, Luks1Params}; -use cryptsetup_rs::{Luks1CryptDevice, CryptDevice}; +use cryptsetup_rs::{CryptDevice, Luks1CryptDevice}; + use libcryptsetup_sys::crypt_keyslot_info; -use ctap; -use ctap::extensions::hmac::{FidoHmacCredential, HmacExtension}; -use ctap::FidoDevice; +use structopt::StructOpt; use std::fs::File; use std::io::{Read, Write}; -use std::path::Path; -use std::thread; -use std::time::Duration; - -pub fn setup() -> Fido2LuksResult<()> { - while !authenticator_connected()? { - eprintln!("Please connect your authenticator"); - for _ in 0..3 { - thread::sleep(Duration::from_secs(1)); - if authenticator_connected()? { - break; - } - } - } - - let mut config = Config::default(); - - let save_config = |c: &Config| { - File::create("fido2luks.json") - .expect("Failed to save config") - .write_all(serde_json::to_string_pretty(c).unwrap().as_bytes()) - .expect("Failed to save config"); - }; - - fn ask_bool(q: &str) -> bool { - ask_str(&format!("{} (y/n)", q)).expect("Failed to read from stdin") == "y" - } - - println!("1. Generating a credential"); - let mut ccred: Option = None; - for di in ctap::get_devices().expect("Failed to query USB for 2fa devices") { - let mut dev = FidoDevice::new(&di).expect("Failed to open 2fa device"); - match dev.make_hmac_credential() { - Ok(cred) => { - ccred = Some(cred); - break; - } - Err(_e) => println!("Failed to to obtain credential trying next device(if applicable)"), - } - } - config.credential_id = hex::encode(ccred.expect("No credential could be obtained").id); - save_config(&config); - - loop { - let device = ask_str("Path to your luks device: ").expect("Failed to read from stdin");; - if Path::new(&device).exists() - || ask_bool(&format!("{} does not exist, save anyway?", device)) - { - config.device = device.into(); - break; - } - } - - save_config(&config); - - config.mapper_name = ask_str("Name for decrypted disk: ").expect("Failed to read from stdin");; - - save_config(&config); - - println!("Config saved to: fido2luks.json"); - - //let slot = add_key_to_luks(&config).expect("Failed to add key to device"); - - //println!("Added key to slot: {}", slot); - - Ok(()) -} +use std::process::exit; pub fn add_key_to_luks(device: PathBuf, secret: &[u8; 32], exclusive: bool) -> Fido2LuksResult { fn offer_format( @@ -116,8 +49,12 @@ pub fn add_key_to_luks(device: PathBuf, secret: &[u8; 32], exclusive: bool) -> F handle.set_iteration_time(50); let slot = handle.add_keyslot(secret, prev_key.as_ref().map(|b| b.as_slice()), None)?; if exclusive { - for old_slot in 0..8u8 { - if old_slot != slot && (handle.keyslot_status(old_slot.into()) == crypt_keyslot_info::CRYPT_SLOT_ACTIVE || handle.keyslot_status(old_slot.into()) == crypt_keyslot_info::CRYPT_SLOT_ACTIVE_LAST) { + for old_slot in 0..8u8 { + if old_slot != slot + && (handle.keyslot_status(old_slot.into()) == crypt_keyslot_info::CRYPT_SLOT_ACTIVE + || handle.keyslot_status(old_slot.into()) + == crypt_keyslot_info::CRYPT_SLOT_ACTIVE_LAST) + { handle.destroy_keyslot(old_slot)?; } } @@ -128,3 +65,142 @@ pub fn add_key_to_luks(device: PathBuf, secret: &[u8; 32], exclusive: bool) -> F pub fn authenticator_connected() -> Fido2LuksResult { Ok(!device::get_devices()?.is_empty()) } + +#[derive(Debug, StructOpt)] +pub struct Args { + /// Request passwords via Stdin instead of using the password helper + #[structopt(short = "i", long = "interactive")] + pub interactive: bool, + #[structopt(subcommand)] + pub command: Command, +} + +#[derive(Debug, StructOpt, Clone)] +pub struct SecretGeneration { + /// FIDO credential id, generate using fido2luks credential + #[structopt(name = "credential-id", env = "FIDO2LUKS_CREDENTIAL_ID")] + pub credential_id: String, + /// Salt for secret generation, defaults to Password + #[structopt(name = "salt", env = "FIDO2LUKS_SALT", default_value = "Ask")] + pub salt: InputSalt, + /// Script used to obtain passwords, overridden by --interactive flag + #[structopt( + name = "password-helper", + env = "FIDO2LUKS_PASSWORD_HELPER", + default_value = "/usr/bin/systemd-ask-password 'Please enter second factor for LUKS disk encryption!'" + )] + pub password_helper: PasswordHelper, +} + +impl SecretGeneration { + pub fn patch(&self, args: &Args) -> Self { + let mut me = self.clone(); + if args.interactive { + me.password_helper = PasswordHelper::Stdin; + } + me + } + + pub fn obtain_secret(&self) -> Fido2LuksResult<[u8; 32]> { + let salt = self.salt.obtain(&self.password_helper)?; + Ok(assemble_secret( + &perform_challenge(&self.credential_id, &salt)?, + &salt, + )) + } +} + +#[derive(Debug, StructOpt)] +pub enum Command { + #[structopt(name = "print-secret")] + PrintSecret { + /// Prints the secret as binary instead of hex encoded + #[structopt(short = "b", long = "bin")] + binary: bool, + #[structopt(flatten)] + secret_gen: SecretGeneration, + }, + /// Adds a generated key to the specified LUKS device + #[structopt(name = "add-key")] + AddKey { + #[structopt(env = "FIDO2LUKS_DEVICE")] + device: PathBuf, + /// Will wipe all other keys + #[structopt(short = "e", long = "exclusive")] + exclusive: bool, + #[structopt(flatten)] + secret_gen: SecretGeneration, + }, + /// Open the LUKS device + #[structopt(name = "open")] + Open { + #[structopt(env = "FIDO2LUKS_DEVICE")] + device: PathBuf, + #[structopt(env = "FIDO2LUKS_MAPPER_NAME")] + name: String, + #[structopt(flatten)] + secret_gen: SecretGeneration, + }, + /// Generate a new FIDO credential + #[structopt(name = "credential")] + Credential, + /// Check if an authenticator is connected + #[structopt(name = "connected")] + Connected, +} + +pub fn parse_cmdline() -> Args { + Args::from_args() +} + +pub fn run_cli() -> Fido2LuksResult<()> { + let args = parse_cmdline(); + match &args.command { + Command::Credential => { + let cred = make_credential_id()?; + println!("{}", hex::encode(&cred.id)); + Ok(()) + } + Command::PrintSecret { + binary, + ref secret_gen, + } => { + let secret = secret_gen.patch(&args).obtain_secret()?; + if *binary { + io::stdout().write(&secret[..])?; + } else { + io::stdout().write(hex::encode(&secret[..]).as_bytes())?; + } + Ok(io::stdout().flush()?) + } + Command::AddKey { + device, + exclusive, + ref secret_gen, + } => { + let secret = secret_gen.patch(&args).obtain_secret()?; + let slot = add_key_to_luks(device.clone(), &secret, *exclusive)?; + println!( + "Added to key to device {}, slot: {}", + device.display(), + slot + ); + Ok(()) + } + Command::Open { + device, + name, + ref secret_gen, + } => { + let secret = secret_gen.patch(&args).obtain_secret()?; + open_container(&device, &name, &secret) + } + Command::Connected => match get_devices() { + Ok(ref devs) if !devs.is_empty() => { + println!("Found {} devices", devs.len()); + Ok(()) + } + _ => exit(1), + }, + } +} diff --git a/src/config.rs b/src/config.rs index 58dc394..9d3708c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -3,88 +3,14 @@ use crate::*; use crypto::digest::Digest; use crypto::sha2::Sha256; -use serde_derive::{Deserialize, Serialize}; -use std::collections::HashMap; -use std::convert::TryInto; -use std::env; +use std::fmt; use std::fs::File; use std::io::Read; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::process::Command; +use std::str::FromStr; -#[derive(Debug, Deserialize, Serialize)] -pub struct EnvConfig { - pub credential_id: String, - pub device: Option, - pub salt: String, - pub mapper_name: Option, - pub password_helper: String, -} - -impl TryInto for EnvConfig { - type Error = Fido2LuksError; - - fn try_into(self) -> Fido2LuksResult { - Ok(Config { - credential_id: self.credential_id, - device: self - .device - .ok_or(Fido2LuksError::ConfigurationError { - cause: ConfigurationError::MissingField("DEVICE".into()), - })? - .into(), - mapper_name: self.mapper_name.ok_or(Fido2LuksError::ConfigurationError { - cause: ConfigurationError::MissingField("DEVICE_MAPPER".into()), - })?, - password_helper: PasswordHelper::Script(self.password_helper), - input_salt: self.salt.as_str().into(), - }) - } -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct Config { - pub credential_id: String, - pub input_salt: InputSalt, - pub device: PathBuf, - pub mapper_name: String, - pub password_helper: PasswordHelper, -} - -impl Config { - pub fn load_default_location() -> Fido2LuksResult { - Self::load_config( - &mut File::open( - env::vars() - .collect::>() - .get("FIDO2LUKS_CONFIG") - .unwrap_or(&"/etc/fido2luks.json".to_owned()), - ) - .or(File::open("fido2luks.json"))?, - ) - } - - pub fn load_config(reader: &mut dyn Read) -> Fido2LuksResult { - let mut conf_str = String::new(); - reader.read_to_string(&mut conf_str)?; - - Ok(serde_json::from_str(&conf_str)?) - } -} - -impl Default for Config { - fn default() -> Self { - Config { - credential_id: "".into(), - input_salt: Default::default(), - device: "/dev/some-vg/".into(), - mapper_name: "2fa-secured-luks".into(), - password_helper: PasswordHelper::default(), - } - } -} - -#[derive(Debug, Deserialize, Serialize)] +#[derive(Debug, Clone)] pub enum InputSalt { AskPassword, File { path: PathBuf }, @@ -107,6 +33,24 @@ impl From<&str> for InputSalt { } } +impl FromStr for InputSalt { + type Err = Fido2LuksError; + + fn from_str(s: &str) -> Result { + Ok(Self::from(s)) + } +} + +impl fmt::Display for InputSalt { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + f.write_str(&match self { + InputSalt::AskPassword => "ask".to_string(), + InputSalt::File { path } => path.display().to_string(), + InputSalt::Both { path } => ["ask", path.display().to_string().as_str()].join(" + "), + }) + } +} + impl InputSalt { pub fn obtain(&self, password_helper: &PasswordHelper) -> Fido2LuksResult<[u8; 32]> { let mut digest = Sha256::new(); @@ -140,7 +84,7 @@ impl InputSalt { } } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Debug, Clone)] pub enum PasswordHelper { Script(String), Systemd, @@ -149,7 +93,10 @@ pub enum PasswordHelper { impl Default for PasswordHelper { fn default() -> Self { - PasswordHelper::Script("/usr/bin/systemd-ask-password --no-tty 'Please enter second factor for LUKS disk encryption!'".into()) + PasswordHelper::Script( + "/usr/bin/systemd-ask-password 'Please enter second factor for LUKS disk encryption!'" + .into(), + ) } } @@ -162,6 +109,24 @@ impl From<&str> for PasswordHelper { } } +impl FromStr for PasswordHelper { + type Err = Fido2LuksError; + + fn from_str(s: &str) -> Result { + Ok(Self::from(s)) + } +} + +impl fmt::Display for PasswordHelper { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + f.write_str(&match self { + PasswordHelper::Stdin => "stdin".to_string(), + PasswordHelper::Systemd => "systemd".to_string(), + PasswordHelper::Script(path) => path.clone(), + }) + } +} + impl PasswordHelper { pub fn obtain(&self) -> Fido2LuksResult { use PasswordHelper::*; diff --git a/src/error.rs b/src/error.rs index 97bfb0a..d7cc0e7 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,5 +1,5 @@ use ctap::FidoError; -use std::{fmt, io}; +use std::io; pub type Fido2LuksResult = Result; @@ -18,20 +18,11 @@ pub enum Fido2LuksError { #[fail(display = "no authenticator found, please ensure you device is plugged in")] IoError { cause: io::Error }, #[fail(display = "failed to parse config, please check formatting and contents")] - ConfigurationError { cause: ConfigurationError }, - #[fail(display = "the submitted secret is not applicable to this luks device")] WrongSecret, #[fail(display = "not an utf8 string")] StringEncodingError { cause: FromUtf8Error }, } -#[derive(Debug)] -pub enum ConfigurationError { - Json(serde_json::error::Error), - Env(envy::Error), - MissingField(String), -} - #[derive(Debug, Fail)] pub enum AskPassError { #[fail(display = "unable to retrieve password: {}", _0)] @@ -40,22 +31,6 @@ pub enum AskPassError { Mismatch, } -impl From for Fido2LuksError { - fn from(e: serde_json::error::Error) -> Self { - Fido2LuksError::ConfigurationError { - cause: ConfigurationError::Json(e), - } - } -} - -impl From for Fido2LuksError { - fn from(e: envy::Error) -> Self { - Fido2LuksError::ConfigurationError { - cause: ConfigurationError::Env(e), - } - } -} - use std::string::FromUtf8Error; use Fido2LuksError::*; diff --git a/src/main.rs b/src/main.rs index 3efcf48..96419c7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,5 @@ #[macro_use] extern crate failure; -extern crate serde_derive; use crate::cli::*; use crate::config::*; use crate::device::*; @@ -12,15 +11,8 @@ use cryptsetup_rs as luks; use cryptsetup_rs::Luks1CryptDevice; use ctap; -use luks::device::Error::CryptsetupError; - -use std::collections::HashMap; -use std::env; - -use std::convert::TryInto; -use std::io::{self, stdout, Write}; +use std::io::{self}; use std::path::PathBuf; -use std::process::exit; mod cli; mod config; @@ -41,179 +33,7 @@ fn assemble_secret(hmac_result: &[u8], salt: &[u8]) -> [u8; 32] { digest.result(&mut secret); secret } -fn ask_str(q: &str) -> Fido2LuksResult { - let stdin = io::stdin(); - let mut s = String::new(); - print!("{}", q); - io::stdout().flush()?; - stdin.read_line(&mut s)?; - Ok(s.trim().to_owned()) -} - -fn open(conf: &Config, secret: &[u8; 32]) -> Fido2LuksResult<()> { - dbg!(hex::encode(&secret)); - match open_container(&conf.device, &conf.mapper_name, &secret) { - Err(Fido2LuksError::LuksError { - cause: CryptsetupError(errno), - }) if errno.0 == 1 => Err(Fido2LuksError::WrongSecret)?, - e => e?, - }; - Ok(()) -} - -/*fn package_self() -> Fido2LuksResult<()> { - let conf = Config::load_default_location()?; - let binary_path: PathBuf = env::args().next().unwrap().into(); - let mut me = File::open(binary_path)?; - - me.seek(io::SeekFrom::End(("config".as_bytes().len() * -1) as i64 - 4))?; - - let conf_len = me.read_u32()?; - - let mut buf = vec![0u8; 512]; - - me.read(&mut buf[0..6])?; - - if String::from_utf8((&buf[0..6]).iter().collect()).map(|s| &s == "config").unwrap_or(false) { - - } - - Ok(()) -}*/ fn main() -> Fido2LuksResult<()> { - let args: Vec<_> = env::args().skip(1).collect(); - fn config_env() -> Fido2LuksResult { - Ok(envy::prefixed("FIDO2LUKS_").from_env::()?) - } - fn secret_from_env_config(conf: &EnvConfig) -> Fido2LuksResult<[u8; 32]> { - let conf = config_env()?; - let salt = - InputSalt::from(conf.salt.as_str()).obtain(&conf.password_helper.as_str().into())?; - Ok(assemble_secret( - &perform_challenge(&conf.credential_id, &salt)?, - &salt, - )) - } - match &args.iter().map(|s| s.as_str()).collect::>()[..] { - ["print-secret"] => { - let conf = config_env()?; - io::stdout().write(hex::encode(&secret_from_env_config(&conf)?[..]).as_bytes())?; - Ok(io::stdout().flush()?) - } - ["open"] => { - let mut conf = config_env()?; - open_container( - &conf - .device - .as_ref() - .expect("please specify FIDO2LUKS_DEVICE") - .into(), - &conf - .mapper_name - .as_ref() - .expect("please specify FIDO2LUKS_MAPPER_NAME"), - &secret_from_env_config(&conf)?, - ) - } - ["open", device, mapper_name] => { - let mut conf = config_env()?; - conf.mapper_name = Some(mapper_name.to_string()); - conf.device = Some(device.to_string()); - open_container( - &conf - .device - .as_ref() - .expect("please specify FIDO2LUKS_DEVICE") - .into(), - &conf - .mapper_name - .as_ref() - .expect("please specify FIDO2LUKS_MAPPER_NAME"), - &secret_from_env_config(&conf)?, - ) - } - ["credential"] => { - let cred = make_credential_id()?; - println!("{}", hex::encode(&cred.id)); - Ok(()) - } - ["addkey", device] => { - let mut conf = config_env()?; - conf.device = conf.device.or(Some(device.to_string())); - let slot = add_key_to_luks( - conf.device.as_ref().unwrap().into(), - &secret_from_env_config(&conf)?, true - )?; - println!("Added to key to device {}, slot: {}", device, slot); - Ok(()) - } - _ => { - println!( - "Usage:\n - fido2luks open [name]\n - fido2luks addkey \n\n - Environment variables:\n - \n - \n - " - ); - Ok(()) - } - } -} - -fn main_old() -> Fido2LuksResult<()> { - let args: Vec<_> = env::args().skip(1).collect(); //Ignore program name -> Vec - let env = env::vars().collect::>(); - let secret = |conf: &Config| -> Fido2LuksResult<[u8; 32]> { - let salt = conf.input_salt.obtain(&conf.password_helper)?; - - Ok(assemble_secret( - &perform_challenge(&conf.credential_id, &salt)?, - &salt, - )) - }; - if args.is_empty() { - let conf = Config::load_default_location()?; - if env.contains_key("CRYPTTAB_NAME") { - //Indicates that this script is being run as keyscript - let mut out = stdout(); - out.write(&secret(&conf)?)?; - Ok(out.flush()?) - } else { - io::stdout().write(&secret(&conf)?)?; - Ok(io::stdout().flush()?) - } - } else { - match args.first().map(|s| s.as_ref()).unwrap() { - //"addkey" => add_key_to_luks(&Config::load_default_location()?).map(|_| ()), - "setup" => setup(), - "open" if args.get(1).map(|a| &*a == "-e").unwrap_or(false) => { - let conf = envy::prefixed("FIDO2LUKS_") - .from_env::() - .expect("Missing env config values") - .try_into()?; - open(&conf, &secret(&conf)?) - } - "open" => open( - &Config::load_default_location()?, - &secret(&Config::load_default_location()?)?, - ), - "connected" => match authenticator_connected()? { - false => { - println!("no"); - exit(1) - } - _ => { - println!("yes"); - exit(0) - } - }, - _ => { - eprintln!("Usage: setup | addkey | connected"); - Ok(()) - } //"selfcontain" => package_self() - } - } + run_cli() }