横井?

サーバー"OS編" 

OS入手 

OS選択の基準としては自分の必要な機能があるものはどれか、
サポートはいつまで続くのかを考えてその中で最良なものを選択する。
OSを開発しようとしない限りは安定版で最新のものを使っておけば問題はないであろう。
※各OSのリリース日とサポート終了日を表にまとめてみた

今回はCentOS7を例として手順を説明する。

(1)CentOSのダウンロードページからインストールディスクイメージ(CentOS-7-x86_64-Minimal-xxxx.iso)をダウンロードする。

(2)ダウンロードしたディスクイメージが破損していないかチェックするために使用するSHA256SUMをディスクイメージと同じフォルダにダウンロードする。 ※SHA256SUMのダウンロードは、ブラウザがChromeの場合、リンク右クリックで「名前を付けてリンク先を保存」でダウンロードする

(3)ダウンロードしたディスクイメージが破損していないかチェックする。

コマンドプロンプトを起動し以下の3つのコマンドを実行する

cd C:\Users\xxxxxxxx\Downloads
certutil -hashfile CentOS-7-x86_64-Minimal-2009.iso SHA256
type sha256sum.txt | findstr Minimal

コマンド実行後以下の図のようになればよい。

hash.PNG

(4)ダウンロードしたインストールディスクイメージをメディアへ書き込む。 ダウンロードしたディスクイメージを右クリック⇒「ディスク イメージの書き込み」または「プログラムから開く」⇒「Windows ディスク イメージ書き込みツール」を選択してインストールディスクイメージをメディアへ書き込む。
※参考サイト
Windows 7/8.1/10でISO/IMGファイルをCD/DVD-Rに書き込む

OSインストール 

CentOSのインストールディスクをディスクドライブにセットして再起動する。 ※BIOSの設定で1番最初にディスクドライブからブートできるようになっている必要がある CentOSインストール実行 空ENTER

言語選択 「日本語」を選択して「続行」

ネットワーク設定 「ネットワークとホスト名」

「設定」

「IPv4のセッティング」タブ 「方式」で「手動」を選択 「追加」ボタン 「アドレス」にサーバーのIPアドレス(例:192.168.1.30)を入力 「ネットマスク」にサーバーのネットマスク(例:24)を入力 「ゲートウェイ」にルーターのIPアドレス(例:192.168.1.1)を入力 「DNSサーバー」にルーターのIPアドレス(例:192.168.1.1)を入力 「保存」ボタン

「オン」 「ホスト名」にサーバーのホスト名(例:centos.centossrv.com)を入力 「完了」ボタン

インストール先設定 「インストール先」

「完了」ボタン

インストール開始 「インストールの開始」

root(管理ユーザー)パスワード設定 「rootパスワード」

「rootパスワード」、「確認」にroot(管理ユーザー)パスワードを入力 「完了」ボタン

インストール完了 「再起動」

CentOS 7起動後の画面

CentOS7初期設定 

(1)rootでのログイン&ログアウト 

centos login: root ← ログインユーザー名としてrootと入力 Password:  ← rootのパスワード応答(表示はされない)

[root@centos ~]#  ← rootでログインした状態

[root@centos ~]# exit ← ログアウト

centos login: ← ログアウトした状態

(2)一般ユーザー(パンピー)の作成&削除(例として一般ユーザー名をcentosとする)&aname(ja76455e,super,full,nouserselect){ };

[root@centos ~]# useradd centos ← 一般ユーザーcentosの作成

[root@centos ~]# passwd centos ← centosのパスワード設定 ユーザー centos のパスワードを変更。 新しいパスワード: ← centosのパスワード応答 新しいパスワードを再入力してください: ← centosのパスワード応答(確認) passwd: 全ての認証トークンが正しく更新できました。

[root@centos ~]# userdel -r centos ← 一般ユーザーcentosの削除

(3)一般ユーザーからrootになる 

[centos@centos ~]$  ← centosという名前の一般ユーザーでログインしている状態

[centos@centos ~]$ su - ← suコマンドでrootになる(-を忘れずに) パスワード: ← rootのパスワード応答

[root@centos ~]#  ← rootになった

[root@centos ~]# exit ← rootから一般ユーザーに戻る

[centos@centos ~]$  ← centosに戻った ※rootは制限なくなんでも出来てしまい、誤操作により重要なファイルを削除してしまったりすることがあるため、基本は一般ユーザーでログインし、root権限が必要な操作を行う場合のみ、suコマンドでrootになるようにする。

(4)rootになれるユーザーを管理者のみにする 

例として、管理者用の一般ユーザー名をcentosとする [root@centos ~]# usermod -G wheel centos ← 管理者ユーザーをwheelグループに追加

[root@centos ~]# vi /etc/pam.d/su※Linuxのテキストデエディタ、viエディタの使い方

#auth required pam_wheel.so use_uid ↓ auth required pam_wheel.so use_uid ← コメント解除

管理者用一般ユーザーからはrootになれて、管理者以外の一般ユーザーからはrootになれないことを確認

(5)sshでのrootログインを無効にする 

Linuxにおいて神であるrootでログインできるのは色々とマズいのでsshだと一般ユーザでログインするようにしましょう

rootログインを無効に

# vim /etc/ssh/sshd_config yesをnoに書き換える

  1. PermitRootLogin no sshdを再起動

# systemctl restart sshd

(6)パッケージ管理システム設定 

RPMパッケージのインストール・アンインストールを行うyumの初期設定を行う [root@centos ~]# yum -y update ← インストール済パッケージの一括アップデート ※大量のパッケージのダウンロード/アップデートを行うため時間がかかる

[root@centos ~]# yum -y install yum-cron ← yum-cronインストール

[root@centos ~]# vi /etc/yum/yum-cron.conf ← yum-cron設定

# Whether updates should be applied when they are available. Note

# that download_updates must also be yes for the update to be applied. apply_updates = yes ← ダウンロード&アップデートを自動で行うようにする

[root@centos ~]# systemctl start yum-cron ← パッケージ自動更新起動

[root@centos ~]# systemctl enable yum-cron ← パッケージ自動更新自動起動設定

[root@centos ~]# yum -y groupinstall base "Development tools" ← ベース、開発ツールパッケージ群インストール

(7)root宛メールを転送する 

システムからroot宛に重要なメールが送られてくるので、root宛メールを普段使用しているメールアドレス宛に転送するようにする メールサーバーのOP25B対策(Postfix編)実施

[root@centos ~]# sed -i '/^root:/d' /etc/aliases ← 旧root宛メール転送設定削除

[root@centos ~]# echo "root: hoge@nifty.com" >> /etc/aliases  ← root宛メールを普段使用しているメールアドレス(例:hoge@nifty.com)宛に転送する

[root@centos ~]# newaliases ← 転送設定反映

[root@centos ~]# echo test|mail root ← テストメールをroot宛に送信する

テストメールが転送先メールアドレス宛に届いていることを確認する

(8)SELinuxの無効化 

これを行うことで使えなかったサービスなどが使えるようになるらしい(・・?)(本当かな?)

[root@centos ~]# getenforce ← SELinux状態確認 Enforcing ← SELinux有効

[root@centos ~]# setenforce 0 ← SELinux無効化

[root@centos ~]# getenforce ← SELinux状態確認 Permissive ← SELinux無効

[root@centos ~]# vi /etc/sysconfig/selinux ← SELinux設定ファイル編集 SELINUX=enforcing ↓ SELINUX=disabled ← システム起動時にSELinuxを無効化

(9)ファイアウォール停止※必要な場合のみ 

ルーターでブロックするためファイアウォールが不要な場合はファイアウォールを停止する [root@centos ~]# systemctl stop firewalld ← ファイアウォール停止

[root@centos ~]# systemctl disable firewalld ← ファイアウォール自動起動解除

(10)システムの停止または再起動 

[root@centos ~]# halt ← システム停止する場合

[root@centos ~]# reboot ← システム再起動する場合 ※その他のLinuxコマンドについては、Linuxコマンド集を参照

サーバー"セキュリティ編" 

ソフトウェアアップデートand初期セキュリティ 

