LoginSignup
8
8

More than 5 years have passed since last update.

CentOS 7 に Apache と MariaDB 10.2 をインストールし SFTP 接続

Last updated at Posted at 2015-07-31

導入

さくらの VPS のOS再インストールによって CentOS 7 にアップグレードした際に非常に手間取りましたので、備忘として残しておきます。

すでにOpenSSHを利用している ことを前提で記述しています。クライアントには Windows 7 上で FileZilla Client を使用しています。また、鍵生成には Tera Term を使用しています。

Apache

インストール

CentOS の公式 yum リポジトリで Apache 2.4 の RPM パッケージが提供されているので、それをインストールします。
さくらの VPS の場合はすでにインストールされていますが、有効化と起動は必要です。

# Apacheのインストール
sudo yum install httpd

# httpd.service の有効化 (OS起動時に自動的に起動)
sudo systemctl enable httpd

# 起動
sudo systemctl start httpd

次の記事などを参考にApacheの設定を行います。

ファイアウォールの設定

#【mod_sslを利用していない場合】TCPの80番ポートの通信を許可
sudo firewall-cmd --permanent --add-service=http

#【mod_sslを利用している場合】TCPの80番ポートと443番ポートの通信を許可
sudo firewall-cmd --permanent --add-service=http --add-service=https

# firewalld の設定を再読み込み
sudo firewall-cmd --reload

既定のポート以外を利用している場合は、以下のように許可します。

# (例) TCPの49152番ポートの通信を許可
sudo firewall-cmd --permanent --add-port=49152/tcp

Apacheの操作

コマンド 効果
httpd -v バージョンを表示します。
sudo -u apache apachectl configtest 設定ファイルに文法ミスが無いか確認します。
sudo systemctl start httpd サービスを開始します。
sudo httpd -k stop サービスを停止します。1 2
sudo systemctl stop httpd サービスを緩やかに停止します。3
sudo httpd -k restart サービスを再起動します。1
sudo service httpd reload サービスを緩やかに再起動します。4
sudo httpd -k stop; sleep 1s; sudo systemctl start httpd サービスを親プロセスも含めて完全に再起動します。1
sudo systemctl restart httpd サービスが緩やかに停止するのを待機した後で再起動します。
sudo tail /var/log/httpd/error_log tail コマンドでエラーログの末尾10行を表示します。5
sudo tail /var/log/httpd/access_log tail コマンドでアクセスログの末尾10行を表示します。5 6

MariaDB

*.repo のシンタックスハイライト

CentOS 標準の yum リポジトリで提供されているテキストエディタのうち Vim 以外のエディタは、初期状態でリポジトリ定義ファイルのシンタックスハイライトが機能しません。以下のように設定ファイルの編集などを行い、シンタックスハイライトを有効にします。

Emacs

個人設定ファイルを新規作成 (または追記) し、ファイル名が .repo で終わるファイルを conf-mode で開くようにする設定を追加します。

~/.emacs
;; .repo ファイルを Conf モードで開く
(add-to-list 'auto-mode-alist '("\\.repo$" . conf-mode))

gedit

ファイル名が .repo で終わるファイルを INI ファイルとして開くようにし、一行コメントアウト開始文字に # を追加します。

/usr/share/gtksourceview-*/language-specs/ini.lang
                    <!--##############
                        ## 以上省略 ##
                        ##############-->

  <metadata>
    <property name="mimetypes">text/x-ini-file;application/x-ini-file</property>
    <property name="globs">*.ini;*.repo</property><!--## *.repo を追加 ##-->
    <property name="line-comment-start">;</property>
  </metadata>

                    <!--##############
                        ##   中略   ##
                        ##############-->

  <definitions>
    <context id="line-comment" style-ref="comment" end-at-line-end="true">
      <start>;</start>
    </context>
    <!--## ここから ##-->
    <context id="bash-line-comment" style-ref="comment" end-at-line-end="true">
      <start>#</start>
    </context><!--## ここまで ##-->
    <context id="group" style-ref="keyword">
      <start>^\[</start>
      <end>\]$</end>
    </context>

                    <!--##############
                        ##   中略   ##
                        ##############-->

    <context id="ini">
      <include>
        <context ref="line-comment"/>
        <context ref="bash-line-comment"/><!--## 追加 ##-->
        <context ref="group"/>
        <context ref="non-standard-key"/>
        <context ref="language"/>
        <context ref="variable"/>
        <context ref="boolean-value"/>
        <context ref="single-quoted-string"/>
        <context ref="double-quoted-string"/>
        <context ref="decimal-number"/>
        <context ref="integer"/>
      </include>
    </context>
  </definitions>
</language>

