1
0

More than 3 years have passed since last update.

Conoha VPSでUbuntu構築(WSL + Windows Terminal)

Last updated at Posted at 2021-03-08

2021/3/10追記: VPSでブログという目的でこの記事を執筆しましたが、
VPSでお金を払ってブログという考えは、あまりトレンドではないような気もしてきたのでもう少し考えます。
また他にもWEBについて色々勉強したいので、他のことで実現できるように検討します。
この記事はConohaUbuntuにSSH接続までで終わりとします。

概要

本記事では、Conoha VPSでUbuntuをインストールし、ブログ運営を行うまでの道のりを書いています。
また、わからないところは逐次調べながらやってるのでかなり冗長です。
不必要な情報も多数あると思いますので、わかるところは飛ばしながら読んでいただけたらと思います。
また、作業した順番をベースに本記事を執筆しましたので、設定の順番等おかしなところもあると思いますが、ご了承ください。
致命的な問題があれば修正します。

なぜUbuntuなのか

OSはUbuntuを選びました。2013~2018年頃はCentOSも主流だったと思います。
私も以前CentOSを使っていました。CentOSは2021/12/31でサポート終了するらしいです。

https://w3techs.com/technologies/history_details/os-linux/all/y
ここを見てUbuntuを選択しました。Linuxディストリビューションの中で1番のシェアを誇ってるようです。
2015年ほど前だと私の中でUbuntuはGUIのイメージがありましたが。

Conohaを申し込む

申し込む。割愛。

SSHクライアント

まず、SSH接続のクライアントについて。

2015年頃は私はPuTTYごった煮版を使用していました。
他の方がPuTTYの日本語版を開発されてるようですが、ごった煮版はもう公開していないらしい。
現在はトレンドが変わっているみたいです。
候補としては
・RLogin → 老舗
・TeraTerm → 老舗
・Windows Terminal → 現在Microsoftが開発中

試しに、Windows Terminalを使ってみることにしました。

Windows Terminalについて

Windows TerminalはTerminal本体というわけではなく、コンソールアプリケーションの"cmd.exe","PowerShell"などを統合できるソフトウェアというほうが意味合いが近い気がします。

今回は、Linux環境からやりたい為、まずWindowsにも「Windows Subsystem for Linux」通称「WSL」でUbuntuをいれます。

WSL2というバージョンアップ版もあるが、今回はWSLで行いました。今後移行するかは検討中。

作業する前に

WSLを構築する上で色々やり直したいとき

「アプリと機能」からUbuntu環境をリセット可能です。

参考:https://www.atmarkit.co.jp/ait/articles/1807/06/news028.html

Conohaでもわからなくなったら

https://support.conoha.jp/v/changeos/
わかんなくなったらここみてサーバー再構築してやり直しましょう。

1. Windows Subsystem for Linux (WSL)構築

1-1. WSLインストール

参考:https://qiita.com/matarillo/items/61a9ead4bfe2868a0b86

WSL画面
Installing, this may take a few minutes...
Please create a default UNIX user account. The username does not need to match your Windows username.
For more information visit: https://aka.ms/wslusers
Enter new UNIX username:

1-2. 一般ユーザの追加

一般のユーザ名を聞かれるので、適宜入力。今回はwsluserとします。
以下、【】は入力項目として読み替えてください。

WSL画面
Enter new UNIX username: 【wsluser】
New password:【パスワード入力】
Retype new password:【パスワード入力(確認)】
passwd: password updated successfully
Installation successful!
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.

Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 4.4.0-18362-Microsoft x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Mon Mar  8 11:51:01 JST 2021

  System load:           0.52
  Usage of /home:        unknown
  Memory usage:          33%
  Swap usage:            0%
  Processes:             7
  Users logged in:       0
  IPv4 address for eth0: ********************
  IPv6 address for eth0: ********************
  IPv6 address for eth0: ********************

1 update can be installed immediately.
0 of these updates are security updates.
To see these additional updates run: apt list --upgradable


The list of available updates is more than a week old.
To check for new updates run: sudo apt update


This message is shown once a day. To disable it please create the
/home/wsluser/.hushlogin file.

一旦exit

WSL画面
exit

コマンドプロンプトからrootログイン。

cmd.exe
wsl -d Ubuntu -u root

1-3. rootのパスワード変更

初期はPWかかってない為、パスワード変更しておく。

cmd.exe
Microsoft Windows [Version 10.0.18363.1379]
(c) 2019 Microsoft Corporation. All rights reserved.

C:\Users\wsluser>wsl -d Ubuntu -u root
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 4.4.0-18362-Microsoft x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Mon Mar  8 11:54:31 JST 2021

  System load:           0.52
  Usage of /home:        unknown
  Memory usage:          33%
  Swap usage:            0%
  Processes:             9
  Users logged in:       0
  IPv4 address for eth0: ******************
  IPv6 address for eth0: ******************
  IPv6 address for eth0: ******************

1 update can be installed immediately.
0 of these updates are security updates.
To see these additional updates run: apt list --upgradable


