bash scrip sequrity - ghdrako/doc_snipets GitHub Wiki
Securing input
the script checks if the input is non-empty and contains only valid characters (alphanumeric characters, underscores, hyphens, and dots). Quoting the variable expansion ensures that special characters do not break out of the intended context.
#!/bin/bash
echo "Enter the filename to delete:"
read filename
if [ -n $filename && $filename =~ ^[A-Za-z0-9._-]+$ ](/ghdrako/doc_snipets/wiki/--n-$filename-&&-$filename-=~-^[A-Za-z0-9._-]+$-); then
rm "$filename"
else
echo "Invalid filename."
fi
Essential Steps in Input Validation and Sanitization:
- Define Valid Input Criteria: Before you can validate or sanitize input, it is critical to define what constitutes valid input. For example, if a script expects a username, the valid input could be defined as an alphanumeric string between 1 and 32 characters long, without spaces or special characters.
valid_username_regex="^[a-zA-Z0-9]{1,32}$"
- Input Validation: Validation checks confirm that the input data meets the criteria defined. It can be implemented by using conditional statements to compare input against the validation regexn or other rules.
#!/bin/bash
valid_username_regex="^[a-zA-Z0-9]{1,32}$"
read -p "Enter username: " username
if [ $username =~ $valid_username_regex ](/ghdrako/doc_snipets/wiki/-$username-=~-$valid_username_regex-); then
echo "Username is valid."
else
echo "Invalid username. Please enter a valid alphanumeric username."
exit 1
fi
- Input Sanitization: Sanitization ensures that even if the input is syntactically correct, it is free from malicious content. For instance, filenames or paths entered by the user should not contain dangerous characters.
Sanitization can involve:
- Removing unsafe characters
- Escaping special characters
- Trimming excess whitespace
#!/bin/bash
read -p "Enter the filename: " filename
# Remove potentially dangerous characters
safe_filename=$(echo "$filename" | tr -cd '[:alnum:]._-')
echo "Sanitized filename: $safe_filename"
The 'tr' command is used to remove any characters from the input filename that are not alphanumeric, dots,underscores, or hyphens, ensuring the filename is safe to use.
- Combining Validation and Sanitization
#!/bin/bash
valid_username_regex="^[a-zA-Z0-9]{1,32}$"
read -p "Enter username: " username
read -p "Enter filename: " filename
# Check if username is valid
if [ $username =~ $valid_username_regex ](/ghdrako/doc_snipets/wiki/-$username-=~-$valid_username_regex-); then
echo "Username is valid."
else
echo "Invalid username. Please enter a valid alphanumeric username."
exit 1
fi
# Sanitize filename input
safe_filename=$(echo "$filename" | tr -cd '[:alnum:]._-')
echo "Sanitized filename: $safe_filename"
- Avoiding Command Injection
#!/bin/bash
# Read user input
read -p "Enter directory name: " dir
# Validate directory name
if [ $dir =~ ^[a-zA-Z0-9_-]+$ ](/ghdrako/doc_snipets/wiki/-$dir-=~-^[a-zA-Z0-9_-]+$-); then
echo "Valid directory name."
else
echo "Invalid directory name."
exit 1
fi
# Safely create a directory
mkdir -- "$dir"
The ‘–‘ in the ‘mkdir‘ command ensures that arguments following it are treated as operands even if they begin with a ‘-‘. This guards against filenames that might appear as options.
za pomocą mkdir -- "$dir"
, zapewniając bezpieczeństwo w przypadku, gdy nazwa zaczyna się od myślnika.
Handling Sensitive Data Securely
Avoid hardcoding sensitive information. Instead, leverage environment variables, secure storage mechanisms,and access controls.
Environment Variables
export DB_PASSWORD="my_secure_password"
#!/bin/bash
echo "Connecting to database with password: ${DB_PASSWORD}"
Using Configuration Files with Restricted Access
#!/bin/bash
source /etc/my_sensitive_config.conf
echo "Connecting to database with password: ${DB_PASSWORD}"
Using Secret Management Tools
- Ustawienie serwera Vault:
vault server -config=/path/to/config.hcl
- Przechowywanie sekretów:
vault kv put secret/db_password value="my_secure_password"
- Uzyskiwanie sekretów w skryptach:
#!/bin/bash
export VAULT_ADDR='http://127.0.0.1:8200'
vault kv get -format=json secret/db_password | jq -r '.data.data.value'
managing sensitive data
sensitive data such as passwords, API keys, and personal information
Restrictive permission
chmod 700 script.sh
Handling command exit code
#!/bin/bash
mkdir /secure/dir
if [ $? -ne 0 ](/ghdrako/doc_snipets/wiki/-$?--ne-0-); then
echo "Failed to create directory."
exit 1
fi
Security vulnerabilities
Command Injection Attacks
If user inputs are not validated and sanitized appropriately, an attacker can inject malicious commands, potentially gaining unauthorized access to the system or executing harmful operations.
#!/bin/bash
echo "Enter filename:"
read filename
if [ -f "$filename" ](/ghdrako/doc_snipets/wiki/--f-"$filename"-); then
cat "$filename"
else
echo "File does not exist."
fi
the -f
test ensures the input is a valid file.
Race condition
Safe a script checks for the existence of a file before creating it using flock
#!/bin/bash
(
flock -n 200 || exit 1
if [ ! -e /tmp/myfile ](/ghdrako/doc_snipets/wiki/-!--e-/tmp/myfile-); then
touch /tmp/myfile
fi
) 200>/tmp/myfile.lock
In this script, flock ensures that the operations on /tmp/myfile are atomic, preventing race conditions.
Blokada pliku:
- Skrypt otacza swoją główną logikę blokadą pliku. Korzysta z polecenia flock -n 200, gdzie 200 to numer deskryptora pliku, który jest używany do blokady.
- Opcja
-n
oznacza, że jeśli nie uda się zablokować pliku (np. ponieważ inny proces już go zablokował), skrypt natychmiast zakończy się (exit 1), zamiast czekać na zwolnienie blokady.
Sprawdzanie istnienia pliku:
- Skrypt sprawdza, czy plik /tmp/myfile istnieje przy pomocy warunku ! -e /tmp/myfile .
- Jeśli plik nie istnieje, tworzy go poleceniem touch /tmp/myfile.
Blokowanie pliku na deskryptorze 200:
- Deskryptor 200 jest powiązany z plikiem blokady /tmp/myfile.lock. Dzięki temu tylko jeden proces może mieć dostęp do tego pliku na raz.