#!/bin/bash
# ============================================================
# Scan-Ziel: Debian - Maximale Dienste für nmap Service/TLS-Detection
# Voraussetzung: /etc/ssl/own.key + /etc/ssl/own.crt vorhanden
# ============================================================
set -e

KEY=/etc/ssl/own.key
CRT=/etc/ssl/own.crt

if [[ ! -f "$KEY" || ! -f "$CRT" ]]; then
    echo "FEHLER: $KEY oder $CRT nicht gefunden. Abbruch."
    exit 1
fi

export DEBIAN_FRONTEND=noninteractive
apt-get update -y

# ============================================================
# PAKETE
# ============================================================
apt-get install -y \
    apache2 \
    nginx \
    openssh-server \
    dovecot-imapd dovecot-pop3d \
    postfix \
    inetutils-telnetd \
    fingerd \
    xinetd \
    samba \
    proftpd-basic \
    nfs-kernel-server \
    rsync \
    snmpd \
    squid \
    stunnel4 \
    mariadb-server \
    postgresql \
    redis-server \
    cups \
    inn2 \
    slapd ldap-utils \
    xrdp \
    ircd-ircu \
    tftpd-hpa \
    ident2 \
    ncat \
    bind9 bind9-utils \
    2>/dev/null || true

# ============================================================
# APACHE2 - HTTP :8081 + HTTPS :8444
# (nginx belegt 8080/8443, apache bekommt eigene Ports)
# ============================================================
a2enmod ssl >/dev/null 2>&1
sed -i 's/^Listen 80$/Listen 8081/' /etc/apache2/ports.conf
sed -i 's/^Listen 443$/#Listen 443/' /etc/apache2/ports.conf
cat > /etc/apache2/sites-available/000-default.conf <<EOF
<VirtualHost *:8081>
    ServerName localhost
    DocumentRoot /var/www/html
</VirtualHost>
EOF
cat > /etc/apache2/sites-available/tls.conf <<EOF
<VirtualHost *:8444>
    ServerName localhost
    SSLEngine on
    SSLCertificateFile    $CRT
    SSLCertificateKeyFile $KEY
    DocumentRoot /var/www/html
</VirtualHost>
EOF
echo "Listen 8444" >> /etc/apache2/ports.conf
a2ensite tls.conf >/dev/null 2>&1
systemctl enable apache2 && systemctl restart apache2 || true

# ============================================================
# NGINX - HTTP :8080 + HTTPS :8443
# ============================================================
cat > /etc/nginx/sites-available/scanlab <<EOF
server {
    listen 8080;
    server_name localhost;
    root /var/www/html;
}
server {
    listen 8443 ssl;
    server_name localhost;
    ssl_certificate     $CRT;
    ssl_certificate_key $KEY;
    root /var/www/html;
}
EOF
ln -sf /etc/nginx/sites-available/scanlab /etc/nginx/sites-enabled/scanlab
rm -f /etc/nginx/sites-enabled/default
systemctl enable nginx && systemctl restart nginx || true

# ============================================================
# PROFTPD - FTP :21 + STARTTLS
# ============================================================
cat > /etc/proftpd/proftpd.conf <<'EOF'
ServerName "ProFTPD Scanlab"
ServerType standalone
DefaultServer on
Port 21

<Anonymous /var/ftp>
  User ftp
  Group nogroup
  UserAlias anonymous ftp
  MaxClients 10
</Anonymous>

<IfModule mod_tls.c>
  TLSEngine on
  TLSLog /var/log/proftpd/tls.log
  TLSProtocol SSLv23
  TLSCertificateFile /etc/ssl/own.crt
  TLSCertificateKeyFile /etc/ssl/own.key
  TLSOptions NoCertRequest
  TLSVerifyClient off
  TLSRequired off
</IfModule>
EOF
systemctl enable proftpd && systemctl restart proftpd || true

# ============================================================
# SSH - :22
# ============================================================
systemctl enable ssh && systemctl restart ssh || true

# ============================================================
# DOVECOT - IMAP :143 + IMAPS :993 + POP3 :110 + POP3S :995
# ============================================================
cat > /etc/dovecot/conf.d/10-ssl.conf <<EOF
ssl = yes
ssl_cert = <$CRT
ssl_key = <$KEY
EOF
cat > /etc/dovecot/conf.d/10-master.conf <<'EOF'
service imap-login {
  inet_listener imap { port = 143 }
  inet_listener imaps { port = 993 ssl = yes }
}
service pop3-login {
  inet_listener pop3 { port = 110 }
  inet_listener pop3s { port = 995 ssl = yes }
}
EOF
cat > /etc/dovecot/conf.d/10-auth.conf <<'EOF'
disable_plaintext_auth = no
auth_mechanisms = plain login
EOF
systemctl enable dovecot && systemctl restart dovecot || true

