How to set up Squid proxy server

第三方的服務有時候需要綁定固定 IP,導致服務本體不能任意移動,此時我們可以利用 proxy server 來解決這問題
本文使用 Squid 作為 proxy server 演示

Installation

Docker

詳細的資訊可以參考

1
2
3
4
5
6
7
8
9
10
11
12
version: '3'

services:
squid:
image: sameersbn/squid:3.5.27-2
network_mode: bridge
ports:
- "3128:3128"
volumes:
- /srv/docker/squid/cache:/var/spool/squid
- ./squid.conf:/etc/squid/squid.conf
restart: always

command line 做測試

1
http_proxy=http://192.168.28.241:3128 https_proxy=http://192.168.28.241:3128 curl https://ifconfig.co

Configuration

squid.conf,啊,配置太多了,挑幾個重要的寫吧

ACL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# localnet 是可以替換掉名字
acl localnet src 192.168.0.0/16

acl SSL_ports port 443
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 建議從最小權限開始定義,因為以下設定是有順序性的

# deny 所以來自不是定義好 safe ports 的 request
http_access deny !Safe_ports

# deny 所有 ssl 不是走 443 的 request,可以在上一個設定中加入自定義的 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
# 可以加入自定義的 rules,像是 localnet、localhost、allow network 之類的
http_access allow localnet
http_access allow localhost

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

Listen ports

1
http_port 3128

SSL

有空再研究

Examples

golang 為例,透過 proxy server 去訪問 https://ifconfig.co 會返回 IP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package main

import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
)

const (
proxy = "http://192.168.28.241:3128"
ifconfig = "https://ifconfig.co"
)

func main() {
proxyUrl, err := url.Parse(proxy)
if err != nil {
panic(err)
}

c := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyUrl),
},
}

resp, err := c.Get(ifconfig)
if err != nil {
panic(err)
}
defer resp.Body.Close()

content, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}

fmt.Println(content)
}