The list of available updates is more than a week old.
To check for new updates run: sudo apt update


This message is shown once a day. To disable it please create the
/root/.hushlogin file.
root@PCNAME:/mnt/c/Users/wsluser#

cmd.exe
root@PCNAME:/mnt/c/Users/wsluser# passwd root
New password:【パスワード入力】
Retype new password:【パスワード入力(確認)】
passwd: password updated successfully

1-4. WSLのパッケージアップデート

sudo apt update

WSLのインストール時に作成したユーザはデフォルトでsudoグループに含まれているようです。

2. Windows Terminal

2-1. インストール

Microsoft Storeからインストールしてください。

2-2. ログイン時の開始ディレクトリを変更

特に変えなくてもいいですが、デフォルトはWindowsのユーザフォルダなので変更します。

設定から「ディレクトリの開始」を変更。

WindowsTerminal
%USERPROFILE%

WindowsTerminal
//wsl$/Ubuntu/home/[ユーザ名]

絶対パスしか通らなかった。「~」もダメだし空欄でもだめだでした。
シェルでログインするまではあくまでもWindowsのファイルシステムで考えられるのでしょうか。
Windowsのエクスプローラでも入れる上記記述で可能になりました。

参考:https://itengine.seesaa.net/article/474052291.html

3. Windows TerminalでUbuntuからSSH接続

3-1. Conohaにrootログイン

とりあえずConohaにrootでログイン
IPADDRESSは各人のIPADDRESSに読み替えてください。

