Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save everaldo/7e6faa27d87f93935f17eb77ceb0288f to your computer and use it in GitHub Desktop.

Select an option

Save everaldo/7e6faa27d87f93935f17eb77ceb0288f to your computer and use it in GitHub Desktop.
Set up a Ubuntu server to deploy Kamal 2.x Docker containers to, hardened security and production ready
#!/bin/bash
# ==============================================================================
# SERVER HARDENING & DOCKER SETUP (PARA USUÁRIO EXISTENTE)
# ==============================================================================
set -euo pipefail
# --- AJUSTE AQUI ---
DEPLOY_USER="o_seu_usuario_aqui" # Substitua pelo nome do seu usuário de deploy
SSH_PORT=22022
# -------------------
# --- CORES ---
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
print_status() { echo -e "${BLUE}[INFO]${NC} $1"; }
print_success() { echo -e "${GREEN}[OK]${NC} $1"; }
print_warning() { echo -e "${YELLOW}[AVISO]${NC} $1"; }
print_error() { echo -e "${RED}[ERRO]${NC} $1"; exit 1; }
# --- 1. VERIFICAÇÃO DE USUÁRIO ---
check_user_exists() {
if ! id "$DEPLOY_USER" &>/dev/null; then
print_error "O usuário '$DEPLOY_USER' não foi encontrado no sistema. Altere a variável DEPLOY_USER no script."
fi
}
# --- 2. ATUALIZAÇÃO E BASE ---
setup_base() {
print_status "Atualizando pacotes do sistema..."
export DEBIAN_FRONTEND=noninteractive
apt-get update -y && apt-get upgrade -y
apt-get install -y curl nano wget git unzip ufw fail2ban \
software-properties-common apt-transport-https ca-certificates gnupg lsb-release
}
# --- 3. PERMISSÕES E SSH ---
setup_security_ssh() {
print_status "Configurando permissões para '$DEPLOY_USER' e endurecendo SSH..."
# Garante que o usuário está no grupo sudo
usermod -aG sudo "$DEPLOY_USER"
# Configura sudo sem senha para o deploy (opcional, remova se preferir senha)
echo "$DEPLOY_USER ALL=(ALL) NOPASSWD:ALL" > "/etc/sudoers.d/90-$DEPLOY_USER"
# Hardening do SSH
sed -i "s/^#Port 22/Port $SSH_PORT/" /etc/ssh/sshd_config
sed -i "s/^PermitRootLogin.*/PermitRootLogin prohibit-password/" /etc/ssh/sshd_config
sed -i "s/^#PasswordAuthentication yes/PasswordAuthentication no/" /etc/ssh/sshd_config
systemctl restart ssh
print_success "SSH configurado na porta $SSH_PORT. Login por senha DESATIVADO."
}
# --- 4. HARDENING DE REDE (KERNEL) ---
setup_kernel_hardening() {
print_status "Aplicando segurança no Kernel (sysctl)..."
cat <<EOF > /etc/sysctl.d/99-hardening.conf
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 2048
EOF
sysctl -p /etc/sysctl.d/99-hardening.conf
}
# --- 5. FIREWALL ---
setup_firewall() {
print_status "Configurando Firewall UFW..."
ufw default deny incoming
ufw default allow outgoing
ufw allow "$SSH_PORT"/tcp
ufw allow 80/tcp
ufw allow 443/tcp
echo "y" | ufw enable
# Fail2ban
cat <<EOF > /etc/fail2ban/jail.local
[sshd]
enabled = true
port = $SSH_PORT
maxretry = 5
bantime = 1h
EOF
systemctl restart fail2ban
}
# --- 6. INSTALAÇÃO DOCKER ---
setup_docker() {
print_status "Instalando Docker..."
if ! command -v docker &> /dev/null; then
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | \
tee /etc/apt/sources.list.d/docker.list > /dev/null
apt-get update
apt-get install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
print_success "Docker instalado."
fi
# Adiciona o seu usuário ao grupo docker para não precisar de sudo no docker
usermod -aG docker "$DEPLOY_USER"
print_success "Usuário '$DEPLOY_USER' adicionado ao grupo Docker."
}
# --- EXECUÇÃO ---
main() {
[[ $EUID -ne 0 ]] && print_error "Execute como root."
check_user_exists
setup_base
setup_security_ssh
setup_kernel_hardening
setup_firewall
setup_docker
echo -e "\n${GREEN}==============================================${NC}"
echo -e " SETUP FINALIZADO PARA O USUÁRIO: $DEPLOY_USER"
echo -e " PORTA SSH: $SSH_PORT"
echo -e " DOCKER: PRONTO PARA USO"
echo -e "${GREEN}==============================================${NC}"
print_warning "IMPORTANTE: Antes de desconectar, tente abrir um novo terminal e logar:"
echo -e "ssh -p $SSH_PORT $DEPLOY_USER@$(curl -s ifconfig.me)"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment