<?xml version="1.0" encoding="EUC-JP"?>
<rss version="2.0">
   <channel>
      <title>KAJUKAJU.net</title>
      <link>http://www.kajukaju.net/</link>
      <description>CentOSとSolarisでの自宅サーバ構築記</description>
      <language>ja</language>
      <copyright>Copyright 2007</copyright>
      <lastBuildDate>Wed, 11 Apr 2007 15:50:24 +0900</lastBuildDate>
      <generator>http://www.sixapart.com/movabletype/?v=3.34</generator>
      <docs>http://blogs.law.harvard.edu/tech/rss</docs> 

            <item>
         <title>MRTG</title>
         <description><![CDATA[SNMPで取得したMIB情報を可視化（グラフ化）するためにMRTGを導入する。
MRTGは以下のソフトウェアが必要になるので事前にインストールしておく。
　・zlib
　・libpng
　・gd

<a href="http://oss.oetiker.ch/mrtg/" target="_blank">MRTGの公式サイト</a>より最新のソースファイルを入手しインストールする。
<pre>$ wget http://oss.oetiker.ch/mrtg/pub/mrtg-2.15.1.tar.gz
$ tar xvzf mrtg-2.15.1.tar.gz
$ cd mrtg-2.15.1
$ ./configure
$ make
# make install</pre>

MRTGがファイルを作成するディレクトリを作成する。<br />
また、ソースファイルのimagesディレクトリ配下のファイルをコピーしておく。
<pre># mkdir -p /usr/local/mrtg-2/htdocs/
# cp $SRC/images/* /usr/local/mrtg-2/htdocs/</pre>


一番基本的なトラフィックをグラフ化してみる。
トラフィック量を取得するMIBは以下のとおりなのでこの値を使う。
　・.1.3.6.1.2.1.2.2.1.10.2
　・.1.3.6.1.2.1.2.2.1.16.2

　　<strong>/usr/local/mrtg-2/conf/mrtg.cfg</strong>
<pre>######################################################################
# Multi Router Traffic Grapher -- Example Configuration File
######################################################################
# This file is for use with mrtg-2.0
#
# Minimal mrtg.cfg
#--------------------

WorkDir: /usr/local/mrtg-2/htdocs
Language: eucjp

#+++++++++++++++
#Traffic --&gt; bruna --&gt; eth0
#+++++++++++++++
Target[bruna_eth0_traffic]:      .1.3.6.1.2.1.2.2.1.10.2&.1.3.6.1.2.1.2.2.1.16.2:public@192.168.xx.yy:
Options[bruna_eth0_traffic]:     growright,bits
AbsMax[bruna_eth0_traffic]:      1250000
MaxBytes[bruna_eth0_traffic]:    16000
WithPeak[bruna_eth0_traffic]:    wmy
YLegend[bruna_eth0_traffic]:     Bits per Second
ShortLegend[bruna_eth0_traffic]: b/s
LegendI[bruna_eth0_traffic]:     &amp;nbsp;In
LegendO[bruna_eth0_traffic]:     &amp;nbsp;Out
Legend1[bruna_eth0_traffic]:     INトラフィック
Legend2[bruna_eth0_traffic]:     OUTトラフィック
Legend3[bruna_eth0_traffic]:     IN 5分平均ピーク
Legend4[bruna_eth0_traffic]:     OUT 5分平均ピーク
Colours[bruna_eth0_traffic]:     LIGHTBLUE#61A0DF,DKBLUE#0000DD,DARKGREEN#006600,VIOLET#FF00FF
Title[bruna_eth0_traffic]:       bruna --&amp;gt; eth0 --&amp;gt; traffic
PageTop[bruna_eth0_traffic]:     &lt;h1&gt;bruna --&amp;gt; eth0 --&amp;gt; traffic&lt;/h1&gt;</pre>

MRTGは実行したときの取得データを元にグラフを描画するため複数のデータが必要になる。<br />
なお、最初２回のコマンド実行時は過去データが無いためにエラーが出る。
<pre># LANG=C
# /usr/local/mrtg-2/bin/mrtg /usr/local/mrtg-2/conf/mrtg.cfg
Rateup WARNING: /usr/local/mrtg-2/bin/rateup could not read the primary log file for bruna_eth0_traffic
Rateup WARNING: /usr/local/mrtg-2/bin/rateup The backup log file for bruna_eth0_traffic was invalid as well
Rateup WARNING: /usr/local/mrtg-2/bin/rateup Can't remove bruna_eth0_traffic.old updating log file
Rateup WARNING: /usr/local/mrtg-2/bin/rateup Can't rename bruna_eth0_traffic.log to bruna_eth0_traffic.old updating log file

# /usr/local/mrtg-2/bin/mrtg /usr/local/mrtg-2/conf/mrtg.cfg
Rateup WARNING: /usr/local/mrtg-2/bin/rateup Can't remove bbruna_eth0_traffic.old updating log file

# /usr/local/mrtg-2/bin/mrtg /usr/local/mrtg-2/conf/mrtg.cfg</pre>

これで先ほど作成したディレクトリにファイルができているはずである。
<pre># ls -al /usr/local/mrtg-2/htdocs
-rw-r--r--  1 root   root    4023  4月 10 15:40 bruna_eth0_traffic-day.png
-rw-r--r--  1 root   root    1508  4月 10 14:05 bruna_eth0_traffic-month.png
-rw-r--r--  1 root   root    1668  4月 10 15:15 bruna_eth0_traffic-week.png
-rw-r--r--  1 root   root    1883  4月  9 17:40 bruna_eth0_traffic-year.png
-rw-r--r--  1 root   root    6668  4月 10 15:40 bruna_eth0_traffic.html
-rw-r--r--  1 root   root   63636  4月 10 15:40 bruna_eth0_traffic.log
-rw-r--r--  1 root   root   63634  4月 10 15:35 bruna_eth0_traffic.old
-rw-r--r--  1 root   root     343  1月 30 10:15 mrtg-l.gif
-rw-r--r--  1 root   root     538  1月 30 10:15 mrtg-l.png
-rw-r--r--  1 root   root    1144  1月 30 10:15 mrtg-m.gif
-rw-r--r--  1 root   root     414  1月 30 10:15 mrtg-m.png
-rw-r--r--  1 root   root    1779  1月 30 10:15 mrtg-r.gif
-rw-r--r--  1 root   root    1759  1月 30 10:15 mrtg-r.png
-rw-r--r--  1 root   root    4696  1月 30 10:15 mrtg-ti.gif
-rw-r--r--  1 root   root    4293  1月 30 10:15 mrtg-ti.png
-rw-r--r--  1 root   root    3602  1月 30 23:50 mrtg.css</pre>

定期的にMRTGを動かしてデータを収集する必要があるので５分に１回コマンドが実行されるようにcronを設定する。<br />
　　<strong>/etc/crontab</strong>
<pre># For MRTG
0-59/5 * * * * root /usr/local/mrtg-2/bin/mrtg /usr/local/mrtg-2/conf/mrtg.cfg &gt; /dev/null 2&gt;&amp;1</pre>

ブラウザからアクセスできるようApacheの設定変更をおこなう。<br>
　　<strong>/usr/local/apache2/conf/httpd.conf</strong>
<pre>    Alias       /mrtg/         "/usr/local/mrtg-2/htdocs/"</pre>

ブラウザでhttp://site/mrtg/xxx.htmlにアクセスしグラフが見えればOK。
<img alt="bruna_eth0_traffic-day.png" src="http://www.kajukaju.net/centos/bruna_eth0_traffic-day.png" width="500" height="135" />]]></description>
         <link>http://www.kajukaju.net/centos/mrtg.php</link>
         <guid>http://www.kajukaju.net/centos/mrtg.php</guid>
         <category>CentOS</category>
         <pubDate>Wed, 11 Apr 2007 15:50:24 +0900</pubDate>
      </item>
            <item>
         <title>SpamAssassin+MySQL</title>
         <description><![CDATA[SpamAssassinは設定やスパムメールを学習したときの情報をデータベースで保持することができる。
小規模サイトではあまり意味が無いかもしれないけど、連携可能なデータベースにMySQLの記載があったので導入してみる。
<a href="http://svn.apache.org/repos/asf/spamassassin/tags/spamassassin_current_release_3.1.x/sql/README" target="_blank">http://svn.apache.org/repos/asf/spamassassin/tags/spamassassin_current_release_3.1.x/sql/README</a>
<a href="http://wiki.apache.org/spamassassin/UsingSQL" target="_blank">http://wiki.apache.org/spamassassin/UsingSQL</a>

MySQLと連携するためにはPerlからMySQLを扱えるようにする必要がある。<br />
DBD::MySQLをインストールする。
<pre># ln -s /usr/local/mysql/bin/mysql/mysql_config /usr/local/bin/mysql_config
$ wget http://search.cpan.org/CPAN/authors/id/C/CA/CAPTTOFU/DBD-mysql-4.001.tar.gz
$ perl Makefile.pl
$ make
# make install</pre>

SpamAssassin用のデータベースを作成する。
<pre># /usr/local/mysql/bin/mysqladmin -uroot -p create spamdb
Enter password:********

# /usr/local/mysql/bin/mysql -uroot -p
mysql> GRANT ALL ON spamdb.* TO spamd@localhost IDENTIFIED BY '********;
Query OK, 0 rows affected (0.03 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)</pre>

テーブルを作成する。
SpamAssassinのソースファイルの中にテンプレートがあるのでこれを使えばいいのだが、一つは修正して使う。
　・userpref_mysql_custom.sql
　・awl_mysql.sql
　・bayes_mysql.sql

　　<strong>$SRC/sql/userpref_mysql_custom.sql</strong>
<pre>CREATE TABLE `userpref` (
`id` int(8) unsigned NOT NULL auto_increment,
`username` varchar(128) NOT NULL default '',
`preference` varchar(64) NOT NULL default '',
`value` varchar(128) default NULL,
`descript` varchar(128) default NULL,
`added` datetime NOT NULL default '2003-01-01 00:00:00',
`added_by` varchar(128) NOT NULL default '',
`modified` timestamp(14) NOT NULL,
UNIQUE KEY `id` (`id`),
KEY `type` (`preference`),
KEY `added_by` (`added_by`),
KEY `preference` (`preference`),
KEY `username` (`username`)
) TYPE=MyISAM COMMENT='Spamassassin Preferences';</pre>

テンプレートをMySQLに読み込ませてテーブルを作成する。
<pre># /usr/local/mysql/bin/mysql -uroot -p spamdb &lt; userpref_mysql_custom.sql
Enter password:********

$ /usr/local/mysql/bin/mysql -uroot -p spamdb &lt; awl_mysql.sql
Enter password:********

$ /usr/local/mysql/bin/mysql -uroot -p spamdb &lt; bayes_mysql.sql
Enter password:********</pre>

データベースを確認する。
<pre># /usr/local/mysql/bin/mysql -uroot -p spamdb
Enter password:********
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 80
Server version: 5.0.33 Source distribution

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> show tables;
+-------------------+
| Tables_in_spamdb  |
+-------------------+
| awl               |
| bayes_expire      |
| bayes_global_vars |
| bayes_seen        |
| bayes_token       |
| bayes_vars        |
| userpref          |
+-------------------+
7 rows in set (0.01 sec)</pre>

これでデータベース側の設定は完了。
次にSpamAssassin側の設定をおこなっていく。

SpamAssassinのデータベース連携用の設定ファイルを作成する。<br />
　　<strong>/etc/mail/spamassassin/sql.cf</strong>
<pre># Spamassassin to use MySQL for User Preference
user_scores_dsn                  DBI:mysql:spamdb:localhost:3306
user_scores_sql_username         spamd
user_scores_sql_password         ********
user_scores_sql_custom_query     SELECT preference, value FROM _TABLE_ WHERE username = _USERNAME_ OR username = '$GLOBAL' OR username = CONCAT('%',_DOMAIN_) ORDER BY username ASC

# Spamassissin to use MySQL for AWL data
auto_whitelist_factory          Mail::SpamAssassin::SQLBasedAddrList
user_awl_dsn                    DBI:mysql:spamdb:localhost:3306
user_awl_sql_username           spamd
user_awl_sql_password           ********

# Spamassissin to use MySQL for bayes data
bayes_store_module              Mail::SpamAssassin::BayesStore::SQL
bayes_sql_dsn                   DBI:mysql:spamdb:localhost:3306
bayes_sql_username              spamd
bayes_sql_password              ********
bayes_sql_override_username     spamd</pre>

パーミッションを変更する。
<pre># chown spamd:spamd sql.cf</pre>

SpamAssassinの設定をMySQLに移行する。
ちなみにMySQLの場合だと設定変更にSpamAssassinの再起動は必要ではなく、MySQLの設定がリアルタイムで反映されるようになる。
<pre>mysql&gt; INSERT INTO userpref (username,preference,value) VALUES ('$GLOBAL','rewrite_header Subject','[SPAM]');
mysql&gt; INSERT INTO userpref (username,preference,value) VALUES ('$GLOBAL','report_safe','0');
mysql&gt; INSERT INTO userpref (username,preference,value) VALUES ('$GLOBAL','required_score','10.0');
mysql&gt; INSERT INTO userpref (username,preference,value) VALUES ('$GLOBAL','use_bayes','1');
mysql&gt; INSERT INTO userpref (username,preference,value) VALUES ('$GLOBAL','bayes_auto_learn','1');

mysql> select username,preference,value from userpref;
+----------+-------------------------+---------------------+
| username | preference              | value               |
+----------+-------------------------+---------------------+
| $GLOBAL  | rewrite_header Subject  | [SPAM]              |
| $GLOBAL  | report_safe             | 0                   |
| $GLOBAL  | required_score          | 10.0                |
| $GLOBAL  | use_bayes               | 1                   |
| $GLOBAL  | bayes_auto_learn        | 1                   |
+----------+-------------------------+---------------------+
7 rows in set (0.01 sec)</pre>

これで準備はOK。
SpamAssassinをデバッグモードで動かし動作確認をする。
ログを抜粋してみた。
<pre># tail /var/log/mail.log
（省略）
Feb  6 20:28:59 bruna spamd[12826]: config: read file /etc/mail/spamassassin/sql.cf
Feb  6 20:29:04 bruna spamd[12826]: bayes: database connection established
Feb  6 20:29:04 bruna spamd[12826]: bayes: found bayes db version 3
Feb  6 20:29:04 bruna spamd[12826]: bayes: Using userid: 1
Feb  6 20:29:04 bruna spamd[12826]: bayes: not available for scanning, only 1 spam(s) in bayes DB &lt; 200

（省略）

Feb  6 20:29:07 bruna spamd[12826]: auto-whitelist: sql-based connected to DBI:mysql:spamdb:localhost:3306
Feb  6 20:29:07 bruna spamd[12826]: auto-whitelist: sql-based using username: root
Feb  6 20:29:07 bruna spamd[12826]: auto-whitelist: sql-based get_addr_entry: no entry found for ignore@compiling.spamassassin.taint.org|ip=none
Feb  6 20:29:07 bruna spamd[12826]: auto-whitelist: sql-based ignore@compiling.spamassassin.taint.org|ip=none scores 0/0
Feb  6 20:29:07 bruna spamd[12826]: auto-whitelist: AWL active, pre-score: 2.216, autolearn score: 2.216, mean: undef, IP: undef
Feb  6 20:29:07 bruna spamd[12826]: auto-whitelist: sql-based finish: disconnected from DBI:mysql:spamdb:localhost:3306
Feb  6 20:29:07 bruna spamd[12826]: auto-whitelist: post auto-whitelist score: 2.216</pre>

メールの送受信でデータベース内に情報が蓄積されていく。
<pre>mysql> select * from awl;
+-----------------------+----------------------------+---------+-------+----------+
| username              | email                      | ip      | count | totscore |
+-----------------------+----------------------------+---------+-------+----------+
| root                  | pinkgirl85236@yahoo.com.cn | 211.212 |     1 |   17.057 |
| testuser@kajukaju.net | testuser@gmail.com         | 64.233  |     1 |    -1.44 |
+-----------------------+----------------------------+---------+-------+----------+

mysql> select * from bayes_seen;
+----+-------------------------------------------------------+------+
| id | msgid                                                 | flag |
+----+-------------------------------------------------------+------+
|  1 | 17c56e877d2fb11da210512f9879e9c4b9171f35@sa_generated | s    |
|  2 | 316dda809347c69678e368e4c6174d32569593d9@sa_generated | h    |
+----+-------------------------------------------------------+------+
2 rows in set (0.00 sec)

mysql> select * from bayes_vars;
+----+-----------------------+------------+-----------+-------------+-------------+------------------+--------------------+------------------+------------------+
| id | username              | spam_count | ham_count | token_count | last_expire | last_atime_delta | last_expire_reduce | oldest_token_age | newest_token_age |
+----+-----------------------+------------+-----------+-------------+-------------+------------------+--------------------+------------------+------------------+
|  1 | root                  |          1 |         0 |          48 |           0 |                0 |                  0 |       1170761146 |       1170761146 |
|  2 | testuser@kajukaju.net |          0 |         1 |          58 |           0 |                0 |                  0 |       1170761512 |       1170761512 |
+----+-----------------------+------------+-----------+-------------+-------------+------------------+--------------------+------------------+------------------+
2 rows in set (0.00 sec)</pre>

ベイジアンフィルタの情報はユーザ（メールアドレス）ごとに蓄積されている。<br />
手動でメールを学習させるときにはユーザを指定する必要があるので注意する。
<pre># sa-learn --progress --spam <strong>--username=testuser@kajukaju.net</strong> /home/testuser/
100% [===============================================]   0.61 msgs/sec 00m24s DONE
Learned tokens from 15 message(s) (15 message(s) examined)</pre>]]></description>
         <link>http://www.kajukaju.net/centos/spamassassin_mysql.php</link>
         <guid>http://www.kajukaju.net/centos/spamassassin_mysql.php</guid>
         <category>CentOS</category>
         <pubDate>Mon, 09 Apr 2007 12:15:13 +0900</pubDate>
      </item>
            <item>
         <title>SpamAssassin</title>
         <description><![CDATA[スパムメールがひどい状況（1日100通以上）になってきたのでアンチスパムソフトであるSpamAssassinを導入する。
SpamAssassinはベイジアンフィルタ型のアンチスパムソフトなのでメールを受信するたびに学習して賢くなっていくのが特徴。
もちろんホワイトリストやブラックリストを使うことも可能。

SpamAssassinはPerlでかかれており、動作させるためにはいくつかのPerlモジュールが必要。
make時にインストールされていない旨表示されたら個別にインストールしておく。
　・Digest::SHA1
　・HTML::Parser
　・Net::DNS
　・Mail::SPF::Query
　・IP::Country
　・Razor2	
　・Net::Ident
　・IO::Socket::INET6
　・IO::Socket::SSL
　・Time::HiRes
　・DBI
　・LWP::UserAgent
　・HTTP::Date
　・Archive::Tar
　・IO::Zlib

SpamAssassinを起動する専用ユーザを作成する。
<pre># /usr/sbin/groupadd -g 206 spamd
# /usr/sbin/useradd -u 206 -g 206 -s /sbin/nologin -d /etc/mail/spamassassin spamd</pre>

<a href="http://spamassassin.apache.org/" target="_blank">SpamAssassin</a>の公式サイトよりソースファイルを入手しインストールする。
<pre>$ wget http://ftp.kddilabs.jp/infosystems/apache/spamassassin/source/Mail-SpamAssassin-3.1.7.tar.bz2
$ tar xvjf Mail-SpamAssassin-3.1.7.tar.bz2
$ cd Mail-SpamAssassin-3.1.7

$ perl Makefile.PL PREFIX=/usr/local
$ make
# make install
# chown -R spamd:spamd /etc/mail/spamassassin/</pre>

ソースに含まれているサンプルのスパムメールを使って動作確認をしておく。
<pre># /usr/local/spamassassin/bin/spamassassin -t &lt; sample-spam.txt

（省略）

Content analysis details:   (1000.0 points, 5.0 required)

 pts rule name              description
---- ---------------------- --------------------------------------------------
-0.0 NO_RELAYS              Informational: message was not relayed via SMTP
1000 GTUBE                  BODY: Generic Test for Unsolicited Bulk Email
-0.0 NO_RECEIVED            Informational: message has no Received headers</pre>

SpamAssassinの設定ファイルを編集する。<br />
TLECというところで設定ファイルのサンプルを公開しているので使用させて頂く。
<pre># cd /etc/mail/spamassassin
# wget -O local.cf http://tlec.linux.or.jp/docs/user_prefs
# echo "report_safe 0" &gt;&gt; local.cf</pre>

起動スクリプトを作成する。<br />
　　<strong>/etc/rc.d/init.d/spamd</strong>
<pre>#!/bin/bash
#
# spamassassin This script starts and stops the spamd daemon
#
# chkconfig: 345 70 30
# processname: spamd
# description: spamd is a daemon process which uses SpamAssassin to check \
#              email messages for SPAM.  It is normally called by spamc \
#              from a MDA.

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
[ -r /etc/sysconfig/network ] && . /etc/sysconfig/network

RETVAL=0
prog="spamd"

# Set default spamd configuration.
SPAMDOPTIONS="-d -c -m5 -H"
SPAMD_PID=/var/run/spamd.pid


# Tack on path to spamd if not already in PATH
SPAMD_PATH=":/usr/local/bin/"

PATH=$PATH$SPAMD_PATH
export PATH


# See how we were called.
start() {
        # Start daemon.
        echo -n $"Starting $prog: "
        daemon $NICELEVEL spamd $SPAMDOPTIONS -r $SPAMD_PID
        RETVAL=$?
        echo

        [ $RETVAL -eq 0 ] && touch /var/lock/subsys/spamd
        return $RETVAL
}

stop() {
        # Stop daemons.
        echo -n $"Stopping $prog: "
        killproc spamd

        RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/spamd
        return $RETVAL
}

case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  restart)
        stop
        start
        ;;
  condrestart)
       [ -e /var/lock/subsys/spamd ] && restart
       ;;
  status)
        status spamd
        RETVAL=$?
        ;;
  *)
        echo "Usage: $0 {start|stop|status|restart|condrestart}"
        exit 1
