目前分類:FreeBSD (119)

瀏覽方式: 標題列表 簡短摘要

近期主管機關會拿 SecurityHeaders 網站來檢測網站,因此調整了一下 Apache 和 PHP 的設定

以下為 Apache 的設定,原則上以下設定有做完應該就可以拿到 A+ 的等級了

<IfModule headers_module>

    #

    # Avoid passing HTTP_PROXY environment to CGI's on this or any proxied

    # backend servers which have lingering "httpoxy" defects.

    # 'Proxy' request header is undefined by the IETF, not listed by IANA

    #

    RequestHeader unset Proxy early

 

    #HTTP Strict Transport Security (HSTS)

    Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"

 

    #Content-Security-Policy (CSP)

    Header set Content-Security-Policy "frame-ancestors 'self';"

 

    #X-XSS-Protection

    Header set X-XSS-Protection "1; mode=block"

 

    #X-Content-Type-Options

    Header set X-Content-Type-Options nosniff

 

    #Permissions-Policy

    Header always set Permissions-Policy "geolocation=(),midi=(),sync-xhr=(),microphone=(),camera=(),magnetometer=(),gyroscope=(),fullscreen=(self),payment=()"

 

    #X-Frame-Options

    Header always append X-Frame-Options SAMEORIGIN

 

    #Referrer-Policy

    #Header set Referrer-Policy "no-referrer-when-downgrade"

    Header set Referrer-Policy "strict-origin-when-cross-origin"

</IfModule>

另外 PHP 也可以優化一下,要設定 php.ini

; Whether to use cookies.

; http://php.net/session.use-cookies

session.use_cookies = 1

 

; http://php.net/session.cookie-secure

session.cookie_secure = 1

 

; This option forces PHP to fetch and use a cookie for storing and maintaining

; the session id. We encourage this operation as it's very helpful in combating

; session hijacking when not specifying and managing your own session id. It is

; not the be-all and end-all of session hijacking defense, but it's a good start.

; http://php.net/session.use-only-cookies

session.use_only_cookies = 1

 

; Whether or not to add the httpOnly flag to the cookie, which makes it

; inaccessible to browser scripting languages such as JavaScript.

; http://php.net/session.cookie-httponly

session.cookie_httponly = True

 

; Add SameSite attribute to cookie to help mitigate Cross-Site Request Forgery (CSRF/XSRF)

; Current valid values are "Strict", "Lax" or "None". When using "None",

; make sure to include the quotes, as `none` is interpreted like `false` in ini files.

; https://tools.ietf.org/html/draft-west-first-party-cookies-07

session.cookie_samesite = Lax

 

參考資料

[1] DEVCORE - HTTP Headers 的資安議題 (1)

[2] 增加安全的 HTTP Headers

Bojack 發表在 痞客邦 留言(0) 人氣()

最近將網站重新升級至 FreeBSD 12.1 的版本,其中 Web Server 的部份仍延用 Apache 使用

另外因為目前 HTTPS 已經是基本標準了,但啟用 HTTPS 不代表一定是安全,還是有一些地方要注意的

因分享一下我是如何調整 Apache 來符合 SSLLabs A+ 標準

螢幕快照 2020-04-25 上午11.26.12.png

1. 首先要調整 Cipher,這是我的設定

SSLCipherSUite "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH EDH+aRSA !CAMELLIA !SEED !3DES !RC4 !aNULL !eNULL !LOW !MD5 !EXP !PSK !SRP !DSS"

2. 調整 SSL Protocol,只支援 TLS 1.2 以上

SSLProtocol +TLSv1.2 +TLSv1.3

3. 讓網站支援 HSTS,我是加在 httpd-ssl.conf 每個 VirtualHost 底下第一行

Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"

4. 讓網站 DNS 支援 Certification Authority Authorization (CAA)

可以參考這篇文章說明,設定 DNS CAA 紀錄,保護自己的 SSL/TLS 憑證

另外我用的 Apache 版本是 2.4.43,OpenSSL 的版本是 1.1.1.d

 

文章標籤

Bojack 發表在 痞客邦 留言(0) 人氣()

