sshdの接続元を日本のIPに限定する

環境情報

OS Ubuntu
Version 24.04.2 LTS

hosts.allowとhosts.denyの設定

最終行は改行が必要です(改行がないと正常に動作しません)

/etc/hosts.allow

1
2
sshd: /etc/jp.allow

/etc/hosts.deny

1
2
ALL : ALL

スクリプト

必要なライブラリの取得します

1
pip install requests

jp_allow.py

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import requests

# IPリストを取得するURL
URL = "https://ipv4.fetus.jp/jp.txt"

def convert_subnet(cidr_value):
'''
サブネットを255.255.255.0形式に変換する関数
'''
subnet_map = {
8: "255.0.0.0",
9: "255.128.0.0",
10: "255.192.0.0",
11: "255.224.0.0",
12: "255.240.0.0",
13: "255.248.0.0",
14: "255.252.0.0",
15: "255.254.0.0",
16: "255.255.0.0",
17: "255.255.128.0",
18: "255.255.192.0",
19: "255.255.224.0",
20: "255.255.240.0",
21: "255.255.248.0",
22: "255.255.252.0",
23: "255.255.254.0",
24: "255.255.255.0",
25: "255.255.255.128",
26: "255.255.255.192",
27: "255.255.255.224",
28: "255.255.255.240",
29: "255.255.255.248",
30: "255.255.255.252",
31: "255.255.255.254",
32: "255.255.255.255"
}
return subnet_map.get(cidr_value)
# URLからデータを取得
response = requests.get(URL, timeout=5)
ip_data = response.text.splitlines()

# jp.allow形式に変換
with open("/etc/jp.allow", "w", encoding="utf-8") as file:
output = []
for line in ip_data:
if line and not line.startswith("#"): # コメント行をスキップ
ip, cidr = line.split('/')
subnet = convert_subnet(int(cidr))
output.append(f"{ip}/{subnet}")

file.write(" ".join(output)) # スペースで区切って書き込み

print("IPリストがjp.allowファイルに変換されました。")

実行

/etc に書き込むため管理者権限が必要です

1
sudo python jp_allow.py

注意

hosts.allowとhosts.denyは接続の度に動的に読み込まれるので、別ターミナル等で試行してからセッションを切断してください