2009年10月27日 星期二

my iptables rule

網路狀態: 電腦直接連中華電信小烏龜 ADSL 上網,沒有開任何服務,只有裝 openntpd 利用 time.stdtime.gov.tw校時,針對 port scan 作防範,對於 icmp 封包沒有設防,INPUT 預設 log後丟棄

Ref: packet-filtering-HOWTO酷學園翻譯鳥哥私房菜- Linux 防火牆與 NAT 主機
酷學園小州學長範例ArchWiki石牌國小防火牆設定ip-sysctl.txt

Updated 10/30:網路設定 pppoe-setup 時若有選擇防火牆 (Standalone 或 Masq) 也會影響 iptables 設定,記得重跑一次,選擇 None


#! /bin/sh
#
# Create iptables'rules, remember to move it to
# /etc/iptables , then modify /etc/conf.d/iptables
#
# Author : lefthaha (at) gmail {dot} com
# Last Modify : 2009 /10 / 26

# clean current rules
iptables -F
iptables -X
iptables -Z

# set Policy
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# accept traffic from loopback iterface
iptables -A INPUT -i lo -j ACCEPT
# accept ICMP messages
iptables -A INPUT -p ICMP -j ACCEPT
# accept establised packet
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

# create new chain
iptables -N block
iptables -N open
iptables -A INPUT -p TCP -j block
iptables -A INPUT -j open

# log then reject packet for imitate default behaviour
iptables -A INPUT -j LOG
iptables -A INPUT -p TCP -j REJECT --reject-with tcp-reset
iptables -A INPUT -p UDP -j REJECT --reject-with icmp-port-unreachable

#################### block chain rules ###################
# from http://www.study-area.org/tips/iptables_def.htm and
# http://wiki.archlinux.org/index.php/Simple_stateful_firewall_HOWTO
# http://www.spps.tp.edu.tw/documents/memo/iptables/iptables.htm

# Force SYN packets check
iptables -A block -i ppp0 -p TCP ! --syn -m state --state NEW -j DROP
# NMAP FIN/URG/PSH
iptables -A block -i ppp0 -p TCP --tcp-flags ALL FIN,URG,PSH -j DROP
# Xmas Tree
iptables -A block -i ppp0 -p TCP --tcp-flags ALL ALL -j DROP
# another Xmas Tree
iptables -A block -i ppp0 -p TCP --tcp-flags ALL SYN,RST,ACK,FIN,URG \
-j DROP

# nmap-Xmas
iptables -A block -i ppp0 -p TCP --tcp-flags URG,PSH,FIN URG,PSH,FIN \
-j DROP

# Null Scan
iptables -A block -i ppp0 -p TCP --tcp-flags ALL NONE -j DROP
# SYN/RST
iptables -A block -i ppp0 -p TCP --tcp-flags SYN,RST SYN,RST -j DROP
# SYN/FIN
iptables -A block -i ppp0 -p TCP --tcp-flags SYN,FIN SYN,FIN -j DROP
# FIN
iptables -A block -i ppp0 -p TCP --tcp-flags ALL FIN -j DROP

#################### open chain rules ####################
# for opened services

# for the connection close FIN/ACK packet
iptables -A open -p TCP --tcp-flags ALL ACK,FIN --sport 80 \
--dport 1024: -j ACCEPT

iptables-save > my_firewall.rules

echo If No error message, use iptables -L -nv to check,
echo Next move ./my_firewall.rules to /etc/iptables
echo then modify /etc/conf.d/iptables to load the rules at boot

2009年10月26日 星期一

Network basic concept

最近在設定 iptables , 要有一些基本知識,就翻了些網頁,順便做點筆記,以後忘掉時才有東西可查

Ref:鳥哥私房菜 - 網路基礎概念Network Sorcery - IPRFC791酷學園 - TCP 與 UDPNetwork Sorcery - TCPRFC793




A Class :
0xxxxxxx.xxxxxxxx.xxxxxxxx.xxxxxxxx ==> NetI_D 的開頭是 0
|-Net-ID|-----------Host-ID-------|
B Class :
10xxxxxx.xxxxxxxx.xxxxxxxx.xxxxxxxx ==> NetI_D 的開頭是 10
|-----Net-ID-----|----Host-ID-----|
C Class :
110xxxxx.xxxxxxxx.xxxxxxxx.xxxxxxxx ==> NetI_D 的開頭是 110
|----------Net-ID---------|-Host-ID|

三種分級在十進位的表示:
A Class : 0.xx.xx.xx ~ 126.xx.xx.xx
B Class : 128.xx.xx.xx ~ 191.xx.xx.xx
C Class : 192.xx.xx.xx ~ 223.xx.xx.xx

Network : Host-ID all '0' , first IP in that that network
Broadcast : Host-ID all '1' , last IP in that that network
Netmask : Net-ID all '1' , Host-ID all '0'
Network / Netmask : Network / bits , bits = How many Net-ID bits

example.
a.
192.168.0.0 / 24
available ip -- 192.168.0.0 ~ 192.168.0.255
b.
192.168.0.128 / 25 is the same with 192.168.0.128/255.255.255.128
25 bits fo Net-ID , available ip -- 192.168.0.128 ~ 192.168.0.255

private IP
A Class:10.0.0.0 - 10.255.255.255
B Class:172.16.0.0 - 172.31.255.255
C Class:192.168.0.0 - 192.168.255.255

three-way handshake:
1.
Server is listening , Client sent TCP packet (SYN , seq = 1200)
# 1200 is the initial sequence number ,
# server expect the first data byte seq = 1200+1
# server also replies a sequence number to client
2.
Server replies packet ( SYN ,ACK, seq = 2340 ack = 1201 )
# Client will also expect server to sent data for seq = 2340+1
3.
Client replies packet (ACK , ack = 2341, seq = 1201 )

2009年10月20日 星期二

HomeBank 基本觀念翻譯

因為個人對金錢沒什麼觀念,就找了個記帳軟體來警惕一下自己 :)

HomeBank 在 Windows 和 OSX 及 Linux 上都可執行,雖然功能有點陽春,但現在對一個只有支出沒有收入和資產的家裡蹲應該足夠了,或許以後會嘗試看看 GnuCash

翻譯文件來源:HomeBank User Manual

我平常是使用英文版,大部份名詞是參考中文版的 HomeBank 加上一些自己的瞎猜 :)

基本觀念:

錢包(Wallet):最高的資料層級,相當於一個 HomeBanke 檔案 (.xhb),其下可建立不同帳號與交易

帳戶(Accounts):第二層的資料,許多不同的帳戶構成一個錢包,每個帳戶下可擁有許多的交易

交易(Transactions):最下層的資料,許多筆的交易形成了帳戶下的金錢流動,另外還提供了幾筆特別的資料欄位
  • 標籤(tags):每筆交易可擁有許多標籤,以空白來分隔不同的標籤,最後可用來分析或分類
  • 付款方式(payment):顯示付款方式的小圖片
  • 資訊(info):有關付款方式的一些資訊,例如日期或支票號碼等 (使用透支報告時只會顯示敘述,不顯示資訊!)
  • 提醒(remind state):追蹤借出去的款項
  • 統計報告(Statistics report):可依照分類、收/付款人、標籤、月、年來顯示交易總和
  • 透支報告(OverDrawn report):可依時間列出各項交易
  • 汽車報告(car-cost data):包含一些有關車輛資料,如加油、里程數…等

Archives(中文版翻的很怪 -"封存的資料庫"):有規律性的金錢匯入或扣款,例如每個月的薪水入帳、房貸扣款、保險費、稅金…等

收/付款人(Payees):可用來分析或分類交易紀錄,輸入過一次後,會自動儲存在清單內供使用者選取

分類(Categories):一樣可用來分析交易紀錄,並可設定次分類、這分類是否為收入

預算(Budget):可為某些分類設定每個月的預算上限,最後用來比對實際上的花費或收入

結餘(Balances):分成三個部份來呈現不同時間點的結餘
  • 銀行(Bank):"有效交易(validated transactions)" 的金額總和
  • 今天(Today):目前的結餘,交易日期在今日之前(包含今日)的交易金額總和 (包含尚未認証(validate)的交易)
  • 未來(Future):包含所有交易的結餘(可設定某些交易日期在未來發生,如還款或信用卡扣款)

2009年10月19日 星期一

[Python] Slicing on sequences

今天在 comp.lang.python 的討論裡看到一篇 Reverse Iteration Through Integers
,提到 list[::-1] 的用法,就找了一下 python docs

Sequences also support slicing: a[i:j] selects all items with index k such that i <= k < j.

When used as an expression, a slice is a sequence of the same type.

This implies that the index set is renumbered so that it starts at 0.

Some sequences also support “extended slicing” with a third “step” parameter: a[i:j:k] selects all items of a with index x where x = i + n*k, n >= 0 and i <= x < j.



所以 a[::-1]  的 index X 會由 X = 0+1*(-1) = -1,X = 0+2*(-1) = -2 這樣慢慢往回跑

Test code:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
a = 123450
print "a=",a,"\t type = ",type(a)
b = str(a)
print "b=",b,"\t type = ",type(b)
c = b[::-1]
print "c=",c,"\t type = ",type(c)
d = int(c)
print "d=",d,"\t type = ",type(d)

[小程式]hipls

有時候無聊會想聽聽廣播,又懶得多開一個網頁, hinedo 似乎可以直接播放,但之前用 openSUSE 時編不起來,就乾脆自己寫一個,這程式會直接到 hiChannel 抓所有的廣播電台清單,讓使用者選擇想聽那幾個電台,然後再將這幾個電台網址存成一份 playlist ,只要使用支援 mms 協定的播放器播放就可以聽了,目前遇到的問題是用 mpayer 播放會顯示亂碼...

用 python 內建函式庫寫的,照理說 windows 也可以使用,不過我只在 linux 上試過,有問題歡迎回報 :)

Updated 11/05:修改顯示電台清單時,因為中文字元長度問題而無法對齊的狀況

Usage:
1. save as hipls.py
2. python hipls.py

Download:hipls.py

Source Code:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author : lefthaha (at) gmail{dot}com
# License :http://creativecommons.org/licenses/by-nc-sa/2.5/tw
# Last Modify : 2009/11/05
#

import sys
import urllib2
import re
import string

def get_html(url):
# must add header to connect hichannel
# http://www.voidspace.org.uk/python/articles/urllib2.shtml
headers = {"User-Agent":" Mozilla/5.0 "}
req = urllib2.Request(url, None, headers)
response = urllib2.urlopen(req)
return response.readlines()

def get_match(pattern, target):
result = []
for line in target:
result.append( pattern.findall(line) )
# strip empty result , able to handle multiple matches
result = filter(lambda x: x is not None, result)
result = [ x[i] for x in result for i in range( len(x) ) ]
return result

def show_all(rlist):
# Updated 2009/11/05
print "目前搜尋到的電台有:"
for num in range(0, len(rlist)-1, 2):
name1 = rlist[num].name.decode("UTF8")
mytab = len(name1.encode("BIG5")) - len(name1)
print "({0:02}) {1:{4}} ({2:02}) {3}".format(num+1,\
rlist[num].name, num+2, rlist[num+1].name, 30+mytab)
print "請輸入你喜歡的電台編號,並且以逗號區別 (ex : 5,4,3,2,1):"

def edit_list(rlist):
show_all(rlist)
inl = re.split(r",|," ,sys.stdin.readline() )
print "你所輸入的電台順序是:"
for num in range( len(inl) ):
inl[num] = string.atoi(inl[num])-1
print "({0}) {1}".format(num+1,rlist[inl[num]].name)
print "以上是否正確?(Y/n)"
if re.match(r"[y|Y]", sys.stdin.readline() ) is not None:
return inl
else:
print "請重新選擇電台順序"
return None

def create_list(all_list, to_save):
entries = len(to_save)
content = "[playlist]\nNumberOfEntries={0}\n\n".format(entries)
for num in range(entries):
content = content + \
"File{0}={1}\nTitle{0}={2}\nLength{0}=-1\n\n".format(num+1,\
all_list[ to_save[num]].get_mms(),all_list[ to_save[num]].name )
content = content + "Version=2"
plsf = open("MyHipls.pls",'w')
plsf.write(content)
plsf.close()

class Radio:
def __init__(self, rid_url):
# strip useless strings
rid_url = re.sub( r".*id=|&lt;", "", rid_url)
rid_url = re.sub( r"\">", ",", rid_url)
# split and assign radio id and name
self.rid, self.name = re.split(",", rid_url)
self.player_url="http://hichannel.hinet.net/player/radio/\
index.jsp?radio_id=" + self.rid
def get_mms(self):
page = get_html(self.player_url)
#?data=mms://bcr.media.hinet.net/RA000007&id=RADIO:206&group="+g);
line = get_match(re.compile(r".*=mms:.*"), page)
line = re.sub(r".*mms", "mms", line[0])
self.mms_url = re.sub(r"&id.*", '', line)
return self.mms_url

def main():
list_url = "http://hichannel.hinet.net/radioRank.do?typeId=99"
list_page = get_html(list_url)
# example : &lt;a href="/radio.do?id=177">ICRT&lt;/a>
rids = get_match( re.compile(r"&lt;a.*\"/radio.+\d\">[^&lt;]+?&lt;"), list_page)
radio_list=[]
for line in rids:
# initialize class Radio
radio_list.append( Radio(line) )
list_to_save = None
while( list_to_save is None):
list_to_save = edit_list(radio_list)
create_list(radio_list, list_to_save)
print "已將所選擇的電台清單儲存至 MyHipls.pls !"

if __name__ == "__main__":
main()

2009年10月14日 星期三

Use XDM with LXDE

ref : Arch WIki Install LXDE on Archlinuxgcin man page XDM Problems kill xconsole after login

因為昨天 system update 後 gdm 跑出一堆錯誤訊息,功能也不太正常,乾脆換成用 xdm 登入,順便將啟動 X11 的方式改成 inittab method,過程紀錄如下

