#!/usr/bin/env bash # Copyright 2020-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 MY_VERSION="1.1" MY_NAME="p11ne-db" MY_DESC="p11ne database formatting tool" USAGE="\ $MY_NAME v$MY_VERSION - $MY_DESC Usage: $(basename "$0") [arguments] Commands: pack-key Packs an input PEM private key into a p11ne specific format. --id --label --key-file [--cert-file] --out-file --kms-key-id --kms-region " # Database format converter cmd_pack-key() { local nargs="$#"; if [ $nargs -ne 12 -a $nargs -ne 14 ]; then die "Invalid arguments. Please use \`$0 help\` for help." fi while [[ "$#" -gt 0 ]]; do case $1 in --id) id="$2"; shift ;; --label) label="$2"; shift ;; --key-file) key_file="$2"; shift ;; --cert-file) cert_file="$2"; shift ;; --out-file) out_file="$2"; shift ;; --kms-key-id) key_id="$2"; shift ;; --kms-region) region="$2"; shift ;; *) cmd_help; die "Invalid argument: $1. Please use \`$0 help\` for help.";; esac shift done if [ $nargs -eq 12 -a -n "$cert_file" ]; then die "Invalid arguments. Please use \`$0 help\` for help." fi # The key file if [ ! -f "$key_file" ]; then die "Cannot find the input key file." fi # Read and pack the key local key key=$(<"$key_file") ok_or_die "Cannot open the input file." #ensure aws cli which aws > /dev/null ok_or_die "aws cli is not present on this machine. Please install the aws cli and try again." #encrypt with kms - the result is the Base64 representation of the cyphertext enc_key=$(aws kms encrypt --key-id $key_id --plaintext "$key" --region $region --query CiphertextBlob --output text) ok_or_die "Failed to encrypt the key" # Read the cert (optional) local cert if [ -n "$cert_file" -a -f "$cert_file" ]; then cert=$(<"$cert_file") fi local out_data out_data=$( jq -Rn \ --arg a "$enc_key" \ --arg b "$id" \ --arg c "$label" \ --arg d "$cert" \ '[{encrypted_pem_b64: $a, id: $b | tonumber, label: $c, cert_pem: $d}] | del(.[][] | select(. == ""))') ok_or_die "Cannot format the input key." echo "$out_data" > "$out_file.db" ok_or_die "Cannot write to output file." } # Exit with an error message and (optional) code # Usage: die [-c ] # die() { code=1 [[ "$1" = "-c" ]] && { code="$2" shift 2 } say_err "$@" exit "$code" } # Exit with an error message if the last exit code is not 0 # ok_or_die() { code=$? [[ $code -eq 0 ]] || die -c $code "$@" } # Send a text message to stderr # say_err() { [ -t 2 ] && [ -n "$TERM" ] \ && echo "$(tput setaf 1)[$MY_NAME] $*$(tput sgr0)" 1>&2 \ || echo "[$MY_NAME] $*" 1>&2 } cmd_help() { echo "$USAGE" } main() { if [ "$#" -eq 0 ]; then cmd_help exit 1 fi local cmd="$1" declare -f "cmd_$cmd" > /dev/null ok_or_die "Unknown command: $1. Please use \`$0 help\` for help." cmd_"$@" } main "${@}"