Lessons

Squid Proxy Server

Level: Advanced Module: Web Services 14 min read Lesson 27 of 66

Overview

  • What you’ll learn: Forward proxy concepts, Squid installation on Ubuntu, access control lists (ACLs), http_access rules, cache configuration, disk and memory caching, and proxy authentication with basic and NCSA methods.
  • Prerequisites: Module 3 — Lessons 21–26 (HTTP Fundamentals through Reverse Proxy and Load Balancing)
  • Estimated reading time: 18 minutes

Introduction

A forward proxy is a server that sits between client machines on an internal network and the Internet, intercepting outbound requests and forwarding them on behalf of the clients. Unlike a reverse proxy (which protects servers), a forward proxy protects and controls clients. Forward proxies are widely used in enterprise environments for content filtering, bandwidth optimization through caching, access control, and monitoring employee Internet usage.

Squid is the most widely deployed open-source forward proxy and caching server. It has been in active development since the 1990s and supports HTTP, HTTPS, FTP, and other protocols. Squid can cache frequently accessed content to reduce bandwidth consumption and improve response times, enforce access policies through a flexible ACL system, and authenticate users before allowing Internet access.

In this lesson, you will learn the theory behind forward proxies, install and configure Squid on Ubuntu Server, define access control lists, configure caching parameters, and set up user authentication. By the end, you will be able to deploy a fully functional Squid proxy that controls and optimizes Internet access for your network.

Forward Proxy Concepts

In a forward proxy architecture, clients are configured to send their HTTP requests to the proxy server rather than directly to the destination. The proxy evaluates the request against its access policies, and if allowed, fetches the resource from the Internet and returns it to the client. The destination server sees the proxy’s IP address, not the client’s.

Forward proxies serve several purposes in enterprise and educational environments:

  • Content Filtering: Block access to specific websites, domains, or content categories (e.g., social media, malware sites).
  • Caching: Store frequently accessed content locally, reducing bandwidth usage and improving response times for repeated requests.
  • Access Control: Restrict Internet access based on source IP, user authentication, time of day, or destination.
  • Anonymity: Hide client IP addresses from destination servers, providing a layer of privacy.
  • Monitoring and Logging: Record all web traffic for auditing, compliance, or troubleshooting purposes.

There are two deployment modes for forward proxies:

  • Explicit Proxy: Clients are manually configured (or auto-configured via PAC files) to use the proxy. The client knows it is communicating through a proxy.
  • Transparent Proxy: Network infrastructure (firewall/router rules) redirects traffic through the proxy without client configuration. The client is unaware of the proxy.

Installing and Configuring Squid on Ubuntu

Squid is available in the Ubuntu default repositories. Installation is straightforward, and the main configuration file is located at /etc/squid/squid.conf. The default configuration is extensively commented and spans thousands of lines. It is good practice to back up the original before making changes.

# Install Squid
$ sudo apt update
$ sudo apt install squid -y

# Verify installation and service status
$ squid -v | head -1
Squid Cache: Version 5.7

$ sudo systemctl status squid
● squid.service - Squid Web Proxy Server
     Active: active (running)

# Back up the original configuration
$ sudo cp /etc/squid/squid.conf /etc/squid/squid.conf.original

# The default config has ~8000 lines of comments and directives
$ wc -l /etc/squid/squid.conf
8441 /etc/squid/squid.conf

# Strip comments to see active directives
$ grep -v "^#" /etc/squid/squid.conf | grep -v "^$"

After installation, Squid listens on port 3128 by default. The default configuration denies all external access and only permits requests from localhost. You need to customize the ACLs and access rules to allow your network’s clients to use the proxy.

# /etc/squid/squid.conf — Basic configuration

# Define the port Squid listens on
http_port 3128

# Define your local network
acl localnet src 10.0.0.0/8
acl localnet src 172.16.0.0/12
acl localnet src 192.168.0.0/16

# Define safe ports
acl SSL_ports port 443
acl Safe_ports port 80          # http
acl Safe_ports port 443         # https
acl Safe_ports port 21          # ftp
acl Safe_ports port 1025-65535  # unregistered ports

