Instructions to set up a basic LAMP+SSH server environment
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1037 lines
61 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. Linux servers - Exercice 5
  2. ==============
  3. *Disclaimer:*
  4. --------------
  5. This exercise is a part of [Linux servers (ICT4TN021, spring 2018) // Linux-palvelimet (ICT4TN021, kevät 2018)](http://www.haaga-helia.fi/fi/opinto-opas/opintojaksokuvaukset/ICT4TN021) school course organized as a part of Information Technology studies in Haaga-Helia university of Applied Sciences, Helsinki, Finland. Course lecturer [Tero Karvinen](http://terokarvinen.com/) has defined the original assignment descriptions in Finnish presented in this document in English. Answers and translations have been written by Pekka Helenius (me, ~ Fincer).
  6. **a)** Install SSH server daemon
  7. --------------
  8. **Answer:**
  9. SSH daemon has already been installed on the virtual server machine (you can't establish a connection to the server with a SSH client program otherwise). However, the installation on Debian-based systems goes as follows:
  10. ```
  11. phelenius@my-machine:~$ sudo apt-get update && sudo apt-get install openssh-server
  12. ```
  13. Start SSH daemon and check whether it is active or not:
  14. ```
  15. phelenius@my-machine:~$ sudo systemctl start sshd.service
  16. phelenius@my-machine:~$ [[ $(systemctl is-active sshd | grep ^active | wc -w) -eq 1 ]] && echo "REPLY: SSH server daemon is active" || echo "REPLY: SSH server daemon is not active"
  17. REPLY: SSH server daemon is active
  18. ```
  19. SSH server daemon has been installed and is active on the server computer. Let's take a look-up into Systemd process tree:
  20. ```
  21. phelenius@my-machine:~$ systemctl status
  22. ...
  23. CGroup: /
  24. ├─init.scope
  25. │ └─1 /lib/systemd/systemd --system --deserialize 20
  26. ├─system.slice
  27. ...
  28. │ ├─ssh.service
  29. │ │ ├─1534 /usr/sbin/sshd -D
  30. │ │ ├─2365 sshd: [accepted]
  31. │ │ └─2366 sshd: [net]
  32. ```
  33. Executable root binary file (sbin) is `/usr/sbin/sshd_ with command parameter _-D` (Process Identifier/Process ID/PID is 1534).
  34. **NOTE:** The following is stated about `-D` parameter in sshd manual:
  35. ```
  36. phelenius@my-machine:~$ man sshd | grep -E "\-D" -C1
  37. -D When this option is specified, sshd will not detach and does not become a daemon. This allows easy monitoring of sshd.
  38. ```
  39. `-D` parameter definition by [SSH Communications Security](https://www.ssh.com/ssh/sshd/):
  40. > -D Do not detach and become daemon. This is often used when sshd is run using systemd. This allows easier monitoring of the process in such environments. Without this option, the SSH server forks and detaches from terminal, making itself a background daemon process. The latter has been the traditional way to run the SSH server until recently. Many embedded systems would still use the latter.
  41. About relevance of the `-D` parameter has been discussed, for instance, on [superuser.com (Differences between ssh -L to -D](https://superuser.com/questions/408031/differences-between-ssh-l-to-d)).
  42. **b)** Establish a firewall protection to the server computer (Note: allow SSH traffic before that)
  43. --------------
  44. **Answer:**
  45. The firewall protection is done by using Linux kernel ip_table module(s). Firewall rules can be modified in User Space with the corresponding iptables command or with the simplified Python 3 based program/script 'Uncomplicated Firewall' (`ufw`). Other firewall solutions also exists on Linux, please see ['Other firewall solutions'](https://github.com/Fincer/linux_server_setup/blob/master/exercises/h5.md#other-firewall-solutions) below.
  46. We can check which loadable kernel modules have been enabled in Linux kernel with the kernel-related lsmod command.
  47. ```
  48. phelenius@my-machine:~$ man lsmod | sed -n '/NAME/{n;p}' | sed 's/\s*//'
  49. lsmod - Show the status of modules in the Linux Kernel
  50. ...
  51. phelenius@my-machine:~$ lsmod |grep filter
  52. ip6table_filter 16384 1
  53. ip6_tables 28672 1 ip6table_filter
  54. iptable_filter 16384 1
  55. ip_tables 24576 1 iptable_filter
  56. x_tables 36864 14 ip6table_filter,xt_hl,xt_recent,ip_tables,xt_tcpudp,xt_limit,xt_conntrack,xt_LOG,iptable_filter,ip6t_rt,ipt_REJECT,ip6_tables,xt_addrtype,ip6t_REJECT
  57. ```
  58. Source codes of these modules can be found on git.kernel.org: [ipv6 netfilter](https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/net/ipv6/netfilter), [ipv6 netfilter core](https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/net/ipv6/netfilter.c), [ipv4 netfilter](https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/net/ipv4/netfilter), [ipv4 netfilter core](https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/net/ipv4/netfilter.c)
  59. ### UFW configuration
  60. By default, python-based Uncomplicated Firewall (`ufw`) is usually pre-installed on many Linux distributions, including Debian-based systems. It's usually the default firewall front-end for `iptables` on Linux systems. Let's confirm that:
  61. ```
  62. phelenius@my-machine:~$ if [[ $(dpkg --get-selections |grep ufw | awk '{print $1}' | wc -l) -eq 0 ]]; then sudo apt-get update && sudo apt-get -y install ufw && echo "REPLY: UFW is installed now"; else echo "REPLY: UFW has already been installed"; fi
  63. REPLY: UFW has already been installed
  64. ```
  65. Therefore UFW firewall is installed. Otherwise it would be installed on the system with `apt-get install ufw` command.
  66. By default, the Linux firewall blocks SSH input traffic (default port `22`). This input port can be opened by applying the following ufw command:
  67. ```
  68. phelenius@my-machine:~$ sudo ufw allow 22/tcp
  69. ```
  70. or with the command (however, not specific port number is defined here):
  71. ```
  72. phelenius@my-machine:~$ sudo ufw allow ssh
  73. ```
  74. Afterwards, UFW can be re-enabled with the following command:
  75. ```
  76. phelenius@my-machine:~$ sudo ufw enable
  77. Command may disrupt existing ssh connections. Proceed with operation (y|n)?
  78. ```
  79. Your answer should be `y` (yes). The firewall does not close (possibly already established) SSH connection because we have opened port `22` TCP input traffic. We get a notification, stating:
  80. ```
  81. Firewall is active and enabled on system startup
  82. ```
  83. **NOTE:** The message is bit unclear, because according to some testing, the ufw firewall may still not be enabled on system boot. Automated start of ufw during system boot can foolproofly be enabled with:
  84. ```
  85. phelenius@my-machine:~$ sudo systemctl enable ufw.service
  86. Created symlink /etc/systemd/system/multi-user.target.wants/ufw.service -> /usr/lib/systemd/system/ufw.service.
  87. ```
  88. Alternatively, the following message may appear:
  89. ```
  90. Synchronizing state of ufw.service with SysV init with /lib/systemd/systemd-sysv-install...
  91. Executing /lib/systemd/systemd-sysv-install enable ufw
  92. ```
  93. ### iptables configuration
  94. **1.** Remove UFW from the Linux system, and remove all relevant UFW entries from iptables firewall rule list.
  95. **NOTE:** Warning: (May) delete other important iptables rules configured by system administration!
  96. **NOTE:** Be sure that you have direct access (local terminal, without network) to the target machine in a case of failure. Otherwise you may lock yourself out from the server.
  97. ```
  98. sudo systemctl stop ufw.service && sudo systemctl disable ufw.service
  99. sudo apt-get purge --remove ufw
  100. sudo iptables --flush && sudo iptables --delete-chains
  101. ```
  102. **2.** Confirm deletion of ufw entries from iptables firewall rule list with
  103. ```
  104. sudo iptables -S
  105. ```
  106. Output should be:
  107. ```
  108. -P INPUT ACCEPT
  109. -P FORWARD ACCEPT
  110. -P OUTPUT ACCEPT
  111. ```
  112. **3.** Add new firewall rules to iptables and keep already established connections open:
  113. ```
  114. sudo iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  115. ```
  116. **4.** Drop all connections, excluding already established connections like SSH:
  117. ```
  118. sudo iptables -A INPUT -j DROP
  119. sudo iptables -A FORWARD -j DROP
  120. ```
  121. **5.** Allow SSH traffic (port number: `22`, protocol: `tcp`, etc.):
  122. ```
  123. sudo iptables -I INPUT -p tcp --dport 22 -j ACCEPT
  124. ```
  125. **NOTE:** This applies only to IPv4 connections. For IPv6, check [iptables6](https://www.linux.com/learn/intro-to-linux/2017/8/iptables-rules-ipv6).
  126. **NOTE:** The forementioned command can be written so that connections only from a single IP is allowed, by using `eth0` network interface. For instance:
  127. ```
  128. sudo iptables -I INPUT -p tcp -i eth0 -s 231.123.24.24 --dport 22 -j ACCEPT
  129. ```
  130. **NOTE:** Be sure you have enabled 'net.ifnames=0' in your udev rules to get network interface names like `eth0`, `wlan0` etc.!
  131. More about setting iptables firewall rules, take a look on [DigitalOcean website](https://www.digitalocean.com/community/tutorials/iptables-essentials-common-firewall-rules-and-commands) and [iptables - Append vs. Insert - website](https://serverfault.com/questions/472258/difference-between-iptables-a-and-i-option), for instance.
  132. **6.** Confirm proper iptables firewall rules with `sudo iptables -S` command:
  133. ```
  134. -P INPUT ACCEPT
  135. -P FORWARD ACCEPT
  136. -P OUTPUT ACCEPT
  137. -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  138. -A INPUT -j DROP
  139. -A FORWARD -j DROP
  140. -I INPUT -p tcp --dport 22 -j ACCEPT
  141. ```
  142. **7.** Save the rules so that they won't be lost after rebooting:
  143. ```
  144. sudo iptables-save | sudo tee /etc/iptables/iptables.save > /dev/null
  145. cat /etc/iptables/iptables.save
  146. ```
  147. **8.** Apply and enable the rules. You can restart iptables service (Packet Filtering Framework) if you prefer to do so:
  148. ```
  149. sudo iptables-restore && sudo systemctl restart iptables.service
  150. ```
  151. **9.** Confirm the current iptables firewall rules with the command `sudo iptables -S`.
  152. More about iptables:
  153. - [DigitalOcean - Iptables Essentials: Common Firewall Rules and Commands, SSH service](https://www.digitalocean.com/community/tutorials/iptables-essentials-common-firewall-rules-and-commands#service-ssh)
  154. - [DigitalOcean - Iptables Essentials: Common Firewall Rules and Commands, Saving rules](https://www.digitalocean.com/community/tutorials/iptables-essentials-common-firewall-rules-and-commands#saving-rules).
  155. - [The Geek Stuff - 25 Most Frequently Used Linux IPTables Rules Examples](https://www.thegeekstuff.com/2011/06/iptables-rules-examples)
  156. ### Other firewall solutions
  157. In addition to UFW, other iptables-based firewall solutions have been developed on Linux. Take a look on [Firestarter](http://www.fs-security.com/), [Firewalld](https://fedoraproject.org/wiki/Firewalld?rd=FirewallD), [PeerGuardian](https://sourceforge.net/projects/peerguardian/?source=navbar), [FWBuilder](http://www.fwbuilder.org/), etc.
  158. ------------------------------------------------
  159. ### EXTRA - root account: more restrictions
  160. In addition to previous root restrictions, the following extra restrictions were applied, too:
  161. - root default shell were changed to `/sbin/nologin` in `/etc/passwd` file
  162. - root account were locked by applying command `sudo usermod root --lock` (this was done already, it sets up an exclamation mark prefix to the root account password in file `/etc/shadow`
  163. - root access removal of TTY sessions by commenting out relevant lines in file `/etc/securetty`
  164. - SSH: setting `PermitRootLogin no` were applied in SSH server configuration file `/etc/ssh/sshd_config`
  165. PAM configuration files (Pluggable Authentitation Modules) were not altered in `/etc/pam.d/` although security can be improved by applying some special system-spefific authentication rules there. PAM rules can restrict root permissions as well, including executable daemon processes and commands (i.e. you can restrict even root execution rights in the target system, in contradiction what is usually told for new Linux users that "root can do anything". With PAM, you can restrict that "anything" privilege.)
  166. Reference: [Red Hat - 4.4.2. Disallowing Root Access](https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/4/html/Security_Guide/s2-wstation-privileges-noroot.html)
  167. **c)** Transfer files using SSH protocol
  168. --------------
  169. **Answer:**
  170. Let's use [Secure Copy (scp)](https://en.wikipedia.org/wiki/Secure_copy) command for file transfers.
  171. The assignment has been done in the following command sequence. The following steps are executed:
  172. **1.** Create new subdirectory `httpd` into the current user's home directory on the local computer
  173. **2.** Download related control, description and patch files of debian package of Apache web server, version `2.4.18-2ubuntu3.5` from archive.ubuntu.com ([packages.ubuntu.com](https://packages.ubuntu.com/xenial/apache2)). Target directory for the download is the recently created subdirectory `httpd`
  174. **3.** Extract the downloaded archive files into `$HOME/httpd`. Subdirectory `debian` will be created in `httpd` directory.
  175. **4.** Establish a new SSH connection to the server computer with server user `newuser`, use port `1234` and create directory `$HOME/patches` for this user.
  176. **5.** Transfer all local files (and directories) which 1) start with any character 2) end with suffix `.diff` and `.patch` 3) locate at the current user's `./httpd/debian/patches/` subdirectory
  177. to the directory `$HOME/patches` located at the server computer (where `$HOME` is `/home/newuser/`). SSH connection port is `1234`. Use `scp` command.
  178. For more information about patches, check
  179. - [What is the format of a patch file - stackoverflow.com](https://stackoverflow.com/questions/987372/what-is-the-format-of-a-patch-file)
  180. - [Patch command examples - thegeekstuff.com](https://www.thegeekstuff.com/2014/12/patch-command-examples))
  181. **6.** List contents of the remote subdirectory `$HOME/patches` with SSH connection, use port `1234`
  182. **7.** Delete current user's local subdirectory `httpd` and its contents. `-R` or `-r` stands for recursive deletion, `-f` stands for forceful removal. Remote files in the server computer's directory `/home/newuser/patches/` will be kept intact.
  183. ```
  184. [20/02/2018 13:24:40 - fincer: ~ ]$ mkdir httpd
  185. [20/02/2018 13:24:54 - fincer: ~ ]$ wget http://archive.ubuntu.com/ubuntu/pool/main/a/apache2/apache2_2.4.18-2ubuntu3.5.debian.tar.xz -P httpd
  186. --2018-02-20 13:25:13-- http://archive.ubuntu.com/ubuntu/pool/main/a/apache2/apache2_2.4.18-2ubuntu3.5.debian.tar.xz
  187. Resolving archive.ubuntu.com... 2001:67c:1560:8001::11, 2001:67c:1360:8001::17, 2001:67c:1560:8001::14, ...
  188. Connecting to archive.ubuntu.com|2001:67c:1560:8001::11|:80... connected.
  189. HTTP request sent, awaiting response... 200 OK
  190. Length: 387448 (378K) [application/x-xz]
  191. Saving to: ‘httpd/apache2_2.4.18-2ubuntu3.5.debian.tar.xz’
  192. apache2_2.4.18-2ubuntu3.5.debian.tar.xz 100%[==================================================================================>] 378.37K 450KB/s in 0.8s
  193. 2018-02-20 13:25:15 (450 KB/s) - ‘httpd/apache2_2.4.18-2ubuntu3.5.debian.tar.xz’ saved [387448/387448]
  194. [20/02/2018 13:25:15 - fincer: ~ ]$ tar xf apache2_2.4.18-2ubuntu3.5.debian.tar.xz -C httpd
  195. [20/02/2018 13:25:35 - fincer: ~ ]$ ssh newuser@174.138.2.190 -p 1234 mkdir patches
  196. newuser@174.138.2.190's password:
  197. [20/02/2018 13:26:12 - fincer: ~ ]$ scp -P 1234 ./httpd/debian/patches/*.{diff,patch} newuser@174.138.2.190:./patches/
  198. newuser@174.138.2.190's password:
  199. hostnames_with_underscores.diff 100% 479 114.6KB/s 00:00
  200. reproducible_builds.diff 100% 1710 427.2KB/s 00:00
  201. build_suexec-custom.patch 100% 1981 473.6KB/s 00:00
  202. customize_apxs.patch 100% 9316 888.9KB/s 00:00
  203. CVE-2016-0736.patch 100% 12KB 867.4KB/s 00:00
  204. CVE-2016-2161.patch 100% 4787 493.1KB/s 00:00
  205. CVE-2016-5387.patch 100% 666 287.9KB/s 00:00
  206. CVE-2016-8743.patch 100% 80KB 1.0MB/s 00:00
  207. CVE-2017-3167.patch 100% 8922 698.9KB/s 00:00
  208. CVE-2017-3169.patch 100% 4663 458.1KB/s 00:00
  209. CVE-2017-7668.patch 100% 1746 482.5KB/s 00:00
  210. CVE-2017-7679.patch 100% 1925 527.4KB/s 00:00
  211. CVE-2017-9788.patch 100% 2252 582.1KB/s 00:00
  212. CVE-2017-9798.patch 100% 1172 381.3KB/s 00:00
  213. fhs_compliance.patch 100% 2541 635.6KB/s 00:00
  214. no_LD_LIBRARY_PATH.patch 100% 444 199.8KB/s 00:00
  215. prefork_single_process_crash.patch 100% 773 359.0KB/s 00:00
  216. suexec-custom.patch 100% 5785 792.4KB/s 00:00
  217. suexec-CVE-2007-1742.patch 100% 2356 589.3KB/s 00:00
  218. suexec_is_shared.patch 100% 622 194.1KB/s 00:00
  219. [20/02/2018 13:28:03 - fincer: ~ ]$ ssh newuser@174.138.2.190 -p 1234 ls -l ./patches
  220. newuser@174.138.2.190's password:
  221. total 196
  222. -rw-r--r-- 1 newuser newuser 12446 Feb 20 11:38 CVE-2016-0736.patch
  223. -rw-r--r-- 1 newuser newuser 4787 Feb 20 11:38 CVE-2016-2161.patch
  224. -rw-r--r-- 1 newuser newuser 666 Feb 20 11:38 CVE-2016-5387.patch
  225. -rw-r--r-- 1 newuser newuser 81900 Feb 20 11:38 CVE-2016-8743.patch
  226. -rw-r--r-- 1 newuser newuser 8922 Feb 20 11:38 CVE-2017-3167.patch
  227. -rw-r--r-- 1 newuser newuser 4663 Feb 20 11:38 CVE-2017-3169.patch
  228. -rw-r--r-- 1 newuser newuser 1746 Feb 20 11:38 CVE-2017-7668.patch
  229. -rw-r--r-- 1 newuser newuser 1925 Feb 20 11:38 CVE-2017-7679.patch
  230. -rw-r--r-- 1 newuser newuser 2252 Feb 20 11:38 CVE-2017-9788.patch
  231. -rw-r--r-- 1 newuser newuser 1172 Feb 20 11:38 CVE-2017-9798.patch
  232. -rw-r--r-- 1 newuser newuser 1981 Feb 20 11:38 build_suexec-custom.patch
  233. -rw-r--r-- 1 newuser newuser 9316 Feb 20 11:38 customize_apxs.patch
  234. -rw-r--r-- 1 newuser newuser 2541 Feb 20 11:38 fhs_compliance.patch
  235. -rw-r--r-- 1 newuser newuser 479 Feb 20 11:38 hostnames_with_underscores.diff
  236. -rw-r--r-- 1 newuser newuser 444 Feb 20 11:38 no_LD_LIBRARY_PATH.patch
  237. -rw-r--r-- 1 newuser newuser 773 Feb 20 11:38 prefork_single_process_crash.patch
  238. -rw-r--r-- 1 newuser newuser 1710 Feb 20 11:38 reproducible_builds.diff
  239. -rw-r--r-- 1 newuser newuser 2356 Feb 20 11:38 suexec-CVE-2007-1742.patch
  240. -rw-r--r-- 1 newuser newuser 5785 Feb 20 11:38 suexec-custom.patch
  241. -rw-r--r-- 1 newuser newuser 622 Feb 20 11:38 suexec_is_shared.patch
  242. [20/02/2018 13:32:01 - fincer: ~ ]$ rm -Rf httpd
  243. ```
  244. **d)** Automate SSH login with public key method
  245. --------------
  246. **Answer:**
  247. **1.** Let's generate a key pair on the client computer with a user who is wanted to have the public key authentication method for SSH connections. Both private and public keys are generated with `ssh-keygen` command. Accept the default settings unless you have any requirements to customize them.
  248. **2.** Copy the **public key** to the server computer with your SSH client using command `ssh-copy-id -i $HOME/.ssh/id_rsa.pub username@server-ip-or-name`. The command copies your public key to the subdirectory `.ssh/authorized_keys` located at the server computer.
  249. **NOTE:** Copy public key only, do **NOT** copy the private key!!
  250. More about the topic:
  251. [ssh.com - Key Pair - Public and Private](https://www.ssh.com/ssh/public-key-authentication#sec-Key-Pair-Public-and-Private)
  252. **3.** Let confirm that SSH server daemon configuration file (`/etc/ssh/sshd_config` by default) has the following settings in place (either use `sudo nano /etc/ssh/sshd_config` or `sudoedit /etc/ssh/sshd_config`):
  253. ```
  254. AuthenticationMethods publickey
  255. PubkeyAuthentication yes
  256. AuthorizedKeysFile .ssh/authorized_keys
  257. ```
  258. **Extra hint 1:** SSH client settings are generally defined in `/etc/ssh/ssh_config`
  259. **Extra hint 2:** You can use ssh command with `-v` parameter to gain more information about used authentication methods in unclear cases or for debugging purposes. The `-v` parameter is defined as follows:
  260. > -v Verbose mode. Causes ssh to print debugging messages about its progress. This is helpful in debugging connection, authentication, and configuration problems. Multiple -v options increase the verbosity. The maximum is 3.
  261. **4.** We shall restart server SSH daemon with `sudo systemctl restart sshd.service` command (note! this interrupts any existing & opened SSH connections)
  262. **5.** We shall test public key authentication from the client computer. Use same user account which you previously used for executing `ssh-keygen` command on the client computer. The client computer user should be able to login into SSH server without a password.
  263. **EXTRA: Modifying welcome banner**
  264. Let's modify default Ubuntu login/SSH banner message by executing the following bash script:
  265. ```
  266. #!/bin/bash
  267. # Modify SSH login banner message
  268. ## 00-header file:
  269. #
  270. sudo sed -i 's?printf "Welcome to %s (%s %s %s)\\n" "$DISTRIB_DESCRIPTION" "$(uname -o)" "$(uname -r)" "$(uname -m)"?printf "Welcome to %s\\nUptime:
  271. %s\\n\\n" "Server Computer" "$(uptime)"?' /etc/update-motd.d/00-header
  272. ## File extensions of the following files will be modified
  273. ## We could also remove these files with 'sudo rm <file>'
  274. #
  275. FILES=( 10-help-text 51-cloudguest 90-updates-available 91-release-upgrade )
  276. cd /etc/update-motd.d/
  277. for file in ${FILES[@]}; do sudo mv $file $file.old; done
  278. cd
  279. ```
  280. **NOTE:** Location of the banner file varies between different Linux distributions. For instance, Arch Linux uses banner file `/etc_motd`.
  281. **e)** Install, configure and start sysstat. Use sar command to confirm whether the sysstat package services have been enabled (for instance, log entry "Linux reboot..." exists). Run sysstat a day or two. Afterwards, check computer workload history with sysstat commands sar, iostat, pidstat etc. Analyze the results, i.e. explain the results in detail.
  282. --------------
  283. **Answer:**
  284. **1.** We shall connect to the server computer (running Ubuntu) and then install the required package with command sequence `sudo apt-get update && sudo apt-get install -y install sysstat`
  285. **2.** Run [shell-based sysstat script](https://github.com/Fincer/linux_server_setup/blob/master/scripts/sysstat_command.sh) which runs `sar` and `pidstat` commands for two days with 20 second intervals.
  286. **NOTE:** The script can be opmitized more/adapted better to suit the real requirements for the server environment (statistics interval, collection period, etc.)
  287. **3.** The script described in step 2 has generated sar analytics file `sar-stats_2018-02-24_2018-02-26.file` into path `/home/newuser/sar_statistics/` on the server computer.
  288. Time period: 24. - 26.02.2018
  289. The following sums up some command samples which can be applied to the analytics file.
  290. | File | Description |
  291. |------------------------------------|-------------------------------------------------|
  292. | sar -u -f <analytics-file> | Processor workload statistics |
  293. | sar -v -f <analytics-file> | Inode and file statistics |
  294. | sar -r -f <analytics-file> | Memory consumption statistics |
  295. | sar -n DEV -f <analytics-file> | Network stats: devices |
  296. | sar -n EDEV -f <analytics-file> | Network stats: errors in devices |
  297. | sar -n IP -f <analytics-file> | Network stats: IPv4 traffic |
  298. | sar -n EIP -f <analytics-file> | Network stats: errors in IPv4 traffic |
  299. | sar -n IP6 -f <analytics-file> | Network stats: IPv6 traffic |
  300. | sar -n EIP6 -f <analytics-file> | Network stats: errors in IPv6 traffic |
  301. | sar -n SOCK -f <analytics-file> | Network stats: IPv4 socket |
  302. | sar -n SOCK6 -f <analytics-file> | Network stats: IPv6 socket |
  303. | sar -n TCP -f <analytics-file> | Network stats: TCPv4 protocol traffic |
  304. | sar -n ETCP -f <analytics-file> | Network stats: errors in TCPv4 protocol traffic |
  305. | sar -S -f <analytics-file> | Swap memory consumption |
  306. | sar -w -f <analytics-file> | Process statistics |
  307. | sar -F MOUNT / -f <analytics-file> | File system which is mounted at / |
  308. Statistics can be combined etc, as you can find out with 'man sar' command:
  309. ```
  310. sar -u 2 5
  311. Report CPU utilization for each 2 seconds. 5 lines are displayed.
  312. sar -I 14 -o int14.file 2 10
  313. Report statistics on IRQ 14 for each 2 seconds. 10 lines are displayed. Data are stored in a file called int14.file.
  314. sar -r -n DEV -f /var/log/sysstat/sa16
  315. Display memory and network statistics saved in daily data file 'sa16'.
  316. sar -A
  317. Display all the statistics saved in current daily data file.
  318. ```
  319. Or [The Geek Stuff - 10 Useful Sar (Sysstat) Examples for UNIX / Linux Performance Monitoring](https://www.thegeekstuff.com/2011/03/sar-examples/?utm_source=feedburner)
  320. What are inode and swap? Check
  321. - [inode - 1](https://www.cyberciti.biz/tips/understanding-unixlinux-filesystem-inodes.html)
  322. - [inode - 2](https://unix.stackexchange.com/questions/117093/find-where-inodes-are-being-used)
  323. - [Swap](https://wiki.archlinux.org/index.php/swap)
  324. Additionally, the following pidstat files were generated:
  325. | File | Description |
  326. |----------------------------|------------------------------------|
  327. | pidstat_stats_cpu-tasks | Processor workload statistics |
  328. | pidstat_stats_io | I/O statistics |
  329. | pidstat_stats_kerneltables | Statistics of Linux kernel tables |
  330. | pidstat_stats_pagefaults | Page fault statistics |
  331. | pidstat_stats_stacks | Process stack statistics |
  332. (Check. [Stacks](https://stackoverflow.com/questions/8905271/what-is-the-linux-stack), [Page fault](https://en.wikipedia.org/wiki/Page_fault))
  333. Additionally, iostat command was run on the background.
  334. **4.** Let's take a closer look on two sar analytics files and I/O statistics file. The following commands open analytics files in more detailed view.
  335. ------------------------------------------------
  336. ### SAR network statistics - IPv4 traffic
  337. **command: sar -n IP -f sar-stats_2018-02-24_2018-02-26.file**
  338. ![sar-stats-ipv4](https://github.com/Fincer/linux_server_setup/blob/master/images/sar-stats_ipv4.png)
  339. **Observation period:** 24.-26.02.2018
  340. | Field | Description | Average |
  341. |-------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------|
  342. | Left column | Record time | |
  343. | irec/s | The total number of input datagrams received from interfaces per second, including those received in error. | 1.33 |
  344. | fwddgm/s | The number of input datagrams per second, for which this entity was not their final IP destination, as a result of which an attempt was made to find a route to forward them to that final destination. | 0.00 |
  345. | idel/s | The total number of input datagrams,successfully,delivered,per,second,to,IP user-protocols (including ICMP). | 1.30 |
  346. | orq/s | The total number of IP datagrams which local IP user-protocols (including ICMP) supplied per second to IP in requests for,transmission. Note that this,counter,does,not include any datagrams counted in fwddgm/s. | 1.45 |
  347. | asmrq/s | The number of IP fragments received per second which needed to be reassembled at this entity. | 0.00 |
  348. | asmok/s | The number of IP datagrams successfully re-assembled per second. | 0.00 |
  349. | fragok/s | The number of IP datagrams that,have,been,successfully fragmented at this entity per second. | 0.00 |
  350. | fragcrt/s | The number of IP datagram fragments that have been generated per second as a result of fragmentation at this entity. | 0.00 |
  351. **NOTE:** Descriptions are provided in sysstat package (manpages).
  352. **Analysis - IPV4**
  353. The server computer has not forwarded a single datagram in the observation period. Input network traffic has been received which can be concluded by observing `irec/s`, `idel/s` and `orq/s` field values. The current workload of the server computer is very low, including only HTTP daemon (Apache web server) and SSH server daemon. No webpages are available on the server which could increase input HTTP/HTTPS protocol based traffic. HTTPS was not enabled in the server computer.
  354. By default, the server computer allows `128` simultaneous input network connections (command `cat /proc/sys/net/core/somaxconn`. **NOTE:** The value can be changed by issuing `echo 1024 | sudo tee /proc/sys/net/core/somaxconn`, for instance).
  355. MTU value of the web server computer for network interface `eth0` was `1500` (you can check it with `ifconfig` command). MTU stands for **Maximum Transmission Unit** which determines the highest PDU unit ([Protocol Data Unit](https://en.wikipedia.org/wiki/Protocol_data_unit)) that can be transferred over the network at once.
  356. Check also
  357. - [MTU - hyperlink 1](http://www.tcpipguide.com/free/t_IPDatagramSizeMaximumTransmissionUnitMTUFragmentat.htm)
  358. - [MTU - hyperlink 2](https://en.wikipedia.org/wiki/Maximum_transmission_unit)
  359. - [Stack Overflow - What's the practical limit on the size of single packet transmitted over domain socket?](https://stackoverflow.com/questions/21856517/whats-the-practical-limit-on-the-size-of-single-packet-transmitted-over-domain)
  360. - [Stack Overflow - What is the default size of datagram queue length in Unix Domain Sockets (AF_UNIX)? Is it configurable?](https://stackoverflow.com/questions/21448960/what-is-the-default-size-of-datagram-queue-length-in-unix-domain-sockets-af-uni)
  361. - [IP fragmentation](https://en.wikipedia.org/wiki/IP_fragmentation)
  362. - Related article: [Linux Tune Network Stack (Buffers Size) To Increase Networking Performance](https://www.cyberciti.biz/faq/linux-tcp-tuning/)
  363. **NOTE:** About datagrams, [quoted from Wikipedia](https://en.wikipedia.org/wiki/Datagram#Internet_Protocol):
  364. > The term datagram is often considered synonymous to packet but there are some nuances. The term datagram is generally reserved for packets of an unreliable service, which cannot notify the sender if delivery fails, while the term packet applies to any packet, reliable or not. Datagrams are the IP packets that provide a quick and unreliable service like UDP, and all IP packets are datagrams; however, at the TCP layer, what is termed a TCP segment is the sometimes necessary IP fragmentation of a datagram, but those are referred to as "packets".
  365. ------------------------------------------------
  366. ### SAR - memory consumption statistics - RAM & Swap
  367. **command: sar -r -f sar-stats_2018-02-24_2018-02-26.file**
  368. **command: sar -S -f sar-stats_2018-02-24_2018-02-26.file**
  369. ![sar-stats-memusage](https://github.com/Fincer/linux_server_setup/blob/master/images/sar-stats_memusage.png)
  370. **Observation period:** 24.-26.02.2018
  371. **NOTE:** Average values are not visible in the attached picture!
  372. | Field | Description | Average |
  373. |-------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------|
  374. | Left column | Record time | |
  375. | kbmemfree | Amount of free memory available in kilobytes. | 87631 KB (~ 87 MB) |
  376. | kbmemused | Amount,of,used,memory in kilobytes. This does not take into account memory used by the kernel itself. | 928 457 KB (~ 928 MB) |
  377. | %memused | Percentage of used memory. | 91.38 % |
  378. | kbbuffers | Amount of memory used as buffers by the kernel in kilobytes. | 77 746 KB (~ 77 MB) |
  379. | kbcached | Amount of memory used to cache data by the kernel in kilobytes. | 644 777 KB (~ 644 MB) |
  380. | kbcommit | Amount of memory in kilobytes needed for current workload. This is an estimate of how much RAM/swap is needed to guarantee that there never is out of memory. | 470 619 KB (~ 470 MB) |
  381. | %commit | Percentage of memory needed for current workload in relation to the total amount of memory (RAM+swap).,This number may be greater than 100% because the,kernel,usually overcommits memory. | 46.32 % |
  382. | kbactive | Amount of active memory in kilobytes (memory that has been used more recently and usually not reclaimed unless absolutely necessary). | 468 703 KB (~ 468 MB) |
  383. | kbinact | Amount of inactive memory in kilobytes (memory which has been less recently used. It is more eligible to be reclaimed for other purposes). | 301 098 KB (~ 301 MB) |
  384. | kbdirty | Amount of memory in kilobytes waiting to get written back to the disk. | 254 KB (0.254 MB) |
  385. **NOTE:** Descriptions are provided in `sysstat` package (manpages).
  386. **Analysis - Memory Statistics**
  387. The target server memory size:
  388. ```
  389. [newuser@goauldhost: ~ ]$ grep -i memtotal /proc/meminfo
  390. MemTotal: 1016088 kB
  391. ```
  392. i.e. approximately ~ 1016 MB.
  393. Great part of this memory were in use during the observation period. There were multiple active processes running on the server computer during the period, thus increased workload was intended and meant for statistics collection.
  394. The web server didn't have Swap partition or Swap file. This can be found out by
  395. - executing command `for i in "cat /etc/fstab" "sudo fdisk -l"; do $i | grep -i swap; echo $?; done` which returns value 1 two times (meaning returning of 'false' boolean value to shell two separate times)
  396. - Or, for instance:
  397. ```
  398. [newuser@goauldhost: ~ ]$ cat /etc/fstab
  399. LABEL=cloudimg-rootfs / ext4 defaults 0 0
  400. LABEL=UEFI /boot/efi vfat defaults 0 0
  401. [newuser@goauldhost: ~ ]$ sudo fdisk -l
  402. [sudo] password for newuser:
  403. Disk /dev/vda: 25 GiB, 26843545600 bytes, 52428800 sectors
  404. Units: sectors of 1 * 512 = 512 bytes
  405. Sector size (logical/physical): 512 bytes / 512 bytes
  406. I/O size (minimum/optimal): 512 bytes / 512 bytes
  407. Disklabel type: gpt
  408. Disk identifier: 39DFE5D0-C8FB-44D8-93F8-EBB37A54BDF8
  409. Device Start End Sectors Size Type
  410. /dev/vda1 227328 52428766 52201439 24.9G Linux filesystem
  411. /dev/vda14 2048 10239 8192 4M BIOS boot
  412. /dev/vda15 10240 227327 217088 106M Microsoft basic data
  413. ```
  414. It may not be wise to collect Swap statistics (although Linux kernel [Swappiness value](https://en.wikipedia.org/wiki/Swappiness) has default value `60` defined in `/proc/sys/vm/swappiness` on DigitalOcean virtual servers).
  415. ------------------------------------------------
  416. ### SAR - I/O statistics
  417. ![sar-iostat](https://github.com/Fincer/linux_server_setup/blob/master/images/sar-iostats.png)
  418. Main command: `iostat -dmtx 20`
  419. ```
  420. -d Display the device utilization report.
  421. -m Display statistics in megabytes per second.
  422. -t Print the time for each report displayed.
  423. -x Display extended statistics.
  424. 20 20 sec interval.
  425. ```
  426. | Field | Description |
  427. |--------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
  428. | Device | Device or partition defined in system directory '/dev'. |
  429. | rrqm/s | The number of read requests merged per second that were queued to the device. |
  430. | wrqm/s | The percentage of write requests merged together before being sent to the device. |
  431. | r/s | The number (after merges) of read requests completed per second for the device. |
  432. | w/s | The number (after merges) of write requests completed per second for the device. |
  433. | rMB/s | The number of sectors (KB, MB) read from the device per second. |
  434. | wMB/s | The number of sectors (KB, MB) write from the device per second. |
  435. | avgrq-sz (areq-sz) | The average size (in kilobytes) of the I/O requests,that were issued to the device. |
  436. | avgqu-sz (aqu-sz) | The average queue length of the requests that were issued to the device. |
  437. | await | The average time (ms) for I/O requests issued to the device to be served. This includes the time spent by the requests in queue and the time spent servicing them. |
  438. | r_await | The average time (ms) for read requests issued to the device to be served. This includes the time spent by the requests in queue and the time spent servicing them. |
  439. | w_await | The average time (ms),for,write,requests issued to the device to be served. This includes the time spent by the requests in queue and the time spent servicing them. |
  440. | svctm | The average service time (ms) for I/O requests that were issued to the device. This field will be removed in a future sysstat version. |
  441. | %util | Percentage of elapsed time during which I/O requests were issued to the device (bandwidth utilization for the device). Device saturation occurs when this value is close to 100% for devices serving requests serially. But for devices serving requests in parallel, such as RAID arrays and modern SSDs, this number does not reflect their performance limits. |
  442. **NOTE:** Descriptions are provided in sysstat package (manpages).
  443. **Analysis - I/O Statistics**
  444. Virtual partition `/dev/vda` were hibernated most of the time during the observation period. Little variation can be seen in writing requests (`wrqm/s`), in succeeded writing requests (`w/s`) and in written sector count (`wMB/s`). Average sector size is 10-20 sectors (`avgrq-sz`) which is quite little. I/O and read request service times are mostly 0.0. Workload of the virtual hard drive is low during the observation period.
  445. ------------------------------------------------
  446. In addition to sysstat, `top` command could have been used in some TTY session in order to observe processes in real time, and with [inotify](https://en.wikipedia.org/wiki/Inotify), some file system changes could have been reported. Sysstat's advantage is that programs which are included in it can record and save analytics in binary format for further and detailed inspection.
  447. **f)** (optional) Change sshd (SSH server process) port
  448. --------------
  449. **Answer:**
  450. Let the following shell script do the job...
  451. ```
  452. #!/bin/bash
  453. # SSH server daemon configuration file in the system
  454. SSH_CONFIG=/etc/ssh/sshd_config
  455. # New SSH server daemon input port as user input value.
  456. NEW_SSH_PORT=$1
  457. [[ -f $SSH_CONFIG ]] \
  458. && sed -i "s/.*Port.*/Port $NEW_SSH_PORT/" $SSH_CONFIG && echo "SSH server: new port $NEW_SSH_PORT is set." \
  459. || echo "SSH server configuration file could not be found!"
  460. if [[ $(cat $SSH_CONFIG | grep -i port | awk '{print $2}') == $NEW_SSH_PORT ]]; then
  461. echo -e "SSH server input port has been changed to $NEW_SSH_PORT.\n \
  462. Restarting SSH server daemon in order to apply the changes (root required)."
  463. sudo systemctl restart sshd.service
  464. if [[ $? == 0 ]]; then
  465. echo "SSH server daemon restarted, new input port is $NEW_SSH_PORT."
  466. else
  467. echo "Something went wrong while restarting SSH server daemon. Execute 'systemctl status sshd.service' \
  468. to get more information about the problem."
  469. fi
  470. fi
  471. ```
  472. Save the above script code in file `$HOME/ssh-port.sh`, for instance. Change the port with command `bash $HOME/ssh-port.sh 4312` where the number value is your new SSH port (`4312` in this case).
  473. ------------------------------------------------
  474. ### EXTRA - Using new port address of SSH server daemon when connecting with a client computer/program
  475. Changing SSH server input port on the server computer must be taken into account while establishing connection with a client computer. Because the default SSH port `22` is not used anymore, the following syntax must be applied while connecting to the SSH server computer:
  476. ```
  477. [19/02/2018 23:23:49 - fincer: ~ ]$ ssh newuser@174.138.2.190 -p <new-port-number>
  478. ```
  479. ------------------------------------------------
  480. ### EXTRA - detecting SSH port change with port scanning techniques (nmap)
  481. Enable log level `VERBOSE` in `/etc/ssh/sshd_config` configuration file (`LogLevel VERBOSE`), restart SSH server daemon with command `sudo systemctl restart sshd.service` and try port scanning with another computer.
  482. Port scanning:
  483. ```
  484. nmap -sS -F -v -O 174.138.2.190
  485. ```
  486. nmap output when port scanning is applied with another computer using target IP `174.138.2.190` and port `1234` (**NOTE:** This scanning has been applied to my own server only **once** as an experiment, not in bad intentions! Make sure you have permission to proceed with your scanning and do not attack to any server just for fun, to avoid any problems!):
  487. ```
  488. phelenius@my-machine:~$ sudo nmap -sS -p 1234 -O -v 174.138.2.190
  489. Starting Nmap 7.01 ( https://nmap.org ) at 2018-02-19 20:02 EET
  490. Initiating Ping Scan at 20:02
  491. Scanning 174.138.2.190 [4 ports]
  492. Completed Ping Scan at 19:59, 0.20s elapsed (1 total hosts)
  493. Initiating Parallel DNS resolution of 1 host. at 20:02
  494. Completed Parallel DNS resolution of 1 host. at 20:02, 0.01s elapsed
  495. Initiating SYN Stealth Scan at 20:02
  496. Scanning 174.138.2.190 [1 port]
  497. Completed SYN Stealth Scan at 20:02, 0.20s elapsed (1 total ports)
  498. Initiating OS detection (try #1) against 174.138.2.190
  499. adjust_timeouts2: packet supposedly had rtt of -125997 microseconds. Ignoring time.
  500. adjust_timeouts2: packet supposedly had rtt of -125997 microseconds. Ignoring time.
  501. Retrying OS detection (try #2) against 174.138.2.190
  502. adjust_timeouts2: packet supposedly had rtt of -150518 microseconds. Ignoring time.
  503. adjust_timeouts2: packet supposedly had rtt of -150518 microseconds. Ignoring time.
  504. WARNING: OS didn't match until try #2
  505. Nmap scan report for 174.138.2.190
  506. Host is up (0.00041s latency).
  507. PORT STATE SERVICE
  508. 1234/tcp open unknown
  509. Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
  510. Device type: switch|general purpose|media device
  511. Running: Cisco CatOS 7.X|8.X, HP Tru64 UNIX 5.X, Vantage embedded
  512. OS CPE: cpe:/h:cisco:catalyst_ws-c6506 cpe:/o:cisco:catos:7.6 cpe:/o:cisco:catos:8.3 cpe:/o:hp:tru64:5.1a cpe:/h:vantage:hd7100s
  513. OS details: Cisco Catalyst WS-C6506 switch (CatOS 7.6(16)), Cisco Catalyst switch (CatOS 8.3(2)), HP Tru64 UNIX 5.1A, Vantage HD7100S satellite receiver
  514. Read data files from: /usr/bin/../share/nmap
  515. OS detection performed. Please report any incorrect results at https://nmap.org/submit/ .
  516. Nmap done: 1 IP address (1 host up) scanned in 3.39 seconds
  517. Raw packets sent: 44 (6.312KB) | Rcvd: 18 (1.820KB)
  518. ```
  519. If SSH server uses the default input port `22`, the following is likely to be presented in output of `nmap` command (unless you've defined a particular port to be scanned in your `nmap` command, like port `1234`):
  520. ```
  521. PORT STATE SERVICE
  522. 22/tcp filtered ssh
  523. ```
  524. Corresponding log entries of targeted SSH server during the nmap scanning (`/var/log/auth.log`):
  525. ```
  526. Feb 19 18:02:46 goauldhost sshd[30057]: Connection from XXX.XXX.XXX.XXX port 6967 on 174.138.2.190 port 1234
  527. Feb 19 18:02:46 goauldhost sshd[30057]: Did not receive identification string from XXX.XXX.XXX.XXX
  528. Feb 19 18:02:46 goauldhost sshd[30058]: Connection from XXX.XXX.XXX.XXX port 52205 on 174.138.2.190 port 1234
  529. Feb 19 18:02:46 goauldhost sshd[30058]: Did not receive identification string from XXX.XXX.XXX.XXX
  530. Feb 19 18:02:47 goauldhost sshd[30059]: Connection from XXX.XXX.XXX.XXX port 25326 on 174.138.2.190 port 1234
  531. Feb 19 18:02:47 goauldhost sshd[30059]: Did not receive identification string from XXX.XXX.XXX.XXX
  532. Feb 19 18:02:47 goauldhost sshd[30060]: Connection from XXX.XXX.XXX.XXX port 32812 on 174.138.2.190 port 1234
  533. Feb 19 18:02:47 goauldhost sshd[30060]: Did not receive identification string from XXX.XXX.XXX.XXX
  534. Feb 19 18:02:47 goauldhost sshd[30061]: Connection from XXX.XXX.XXX.XXX port 17024 on 174.138.2.190 port 1234
  535. Feb 19 18:02:47 goauldhost sshd[30061]: Did not receive identification string from XXX.XXX.XXX.XXX
  536. Feb 19 18:02:47 goauldhost sshd[30062]: Connection from XXX.XXX.XXX.XXX port 53268 on 174.138.2.190 port 1234
  537. Feb 19 18:02:47 goauldhost sshd[30062]: Did not receive identification string from XXX.XXX.XXX.XXX
  538. Feb 19 18:02:47 goauldhost sshd[30063]: Connection from XXX.XXX.XXX.XXX port 34923 on 174.138.2.190 port 1234
  539. Feb 19 18:02:47 goauldhost sshd[30063]: Did not receive identification string from XXX.XXX.XXX.XXX
  540. Feb 19 18:02:47 goauldhost sshd[30064]: Connection from XXX.XXX.XXX.XXX port 14489 on 174.138.2.190 port 1234
  541. Feb 19 18:02:47 goauldhost sshd[30064]: Did not receive identification string from XXX.XXX.XXX.XXX
  542. Feb 19 18:02:47 goauldhost sshd[30065]: Connection from XXX.XXX.XXX.XXX port 40086 on 174.138.2.190 port 1234
  543. Feb 19 18:02:47 goauldhost sshd[30065]: Did not receive identification string from XXX.XXX.XXX.XXX
  544. Feb 19 18:02:47 goauldhost sshd[30066]: Connection from XXX.XXX.XXX.XXX port 38147 on 174.138.2.190 port 1234
  545. Feb 19 18:02:47 goauldhost sshd[30066]: Did not receive identification string from XXX.XXX.XXX.XXX
  546. Feb 19 18:02:48 goauldhost sshd[30067]: Connection from XXX.XXX.XXX.XXX port 49215 on 174.138.2.190 port 1234
  547. Feb 19 18:02:48 goauldhost sshd[30067]: Did not receive identification string from XXX.XXX.XXX.XXX
  548. Feb 19 18:02:48 goauldhost sshd[30068]: Connection from XXX.XXX.XXX.XXX port 34445 on 174.138.2.190 port 1234
  549. Feb 19 18:02:48 goauldhost sshd[30068]: Did not receive identification string from XXX.XXX.XXX.XXX
  550. Feb 19 18:02:48 goauldhost sshd[30069]: Connection from XXX.XXX.XXX.XXX port 4600 on 174.138.2.190 port 1234
  551. Feb 19 18:02:48 goauldhost sshd[30069]: Did not receive identification string from XXX.XXX.XXX.XXX
  552. Feb 19 18:02:48 goauldhost sshd[30070]: Connection from XXX.XXX.XXX.XXX port 59405 on 174.138.2.190 port 1234
  553. Feb 19 18:02:48 goauldhost sshd[30070]: Did not receive identification string from XXX.XXX.XXX.XXX
  554. Feb 19 18:02:48 goauldhost sshd[30071]: Connection from XXX.XXX.XXX.XXX port 7848 on 174.138.2.190 port 1234
  555. Feb 19 18:02:48 goauldhost sshd[30071]: Did not receive identification string from XXX.XXX.XXX.XXX
  556. Feb 19 18:02:49 goauldhost sshd[30072]: Connection from XXX.XXX.XXX.XXX port 5206 on 174.138.2.190 port 1234
  557. Feb 19 18:02:49 goauldhost sshd[30072]: Did not receive identification string from XXX.XXX.XXX.XXX
  558. Feb 19 18:02:50 goauldhost sshd[30073]: Connection from XXX.XXX.XXX.XXX port 5517 on 174.138.2.190 port 1234
  559. Feb 19 18:02:50 goauldhost sshd[30073]: Did not receive identification string from XXX.XXX.XXX.XXX
  560. Feb 19 18:02:50 goauldhost sshd[30074]: Connection from XXX.XXX.XXX.XXX port 3970 on 174.138.2.190 port 1234
  561. Feb 19 18:02:50 goauldhost sshd[30074]: Did not receive identification string from XXX.XXX.XXX.XXX
  562. Feb 19 18:02:50 goauldhost sshd[30075]: Connection from XXX.XXX.XXX.XXX port 38690 on 174.138.2.190 port 1234
  563. Feb 19 18:02:50 goauldhost sshd[30075]: Did not receive identification string from XXX.XXX.XXX.XXX
  564. Feb 19 18:02:50 goauldhost sshd[30076]: Connection from XXX.XXX.XXX.XXX port 50572 on 174.138.2.190 port 1234
  565. Feb 19 18:02:50 goauldhost sshd[30076]: Did not receive identification string from XXX.XXX.XXX.XXX
  566. Feb 19 18:02:50 goauldhost sshd[30077]: Connection from XXX.XXX.XXX.XXX port 27830 on 174.138.2.190 port 1234
  567. Feb 19 18:02:50 goauldhost sshd[30077]: Did not receive identification string from XXX.XXX.XXX.XXX
  568. Feb 19 18:02:50 goauldhost sshd[30078]: Connection from XXX.XXX.XXX.XXX port 49371 on 174.138.2.190 port 1234
  569. Feb 19 18:02:50 goauldhost sshd[30078]: Did not receive identification string from XXX.XXX.XXX.XXX
  570. Feb 19 18:02:51 goauldhost sshd[30079]: Connection from XXX.XXX.XXX.XXX port 36802 on 174.138.2.190 port 1234
  571. Feb 19 18:02:51 goauldhost sshd[30079]: Did not receive identification string from XXX.XXX.XXX.XXX
  572. Feb 19 18:02:51 goauldhost sshd[30080]: Connection from XXX.XXX.XXX.XXX port 50546 on 174.138.2.190 port 1234
  573. Feb 19 18:02:51 goauldhost sshd[30080]: Did not receive identification string from XXX.XXX.XXX.XXX
  574. Feb 19 18:02:51 goauldhost sshd[30081]: Connection from XXX.XXX.XXX.XXX port 43542 on 174.138.2.190 port 1234
  575. Feb 19 18:02:51 goauldhost sshd[30081]: Did not receive identification string from XXX.XXX.XXX.XXX
  576. Feb 19 18:02:51 goauldhost sshd[30082]: Connection from XXX.XXX.XXX.XXX port 56108 on 174.138.2.190 port 1234
  577. Feb 19 18:02:51 goauldhost sshd[30082]: Did not receive identification string from XXX.XXX.XXX.XXX
  578. Feb 19 18:02:51 goauldhost sshd[30083]: Connection from XXX.XXX.XXX.XXX port 6399 on 174.138.2.190 port 1234
  579. Feb 19 18:02:51 goauldhost sshd[30083]: Did not receive identification string from XXX.XXX.XXX.XXX
  580. Feb 19 18:02:51 goauldhost sshd[30084]: Connection from XXX.XXX.XXX.XXX port 55980 on 174.138.2.190 port 1234
  581. Feb 19 18:02:51 goauldhost sshd[30084]: Did not receive identification string from XXX.XXX.XXX.XXX
  582. Feb 19 18:02:51 goauldhost sshd[30085]: Connection from XXX.XXX.XXX.XXX port 12713 on 174.138.2.190 port 1234
  583. Feb 19 18:02:51 goauldhost sshd[30085]: Did not receive identification string from XXX.XXX.XXX.XXX
  584. Feb 19 18:02:51 goauldhost sshd[30086]: Connection from XXX.XXX.XXX.XXX port 5026 on 174.138.2.190 port 1234
  585. Feb 19 18:02:51 goauldhost sshd[30086]: Did not receive identification string from XXX.XXX.XXX.XXX
  586. ```
  587. The server computer has logged invalid nmap connection requests. In this case, we have defined the known SSH connection port number `1234` in our `nmap` command on the client computer (which is INPUT port at the server end, OUTPUT port at the client end).
  588. You may check suggested countermeasures against port scanners on [Unix & Linux Stack Exchange](https://unix.stackexchange.com/questions/345114/how-to-protect-against-port-scanners/407904#407904). Does these measures interfere negatively to other network traffic in busy server environments? This depends on which ports (read: server daemon programs/services) are targets of your countermeasures.
  589. Another `nmap` command shows us the following:
  590. ```
  591. phelenius@my-machine:~$ sudo nmap 174.138.2.190 -sV
  592. Starting Nmap 7.01 ( https://nmap.org ) at 2018-02-20 14:50 EET
  593. Nmap scan report for 174.138.2.190
  594. Host is up (0.33s latency).
  595. Not shown: 998 filtered ports
  596. PORT STATE SERVICE VERSION
  597. 1234/tcp open ssh OpenSSH 7.6 (protocol 2.0)
  598. 80/tcp open http
  599. ...
  600. ```
  601. ... which reveals the actual service behind our new-defined port 1234/tcp to an attacker. In addition, the attacker can get more information about the server system, especially on Debian-based Linux distributions. For instance:
  602. ```
  603. ...
  604. PORT STATE SERVICE VERSION
  605. 22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu2.4 (Ubuntu Linux; protocol 2.0)
  606. ...
  607. ```
  608. This information can be hidden by adding line `DebianBanner no` in `/etc/ssh/sshd_config` on Debian-based Linux systems and restarting the SSH server daemon with command `sudo systemctl restart sshd.service` afterwards
  609. **NOTE:** Port scanning does not leave any log traces behind in Apache's access.log file (`/var/log/apache/access.log`)!
  610. Check also
  611. - [MyPapit GNU/Linux - How to Hide OpenSSH Ubuntu version from Nmap and other scanners](https://blog.mypapit.net/2015/08/how-to-hide-openssh-ubuntu-release-from-nmap-and-other-scanners.html)
  612. - [serverfault.com - How to hide web server name and openssh version on linux when scanning server ports?](https://serverfault.com/questions/81690/how-to-hide-web-server-name-and-openssh-version-on-linux-when-scanning-server-po/81697#81697)
  613. - [Unix & Linux Stack Exchange - Change SSH banner which is grabbed by netcat](https://unix.stackexchange.com/questions/269024/change-ssh-banner-which-is-grabbed-by-netcat/269027#269027)
  614. - [GitHub - metacloud/openssh - Include the Debian version in our identification](https://github.com/metacloud/openssh/blob/master/debian/patches/package-versioning.patch)
  615. ------------------------------------------------
  616. ### EXTRA - Using Port Knocking technique against port scanning
  617. Nmap requests are targeted to layer 3 (Network Layer) in OSI model. Additional security measures can be taken by applying [Port Knocking login techniques](https://wiki.archlinux.org/index.php/Port_knocking) on the server computer.
  618. **WARNING!** The following **Knockd daemon** may break easily. Thus it can not be recommended for critical or rapidly updating server environments. For instance, dhcpcd version 7 or above breaks `knockd` daemon. Many users have had problems to start the daemon service during server boot-up process. Knockd assumes that you have a preconfigured network interface with established network connection (this is not 100% valid information but this is my best guess).
  619. [DigitalOcean, "Port Knocking" - Ubuntu, knockd](https://www.digitalocean.com/community/tutorials/how-to-use-port-knocking-to-hide-your-ssh-daemon-from-attackers-on-ubuntu):
  620. Dynamic firewall rules are manually applied to the server (iptables, for instance) or separate daemon process ([for instance, knockd](http://www.zeroflux.org/projects/knock)) is set up on the server computer. Daemon process is used to open a pre-defined port only if a client program has knocked correct server port numbers in right order and using correct protocol, either TCP or UDP, and this all has been done in predefined time limit. Additionally, limited timeout for user log-in can be set. For instance, a correctly authenticated user must log in in 10 seconds ater Knock daemon has opened a SSH port for that time period. When the time limit is reached, Knock daemon closes the port for any further connection attempts unless the knock port sequence is re-applied.
  621. Knocking technique must be configured so that firewall does not close already established connections (like SSH in our case), but refuses any further connection attempts so that the port can not be detected with nmap port scanning techniques after the time limit has been reached.
  622. [DigitalOcean, "Port Knocking" - FWKnop - Single packet authentication](https://www.digitalocean.com/community/tutorials/how-to-use-fwknop-to-enable-single-packet-authentication-on-ubuntu-12-04):
  623. Some more or less secure implementations for port knocking exist. Various encryption methods can be applied to the knocking technique, making it more difficult for an attacker to sniff network packets between a server and a client. One solution using encyption methods is [fwknop](http://www.cipherdyne.org/fwknop/) which uses `Single Packet Authorization` (SPA) method instead of insecure port sequences.
  624. More about Port Knocking technique:
  625. - [Improved Port Knocking with Strong Authentication - Rennie deGraaf, John Aycock, and Michael Jacobson, Jr.∗ (Department of Computer Science - University of Calgary)](https://www.acsac.org/2005/papers/156.pdf)
  626. - [OpenWRT website](https://wiki.openwrt.org/doc/howto/portknock.server)
  627. - [portknocking.org](http://www.portknocking.org/) and practical solutions on [Implementations sub-page](http://www.portknocking.org/view/implementations)
  628. - [Information Security Stack Exchange - Port Knocking is it a good idea?](https://security.stackexchange.com/questions/1194/port-knocking-is-it-a-good-idea/1196#1196)
  629. **NOTE:** Port Knocking technique must not be applied to block ports of server daemon processes which are required to be always reachable from a client program (take Apache server for an example). For SSH which does not require 24/7/365 connection, port knocking techniques can be applied more reliably. In addition to public key, password and PAM authentication methods, port knocking adds one more security layer to the stack. However, you must not apply these security countermeasures individually but use them together, instead. **The goal is to make it more difficult for an attacker to penetrate your network security.**
  630. ------------------------------------------------
  631. ### EXTRA - ARP Scan and spoofing your MAC address
  632. Program [arp-scan](https://www.blackmoreops.com/2015/12/31/use-arp-scan-to-find-hidden-devices-in-your-network/) can be used in limited scale to scan a MAC address (OSI model layer 2, Data Link Layer) in a network.
  633. Unique MAC address of a network interface (network card) can programmatically be spoofed with [these Arch Wiki instructions](https://wiki.archlinux.org/index.php/MAC_address_spoofing#Method_1:_systemd-networkd) or with my [Spoof MAC Address shell script](https://github.com/Fincer/linux_server_setup/blob/master/scripts/spoof_mac_address.sh).
  634. Sample results of ARP Scan.
  635. BEFORE:
  636. ```
  637. [20/02/2018 18:52:35 - fincer: ~ ]$ sudo arp-scan --interface=wlan0 --localnet
  638. [sudo] password for fincer:
  639. Interface: wlan0, datalink type: EN10MB (Ethernet)
  640. Starting arp-scan 1.9 with 256 hosts (http://www.nta-monitor.com/tools/arp-scan/)
  641. A.B.C.D f4:0e:22:ad:b8:7d (Unknown)
  642. 1.2.3.4 18:a9:05:4b:61:58 Hewlett-Packard Company
  643. ```
  644. AFTER - MAC address of a computer having IP address 1.2.3.4 has been changed:
  645. ```
  646. [20/02/2018 18:54:28 - fincer: ~ ]$ sudo arp-scan --interface=wlan0 --localnet
  647. Interface: wlan0, datalink type: EN10MB (Ethernet)
  648. Starting arp-scan 1.9 with 256 hosts (http://www.nta-monitor.com/tools/arp-scan/)
  649. A.B.C.D f4:0e:22:ad:b8:7d (Unknown)
  650. 1.2.3.4 aa:0c:9a:fa:7b:d4 (Unknown)
  651. ```
  652. The following warning messages may be expected after spoofing a MAC address and when you establish SSH connection from a local computer to your server:
  653. ```
  654. Warning: Permanently added the ECDSA host key for IP address '[1.2.3.4]:22' to the list of known hosts.
  655. ```
  656. **g)** (optional) Allow SSH login only for users in group 'sshers'. Add your account to this group.
  657. --------------
  658. **Answer:**
  659. **1.** Log in to the server computer (`ssh username@server-ip -p <ssh-port>`)
  660. **2.** Add group `sshers` with GID number `876` (you don't have to define GID here)
  661. ```
  662. sudo groupadd -g 876 sshers
  663. ```
  664. **3.** You can confirm existence of the created group with command `grep sshers /etc/group`. Output:
  665. ```
  666. sshers:x:876:
  667. ```
  668. **4.** Add the current user (read: yourself) `newuser` into this group
  669. ```
  670. sudo usermod -aG sshers newuser
  671. ```
  672. **5.** Command `grep sshers /etc/group` output now:
  673. ```
  674. sshers:x:876:newuser
  675. ```
  676. You can alternatively check groups of `newuser` by executing command `groups` while being that user:
  677. ```
  678. [27/02/2018 10:39:58 - newuser@goauldhost: ~ ]$ groups
  679. sshers newuser sudo
  680. ```
  681. or using command `sudo -u newuser groups` as any system user who can execute commands with sudo.
  682. **NOTE:** `groups` command gives you correct output only after re-login.
  683. **6.** Allow SSH login only to members of the group `sshers`.
  684. Manual page of `sshd_config` (`man sshd_config`) describes `AllowGroups` option as follows:
  685. > AllowGroups
  686. > This keyword can be followed by a list of group name patterns, separated by spaces. If specified, login is allowed only for users whose primary group or supplementary group list matches one of the patterns. Only group names are valid; a numerical group ID is not recognized. By default, login is allowed for all groups. The allow/deny directives are processed in the following order: DenyUsers, AllowUsers, DenyGroups, and finally AllowGroups.
  687. Let's apply the following information into SSH server daemon configuration file `/etc/ssh/sshd_config`:
  688. ```
  689. PermitRootLogin no
  690. AllowGroups sshers
  691. ```
  692. And comment out the following lines (be careful here!):
  693. ```
  694. # DenyUsers <user accounts>
  695. # AllowUsers <user accounts>
  696. # DenyGroups <group names>
  697. ```
  698. If those lines are not defined in the configuration file, it is OK.
  699. You can add multiple groups and users after those keywords, as you like.
  700. For additional security, the following options can be applied as well (into `/etc/ssh/sshd_config` file), depending on your requests for SSH authentication policy:
  701. ```
  702. IgnoreRhosts yes
  703. PermitEmptyPasswords no
  704. ChallengeResponseAuthentication yes
  705. UsePAM yes
  706. MaxAuthTries 3
  707. ```
  708. etc. More options and configurations can be found with commands `man sshd_config` and `man sshd`
  709. **7.** Let's save this configuration and restart SSH server daemon by applying command `sudo systemctl restart sshd.service` (NOTE! Disconnects already-established/existing SSH connections!)
  710. **8.** Test SSH login with a client computer using remote user `newuser` (belonging to the remote group `sshers`). Command syntax is: `ssh newuser@server-ip -p <server-port>`
  711. **h)** (optional) Attach a remote network directory with sshfs.
  712. --------------
  713. **Answer:**
  714. SSHFS stands for SSH File System. Corresponding program `sshfs` has been developed to attach SSH server file systems (folders/files) remotely on a client computer so that all attached file systems can locally be browsed on the client computer. SSHFS uses encrypted SFTP protocol (SSH/Secure File Transfer Protocol) for file tranfers.
  715. **1.** Install `sshfs` with command sequence `sudo apt-get update && sudo apt-get -y install sshfs` on a Debian-based Linux system.
  716. **2.** Mount remote folder `/home/newuser/public_html/` (server), to path `/home/<current-user>/public_html_ssh_remote` on your client computer.
  717. ```
  718. mkdir $HOME/public_html_ssh_remote && sshfs newuser@174.138.2.190:./public_html $HOME/public_html_ssh_remote -p <ssh port>
  719. ```
  720. **NOTE:** If you use public key SSH authentication method, you are not asked for any password.
  721. **3.** Check that you have successfully mounted your remote server folder `/home/newuser/public_html` to the client computer (command `ls ~/public_html_ssh_remote/`). Output should be as follows:
  722. ```
  723. index.html
  724. ```
  725. Additionally, check output of command `mount | grep public_html_ssh_remote`:
  726. ```
  727. newuser@174.138.2.190:./public_html on /home/phelenius/public_html_ssh_remote type fuse.sshfs (rw,nosuid,nodev,relatime,user_id=1000,group_id=1000)
  728. ```
  729. **4.** Unmount the remote folder by issuing command `sudo umount /home/phelenius/public_html_ssh_remote`. On the client end, `ls` command should have empty output for directory `public_html_ssh_remote`.