目前透過一些網站 (如 What's MyIP) 或瀏覽器外掛 (如 Wappalyzer) 都可以很簡易識別公開在網路上 Web 伺服器的主機資訊

若不希望被人知道目前主機是用什麼版本,只要透過修改 Apache 及 PHP 的二個設定檔就可以隱藏起來了

Apache 的部份只要在 httpd.conf 裡面加入以下二行

ServerSignature Off

ServerTokens Prod

PHP 的部份只要在 php.ini 設定一行

expose_php = Off

這樣子就可以囉 !

Bojack 發表在 痞客邦 留言(0) 人氣()

簡述幾個安裝步驟

首先安裝 Certbot Ports 套件,這也是 Let's Encrypt 建議的工具
# cd /usr/ports/security/py-certbot/
# make install clean

這過程會有一點久,因為它要連同一起裝 python

安裝好之後就可以來申請憑證了,首先先確認您的網站根目錄在哪兒,以我的來說是在 /usr/local/www/apache24/data 底下,這路徑等等會用到

申請憑證指令如下 (請自行更換紅字網址名稱)

# certbot certonly --webroot --webroot-path /usr/local/www/apache24/data/ -d www.bojack.com

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): bojack@bojack.com <--- 請輸入您的 Email

Bojack 發表在 痞客邦 留言(0) 人氣()

以前更新 FreeBSD 的 Ports 都是用 cvsup,但在新版本都不適用了,取而代之的是用 portsnap

簡單記錄一下步驟

1. 先更新 /etc/portsnap.conf 裡的 SERVERNAME=portsnap.tw.FreeBSD.org,改成指向台灣的站

2. 第一次使用 Portsnap 請先下指令 #portsnap fetch extract

3. 日後要更新 Ports 就下指令 #portsnap fetch update

Bojack 發表在 痞客邦 留言(0) 人氣()

架構圖如下

PC ---- 172.16.1.0/24 ( vlan103 ) <---> Core Switch <---> 192.168.1.0/24 ( vlan102 ) ---- DHCP Server 192.168.1.2

之前曾有架設過 DHCP Server 的經驗,不過當時是在同一個網段做 IP 配發的動作

若要在不同網段也配發 IP,舉例來說我的 DHCP Server 在 vlan102 192.168.1.0/24 的網段,想要配發 vlan103 172.16.1.0/24 的網段 IP 該怎麼做呢?

這是我的設定參考一下

ddns-update-style none;
authoritative;
default-lease-time      86400;
max-lease-time          172800;

subnet 192.168.1.0 netmask 255.255.255.0 {
}

shared-network vlan103 {
        subnet 172.16.1.0 netmask 255.255.255.0 {
         range 172.16.1.10 172.16.1.100;
         option subnet-mask 255.255.255.0;
         option routers 172.16.1.1;
         option broadcast-address 172.16.1.255;
         option domain-name-servers 168.95.1.1,8.8.8.8;
        }
}

至於 Router 的部份設定如下,設定 DHCP Relay 即可

interface Vlan103
   ip address 172.16.1.1 255.255.255.0
   ip helper-address 192.168.1.2

 

Bojack 發表在 痞客邦 留言(0) 人氣()

現今的資安問題,其實有很大的問題都發生在網站上面,網站程式若沒有開發好就有可能遭到駭客入侵與攻擊

而網路上的使用者若不小心瀏覽了被駭的網站,也是有可能在不知覺的情況發生中毒或資料遭竊取

網站程式應該如何被檢核呢?簡單來說可分為黑箱 ( 實際模擬駭客攻擊行為 ) 或白箱 ( 檢核原始碼 ) 測試,詳細的資訊可以參考 iThome 這一篇靜態程式碼安全性檢核說明

若對資安有些了解的朋友,針對 WAF ( Web Application Firewall ) 這個字眼應該不會很陌生,在程式尚未改寫已知的漏洞時,這時 WAF 就可以跳出來幫忙擋一下了

不過還是要說,利用 WAF 來擋並不是治本的方法,它只是能就所知的攻擊手法進行防護,程式有哪些 Bug 還是得花時間改寫才能夠確保沒問題

而市面上其實也是有一些 Commercial WAF,不過就是得花$$買,這篇教學是用免錢的方式直接在 Web Server 上架起 WAF 的防護功能

以我的 FreeBSD 環境來說,利用 Ports 就可以很輕易的將 ModSecurity 安裝起來

# cd /usr/ports/www/mod_security
# make install clean

裝好之後來去將設定檔放上去 Apache 裡的 httpd.conf

# cd /usr/local/etc/apache22
# vi httpd.conf

加入下面幾行

# 載入 mod_security
LoadModule security2_module libexec/apache22/mod_security2.so
Include /usr/local/etc/modsecurity.conf

# 將自己假裝成 IIS,等等測試用
<IfModule mod_security2.c>
SecServerSignature "Microsoft-IIS/5.0"
</IfModule>

接下來去產生 modsecurity.conf

# cd /usr/local/etc/
# cp modsecurity.conf-example modsecurity.conf

modsecurity.conf 產生出來之後,可以去做一些適度的修改,以下是我有改的地方

SecRuleEngine DetectionOnly
SecAuditLog /var/log/mod_security/modsec_audit.log
SecDebugLog /var/log/mod_security/modsec_debug.log

好了之後重新啟動 Apache 即可,至於要改 modsecurity 有沒有生效呢?可以透過剛才我們加入假裝成 IIS 的設定來檢驗

# telnet 127.0.0.1 80
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
get http:1.1 / (輸入左邊的指令)

HTTP/1.1 400 Bad Request
Date: Thu, 24 Jan 2013 07:31:43 GMT
Server: Microsoft-IIS/5.0
Content-Length: 226
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
</body></html>
Connection closed by foreign host.

到這邊就算安裝完成了,接下來要來設定一些常用的 Rule,在 ModSecurity 的網站上有提供二個版本

一個是 OWASP ModSecurity Core Rule Set ,這是不用錢的,而另一個是 Commercial Rules ,能擋的東西就不少了

本篇的教學既然是以免費的為主,那當然是用 OWASP ModSecurity Core Rule Set 來設定囉 ~~ 先下載 Core Rule Set 設定檔並解開到 Apache 的目錄底下

# cd /tmp
# tar -zxvf SpiderLabs-owasp-modsecurity-crs-2.2.7-0-ga77c1a1.tar.gz
# mv SpiderLabs-owasp-modsecurity-crs-a77c1a1 /usr/local/etc/apache22/Includes/crs

接下來我們要將要啟用的規則與設定都 copy 過去 activated_rules 目錄

# cd /usr/local/etc/apache22/Includes/crs
# cp modsecurity_crs_10_setup.conf.example activated_rules/modsecurity_crs_10_setup.conf
# cd activated_rules
# cp ../base_rules/* .
# cp ../optional_rules/* .

這時再回頭去改一下 Apache 的 httpd.conf 的設定,改這下面這樣

<IfModule mod_security2.c>
SecServerSignature "Microsoft-IIS/5.0"
Include "/usr/local/etc/apache22/Includes/crs/activated_rules/*.conf"
</IfModule>

接下來重新啟動一下 Apache,不過此時會發現一直啟動不了,會有 Error 訊息如下

Syntax error on line 52 of /usr/local/etc/apache22/Includes/crs-bak/activated_rules/modsecurity_crs_20_protocol_violations.conf: Error parsing actions: Unknown action: ver

原因在這裡可以看到,因為目前我在 Ports 安裝的 ModSecurity 是 2.6.6 版,而下載回來的 Core Rule Set 是 for 2.7.0 用的,因為版本不相容的關係所以會無法使用

所以請重新下載舊版的即可,從這邊就可以下載了,再重新啟動一次 Apache ~~ 大功告成!

[1] ModSecurity

[2] 以 ModSecurity 實作 Webapp Firewall

[3] How to install apache2 mod_security and mod_evasive on Ubuntu 12.04 LTS server

Bojack 發表在 痞客邦 留言(0) 人氣()

首先先到 ports 裡安裝 portupgrade

# cd /usr/ports/ports-mgmt/portupgrade
# make install clean

在開始更新套件之前,首先要做的事情就是先更新 Ports tree

# cd /usr/ports
# make update

接下來列出有哪些套件是需要更新,可以透過下列的指令來檢視

# pkg_version -v | grep '<'

在更新之前請先利用指令 pkgdb 來檢查程式的相依性,避免等等升級時出問題

# pkgdb -F

假設我要更新的是 php 5.4.5 -> 5.4.7,同時也想要一併更新相關的 extensions

# portupgrade -fry php-5.4.5

-f 是強制更新的意思
-r 是把有相依性的套件也一併升級
-y 反是有要問 yes 的地方一律回答 yes

然後系統就會開始更新了,這時就會花一點時間

當更新作業完成時,可以再整理一次 package

# pkgdb -F

也可以透過下列指令一併清楚升級時產生的暫存檔

# portsclean -CD

大功告成 n_n

[1] 不自量力的Weithenn - PortUpgrade-升級已安裝套件

[2] BRYAN手札-生活記趣 - 使用 portupgrade 來升級 FreeBSD 上的套件

[3] zgod拉哩拉紮 專業高級水電工 - [FreeBSD] portupgrade好用啊XD

Bojack 發表在 痞客邦 留言(0) 人氣()

一個很簡單的 shell,寫好後放到 crontab 每天執行一次就可以了

#!/bin/sh
#先產生昨天的日期,請自行決定要用 FreeBSD or Linux 的
#FreeBSD 的用法
dt=`date -v-1d "+ %Y%m%d`

#Linux 的 Shell
#dt=`date -d'-1 day' +%Y%m%d`

#切換到 log 存放的目錄
cd /xxx/xxx/xxx