# Access rules — order matters (first match wins)
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow localhost manager
http_access deny manager
http_access allow localnet
http_access allow localhost
http_access deny all

# Restart Squid to apply changes
$ sudo systemctl restart squid

# Test the proxy from a client
$ curl -x http://proxy-server:3128 http://www.example.com/

ACLs and http_access Rules

Squid’s access control system is built on two components: ACL definitions that classify requests based on various criteria, and http_access rules that allow or deny requests based on those classifications. The ACL system is extremely flexible and supports many element types.

Common ACL types include:

  • src: Match based on client source IP address or network range.
  • dst: Match based on destination IP address.
  • dstdomain: Match based on destination domain name.
  • port: Match based on destination port number.
  • time: Match based on day of week and time of day.
  • url_regex: Match based on regular expression against the URL.
  • proxy_auth: Match based on authenticated username.
# ACL examples in /etc/squid/squid.conf

# Block specific domains
acl blocked_sites dstdomain .facebook.com .twitter.com .tiktok.com
http_access deny blocked_sites

# Block domains from a file
acl blocked_list dstdomain "/etc/squid/blocked-domains.txt"
http_access deny blocked_list

# Allow access only during business hours (Mon-Fri, 8am-6pm)
acl business_hours time MTWHF 08:00-18:00
acl staff_network src 192.168.10.0/24
http_access allow staff_network business_hours
http_access deny staff_network

# Block URLs containing certain keywords
acl bad_urls url_regex -i gambling poker casino
http_access deny bad_urls

# Allow specific IPs unrestricted access (e.g., IT department)
acl it_dept src 192.168.10.50 192.168.10.51 192.168.10.52
http_access allow it_dept

# Create the blocked domains file
$ sudo tee /etc/squid/blocked-domains.txt <<EOF
.facebook.com
.instagram.com
.tiktok.com
.reddit.com
EOF

# Reconfigure Squid without full restart
$ sudo squid -k reconfigure

The http_access rules are processed from top to bottom, and the first matching rule determines whether the request is allowed or denied. This means rule ordering is critical — more specific rules should appear before general ones. Always end with http_access deny all as a safety net.

Cache Configuration

Caching is one of Squid’s primary features. When a client requests a resource that Squid has already cached, it returns the cached copy without contacting the origin server. This reduces bandwidth, lowers latency for clients, and decreases load on origin servers. Squid supports both memory caching (fast, limited) and disk caching (larger, slower).

# /etc/squid/squid.conf — Cache configuration

# Memory cache size (objects stored in RAM for fastest access)
cache_mem 256 MB

# Maximum size of individual objects stored in memory
maximum_object_size_in_memory 1 MB

# Disk cache: type, directory, size (MB), L1 dirs, L2 dirs
# ufs = standard Squid storage, 10000 MB = 10 GB
cache_dir ufs /var/spool/squid 10000 16 256

# Maximum size of individual cached objects on disk
maximum_object_size 100 MB

# Minimum object size to cache (skip tiny objects)
minimum_object_size 0 KB

# Cache replacement policy
cache_replacement_policy lru

# Memory replacement policy
memory_replacement_policy lru

# Cache log location
cache_log /var/log/squid/cache.log

# Access log — records all client requests
access_log /var/log/squid/access.log squid

# Refresh patterns: min_age percentage max_age
# Controls how long cached objects remain fresh
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

# Initialize the cache directories (first time only)
$ sudo squid -z

# Restart to apply cache changes
$ sudo systemctl restart squid

# Monitor cache performance
$ sudo squidclient -h 127.0.0.1 mgr:info | grep -A5 "Cache"

# View cache hit/miss statistics
$ sudo tail -f /var/log/squid/access.log | awk '{print $4}'

The cache_dir directive defines where and how much disk space Squid uses for caching. The ufs storage type is the default and works well for most deployments. The two numbers after the size (16 and 256) define the number of first-level and second-level subdirectories used to organize cached files. The refresh_pattern directives control how Squid determines whether a cached object is still fresh or needs revalidation from the origin server.

Authentication

Squid supports several authentication schemes to require users to identify themselves before accessing the Internet. The most common approach is NCSA Basic authentication, which uses an Apache-compatible password file. This is suitable for small to medium deployments. For larger environments, LDAP or Active Directory integration is recommended.

# Install the htpasswd utility (from apache2-utils)
$ sudo apt install apache2-utils -y

# Create a password file and add the first user
$ sudo htpasswd -c /etc/squid/passwords user1
New password: ********
Re-type new password: ********

# Add additional users (without -c flag to avoid overwriting)
$ sudo htpasswd /etc/squid/passwords user2
$ sudo htpasswd /etc/squid/passwords user3

# Set correct permissions
$ sudo chown proxy:proxy /etc/squid/passwords
$ sudo chmod 640 /etc/squid/passwords

# Configure authentication in /etc/squid/squid.conf
# Add these lines BEFORE any http_access rules

# Define the authentication helper program
auth_param basic program /usr/lib/squid/basic_ncsa_auth /etc/squid/passwords
auth_param basic children 5 startup=5 idle=1
auth_param basic realm Squid Proxy Authentication
auth_param basic credentialsttl 2 hours

# Create an ACL for authenticated users
acl authenticated proxy_auth REQUIRED

# Require authentication for all access
http_access allow authenticated
http_access deny all

# Restart Squid
$ sudo systemctl restart squid

# Test authenticated proxy access
$ curl -x http://user1:password@proxy-server:3128 http://www.example.com/

# Verify in the access log that the username appears
$ sudo tail -5 /var/log/squid/access.log

The auth_param directives configure the authentication mechanism. The basic_ncsa_auth helper reads the password file and validates credentials. The children parameter controls how many authentication helper processes run — increase this for environments with many concurrent users. The credentialsttl setting controls how long Squid caches valid credentials before requiring re-authentication.

Key Takeaways

  • A forward proxy acts on behalf of clients, providing content filtering, caching, access control, and monitoring for outbound Internet traffic.
  • Squid is installed via apt on Ubuntu and listens on port 3128 by default; the main configuration file is /etc/squid/squid.conf.
  • ACLs classify requests by source IP, destination domain, port, time, URL pattern, or authenticated user; http_access rules allow or deny based on these classifications, processed top to bottom.
  • Squid caching uses both memory (cache_mem) and disk (cache_dir) storage, with refresh_pattern directives controlling object freshness and revalidation timing.
  • NCSA Basic authentication with htpasswd provides simple user-based access control; for larger deployments, integrate with LDAP or Active Directory.

What’s Next

Congratulations on completing Module 3 — Web Services! You have learned HTTP fundamentals, configured Apache2 and Nginx web servers, secured sites with TLS/HTTPS, deployed PHP applications, set up reverse proxies with load balancing, and configured Squid as a forward proxy. In Module 4, you will explore Storage and File Systems, covering disk partitioning, LVM, file system types, NFS, and Samba.

繁體中文

概述

  • 學習目標:正向代理概念、在 Ubuntu 上安裝 Squid、存取控制清單(ACL)、http_access 規則、快取設定、磁碟與記憶體快取,以及使用 basic 和 NCSA 方法的代理認證。
  • 先決條件:模組 3 — 第 21–26 課(從 HTTP 基礎到反向代理與負載平衡)
  • 預計閱讀時間:18 分鐘

簡介

正向代理是位於內部網路上的用戶端機器和網際網路之間的伺服器,攔截外出請求並代表用戶端轉發。與反向代理(保護伺服器)不同,正向代理保護和控制用戶端。正向代理在企業環境中被廣泛用於內容過濾、透過快取最佳化頻寬、存取控制和監控員工的網際網路使用。

Squid 是部署最廣泛的開源正向代理和快取伺服器。它自 1990 年代以來一直在積極開發中,支援 HTTP、HTTPS、FTP 和其他協定。Squid 可以快取經常存取的內容以減少頻寬消耗並改善回應時間、透過靈活的 ACL 系統執行存取政策,以及在允許網際網路存取之前對使用者進行認證。

在本課程中,您將學習正向代理背後的理論、在 Ubuntu Server 上安裝和設定 Squid、定義存取控制清單、設定快取參數,以及設定使用者認證。完成後,您將能夠部署一個功能完整的 Squid 代理,控制和最佳化您網路的網際網路存取。

正向代理概念

在正向代理架構中,用戶端被設定為將其 HTTP 請求發送到代理伺服器,而不是直接發送到目的地。代理根據其存取政策評估請求,如果允許,則從網際網路獲取資源並將其返回給用戶端。目的地伺服器看到的是代理的 IP 位址,而不是用戶端的。

正向代理在企業和教育環境中有多種用途:

  • 內容過濾:封鎖對特定網站、網域或內容類別的存取(例如社交媒體、惡意軟體網站)。
  • 快取:在本地儲存經常存取的內容,減少頻寬使用並改善重複請求的回應時間。
  • 存取控制:根據來源 IP、使用者認證、時間或目的地限制網際網路存取。
  • 匿名性:對目的地伺服器隱藏用戶端 IP 位址,提供一層隱私。
  • 監控和日誌:記錄所有網頁流量以供稽核、合規或故障排除。

正向代理有兩種部署模式:

  • 明確代理:用戶端手動設定(或透過 PAC 檔案自動設定)使用代理。用戶端知道它正在透過代理通訊。
  • 透明代理:網路基礎設施(防火牆/路由器規則)將流量重新導向通過代理,無需用戶端設定。用戶端不知道代理的存在。

在 Ubuntu 上安裝和設定 Squid

Squid 可在 Ubuntu 預設儲存庫中取得。安裝很簡單,主要設定檔位於 /etc/squid/squid.conf。預設設定有大量註解,跨越數千行。在進行修改之前備份原始檔案是良好的做法。

# 安裝 Squid
$ sudo apt update
$ sudo apt install squid -y

# 驗證安裝和服務狀態
$ squid -v | head -1
Squid Cache: Version 5.7

$ sudo systemctl status squid

# 備份原始設定
$ sudo cp /etc/squid/squid.conf /etc/squid/squid.conf.original

# 移除註解查看有效指令
$ grep -v "^#" /etc/squid/squid.conf | grep -v "^$"
# /etc/squid/squid.conf — 基本設定

# 定義 Squid 監聽的連接埠
http_port 3128

# 定義您的本地網路
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 SSL_ports port 443
acl Safe_ports port 80          # http
acl Safe_ports port 443         # https
acl Safe_ports port 21          # ftp
acl Safe_ports port 1025-65535  # 未註冊連接埠

# 存取規則——順序很重要(第一個匹配獲勝)
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow localhost manager
http_access deny manager
http_access allow localnet
http_access allow localhost
http_access deny all

# 重新啟動 Squid 以套用變更
$ sudo systemctl restart squid

# 從用戶端測試代理
$ curl -x http://proxy-server:3128 http://www.example.com/

ACL 與 http_access 規則

Squid 的存取控制系統建立在兩個元件上:ACL 定義根據各種條件對請求進行分類,http_access 規則根據這些分類允許或拒絕請求。ACL 系統非常靈活,支援多種元素類型。

常見的 ACL 類型包括:

  • src:根據用戶端來源 IP 位址或網路範圍匹配。
  • dst:根據目的地 IP 位址匹配。
  • dstdomain:根據目的地網域名稱匹配。
  • port:根據目的地連接埠號匹配。
  • time:根據星期幾和時間匹配。
  • url_regex:根據正規表示式匹配 URL。
  • proxy_auth:根據已認證的使用者名稱匹配。
# /etc/squid/squid.conf 中的 ACL 範例

# 封鎖特定網域
acl blocked_sites dstdomain .facebook.com .twitter.com .tiktok.com
http_access deny blocked_sites

# 從檔案封鎖網域
acl blocked_list dstdomain "/etc/squid/blocked-domains.txt"
http_access deny blocked_list