# ============================================================
# POSTFIX - SMTP :25 + Submission :587 STARTTLS + SMTPS :465
# ============================================================
cat >> /etc/postfix/main.cf <<EOF

# TLS
smtpd_tls_cert_file=$CRT
smtpd_tls_key_file=$KEY
smtpd_use_tls=yes
smtpd_tls_security_level=may
smtp_tls_security_level=may
EOF
cat >> /etc/postfix/master.cf <<'EOF'
587       inet  n       -       y       -       -       smtpd
  -o syslog_name=postfix/submission
  -o smtpd_tls_security_level=encrypt
465       inet  n       -       y       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes
EOF
systemctl enable postfix && systemctl restart postfix || true

# ============================================================
# XINETD - Telnet :23, Finger :79, Time :37
# ============================================================

# Telnet - inetutils-telnetd legt Binary unter /usr/sbin/telnetd ab
cat > /etc/xinetd.d/telnet <<'EOF'
service telnet
{
    flags           = REUSE
    socket_type     = stream
    wait            = no
    user            = root
    server          = /usr/sbin/telnetd
    log_on_failure  += USERID
    disable         = no
}
EOF

# Finger - fingerd-Paket
FINGERD_BIN=$(find /usr -name "fingerd" 2>/dev/null | head -1)
if [[ -z "$FINGERD_BIN" ]]; then
    FINGERD_BIN="/usr/sbin/fingerd"
fi
cat > /etc/xinetd.d/finger <<EOF
service finger
{
    socket_type = stream
    wait        = no
    user        = nobody
    server      = $FINGERD_BIN
    disable     = no
}
EOF

# Time :37 (interner xinetd-Dienst, kein externes Binary nötig)
cat > /etc/xinetd.d/time <<'EOF'
service time
{
    type        = INTERNAL
    id          = time-stream
    socket_type = stream
    protocol    = tcp
    wait        = no
    disable     = no
}
EOF

systemctl enable xinetd && systemctl restart xinetd || true

# ============================================================
# STUNNEL4 - TLS-Wrapper für diverse Dienste
# ============================================================
cat > /etc/stunnel/stunnel.conf <<EOF
cert = $CRT
key  = $KEY
sslVersion = all
options = NO_SSLv2
options = NO_SSLv3

; FTPS implicit :990 -> proftpd :21
[ftps]
accept  = 990
connect = 21

; LDAPS :636 -> slapd :389
[ldaps]
accept  = 636
connect = 389

; MySQL/TLS :3307 -> :3306
[mysqls]
accept  = 3307
connect = 3306

; Redis/TLS :6380 -> :6379
[rediss]
accept  = 6380
connect = 6379

; NNTPS :563 -> inn2 :119
[nntps]
accept  = 563
connect = 119

; Telnet/TLS :992 -> :23
[telnets]
accept  = 992
connect = 23

; Rsync/TLS :8730 -> :873
[rsyncs]
accept  = 8730
connect = 873
EOF
cat > /etc/default/stunnel4 <<'EOF'
ENABLED=1
OPTIONS=""
EOF
systemctl enable stunnel4 && systemctl restart stunnel4 || true

# ============================================================
# SAMBA - SMB :445 + NetBIOS :137/138/139
# ============================================================
cat > /etc/samba/smb.conf <<EOF
[global]
   workgroup = SCANLAB
   server string = Samba Scanlab
   security = user
   map to guest = Bad User
[public]
   path = /tmp
   guest ok = yes
   read only = yes
EOF
systemctl enable smbd nmbd && systemctl restart smbd nmbd || true

# ============================================================
# SNMP - :161 UDP
# ============================================================
cat > /etc/snmp/snmpd.conf <<EOF
rocommunity public
agentAddress udp:161
sysDescr Scanlab Debian
EOF
systemctl enable snmpd && systemctl restart snmpd || true

# ============================================================
# SQUID HTTP-Proxy - :3128
# ============================================================
cat >> /etc/squid/squid.conf <<'EOF'
http_access allow all
EOF
systemctl enable squid && systemctl restart squid || true

