LoginSignup
23
26

More than 5 years have passed since last update.

Ubuntu 16.04 iptables設定(基礎知識)

Last updated at Posted at 2017-11-03

はじめに

iptablesの初期設定メモです。
(他の目的で作っていたのですが、断念したので記事再利用)

事前準備

インターフェースの確認

まずはインターフェースの確認
ip link show

続けてIPアドレスの状態確認
ifconfig

もし差異があれば、以下を実行してIPアドレス設定。
今回はubuntu16.04を使っているので、以下。

cd /etc/network/
sudo vi interfaces

staticでIPを追加する場合は、以下を追記

auto ens4
iface ens4 inet static
address 192.168.100.1
network 192.168.100.0
netmask 255.255.255.224
broadcast 192.168.100.31
gateway 192.168.100.1

再起動後、PINGで通信確認

参考記事:
Linuxで固定IP設定(設定ファイル・コマンド)

iptables設定

「iptables」設定ファイル作成

ip tablesの設定をまとめた「iptables」を作成する
記載内容は以下。

# clear iptables and NAT tables

iptables -F
iptables -t nat -F

# Internet to LAN  -> DROP
# LAN to Internet  -> ACCEPT

iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# icmp and lo -> ACCEPT

iptables -A INPUT -p icmp -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT

# DNS and http/https for github

iptables -A INPUT -p tcp --sport 53 -j ACCEPT
iptables -A INPUT -p udp --sport 53 -j ACCEPT
iptables -A INPUT -p tcp --sport 80 -j ACCEPT
iptables -A INPUT -p tcp --sport 443 -j ACCEPT

設定反映

bashを使って設定を反映。
sudo bash iptables

出力が長いので、logsファイルを作成してmoreで確認。

# sudo iptables -L -n > logs
# more logs
Chain INPUT (policy DROP)
target     prot opt source               destination
ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:53
ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0            udp dpt:53
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:80
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:443

Chain FORWARD (policy DROP)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

サーバ再起動時のiptables反映

ubuntuさんはiptablesの内容が再起動時に保存されない。
以下の作業が必要。

設定の保存
# sudo iptables-save | sudo tee /etc/iptables.rules

iptables復元用スクリプト作成

# cd /etc/network/if-pre-up.d/
# sudo vi iptables_start

スクリプトの内容はこんな感じ

#!/bin/sh
/sbin/iptables-restore < /etc/iptables.rules
exit 0

最後に実行権限を付与

# sudo chmod a+x /etc/network/if-pre-up.d/iptables_start

再起動して動作確認。
インターネット側からSSHでアクセスできなくなったことを確認するのが手っ取り早い。

動作確認が終わったら、コンソール/LAN からSSHの利用ポートを再設定すること。

23
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
26