# 僅在上班時間允許存取(週一至週五,上午 8 點至下午 6 點)
acl business_hours time MTWHF 08:00-18:00
acl staff_network src 192.168.10.0/24
http_access allow staff_network business_hours
http_access deny staff_network

# 封鎖包含特定關鍵字的 URL
acl bad_urls url_regex -i gambling poker casino
http_access deny bad_urls

# 允許特定 IP 不受限制存取(例如 IT 部門)
acl it_dept src 192.168.10.50 192.168.10.51 192.168.10.52
http_access allow it_dept

# 重新設定 Squid 而不完全重啟
$ sudo squid -k reconfigure

http_access 規則從上到下處理,第一個匹配的規則決定請求是否被允許或拒絕。這意味著規則順序至關重要——更具體的規則應該出現在一般規則之前。始終以 http_access deny all 作為安全網結束。

快取設定

快取是 Squid 的主要功能之一。當用戶端請求 Squid 已快取的資源時,它會返回快取副本而不聯繫原始伺服器。這減少了頻寬、降低了用戶端的延遲,並減少了原始伺服器的負載。Squid 支援記憶體快取(快速、有限)和磁碟快取(較大、較慢)。

# /etc/squid/squid.conf — 快取設定

# 記憶體快取大小
cache_mem 256 MB

# 記憶體中個別物件的最大大小
maximum_object_size_in_memory 1 MB

# 磁碟快取:類型、目錄、大小(MB)、L1 目錄數、L2 目錄數
cache_dir ufs /var/spool/squid 10000 16 256

# 磁碟上個別快取物件的最大大小
maximum_object_size 100 MB

# 快取取代政策
cache_replacement_policy lru

# 存取日誌
access_log /var/log/squid/access.log squid

# 重新整理模式:min_age 百分比 max_age
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

# 初始化快取目錄(僅首次)
$ sudo squid -z

# 重新啟動以套用快取變更
$ sudo systemctl restart squid

# 監控快取效能
$ sudo squidclient -h 127.0.0.1 mgr:info | grep -A5 "Cache"

認證

Squid 支援多種認證方案,要求使用者在存取網際網路之前進行身分驗證。最常見的方法是 NCSA Basic 認證,使用與 Apache 相容的密碼檔案。這適用於中小型部署。對於大型環境,建議整合 LDAP 或 Active Directory。

# 安裝 htpasswd 工具(來自 apache2-utils)
$ sudo apt install apache2-utils -y

# 建立密碼檔案並新增第一個使用者
$ sudo htpasswd -c /etc/squid/passwords user1

# 新增額外使用者(不使用 -c 選項以避免覆蓋)
$ sudo htpasswd /etc/squid/passwords user2

# 設定正確的權限
$ sudo chown proxy:proxy /etc/squid/passwords
$ sudo chmod 640 /etc/squid/passwords

# 在 /etc/squid/squid.conf 中設定認證
auth_param basic program /usr/lib/squid/basic_ncsa_auth /etc/squid/passwords
auth_param basic children 5 startup=5 idle=1
auth_param basic realm Squid Proxy Authentication
auth_param basic credentialsttl 2 hours

# 為已認證使用者建立 ACL
acl authenticated proxy_auth REQUIRED

# 要求所有存取都需認證
http_access allow authenticated
http_access deny all

# 重新啟動 Squid
$ sudo systemctl restart squid

# 測試已認證的代理存取
$ curl -x http://user1:password@proxy-server:3128 http://www.example.com/

重點摘要

  • 正向代理代表用戶端行動,為外出網際網路流量提供內容過濾、快取、存取控制和監控。
  • Squid 在 Ubuntu 上透過 apt 安裝,預設監聽連接埠 3128;主要設定檔為 /etc/squid/squid.conf
  • ACL 根據來源 IP、目的地網域、連接埠、時間、URL 模式或已認證使用者對請求進行分類;http_access 規則根據這些分類允許或拒絕,從上到下處理。
  • Squid 快取使用記憶體(cache_mem)和磁碟(cache_dir)儲存,refresh_pattern 指令控制物件的新鮮度和重新驗證時間。
  • 使用 htpasswd 的 NCSA Basic 認證提供簡單的基於使用者的存取控制;對於大型部署,請整合 LDAP 或 Active Directory。

下一步

恭喜您完成模組 3 — Web 服務!您已學習了 HTTP 基礎、設定了 Apache2 和 Nginx Web 伺服器、使用 TLS/HTTPS 保護網站、部署了 PHP 應用程式、設定了具有負載平衡的反向代理,以及設定了 Squid 作為正向代理。在模組 4 中,您將探索儲存與檔案系統,涵蓋磁碟分割、LVM、檔案系統類型、NFS 和 Samba。

日本語

概要

  • 学習内容:フォワードプロキシの概念、Ubuntu での Squid インストール、アクセス制御リスト(ACL)、http_access ルール、キャッシュ設定、ディスクとメモリキャッシュ、basic および NCSA メソッドによるプロキシ認証。
  • 前提条件:モジュール 3 — レッスン 21–26(HTTP 基礎からリバースプロキシとロードバランシングまで)
  • 推定読了時間:18分

はじめに

フォワードプロキシは、内部ネットワーク上のクライアントマシンとインターネットの間に位置するサーバーで、アウトバウンドリクエストを傍受し、クライアントに代わって転送します。リバースプロキシ(サーバーを保護する)とは異なり、フォワードプロキシはクライアントを保護し制御します。フォワードプロキシは、コンテンツフィルタリング、キャッシュによる帯域幅最適化、アクセス制御、従業員のインターネット使用監視のために企業環境で広く使用されています。

Squid は最も広くデプロイされているオープンソースのフォワードプロキシおよびキャッシュサーバーです。1990年代から活発に開発されており、HTTP、HTTPS、FTP およびその他のプロトコルをサポートしています。Squid は頻繁にアクセスされるコンテンツをキャッシュして帯域幅消費を削減し応答時間を改善し、柔軟な ACL システムを通じてアクセスポリシーを適用し、インターネットアクセスを許可する前にユーザーを認証できます。

このレッスンでは、フォワードプロキシの背後にある理論を学び、Ubuntu Server に Squid をインストールして設定し、アクセス制御リストを定義し、キャッシュパラメータを設定し、ユーザー認証をセットアップします。終了時には、ネットワークのインターネットアクセスを制御し最適化する、完全に機能する Squid プロキシをデプロイできるようになります。

フォワードプロキシの概念

フォワードプロキシアーキテクチャでは、クライアントは HTTP リクエストを直接宛先に送信するのではなく、プロキシサーバーに送信するよう設定されます。プロキシはアクセスポリシーに基づいてリクエストを評価し、許可された場合はインターネットからリソースを取得してクライアントに返します。宛先サーバーはクライアントの IP ではなくプロキシの IP アドレスを認識します。

フォワードプロキシは企業および教育環境でいくつかの目的に使用されます:

  • コンテンツフィルタリング:特定のウェブサイト、ドメイン、またはコンテンツカテゴリ(ソーシャルメディア、マルウェアサイトなど)へのアクセスをブロック。
  • キャッシュ:頻繁にアクセスされるコンテンツをローカルに保存し、帯域幅使用量を削減して繰り返しリクエストの応答時間を改善。
  • アクセス制御:ソース IP、ユーザー認証、時間帯、または宛先に基づいてインターネットアクセスを制限。
  • 匿名性:宛先サーバーからクライアント IP アドレスを隠し、プライバシーの層を提供。
  • モニタリングとロギング:監査、コンプライアンス、またはトラブルシューティングのためにすべての Web トラフィックを記録。

フォワードプロキシには2つのデプロイモードがあります:

  • 明示的プロキシ:クライアントが手動で(または PAC ファイルを通じて自動的に)プロキシを使用するよう設定されます。
  • 透過プロキシ:ネットワークインフラストラクチャ(ファイアウォール/ルーターのルール)がクライアント設定なしにトラフィックをプロキシ経由にリダイレクトします。