# ============================================================
# MARIADB - :3306 auf alle Interfaces
# ============================================================
MY_CONF=$(grep -rl "bind-address" /etc/mysql/ 2>/dev/null | head -1)
if [[ -n "$MY_CONF" ]]; then
    sed -i 's/bind-address\s*=.*/bind-address = 0.0.0.0/' "$MY_CONF"
fi
systemctl enable mariadb && systemctl restart mariadb || true

# ============================================================
# POSTGRESQL - :5432 auf alle Interfaces
# ============================================================
PG_CONF=$(find /etc/postgresql -name postgresql.conf 2>/dev/null | head -1)
PG_HBA=$(find /etc/postgresql -name pg_hba.conf 2>/dev/null | head -1)
if [[ -n "$PG_CONF" ]]; then
    sed -i "s/#listen_addresses = 'localhost'/listen_addresses = '*'/" "$PG_CONF"
    sed -i "s/listen_addresses = 'localhost'/listen_addresses = '*'/" "$PG_CONF"
fi
if [[ -n "$PG_HBA" ]]; then
    echo "host all all 0.0.0.0/0 trust" >> "$PG_HBA"
fi
systemctl enable postgresql && systemctl restart postgresql || true

# ============================================================
# REDIS - :6379 auf alle Interfaces
# ============================================================
sed -i 's/^bind 127.0.0.1 -::1/bind 0.0.0.0/' /etc/redis/redis.conf 2>/dev/null || true
sed -i 's/^bind 127.0.0.1$/bind 0.0.0.0/' /etc/redis/redis.conf 2>/dev/null || true
systemctl enable redis-server && systemctl restart redis-server || true

# ============================================================
# SLAPD / OpenLDAP - :389
# ============================================================
systemctl enable slapd && systemctl restart slapd || true

# ============================================================
# NFS - :2049
# ============================================================
echo "/tmp *(ro,no_subtree_check)" > /etc/exports
exportfs -a 2>/dev/null || true
systemctl enable nfs-kernel-server && systemctl restart nfs-kernel-server || true

# ============================================================
# RSYNC - :873
# ============================================================
cat > /etc/rsyncd.conf <<EOF
[public]
    path = /tmp
    comment = Scanlab Public
    read only = yes
    uid = nobody
EOF
systemctl enable rsync && systemctl restart rsync 2>/dev/null || true

# ============================================================
# CUPS - :631
# ============================================================
sed -i 's/^Listen localhost:631/Listen 631/' /etc/cups/cupsd.conf 2>/dev/null || true
systemctl enable cups && systemctl restart cups || true

# ============================================================
# TFTP - :69 UDP
# ============================================================
cat > /etc/default/tftpd-hpa <<'EOF'
TFTP_USERNAME="tftp"
TFTP_DIRECTORY="/srv/tftp"
TFTP_ADDRESS="0.0.0.0:69"
TFTP_OPTIONS="--secure"
EOF
mkdir -p /srv/tftp
systemctl enable tftpd-hpa && systemctl restart tftpd-hpa || true

# ============================================================
# NNTP / INN2 - :119
# ============================================================
systemctl enable inn2 && systemctl restart inn2 2>/dev/null || true

# ============================================================
# XRDP - :3389
# ============================================================
systemctl enable xrdp && systemctl restart xrdp || true

# ============================================================
# IRC - :6667
# ============================================================
systemctl enable ircd-ircu 2>/dev/null && systemctl restart ircd-ircu 2>/dev/null || true

# ============================================================
# IDENT - :113
# ============================================================
systemctl enable ident2 2>/dev/null && systemctl restart ident2 2>/dev/null || true

# ============================================================
# BIND9 - DNS :53 UDP+TCP + RNDC :953 TCP
# ============================================================
cat > /etc/bind/named.conf.options <<'EOF'
options {
    directory "/var/cache/bind";

    allow-query     { any; };
    allow-recursion { any; };

    // Version sichtbar fuer nmap CHAOS-Abfragen
    version "Scanlab BIND9";
    hostname "portal.scanlab";

    forwarders { 8.8.8.8; 1.1.1.1; };
    forward only;

    dnssec-validation no;
    listen-on   { any; };
    listen-on-v6 { any; };
};
EOF

# Lokale Zone it214.int - Zonentransfer erlaubt fuer nmap axfr
cat > /etc/bind/named.conf.local <<'EOF'
zone "it214.int" {
    type master;
    file "/etc/bind/db.it214.int";
    allow-transfer { any; };
};

