Created
June 11, 2024 00:09
-
-
Save nasrulhazim/02d32224cee7bf53edeac990528c4a7c to your computer and use it in GitHub Desktop.
Configure SELinux for NGINX
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Function to display usage | |
usage() { | |
echo "Usage: $0 -d <project_directory> [-p <ports>]" | |
echo " -d <project_directory> : The directory to be used by the web server (mandatory)" | |
echo " -p <ports> : Comma-separated list of http ports (default: 80,443)" | |
exit 1 | |
} | |
# Default ports | |
DEFAULT_PORTS="80,443" | |
# Parse arguments | |
while getopts "d:p:" opt; do | |
case ${opt} in | |
d) | |
WEB_DIR=${OPTARG} | |
;; | |
p) | |
PORTS=${OPTARG} | |
;; | |
*) | |
usage | |
;; | |
esac | |
done | |
# Check if project directory is provided | |
if [ -z "${WEB_DIR}" ]; then | |
echo "Error: Project directory is mandatory." | |
usage | |
fi | |
# Set default ports if not provided | |
if [ -z "${PORTS}" ]; then | |
PORTS=${DEFAULT_PORTS} | |
fi | |
# Convert comma-separated ports into an array | |
IFS=',' read -r -a HTTP_PORTS <<< "${PORTS}" | |
echo "Configuring SELinux for Nginx/Apache" | |
# Allow nginx or apache to access public files of web application | |
echo "Setting SELinux context for web directory: $WEB_DIR" | |
chcon -Rv --type=httpd_sys_content_t $WEB_DIR | |
echo "Enabling httpd network connect" | |
setsebool httpd_can_network_connect on -P | |
echo "Adding SELinux context rule for web directory" | |
semanage fcontext -a -t httpd_sys_content_t $WEB_DIR | |
echo "Restoring SELinux context for web directory" | |
restorecon -Rv $WEB_DIR | |
# Check current http ports in SELinux | |
echo "Listing current SELinux http ports" | |
semanage port -l | grep http | |
# Add required http ports | |
for PORT in "${HTTP_PORTS[@]}"; do | |
echo "Adding http port: $PORT" | |
semanage port -a -t http_port_t -p tcp $PORT || echo "Port $PORT already exists, skipping..." | |
done | |
# Restart nginx and related services | |
echo "Restarting nginx service" | |
systemctl restart nginx | |
# Set SELinux booleans for using nginx as a proxy | |
echo "Setting SELinux booleans for network relay and connect" | |
setsebool -P httpd_can_network_relay 1 | |
setsebool -P httpd_can_network_connect 1 | |
echo "SELinux configuration for Nginx/Apache completed." | |
# Checking the status of SELinux booleans and ports | |
echo "Checking SELinux booleans:" | |
getsebool httpd_can_network_relay | |
getsebool httpd_can_network_connect | |
echo "Checking configured http ports:" | |
semanage port -l | grep http | |
echo "All tasks completed." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment