19 January 2008

Perintah dasar Linux


Perintah untuk berbagai operasi dasar di sistem operasi linux, beserta penjelasannya, dapat saudara lihat pada tabel yang telah penulis susun sebagai berikut:
Perintah Keterangan
any_command –help Menampilkan keterangan bantu tentang pemakaian perintah. “–help” sama dengan perintah pada DOS “/h”.
ls Melihat isi file dari direktori aktif. Pada linux perintah dir hanya berupa alias dari perintah ls. Untuk perintah ls sendiri sering dibuatkan alias ls –color, agar pada waktu di ls ditampilkan warna-warna sesuai dengan file-filenya, biasanya hijau untuk execute, dsb.
ls -al Melihat seluruh isi file pada direktori aktif beserta file hidden, lalu ditampilkan layar per layar.
cd directory Change directory. Menggunakan cd tanpa nama direktori akan menghantarkan anda ke home direktori. Dan cd - akan menghantarkan anda ke direktori sebelumnya.
cp source destination Mengopi suatu file
mcopy source destination Mengcopy suatu file dari/ke dos filesystem. Contoh mcopy a:autoexec.bat ~/junk . Gunakan man mtools untuk command yang sejenis : mdir, mcd, mren, mmove, mdel, mmd, mrd, mformat….
mv source destination Memindahkan atau mengganti nama file
ln -s source destination Membuat Simbolic Links, contoh ln -sf /usr/X11R6/bin/XF86_SVGA /etc/X11/X, membuat Simbolic link dari file XF86_SVGA ke X
rm files Menghapus file
mkdir directory Membuat direktori baru
rmdir directory Menghapus direktori yang telah kosong
rm -r files (recursive remove) Menghapus file, direktori dan subdirektorinya. Hati-hati menggunakan perintah ini apabila anda login sebagai root, karena root dengan mudah dapat menghapus seluruh file pada sistem dengan perintah di atas, tidak ada perintah untuk undelete di Linux
more Untuk melihat isi suatu file, dengan tambahan perintah more, maka isi file tersebut ditampilkan layar per layar.
less filename Melihat suatu file layar per layar, dan tekan tombol “q” apabila ingin keluar,
pico filename Edit suatu text file.
pico -w filename Edit suatu text file, dengan menonaktifkan fungsi word wrap, sangat berguna untuk mengedit file seperti /etc/fstab.
lynx file.html Melihat file html atau browse ke net dengan text mode, dimana gambar/image tidak dapat ditampilkan, tapi lynx adalah suatu browser yang sangat cepat, sangat berguna bila anda hanya menginginkan suatu artikel tanpa image.
tar -zxvf filename.tar.gz Meng-untar sebuah file tar sekaligus meng-uncompress file tersebut (*.tar.gz atau *.tgz), untuk meletakkannya direktori yg diinginkan tambahkan option -C direktori, contoh tar -zxvf filename.tar.gz -C /opt (meletakkan file tersebut di direktori /opt
tar -xvf filename.tar Meng-untar sebuah file tar yang tidak terkompress (*.tar).
gunzip filename.gz Meng-uncompress sebuah file zip (*.gz” or *.z). dengan menggunakan gzip (juga zip atau compress) jika anda menginginkan mengompress file.
bunzip2 filename.bz2 Meng-uncompress file dengan format (*.bz2) dengan utiliti “bzip2″, digunakan pada file yang besar.
unzip filename.zip Meng-uncompress file dengan format (*.zip) dengan utiliti “unzip” yang kompatibel dengan pkzip for DOS.
find / -name “filename” Mencari “namafile” pada komputer anda dimulai dengan direktori /. Namafile tersebut mungkin saja berisi wildcard (*,?).
locate filename Mencari file dengan string “filename”. Sangat mudah dan cepat dari perintah di atas.
pine Email reader yang sangat mudah digunakan, dan menjadi favorit banyak pemakai mesin Unix. Atau anda bisa pakai email yang sangat customize, yaitu mutt ,
talk username1 Berbicara dengan keyboard dengan user lain yg sedang login pada mesin kita (atau gunakan talk username1@machinename untuk berbicara dengan komputer lain). Untuk menerima undangan percakapan, ketikkan talk username2. Jika seseorang mencoba untuk berbicara dengan anda dan itu dirasakan mengganggu, anda bisa menggunakan perintah mesg n untuk menolak pesan tersebut. Dan gunakan perintah who atau rwho untuk melihat siapa user yang mengganggu tersebut.
mc Menjalankan “Morton Commander” … eh… salah maksudnya “Midnight Commander” sebagai file manager, cepat dan bagus.
telnet server Untuk menghubungkan komputer kita ke komputer lain dengan menggunakan protokol TELNET. Gunakan nama mesin atau Nomor IP mesin, dan anda akan mendapatkan prompt login name dari mesin tersebut, masukkan passwordnya, oh ya .. anda juga harus punya account di mesin remote tersebut. Telnet akan menghubungkan anda dengan komputer lain dan membiarkan anda untuk mengoperasikan mesin tersebut. Telnet sangat tidak aman, setiap yang anda ketik menjadi “open text”, juga dengan password anda! Gunakan ssh alih-alih telnet untuk mengakses mesin secara remote.
rlogin server (remote login) Menghubungkan anda kekomputer lain. Loginname dan password, tetapi apabila account anda tersebut telah dipakai, maka anda akan mendapatkan pesan kesalahan pada password anda. Sangat tidak aman juga, gunakan ssh sebagai gantinya.
rsh server (remote shell) Jalan lain untuk menghubungkan anda ke remote machine. Apabila login name/password anda sedang dipakai di remote mesin tsb, maka password anda tidak akan berlaku. Idem dengan rlogin, gantikan dengan ssh.
ftp server Ftp ke mesin lain, ini sangat berguna untuk mengopy file ke/dari remote mesin. Juga tidak aman, gunakan scp dari keluarga ssh sebagai gantinya.
minicom Program Minicom (dapat dikatakan seperti “Procomm/Hyperterminal for Linux”).
./program_name Menjalankan program pada direktori aktif, yang mana tidak terdapat pada PATH anda
xinit Menjalankan X-window server (tanpa windows manager).
startx Menjalankan X-window server dan meload default windows manager. Sama seperti perintah “win” under DOS dengan Win3.1
startx – :1 Menjalankan sesi X-windows berikutnya pada display 1 (default menggunakan display 0). Anda dapat menjalankan banyak GUI terminal secara bersamaan, untuk pindah antar GUI gunakan , , etc, tapi ini akan lebih banyak memakan memori.
xterm (pada X terminal) ,menjalankan X-windows terminal. Untuk keluar ketikkan exit
xboing (pada X terminal). Sangat lucu deh …., seperti games-games lama …..
gimp (pada X terminal) Program image editor yang sangat bagus, bisa disamakan dengan Adobe Photoshop, yang membedakan adalah program ini gratis.
netscape (pada X terminal) menjalankan netscape, versi pada waktu tulisan ini dibuat telah mencapai versi 4.7
netscape -display host:0.0 (pada X terminal) menjalankan netscape pada mesin yang aktif dan menampilkan outputnya pada mesin yang bernama host display 0 screen 0. Anda harus memberikan akses untuk mesin aktif untuk menampilkannya pada mesin host dengan perintah xhost
shutdown -h now (sebagai root) Shut down sistem. Umumnya digunakan untuk remote shutdown. Gunakan untuk shutdown pada konsol (dapat dijalankan oleh user).
halt reboot (sebagai root) Halt atau reboot mesin. Lebih simple dari perintah di atas.
man topic Menampilkan daftar dari sistem manual pages (help) sesuai dengan topic. Coba man man. lalu tekan q untuk keluar dari viewer. Perintah info topic Manual pages dapat dibaca dilhat dengan cara any_command –help.
apropos topic Menampilkan bantuan manual berdasarkan topik..
pwd Melihat direktori kerja saat ini
hostname Menampilkan nama local host (mesin dimana anda sedang bekerja). Gunakan perintah netconf (sebagai root) untuk merubah nama host dari mesin tersebut, atau edit file /etc/hosts
whoami Mencetak login name anda
id username Mencetak user id (uid) atau group id (gid)
date Mencetak atau merubah tanggal dan waktu pada komputer, contoh merubah tanggal dan waktu ke 2000-12-31 23:57 dengan perintah; date 123123572000
time Melihat jumlah waktu yg ditangani untuk penyelesaian suatu proses + info lainnya. Jangan dibingungkan dengan perintah date
who Melihat user yang login pada komputer kita.
rwho -a Melihat semua user yg login pada network anda. Layanan perintah rwho ini harus diaktifkan, jalankan setup sebagai root untuk mengaktifkannya.
finger username Melihat informasi user, coba jalankan; finger root
last Melihat user sebelumnya yang telah login di komputer.
uptime Melihat jumlah waktu pemakaian komputer oleh seseorang, terhitung proses reboot terakhir.
ps (=print status) Melihat proses-proses yang dijalankan oleh user
ps axu Melihat seluruh proses yang dijalankan, walaupun tanpa terminal control, juga ditampilkan nama dari user untuk setiap proses.
top Melihat proses yang berjalan, dengan urutan penggunaan cpu.
uname -a Informasi system kernel anda
free Informasi memory (dalam kilobytes).
df -h (=disk free) Melihat informasi pemakaian disk pada seluruh system (in human-readable form)
du / -bh (=disk usage) Melihat secara detil pemakaian disk untuk setiap direktori, dimulai dari root (in human legible form).
cat /proc/cpuinfo Cpu info. Melihat file pada /proc directori yang bukan merupakan file nyata (not real files).
cat /proc/interrupts Melihat alamat interrupt yang dipakai.
cat /proc/version Versi dari Linux dan informasi lainnya.
cat /proc/filesystems Melihat filesystem yang digunakan.
cat /etc/printcap Melihat printer yang telah disetup
lsmod (as root) Melihat module-module kernel yang telah di load.
set Melihat environment dari user yang aktif
echo $PATH Melihat isi dari variabel PATH. Perintah ini dapat digunakan untuk menampilkan variabel environmen lain dengan baik. Gunakan set untuk melihat environmen secara penuh.
dmesg Mencetak pesan-pesan pada waktu proses boot. (menampilkan file: /var/log/dmesg).
clear Membersihkan layar.
adduser Menambah pengguna.

DHCP Server di Linux dg client Linux & Windows

Server DHCP di Linux
DHCP server adalah sebuah service yg memberikan pelayanan dalam sebuah jaringan komputer dimana IP address (+ beberapa setting lain) tidak dipasang secara statis di masing2x komputer, melainkan diberikan oleh server secara dinamis (bisa juga statis tapi tetap diberikan oleh server, yg dikenal dg reservasi atau pencadangan IP address tertentu yg diberikan kepada komputer dg MAC address tertentu pula). Hal ini akan sangat membantu seorang administrator jaringan untuk mengelola suatu jaringan besar yg terdiri dari ratusan bahkan ribuan komputer dengan mempermudah pengelolaan jaringan dg memusatkan pengelolaan IP address jaringan dalam sebuah server. Jadi setiap komputer dalam jaringan akan meminta konfigurasi IP kepada server DHCP yg akan membagikan IP address sesuai konfigurasi yg dipasang di server tsb.
DHCP server berjalan di atas sistem Windows maupun Linux dg hampir tidak ada perbedaan dalam kemampuannya memberikan layanan utama berupa pemberian IP Address pada jaringan secara dinamis.
Karakteristik dari DHCP server yang berjalan di sistem Linux:
1. Server dapat berjalan lebih cepat & stabil. Sistem-sistem Unix clone sudah diakui mempunyai reliabilitas yang sangat tinggi dalam menjalankan aplikasi-aplikasinya, dan ini berarti termasuk juga di Linux yang juga merupakan salah satu clone Unix. Linux juga seperti turunan Unix lain dapat dioperasikan hanya dengan command text saja. Ini berarti resource yang dibutuhkan server pasti lebih kecil daripada resource yang dibutuhkan untuk menjalankan software berbasis grafis seperti di sistem Windows.
2. Dijalankan dengan dua aplikasi daemon untuk server dan client, misalnya : dhcpd (DHCP daemon) untuk server dan dhcpcd (DHCP client daemon) untuk client.
3. File-file setting untuk DHCP di Linux umumnya diletakkan di dalam direktori /etc dan /var/lib/dhcp
4. Setting DHCP dilakukan dalam sebuah file yaitu : /etc/dhcpd.conf dan akan menyimpan hasil transaksi penyewaan IP address di dalam sebuah file yang bernama /var/lib/dhcpcd.leases. Bila file ini tidak ada, DHCP tidak akan dapat bekerja.
5. Setting relatif mudah karena hanya dipusatkan di satu file saja (/etc/dhcpd.conf) dan hanya terdiri dari beberapa baris perintah untuk memberikan layanan yang cukup lengkap.
Bagaimana DHCP bekerja dalam Linux
Client DHCP bekerja sebagai program level aplikasi. Sekalipun mengkonfigurasikan beberapa aspek mendasar dari operasi kernel sistem operasi, namun tidak perlu dijalankan sebagai kode kernel level. Dalam hal ini semua yang dilakukan client sebenarnya adalah :
• Mengirim dan menerima beberapa paket UDP
• Mengekstrak nilai dari jawaban DHCPACK
• Menerapkan nilai tersebut pada sistem, seperti yang dilakukan ifconfig atau route.
Sedikit kesulitannya adalah client harus menangani lease DHCP sehingga setiap kali ia harus menghubungi server untuk memperpanjang lease terbaru. Untuk alasan ini, client berjalan sebagai “daemon”, yaitu aplikasi yang berjalan pada background, tidak terkoneksi ke terminal apapun (hal ini menjelaskan nama client dhcpcd, sekalipun untuk pertamakalinya akan tampak membingungkan).
Detail lease dicatat dalam dalam suatu file teks. Sekalipun mesin tersebut reboot dalam masa itu, client DHCP dapat menggunakan informasi ini pada saat berikutnya client me-request lease dari server DHCP. Dengan demikian satu mesin dapat menggunakan IP yg sama selama beberapa lama sekalipun alamat tersebut dialokasikan secara dinamis. Informasi ini juga disimpan dalam file dhcpcd.leases yg biasanya terdapat dalam direktodi /var/lib/dhcp
Instalasi DHCP server pada Linux
Cara menginstall server DHCP pada Linux relatif mudah. Di sini saya menggunakan Linux Mandriva 2007.1 yang merupakan turunan dari Red Hat Linux sehingga dapat menggunakan paket instalasi RPM yang lebih mudah. Perintah text instalasi secara manual misalnya seperti ini (sbg root) :
# rpm –ivh dhcp-server-3.0.5-7mdv2007.1.rpm
maka sistem akan menginstalkan paket instalasi DHCP server. Bila ada dependensi harus diinstall dulu secara manual. Tetapi pada distro Mandriva 2007.1 dapat dilakukan cara instalasi yang lebih mudah yaitu dengan menggunakan utility urpmi seperti ini :
# urpmi dhcp
maka sistem akan menginstallkan paket DHCP sekaligus dengan semua dependensi yang dibutuhkan. Untuk melakukan pengecekan apakah software sudah terinstall digunakan perintah :
# rpm –qa |grep dhcp
maka sistem akan menampilkan software-software terinstall yang mengandung kata “dhcp”.

Setelah instalasi selesai, sistem akan membuat file-file konfigurasi untuk DHCP yang terdiri dari 2 file utama yang harus ada untuk dapat menjalankan aplikasi DHCP yang diinstall, yaitu :
• /etc/dhcpd.conf
• /var/lib/dhcp/dhcpcd.leases
Isi dari file /etc/dhcpd.conf yang digunakan untuk memberikan layanan DHCP server pada jaringan bisa di setting sesuai kebutuhan dan dapat dipakai oleh DHCP client baik dari sistem Linux maupun dari sistem Windows. File /var/lib/dhcpd/dhcpcd.leases juga harus ada walaupun pada awalnya hanya sebuah file kosong. Tanpa file ini DHCP tidak akan berjalan. Sebagai contoh di sini kita akan setting server DHCP untuk kebutuhan2x sebagai berikut :
1. PC server DHCP (Linux Mandriva 2007.1) disetting IP statis 192.168.0.1
2. Memberikan alamat IP antara 192.168.0.11 dan 192.168.0.100 pada jaringan
3. Memberikan pada client setting-setting sebagai berikut : subnet mask 255.255.255.0, alamat broadcast 192.168.0.255, default gateway 192.168.0.1, server DNS 192.168.0.10, nama domain default adalah jarkom.net, dan server WINS pada 192.168.0.11 (untuk client windows versi lama)
4. Memberikan lease-lease untuk waktu default 6 jam dan maximal 12 jam
5. Memberikan reservasi alamat IP untuk kartu ethernet dengan MAC address 00-14-2A-06-18-D5 dengan alamat 192.168.0.30 pada komputer Windows XP dan MAC address 00-0C-29-77-78-67 dengan alamat 192.168.0.50 pada komputer Linux openSUSE 10.2
Untuk kebutuhan setting seperti itu maka isi file /etc/dhcpd.conf harus diedit & disesuaikan sehingga menjadi seperti dalam gambar berikut yg sudah diberikan keterangan penggunaan masing2x barisnya.

Dan kemudian untuk menjalankannya harus dilakukan restart terhadap service-nya dulu :
# /etc/rc.d/init.d/dhcpd restart
Perintah ini juga harus selalu dilakukan setelah melakukan perubahan apapun pada isi file /etc/dhcpd.conf. Kemudian apabila menghendaki agar DHCP server selalu start secara otomatis pada saat komputer dijalankan, maka perintah “/etc/rc.d/init.d/dhcpd start” harus dimasukkan dalam file /etc/rc.local yang berfungsi seperti file autoexec.bat dalam sistem Windows.
Instalasi DHCP Client
Memperoleh IP address dinamis server DHCP dari PC client dilakukan dengan cukup mudah baik pada sistem Windows maupun pada sistem Linux. Dan keduanya juga dapat dikonfigurasi dengan menggunakan utility grafis maupun text command. Cara instalasinya misalnya seperti demikian :
1. Client Windows XP Professional SP2.
Dari client Windows bisa dilakukan setting untuk permintaan IP addres di server dengan memilih Obtain dalam halaman setting Control Panel - Network.
Atau juga dapat dengan command text di command prompt dengan mengetikkan di Command Prompt perintah untuk meminta lease IP address baru pada server DHCP :
C:\> ipconfig /renew
Dan bila diinginkan untuk menghapus konfigurasi lesase DHCP yang sedang berjalan digunakan perintah :
C:\> ipconfig /release
Untuk melihat konfigurasi yang telah terpasang, gunakan perintah :
C:\> ipconfig /all

2. Client Linux openSUSE 10.2
Untuk DHCP client di Linux juga relatif mudah memasangnya, pertama dengan menyesuaikan setting di file /etc/sysconfig/network/ifcfg-eth0-[mac-address] seperti gambar berikut. Catatan : path dan nama file bisa tidak sama tergantung distro Linux yang dipakai. Path dan nama file tadi adalah untuk distro Linux openSUSE 10.2 yang saya pakai di sini.

Kemudian cek apakah aplikasi dhcpcd sudah terinstall di komputer Linux yg akan dijadikan DHCP client (cat : untuk distro selain openSUSE mungkin bisa berbeda) :
# rpm -qa |grep dhcpcd
Kalau belum terinstall, install dulu dengan menggunakan tool YaST untuk software DHCP client. Bisa lakukan dg memasukkan kata “dhcpcd” di kolom search software. Setelah muncul, beri check lalu jalankan instalasi. Setelah instalasi selesai ulangi pengecekan di shell dg perintah yg sama.
Kemudian gunakan command text seperti berikut untuk melepas lease IP (dhcpcd –d –k eth0) dan merequest IP address dari server DHCP (dhcpcd –d –B eth0):

Opsi –k >>> adalah untuk melepas lease IP yang sedang berjalan
Opsi -Badalah untuk meminta lease IP baru pada server DHCP
Opsi -d >>> adalah agar dhcpcd mengirimkan banyak informasi ke file /var/log/messages yang akan berguna untuk mengetahui seriap detail proses yang terjadi, termasuk untuk memudahkan troubleshooting bila ada suatu masalah yang terjadi. File tersebut salah satu file log terpenting dalam Linux yang mencatat hampir semua peristiwa yang terjadi dalam sistem, termasuk semua yang terjadi pada saat koneksi DHCP server & client terbentuk.
Gambar berikut adalah menampilkan isi dari file /var/log/messages di shell secara dinamis dengan menampilkan terus menerus baris-baris terbaru yang terjadi, dengan menggunakan perintah :
# tail –f /var/log/messages

Pada client DHCP yang menggunakan Linux, apabila menggunakan konfigurasi DHCP untuk mendapatkan nama domain dan alamat DNS server dalam jaringan, maka setelah client mendapatkan lease IP baru dari server DHCP, maka otomatis DHCP akan merubah isi file /etc/resolv.conf yaitu sebuah file yang berisi konfigurasi nama domain & alamat DNS server untuk komputer yang bersangkutan. Sehingga bila file itu sudah berisi suatu setting tertentu secara manual, maka DHCP akan menghapusnya dan menggantinya dengan konfigurasi yang ada di server DHCP. Sebenarnya hal ini bisa dihindari dengan menambahkan satu opsi lagi dalam command text sewaktu meminta lease IP baru dari server. Opsi-opsi itu dapat dilihat dengan menjalankan perintah :
# man dhcpcd
atau
# dhcpcd –help
Setelah ada DHCP client yang meminta lease IP baru ke server DHCP, maka dhcpd akan menuliskan setiap penyewaan IP yang terjadi ke sebuah file yang bernama : /var/lib/dhcp/dhcpcd.leases di server DHCP. Isi file tersebut adalah seperti gambar berikut :

Begitulah sedikit share dari aku tentang cara instalasi dan setting Server DHCP menggunakan Linux dg Client DHCP menggunakan platform Linux & Windows. Semoga dapat bermanfaat buat rekan2x Linuxers yg membutuhkan.
-rkh-

Routing

Apa itu Routing?
Routing adalah proses dimana suatu item dapat sampai ke tujuan dari satu lokasi ke lokasi lain. Beberapa contoh item yang dapat di-routing : mail, telepon call, dan data. Di dalam jaringan, Router adalah perangkat yang digunakan untuk melakukan routing trafik.
Router atau perangkat-perangkat lain yang dapat melakukan fungsi routing, membutuhkan informasi sebagai berikut :
• Alamat Tujuan/Destination Address - Tujuan atau alamat item yang akan dirouting
• Mengenal sumber informasi - Dari mana sumber (router lain) yang dapat dipelajari oleh router dan memberikan jalur sampai ke tujuan.
• Menemukan rute - Rute atau jalur mana yang mungkin diambil sampai ke tujuan.
• Pemilihan rute - Rute yang terbaik yang diambil untuk sampai ke tujuan.
• Menjaga informasi routing - Suatu cara untuk menjaga jalur sampai ke tujuan yang sudah diketahui dan paling sering dilalui.
Tabel Routing
Sebuah router mempelajari informasi routing dari mana sumber dan tujuannya yang kemudian ditempatkan pada tabel routing. Router akan berpatokan pada tabel ini, untuk memberitahu port yang akan digunakan untuk meneruskan paket ke alamat tujuan.

Jika jaringan tujuan, terhubung langsung (directly connected) di router, Router sudah langsung mengetahui port yang harus digunakan untuk meneruskan paket.

Jika jaringan tujuan tidak terhubung langsung di badan router, Router harus mempelajari rute terbaik yang akan digunakan untuk meneruskan paket. Informasi ini dapat dipelajari dengan cara :
1. Manual oleh “network administrator”
2. Pengumpulan informasi melalui proses dinamik dalam jaringan.
Mengenal Rute Statik dan Dinamik
Ada dua cara untuk memberitahu router bagaimana cara meneruskan paket ke jaringan yang tidak terhubung langsung (not directly connected) di badan router.

Dua metode untuk mempelajari rute melalui jaringan adalah :
Rute Statik - Rute yang dipelajari oleh router ketika seorang administrator membentuk rute secara manual. Administrator harus memperbarui atau meng”update” rute statik ini secara manual ketika terjadi perubahan topologi antar jaringan (internetwork).
Rute Dinamik - Rute secara Dinamik dipelajari oleh router setelah seorang administrator mengkonfigurasi sebuah protokol routing yang membantu menentukan rute. Tidak seperti rute Statik, pada rute Dinamik, sekali seorang administrator jaringan mengaktifkan rute Dinamik, maka rute akan diketahui dan diupdate secara otomatis oleh sebuah proses routing ketika terjadi perubahan topologi jaringan yang diterima dari “internetwork”.

16 January 2008

Agar IP Local Bisa Diakses Oleh IP Luar

Artikel ini sengaja aku tulis karena biar tidak lupa bila suatu saat aku berhadapan dengan kasus ini lagi. Permasalahan nya adalah ketika kita cuma dikasih satu IP Address Publik oleh pihak ISP. Untuk menyiasati hal ini, agar beberapa server kita (Web Server, FTP server, Email Server) yang ada di IP lokal bisa diakses oleh Internet kita dapat menggunakan salah satu aplikasi dilinux yang sudah terkenal bandel…

Bagaimana caranya?

Solusinya adalah dengan NAT (Network Address Translation) yaitu mentranslasikan suatu IP Address ke sisi jaringan yang lain. Pada sistem Operasi Linux kita dapat melakukannya secara standard dengan menggunakan tools iptables. iptables sebagai tools pengatur trafik jaringan memiliki kemampuan untuk melakukan hal tersebut. iptables dijalankan dari sisi server akan meneruskan traffik yang merekues dari sisi publik/internet diteruskan ke sisi lokal.

Sehingga sintaksnya akan menjadi seperti demikian

iptables -t nat -I PREROUTING -p tcp -s IP_Publik_Yang_Merekuest –dport Port_Tujuan -j DNAT –to-destination IP_Lokal_tujuan:Port_aplikasinya

Penjelasan

-t nat = table nat pada iptables
-I PREROUTING = Insert pada chain Prerouting
-p tcp = protokol tcp
-s = Source/sumber Ip address yang merekues. Kalau semua diijinkan = 0/0
–dport = port tujuan yang diminta dari sisi publik
-j DNAT = Target Destination NAT
–to-destination = ke tujuan ip lokal yang diinginkan

Misal kita memiliki ip publik202.130.202.111 dan webserver ada pada sisi lokal 192.168.0.250 maka kita bisa melakukan seperti ini



iptables - t nat -I PREROUTING -p tcp -s 0/0 –dport 80 -j DNAT –to-destination 192.168.0.250:80



Atau jika port 80 telah digunakan oleh server itu sendiri, kitabisa memanfaatkan port yang kosong dari sisi server tersebut misal

iptables - t nat -I PREROUTING -p tcp -s 0/0 –dport 88 -j DNAT –to-destination 192.168.0.250:80

Namun, proses pemanggilan dalam browser harus lengkap menggunakan port

http://202.130.202.111:88

Ya, langkah ini juga bisa di balik apabila seorang administrator jaringan ingin merouting jaringan, agar rekuest ke port tertentu, dapat dialihkan ke route lain, namun logika dibalik dan port destination di belakang di hilangkan. Contoh:

iptables -t nat -I PREROUTING -p tcp -s 192.168.0.0/24 –dport 80 -j DNAT –to-destination 202.130.202.111

Langkah ini juga bisa di gunakan untuk protokol lain juga selain web seperti ssh, remote server dal protokol lainnya.

12 January 2008

Membangun DNS Server Sederhana

(Workshop ini diujicobakan pada distro Mandriva 2007.0)

Pada Kasus kali ini digambarkan sebuah jaringan terdiri dari 2 buah komputer sebagai dns server.

Komputer 1 : 192.168.1.83 (ok,tux.ok)
Komputer 2 : 192.168.1.84 (linux.ok)

Komputer 1 digunakan sebagai DNS Server yang menyimpan top domain “ok” dan domain “tux.ok”. Sedangkan Komputer 2 digunakan sebagai DNS Server yang menyimpan domain “linux.ok”.

Pada komputer 1 :

1.Edit file /etc/resolv.conf

# vi /etc/resolv.conf

Agar komputer client di dalam jaringan tidak dapat menanyakan tentang nama domain lain ke luar dari jaringan lokal, maka arahkan nameserver yang pertama pada komputer 1 tersebut ke dirinya sendiri.

nameserver 192.168.1.83

2.Edit file /etc/named.conf

# vi /etc/named.conf

Tambahkan baris-baris berikut :

zone “ok” {
type master;
file “master/ok.zone”;
};

zone “tux.ok” {
type master;
file “master/tux.ok”;
};

3.Buat file zone “ok.zone”

# vi /var/lib/named/var/named/master/ok.zone

$TTL 38400
@ IN SOA ns.server.ok. root (
42 ; serial
10800 ; refresh
3600 ; retry
604800 ; expire
38400 ; minimum
)
IN NS ns.server.ok.
IN MX 10 mail.server.ok.
IN A 192.168.1.83
ns.server.ok. IN A 192.168.1.83
ns IN A 192.168.1.83
mail IN A 192.168.1.83
www IN A 192.168.1.83
linux.ok. IN NS ns.linux.ok.
ns.linux.ok. IN A 192.168.1.84
tux.ok. IN NS ns.tux.ok.
ns.tux.ok. IN A 192.168.1.83

4.Buat file zone “tux.ok.zone”

# vi /var/lib/named/var/named/master/tux.ok.zone

$TTL 38400
@ IN SOA ns.tux.ok. root (
42 ; serial
10800 ; refresh
3600 ; retry
604800 ; expire
38400 ; minimum
)
IN NS ns.tux.ok.
IN MX 10 mail.tux.ok.
IN A 192.168.1.83
ns IN A 192.168.1.83
mail IN A 192.168.1.83
www IN A 192.168.1.83

5.Rubah kepemilikan masing-masing file zone tersebut dengan merubah group kepemilikan menjadi named.

# chown root.named /var/lib/named/var/named/master/ok.zone
# chown root.named /var/lib/named/var/named/master/tux.ok.zone

6.Edit file /var/lib/named/etc/trusted_networks_acl.conf untuk menentukan pada jaringan mana DNS Server akan digunakan.

# vi /var/lib/named/etc/trusted_networks_acl.conf

Tambahkan 192.168.1.0/24, jika anda menggunakan jaringan 192.168.1.x dengan subnet mask 255.255.255.0.

7.Start service DNS pada komputer tersebut

# service named start

Pada Komputer 2 :

1.Edit file /etc/resolv.conf

# vi /etc/resolv.conf

Agar komputer mengarahkan pertanyaan DNS ke komputer 1 tambahkan baris berikut :

nameserver 192.168.1.83

2.Edit file /etc/named.conf

# vi /etc/named.conf

Tambahkan baris-baris berikut :

zone “linux.ok” {
type master;
file “master/linux.ok.zone”;
};

3.Buat file zone “linux.ok.zone”

# vi /var/lib/named/var/named/master/linux.ok.zone

$TTL 38400
@ IN SOA ns.linux.ok. root (
42 ; serial
10800 ; refresh
3600 ; retry
604800 ; expire
38400 ; minimum
)
IN NS ns.linux.ok.
IN MX 10 mail.linux.ok.
IN A 192.168.1.84
ns IN A 192.168.1.84
mail IN A 192.168.1.84
www IN A 192.168.1.84

4.Rubah kepemilikan file zone tersebut dengan merubah group kepemilikan menjadi named.

# chown root.named /var/lib/named/var/named/master/linux.ok.zone

5.Edit file /var/lib/named/etc/trusted_networks_acl.conf untuk menentukan pada jaringan mana DNS Server akan digunakan.

# vi /var/lib/named/etc/trusted_networks_acl.conf

Tambahkan 192.168.1.0/24, jika anda menggunakan jaringan 192.168.1.x dengan subnet mask 255.255.255.0.

6.Restart service DNS pada komputer tersebut

# service named restart

Selanjutnya untuk mengetes DNS Server tersebut, gunakan perintah-perintah berikut :

# dig linux.ok any

# nslookup www.tux.ok

# host linux.ok

# ping mail.tux.ok

Apabila pada saat restart service terdapat kesalahan/error, coba lihat pesan kesalahan pada file /var/log/messages
# tail /var/log/messages

Apabila service sudah berjalan dengan baik, akan tetapi masih terdapat kesalah pada saat tes, maka lihat pesan kesalahan pada file /var/lib/named/var/log/default.log
# tail /var/lib/named/var/log/default.log

Popularity: 24%

All About Iptables...

Download And Install The Iptables Package

Before you begin, you need to make sure that the iptables software RPM is installed. (See Chapter 6, "Installing Linux Software", if you need a refresher.) When searching for the RPMs, remember that the filename usually starts with the software package name by a version number, as in iptables-1.2.9-1.0.i386.rpm.
How To Start iptables

You can start, stop, and restart iptables after booting by using the commands:

[root@bigboy tmp]# service iptables start
[root@bigboy tmp]# service iptables stop
[root@bigboy tmp]# service iptables restart

To get iptables configured to start at boot, use the chkconfig command:.

[root@bigboy tmp]# chkconfig iptables on

Determining The Status of iptables

You can determine whether iptables is running or not via the service iptables status command. Fedora Core will give a simple status message. For example

[root@bigboy tmp]# service iptables status
Firewall is stopped.
[root@bigboy tmp]#

Packet Processing In iptables

All packets inspected by iptables pass through a sequence of built-in tables (queues) for processing. Each of these queues is dedicated to a particular type of packet activity and is controlled by an associated packet transformation/filtering chain.

There are three tables in total. The first is the mangle table which is responsible for the alteration of quality of service bits in the TCP header. This is hardly used in a home or SOHO environment.

The second table is the filter queue which is responsible for packet filtering. It has three built-in chains in which you can place your firewall policy rules. These are the:

* Forward chain: Filters packets to servers protected by the firewall.
* Input chain: Filters packets destined for the firewall.
* Output chain: Filters packets originating from the firewall.

The third table is the nat queue which is responsible for network address translation. It has two built-in chains; these are:

* Pre-routing chain: NATs packets when the destination address of the packet needs to be changed.
* Post-routing chain: NATs packets when the source address of the packet needs to be changed

Table 14-1 Processing For Packets Routed By The Firewall
Queue Type Queue Function Packet Transformation Chain in Queue Chain Function
Filter Packet filtering

FORWARD

Filters packets to servers accessible by another NIC on the firewall.

INPUT

Filters packets destined to the firewall.

OUTPUT

Filters packets originating from the firewall
Nat Network Address Translation

PREROUTING

Address translation occurs before routing. Facilitates the transformation of the destination IP address to be compatible with the firewall's routing table. Used with NAT of the destination IP address, also known as destination NAT or DNAT.

POSTROUTING

Address translation occurs after routing. This implies that there was no need to modify the destination IP address of the packet as in pre-routing. Used with NAT of the source IP address using either one-to-one or many-to-one NAT. This is known as source NAT, or SNAT.

OUTPUT

Network address translation for packets generated by the firewall. (Rarely used in SOHO environments)
Mangle TCP header modification

PREROUTING
POSTROUTING
OUTPUT
INPUT
FORWARD

Modification of the TCP packet quality of service bits before routing occurs. (Rarely used in SOHO environments)


You need to specify the table and the chain for each firewall rule you create. There is an exception: Most rules are related to filtering, so iptables assumes that any chain that's defined without an associated table will be a part of the filter table. The filter table is therefore the default.

To help make this clearer, take a look at the way packets are handled by iptables. In Figure 14.1 a TCP packet from the Internet arrives at the firewall's interface on Network A to create a data connection.

The packet is first examined by your rules in the mangle table's PREROUTING chain, if any. It is then inspected by the rules in the nat table's PREROUTING chain to see whether the packet requires DNAT. It is then routed.

If the packet is destined for a protected network, then it is filtered by the rules in the FORWARD chain of the filter table and, if necessary, the packet undergoes SNAT in the POSTROUTING chain before arriving at Network B. When the destination server decides to reply, the packet undergoes the same sequence of steps. Both the FORWARD and POSTROUTING chains may be configured to implement quality of service (QoS) features in their mangle tables, but this is not usually done in SOHO environments.

If the packet is destined for the firewall itself, then it passes through the mangle table of the INPUT chain, if configured, before being filtered by the rules in the INPUT chain of the filter table before. If it successfully passes these tests then it is processed by the intended application on the firewall.

At some point, the firewall needs to reply. This reply is routed and inspected by the rules in the OUTPUT chain of the mangle table, if any. Next, the rules in the OUTPUT chain of the nat table determine whether DNAT is required and the rules in the OUTPUT chain of the filter table are then inspected to help restrict unauthorized packets. Finally, before the packet is sent back to the Internet, SNAT and QoS mangling is done by the POSTROUTING chain
Figure 14-1 Iptables Packet Flow Diagram

Image:iptables.gif

It is now time to discuss the ways in which you add rules to these chains.
Targets And Jumps

Each firewall rule inspects each IP packet and then tries to identify it as the target of some sort of operation. Once a target is identified, the packet needs to jump over to it for further processing. Table 14.2 lists the built-in targets that iptables uses.


Table 14-2 Descriptions Of The Most Commonly Used Targets
target Desciption Most Common Options
ACCEPT

* iptables stops further processing.
* The packet is handed over to the end application or the operating system for processing



N/A
DROP

* iptables stops further processing.
* The packet is blocked



N/A
LOG

* The packet information is sent to the syslog daemon for logging
* iptables continues processing with the next rule in the table
* As you can't log and drop at the same time, it is common to have two similar rules in sequence. The first will log the packet, the second will drop it.



--log-prefix "string"

Tells iptables to prefix all log messages with a user defined string. Frequently used to tell why the logged packet was dropped
REJECT

* Works like the DROP target, but will also return an error message to the host sending the packet that the packet was blocked



--reject-with qualifier

The qualifier tells what type of reject message is returned. Qualifiers include:

icmp-port-unreachable (default)
icmp-net-unreachable
icmp-host-unreachable
icmp-proto-unreachable
icmp-net-prohibited
icmp-host-prohibited
tcp-reset
echo-reply

DNAT

* Used to do destination network address translation. ie. rewriting the destination IP address of the packet



--to-destination ipaddress

Tells iptables what the destination IP address should be
SNAT

* Used to do source network address translation rewriting the source IP address of the packet
* The source IP address is user defined



--to-source
[-
][:-]

Specifies the source IP address and ports to be used by SNAT.
MASQUERADE

* Used to do Source Network Address Translation.
* By default the source IP address is the same as that used by the firewall's interface



[--to-ports [-]]

Specifies the range of source ports to which the original source port can be mapped.
Important Iptables Command Switch Operations

Each line of an iptables script not only has a jump, but they also have a number of command line options that are used to append rules to chains that match your defined packet characteristics, such the source IP address and TCP port. There are also options that can be used to just clear a chain so you can start all over again. Tables 14.2 through 14.6 list the most common options.
Table 14-2 General Iptables Match Criteria
iptables command Switch Desciption
-t <-table-> If you don't specify a table, then the filter table is assumed. As discussed before, the possible built-in tables include: filter, nat, mangle
-j Jump to the specified target chain when the packet matches the current rule.
-A Append rule to end of a chain
-F Flush. Deletes all the rules in the selected table
-p Match protocol. Types include, icmp, tcp, udp, and all
-s Match source IP address
-d Match destination IP address
-i Match "input" interface on which the packet enters.
-o Match "output" interface on which the packet exits


In this command switches example

iptables -A INPUT -s 0/0 -i eth0 -d 192.168.1.1 -p TCP -j ACCEPT

iptables is being configured to allow the firewall to accept TCP packets coming in on interface eth0 from any IP address destined for the firewall's IP address of 192.168.1.1. The 0/0 representation of an IP address means any.
Table 14-4 Common TCP and UDP Match Criteria
Switch Desciption
-p tcp --sport TCP source port. Can be a single value or a range in the format: start-port-number:end-port-number
-p tcp --dport TCP destination port. Can be a single value or a range in the format: starting-port:ending-port
-p tcp --syn Used to identify a new TCP connection request. ! --syn means, not a new connection request
-p udp --sport UDP source port. Can be a single value or a range in the format: starting-port:ending-port
-p udp --dport UDP destination port. Can be a single value or a range in the format: starting-port:ending-port


In this example:

iptables -A FORWARD -s 0/0 -i eth0 -d 192.168.1.58 -o eth1 -p TCP \
--sport 1024:65535 --dport 80 -j ACCEPT

iptables is being configured to allow the firewall to accept TCP packets for routing when they enter on interface eth0 from any IP address and are destined for an IP address of 192.168.1.58 that is reachable via interface eth1. The source port is in the range 1024 to 65535 and the destination port is port 80 (www/http).
Table 14-5 Common ICMP (Ping) Match Criteria
Matches used with ---icmp-type Desciption
--icmp-type The most commonly used types are echo-reply and echo-request


In this example:

iptables -A OUTPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT

iptables is being configured to allow the firewall to send ICMP echo-requests (pings) and in turn, accept the expected ICMP echo-replies.

Consider another example

iptables -A INPUT -p icmp --icmp-type echo-request \
-m limit --limit 1/s -i eth0 -j ACCEPT

The limit feature in iptables specifies the maximum average number of matches to allow per second. You can specify time intervals in the format /second, /minute, /hour, or /day, or you can use abbreviations so that 3/second is the same as 3/s.

In this example, ICMP echo requests are restricted to no more than one per second. When tuned correctly, this feature allows you to filter unusually high volumes of traffic that characterize denial of service (DOS) attacks and Internet worms.

iptables -A INPUT -p tcp --syn -m limit --limit 5/s -i eth0 -j ACCEPT

You can expand on the limit feature of iptables to reduce your vulnerability to certain types of denial of service attack. Here a defense for SYN flood attacks was created by limiting the acceptance of TCP segments with the SYN bit set to no more than five per second.
Table 14-6 Common Extended Match Criteria
Switch Desciption
-m multiport --sport A variety of TCP/UDP source ports separated by commas. Unlike when -m isn't used, they do not have to be within a range.
-m multiport --dport A variety of TCP/UDP destination ports separated by commas. Unlike when -m isn't used, they do not have to be within a range.
-m multiport --ports A variety of TCP/UDP ports separated by commas. Source and destination ports are assumed to be the same and they do not have to be within a range.
-m --state

The most frequently tested states are:

ESTABLISHED: The packet is part of a connection that has seen packets in both directions

NEW: The packet is the start of a new connection

RELATED: The packet is starting a new secondary connection. This is a common feature of such protocols such as an FTP data transfer, or an ICMP error.

INVALID: The packet couldn't be identified. Could be due to insufficient system resources, or ICMP errors that don't match an existing data flow.

This is an expansion on the previous example:

iptables -A FORWARD -s 0/0 -i eth0 -d 192.168.1.58 -o eth1 -p TCP \
--sport 1024:65535 -m multiport --dport 80,443 -j ACCEPT

iptables -A FORWARD -d 0/0 -o eth0 -s 192.168.1.58 -i eth1 -p TCP \
-m state --state ESTABLISHED -j ACCEPT

Here iptables is being configured to allow the firewall to accept TCP packets to be routed when they enter on interface eth0 from any IP address destined for IP address of 192.168.1.58 that is reachable via interface eth1. The source port is in the range 1024 to 65535 and the destination ports are port 80 (www/http) and 443 (https). The return packets from 192.168.1.58 are allowed to be accepted too. Instead of stating the source and destination ports, you can simply allow packets related to established connections using the -m state and --state ESTABLISHED options.
Using User Defined Chains

As you may remember, you can configure iptables to have user-defined chains. This feature is frequently used to help streamline the processing of packets. For example, instead of using a single, built-in chain for all protocols, you can use the chain to determine the protocol type for the packet and then hand off the actual final processing to a user-defined, protocol-specific chain in the filter table. In other words, you can replace a long chain with a stubby main chain pointing to multiple stubby chains, thereby shortening the total length of all chains the packet has to pass through. For example

iptables -A INPUT -i eth0 -d 206.229.110.2 -j fast-input-queue
iptables -A OUTPUT -o eth0 -s 206.229.110.2 -j fast-output-queue

iptables -A fast-input-queue -p icmp -j icmp-queue-in
iptables -A fast-output-queue -p icmp -j icmp-queue-out

iptables -A icmp-queue-out -p icmp --icmp-type echo-request \
-m state --state NEW -j ACCEPT

iptables -A icmp-queue-in -p icmp --icmp-type echo-reply -j ACCEPT

Here six queues help assist in improving processing speed. Table 14.7 summarizes the function of each.
Table 14.7 Custom Queues Example Listing
Chain Desciption
INPUT The regular built-in INPUT chain in iptables
OUTPUT The regular built-in OUTPUT chain in iptables
fast-input-queue Input chain dedicated to identifying specific protocols and shunting the packets to protocol specific chains.
fast-output-queue Output chain dedicated to identifying specific protocols and shunting the packets to protocol specific chains.
icmp-queue-out Output queue dedicated to ICMP
icmp-queue-in Input queue dedicated to ICMP
Saving Your iptables Scripts

The service iptables save command permanently saves the iptables configuration in the /etc/sysconfig/iptables file. When the system reboots, the iptables-restore program reads the configuration and makes it the active configuration.

The format of the /etc/sysconfig/iptables file is slightly different from that of the scripts shown in this chapter. The initialization of built-in chains is automatic and the string "iptables" is omitted from the rule statements.

Here is a sample /etc/sysconfig/iptables configuration that allows ICMP, IPSec (ESP and AH packets), already established connections, and inbound SSH.

[root@bigboy tmp]# cat /etc/sysconfig/iptables
# Generated by iptables-save v1.2.9 on Mon Nov 8 11:00:07 2004
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [144:12748]
:RH-Firewall-1-INPUT - [0:0]
-A INPUT -j RH-Firewall-1-INPUT
-A FORWARD -j RH-Firewall-1-INPUT
-A RH-Firewall-1-INPUT -i lo -j ACCEPT
-A RH-Firewall-1-INPUT -p icmp -m icmp --icmp-type 255 -j ACCEPT
-A RH-Firewall-1-INPUT -p esp -j ACCEPT
-A RH-Firewall-1-INPUT -p ah -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited
COMMIT
# Completed on Mon Nov 8 11:00:07 2004
[root@bigboy tmp]#

It is never a good idea to edit this script directly because it is always overwritten by the save command and it doesn't save any comments at all, which can also make it extremely difficult to follow. For these reasons, you're better off writing and applying a customized script and then using the service iptables save command to make the changes permanent.
Fedora's iptables Rule Generator

Fedora comes with a program called lokkit that you can use to generate a very rudimentary firewall rule set. It prompts for the level of security and then gives you the option of doing simple customizations. It is a good place for beginners to start on a test system so that they can see a general rule structure.

Like the service iptables save command, lokkit saves the firewall rules in a new /etc/sysconfig/iptables file for use on the next reboot.

Once you have become familiar with the iptables syntax, it's best to write scripts that you can comment and then save it to /etc/sysconfig/iptables. It makes them much more manageable and readable.
Recovering From A Lost Script

Sometimes the script you created to generate iptables rules may get corrupted or lost, or you might inherit a new system from an administer and cannot find the original script used to protect it. In these situations, you can use the iptables-save and iptables-restore commands to assist you with the continued management of the server.

Unlike the service iptables save command, which actually saves a permanent copy of the firewall's active configuration in the /etc/sysconfig/iptables file, iptables-save displays the active configuration to the screen in /etc/sysconfig/iptables format. If you redirect the iptables-save screen output to a file with the > symbol, then you can edit the output and reload the updated rules when they meet your new criteria with the iptables-restore command.

This example exports the iptables-save output to a text file named firewall-config.

[root@bigboy tmp]# iptables-save > firewall-config
[root@bigboy tmp]# cat firewall-config
# Generated by iptables-save v1.2.9 on Mon Nov 8 11:00:07 2004
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [144:12748]
:RH-Firewall-1-INPUT - [0:0]
-A INPUT -j RH-Firewall-1-INPUT
-A FORWARD -j RH-Firewall-1-INPUT
-A RH-Firewall-1-INPUT -i lo -j ACCEPT
-A RH-Firewall-1-INPUT -p icmp -m icmp --icmp-type 255 -j ACCEPT
-A RH-Firewall-1-INPUT -p esp -j ACCEPT
-A RH-Firewall-1-INPUT -p ah -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited
COMMIT
# Completed on Mon Nov 8 11:00:07 2004
[root@bigboy tmp]#

After editing the firewall-config file with the commands you need, you can reload it into the active firewall rule set with the iptables-restore command.

[root@bigboy tmp]# iptables-restore < firewall-config

Finally, you should permanently save the active configuration so that it will be loaded automatically when the system reboots:

[root@bigboy tmp]# service iptables save

If desired, you can eventually convert this firewall-config file into a regular iptables script so that it becomes more easily recognizable and manageable.
Loading Kernel Modules Needed By iptables

The iptables application requires you to load certain kernel modules to activate some of its functions. Whenever any type of NAT is required, the iptable_nat module needs to be loaded. The ip_conntrack_ftp module needs to be added for FTP support and should always be loaded with the ip_conntrack module which tracks TCP connection states. As most scripts probably will keep track of connection states, the ip_conntrack module will be needed in any case. The ip_nat_ftp module also needs to be loaded for FTP servers behind a NAT firewall.

Unfortunately, the /etc/sysconfig/iptables file doesn't support the loading of modules, so you'll have to add the statements to your /etc/rc.local file which is run at the end of every reboot.

The script samples in this chapter include these statements only as a reminder to place them in the /etc/rc.local file

# File: /etc/rc.local

# Module to track the state of connections
modprobe ip_conntrack

# Load the iptables active FTP module, requires ip_conntrack
modprobe ip_conntrack_ftp

# Load iptables NAT module when required
modprobe iptable_nat

# Module required for active an FTP server using NAT
modprobe ip_nat_ftp

Sample iptables Scripts

This section provides some sample scripts you can use to get iptables working for you. Pay special attention to the logging example at the end.

The basic initialization script snippet should also be included in all your scripts to ensure the correct initialization of your chains should you decide to restart your script after startup. This chapter also includes other snippets that will help you get basic functionality. It should be a good guide to get you started.

Note: Once you feel more confident, you can use Appendix II "Codes, Scripts, and Configurations", to find detailed scripts. The appendix shows you how to allow your firewall to:

* Be used as a Linux Web, mail and DNS server
* Be the NAT router for your home network
* Prevent various types of attacks using corrupted TCP, UDP and ICMP packets.
* Provide outbound passive FTP access from the firewall

There are also simpler code snippets in the Appendix II "Codes, Scripts, and Configurations", for Inbound and outbound FTP connections to and from your firewall
Basic Operating System Defense

You can do several things before employing your firewall script to improve the resilience of your firewall to attack. For example, the Linux operating system has a number of built-in protection mechanisms that you should activate by modifying the system kernel parameters in the /proc filesystem via the /etc/sysctl.conf file. Using of /etc/sysctl.conf to modify kernel parameters is explained in more detail in , Appendix I "Miscellaneous Linux Topics".

Here is a sample configuration:

# File: /etc/sysctl.conf

#---------------------------------------------------------------
# Disable routing triangulation. Respond to queries out
# the same interface, not another. Helps to maintain state
# Also protects against IP spoofing
#---------------------------------------------------------------

net/ipv4/conf/all/rp_filter = 1


#---------------------------------------------------------------
# Enable logging of packets with malformed IP addresses
#---------------------------------------------------------------

net/ipv4/conf/all/log_martians = 1


#---------------------------------------------------------------
# Disable redirects
#---------------------------------------------------------------

net/ipv4/conf/all/send_redirects = 0


#---------------------------------------------------------------
# Disable source routed packets
#---------------------------------------------------------------

net/ipv4/conf/all/accept_source_route = 0


#---------------------------------------------------------------
# Disable acceptance of ICMP redirects
#---------------------------------------------------------------

net/ipv4/conf/all/accept_redirects = 0


#---------------------------------------------------------------
# Turn on protection from Denial of Service (DOS) attacks
#---------------------------------------------------------------

net/ipv4/tcp_syncookies = 1


#---------------------------------------------------------------
# Disable responding to ping broadcasts
#---------------------------------------------------------------

net/ipv4/icmp_echo_ignore_broadcasts = 1

#---------------------------------------------------------------
# Enable IP routing. Required if your firewall is protecting a
# network, NAT included
#---------------------------------------------------------------

net/ipv4/ip_forward = 1

Advanced iptables Initialization

You may also want to add some more advanced initialization steps to your script, including checks for Internet traffic from RFC1918 private addresses. The sample script snippet below outlines how to do this. More complex initializations would include checks for attacks using invalid TCP flags and directed broadcasts which are beyond the scope of this book.

The script also uses multiple user-defined chains to make the script shorter and faster as the chains can be repeatedly accessed. This removes the need to repeat the same statements over and over again.

You can take even more precautions to further protect your network. The complete firewall script in Appendix II "Codes, Scripts, and Configurations", outlines most of them.

#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=
#
# Define networks: NOTE!! You may want to put these "EXTERNAL"
# definitions at the top of your script.
#
#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=

EXTERNAL_INT="eth0" # External Internet interface
EXTERNAL_IP="97.158.253.25" # Internet Interface IP address

#---------------------------------------------------------------
# Initialize our user-defined chains
#---------------------------------------------------------------

iptables -N valid-src
iptables -N valid-dst

#---------------------------------------------------------------
# Verify valid source and destination addresses for all packets
#---------------------------------------------------------------

iptables -A INPUT -i $EXTERNAL_INT -j valid-src
iptables -A FORWARD -i $EXTERNAL_INT -j valid-src
iptables -A OUTPUT -o $EXTERNAL_INT -j valid-dst
iptables -A FORWARD -o $EXTERNAL_INT -j valid-dst

#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
#
# Source and Destination Address Sanity Checks
#
# Drop packets from networks covered in RFC 1918 (private nets)
# Drop packets from external interface IP
#
#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#

iptables -A valid-src -s $10.0.0.0/8 -j DROP
iptables -A valid-src -s $172.16.0.0/12 -j DROP
iptables -A valid-src -s $192.168.0.0/16 -j DROP
iptables -A valid-src -s $224.0.0.0/4 -j DROP
iptables -A valid-src -s $240.0.0.0/5 -j DROP
iptables -A valid-src -s $127.0.0.0/8 -j DROP
iptables -A valid-src -s 0.0.0.0/8 -j DROP
iptables -A valid-src -d 255.255.255.255 -j DROP
iptables -A valid-src -s 169.254.0.0/16 -j DROP
iptables -A valid-src -s $EXTERNAL_IP -j DROP
iptables -A valid-dst -d $224.0.0.0/4 -j DROP

Allowing DNS Access To Your Firewall

You'll almost certainly want your firewall to make DNS queries to the Internet. This is not because it is required for the basic functionality of the firewall, but because of Fedora Linux's yum RPM updater which will help to keep the server up to date with the latest security patches. The following statements will apply not only for firewalls acting as DNS clients but also for firewalls working in a caching or regular DNS server role.

#---------------------------------------------------------------
# Allow outbound DNS queries from the FW and the replies too
#
# - Interface eth0 is the internet interface
#
# Zone transfers use TCP and not UDP. Most home networks
# / websites using a single DNS server won't require TCP statements
#
#---------------------------------------------------------------

iptables -A OUTPUT -p udp -o eth0 --dport 53 --sport 1024:65535 \
-j ACCEPT

iptables -A INPUT -p udp -i eth0 --sport 53 --dport 1024:65535 \
-j ACCEPT

Allowing WWW And SSH Access To Your Firewall

This sample snippet is for a firewall that doubles as a web server that is managed remotely by its system administrator via secure shell (SSH) sessions. Inbound packets destined for ports 80 and 22 are allowed thereby making the first steps in establishing a connection. It isn't necessary to specify these ports for the return leg as outbound packets for all established connections are allowed. Connections initiated by persons logged into the Web server will be denied as outbound NEW connection packets aren't allowed.

#---------------------------------------------------------------
# Allow previously established connections
# - Interface eth0 is the internet interface
#---------------------------------------------------------------

iptables -A OUTPUT -o eth0 -m state --state ESTABLISHED,RELATED \
-j ACCEPT

#---------------------------------------------------------------
# Allow port 80 (www) and 22 (SSH) connections to the firewall
#---------------------------------------------------------------

iptables -A INPUT -p tcp -i eth0 --dport 22 --sport 1024:65535 \
-m state --state NEW -j ACCEPT
iptables -A INPUT -p tcp -i eth0 --dport 80 --sport 1024:65535 \
-m state --state NEW -j ACCEPT


Allowing Your Firewall To Access The Internet

This iptables script enables a user on the firewall to use a Web browser to surf the Internet. HTTP traffic uses TCP port 80, and HTTPS uses port 443.

Note: HTTPS (secure HTTP) is used for credit card transactions frequently, as well as by RedHat Linux servers running up2date. FTP and HTTP are frequently used with yum.

#---------------------------------------------------------------
# Allow port 80 (www) and 443 (https) connections from the firewall
#---------------------------------------------------------------

iptables -A OUTPUT -j ACCEPT -m state \
--state NEW,ESTABLISHED,RELATED -o eth0 -p tcp \
-m multiport --dport 80,443 -m multiport --sport 1024:65535

#---------------------------------------------------------------
# Allow previously established connections
# - Interface eth0 is the internet interface
#---------------------------------------------------------------

iptables -A INPUT -j ACCEPT -m state --state ESTABLISHED,RELATED \
-i eth0 -p tcp



If you want all TCP traffic originating from the firewall to be accepted, then remove the line:

-m multiport --dport 80,443 -m multiport --sport 1024:65535

Allow Your Home Network To Access The Firewall

In this example, eth1 is directly connected to a home network using IP addresses from the 192.168.1.0 network. All traffic between this network and the firewall is simplistically assumed to be trusted and allowed.

Further rules will be needed for the interface connected to the Internet to allow only specific ports, types of connections and possibly even remote servers to have access to your firewall and home network.

#---------------------------------------------------------------
# Allow all bidirectional traffic from your firewall to the
# protected network
# - Interface eth1 is the private network interface
#---------------------------------------------------------------

iptables -A INPUT -j ACCEPT -p all -s 192.168.1.0/24 -i eth1
iptables -A OUTPUT -j ACCEPT -p all -d 192.168.1.0/24 -o eth1

Masquerading (Many to One NAT)

As explained in Chapter 2, "Introduction to Networking", masquerading is another name for what many call many to one NAT. In other words, traffic from all devices on one or more protected networks will appear as if it originated from a single IP address on the Internet side of the firewall.

Note: The masquerade IP address always defaults to the IP address of the firewall's main interface. The advantage of this is that you never have to specify the NAT IP address. This makes it much easier to configure iptables NAT with DHCP.

You can configure many to one NAT to an IP alias, using the POSTROUTING and not the MASQUERADE statement. An example of this can be seen in the static NAT section that follows.

Keep in mind that iptables requires the iptables_nat module to be loaded with the modprobe command for the masquerade feature to work. Masquerading also depends on the Linux operating system being configured to support routing between the internet and private network interfaces of the firewall. This is done by enabling IP forwarding or routing by giving the file /proc/sys/net/ipv4/ip_forward the value 1 as opposed to the default disabled value of 0.

Once masquerading has been achieved using the POSTROUTING chain of the nat table, you will have to configure iptables to allow packets to flow between the two interfaces. To do this, use the FORWARD chain of the filter table. More specifically, packets related to NEW and ESTABLISHED connections will be allowed outbound to the Internet, but only packets related to ESTABLISHED connections will be allowed inbound. This helps to protect the home network from anyone trying to initiate connections from the Internet:

#---------------------------------------------------------------
# Load the NAT module
#
# Note: It is best to use the /etc/rc.local example in this
# chapter. This value will not be retained in the
# /etc/sysconfig/iptables file. Included only as a reminder.
#---------------------------------------------------------------

modprobe iptable_nat

#---------------------------------------------------------------
# Enable routing by modifying the ip_forward /proc filesystem file
#
# Note: It is best to use the /etc/sysctl.conf example in this
# chapter. This value will not be retained in the
# /etc/sysconfig/iptables file. Included only as a reminder.
#---------------------------------------------------------------

echo 1 > /proc/sys/net/ipv4/ip_forward

#---------------------------------------------------------------
# Allow masquerading
# - Interface eth0 is the internet interface
# - Interface eth1 is the private network interface
#---------------------------------------------------------------

iptables -A POSTROUTING -t nat -o eth0 -s 192.168.1.0/24 -d 0/0 \
-j MASQUERADE

#---------------------------------------------------------------
# Prior to masquerading, the packets are routed via the filter
# table's FORWARD chain.
# Allowed outbound: New, established and related connections
# Allowed inbound : Established and related connections
#---------------------------------------------------------------

iptables -A FORWARD -t filter -o eth0 -m state \
--state NEW,ESTABLISHED,RELATED -j ACCEPT

iptables -A FORWARD -t filter -i eth0 -m state \
--state ESTABLISHED,RELATED -j ACCEPT


Note: If you configure your firewall to do masquerading, then if should be the used as the default gateway for all your servers on the network.
Port Forwarding Type NAT (DHCP DSL)

In many cases home users may get a single DHCP public IP address from their ISPs. If a Linux firewall is also your interface to the Internet and you want to host a Web site on one of the NAT protected home servers, then you will have to use port forwarding. Here the combination of the firewall's single IP address, the remote server's IP address, and the source/destination port of the traffic can be used to uniquely identify a traffic flow. All traffic that matches a particular combination of these factors may then be forwarded to a single server on the private network.

Port forwarding is handled by the PREROUTING chain of the nat table. As in masquerading, the iptables_nat module has to be loaded and routing has to be enabled for port forwarding to work. Routing too must be allowed in iptables with the FORWARD chain, this includes all NEW inbound connections from the Internet matching the port forwarding port plus all future packets related to the ESTABLISHED connection in both directions:

#---------------------------------------------------------------
# Load the NAT module
#
# Note: It is best to use the /etc/rc.local example in this
# chapter. This value will not be retained in the
# /etc/sysconfig/iptables file. Included only as a reminder.
#---------------------------------------------------------------

modprobe iptable_nat

#---------------------------------------------------------------
# Get the IP address of the Internet interface eth0 (linux only)
#
# You'll have to use a different expression to get the IP address
# for other operating systems which have a different ifconfig output
# or enter the IP address manually in the PREROUTING statement
#
# This is best when your firewall gets its IP address using DHCP.
# The external IP address could just be hard coded ("typed in
# normally")
#---------------------------------------------------------------

external_int="eth0"
external_ip="`ifconfig $external_int | grep 'inet addr' | \
awk '{print $2}' | sed -e 's/.*://'`"
#---------------------------------------------------------------
# Enable routing by modifying the ip_forward /proc filesystem file
#
# Note: It is best to use the /etc/sysctl.conf example in this
# chapter. This value will not be retained in the
# /etc/sysconfig/iptables file. Included only as a reminder.
#---------------------------------------------------------------

echo 1 > /proc/sys/net/ipv4/ip_forward

#---------------------------------------------------------------
# Allow port forwarding for traffic destined to port 80 of the
# firewall's IP address to be forwarded to port 8080 on server
# 192.168.1.200
#
# - Interface eth0 is the internet interface
# - Interface eth1 is the private network interface
#---------------------------------------------------------------

iptables -t nat -A PREROUTING -p tcp -i eth0 -d $external_ip \
--dport 80 --sport 1024:65535 -j DNAT --to 192.168.1.200:8080

#---------------------------------------------------------------
# After DNAT, the packets are routed via the filter table's
# FORWARD chain.
# Connections on port 80 to the target machine on the private
# network must be allowed.
#---------------------------------------------------------------

iptables -A FORWARD -p tcp -i eth0 -o eth1 -d 192.168.1.200 \
--dport 8080 --sport 1024:65535 -m state --state NEW -j ACCEPT

iptables -A FORWARD -t filter -o eth0 -m state \
--state NEW,ESTABLISHED,RELATED -j ACCEPT

iptables -A FORWARD -t filter -i eth0 -m state \
--state ESTABLISHED,RELATED -j ACCEPT


Static NAT

In this example, all traffic to a particular public IP address, not just to a particular port, is translated to a single server on the protected subnet. Because the firewall has more than one IP address, I can't recommend MASQUERADE; it will force masquerading as the IP address of the primary interface and not as any of the alias IP addresses the firewall may have. Instead, use SNAT to specify the alias IP address to be used for connections initiated by all other servers in the protected network.

Note: Although the nat table NATs all traffic to the target servers (192.168.1.100 to 102), only connections on ports 80,443 and 22 are allowed through by the FORWARD chain. Also notice how you have to specify a separate -m multiport option whenever you need to match multiple non-sequential ports for both source and destination.

In this example the firewall:

* Uses one to one NAT to make the server 192.168.1.100 on your home network appear on the Internet as IP addresses 97.158.253.26.
* Creates a many to one NAT for the 192.168.1.0 home network in which all the servers appear on the Internet as IP address 97.158.253.29. This is different from masquerading

You will have to create alias IP addresses for each of these Internet IPs for one to one NAT to work.

#---------------------------------------------------------------
# Load the NAT module
#
# Note: It is best to use the /etc/rc.local example in this
# chapter. This value will not be retained in the
# /etc/sysconfig/iptables file. Included only as a reminder.
#---------------------------------------------------------------

modprobe iptable_nat

#---------------------------------------------------------------
# Enable routing by modifying the ip_forward /proc filesystem file
#
# Note: It is best to use the /etc/sysctl.conf example in this
# chapter. This value will not be retained in the
# /etc/sysconfig/iptables file. Included only as a reminder.
#---------------------------------------------------------------

echo 1 > /proc/sys/net/ipv4/ip_forward

#---------------------------------------------------------------
# NAT ALL traffic:
###########
# REMEMBER to create aliases for all the internet IP addresses below
###########
#
# TO: FROM: MAP TO SERVER:
# 97.158.253.26 Anywhere 192.168.1.100 (1:1 NAT - Inbound)
# Anywhere 192.168.1.100 97.158.253.26 (1:1 NAT - Outbound)
# Anywhere 192.168.1.0/24 97.158.253.29 (FW IP)
#
# SNAT is used to NAT all other outbound connections initiated
# from the protected network to appear to come from
# IP address 97.158.253.29
#
# POSTROUTING:
# NATs source IP addresses. Frequently used to NAT connections from
# your home network to the Internet
#
# PREROUTING:
# NATs destination IP addresses. Frequently used to NAT
# connections from the Internet to your home network
#
# - Interface eth0 is the internet interface
# - Interface eth1 is the private network interface
#---------------------------------------------------------------

# PREROUTING statements for 1:1 NAT
# (Connections originating from the Internet)

iptables -t nat -A PREROUTING -d 97.158.253.26 -i eth0 \
-j DNAT --to-destination 192.168.1.100

# POSTROUTING statements for 1:1 NAT
# (Connections originating from the home network servers)

iptables -t nat -A POSTROUTING -s 192.168.1.100 -o eth0 \
-j SNAT --to-source 97.158.253.26

# POSTROUTING statements for Many:1 NAT
# (Connections originating from the entire home network)

iptables -t nat -A POSTROUTING -s 192.168.1.0/24 \
-j SNAT -o eth0 --to-source 97.158.253.29

# Allow forwarding to each of the servers configured for 1:1 NAT
# (For connections originating from the Internet. Notice how you
# use the real IP addresses here)

iptables -A FORWARD -p tcp -i eth0 -o eth1 -d 192.168.1.100 \
-m multiport --dport 80,443,22 \
-m state --state NEW -j ACCEPT


# Allow forwarding for all New and Established SNAT connections
# originating on the home network AND already established
# DNAT connections

iptables -A FORWARD -t filter -o eth0 -m state \
--state NEW,ESTABLISHED,RELATED -j ACCEPT

# Allow forwarding for all 1:1 NAT connections originating on
# the Internet that have already passed through the NEW forwarding
# statements above

iptables -A FORWARD -t filter -i eth0 -m state \
--state ESTABLISHED,RELATED -j ACCEPT

Troubleshooting iptables

A number of tools are at your disposal for troubleshooting iptables firewall scripts. One of the best methods is to log all dropped packets to the /var/log/messages file.
Checking The Firewall Logs

You track packets passing through the iptables list of rules using the LOG target. You should be aware that the LOG target:

* Logs all traffic that matches the iptables rule in which it is located.
* Automatically writes an entry to the /var/log/messages file and then executes the next rule.

If you want to log only unwanted traffic, therefore, you have to add a matching rule with a DROP target immediately after the LOG rule. If you don't, you'll find yourself logging both desired and unwanted traffic with no way of discerning between the two, because by default iptables doesn't state why the packet was logged in its log message.

This example logs a summary of failed packets to the file /var/log/messages. You can use the contents of this file to determine which TCP/UDP ports you need to open to provide access to specific traffic that is currently stopped.

#---------------------------------------------------------------
# Log and drop all other packets to file /var/log/messages
# Without this we could be crawling around in the dark
#---------------------------------------------------------------

iptables -A OUTPUT -j LOG
iptables -A INPUT -j LOG
iptables -A FORWARD -j LOG

iptables -A OUTPUT -j DROP
iptables -A INPUT -j DROP
iptables -A FORWARD -j DROP


Here are some examples of the output of this file:

* Firewall denies replies to DNS queries (UDP port 53) destined to server 192.168.1.102 on the home network.

Feb 23 20:33:50 bigboy kernel: IN=wlan0 OUT= MAC=00:06:25:09:69:80:00:a0:c5:e1:3e:88:08:00 SRC=192.42.93.30 DST=192.168.1.102 LEN=220 TOS=0x00 PREC=0x00 TTL=54 ID=30485 PROTO=UDP SPT=53 DPT=32820 LEN=200

* Firewall denies Windows NetBIOS traffic (UDP port 138)

Feb 23 20:43:08 bigboy kernel: IN=wlan0 OUT= MAC=ff:ff:ff:ff:ff:ff:00:06:25:09:6a:b5:08:00 SRC=192.168.1.100 DST=192.168.1.255 LEN=241 TOS=0x00 PREC=0x00 TTL=64 ID=0 DF PROTO=UDP SPT=138 DPT=138 LEN=221

* Firewall denies Network Time Protocol (NTP UDP port 123)

Feb 23 20:58:48 bigboy kernel: IN= OUT=wlan0 SRC=192.168.1.102 DST=207.200.81.113 LEN=76 TOS=0x10 PREC=0x00 TTL=64 ID=0 DF PROTO=UDP SPT=123 DPT=123 LEN=56

The traffic in all these examples isn't destined for the firewall; Therefore, you should check your INPUT, OUTPUT, FORWARD, and NAT related statements. If the firewall's IP address is involved, then you should focus on the INPUT and OUTPUT statements

If nothing shows up in the logs, then follow the steps in Chapter 4, "Simple Network Troubleshooting", to determine whether the data is reaching your firewall at all and, if it is not, the location on your network that could be causing the problem.

As a general rule, you won't be able to access the public NAT IP addresses from servers on your home network. Basic NAT testing requires you to ask a friend to try to connect to your home network from the Internet.

You can then use the logging output in /var/log/messages to make sure that the translations are occurring correctly and iptables isn't dropping the packets after translation occurs.
iptables Won't Start

The iptables startup script expects to find the /etc/sysconfig/iptables before it starts. If none exists, then symptoms include the firewall status always being stopped and the /etc/init.d/iptables script running without the typical [OK] or [FAILED] messages.

If you have just installed iptables and have never applied a policy, then you will face this problem. Unfortunately, running the service iptables save command before restarting won't help either. You have to create this file.

[root@bigboy tmp]# service iptables start
[root@bigboy tmp]#

[root@bigboy tmp]# touch /etc/sysconfig/iptables
[root@bigboy tmp]# chmod 600 /etc/sysconfig/iptables

[root@bigboy tmp]# service iptables start
Applying iptables firewall rules: [ OK ]
[root@bigboy tmp]#

Conclusion

A firewall is a critical part of any establishment that connects to an unprotected network such as the Internet, but a firewall is never sufficient. Web site security involves not just protection from corrupted packets or maliciously overwhelming volumes of traffic, but also involves daily data backups to help recovery from device failures, regular application patching, enforced password policies, restricted and monitored physical access to your servers, reliable power and cooling, secured cabling, redundant hardware, and, probably most importantly, well trained and motivated employees. Security should be viewed as anything that contributes to the desired risk-free functioning of your site, and it is well worth the money to invest in and learn from a book that specializes in the topic.
Retrieved from "http://www.linuxhomenetworking.com/wiki/index.php/Quick_HOWTO_:_Ch14_:_Linux_Firewalls_Using_iptables"