Ubuntu での Squid のインストールと設定

Squid は Ubuntu のデフォルトリポジトリで利用可能です。インストールは簡単で、メインの設定ファイルは /etc/squid/squid.conf にあります。デフォルト設定は広範にコメントされており、数千行に及びます。変更を加える前に元のファイルをバックアップすることをお勧めします。

# Squid をインストール
$ sudo apt update
$ sudo apt install squid -y

# インストールとサービスのステータスを確認
$ squid -v | head -1
Squid Cache: Version 5.7

$ sudo systemctl status squid

# 元の設定をバックアップ
$ sudo cp /etc/squid/squid.conf /etc/squid/squid.conf.original

# コメントを除去して有効なディレクティブを確認
$ grep -v "^#" /etc/squid/squid.conf | grep -v "^$"
# /etc/squid/squid.conf — 基本設定

# Squid がリッスンするポートを定義
http_port 3128

# ローカルネットワークを定義
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 SSL_ports port 443
acl Safe_ports port 80          # http
acl Safe_ports port 443         # https
acl Safe_ports port 21          # ftp
acl Safe_ports port 1025-65535  # 未登録ポート

# アクセスルール——順序が重要(最初のマッチが適用)
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow localhost manager
http_access deny manager
http_access allow localnet
http_access allow localhost
http_access deny all

# Squid を再起動して変更を適用
$ sudo systemctl restart squid

# クライアントからプロキシをテスト
$ curl -x http://proxy-server:3128 http://www.example.com/

ACL と http_access ルール

Squid のアクセス制御システムは2つのコンポーネントで構成されています:さまざまな基準に基づいてリクエストを分類する ACL 定義と、それらの分類に基づいてリクエストを許可または拒否する http_access ルールです。ACL システムは非常に柔軟で、多くの要素タイプをサポートしています。

一般的な ACL タイプ:

  • src:クライアントのソース IP アドレスまたはネットワーク範囲に基づいてマッチ。
  • dst:宛先 IP アドレスに基づいてマッチ。
  • dstdomain:宛先ドメイン名に基づいてマッチ。
  • port:宛先ポート番号に基づいてマッチ。
  • time:曜日と時刻に基づいてマッチ。
  • url_regex:URL に対する正規表現に基づいてマッチ。
  • proxy_auth:認証されたユーザー名に基づいてマッチ。
# /etc/squid/squid.conf での ACL の例

# 特定のドメインをブロック
acl blocked_sites dstdomain .facebook.com .twitter.com .tiktok.com
http_access deny blocked_sites

# ファイルからドメインをブロック
acl blocked_list dstdomain "/etc/squid/blocked-domains.txt"
http_access deny blocked_list

# 営業時間中のみアクセスを許可(月〜金、8時〜18時)
acl business_hours time MTWHF 08:00-18:00
acl staff_network src 192.168.10.0/24
http_access allow staff_network business_hours
http_access deny staff_network

# 特定のキーワードを含む URL をブロック
acl bad_urls url_regex -i gambling poker casino
http_access deny bad_urls

# 特定の IP に無制限アクセスを許可(例:IT 部門)
acl it_dept src 192.168.10.50 192.168.10.51 192.168.10.52
http_access allow it_dept

# 完全な再起動なしに Squid を再設定
$ sudo squid -k reconfigure

http_access ルールは上から下に処理され、最初にマッチしたルールがリクエストの許可または拒否を決定します。つまり、ルールの順序が重要です——より具体的なルールは一般的なルールの前に配置する必要があります。安全策として常に http_access deny all で終了してください。

キャッシュ設定

キャッシュは Squid の主要機能の一つです。クライアントが Squid がすでにキャッシュしているリソースをリクエストすると、オリジンサーバーに問い合わせずにキャッシュされたコピーを返します。これにより帯域幅が削減され、クライアントの遅延が低下し、オリジンサーバーの負荷が減少します。Squid はメモリキャッシュ(高速、限定的)とディスクキャッシュ(大容量、低速)の両方をサポートしています。

