3

I'd like to compute a HMAC-SHA512 digest in my bash script. So far I've found only this repeated many times over many different sites.

echo -n message | openssl dgst -sha256 -hmac secret -binary >message.mac

Apparently no one posting this realizes this is not the proper way to pass a secret string to a program as the secret will be visible in the process list for every other process running on the system. Is there any other way (perhaps with other tool) to easily make an HMAC in the shell with better interface for passing secrets?

UPDATE

I use the following tool (~/bin/hmac) now. It takes the key from the MACKEY environment variable.

#!/usr/bin/env python3
import hmac, sys, os

key    = os.environ['MACKEY'].encode('utf-8')
algo   = os.getenv('MACALGO', 'sha512')
digest = hmac.new(key, digestmod = algo)

while True:
    buf = sys.stdin.buffer.read(512)
    if not buf:
        break
    digest.update(buf)

print(digest.hexdigest())

Usage:

echo -n message | MACKEY=foobar hmac

2 Answers2

2

Re-directions are not part of the argument list.

This are considered safe from ps snooping:

cmd </file/key
cmd <<<"key"

Un-named pipes are also possible inside an script

echo "secret" | cmd

Example of secure password passing

So, this script is regarded as secure:

#!/bin/bash

read secretkey </dev/stdin

var="<?= hash_hmac(\"sha512\", \"$1\", \"$secretkey\"); ?>"

php7.1 <<<"$var"

The </dev/stdin could be replaced with a </dir/keyfile if the key could be stored in a file.

For the stdin version, use it as this:

./script "Message" <<<"secretkey"
0

I have asked the same question on OpenSSL mailing list

If you are on Fedora 37 or RHEL 8, the libkcapi-hmaccalc package provides sha1hmac, sha512hmac, etc.

so you can replace:

$ echo -n toto | openssl dgst -hmac tata -sha1
SHA1(stdin)= 6c497bab7bcc37d768364b570445ee10a4fb17d6

with

$ echo -n toto | sha1hmac -k <(echo -n tata) 
6c497bab7bcc37d768364b570445ee10a4fb17d6

see man page

This prevents the secret key to leak in the process list (you still need to check that the key is not written in the Bash history, but this was not the scope of your question).

frigo
  • 31
  • 1