| 1 | #!/bin/bash -e |
| 2 | # vim: set tabstop=8 shiftwidth=4 softtabstop=4 expandtab smarttab colorcolumn=80: |
| 3 | # |
| 4 | # Copyright (c) 2024 Oldřich Jedlička |
| 5 | # |
| 6 | # Author: Oldřich Jedlička <[email protected]> |
| 7 | # |
| 8 | # This program is free software: you can redistribute it and/or modify |
| 9 | # it under the terms of the GNU General Public License as published by |
| 10 | # the Free Software Foundation, either version 3 of the License, or |
| 11 | # (at your option) any later version. |
| 12 | # |
| 13 | # This program is distributed in the hope that it will be useful, |
| 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 16 | # GNU General Public License for more details. |
| 17 | # |
| 18 | # You should have received a copy of the GNU General Public License |
| 19 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 20 | # |
| 21 | |
| 22 | [ $# -eq 1 ] && [ "$1" == "--summary" ] && exit 2 |
| 23 | |
| 24 | if [ -t 0 ]; then |
| 25 | exec >&2 |
| 26 | echo |
| 27 | echo "Usage: clevis decrypt tpm1 < JWE > PLAINTEXT" |
| 28 | echo |
| 29 | exit 2 |
| 30 | fi |
| 31 | |
| 32 | tpm_version_bin="$(command -v tpm_version || echo /usr/sbin/tpm_version)" |
| 33 | if ! "$tpm_version_bin" >/dev/null 2>&1; then |
| 34 | # The tpm_version outputs garbage to stdout on success, so let the |
| 35 | # tpm_version output the error again cleanly now |
| 36 | echo "The tpm1 pin requires tcsd daemon (trousers) running:" >&2 |
| 37 | if [ -x "$tpm_version_bin" ]; then |
| 38 | ( "$tpm_version_bin" 2>&1 | tr '\0' ' ' ) >&2 |
| 39 | else |
| 40 | echo Cannot check, tpm_version from tpm-tools not found >&2 |
| 41 | fi |
| 42 | exit 1 |
| 43 | fi |
| 44 | |
| 45 | read -r -d . hdr |
| 46 | |
| 47 | if ! jhd="$(jose b64 dec -i- <<< "$hdr")"; then |
| 48 | echo "Error decoding JWE protected header!" >&2 |
| 49 | exit 1 |
| 50 | fi |
| 51 | |
| 52 | if [ "$(jose fmt -j- -Og clevis -g pin -u- <<< "$jhd")" != "tpm1" ]; then |
| 53 | echo "JWE pin mismatch!" >&2 |
| 54 | exit 1 |
| 55 | fi |
| 56 | |
| 57 | if ! jwk_b64="$(jose fmt -j- -Og clevis -g tpm1 -g jwk -Su- <<< "$jhd")"; then |
| 58 | echo "JWE missing required 'jwk' header parameter!" >&2 |
| 59 | exit 1 |
| 60 | fi |
| 61 | |
| 62 | if ! jwk_sealed="$(jose b64 dec -i- <<< "$jwk_b64")"; then |
| 63 | echo "Decoding jwk from Base64 failed!" >&2 |
| 64 | exit 1 |
| 65 | fi |
| 66 | |
| 67 | if ! jwk="$(tpm_unsealdata -i /dev/stdin -z <<< "$jwk_sealed")"; then |
| 68 | echo "Unable to unseal jwk!" >&2 |
| 69 | exit 1 |
| 70 | fi |
| 71 | |
| 72 | exec jose jwe dec -k- -i- < <(echo -n "$jwk$hdr."; /bin/cat) |