본문 바로가기

실전용 리눅스 프록시 도구별 서버 성능과 보안을 한눈에 살펴보기

728x90

리눅스에서 활용 가능한 프록시 도구 종합

리눅스 서버 환경에서 프록시 서버는 네트워크 트래픽을 중계하거나 필터링하고, 사용자 요청을 제어하는 데 핵심적인 역할을 합니다. 특히 내부망 접근 제어, 트래픽 로깅, 캐싱, 콘텐츠 필터링, 인증, 암호화 전환, VPN 대체 등 다양한 보안·운영 목적에 맞게 활용됩니다. 이러한 프록시 도구는 기능과 용도에 따라 HTTP 프록시, SOCKS 프록시, 리버스 프록시, 로드 밸런서 기반 프록시, 필터링 프록시 등으로 구분되며, 리눅스에서 오픈소스로 쉽게 구축할 수 있는 여러 도구들이 존재합니다.

프록시 서버의 주요 활용 시나리오

  1. 보안 강화: 내부 네트워크와 외부 인터넷 간의 격리, IP 주소 은닉
  2. 접근 제어: 특정 웹사이트나 서비스에 대한 접근 차단 또는 허용
  3. 성능 향상: 자주 요청되는 콘텐츠의 캐싱을 통한 대역폭 절약
  4. 모니터링: 네트워크 트래픽 로깅 및 분석
  5. 익명성 보장: 사용자의 실제 IP 주소 은닉
  6. 로드 밸런싱: 여러 서버로 트래픽 분산

다음과 같은 기준에 따라 각 도구를 소개합니다.

  • 경량/고성능 여부
  • 🔄 프록시 타입 (HTTP, SOCKS, 리버스 등)
  • 🔧 설정 및 설치 난이도
  • 🔒 접근 제어 및 인증 기능
  • 📊 로깅 및 모니터링 가능 여부
300x250

아래는 TinyProxy, Sing-box, Squid, HAProxy, Nginx, Privoxy, SSH 터널링, 3proxy, Dante 등 실무에서 자주 사용되는 프록시 도구를 설치 명령어와 주요 설정 예시와 함께 소개하며, 보안 구성 시 필수 고려사항까지 정리합니다.

각 도구의 특징을 이해하고 환경에 맞는 솔루션을 선택해보세요. 🔐✨

TinyProxy - 초경량 HTTP/HTTPS 프록시

TinyProxy는 이름 그대로 매우 작고 가벼운 HTTP/HTTPS 프록시 서버입니다. C언어로 작성되어 메모리 사용량이 적고, 임베디드 시스템이나 리소스가 제한된 환경에서도 효율적으로 동작합니다.

주요 용도

  • 소규모 네트워크의 웹 프록시: 가정이나 소규모 사무실의 인터넷 게이트웨이
  • 개발/테스트 환경: 간단한 프록시 테스트 환경 구축
  • IoT 디바이스: 제한된 리소스 환경에서의 프록시 서비스
  • 컨테이너 환경: Docker 등 컨테이너에서 경량 프록시로 활용

핵심 기능

  • HTTP/HTTPS 프록시 지원
  • 투명 프록시 모드
  • 접근 제어 리스트 (ACL)
  • 업스트림 프록시 연결
  • URL 필터링
  • 최소한의 메모리 사용 (약 2MB)

설치

# Ubuntu/Debian
sudo apt-get update
sudo apt-get install tinyproxy

# CentOS/RHEL/Rocky Linux
sudo yum install epel-release
sudo yum install tinyproxy

# 소스 컴파일 설치
wget https://github.com/tinyproxy/tinyproxy/releases/download/1.11.1/tinyproxy-1.11.1.tar.gz
tar -xzf tinyproxy-1.11.1.tar.gz
cd tinyproxy-1.11.1
./configure --enable-transparent
make
sudo make install

상세 설정 (/etc/tinyproxy/tinyproxy.conf)

# 기본 네트워크 설정
Port 8888                    # 프록시 포트
Listen 0.0.0.0              # 모든 인터페이스에서 수신
BindSame yes                # 클라이언트와 동일한 IP로 외부 연결

# 프로세스 설정
User tinyproxy              # 실행 사용자
Group tinyproxy             # 실행 그룹
PidFile "/var/run/tinyproxy/tinyproxy.pid"

# 접근 제어
Allow 127.0.0.1            # 로컬호스트 허용
Allow 192.168.1.0/24       # 특정 서브넷 허용
Allow 10.0.0.0/8           # 사설 IP 대역 허용

# 업스트림 프록시 (필요시)
# upstream http proxy.company.com:8080 ".company.com"
# upstream socks5 127.0.0.1:9050 ".onion"

# 로깅 설정
LogLevel Info              # Critical, Error, Warning, Notice, Info, Debug
LogFile "/var/log/tinyproxy/tinyproxy.log"
Syslog On                  # syslog로도 로깅

# 성능 설정
MaxClients 100             # 최대 동시 접속 수
MinSpareServers 5          # 최소 대기 서버 수
MaxSpareServers 20         # 최대 대기 서버 수
StartServers 10            # 시작시 서버 수
MaxRequestsPerChild 0      # 0은 무제한

# 헤더 설정
ViaProxyName "tinyproxy"   # Via 헤더에 표시될 이름
DisableViaHeader No        # Via 헤더 비활성화 여부
XTinyproxy Yes            # X-Tinyproxy 헤더 추가

# 타임아웃 설정
Timeout 600               # 연결 타임아웃 (초)
ConnectPort 443           # CONNECT 메소드 허용 포트
ConnectPort 563

# 필터링 설정
Filter "/etc/tinyproxy/filter"
FilterURLs On             # URL 필터링 활성화
FilterExtended On         # 확장 필터 사용
FilterDefaultDeny Yes     # 기본 거부 정책

# 에러 페이지
ErrorFile 404 "/usr/share/tinyproxy/404.html"
ErrorFile 403 "/usr/share/tinyproxy/403.html"

필터 설정 예시 (/etc/tinyproxy/filter)

# 광고 차단
\.doubleclick\.net
\.googleadservices\.com
\.googlesyndication\.com

# 소셜 미디어 차단
\.facebook\.com
\.twitter\.com
\.instagram\.com

# 특정 파일 형식 차단
\.exe$
\.zip$
\.torrent$

운영 명령어

# 서비스 관리
sudo systemctl start tinyproxy
sudo systemctl stop tinyproxy
sudo systemctl restart tinyproxy
sudo systemctl status tinyproxy

# 설정 검증
sudo tinyproxy -c /etc/tinyproxy/tinyproxy.conf -t

# 디버그 모드 실행
sudo tinyproxy -d -c /etc/tinyproxy/tinyproxy.conf

# 로그 모니터링
tail -f /var/log/tinyproxy/tinyproxy.log

# 통계 확인
sudo kill -USR1 $(cat /var/run/tinyproxy/tinyproxy.pid)

Sing-box - 차세대 멀티 프로토콜 프록시

Sing-box는 Go 언어로 작성된 현대적인 프록시 플랫폼으로, 다양한 프로토콜을 통합 지원하며 높은 성능과 유연성을 제공합니다. V2Ray, Trojan, Shadowsocks 등 여러 프로토콜을 하나의 플랫폼에서 관리할 수 있습니다.

주요 용도

  • 다중 프로토콜 프록시 서버: 하나의 서버에서 여러 프록시 프로토콜 운영
  • 네트워크 우회: 검열이나 차단을 우회하기 위한 도구
  • 프록시 체인: 여러 프록시를 연결하여 복잡한 라우팅 구성
  • 트래픽 분류: 규칙 기반 라우팅으로 트래픽 최적화

핵심 기능

  • 다중 인바운드/아웃바운드 지원
  • 규칙 기반 라우팅
  • DNS 오버 HTTPS/TLS
  • 트래픽 스니핑 및 자동 프로토콜 감지
  • GeoIP/GeoSite 데이터베이스 지원
  • WebSocket, gRPC, HTTP/2 전송 지원

설치