Kate

ファイル名が .repo で終わるファイルを INI ファイルとして開くようにします。

/usr/share/kde*/apps/katepart/syntax/ini.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE language SYSTEM "language.dtd">
<language name="INI Files" section="Configuration" extensions="*.ini;*.pls;*.kcfgc;*.repo" mimetype="" version="1.1" kateversion="2.0" author="Jan Janssen (medhefgo@web.de)" license="LGPL"> <!-- extensions属性値に *.repo を追加 -->

                    <!--##############
                        ## 以下省略 ##
                        ##############-->

nano

Arch Linux の nano-syntax-highlighting-git パッケージを利用します。7 8

# INIファイルのシンタックスハイライトを行う設定ファイルをダウンロード
wget https://raw.githubusercontent.com/scopatz/nanorc/master/ini.nanorc

# .repo で終わるファイルをINIファイルとして扱うようにする
sed --in-place 's/)\$/|repo)$/' ini.nanorc

# シンタックスハイライトを行う設定ファイル保管場所に移動
sudo mv ini.nanorc /usr/share/nano/

# nanoの個人設定ファイルから読み込むようにする
echo $'\n\n'## INI files$'\n'include "/usr/share/nano/ini.nanorc" >> ~/.nanorc

インストール

CentOS の公式リポジトリでは、古いバージョンである MariaDB 5.5 が提供されています。そこでMariaDBの公式リポジトリを追加し、そちらから最新バージョンをインストールします。

yum による MariaDB のインストール - MariaDB Knowledge Base

上のページに目を通し、手順に従ってインストールを完了させます。

/etc/yum.repos.d/MariaDB.repo
[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.2/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1
# MariaDBのサーバー・コマンドラインクライアントをインストール
sudo yum install MariaDB-server MariaDB-client

# 起動
sudo systemctl start mariadb

RPM パッケージのダウンロードが完了した後に GPG 公開鍵を取り込んでも良いか訊ねられるため、Fingerprint が https://mariadb.com/kb/ja/gpg/ と大文字小文字無視で一致するか確認します。

符号化方式の設定

MariaDB 設定ファイル (*.cnf) でシンタックスハイライトを有効化する場合は、*.repo のシンタックスハイライトrepocnf に読み替えて設定してください。

サーバー

MariaDB の既定の文字集合 (character set) は latin1 で、これは「windows-1252」という符号化方式 (文字エンコーディング) を表します。以下のように設定ファイルを編集し、MariaDB で「UTF-8」を表す文字集合である utf8mb4 へ変更します。なお、MariaDB の文字集合 utf8 は、「補助文字 (4バイト文字) を扱えないUTF-8」を表します。

/etc/my.cnf.d/server.cnf
#
# These groups are read by MariaDB server.
# Use it for options that only the server (but not clients) should see
#
# See the examples of server my.cnf files in /usr/share/mysql/
#

# this is read by the standalone daemon and embedded servers
[server]
character-set-server=utf8mb4
log-bin=mariadb-bin
## ↑この2行を追加 ##
event-scheduler=ON
## ↑イベントスケジューラを有効化する場合はこの行も追加 ##

# this is only for the mysqld standalone daemon
[mysqld]

# this is only for embedded server
[embedded]

# This group is only read by MariaDB servers, not by MySQL.
# If you use the same .cnf file for MySQL and MariaDB,
# you can put MariaDB-only options here
[mariadb]

# This group is only read by MariaDB-10.0 servers.
# If you use the same .cnf file for MariaDB of different versions,
# use this group for options that older servers don't understand
[mariadb-10.0]

character_set_server によって、character_set_databasecollation_servercollation_database は自動的に設定されます。上記の log-bin の値 mariadb-bin はバイナリログファイルの接頭辞で、任意の値でかまいません。クライアント側の符号化方式は、クライアント側の設定に依存します。

# 設定の反映
sudo systemctl restart mariadb

systemctl reload mariadb では、システム変数の設定は反映されません。

コマンドラインクライアント

MariaDB-client パッケージに含まれるコマンド (mysql など) の既定の符号化方式は auto で、これを utf8mb4 に変更しておきます。

/etc/my.cnf.d/client.cnf
#
# These two groups are read by the client library
# Use it for options that affect all clients, but not the server
#


[client]
default-character-set=utf8mb4
## ↑この行を追加 ##

# This group is not read by mysql client library,
# If you use the same .cnf file for MySQL and MariaDB,
# use it for MariaDB-only client options
[client-mariadb]

なお、default_character_set が廃止され character_set_server に改名されたというのはサーバーシステム変数の話です。mysql コマンドなどでは --default-character-set オプションのままなので、ご注意ください。 9 10

その他の初期設定

mysql_secure_installation - MariaDB Knowledge Base

上のページに目を通し、mysql_secure_installation コマンドを実行します。root パスワードをまだ設定していないので、Set root password? [Y/n] に対してもそのまま Enter を押します。11

[100@localhost ~]$ mysql_secure_installation ⏎

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.
Enter current password for root (enter for none): ⏎    ## 現在のルートパスワード。未設定なのでそのままEnter ##
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.

Set root password? [Y/n] ⏎                             ## MariaDBのrootユーザーにパスワードを設定するか訊かれる。「Y」(Yes) が既定値なのでそのままEnter ##
New password: ******** ⏎                               ## MariaDBのrootユーザーのパスワードを入力してEnter ##
Re-enter new password: ******** ⏎                      ## 同じパスワードを再入力してEnter ##
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] ⏎                        ## 匿名ユーザーを削除するか訊かれる。「Y」(Yes) が既定値なのでそのままEnter ##
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] ⏎                  ## rootユーザーのリモートログインを禁止するか訊かれる。「Y」(Yes) が既定値なのでそのままEnter ##
 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] ⏎         ## testデータベースを削除するか訊かれる。「Y」(Yes) が既定値なのでそのままEnter ##
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] ⏎                   ## 権限テーブルを再読み込みするか訊かれる。「Y」(Yes) が既定値なのでそのままEnter ##
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