Conoha
wsluser@PCNAME:~$ ssh root@IPADDRESS
root@IPADDRESS's password:
Welcome to Ubuntu 20.04.1 LTS (GNU/Linux 5.4.0-42-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Mon 08 Mar 2021 01:38:52 PM JST

  System load:  0.0                Processes:             109
  Usage of /:   17.1% of 29.40GB   Users logged in:       1
  Memory usage: 35%                IPv4 address for eth0: IPADDRESS
  Swap usage:   3%

 * Introducing self-healing high availability clusters in MicroK8s.
   Simple, hardened, Kubernetes for production, from RaspberryPi to DC.

     https://microk8s.io/high-availability

108 updates can be installed immediately.
0 of these updates are security updates.
To see these additional updates run: apt list --upgradable


*** System restart required ***
Last login: Mon Mar  8 11:33:00 2021
root@IPADDRESS:~#

3-2. 一般ユーザ作成

「conohauser」とした。

root@IPADDRESS:~# adduser conohauser
Adding user `conohauser' ...
Adding new group `conohauser' (1000) ...
Adding new user `conohauser' (1000) with group `conohauser' ...
Creating home directory `/home/conohauser' ...
Copying files from `/etc/skel' ...
New password:
Retype new password:
passwd: password updated successfully
Changing the user information for conohauser
Enter the new value, or press ENTER for the default
        Full Name []:
        Room Number []:
        Work Phone []:
        Home Phone []:
        Other []:
Is the information correct? [Y/n] y

注釈:adduserはホームディレクトリも作成してくれる。useraddはホームディレクトリ作成してくれない。

参考:https://www-creators.com/archives/241

3-3. Conoha Update

Conoha側もUpdateしておく。

apt update

sudo apt-get dist-upgradeもしないとだめみたい?

sudo apt-get dist-upgrade
(中略)
105 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
Need to get 142 MB of archives.
After this operation, 22.6 MB of additional disk space will be used.
Do you want to continue? [Y/n]

YesでEnter。

Configuration file '/etc/cloud/cloud.cfg'
 ==> Modified (by you or by a script) since installation.
 ==> Package distributor has shipped an updated version.
   What would you like to do about it ?  Your options are:
    Y or I  : install the package maintainer's version
    N or O  : keep your currently-installed version
      D     : show the differences between the versions
      Z     : start a shell to examine the situation
 The default action is to keep your current version.
*** cloud.cfg (Y/I/N/O/D/Z) [default=N] ?

よくわからんが、全部インストールする。

Configuration file '/etc/cloud/cloud.cfg'
 ==> Modified (by you or by a script) since installation.
 ==> Package distributor has shipped an updated version.
   What would you like to do about it ?  Your options are:
    Y or I  : install the package maintainer's version
    N or O  : keep your currently-installed version
      D     : show the differences between the versions
      Z     : start a shell to examine the situation
 The default action is to keep your current version.
*** cloud.cfg (Y/I/N/O/D/Z) [default=N] ? y
Installing new version of config file /etc/cloud/cloud.cfg ...

Configuration file '/etc/cloud/cloud.cfg.d/05_logging.cfg'
 ==> Deleted (by you or by a script) since installation.
 ==> Package distributor has shipped an updated version.
   What would you like to do about it ?  Your options are:
    Y or I  : install the package maintainer's version
    N or O  : keep your currently-installed version
      D     : show the differences between the versions
      Z     : start a shell to examine the situation
 The default action is to keep your current version.
*** 05_logging.cfg (Y/I/N/O/D/Z) [default=N] ? y
Installing new version of config file /etc/cloud/cloud.cfg.d/05_logging.cfg ...
Installing new version of config file /etc/cloud/templates/hosts.freebsd.tmpl ...
Setting up initramfs-tools (0.136ubuntu6.3) ...
0 updates can be installed immediately.
0 of these updates are security updates

0 updateになった。

4. 公開鍵認証でSSH接続するようにする

4-1. Keyの作成

暗号方式はECDSAがいいらしい。

WSLのUbuntuのTerminalから行った。

WindowsTerminal
wsluser@PCNAME:~$ ssh-keygen -t ecdsa
Generating public/private ecdsa key pair.
Enter file in which to save the key (/home/wsluser/.ssh/id_ecdsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/wsluser/.ssh/id_ecdsa
Your public key has been saved in /home/wsluser/.ssh/id_ecdsa.pub
The key fingerprint is:
SHA256:******
The key's randomart image is:
+---[ECDSA 256]---+
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
+----[SHA256]-----+
wsluser@PCNAME:~$

4-2. Conoha側に公開鍵をコピーする。

WindowsTerminal
ssh-copy-id -i ~/.ssh/id_ecdsa.pub conohauser@IPADDRESS
WindowsTerminal
wsluser@PCNAME:~$ ssh-copy-id -i ~/.ssh/id_ecdsa.pub conohauser@IPADDRESS
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/wsluser/.ssh/id_ecdsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
conohauser@IPADDRESS's password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'conohauser@IPADDRESS'"
and check to make sure that only the key(s) you wanted were added.

ちなみにPowerShellでやる場合ssh-copy-idが使えないです。以下のコマンドで代替できます。

cat W:\Conoha\.ssh\id_ecdsa.pub | ssh user@IPADDRESS `
" `
mkdir -p ~/.ssh && chmod 700 ~/.ssh && `
cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys `
"
PS C:\Users\wsluser> cat Z:\Conoha\.ssh\id_ecdsa.pub | ssh user@IPADDRESS >`
>> " `
>> mkdir -p ~/.ssh && chmod 700 ~/.ssh && `
>> cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys `
>> "
The authenticity of host 'IPADDRESS (IPADDRESS)' can't be established.
ECDSA key fingerprint is SHA256::******.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'IPADDRESS' (ECDSA) to the list of known hosts.
user@IPADDRESS's password:

これで、ssh conohauser@IPADDRESSとやるだけで公開鍵認証でログインすることができるようになりました。

参考:https://qiita.com/kazokmr/items/754169cfa996b24fcbf5

ssh -i id_rsa [リモートユーザー]@[リモートサーバーのホスト名]
-i id_rsa には秘密鍵のパスを指定する。 なおデフォルトでは、 /home/[User名]/.ssh ディレクトリを参照>する。保管先が別ならパスで指定すること

5. 一般ユーザに権限付与

このままだと、一般ユーザーがsudoできない。

conohauser@IPADDRESS:~$ sudo ll
[sudo] password for conohauser:
conohauser is not in the sudoers file.  This incident will be reported.
conohauser@IPADDRESS:~$

とりあえずsu -

余談
suはsuper userではなく、substitute user
https://www.atmarkit.co.jp/ait/articles/1706/02/news014_2.html

conohauser@IPADDRESS:~$ su -
Password:
root@IPADDRESS:~#

5-1. visudoの編集

visudo見てみる。visudo実行。デフォはGNU nanoになってるみたい。

ちなみに/etc/sudoersを編集してる。visudoはそれを編集するコマンドで、別途用意されてる。
visudoで編集するようにします。

visudo
Ubuntu 20.04.2 LTS visudo
#
# This file MUST be edited with the 'visudo' command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#
# See the man page for details on how to write a sudoers file.
#
Defaults        env_reset
Defaults        mail_badpass
Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root    ALL=(ALL:ALL) ALL

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

# See sudoers(5) for more information on "#include" directives:

#includedir /etc/sudoers.d

CentOSのときと違う。wheelとかがない。

http://virtual.cocolog-nifty.com/virtualmachine/2013/12/wheel-sudo-cent.html
CentOS6.5のときのvisudo

CentOSvisudo
##
##      user    MACHINE=COMMANDS
##
## The COMMANDS section may have other options added to it.
##
## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL

## Allows members of the 'sys' group to run networking, software,
## service management apps and more.
# %sys ALL = NETWORKING, SOFTWARE, SERVICES, STORAGE, DELEGATING, PROCESSES, LOCATE, DRIVERS

## Allows people in group wheel to run all commands
%wheel        ALL=(ALL)       ALL

## Same thing without a password
# %wheel        ALL=(ALL)       NOPASSWD: ALL

## Allows members of the users group to mount and unmount the
## cdrom as root
# %users  ALL=/sbin/mount /mnt/cdrom, /sbin/umount /mnt/cdrom

## Allows members of the users group to shutdown this system
# %users  localhost=/sbin/shutdown -h now

## Read drop-in files from /etc/sudoers.d (the # here does not mean a comment)
#includedir /etc/sudoers.d

理解がてら全部軽く訳してみる。

参考:https://qiita.com/okkn/items/dfd736d7ca284f5c6be6
参考:http://manpages.ubuntu.com/manpages/focal/ja/man5/sudoers.5.html

5-2. CentOSのvisudo

CentOS_visudo
##
##      user    MACHINE=COMMANDS
##  構文の説明
##  訳:[ユーザ名] [マシン]=[コマンド]
##
## The COMMANDS section may have other options added to it.
## 訳:このコマンドセクションは他のオプションが追加される必要があります。
##
## Allow root to run any commands anywhere
## 訳:全てのディレクトリで全てのコマンドを実行できるようにrootに許可します。
root    ALL=(ALL)       ALL

## ユーザ"root"は全て(ALL)のユーザになることができ、全て(ALL)のコマンドを実行することができる。

# 【構文】
# ALL=(USER:GROUP) COMMANDS
# 【例】
# ALL=(ALL:ALL) ALL
#     全てのユーザ、全てのグループになることができ、全てのコマンドを実行できる。
# ALL=(ALL)     ALL
#     全てのユーザになることができ、全てのコマンドを実行できる。
# ALL=(:ALL)    ALL
#     全てのグループになることができ、全てのコマンドを実行できる。
# ALL=(ALL)     /usr/bin/ls
#     全てのユーザになることができ、コマンド"ls"のみ実行できる。
# ALL=(ALL)     /usr/bin/ls,/usr/bin/mkdir 
#     全てのユーザになることができ、コマンド"ls","mkdir"のみ実行できる。
# ※左辺のALLの意味は全ての「マシン(ホストとも読み替えれるか)」に対して許可するという意味である。
#  ここらへんの理解はできてないので、manpageを参照されたし。趣味でサーバ構築する分にはALLで問題ないと思う。

## Allows members of the 'sys' group to run networking, software,
## service management apps and more.
## 訳:'sys'グループのメンバが、ネットワーク、ソフトウェア、
##     サービス管理などのアプリを実行できるようにします。
##
## デフォルトではコメントアウトされており、機能していない。

# %sys ALL = NETWORKING, SOFTWARE, SERVICES, STORAGE, DELEGATING, PROCESSES, LOCATE, DRIVERS

# 【構文】
# 上のと同じだが、Groupを指定する場合は先頭に'%'を付ける必要がある。
# また、「NETWORKING」「SOFTWARE」・・・といったコマンドのグループをエイリアスで登録することによって、
# ","で区切らずとも特定の複数のコマンドに対して許可できるようになる。
# 例えばmanpageでは以下の例が取り上げられてる。

#     # Cmnd alias の指定
#       Cmnd_Alias     DUMPS = /usr/bin/mt, /usr/sbin/dump, /usr/sbin/rdump,\
#                      /usr/sbin/restore, /usr/sbin/rrestore,\
#                      sha224:0GomF8mNN3wlDt1HD9XldjJ3SNgpFdbjO1+NsQ== \
#                      /home/operator/bin/start_backups
#       Cmnd_Alias     KILL = /usr/bin/kill
#       Cmnd_Alias     PRINTING = /usr/sbin/lpc, /usr/bin/lprm
#       Cmnd_Alias     SHUTDOWN = /usr/sbin/shutdown
#       Cmnd_Alias     HALT = /usr/sbin/halt
#       Cmnd_Alias     REBOOT = /usr/sbin/reboot
#       Cmnd_Alias     SHELLS = /usr/bin/sh, /usr/bin/csh, /usr/bin/ksh,\
#                       /usr/local/bin/tcsh, /usr/bin/rsh,\
#                       /usr/local/bin/zsh
#       Cmnd_Alias     SU = /usr/bin/su
#       Cmnd_Alias     PAGERS = /usr/bin/more, /usr/bin/pg, /usr/bin/less

# もし、「NETWORKING」といったコマンドグループを有効にしたければ、
# Cmnd_Aliasを用いてエイリアス登録をする必要があるだろう。
# 【例】 Cmnd_Alias    NETWORKING  =  /usr/bin/su






## Allows people in group wheel to run all commands
## 訳:"wheel"グループの人間を全てのコマンドが実行できるように許可します。
%wheel        ALL=(ALL)       ALL


## Same thing without a password
## 訳:パスワードなしで同じことができます。
##
## 普通、sudoするとユーザのパスワードを求められますが、 NOPASSWD:ALLとすることで
## ユーザのパスワードを毎回認証しないようにすることができる。
## 
## もし、NOPASSWDを設定するのならば、特定のコマンドのみに絞ったほうがセキュリティ的にはいいだろう。
## 
# %wheel        ALL=(ALL)       NOPASSWD: ALL

# コマンドを絞った場合
# %wheel        ALL=(ALL)       NOPASSWD: /bin/commands


## Allows members of the users group to mount and unmount the
## cdrom as root
## 訳: "users"グループのメンバはrootとして"cdrom"ディレクトリを"マウント","アンマウント"
##     できるように許可します。

# %users  ALL=/sbin/mount /mnt/cdrom, /sbin/umount /mnt/cdrom

# ","の位置が重要。
# "users"グループのメンバは "mount /mnt/cdrom"と"unmount /mnt/cdrom"ができるようになる。
# もしカンマがない場合、"mount /mnt/cdrom unmount /mnt/cdrom"というコマンドを
# 実行できるようになり意図したものとは違う挙動を行う。
# ワイルドカードを使用し、コマンドを許可してる場合、更に深刻になる可能性がある。下記にmanpageを貼る。

# 以下manpage
#       sudoers 中でコマンドライン引き数にワイルドカードを使用するときは、 注意しなければならな
#       い。
#       コマンドライン引き数は、結合して一つの文字列にした上で、マッチングを行う。 そのため、'?'
#       や '*' といったワイルドカード文字が、 ユーザが指定したコマンドライン引き数と、 単語の境界
#       をまたいでマッチしてしまうことになるのだ。 これは想定外のことかもしれない。たとえ
#       ば、sudoers に次のような行があると、
#
#           %operator ALL = /bin/cat /var/log/messages*
#
#       以下のコマンドが実行できることになるが、
#
#           $ sudo cat /var/log/messages.1
#
#       また、以下のコマンドの実行も可能になってしまう。
#
#           $ sudo cat /var/log/messages /etc/shadow
#
#       後者は、おそらく意図に反しているだろう。たいていの場合、 コマンドラインの処理は、sudoers
#       ファイルの中ではなく、 スクリプト言語中で行った方が間違いがない。




## Allows members of the users group to shutdown this system
## 訳:"users"グループのメンバにこのシステムをシャットダウンすることを許可します。

# %users  localhost=/sbin/shutdown -h now

## Read drop-in files from /etc/sudoers.d (the # here does not mean a comment)
## 訳:"etc/sudoers.d"を読み込みます。(下記の文の"#"はここではコメントという意味ではないです。)

#includedir /etc/sudoers.d

# つまり、"/etc/sudoers.d"に同じ様な構文で記述すればそちらを読み込みに行ってくれる。
# includedirは先頭の"#"をコメントアウトと解釈しないので、
# コメントアウトだなといって余分に削除しないようにする。


5-3. Ubuntuのvisudo

CentOSで大体の書き方がわかりました。次に、Ubuntuのvisudoの中身を見てみます。

Ubuntu_visudo
#
# This file MUST be edited with the 'visudo' command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#
# See the man page for details on how to write a sudoers file.
#
# 訳:このファイルはrootユーザで"visudo"コマンドを用いて編集するように!
# 
# 訳:このファイルを直接編集することではなく、"/etc/sudoers.d/"に追記するように検討してください。
# 
# 訳:"sudoers"ファイルの作成方法の詳細については、manページを参照してください。

# visudoで編集せず他のテキストエディタで直接ファイルを開いてしまうと、構文チェック等が行われないため
# 意図しない動作及び最悪sudoが使えなくなる恐れがあるので、注意喚起を行っている。



Defaults        env_reset
Defaults        mail_badpass
Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"

# 上記はデフォルト設定。
# "Defaults"文を先頭につけることによって、これから下の許可ユーザに対しての
# デフォルト値を決定することができる。
#
# Defaults        env_reset
# 訳:"env_reset"を記述することによって、sudoしたユーザの環境に上書きされる。
#    ただ、全ての環境変数がsudoしたユーザになるわけではない。
#    TERM, PATH, HOME, MAIL, SHELL, LOGNAME, USER, USERNAME, SUDO_*
#    上環境変数のみ上書きされる。
#    また、env_keepやenv_checkを用いて上書きされる環境変数を追加することができる。
#
# Defaults        mail_badpass
# 訳:sudo を実行するユーザが正しいパスワードを入力しなかったら、 mailto ユーザにメールを送付する。
#    ユーザが実行しようとしているコマンドが sudoers によって許可されていない場合に、
#    mail_all_cmnds, # mail_always, ail_no_host, mail_no_perms, 
#    mail_no_user フラグのどれかがセットされていると、このフラグは効果を持たないことになる。

# Defaults        secure_path=***    
# 訳:sudo から実行されるあらゆるコマンドが使用するパスを記述する。
#    この場合はsbin,binを許可している。




# Host alias specification
# 訳:ホストエイリアスの記述


# User alias specification
# 訳:ユーザエイリアスの記述

# Cmnd alias specification
# 訳:コマンドエイリアスの記述

# 各記述はエイリアスで複数のユーザやコマンドを許可/禁止したい場合に記述する。


# User privilege specification
# 訳:ユーザ特権の記述
root    ALL=(ALL:ALL) ALL

# rootは全てのユーザ、全てのグループになることができ、全てのコマンドを実行できる。


# Members of the admin group may gain root privileges
# 訳:"admin"グループはroot権限を取得できます。
%admin ALL=(ALL) ALL

# adminは全てのユーザになることはできますが、グループになることはできないよう。


# Allow members of group sudo to execute any command
# 訳:"sudo"グループは全てのコマンドを実行できるようになります。
%sudo   ALL=(ALL:ALL) ALL

# adminより権限が多い。
# なぜ似たような権限グループが2つのあるのか。
# 参照:https://itectec.com/ubuntu/ubuntu-the-difference-between-the-sudo-and-admin-group/
# Ubuntu 11.10まではsudoグループはなく、"admin"グループで管理していた。
# 変更された経緯は不明だが、下位バージョンからのアップグレードユーザの為の互換として残しているようである。
# なぜ、adminはグループ権限がないかは不明。


# See sudoers(5) for more information on "#include" directives:
# 訳:"#include"の詳細については、manpageの"sudoers(5)"を参照してください。
#
# こちらも#includeの"#"はコメントアウトでないので注意。

#includedir /etc/sudoers.d

5-4 sudoグループに追加

要は、

root@IPADDRESS:~# gpasswd -a conohauser sudo
Adding user conohauser to group sudo

これ書くだけです。

これでsudoできるようになりました。
もしくは下記でも可能。(gpasswdとユーザ名、グループ名の指定が逆なので注意)

usermod -G sudo ユーザ名

6. SSH接続の設定

6-1. sshd_configの中身

sudo vim /etc/ssh/sshd_config
sshd_config
  1 #       $OpenBSD: sshd_config,v 1.103 2018/04/09 20:41:22 tj Exp $
  2
  3 # This is the sshd server system-wide configuration file.  See
  4 # sshd_config(5) for more information.
  5
  6 # This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin
  7
  8 # The strategy used for options in the default sshd_config shipped with
  9 # OpenSSH is to specify options with their default value where
 10 # possible, but leave them commented.  Uncommented options override the
 11 # default value.
 12
 13 Include /etc/ssh/sshd_config.d/*.conf
 14
 15 #Port 22
 16 #AddressFamily any
 17 #ListenAddress 0.0.0.0
 18 #ListenAddress ::
 19
 20 #HostKey /etc/ssh/ssh_host_rsa_key
 21 #HostKey /etc/ssh/ssh_host_ecdsa_key
 22 #HostKey /etc/ssh/ssh_host_ed25519_key
 23
 24 # Ciphers and keying
 25 #RekeyLimit default none
 26
 27 # Logging
 28 #SyslogFacility AUTH
 29 #LogLevel INFO
 30
 31 # Authentication:
 32
 33 #LoginGraceTime 2m
 34 PermitRootLogin yes
 35 #StrictModes yes
 36 #MaxAuthTries 6
 37 #MaxSessions 10
 38
 39 #PubkeyAuthentication yes
 40
 41 # Expect .ssh/authorized_keys2 to be disregarded by default in future.
 42 #AuthorizedKeysFile     .ssh/authorized_keys .ssh/authorized_keys2
 43
 44 #AuthorizedPrincipalsFile none
 45
 46 #AuthorizedKeysCommand none
 47 #AuthorizedKeysCommandUser nobody
 48
 49 # For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
 50 #HostbasedAuthentication no
 51 # Change to yes if you don't trust ~/.ssh/known_hosts for
 52 # HostbasedAuthentication
 53 #IgnoreUserKnownHosts no
 54 # Don't read the user's ~/.rhosts and ~/.shosts files
 55 #IgnoreRhosts yes
 56
 57 # To disable tunneled clear text passwords, change to no here!
 58 PasswordAuthentication yes
 59 #PermitEmptyPasswords no
 60
 61 # Change to yes to enable challenge-response passwords (beware issues with
 62 # some PAM modules and threads)
 63 ChallengeResponseAuthentication no
 64
 65 # Kerberos options
 66 #KerberosAuthentication no
 67 #KerberosOrLocalPasswd yes
 68 #KerberosTicketCleanup yes
 69 #KerberosGetAFSToken no
 70
 71 # GSSAPI options
 72 #GSSAPIAuthentication no
 73 #GSSAPICleanupCredentials yes
 74 #GSSAPIStrictAcceptorCheck yes
 75 #GSSAPIKeyExchange no
 76
 77 # Set this to 'yes' to enable PAM authentication, account processing,
 78 # and session processing. If this is enabled, PAM authentication will
 79 # be allowed through the ChallengeResponseAuthentication and
 80 # PasswordAuthentication.  Depending on your PAM configuration,
 81 # PAM authentication via ChallengeResponseAuthentication may bypass
 82 # the setting of "PermitRootLogin without-password".
 83 # If you just want the PAM account and session checks to run without
 84 # PAM authentication, then enable this but set PasswordAuthentication
 85 # and ChallengeResponseAuthentication to 'no'.
 86 UsePAM yes
 87
 88 #AllowAgentForwarding yes
 89 #AllowTcpForwarding yes
 90 #GatewayPorts no
 91 X11Forwarding yes
 92 #X11DisplayOffset 10
 93 #X11UseLocalhost yes
 94 #PermitTTY yes
 95 PrintMotd no
 96 #PrintLastLog yes
 97 #TCPKeepAlive yes
 98 #PermitUserEnvironment no
 99 #Compression delayed
100 #ClientAliveInterval 0
101 #ClientAliveCountMax 3
102 #UseDNS no
103 #PidFile /var/run/sshd.pid
104 #MaxStartups 10:30:100
105 #PermitTunnel no
106 #ChrootDirectory none
107 #VersionAddendum none
108
109 # no default banner path
110 #Banner none
111
112 # Allow client to pass locale environment variables
113 AcceptEnv LANG LC_*
114
115 # override default of no subsystems
116 Subsystem sftp  /usr/lib/openssh/sftp-server
117
118 # Example of overriding settings on a per-user basis
119 #Match User anoncvs
120 #       X11Forwarding no
121 #       AllowTcpForwarding no
122 #       PermitTTY no
123 #       ForceCommand cvs server
124 PasswordAuthentication yes

6-2. sshd_configを読み解く

参考:https://unskilled.site/sshd_config%E3%81%AE%E8%A8%AD%E5%AE%9A%E9%A0%85%E7%9B%AE%E3%81%AE%E7%90%86%E8%A7%A3%E3%82%92%E7%9B%AE%E6%8C%87%E3%81%99/

sshd_config(翻訳+説明)
#       $OpenBSD: sshd_config,v 1.103 2018/04/09 20:41:22 tj Exp $

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.
# 訳:これは、sshdサーバーのシステム全体の構成ファイルです。
#    詳細については"sshd_config(5)"を参照してください。
# This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin
# 訳:このsshdは /usr/bin:/bin:/usr/sbin:/sbin によってコンパイルされています。
# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.
# 訳:OpenSSHに同梱されているデフォルトのsshd_configのオプションに使用されるものは、
#    可能な場合はデフォルト値でオプションを指定しますが、コメントとして残しておきます。
#    コメントされていないオプションは、デフォルト値を上書きします。

# 説明:/etc/ssh/sshd_config.d/にある拡張.confのファイルをインクルードする。
Include /etc/ssh/sshd_config.d/*.conf

# 説明:SSHに使うポート番号を指定。デフォルト:22
#      セキュリティ的に変えたほうがいいとされている。
#Port 22

# 説明:接続させるIPプロトコルの設定。デフォルト:any
#     any  → IPv4,IPv6両方
#     inet → IPv4
#     inet6→ IPv6
#AddressFamily any

# 説明:SSH接続を受け付けるローカルアドレス。デフォルト0.0.0.0(全て許可)
#ListenAddress 0.0.0.0
#ListenAddress ::

# 説明:ホストの秘密鍵ファイルの設定。
#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
#HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
# 訳:暗号と鍵

# 説明:セッション鍵の再生成頻度の指定。難しいから飛ばす。
#RekeyLimit default none

# Logging
# 訳:ロギング

# 説明:ログのファシリティの指定。カテゴリのようなもの?デフォルト:AUTH
#      ただ、AUTHPRIVが推奨されてるようである。
# 参考:https://mochikoastech.hatenablog.com/entry/archives/7
#SyslogFacility AUTH

# 説明:ログの出力するレベルの指定。デフォルト:INFO
#LogLevel INFO


# Authentication:
# 訳:認証

# 説明:SSH接続を受けてから認証するまでの制限時間の設定。デフォルト:2分
#LoginGraceTime 2m

# 説明:SSHでのrootログインの可否。デフォルト:yes
#      セキュリティ的にnoにしたほうがいいと言われている。
PermitRootLogin yes

# 説明:SSH関連のファイルのパーミッションをチェックする。
#      オープンになっていた場合認証が失敗する。デフォルト:yes
#StrictModes yes

# 説明:認証できる試行回数の指定。デフォルト:6
#MaxAuthTries 6

# 説明:最大同時接続数の指定。デフォルト:10
#MaxSessions 10

# 説明:公開鍵認証をするかの指定。デフォルト:yes
#PubkeyAuthentication yes

# Expect .ssh/authorized_keys2 to be disregarded by default in future.
# 訳:将来的には、「.ssh/authorized_keys2」はデフォルトで無視されるようにするつもりです。
# 説明:公開鍵認証に使用するファイル。
#      デフォルト: .ssh/authorized_keys .ssh/authorized_keys2
#      authorized_keys2は昔の名残なので削除しても良い。
#      参考:https://l-w-i.net/t/openssh/key_002.txt
#AuthorizedKeysFile     .ssh/authorized_keys .ssh/authorized_keys2

# 説明:難しいので飛ばす。
#AuthorizedPrincipalsFile none

# 説明:公開鍵を探すプログラムを指定する。 デフォルト: none
#AuthorizedKeysCommand none

# 説明:上記プログラムのユーザの指定
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
# 訳:これを機能させるためには「/etc/ssh/ssh_known_hosts」内にホストキーが必要です。

# 説明:ホストベース認証の可否。 デフォルト: no
#HostbasedAuthentication no


# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
# 訳:HostbasedAuthenticationの「〜/.ssh/known_hosts」を信頼しない場合は、
#    yesに変更してください。
#IgnoreUserKnownHosts no


# Don't read the user's ~/.rhosts and ~/.shosts files
# 訳:ユーザの「~/.rhosts」「~/.shosts」を読み取らない。

# 説明:Rhostという静的なファイルでの認証方法。安全でないので現在では普通使用されない。
#IgnoreRhosts yes



# To disable tunneled clear text passwords, change to no here!
# 訳:SSHトンネルでのテキストパスワードで認証するログインを無効にするためには、これをnoにしてください。

# 説明:訳が難しいが、パスワード認証を許可するかどうか。デフォルト:yes
#      セキュリティ的にはnoにしたほうがいいと言われている。公開鍵認証でのみログインする。
PasswordAuthentication yes

# 説明:空のパスワードを許可するか。デフォルト:no
#PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
# 訳:チャレンジレスポンス認証を有効にするには、yesに変更します
#   (一部のPAMモジュールとスレッドの問題に注意してください)

# 説明:チャレンジレスポンス認証を使うかの指定。 デフォルト:no
ChallengeResponseAuthentication no


# Kerberos options
# 訳:ケロベロス認証の設定

# 説明:難しいので飛ばす。公開鍵認証できれば不要と思われる。
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
# 訳:GSSAPI認証の設定

# 説明:難しいので飛ばす。公開鍵認証できれば不要と思われる。
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no



# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
# 訳:これを「yes」に設定すると、PAM認証、アカウント処理、およびセッション処理が有効になります。 
#    これが有効になっている場合、PAM認証はChallengeResponseAuthenticationと
#    PasswordAuthenticationを介して許可されます。 PAM構成によっては、
#    ChallengeResponseAuthenticationを介したPAM認証が、「パスワードなしのermitRootLogin」
#    の設定をバイパスする場合があります。 PAMアカウントとセッションチェックをPAM認証なしで実行するだけ
#    の場合は、これを有効にしますが、PasswordAuthenticationと
#    ChallengeResponseAuthenticationを「no」に設定します。

# 説明:上記訳はただの機械翻訳になってしまった。難しいので飛ばす。デフォルト:yes
#      ただ、公開鍵認証のログインのみだと必要なさそう。
UsePAM yes


# 説明:その他設定。すいませんが割愛します。
#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
PrintMotd no
#PrintLastLog yes
#TCPKeepAlive yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS no
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
# 訳:デフォルトのバナーパスはないです。

# 説明:SSHログインする前にメッセージを表示させることができる。
#      テキストファイルのパスを指定する。 デフォルト: none
#Banner none

# Allow client to pass locale environment variables
# 訳:クライアントがロケール環境変数を渡すことを許可します。

# 説明:難しいので飛ばす。
AcceptEnv LANG LC_*

# override default of no subsystems
# 訳:サブシステムなしのデフォルトを上書きする。

# 説明:難しいので飛ばす。
Subsystem sftp  /usr/lib/openssh/sftp-server


# Example of overriding settings on a per-user basis
# 訳:ユーザごとに設定を上書きする例

# 説明:ユーザごとに設定ができる。
#      次のMatch文までか、ファイルの最後まで行う。
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       PermitTTY no
#       ForceCommand cvs server
PasswordAuthentication yes
# ↑なぜここにもう1個パスワード認証があるのかわからない。例ならコメントアウトしてほしいところ。

6-3. sshd_config変更点

結局変えるところは下記

設定名 設定値
Port 任意の番号
SyslogFacility AUTHPRIV
PermitRootLogin no
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no
UsePAM no

注釈:以前はProtocolの指定もあったと思うが、現在は設定がなく2が強制されている。
他にもAllowUsersを設定してもいいかもしれない。

6-4. sshdリスタート

このままだと変更が反映されないので
下記実行

sudo /etc/init.d/ssh restart

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

SSHのポートを変えたので、ファイアーウォールの設定を変更する。

7-1. ufwを使う

Uncomplicated FireWall = ufw を使って、ファイアーウォールのルールを設定する。
iptablesのほうが詳しく設定できるが、今回は簡単にiptablesの設定ができるufwというツール使ってみます。

7-2. Conohaの設定

その前に、Conohaの管理画面で全てのポートを開けるように設定変更してください。
Conohaではなくufw側で設定します。

7-3. ufwの設定

ufwを有効にする。

sudo ufw enable

さきほどSSHの設定で設定したポート番号を指定。

sudo ufw allow ポート番号
conohauser@IPADDRESS:~$ sudo ufw allow ポート番号
Rule added
Rule added (v6)

設定を反映させる。

conohauser@IPADDRESS:~$  sudo ufw reload
Firewall reloaded

7-4. SSH接続できるか確認

ssh conohauser@IPADDRESS -p ポート番号

できたら完了です。

最後に

Twitterやってるので、よかったらフォローお願いします。
Twitter: https://twitter.com/daemokra
間違いの指摘や、こうしたほうがわかりやすい質問などいただければと思います。
私もLinux初心者なので、意見を交換できたら嬉しいです。

以上です。

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