読者です 読者をやめる 読者になる 読者になる

labunix's blog

labunixのラボUnix

さくらVPSデビューした(Debian Wheezy)

■さくらVPSにDebian Wheezyを導入する。
 主に個人でのクライアント用途。
 「禁止事項について」の項にあるような用途ではない。

 サービスのご利用にあたって
 http://support.sakura.ad.jp/support/caution.html

■GUIは直接実行しない。DBは公開用途で使用しない。
 と言う自分への追加条件を課して、2GBプラン、東京を選択。
 ※「つぎへ」に対して「もどる」が無いので注意。

■標準が「CentOS 6 x86_64」なので、
 カスタムOSインストールで「Debian 7 amd64」に。
 ブラウザはfirefoxなのでHTML5モードでOSをインストール。

$ file firefox | awk -F\, '{print $1}'
firefox: ELF 64-bit LSB executable

$ ./firefox --version
Mozilla Firefox 31.0

■パーティションは手動で設定
 インストール時間は約60分。
 最初なので設定値を色々悩んだのが大きい。
 KVM仮想マシンらしい動き。決して速くは無い。

■CUIインストールでもいつも扱っているNetinstallerとは選択可能な設定が若干異なる。
 virtio経由のディスクなので、高いI/Oを消費するユーザを制限するというポリシーは、
 分かりやすい手段だと思う。

# fdisk -l /dev/vda

Disk /dev/vda: 214.7 GB, 214748364800 bytes
16 heads, 63 sectors/track, 416101 cylinders, total 419430400 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x0004b276

   Device Boot      Start         End      Blocks   Id  System
/dev/vda1   *        2048      999423      498688   83  Linux
/dev/vda2          999424    28342271    13671424   82  Linux swap / Solaris
/dev/vda3        28342272   224045055    97851392   83  Linux
/dev/vda4       224047102   419428351    97690625    5  Extended
/dev/vda5       224047104   419428351    97690624   83  Linux

■リモートコンソールのカーソルがなんとなく馴染めないので、
 sshのポート変更に留めてssh経由の作業とする。
 以下はデフォルトポート。

# grep ^Port /etc/ssh/sshd_config 
Port 22

# /etc/init.d/ssh restart

■DNSはインストール中1つしか設定していなかったので追加する。
 仮想マシン内の変更なので、ここではOSを再起動する。

# grep dns-nameservers /etc/network/interfaces | sed s/"[0-9]"/"X"/g
	dns-nameservers XXX.XXX.XXX.XX
	dns-nameservers XXX.XXX.XXX.XX

# shutdown -r now && exit

■DNSクライアントも無い、vimも無い。sources.listの設定も無い。
 なので、APT設定とインストール。

# cat /etc/apt/sources.list

#deb cdrom:[Debian GNU/Linux 7.4.0 _Wheezy_ - Official amd64 NETINST Binary-1 20140208-13:45]/ wheezy main

deb http://ftp.jp.debian.org/debian/ wheezy main contrib non-free
deb-src http://ftp.jp.debian.org/debian/ wheezy main

deb http://security.debian.org/ wheezy/updates main
deb-src http://security.debian.org/ wheezy/updates main

# wheezy-updates, previously known as 'volatile'
deb http://ftp.jp.debian.org/debian/ wheezy-updates main
deb-src http://ftp.jp.debian.org/debian/ wheezy-updates main

# apt-get update
# apt-cache search utils | grep "^dns\|^bind"dnsmasq-utils - Utilities for manipulating DHCP leases
bind9utils - BIND 用ユーティリティ
dnsutils - BIND に付属のクライアント
# apt-get install -y vim dnsutils ntp ntpdate fail2ban chkconfig

■上位NTPサーバをDNSクライアントで確認。
 使えるのは「ntp1.sakura.ad.jp」のみ。

# dig ntp.sakura.ne.jp | grep ^ntp
ntp.sakura.ne.jp.	3600	IN	A	202.181.99.21

# dig ntp1.sakura.ad.jp | grep ^ntp
ntp1.sakura.ad.jp.	3578	IN	A	210.188.224.14

# ntpdate ntp.sakura.ne.jp
27 Aug 21:58:29 ntpdate[5163]: no server suitable for synchronization found

# ntpdate ntp1.sakura.ad.jp
27 Aug 21:58:40 ntpdate[5164]: adjust time server 210.188.224.14 offset 0.000039 sec

■NTPサーバを設定。

# grep -v "^#\|^\$" /etc/ntp.conf 
driftfile /var/lib/ntp/ntp.drift
statistics loopstats peerstats clockstats
filegen loopstats file loopstats type day enable
filegen peerstats file peerstats type day enable
filegen clockstats file clockstats type day enable
server ntp1.sakura.ad.jp iburst
restrict default ignore
restrict -6 default ignore
restrict 127.0.0.1
restrict ::1
restrict ntp1.sakura.ad.jp kod notrap nomodify nopeer noquery
disable monitor

# /etc/init.d/ntp restart

■stratumが16より小さく、leapが00になるまでしばし待つ。

# watch -d -n 1 'ntpq -pn -c rv'
Every 1.0s: ntpq -pn -c rv                              Wed Aug 27 22:03:34 2014

     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
*210.188.224.14  133.243.238.163  2 u   10   64    3    0.864   -0.032   0.139
associd=0 status=0614 leap_none, sync_ntp, 1 event, freq_mode,
version="ntpd 4.2.6p5@1.2349-o Sat May 12 09:54:55 UTC 2012 (1)",
processor="x86_64", system="Linux/3.2.0-4-amd64", leap=00, stratum=3,
precision=-17, rootdelay=2.856, rootdisp=946.116, refid=210.188.224.14,
reftime=d7a8555e.51b5ffc5  Wed, Aug 27 2014 22:02:22.319,
clock=d7a855a6.da3fbca6  Wed, Aug 27 2014 22:03:34.852, peer=2516, tc=6,
mintc=3, offset=0.127, frequency=0.001, sys_jitter=0.000,
clk_jitter=0.045, clk_wander=0.000

■内部はloからのみ参照出来ること。
 「-d」オプション無しだと「123/UDP」同士で通信。
 「-d」オプションありだと「123/UDP」の対向はハイポートを使う。

# ntpdate 127.0.0.1
27 Aug 22:04:20 ntpdate[5491]: the NTP socket is in use, exiting

# ntpdate -d 127.0.0.1 | tail -1
27 Aug 22:05:59 ntpdate[5695]: adjust time server 127.0.0.1 offset -0.000028 sec

■内部の外部と接続するインターフェイスからは時刻情報を取得出来ないこと。
 配下への配信も、外部からの参照も出来ないこと。

# ntpdate -d `hostname -s` | tail -1
27 Aug 22:08:30 ntpdate[6288]: no server suitable for synchronization found

■DNS設定は2週間の無料期間が過ぎてからなので、今回はスルー。
 fail2banもDNSサーバ用には構成しない。

■ssh用のfail2ban設定
 ※sshの変更先ポートが「10022」の場合

# grep "^\[ssh" -A 7 /etc/fail2ban/jail.conf 
[ssh]

enabled  = true
port     = ssh,10022
filter   = sshd
logpath  = /var/log/auth.log
maxretry = 6

--
[ssh-ddos]

enabled  = true
port     = ssh,10022
filter   = sshd-ddos
logpath  = /var/log/auth.log
maxretry = 6

# /etc/init.d/fail2ban restart

■メールサーバはpostfixに変更。ひとまずシステムメールとして使えるようにしておく。

# netstat -anp | grep 25
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      2350/exim4      
tcp6       0      0 ::1:25                  :::*                    LISTEN      2350/exim4      

# apt-get install -y postfix procmail

■postfixのfail2ban設定

# grep "^\[postfix" -A 7 /etc/fail2ban/jail.conf 
[postfix]

enabled  = true
port     = smtp,ssmtp
filter   = postfix
logpath  = /var/log/mail.log

# /etc/init.d/fail2ban restart

■スパム対策

# apt-get install -y spamassassin
# sed -i s/"\(ENABLED=\)0"/"\11"/ /etc/default/spamassassin
# grep -B 1 ENABLE /etc/default/spamassassin
# Change to one to enable spamd
ENABLED=1

# grep TextCat /etc/mail/spamassassin/*.pre
/etc/mail/spamassassin/v310.pre:# TextCat - language guesser
/etc/mail/spamassassin/v310.pre:#loadplugin Mail::SpamAssassin::Plugin::TextCat

# sed -i s/"#\(loadplugin Mail::SpamAssassin::Plugin::TextCat\)"/"\1"/ /etc/mail/spamassassin/v310.pre
# grep TextCat /etc/mail/spamassassin/v310.pre
# TextCat - language guesser
loadplugin Mail::SpamAssassin::Plugin::TextCat
# /etc/init.d/spamassassin start
spamd.

■procmailrcの設定

# cat /etc/procmailrc 
LOGFILE=$HOME/.procmail.log
LOCKFILE=$HOME/.lockfile
MAILDIR=$HOME/

#:0
#* ^Subject:.*iso-2022-jp
#* ^Subject:.*\/.*
#* ? echo "$MATCH" | nkf -me | egrep '未承諾広告'
#spam/.

# X-Spam ヘッダが無ければspamassassinに渡す
:0fw
*!^X-Spam.*
|spamassassin

# X-Spam-StatusがYesなら~/spam/ に移動
:0
* ^X-Spam-Status: Yes
$MAILDIR/.spam/

■「.spam」フォルダの作成

# mkdir /etc/skel/.spam
# mkdir /root/.spam;mkdir /home/labunix/.spam

■postfixとprocmailrc連携の設定

# dpkg-reconfigure postfix
[ ok ] Stopping Postfix Mail Transport Agent: postfix.
setting synchronous mail queue updates: false
setting myorigin
setting destinations: XXXXXX.sakura.ne.jp, localhost.sakura.ne.jp, localhost
setting relayhost: 
setting mynetworks: 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
setting mailbox_size_limit: 0
setting recipient_delimiter: +
setting inet_interfaces: all
setting inet_protocols: ipv4

Postfix is now set up with the changes above.  If you need to make changes, edit
/etc/postfix/main.cf (and others) as needed.  To view Postfix configuration
values, see postconf(1).

After modifying main.cf, be sure to run '/etc/init.d/postfix reload'.

Running newaliases
[ ok ] Stopping Postfix Mail Transport Agent: postfix.
[ ok ] Starting Postfix Mail Transport Agent: postfix.

■テストメール

# echo "test" | mail -s "test" `whoami`@`hostname -f`
# grep "^X-S" /var/spool/mail/labunix 
X-Spam-Checker-Version: SpamAssassin 3.3.2 (2011-06-06) on
X-Spam-Level: 
X-Spam-Status: No, score=0.4 required=5.0 tests=NO_DNS_FOR_FROM,NO_RELAYS

■ウイルス対策

# apt-get install -y clamav-daemon
# /etc/init.d/clamav-freshclam stop && freshclam && /etc/init.d/clamav-freshclam start
[ ok ] Stopping ClamAV virus database updater: freshclam.
ClamAV update process started at Wed Aug 27 22:22:23 2014
nonblock_recv: recv timing out (30 secs)
WARNING: getfile: Download interrupted: Operation now in progress (IP: 203.212.42.128)
WARNING: Can't download main.cvd from db.local.clamav.net
Trying again in 5 secs...
ClamAV update process started at Wed Aug 27 23:14:42 2014
Downloading main.cvd [100%]
main.cvd updated (version: 55, sigs: 2424225, f-level: 60, builder: neo)
Downloading daily.cvd [100%]
daily.cvd updated (version: 19312, sigs: 1094307, f-level: 63, builder: jesler)
Downloading bytecode.cvd [100%]
bytecode.cvd updated (version: 242, sigs: 46, f-level: 63, builder: dgoddard)
Database updated (3518578 signatures) from db.local.clamav.net (IP: 218.44.253.75)
WARNING: Clamd was NOT notified: Can't connect to clamd through /var/run/clamav/clamd.ctl: No such file or directory
[ ok ] Starting ClamAV virus database updater: freshclam.

■ウイルスチェック

# clamscan --infected --remove --recursive /tmp

----------- SCAN SUMMARY -----------
Known viruses: 3513037
Engine version: 0.98.4
Scanned directories: 1
Scanned files: 0
Infected files: 0
Data scanned: 0.00 MB
Data read: 0.00 MB (ratio 0.00:1)
Time: 8.918 sec (0 m 8 s)

■メールウイルス対策

# apt-get install -y amavisd-new
# postconf -e "soft_bounce = yes"
# /etc/init.d/postfix reload
[ ok ] Reloading Postfix configuration...done.

# tail -30 /etc/postfix/master.cf 
amavisfeed unix    -       -       n        -      2     lmtp
  -o lmtp_data_done_timeout=1200
  -o lmtp_send_xforward_command=yes
  -o lmtp_tls_note_starttls_offer=no
amavisfeed unix    -       -       n       -       2     smtp
  -o smtp_data_done_timeout=1200
  -o smtp_send_xforward_command=yes
  -o smtp_tls_note_starttls_offer=no
