Hardcoded HMAC key

Hardcoded HMAC key

Description

An HMAC key embedded in source may be recovered from the repository or distributed application. HMAC verifies a message’s origin and integrity without encrypting its contents.

Potential impact

Someone with the key can produce a valid authentication code for an altered message or forged token. A service that trusts it may accept unauthorized requests.

Remediation

Load the key from access-controlled runtime configuration or an environment variable. Keep it out of repositories and logs. If exposed, replace it, retire the old key on verifiers and check relevant logs for misuse.

Examples

Before

javascript
const crypto = require('crypto');

const HMAC_KEY = 'abcd1234abcd1234abcd1234'; // Hardcoded key

function makeHmac(data) {
  return crypto.createHmac('sha256', HMAC_KEY).update(data).digest('hex');
}

After

javascript
const crypto = require('crypto');

const HMAC_KEY = process.env.HMAC_KEY; // Read the key from the environment

function makeHmac(data) {
  if (!HMAC_KEY) {
    throw new Error('HMAC 키가 설정되지 않았습니다.');
  }
  return crypto.createHmac('sha256', HMAC_KEY).update(data).digest('hex');
}

makeHmac stops when called with HMAC_KEY unset or empty. Restrict who can supply or read the environment variable.

References