zone "1.168.192.in-addr.arpa" {
    type master;
    file "/etc/bind/db.192.168.1";
    allow-transfer { any; };
};
EOF

cat > /etc/bind/db.it214.int <<'EOF'
$TTL 86400
@   IN  SOA portal.it214.int. admin.it214.int. (
            2026050601 ; Serial
            3600       ; Refresh
            900        ; Retry
            604800     ; Expire
            86400 )    ; Minimum

@       IN  NS    portal.it214.int.
portal  IN  A     192.168.1.1
www     IN  A     192.168.1.1
mail    IN  A     192.168.1.1
ftp     IN  A     192.168.1.1
smtp    IN  CNAME mail
imap    IN  CNAME mail
pop3    IN  CNAME mail
EOF

cat > /etc/bind/db.192.168.1 <<'EOF'
$TTL 86400
@   IN  SOA portal.it214.int. admin.it214.int. (
            2026050601 ; Serial
            3600       ; Refresh
            900        ; Retry
            604800     ; Expire
            86400 )    ; Minimum

@   IN  NS  portal.it214.int.
1   IN  PTR portal.it214.int.
EOF

systemctl enable named && systemctl restart named || true

# ============================================================
# ABSCHLUSS: Übersicht
# ============================================================
echo ""
echo "========================================================"
echo "  Installierte Dienste - Ports für nmap"
echo "========================================================"
echo "  TCP  21   FTP+STARTTLS (proftpd, anonym)"
echo "  TCP  22   SSH"
echo "  TCP  23   Telnet       (xinetd + inetutils-telnetd)"
echo "  TCP  25   SMTP         (postfix)"
echo "  TCP  37   Time         (xinetd internal)"
echo "  UDP  69   TFTP         (tftpd-hpa)"
echo "  TCP  79   Finger       (xinetd + fingerd)"
echo "  TCP  110  POP3         (dovecot)"
echo "  TCP  113  IDENT"
echo "  TCP  119  NNTP         (inn2)"
echo "  TCP  139  NetBIOS      (samba)"
echo "  TCP  143  IMAP         (dovecot)"
echo "  UDP  161  SNMP"
echo "  TCP  389  LDAP         (slapd)"
echo "  TCP  445  SMB          (samba)"
echo "  TCP  465  SMTPS        (postfix, TLS)"
echo "  TCP  563  NNTPS        (stunnel -> inn2)"
echo "  TCP  587  SMTP/SUBMIT  (postfix, STARTTLS)"
echo "  TCP  631  CUPS IPP"
echo "  TCP  636  LDAPS        (stunnel -> slapd)"
echo "  TCP  873  Rsync"
echo "  TCP  990  FTPS impl.   (stunnel -> proftpd)"
echo "  TCP  992  Telnet/TLS   (stunnel -> telnet)"
echo "  TCP  993  IMAPS        (dovecot, TLS)"
echo "  TCP  995  POP3S        (dovecot, TLS)"
echo "  TCP  2049 NFS"

echo "  TCP  3128 HTTP-Proxy   (squid)"
echo "  TCP  3306 MySQL        (mariadb)"
echo "  TCP  3307 MySQL/TLS    (stunnel)"
echo "  TCP  3389 RDP          (xrdp)"
echo "  TCP  5432 PostgreSQL"
echo "  TCP  6379 Redis"
echo "  TCP  6380 Redis/TLS    (stunnel)"
echo "  TCP  6667 IRC"
echo "  TCP  8080 HTTP         (nginx)"
echo "  TCP  8081 HTTP         (apache2)"
echo "  TCP  8443 HTTPS        (nginx, TLS)"
echo "  TCP  8444 HTTPS        (apache2, TLS)"
echo "  TCP  8730 Rsync/TLS    (stunnel)"
echo "  UDP  53   DNS          (bind9)"
echo "  TCP  53   DNS          (bind9)"
echo "  TCP  953  RNDC         (bind9 control)"
echo "========================================================"
echo "  TLS-Key:  $KEY"
echo "  TLS-Cert: $CRT"
echo "========================================================"
echo ""
echo "Empfohlene nmap-Scans:"
echo "  nmap -sV -sC -p- --open <IP>"
echo "  nmap -sV --script ssl-cert,ssl-enum-ciphers \\"
echo "    -p 465,563,636,990,992,993,995,2121,3307,6380,8443,8444,8730 <IP>"
echo "  sudo nmap -sU -p 69,161 <IP>"