データベースのリストアとユーザーの作成

mysql --user=root --password を実行し、MariaDB の root ユーザーでログインします。11

-- リストア (ファイル名が backup.sql の場合)
source backup.sql;

-- 一般ユーザーの作成と ⦅データベース名A⦆ に対する権限の付与
GRANT ALL PRIVILEGES ON '⦅データベース名A⦆'.* TO '⦅MariaDBのユーザー名⦆'@localhost IDENTIFIED BY '⦅MariaDBのユーザーのパスワード⦆';

-- 作成したユーザーに ⦅データベース名B⦆ に対する権限も付与
GRANT ALL PRIVILEGES ON '⦅データベース名B⦆'.* TO '⦅MariaDBのユーザー名⦆'@localhost;

-- 権限テーブルの再読み込み
FLUSH PRIVILEGES;

-- ログアウト
exit

SFTP

SFTPユーザーの作成

ホームディレクトリをSFTPルートディレクトリとするユーザーを「homeroot」、ホームディレクトリの下位ディレクトリ public_html をSFTPルートディレクトリとするユーザーを「dirroot」として説明します。

# シェルにログインできないユーザーを作成
sudo adduser --shell /sbin/nologin homeroot
sudo passwd homeroot
sudo adduser --shell /sbin/nologin dirroot
sudo passwd dirroot

SSH公開鍵を設定

  1. Tera Term メニューバーから、設定 ▸ SSH鍵生成 を開きます。
  2. 「生成」ボタンを押すと鍵が生成されます。
  3. パスフレーズを入力します。11
  4. 「秘密鍵の保存」ボタンを押し、任意の場所に保存します。12
  5. 「公開鍵の保存」ボタンを押し、任意の場所に保存します。12
  6. 保存した公開鍵を Tera Term ウィンドウ内にドラッグ&ドロップし、「SCP」でファイルを転送します。

「homeroot」の公開鍵を homeroot.pub、「dirroot」の公開鍵を dirroot.pub として説明します。

# SSHの設定ディレクトリを作成
sudo mkdir --mode=500 /home/{homeroot,dirroot}/.ssh

# 公開鍵を設定ディレクトリに配置
sudo mv ~/homeroot.pub /home/homeroot/.ssh/authorized_keys
sudo mv ~/dirroot.pub /home/dirroot/.ssh/authorized_keys

# SSHの設定ディレクトリ、および公開鍵のアクセス権・所有者を変更
sudo chmod 400 /home/{homeroot,dirroot}/.ssh/authorized_keys
sudo chown --recursive homeroot:homeroot /home/homeroot/.ssh
sudo chown --recursive dirroot:dirroot /home/dirroot/.ssh

#【SELinux】公開鍵のラベルを貼り直す
sudo restorecon /home/{homeroot,dirroot}/.ssh/authorized_keys

SFTPルートディレクトリの設定

SFTP ルートディレクトリとその上位ディレクトリの所有者が root 以外の場合、ChrootDirectory を設定したときに接続を弾かれます。

# SFTPルートディレクトリの作成、ディレクトリの所有者を変更
sudo chown root /home/{homeroot,dirroot}
sudo chmod 750 /home/{homeroot,dirroot}
sudo mkdir --mode=775 /home/dirroot/public_html
sudo chgrp dirroot /home/dirroot/public_html

