Skip to content

Instantly share code, notes, and snippets.

@henno
Created May 13, 2024 23:14
Show Gist options
  • Save henno/41c30ee34764c4d2fc86d1178b94302d to your computer and use it in GitHub Desktop.
Save henno/41c30ee34764c4d2fc86d1178b94302d to your computer and use it in GitHub Desktop.
#!/bin/sh
# This script checks the consistency between a public key stored in DNS records and a public key derived from a provided private key file.
# It requires three arguments:
# 1. A selector that identifies the public key in the DNS.
# 2. A domain name where the DNS record is located.
# 3. The path to the private key file.
#
# Usage:
# ./script_name <selector> <domain> <private_key_file>
#
# Outputs:
# The script fetches the public key from DNS using the specified selector and domain, extracts the public key from the provided private key file, and compares them.
# It provides a visual comparison and verification result indicating whether the public keys match or not.
# Checking the number of arguments
if [ $# -ne 3 ]; then
echo "Usage: $0 <selector> <domain> <private_key_file>"
echo "Ensure you provide exactly three arguments: the selector, domain, and path to the private key file."
exit 1
fi
selector=$1
domain=$2
private_key_file=$3
# Fetch the public key from DNS
echo "Fetching public key from DNS..."
dns_record=$(dig +short ${selector}._domainkey.${domain} TXT)
if [ -z "$dns_record" ]; then
echo "Failed to retrieve DNS record. Make sure the domain and selector are correct."
exit 2
fi
echo "DNS record fetched: $dns_record"
# Extracting the public key part from the DNS record
public_key_dns=$(echo $dns_record | sed -e 's/.*p=//g' -e 's/[^a-zA-Z0-9+=\/]//g')
echo "Extracted public key from DNS (formatted for comparison):"
echo "$public_key_dns"
# Extracting the public key from the private key
echo "Extracting public key from private key file..."
public_key_file=$(openssl rsa -in $private_key_file -pubout -outform PEM 2>/dev/null | openssl rsa -pubin -pubout -outform PEM 2>/dev/null | grep -v -- "---" | tr -d '\n')
if [ -z "$public_key_file" ]; then
echo "Failed to extract public key from private key file. Check your private key file."
exit 3
fi
echo "Derived public key from private key file (formatted for comparison):"
echo "$public_key_file"
# Print both keys aligned for easier visual comparison
echo
echo "Compare the following lines to check for a match:"
printf "%-15s %s\n" " DNS Public Key:" "$public_key_dns"
printf "%-15s %s\n" "File Public Key:" "$public_key_file"
# Comparing the public keys
if [ "$public_key_dns" = "$public_key_file" ]; then
echo "Valid: The public key in DNS matches the public key derived from the private key."
else
echo "Invalid: The public key in DNS does not match the public key derived from the private key."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment