My Yahoo!に追加 Yahoo!ブックマークに登録

先日からVirtualBoxにubuntuサーバをインストールして色々やっていますが、結果第一弾としてiptablesを使ったルータの作り方をお送りします!

と言っても、まだ途中なので基本部分だけですが(^^;

まず、ubuntuの本家フォーラムから参考となるページをあさってきます
つか、もうほぼこれでクリアなんですが(^^;

で、参考のページに書いてあるコードを元に、dhcpサーバの設定と、ルーティングの設定をそれぞれ行います。
まずはdhcpの設定ですが、 dhcpサーバがインストールされていないので、先にインストールしておきます。

sudo apt-get install dhcp3-server

続いて、/etc/dhcp3/dhcpd.confファイルを以下のように編集します。

# Configuration file for ISC dhcpd (see 'man dhcpd.conf')
#
# For more information regarding the ISC DHCP Daemon,
# please visit: http://www.isc.org/sw/dhcp/
#
##########################################################
#
# Configuration Notes:
#
# This configuration file assumes that you
# have a total of 4 NIC cards installed on your system,
# with eth2 connecting (as a client) to a remote dhcp server. 
#
# This will assign a dhcp subnet to each additional NIC card
# (eth1, eth0), which can be used to create a
# multi-subnet DHCP Server.
#
# Example by: Sean O'Donnell http://code.seanodonnell.com
# サンプルを元にリーフが変更しました。
# http://blog.livedoor.jp/leaf_hiro/
#
##########################################################
#
# DHCP CLIENT CONFIGURATION SETTINGS
#

# DynamicDNSと連携する場合は「interim」を指定してください。
# それ以外の場合はDynamicDNSを使わないようにするため「ad-hoc」を指定してください。
# まったくDNSと関係なくする場合は「none」でもよいようです。

ddns-update-style ad-hoc; 

# ドメインを指定します。外に公開するのでなければ、厳密なドメインではなく適当でよいようです。
# LAN内部であればドメインを指定しないでも他のマシンにアクセスできます。

option domain-name "my-dhcp-server.com";

# DNSサーバを指定してください。
option domain-name-servers 192.168.1.1, 192.168.2.1;

##########################################################
#
# DHCP SERVER CONFIGURATION SETTINGS 
# 元の例ではLANカード2枚に対してdhcpサービスを提供するようになっていますが、
# 必要無ければ片方の設定を削除してください。(リーフは削除してます)
# 普通は外から来る方にはdhcpサーバの設定は必要ありません。

# assign the defaul lease time (seconds)

default-lease-time 600000000;

# assign the max lease time (seconds)
max-lease-time 720000000;

# eth0 subnet configuration
#subnet 192.168.1.0 netmask 255.255.255.0 {
#  range 192.168.1.2 192.168.1.99;
#  option routers 192.168.1.1;
#  option broadcast-address 192.168.1.255;
#}

# eth1 subnet configuration

subnet 192.168.2.0 netmask 255.255.255.0 {
  range 192.168.2.2 192.168.2.99;
  option routers 192.168.2.1;
  option broadcast-address 192.168.2.255;
}

##########################################################
# end config

次に、dhcpのサービスを提供するLANカードを指定します。
/etc/default/dhcp3-serverを開いて

# Defaults for dhcp initscript
# sourced by /etc/init.d/dhcp
# installed at /etc/default/dhcp3-server by the maintainer scripts

#
# This is a POSIX shell fragment
#

# On what interfaces should the DHCP server (dhcpd) serve DHCP requests? 
#       Separate multiple interfaces with spaces, e.g. "eth0 eth1".
INTERFACES="eth1"

のように記述します。
リーフはeth0が外側(Internet側)で、eth1が内側(LAN側)なので、eth1だけを残しています。
これで、dhcpの設定は終わりです。あとで、DynamicDNSの設定をするのですがとりあえずはこのままにしておきます。

で、ルーティングですが、こちらも参考ページの設定をちょこっと改造しておきます。
元のサンプルでは「sh」で起動するようになってるんですが、それだと「echo」の動きがおかしいので(オプションを認識しない)「bash」にしておきます。
それ以外にもちょこちょこ直しているのですが、気になる方は下のサンプルと元のを見比べてください。
なお、IPマスカレードのテスト用設定がしてあるので、不要であれば削除してください。
削除しないと(ログレベルを見直さないと)テスト用に大量にログを吐くようになっているので注意してください。
ログは「/var/log/syslog」にでるはずです。

※注意!
このサンプルはあくまで試験的なものです。このまま使うと外から(Internet側から)もつなぎ放題なので、実際に使用する際は必ず外からのアクセスをブロックするようにしてください!
細かい動作内容を確認したい場合は書籍などを見ることをおすすめします。
  

#!/bin/bash
#
# サンプルを元にリーフが変更しました。
# http://blog.livedoor.jp/leaf_hiro/
#
#firewall-iptables
FWVER=0.76-leaf
#
#               Initial SIMPLE IP Masquerade test for 2.6 / 2.4 kernels
#               using IPTABLES.
#
#               Once IP Masquerading has been tested, with this simple
#               ruleset, it is highly recommended to use a stronger
#               IPTABLES ruleset either given later in this HOWTO or
#               from another reputable resource.
#
#
# Log:
#       0.76 - Added comments on why the default policy is ACCEPT
#       0.75 - Added more kernel modules to the comments section 
#       0.74 - the ruleset now uses modprobe vs. insmod
#       0.73 - REJECT is not a legal policy yet; back to DROP
#       0.72 - Changed the default block behavior to REJECT not DROP
#       0.71 - Added clarification that PPPoE users need to use 
#              "ppp0" instead of "eth0" for their external interface
#       0.70 - Added commented option for IRC nat module
#            - Added additional use of environment variables
#            - Added additional formatting 
#       0.63 - Added support for the IRC IPTABLES module
#       0.62 - Fixed a typo on the MASQ enable line that used eth0
#              instead of $EXTIF
#       0.61 - Changed the firewall to use variables for the internal 
#              and external interfaces.
#       0.60 - 0.50 had a mistake where the ruleset had a rule to DROP
#              all forwarded packets but it didn't have a rule to ACCEPT
#              any packets to be forwarded either
#            - Load the ip_nat_ftp and ip_conntrack_ftp modules by default
#       0.50 - Initial draft
#

echo -e "\n\nLoading simple rc.firewall-iptables version $FWVER..\n"


# The location of the iptables and kernel module programs 
#
#   If your Linux distribution came with a copy of iptables,
#   most likely all the programs will be located in /sbin.  If
#   you manually compiled iptables, the default location will
#   be in /usr/local/sbin 
#
# ** Please use the "whereis iptables" command to figure out
# ** where your copy is and change the path below to reflect
# ** your setup
#
IPTABLES=/sbin/iptables
DEPMOD=/sbin/depmod
MODPROBE=/sbin/modprobe


#Setting the EXTERNAL and INTERNAL interfaces for the network
#
#  Each IP Masquerade network needs to have at least one
#  external and one internal network.  The external network 
#  is where the natting will occur and the internal network
#  should preferably be addressed with a RFC1918 private address
#  scheme.
#
#  For this example, "eth0" is external and "eth1" is internal" 
#
#
#  NOTE:  If this doesnt EXACTLY fit your configuration, you must
#         change the EXTIF or INTIF variables above. For example:
#
#            If you are a PPPoE or analog modem user:
#
#               EXTIF="ppp0" 
#
#
EXTIF="eth2"
INTIF="eth1"
#INTIF2="eth0"
echo "   External Interface:  $EXTIF"
echo "   Internal Interface:  $INTIF"
#echo "   Internal Interface:  $INTIF2" 

EXTIP=`ifconfig ${EXTIF} | sed -n 's/.*inet addr:\([0-9\.]*\).*Bcast.*/\1/gp'`
echo "   External IP:  $EXTIP"

#======================================================================
#== No editing beyond this line is required for initial MASQ testing == 


echo -en "   loading modules: "

# Need to verify that all modules have all required dependencies
#
echo "  - Verifying that all kernel modules are ok"
$DEPMOD -a

# With the new IPTABLES code, the core MASQ functionality is now either 
# modular or compiled into the kernel.  This HOWTO shows ALL IPTABLES
# options as MODULES.  If your kernel is compiled correctly, there is
# NO need to load the kernel modules manually.
#
#  NOTE: The following items are listed ONLY for informational reasons. 
#        There is no reason to manual load these modules unless your
#        kernel is either mis-configured or you intentionally disabled
#        the kernel module autoloader.
#

# Upon the commands of starting up IP Masq on the server, the 
# following kernel modules will be automatically loaded:
#
# NOTE:  Only load the IP MASQ modules you need.  All current IP MASQ
#        modules are shown below but are commented out from loading.
# =============================================================== 

echo "----------------------------------------------------------------------"

#Load the main body of the IPTABLES module - "iptable"
#  - Loaded automatically when the "iptables" command is invoked 
#
#  - Loaded manually to clean up kernel auto-loading timing issues
#
echo -en "ip_tables, "
$MODPROBE ip_tables


#Load the IPTABLES filtering module - "iptable_filter"
#  - Loaded automatically when filter policies are activated 


#Load the stateful connection tracking framework - "ip_conntrack"
#
# The conntrack  module in itself does nothing without other specific
# conntrack modules being loaded afterwards such as the "ip_conntrack_ftp" 
# module
#
#  - This module is loaded automatically when MASQ functionality is
#    enabled
#
#  - Loaded manually to clean up kernel auto-loading timing issues
#
echo -en "ip_conntrack, " 
$MODPROBE ip_conntrack


#Load the FTP tracking mechanism for full FTP tracking
#
# Enabled by default -- insert a "#" on the next line to deactivate
#
echo -en "ip_conntrack_ftp, " 
$MODPROBE ip_conntrack_ftp


#Load the IRC tracking mechanism for full IRC tracking
#
# Enabled by default -- insert a "#" on the next line to deactivate
#
echo -en "ip_conntrack_irc, " 
$MODPROBE ip_conntrack_irc


#Load the general IPTABLES NAT code - "iptable_nat"
#  - Loaded automatically when MASQ functionality is turned on
#
#  - Loaded manually to clean up kernel auto-loading timing issues 
#
echo -en "iptable_nat, "
$MODPROBE iptable_nat


#Loads the FTP NAT functionality into the core IPTABLES code
# Required to support non-PASV FTP.
#
# Enabled by default -- insert a "#" on the next line to deactivate 
#
echo -en "ip_nat_ftp, "
$MODPROBE ip_nat_ftp


#Loads the IRC NAT functionality into the core IPTABLES code
# Required to support NAT of IRC DCC requests
#
# Disabled by default -- remove the "#" on the next line to activate 
#
#echo -e "ip_nat_irc"
#$MODPROBE ip_nat_irc

echo "----------------------------------------------------------------------"

# Just to be complete, here is a partial list of some of the other 
# IPTABLES kernel modules and their function.  Please note that most
# of these modules (the ipt ones) are automatically loaded by the
# master kernel module for proper operation and don't need to be
# manually loaded. 
# --------------------------------------------------------------------
#
#    ip_nat_snmp_basic - this module allows for proper NATing of some
#                        SNMP traffic
#
#    iptable_mangle    - this target allows for packets to be
#                        manipulated for things like the TCPMSS
#                        option, etc.
#
# --
#
#    ipt_mark       - this target marks a given packet for future action.
#                     This automatically loads the ipt_MARK module
#
#    ipt_tcpmss     - this target allows to manipulate the TCP MSS
#                     option for braindead remote firewalls.
#                     This automatically loads the ipt_TCPMSS module
#
#    ipt_limit      - this target allows for packets to be limited to
#                     to many hits per sec/min/hr
#
#    ipt_multiport  - this match allows for targets within a range
#                     of port numbers vs. listing each port individually
#
#    ipt_state      - this match allows to catch packets with various
#                     IP and TCP flags set/unset
#
#    ipt_unclean    - this match allows to catch packets that have invalid
#                     IP/TCP flags set
#
#    iptable_filter - this module allows for packets to be DROPped,
#                     REJECTed, or LOGged.  This module automatically
#                     loads the following modules:
#
#                     ipt_LOG - this target allows for packets to be
#                               logged
#
#                     ipt_REJECT - this target DROPs the packet and returns
#                                  a configurable ICMP packet back to the
#                                  sender.
#

echo -e "   Done loading modules.\n"



#CRITICAL:  Enable IP forwarding since it is disabled by default since 
#
#           Redhat Users:  you may try changing the options in
#                          /etc/sysconfig/network from:
#
#                       FORWARD_IPV4=false
#                             to
#                       FORWARD_IPV4=true
#
echo "   Enabling forwarding.."
echo "1" > /proc/sys/net/ipv4/ip_forward


# Dynamic IP users:
#
#   If you get your IP address dynamically from SLIP, PPP, or DHCP, 
#   enable this following option.  This enables dynamic-address hacking
#   which makes the life with Diald and similar programs much easier.
#
echo "   Enabling DynamicAddr.."
echo "1" > /proc/sys/net/ipv4/ip_dynaddr 


# Enable simple IP forwarding and Masquerading
#
#  NOTE:  In IPTABLES speak, IP Masquerading is a form of SourceNAT or SNAT.
#
#  NOTE #2:  The following is an example for an internal LAN address in the 
#            192.168.0.x network with a 255.255.255.0 or a "24" bit subnet mask
#            connecting to the Internet on external interface "eth0".  This
#            example will MASQ internal traffic out to the Internet but not
#            allow non-initiated traffic into your internal network.
#
#
#         ** Please change the above network numbers, subnet mask, and your
#         *** Internet connection interface name to match your setup 
#


#Clearing any previous configuration
#
#  Unless specified, the defaults for INPUT and OUTPUT is ACCEPT
#    The default for FORWARD is DROP (REJECT is not a valid policy)
#
#   Isn't ACCEPT insecure?  To some degree, YES, but this is our testing 
#   phase.  Once we know that IPMASQ is working well, I recommend you run
#   the rc.firewall-*-stronger rulesets which set the defaults to DROP but
#   also include the critical additional rulesets to still let you connect to 
#   the IPMASQ server, etc.
#
echo -e "\n\n   Clearing any existing rules and setting default policy.."
$IPTABLES -P INPUT ACCEPT
$IPTABLES -F INPUT
$IPTABLES -P OUTPUT ACCEPT
$IPTABLES -F OUTPUT
$IPTABLES -P FORWARD DROP
$IPTABLES -F FORWARD
$IPTABLES -t nat -F

# IPマスカレードのテスト用設定。不要であれば削除してください。
# テスト用に大量にログを吐くようになっているので注意!
# ログは「/var/log/syslog」にでます。

$IPTABLES -A INPUT -j LOG --log-prefix "[FIREWALL INPUT]:" --log-level debug
$IPTABLES -A OUTPUT -j LOG --log-prefix "[FIREWALL OUTPUT]:" --log-level debug
$IPTABLES -A FORWARD -j LOG --log-prefix "[FIREWALL FORWARD]:" --log-level debug

echo -e " \n  FWD: Allow all connections OUT and only existing and related ones IN\n"
$IPTABLES -A FORWARD -i $EXTIF -o $INTIF -m state --state ESTABLISHED,RELATED -j ACCEPT 
$IPTABLES -A FORWARD -i $INTIF -o $EXTIF -j ACCEPT

# eth2の設定は不要なのでコメントアウトしてます。
# $IPTABLES -A FORWARD -i $EXTIF -o $INTIF2 -m state --state ESTABLISHED,RELATED -j ACCEPT
# $IPTABLES -A FORWARD -i $INTIF -o $INTIF2 -m state --state ESTABLISHED,RELATED -j ACCEPT 
# $IPTABLES -A FORWARD -i $INTIF2 -o $INTIF -m state --state ESTABLISHED,RELATED -j ACCEPT
# $IPTABLES -A FORWARD -i $INTIF2 -o $EXTIF -j ACCEPT

$IPTABLES -t nat -A POSTROUTING -o $EXTIF -j SNAT --to $EXTIP

echo -e "\n   Enabling SNAT (MASQUERADE) functionality on $EXTIF"
$IPTABLES -t nat -A POSTROUTING -o $EXTIF -j MASQUERADE

echo -e "\nrc.firewall-iptables v$FWVER done.\n"

ここまでの設定をすればルータのeth1側につないだパソコンに自動でIPアドレスが振られ、ルータ経由でインターネットに接続できるはずです。

ただし、何度も書きますが、このまま外につなぐと外からもつなぎ放題なので注意してください!


関連するBlogはこちらからどうぞ〜! → 人気ブログランキングへにほんブログ村 IT技術ブログ Linuxへ