#【SELinux】SSHによるホームディレクトリの読み書きを許可
sudo setsebool -P ssh_chroot_rw_homedirs on
sudo restorecon -R /home/homeroot

ここでは、ホームディレクトリ自体には書き込めないようにしています。

ドキュメントルートからマウント

HTTP サーバーのドキュメントルート下位に直接ファイルをアップロードする例です。

/etc/fstab
                        ##############
                        ## 以上省略 ##
                        ##############

# ↓この行を追記
/var/www/common /home/ftpuser/common none bind 0 0

/etc/fstab の末尾には必ず改行を入れてください。

# ドキュメントルートのグループを変更、グループにも書き込み権限を与える
sudo chgrp homeroot /var/www/html
sudo chmod 775 /var/www/html

# マウント先のディレクトリ (マウントポイント) を作成
sudo mkdir /home/homeroot/html

# /etc/fstab の設定を適用
sudo mount -a

OpenSSHの設定

/etc/ssh/sshd_config
                        ##############
                        ## 以上省略 ##
                        ##############

# no default banner path
#Banner none

# Accept locale-related environment variables
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS

# override default of no subsystems
#Subsystem  sftp        /usr/libexec/openssh/sftp-server
## ↑この行をコメントアウト ##
Subsystem   sftp        internal-sftp
## ↑この行を追加 ##

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

## ↓この行以降を追記 ##
Match User homeroot,dirroot
      ForceCommand internal-sftp

Match User homeroot
      ChrootDirectory %h

Match User dirroot
      ChrootDirectory %h/public_html

FileZillaから接続

秘密鍵の設定

アカウントごとではなく、まとめて登録を行います。

  1. FileZilla FTP Client メニューバーから、編集 ▸ 設定 を開きます。
  2. 設定ダイアログの左のメニューで、接続 ▸ SFTP とたどります。
  3. 設定ダイアログ真ん中下あたりの「鍵ファイルを追加」ボタンを押し、秘密鍵ファイルを登録します。
    • パスフレーズで保護されていないPuTTY形式の鍵のみ利用可能です。
    • 上記以外の形式の鍵を登録しようとすると、鍵を変換するか訊ねられます。
    • bcrypt KDF 形式の鍵は解析できず、FileZillaでは変換もできません。
    • アカウントごとに複数の秘密鍵が存在する場合でも、すべてここに追加します。

接続設定

  1. FileZilla FTP Client メニューバーから、ファイル ▸ サイト マネージャ を開きます。
  2. 左下の「新しいサイト」ボタンを押し、任意の名前を付けます。
  3. ホスト欄にサーバーのIPアドレス、ポート欄にOpenSSHで使用するポート番号を入力します。
  4. プロトコルのプルダウンメニューで「SFTP - SSH File Transfer Protocol」を選択します。
  5. ログオンの種類のプルダウンメニューで「通常」を選択します。
  6. ユーザ欄には Linux のユーザー名を記入し、パスワードは空欄にします。
  7. 必要であれば、「詳細」タブの「既定のローカル ディレクトリ」と「既定のリモート ディレクトリ」に記入し、「同期ブラウジングを使用」にチェックを入れます。
    • 「既定のリモート ディレクトリ」は、SFTPルートディレクトリからの絶対パスになっている必要があります。
  8. 「接続」

参考ページ・脚注


  1. クライアントと通信中の場合は強制的に切断します。 

  2. systemctl コマンドを介していないため、systemctl status httpd でステータスを表示した際、Active 欄に failed (Result: exit-code) と表示されます。 

  3. クライアントと通信中の子プロセスを強制終了せず、通信が終わったプロセスから順に停止します。 

  4. クライアントと通信中の子プロセスを強制終了せず、通信が終わったプロセスから順に新しいプロセスに置き換えていきます。 

  5. 一般ユーザーには /var/log/httpd 以下の読み込み権限が与えられていないため、エラーログやアクセスログの読み取りには root 権限が必要です。 

  6. 初期設定ではTLS接続のアクセスログを /var/log/httpd/ssl_access_log に記録するようになっている場合があります。 

  7. nano (日本語) - ArchWiki 

  8. 37.nanoエディタの設定ファイル、nanorcをいじる | Linuxゲリラ戦記 

  9. MySQL 5.5.3-m3, 5.5.4-m3 同時リリース - sakaikの日々雑感~(T)編 

  10. mysql Options | mysql Command-line Client - MariaDB Knowledge Base 

  11. いざログインしようとしたときに認証失敗しないよう、記号や暗号化方式の互換性 に目を通しておいてください。 

  12. OpenSSH 形式で保存されます。 

8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8