esac

exit $?</pre>

起動スクリプトを登録する。
<pre># vi /etc/service
spamd           783/tcp                         # SpamAssassin

# chmod 755 /etc/rc.d/init.d/spamd
# /sbin/chkconfig --add spamd
# /sbin/chkconfig --list |grep spamd
spamd           0:off   1:off   2:on    3:on    4:on    5:on    6:off</pre>

SpamAssassinを起動する。
<pre># /sbin/service spamd start
spamd を起動中:                                            [  OK  ]

# ps aux
USER       PID %CPU %MEM   VSZ  RSS TTY      STAT START   TIME COMMAND
root     13005 23.8 12.9 39548 33140 ?       Ss   13:23   0:09 /usr/local/spamassassin/bin/spamd -d -c -m5 -H -r /var/run/spamd.pid
root     13008  0.0 12.3 39548 31492 ?       S    13:23   0:00 spamd child
root     13009  0.0 12.2 39548 31372 ?       S    13:23   0:00 spamd child

# netstat -an
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      0 127.0.0.1:783               0.0.0.0:*                   LISTEN</pre>

サーバ稼働時のログ
<pre># tail /vr/log/maillog
Jan 31 20:19:35 bruna spamd[26479]: logger: removing stderr method
Jan 31 20:19:38 bruna spamd[26481]: config: failed to parse, now a plugin, skipping: ok_languages ja en
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test DIGEST_MULTIPLE has undefined dependency 'DCC_CHECK'
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test CURRWROTE has undefined dependency 'RCVD_FORGED_WROTE'
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test KEITAIFROMISP has undefined dependency 'INFOSPHERE'
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test ___TVD has undefined dependency 'TVD_FW_GRAPHIC_ID1'
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test ___TVD has undefined dependency 'TVD_FW_GRAPHIC_ID2'
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test ___TVD has undefined dependency 'TVD_FW_GRAPHIC_ID3'
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test ___TVD has undefined dependency 'TVD_FW_GRAPHIC_NAME_LONG'
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test SPANFLOAT has dependency 'FORGED_RCVD_HELO' with a zero score
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test UKGEOFORMAT2 has dependency 'FORGED_RCVD_HELO' with a zero score
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test SUBJ_SPACES_UNIQID has dependency 'SUBJ_HAS_UNIQ_ID' with a zero score
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test SORBSDUL00 has dependency 'BAYES_00' with a zero score
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test FRGDHLDIRECT has dependency 'FORGED_RCVD_HELO' with a zero score
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test ___DCN has undefined dependency 'DCC_CHECK'
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test URIBLSBL00 has dependency 'BAYES_00' with a zero score
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test SPAMCOP00 has dependency 'BAYES_00' with a zero score
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test CORE_B64 has dependency 'MIME_BASE64_NO_NAME' with a zero score
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test CORE_B64 has dependency 'MIME_BASE64_BLANKS' with a zero score
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test BASE64TXT60 has dependency 'MIME_BASE64_NO_NAME' with a zero score
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test BASE64TXT60 has dependency 'MIME_BASE64_BLANKS' with a zero score
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test FRGDMTAWROTE has undefined dependency 'RCVD_FORGED_WROTE'
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test HTMLIMG_FRGDHELO has dependency 'FORGED_RCVD_HELO' with a zero score
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test STILL_TVDFUZREF has undefined dependency 'TVD_FUZZY_FINANCE'
Jan 31 20:19:43 bruna spamd[26481]: rules: meta test RCVDSBLBLACK has undefined dependency 'URIBL_BLACK'
Jan 31 20:19:44 bruna spamd[26481]: spamd: server started on port 783/tcp (running version 3.1.7)
Jan 31 20:19:44 bruna spamd[26481]: spamd: server pid: 26481
Jan 31 20:19:44 bruna spamd[26481]: spamd: server successfully spawned child process, pid 26485
Jan 31 20:19:44 bruna spamd[26481]: spamd: server successfully spawned child process, pid 26486
Jan 31 20:19:44 bruna spamd[26481]: prefork: child states: II

# tail /var/log/boot.log
Jan 31 20:19:35 bruna spamd: spamd 起動 succeeded</pre>

MTAであるPostfixと連携する。<br />
イメージ的には「外部MTA」→「Postfix」→「SpamAssassin」→「メールスプール」→「MailDrop」となる。<br />
<a href="http://wiki.apache.org/spamassassin/IntegratedSpamdInPostfix" target="?blank">ここ</a>を参考にPostfixの設定ファイルを編集する。<br />
　　<strong>/etc/postfix/master.cf</strong>
<pre>smtp      inet  n       -       n       -       -       smtpd
  -o content_filter=spamassassin

（省略）

spamassassin  unix  -   n       n       -       -       pipe
  user=spamd argv=/usr/local/bin/spamc -e /usr/sbin/sendmail -oi -f ${sender} ${recipient}</pre>

外部からメールを受信したときのログで正常に動作しているか確認する。
<pre>Jan 29 14:09:50 bruna postfix/smtpd[14997]: connect from nz-out-0506.google.com[64.233.162.229]
Jan 29 14:09:51 bruna postfix/smtpd[14997]: 64D7A5B46C: client=nz-out-0506.google.com[64.233.162.229]
Jan 29 14:09:51 bruna postfix/cleanup[15000]: 64D7A5B46C: message-id=&lt;4c1f7c180701282109w791906a2nc5f54d72a740602c@mail.gmail.com&gt;
Jan 29 14:09:51 bruna postfix/qmgr[14926]: 64D7A5B46C: from=&lt;example@gmail.com&gt;, size=1312, nrcpt=1 (queue active)
Jan 29 14:09:51 bruna spamd[14976]: spamd: connection from bruna [127.0.0.1] at port 33012
Jan 29 14:09:51 bruna spamd[14976]: spamd: setuid to spamd succeeded
Jan 29 14:09:51 bruna spamd[14976]: spamd: creating default_prefs: /etc/mail/spamassassin/.spamassassin/user_prefs
Jan 29 14:09:51 bruna spamd[14976]: config: created user preferences file: /etc/mail/spamassassin/.spamassassin/user_prefs
Jan 29 14:09:51 bruna spamd[14976]: spamd: processing message &lt;4c1f7c180701282109w791906a2nc5f54d72a740602c@mail.gmail.com&gt; for spamd:206
Jan 29 14:09:52 bruna spamd[14976]: spamd: clean message (-1.5/13.0) for spamd:206 in 0.5 seconds, 1288 bytes.
Jan 29 14:09:52 bruna spamd[14976]: spamd: result: . -1 - ALL_TRUSTED,CONTENT_TYPE_PRESENT,ISO2022JP_BODY,ISO2022JP_CHARSET,QENCPTR2 scantime=0.5,size=1288,user=spamd,uid=206,required_score=13.0,rhost=bruna,raddr=127.0.0.1,rport=33012,mid=<4c1f7c180701282109w791906a2nc5f54d72a740602c@mail.gmail.com>,autolearn=ham
Jan 29 14:09:52 bruna postfix/pickup[14925]: 624865B46F: uid=206 from=&lt;example@gmail.com&gt;
Jan 29 14:09:52 bruna postfix/cleanup[15000]: 624865B46F: message-id=&lt;4c1f7c180701282109w791906a2nc5f54d72a740602c@mail.gmail.com&gt;
Jan 29 14:09:52 bruna postfix/pipe[15001]: 64D7A5B46C: to=&lt;testuser@kajukaju.net&gt;, relay=spamassassin, delay=1.2, delays=0.56/0.02/0/0.62, dsn=2.0.0, status=sent (delivered via spamassassin service)
Jan 29 14:09:52 bruna postfix/qmgr[14926]: 64D7A5B46C: removed
Jan 29 14:09:52 bruna postfix/qmgr[14926]: 624865B46F: from=&lt;example@gmail.com&gt;, size=1671, nrcpt=1 (queue active)
Jan 29 14:09:52 bruna spamd[14972]: prefork: child states: II</pre>

SpamAssassinのデーモンであるspamdがrootで動いている。<br />
セキュリティを確保するために専用ユーザ(spamd)で動くようにする。<br />
起動スクリプトを一部修正する。<br />
　　<strong>/etc/rc.d/init.d/spamd</strong>
<pre>SPAMDOPTIONS="-d -c -m5 -H"
　↓
SPAMDOPTIONS="-d -c -m5 -H <strong>-u spamd</strong>"</pre>

spamdユーザで起動していることを確認する。
<pre># ps auxww
root      2215  0.0  7.6 47056 39368 ?       Ss   Apr04   3:35 /usr/local/bin/spamd -d -m 5 -H -u spamd -r /var/run/spamd.pid
spamd    16945  0.1  8.6 52400 44548 ?       S    Apr06   5:06 spamd child
spamd    17775  0.0  7.3 47056 37716 ?       S    Apr08   0:00 spamd child</pre>]]></description>
         <link>http://www.kajukaju.net/centos/spamassassin.php</link>
         <guid>http://www.kajukaju.net/centos/spamassassin.php</guid>
         <category>CentOS</category>
         <pubDate>Fri, 06 Apr 2007 17:29:17 +0900</pubDate>
      </item>
            <item>
         <title>Postfix</title>
         <description><![CDATA[<strong>※netqmailの情報はこちら。 --&gt; <a href="http://www.kajukaju.net/centos/netqmail.php">netqmail</a></strong>

自宅から外部へメールを送信するのとkajukaju.netドメイン宛のメールを受信するためにSMTPサーバを導入する。

CentOSの場合は既にsendmailがインストールされているのでアンインストールする。
<pre># yum remove sendmail
=============================================================================
 Package                 Arch       Version          Repository        Size
=============================================================================
Removing:
 sendmail                i386       8.13.1-3.RHEL4.5  installed         1.2 M
Removing for dependencies:
 mdadm                   i386       1.6.0-3          installed         153 k
 redhat-lsb              i386       3.0-8.EL         installed          21 k

Transaction Summary
=============================================================================
Install      0 Package(s)
Update       0 Package(s)
Remove       3 Package(s)
Total download size: 0
Is this ok [y/N]: y
Downloading Packages:
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
  Removing  : mdadm                        ######################### [1/3]
  Removing  : sendmail                     ######################### [2/3]
  Removing  : redhat-lsb                   ######################### [3/3]

Removed: sendmail.i386 0:8.13.1-3.RHEL4.5
Dependency Removed: mdadm.i386 0:1.6.0-3 redhat-lsb.i386 0:3.0-8.EL
Complete!</pre>

Postfixを起動する専用ユーザを作成する。
<blockquote># /usr/sbin/groupadd -g 202 postfix
# /usr/sbin/groupadd -g 203 postdrop
# /usr/sbin/useradd -u 202 -g 202 -d /dev/null -s /sbin/nologin postfix</blockquote>

<a href="http://www.postfix.org/" target="_blank">Postfix</a>の公式サイトより最新のソースファイルを入手しインストールする。
<blockquote>$ wget http://mirror.postfix.jp/postfix-release/official/postfix-2.3.6.tar.gz
$ make
# make install

（省略）
install_root: [/]
tempdir: [/workdir/postfix-2.1.1] 
config_directory: [/etc/postfix] 
daemon_directory: [/usr/libexec/postfix] /usr/local/libexec/postfix
command_directory: [/usr/sbin] /usr/local/sbin
queue_directory: [/var/spool/postfix] 
sendmail_path: [/usr/sbin/sendmail] 
newaliases_path: [/usr/bin/newaliases] 
mailq_path: [/usr/bin/mailq] 
mail_owner: [postfix] 
setgid_group: [postdrop] 
html_directory: [no] 
manpage_directory: [/usr/local/man] 
readme_directory: [no] </blockquote>

Postfixの設定ファイルを編集。<br />
　　<strong>/etc/postfix/main.cf</strong>
<blockquote># Global Postfix configuration file. This file lists only a subset
# of all parameters. For the syntax, and for a complete parameter
# list, see the postconf(5) manual page (command: "man 5 postconf").
#
# For common configuration examples, see BASIC_CONFIGURATION_README
# and STANDARD_CONFIGURATION_README. To find these documents, use
# the command "postconf html_directory readme_directory", or go to
# http://www.postfix.org/.
#
# For best results, change no more than 2-3 parameters at a time,
# and test if Postfix still works after every change.

# SOFT BOUNCE
#
# The soft_bounce parameter provides a limited safety net for
# testing.  When soft_bounce is enabled, mail will remain queued that
# would otherwise bounce. This parameter disables locally-generated
# bounces, and prevents the SMTP server from rejecting mail permanently
# (by changing 5xx replies into 4xx replies). However, soft_bounce
# is no cure for address rewriting mistakes or mail routing mistakes.
#
#soft_bounce = no

# LOCAL PATHNAME INFORMATION
#
# The queue_directory specifies the location of the Postfix queue.
# This is also the root directory of Postfix daemons that run chrooted.
# See the files in examples/chroot-setup for setting up Postfix chroot
# environments on different UNIX systems.
#
queue_directory = /var/spool/postfix

# The command_directory parameter specifies the location of all
# postXXX commands.
#
command_directory = /usr/local/sbin

# The daemon_directory parameter specifies the location of all Postfix
# daemon programs (i.e. programs listed in the master.cf file). This
# directory must be owned by root.
#
daemon_directory = /usr/local/libexec/postfix

# QUEUE AND PROCESS OWNERSHIP
#
# The mail_owner parameter specifies the owner of the Postfix queue
# and of most Postfix daemon processes.  Specify the name of a user
# account THAT DOES NOT SHARE ITS USER OR GROUP ID WITH OTHER ACCOUNTS
# AND THAT OWNS NO OTHER FILES OR PROCESSES ON THE SYSTEM.  In
# particular, don't specify nobody or daemon. PLEASE USE A DEDICATED
# USER.
#
mail_owner = postfix

# The default_privs parameter specifies the default rights used by
# the local delivery agent for delivery to external file or command.
# These rights are used in the absence of a recipient user context.
# DO NOT SPECIFY A PRIVILEGED USER OR THE POSTFIX OWNER.
#
#default_privs = nobody

# INTERNET HOST AND DOMAIN NAMES
#
# The myhostname parameter specifies the internet hostname of this
# mail system. The default is to use the fully-qualified domain name
# from gethostname(). $myhostname is used as a default value for many
# other configuration parameters.
#
#myhostname = host.domain.tld
#myhostname = virtual.domain.tld
<strong>myhostname = postman.kajukaju.net</strong>

# The mydomain parameter specifies the local internet domain name.
# The default is to use $myhostname minus the first component.
# $mydomain is used as a default value for many other configuration
# parameters.
#
#mydomain = domain.tld
<strong>mydomain = kajukaju.net</strong>

# SENDING MAIL
#
# The myorigin parameter specifies the domain that locally-posted
# mail appears to come from. The default is to append $myhostname,
# which is fine for small sites.  If you run a domain with multiple
# machines, you should (1) change this to $mydomain and (2) set up
# a domain-wide alias database that aliases each user to
# user@that.users.mailhost.
#
# For the sake of consistency between sender and recipient addresses,
# myorigin also specifies the default domain name that is appended
# to recipient addresses that have no @domain part.
#
#myorigin = $myhostname
#myorigin = $mydomain
<strong>myorigin = $mydomain</strong>

# RECEIVING MAIL

# The inet_interfaces parameter specifies the network interface
# addresses that this mail system receives mail on.  By default,
# the software claims all active interfaces on the machine. The
# parameter also controls delivery of mail to user@[ip.address].
#
# See also the proxy_interfaces parameter, for network addresses that
# are forwarded to us via a proxy or network address translator.
#
# Note: you need to stop/start Postfix when this parameter changes.
#
#inet_interfaces = all
#inet_interfaces = $myhostname
#inet_interfaces = $myhostname, localhost
<strong>inet_interfaces = all</strong>

# The proxy_interfaces parameter specifies the network interface
# addresses that this mail system receives mail on by way of a
# proxy or network address translation unit. This setting extends
# the address list specified with the inet_interfaces parameter.
#
# You must specify your proxy/NAT addresses when your system is a
# backup MX host for other domains, otherwise mail delivery loops
# will happen when the primary MX host is down.
#
#proxy_interfaces =
#proxy_interfaces = 1.2.3.4

# The mydestination parameter specifies the list of domains that this
# machine considers itself the final destination for.
#
# These domains are routed to the delivery agent specified with the
# local_transport parameter setting. By default, that is the UNIX
# compatible delivery agent that lookups all recipients in /etc/passwd
# and /etc/aliases or their equivalent.
#
# The default is $myhostname + localhost.$mydomain.  On a mail domain
# gateway, you should also include $mydomain.
#
# Do not specify the names of virtual domains - those domains are
# specified elsewhere (see VIRTUAL_README).
#
# Do not specify the names of domains that this machine is backup MX
# host for. Specify those names via the relay_domains settings for
# the SMTP server, or use permit_mx_backup if you are lazy (see
# STANDARD_CONFIGURATION_README).
#
# The local machine is always the final destination for mail addressed
# to user@[the.net.work.address] of an interface that the mail system
# receives mail on (see the inet_interfaces parameter).
#
# Specify a list of host or domain names, /file/name or type:table
# patterns, separated by commas and/or whitespace. A /file/name
# pattern is replaced by its contents; a type:table is matched when
# a name matches a lookup key (the right-hand side is ignored).
# Continue long lines by starting the next line with whitespace.
#
# See also below, section "REJECTING MAIL FOR UNKNOWN LOCAL USERS".
#
#mydestination = $myhostname, localhost.$mydomain, localhost
#mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
#mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain,
#       mail.$mydomain, www.$mydomain, ftp.$mydomain
<strong>mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain</strong>

# REJECTING MAIL FOR UNKNOWN LOCAL USERS
#
# The local_recipient_maps parameter specifies optional lookup tables
# with all names or addresses of users that are local with respect
# to $mydestination, $inet_interfaces or $proxy_interfaces.
#
# If this parameter is defined, then the SMTP server will reject
# mail for unknown local users. This parameter is defined by default.
#
# To turn off local recipient checking in the SMTP server, specify
# local_recipient_maps = (i.e. empty).
#
# The default setting assumes that you use the default Postfix local
# delivery agent for local delivery. You need to update the
# local_recipient_maps setting if:
#
# - You define $mydestination domain recipients in files other than
#   /etc/passwd, /etc/aliases, or the $virtual_alias_maps files.
#   For example, you define $mydestination domain recipients in
#   the $virtual_mailbox_maps files.
#
# - You redefine the local delivery agent in master.cf.
#
# - You redefine the "local_transport" setting in main.cf.
#
# - You use the "luser_relay", "mailbox_transport", or "fallback_transport"
#   feature of the Postfix local delivery agent (see local(8)).
#
# Details are described in the LOCAL_RECIPIENT_README file.
#
# Beware: if the Postfix SMTP server runs chrooted, you probably have
# to access the passwd file via the proxymap service, in order to
# overcome chroot restrictions. The alternative, having a copy of
# the system passwd file in the chroot jail is just not practical.
#
# The right-hand side of the lookup tables is conveniently ignored.
# In the left-hand side, specify a bare username, an @domain.tld
# wild-card, or specify a user@domain.tld address.
#
#local_recipient_maps = unix:passwd.byname $alias_maps
#local_recipient_maps = proxy:unix:passwd.byname $alias_maps
#local_recipient_maps =

# The unknown_local_recipient_reject_code specifies the SMTP server
# response code when a recipient domain matches $mydestination or
# ${proxy,inet}_interfaces, while $local_recipient_maps is non-empty
# and the recipient address or address local-part is not found.
#
# The default setting is 550 (reject mail) but it is safer to start
# with 450 (try again later) until you are certain that your
# local_recipient_maps settings are OK.
#
unknown_local_recipient_reject_code = 550

# TRUST AND RELAY CONTROL

# The mynetworks parameter specifies the list of "trusted" SMTP
# clients that have more privileges than "strangers".
#
# In particular, "trusted" SMTP clients are allowed to relay mail
# through Postfix.  See the smtpd_recipient_restrictions parameter
# in postconf(5).
#
# You can specify the list of "trusted" network addresses by hand
# or you can let Postfix do it for you (which is the default).
#
# By default (mynetworks_style = subnet), Postfix "trusts" SMTP
# clients in the same IP subnetworks as the local machine.
# On Linux, this does works correctly only with interfaces specified
# with the "ifconfig" command.
#
# Specify "mynetworks_style = class" when Postfix should "trust" SMTP
# clients in the same IP class A/B/C networks as the local machine.
# Don't do this with a dialup site - it would cause Postfix to "trust"
# your entire provider's network.  Instead, specify an explicit
# mynetworks list by hand, as described below.
#
# Specify "mynetworks_style = host" when Postfix should "trust"
# only the local machine.
#
#mynetworks_style = class
#mynetworks_style = subnet
#mynetworks_style = host

# Alternatively, you can specify the mynetworks list by hand, in
# which case Postfix ignores the mynetworks_style setting.
#
# Specify an explicit list of network/netmask patterns, where the
# mask specifies the number of bits in the network part of a host
# address.
#
# You can also specify the absolute pathname of a pattern file instead
# of listing the patterns here. Specify type:table for table-based lookups
# (the value on the table right-hand side is not used).
#
#mynetworks = 168.100.189.0/28, 127.0.0.0/8
#mynetworks = $config_directory/mynetworks
#mynetworks = hash:/etc/postfix/network_table
<strong>mynetworks = 10.33.77.0/24, 127.0.0.0/8</strong>

# The relay_domains parameter restricts what destinations this system will
# relay mail to.  See the smtpd_recipient_restrictions description in
# postconf(5) for detailed information.
#
# By default, Postfix relays mail
# - from "trusted" clients (IP address matches $mynetworks) to any destination,
# - from "untrusted" clients to destinations that match $relay_domains or
#   subdomains thereof, except addresses with sender-specified routing.
# The default relay_domains value is $mydestination.
#
# In addition to the above, the Postfix SMTP server by default accepts mail
# that Postfix is final destination for:
# - destinations that match $inet_interfaces or $proxy_interfaces,
# - destinations that match $mydestination
# - destinations that match $virtual_alias_domains,
# - destinations that match $virtual_mailbox_domains.
# These destinations do not need to be listed in $relay_domains.
#
# Specify a list of hosts or domains, /file/name patterns or type:name
# lookup tables, separated by commas and/or whitespace.  Continue
# long lines by starting the next line with whitespace. A file name
# is replaced by its contents; a type:name table is matched when a
# (parent) domain appears as lookup key.
#
# NOTE: Postfix will not automatically forward mail for domains that
# list this system as their primary or backup MX host. See the
# permit_mx_backup restriction description in postconf(5).
#
#relay_domains = $mydestination

# INTERNET OR INTRANET

# The relayhost parameter specifies the default host to send mail to
# when no entry is matched in the optional transport(5) table. When
# no relayhost is given, mail is routed directly to the destination.
#
# On an intranet, specify the organizational domain name. If your
# internal DNS uses no MX records, specify the name of the intranet
# gateway host instead.
#
# In the case of SMTP, specify a domain, host, host:port, [host]:port,
# [address] or [address]:port; the form [host] turns off MX lookups.
#
# If you're connected via UUCP, see also the default_transport parameter.
#
#relayhost = $mydomain
#relayhost = [gateway.my.domain]
#relayhost = [mailserver.isp.tld]
#relayhost = uucphost
#relayhost = [an.ip.add.ress]

# REJECTING UNKNOWN RELAY USERS
#
# The relay_recipient_maps parameter specifies optional lookup tables
# with all addresses in the domains that match $relay_domains.
#
# If this parameter is defined, then the SMTP server will reject
# mail for unknown relay users. This feature is off by default.
#
# The right-hand side of the lookup tables is conveniently ignored.
# In the left-hand side, specify an @domain.tld wild-card, or specify
# a user@domain.tld address.
#
#relay_recipient_maps = hash:/etc/postfix/relay_recipients

# INPUT RATE CONTROL
#
# The in_flow_delay configuration parameter implements mail input
# flow control. This feature is turned on by default, although it
# still needs further development (it's disabled on SCO UNIX due
# to an SCO bug).
#
# A Postfix process will pause for $in_flow_delay seconds before
# accepting a new message, when the message arrival rate exceeds the
# message delivery rate. With the default 100 SMTP server process
# limit, this limits the mail inflow to 100 messages a second more
# than the number of messages delivered per second.
#
# Specify 0 to disable the feature. Valid delays are 0..10.
#
#in_flow_delay = 1s

# ADDRESS REWRITING
#
# The ADDRESS_REWRITING_README document gives information about
# address masquerading or other forms of address rewriting including
# username->Firstname.Lastname mapping.

# ADDRESS REDIRECTION (VIRTUAL DOMAIN)
#
# The VIRTUAL_README document gives information about the many forms
# of domain hosting that Postfix supports.

# "USER HAS MOVED" BOUNCE MESSAGES
#
# See the discussion in the ADDRESS_REWRITING_README document.

# TRANSPORT MAP
#
# See the discussion in the ADDRESS_REWRITING_README document.
<strong>transport_maps = hash:/etc/postfix/transport</strong>

# ALIAS DATABASE
#
# The alias_maps parameter specifies the list of alias databases used
# by the local delivery agent. The default list is system dependent.
#
# On systems with NIS, the default is to search the local alias
# database, then the NIS alias database. See aliases(5) for syntax
# details.
#
# If you change the alias database, run "postalias /etc/aliases" (or
# wherever your system stores the mail alias file), or simply run
# "newaliases" to build the necessary DBM or DB file.
#
# It will take a minute or so before changes become visible.  Use
# "postfix reload" to eliminate the delay.
#
#alias_maps = dbm:/etc/aliases
#alias_maps = hash:/etc/aliases
#alias_maps = hash:/etc/aliases, nis:mail.aliases
#alias_maps = netinfo:/aliases
<strong>alias_maps = hash:/etc/aliases</strong>

# The alias_database parameter specifies the alias database(s) that
# are built with "newaliases" or "sendmail -bi".  This is a separate
# configuration parameter, because alias_maps (see above) may specify
# tables that are not necessarily all under control by Postfix.
#
#alias_database = dbm:/etc/aliases
#alias_database = dbm:/etc/mail/aliases
#alias_database = hash:/etc/aliases
#alias_database = hash:/etc/aliases, hash:/opt/majordomo/aliases
<strong>alias_database = hash:/etc/aliases</strong>

# ADDRESS EXTENSIONS (e.g., user+foo)
#
# The recipient_delimiter parameter specifies the separator between
# user names and address extensions (user+foo). See canonical(5),
# local(8), relocated(5) and virtual(5) for the effects this has on
# aliases, canonical, virtual, relocated and .forward file lookups.
# Basically, the software tries user+foo and .forward+foo before
# trying user and .forward.
#
#recipient_delimiter = +

# DELIVERY TO MAILBOX
#
# The home_mailbox parameter specifies the optional pathname of a
# mailbox file relative to a user's home directory. The default
# mailbox file is /var/spool/mail/user or /var/mail/user.  Specify
# "Maildir/" for qmail-style delivery (the / is required).
#
#home_mailbox = Mailbox
#home_mailbox = Maildir/
<strong>home_mailbox = Maildir/</strong>

# The mail_spool_directory parameter specifies the directory where
# UNIX-style mailboxes are kept. The default setting depends on the
# system type.
#
#mail_spool_directory = /var/mail
<strong>mail_spool_directory = /var/spool/mail</strong>

# The mailbox_command parameter specifies the optional external
# command to use instead of mailbox delivery. The command is run as
# the recipient with proper HOME, SHELL and LOGNAME environment settings.
# Exception:  delivery for root is done as $default_user.
#
# Other environment variables of interest: USER (recipient username),
# EXTENSION (address extension), DOMAIN (domain part of address),
# and LOCAL (the address localpart).
#
# Unlike other Postfix configuration parameters, the mailbox_command
# parameter is not subjected to $parameter substitutions. This is to
# make it easier to specify shell syntax (see example below).
#
# Avoid shell meta characters because they will force Postfix to run
# an expensive shell process. Procmail alone is expensive enough.
#
# IF YOU USE THIS TO DELIVER MAIL SYSTEM-WIDE, YOU MUST SET UP AN
# ALIAS THAT FORWARDS MAIL FOR ROOT TO A REAL USER.
#
#mailbox_command = /some/where/procmail
#mailbox_command = /some/where/procmail -a "$EXTENSION"

# The mailbox_transport specifies the optional transport in master.cf
# to use after processing aliases and .forward files. This parameter
# has precedence over the mailbox_command, fallback_transport and
# luser_relay parameters.
#
# Specify a string of the form transport:nexthop, where transport is
# the name of a mail delivery transport defined in master.cf.  The
# :nexthop part is optional. For more details see the sample transport
# configuration file.
#
# NOTE: if you use this feature for accounts not in the UNIX password
# file, then you must update the "local_recipient_maps" setting in
# the main.cf file, otherwise the SMTP server will reject mail for
# non-UNIX accounts with "User unknown in local recipient table".
#
#mailbox_transport = lmtp:unix:/file/name
#mailbox_transport = cyrus

# The fallback_transport specifies the optional transport in master.cf
# to use for recipients that are not found in the UNIX passwd database.
# This parameter has precedence over the luser_relay parameter.
#
# Specify a string of the form transport:nexthop, where transport is
# the name of a mail delivery transport defined in master.cf.  The
# :nexthop part is optional. For more details see the sample transport
# configuration file.
#
# NOTE: if you use this feature for accounts not in the UNIX password
# file, then you must update the "local_recipient_maps" setting in
# the main.cf file, otherwise the SMTP server will reject mail for
# non-UNIX accounts with "User unknown in local recipient table".
#
#fallback_transport = lmtp:unix:/file/name
#fallback_transport = cyrus
#fallback_transport =

# The luser_relay parameter specifies an optional destination address
# for unknown recipients.  By default, mail for unknown@$mydestination,
# unknown@[$inet_interfaces] or unknown@[$proxy_interfaces] is returned
# as undeliverable.
#
# The following expansions are done on luser_relay: $user (recipient
# username), $shell (recipient shell), $home (recipient home directory),
# $recipient (full recipient address), $extension (recipient address
# extension), $domain (recipient domain), $local (entire recipient
# localpart), $recipient_delimiter. Specify ${name?value} or
# ${name:value} to expand value only when $name does (does not) exist.
#
# luser_relay works only for the default Postfix local delivery agent.
#
# NOTE: if you use this feature for accounts not in the UNIX password
# file, then you must specify "local_recipient_maps =" (i.e. empty) in
# the main.cf file, otherwise the SMTP server will reject mail for
# non-UNIX accounts with "User unknown in local recipient table".
#
#luser_relay = $user@other.host
#luser_relay = $local@other.host
#luser_relay = admin+$local

# JUNK MAIL CONTROLS
#
# The controls listed here are only a very small subset. The file
# SMTPD_ACCESS_README provides an overview.

# The header_checks parameter specifies an optional table with patterns
# that each logical message header is matched against, including
# headers that span multiple physical lines.
#
# By default, these patterns also apply to MIME headers and to the
# headers of attached messages. With older Postfix versions, MIME and
# attached message headers were treated as body text.
#
# For details, see "man header_checks".
#
#header_checks = regexp:/etc/postfix/header_checks

# FAST ETRN SERVICE
#
# Postfix maintains per-destination logfiles with information about
# deferred mail, so that mail can be flushed quickly with the SMTP
# "ETRN domain.tld" command, or by executing "sendmail -qRdomain.tld".
# See the ETRN_README document for a detailed description.
#
# The fast_flush_domains parameter controls what destinations are
# eligible for this service. By default, they are all domains that
# this server is willing to relay mail to.
#
#fast_flush_domains = $relay_domains

# SHOW SOFTWARE VERSION OR NOT
#
# The smtpd_banner parameter specifies the text that follows the 220
# code in the SMTP server's greeting banner. Some people like to see
# the mail version advertised. By default, Postfix shows no version.
#
# You MUST specify $myhostname at the start of the text. That is an
# RFC requirement. Postfix itself does not care.
#
#smtpd_banner = $myhostname ESMTP $mail_name
#smtpd_banner = $myhostname ESMTP $mail_name ($mail_version)
<strong>smtpd_banner = $myhostname ESMTP $mail_name ($mail_version)</strong>

# PARALLEL DELIVERY TO THE SAME DESTINATION
#
# How many parallel deliveries to the same user or domain? With local
# delivery, it does not make sense to do massively parallel delivery
# to the same user, because mailbox updates must happen sequentially,
# and expensive pipelines in .forward files can cause disasters when
# too many are run at the same time. With SMTP deliveries, 10
# simultaneous connections to the same domain could be sufficient to
# raise eyebrows.
#
# Each message delivery transport has its XXX_destination_concurrency_limit
# parameter.  The default is $default_destination_concurrency_limit for
# most delivery transports. For the local delivery agent the default is 2.

#local_destination_concurrency_limit = 2
#default_destination_concurrency_limit = 20

# DEBUGGING CONTROL
#
# The debug_peer_level parameter specifies the increment in verbose
# logging level when an SMTP client or server host name or address
# matches a pattern in the debug_peer_list parameter.
#
debug_peer_level = 2

# The debug_peer_list parameter specifies an optional list of domain
# or network patterns, /file/name patterns or type:name tables. When
# an SMTP client or server host name or address matches a pattern,
# increase the verbose logging level by the amount specified in the
# debug_peer_level parameter.
#
#debug_peer_list = 127.0.0.1
#debug_peer_list = some.domain

# The debugger_command specifies the external command that is executed
# when a Postfix daemon program is run with the -D option.
#
# Use "command .. & sleep 5" so that the debugger can attach before
# the process marches on. If you use an X-based debugger, be sure to
# set up your XAUTHORITY environment variable before starting Postfix.
#
debugger_command =
         PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin
         xxgdb $daemon_directory/$process_name $process_id & sleep 5

# If you can't use X, use this to capture the call stack when a
# daemon crashes. The result is in a file in the configuration
# directory, and is named after the process name and the process ID.
#
# debugger_command =
#       PATH=/bin:/usr/bin:/usr/local/bin; export PATH; (echo cont;
#       echo where) | gdb $daemon_directory/$process_name $process_id 2&gt;&amp;1
#       &gt;$config_directory/$process_name.$process_id.log &amp; sleep 5
#
# Another possibility is to run gdb under a detached screen session.
# To attach to the screen sesssion, su root and run "screen -r
# &lt;id_string&gt;" where &lt;id_string&gt; uniquely matches one of the detached
# sessions (from "screen -list").
#
# debugger_command =
#       PATH=/bin:/usr/bin:/sbin:/usr/sbin; export PATH; screen
#       -dmS $process_name gdb $daemon_directory/$process_name
#       $process_id & sleep 1

# INSTALL-TIME CONFIGURATION INFORMATION
#
# The following parameters are used when installing a new Postfix version.
#
# sendmail_path: The full pathname of the Postfix sendmail command.
# This is the Sendmail-compatible mail posting interface.
#
sendmail_path = /usr/sbin/sendmail

# newaliases_path: The full pathname of the Postfix newaliases command.
# This is the Sendmail-compatible command to build alias databases.
#
newaliases_path = /usr/bin/newaliases

# mailq_path: The full pathname of the Postfix mailq command.  This
# is the Sendmail-compatible mail queue listing command.
#
mailq_path = /usr/bin/mailq

# setgid_group: The group for mail submission and queue management
# commands.  This must be a group name with a numerical group ID that
# is not shared with other accounts, not even with the Postfix account.
#
setgid_group = postdrop

# html_directory: The location of the Postfix HTML documentation.
#
html_directory = no

# manpage_directory: The location of the Postfix on-line manual pages.
#
manpage_directory = /usr/local/man

# sample_directory: The location of the Postfix sample configuration files.
# This parameter is obsolete as of Postfix 2.1.
#
sample_directory = /etc/postfix

# readme_directory: The location of the Postfix README files.
#
readme_directory = no</blockquote>

起動スクリプトを作成する。<br />
　　<strong>/etc/rc.d/init.d/postfix</strong>
<pre>#!/bin/bash
#
# postfix         Postfix Mail Transfer Agent
#
# chkconfig: 345 80 30
# description: Postfix is a Mail Transport Agent, which is the program
#              that moves mail from one machine to another.
# pidfile: /var/spool/postfix/pid/master.pid
# config: /etc/postfix/main.cf
# config: /etc/postfix/master.cf

# Source Redhat function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
[ -r /etc/sysconfig/network ] &amp;&amp; . /etc/sysconfig/network

RETVAL=0
prog="postfix"

# Tack on path to postfix if not already in PATH
POSTFIX_PATH=":/usr/local/sbin"

PATH=$PATH$POSTFIX_PATH
export PATH


start() {
        # Start daemons.
        echo -n $"Starting $prog: "
        /usr/local/sbin/postfix start 2&gt;/dev/null 1&gt;&amp;2 &amp;&amp; success || failure
        RETVAL=$?;

        [ $RETVAL -eq 0 ] &amp;&amp; touch /var/lock/subsys/postfix
        echo
        return $RETVAL
}

stop() {
        # Stop daemons.
        echo -n $"Stopping $prog: "
        /usr/local/sbin/postfix stop 2&gt;/dev/null 1&gt;&amp;2 &amp;&amp; success || failure
        RETVAL=$?

        [ $RETVAL -eq 0 ] &amp;&amp; rm -f /var/lock/subsys/postfix
        echo
        return $RETVAL
}

reload() {
        echo -n "Reloading postfix: "
        /usr/local/sbin/postfix reload 2&gt;/dev/null 1&gt;&amp;2 &amp;&amp; success || failure
        RETVAL=$?
        echo
        return $RETVAL
}

abort() {
        /usr/local/sbin/postfix abort 2&gt;/dev/null 1&gt;&amp;2 &amp;&amp; success || failure
        return $?
}

flush() {
        /usr/local/sbin/postfix flush 2&gt;/dev/null 1&gt;&2 &amp;&amp; success || failure
        return $?
}

check() {
        /usr/local/sbin/postfix check 2&gt;/dev/null 1&gt;&2 &amp;&amp; success || failure
        return $?
}

# See how we were called.
case "$1" in
        start)
                start
                ;;
        stop)
                stop
                ;;
        status)
                status named
                RETVAL=$?
                ;;
        restart)
                stop
                start
                RETVAL=$?
                ;;
        reload)
                reload
                ;;
        abort)
               abort
               ;;
        flush)
               flush
               ;;
        check)
               check
               ;;
        *)
                echo $"Usage: $0 {start|stop|status|restart|reload|abort|flush|check}"
                exit 1
esac

exit $?</pre>

起動スクリプトを登録する。
<pre># chmod 755 /etc/rc.d/init.d/postfix
# /sbin/chkconfig --add postfix
# /sbin/chkconfig --list |grep postfix
postfix         0:off   1:off   2:off   3:on    4:on    5:on    6:off</pre>

Postfixを起動する。
<pre># /sbin/service postfix start
postfix を起動中:                                          [  OK  ]

# ps auxww
USER       PID %CPU %MEM   VSZ  RSS TTY      STAT START   TIME COMMAND
root      9632  0.0  0.3  3556 1016 ?        Ss   15:40   0:00 /usr/local/libexec/postfix/master
postfix   9635  0.0  0.3  3512  960 ?        S    15:40   0:00 pickup -l -t fifo -u
postfix   9636  0.0  0.3  3312  992 ?        S    15:40   0:00 qmgr -l -t fifo -u

# netstat -an
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      0 0.0.0.0:25                  0.0.0.0:*                   LISTEN</pre>

サーバ稼働時のログ
<blockquote># tail -f /var/log/maillog
Jan 27 15:40:49 bruna postfix/postfix-script: starting the Postfix mail system
Jan 27 15:40:49 bruna postfix/master[9632]: daemon started -- version 2.3.6, configuration /etc/postfix

# tail -f /var/log/boot.log
Jan 27 15:40:49 bruna postfix:  succeeded</blockquote>

メールの送信テストを行い問題がないことを確認する。
　・内部→内部
　・内部→外部
　・外部→内部
<strong>　・外部→外部　※送信できてはいけない</strong>

メール送信時のログ
<blockquote># tail /var/log/mail.log
Jan 27 15:45:37 bruna postfix/smtpd[9778]: connect from bruna[127.0.0.1]
Jan 27 15:46:12 bruna postfix/smtpd[9778]: C65CC5B1E6: client=bruna[127.0.0.1]
Jan 27 15:46:18 bruna postfix/cleanup[9781]: C65CC5B1E6: message-id=<20070127064612.C65CC5B1E6@postman.kajukaju.net>
Jan 27 15:46:18 bruna postfix/qmgr[9770]: C65CC5B1E6: from=&lt;sample@kajukaju.net&gt;, size=344, nrcpt=1 (queue active)
Jan 27 15:46:21 bruna postfix/smtp[9782]: C65CC5B1E6: to=&lt;abuse@gmail.com&gt;, relay=gmail-smtp-in.l.google.com[64.233.163.114]:25, delay=21, delays=18/0.03/0.88/1.6, dsn=2.0.0, status=sent (250 2.0.0 OK 1169880378 36si3488318nzk)
Jan 27 15:46:21 bruna postfix/qmgr[9770]: C65CC5B1E6: removed
Jan 27 15:46:31 bruna postfix/smtpd[9778]: disconnect from bruna[127.0.0.1]</blockquote>

管理者アカウントに対してエイリアスを設定する。<br />
　　<strong>/etc/aliases</strong>
<pre># Basic system aliases -- these MUST be present.
root:           user1,user2
mailer-daemon:  user1,user2
postmaster:     user1,user2</pre>

ファイルのをPostfixが読み込める形式に変換する。
<blockquote># /usr/local/sbin/postalias /etc/aliases</blockquote>

Postixに接続してきた際のバナー情報を秘匿する。<br />
　　<strong>/etc/postfix/main.cf</strong>
<blockquote>#smtpd_banner = $myhostname ESMTP $mail_name ($mail_version)
smtpd_banner = $myhostname ESMTP $mail_name</blockquote>

Postfixを再起動すると有効になる。
<blockquote>○設定前
# telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.localdomain (127.0.0.1).
Escape character is '^]'.
<strong>220 postman.kajukaju.net ESMTP Postfix (2.3.6)</strong>

○設定後
# telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.localdomain (127.0.0.1).
Escape character is '^]'.
<strong>220 postman.kajukaju.net ESMTP Postfix</strong></blockquote>]]></description>
         <link>http://www.kajukaju.net/centos/postfix_1.php</link>
         <guid>http://www.kajukaju.net/centos/postfix_1.php</guid>
         <category>CentOS</category>
         <pubDate>Wed, 07 Mar 2007 19:45:24 +0900</pubDate>
      </item>
            <item>
         <title>syslog-ng</title>
         <description><![CDATA[OSやアプリケーションが出力するログを管理するシスログサーバとしてOS標準のsyslogdではなくsyslog-ngを導入する。
syslog-ngの特長は下記の通り。
　・TCPポートを使用したLISTENが可能
　・特定キーワードに合致した場合にプログラムを実行することが可能
　・ユーザ権限での動作が可能

以前はsyslog-ng-1.6.6をインストールしていたが、2.0系のバージョンがリリースされているのでバージョンアップすることにする。<br />
1.6系のsyslog-ngはlibolが必要だったが2.0系ではGLib2.0とEventLogが必要になる。<br />
CentOSではGLib2.0がRPMであるので利用する。
<blockquote># rpm -qa |grep glib2
glib2-2.4.7-1
glib2-devel-2.4.7-1</blockquote>

EventLogは<a href="http://www.balabit.com/products/syslog_ng/" target="_blank">syslog-ngの公式サイト</a>で入手可能。
<blockquote>$ wget http://www.balabit.com/downloads/syslog-ng/2.0/src/eventlog-0.2.5.tar.gz
$ tar xvzf eventlog-0.2.5.tar.gz
$ cd eventlog-0.2.5
$ ./configure
$ make
# make install</blockquote>

準備ができたところでメインのsyslog-ngをインストールする。<br />
インストール時にeventlog.pcを見つけられないためエラーが発生してしまった。<br />
PKG_CONFIG_PATHを設定することで対応可能。<br />
./configure時に以下エラーが出る。
<blockquote>checking for pkg-config... /usr/bin/pkg-config
checking pkg-config is at least version 0.9.0... yes
checking for GLIB... yes
checking for EVTLOG... Package eventlog was not found in the pkg-config search path.
Perhaps you should add the directory containing `eventlog.pc'
to the PKG_CONFIG_PATH environment variable
No package 'eventlog' found
configure: error: Cannot find eventlog version &gt;= 0.2: is pkg-config in path?</blockquote>

PKG_CONFIG_PATHを設定してインストール。
<blockquote>$ wget http://www.balabit.com/downloads/syslog-ng/2.0/src/syslog-ng-2.0.2.tar.gz
$ tar xvzf syslog-ng-2.0.2.tar.gz
$ cd syslog-ng-2.0.2
<strong>$ PKG_CONFIG_PATH=/usr/local/lib/pkgconfig
$ export PKG_CONFIG_PATH</strong>
$ ./configure --sysconfdir=/etc
$ make
# make install</blockquote>

設定ファイルを作成する。<br />
ここは運用を見ながら随時変更しているので参照する場合は自サイトに適した形に適宜変更することをお奨めする。
<pre>----------------------------------------------------------------------------------------------------
# syslog-ng configuration file.
#
# This should behave pretty much like the original syslog on RedHat. But
# it could be configured a lot smarter.
#
# See syslog-ng(8) and syslog-ng.conf(5) for more information.
#
# 20000925 gb@sysfive.com
#
# Updated by Frank Crawford (&lt;Frank.Crawford@ac3.com.au&gt;) - 10 Aug 2002
#       - for Red Hat 7.3
#       - totally do away with klogd
#       - add message "kernel:" as is done with klogd.
#
# Updated by Frank Crawford (&lt;Frank.Crawford@ac3.com.au&gt;) - 22 Aug 2002
#       - use the log_prefix option as per Balazs Scheidler's email
#

options { sync (0);
          time_reopen (10);
          log_fifo_size (1000);
          long_hostnames (off);
          use_dns (yes);
          use_fqdn (no);
          create_dirs (no);
          keep_hostname (yes);
          stats(86400);
          dir_perm(0755);
          perm(0644);
        };

#
# At around 1999 some distributions have changed from using SOCK_STREAM
# to SOCK_DGRAM sockets, see these posts about the issue:
#
# http://www.security-express.com/archives/bugtraq/1999-q4/0071.html
# http://marc.theaimsgroup.com/?l=sysklogd&m=96989685607952&w=2
#
# libc and syslog clients generally automatically detect the socket type,
# so you are free to decide which of unix-stream or unix-dgram you want to use.
#

#-------------------
# source
#-------------------
source int   { file ("/proc/kmsg" log_prefix("kernel: ")); unix-stream ("/dev/log"); internal(); };
source ext   { udp(); };



#-------------------
# destination
#-------------------
destination alluser     { usertty("*"); };
#destination auth       { file("/var/log/auth.log.$YEAR$MONTH"); };
#destination authpriv   { file("/var/log/authpriv.log.$YEAR$MONTH"); };
#destination lpr        { file("/var/log/lpr.log.$YEAR$MONTH"); };
destination boot        { file("/var/log/boot.log.$YEAR$MONTH"); };
destination console     { file("/dev/console"); };
destination cron        { file("/var/log/cron.log.$YEAR$MONTH"); };
destination daemon      { file("/var/log/daemon.log.$YEAR$MONTH"); };
destination kern        { file("/var/log/kernel.log.$YEAR$MONTH"); };
destination local0      { file("/var/log/local0.log.$YEAR$MONTH"); };
destination local1      { file("/var/log/local1.log.$YEAR$MONTH"); };
destination local2      { file("/var/log/local2.log.$YEAR$MONTH"); };
destination local3      { file("/var/log/local3.log.$YEAR$MONTH"); };
destination local4      { file("/var/log/local4.log.$YEAR$MONTH"); };
destination local5      { file("/var/log/local5.log.$YEAR$MONTH"); };
destination local6      { file("/var/log/local6.log.$YEAR$MONTH"); };
destination local7      { file("/var/log/local7.log.$YEAR$MONTH"); };
destination mail        { file("/var/log/mail.log.$YEAR$MONTH"); };
destination messages    { file("/var/log/messages.$YEAR$MONTH"); };
destination named       { file("/var/log/named.log.$YEAR$MONTH"); };
destination news        { file("/var/log/news.log.$YEAR$MONTH"); };
destination router      { file("/var/log/router.log.$YEAR$MONTH"); };
destination secure      { file("/var/log/secure.$YEAR$MONTH"); };
destination snmp        { file("/var/log/snmp.log.$YEAR$MONTH"); };
destination sshd        { file("/var/log/ssh.log.$YEAR$MONTH"); };
destination syslog      { file("/var/log/syslog.log.$YEAR$MONTH"); };
destination user        { file("/var/log/user.log.$YEAR$MONTH"); };

#-------------------
# filter
#-------------------
#filter f_auth          { facility(auth); };
#filter f_authpriv      { facility(authpriv); };
#filter f_lpr           { facility(lpr); };
filter f_console        { level(warn..emerg) and facility(kern); };
filter f_cron           { facility(cron); };
filter f_daemon         { facility(daemon); };
filter f_emergency      { level(emerg); };
filter f_kern           { facility(kern); };
filter f_local0         { facility(local0); };
filter f_local1         { facility(local1); };
filter f_local2         { facility(local2); };
filter f_local3         { facility(local3); };
filter f_local4         { facility(local4); };
filter f_local5         { facility(local5); };
filter f_local6         { facility(local6); };
filter f_local7         { facility(local7); };
filter f_mail           { facility(mail); };
filter f_messages       { level(info..warn) and not facility(auth,authpriv,cron,lpr,mail,news,local1,local2); };
filter f_named          { program("named"); };
filter f_news           { facility(news); };
filter f_secure         { facility(auth,authpriv); };
filter f_sshd           { program("sshd"); };
filter f_syslog         { program("syslog-ng"); };
filter f_user           { facility(user); };

#-------------------
# log
#-------------------
#log { source(int); filter(f_auth);       destination(auth); };
#log { source(int); filter(f_authpriv);   destination(authpriv); };
#log { source(int); filter(f_lpr);        destination(lpr); };
log  { source(int); filter(f_console);    destination(console); };
log  { source(int); filter(f_cron);       destination(cron); };
log  { source(int); filter(f_daemon);     destination(daemon); };
log  { source(int); filter(f_emergency);  destination(alluser); };
log  { source(int); filter(f_kern);       destination(kern); };
log  { source(int); filter(f_local0);     destination(local0); };
log  { source(int); filter(f_local1);     destination(snmp); };
log  { source(int); filter(f_local2);     destination(local2); };
log  { source(int); filter(f_local3);     destination(local3); };
log  { source(int); filter(f_local4);     destination(local4); };
log  { source(int); filter(f_local5);     destination(local5); };
log  { source(int); filter(f_local6);     destination(local6); };
log  { source(int); filter(f_local7);     destination(boot); };
log  { source(int); filter(f_mail);       destination(mail); };
log  { source(int); filter(f_messages);   destination(messages); };
log  { source(int); filter(f_named);      destination(named); };
log  { source(int); filter(f_news);       destination(news); };
log  { source(int); filter(f_secure);     destination(secure); };
log  { source(int); filter(f_sshd);       destination(sshd); };
log  { source(int); filter(f_syslog);     destination(syslog); };
log  { source(int); filter(f_user);       destination(user); };

log  { source(ext); filter(f_local4);     destination(router); };</pre>

設定ファイルに誤りがないか確認する。<br />
誤りがある場合は下記のように該当する行数が出る。（ちなみにこれは175行目がおかしい場合）
<blockquote># /usr/local/sbin/syslog-ng -f /etc/syslog-ng.conf -s
syntax error at 175</blockquote>

ソースに含まれているサンプルを基に起動スクリプトを作成する。
<blockquote># cp $SOURCE/syslog-ng-1.6.6/contrib/init.d.RedHat-7.3 /etc/rc.d/init.d/syslog-ng</blockquote>

　　<strong>/etc/rc.d/init.d/syslog-ng</strong>
<pre>################################################################################
#
# Program: syslog-ng init script for Red Hat
#
################################################################################
# the following information is for use by chkconfig
# if you are want to manage this through chkconfig (as you should), you must
# first must add syslog-ng to chkconfig's list of startup scripts it
# manages by typing:
#
#               chkconfig --add syslog-ng
#
# DO NOT CHANGE THESE LINES (unless you know what you are doing)
# chkconfig: 2345 12 88
# description: syslog-ng is the next generation of the syslog daemon. \
# syslog-ng gives you the flexibility of logging not only by facility and \
# severity, but also by host, message content, date, etc. it can also replace \
# klogd's function of logging kernel messages
#
# This following block of lines is correct, do not change! (for more info, see
# http://www.linuxbase.org/spec/refspecs/LSB_1.1.0/gLSB/facilname.html)
### BEGIN INIT INFO
# Provides: $syslog
### END INIT INFO
################################################################################
#
#  This is an init script for syslog-ng on the Linux platform.
#
#  It totally relies on the Redhat function library and works the same
#  way as other typical Redhat init scripts.
#
#
# Platforms (tested): Linux (Redhat 7.3)
#
#
# Author: Gregor Binder &lt;gbinder@sysfive.com&gt;
# Changed: October 10, 2000
#
# Last Changed: September 27, 2002
# Updated by: Diane Davidowicz
#       changes: Brought the start script up to snuff as far as compliance
#                with managing the startup script through chkconfig;
#                added PATH variable ability to hook in path to syslog-ng (if
#                its necessary); converted init script format to the
#                standard init script format in Red Hat (7.3 to be exact)
#                including using the /etc/sysconfig/syslog-ng file to
#                managed the arguments to syslog-ng without changing this
#                script, and disabled klogd but noted where and under what
#                conditions it should be enabled. HAPPY LOGGING.
#
#     Copyright (c) 2000 by sysfive.com GmbH, All rights reserved.
#
#
################################################################################
#
# configuration
#

#
# Source Redhat function library.
. /etc/rc.d/init.d/functions


# Source networking configuration.
[ -r /etc/sysconfig/network ] &amp;&amp; . /etc/sysconfig/network

RETVAL=0
prog="syslog-ng"


# /etc/sysconfig/ is the standard way to pull in options for a daemon to use.
# Source config
if [ -f /etc/sysconfig/syslog-ng ] ; then
        . /etc/sysconfig/syslog-ng
else
        SYSLOGNG_OPTIONS=
        KLOGD_OPTIONS=
fi


# Tack on path to syslog-ng if not already in PATH
SYSLOGNG_PATH=":/usr/local/sbin"

PATH=$PATH$SYSLOGNG_PATH
export PATH


umask 077
ulimit -c 0

# See how we were called.
start() {
        # Start daemons.
        echo -n $"Starting $prog: "
        daemon syslog-ng $SYSLOGNG_OPTIONS
        RETVAL=$?

        # syslog-ng can handle kernel messages. If you do this, don't
        # run klogd. Consult the following FAQ question to find out why.
        #
        # http://www.campin.net/syslog-ng/faq.html#klogd
        #
        # If you still prefer to run klogd without syslog-ng handling
        # kernel messages, uncomment the following block of lines

        #echo -n $"Starting kernel logger: "
        #daemon klogd $KLOGD_OPTIONS
        #echo

        [ $RETVAL -eq 0 ] &amp;&amp; touch /var/lock/subsys/syslog-ng
        echo
        return $RETVAL
}

stop() {
        # Stop daemons.
        # Same here concerning klogd. Uncomment the following block of
        # code if you are needing to run it

        #echo -n $"Shutting down kernel logger: "
        #killproc klogd
        #echo

        echo -n $"Stopping $prog: "
        killproc syslog-ng
        RETVAL=$?

        [ $RETVAL -eq 0 ] &amp;&amp; rm -f /var/lock/subsys/syslog-ng
        echo
        return $RETVAL
}

case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  status)
        status syslog-ng
        RETVAL=$?
        ;;
  restart)
        stop
        start
        RETVAL=$?
        ;;
  *)
        echo $"Usage: $0 {start|stop|status|restart}"
        exit 1
esac

exit $?</pre>

起動スクリプトを登録する。
<pre># chmod 755 /etc/rc.d/init.d/syslog-ng
# /sbin/chkconfig --add syslog-ng
<strong># /sbin/chkconfig syslog off</strong>
# /sbin/chkconfig --list
syslog            0:オフ  1:オフ  2:オフ  3:オフ  4:オフ  5:オフ  6:オフ
syslog-ng       0:オフ  1:オフ  2:オン  3:オン  4:オン  5:オン  6:オフ</pre>

syslog-ngを起動する。
<pre># /sbin/service syslog stop
カーネルロガーを停止中:                                    [  OK  ]
システムロガーを停止中:                                    [  OK  ]

# /sbin/service syslog-ng start
syslog-ng を起動中:                                        [  OK  ]

# ps aux
USER       PID %CPU %MEM   VSZ  RSS TTY      STAT START   TIME COMMAND
root     15012  0.0  0.2  3340  596 ?        Ss   12:55   0:00 syslog-ng

# netstat -an |less
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
udp        0      0 0.0.0.0:514                 0.0.0.0:*</pre>

動作確認。
<blockquote># logger -p kern.info "syslog test"

# tail /var/log/messages
Jan 30 13:17:29 bruna root: syslog test</blockquote>

サーバ稼働時のログ。
<blockquote># tail /var/log/messages
Jan 30 12:54:57 bruna kernel: Kernel logging (proc) stopped.
Jan 30 12:54:57 bruna kernel: Kernel log daemon terminating.
Jan 30 12:54:59 bruna syslog: klogd 停止 succeeded
Jan 30 12:54:59 bruna exiting on signal 15
Jan 30 12:55:10 bruna syslog-ng[15012]: syslog-ng starting up; version='2.0.2'
Jan 30 12:55:10 bruna syslog-ng: syslog-ng 起動 succeeded

# tail /var/log/boot.log
Jan 30 12:55:10 bruna syslog-ng: syslog-ng 起動 succeeded</blockquote>

OS再起同時にsyslogとsyslog-ngの両方が起動しないようにsyslogを完全に停止させる。
<pre># /sbin/chkconfig syslog off
# /sbin/chkconfig --list |grep syslog
syslog          0:off   1:off   2:off   3:off   4:off   5:off   6:off
syslog-ng       0:off   1:off   2:on    3:on    4:on    5:on    6:off</pre>

シスログサーバに出力されたログメッセージの中から特定キーワードに合致した場合に自動でメールを送信してサーバの不具合の早期発見が可能な仕組みを構築する。

まずはPerlによるメール送信スクリプトの作成。<br />
このPerlスクリプトではsendmailコマンドを使用しているが、Sendmail、Postfix、qmailのいずれかのMTAがインストールされていればsendmailコマンドがインストールされているはずである。<br />
　　<strong>/usr/local/bin/alert_mail.pl</strong>
<pre>#!/usr/bin/perl

### For Sendmail
#$sendmail = '/usr/lib/sendmail';

### For Postfix
#$sendmail = '/usr/sbin/sendmail';

### For qmail
$sendmail = '/var/qmail/bin/sendmail';

$from = 'username@kajukaju.net';
$to = 'username@kajukaju.net';

$header = &lt;&lt;END;
From: $from
To: $to
Subject: Syslog-ng Alert!
Mime-Version: 1.0
Content-Type: text/plain; charset="ISO-2022-JP"
Content-Transfer-Encoding: 7bit
X-Mailer: syslog-ng auto sender program ver1.0 by kajukaju.net

END

while (&lt;STDIN&gt;) {
        if ($_) {
                  $body = $_;
                  $body =~ s/^&lt;[0-9]*&gt;//g;
                  open(MAIL, "| $sendmail -t -i");
                  print MAIL $header,$body;
                  close(MAIL);
        }
}</pre>

（例）　“end msg”という文字列がシスログに出力された場合にメールを送信する場合。<br />
syslog-ngの設定に追記する。<br />
　　<strong>/usr/local/etc/syslog-ng.conf</strong>
<blockquote>destination d_qmail_endmsg { program("/usr/local/bin/alert_mail.pl"); };
filter f_qmail_endmsg { match("<strong>end msg</strong>"); };
log { source(s_sys); filter(f_qmail_endmsg); destination(d_qmail_endmsg); };</blockquote>

設定を有効にするためにsyslog-ngを再起動。
<blockquote># /sbin/service/syslog-ng restart</blockquote>

設定した宛先にメールが送信されることを確認する。]]></description>
         <link>http://www.kajukaju.net/centos/syslogng.php</link>
         <guid>http://www.kajukaju.net/centos/syslogng.php</guid>
         <category>CentOS</category>
         <pubDate>Tue, 06 Mar 2007 20:26:32 +0900</pubDate>
      </item>
            <item>
         <title>vpopmail</title>
         <description><![CDATA[メールサーバでのユーザ管理をqmailから切り離すためにvpopmailを導入する。
vpopmailはqmailやPostfixでバーチャルサーバを実現するソフトウェアだが単一ドメインでの運用も可能。

vpopmail専用ユーザを作成する。
<blockquote># mkdir /usr/local/vpopmail
# /usr/sbin/groupadd -g 209 vchkpw
# /usr/sbin/useradd -u 209 -g 209 -d /usr/local/vpopmail -s /sbin/nologin vpopmail</blockquote>

<a href="http://www.inter7.com/" target="_blank">vpopmailの公式サイト</a>より最新のソースファイルを入手しインストールする。
<blockquote>$ wget http://jaist.dl.sourceforge.net/sourceforge/vpopmail/vpopmail-5.4.17.tar.gz
$ tar xvzf vpopmail-5.4.17.tar.gz
$ cd vpopmail-5.4.17
# ./configure --prefix=/usr/local/vpopmail --disable-clear-passwd
# make
# make install-strip</blockquote>

新規ドメインを作成する。<br>
これでpostmasterアカウントが作成される。
<blockquote># /usr/local/vpopmail/bin/vadddomain kajukaju.net
Please enter password for postmaster: ********
enter password again: ********</blockquote>

以下のファイルが書き換えられる。
<blockquote>/var/qmail/control/locals
/var/qmail/control/rcpthosts
/var/qmail/control/virtualdomains
/var/qmail/users/assign</blockquote>

新規ユーザを作成する。
<blockquote># /usr/local/vpopmail/bin/vadduser user@kajukaju.net
Please enter password for user@kajukaju.net: ********
enter password again: ********</blockquote>

エイリアスを作成する。
<blockquote># /usr/local/vpopmail/bin/valias -i to@kajukaju.net from@kajukaju.net</blockquote>

vpopmailのデフォルトでは存在しないアカウント宛のメールに対してエラーメッセージを送信してしまう。<br>
エラーメッセージを送信せず受信後、破棄する設定に変更する。<br>
　　<strong>/usr/local/vpopmail/domains/kajukaju.net/.qmail-default</strong>
<blockquote>●変更前
/usr/local/vpopmail/bin/vdelivermail '' bounce-no-mailbox

●変更後
| /usr/local/vpopmail/bin/vdelivermail '' delete</blockquote>

受信メールがvpopmailのディレクトリにスプールされるか確認する。
<pre># ls -al /usr/local/vpopmail/domains/kajukaju.net/user/Mail
dir/new/
合計 16
drwx------  2 vpopmail vchkpw 4096  7月  8 12:41 .
drwx------  5 vpopmail vchkpw 4096  7月  8 12:29 ..
-rw-------  1 vpopmail vchkpw 1061  7月  8 12:41 1152330064.18630.bruna,S=1061
-rw-------  1 vpopmail vchkpw  945  7月  8 12:41 1152330099.18634.bruna,S=945</pre>

受信時のメールログ
<blockquote># tail /var/log/mail.log
Jul  8 12:41:37 bruna smtpd: 1152330097.348998 tcpserver: status: 1/40
Jul  8 12:41:37 bruna smtpd: 1152330097.349203 tcpserver: pid 18631 from 192.168.1.xx
Jul  8 12:41:37 bruna smtpd: 1152330097.351451 tcpserver: ok 18631 bruna.kajukaju.net:192.168.1.yy:25 :192.168.1.xx::2222
Jul  8 12:41:39 bruna qmail: 1152330099.863648 new msg 560304
Jul  8 12:41:39 bruna qmail: 1152330099.864053 info msg 560304: bytes 876 from <test@example.com> qp 18632 uid 203
Jul  8 12:41:39 bruna qmail: 1152330099.886477 starting delivery 4: msg 560304 to local <strong>kajukaju.net-user@kajukaju.net</strong>
Jul  8 12:41:39 bruna qmail: 1152330099.887548 status: local 1/10 remote 0/20
Jul  8 12:41:39 bruna qmail: 1152330099.908372 delivery 4: success: did_0+0+1/
Jul  8 12:41:39 bruna qmail: 1152330099.909815 status: local 0/10 remote 0/20
Jul  8 12:41:39 bruna qmail: 1152330099.910878 end msg 560304
Jul  8 12:41:40 bruna smtpd: 1152330100.311893 tcpserver: end 18631 status 0
Jul  8 12:41:40 bruna smtpd: 1152330100.312801 tcpserver: status: 0/40</blockquote>]]></description>
         <link>http://www.kajukaju.net/centos/vpopmail.php</link>
         <guid>http://www.kajukaju.net/centos/vpopmail.php</guid>
         <category>CentOS</category>
         <pubDate>Wed, 01 Nov 2006 15:57:18 +0900</pubDate>
      </item>
            <item>
         <title>MySQL</title>
         <description><![CDATA[<strong>※MySQL-4.xの情報はページが移動しました。 --> <a href="http://www.kajukaju.net/centos/mysql_old.php">MySQL(4.x)</a></strong>

様々なアプリケーションでデータベースサーバが必要になる場面が出てくることがそ予想されるのでMySQLを導入する。
MySQL 5.xに対応するアプリケーションが増えてきたのでMySQL 5.xを導入する。

MySQLを起動する専用ユーザを作成する。
<blockquote># /usr/sbin/groupadd -g 211 mysql
# /usr/sbin/useradd -u 211 -g 211 -d /usr/local/mysql -s /sbin/nologin mysql</blockquote>

<a href="http://www.mysql.com/" target="_blank">MySQLの公式サイト</a>よりソースファイルを入手しインストールする。
<blockquote>$ wget http://dev.mysql.com/get/Downloads/MySQL-5.0/mysql-5.0.26.tar.gz/from/http://ftp.iij.ad.jp/pub/db/mysql/
$ tar xvzf mysql-5.0.26.tar.gz
$ cd mysql-5.0.26
$ ./configure --prefix=/usr/local/mysql --localstatedir=/data/mysql --with-charset=ujis --with-extra-charsets=all --with-mysqld-user=mysql
$ make
# make install</blockquote>

権限テーブルを初期化する。
<blockquote># /usr/local/mysql/bin/mysql_install_db --user=mysql
Installing all prepared tables
Fill help tables

To start mysqld at boot time you have to copy support-files/mysql.server
to the right place for your system

PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
To do so, start the server, then issue the following commands:
/usr/local/mysql/bin/mysqladmin -u root password 'new-password'
/usr/local/mysql/bin/mysqladmin -u root -h boris2 password 'new-password'
See the manual for more instructions.

You can start the MySQL daemon with:
cd /usr/local/mysql ; /usr/local/mysql/bin/mysqld_safe &

You can test the MySQL daemon with the benchmarks in the 'sql-bench' directory:
cd sql-bench ; perl run-all-tests

Please report any problems with the /usr/local/mysql/bin/mysqlbug script!

The latest information about MySQL is available on the web at
http://www.mysql.com
Support MySQL by buying support/licenses at http://shop.mysql.com</blockquote>

作成されたデータベース領域を確認する。
<pre># ls -al /data/mysql/
合計 16
drwx------    4 mysql    root         4096  10月 14 20:15 .
drwxr-xr-x    4 root     root         4096  10月 14 20:15 ..
drwx------    2 mysql    root         4096  10月 14 20:15 mysql
drwx------    2 mysql    root         4096  10月 14 20:15 test</pre>


ソースの中に設定ファイルのサンプルがあるのでコピーして使用する。
MySQLのログを取得するため一部修正している。
<blockquote># cp {$SOURCE}/support-files/my-medium.cnf /etc/my.cnf</blockquote>

　　<strong>/etc/my.cnf</strong>
<blockquote># Example MySQL config file for medium systems.
#
# This is for a system with little memory (32M - 64M) where MySQL plays
# an important part, or systems up to 128M where MySQL is used together with
# other programs (such as a web server)
#
# You can copy this file to
# /etc/my.cnf to set global options,
# mysql-data-dir/my.cnf to set server-specific options (in this
# installation this directory is /data/mysql) or
# ~/.my.cnf to set user-specific options.
#
# In this file, you can use all long options that a program supports.
# If you want to know which options a program supports, run the program
# with the "--help" option.

# The following options will be passed to all MySQL clients
[client]
#password       = your_password
port            = 3306
socket          = /tmp/mysql.sock

# Here follows entries for some specific programs

# The MySQL server
[mysqld]
port            = 3306
socket          = /tmp/mysql.sock
skip-locking
key_buffer = 16M
max_allowed_packet = 1M
table_cache = 64
sort_buffer_size = 512K
net_buffer_length = 8K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M

# Don't listen on a TCP/IP port at all. This can be a security enhancement,
# if all processes that need to connect to mysqld run on the same host.
# All interaction with mysqld must be made via Unix sockets or named pipes.
# Note that using this option without enabling named pipes on Windows
# (via the "enable-named-pipe" option) will render mysqld useless!
#
#skip-networking

# Replication Master Server (default)
# binary logging is required for replication
log-bin=/var/log/mysql/mysql-bin

# required unique id between 1 and 2^32 - 1
# defaults to 1 if master-host is not set
# but will not function as a master if omitted
server-id       = 1

# Replication Slave (comment out master section to use this)
#
# To configure this host as a replication slave, you can choose between
# two methods :
#
# 1) Use the CHANGE MASTER TO command (fully described in our manual) -
#    the syntax is:
#
#    CHANGE MASTER TO MASTER_HOST=<host>, MASTER_PORT=<port>,
#    MASTER_USER=<user>, MASTER_PASSWORD=<password> ;
#
#    where you replace <host>, <user>, <password> by quoted strings and
#    <port> by the master's port number (3306 by default).
#
#    Example:
#
#    CHANGE MASTER TO MASTER_HOST='125.564.12.1', MASTER_PORT=3306,
#    MASTER_USER='joe', MASTER_PASSWORD='secret';
#
# OR
#
# 2) Set the variables below. However, in case you choose this method, then
#    start replication for the first time (even unsuccessfully, for example
#    if you mistyped the password in master-password and the slave fails to
#    connect), the slave will create a master.info file, and any later
#    change in this file to the variables' values below will be ignored and
#    overridden by the content of the master.info file, unless you shutdown
#    the slave server, delete master.info and restart the slaver server.
#    For that reason, you may want to leave the lines below untouched
#    (commented) and instead use CHANGE MASTER TO (see above)
#
# required unique id between 2 and 2^32 - 1
# (and different from the master)
# defaults to 2 if master-host is set
# but will not function as a slave if omitted
#server-id       = 2
#
# The replication master for this slave - required
#master-host     =   <hostname>
#
# The username the slave will use for authentication when connecting
# to the master - required
#master-user     =   <username>
#
# The password the slave will authenticate with when connecting to
# the master - required
#master-password =   <password>
#
# The port the master is listening on.
# optional - defaults to 3306
#master-port     =  <port>
#
# binary logging - not required for slaves, but recommended
#log-bin=mysql-bin

# Point the following paths to different dedicated disks
#tmpdir         = /tmp/
#log-update     = /path-to-dedicated-directory/hostname

# Uncomment the following if you are using BDB tables
#bdb_cache_size = 4M
#bdb_max_lock = 10000

# Uncomment the following if you are using InnoDB tables
#innodb_data_home_dir = /data/mysql/
#innodb_data_file_path = ibdata1:10M:autoextend
#innodb_log_group_home_dir = /data/mysql/
#innodb_log_arch_dir = /data/mysql/
# You can set .._buffer_pool_size up to 50 - 80 %
# of RAM but beware of setting memory usage too high
#innodb_buffer_pool_size = 16M
#innodb_additional_mem_pool_size = 2M
# Set .._log_file_size to 25 % of buffer pool size
#innodb_log_file_size = 5M
#innodb_log_buffer_size = 8M
#innodb_flush_log_at_trx_commit = 1
#innodb_lock_wait_timeout = 50

# Admin Customise
log-error = /var/log/mysql/mysql.err.log
#log = /var/log/mysql/mysql.log
#log-update = /var/log/mysql/update.log



[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates

[isamchk]
key_buffer = 20M
sort_buffer_size = 20M
read_buffer = 2M
write_buffer = 2M

[myisamchk]
key_buffer = 20M
sort_buffer_size = 20M
read_buffer = 2M
write_buffer = 2M

[mysqlhotcopy]
interactive-timeo</blockquote>

起動スクリプトを作成する。
ソースの中に起動スクリプトのサンプルがあるのでコピーして使用する。
<pre># cp {$SOURCE/}support-files/mysql.server /etc/rc.d/init.d/mysql
# chmod 755 /etc/rc.d/init.d/mysql
# /sbin/chkconfig --add mysql
# /sbin/chkconfig --list |grep mysql
mysql           0:オフ  1:オフ  2:オン  3:オン  4:オン  5:オン  6:オフ</pre>

MySQLを起動する。
<pre># /sbin/service mysql start
Starting MySQL.. SUCCESS!

# /sbin/service mysql stop
Shutting down MySQL.. SUCCESS!

# ps -aux |grep mys
root     13773  0.1  0.2  5232 1200 pts/1    S    20:25   0:00 /bin/sh /usr/local/mysql/bin/mysqld_safe --datadir=/data/mysql --pid-file=/data/mysql/bruna.pid
mysql    13800  1.9  2.9 114844 15020 pts/1  S    20:25   0:01 /usr/local/mysql/libexec/mysqld --basedir=/usr/local/mysql --datadir=/data/mysql --user=mysql --pid-file=/data/mysql/bruna.pid --skip-locking --port=3306 --socket=/tmp/mysql.sock

# netstat -an |grep 3306
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      0 0.0.0.0:3306                0.0.0.0:*                   LISTEN

Active UNIX domain sockets (servers and established)
Proto RefCnt Flags       Type       State         I-Node Path
unix  2      [ ACC ]     STREAM     LISTENING     387040 /tmp/mysql.sock</pre>

ログを確認する。
<blockquote># tail /var/log/mysql/mysql.err.log
061014 12:06:29  InnoDB: Log file ./ib_logfile1 did not exist: new to be created
InnoDB: Setting log file ./ib_logfile1 size to 5 MB
InnoDB: Database physically writes the file full: wait...
InnoDB: Doublewrite buffer not found: creating new
InnoDB: Doublewrite buffer created
InnoDB: Creating foreign key constraint system tables
InnoDB: Foreign key constraint system tables created
061014 12:06:29  InnoDB: Started; log sequence number 0 0
061014 12:06:29 [Note] /usr/local/mysql/libexec/mysqld: ready for connections.
Version: '5.0.26-log'  socket: '/tmp/mysql.sock'  port: 3306  Source distribution
061014 12:08:25 [Note] /usr/local/mysql/libexec/mysqld: Normal shutdown

061014 12:08:25  InnoDB: Starting shutdown...
061014 12:08:27  InnoDB: Shutdown completed; log sequence number 0 43655
061014 12:08:27 [Note] /usr/local/mysql/libexec/mysqld: Shutdown complete

061014 12:08:28  mysqld ended</blockquote>

インストールした状態だと誰もがパスワード無しでmysqlに接続できてしまう。
↓でパスワード欄が空白なことがわかる。
<pre># /usr/local/mysql/bin/mysql -uroot
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2 to server version: 5.0.26-log

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> select host,user,password from mysql.user;
+-----------+------+----------+
| host      | user | password |
+-----------+------+----------+
| localhost | root |          |
| bruna     | root |          |
| bruna     |      |          |
| localhost |      |          |
+-----------+------+----------+
4 rows in set (0.02 sec)</pre>

rootにはパスワードを設定し匿名ユーザは削除する。
<pre># /usr/local/mysql/bin/mysqladmin -uroot password '********'

mysql> set password for root@bruna=password('********');
Query OK, 0 rows affected (0.02 sec)

mysql> delete from mysql.user where user="";
Query OK, 2 rows affected (0.12 sec)</pre>

再度確認してみる。
<pre>mysql> select host,user,password from mysql.user;
+-----------+------+-------------------------------------------+
| host      | user | password                                  |
+-----------+------+-------------------------------------------+
| localhost | root | *5AAAACCCBBBAAAAABBB222ACACACECCCC5555666 |
| bruna    | root | *5AAAACCCBBBAAAAABBB222ACACACECCCC5555666 |
+-----------+------+-------------------------------------------+
2 rows in set (0.00 sec)</pre>

ログのローテート設定をする。<br>
ソースの中にサンプルがあるのでコピーして使用する。
<blockquote># cp {$SOURCED/}support-files/mysql-log-rotate /etc/logrotate.d/mysql</blockquote>]]></description>
         <link>http://www.kajukaju.net/centos/mysql.php</link>
         <guid>http://www.kajukaju.net/centos/mysql.php</guid>
         <category>CentOS</category>
         <pubDate>Sun, 15 Oct 2006 01:42:27 +0900</pubDate>
      </item>
            <item>
         <title>PHP</title>
         <description><![CDATA[Webアプリケーションの開発言語であるPHPを導入する。
PHPを導入することで動的なページの生成やSQLサーバとの連携などWebベースの仕組みの幅が広がることが期待される。

PHPをインストールするためには以下のソフトウェアが必要になる。
事前にRPMでインストールしておく。
　・bison
　・flex
　・libxml2
　・libxml2-devel

<a href="http://www.php.net/" target="_blank">PHP</a>の公式サイトより 最新のソースファイルを入手する。
<pre>$ wget http://jp2.php.net/get/php-5.1.4.tar.bz2/from/jp.php.net/mirror
$ tar xvjf php-5.1.4.tar.bz2
$ cd php-5.1.4
$ ./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql=/usr/local/mysql --with-zlib --with-gd --enable-mbstring --enable-mbregex --disable-ipv6
$ make
# make install</pre>

PHPの設定ファイルであるphp.iniをソースより流用する。
<pre># cp $SOURCE/php.ini-dist /usr/local/lib/php.ini</pre>

Apacheの設定を変更しPHPスクリプトが実行されるようにする。<br>
　　<strong>/usr/local/apache2/conf/httpd.conf</strong>
<pre># LoadModule foo_module modules/mod_foo.so
<strong>LoadModule php5_module        modules/libphp5.so</strong>

&lt;IfModule mime_module&gt;
    # If the AddEncoding directives above are commented-out, then you
    # probably should define those extensions to indicate media types:
    #
    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz
    <strong>AddType application/x-httpd-php .php</strong>
&lt;/IfModule&gt;

&lt;IfModule dir_module&gt;
    DirectoryIndex index.html <strong>index.php</strong>
&lt;/IfModule&gt;</pre>

設定変更を反映させる。
<pre># /sbin/service httpd configtest
Syntax OK

# /sbin/service httpd restart
httpdを停止中:                                             [  OK  ]
httpdを起動中:                                             [  OK  ]</pre>

以下の内容のPHPスクリプトを作成しブラウザでアクセスする。<br>
　　<strong>/usr/local/apache2/htdocs/info.php</strong>
<pre>&lt;?php
    phpinfo();
?&gt;</pre>

<img src="http://www.kajukaju.net/centos/phpinfo.png" width="800" height="600" alt="phpinfo" />

PHPをインストールした状態だと↓のようにHTTPのレスポンスヘッダにPHPのバージョン情報が出てしまう。
<blockquote>HTTP/1.x 200 OK
Date: Thu, 12 Oct 2006 23:47:13 GMT
Server: Apache
<strong>X-Powered-By: PHP/5.1.6</strong>
Content-Type: text/html</blockquote>

さらに特定のURLにアクセスすることでPHPの情報を取得することも可能。
http://www.kajukaju.net/index.php?=PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000
<img src="http://www.kajukaju.net/centos/expose.png" width="800" height="600" alt="expose" />

これらの情報を秘匿するためにphp.iniを修正する。<br>
　　<strong>/usr/local/lib/php.ini</strong>
<blockquote>;
; Misc
;
; Decides whether PHP may expose the fact that it is installed on the server
; (e.g. by adding its signature to the Web server header).  It is no security
; threat in any way, but it makes it possible to determine whether you use PHP
; on your server or not.
<strong>expose_php = Off</strong></blockquote>

Apacheを再起動して完了。
<pre># /sbin/service httpd restart
httpd を停止中:                                            [  OK  ]
httpd を起動中:                                            [  OK  ]</pre>]]></description>
         <link>http://www.kajukaju.net/centos/php.php</link>
         <guid>http://www.kajukaju.net/centos/php.php</guid>
         <category>CentOS</category>
         <pubDate>Fri, 13 Oct 2006 09:12:56 +0900</pubDate>
      </item>
            <item>
         <title>OpenSSH</title>
         <description><![CDATA[リモートからサーバの管理をするためにOpenSSHを導入する。
SSHはリモートログインをするという性質上、特にセキュリティには気をつける必要があるため、Privilege Separationを有効にする。

privsep用の専用ユーザを作成する。（CentOSのデフォルトで作成済み）
<pre># /usr/sbin/groupadd -g 74 sshd
# /usr/sbin/useradd -u 74 -g 74 -d /var/empty/sshd -s /sbin/nologin</pre>

<a href="http://www.openssh.com/" target="_blank">OpenSSHの公式サイト</a>より最新のソースファイルを入手しインストールする。
<pre>$ wget ftp://ftp.iij.ad.jp/pub/OpenBSD/OpenSSH/portable/openssh-4.4p1.tar.gz
$ tar xvzf openssh-4.4p1.tar.gz
$ cd openssh-4.4p1
$ ./configure --prefix=/usr/local/openssh \
  --with-privsep-user=sshd \
  --with-privsep-path=/var/empty/sshd \
  --without-zlib-version-check

$ make
# make install</pre>

OpenSSHの設定を行う。<br>
　　<strong>/usr/local/openssh/sshd_config</strong>
<pre>#       $OpenBSD: sshd_config,v 1.74 2006/07/19 13:07:10 dtucker Exp $

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/openssh/bin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options change a
# default value.

Port 22
Protocol 2
#AddressFamily any
ListenAddress 0.0.0.0
#ListenAddress ::

# HostKey for protocol version 1
#HostKey /usr/local/openssh/etc/ssh_host_key
# HostKeys for protocol version 2
#HostKey /usr/local/openssh/etc/ssh_host_rsa_key
#HostKey /usr/local/openssh/etc/ssh_host_dsa_key

# Lifetime and size of ephemeral version 1 server key
#KeyRegenerationInterval 1h
#ServerKeyBits 768

# Logging
# obsoletes QuietMode and FascistLogging
SyslogFacility AUTH
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
#PermitRootLogin yes
#StrictModes yes
#MaxAuthTries 6

#RSAAuthentication yes
#PubkeyAuthentication yes
#AuthorizedKeysFile     .ssh/authorized_keys

# For this to work you will also need host keys in /usr/local/openssh/etc/ssh_known_hosts
#RhostsRSAAuthentication no
# similar for protocol version 2
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
PasswordAuthentication yes
#PermitEmptyPasswords no

# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
#UsePAM no

#AllowTcpForwarding yes
#GatewayPorts no
#X11Forwarding no
#X11DisplayOffset 10
#X11UseLocalhost yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS yes
#PidFile /var/run/sshd.pid
#MaxStartups 10
#PermitTunnel no

# no default banner path
#Banner /some/path

# override default of no subsystems
Subsystem       sftp    /usr/local/openssh/libexec/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       ForceCommand cvs server</pre>

起動スクリプトを作成する。
サンプルがソースファイル内にあるのでコピーして使用する。
<pre># cp {$SOURCE}/contrib/redhat/sshd.init /etc/rc.d/init.d/sshd</pre>

　　<strong>/etc/rc.d/init.d/sshd</strong>
<pre>#!/bin/bash
#
# Init file for OpenSSH server daemon
#
# chkconfig: 2345 55 25
# description: OpenSSH server daemon
#
# processname: sshd
# config: /etc/ssh/ssh_host_key
# config: /etc/ssh/ssh_host_key.pub
# config: /etc/ssh/ssh_random_seed
# config: /etc/ssh/sshd_config
# pidfile: /var/run/sshd.pid

# source function library
. /etc/rc.d/init.d/functions

# pull in sysconfig settings
[ -f /etc/sysconfig/sshd ] && . /etc/sysconfig/sshd

RETVAL=0
prog="sshd"

# Some functions to make the below more readable
KEYGEN=/usr/local/openssh/bin/ssh-keygen
SSHD=/usr/local/openssh/sbin/sshd
RSA1_KEY=/usr/local/openssh/etc/ssh_host_key
RSA_KEY=/usr/local/openssh/etc/ssh_host_rsa_key
DSA_KEY=/usr/local/openssh/etc/ssh_host_dsa_key
PID_FILE=/var/run/sshd.pid

do_rsa1_keygen() {
        if [ ! -s $RSA1_KEY ]; then
                echo -n $"Generating SSH1 RSA host key: "
                if $KEYGEN -q -t rsa1 -f $RSA1_KEY -C '' -N '' >&/dev/null; then
                        chmod 600 $RSA1_KEY
                        chmod 644 $RSA1_KEY.pub
                        if [ -x /sbin/restorecon ]; then
                            /sbin/restorecon $RSA1_KEY.pub
                        fi
                        success $"RSA1 key generation"
                        echo
                else
                        failure $"RSA1 key generation"
                        echo
                        exit 1
                fi
        fi
}

do_rsa_keygen() {
        if [ ! -s $RSA_KEY ]; then
                echo -n $"Generating SSH2 RSA host key: "
                if $KEYGEN -q -t rsa -f $RSA_KEY -C '' -N '' >&/dev/null; then
                        chmod 600 $RSA_KEY
                        chmod 644 $RSA_KEY.pub
                        if [ -x /sbin/restorecon ]; then
                            /sbin/restorecon $RSA_KEY.pub
                        fi
                        success $"RSA key generation"
                        echo
                else
                        failure $"RSA key generation"
                        echo
                        exit 1
                fi
        fi
}

do_dsa_keygen() {
        if [ ! -s $DSA_KEY ]; then
                echo -n $"Generating SSH2 DSA host key: "
                if $KEYGEN -q -t dsa -f $DSA_KEY -C '' -N '' >&/dev/null; then
                        chmod 600 $DSA_KEY
                        chmod 644 $DSA_KEY.pub
                        if [ -x /sbin/restorecon ]; then
                            /sbin/restorecon $DSA_KEY.pub
                        fi
                        success $"DSA key generation"
                        echo
                else
                        failure $"DSA key generation"
                        echo
                        exit 1
                fi
        fi
}

do_restart_sanity_check()
{
        $SSHD -t
        RETVAL=$?
        if [ ! "$RETVAL" = 0 ]; then
                failure $"Configuration file or keys are invalid"
                echo
        fi
}

start()
{
        # Create keys if necessary
        do_rsa1_keygen
        do_rsa_keygen
        do_dsa_keygen

        echo -n $"Starting $prog:"
        initlog -c "$SSHD $OPTIONS" && success || failure
        RETVAL=$?
        [ "$RETVAL" = 0 ] && touch /var/lock/subsys/sshd
        echo
}

stop()
{
        echo -n $"Stopping $prog:"
        killproc $SSHD -TERM
        RETVAL=$?
        [ "$RETVAL" = 0 ] && rm -f /var/lock/subsys/sshd
        echo
}

reload()
{
        echo -n $"Reloading $prog:"
        killproc $SSHD -HUP
        RETVAL=$?
        echo
}

case "$1" in
        start)
                start
                ;;
        stop)
                stop
                ;;
        restart)
                stop
                start
                ;;
        reload)
                reload
                ;;
        condrestart)
                if [ -f /var/lock/subsys/sshd ] ; then
                        do_restart_sanity_check
                        if [ "$RETVAL" = 0 ] ; then
                                stop
                                # avoid race
                                sleep 3
                                start
                        fi
                fi
                ;;
        status)
                status $SSHD
                RETVAL=$?
                ;;
        *)
                echo $"Usage: $0 {start|stop|restart|reload|condrestart|status}"
                RETVAL=1
esac
exit $RETVAL</pre>

起動スクリプトを登録する。
<pre># chmod 755 /etc/rc.d/init.d/sshd
# /sbin/chkconfig --add sshd
# /sbin/chkconfig --list
sshd            0:off   1:off   2:off   3:on    4:on    5:on    6:off</pre>

OpenSSHを起動する。
<pre># /sbin/service sshd start
sshd を起動中:                                             [  OK  ]</pre>

起動確認をする。
<pre># netstat -an |grep 22
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN

$ ps aux |grep ssh
root      5235  0.0  0.3  4636  876 ?        Ss   03:08   0:00 /usr/local/openssh/sbin/sshd</pre>

サーバ稼働時のログ。
<pre># tail /var/log/secure
Sep 30 02:57:14 bruna sshd[4986]: Server listening on 0.0.0.0 port 22.
Sep 30 03:00:25 bruna sshd[4986]: Received signal 15; terminating.

# tail /var/log/boot.log
Sep 30 02:57:14 bruna sshd:  succeeded
Sep 30 03:00:25 bruna sshd: sshd -TERM succeeded</pre>

Privilege Separationが有効か確認するため一般ユーザでログインして確認する。<br>
下記の通り、Privilege Separationが有効のときはユーザ権限でsshdが動いていることがわかる。
<pre>●Privilege Separation有効
$ ps aux |grep ssh
root      5235  0.0  0.3  4636  876 ?        Ss   03:08   0:00 /usr/local/openssh/sbin/sshd
<strong>root      9279  0.0  0.6  6580 1740 ?        Ss   10:36   0:00 sshd: user [priv]
user      9281  0.0  0.4  6600 1108 ?        S    10:37   0:00 sshd: user@pts/0</strong>

●Privilege Separation無効
$ ps aux |grep ssh
root      9542  0.0  0.3  4752  876 ?        Ss   11:00   0:00 /usr/local/openssh/sbin/sshd
root      9561  3.1  0.6  4608 1788 ?        Ss   11:01   0:00 sshd: user@pts/1</pre>

最後にRPMで導入されているOpenSSHを削除する。<br>
※起動スクリプト(/etc/rc.d/init.d/sshd)とディレクトリ(/var/empty/sshd)が削除されてしまうので注意する。
<pre># yum remove openssh
Dependencies Resolved

=============================================================================
 Package                 Arch       Version          Repository        Size
=============================================================================
Removing:
 openssh                 i386       3.9p1-8.RHEL4.15  installed         807 k
Removing for dependencies:
 openssh-clients         i386       3.9p1-8.RHEL4.15  installed         625 k
 openssh-server          i386       3.9p1-8.RHEL4.15  installed         357 k

Transaction Summary
=============================================================================
Install      0 Package(s)
Update       0 Package(s)
Remove       3 Package(s)
Total download size: 0
Is this ok [y/N]: y
Downloading Packages:
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
warning: /etc/ssh/sshd_config saved as /etc/ssh/sshd_config.rpmsave
warning: /etc/rc.d/init.d/sshd saved as /etc/rc.d/init.d/sshd.rpmsave
  Removing  : openssh-server               ######################### [1/3]
  Removing  : openssh-clients              ######################### [2/3]
  Removing  : openssh                      ######################### [3/3]

Removed: openssh.i386 0:3.9p1-8.RHEL4.15
Dependency Removed: openssh-clients.i386 0:3.9p1-8.RHEL4.15 openssh-server.i386 0:3.9p1-8.RHEL4.15
Complete!</pre>

/var/empty/sshdがないとき。
<pre># /sbin/service sshd start
sshd を起動中:Missing privilege separation directory: /var/empty/sshd
                                                           [失敗]</pre>]]></description>
         <link>http://www.kajukaju.net/centos/openssh.php</link>
         <guid>http://www.kajukaju.net/centos/openssh.php</guid>
         <category>CentOS</category>
         <pubDate>Sat, 30 Sep 2006 10:28:39 +0900</pubDate>
      </item>
            <item>
         <title>netqmail</title>
         <description><![CDATA[<strong>※qmailの情報はページが移動しました。 --&gt; <a href="http://www.kajukaju.net/centos/qmail.php">qmail</a></strong>

自宅から外部へメールを送信するのとkajukaju.netドメイン宛のメールを受信するためにSMTPサーバを導入する。

qmailを起動する専用ユーザを作成する。
<pre># /usr/sbin/groupadd -g 205 nofiles
# /usr/sbin/groupadd -g 206 qmail

# /usr/sbin/useradd -u 205 -g nofiles -d /var/qmail/alias -s /sbin/nologin alias
# /u/var/qmail/control/localssr/sbin/useradd -u 206 -g nofiles -d /var/qmail -s /sbin/nologin qmaild
# /usr/sbin/useradd -u 207 -g nofiles -d /var/qmail -s /sbin/nologin qmaill
# /usr/sbin/useradd -u 208 -g nofiles -d /var/qmail -s /sbin/nologin qmailp
# /usr/sbin/useradd -u 209 -g qmail -d /var/qmail -s /sbin/nologin qmailq
# /usr/sbin/useradd -u 210 -g qmail -d /var/qmail -s /sbin/nologin qmailr
# /usr/sbin/useradd -u 211 -g qmail -d /var/qmail -s /sbin/nologin qmails</pre>

qmailの公式サイトより最新のソースファイルを入手しインストールする。
また、以下のパッチも適用する。
　・qmail-date-localtime.patch --&gt; ヘッダの日付をローカルタイムに変換する

上記以外でも気になるパッチがある（今回は未適用）。
　・qmail-qread-date-localtime.patch --&gt; qmail-date-localtime.patchの不具合修正
　・badrcptto.patch --&gt; 指定宛先宛のメールを拒否
　・qmail-bouncecontrol-1.03.patch --&gt; qmail標準のバウンスメッセージを変更

<pre>$ wget http://www9.jp.qmail.org/netqmail-1.05.tar.gz
$ tar xvzf netqmail-1.05.tar.gz
$ cd netqmail-1.05/other-patches
$ wget http://www.alib.jp/files/qmail-date-localtime.patch
$ cd /work/netqmail-1.05
$ ./collate.sh
$ cd netqmail-1.05
$ patch -p1 &lt; ../other-patches/qmail-date-localtime.patch
# make setup check</pre>

次にucspi-tcpをインストールする。
<pre>$ wget http://cr.yp.to/ucspi-tcp/ucspi-tcp-0.88.tar.gz
$ tar xvzf ucspi-tcp-0.88.tar.gz
$ cd ucspi-tcp-0.88

$ patch -p1 &lt; ../netqmail-1.05/other-patches/ucspi-tcp-0.88.errno.patch
patching file error.h
$ patch -p1 &lt; ../netqmail-1.05/other-patches/ucspi-tcp-0.88.a_record.patch
patching file rblsmtpd.c
$ patch -p1 &lt; ../netqmail-1.05/other-patches/ucspi-tcp-0.88.nodefaultrbl.patch
patching file rblsmtpd.c
Hunk #1 succeeded at 193 (offset 38 lines).
Hunk #3 succeeded at 227 (offset 38 lines).
$ make
# make setup check</pre>

qmailの設定ファイルを編集。
設定のポイント
　・ホスト名は [postman.kajukaju.net]
　・サーバが受け取るドメイン名は [@kajukaju.net]
　・メールの中継を許可するドメイン名は [@kajukaju.net]
　・受信メールの最大サイズは [10MB(10485760byte)]
　・送信キューの有効期限は［1日(86400秒)］

　　<strong>/var/qmail/control/me</strong>
<pre>postman.kajukaju.net</pre>

　　<strong>/var/qmail/control/locals</strong>
<pre>kajukaju.net</pre>

　　<strong>/var/qmail/control/rcpthosts</strong>
<pre>kajukaju.net</pre>

　　<strong>/var/qmail/control/databytes</strong>
<pre>10485760</pre>

　　<strong>/var/qmail/control/queuelifetime</strong>
<pre>86400</pre>

中継許可ホストの作成<br>
　　<strong>/var/qmail/control/smtp.rules.txt</strong>
<pre>127.0.0.1:allow,RELAYCLIENT=&quot;&quot;
192.168.1.:allow,RELAYCLIENT=&quot;&quot;</pre>

smtp.rules.txtをqmailが認識できる形に変換する。
<pre># /usr/local/bin/tcprules /var/qmail/control/smtp.rules.cdb /var/qmail/control/smtp.rules.temp &lt; /var/qmail/control/smtp.rules.txt

# ls -al /var/qmail/control/ |grep rules
-rw-r--r--    1 root     root         2143  6月 22 22:22 smtp.rules.cdb
-rw-r--r--    1 root     root           63  6月 22 22:21 smtp.rules.txt</pre>

起動スクリプトを作成する。<br>
　　<strong>/etc/rc.d/init.d/qmail</strong>
<pre>作成中
・・・
・・・</pre>

起動スクリプトを登録する。
<pre># chmod 755 /etc/rc.d/init.d/qmail
# /sbin/chkconfig --add qmail
# /sbin/chkconfig --list |grep qmail
qmail           0:off   1:off   2:off   3:on    4:on    5:on    6:off</pre>

qmailを起動する。
<pre># /sbin/service qmail start
Starting qmail-start:
Starting qmail-send:

# /sbin/service qmail stop
Stopping qmail:                                            [  OK  ]

# ps aux |grep qmail
qmails   17086  0.0  0.1  2304  352 pts/0    S    18:38   0:00 qmail-send
qmaill   17087  0.0  0.1  2096  432 pts/0    S    18:38   0:00 splogger qmail 2
root     17088  0.0  0.1  3404  304 pts/0    S    18:38   0:00 qmail-lspawn ./Maildir/
qmailr   17089  0.0  0.1  3244  304 pts/0    S    18:38   0:00 qmail-rspawn
qmailq   17090  0.0  0.1  3212  304 pts/0    S    18:38   0:00 qmail-clean
qmaild   17091  0.0  0.1  1524  468 pts/0    S    18:38   0:00 tcpserver -v -u 203 -g 202 -R -x /var/qmail/control/smtp.rules.cdb 0 smtp qmail-smtpd
root     17092  0.0  0.1  3140  432 pts/0    S    18:38   0:00 /var/qmail/bin/splogger smtpd 2

# netstat -an
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      0 0.0.0.0:25                  0.0.0.0:*                   LISTEN</pre>

サーバ稼働時のログ
<pre># tail /var/log/mail.log
Jul  3 18:38:37 bruna smtpd: 1151919517.369861 tcpserver: status: 0/40
Jul  3 18:38:37 bruna qmail: 1151919517.395068 status: local 0/10 remote 0/20
Jul  3 18:40:07 bruna qmail: 1151919607.538482 status: exiting

# tail /var/log/boot.log
Jul  3 18:40:07 bruna qmail: qmail-send 停止 succeeded
Jul  3 18:40:07 bruna qmail: tcpserver 停止 succeeded</pre>

メールを送信し動作確認をする。
<pre># telnet localhost 25
・・・
・・・</pre>

メール送信時のログ
<pre># tail -f /var/log/mail.log
Jul  3 18:41:22 bruna smtpd: 1151919682.243730 tcpserver: status: 1/40
Jul  3 18:41:22 bruna smtpd: 1151919682.246043 tcpserver: pid 17143 from 192.168.1.yy
Jul  3 18:41:22 bruna smtpd: 1151919682.250408 tcpserver: ok 17143 bruna.kajukaju.net:192.168.1.xx:25 server.kajukaju.net:192.168.1.yy::33660
Jul  3 18:41:54 bruna qmail: 1151919714.516571 new msg 560309
Jul  3 18:41:54 bruna qmail: 1151919714.516786 info msg 560309: bytes 220 from &lt;user@kajukaju.net&gt; qp 17144 uid 203
Jul  3 18:41:54 bruna qmail: 1151919714.524802 starting delivery 1: msg 560309 to remote xxx@example.com
Jul  3 18:41:54 bruna qmail: 1151919714.525827 status: local 0/10 remote 1/20
Jul  3 18:41:55 bruna qmail: 1151919715.044666 delivery 1: success: 211.9.231.122_accepted_message./Remote_host_said:_250_2.0.0_k639fs90070130_Message_accepted_for_delivery/
Jul  3 18:41:55 bruna qmail: 1151919715.044904 status: local 0/10 remote 0/20
Jul  3 18:41:55 bruna qmail: 1151919715.044997 end msg 560309
Jul  3 18:41:55 bruna smtpd: 1151919715.746928 tcpserver: end 17143 status 0
Jul  3 18:41:55 bruna smtpd: 1151919715.748744 tcpserver: status: 0/40</pre>

ログのローテート<br>
　　<strong>/etc/logrotate.d/syslog</strong>
<pre>/var/log/messages /var/log/secure <strong>/var/log/mail.log</strong> /var/log/boot.log /var/log/cron.log /var/log/snmp.log /var/log/named.log {
    sharedscripts
    postrotate
        /bin/kill -HUP `cat /var/run/syslog-ng.pid 2&gt; /dev/null` 2&gt; /dev/null || true
    endscript
}</pre>]]></description>
         <link>http://www.kajukaju.net/centos/netqmail.php</link>
         <guid>http://www.kajukaju.net/centos/netqmail.php</guid>
         <category>CentOS</category>
         <pubDate>Thu, 10 Aug 2006 17:25:16 +0900</pubDate>
      </item>
            <item>
         <title>qmail</title>
         <description><![CDATA[自宅から外部へメールを送信するのとkajukaju.netドメイン宛のメールを受信するためにSMTPサーバを導入する。
KAJUKAJU.netが接続しているISPではOutbound 25 blockが導入されているため外部へのメール送信は全てISPのSMTPサーバ経由で配送させる。

qmailを起動する専用ユーザを作成する。
<blockquote># /usr/sbin/groupadd -g 205 nofiles
# /usr/sbin/groupadd -g 206 qmail

# /usr/sbin/useradd -u 205 -g nofiles -d /var/qmail/alias -s /sbin/nologin alias
# /usr/sbin/useradd -u 206 -g nofiles -d /var/qmail -s /sbin/nologin qmaild
# /usr/sbin/useradd -u 207 -g nofiles -d /var/qmail -s /sbin/nologin qmaill
# /usr/sbin/useradd -u 208 -g nofiles -d /var/qmail -s /sbin/nologin qmailp
# /usr/sbin/useradd -u 209 -g qmail -d /var/qmail -s /sbin/nologin qmailq
# /usr/sbin/useradd -u 210 -g qmail -d /var/qmail -s /sbin/nologin qmailr
# /usr/sbin/useradd -u 211 -g qmail -d /var/qmail -s /sbin/nologin qmails</blockquote>

qmailの公式サイトより最新のソースファイルを入手しインストールする。
また、以下のパッチも適用する。
　　・qmail-date-localtime.patch	--&gt;	ヘッダの日付をローカルタイムに変換する
　　・qmail-103.patch			--&gt;	512バイト以上のDNS応答パケットに対応する
　　・qmail-smtpd-relay-reject		--&gt;	%，!，@（は2個）がある場合受信を拒否する
　　・qmail-0.0.0.0.patch			--&gt;	 IPアドレスが0.0.0.0のホストを自ホストとする 
　　・qmail-1.03.errno.patch		--&gt;	glibc-2.3.1以降対応用
　　・qmail-1.03.qmail_local.patch	--&gt;	glibc-2.3.1以降対応用

上記以外でも気になるパッチがある（今回は未適用）。
　　・qmail-qread-date-localtime.patch	--&gt;	qmail-date-localtime.patchの不具合修正
　　・badrcptto.patch				--&gt;	指定宛先宛のメールを拒否
　　・qmail-bouncecontrol-1.03.patch	--&gt;	qmail標準のバウンスメッセージを変更

<pre>$ wget ftp://ftp.jp.qmail.org/qmail/qmail-1.03.tar.gz
$ tar xvzf qmail-1.03.tar.gz
$ cd qmail-1.03
$ patch -s -p1 &lt; ../qmail-date-localtime.patch
$ patch -s -p1 &lt; ../qmail-103.patch
$ patch -s -p1 &lt; ../qmail-smtpd-relay-reject
$ patch -s -p1 &lt; ../qmail-0.0.0.0.patch
$ patch -s -p1 &lt; ../qmail-1.03.errno.patch
$ patch -s -p1 &lt; ../qmail-1.03.qmail_local.patch

○実際にパッチが当てられたファイルは以下のとおり
$ ls -al |grep &quot;6月 26&quot;
drwxr-xr-x    3 user    group         4096  6月 26 00:43 ..
-rw-r--r--      1 user    group         1763  6月 26 00:45 cdb_seek.c
-rw-r--r--      1 user    group         1811  6月 26 00:45 date822fmt.c
-rw-r--r--      1 user    group         8927  6月 26 00:45 dns.c
-rw-r--r--      1 user    group           767  6月 26 00:45 error.3
-rw-r--r--      1 user    group           432  6月 26 00:45 error.h
-rw-r--r--      1 user    group         2456  6月 26 00:45 ipme.c
-rw-r--r--      1 user    group       17982  6月 26 00:45 qmail-local.c
-rw-r--r--      1 user    group       11635  6月 26 00:45 qmail-smtpd.c

# make
# make setup check</pre>

qmailの設定ファイルを編集。
設定のポイント
　　・ホスト名は [postman.kajukaju.net]
　　・サーバが受け取るドメイン名は [@kajukaju.net]
　　・メールの中継を許可するドメイン名は [@kajukaju.net]
　　・受信メールの最大サイズは [10MB(10485760byte)]

　　<strong>/var/qmail/control/me</strong>
<blockquote>postman.kajukaju.net</blockquote>

　　<strong>/var/qmail/control/locals</strong>
<blockquote>kajukaju.net</blockquote>

　　<strong>/var/qmail/control/rcpthosts</strong>
<blockquote>kajukaju.net</blockquote>

　　<strong>/var/qmail/control/databytes</strong>
<blockquote>10485760</blockquote>

バウンスメール受信用、内部エラー発生時受信用の管理者アカウントを作成する。
実際にはこれら管理者アカウント宛のメールは実メールに転送する。
<blockquote># echo &quot;&amp;username&quot; &gt; /var/qmail/alias/.qmail-root
# echo &quot;&amp;username&quot; &gt; /var/qmail/alias/.qmail-mailer-daemon
# echo &quot;&amp;username&quot; &gt; /var/qmail/alias/.qmail-postmaster</blockquote>

各ユーザアカウントに対してメールボックスを作成する。
qmailはmailbox形式、Maildir形式どちらでも対応可能だがMaildir形式にする。
<pre># su - username
$ /var/qmail/bin/maildirmake /home/username/Maildir
$ ls -al /home/username/Maildir
drwx------    8 user group        4096  6月 26 22:18 .
drwx------    4 user group        4096  6月 16 13:38 ..
drwx------    2 user group        8192  6月 26 21:22 cur
drwx------    2 user group        8192  6月 26 21:40 new
drwx------    2 user group        4096  6月 26 21:40 tmp</pre>

新規にアカウントを作成したときに自動的にメールボックスが作成されるようにスケルトンディレクトリにも作成しておくとよい。
<blockquote># /var/qmail/bin/maildirmake /etc/skel/Maildir</blockquote>

qmailの起動スクリプトを編集しMaildir形式で起動するようにする。<br />
　　<strong>/var/qmail/boot/home</strong>
<blockquote>#!/bin/sh

# Using splogger to send the log through syslog.
# Using qmail-local to deliver messages to ~/Mailbox by default.

exec env - PATH="/var/qmail/bin:$PATH" \
#qmail-start ./Mailbox splogger qmail
<strong>qmail-start ./Maildir/ splogger qmail</strong></blockquote>

このままではqmailは/var/qmail/control/rcpthostsに書いた宛先宛のメールしか受け取らない。
外部宛てにメールを送信するためにucspi-tcpを導入する。

ucspi-tcpの公式サイトより最新のソースファイルを入手しインストールする。
また、以下のパッチも適用する。
　　・ucspi-tcp-0.88.errno.patch	--&gt;	glibc-2.3.1以降対応用
　　・ucspi-tcp-0.88.a_record.patch	--&gt;	glibc-2.3.1以降対応用
　　・ucspi-tcp-0.88.nobase.patch	--&gt;	glibc-2.3.1以降対応用

<pre>$ wget http://cr.yp.to/ucspi-tcp/ucspi-tcp-0.88.tar.gz
$ tar xvzf ucspi-tcp-0.88.tar.gz
$ cd ucspi-tcp-0.88.tar.gz
$ patch -s -p1 &lt; ../ucspi-tcp-0.88.errno.patch
$ patch -s -p1 &lt; ../ucspi-tcp-0.88.a_record.patch
$ patch -s -p1 &lt; ../ucspi-tcp-0.88.nobase.patch

○実際にパッチが当てられたファイルは以下のとおり
$ ls -la |grep "6月 26"
drwxr-xr-x    2 user    group        8192  6月 26 01:44 .
drwxr-xr-x    4 user    group        4096  6月 26 01:44 ..
-rw-r--r--      1 user    group          513  6月 26 01:44 error.h
-rw-r--r--      1 user    group        5561  6月 26 01:44 rblsmtpd.c
-rw-r--r--      1 user    group        5569  6月 26 01:44 rblsmtpd.c.orig

# make
# make setup check</pre>

メールの中継を許可するホスト、ネットワークを指定する。
今回は以下のホスト、ネットワークを許可した。
　　・127.0.0.1
　　・192.168.1.0/24

　　<strong>/var/qmail/control/smtp.rules.txt</strong>
<blockquote>127.0.0.1:allow,RELAYCLIENT=&quot;&quot;
192.168.1.:allow,RELAYCLIENT=&quot;&quot;</blockquote>

ucspi-tcpが理解できるファイル形式に変換する。
<blockquote># /usr/local/bin/tcprules /var/qmail/control/smtp.rules.cdb /var/qmail/control/smtp.rules.temp &lt; /var/qmail/control/smtp.rules.txt</blockquote>

起動スクリプトを作成する。<br />
　　<strong>/etc/rc.d/init.d/qmail</strong>
<pre>#!/bin/sh
#
# qmail         This shell script takes care of starting and stopping
#               qmail on RedHat or other chkconfig-based system.
#
# chkconfig: 345 24 76
#
# processname: qmail

#
# Source Redhat function library.
#
. /etc/rc.d/init.d/functions

# Track on path to qmail if not already in PATH
QMAIL_PATH=&quot;:/usr/local/bin:/var/qmail/bin&quot;

PATH=$PATH$QMAIL_PATH
export PATH

# See how we were called.
start() {
        # Start daemons.
        echo -n &quot;Starting qmail-start: &quot;
        qmail-start ./Maildir/ splogger qmail &amp;
        touch &quot;/var/lock/subsys/qmail-start&quot;
        echo

        # Start SMTP
        echo -n &quot;Starting qmail-send: &quot;
        tcpserver -v -u 206 -g 205 -R -x /var/qmail/control/smtp.rules.cdb 0 smt
        p qmail-smtpd 2&gt;&amp;1 | /var/qmail/bin/splogger smtpd 3 &amp;
        touch &quot;/var/lock/subsys/qmail-smtpd&quot;
        echo
}

stop() {
        # Stop daemon.
        echo -n &quot;Stopping qmail: &quot;
        pkill qmail-send
        kill `ps -aux | grep qmaild | grep -v grep | awk '{print $2;}'`
        rm -rf /var/lock/subsys/qmail-start
        rm -rf /var/lock/subsys/qmail-smtpd
        echo
}

case &quot;$1&quot; in
  start)
        start
        ;;
  stop)
        stop
        ;;
  status)
        status qmail-smtpd
        RETVAL=$?
        ;;
  restart)
        stop
        start
        ;;
  *)
        echo $&quot;Usage: $0 {start|stop|status|restart}&quot;
        exit 1
esac

exit $?</pre>

起動スクリプトを登録する。
<pre># /sbin/chkconfig --add qmail
# /sbin/chkconfig --list |grep qmail
qmail           0:オフ  1:オフ  2:オフ  3:オン  4:オン  5:オン  6:オフ</pre>

qmailを起動する。
<pre># /var/qmail/boot/home &amp;
# tcpserver -v -u 206 -g 205 -x /var/qmail/control/smtp.rules.cdb 0 smtp /var/qmail/bin/qmail-smtpd 2&gt;&amp;1 | /var/qmail/bin/splogger smtpd 3 &amp;

# ps -aux |grep qmail
qmails    32582         1  0 01:39 pts/1    00:00:00 qmail-send
qmaill     32583 32582  0 01:39 pts/1    00:00:00 splogger qmail
root       32584 32582  0 01:39 pts/1    00:00:00 qmail-lspawn ./Maildir/
qmailr    32585 32582  0 01:39 pts/1    00:00:00 qmail-rspawn
qmailq   32586 32582  0 01:39 pts/1    00:00:00 qmail-clean
qmaild       922 32650  0 01:54 pts/1    00:00:00 tcpserver -v -u 206 -g 205 -x /var/qmail/control/smtp.rules.cdb 0 smtp /var/qmail/bin/qmail-smtpd
root           923 32650  0 01:54 pts/1    00:00:00 /var/qmail/bin/splogger smtpd 3

# netstat -an |grep 25
tcp        0      0 0.0.0.0:25                  0.0.0.0:*                 LISTEN</pre>

動作確認をする。
<blockquote># telnet postman.kajukaju.net 25
Trying 192.168.1.xx...
Connected to boris (192.168.1.xx).
Escape character is '^]'.
220 postman.kajukaju.net ESMTP
helo localhost
250 postman.kajukaju.net
mail from:&lt;user@domainname&gt;
250 ok
rcpt to:&lt;username@kajukaju.net&gt;
250 ok
data
354 go ahead
This mail is testmail.
.
250 ok 1119718602 qp 931
quit
221 postman.kajukaju.net
Connection closed by foreign host.</blockquote>

メールが受信できていることを確認する。
<pre># ls -al /home/username/Maildir/new
合計 20
drwx------    2 user group        8192  7月 21 21:40 .
drwx------    8 user group        4096  7月 21 22:18 ..
-rw-------     1 user group        6354  7月 21 21:40 1121949653.M381302P7128V0000000000002107I0009E707_0.boris,S=6354</pre>

サーバ稼働時のログ。
<blockquote># tail /var/log/maillog
Jun 26 01:39:44 boris qmail: 1119717584.852036 status: local 0/10 remote 0/20
Jun 26 01:56:42 boris qmail: 1119718602.072734 new msg 336688
Jun 26 01:56:42 boris qmail: 1119718602.072902 info msg 336688: bytes 167 from <user@domainname> qp 931 uid 206
Jun 26 01:56:42 boris qmail: 1119718602.083708 starting delivery 1: msg 336688 to local username@kajukaju.net
Jun 26 01:56:42 boris qmail: 1119718602.083848 status: local 1/10 remote 0/20
Jun 26 01:56:42 boris qmail: 1119718602.099562 delivery 1: success: did_1+0+0/
Jun 26 01:56:42 boris qmail: 1119718602.099712 status: local 0/10 remote 0/20
Jun 26 01:56:42 boris qmail: 1119718602.099758 end msg 336688</blockquote>

ログローテートの設定追加。<br ?>
　　<strong>/etc/logrotate.d/syslog</strong> 
<pre>/var/log/messages /var/log/secure <strong>/var/log/mail.log</strong> /var/log/boot.log /var/log/cron.log /var/log/snmp.log /var/log/named.log {
    sharedscripts
    postrotate
        /bin/kill -HUP `cat /var/run/syslog-ng.pid 2&gt; /dev/null` 2&gt; /dev/null || true
    endscript
}</pre>]]></description>
         <link>http://www.kajukaju.net/centos/qmail.php</link>
         <guid>http://www.kajukaju.net/centos/qmail.php</guid>
         <category>CentOS</category>
         <pubDate>Thu, 10 Aug 2006 16:37:21 +0900</pubDate>
      </item>
            <item>
         <title>BIND</title>
         <description><![CDATA[ネットワーク内のホストの名前解決を行うためにDNSサーバを導入する。
今回導入するDNSサーバを利用できるのは自宅のネットワークに属するホストのみで、このDNSサーバが名前解決の出来ないホストについてはISPが提供しているDNSサーバに問い合わせを行う。

<a href="http://www.isc.org/sw/bind/" target="_blank">BINDの公式サイト</a>より 最新のソースファイルを入手しインストールする。
<pre>$ wget ftp://ftp.isc.org/isc/bind9/9.3.2/bind-9.3.2.tar.gz
$ tar xvzf bind-9.3.2.tar.gz
$ cd bind-9.3.2
$ ./configure --disable-ipv6 --sysconfdir=/etc
$ make
# make install</pre>

BINDを起動する専用ユーザを作成する。
<pre># /usr/sbin/groupadd -g 204 named
# /usr/sbin/useradd -u 204 -g 204 -s /sbin/nologin -d /var/named named</p