127.0.0.1:10025 inet n    -       n       -       -     smtpd
  -o content_filter=
  -o smtpd_delay_reject=no
  -o smtpd_client_restrictions=permit_mynetworks,reject
  -o smtpd_helo_restrictions=
  -o smtpd_sender_restrictions=
  -o smtpd_recipient_restrictions=permit_mynetworks,reject
  -o smtpd_data_restrictions=reject_unauth_pipelining
  -o smtpd_end_of_data_restrictions=
  -o smtpd_restriction_classes=
  -o mynetworks=127.0.0.0/8
  -o smtpd_error_sleep_time=0
  -o smtpd_soft_error_limit=1001
  -o smtpd_hard_error_limit=1000
  -o smtpd_client_connection_count_limit=0
  -o smtpd_client_connection_rate_limit=0
  -o receive_override_options=no_header_body_checks,no_unknown_recipient_checks,no_milters
  -o local_header_rewrite_clients=
  -o smtpd_milters=
  -o local_recipient_maps=
  -o relay_recipient_maps=

# postconf -e 'content_filter=amavisfeed:[127.0.0.1]:10024'
# /etc/init.d/postfix reload
# netstat -an --program | grep 1002[45]
tcp        0      0 127.0.0.1:10024         0.0.0.0:*               LISTEN      26280/amavisd-new (
tcp        0      0 127.0.0.1:10025         0.0.0.0:*               LISTEN      24018/master    

■メールウイルススキャンをamavis側で有効にする

# grep -A 1 checks_maps /etc/amavis/conf.d/15-content_filter_mode
@bypass_virus_checks_maps = (
   \%bypass_virus_checks, \@bypass_virus_checks_acl, \$bypass_virus_checks_re);
--
@bypass_spam_checks_maps = (
   \%bypass_spam_checks, \@bypass_spam_checks_acl, \$bypass_spam_checks_re);

# /etc/init.d/amavis restart
Stopping amavisd: amavisd-new.
Starting amavisd: amavisd-new.
# /etc/init.d/postfix restart
[ ok ] Stopping Postfix Mail Transport Agent: postfix.
[ ok ] Starting Postfix Mail Transport Agent: postfix.
# /etc/init.d/clamav-daemon restart
[....] Stopping ClamAV daemon: clamdNo clamd found running; none killed.
. ok 
[ ok ] Starting ClamAV daemon: clamd .

■メール送信テスト

$ echo "test" | mail -s "test" `whoami`@`hostname -f`
# grep "^X-[SV]" /var/spool/mail/labunix  | tail -3
X-Spam-Level: 
X-Spam-Status: No, score=0.2 required=5.0 tests=ALL_TRUSTED,DKIM_ADSP_NXDOMAIN,
X-Virus-Scanned: Debian amavisd-new at XXXXX.sakura.ne.jp

■起動時のデーモンを確認

# runlevel
N 2
# chkconfig --list | grep "2\:on"
acpid                     0:off  1:off  2:on   3:on   4:on   5:on   6:off
amavis                    0:off  1:off  2:on   3:on   4:on   5:on   6:off
bootlogs                  0:off  1:on   2:on   3:on   4:on   5:on   6:off
clamav-daemon             0:off  1:off  2:on   3:on   4:on   5:on   6:off
clamav-freshclam          0:off  1:off  2:on   3:on   4:on   5:on   6:off
cron                      0:off  1:off  2:on   3:on   4:on   5:on   6:off
exim4                     0:off  1:off  2:on   3:on   4:on   5:on   6:off
fail2ban                  0:off  1:off  2:on   3:on   4:on   5:on   6:off
motd                      0:off  1:on   2:on   3:on   4:on   5:on   6:off
ntp                       0:off  1:off  2:on   3:on   4:on   5:on   6:off
postfix                   0:off  1:off  2:on   3:on   4:on   5:on   6:off
rc.local                  0:off  1:off  2:on   3:on   4:on   5:on   6:off
rmnologin                 0:off  1:off  2:on   3:on   4:on   5:on   6:off
rsyslog                   0:off  1:off  2:on   3:on   4:on   5:on   6:off
spamassassin              0:off  1:off  2:on   3:on   4:on   5:on   6:off
ssh                       0:off  1:off  2:on   3:on   4:on   5:on   6:off

■exim4を削除

# apt-get purge -y exim4
# chkconfig -d exim4
exim4                     0:off  1:off  2:off  3:off  4:off  5:off  6:off

■以下になった。

# chkconfig --list | grep "2\:on"
acpid                     0:off  1:off  2:on   3:on   4:on   5:on   6:off
amavis                    0:off  1:off  2:on   3:on   4:on   5:on   6:off
bootlogs                  0:off  1:on   2:on   3:on   4:on   5:on   6:off
clamav-daemon             0:off  1:off  2:on   3:on   4:on   5:on   6:off
clamav-freshclam          0:off  1:off  2:on   3:on   4:on   5:on   6:off
cron                      0:off  1:off  2:on   3:on   4:on   5:on   6:off
fail2ban                  0:off  1:off  2:on   3:on   4:on   5:on   6:off
motd                      0:off  1:on   2:on   3:on   4:on   5:on   6:off
ntp                       0:off  1:off  2:on   3:on   4:on   5:on   6:off
postfix                   0:off  1:off  2:on   3:on   4:on   5:on   6:off
rc.local                  0:off  1:off  2:on   3:on   4:on   5:on   6:off
rmnologin                 0:off  1:off  2:on   3:on   4:on   5:on   6:off
rsyslog                   0:off  1:off  2:on   3:on   4:on   5:on   6:off
spamassassin              0:off  1:off  2:on   3:on   4:on   5:on   6:off
ssh                       0:off  1:off  2:on   3:on   4:on   5:on   6:off

■余談
 書き込み性能はスルーするとして、
 ext4とスワップパーティションの読み込み性能をチェック
 fdiskコマンドを使う箇所はGPTパーティションだと出来ない。

# fdisk -l /dev/vda | sed s/"\*"// | grep ^/dev | awk '{print $1,$5}' 
/dev/vda1 83
/dev/vda2 82
/dev/vda3 83
/dev/vda4 5
/dev/vda5 83

# apt-get install -y hdparm
# fdisk -l /dev/vda | grep "^/dev.* 8[23] " | awk '{print $1}' | for list in `xargs`;do hdparm -t "$list";done

/dev/vda1:
 Timing buffered disk reads: 486 MB in  1.23 seconds = 394.74 MB/sec

/dev/vda2:
 Timing buffered disk reads: 1774 MB in  3.00 seconds = 590.78 MB/sec

/dev/vda3:
 Timing buffered disk reads: 1620 MB in  3.00 seconds = 539.64 MB/sec

/dev/vda5:
 Timing buffered disk reads: 1640 MB in  3.00 seconds = 546.18 MB/sec

■CPUとメモリの使用率

# top -b -n 1 | head -5
top - 23:48:28 up  2:23,  2 users,  load average: 0.00, 0.02, 0.05
Tasks:  86 total,   1 running,  85 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.5 us,  0.2 sy,  0.0 ni, 99.1 id,  0.0 wa,  0.0 hi,  0.0 si,  0.1 st
KiB Mem:   2061060 total,   764664 used,  1296396 free,     1692 buffers
KiB Swap: 13671420 total,        0 used, 13671420 free,   216440 cached

# free -m
             total       used       free     shared    buffers     cached
Mem:          2012        744       1268          0          0        210
-/+ buffers/cache:        533       1479
Swap:        13350          0      13350

■CPU使用率が0.0%より大きいか、メモリ使用率が1%より大きいプロセスの一覧

# ps axo pid,cmd,%cpu,%mem | awk '($NF>1)||($(NF-1)>0.0){print}'
 2386 sshd: labunix@pts/0          0.1  0.0
22506 /usr/sbin/spamd --create-pr  0.0  2.9
22507 spamd child                  0.0  2.8
22508 spamd child                  0.0  2.8
26843 /usr/bin/freshclam -d --qui  0.1  0.1
28201 /usr/sbin/amavisd-new (mast  0.1  4.7
28202 /usr/sbin/amavisd-new (ch1-  0.0  4.8
28203 /usr/sbin/amavisd-new (virg  0.0  4.7
29388 /usr/sbin/clamd -c /etc/cla  0.0 13.5

■開いてるポートはsshとmailのみ。
 OB25やiptablesはとりあえず後にしておこう。

# apt-get install -y nmap
# nmap -sT `hostname -s`

Starting Nmap 6.00 ( http://nmap.org ) at 2014-08-27 23:59 JST
Nmap scan report for XXXXX (XXX.XXX.XXX.XXX)
Host is up (0.0011s latency).
rDNS record for XXX.XXX.XXX.XXX: XXXXX.sakura.ne.jp
Not shown: 998 closed ports
PORT     STATE SERVICE
25/tcp   open  smtp
XX022/tcp open  oa-system

Nmap done: 1 IP address (1 host up) scanned in 0.17 seconds

■後片付け

# apt-get purge -y nmap hdparm
# for opt in update upgrade autoremove autoclean;do apt-get $opt -y -f ;done
# dpkg -l | grep ^rc | awk '{print $2}' | apt-get purge -y `xargs`
# for opt in update upgrade autoremove autoclean;do apt-get $opt -y -f ;done
# shutdown -r now && exit