#壓縮昨天一整天的 log ( log 檔可能長成這樣 asa_log-20121116 )
tar -zcvf asa_log-`echo $dt`.tar.gz asa_log-`echo $dt`

#將壓縮好的檔案搬移到某處
mv asa_log-`echo $dt`.tar.gz /xxx/xxx/asa_log-`echo $dt`.tar.gz

#刪除原來的未壓縮的 log
rm -rf asa_log-`echo $dt`

Bojack 發表在 痞客邦 留言(0) 人氣()

今天處理到一個問題,有某個系統要和 LDAP Server 主機做認證,一直認證不過,從 log 裡發現這行訊息

conn=1 op=0 RESULT tag=97 err=2 text=historical protocol version requested, use LDAPv3 instead

因為 OpenLDAP 2.* 預設都是只接受 LDAP V3 協定認證,所以碰到來自 V2 的就不行了

只要在 slapd.conf 加入下面這一行,重新啟動 LDAP Server 就 OK 了!

allow bind_v2

Bojack 發表在 痞客邦 留言(0) 人氣()

原則上這篇是接續【FreeBSD】BIND 9 的 View 實作的筆記,我們原本已經有一台 DNS 了,但如果它掛了帶來的衝擊影響其實蠻大的

因此通常在 DNS 的部份我們會放二台 DNS,一台是 Master 主要的,另一台 Slave 就是定時去抄寫 Master 的紀錄

首先我們在 Slave DNS 的部份要設定二個 IP,10.1.1.5 是用來查詢 Master DNS 裡 Intranet 的紀錄,而 10.1.1.6 是用來查詢 Master DNS 裡 Internet 的紀錄

如果 Slave DNS 不綁定二個 IP 的話,就只能查到 Intranet 或 Internet 其中一個 View 的紀錄了

這台是 Master DNS ( 10.1.1.4 ) 的 /etc/named/named.conf

acl "lan" { 10.1.1.0/24; };

view "internal" {
        match-clients { !10.1.1.6; lan; 127.0.0.1; };
        zone "." IN {
                type hint;
                file "/etc/namedb/named.root";
        };
        zone "bojack.net" IN {
                type master;
                file "/etc/namedb/master/bojack.intranet";
                allow-transfer { 10.1.1.5; };
        };
};

view "external" {
        match-clients { any; };
        recursion no;
        zone "." IN {
                type hint;
                file "/etc/namedb/named.root";
        };
        zone "bojack.net" IN {
                type master;
                file "/etc/namedb/master/bojack.internet";
                allow-transfer { 10.1.1.6; };
        };
};

這台是 Slave DNS ( 10.1.1.5 & 10.1.1.6 ) 的 /etc/named/named.conf

acl "lan" { 10.1.1.0/24; };

view "internal" {
        match-clients { lan; 127.0.0.1; };
        zone "." IN {
                type hint;
                file "/etc/namedb/named.root";
        };
        zone "bojack.net" IN {
                type slave;
                file "/etc/namedb/master/bojack.intranet";
                masters { 10.1.1.4; };
                transfer-source 10.1.1.5;
        };
};

view "external" {
        match-clients { any; };
        recursion no;
        zone "." IN {
                type hint;
                file "/etc/namedb/named.root";
        };
        zone "bojack.net" IN {
                type slave;
                file "/etc/namedb/master/bojack.internet";
                masters { 10.1.1.4; };
                transfer-source 10.1.1.6;
        };
};

接下來只要重啟二台 DNS 就可以有 Master & Slave 的備援功能了!

參考資料

[1] Bind9 View 底下的 master/slave 設定方案

Bojack 發表在 痞客邦 留言(0) 人氣()

BIND 9 之後提供一個很好用的功能 View,我們可以依據不同的 IP 查詢來回應不同的結果,通常針對 Internet & Intranet 的環境更是適合

以下是我實作的環境,我中間的 DNS Server 目前只綁一個 Private,至於回應外部的 Public IP 則是透過防火牆 NAT mode 轉進來

要實作 View 只要在 named.conf 裡動一點手腳即可,設定如下

acl "lan" { 10.1.1.0/24; };  //首先先定義出內網的 IP 範圍

view "internal" {
        match-clients { lan; 127.0.0.1; };  //當來自於 lan 或 127.0.0.1 的查詢時,BIND 就回應 bojack.intranet 裡的記錄
        zone "." IN {
                type hint;
                file "/etc/namedb/named.root";
        };
        zone "bojack.net" IN {
                type master;
                file "/etc/namedb/master/bojack.intranet";
        };
};

view "external" {
        match-clients { any; };  //除了 lan 或 127.0.0.1 的查詢時,BIND 就回應 bojack.internet 裡的記錄
        recursion no;
        zone "." IN {
                type hint;
                file "/etc/namedb/named.root";
        };
        zone "bojack.net" IN {
                type master;
                file "/etc/namedb/master/bojack.internet";
        };
};

接下來重啟 BIND 就可以啟用 View 的功能了!

參考資料

[1] bind - DNS 設定

Bojack 發表在 痞客邦 留言(0) 人氣()

困擾了很久的問題在 weithenn 的教學找到了解決方法

freebsd#vi /etc/mtree/BIND.chroot.dist

把下面預設的這一行

/set type=dir uname=root gname=wheel mode=0755

改成

/set type=dir uname=bind gname=wheel mode=0755

Bojack 發表在 痞客邦 留言(1) 人氣()

原則上確定系統 kernel 是否支援 md

# cat /usr/src/sys/i386/conf/GENERIC | grep 'md'
device          md              # Memory "disks"

沒有支援的話請重編 Kernel,接下來查看一下您原本的 SWAP 空間

# swapinfo -h
Device          1K-blocks     Used    Avail Capacity
/dev/ad1s1b      1048576       0B      1G     0%

目前我這台是 1G,假設我想要加到 2G 的話請用下面指令,並且修改權限

# dd if=/dev/zero of=/usr/swap0 bs=1024k count=1024
# chmod 0600 /usr/swap0

最後在 /etc/rc.conf  加入這一行

swapfile="/usr/swap0"

好了之後重開機即可生效,若不想重開機可使用下列指令

# mdconfig -a -t vnode -f /usr/swap0 -u 0 && swapon /dev/md0

參考資料

[1] 小惡魔 – 電腦技術 – 工作筆記 – AppleBOY - [FreeBSD]解決swap不夠的情況:Add Swap Space

 

Bojack 發表在 痞客邦 留言(0) 人氣()

其實這個技術出來很久很久了,早在以前自己有架設 WordPress 時發現到這東西

以往寫程式式,網址呈現的樣子大概會是這樣

http://www.bojack.net/news/index.php?newsid=10

而利用 mod_rewrite 可以讓網址做些許的改變,就像下面這二行範例一樣

http://www.bojack.net/news/10 or

http://www.bojack.net/news/10.html

至於為什麼要這麼做,就個人的感受是網址至少看起來簡潔了不少

另外 gslin 大神說明也指出,這樣做的話會使得系統程式較有彈性,程式若有做改變時對使用者來說也不會有太多餘影響

而最近幫單位寫了一個類似免費空間 ( Free File Hosting ) 的介面,因為同仁常因 E-mail 附件超過了限制的大小 ( ex: 20M ) 時常常向 MIS 求救

於是這個系統就這樣產生了 ~ 其中就有用到 mod_rewrite 的功能

首先要讓 Apache 支援 mod_rewrite,可以在 httpd.conf 看有沒有這一行

LoadModule rewrite_module modules/mod_rewrite.so

接下來要準備設定 mod_rewrite,原則上有二種寫法,一種是直接寫在 httpd.conf 裡面,另一種是寫在 .htaccess 裡面

若要寫在 .htaccess 也要特別注意 Apache 是否有支援,假設我的網頁是放在 /www/htdocs/freefile 底下

那麼建議在 httpd.conf 加入這些設定,Apache 預設是將 AllowOverride 設定為 None,所以在您要使用的地方先開啟它,這樣才會讓 .htaccess 生效

<Directory /www/htdocs/freefile>
 AllowOverride All
 Order deny,allow
 Deny from all
< /Directory>

最後就是寫 .htaccess 了,範例如下

RewriteEngine On //開啟Rewrite功能
RewriteRule ^([0-9A-Za-z]+).html$ index.php?name=$1 //Rewrite規則
RewriteRule ^([0-9a-z]+)/([0-9]*)$ index.php?name=$1&id=$2 //Rewrite規則

我們再拿第一個規則出來討論,就會長成這樣

RewriteRule ^([0-9A-Za-z]+).html$ index.php?name=$1 //Rewrite規則

這是套用前跟套用後的差別

http://www.bojack.net/news/index.php?name=Abc10

http://www.bojack.net/news/Abc10.html

至於第二個規則如下,看倌自行參考

http://www.bojack.net/news/index.php?name=abc10&id=10

http://www.bojack.net/news/abc10/10

上面的這些規則其實也就是正規化表示法 ( RegularExpresson ) 的應用,可自行 Google 查一下用法

參考資料

[1] Gea-Suan Lin's BLOG - 為什麼要使用 mod_rewrite?

[2] 風和日麗 天氣晴 - Apache 的 .htaccess 失效?

[3] 小開PHP私房菜 - mod_rewrite 網址轉換

[4] Apache’s AllowOverride All doesn’t do what you think it does

Bojack 發表在 痞客邦 留言(0) 人氣()

原則上需要工具 Win32DiskImager 再加上從 FreeBSD 官網 Download 的 IMG 即可

我是下載 FreeBSD-8.2-RELEASE-i386-memstick.img

下載 Win32DiskImager 執行後,瀏覽 FreeBSD-8.2-RELEASE-i386-memstick.img 後,Device 請選擇 USB 的磁碟編號

好了之後按下 Write 就會開始寫入,完成後它就是個可以用來開機跟安裝囉!

Bojack 發表在 痞客邦 留言(0) 人氣()

剛剛搞定了 Apache + SSL,再來補上一篇 :D

如果要強迫使用者只能走 HTTPS 連線,那就在 httpd.conf 設定一下

首先找到要強迫走 HTTPS 的 Directory,我把我的 DocumentRoot 的範例放上來

<Directory "/usr/local/www/apache22/data">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.2/mod/core.html#options
    # for more information.
    #
    Options FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   Options FileInfo AuthConfig Limit
    #
    AllowOverride None

    #
    # Controls who can get stuff from this server.
    #
    Order allow,deny
    Allow from all

    RewriteEngine on
    RewriteCond %{SERVER_PORT} !^443$
    RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]

</Directory>

加入上面紅色三行即可 :D

至於要用 PHP 程式去控制的話可以參考這一篇 [PHP] 強制使用https連線

參考資料

[1] 今天也要全力以赴 - Apache 強制使用https

[2] Allen開放源碼研究室 - [PHP] 強制使用https連線

Bojack 發表在 痞客邦 留言(0) 人氣()

這二天想做個 HTTPS 連線,把筆記再記一下好了

環境是 FreeBSD 8.2 + Apache 2.2,順序是

1. 自己當 CA

2. 自己再簽一張 Server 的憑證,並由 CA 來簽核它

前置作業如下

# cd /etc/ssl
# cp openssl.cnf openssl.cnf.org
# mkdir certs crl newcerts private
# echo "01" > serial
# touch index.txt
# openssl rand 1024 > ./private/.rand
# chmod 600 ./private/.rand

將 openssl.cnf 裡面這二行設定一下

# vi openssl.cnf
dir = /etc/ssl   # Where everything is kept
default_days = 3650   # how long to certify for

開始簽發一張 RootCA,CA 的期限設為 20 年

# openssl req -new -x509 -keyout private/cakey.pem -out cacert.pem -days 7305 -config openssl.cnf
Generating a 1024 bit RSA private key
..................................++++++
...............................................................................++++++
writing new private key to 'private/cakey.pem'
Enter PEM pass phrase: 請輸入公正單位密碼
Verifying - Enter PEM pass phrase: 請再一次輸入公正單位密碼
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:TW
State or Province Name (full name) [Some-State]:Taiwan
Locality Name (eg, city) []:Taipei
Organization Name (eg, company) [Internet Widgits Pty Ltd]:單位名稱
Organizational Unit Name (eg, section) []:部門名稱
Common Name (eg, YOUR name) []:請輸入完整的 DomainName
Email Address []:bojack@bojack.com
#

CA 製作好之後,接下來要來製作自己 Server 的憑證

# openssl req -nodes -new -x509 -keyout mykey.pem -out myreq.pem -days 365 -config openssl.cnf
Generating a 1024 bit RSA private key
...++++++
.............................................................++++++
writing new private key to 'mykey.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:TW
State or Province Name (full name) [Some-State]:Taiwan
Locality Name (eg, city) []:Taipei
Organization Name (eg, company) [Internet Widgits Pty Ltd]:單位名稱
Organizational Unit Name (eg, section) []:部門名稱
Common Name (eg, YOUR name) []:請輸入完整的 DomainName
Email Address []:bojack@bojack.com
# openssl x509 -x509toreq -in myreq.pem -signkey mykey.pem -out tmp.pem
Getting request Private Key
Generating certificate request
# openssl ca -config openssl.cnf -policy policy_anything -out mycert.pem -infiles tmp.pem
Using configuration from openssl.cnf
Enter pass phrase for /etc/ssl/private/cakey.pem:請輸入公正單位密碼
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Sep 14 03:16:27 2011 GMT
            Not After : Sep 13 03:16:27 2012 GMT
        Subject:
            countryName               = TW
            stateOrProvinceName       = Taiwan
            localityName              = Taipei
            organizationName          = 公司名稱
            organizationalUnitName    = 部門名稱
            commonName                = 機器完整 DomainName
            emailAddress              = bojack@bojack.com
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            Netscape Comment:
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier:
                22:22:22:22:22:22:22:22:22:22:22:22:22:22:22:22:22:22:22:22
            X509v3 Authority Key Identifier:
                keyid:22:22:22:22:22:22:22:22:22:22:22:22:22:22:22:22:22:22:22:22

Certificate is to be certified until Sep 13 03:16:27 2012 GMT (365 days)
Sign the certificate? [y/n]:y

1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
#

這樣子製作好的憑證就由 CA 簽好了(其實也只是自己球員當裁判 :p) 

最後來幫檔案搬個家也變個名稱

# cd /etc/ssl
# mv cacert.pem ./certs/ca.crt
# mv mycert.pem ./certs/server.crt
# mv mykey.pem ./private/server.key
# mv ./private/cakey.pem ./private/ca.key
# rm myreq.pem tmp.pem

把製作出來的金鑰設定一下權限

# chmod -R 400 private

到此為止咱們的憑證就製作完了,接下來要到 Apache 做後續的設定

先編輯 Apache 的設定檔 httpd.conf 找到這一行把前面的 # 拿掉

Include etc/apache22/extra/httpd-ssl.conf

接下來編輯 httpd-ssl.conf

#   General setup for the virtual host
DocumentRoot "/usr/local/www/apache22/data"
ServerName 主機名稱:443
ServerAdmin 網站管理者 E-mail
ErrorLog "/var/log/httpd-error.log"
TransferLog "/var/log/httpd-access.log"

SSLCertificateFile "/etc/ssl/certs/server.crt"
SSLCertificateKeyFile "/etc/ssl/private/server.key"
SSLCertificateChainFile "/etc/ssl/certs/ca.crt"

而 /etc/rc.conf 請確認改成這樣

apache22_enable="YES"
apache22_http_accept_enable="YES"
apache22_flags="-DSSL"

最後重新啟動 Apache 再連 https://你的主機/ 應該就 OK 了!

另外也有找到這一篇 FreeBSD 產生 apache2 ssl 認證,按照這做也是 OK 的

Bojack 發表在 痞客邦 留言(0) 人氣()

2006 年寫過一篇 @Unix-likes 系統中,如何消除檔案裡的 ^M,昨天看到 網絡技術日誌 這篇 Unix 及 Windows 文字檔案轉換

特別再記錄一下在 FreeBSD 裡怎麼做,原則上就是用這二個指令,dos2unix 跟 unix2dos

在 Windows 的環境裡面換行是用 Ctrl-m (^M),而在 UNIX 裡是用 EOL (End-Of-Line)

把檔案從 Unix 上下載到 Windows 裡做編輯時比較沒有感覺,不過一旦把編輯好的檔案扔回 Unix 後就會明顯看到有一堆 ^M

舉例來說這是一小段 PHP 的程式,看了實在很痛苦

<?php^M
^M
// Connect to  LDAP Server^M
$ldapconn = ldap_connect(" LDAP Server ")  or die("Could not connect to LDAP server.");^M
$set = ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);^M

現在解決的辦法就是用指令就可以搞定了

# dos2unix 原始檔名 目的檔名

參考文章

網絡技術日誌 - Unix 及 Windows  文字檔案轉換

Bojack 發表在 痞客邦 留言(0) 人氣()

RRDtool 是原 MRTG 作者另外開發的套件,它可將系統吐出來的資料做 logging 並繪製成圖表

而系統所吐出來的資料是 based on SNMP ( Simple Network Management Protocol ),所以只要是支援 SNMP 的設備都可以用 RRDtool 來做記錄與分析

不過仔細看了一下 RRDtool 操作的語法算小複雜,因此本篇教學會再搭配 Cacti 來協助控制 RRDtool 繪製報表

我的安裝環境如下

[ 安裝所需套件 ]

首先我們先安裝 RRDtool

# cd /usr/ports/databases/rrdtool
# make install clean

接下來安裝 Net-SNMP,因為 Cacti 需利用 Net-SNMP 裡的 snmpwalk 和 snmpget 這二個指令進行資料採集,所以這個是必裝的

# cd /usr/ports/net-mgmt/net-snmp
# make install clean

最後安裝 Cacti

# cd /usr/ports/net-mgmt/cacti
# make install clean

上述三個套件安裝完之後,就可以開始來設定囉!

[ 設定 SNMP ]

首先先來設定 SNMP 的部份

# cd /usr/local/share/snmp
# vi snmpd.conf

snmpd.conf 內容如下

rocommunity MySNMP  // 設定 SNMP Read-Only 的 Community
syslocation MyOffice  // 系統所在地
syscontact bojack@gmail.com  // 管理者 E-mail

另外請在 /etc/rc.conf 加入一行 snmpd_enable="YES"

加好了之後就來啟動 SNMP 吧