最強のセキュリティ対策!!!!!!(定期的に実行してね(*´ω`*)) 

                                                                                                                  

yum update

                                                                                                                  

Apache Update and EPEL導入 

iusを使う yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm yum --enablerepo=epel -y install nghttp2 yum -y install mailcap yum install https://repo.ius.io/ius-release-el7.rpm

yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm yum --enablerepo=epel -y install nghttp2 yum -y install mailcap yum install https://repo.ius.io/ius-release-el7.rpm yum updateで自動でアップデートされないように、下記のファイルを修正。 /etc/yum.repos.d/icu.repo のenabled=0をゼロとする。

yum --disablerepo=base,extras,updates --enablerepo=ius,epel -y update systemctl stop httpd yum remove httpd yum remove httpd-tools yum --disablerepo=base,extras,updates --enablerepo=ius,epel install httpd yum -y install openldap-devel expat-devel yum --disablerepo=base,extras,updates --enablerepo=ius,epel install mod_ssl yum --disablerepo=base,extras,updates --enablerepo=ius,epel install httpd-devel yum --disablerepo=base,extras,updates --enablerepo=ius,epel install httpd-devel --skip-broken

systemctl start httpd systemctl enable httpd cat /dev/null > /etc/httpd/conf.d/welcome.conf cat /dev/null > /etc/httpd/conf.d/autoindex.conf systemctl restart httpd.service

ssh関連 

ssh導入方法(一応)

公開鍵認証方式関連の説明はあるが実行していない。その代わり、sshを無効にしている。

systemctl stop sshd.service

nkfインストール 

sudo yum install -y nkf --enablerepo=epel

ファイル改竄検知システム導入(Tripwire) 

■Tripwireインストール EPELリポジトリ導入(EPEL)を参照してEPELリポジトリを導入する

[root@centos ~]# yum -y install tripwire ← tripwireインストール

[root@centos ~]# tripwire-setup-keyfiles ← tripwire初期設定


The Tripwire site and local passphrases are used to sign a variety of files, such as the configuration, policy, and database files.

Passphrases should be at least 8 characters in length and contain both letters and numbers.

See the Tripwire manual for more information.


Creating key files...

(When selecting a passphrase, keep in mind that good passphrases typically have upper and lower case letters, digits and punctuation marks, and are at least 8 characters in length.)

Enter the site keyfile passphrase: ← 任意のサイトパスフレーズ応答 Verify the site keyfile passphrase: ← 任意のサイトパスフレーズ応答(確認) Generating key (this may take several minutes)...Key generation complete.

(When selecting a passphrase, keep in mind that good passphrases typically have upper and lower case letters, digits and punctuation marks, and are at least 8 characters in length.)

Enter the local keyfile passphrase: ← 任意のローカルパスフレーズ応答 Verify the local keyfile passphrase: ← 任意のローカルパスフレーズ応答(確認) Generating key (this may take several minutes)...Key generation complete.


Signing configuration file... Please enter your site passphrase: ← サイトパスフレーズ応答 Wrote configuration file: /etc/tripwire/tw.cfg

A clear-text version of the Tripwire configuration file: /etc/tripwire/twcfg.txt has been preserved for your inspection. It is recommended that you move this file to a secure location and/or encrypt it in place (using a tool such as GPG, for example) after you have examined it.


Signing policy file... Please enter your site passphrase: ← サイトパスフレーズ応答 Wrote policy file: /etc/tripwire/tw.pol

A clear-text version of the Tripwire policy file: /etc/tripwire/twpol.txt has been preserved for your inspection. This implements a minimal policy, intended only to test essential Tripwire functionality. You should edit the policy file to describe your system, and then use twadmin to generate a new signed copy of the Tripwire policy.

Once you have a satisfactory Tripwire policy file, you should move the clear-text version to a secure location and/or encrypt it in place (using a tool such as GPG, for example).

Now run "tripwire --init" to enter Database Initialization Mode. This reads the policy file, generates a database based on its contents, and then cryptographically signs the resulting database. Options can be entered on the command line to specify which policy, configuration, and key files are used to create the database. The filename for the database can be specified as well. If no options are specified, the default values from the current configuration file are used.

■Tripwire設定 (1)Tripwire設定 [root@centos ~]# vi /etc/tripwire/twcfg.txt ← Tripwire設定ファイル(テキスト版)作成 LOOSEDIRECTORYCHECKING =true ← ファイル変更時に所属ディレクトリの変更を通知しないようにする

REPORTLEVEL =4 ← リポートレベルを変更する

[root@centos ~]# twadmin -m F -c /etc/tripwire/tw.cfg -S /etc/tripwire/site.key /etc/tripwire/twcfg.txt ← Tripwire設定ファイル(暗号署名版)作成 Please enter your site passphrase: ← サイトパスフレーズ応答 Wrote configuration file: /etc/tripwire/tw.cfg

[root@centos ~]# rm -f /etc/tripwire/twcfg.txt ← Tripwire設定ファイル(テキスト版)削除

※Tripwire設定ファイル(テキスト版)を復元する場合 [root@centos ~]# twadmin -m f -c /etc/tripwire/tw.cfg > /etc/tripwire/twcfg.txt

(2)ポリシーファイル設定 Tripwireは、ポリシーファイルを元に作成したデータベースと、現在のファイル状態を比較することにより、ファイルが変更されたかどうかを検知するが、デフォルトのポリシーファイルでは存在しないファイルのチェックが有効になっていたり、逆に存在するファイルのチェックが無効になっていたりするため、存在しないファイルのチェックを無効に、存在するファイルのチェックを有効にするPerlスクリプトを作成して、ポリシーファイルを最適化する。 [root@centos ~]# vi /etc/tripwire/twpolmake.pl ← ポリシーファイル最適化スクリプト作成

#!/usr/bin/perl

# Tripwire Policy File customize tool

# ----------------------------------------------------------------

# Copyright (C) 2003 Hiroaki Izumi

# This program is free software; you can redistribute it and/or

# modify it under the terms of the GNU General Public License

# as published by the Free Software Foundation; either version 2

# of the License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,

# but WITHOUT ANY WARRANTY; without even the implied warranty of

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the

# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License

# along with this program; if not, write to the Free Software

# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

# ----------------------------------------------------------------

# Usage:

# perl twpolmake.pl {Pol file}

# ----------------------------------------------------------------

# $POLFILE=$ARGV[0];

open(POL,"$POLFILE") or die "open error: $POLFILE" ; my($myhost,$thost) ; my($sharp,$tpath,$cond) ; my($INRULE) = 0 ;

while (<POL>) {

   chomp;
   if (($thost) = /^HOSTNAME\s*=\s*(.*)\s*;/) {
       $myhost = `hostname` ; chomp($myhost) ;
       if ($thost ne $myhost) {
           $_="HOSTNAME=\"$myhost\";" ;
       }
   }
   elsif ( /^{/ ) {
       $INRULE=1 ;
   }
   elsif ( /^}/ ) {
       $INRULE=0 ;
   }
   elsif ($INRULE == 1 and ($sharp,$tpath,$cond) = /^(\s*\#?\s*)(\/\S+)\b(\s+->\s+.+)$/) {
       $ret = ($sharp =~ s/\#//g) ;
       if ($tpath eq '/sbin/e2fsadm' ) {
           $cond =~ s/;\s+(tune2fs.*)$/; \#$1/ ;
       }
       if (! -s $tpath) {
           $_ = "$sharp#$tpath$cond" if ($ret == 0) ;
       }
       else {
           $_ = "$sharp$tpath$cond" ;
       }
   }
   print "$_\n" ;

} close(POL) ;

[root@centos ~]# perl /etc/tripwire/twpolmake.pl /etc/tripwire/twpol.txt > /etc/tripwire/twpol.txt.new ← ポリシーファイル最適化

[root@centos ~]# echo ! "/var/lib/tripwire/`hostname`.twd ;" >> /etc/tripwire/twpol.txt.new ← Tripwireデータベース自体をチェック対象外にする

[root@centos ~]# echo ! "/tmp/tripwire.log ;" >> /etc/tripwire/twpol.txt.new ← Tripwireログをチェック対象外にする※後述のTripwire定期自動実行スクリプトで使用

[root@centos ~]# twadmin -m P -c /etc/tripwire/tw.cfg -p /etc/tripwire/tw.pol -S /etc/tripwire/site.key /etc/tripwire/twpol.txt.new ← 最適化済ポリシーファイルを元にポリシーファイル(暗号署名版)作成 Please enter your site passphrase: ← サイトパスフレーズ応答 Wrote policy file: /etc/tripwire/tw.pol

[root@centos ~]# rm -f /etc/tripwire/twpol.txt* ← ポリシーファイル(テキスト版)削除

※ポリシーファイル(テキスト版)を復元する場合 [root@centos ~]# twadmin -m p -c /etc/tripwire/tw.cfg -p /etc/tripwire/tw.pol -S /etc/tripwire/site.key > /etc/tripwire/twpol.txt

(3)データベース作成 [root@centos ~]# tripwire -m i -s -c /etc/tripwire/tw.cfg ← Tripwireデータベース作成 Please enter your local passphrase: ← ローカルパスフレーズ応答

■Tripwire確認 [root@centos ~]# tripwire -m c -s -c /etc/tripwire/tw.cfg ← Tripwireチェック実行 Open Source Tripwire(R) 2.4.3.1 Integrity Check Report

Report generated by: root Report created on: 2017年01月26日 10時33分26秒 Database last updated on: Never

=============================================================================== Report Summary: ===============================================================================

Host name: centos.centossrv.com Host IP address: xxx.xxx.xxx.xxx Host ID: None Policy file used: /etc/tripwire/tw.pol Configuration file used: /etc/tripwire/tw.cfg Database file used: /var/lib/tripwire/centos.centossrv.com.twd Command line used: tripwire -m c -s -c /etc/tripwire/tw.cfg

=============================================================================== Rule Summary: ===============================================================================


 Section: Unix File System

 Rule Name                       Severity Level    Added    Removed  Modified
 ---------                       --------------    -----    -------  --------
 User binaries                   66                0        0        0
 Tripwire Binaries               100               0        0        0
 Libraries                       66                0        0        0
 Operating System Utilities      100               0        0        0
 File System and Disk Administraton Programs
                                 100               0        0        0
 Kernel Administration Programs  100               0        0        0
 Networking Programs             100               0        0        0
 System Administration Programs  100               0        0        0
 Hardware and Device Control Programs
                                 100               0        0        0
 System Information Programs     100               0        0        0
 Application Information Programs
                                 100               0        0        0
 (/sbin/rtmon)
 Critical Utility Sym-Links      100               0        0        0
 Shell Binaries                  100               0        0        0
 Critical system boot files      100               0        0        0
 Tripwire Data Files             100               0        0        0
 System boot changes             100               0        0        0
 OS executables and libraries    100               0        0        0
 Critical configuration files    100               0        0        0
 Security Control                100               0        0        0
 Login Scripts                   100               0        0        0
 Root config files               100               0        0        0
 Invariant Directories           66                0        0        0
 Temporary directories           33                0        0        0
 Critical devices                100               0        0        0
 (/proc/kcore)

Total objects scanned: 47479 Total violations found: 0 ← 変更なし

=============================================================================== Object Summary: ===============================================================================


# Section: Unix File System


No violations.

=============================================================================== Error Report: ===============================================================================

No Errors


End of report *** 

Open Source Tripwire 2.4 Portions copyright 2000 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. This software comes with ABSOLUTELY NO WARRANTY; for details use --version. This is free software which may be redistributed or modified only under certain conditions; see COPYING for details. All rights reserved.

[root@centos ~]# echo test > test.txt ← 試しにテストファイルを作成する

[root@centos ~]# tripwire -m c -s -c /etc/tripwire/tw.cfg ← Tripwireチェック再実行 Open Source Tripwire(R) 2.4.3.1 Integrity Check Report

Report generated by: root Report created on: 2017年01月26日 10時37分34秒 Database last updated on: Never

=============================================================================== Report Summary: ===============================================================================

Host name: centos.centossrv.com Host IP address: xxx.xxx.xxx.xxx Host ID: None Policy file used: /etc/tripwire/tw.pol Configuration file used: /etc/tripwire/tw.cfg Database file used: /var/lib/tripwire/centos.centossrv.com.twd Command line used: tripwire -m c -s -c /etc/tripwire/tw.cfg

=============================================================================== Rule Summary: ===============================================================================


 Section: Unix File System

 Rule Name                       Severity Level    Added    Removed  Modified
 ---------                       --------------    -----    -------  --------
 User binaries                   66                0        0        0
 Tripwire Binaries               100               0        0        0
 Libraries                       66                0        0        0
 Operating System Utilities      100               0        0        0
 File System and Disk Administraton Programs
                                 100               0        0        0
 Kernel Administration Programs  100               0        0        0
 Networking Programs             100               0        0        0
 System Administration Programs  100               0        0        0
 Hardware and Device Control Programs
                                 100               0        0        0
 System Information Programs     100               0        0        0
 Application Information Programs
                                 100               0        0        0
 (/sbin/rtmon)
 Critical Utility Sym-Links      100               0        0        0
 Shell Binaries                  100               0        0        0
 Critical system boot files      100               0        0        0
 Tripwire Data Files             100               0        0        0
 System boot changes             100               0        0        0
 OS executables and libraries    100               0        0        0
 Critical configuration files    100               0        0        0
 Security Control                100               0        0        0
 Login Scripts                   100               0        0        0

Root config files 100 1 0 0 

 Invariant Directories           66                0        0        0
 Temporary directories           33                0        0        0
 Critical devices                100               0        0        0
 (/proc/kcore)

Total objects scanned: 47480 Total violations found: 1 ← 1件の変更を検知した

=============================================================================== Object Summary: ===============================================================================


# Section: Unix File System



Rule Name: Root config files (/root) Severity Level: 100


=============================================================================== Error Report: ===============================================================================

No Errors


End of report *** 

Open Source Tripwire 2.4 Portions copyright 2000 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. This software comes with ABSOLUTELY NO WARRANTY; for details use --version. This is free software which may be redistributed or modified only under certain conditions; see COPYING for details. All rights reserved.

[root@centos ~]# twprint -m r --report-level 1 -c /etc/tripwire/tw.cfg -r /var/lib/tripwire/report/centos.centossrv.com-20170123-184023.twr ← チェック結果サマリ参照 Note: Report is not encrypted. Added: "/root/test.txt" ← /root/test.txtの追加を検知した

[root@centos ~]# rm -f test.txt ← テストファイル削除(後始末)

■Tripwire定期自動実行設定 [root@centos ~]# yum -y install tmpwatch ← tmpwatchインストール

[root@centos ~]# vi tripwire.sh ← Tripwire定期自動実行スクリプト作成

#!/bin/bash

# 既存のTripwire定期自動実行設定削除 rm -f /etc/cron.daily/tripwire-check

# パスフレーズ設定 LOCALPASS=xxxxxxxx # ローカルパスフレーズ SITEPASS=xxxxxxxx # サイトパスフレーズ

TRIPWIRE=/usr/sbin/tripwire TWADMIN=/usr/sbin/twadmin TWPRINT=/usr/sbin/twprint cd /etc/tripwire

# Tripwireチェック実行

# ※ファイル変更を検知した場合のみroot宛にサマリをメールする rm -f /var/lib/tripwire/report/`hostname`-`date +%Y%m%d`-*.twr ${TRIPWIRE} -m c -s -c tw.cfg > /tmp/tripwire.log if [ $(grep "Total violations found" /tmp/tripwire.log | awk '{print $4}') -ne 0 ]; then

   ${TWPRINT} -m r --report-level 1 -c tw.cfg -r /var/lib/tripwire/report/`hostname`-`date +%Y%m%d`-*.twr | \
   mail -s "Tripwire Integrity Check Report from `hostname`" root

fi

# Tripwireチェック実行結果(過去分)削除

# ※過去90日分保管 tmpwatch -m 2160 /var/lib/tripwire/report

# ポリシーファイル最新化 ${TWADMIN} -m p -c tw.cfg -p tw.pol -S site.key > twpol.txt perl twpolmake.pl twpol.txt > twpol.txt.new ${TWADMIN} -m P -c tw.cfg -p tw.pol -S site.key -Q $SITEPASS twpol.txt.new > /dev/null rm -f twpol.txt* *.bak

# データベース最新化 rm -f /var/lib/tripwire/*.twd* ${TRIPWIRE} -m i -s -c tw.cfg -P $LOCALPASS

[root@centos ~]# chmod 700 tripwire.sh ← Tripwire定期自動実行スクリプトへ実行権限付加

[root@centos ~]# echo "0 3 * * * root /root/tripwire.sh" > /etc/cron.d/tripwire ← Tripwire定期自動実行設定追加※毎日3:00にTripwire定期実行スクリプトを実行する

■ポリシーファイルメンテナンス 日々のチェック結果より、あらかじめ変更がわかっているディレクトリやファイルについては検知されないようにする。 [root@centos ~]# twadmin -m p -c /etc/tripwire/tw.cfg -p /etc/tripwire/tw.pol -S /etc/tripwire/site.key > /etc/tripwire/twpol.txt ← ポリシーファイル(テキスト版)作成

[root@centos ~]# echo '!/var/log/sa ;' >> /etc/tripwire/twpol.txt ← 例としてディレクトリ/var/log/saをチェック対象外にする

[root@centos ~]# echo '!/etc/sysconfig/iptables ;' >> /etc/tripwire/twpol.txt ← 例としてファイル/etc/sysconfig/iptablesをチェック対象外にする

[root@centos ~]# twadmin -m P -c /etc/tripwire/tw.cfg -p /etc/tripwire/tw.pol -S /etc/tripwire/site.key /etc/tripwire/twpol.txt ← 最適化済ポリシーファイルを元にポリシーファイル(暗号署名版)作成 Please enter your site passphrase: ← サイトパスフレーズ応答 Wrote policy file: /etc/tripwire/tw.pol

[root@centos ~]# rm -f /etc/tripwire/twpol.txt /etc/tripwire/tw.pol.bak ← ポリシーファイル(テキスト版&バックアップ)削除

[root@centos ~]# rm -f /var/lib/tripwire/*.twd* ; tripwire -m i -s -c /etc/tripwire/tw.cfg ← Tripwireデータベース更新 Please enter your local passphrase: ← ローカルパスフレーズ応答

rootkit検知ツール導入(chkrootkit) 

■概要 chkrootkitというrootkit検知ツールを導入して、rootkitがLinuxサーバーにインストールされてしまっていないかチェックする。 chkrootkitは、以下のコマンドを使用してチェックするため、コマンド自体がrootkitを検知できないように改竄されてからでは意味がないので、Linuxインストール後の初期の段階で導入しておくのが望ましい。

【chkrootkitが使用するコマンド】 awk, cut, echo, egrep, find, head, id, ls, netstat, ps, strings, sed, uname

なお、chkrootkitが検知できるのは既知のrootkitのみであり、新たなrootkitの検知はできない。 また、rootkitが設置されていないにもかかわらず、chkrootkitが誤ってrootkitを検知したとアラームをあげる場合もあるので、chkrootkitによるrootkitの検知結果は参考程度としておく。

■chkrootkitインストール 【CentOS7の場合】 [root@centos ~]# wget ftp://ftp.pangeia.com.br/pub/seg/pac/chkrootkit.tar.gz ← chkrootkitダウンロード

[root@centos ~]# tar zxvf chkrootkit.tar.gz ← chkrootkit展開

[root@centos ~]# mkdir -p ~/bin && mv chkrootkit-0.50/chkrootkit ~/bin ← chkrootkitを移動

[root@centos ~]# rm -rf chkrootkit-0.50/ ← chkrootkit展開先ディレクトリを削除

[root@centos ~]# rm -f chkrootkit.tar.gz ← ダウンロードしたchkrootkitを削除

【CentOS6の場合】 EPELリポジトリ導入(EPEL)を参照してEPELリポジトリを導入する

[root@centos ~]# yum -y install chkrootkit ← chkrootkitインストール

■chkrootkit確認 [root@centos ~]# chkrootkit | grep INFECTED ← chkrootkit実行 上記chkrootkit実行結果として"INFECTED"という行が表示されなければ問題なし

■chkrootkit定期自動実行設定 [root@centos ~]# vi /etc/cron.daily/chkrootkit ← chkrootkit実行スクリプトを毎日自動実行されるディレクトリへ作成

#!/bin/bash

PATH=/usr/bin:/bin:/root/bin

LOG=/tmp/$(basename ${0})

# chkrootkit実行 chkrootkit > $LOG 2>&1

# ログ出力 cat $LOG | logger -t $(basename ${0})

# SMTPSのbindshell誤検知対応 if [ ! -z "$(grep 465 $LOG)" ] && \

  [ -z $(/usr/sbin/lsof -i:465|grep bindshell) ]; then
       sed -i '/465/d' $LOG

fi

# upstartパッケージ更新時のSuckit誤検知対応 if [ ! -z "$(grep Suckit $LOG)" ] && \

  [ -z "$(rpm -V `rpm -qf /sbin/init`)" ]; then
       sed -i '/Suckit/d' $LOG

fi

# rootkit検知時のみroot宛メール送信 [ ! -z "$(grep INFECTED $LOG)" ] && \ grep INFECTED $LOG | mail -s "chkrootkit report in `hostname`" root

[root@centos ~]# chmod 700 /etc/cron.daily/chkrootkit ← chkrootkit実行スクリプトへ実行権限付加 これで毎日定期的にrootkitがインストールされていないかチェックされ、インストールされていた場合はroot宛にメールが届くようになる。また、chkrootkitの実行結果は/var/log/messagesに保存される。

■chkrootkitで使用する安全なコマンドの確保 chkrootkitが使用するコマンド群が既に改竄されていた場合、rootkitを正常に検出できなくなるので、chkrootkitが使用するコマンド群をコピーしておき、必要な場合にはそのコマンド群を使用してchkrootkitを実行する。 [root@centos ~]# mkdir chkrootkitcmd ← chkrootkit使用コマンド退避先ディレクトリ作成

[root@centos ~]# cp `which --skip-alias awk cut echo egrep find head id ls netstat ps strings sed ssh uname` chkrootkitcmd/ ← chkrootkit使用コマンドを退避先ディレクトリへコピー

[root@centos ~]# chkrootkit -p /root/chkrootkitcmd|grep INFECTED ← 試しに退避したchkrootkit使用コマンドを使用してchkrootkit実行

[root@centos ~]# zip -r chkrootkitcmd.zip chkrootkitcmd/ && rm -rf chkrootkitcmd ← chkrootkit使用コマンド退避先ディレクトリを圧縮して削除

[root@centos ~]# echo|mail -a chkrootkitcmd.zip -s chkrootkitcmd.zip root ← chkrootkit使用コマンド(圧縮版)をroot宛にメール送信

[root@centos ~]# rm -f chkrootkitcmd.zip ← chkrootkit使用コマンド(圧縮版)削除

アンチウイルスソフト導入(Clam AntiVirus) 

■概要 Linux用のフリーのアンチウイルスソフトであるClam AntiVirusを導入する。

※CentOS6はこちら

■Clam AntiVirusインストール EPELリポジトリ導入(EPEL)を参照してEPELリポジトリを導入する

[root@centos ~]# yum -y install clamav clamav-server-systemd clamav-update clamav-scanner-systemd ← Clam AntiVirusインストール

■ウイルス定義ファイル最新化 [root@centos ~]# vi /etc/freshclam.conf ← ウイルス定義ファイル更新設定ファイル編集

# Comment or remove the line below.

#Example ← 行頭に#を追加してコメントアウト(ウイルス定義ファイル更新機能の有効化)

# Send the RELOAD command to clamd.

# Default: no

#NotifyClamd /path/to/clamd.conf NotifyClamd /etc/clamd.d/scan.conf ← 追加(ウイルス定義ファイル更新をclamdに通知する)

[root@centos ~]# vi /etc/sysconfig/freshclam ← ウイルス定義ファイル自動更新設定ファイル編集

#FRESHCLAM_DELAY= ← 行頭に#を追加してコメントアウト

[root@centos ~]# freshclam ← ウイルス定義ファイル最新化 ClamAV update process started at Sat Sep 3 13:22:28 2016 main.cvd is up to date (version: 57, sigs: 4218790, f-level: 60, builder: amishhammer) nonblock_connect: connect timing out (30 secs) Can't connect to port 80 of host database.clamav.net (IP: 172.110.204.67) Trying host database.clamav.net (208.72.56.53)... connect_error: getsockopt(SO_ERROR): fd=4 error=111: Connection refused Can't connect to port 80 of host database.clamav.net (IP: 208.72.56.53) Trying host database.clamav.net (64.22.33.90)... WARNING: getfile: daily-21724.cdiff not found on database.clamav.net (IP: 64.22.33.90) WARNING: getpatch: Can't download daily-21724.cdiff from database.clamav.net WARNING: getfile: daily-21724.cdiff not found on database.clamav.net (IP: 150.214.142.197) WARNING: getpatch: Can't download daily-21724.cdiff from database.clamav.net WARNING: getfile: daily-21724.cdiff not found on database.clamav.net (IP: 194.186.47.19) WARNING: getpatch: Can't download daily-21724.cdiff from database.clamav.net WARNING: Incremental update failed, trying to download daily.cvd Downloading daily.cvd [100%] daily.cvd updated (version: 22176, sigs: 575124, f-level: 63, builder: neo) Downloading bytecode-279.cdiff [100%] Downloading bytecode-280.cdiff [100%] Downloading bytecode-281.cdiff [100%] Downloading bytecode-282.cdiff [100%] Downloading bytecode-283.cdiff [100%] bytecode.cld updated (version: 283, sigs: 53, f-level: 63, builder: neo) Database updated (4793967 signatures) from database.clamav.net (IP: 69.12.162.28) ERROR: Please edit the example config file /etc/clamd.d/scan.conf ERROR: NotifyClamd: Can't find or parse configuration file /etc/clamd.d/scan.conf ※以後のウイルス定義ファイルのアップデートは、/etc/cron.d/clamav-updateにより定期的に自動で行われる

■Clam AntiVirus設定 [root@centos ~]# vi /etc/clamd.d/scan.conf ← Clam AntiVirus設定ファイル編集

# Comment or remove the line below.

#Example ← 行頭に#を追加してコメントアウト

# Run as another user (clamd must be started by root for this option to work)

# Default: don't drop privileges

#User clamscan ← 行頭に#を追加してコメントアウト(root権限で動作するようにする)

# Path to a local socket file the daemon will listen on.

# Default: disabled (must be specified by a user) LocalSocket /var/run/clamd.scan/clamd.sock ← 行頭の#を削除

■Clam AntiVirus起動 [root@centos ~]# systemctl start clamd@scan ← clamd起動

※※clamd起動が以下のメッセージを出力して失敗する場合の対処(ここから)※※ Job for clamd@scan.service failed because a timeout was exceeded. See "systemctl status clamd@scan.service" and "journalctl -xe" for details.

[root@centos ~]# vi /lib/systemd/system/clamd@.service ← clamd起動スクリプト修正 [Service] Type = forking ExecStart = /usr/sbin/clamd -c /etc/clamd.d/%i.conf Restart = on-failure TimeoutSec=5min ← 追加(起動完了までに待機する時間を5分に設定)

[root@centos ~]# systemctl daemon-reload ← clamd起動スクリプト修正反映

[root@centos ~]# systemctl start clamd@scan ← clamd起動 ※※clamd起動が以下のメッセージを出力して失敗する場合の対処(ここまで)※※

[root@centos ~]# systemctl enable clamd@scan ← clamd自動起動設定

■ウイルススキャンテスト [root@centos ~]# clamdscan -c /etc/clamd.d/scan.conf --remove ← ウイルススキャンテスト(ウイルスなしの場合) /root: OK


Infected files: 0 ← ウイルスは検知されなかった Time: 1.924 sec (0 m 1 s)

[root@centos ~]# wget http://www.eicar.org/download/eicar.com ← テスト用ウイルスをダウンロード [root@centos ~]# wget http://www.eicar.org/download/eicar.com.txt ← 〃 [root@centos ~]# wget http://www.eicar.org/download/eicar_com.zip ← 〃 [root@centos ~]# wget http://www.eicar.org/download/eicarcom2.zip ← 〃

[root@centos ~]# clamdscan -c /etc/clamd.d/scan.conf --remove ← ウイルススキャンテスト(ウイルスありの場合) /root/eicar.com: Eicar-Test-Signature FOUND ← ウイルス検知 /root/eicar.com: Removed. ← ウイルス削除 /root/eicar.com.txt: Eicar-Test-Signature FOUND ← ウイルス検知 /root/eicar.com.txt: Removed. ← ウイルス削除 /root/eicar_com.zip: Eicar-Test-Signature FOUND ← ウイルス検知 /root/eicar_com.zip: Removed. ← ウイルス削除 /root/eicarcom2.zip: Eicar-Test-Signature FOUND ← ウイルス検知 /root/eicarcom2.zip: Removed. ← ウイルス削除


Infected files: 4 ← 4つのウイルスを検知した Time: 23.913 sec (0 m 23 s)

■ウイルススキャン定期自動実行設定 (1)ウイルススキャン定期自動実行設定 [root@centos ~]# vi /etc/cron.daily/clamdscan ← ウイルススキャン日次実行スクリプト作成

#!/bin/bash

# 設定ファイル CONFIG=/etc/clamd.d/scan.conf

# スキャン実行

# ※ウイルス検知時は隔離ディレクトリへ隔離 CLAMSCANLOG=`mktemp` QUARANTINEDIR=/tmp/clamdscan-quarantinedir-$(date +%Y%m%d) mkdir -p ${QUARANTINEDIR} clamdscan -c ${CONFIG} --move=${QUARANTINEDIR} / > ${CLAMSCANLOG} 2>&1

# ウイルス検知時のみroot宛にメール通知 if [ -z "$(grep FOUND$ ${CLAMSCANLOG})" ]; then

   rm -rf ${QUARANTINEDIR}

else

   grep -A 1 FOUND$ ${CLAMSCANLOG} | mail -s "Virus Found in `hostname` => ${QUARANTINEDIR}" root

fi

# スキャンログをシスログに出力 cat ${CLAMSCANLOG} | logger -t $(basename ${0}) rm -f ${CLAMSCANLOG}

[root@centos ~]# chmod +x /etc/cron.daily/clamdscan ← ウイルススキャン日次実行スクリプトへ実行権限付加

[root@centos ~]# echo ExcludePath ^/tmp/clamdscan-quarantinedir-.*/ >> /etc/clamd.d/scan.conf ← ウイルス隔離ディレクトリをスキャン対象外にする

[root@centos ~]# echo ExcludePath ^/proc/ >> /etc/clamd.d/scan.conf ← 例として/procディレクトリをスキャン対象外にする

[root@centos ~]# echo ExcludePath ^/sys/ >> /etc/clamd.d/scan.conf ← 例として/sysディレクトリをスキャン対象外にする

[root@centos ~]# systemctl restart clamd@scan ← clamd再起動(スキャン除外設定反映) これで、毎日定期的に全ファイルのウイルススキャンが行われ、ウイルスを検知した場合のみroot宛にメールが送られてくるようになる。

(2)ウイルス検知後の対応 ウイルス検知メールが送られてきた場合、内容を確認し、ウイルスであると確認できた場合、当該ファイルを隔離先(ウイルス検知メール件名に記載)から削除する。 ウイルスでない(ClamAVによる誤検知)と確認できた場合、当該ファイルを隔離先から復元し、次回以降、誤検知しないように当該ファイルをスキャン対象外にする。

ファイアウォール構築(iptables)(計算機センターで管理しているからいらないかもしれないが一応) 

■概要 Linuxサーバー上にファイアウォールを構築する。 ここでは、Linuxのパケットフィルタリング機能であるiptablesを使用して、Web等外部に公開するサービス以外のポートへのアクセスをブロックするようにする。

※通常はルーター側にもファイアウォール機能があるため、Linuxサーバー上でファイアウォールを構築後にポートを開放する場合は、ルーター側とLinuxサーバー側の2箇所でポート開放を行う必要があることに注意

【想定するネットワーク環境】

■iptables設定 (1)iptables設定 [root@centos ~]# yum -y install iptables-services ← iptables-servicesインストール※CentOS7の場合

[root@centos ~]# vi iptables.sh ← ファイアウォール設定スクリプト作成

#!/bin/bash

#---------------------------------------#

# 設定開始 #

#---------------------------------------#

# 内部ネットワークアドレス定義 LOCALNET=192.168.1.0/24

#---------------------------------------#

# 設定終了 #

#---------------------------------------#

# デフォルトルール(以降のルールにマッチしなかった場合に適用するルール)設定 IPTABLES_CONFIG=`mktemp` echo "*filter" >> $IPTABLES_CONFIG echo ":INPUT DROP [0:0]" >> $IPTABLES_CONFIG # 受信はすべて破棄 echo ":FORWARD DROP [0:0]" >> $IPTABLES_CONFIG # 通過はすべて破棄 echo ":OUTPUT ACCEPT [0:0]" >> $IPTABLES_CONFIG # 送信はすべて許可 echo ":ACCEPT_COUNTRY - [0:0]" >> $IPTABLES_CONFIG # 指定した国からのアクセスを許可 echo ":DROP_COUNTRY - [0:0]" >> $IPTABLES_CONFIG # 指定した国からのアクセスを破棄 echo ":LOG_PINGDEATH - [0:0]" >> $IPTABLES_CONFIG # Ping of Death攻撃はログを記録して破棄

# 自ホストからのアクセスをすべて許可 echo "-A INPUT -i lo -j ACCEPT" >> $IPTABLES_CONFIG

# 内部からのアクセスをすべて許可 echo "-A INPUT -s $LOCALNET -j ACCEPT" >> $IPTABLES_CONFIG

# 内部から行ったアクセスに対する外部からの返答アクセスを許可 echo "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT" >> $IPTABLES_CONFIG

# SYN Cookiesを有効にする

# ※TCP SYN Flood攻撃対策 sysctl -w net.ipv4.tcp_syncookies=1 > /dev/null sed -i '/net.ipv4.tcp_syncookies/d' /etc/sysctl.conf echo "net.ipv4.tcp_syncookies=1" >> /etc/sysctl.conf

# ブロードキャストアドレス宛pingには応答しない

# ※Smurf攻撃対策 sysctl -w net.ipv4.icmp_echo_ignore_broadcasts=1 > /dev/null sed -i '/net.ipv4.icmp_echo_ignore_broadcasts/d' /etc/sysctl.conf echo "net.ipv4.icmp_echo_ignore_broadcasts=1" >> /etc/sysctl.conf

# ICMP Redirectパケットは拒否 sed -i '/net.ipv4.conf.*.accept_redirects/d' /etc/sysctl.conf for dev in `ls /proc/sys/net/ipv4/conf/` do

   sysctl -w net.ipv4.conf.$dev.accept_redirects=0 > /dev/null
   echo "net.ipv4.conf.$dev.accept_redirects=0" >> /etc/sysctl.conf

done

# Source Routedパケットは拒否 sed -i '/net.ipv4.conf.*.accept_source_route/d' /etc/sysctl.conf for dev in `ls /proc/sys/net/ipv4/conf/` do

   sysctl -w net.ipv4.conf.$dev.accept_source_route=0 > /dev/null
   echo "net.ipv4.conf.$dev.accept_source_route=0" >> /etc/sysctl.conf

done

# フラグメント化されたパケットはログを記録して破棄 echo "-A INPUT -f -j LOG --log-prefix \"[IPTABLES FRAGMENT] : \"" >> $IPTABLES_CONFIG echo "-A INPUT -f -j DROP" >> $IPTABLES_CONFIG

# 外部とのNetBIOS関連のアクセスはログを記録せずに破棄

# ※不要ログ記録防止 echo "-A INPUT ! -s $LOCALNET -p tcp -m multiport --dports 135,137,138,139,445 -j DROP" >> $IPTABLES_CONFIG echo "-A INPUT ! -s $LOCALNET -p udp -m multiport --dports 135,137,138,139,445 -j DROP" >> $IPTABLES_CONFIG echo "-A OUTPUT ! -d $LOCALNET -p tcp -m multiport --sports 135,137,138,139,445 -j DROP" >> $IPTABLES_CONFIG echo "-A OUTPUT ! -d $LOCALNET -p udp -m multiport --sports 135,137,138,139,445 -j DROP" >> $IPTABLES_CONFIG

# 1秒間に4回を超えるpingはログを記録して破棄

# ※Ping of Death攻撃対策 echo "-A LOG_PINGDEATH -m limit --limit 1/s --limit-burst 4 -j ACCEPT" >> $IPTABLES_CONFIG echo "-A LOG_PINGDEATH -j LOG --log-prefix \"[IPTABLES PINGDEATH] : \"" >> $IPTABLES_CONFIG echo "-A LOG_PINGDEATH -j DROP" >> $IPTABLES_CONFIG echo "-A INPUT -p icmp --icmp-type echo-request -j LOG_PINGDEATH" >> $IPTABLES_CONFIG

# 全ホスト(ブロードキャストアドレス、マルチキャストアドレス)宛パケットはログを記録せずに破棄

# ※不要ログ記録防止 echo "-A INPUT -d 255.255.255.255 -j DROP" >> $IPTABLES_CONFIG echo "-A INPUT -d 224.0.0.1 -j DROP" >> $IPTABLES_CONFIG

# 113番ポート(IDENT)へのアクセスには拒否応答

# ※メールサーバ等のレスポンス低下防止 echo "-A INPUT -p tcp --dport 113 -j REJECT --reject-with tcp-reset" >> $IPTABLES_CONFIG

# ACCEPT_COUNTRY_MAKE関数定義

# 指定された国のIPアドレスからのアクセスを許可するユーザ定義チェイン作成 ACCEPT_COUNTRY_MAKE(){

   for addr in `cat /tmp/cidr.txt|grep ^$1|awk '{print $2}'`
   do
       echo "-A ACCEPT_COUNTRY -s $addr -j ACCEPT" >> $IPTABLES_CONFIG
   done
   grep ^$1 $IP_LIST >> $CHK_IP_LIST

}

# DROP_COUNTRY_MAKE関数定義

# 指定された国のIPアドレスからのアクセスを破棄するユーザ定義チェイン作成 DROP_COUNTRY_MAKE(){

   for addr in `cat /tmp/cidr.txt|grep ^$1|awk '{print $2}'`
   do
       echo "-A DROP_COUNTRY -s $addr -m limit --limit 1/s -j LOG --log-prefix \"[IPTABLES DENY_COUNTRY] : \"" >> $IPTABLES_CONFIG
       echo "-A DROP_COUNTRY -s $addr -j DROP" >> $IPTABLES_CONFIG
   done
   grep ^$1 $IP_LIST >> $CHK_IP_LIST

}

# IPアドレスリスト取得 IP_LIST=/tmp/cidr.txt CHK_IP_LIST=/tmp/IPLIST if [ ! -f $IP_LIST ]; then

   wget -q http://nami.jp/ipv4bycc/cidr.txt.gz
   gunzip -c cidr.txt.gz > $IP_LIST
   rm -f cidr.txt.gz

fi rm -f $CHK_IP_LIST

# 日本からのアクセスを許可するユーザ定義チェインACCEPT_COUNTRY作成 ACCEPT_COUNTRY_MAKE JP

# 以降,日本からのみアクセスを許可したい場合はACCEPTのかわりにACCEPT_COUNTRYを指定する

# 全国警察施設への攻撃元上位5カ国(日本・アメリカを除く)からのアクセスをログを記録して破棄

# 直近1週間の状況 http://www.npa.go.jp/cyberpolice/detect/observation.html

# 前月の状況 http://www.npa.go.jp/cyberpolice/detect/index.html

# 国コード一覧 https://ja.wikipedia.org/wiki/ISO_3166-1#%E7%95%A5%E5%8F%B7%E4%B8%80%E8%A6%A7 DROP_COUNTRY_MAKE RU DROP_COUNTRY_MAKE NL DROP_COUNTRY_MAKE CN DROP_COUNTRY_MAKE DE DROP_COUNTRY_MAKE VN echo "-A INPUT -j DROP_COUNTRY" >> $IPTABLES_CONFIG

#----------------------------------------------------------#

# 各種サービスを公開する場合の設定(ここから) #

#----------------------------------------------------------#

# 外部からのTCP22番ポート(SSH)へのアクセスを日本からのみ許可

# ※SSHサーバーを公開する場合のみ echo "-A INPUT -p tcp --dport 22 -j ACCEPT_COUNTRY" >> $IPTABLES_CONFIG

# 外部からのTCP/UDP53番ポート(DNS)へのアクセスを許可

# ※外部向けDNSサーバーを運用する場合のみ echo "-A INPUT -p tcp --dport 53 -j ACCEPT" >> $IPTABLES_CONFIG echo "-A INPUT -p udp --dport 53 -j ACCEPT" >> $IPTABLES_CONFIG

# 外部からのTCP80番ポート(HTTP)へのアクセスを許可

# ※Webサーバーを公開する場合のみ echo "-A INPUT -p tcp --dport 80 -j ACCEPT" >> $IPTABLES_CONFIG

# 外部からのTCP443番ポート(HTTPS)へのアクセスを許可

# ※Webサーバーを公開する場合のみ echo "-A INPUT -p tcp --dport 443 -j ACCEPT" >> $IPTABLES_CONFIG

# 外部からのTCP25番ポート(SMTP)へのアクセスを許可

# ※SMTPサーバーを公開する場合のみ echo "-A INPUT -p tcp --dport 25 -j ACCEPT" >> $IPTABLES_CONFIG

# 外部からのTCP587番ポート(SUBMISSION)へのアクセスを日本からのみ許可

# ※SMTPサーバーを公開する場合のみ

# ※SMTPSサーバー(TCP465番ポート)を公開する場合は不要

#echo "-A INPUT -p tcp --dport 587 -j ACCEPT_COUNTRY" >> $IPTABLES_CONFIG

# 外部からのTCP465番ポート(SMTPS)へのアクセスを日本からのみ許可

# ※SMTPSサーバーを公開する場合のみ echo "-A INPUT -p tcp --dport 465 -j ACCEPT_COUNTRY" >> $IPTABLES_CONFIG

# 外部からのTCP110番ポート(POP3)へのアクセスを日本からのみ許可

# ※POP3サーバーを公開する場合のみ echo "-A INPUT -p tcp --dport 110 -j ACCEPT_COUNTRY" >> $IPTABLES_CONFIG

# 外部からのTCP995番ポート(POP3S)へのアクセスを日本からのみ許可

# ※POP3Sサーバーを公開する場合のみ echo "-A INPUT -p tcp --dport 995 -j ACCEPT_COUNTRY" >> $IPTABLES_CONFIG

# 外部からのTCP143番ポート(IMAP)へのアクセスを日本からのみ許可

# ※IMAPサーバーを公開する場合のみ echo "-A INPUT -p tcp --dport 143 -j ACCEPT_COUNTRY" >> $IPTABLES_CONFIG

# 外部からのTCP993番ポート(IMAPS)へのアクセスを日本からのみ許可

# ※IMAPSサーバーを公開する場合のみ echo "-A INPUT -p tcp --dport 993 -j ACCEPT_COUNTRY" >> $IPTABLES_CONFIG

# 外部からのUDP500番ポート、UDP4500番ポート(L2TP over IPsec)へのアクセスを日本からのみ許可

# ※SoftEther VPN Serverを公開する場合のみ echo "-A INPUT -p udp --dport 500 -j ACCEPT_COUNTRY" >> $IPTABLES_CONFIG echo "-A INPUT -p udp --dport 4500 -j ACCEPT_COUNTRY" >> $IPTABLES_CONFIG

# 外部からのTCP20000番ポート(Usermin)へのアクセスを日本からのみ許可

# ※Userminサーバーを公開する場合のみ echo "-A INPUT -p tcp --dport 20000 -j ACCEPT_COUNTRY" >> $IPTABLES_CONFIG

# 外部からのTCP8080番ポート、TCP8443番ポートへのアクセスを日本からのみ許可

# ※動画配信サーバー(https://centossrv.com/nginx-nginx-rtmp-module.shtml)を公開する場合のみ echo "-A INPUT -p tcp --dport 8080 -j ACCEPT_COUNTRY" >> $IPTABLES_CONFIG echo "-A INPUT -p tcp --dport 8443 -j ACCEPT_COUNTRY" >> $IPTABLES_CONFIG

#----------------------------------------------------------#

# 各種サービスを公開する場合の設定(ここまで) #

#----------------------------------------------------------#

# 拒否IPアドレスからのアクセスはログを記録せずに破棄

# ※拒否IPアドレスは/root/deny_ipに1行ごとに記述しておくこと

# (/root/deny_ipがなければなにもしない) if [ -s /root/deny_ip ]; then

   for ip in `cat /root/deny_ip`
   do
       echo "-I INPUT -s $ip -j DROP" >> $IPTABLES_CONFIG
   done

fi

# 上記のルールにマッチしなかったアクセスはログを記録して破棄 echo "-A INPUT -m limit --limit 1/s -j LOG --log-prefix \"[IPTABLES INPUT] : \"" >> $IPTABLES_CONFIG echo "-A INPUT -j DROP" >> $IPTABLES_CONFIG echo "-A FORWARD -m limit --limit 1/s -j LOG --log-prefix \"[IPTABLES FORWARD] : \"" >> $IPTABLES_CONFIG echo "-A FORWARD -j DROP" >> $IPTABLES_CONFIG

# ファイアウォール設定反映 echo "COMMIT" >> $IPTABLES_CONFIG cat $IPTABLES_CONFIG > /etc/sysconfig/iptables if [ -f /usr/libexec/iptables/iptables.init ]; then

   /usr/libexec/iptables/iptables.init restart

else

   /etc/rc.d/init.d/iptables restart

fi rm -f $IPTABLES_CONFIG

(2)IPアドレスリスト更新チェック IPアドレスリストは頻繁に更新されるので、毎日自動でIPアドレスリストの更新有無をチェックし、更新がある場合はファイアウォール設定スクリプトを再起動するようにする。 [root@centos ~]# vi /etc/cron.daily/iplist_check.sh ← IPアドレスリストチェックスクリプト作成

#!/bin/bash

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# 新旧IPLIST差分チェック件数(0を指定するとチェックしない)

# ※新旧IPLIST差分がSABUN_CHKで指定した件数を越える場合はiptables設定スクリプトを実行しない

# ※新旧IPLIST差分チェック理由はhttp://centossrv.com/bbshtml/webpatio/1592.shtmlを参照 SABUN_CHK=100 [ $# -ne 0 ] && SABUN_CHK=${1}

# IPアドレスリスト取得 IP_LIST=/tmp/cidr.txt CHK_IP_LIST=/tmp/IPLIST wget -q http://nami.jp/ipv4bycc/cidr.txt.gz gunzip -c cidr.txt.gz > $IP_LIST rm -f cidr.txt.gz

# チェック対象IPアドレスリスト最新化 rm -f IPLIST.new for country in `awk '{print $1}' $CHK_IP_LIST |uniq` do

   grep ^$country $IP_LIST >> IPLIST.new

done

# チェック対象IPアドレスリスト更新チェック diff -q $CHK_IP_LIST IPLIST.new > /dev/null 2>&1 if [ $? -ne 0 ]; then

   if [ ${SABUN_CHK} -ne 0 ]; then
       if [ $(diff $CHK_IP_LIST IPLIST.new | egrep -c '<|>') -gt ${SABUN_CHK} ]; then
           (
            diff $CHK_IP_LIST IPLIST.new
            echo
            echo "iptables.sh not executed."
           ) | mail -s 'IPLIST UPDATE' root
           rm -f IPLIST.new
           exit
       fi
   fi
   /bin/mv IPLIST.new $CHK_IP_LIST
   sh /root/iptables.sh > /dev/null

else

   rm -f IPLIST.new

fi

[root@centos ~]# chmod +x /etc/cron.daily/iplist_check.sh ← IPアドレスリストチェックスクリプトに実行権限付加 ※CRONより/root/iptables.sh not executed.という内容のメールが届いた場合の対処 なんらかの理由で、http://nami.jp/ipv4bycc/から取得した最新のIPアドレスリストと、前回取得したIPアドレスリストとの差分が100件を超えたため、iptables設定スクリプトを実行しなかったことを示す。 サーバーを長時間停止していた等、前回取得したIPアドレスリストとの差分が100件を超える理由が明確な場合には、「/etc/cron.daily/iplist_check.sh 0」と実行することにより強制的にiptables設定スクリプトを実行する。

■iptables起動 [root@centos ~]# sh iptables.sh ← ファイアウォール設定スクリプト実行

[root@centos ~]# systemctl enable iptables ← iptables自動起動設定※CentOS7の場合 [root@centos ~]# chkconfig iptables on ← iptables自動起動設定※CentOS6の場合

■iptables確認 Shields UP! - Internet Vulnerability Profilingで「Proceed」ボタン(2つあるがどちらでもよい)をクリック⇒「All Service Ports」ボタンをクリックして、外部からのアクセスを許可または拒否応答しているポートのみOPENまたはCLOSEDで、その他のポートはSTEALTHであることを確認

 

 

 

 

 

サーバー"webサーバー編" 

共通事項 

blockly 

サーバー"運用保守編" 

CentOSを最新バージョンにアップデートする手順を紹介します。 本作業を行うことで、常に最新のCentOS を利用することが可能になります。

注意 実行タイミングやサーバー環境によっては、システムやアプリケーションの誤作動や 不具合、場合によっては、サーバー自体が起動しなくなる可能性があります。 そうなっても良いように、実行する場合は、必ずテスト環境(壊れても良い環境)で 事前確認を行ってください。

今回の例では、CentOS7.4を使用していますが、 他のバージョンでも基本的に手順は同じになります。

1.Linux のバージョンを確認します。 $ su - パスワード:    ←rootパスワードを入力します(パスワードは入力しても表示されません)

# cat /etc/redhat-release CentOS Linux release 7.4.1708 (Core)

2.カーネルバージョンを確認します。

# uname -a Linux Tiger 3.10.0-693.el7.x86_64 #1 SMP Tue Aug 22 21:09:27 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

3.カーネルをアップデート対象から除外する設定を行います。 バージョンアップの多くのトラブル原因は、 カーネルアップデートなので、取り敢えず除外します。 13 行目に「exclude=kernel*」を追加します。

# vi /etc/yum.conf


[main] cachedir=/var/cache/yum/$basearch/$releasever keepcache=0 debuglevel=2 logfile=/var/log/yum.log exactarch=1 obsoletes=1 gpgcheck=1 plugins=1 installonly_limit=5 bugtracker_url=http://bugs.centos.org/set_project.php?project_id=23&ref=http://bugs.centos.org/bug_repor t_page.php?category=yum distroverpkg=centos-release exclude=kernel*  ←「exclude=kernel*」を追加します。


編集後、「:wq」で保存終了します。

4.yumアップデートを実施します。 yum コマンドでアップデートを実施します。 途中、処理を続行するか問われるので「y」を入力します。 ※表示される内容は、実行タイミングによって異なります。


# yum update 読み込んだプラグイン:fastestmirror, langpacks base | 3.6 kB 00:00:00 extras | 3.4 kB 00:00:00 updates | 3.4 kB 00:00:00 (1/4): extras/7/x86_64/primary_db | 147 kB 00:00:03 (2/4): updates/7/x86_64 /primary_db | 2.0 MB 00:00:08

~中略~

libinput x86_64 1.8.4 -2.el7 base 142 k libwayland-client x86_64 1.14.0-2.el7 base 32 k libwayland-cursor x86_64 1.14.0 -2.el7 base 20 k libwayland-server x86_64 1.14.0 -2.el7 base 38 k llvm-private x86_64 5.0.0 -3.el7 base 20 M lz4 x86_64 1.7.5 -2.el7 base 98 k mesa-libwayland-egl x86_64 17.2.3 -8.20171019.el7 base 17 k unbound-libs x86_64 1.6.6 -1.el7 base 405 k volume_key-libs x86_64 0.3.9-8.el7 base 140 k

トランザクションの要約 ============================================================ インストール 4 パッケージ(+20 個の依存関係のパッケージ) 更新 613 パッケージ  ←この辺りの数字は、実行タイミングによって異なります。

合計容量: 642 M 総ダウンロード容量: 641 M Is this ok [y/d/N]: y  ←「y」を入力します。

~中略~

xorg-x11-server-common.x86_64 0:1.19.5-5.el7 xorg-x11-xinit.x86_64 0:1.3.4-2.el7 yum.noarch 0:3.4.3-158.el7.centos yum-plugin-fastestmirror.noarch 0:1.1.31 -45.el7 yum-utils.noarch 0:1.1.31-45.el7

置換: grub2.x86_64 1:2.02-0.64.el7.centos grub2 -tools.x86_64 1:2.02-0.64.el7.centos

完了しました!


5.サーバーを再起動します。

# shutdown -r now

6.再起動後、Linux のバージョンを確認します。 下記の例では、CentOS7.5 にバージョンアップしていますが、 実行タイミングによってバージョンが異なる場合があります。 $ su - パスワード:

# cat /etc/redhat-release CentOS Linux release 7.5.1804 (Core)

7.カーネルバージョンを確認します。 カーネルのバージョンはアップデートから除外しているので、変わっていません。

# uname -a Linux Tiger 3.10.0-693.el7.x86_64 #1 SMP Tue Aug 22 21:09:27 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

8.カーネルのバージョンアップをします。 13 行目の「exclude=kernel*」行頭に「#」を追加します。

# vi /etc/yum.conf


[main] cachedir=/var/cache/yum/$basearch/$releasever keepcache=0 debuglevel=2 logfile=/var/log/yum.log exactarch=1 obsoletes=1 gpgcheck=1 plugins=1 installonly_limit=5 bugtracker_url=http://bugs.centos.org/set_project.php?project_id=23&ref=http://bugs.centos.org/bug_repor t_page.php?category=yum distroverpkg=centos-release

#exclude=kernel*    ←行頭に「#」を追加します。


編集後、「:wq」で保存終了します。

9.yumアップデートを実施します。 yum コマンドでアップデートを実施します。 途中、処理を続行するか問われるので「y」を入力します。 ※表示される内容は、実行タイミングによって異なります。


# yum update 読み込んだプラグイン:fastestmirror, langpacks Loading mirror speeds from cached hostfile

base: ftp.nara.wide.ad.jp 

extras: ftp.nara.wide.ad.jp 

~中略~

依存性を解決しました

============================================================ Package アーキテクチャーバージョン リポジトリー 容量 ============================================================ インストール中: kernel x86_64 3.10.0-862.3.2.el7 updates 46 M kernel-devel x86_64 3.10.0-862.3.2.el7 updates 16 M 更新します: kernel-headers x86_64 3.10.0-862.3.2.el7 updates 7.1 M kernel-tools x86_64 3.10.0-862.3.2.el7 updates 6.2 M kernel-tools-libs x86_64 3.10.0-862.3.2.el7 updates 6.2 M

トランザクションの要約 ============================================================ インストール 2 パッケージ  ←この辺りの数字や内容は、実行タイミングによって異なります。 更新 3 パッケージ

総ダウンロード容量: 81 M Is this ok [y/d/N]: y ←「y」を入力します。

~中略~

検証中 : kernel-headers-3.10.0-693.el7.x86_64 7/8 検証中 : kernel-tools-libs-3.10.0-693.el7.x86_64 8/8

インストール: kernel.x86_64 0:3.10.0-862.3.2.el7 kernel -devel.x86_64 0:3.10.0-862.3.2.el7

更新: kernel-headers.x86_64 0:3.10.0-862.3.2.el7 kernel-tools.x86_64 0:3.10.0-862.3.2.el7 kernel-tools-libs.x86_64 0:3.10.0-862.3.2.el7

完了しました!


10.サーバーを再起動します。

# shutdown -r now

11.カーネルバージョンを確認します。 カーネルがバージョンアップしています。 $ su - パスワード: [root@Tiger ~]# uname -a Linux Tiger 3.10.0-862.3.2.el7.x86_64 #1 SMP Mon May 21 23:36:36 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

本手順を実施することで、常に最新のCentOS を利用することが出来ます。 しかし、冒頭でも説明しましたが、アップデートによるトラブルが発生する場合も ありますので、実施する際は、必ずテスト環境で問題がないことを確認してから、 本番環境で実施してください。


トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS