From 770fe178d2d87533e512f5fdb5aba57a603f49aa Mon Sep 17 00:00:00 2001
From: Alperen <alperene@aof.anadolu.edu.tr>
Date: Sat, 9 Nov 2024 23:21:39 +0300
Subject: fix: sanitize domain input to prevent command injection

- Added input validation for the domain parameter to allow only alphanumeric characters, dots, and dashes.
- This mitigates a command injection vulnerability on line 9 where unsanitized user input could be injected into the sed command.
- The fix improves security for local script execution in multi-user environments or when the script is run with elevated privileges.
---
 adddomain.sh | 19 ++++++++++++-------
 1 file changed, 12 insertions(+), 7 deletions(-)

diff --git a/adddomain.sh b/adddomain.sh
index d44b567..fe95a90 100755
--- a/adddomain.sh
+++ b/adddomain.sh
@@ -1,28 +1,33 @@
 #!/bin/sh
 
 domain="$1"
-[ -z "$1" ] && exit
+[ -z "$domain" ] && exit
+
+# Input validation to allow only valid domain characters
+if ! [[ "$domain" =~ ^[a-zA-Z0-9.-]+$ ]]; then
+    echo "Invalid domain format. Only alphanumeric characters, dashes, and dots are allowed."
+    exit 1
+fi
 
-domain="$1"
 subdom="mail"
 
-# Add the domain to the valid postfix addresses.
+# Add the domain to the valid postfix addresses
 grep -q "^mydestination.*$domain" /etc/postfix/main.cf ||
-	sed -i "s/^mydestination.*/&, $domain/" /etc/postfix/main.cf
+    sed -i "s/^mydestination.*/&, $domain/" /etc/postfix/main.cf
 
-# Create DKIM for new domain.
+# Create DKIM for the new domain
 mkdir -p "/etc/postfix/dkim/$domain"
 opendkim-genkey -D "/etc/postfix/dkim/$domain" -d "$domain" -s "$subdom"
 chgrp -R opendkim /etc/postfix/dkim/*
 chmod -R g+r /etc/postfix/dkim/*
 
-# Add entries to keytable and signing table.
+# Add entries to keytable and signing table
 echo "$subdom._domainkey.$domain $domain:$subdom:/etc/postfix/dkim/$domain/$subdom.private" >> /etc/postfix/dkim/keytable
 echo "*@$domain $subdom._domainkey.$domain" >> /etc/postfix/dkim/signingtable
 
 systemctl reload opendkim postfix
 
-# Print out DKIM TXT entry.
+# Print out DKIM TXT entry
 pval="$(tr -d '\n' <"/etc/postfix/dkim/$domain/$subdom.txt" | sed "s/k=rsa.* \"p=/k=rsa; p=/;s/\"\s*\"//;s/\"\s*).*//" | grep -o 'p=.*')"
 
 dkimentry="$subdom._domainkey.$domain	TXT	v=DKIM1; k=rsa; $pval"
-- 
cgit v1.2.3