0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Conoha VPS Ver.3.0でWebサーバ構築(その1)

0
Last updated at Posted at 2026-10-31

今回やりたいこと

今、Conoha VPSでブログを運営しているのですが、
Conoha VPSコンソールが未だにVer.2.0を使用しています。

image.png

Webサーバを立ち上げたのが2019年なので、その4年後にVer.3.0が登場したんですね。
そして、ログインする度に「Ver.3.0が使えますよ!」ってうるさい。
しかし、Ver.2.0で作成したインスタンスはVer.3.0に引っ越すことができません。

が、最近、情報漏洩が社会問題になっていますし、
この際にVer.3.0にサーバを1から再構築するもの手だな、と思いました。

この記事は、その際の作業メモのまとめです。

サーバの選択

image.png

  • サービスはVPS
  • イメージタイプはUbuntu 26.04(現時点で最新の安定バージョン)

image.png

  • オプションはSSH Keyを新規に自動作成してもらいました

SSH KeyはSSHでVPSにログインするのに必要なので、ダウンロードしたら無くさないように。
再ダウンロードはできません。

VPSにSSH接続

ここで、VPSにSSHでログイン出来なくて悩みました。
インスタンス作成時に固定IPアドレスも割り当てられたのですが、そのIPアドレスにSSHどころかpingも届かないのです。

で、原因はセキュリティグループの設定でした。

元ネタはこれ。
https://qiita.com/plnnano/items/d55b8d76ec010bc9ce85

image.png

セキュリティグループがdefaultだけのままでは「何も受け付けない」という設定(と認識)なので、セキュリティグループを以下に設定します。
image.png
要は許可するプロトコルをセキュリティグループに設定する必要があるんですね。

PS> ssh -i "$env:USERPROFILE\.ssh\conoha.pem" root@[IPアドレス]

ダウンロードしたSSH Keyはconoha.pemにリネームして、[ユーザー]/.ssh/配下に保存しています。

rootでログインを確認したら次に行きます。

ユーザー作成

ここではrootではないユーザーを作成して、sudo権限を付与します。

ユーザー作成

# adduser taki

sudo権限を付与

# usermod -aG sudo taki

SSH公開鍵を登録

作成したユーザーにSSH公開鍵を設定し、SSH Keyを使用したログインを可能にします。
SSH Keyはrootと同じ物を使用します。
将来的にはrootでのログインを禁止するので。

PS> ssh-keygen -y -f "$env:USERPROFILE\.ssh\conoha.pem"

テキストが出力されるので、

# install -d -m 700 -o taki -g taki /home/taki/.ssh
# nano /home/taki/.ssh/authorized_keys

テキストの内容を貼り付けて保存。

chown taki:taki /home/taki/.ssh/authorized_keys
chmod 600 /home/taki/.ssh/authorized_keys

SSHでユーザーログイン

PS> ssh -i "$env:USERPROFILE\.ssh\conoha.pem" taki@[IPアドレス]

ログイン出来たら以下でsudo権限があることを確認。

$ sudo whoami

image.png

リブート後に公開鍵認証が機能していることを確認する。

$ sudo reboot
PS> ssh -o PreferredAuthentications=publickey -o PasswordAuthentication=no -i "$env:USERPROFILE\.ssh\conoha.pem" taki@[IPアドレス]

SSHのセキュリティ強化

以下の設定を行います。

  • rootユーザーのSSHログインを禁止
  • パスワード認証を無効化して公開鍵認証だけにする
  • SSHの認証試行回数を制限する

公開鍵認証の確認

PS> ssh -o IdentitiesOnly=yes `
    -o PreferredAuthentications=publickey `
    -o PasswordAuthentication=no `
    -i "$env:USERPROFILE\.ssh\conoha.pem" `
    taki@[IPアドレス]

ログインしたままにしておいて操作する。

現在のSSH設定を確認

sudo sshd -T | grep -E '^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication|pubkeyauthentication|maxauthtries) '
taki@vm-07bd3644-8a:~$ sudo sshd -T | grep -E '^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication|pubkeyauthentication|maxauthtries) '
[sudo: authenticate] Password:
maxauthtries 6
permitrootlogin yes
pubkeyauthentication yes
passwordauthentication no
kbdinteractiveauthentication no

すでにパスワード認証は無効化されているので、
rootでのログインを禁止し、試行回数を3回に変更します。

既存設定を確認

$ sudo grep -RnE '^[[:space:]]*(Include|PermitRootLogin|MaxAuthTries)' \
  /etc/ssh/sshd_config /etc/ssh/sshd_config.d/
taki@vm-07bd3644-8a:~$ sudo grep -RnE '^[[:space:]]*(Include|PermitRootLogin|MaxAuthTries)' \
  /etc/ssh/sshd_config /etc/ssh/sshd_config.d/
/etc/ssh/sshd_config:24:Include /etc/ssh/sshd_config.d/*.conf
/etc/ssh/sshd_config:54:PermitRootLogin yes

/etc/ssh/sshd_config:24:Include /etc/ssh/sshd_config.d/*.conf
/etc/ssh/sshd_config:54:PermitRootLogin yes
この順番で設定を読み込んで適用しているので、
追加設定ファイルで設定を上書きする。

セキュリティ設定ファイルを作成

$ sudo nano /etc/ssh/sshd_config.d/00-hardening.conf

以下を貼り付けて保存。

# SSH security hardening
PermitRootLogin no
MaxAuthTries 3
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes

構文チェック

sudo sshd -t

何も出力されなければOK。

設定内容の確認

sudo sshd -T | grep -E '^(permitrootlogin|maxauthtries|passwordauthentication|kbdinteractiveauthentication|pubkeyauthentication) '

以下が出力されればOK

maxauthtries 3
permitrootlogin no
pubkeyauthentication yes
passwordauthentication no
kbdinteractiveauthentication no

SSHの設定を反映

$ sudo systemctl reload ssh

サービスの状態を確認

$ systemctl is-active ssh

activeと表示されればOK

接続確認

ほかのPowerShellから実行

ユーザーログインが出来ることを確認

PS> ssh -o IdentitiesOnly=yes -o PreferredAuthentications=publickey -o PasswordAuthentication=no -i "$env:USERPROFILE\.ssh\conoha.pem" taki@[IPアドレス]

接続できればOK

rootログインが出来ないことを確認

PS> ssh -o BatchMode=yes -i "$env:USERPROFILE\.ssh\conoha.pem" root@[IPアドレス]
Permission denied (publickey).

と表示されればOK

UFWの設定確認

セキュリティグループによる保護+ubuntuのファイヤーウォールの保護を目指します。

現在の設定を確認

$ sudo ufw status verbose
taki@vm-07bd3644-8a:~$ sudo ufw status verbose
[sudo: authenticate] Password:
Status: active
Logging: on (low)
Default: reject (incoming), allow (outgoing), disabled (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
22/tcp (OpenSSH)           ALLOW IN    Anywhere
22/tcp (OpenSSH (v6))      ALLOW IN    Anywhere (v6)

taki@vm-07bd3644-8a:~$ sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
Rule added
Rule added (v6)
Rule added
Rule added (v6)
taki@vm-07bd3644-8a:~$ sudo ufw status numbered
Status: active

     To                         Action      From
     --                         ------      ----
[ 1] OpenSSH                    ALLOW IN    Anywhere
[ 2] 80/tcp                     ALLOW IN    Anywhere
[ 3] 443/tcp                    ALLOW IN    Anywhere
[ 4] OpenSSH (v6)               ALLOW IN    Anywhere (v6)
[ 5] 80/tcp (v6)                ALLOW IN    Anywhere (v6)
[ 6] 443/tcp (v6)               ALLOW IN    Anywhere (v6)

すでに設定済みでした。

ポート 用途 IPv4 IPv6
22/TCP SSH 許可 許可
80/TCP HTTP 許可 許可
443/TCP HTTPS 許可 許可
その他の受信 不要な通信 原則拒否 原則拒否

さらに、

  • Status: active → UFW有効
  • Default: reject (incoming) → 未許可の受信通信を拒否
  • allow (outgoing) → 外部への通信は許可
  • Logging: on (low) → ファイアウォールのログ記録も有効

自動セキュリティアップデート

インストール状態の確認

$ dpkg -l unattended-upgrades
taki@vm-07bd3644-8a:~$ dpkg -l unattended-upgrades
┌── Desired=Unknown/Install/Remove/Purge/Hold
│┌─ Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
││┌ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
│││ Name                Version      Architecture Description
├┼┼─═══════════════════─════════════─════════════─═══════════════════════════════════════════
ii  unattended-upgrades 2.12ubuntu9  all          automatic installation of security upgrades

インストール済みでした。

自動更新の設定の確認

$ cat /etc/apt/apt.conf.d/20auto-upgrades
taki@vm-07bd3644-8a:~$ cat /etc/apt/apt.conf.d/20auto-upgrades
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
taki@vm-07bd3644-8a:~$ systemctl list-timers 'apt-daily*'
NEXT                        LEFT LAST                        PASSED UNIT                    ACTIVATES
Mon 2026-10-26 05:32:29 JST  12h Sun 2026-10-25 09:03:05 JST      - apt-daily.timer         apt-daily.service
Mon 2026-10-26 06:02:10 JST  12h Sun 2026-10-25 06:04:52 JST      - apt-daily-upgrade.timer apt-daily-upgrade.service

2 timers listed.
Pass --all to see loaded but inactive timers, too.

APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
これが"1"になっていれば有効になっている状態です。

自動再起動の設定確認

現在の設定内容を確認

$ sudo grep -RnE '^[[:space:]]*Unattended-Upgrade::(Allowed-Origins|Origins-Pattern|Automatic-Reboot)' \
  /etc/apt/apt.conf.d/
taki@vm-07bd3644-8a:~$ sudo grep -RnE '^[[:space:]]*Unattended-Upgrade::(Allowed-Origins|Origins-Pattern|Automatic-Reboot)' \
  /etc/apt/apt.conf.d/
/etc/apt/apt.conf.d/50unattended-upgrades:6:Unattended-Upgrade::Allowed-Origins {
$ sudo sed -n '1,85p' /etc/apt/apt.conf.d/50unattended-upgrades
taki@vm-07bd3644-8a:~$ sudo sed -n '1,85p' /etc/apt/apt.conf.d/50unattended-upgrades
// Automatically upgrade packages from these (origin:archive) pairs
//
// Note that in Ubuntu security updates may pull in new dependencies
// from non-security sources (e.g. chromium). By allowing the release
// pocket these get automatically pulled in.
Unattended-Upgrade::Allowed-Origins {
        "${distro_id}:${distro_codename}";
        "${distro_id}:${distro_codename}-security";
        // Extended Security Maintenance; doesn't necessarily exist for
        // every release and this system may not have it installed, but if
        // available, the policy for updates is such that unattended-upgrades
        // should also install from here by default.
        "${distro_id}ESMApps:${distro_codename}-apps-security";
        "${distro_id}ESM:${distro_codename}-infra-security";
//      "${distro_id}:${distro_codename}-updates";
//      "${distro_id}:${distro_codename}-proposed";
//      "${distro_id}:${distro_codename}-backports";
};

// Python regular expressions, matching packages to exclude from upgrading
Unattended-Upgrade::Package-Blacklist {
    // The following matches all packages starting with linux-
//  "linux-";

    // Use $ to explicitely define the end of a package name. Without
    // the $, "libc6" would match all of them.
//  "libc6$";
//  "libc6-dev$";
//  "libc6-i686$";

    // Special characters need escaping
//  "libstdc\+\+6$";

    // The following matches packages like xen-system-amd64, xen-utils-4.1,
    // xenstore-utils and libxenstore3.0
//  "(lib)?xen(store)?";

    // For more information about Python regular expressions, see
    // https://docs.python.org/3/howto/regex.html
};

// This option controls whether the development release of Ubuntu will be
// upgraded automatically. Valid values are "true", "false", and "auto".
Unattended-Upgrade::DevRelease "auto";

// This option allows you to control if on a unclean dpkg exit
// unattended-upgrades will automatically run
//   dpkg --force-confold --configure -a
// The default is true, to ensure updates keep getting installed
//Unattended-Upgrade::AutoFixInterruptedDpkg "true";

// Split the upgrade into the smallest possible chunks so that
// they can be interrupted with SIGTERM. This makes the upgrade
// a bit slower but it has the benefit that shutdown while an upgrade
// is running is possible (with a small delay)
//Unattended-Upgrade::MinimalSteps "true";

// Install all updates when the machine is shutting down
// instead of doing it in the background while the machine is running.
// This will (obviously) make shutdown slower.
// Unattended-upgrades increases logind's InhibitDelayMaxSec to 30s.
// This allows more time for unattended-upgrades to shut down gracefully
// or even install a few packages in InstallOnShutdown mode, but is still a
// big step back from the 30 minutes allowed for InstallOnShutdown previously.
// Users enabling InstallOnShutdown mode are advised to increase
// InhibitDelayMaxSec even further, possibly to 30 minutes.
//Unattended-Upgrade::InstallOnShutdown "false";

// Send email to this address for problems or packages upgrades
// If empty or unset then no email is sent, make sure that you
// have a working mail setup on your system. A package that provides
// 'mailx' must be installed. E.g. "user@example.com"
//Unattended-Upgrade::Mail "";

// Set this value to one of:
//    "always", "only-on-error" or "on-change"
// If this is not set, then any legacy MailOnlyOnError (boolean) value
// is used to chose between "only-on-error" and "on-change"
//Unattended-Upgrade::MailReport "on-change";

// Remove unused automatically installed kernel-related packages
// (kernel images, kernel headers and kernel version locked tools).
//Unattended-Upgrade::Remove-Unused-Kernel-Packages "true";

// Do automatic removal of newly unused dependencies after the upgrade
taki@vm-07bd3644-8a:~$ apt-config dump | grep -E '^Unattended-Upgrade::Automatic-Reboot'
taki@vm-07bd3644-8a:~$

セキュリティ更新のみを対象にしたいので、

Unattended-Upgrade::Allowed-Origins {
        "${distro_id}:${distro_codename}";
        "${distro_id}:${distro_codename}-security";
        "${distro_id}ESMApps:${distro_codename}-apps-security";
        "${distro_id}ESM:${distro_codename}-infra-security";
};

これを

Unattended-Upgrade::Allowed-Origins {
        "${distro_id}:${distro_codename}-security";
        "${distro_id}ESMApps:${distro_codename}-apps-security";
        "${distro_id}ESM:${distro_codename}-infra-security";
        "${distro_id}:${distro_codename}-updates";
};

に変更。

自動再起動を明示的に無効化

$ sudo nano /etc/apt/apt.conf.d/52unattended-upgrades-local

以下を記述を追加して保存。

Unattended-Upgrade::Automatic-Reboot "false";

ドライラン

$ sudo unattended-upgrade --dry-run --debug

エラーがなければOK。

Fail2banの導入

Fail2banは不正ログインを検知すると、そのIPアドレスからの接続を一時的に遮断するツール。

インストールの確認

$ dpkg -l fail2ban
taki@vm-07bd3644-8a:~$ dpkg -l fail2ban
┌── Desired=Unknown/Install/Remove/Purge/Hold
│┌─ Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
││┌ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
│││ Name           Version      Architecture Description
├┼┼─══════════════─════════════─════════════─═══════════════════════════════════════════════════
ii  fail2ban       1.1.0-9      all          ban hosts that cause multiple authentication errors
taki@vm-07bd3644-8a:~$

サービスの稼働状態の確認

$ sudo systemctl status fail2ban --no-pager

Fail2banの全体状態の確認

$ sudo systemctl status fail2ban --no-pager

SSH監視の状態の確認

$ sudo systemctl status fail2ban --no-pager
taki@vm-07bd3644-8a:~$ sudo systemctl status fail2ban --no-pager
● fail2ban.service - Fail2Ban Service
     Loaded: loaded (/usr/lib/systemd/system/fail2ban.service; enabled; preset: enabled)
     Active: active (running) since Mon 2026-10-26 06:03:16 JST; 1 day 12h ago
 Invocation: a5ca15c04e694a29b0c018b149f59833
       Docs: man:fail2ban(1)
   Main PID: 11166 (fail2ban-server)
      Tasks: 5 (limit: 420)
     Memory: 17.4M (peak: 20.4M)
        CPU: 2min 9.242s
     CGroup: /system.slice/fail2ban.service
             └─11166 /usr/bin/python3 /usr/bin/fail2ban-server -xf start

Oct 26 06:03:16 vm-07bd3644-8a systemd[1]: Started fail2ban.service - Fail2Ban Service.
Oct 26 06:03:16 vm-07bd3644-8a fail2ban-server[11166]: Server ready
taki@vm-07bd3644-8a:~$ sudo fail2ban-client status
Status
|- Number of jail:      1
`- Jail list:   sshd
taki@vm-07bd3644-8a:~$ sudo fail2ban-client status sshd
Status for the jail: sshd
|- Filter
|  |- Currently failed: 0
|  |- Total failed:     258
|  `- Journal matches:  _SYSTEMD_UNIT=ssh.service + _COMM=sshd
`- Actions
   |- Currently banned: 5
   |- Total banned:     14
   `- Banned IP list:   195.178.110.227 175.6.146.164 101.96.220.35 195.178.110.217 2.57.122.76
taki@vm-07bd3644-8a:~$

fail2banの遮断ルールを確認

sudo fail2ban-client get sshd actions
sudo fail2ban-client get sshd maxretry
sudo fail2ban-client get sshd findtime
sudo fail2ban-client get sshd bantime
taki@vm-07bd3644-8a:~$ sudo fail2ban-client get sshd actions
The jail sshd has the following actions:
nftables
taki@vm-07bd3644-8a:~$ sudo fail2ban-client get sshd maxretry
sudo fail2ban-client get sshd findtime
sudo fail2ban-client get sshd bantime
5
600
86400
taki@vm-07bd3644-8a:~$

現在のFail2ban設定

設定項目 現在の値 意味
actions nftables nftablesでIPアドレスを遮断
maxretry 5回 認証失敗5回でBAN
findtime 600秒 10分間の失敗回数を集計
bantime 86400秒 24時間BAN

これで一旦VPSの立ち上げ完了。
基本的に何も設定しなくても、必要な設定は出来ていましたね。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?