# /etc/squid/squid.conf — キャッシュ設定

# メモリキャッシュサイズ
cache_mem 256 MB

# メモリ内の個別オブジェクトの最大サイズ
maximum_object_size_in_memory 1 MB

# ディスクキャッシュ:タイプ、ディレクトリ、サイズ(MB)、L1ディレクトリ、L2ディレクトリ
cache_dir ufs /var/spool/squid 10000 16 256

# ディスク上のキャッシュオブジェクトの最大サイズ
maximum_object_size 100 MB

# キャッシュ置換ポリシー
cache_replacement_policy lru

# アクセスログ
access_log /var/log/squid/access.log squid

# リフレッシュパターン:min_age パーセンテージ max_age
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

# キャッシュディレクトリを初期化(初回のみ)
$ sudo squid -z

# キャッシュ変更を適用するため再起動
$ sudo systemctl restart squid

# キャッシュパフォーマンスを監視
$ sudo squidclient -h 127.0.0.1 mgr:info | grep -A5 "Cache"

認証

Squid は、インターネットにアクセスする前にユーザーに身元確認を要求するいくつかの認証スキームをサポートしています。最も一般的なアプローチは NCSA Basic 認証で、Apache 互換のパスワードファイルを使用します。これは小中規模のデプロイメントに適しています。大規模環境では、LDAP または Active Directory との統合が推奨されます。

# htpasswd ユーティリティをインストール(apache2-utils から)
$ sudo apt install apache2-utils -y

# パスワードファイルを作成し最初のユーザーを追加
$ sudo htpasswd -c /etc/squid/passwords user1

# 追加ユーザーを追加(-c フラグなしで上書きを防止)
$ sudo htpasswd /etc/squid/passwords user2

# 正しいパーミッションを設定
$ sudo chown proxy:proxy /etc/squid/passwords
$ sudo chmod 640 /etc/squid/passwords

# /etc/squid/squid.conf で認証を設定
auth_param basic program /usr/lib/squid/basic_ncsa_auth /etc/squid/passwords
auth_param basic children 5 startup=5 idle=1
auth_param basic realm Squid Proxy Authentication
auth_param basic credentialsttl 2 hours

# 認証済みユーザー用の ACL を作成
acl authenticated proxy_auth REQUIRED

# すべてのアクセスに認証を要求
http_access allow authenticated
http_access deny all

# Squid を再起動
$ sudo systemctl restart squid

# 認証付きプロキシアクセスをテスト
$ curl -x http://user1:password@proxy-server:3128 http://www.example.com/

重要ポイント

  • フォワードプロキシはクライアントの代理として動作し、アウトバウンドインターネットトラフィックのコンテンツフィルタリング、キャッシュ、アクセス制御、モニタリングを提供する。
  • Squid は Ubuntu で apt を通じてインストールされ、デフォルトでポート 3128 をリッスンする;メインの設定ファイルは /etc/squid/squid.conf
  • ACL はソース IP、宛先ドメイン、ポート、時間、URL パターン、または認証済みユーザーによってリクエストを分類する;http_access ルールはこれらの分類に基づいて上から下に処理され許可または拒否する。
  • Squid キャッシュはメモリ(cache_mem)とディスク(cache_dir)ストレージを使用し、refresh_pattern ディレクティブがオブジェクトの鮮度と再検証タイミングを制御する。
  • htpasswd による NCSA Basic 認証はシンプルなユーザーベースのアクセス制御を提供する;大規模デプロイメントでは LDAP または Active Directory と統合する。

次のステップ

モジュール 3 — Web サービスの完了おめでとうございます!HTTP 基礎、Apache2 と Nginx Web サーバーの設定、TLS/HTTPS によるサイトの保護、PHP アプリケーションのデプロイ、ロードバランシング付きリバースプロキシの設定、Squid フォワードプロキシの設定を学びました。モジュール 4 では、ストレージとファイルシステムを探索し、ディスクパーティショニング、LVM、ファイルシステムタイプ、NFS、Samba をカバーします。

You Missed