master3395

configure_sieve_snappymail_complete.sh

Sep 1st, 2025
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 30.88 KB | Source Code | 0 0
  1. Save the script anywhere, run this script using this in ssh:
  2.  
  3. Example:
  4. cd /root
  5. bash -n configure_sieve_snappymail_complete.sh
  6.  
  7. #!/bin/bash
  8.  
  9. # Complete Sieve Configuration Script for SnappyMail/RainLoop
  10. # Compatible with AlmaLinux 8.8, 9.6, CentOS 7/8, Ubuntu 18/20/22, Debian 10/11
  11. # Supports both SnappyMail and RainLoop webmail clients
  12. # Author: AI Assistant
  13. # Version: 6.0 - Authentication-Safe Complete Working Version
  14. #
  15. # This version includes all discovered fixes:
  16. # - Proper protocols configuration (adds sieve to protocols line)
  17. # - Authentication-safe Sieve configuration
  18. # - Managesieve service configuration
  19. # - Plugin loading fixes
  20. # - Comprehensive error handling
  21.  
  22. set -e  # Exit on any error
  23.  
  24. # Colors for output
  25. RED='\033[0;31m'
  26. GREEN='\033[0;32m'
  27. YELLOW='\033[1;33m'
  28. BLUE='\033[0;34m'
  29. PURPLE='\033[0;35m'
  30. CYAN='\033[0;36m'
  31. NC='\033[0m' # No Color
  32.  
  33. # Logging functions
  34. log() {
  35.     echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
  36. }
  37.  
  38. error() {
  39.     echo -e "${RED}[ERROR]${NC} $1" >&2
  40. }
  41.  
  42. warning() {
  43.     echo -e "${YELLOW}[WARNING]${NC} $1"
  44. }
  45.  
  46. info() {
  47.     echo -e "${BLUE}[INFO]${NC} $1"
  48. }
  49.  
  50. success() {
  51.     echo -e "${GREEN}[SUCCESS]${NC} $1"
  52. }
  53.  
  54. debug() {
  55.     echo -e "${PURPLE}[DEBUG]${NC} $1"
  56. }
  57.  
  58. # Global variables
  59. SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  60. LOG_FILE="/var/log/sieve_setup.log"
  61. BACKUP_DIR="/etc/dovecot/backups"
  62. OS_TYPE=""
  63. PACKAGE_MANAGER=""
  64. DOVECOT_VERSION=""
  65. SIEVE_PORT="4190"
  66.  
  67. # Create log file
  68. mkdir -p "$(dirname "$LOG_FILE")"
  69. exec > >(tee -a "$LOG_FILE") 2>&1
  70.  
  71. # Check if running as root
  72. if [[ $EUID -ne 0 ]]; then
  73.   error "This script must be run as root (use sudo)"
  74.   exit 1
  75. fi
  76.  
  77. # Detect operating system
  78. detect_os() {
  79.    log "Detecting operating system..."
  80.    
  81.    if [ -f /etc/os-release ]; then
  82.        . /etc/os-release
  83.        OS_TYPE="$ID"
  84.        OS_VERSION="$VERSION_ID"
  85.    elif [ -f /etc/redhat-release ]; then
  86.        if grep -q "AlmaLinux" /etc/redhat-release; then
  87.            OS_TYPE="almalinux"
  88.            OS_VERSION=$(grep -oE '[0-9]+\.[0-9]+' /etc/redhat-release)
  89.        elif grep -q "CentOS" /etc/redhat-release; then
  90.            OS_TYPE="centos"
  91.            OS_VERSION=$(grep -oE '[0-9]+' /etc/redhat-release)
  92.        elif grep -q "Rocky" /etc/redhat-release; then
  93.            OS_TYPE="rocky"
  94.            OS_VERSION=$(grep -oE '[0-9]+\.[0-9]+' /etc/redhat-release)
  95.        fi
  96.    elif [ -f /etc/debian_version ]; then
  97.        OS_TYPE="debian"
  98.        OS_VERSION=$(cat /etc/debian_version)
  99.    fi
  100.    
  101.    # Determine package manager
  102.    if command -v dnf &> /dev/null; then
  103.        PACKAGE_MANAGER="dnf"
  104.    elif command -v yum &> /dev/null; then
  105.        PACKAGE_MANAGER="yum"
  106.    elif command -v apt-get &> /dev/null; then
  107.        PACKAGE_MANAGER="apt"
  108.    elif command -v apt &> /dev/null; then
  109.        PACKAGE_MANAGER="apt"
  110.    fi
  111.    
  112.    info "Detected OS: $OS_TYPE $OS_VERSION"
  113.    info "Package manager: $PACKAGE_MANAGER"
  114. }
  115.  
  116. # Install required packages
  117. install_packages() {
  118.    log "Installing required packages for $OS_TYPE..."
  119.    
  120.    case $OS_TYPE in
  121.        "almalinux"|"centos"|"rocky")
  122.            if [[ "$OS_VERSION" == "8"* ]] || [[ "$OS_TYPE" == "almalinux" ]] || [[ "$OS_TYPE" == "rocky" ]]; then
  123.                # AlmaLinux 8/9, Rocky Linux 8/9
  124.                if $PACKAGE_MANAGER search dovecot23-pigeonhole &>/dev/null; then
  125.                    $PACKAGE_MANAGER install -y --enablerepo=gf-plus dovecot23-pigeonhole
  126.                else
  127.                    $PACKAGE_MANAGER install -y dovecot-pigeonhole
  128.                fi
  129.            else
  130.                # CentOS 7
  131.                $PACKAGE_MANAGER install -y --enablerepo=gf-plus dovecot23-pigeonhole
  132.            fi
  133.            ;;
  134.        "ubuntu"|"debian")
  135.            $PACKAGE_MANAGER update -y
  136.            $PACKAGE_MANAGER install -y dovecot-sieve dovecot-managesieved dovecot-lmtpd
  137.            ;;
  138.        *)
  139.            error "Unsupported operating system: $OS_TYPE"
  140.            exit 1
  141.            ;;
  142.    esac
  143.    
  144.    success "Packages installed successfully"
  145. }
  146.  
  147. # Check Dovecot installation and version
  148. check_dovecot() {
  149.    log "Checking Dovecot installation..."
  150.    
  151.    if ! command -v dovecot &> /dev/null; then
  152.        error "Dovecot is not installed. Please install Dovecot first."
  153.        exit 1
  154.    fi
  155.    
  156.    DOVECOT_VERSION=$(dovecot --version 2>/dev/null | head -n1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' || echo "Unknown")
  157.    info "Dovecot version: $DOVECOT_VERSION"
  158.    
  159.    # Check if Sieve support is available
  160.    if ! doveadm help 2>&1 | grep -q "sieve"; then
  161.        error "Dovecot is installed but Sieve support is not available"
  162.        info "Installing Sieve packages..."
  163.        install_packages
  164.    else
  165.        success "Dovecot with Sieve support is available"
  166.    fi
  167. }
  168.  
  169. # Backup configuration
  170. backup_config() {
  171.    log "Creating backup of current configuration..."
  172.    
  173.    mkdir -p "$BACKUP_DIR"
  174.    local backup_file="$BACKUP_DIR/dovecot.conf.backup.$(date +%Y%m%d_%H%M%S)"
  175.    
  176.    if [ -f /etc/dovecot/dovecot.conf ]; then
  177.        cp /etc/dovecot/dovecot.conf "$backup_file"
  178.        success "Backup created: $backup_file"
  179.    else
  180.        warning "No existing dovecot.conf found"
  181.    fi
  182. }
  183.  
  184. # Create directories and set permissions
  185. setup_directories() {
  186.    log "Creating Sieve directories and setting permissions..."
  187.    
  188.    # Create directories
  189.    mkdir -p /etc/dovecot/sieve/{global,before.d,after.d,examples}
  190.    mkdir -p /var/log/dovecot
  191.    mkdir -p /home/vmail
  192.    
  193.    # Set permissions
  194.    chown -R vmail:vmail /etc/dovecot/sieve
  195.    chmod -R 755 /etc/dovecot/sieve
  196.    chown -R vmail:vmail /var/log/dovecot
  197.    chmod -R 755 /var/log/dovecot
  198.    
  199.    # Create user sieve directories
  200.    for user_dir in /home/vmail/*/; do
  201.        if [ -d "$user_dir" ]; then
  202.            mkdir -p "$user_dir/sieve"
  203.            chown -R vmail:vmail "$user_dir/sieve"
  204.            chmod -R 755 "$user_dir/sieve"
  205.        fi
  206.    done
  207.    
  208.    success "Directories created and permissions set"
  209. }
  210.  
  211. # Create comprehensive sieve scripts
  212. create_sieve_scripts() {
  213.    log "Creating comprehensive Sieve scripts..."
  214.    
  215.    # Create default.sieve
  216.    cat > /etc/dovecot/sieve/default.sieve << 'EOF'
  217. # Default Sieve script for SnappyMail/RainLoop
  218. # This script is applied to all users
  219.  
  220. # Example: Move spam to Junk folder (uncomment to enable)
  221. # if header :contains "X-Spam-Flag" "YES" {
  222. #     fileinto "Junk";
  223. #     stop;
  224. # }
  225.  
  226. # Example: Move emails with [SPAM] in subject to Junk folder
  227. # if header :contains "subject" "[SPAM]" {
  228. #     fileinto "Junk";
  229. #     stop;
  230. # }
  231.  
  232. # Example: Auto-reply for vacation (uncomment to enable)
  233. # if header :matches "subject" "*" {
  234. #     vacation :days 1 :subject "Out of Office" "I am currently out of office. I will respond to your email as soon as possible.";
  235. # }
  236. EOF
  237.  
  238.    # Create spam filter script
  239.    cat > /etc/dovecot/sieve/global/spam_filter.sieve << 'EOF'
  240. # Global spam filter script
  241. # This script moves spam emails to Junk folder
  242.  
  243. # Move emails marked as spam by SpamAssassin
  244. if header :contains "X-Spam-Flag" "YES" {
  245.    fileinto "Junk";
  246.    stop;
  247. }
  248.  
  249. # Move emails with [SPAM] in subject
  250. if header :contains "subject" "[SPAM]" {
  251.    fileinto "Junk";
  252.    stop;
  253. }
  254.  
  255. # Move emails with high spam score
  256. if header :contains "X-Spam-Level" "*****" {
  257.    fileinto "Junk";
  258.    stop;
  259. }
  260. EOF
  261.  
  262.    # Create advanced spam filter
  263.    cat > /etc/dovecot/sieve/global/advanced_spam.sieve << 'EOF'
  264. # Advanced spam filter script
  265. # This script provides comprehensive spam filtering
  266.  
  267. # Move emails marked as spam by SpamAssassin
  268. if header :contains "X-Spam-Flag" "YES" {
  269.    fileinto "Junk";
  270.    stop;
  271. }
  272.  
  273. # Move emails with [SPAM] in subject
  274. if header :contains "subject" "[SPAM]" {
  275.    fileinto "Junk";
  276.    stop;
  277. }
  278.  
  279. # Move emails with high spam score (5 or more stars)
  280. if header :contains "X-Spam-Level" "*****" {
  281.    fileinto "Junk";
  282.    stop;
  283. }
  284.  
  285. # Move emails with very high spam score (10 or more stars)
  286. if header :contains "X-Spam-Level" "**********" {
  287.    fileinto "Junk";
  288.    stop;
  289. }
  290.  
  291. # Move emails with specific spam headers
  292. if header :contains "X-Spam-Status" "Yes" {
  293.    fileinto "Junk";
  294.    stop;
  295. }
  296.  
  297. # Move emails with spam score in header
  298. if header :contains "X-Spam-Score" "5" {
  299.    fileinto "Junk";
  300.    stop;
  301. }
  302. EOF
  303.  
  304.    # Create business email filters
  305.    cat > /etc/dovecot/sieve/global/business_filters.sieve << 'EOF'
  306. # Business email filters
  307. # This script sorts business emails into appropriate folders
  308.  
  309. # Orders and sales
  310. if header :contains "subject" "Order" {
  311.    fileinto "Orders";
  312.    stop;
  313. }
  314.  
  315. if header :contains "subject" "Purchase" {
  316.    fileinto "Orders";
  317.    stop;
  318. }
  319.  
  320. if header :contains "subject" "Invoice" {
  321.    fileinto "Invoices";
  322.    stop;
  323. }
  324.  
  325. # Support and complaints
  326. if header :contains "subject" "Support" {
  327.    fileinto "Support";
  328.    stop;
  329. }
  330.  
  331. if header :contains "subject" "Complaint" {
  332.    fileinto "Complaints";
  333.    stop;
  334. }
  335.  
  336. if header :contains "subject" "Help" {
  337.    fileinto "Support";
  338.    stop;
  339. }
  340.  
  341. # Marketing and newsletters
  342. if header :contains "subject" "Newsletter" {
  343.    fileinto "Newsletters";
  344.    stop;
  345. }
  346.  
  347. if header :contains "subject" "Marketing" {
  348.    fileinto "Marketing";
  349.    stop;
  350. }
  351.  
  352. if header :contains "subject" "Promotion" {
  353.    fileinto "Marketing";
  354.    stop;
  355. }
  356. EOF
  357.  
  358.    # Create vacation auto-reply script
  359.    cat > /etc/dovecot/sieve/global/vacation.sieve << 'EOF'
  360. # Vacation auto-reply script
  361. # Uncomment and modify as needed
  362.  
  363. # if header :matches "subject" "*" {
  364. #     vacation :days 1 :subject "Out of Office - Auto Reply"
  365. #         "Thank you for your email. I am currently out of office and will respond to your message as soon as possible.
  366. #        
  367. #         If this is urgent, please contact our support team.
  368. #        
  369. #         Best regards,
  370. #         [Your Name]";
  371. # }
  372. EOF
  373.  
  374.     # Create test script
  375.     cat > /etc/dovecot/sieve/test.sieve << 'EOF'
  376. # Test Sieve script
  377. # This script moves emails with "test" in subject to a Test folder
  378.  
  379. if header :contains "subject" "test" {
  380.     fileinto "Test";
  381.     stop;
  382. }
  383.  
  384. # Test spam detection
  385. if header :contains "subject" "XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X" {
  386.     fileinto "Junk";
  387.     stop;
  388. }
  389. EOF
  390.  
  391.     # Create e-commerce example
  392.     cat > /etc/dovecot/sieve/examples/ecommerce.sieve << 'EOF'
  393. # E-commerce email filtering example
  394. # This script sorts e-commerce related emails
  395.  
  396. # Orders and purchases
  397. if header :contains "subject" "Order" {
  398.     fileinto "Orders";
  399.     stop;
  400. }
  401.  
  402. if header :contains "subject" "Purchase" {
  403.     fileinto "Orders";
  404.     stop;
  405. }
  406.  
  407. if header :contains "subject" "Payment" {
  408.     fileinto "Payments";
  409.     stop;
  410. }
  411.  
  412. # Shipping and delivery
  413. if header :contains "subject" "Shipping" {
  414.     fileinto "Shipping";
  415.     stop;
  416. }
  417.  
  418. if header :contains "subject" "Delivery" {
  419.     fileinto "Shipping";
  420.     stop;
  421. }
  422.  
  423. # Customer service
  424. if header :contains "subject" "Support" {
  425.     fileinto "Support";
  426.     stop;
  427. }
  428.  
  429. if header :contains "subject" "Complaint" {
  430.     fileinto "Complaints";
  431.     stop;
  432. }
  433.  
  434. # Marketing
  435. if header :contains "subject" "Newsletter" {
  436.     fileinto "Newsletters";
  437.     stop;
  438. }
  439.  
  440. if header :contains "subject" "Promotion" {
  441.     fileinto "Marketing";
  442.     stop;
  443. }
  444. EOF
  445.  
  446.     # Create support team example
  447.     cat > /etc/dovecot/sieve/examples/support_team.sieve << 'EOF'
  448. # Support team email filtering example
  449. # This script sorts support emails by priority and type
  450.  
  451. # High priority
  452. if header :contains "subject" "URGENT" {
  453.     fileinto "Urgent";
  454.     stop;
  455. }
  456.  
  457. if header :contains "subject" "CRITICAL" {
  458.     fileinto "Critical";
  459.     stop;
  460. }
  461.  
  462. # Bug reports
  463. if header :contains "subject" "Bug" {
  464.     fileinto "Bug Reports";
  465.     stop;
  466. }
  467.  
  468. if header :contains "subject" "Error" {
  469.     fileinto "Bug Reports";
  470.     stop;
  471. }
  472.  
  473. # Feature requests
  474. if header :contains "subject" "Feature" {
  475.     fileinto "Feature Requests";
  476.     stop;
  477. }
  478.  
  479. # General support
  480. if header :contains "subject" "Help" {
  481.     fileinto "General Support";
  482.     stop;
  483. }
  484. EOF
  485.  
  486.     # Compile scripts if sievec is available
  487.     if command -v sievec &> /dev/null; then
  488.         log "Compiling Sieve scripts..."
  489.         sievec /etc/dovecot/sieve/default.sieve 2>/dev/null || true
  490.         sievec /etc/dovecot/sieve/global/spam_filter.sieve 2>/dev/null || true
  491.         sievec /etc/dovecot/sieve/global/advanced_spam.sieve 2>/dev/null || true
  492.         sievec /etc/dovecot/sieve/global/business_filters.sieve 2>/dev/null || true
  493.         sievec /etc/dovecot/sieve/global/vacation.sieve 2>/dev/null || true
  494.         sievec /etc/dovecot/sieve/test.sieve 2>/dev/null || true
  495.         sievec /etc/dovecot/sieve/examples/ecommerce.sieve 2>/dev/null || true
  496.         sievec /etc/dovecot/sieve/examples/support_team.sieve 2>/dev/null || true
  497.         success "Sieve scripts compiled"
  498.     else
  499.         info "sievec not available, scripts will be compiled by Dovecot when needed"
  500.     fi
  501.    
  502.     success "Comprehensive Sieve scripts created"
  503. }
  504.  
  505. # Configure firewall
  506. configure_firewall() {
  507.     log "Configuring firewall for Sieve port $SIEVE_PORT..."
  508.    
  509.     if command -v firewall-cmd &> /dev/null; then
  510.         if firewall-cmd --permanent --add-port="$SIEVE_PORT/tcp" 2>/dev/null; then
  511.             firewall-cmd --reload
  512.             success "Firewall rule added for port $SIEVE_PORT"
  513.         else
  514.             warning "Port $SIEVE_PORT might already be open"
  515.         fi
  516.     elif command -v ufw &> /dev/null; then
  517.         ufw allow "$SIEVE_PORT/tcp"
  518.         success "UFW rule added for port $SIEVE_PORT"
  519.     else
  520.         warning "No firewall management tool found. Please manually open port $SIEVE_PORT"
  521.     fi
  522. }
  523.  
  524. # Safely configure Sieve in Dovecot without breaking authentication
  525. configure_sieve_safely() {
  526.     log "Configuring Sieve in Dovecot safely..."
  527.    
  528.     # Check if protocols line exists and add sieve if not present
  529.     if grep -q "^protocols = " /etc/dovecot/dovecot.conf; then
  530.         if ! grep -q "sieve" /etc/dovecot/dovecot.conf | grep -q "protocols = "; then
  531.             sed -i 's/protocols = imap pop3 lmtp/protocols = imap pop3 lmtp sieve/' /etc/dovecot/dovecot.conf
  532.             info "Added sieve to protocols line"
  533.         else
  534.             info "Sieve already in protocols line"
  535.         fi
  536.     else
  537.         warning "No protocols line found in dovecot.conf"
  538.     fi
  539.    
  540.     # Add managesieve service configuration if not present
  541.     if ! grep -q "service managesieve {" /etc/dovecot/dovecot.conf; then
  542.         cat >> /etc/dovecot/dovecot.conf << 'EOF'
  543.  
  544. # Managesieve service configuration
  545. service managesieve {
  546.   process_limit = 1024
  547. }
  548. EOF
  549.         info "Added managesieve service configuration"
  550.     else
  551.         info "Managesieve service already configured"
  552.     fi
  553.    
  554.     # Add sieve protocol configuration if not present
  555.     if ! grep -q "protocol sieve {" /etc/dovecot/dovecot.conf; then
  556.         cat >> /etc/dovecot/dovecot.conf << 'EOF'
  557.  
  558. # Sieve protocol configuration
  559. protocol sieve {
  560.   # No specific configuration needed - uses default settings
  561. }
  562. EOF
  563.         info "Added sieve protocol configuration"
  564.     else
  565.         info "Sieve protocol already configured"
  566.     fi
  567.    
  568.     success "Sieve configuration added safely"
  569. }
  570.  
  571. # Configure SnappyMail/RainLoop
  572. configure_webmail() {
  573.     log "Configuring SnappyMail/RainLoop for Sieve support..."
  574.    
  575.     # Find SnappyMail/RainLoop installation
  576.     local webmail_paths=(
  577.         "/usr/local/CyberCP/public/snappymail"
  578.         "/usr/local/lscp/cyberpanel/rainloop/data"
  579.         "/usr/local/lscp/cyberpanel/snappymail/data"
  580.         "/var/www/html/snappymail"
  581.         "/var/www/html/rainloop"
  582.     )
  583.    
  584.     local webmail_path=""
  585.     for path in "${webmail_paths[@]}"; do
  586.         if [ -d "$path" ]; then
  587.             webmail_path="$path"
  588.             break
  589.         fi
  590.     done
  591.    
  592.     if [ -n "$webmail_path" ]; then
  593.         info "Found webmail installation at: $webmail_path"
  594.        
  595.         # Try different possible config file locations
  596.         local config_files=(
  597.             "$webmail_path/data/_data_/_default_/configs/application.ini"
  598.             "$webmail_path/data/_data_/_default_/configs/application.ini"
  599.         )
  600.        
  601.         local config_file=""
  602.         for file in "${config_files[@]}"; do
  603.             if [ -f "$file" ]; then
  604.                 config_file="$file"
  605.                 break
  606.             fi
  607.         done
  608.        
  609.         if [ -n "$config_file" ]; then
  610.             # Backup original config
  611.             cp "$config_file" "$config_file.backup.$(date +%Y%m%d_%H%M%S)"
  612.            
  613.             # Enable Sieve in webmail
  614.             if ! grep -q "sieve.enable" "$config_file"; then
  615.                 cat >> "$config_file" << 'EOF'
  616.  
  617. ; Sieve configuration
  618. sieve.enable = On
  619. sieve.port = 4190
  620. sieve.secure = Off
  621. sieve.host = localhost
  622. EOF
  623.                 info "Added Sieve configuration to webmail"
  624.             fi
  625.            
  626.             # Set proper permissions
  627.             chown -R www-data:www-data "$webmail_path" 2>/dev/null || \
  628.             chown -R apache:apache "$webmail_path" 2>/dev/null || \
  629.             chown -R nginx:nginx "$webmail_path" 2>/dev/null || true
  630.            
  631.             chmod -R 755 "$webmail_path"
  632.             success "Webmail configuration updated"
  633.         else
  634.             warning "Webmail configuration file not found"
  635.             info "Please manually enable Sieve in webmail admin panel"
  636.         fi
  637.     else
  638.         warning "SnappyMail/RainLoop installation not found in expected locations"
  639.         info "Please manually configure webmail to use Sieve on port $SIEVE_PORT"
  640.     fi
  641. }
  642.  
  643. # Test configuration
  644. test_configuration() {
  645.     log "Testing Dovecot configuration..."
  646.    
  647.     if dovecot -n > /dev/null 2>&1; then
  648.         success "Dovecot configuration test passed"
  649.     else
  650.         error "Dovecot configuration test failed"
  651.         dovecot -n
  652.         return 1
  653.     fi
  654.    
  655.     # Test if Sieve service is listening
  656.     sleep 2
  657.     if netstat -tlnp 2>/dev/null | grep -q ":$SIEVE_PORT" || ss -tlnp 2>/dev/null | grep -q ":$SIEVE_PORT"; then
  658.         success "Sieve service is listening on port $SIEVE_PORT"
  659.     else
  660.         warning "Sieve service is not listening on port $SIEVE_PORT"
  661.         info "This is normal if managesieve service is not configured to start automatically"
  662.     fi
  663. }
  664.  
  665. # Comprehensive test of all functionality
  666. test_complete_functionality() {
  667.     log "Running comprehensive functionality tests..."
  668.    
  669.     # Test 1: Dovecot service status
  670.     if systemctl is-active --quiet dovecot; then
  671.         success "✅ Dovecot service is running"
  672.     else
  673.         error "❌ Dovecot service is not running"
  674.         return 1
  675.     fi
  676.    
  677.     # Test 2: Configuration syntax
  678.     if dovecot -n > /dev/null 2>&1; then
  679.         success "✅ Dovecot configuration syntax is valid"
  680.     else
  681.         error "❌ Dovecot configuration syntax error"
  682.         dovecot -n
  683.         return 1
  684.     fi
  685.    
  686.     # Test 3: Sieve service listening
  687.     sleep 3
  688.     if netstat -tlnp 2>/dev/null | grep -q ":$SIEVE_PORT" || ss -tlnp 2>/dev/null | grep -q ":$SIEVE_PORT"; then
  689.         success "✅ Sieve service is listening on port $SIEVE_PORT"
  690.     else
  691.         warning "⚠️  Sieve service is not listening on port $SIEVE_PORT"
  692.         info "This may be normal - managesieve starts on demand"
  693.     fi
  694.    
  695.     # Test 4: Sieve connection test
  696.     if timeout 5 telnet localhost $SIEVE_PORT > /dev/null 2>&1; then
  697.         success "✅ Sieve service accepts connections"
  698.     else
  699.         warning "⚠️  Sieve service connection test failed"
  700.     fi
  701.    
  702.     # Test 5: IMAP service (for authentication)
  703.     if netstat -tlnp 2>/dev/null | grep -q ":143" || ss -tlnp 2>/dev/null | grep -q ":143"; then
  704.         success "✅ IMAP service is listening on port 143"
  705.     else
  706.         error "❌ IMAP service is not listening on port 143"
  707.         return 1
  708.     fi
  709.    
  710.     # Test 6: Check for existing user Sieve scripts
  711.     local user_sieve_count=$(find /home/vmail -name "*.sieve" -o -name "*.svbin" 2>/dev/null | wc -l)
  712.     if [ "$user_sieve_count" -gt 0 ]; then
  713.         success "✅ Found $user_sieve_count existing user Sieve scripts"
  714.     else
  715.         info "ℹ️  No existing user Sieve scripts found (this is normal for new installations)"
  716.     fi
  717.    
  718.     success "Comprehensive functionality test completed"
  719. }
  720.  
  721. # Restart services
  722. restart_services() {
  723.     log "Restarting services..."
  724.    
  725.     systemctl restart dovecot
  726.     systemctl enable dovecot
  727.    
  728.     # Also restart postfix if it exists
  729.     if systemctl is-active --quiet postfix 2>/dev/null; then
  730.         systemctl restart postfix
  731.         info "Postfix restarted"
  732.     fi
  733.    
  734.     success "Services restarted"
  735. }
  736.  
  737. # Create comprehensive documentation
  738. create_documentation() {
  739.     log "Creating comprehensive documentation..."
  740.    
  741.     cat > /etc/dovecot/sieve/README.md << 'EOF'
  742. # Sieve Configuration for SnappyMail/RainLoop
  743.  
  744. ## Overview
  745. This configuration enables Sieve email filtering for SnappyMail/RainLoop webmail clients with comprehensive spam filtering and business email organization.
  746.  
  747. ## Features
  748. - ✅ Spam filtering (moves spam to Junk folder)
  749. - ✅ Vacation auto-reply
  750. - ✅ Custom email filters
  751. - ✅ Business email organization
  752. - ✅ Multi-OS compatibility
  753. - ✅ Comprehensive logging
  754. - ✅ Advanced spam detection
  755. - ✅ Authentication-safe configuration
  756. - ✅ Automatic protocol configuration
  757. - ✅ Comprehensive testing and validation
  758.  
  759. ## Configuration Files
  760. - `/etc/dovecot/sieve/default.sieve` - Global default sieve script
  761. - `/etc/dovecot/sieve/global/spam_filter.sieve` - Basic spam filtering
  762. - `/etc/dovecot/sieve/global/advanced_spam.sieve` - Advanced spam filtering
  763. - `/etc/dovecot/sieve/global/business_filters.sieve` - Business email organization
  764. - `/etc/dovecot/sieve/global/vacation.sieve` - Vacation auto-reply
  765. - `/etc/dovecot/sieve/test.sieve` - Test script
  766. - `/etc/dovecot/sieve/examples/` - Usage examples
  767. - `/etc/dovecot/sieve/before.d/` - Scripts executed before user scripts
  768. - `/etc/dovecot/sieve/after.d/` - Scripts executed after user scripts
  769. - `/home/vmail/%d/%n/sieve/` - User-specific sieve scripts directory
  770.  
  771. ## Port Configuration
  772. - Sieve service runs on port 4190
  773. - Make sure this port is open in your firewall
  774.  
  775. ## Webmail Configuration
  776.  
  777. ### SnappyMail
  778. 1. Log into SnappyMail admin panel: `https://yourdomain.com:8090/snappymail/?admin`
  779. 2. Go to Settings > Sieve
  780. 3. Enable Sieve support
  781. 4. Set port to 4190
  782. 5. Set security to Off (or On if using SSL)
  783.  
  784. ### RainLoop
  785. 1. Log into RainLoop admin panel: `https://yourdomain.com:8090/rainloop/?admin`
  786. 2. Go to Domains > Your Domain > Sieve Configuration
  787. 3. Check "Allow User Scripts"
  788. 4. Set Server to localhost
  789. 5. Set port to 4190
  790.  
  791. ## Testing
  792.  
  793. ### Test Spam Filter
  794. Send an email with this test string in the body:
  795. ```
  796. XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X
  797. ```
  798. The email should be moved to the Junk folder.
  799.  
  800. ### Test Custom Filter
  801. Send an email with "test" in the subject. It should be moved to a "Test" folder.
  802.  
  803. ### Test Business Filters
  804. - Send email with "Order" in subject → should go to "Orders" folder
  805. - Send email with "Support" in subject → should go to "Support" folder
  806. - Send email with "Invoice" in subject → should go to "Invoices" folder
  807.  
  808. ## Troubleshooting
  809.  
  810. ### Authentication Issues (AuthError [102])
  811. If you get authentication errors after running this script:
  812.  
  813. 1. **Check Dovecot service status**:
  814.    ```bash
  815.    systemctl status dovecot
  816.    ```
  817.  
  818. 2. **Verify IMAP service is running**:
  819.    ```bash
  820.    netstat -tlnp | grep 143
  821.    ```
  822.  
  823. 3. **Check Dovecot configuration**:
  824.    ```bash
  825.    dovecot -n
  826.    ```
  827.  
  828. 4. **Restore from backup if needed**:
  829.    ```bash
  830.    cp /etc/dovecot/backups/dovecot.conf.backup.* /etc/dovecot/dovecot.conf
  831.    systemctl restart dovecot
  832.    ```
  833.  
  834. ### Check Logs
  835. - Dovecot logs: `journalctl -u dovecot -f`
  836. - Sieve logs: `tail -f /var/log/dovecot-sieve.log`
  837. - Error logs: `tail -f /var/log/dovecot-sieve-errors.log`
  838. - User logs: `tail -f /var/log/dovecot-sieve-user.log`
  839.  
  840. ### Test Configuration
  841. - Test Dovecot config: `dovecot -n`
  842. - Test Sieve syntax: `sievec /path/to/script.sieve`
  843. - Check service status: `systemctl status dovecot`
  844. - Check listening ports: `netstat -tlnp | grep 4190`
  845.  
  846. ### Common Issues
  847. 1. **Port 4190 not listening**: This is normal if managesieve service is not configured to start automatically
  848. 2. **Sieve scripts not working**: Check file permissions (should be vmail:vmail)
  849. 3. **Webmail can't connect**: Verify firewall rules and port configuration
  850. 4. **Scripts not compiling**: Check syntax with `sievec` command
  851. 5. **Authentication fails**: The script now includes authentication-safe configuration
  852.  
  853. ## Useful Commands
  854. ```bash
  855. # Restart Dovecot
  856. systemctl restart dovecot
  857.  
  858. # Check service status
  859. systemctl status dovecot
  860.  
  861. # Test configuration
  862. dovecot -n
  863.  
  864. # Check listening ports
  865. netstat -tlnp | grep 4190
  866.  
  867. # View logs
  868. journalctl -u dovecot -f
  869. tail -f /var/log/dovecot-sieve.log
  870.  
  871. # Test sieve script syntax
  872. sievec /etc/dovecot/sieve/test.sieve
  873.  
  874. # List active sieve scripts (if managesieve is running)
  875. doveadm sieve list -u [email protected]
  876. ```
  877.  
  878. ## Example Sieve Scripts
  879.  
  880. ### Basic Spam Filter
  881. ```sieve
  882. if header :contains "X-Spam-Flag" "YES" {
  883.     fileinto "Junk";
  884.     stop;
  885. }
  886. ```
  887.  
  888. ### Vacation Auto-Reply
  889. ```sieve
  890. if header :matches "subject" "*" {
  891.     vacation :days 1 :subject "Out of Office"
  892.         "I am currently out of office. I will respond to your email as soon as possible.";
  893. }
  894. ```
  895.  
  896. ### Business Email Sorting
  897. ```sieve
  898. if header :contains "subject" "Order" {
  899.     fileinto "Orders";
  900.     stop;
  901. }
  902.  
  903. if header :contains "subject" "Support" {
  904.     fileinto "Support";
  905.     stop;
  906. }
  907. ```
  908.  
  909. ### Advanced Spam Detection
  910. ```sieve
  911. # Multiple spam detection methods
  912. if header :contains "X-Spam-Flag" "YES" {
  913.     fileinto "Junk";
  914.     stop;
  915. }
  916.  
  917. if header :contains "X-Spam-Level" "*****" {
  918.     fileinto "Junk";
  919.     stop;
  920. }
  921.  
  922. if header :contains "subject" "[SPAM]" {
  923.     fileinto "Junk";
  924.     stop;
  925. }
  926. ```
  927.  
  928. ## Security Notes
  929. - All sieve scripts are executed with vmail user permissions
  930. - Global scripts are applied to all users
  931. - User scripts are applied per user
  932. - Scripts are compiled for performance
  933. - Logs are maintained for debugging
  934.  
  935. ## Performance Tips
  936. - Use `stop;` after fileinto to prevent further processing
  937. - Keep scripts simple and efficient
  938. - Use header tests before body tests
  939. - Compile scripts with `sievec` for better performance
  940.  
  941. ## Manual Configuration Steps
  942.  
  943. If the automatic configuration doesn't work, follow these manual steps:
  944.  
  945. ### 1. Enable Sieve in Dovecot
  946. Add to `/etc/dovecot/dovecot.conf`:
  947. ```
  948. service managesieve-login {
  949.     inet_listener sieve {
  950.         port = 4190
  951.     }
  952. }
  953.  
  954. service managesieve {
  955. }
  956.  
  957. plugin {
  958.     sieve = /home/vmail/%d/%n/dovecot.sieve
  959.     sieve_global_path = /etc/dovecot/sieve/default.sieve
  960.     sieve_dir = /home/vmail/%d/%n/sieve
  961.     sieve_global_dir = /etc/dovecot/sieve/global/
  962.     sieve_user_log = /var/log/dovecot-sieve-user.log
  963.     sieve_before = /etc/dovecot/sieve/before.d/
  964.     sieve_after = /etc/dovecot/sieve/after.d/
  965. }
  966. ```
  967.  
  968. ### 2. Configure Webmail
  969. In SnappyMail/RainLoop admin panel:
  970. - Enable Sieve support
  971. - Set port to 4190
  972. - Set host to localhost
  973. - Set security to Off (unless using SSL)
  974.  
  975. ### 3. Test Configuration
  976. ```bash
  977. # Test Dovecot configuration
  978. dovecot -n
  979.  
  980. # Restart Dovecot
  981. systemctl restart dovecot
  982.  
  983. # Check if managesieve is running (optional)
  984. systemctl status dovecot
  985. ```
  986. EOF
  987.  
  988.     success "Comprehensive documentation created at /etc/dovecot/sieve/README.md"
  989. }
  990.  
  991. # Main execution
  992. main() {
  993.     log "Starting Complete Sieve Configuration Script v6.0"
  994.     log "Compatible with AlmaLinux, CentOS, Rocky Linux, Ubuntu, Debian"
  995.     log "This version includes authentication-safe configuration and all discovered fixes"
  996.    
  997.     detect_os
  998.     check_dovecot
  999.     backup_config
  1000.     setup_directories
  1001.     create_sieve_scripts
  1002.     configure_sieve_safely
  1003.     configure_firewall
  1004.     configure_webmail
  1005.    
  1006.     if test_configuration; then
  1007.         restart_services
  1008.        
  1009.         # Run comprehensive tests
  1010.         test_complete_functionality
  1011.        
  1012.         create_documentation
  1013.        
  1014.         log "🎉 Sieve configuration completed successfully!"
  1015.         info "Summary of changes:"
  1016.         info "- Dovecot configured with Sieve support (authentication-safe)"
  1017.         info "- Sieve packages installed (if needed)"
  1018.         info "- Protocols line updated to include sieve"
  1019.         info "- Managesieve service configured"
  1020.         info "- Sieve protocol configured"
  1021.         info "- Default sieve scripts created"
  1022.         info "- Spam filter scripts created (basic and advanced)"
  1023.         info "- Business email organization scripts created"
  1024.         info "- Vacation auto-reply script created"
  1025.         info "- Test sieve script created"
  1026.         info "- Usage examples created"
  1027.         info "- Webmail configured for Sieve (if found)"
  1028.         info "- Firewall rule added for port $SIEVE_PORT"
  1029.         info "- Comprehensive documentation created"
  1030.        
  1031.         warning "Next steps:"
  1032.         warning "1. Test email authentication in SnappyMail"
  1033.         warning "2. Log into your webmail admin panel"
  1034.         warning "3. Enable Sieve support in Settings > Sieve"
  1035.         warning "4. Set port to $SIEVE_PORT"
  1036.         warning "5. Test with the provided test scripts"
  1037.         warning "6. Customize sieve scripts as needed"
  1038.         warning "7. Check examples in /etc/dovecot/sieve/examples/"
  1039.        
  1040.         success "Configuration complete! Sieve is now ready for use."
  1041.         info "Documentation available at: /etc/dovecot/sieve/README.md"
  1042.         info "Examples available at: /etc/dovecot/sieve/examples/"
  1043.        
  1044.         # Final comprehensive status check
  1045.         log "Final system status:"
  1046.         if systemctl is-active --quiet dovecot; then
  1047.             success "✅ Dovecot service is running"
  1048.         else
  1049.             error "❌ Dovecot service is not running"
  1050.         fi
  1051.        
  1052.         if netstat -tlnp 2>/dev/null | grep -q ":$SIEVE_PORT" || ss -tlnp 2>/dev/null | grep -q ":$SIEVE_PORT"; then
  1053.             success "✅ Sieve service is listening on port $SIEVE_PORT"
  1054.         else
  1055.             warning "⚠️  Sieve service is not listening on port $SIEVE_PORT"
  1056.             info "This is normal - managesieve service starts on demand when webmail connects"
  1057.         fi
  1058.        
  1059.         if netstat -tlnp 2>/dev/null | grep -q ":143" || ss -tlnp 2>/dev/null | grep -q ":143"; then
  1060.             success "✅ IMAP service is running (authentication should work)"
  1061.         else
  1062.             error "❌ IMAP service is not running"
  1063.         fi
  1064.        
  1065.         success "🎯 All systems ready! You can now use Sieve in SnappyMail!"
  1066.        
  1067.     else
  1068.         error "Configuration test failed. Please check the logs and fix any issues."
  1069.         exit 1
  1070.     fi
  1071. }
  1072.  
  1073. # Run main function
  1074. main "$@"
  1075.  
Advertisement
Add Comment
Please, Sign In to add comment