squid

squid
LinuxにProxy環境を構築する為のソフトウェア。
WebProxy以外にも、設定次第ではFTPProxyやReverseProxy、RelayProxyとかも構築出来る。

インストール

1. ビルド・インストール
事前に最新版のsquidをダウンロードしておく事。
オフィシャルにはLanguagePackもあるけれど、squid本体に同梱されているから別途ダウンロードする必要は無い。
./configureかける時に、普通はオプションとかを直接打ち込むのだが、
自分の場合後々流用したり編集したりする事が多いので、オプションだけ別ファイルにしておく。

$ tar zxvf squid-3.3.9.tar.gz
$ echo "--enable-default-err-language=Japanese --enable-err-languages=Japanese --enable-useragent-log --enable-referer-log --enable-linux-netfilter --enable-poll --enable-ssl --enable-large-cache-files --enable-coss-aio-ops --enable-storeio=ufs,aufs,diskd --enable-auth-modules=LDAP,PAM,SMB,MSNT --enable-internal-dns --disable-ident-lookups --disable-ipv6" > ./configure_option.opt
$ cd squid-3.3.9
$ ./configure `cat ../configure_option.opt`
$ make
$ make install

上記の設定だと、インストールディレクトリは『/usr/local/squid』になる。(“--prefix=***”で変更可能)
また、設定ファイルも『/usr/local/squid/etc』の中にあるsquid.confになる。(“--sysconfdir=***”で変更可能。普通だったら“--sysconfdir=/etc”とか)
オプションの詳細についてはドキュメントを読むか、下のサイト様に詳細が書いてある。
サーバ・クライアント設定集 - squidインストールと設定
コロのLinuxサーバー構築 - Squidによるプロキシサーバーの構築


2. 設定
squidの設定内容は説明書で7000行もあるので、必須な物を抜粋して記述していく。
併せて、squidの動作ログ、キャッシュデータ、ダンプを設置するディレクトリの作成と、動作ユーザーも作成する。
なお、上記ディレクトリはファイルの読み書きが頻繁に行われる為、squidデータ専用のHDDを購入→squid専用パーティションとして作成した所を指定する事

$ groupadd squid
$ useradd -g squid -s /sbin/nologin squid
$ mkdir /var/squid
$ cd /var/squid
$ mkdir cache dump logs
$ chown -R squid.squid /var/squid
$ chmod -R 750 /var/squid

必要に応じて、/etc/passwdのhomeを書き換える事

$ vi /usr/local/squid/etc/squid.conf
#
# Recommended minimum configuration:
#

# Example rule allowing access from your local networks.
# Adapt to list your (internal) IP networks from where browsing
# should be allowed
acl localhost src 127.0.0.1/32  #squidサーバー自身
acl localnet src 192.168.1.0/24 #ローカルネットワークアドレス

acl SSL_ports port 443          #SSL系統だけは別で設定
                                #Safe_portsで指定されているポートは、squidを指定するだけで利用可能にする
acl Safe_ports port 80          # http
#acl Safe_ports port 21         # ftp
acl Safe_ports port 443         # https
#acl Safe_ports port 70         # gopher
#acl Safe_ports port 210        # wais
#acl Safe_ports port 1025-65535 # unregistered ports
#acl Safe_ports port 280        # http-mgmt
#acl Safe_ports port 488        # gss-http
#acl Safe_ports port 591        # filemaker
#acl Safe_ports port 777        # multiling http
acl CONNECT method CONNECT

#以下、http_accessとallow/denyを使用してフィルターをかける
#
# Recommended minimum Access Permission configuration:
#
# Deny requests to certain unsafe ports
http_access deny !Safe_ports
# Deny CONNECT to other than secure SSL ports
http_access deny CONNECT !SSL_ports

# Only allow cachemgr access from localhost
http_access allow localhost manager
http_access deny manager

# We strongly recommend the following be uncommented to protect innocent
# web applications running on the proxy server who think the only
# one who can access services on "localhost" is a local user
#http_access deny to_localhost

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

# Example rule allowing access from your local networks.
# Adapt localnet in the ACL section to list your (internal) IP networks
# from where browsing should be allowed
http_access allow localnet
http_access allow localhost

# And finally deny all other access to this proxy
http_access deny all

# Squid normally listens to port 3128
http_port 8080               #待ち受けるポート番号

# Uncomment and adjust the following to add a disk cache directory.
cache_dir ufs /var/squid/cache 128 8 16
                             #キャッシュデータの保存方法をufsにして、
                             #親ディレクトリを8、親の中の子ディレクトリを16、子ディレクトリ内のキャッシュデータの最大サイズはそれぞれ128MByteにする
cache_effective_user squid   #キャッシュデータを書き込むユーザー
cache_effective_group squid  #キャッシュデータを書き込むユーザーのグループ
cache_mem 1024 MB            #使用するメモリプール

# Leave coredumps in the first cache dir
#coredump_dir /usr/local/squid/var/cache/squid
coredump_dir /var/squid/dump

# File descriptor
max_filedesc 65535

#
# Add any of your own refresh_pattern entries above these.
#
#アクセスする度にリフレッシュ(再アクセス)するファイルの種類
refresh_pattern ^ftp:       1440    20% 10080
refresh_pattern ^gopher:    1440    0%  1440
refresh_pattern -i (/cgi-bin/|\?) 0 0%  0
refresh_pattern .       0   20% 4320

# LOG
access_log /var/squid/logs/access.log      #クライアントがsquidにアクセスしてきたログ
cache_log /var/squid/logs/cache.log        #squidの動作ログ
cache_store_log /var/squid/logs/store.log  #保存したキャッシュのログ

# Reply Host Message
visible_hostname unknown                        #squidのDNS逆引き結果(unknownだと相手に逆引きを通知しない)
forwarded_for off                               #プライベートIPを外に漏らさない
#request_header_access Referer deny all         #HTTPヘッダーのReferer(リンク元情報)を消す
#request_header_access User-Agent deny all      #HTTPヘッダーのUser-Agent(ブラウザ情報)を消す
request_header_access Via deny all              #squidの情報(バージョンとか)を外に漏らさない
request_header_access Cache_Control deny all    #キャッシュ制御情報を外に漏らさない
request_header_access X-Forwarded-For deny all  #クライアントのIPアドレスを通知しない

# Squid DNS process
cache_dns_program /usr/local/squid/libexec/dnsserver
pid_filename /var/run/squid/squid.pid
dns_children 32 startup=4 idle=16  #Squidが使用するDNSプロセス
dns_v4_first on                    #IPv4とIPv6両立環境の時にIPv4に優先してアクセス

他にも、メモリキャッシュの容量、ログローテート設定とかをする必要があるが、今回は省略。


3. 起動準備
ソースからインストールすると、起動スクリプトとかも時前で用意する必要がある。
また、起動前にキャッシュフォルダの構成を作成したりする事も必要。

//起動スクリプトを作る。必要に応じてランレベルからシンボリックリンクを張り、自動起動の設定もする。
$ vi /etc/init.d/squid
---
#!/bin/sh
#
# squid           This shell script takes care of starting and stopping
#                 squid (the Squid traffic proxy)
#
# chkconfig: 345 85 20
# description: Squid is a proxy that network traffic on behalf of request

# ---------------------------- #

# Squid parameters.
prefix="/usr/local/squid"
exec_prefix="${prefix}/sbin/squid"
pid_dir="/var/lock/subsys/squid"
conf_dir="${prefix}/etc/squid.conf"

# ---------------------------- #

# Load binary PATH.
PATH=/bin:/sbin:/usr/bin:/usr/sbin:${prefix}/bin:${prefix}/sbin
export PATH

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check network startup status.
[ ${NETWORKING} = "no" ] && exit 0

# Check squid binary permission.
[ -x ${exec_prefix} ] || exit 0

# Check squid configuration presence.
[ -f ${conf_dir} ] || exit 0

# Change file descriptor
ulimit -HSn 65535

# ---------------------------- #

case "$1" in
    start)
        echo -n "Starting squid: "
        ${exec_prefix} -NsY ${conf_dir} &
        RETVAL=$?
        [ ${RETVAL} -eq 0 ] && touch ${pid_dir}
    ;;

    stop)
        echo -n "Shutdown squid: "
        ${exec_prefix} -k shutdown &
        RETVAL=$?
        [ ${RETVAL} -eq 0 ] && rm -f ${pid_dir}
    ;;

    restart)
        stop && start
    ;;

    reload)
        echo -n "Reload squid: "
        ${exec_prefix} -k reconfigure
        exit $?
    ;;

    status)
        ${exec_prefix} -k check
        exit $?
    ;;

    *)
        echo "Usage: rc.squid {start|stop|restart|reload|status}"
        exit 1
    ;;
esac

exit 0

 
OSがsystemdを使っている場合、次のサービスファイルを作成する

# vi /usr/lib/systemd/system/squid.service
---
[Unit]
Description=Squid Web Proxy Server
Documentation=man:squid(8)
After=network.target network-online.target nss-lookup.target

[Service]
Type=forking
User=squid
Group=squid

# Make sure /var/run/squid exists
PermissionsStartOnly=true
ExecStartPre=/usr/bin/install -d /var/run/squid -o squid -g squid
ExecStartPre=/usr/local/squid/sbin/squid --foreground -z

# Set environment variable
PIDFile=/var/run/squid/squid.pid
Environment=CONFIG=/usr/local/squid/etc/squid.conf

ExecStart=/usr/local/squid/sbin/squid -sYC ${CONFIG}
ExecStop=/usr/local/squid/sbin/squid -k shutdown
ExecReload=/usr/local/squid/sbin/squid -k reconfigure

LimitNOFILE=65535
LimitNPROC=65535
StartLimitBurst=0
KillMode=mixed

[Install]
WantedBy=multi-user.target
//設定ファイルの整合性チェック。エラーが出たら設定ファイルを見直す
$ /usr/local/squid/sbin/squid -k parse

//キャッシュディレクトリ内のサブディレクトリを設定通りに作る
$ /usr/local/squid/sbin/squid -z

//squidを起動する
$ /etc/init.d/squid start
$ systemctl start  squid

//squidを停止する
$ /etc/init.d/squid stop
$ systemctl stop squid

//squidの動作確認
$ /usr/local/squid/bin/squidclient -h 127.0.0.1 -p 8080 http://www.yahoo.co.jp/