Skip to content

Instantly share code, notes, and snippets.

@ageis
Created May 14, 2018 09:15
Show Gist options
  • Save ageis/98275c80f60343c9f539a2224eff7849 to your computer and use it in GitHub Desktop.
Save ageis/98275c80f60343c9f539a2224eff7849 to your computer and use it in GitHub Desktop.
OpenPGP KDF-DO setup script for smartcards
#! /bin/bash
# Original author: NIIBE Yutaka <gniibe@fsij.org>
# URL: https://dev.gnupg.org/T3823
# Usage: ./kdf-do-setup.sh
GPG_CONNECT_AGENT=gpg-connect-agent
PW_USER="123456"
PW_ADMIN="12345678"
FILE_USER=${FILE_USER:-/tmp/s2k-user-$$.gpg}
FILE_ADMIN=${FILE_ADMIN:-/tmp/s2k-admin-$$.gpg}
DUMMY_PLAIN_TEXT=$(openssl rand -hex 16)
function rand () {
printf "%04X\n" $RANDOM
}
function cmd_gen_random_8byte () {
# RANDOM is 0..32767, so, use only 24-bit
echo $(rand)$(rand)$(rand)$(rand)$(rand)$(rand) | \
sed -n -e 's/.\(...\).\(...\).\(...\).\(...\).\(...\).\(.\)../\1\2\3\4\5\6/p'
}
function cmd_prepare_s2k () {
local PASSPHRASE=$1 FILE=$2
gpg --batch --passphrase $PASSPHRASE --output $FILE \
--s2k-digest-algo sha256 --s2k-cipher-algo aes256 --symmetric
}
function cmd_show_s2k () {
local PASSPHRASE=$1 FILE=$2
gpg --batch --passphrase $PASSPHRASE \
--show-session-key --list-packets $FILE 2>&1
}
function cmd_extract_s2k () {
sed -n -e 's/^\tsalt \([0-9A-F]*\), count \([0-9]*\).*$/\1\n\2/p' \
-e 's/^gpg.*: session key: ..:\([0-9A-F]*\).$/\1/p'
}
echo $DUMMY_PLAIN_TEXT | cmd_prepare_s2k $PW_USER $FILE_USER
echo $DUMMY_PLAIN_TEXT | cmd_prepare_s2k $PW_ADMIN $FILE_ADMIN
S2K_USER=$(cmd_show_s2k $PW_USER $FILE_USER | cmd_extract_s2k | tr '\n' ' ')
S2K_ADMIN=$(cmd_show_s2k $PW_ADMIN $FILE_ADMIN | cmd_extract_s2k | tr '\n' ' ')
read HASH_USER SALT_USER COUNT_USER <<EOF
$S2K_USER
EOF
read HASH_ADMIN SALT_ADMIN COUNT_ADMIN <<EOF
$S2K_ADMIN
EOF
if test $COUNT_ADMIN != $COUNT_USER; then
echo "Failure: S2K count: $COUNT_ADMIN != $COUNT_USER"
exit 1
fi
echo count: $COUNT_ADMIN
echo Admin
echo salt: $SALT_ADMIN
echo hash: $HASH_ADMIN
echo User
echo salt: $SALT_USER
echo hash: $HASH_USER
SALT_RESETCODE=$(cmd_gen_random_8byte)
KDF_DO_DATA=$(tr -d '\n' <<EOF
8101038201088304
$(printf "%08X" $COUNT_ADMIN)
8408
$SALT_USER
8508
$SALT_RESETCODE
8608
$SALT_ADMIN
8720
$HASH_USER
8820
$HASH_ADMIN
EOF
)
$GPG_CONNECT_AGENT <<EOF
scd serialno
scd apdu 00 A4 04 00 06 D2 76 00 01 24 01
scd apdu 00 20 00 83 08 31 32 33 34 35 36 37 38
scd apdu 00 DA 00 F9 6E $KDF_DO_DATA
/bye
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment