crypto-wrapper.sh 12.1 KB
Newer Older
1 2 3 4 5 6 7
#!/bin/sh
# busybox POSIX-like shell script
set -eu

# protect cache files from other users
umask 0077

Vojtech Myslivec's avatar
Vojtech Myslivec committed
8
VERSION='0.1-alpha'
9
SCRIPTNAME=${0##*/}
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
USAGE="USAGE
    General syntax:
        $SCRIPTNAME command [args..]

        High-level command for Turris devices to query cryptographic functions
        and device info stored during production. This command unifies
        hardware-specific commands such as \`atsha204cmd\` for Turris 1.x and
        Omnia and \`mox-otp\` for MOX.

        All query commands are cached on the filesystem so querying same
        commands will not wear-out cryptographic device.

    Available commands:
        $SCRIPTNAME help
                    Print this message end exits

Vojtech Myslivec's avatar
Vojtech Myslivec committed
26 27 28
        $SCRIPTNAME version
                    Print script version and exits

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
        $SCRIPTNAME serial-number
                    Print serial number of the device

        $SCRIPTNAME sign [file]
                    \"Sign\" given file or standard input if no file is given.
                    Signing on atsha-equipped device is realized via HMAC
                    function with shared secret.

        $SCRIPTNAME sign-hash hash
                    Sign given hash; it must include only hexadecimal characters

                    WARNING:    low-level command; hash must be exactly the one
                                underlying command expects (sha512 on MOX and
                                sha256 on atsha-equipped device)

        $SCRIPTNAME clear-cache
                    Remove all command cache
"
47 48 49 50

# hash used for cache indexing and integrity checks
HASH_TYPE='sha256'

51
CRYPTO_WRAPPER_ROOT_PREFIX='/tmp/crypto_wrapper'
52

53 54 55 56
SYSINFO_MODEL_FILE='/tmp/sysinfo/model'
TYPE_ATSHA='atsha'
TYPE_OTP='otp'

57 58 59 60
# length of a hash for given type (number of hexadecimal characters)
HASH_LENGTH_ATSHA='64'
HASH_LENGTH_OTP='128'

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

# --------------------------------------------------------------------
stderr_mesage() {
    echo "$SCRIPTNAME: $1: $2" >&2
}


error() {
    stderr_mesage 'error' "$*"
}


warning() {
    stderr_mesage 'warning' "$*"
}

Vojtech Myslivec's avatar
Vojtech Myslivec committed
77 78 79 80 81
debug() {
    # double negative due to `set -o errexit`
    [ "${DEBUG:-false}" != true ] || stderr_mesage 'debug' "$*"
}

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
# --------------------------------------------------------------------
# checks existence and readability of file $1
check_file() {
    local file=$1

    [ -f "$file" -a -r "$file" ] || {
        error "'$file' is not a readable file"
        return 1
    }
}

# check hexstring $1 of given length $2
check_hexstring() {
    local hash=$1
    local length=$2

    [ -z "$(echo "$hash" | tr -d '0-9a-f')" ] || {
        error 'Given hash is not hexadecimal string'
        return 1
    }

    [ "${#hash}" -eq "$length" ] || {
        error "Given hash must have $length hexadecimal characters"
        return 1
    }
}


111 112 113 114 115 116 117 118 119 120 121 122 123
# --------------------------------------------------------------------
hash_file() {
    openssl "$HASH_TYPE" "$file" | awk '{print $2}'
}


hash_string() {
    printf '%s' "$1" | openssl "$HASH_TYPE" | awk '{print $2}'
}


# this function must be called before running any other cache related function
cache_init() {
124 125 126 127 128 129
    local user
    user=$(id -nu)

    # global variable
    CRYPTO_WRAPPER_ROOT="${CRYPTO_WRAPPER_ROOT_PREFIX}_${user}"

130 131 132 133
    mkdir -p "$CRYPTO_WRAPPER_ROOT"
}


134 135 136
cache_destroy() {
    rm -f "$CRYPTO_WRAPPER_ROOT"/key_*
    rm -f "$CRYPTO_WRAPPER_ROOT"/hash_*
137
    rm -f "$CRYPTO_WRAPPER_ROOT"/temp_*
138 139 140 141 142
    [ -d "$CRYPTO_WRAPPER_ROOT" ] && rmdir "$CRYPTO_WRAPPER_ROOT"
    return 0
}


143 144 145 146 147 148
# create empty temporary file in cache root
cache_mktemp() {
    mktemp "$CRYPTO_WRAPPER_ROOT/temp_XXXXXX"
}


149 150 151 152
# key should be sha256 hash (HASH_TYPE)
cache_set() {
    local key="$1"
    local value="$2"
153 154
    local hash
    hash=$(hash_string "$value")
155

156
    # key is read first so hash must be written before the key
157
    echo "$value" > "$CRYPTO_WRAPPER_ROOT/hash_$hash"
158
    echo "$value" > "$CRYPTO_WRAPPER_ROOT/key_$key"
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
}


# store value $2 for the key reffered in file $1 to cache
cache_set_file() {
    local key
    key=$(hash_file "$1")
    cache_set "$key" "$2"
}


# store value $2 for the key reffered in $1 (any string) to cache
cache_set_string() {
    local key
    key=$(hash_string "$1")
    cache_set "$key" "$2"
}


# key should be sha256 hash (HASH_TYPE)
cache_get() {
    local key="$1"
    local key_file="$CRYPTO_WRAPPER_ROOT/key_$key"
182 183
    local hash hash_file value

184
    [ -f "$key_file" ] || {
Vojtech Myslivec's avatar
Vojtech Myslivec committed
185
        debug "Key was not found in cache"
186 187
        return 1
    }
188 189 190 191 192
    value=$(cat "$key_file")

    hash=$(hash_string "$value")
    hash_file="$CRYPTO_WRAPPER_ROOT/hash_$hash"
    [ -f "$hash_file" ] || {
Vojtech Myslivec's avatar
Vojtech Myslivec committed
193
        debug "Control file was not found"
194 195 196 197
        return 2
    }

    [ "$value" = "$(cat "$hash_file")" ] || {
Vojtech Myslivec's avatar
Vojtech Myslivec committed
198
        debug "Control hash does not match the value"
199 200 201 202
        return 3
    }

    echo "$value"
203 204 205 206 207 208
}


# get value from cache for the key reffered in file $1
cache_get_file() {
    local file="$1"
209
    local key value
210

211
    key=$(hash_file "$file")
212
    value=$(cache_get "$key") || {
Vojtech Myslivec's avatar
Vojtech Myslivec committed
213
        debug "Value for file '$file' was not found in cache"
214 215
        return 1
    }
216

217 218 219 220 221 222 223
    echo "$value"
}


# get value from cache for the key reffered in $1 string
cache_get_string() {
    local string="$1"
224
    local key value
225

226
    key=$(hash_string "$string")
227
    value=$(cache_get "$key") || {
Vojtech Myslivec's avatar
Vojtech Myslivec committed
228
        debug "Value for string '$string' was not found in cache"
229 230
        return 1
    }
231

232 233
    echo "$value"
}
234 235 236


# --------------------------------------------------------------------
237 238 239
# Run command with output saved to cache. If some value is found in the cache,
# output is get directly from cache without actually running the command.
#
240 241
# First argument is the key type ('string' or 'file') second is the key to the
# cache and the rest is command to run
242
cached_command() {
243 244 245 246
    local key_type="$1"
    local key="$2"
    local cmd="$3"
    local output cache_get_funtion cache_set_funtion
247
    # the rest is arguments
248 249 250 251 252 253 254 255 256 257 258 259
    shift 3

    if   [ "$key_type" = 'string' ]; then
        cache_get_funtion=cache_get_string
        cache_set_funtion=cache_set_string
    elif [ "$key_type" = 'file' ]; then
        cache_get_funtion=cache_get_file
        cache_set_funtion=cache_set_file
    else
        error "'cached_command: Undefined cache key type '$key_type'"
        return 4
    fi
260

261
    if output=$("$cache_get_funtion" "$key"); then
262
        debug "key '$key' found in cache"
263
    else
264 265 266 267 268 269 270
        debug "key '$key' was not found in cache, run the command"
        output=$("$cmd" "$@") || {
            error "Failed to run command '$cmd $*'"
            return 5
        }

        debug 'store output of the command to cache'
271
        "$cache_set_funtion" "$key" "$output"
272 273 274 275
    fi

    echo "$output"
}
276 277 278


cached_atsha_serial() {
279
    cached_command string 'serial' 'atsha204cmd' 'serial-number'
280
}
281 282


283 284 285
# 64-bytes hex string from stdin
cached_atsha_challenge_response() {
    local hash="$1"
286
    check_hexstring "$hash" "$HASH_LENGTH_ATSHA"
287

288 289
    echo "$hash" \
            | cached_command string "$hash" 'atsha204cmd' 'challenge-response'
290 291 292
}


293 294
cached_atsha_challenge_response_file() {
    local file="$1"
295
    check_file "$file"
296

297 298 299
    # this is wierd atsha204cmd interface
    echo "$file" \
            | cached_command file "$file" 'atsha204cmd' 'file-challenge-response'
300
}
301 302 303 304 305 306 307 308 309 310


cached_otp_serial() {
    cached_command string 'serial' 'mox-otp' 'serial-number'
}


# 128-bytes hex string from stdin
cached_otp_sign_hash() {
    local hash="$1"
311 312
    check_hexstring "$hash" "$HASH_LENGTH_OTP"

313 314 315 316 317 318
    cached_command string "$hash" 'mox-otp' 'sign-hash' "$hash"
}


cached_otp_sign() {
    local file="$1"
319 320
    check_file "$file"

321 322
    cached_command file "$file" 'mox-otp' 'sign' "$file"
}
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


# --------------------------------------------------------------------
get_device_type(){
    local model

    [ -f "$SYSINFO_MODEL_FILE" ] || {
        error "Unknown device model; sysinfo file is missing '$SYSINFO_MODEL_FILE'"
        return 2
    }

    model=$(cat "$SYSINFO_MODEL_FILE")
    case "$model" in
        # WARNING:
        #   Turris string is also included in other models
        #   This case must not include wildcards
        Turris)
            debug "Device recognized as Turris 1.x"
            echo "$TYPE_ATSHA"
            ;;

        *Omnia*)
            debug "Device recognized as Omnia"
            echo "$TYPE_ATSHA"
            ;;

        *Mox*)
            debug "Device recognized as MOX"
            echo "$TYPE_OTP"
            ;;

        *)
            error "Unknown device model: '$model'"
            return 2
            ;;

    esac
}
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381


# --------------------------------------------------------------------
do_serial() {
    local device_type
    cache_init

    device_type=$(get_device_type)
    if   [ "$device_type" = "$TYPE_ATSHA" ]; then
        debug "Call atsha serial-number"
        cached_atsha_serial

    elif [ "$device_type" = "$TYPE_OTP" ]; then
        debug "Call otp serial-number"
        cached_otp_serial

    else
        error "Unsupported device_type '$device_type'"
        return 2
    fi
}
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


do_sign() {
    local file="$1"
    local tmp=''
    local device_type
    cache_init

    # use stdin if no file is given – store it to temp file
    [ -z "$file" ] && {
        tmp=$(cache_mktemp)
        debug "Store stdin to '$tmp'"
        cat > "$tmp"
        file="$tmp"
    }

    device_type=$(get_device_type)
    case "$device_type" in
        "$TYPE_ATSHA")
            debug "Call atsha file-challenge-response with '$file'"
            cached_atsha_challenge_response_file "$file"
            ;;

        "$TYPE_OTP")
            debug "Call otp sign with '$file'"
            cached_otp_sign "$file"
            ;;

        *)
            error "Unsupported device_type '$device_type'"
            return 2
            ;;

    esac

    # remove temp file if it was used
    [ -z "$tmp" ] || rm -f "$tmp"
}
420 421 422 423 424


do_sign_hash() {
    # avoid multiline variable and capital letters
    # busybox does not support neither ${var,,} nor tr [:upper:] [:lower:]
425 426
    local hash device_type
    hash=$(echo "${1}" | head -n 1 | tr 'A-Z' 'a-z')
427
    cache_init
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442

    device_type=$(get_device_type)
    if   [ "$device_type" = "$TYPE_ATSHA" ]; then
        debug "Call atsha challenge-response with '$hash'"
        cached_atsha_challenge_response "$hash"

    elif [ "$device_type" = "$TYPE_OTP" ]; then
        debug "Call otp sign-hash with '$hash'"
        cached_otp_sign_hash "$hash"

    else
        error "Unsupported device_type '$device_type'"
        return 2
    fi
}
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460


# --------------------------------------------------------------------
main() {
    # USAGE
    [ "$#" -lt 1 ] && {
        error "No command was given"
        echo "$USAGE" >&2
        exit 1
    }

    command="$1"
    case "$command" in
        # hardware-independent commands -----
        'help')
            echo "$USAGE"
            ;;

Vojtech Myslivec's avatar
Vojtech Myslivec committed
461 462 463 464
        'version')
            echo "$VERSION"
            ;;

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
        'clear'|'clear-cache'|'cache-clear')
            # cache init set CRYPTO_WRAPPER_ROOT variable
            cache_init
            cache_destroy
            ;;

        # hardware-specific commands --------
        'serial'|'serial-number')
            if [ $# -eq 1 ]; then
                do_serial
            else
                error 'Too many arguments for `serial-number` command'
                return 1
            fi
            ;;

        'sign'|'file-challenge-response')
            if   [ $# -eq 1 ]; then
                # sign the stdin
                do_sign ""
            elif [ $# -eq 2 ]; then
                # sign the given file
                do_sign "$2"
            else
                error 'Too many arguments for `sign` command'
                return 1
            fi
            ;;

        'sign-hash'|'challenge-response')
            if   [ $# -eq 1 ]; then
                error 'Hash is missing for `sign-hash` command'
                return 1
            elif [ $# -eq 2 ]; then
                do_sign_hash "$2"
            else
                error 'Too many arguments for `sign-hash` command'
                return 1
            fi
            ;;

        # -----------------------------------
        *)
            error "Unknown command '$command'"
            exit 1
            ;;

    esac
}


# --------------------------------------------------------------------
main "$@"