# /usr/local/etc/rc.d/snmpd start

[ 設定 Cacti ]

設定 Cacti 這部份看個人習慣,如果您已經有 phpMyAdmin 的話可以在裡面操作,或是透過指令方式來新建

原則上我們需要新建一個 Database、User 讓 Cacti 可以存放相關資料

指令操作如下,新增一個 Database 名稱為 cacti

# mysqladmin -u root -p create cacti
Enter password: 輸入 Root 的密碼

新增一個 User 名叫 cacti 讓它可以存取 cacti 這個 Database,密碼設定為 justforcacti

# mysql -u root -p
Enter password: 輸入 Root 的密碼
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.0.92-log FreeBSD port: mysql-server-5.0.92

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> GRANT ALL ON cacti.* TO cacti@localhost IDENTIFIED BY 'justforcacti';
Query OK, 0 rows affected (0.02 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

mysql> quit
Bye

接下來我們要倒入 Database 相關的 Schema

# mysql -u cacti -p cacti < /usr/local/share/cacti/cacti.sql
Enter password: 以本教學為例輸入 justforcacti

Database 的 Schema 建好之後,接下來我們來去設定程式的部份

# cd /usr/local/share/cacti/include/
# vi config.php

config.php 內容如下,原則上要改的地方就只有 username 跟 password 而已

/* make sure these values refect your actual database/host/user/password */
$database_type = "mysql";
$database_default = "cacti";
$database_hostname = "localhost";
$database_username = "cacti";
$database_password = "justforcacti";
$database_port = "3306";

/* Default session name - Session name must contain alpha characters */
#$cacti_session_name = "Cacti";

接下來新增排程設定,固定每 5 分鐘讓 Cacti 去取得資料

# crontab -u cacti -e

加入這一行即可

*/5 * * * * /usr/local/bin/php /usr/local/share/cacti/poller.php > /dev/null 2>&1

接下來我們要在 Apache 裡面設定 Cacti 的路徑

# vi /usr/local/etc/apache22/httpd.conf

在 httpd.conf 加入下面這幾行

Alias /cacti "/usr/local/share/cacti/"
<Directory "/usr/local/share/cacti/">
        Options None
        AllowOverride None
        Order allow,deny
        Allow from all
</Directory>

好了之後要重新啟動 Apache 讓它生效

# /usr/local/etc/rc.d/apache22 restart

[ 初始化 Cacti ]

網址列請打入 http://您的 IP or Domain/cacti,連結成功後第一次應該會有個初始化的動作,直接 Next

由於我們是新安裝,所以請選 New Install

這一頁原則上請確認相關會用到的程式都是 [OK: FILE FOUND] 的情況就可以按 FINISH 了

最後會到登入的頁面,預設的帳號密碼是 admin,密碼也是 admin

第一次登入時會強制要求改密碼

[ 新增一台監控設備 ]

來為我們的系統新增一台要監看的設備吧,我是選了一台 Cisco 6509 ~ 咱們家的 Core Router

選擇畫面中的 Create devices for network

點選上方 Device 右邊的 Add

這次是新增一台 Cisco Router 6509,依序填入相關的資訊

新增成功後系統就會透過 SNMP 相關指令去截取一些資訊回來,接下來我們點選右邊的 Create Graphs for this Host

要產生的圖片分二種,一種是系統已訂好的樣版,另一種是透過 SNMP 產生的資訊,我想先監看 6509 往防火牆的那個介面

因此選擇下方的 SNMP - Interface Statistics

勾選我想看的 GigabitEthernet Gi7/1  介面,右下角選 In/Out Bytes with Total Bandwidth 後按 Create

新增好之後點選左邊的 Graph Management 就可以看到我們剛才新增的圖表,可以點選進去修改一下

修改一下 Title 的部份為 Cisco 6509 往防火牆,好了之後按 Save

點選上面的 graphs 後可以看到總共有右邊三個類型可選,Tree View、List View及Preview View

點選左上方的圖進去後就可以看到 Cisco 6509 往防火牆的流量

這時應該會發現中文字怎麼都不見了吶!

這問題困擾了我一個下午,原則上解決的問題非常非常簡單,Cacti 或 RRDtool 什麼都不用改

就只是 FreeBSD 裡面沒有中文字型罷了,所以就去 Ports  裡面裝就解決了

# cd /usr/ports/chinese/font-std
# make install clean

至於 Cacti 還有一些外掛可以裝,就請自行連過去看看囉

參考資料

[1]  不自量力的 Weithenn - RRDTool-各項數據流量統計

http://pic.pimg.tw/bojack/1314597229-3861575183_m.png

Bojack 發表在 痞客邦 留言(0) 人氣()