edit ~/.xinitrc
-------------------------------------
#!/bin/sh
#
# lefthaha's xinitrc
# ~/.xinitrc
#
#
export LC_CTYPE="zh_TW.UTF-8"

# for GCIN input method
export XMODIFIERS=@im=gcin
export GTK_IM_MODULE=gcin
export QT_IM_MODULE=gcin
gcin &

#stop system beep
xset b off

exec ck-launch-session startlxde
-----------------------------------------
exit editor
chmod +x ~/.xinitrc (!!!!! important !!!!!)

edit /etc/inittab (remember to backup)
from " id:3:initdefault: " change to " id:5:initdefault: "

edit /etc/X11/xdm/Xsetup_0
comment xconsole

after login , if recieve message "GTK+ icon theme is not properly set"
use lxapperance ,apply again

2009年10月9日 星期五

urxvt 設定

Update 2009/10/26 :用 gcin 在 urxvt 內輸入中文有時可行,有時又沒辦法輸入...不知道問題在哪...
Update 2010/11/14 :修改完 ~/.Xdefaults 還要再用 xrdb -merge ~/.Xdefaults ,接著呼叫 urxvt 才能讀到最新設定

Update 2010/12/26 :設定 geometry,讓內容可以顯示到 80x24

ctrl + shift - down arrow : create new tab
ctrl + shift - left / right arrow : switch between tabs


# lefthaha's ~/.Xdefaults
# after modified, use ` xrdb -merage ~/.Xdefaults ` to reload setting
# then launch `urxvt` again to test

# turn compile xft on
#(copy from arch wiki,may increase performance)
URxvt.buffered: true

# set colors
URxvt.background: black
URxvt.foreground: 7
URxvt.cursorColor: green
URxvt.underlineColor: green

# set transparency
URxvt.transparent: on
URxvt.shading: 40

# set fonts
URxvt.font: xft:DejaVu Sans Mono:pixelsize=16,\
xft:Firefly New Sung Mono:pixelsize=16

# set input method
URxvt.inputMethod: gcin
URxvt.preeditType: Root
URxvt.imLocale: zh_TW.UTF-8

# set tabs
URxvt.perl-ext-common: default,tabbed

# set window size
URxvt.geometry: 86x28

# set clickable URLs
URxvt.perl-ext : default,matcher
URxvt.urlLauncher : /usr/bin/firefox
URxvt.matcher.button : 1

# set misc
URxvt.jumpScroll: True
URxvt.cursorUnderline: True
URxvt.cursorBlink: True



Reference:arch wiki-rxvt-unicoderxvt-unicode man pagefaqArch Linux Forums - Configure My urxvt!

讓 xpdf 能正常顯示中文 (Arch Linux)

除了 xpdf 外,要另外安裝 xpdf-chinese-traditional,修改 /etc/xpdf/xpdf.chinese-traditional ,將 displayCIDFontTT 的字型改成可以顯示中文的字體

範例:


#----- begin Chinese Traditional support package (2004-jul-27)
cidToUnicode Adobe-CNS1 /usr/share/xpdf/Adobe-CNS1.cidToUnicode
unicodeMap Big5 /usr/share/xpdf/Big5.unicodeMap
unicodeMap Big5ascii /usr/share/xpdf/Big5ascii.unicodeMap
cMapDir Adobe-CNS1 /usr/share/xpdf/CMap
toUnicodeDir /usr/share/xpdf/CMap
#displayCIDFontTT Adobe-CNS1 /usr/..../bkai00mp.ttf
#----- end Chinese Traditional support package
#這邊改成 odosung.ttc
displayCIDFontTT Adobe-CNS1 /usr/share/fonts/TTF/odosung.ttc

Arch Linux 安裝筆記

Reference:Official Arch Linux Install GuideBeginners' Guide
  1. /etc/fstab 要以 /dev/disk/by-uuid 來 mount ,否則開機時磁碟編號如果變動,就會出現 check filesystems fail ....
  2. rp-pppoe 設定網路時要先查好 DNS ,手動輸入 (Hinet DNS)
  3. 安裝 alsa-utils ,若 alsa-mixer 設定完依然沒有聲音,可再用 alsaconf 來試看看(Aureon Xfire 1723)
  4. 安裝 xorg,nvidia driver,使用 nvidia-xconfig 來產生 /etc/X11/xorg.conf,接下來starx 可以跑,但是滑鼠鍵盤沒反應;安裝 hal ,並新增到 /etc/rc.conf 的 DAEMONS 部份,使用者加上 hal 這個 group 就可成功抓到鍵盤與滑鼠
  5. 要安裝 vim ,必須先 rm /usr/bin/rview