4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

自宅サーバーをcloudflare経由でSSH接続できるようにした話

Last updated at Posted at 2023-10-21

目次

はじめに

1. パスワードログインの無効化
2. SSHポートの変更
3. ファイアウォールの設定
4. クラウドフレアトンネルの設定

おわりに

はじめに

前回は自作サーバーにUbuntuをインストールしてメインPCとSSH接続できるようにしました。↓

今回は自宅サーバーにファイアウォールなどを設定してサーバーを公開していきます。

前提:

  • サーバーにSSH接続ができる
  • 独自ドメインを取得している
  • cloudflareのアカウントを持っている
  • cloudflareを独自ドメインのDNSサーバーとして使用している

1. パスワードログインの無効化

サーバー側で/etc/ssh/sshd_configを開き、以下を追記します。

PasswordAuthentication no

ついでにrootユーザーでのSSH接続を無効化しておきます。

PermitRootLogin no

再起動をして設定を反映させます。

sudo reboot

2. SSHポートの変更

SSHポートをデフォルトの22番から変更しておくことでセキュリティを向上させることができます。

参考: https://dream.jp/vps/support/manual/mnl_security_03.html

/etc/ssh/sshd_configに以下を追記します。

Port {ポート番号}

ポート番号は1024以上の番号にしましょう。

最後にメインPCの~/.ssh/configでポート番号を指定します。

~/.ssh/config
Host {サーバー名}
    User ...
    IdentityFile ...
    HostName ...
    Port {指定したポート番号} (←new!)

3. ファイアウォールの設定

サーバー側で以下のコマンドを実行します。

sudo ufw allow {SSHのポート番号}
sudo ufw enable

4. クラウドフレアトンネルの設定

4-1. サーバー側の設定

こちらのドキュメントに従って進めていきます。

  1. cloudflareのコンソールにログイン
  2. 「Zero Trust」→「Access」→「Tunnels」でトンネルの設定へ行き、「Create a tunnel」を選択
  3. 表示されたコマンドをサーバー側で実行
  4. 「Public Hostname」からドメインを選択。ServiceはSSHを選択してlocalhost:{SSHのポート}を指定する
    • 指定したホスト名は後で使うのでメモっておきましょう

4-2. クライアント側の設定

こちらのドキュメントに従って設定をしていきます。

まずはこちら↓のリンクからcloudflareのアプリをインストールします。

インストールが終わったらwhere cloudflaredで実行ファイルへのパスを確認します。

$ which cloudflared
/usr/bin/cloudflared (環境によって結果は異なります)

~/.ssh/configの設定を以下のように修正します

~/.ssh/config
Host {サーバー名}
    User ...
    IdentityFile ...
    Port ...
    ProxyCommand {先程確認したパス} access ssh --hostname {cloudflareで指定したホスト名}

これでssh {サーバー名}とコマンドを実行するとサーバーにログインができるはずです。

おわりに

今回はcloudflare経由でサーバーにログインができるようにしました。これで自宅以外の場所からでもサーバーにアクセスできるようになりました。
次回は自宅サーバー上でWebサーバーを立てて公開できるようにしようと思います。

参考資料

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?