# 최신 버전 확인 및 다운로드
VERSION=$(curl -s https://api.github.com/repos/SagerNet/sing-box/releases/latest | grep tag_name | cut -d '"' -f 4)
wget https://github.com/SagerNet/sing-box/releases/download/${VERSION}/sing-box-${VERSION#v}-linux-amd64.tar.gz

# 압축 해제 및 설치
tar -xzf sing-box-*.tar.gz
sudo mv sing-box-*/sing-box /usr/local/bin/
sudo chmod +x /usr/local/bin/sing-box

# 설정 디렉토리 생성
sudo mkdir -p /etc/sing-box
sudo mkdir -p /var/log/sing-box

# systemd 서비스 파일 생성
sudo tee /etc/systemd/system/sing-box.service > /dev/null <<EOF
[Unit]
Description=sing-box service
After=network.target

[Service]
Type=simple
User=root
ExecStart=/usr/local/bin/sing-box run -c /etc/sing-box/config.json
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

상세 설정 예시 (/etc/sing-box/config.json)

{
  "log": {
    "level": "info",
    "output": "/var/log/sing-box/sing-box.log",
    "timestamp": true
  },
  "dns": {
    "servers": [
      {
        "tag": "google",
        "address": "tls://8.8.8.8",
        "detour": "direct"
      },
      {
        "tag": "local",
        "address": "223.5.5.5",
        "detour": "direct"
      }
    ],
    "rules": [
      {
        "geosite": "cn",
        "server": "local"
      },
      {
        "geosite": "geolocation-!cn",
        "server": "google"
      }
    ],
    "final": "google",
    "strategy": "ipv4_only"
  },
  "inbounds": [
    {
      "type": "mixed",
      "tag": "mixed-in",
      "listen": "::",
      "listen_port": 2080,
      "sniff": true,
      "sniff_override_destination": true,
      "domain_strategy": "ipv4_only",
      "set_system_proxy": false
    },
    {
      "type": "http",
      "tag": "http-in",
      "listen": "::",
      "listen_port": 8080,
      "users": [
        {
          "username": "admin",
          "password": "secret123"
        }
      ]
    },
    {
      "type": "socks",
      "tag": "socks-in",
      "listen": "::",
      "listen_port": 1080,
      "users": [
        {
          "username": "user1",
          "password": "pass1"
        }
      ]
    },
    {
      "type": "shadowsocks",
      "tag": "ss-in",
      "listen": "::",
      "listen_port": 8388,
      "method": "2022-blake3-aes-128-gcm",
      "password": "8JCsPssfgS8tiRwiMlhARg=="
    },
    {
      "type": "vmess",
      "tag": "vmess-in",
      "listen": "::",
      "listen_port": 10086,
      "users": [
        {
          "uuid": "b831381d-6324-4d53-ad4f-8cda48b30811",
          "alterId": 0
        }
      ]
    }
  ],
  "outbounds": [
    {
      "type": "direct",
      "tag": "direct"
    },
    {
      "type": "block",
      "tag": "block"
    },
    {
      "type": "dns",
      "tag": "dns-out"
    },
    {
      "type": "socks",
      "tag": "proxy-socks",
      "server": "proxy.example.com",
      "server_port": 1080,
      "username": "user",
      "password": "pass"
    },
    {
      "type": "shadowsocks",
      "tag": "proxy-ss",
      "server": "ss.example.com",
      "server_port": 8388,
      "method": "aes-256-gcm",
      "password": "password123"
    },
    {
      "type": "selector",
      "tag": "select",
      "outbounds": ["proxy-socks", "proxy-ss", "direct"],
      "default": "proxy-socks"
    }
  ],
  "route": {
    "geoip": {
      "path": "/etc/sing-box/geoip.db",
      "download_url": "https://github.com/SagerNet/sing-geoip/releases/latest/download/geoip.db"
    },
    "geosite": {
      "path": "/etc/sing-box/geosite.db",
      "download_url": "https://github.com/SagerNet/sing-geosite/releases/latest/download/geosite.db"
    },
    "rules": [
      {
        "protocol": "dns",
        "outbound": "dns-out"
      },
      {
        "geosite": "category-ads-all",
        "outbound": "block"
      },
      {
        "geosite": "cn",
        "geoip": "cn",
        "outbound": "direct"
      },
      {
        "geosite": "geolocation-!cn",
        "outbound": "select"
      },
      {
        "port": [80, 443],
        "outbound": "select"
      },
      {
        "ip_cidr": ["192.168.0.0/16", "10.0.0.0/8"],
        "outbound": "direct"
      }
    ],
    "final": "select",
    "auto_detect_interface": true
  },
  "experimental": {
    "clash_api": {
      "external_controller": "127.0.0.1:9090",
      "external_ui": "/etc/sing-box/ui",
      "secret": "your-secret-string"
    }
  }
}

운영 명령어

# 설정 검증
sing-box check -c /etc/sing-box/config.json

# 서비스 시작
sudo systemctl daemon-reload
sudo systemctl enable sing-box
sudo systemctl start sing-box

# 실시간 로그 확인
journalctl -u sing-box -f

# 수동 실행 (디버그)
sing-box run -c /etc/sing-box/config.json -D /var/lib/sing-box

# GeoIP/GeoSite 데이터베이스 업데이트
sing-box geoip download -o /etc/sing-box/geoip.db
sing-box geosite download -o /etc/sing-box/geosite.db

# 규칙 테스트
sing-box rule-set match /etc/sing-box/config.json "www.google.com"

Squid - 엔터프라이즈급 캐싱 프록시

Squid는 1996년부터 개발된 오랜 역사를 가진 고성능 프록시 서버로, 대규모 엔터프라이즈 환경에서 널리 사용됩니다. 강력한 캐싱 기능과 세밀한 접근 제어를 제공하며, HTTP, HTTPS, FTP 등 다양한 프로토콜을 지원합니다.

주요 용도

  • 기업 프록시 서버: 대규모 조직의 인터넷 게이트웨이
  • 콘텐츠 캐싱: 대역폭 절약을 위한 웹 콘텐츠 캐싱
  • 접근 제어: URL, 시간대, 사용자별 세밀한 접근 제어
  • 리버스 프록시: 웹 서버 앞단의 가속기 역할
  • 투명 프록시: 클라이언트 설정 없이 자동 프록시 적용

핵심 기능

  • 고성능 HTTP 캐싱
  • SSL/TLS 인터셉션 (SSL Bump)
  • 다양한 인증 방식 (Basic, NTLM, Kerberos, LDAP)
  • 세밀한 ACL 기반 접근 제어
  • 계층적 프록시 구조 지원
  • 상세한 로깅 및 보고서
  • ICAP/eCAP 콘텐츠 적응

설치

# Ubuntu/Debian
sudo apt-get update
sudo apt-get install squid squid-common squid-langpack

# CentOS/RHEL
sudo yum install squid

# 컴파일 설치 (고급 기능용)
wget http://www.squid-cache.org/Versions/v5/squid-5.7.tar.gz
tar -xzf squid-5.7.tar.gz
cd squid-5.7
./configure --prefix=/usr/local/squid \
    --enable-ssl-crtd \
    --enable-icap-client \
    --enable-ecap \
    --enable-linux-netfilter \
    --with-openssl \
    --enable-auth-basic \
    --enable-auth-digest \
    --enable-auth-ntlm
make
sudo make install

상세 설정 (/etc/squid/squid.conf)

# 기본 네트워크 설정
http_port 3128
https_port 3129 cert=/etc/squid/cert.pem key=/etc/squid/key.pem

# SSL Bump 설정 (HTTPS 검사)
acl SSL_ports port 443
acl Safe_ports port 80 21 443 70 210 1025-65535
acl CONNECT method CONNECT

ssl_bump server-first all
sslproxy_cert_error allow all
sslproxy_flags DONT_VERIFY_PEER

# 캐시 설정
cache_dir ufs /var/spool/squid 10000 16 256
cache_mem 256 MB
maximum_object_size_in_memory 512 KB
maximum_object_size 20 MB
minimum_object_size 0 KB
cache_swap_low 90
cache_swap_high 95

# 캐시 정책
refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern -i (/cgi-bin/|\?) 0     0%      0
refresh_pattern \.(gif|png|jpg|jpeg|ico)$ 10080 90% 43200
refresh_pattern \.(iso|avi|wav|mp3|mp4|mpeg|swf|flv|x-flv)$ 43200 90% 432000
refresh_pattern \.(deb|rpm|exe|zip|tar|tgz|ram|rar|bin|ppt|doc|tiff)$ 10080 90% 43200
refresh_pattern .               0       20%     4320

# DNS 설정
dns_nameservers 8.8.8.8 8.8.4.4
dns_v4_first on

# ACL 정의
acl localnet src 10.0.0.0/8
acl localnet src 172.16.0.0/12
acl localnet src 192.168.0.0/16
acl localnet src fc00::/7
acl localnet src fe80::/10

# 시간 기반 ACL
acl business_hours time MTWHF 08:00-18:00
acl lunch_time time MTWHF 12:00-13:00

# 콘텐츠 기반 ACL
acl blocked_sites dstdomain "/etc/squid/blocked_sites.txt"
acl allowed_sites dstdomain "/etc/squid/allowed_sites.txt"
acl blocked_keywords url_regex -i "/etc/squid/blocked_keywords.txt"
acl streaming_sites dstdomain .youtube.com .netflix.com
acl downloads urlpath_regex -i \.(exe|zip|rar|iso|mp3|mp4|avi|mkv)$

# 사용자 인증 설정
auth_param basic program /usr/lib/squid/basic_ncsa_auth /etc/squid/passwd
auth_param basic realm Squid Proxy Server
auth_param basic credentialsttl 2 hours
auth_param basic casesensitive on
acl authenticated proxy_auth REQUIRED

# 그룹 기반 ACL
external_acl_type unix_group %LOGIN /usr/lib/squid/ext_unix_group_acl
acl admin_group external unix_group admins
acl user_group external unix_group users

# 대역폭 제한
delay_pools 2
delay_class 1 2
delay_parameters 1 -1/-1 100000/100000
delay_access 1 allow streaming_sites
delay_access 1 deny all

delay_class 2 3
delay_parameters 2 64000/64000 32000/32000 16000/16000
delay_access 2 allow downloads
delay_access 2 deny all

# 접근 제어 규칙
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow localhost manager
http_access deny manager
http_access deny blocked_sites
http_access allow allowed_sites
http_access deny blocked_keywords
http_access allow authenticated business_hours
http_access deny lunch_time
http_access allow localnet
http_access allow localhost
http_access deny all

# 로깅 설정
access_log daemon:/var/log/squid/access.log squid
cache_log /var/log/squid/cache.log
cache_store_log daemon:/var/log/squid/store.log

# 로그 포맷 커스터마이징
logformat custom %ts.%03tu %6tr %>a %Ss/%03>Hs %<st %rm %ru %[un %Sh/%<a %mt
access_log /var/log/squid/custom.log custom

# 에러 페이지
error_directory /usr/share/squid/errors/ko

# 성능 최적화
workers 4
cpu_affinity_map process_numbers=1,2,3,4 cores=1,3,5,7

# 익명화 설정
via off
forwarded_for off
request_header_access X-Forwarded-For deny all
request_header_access Via deny all
request_header_access Cache-Control deny all

# 관리 정보
cache_mgr admin@example.com
visible_hostname proxy.example.com
unique_hostname proxy1.example.com

블랙리스트/화이트리스트 파일 예시

# /etc/squid/blocked_sites.txt
.facebook.com
.twitter.com
.instagram.com
.tiktok.com
.gambling.com
.adult-site.com

# /etc/squid/allowed_sites.txt
.company.com
.partner-company.com
.github.com
.stackoverflow.com

# /etc/squid/blocked_keywords.txt
torrent
gambling
adult
proxy
vpn

운영 명령어

# 설정 검증
squid -k parse

# 캐시 디렉토리 초기화
squid -z

# 서비스 관리
sudo systemctl start squid
sudo systemctl stop squid
sudo systemctl reload squid  # 설정 재로드

# 캐시 관리
squidclient -h localhost mgr:info  # 상태 정보
squidclient -h localhost mgr:mem   # 메모리 사용량
squidclient -h localhost mgr:objects  # 캐시 객체
squidclient -h localhost mgr:utilization  # 활용도

# 특정 URL 캐시 삭제
squidclient -m PURGE http://example.com/file.jpg

# 사용자 인증 파일 생성
htpasswd -c /etc/squid/passwd admin
htpasswd /etc/squid/passwd user1

# 실시간 접속 로그 모니터링
tail -f /var/log/squid/access.log | awk '{print $3 " " $7 " " $9}'

# 트래픽 분석
cat /var/log/squid/access.log | awk '{sum+=$5} END {print sum/1024/1024 " MB"}'

# 상위 요청 URL
cat /var/log/squid/access.log | awk '{print $7}' | sort | uniq -c | sort -rn | head -20

HAProxy - 고성능 로드 밸런서 및 프록시

HAProxy는 고가용성, 로드 밸런싱, TCP/HTTP 프록시 기능을 제공하는 오픈소스 솔루션입니다. 매우 높은 성능과 안정성으로 대규모 웹 서비스에서 널리 사용되며, 단일 프로세스로 초당 수십만 건의 요청을 처리할 수 있습니다.

주요 용도

  • 로드 밸런싱: 여러 백엔드 서버로 트래픽 분산
  • 고가용성: 서버 장애 시 자동 페일오버
  • SSL 터미네이션: SSL/TLS 암호화 처리
  • API 게이트웨이: 마이크로서비스 아키텍처의 진입점
  • 웹 가속: HTTP 압축, 캐싱, 연결 멀티플렉싱

핵심 기능

  • Layer 4 (TCP) 및 Layer 7 (HTTP) 로드 밸런싱
  • 다양한 로드 밸런싱 알고리즘
  • 상태 확인 (Health Check)
  • 세션 지속성 (Sticky Session)
  • SSL/TLS 오프로딩
  • HTTP/2 지원
  • 실시간 통계 및 모니터링
  • 무중단 설정 재로드

설치

# Ubuntu/Debian
sudo apt-get update
sudo apt-get install haproxy

# CentOS/RHEL
sudo yum install haproxy

# 최신 버전 컴파일 설치
wget https://www.haproxy.org/download/2.8/src/haproxy-2.8.1.tar.gz
tar -xzf haproxy-2.8.1.tar.gz
cd haproxy-2.8.1
make TARGET=linux-glibc USE_PCRE=1 USE_OPENSSL=1 USE_ZLIB=1 USE_LUA=1
sudo make install

상세 설정 (/etc/haproxy/haproxy.cfg)

#---------------------------------------------------------------------
# 전역 설정
#---------------------------------------------------------------------
global
    log /dev/log    local0
    log /dev/log    local1 notice
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy
    daemon

    # 성능 튜닝
    maxconn 100000
    nbproc 1
    nbthread 4
    cpu-map auto:1/1-4 0-3

    # SSL 설정
    ssl-default-bind-ciphers ECDHE+AESGCM:ECDHE+AES256:ECDHE+AES128
    ssl-default-bind-options no-sslv3 no-tlsv10 no-tlsv11
    ssl-default-server-ciphers ECDHE+AESGCM:ECDHE+AES256:ECDHE+AES128
    ssl-default-server-options no-sslv3 no-tlsv10 no-tlsv11

    # 디버그
    quiet
    tune.ssl.default-dh-param 2048

#---------------------------------------------------------------------
# 기본값 설정
#---------------------------------------------------------------------
defaults
    log     global
    mode    http
    option  httplog
    option  dontlognull
    option  log-health-checks
    option  log-separate-errors

    # 타임아웃 설정
    timeout connect 5000
    timeout client  50000
    timeout server  50000
    timeout http-request 10s
    timeout http-keep-alive 2s
    timeout queue 1m
    timeout tunnel 1h

    # HTTP 옵션
    option forwardfor       except 127.0.0.0/8
    option httpclose
    option abortonclose
    option redispatch
    retries 3

    # 압축
    compression algo gzip
    compression type text/html text/plain text/css application/javascript

#---------------------------------------------------------------------
# 통계 페이지
#---------------------------------------------------------------------
listen stats
    bind *:8404
    stats enable
    stats uri /stats
    stats realm HAProxy\ Statistics
    stats auth admin:password
    stats admin if TRUE
    stats refresh 30s
    stats show-node
    stats show-legends

#---------------------------------------------------------------------
# 프론트엔드 정의
#---------------------------------------------------------------------
frontend web_frontend
    bind *:80
    bind *:443 ssl crt /etc/haproxy/certs/

    # HTTP to HTTPS 리다이렉트
    redirect scheme https code 301 if !{ ssl_fc }

    # HSTS 헤더
    http-response set-header Strict-Transport-Security max-age=31536000

    # ACL 정의
    acl is_api path_beg /api
    acl is_admin path_beg /admin
    acl is_static path_end .jpg .jpeg .gif .png .css .js .ico
    acl is_websocket hdr(Upgrade) -i WebSocket

    # 요청 라우팅
    use_backend api_servers if is_api
    use_backend admin_servers if is_admin
    use_backend static_servers if is_static
    use_backend websocket_servers if is_websocket
    default_backend web_servers

#---------------------------------------------------------------------
# 백엔드 정의
#---------------------------------------------------------------------
backend web_servers
    balance roundrobin
    option httpchk GET /health

    # 세션 지속성
    cookie SERVERID insert indirect nocache

    # 서버 정의
    server web1 192.168.1.10:80 check cookie web1 weight 10
    server web2 192.168.1.11:80 check cookie web2 weight 10
    server web3 192.168.1.12:80 check cookie web3 weight 5 backup

backend api_servers
    balance leastconn
    option httpchk GET /api/health

    # 속도 제한
    stick-table type ip size 100k expire 30s store http_req_rate(10s)
    http-request track-sc0 src
    http-request deny if { sc_http_req_rate(0) gt 100 }

    server api1 192.168.1.20:8080 check
    server api2 192.168.1.21:8080 check
    server api3 192.168.1.22:8080 check

backend admin_servers
    balance source
    option httpchk GET /admin/health

    # IP 기반 접근 제어
    acl allowed_ips src 192.168.1.0/24 10.0.0.0/8
    http-request deny if !allowed_ips

    server admin1 192.168.1.30:8090 check
    server admin2 192.168.1.31:8090 check

backend static_servers
    balance uri
    option httpchk HEAD /

    # 캐싱 헤더
    http-response set-header Cache-Control "public, max-age=3600"

    server static1 192.168.1.40:80 check
    server static2 192.168.1.41:80 check

backend websocket_servers
    balance source
    option http-server-close
    option forceclose

    server ws1 192.168.1.50:8080 check
    server ws2 192.168.1.51:8080 check

#---------------------------------------------------------------------
# TCP 모드 프록시
#---------------------------------------------------------------------
listen mysql_cluster
    bind *:3306
    mode tcp
    option mysql-check user haproxy
    balance leastconn

    server mysql1 192.168.1.60:3306 check
    server mysql2 192.168.1.61:3306 check backup

listen redis_cluster
    bind *:6379
    mode tcp
    option tcp-check
    tcp-check connect
    tcp-check send PING\r\n
    tcp-check expect string +PONG
    tcp-check send QUIT\r\n
    tcp-check expect string +OK

    server redis1 192.168.1.70:6379 check
    server redis2 192.168.1.71:6379 check

#---------------------------------------------------------------------
# 동적 설정 (Runtime API)
#---------------------------------------------------------------------
listen runtime_api
    bind *:9999
    mode http
    stats enable
    stats uri /
    stats refresh 5s

운영 명령어

# 설정 검증
haproxy -f /etc/haproxy/haproxy.cfg -c

# 서비스 관리
sudo systemctl start haproxy
sudo systemctl reload haproxy  # 무중단 재로드
sudo systemctl status haproxy

# Runtime API 사용
echo "show stat" | socat /run/haproxy/admin.sock -
echo "show info" | socat /run/haproxy/admin.sock -
echo "show servers state" | socat /run/haproxy/admin.sock -

# 서버 상태 변경
echo "disable server web_servers/web1" | socat /run/haproxy/admin.sock -
echo "enable server web_servers/web1" | socat /run/haproxy/admin.sock -
echo "set weight web_servers/web1 50" | socat /run/haproxy/admin.sock -

# 실시간 모니터링
watch -n 1 'echo "show stat" | socat /run/haproxy/admin.sock - | cut -d "," -f 1,2,18,19'

# 로그 분석
tail -f /var/log/haproxy.log | grep -E "(web_servers|api_servers)"

# 연결 상태 확인
ss -antp | grep haproxy

Nginx - 웹 서버 및 리버스 프록시

Nginx는 고성능 웹 서버이자 리버스 프록시 서버로, 비동기 이벤트 기반 아키텍처를 통해 높은 동시성을 처리할 수 있습니다. 정적 콘텐츠 서빙, 로드 밸런싱, HTTP 캐싱, SSL 터미네이션 등 다양한 기능을 제공합니다.

주요 용도

  • 리버스 프록시: 백엔드 애플리케이션 서버 앞단 배치
  • 로드 밸런서: 여러 업스트림 서버로 트래픽 분산
  • 웹 서버: 정적 파일 서빙
  • API 게이트웨이: 마이크로서비스 라우팅
  • SSL/TLS 터미네이션: HTTPS 처리
  • 캐싱 서버: 콘텐츠 캐싱으로 성능 향상

핵심 기능

  • 비동기 이벤트 기반 처리
  • 리버스 프록시 및 로드 밸런싱
  • FastCGI, uWSGI, SCGI 지원
  • URL 재작성 및 리다이렉션
  • 가상 호스트
  • WebSocket 프록시
  • HTTP/2 지원
  • 모듈식 아키텍처

설치

# Ubuntu/Debian
sudo apt-get update
sudo apt-get install nginx nginx-extras

# CentOS/RHEL
sudo yum install epel-release
sudo yum install nginx

# 최신 버전 설치 (Ubuntu)
sudo add-apt-repository ppa:nginx/stable
sudo apt-get update
sudo apt-get install nginx

# 소스 컴파일 (추가 모듈 포함)
wget https://nginx.org/download/nginx-1.24.0.tar.gz
tar -xzf nginx-1.24.0.tar.gz
cd nginx-1.24.0
./configure --prefix=/etc/nginx \
    --with-http_ssl_module \
    --with-http_v2_module \
    --with-http_realip_module \
    --with-http_stub_status_module \
    --with-http_gzip_static_module \
    --with-pcre \
    --with-stream \
    --with-stream_ssl_module
make
sudo make install

메인 설정 (/etc/nginx/nginx.conf)

user www-data;
worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 65535;
pid /var/run/nginx.pid;

# 모듈 로드
load_module modules/ngx_http_geoip_module.so;

events {
    worker_connections 4096;
    use epoll;
    multi_accept on;
}

http {
    # 기본 설정
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # 로깅 설정
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for" '
                    'rt=$request_time uct="$upstream_connect_time" '
                    'uht="$upstream_header_time" urt="$upstream_response_time"';

    access_log /var/log/nginx/access.log main buffer=16k;
    error_log /var/log/nginx/error.log warn;

    # 성능 최적화
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    keepalive_requests 100;
    reset_timedout_connection on;
    client_body_timeout 10;
    client_header_timeout 10;
    send_timeout 10;

    # 버퍼 설정
    client_body_buffer_size 128k;
    client_max_body_size 10m;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 32k;
    output_buffers 1 32k;
    postpone_output 1460;

    # 파일 캐시
    open_file_cache max=1000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    # Gzip 압축
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/xml text/javascript 
               application/x-javascript application/xml+rss 
               application/javascript application/json;
    gzip_disable "msie6";

    # 보안 헤더
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;

    # SSL 설정
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_session_tickets off;
    ssl_stapling on;
    ssl_stapling_verify on;

    # Rate Limiting
    limit_req_zone $binary_remote_addr zone=general:10m rate=10r/s;
    limit_req_zone $binary_remote_addr zone=api:10m rate=100r/s;
    limit_conn_zone $binary_remote_addr zone=addr:10m;

    # 업스트림 정의
    upstream backend_servers {
        least_conn;
        server 192.168.1.10:8080 weight=5 max_fails=3 fail_timeout=30s;
        server 192.168.1.11:8080 weight=5 max_fails=3 fail_timeout=30s;
        server 192.168.1.12:8080 backup;
        keepalive 32;
    }

    upstream api_servers {
        ip_hash;
        server api1.example.com:8080;
        server api2.example.com:8080;
        server api3.example.com:8080;
        keepalive 64;
    }

    # 프록시 캐시 설정
    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m 
                     max_size=1g inactive=60m use_temp_path=off;

    # 가상 호스트 포함
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

# TCP/UDP 프록시 (stream 모듈)
stream {
    upstream mysql_backend {
        server 192.168.1.20:3306;
        server 192.168.1.21:3306 backup;
    }

    server {
        listen 3306;
        proxy_pass mysql_backend;
        proxy_connect_timeout 1s;
    }
}

리버스 프록시 설정 예시 (/etc/nginx/sites-available/reverse-proxy)

# HTTP 리다이렉트
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$server_name$request_uri;
}

# HTTPS 리버스 프록시
server {
    listen 443 ssl http2;
    server_name example.com;

    # SSL 인증서
    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;

    # 로깅
    access_log /var/log/nginx/example.com.access.log main;
    error_log /var/log/nginx/example.com.error.log;

    # 기본 위치
    location / {
        proxy_pass http://backend_servers;
        proxy_http_version 1.1;

        # 프록시 헤더
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Port $server_port;

        # 프록시 타임아웃
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;

        # 프록시 버퍼
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
        proxy_busy_buffers_size 8k;

        # 프록시 캐시
        proxy_cache my_cache;
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
        proxy_cache_background_update on;
        proxy_cache_lock on;
        add_header X-Cache-Status $upstream_cache_status;

        # Rate Limiting
        limit_req zone=general burst=20 nodelay;
        limit_conn addr 10;
    }

    # API 엔드포인트
    location /api/ {
        proxy_pass http://api_servers/;
        proxy_http_version 1.1;

        # API 특화 설정
        proxy_set_header Connection "";
        proxy_buffering off;

        # CORS 헤더
        add_header Access-Control-Allow-Origin * always;
        add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;
        add_header Access-Control-Allow-Headers "Authorization, Content-Type" always;

        if ($request_method = OPTIONS) {
            return 204;
        }

        # API Rate Limiting
        limit_req zone=api burst=100 nodelay;
    }

    # WebSocket 프록시
    location /ws/ {
        proxy_pass http://backend_servers;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        # WebSocket 타임아웃
        proxy_read_timeout 3600s;
        proxy_send_timeout 3600s;
    }

    # 정적 파일
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|pdf|txt)$ {
        root /var/www/static;
        expires 1y;
        add_header Cache-Control "public, immutable";
        access_log off;
    }

    # 상태 페이지
    location /nginx_status {
        stub_status on;
        access_log off;
        allow 127.0.0.1;
        allow 192.168.1.0/24;
        deny all;
    }

    # 에러 페이지
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}

# 로드 밸런싱 예제
server {
    listen 80;
    server_name lb.example.com;

    location / {
        proxy_pass http://backend_servers;

        # 헬스 체크
        health_check interval=5s fails=3 passes=2;

        # 세션 지속성 (IP Hash 대신 쿠키 사용)
        sticky cookie srv_id expires=1h domain=.example.com path=/;
    }
}

보안 강화 설정

# DDoS 방어
http {
    # 연결 제한
    limit_conn_zone $binary_remote_addr zone=perip:10m;
    limit_conn_zone $server_name zone=perserver:10m;

    # 요청 제한
    limit_req_zone $binary_remote_addr zone=allips:10m rate=10r/s;
    limit_req_zone $uri zone=alluri:10m rate=100r/s;

    # 지리적 차단
    geoip_country /usr/share/GeoIP/GeoIP.dat;
    map $geoip_country_code $allowed_country {
        default yes;
        CN no;
        RU no;
    }
}

server {
    # 국가별 차단
    if ($allowed_country = no) {
        return 403;
    }

    # User-Agent 필터링
    if ($http_user_agent ~* (wget|curl|libwww-perl|Python|nikto|sqlmap)) {
        return 403;
    }

    # Referer 검증
    valid_referers none blocked server_names *.example.com;
    if ($invalid_referer) {
        return 403;
    }
}

운영 명령어

# 설정 테스트
nginx -t
nginx -T  # 전체 설정 출력

# 서비스 관리
sudo systemctl start nginx
sudo systemctl reload nginx  # 무중단 재로드
sudo systemctl status nginx

# 로그 모니터링
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log

# 실시간 상태 확인
curl http://localhost/nginx_status

# 로그 분석
# 상위 요청 IP
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20

# 응답 시간 분석
awk '{print $NF}' /var/log/nginx/access.log | sort -n | awk '{sum+=$1; count++} END {print "평균:", sum/count}'

# 캐시 상태 확인
find /var/cache/nginx -type f | wc -l

# 연결 상태
ss -antp | grep nginx | wc -l

Privoxy - 프라이버시 보호 웹 프록시

Privoxy는 프라이버시 보호에 중점을 둔 비캐싱 웹 프록시로, 광고 차단, 쿠키 관리, 웹 페이지 필터링 등의 기능을 제공합니다. 주로 개인 프라이버시 보호와 웹 브라우징 경험 개선을 위해 사용됩니다.

주요 용도

  • 프라이버시 보호: 추적 쿠키 및 웹 비콘 차단
  • 광고 차단: 광고 네트워크 차단
  • 콘텐츠 필터링: 불필요한 콘텐츠 제거
  • Tor 연동: Tor 네트워크와 함께 사용하여 익명성 강화
  • HTTP 헤더 조작: 브라우저 핑거프린팅 방지

핵심 기능

  • 정규표현식 기반 URL 및 콘텐츠 필터링
  • HTTP 헤더 필터링 및 조작
  • 쿠키 관리 및 차단
  • 이미지 차단 및 대체
  • HTTPS 인터셉션 없이 HTTP 트래픽만 필터링
  • 세밀한 액션 기반 규칙 시스템

설치

# Ubuntu/Debian
sudo apt-get update
sudo apt-get install privoxy

# CentOS/RHEL
sudo yum install privoxy

# 소스 컴파일
wget https://www.privoxy.org/sf-download-mirror/Sources/3.0.34/privoxy-3.0.34-stable-src.tar.gz
tar -xzf privoxy-3.0.34-stable-src.tar.gz
cd privoxy-3.0.34-stable
autoheader && autoconf
./configure --prefix=/usr/local
make
sudo make install

메인 설정 (/etc/privoxy/config)

# 네트워크 설정
listen-address  0.0.0.0:8118
listen-address  [::]:8118

# 관리 인터페이스
enable-edit-actions 0
enable-remote-toggle 0
enable-remote-http-toggle 0

# 로깅
logdir /var/log/privoxy
logfile logfile
debug 1     # 로그 레벨 (1-65535)
debug 1024  # 액션 로깅
debug 4096  # 필터 로깅
debug 8192  # 헤더 로깅

# 필터 파일
actionsfile match-all.action
actionsfile default.action
actionsfile user.action
filterfile default.filter
filterfile user.filter

# 신뢰할 수 있는 참조자
trustfile trust

# 버퍼 크기
buffer-limit 4096

# 연결 설정
keep-alive-timeout 5
default-server-timeout 60
socket-timeout 300
max-client-connections 128

# 프록시 체인 (Tor 연동 예시)
forward-socks5t / 127.0.0.1:9050 .
forward 192.168.*.*/ .
forward 10.*.*.*/ .
forward 127.*.*.*/ .
forward localhost/ .

# 압축 처리
compression-level 0

액션 파일 (/etc/privoxy/user.action)

# 글로벌 설정
{+hide-user-agent{Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0} \
 +hide-referrer{conditional-block} \
 +hide-from-header{block} \
 +prevent-compression \
 +session-cookies-only \
 +set-image-blocker{pattern} \
}
/

# 광고 차단
{+block{광고 네트워크} +handle-as-image}
.doubleclick.net
.googleadservices.com
.googlesyndication.com
.google-analytics.com
pagead*.googlesyndication.com
*.facebook.com/tr?
*.amazon-adsystem.com

# 추적기 차단
{+block{추적기} +handle-as-empty-document}
.scorecardresearch.com
.quantserve.com
.outbrain.com
.taboola.com
ssl.google-analytics.com
www.google-analytics.com

# 쿠키 정책
{+session-cookies-only +block-all-cookies}
.advertisingnetwork.com

{+prevent-setting-cookies}
.trackingsite.com

# 특정 사이트 예외
{-block -filter -hide-user-agent -hide-referrer}
.github.com
.stackoverflow.com
.wikipedia.org

# 이미지 차단
{+block-as-image +handle-as-image}
/banner/
/ad/
*_ad.
*_ads.
/sponsors/

# JavaScript 차단
{+block{JavaScript 광고}}
/js/ads.
/javascript/ads/

# 팝업 차단
{+filter{popups} +block}
/popup.
/popunder.

# 소셜 미디어 버튼 차단
{+block{소셜 미디어 위젯}}
.facebook.com/plugins/
.twitter.com/widgets/
plus.google.com/js/
.pinterest.com/js/

# 특정 헤더 제거
{+crunch-client-header{DNT} \
 +crunch-client-header{Referer} \
 +hide-accept-language{en-US,en;q=0.9} \
}
.sensitiveSite.com

필터 파일 (/etc/privoxy/user.filter)

# HTML 광고 제거
FILTER: ads 광고 요소 제거
s|<div[^>]*class="[^"]*ad[^"]*"[^>]*>.*?</div>||sig
s|<div[^>]*id="[^"]*ad[^"]*"[^>]*>.*?</div>||sig

# 추적 스크립트 제거
FILTER: tracking-scripts 추적 스크립트 제거
s|<script[^>]*google-analytics[^>]*>.*?</script>||sig
s|<script[^>]*facebook[^>]*>.*?</script>||sig

# 쿠키 동의 배너 제거
FILTER: cookie-banners 쿠키 배너 제거
s|<div[^>]*cookie-consent[^>]*>.*?</div>||sig
s|<div[^>]*gdpr[^>]*>.*?</div>||sig

# 자동재생 비활성화
FILTER: no-autoplay 자동재생 방지
s|autoplay="autoplay"|autoplay="false"|g
s|autoplay|data-autoplay|g

# 외부 폰트 차단
FILTER: block-fonts 외부 폰트 차단
s|<link[^>]*fonts\.googleapis\.com[^>]*>||g
s|@import.*fonts\.googleapis\.com[^;]*;||g

Tor 연동 설정

# Tor 설치
sudo apt-get install tor

# Privoxy 설정에 추가
forward-socks5t / 127.0.0.1:9050 .

# .onion 도메인 직접 전달
forward-socks5t .onion 127.0.0.1:9050 .

# 로컬 네트워크는 직접 연결
forward 192.168.*.*/ .
forward 10.*.*.*/ .
forward 127.*.*.*/ .
forward localhost/ .

# DNS 누출 방지
forward-socks5t / 127.0.0.1:9050 .

운영 명령어

# 서비스 관리
sudo systemctl start privoxy
sudo systemctl stop privoxy
sudo systemctl restart privoxy
sudo systemctl status privoxy

# 설정 테스트
privoxy --config-test /etc/privoxy/config

# 로그 모니터링
tail -f /var/log/privoxy/logfile

# 프로세스 확인
ps aux | grep privoxy

# 네트워크 연결 확인
netstat -tlnp | grep 8118

# 필터 효과 테스트
curl -x http://localhost:8118 http://example.com | grep -i "ad"

# 헤더 확인
curl -x http://localhost:8118 -I http://example.com

SSH 터널링 (동적 SOCKS 프록시)

SSH는 보안 셸 프로토콜로 원격 서버 접속뿐만 아니라 다양한 터널링 기능을 제공합니다. SSH 터널링을 통해 SOCKS 프록시를 생성하거나 특정 포트를 포워딩할 수 있으며, 모든 트래픽이 암호화되어 전송됩니다.

주요 용도

  • SOCKS 프록시: 동적 포트 포워딩으로 SOCKS5 프록시 생성
  • 보안 터널: 안전하지 않은 네트워크에서 암호화 통신
  • 방화벽 우회: 제한된 네트워크 환경에서 외부 접속
  • 포트 포워딩: 로컬/리모트 포트 포워딩
  • VPN 대체: 간단한 VPN 대체 솔루션

핵심 기능

  • 모든 트래픽 암호화
  • 인증 기반 접속 (패스워드/키)
  • 다중 터널 생성 가능
  • 압축 지원
  • 연결 유지 기능

SSH 클라이언트 설정 (~/.ssh/config)

# 글로벌 설정
Host *
    ServerAliveInterval 60
    ServerAliveCountMax 3
    Compression yes
    TCPKeepAlive yes
    ExitOnForwardFailure yes

# 프록시 서버 설정
Host proxy-server
    HostName proxy.example.com
    User proxyuser
    Port 22
    IdentityFile ~/.ssh/proxy_key
    DynamicForward 1080
    LocalForward 8080 localhost:8080
    RemoteForward 9000 localhost:3000

# 점프 호스트를 통한 연결
Host internal-server
    HostName 192.168.1.100
    User admin
    ProxyJump proxy-server

다양한 SSH 터널링 예시

# 1. 동적 포트 포워딩 (SOCKS 프록시)
ssh -D 1080 -N -f user@remote-server
# -D 1080: 로컬 1080 포트에 SOCKS 프록시 생성
# -N: 원격 명령 실행 안함
# -f: 백그라운드 실행

# 2. 로컬 포트 포워딩
ssh -L 8080:internal-server:80 user@gateway-server
# 로컬 8080 포트를 gateway를 통해 internal-server:80으로 포워딩

# 3. 리모트 포트 포워딩
ssh -R 9000:localhost:3000 user@remote-server
# 원격 서버의 9000 포트를 로컬 3000 포트로 포워딩

# 4. 다중 터널
ssh -D 1080 -L 3306:mysql-server:3306 -L 6379:redis-server:6379 user@gateway

# 5. 압축 사용
ssh -C -D 1080 user@remote-server

# 6. 특정 인터페이스 바인딩
ssh -D 192.168.1.100:1080 user@remote-server

# 7. IPv6 지원
ssh -D [::]:1080 user@remote-server

자동 재연결 스크립트

#!/bin/bash
# /usr/local/bin/ssh-tunnel.sh

# 설정
REMOTE_HOST="proxy.example.com"
REMOTE_USER="proxyuser"
REMOTE_PORT="22"
LOCAL_SOCKS_PORT="1080"
KEY_FILE="$HOME/.ssh/proxy_key"
LOG_FILE="/var/log/ssh-tunnel.log"

# 함수: 로깅
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}

# 함수: 터널 상태 확인
check_tunnel() {
    if pgrep -f "ssh.*-D $LOCAL_SOCKS_PORT" > /dev/null; then
        return 0
    else
        return 1
    fi
}

# 함수: 터널 시작
start_tunnel() {
    log "SSH 터널 시작 중..."
    ssh -D "$LOCAL_SOCKS_PORT" \
        -N \
        -f \
        -o ServerAliveInterval=60 \
        -o ServerAliveCountMax=3 \
        -o ExitOnForwardFailure=yes \
        -o StrictHostKeyChecking=no \
        -o UserKnownHostsFile=/dev/null \
        -i "$KEY_FILE" \
        -p "$REMOTE_PORT" \
        "$REMOTE_USER@$REMOTE_HOST"

    if [ $? -eq 0 ]; then
        log "SSH 터널 시작 성공"
        return 0
    else
        log "SSH 터널 시작 실패"
        return 1
    fi
}

# 함수: 터널 중지
stop_tunnel() {
    log "SSH 터널 중지 중..."
    pkill -f "ssh.*-D $LOCAL_SOCKS_PORT"
    sleep 2
}

# 메인 루프
while true; do
    if ! check_tunnel; then
        log "SSH 터널이 실행 중이지 않음. 재시작 중..."
        stop_tunnel
        start_tunnel
    fi
    sleep 30
done

systemd 서비스 파일

# /etc/systemd/system/ssh-tunnel.service
[Unit]
Description=SSH SOCKS Tunnel
After=network.target

[Service]
Type=simple
User=tunnel
ExecStart=/usr/local/bin/ssh-tunnel.sh
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

SSH 서버 설정 (/etc/ssh/sshd_config)

# 포트 포워딩 허용
AllowTcpForwarding yes
GatewayPorts yes
PermitTunnel yes

# 특정 사용자만 포워딩 허용
Match User proxyuser
    AllowTcpForwarding yes
    X11Forwarding no
    PermitTunnel yes
    ForceCommand /bin/false

# 보안 강화
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
MaxSessions 10

# 연결 유지
ClientAliveInterval 60
ClientAliveCountMax 3

고급 활용 예시

# ProxyCommand를 사용한 다단계 SSH
ssh -o ProxyCommand="ssh -W %h:%p jump-host" target-host

# SSH over HTTPS (443 포트)
ssh -p 443 -D 1080 user@server

# 대역폭 제한
ssh -D 1080 -o "IPQoS lowdelay" user@server

# 특정 암호화 알고리즘 사용
ssh -c aes256-gcm@openssh.com -D 1080 user@server

# 다중 홉 SOCKS 프록시
ssh -D 1080 -J user1@hop1,user2@hop2 user3@destination

모니터링 및 문제 해결

# 활성 SSH 터널 확인
lsof -i -n | grep ssh

# SOCKS 프록시 테스트
curl --socks5 localhost:1080 http://ipinfo.io

# SSH 연결 디버깅
ssh -vvv -D 1080 user@server

# 터널 트래픽 모니터링
tcpdump -i any -n port 1080

# SSH 세션 확인
who -a | grep pts

3proxy - 다목적 프록시 서버

3proxy는 작고 빠른 크로스 플랫폼 프록시 서버로, HTTP, HTTPS, SOCKS, FTP 등 다양한 프록시 프로토콜을 단일 애플리케이션에서 지원합니다. 매우 유연한 설정과 강력한 인증 기능을 제공합니다.

주요 용도

  • 다중 프로토콜 프록시: 하나의 서버에서 여러 프록시 서비스 제공
  • 인증 게이트웨이: 다양한 인증 방식 지원
  • 트래픽 제어: 대역폭 제한 및 트래픽 통계
  • NAT 환경: NAT 뒤의 서버들을 위한 프록시
  • 포트 매핑: TCP/UDP 포트 포워딩

핵심 기능

  • HTTP/HTTPS/SOCKS4/SOCKS5/FTP 프록시
  • 다양한 인증 방식 (내부, 시스템, RADIUS, LDAP)
  • 접근 제어 리스트
  • 트래픽 통계 및 로깅
  • 대역폭 제한
  • 프록시 체이닝
  • IPv6 지원

설치

# 소스 컴파일
wget https://github.com/3proxy/3proxy/archive/0.9.4.tar.gz
tar -xzf 0.9.4.tar.gz
cd 3proxy-0.9.4
make -f Makefile.Linux
sudo make -f Makefile.Linux install

# 바이너리 다운로드 (x64)
wget https://github.com/3proxy/3proxy/releases/download/0.9.4/3proxy-0.9.4.x64.tgz
tar -xzf 3proxy-0.9.4.x64.tgz
sudo cp 3proxy-0.9.4.x64/bin/* /usr/local/bin/

상세 설정 (/etc/3proxy/3proxy.cfg)

# 시스템 설정
daemon
pidfile /var/run/3proxy.pid
monitor /etc/3proxy/3proxy.cfg
nscache 65536
nscache6 65536
timeouts 1 5 30 60 180 1800 15 60

# DNS 서버
nserver 8.8.8.8
nserver 8.8.4.4
nserver 2001:4860:4860::8888
nserver 2001:4860:4860::8844

# 로깅 설정
log /var/log/3proxy/3proxy.log D
logformat "- +_L%t.%. %N.%p %E %U %C:%c %R:%r %O %I %h %T"
archiver gz /usr/bin/gzip %F
rotate 30

# 에러 로그
log /var/log/3proxy/3proxy.error.log E
logformat "- +_L%t.%. %N.%p %E %U %C:%c %R:%r %O %I %h %T %e"

# 통계 로그
log /var/log/3proxy/traffic.log
logformat "%U %b %I"

# 인증 설정
# auth none - 인증 없음
# auth iponly - IP 기반 인증
# auth nbname - NetBIOS 이름 인증
# auth strong - 사용자명/패스워드 인증
auth strong cache

# 사용자 정의
users admin:CL:AdminPass123
users user1:CL:User1Pass
users user2:CL:User2Pass
users guest:CL:GuestPass

# 시스템 사용자 인증
# auth system
# users $/etc/passwd

# RADIUS 인증
# authcache user 60
# auth radius
# radiusserver 192.168.1.100 secret 1812 1813

# ACL 정의
# 시간 기반 ACL
time worktime 1-5:9:00-18:00
time weekend 6-7:0:00-23:59

# 네트워크 기반 ACL
parent 1000 http 0.0.0.0 0

# 서비스별 설정
# HTTP 프록시
proxy -p3128 -a -n
allow admin
allow user1,user2 worktime
deny guest
allow * 127.0.0.1,192.168.1.0/24
deny *

# HTTPS 프록시 (CONNECT)
proxy -p3129 -a -n
allow admin
allow user1,user2
deny * 

# SOCKS5 프록시
socks -p1080 -a -n
allow admin
allow user1,user2
deny *

# 투명 HTTP 프록시
tcppm -i0.0.0.0 -p8080 192.168.1.100 80

# FTP 프록시
ftppr -p2121 -a -n
allow admin,user1
deny *

# POP3 프록시
pop3p -p1110 -a -n
allow *

# 포트 매핑
tcppm -i0.0.0.0 -p2222 192.168.1.10 22
udppm -i0.0.0.0 -p53 8.8.8.8 53

# 대역폭 제한 (바이트/초)
bandlimin 1048576 * * * *
bandlimout 1048576 * * * *

# 특정 사용자 대역폭 제한
bandlimin 524288 user1,user2 * * *
bandlimout 524288 user1,user2 * * *

# 연결 수 제한
maxconn 100

# 프록시 체이닝
parent 1000 socks5 upstream.proxy.com 1080 proxyuser proxypass
chain

# 접근 규칙
# IP 기반
allow * 192.168.1.0/24
allow * 10.0.0.0/8

# 도메인 기반
allow * * *.example.com *
deny * * *.blocked-site.com *

# 포트 기반
allow * * * 80,443,8080
deny * * * 25,110,143

# 최종 거부
deny *

고급 설정 예시

# 로드 밸런싱
parent 500 socks5 server1.example.com 1080
parent 500 socks5 server2.example.com 1080

# 페일오버
parent 1000 socks5 primary.example.com 1080
parent 500 socks5 backup.example.com 1080

# 특정 도메인별 라우팅
allow * * *.google.com *
parent 1000 http proxy.google.com 8080
deny * * *.facebook.com *

# 캐싱 프록시
plugin /usr/local/lib/3proxy/CachePlugin.so cache_size=1024

# SSL 인터셉션
plugin /usr/local/lib/3proxy/SSLPlugin.so \
    cert=/etc/3proxy/cert.pem \
    key=/etc/3proxy/key.pem

# 안티바이러스 통합
plugin /usr/local/lib/3proxy/AVPlugin.so \
    scanner=/usr/bin/clamdscan

웹 관리 인터페이스 설정

# 관리 인터페이스 활성화
admin -p8081 -a -n
allow admin 127.0.0.1
deny *

# 통계 페이지
countin 1 10
countout 1 10
counttraf count
monitor /etc/3proxy/3proxy.cfg

운영 명령어

# 서비스 시작
3proxy /etc/3proxy/3proxy.cfg

# 데몬 모드로 시작
3proxy -d /etc/3proxy/3proxy.cfg

# 설정 테스트
3proxy -t /etc/3proxy/3proxy.cfg

# 프로세스 재시작
kill -USR1 $(cat /var/run/3proxy.pid)

# 로그 로테이션
kill -USR2 $(cat /var/run/3proxy.pid)

# 통계 확인
3proxy -s /var/run/3proxy.stats

# 활성 연결 확인
netstat -antp | grep 3proxy

# 로그 모니터링
tail -f /var/log/3proxy/3proxy.log

systemd 서비스 파일

# /etc/systemd/system/3proxy.service
[Unit]
Description=3proxy Proxy Server
After=network.target

[Service]
Type=forking
PIDFile=/var/run/3proxy.pid
ExecStart=/usr/local/bin/3proxy /etc/3proxy/3proxy.cfg
ExecReload=/bin/kill -USR1 $MAINPID
ExecStop=/bin/kill -TERM $MAINPID
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

Dante - SOCKS 서버

Dante는 기능이 풍부한 SOCKS 서버 구현체로, SOCKS v4와 v5를 모두 지원합니다. 엔터프라이즈 환경에서 사용하기 적합한 강력한 인증과 접근 제어 기능을 제공합니다.

주요 용도

  • SOCKS 프록시 서버: 애플리케이션 레벨 프록시
  • 방화벽 통과: 제한된 네트워크 환경에서 외부 접속
  • 프로토콜 독립적 프록시: TCP/UDP 트래픽 중계
  • 인증 게이트웨이: 다양한 인증 메커니즘 지원

핵심 기능

  • SOCKS v4/v4a/v5 완전 지원
  • 다양한 인증 방식 (없음, 사용자명/패스워드, GSS-API, PAM)
  • 세밀한 접근 제어
  • 대역폭 관리
  • IPv6 지원
  • UDP 연결 지원

설치

# Ubuntu/Debian
sudo apt-get update
sudo apt-get install dante-server

# CentOS/RHEL
sudo yum install epel-release
sudo yum install dante-server

# 소스 컴파일
wget https://www.inet.no/dante/files/dante-1.4.3.tar.gz
tar -xzf dante-1.4.3.tar.gz
cd dante-1.4.3
./configure --prefix=/usr/local \
    --with-socks-conf=/etc/sockd.conf \
    --with-sockd-conf=/etc/sockd.conf
make
sudo make install

서버 설정 (/etc/danted.conf)

# 로깅 설정
logoutput: /var/log/dante/dante.log
errorlog: /var/log/dante/error.log
debug: 1

# 서버 설정
internal: eth0 port = 1080
internal: 0.0.0.0 port = 1080
external: eth0

# 인증 방법
socksmethod: none username

# PAM 인증 사용
#socksmethod: pam.username

# 사용자 권한
user.privileged: root
user.unprivileged: nobody
user.libwrap: nobody

# 타임아웃 설정
timeout.negotiate: 30
timeout.io: 3600
timeout.tcp_fin_wait: 10

# 클라이언트 접속 규칙
client pass {
    from: 192.168.1.0/24 to: 0.0.0.0/0
    log: connect disconnect error
}

client pass {
    from: 10.0.0.0/8 to: 0.0.0.0/0
    log: connect disconnect
}

client block {
    from: 0.0.0.0/0 to: 0.0.0.0/0
    log: connect error
}

# SOCKS 규칙
socks pass {
    from: 192.168.1.0/24 to: 0.0.0.0/0
    protocol: tcp udp
    command: bind connect udpassociate
    log: connect disconnect error
    socksmethod: none
}

socks pass {
    from: 10.0.0.0/8 to: 0.0.0.0/0
    protocol: tcp
    command: connect
    log: connect disconnect
    socksmethod: username
}

# 특정 대상 차단
socks block {
    from: 0.0.0.0/0 to: .facebook.com
    log: connect error
}

socks block {
    from: 0.0.0.0/0 to: 224.0.0.0/4  # 멀티캐스트
    log: connect error
}

# 포트 기반 규칙
socks pass {
    from: 0.0.0.0/0 to: 0.0.0.0/0 port = 80
    protocol: tcp
    command: connect
}

socks pass {
    from: 0.0.0.0/0 to: 0.0.0.0/0 port = 443
    protocol: tcp
    command: connect
}

socks block {
    from: 0.0.0.0/0 to: 0.0.0.0/0 port = 25
    log: connect error
}

# 대역폭 제한
socks pass {
    from: 0.0.0.0/0 to: 0.0.0.0/0
    bandwidth: 1048576  # 1MB/s
}

# 기본 차단
socks block {
    from: 0.0.0.0/0 to: 0.0.0.0/0
    log: connect error
}

클라이언트 설정 (/etc/dante.conf)

# 로깅
debug: 1
logoutput: stderr

# 서버 연결 설정
route {
    from: 0.0.0.0/0 to: 0.0.0.0/0 via: 127.0.0.1 port = 1080
    protocol: tcp udp
    proxyprotocol: socks_v5
    method: none username
}

# 직접 연결 (프록시 사용 안함)
route {
    from: 0.0.0.0/0 to: 192.168.0.0/16 via: direct
}

route {
    from: 0.0.0.0/0 to: 10.0.0.0/8 via: direct
}

route {
    from: 0.0.0.0/0 to: 127.0.0.0/8 via: direct
}

고급 설정 예시

# GSS-API (Kerberos) 인증
socksmethod: gssapi.per-session

# LDAP 통합
extension: bind-extension.so
extension.bind.so: ldap://ldap.example.com

# 연결별 로깅
socks pass {
    from: 0.0.0.0/0 to: 0.0.0.0/0
    log: data  # 모든 데이터 로깅 (주의: 대용량)
}

# 세션 제한
session.max: 1000      # 최대 세션 수
session.throttle: 100  # 초당 최대 새 세션

# CPU 친화도
cpu.mask: 0x01  # CPU 0에 바인딩

# 버퍼 크기
socket.recvbuf.tcp: 65536
socket.sndbuf.tcp: 65536

운영 명령어

# 서비스 관리
sudo systemctl start danted
sudo systemctl stop danted
sudo systemctl restart danted
sudo systemctl status danted

# 설정 검증
danted -V -f /etc/danted.conf

# 디버그 모드 실행
sudo danted -d -f /etc/danted.conf

# 로그 모니터링
tail -f /var/log/dante/dante.log

# 활성 연결 확인
ss -antp | grep danted

# SOCKS 프록시 테스트
curl --socks5 localhost:1080 http://ipinfo.io

# socksify를 사용한 프로그램 실행
socksify wget http://example.com/file.zip

클라이언트 도구 사용

# socksify 설정
export SOCKS_SERVER=127.0.0.1:1080
export SOCKS_USERNAME=user
export SOCKS_PASSWORD=pass

# 프로그램 실행
socksify firefox
socksify ssh user@remote-host

# tsocks 설정 (/etc/tsocks.conf)
server = 127.0.0.1
server_type = 5
server_port = 1080

보안 고려사항 및 모범 사례

접근 제어 강화

# iptables 규칙 예시
# 프록시 포트 접근 제한
iptables -A INPUT -p tcp --dport 8888 -s 192.168.1.0/24 -j ACCEPT
iptables -A INPUT -p tcp --dport 8888 -j DROP

# 연결 수 제한
iptables -A INPUT -p tcp --dport 8888 -m connlimit --connlimit-above 10 -j REJECT

# Rate limiting
iptables -A INPUT -p tcp --dport 8888 -m hashlimit \
    --hashlimit-name proxy_limit \
    --hashlimit-above 5/min \
    --hashlimit-burst 10 \
    --hashlimit-mode srcip \
    -j DROP

# GeoIP 기반 차단
iptables -A INPUT -m geoip --src-cc CN,RU -j DROP

인증 구현

# 기본 인증 파일 생성
htpasswd -c /etc/proxy/users admin
htpasswd /etc/proxy/users user1

# LDAP 인증 설정 예시
auth_param basic program /usr/lib/squid/basic_ldap_auth \
    -b "dc=example,dc=com" \
    -f "(&(objectClass=person)(uid=%s))" \
    ldap://ldap.example.com

# RADIUS 인증
auth_param basic program /usr/lib/squid/basic_radius_auth \
    -h radius.example.com \
    -p 1812 \
    -s radius-secret

로깅 및 모니터링

# rsyslog 설정 (/etc/rsyslog.d/proxy.conf)
:programname, isequal, "proxy" /var/log/proxy/proxy.log
& stop

# 로그 로테이션 (/etc/logrotate.d/proxy)
/var/log/proxy/*.log {
    daily
    rotate 30
    compress
    delaycompress
    missingok
    notifempty
    create 0640 proxy proxy
    sharedscripts
    postrotate
        /bin/kill -USR1 $(cat /var/run/proxy.pid) 2>/dev/null || true
    endscript
}

# 실시간 모니터링 스크립트
#!/bin/bash
watch -n 1 '
echo "=== 활성 연결 ==="
ss -antp | grep -E "(8888|3128|1080)" | wc -l
echo
echo "=== 상위 클라이언트 IP ==="
ss -antp | grep ESTAB | grep -E "(8888|3128|1080)" | \
    awk "{print \$5}" | cut -d: -f1 | sort | uniq -c | sort -rn | head -5
echo
echo "=== 대역폭 사용량 ==="
iftop -t -s 1 -L 5 -f "port 8888 or port 3128 or port 1080" 2>/dev/null | \
    grep "Total send and receive rate"
'

보안 강화 체크리스트

# 1. 시스템 보안
- 최신 패치 적용
- 불필요한 서비스 비활성화
- SELinux/AppArmor 활성화

# 2. 네트워크 보안
- 방화벽 규칙 최소화
- 사설 IP 대역만 허용
- 포트 변경 고려

# 3. 인증 및 암호화
- 강력한 패스워드 정책
- 2FA 구현 검토
- SSL/TLS 인증서 사용

# 4. 모니터링
- 로그 중앙화
- 이상 트래픽 감지
- 정기 감사

# 5. 성능 최적화
- 적절한 타임아웃 설정
- 연결 수 제한
- 캐시 활용

문제 해결 가이드

# 연결 문제 진단
# 1. 프록시 서비스 상태 확인
systemctl status proxy-service

# 2. 포트 리스닝 확인
netstat -tlnp | grep proxy

# 3. 방화벽 규칙 확인
iptables -L -n -v

# 4. 로그 분석
grep -i error /var/log/proxy/*.log

# 5. 네트워크 연결 테스트
telnet proxy-server 8888
curl -v --proxy http://proxy-server:8888 http://example.com

# 6. DNS 해석 확인
nslookup example.com
dig example.com @8.8.8.8

# 7. 프로세스 리소스 확인
top -p $(pgrep proxy)

리눅스 서버에서 사용할 수 있는 주요 프록시 각 도구는 고유한 특징과 사용 사례를 가지고 있으므로, 환경과 요구사항에 맞는 적절한 도구를 선택하여 사용하시기 바랍니다.

728x90
그리드형(광고전용)

댓글