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.

1027 lines
61 KiB

6 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:~$ sudo 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 example, 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 title '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. By default, Uncomplicated Firewall (ufw) is usually pre-installed on many Linux distributions, including Debian-based systems. Let's confirm that:
  60. ```
  61. 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
  62. REPLY: UFW has already been installed
  63. ```
  64. Therefore ufw firewall is installed. Otherwise it would be installed on the system with _apt-get install_ command.
  65. By default, the Linux firewall blocks SSH input traffic (default port 22). This input port can be opened by applying the following ufw command:
  66. ```
  67. phelenius@my-machine:~$ sudo ufw allow 22/tcp
  68. ```
  69. or with the command (however, not specific port number is defined here):
  70. ```
  71. phelenius@my-machine:~$ sudo ufw allow ssh
  72. ```
  73. Afterwards, UFW can be re-enabled with the following command:
  74. ```
  75. phelenius@my-machine:~$ sudo ufw enable
  76. Command may disrupt existing ssh connections. Proceed with operation (y|n)?
  77. ```
  78. 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:
  79. ```
  80. Firewall is active and enabled on system startup
  81. ```
  82. 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:
  83. ```
  84. phelenius@my-machine:~$ sudo systemctl enable ufw.service
  85. Created symlink /etc/systemd/system/multi-user.target.wants/ufw.service -> /usr/lib/systemd/system/ufw.service.
  86. ```
  87. Alternatively, the following message may appear:
  88. ```
  89. Synchronizing state of ufw.service with SysV init with /lib/systemd/systemd-sysv-install...
  90. Executing /lib/systemd/systemd-sysv-install enable ufw
  91. ```
  92. **iptables:**
  93. 1. Remove ufw from the Linux system, and remove all relevant ufw entries from iptables firewall rule list.
  94. **NOTE!** Warning: (May) delete other important iptables rules configured by system administration!
  95. **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.
  96. ```
  97. sudo systemctl stop ufw.service && sudo systemctl disable ufw.service
  98. sudo apt-get purge --remove ufw
  99. sudo iptables --flush && sudo iptables --delete-chains
  100. ```
  101. 2. Confirm deletion of ufw entries from iptables firewall rule list with
  102. ```
  103. sudo iptables -S
  104. ```
  105. Output should be:
  106. ```
  107. -P INPUT ACCEPT
  108. -P FORWARD ACCEPT
  109. -P OUTPUT ACCEPT
  110. ```
  111. 3. Add new firewall rules to iptables and keep already established connections open:
  112. ```
  113. sudo iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  114. ```
  115. 4. Drop all connections, excluding already established connections like SSH:
  116. ```
  117. sudo iptables -A INPUT -j DROP
  118. sudo iptables -A FORWARD -j DROP
  119. ```
  120. 5. Allow SSH traffic (port number: 22, protocol: tcp, etc.):
  121. ```
  122. sudo iptables -I INPUT -p tcp --dport 22 -j ACCEPT
  123. ```
  124. **NOTE!** This applies only to IPv4 connections. For IPv6, check [iptables6](https://www.linux.com/learn/intro-to-linux/2017/8/iptables-rules-ipv6).
  125. **NOTE!** The forementioned command can be written so that connections only from a single IP is allowed, by using eth0 network interface. For example:
  126. ```
  127. sudo iptables -I INPUT -p tcp -i eth0 -s 231.123.24.24 --dport 22 -j ACCEPT
  128. ```
  129. **NOTE:** Be sure you have enabled 'net.ifnames=0' in your udev rules to get network interface names like 'eth0', 'wlan0' etc.!
  130. 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 example.
  131. 6. Confirm proper iptables firewall rules with 'sudo iptables -S' command:
  132. ```
  133. -P INPUT ACCEPT
  134. -P FORWARD ACCEPT
  135. -P OUTPUT ACCEPT
  136. -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  137. -A INPUT -j DROP
  138. -A FORWARD -j DROP
  139. -I INPUT -p tcp --dport 22 -j ACCEPT
  140. ```
  141. 7. Save the rules so that they won't be lost after rebooting:
  142. ```
  143. sudo iptables-save | sudo tee /etc/iptables/iptables.save > /dev/null
  144. cat /etc/iptables/iptables.save
  145. ```
  146. 8. Apply and enable the rules. You can restart iptables service (Packet Filtering Framework) if you prefer to do so:
  147. ```
  148. sudo iptables-restore && sudo systemctl restart iptables.service
  149. ```
  150. 9. Confirm the current iptables firewall rules with the command 'sudo iptables -S'.
  151. More about iptables:
  152. - [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)
  153. - [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).
  154. - [The Geek Stuff - 25 Most Frequently Used Linux IPTables Rules Examples](https://www.thegeekstuff.com/2011/06/iptables-rules-examples)
  155. **Other firewall solutions:**
  156. 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.
  157. ------------------------------------------------
  158. **EXTRA - root account: more restrictions**
  159. In addition to previous root restrictions, the following extra restrictions were applied, too:
  160. - root default shell were changed to _/sbin/nologin_ in file _/etc/passwd_
  161. - 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_
  162. - root access removal of TTY sessions by commenting out relevant lines in file _/etc/securetty_
  163. - SSH: setting _PermitRootLogin no_ were applied in SSH server configuration file _/etc/ssh/sshd_config_
  164. 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.)
  165. 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)
  166. **c)** Transfer files using SSH protocol
  167. --------------
  168. **Answer:**
  169. Let's use [Secure Copy (scp)](https://en.wikipedia.org/wiki/Secure_copy) command for file transfers.
  170. The assignment has been done in the following command sequence. The following steps are executed:
  171. 1. Create new subdirectory _httpd_ into the current user's home directory on the local computer
  172. 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_
  173. 3. Extract the downloaded archive files into $HOME/httpd. Subdirectory _debian_ will be created in _httpd_ directory.
  174. 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.
  175. 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
  176. to the directory _$HOME/patches_ located at the server computer (where $HOME=/home/newuser/). SSH connection port is 1234. Use command scp.
  177. For more information about patches, check [1](https://stackoverflow.com/questions/987372/what-is-the-format-of-a-patch-file), [2](https://www.thegeekstuff.com/2014/12/patch-command-examples))
  178. 6. List contents of the remote subdirectory _$HOME/patches_ with SSH connection, use port 1234..
  179. 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.
  180. ```
  181. [20/02/2018 13:24:40 - fincer: ~ ]$ mkdir httpd
  182. [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
  183. --2018-02-20 13:25:13-- http://archive.ubuntu.com/ubuntu/pool/main/a/apache2/apache2_2.4.18-2ubuntu3.5.debian.tar.xz
  184. Resolving archive.ubuntu.com... 2001:67c:1560:8001::11, 2001:67c:1360:8001::17, 2001:67c:1560:8001::14, ...
  185. Connecting to archive.ubuntu.com|2001:67c:1560:8001::11|:80... connected.
  186. HTTP request sent, awaiting response... 200 OK
  187. Length: 387448 (378K) [application/x-xz]
  188. Saving to: ‘httpd/apache2_2.4.18-2ubuntu3.5.debian.tar.xz’
  189. apache2_2.4.18-2ubuntu3.5.debian.tar.xz 100%[==================================================================================>] 378.37K 450KB/s in 0.8s
  190. 2018-02-20 13:25:15 (450 KB/s) - ‘httpd/apache2_2.4.18-2ubuntu3.5.debian.tar.xz’ saved [387448/387448]
  191. [20/02/2018 13:25:15 - fincer: ~ ]$ tar xf apache2_2.4.18-2ubuntu3.5.debian.tar.xz -C httpd
  192. [20/02/2018 13:25:35 - fincer: ~ ]$ ssh newuser@174.138.2.190 -p 1234 mkdir patches
  193. newuser@174.138.2.190's password:
  194. [20/02/2018 13:26:12 - fincer: ~ ]$ scp -P 1234 ./httpd/debian/patches/*.{diff,patch} newuser@174.138.2.190:./patches/
  195. newuser@174.138.2.190's password:
  196. hostnames_with_underscores.diff 100% 479 114.6KB/s 00:00
  197. reproducible_builds.diff 100% 1710 427.2KB/s 00:00
  198. build_suexec-custom.patch 100% 1981 473.6KB/s 00:00
  199. customize_apxs.patch 100% 9316 888.9KB/s 00:00
  200. CVE-2016-0736.patch 100% 12KB 867.4KB/s 00:00
  201. CVE-2016-2161.patch 100% 4787 493.1KB/s 00:00
  202. CVE-2016-5387.patch 100% 666 287.9KB/s 00:00
  203. CVE-2016-8743.patch 100% 80KB 1.0MB/s 00:00
  204. CVE-2017-3167.patch 100% 8922 698.9KB/s 00:00
  205. CVE-2017-3169.patch 100% 4663 458.1KB/s 00:00
  206. CVE-2017-7668.patch 100% 1746 482.5KB/s 00:00
  207. CVE-2017-7679.patch 100% 1925 527.4KB/s 00:00
  208. CVE-2017-9788.patch 100% 2252 582.1KB/s 00:00
  209. CVE-2017-9798.patch 100% 1172 381.3KB/s 00:00
  210. fhs_compliance.patch 100% 2541 635.6KB/s 00:00
  211. no_LD_LIBRARY_PATH.patch 100% 444 199.8KB/s 00:00
  212. prefork_single_process_crash.patch 100% 773 359.0KB/s 00:00
  213. suexec-custom.patch 100% 5785 792.4KB/s 00:00
  214. suexec-CVE-2007-1742.patch 100% 2356 589.3KB/s 00:00
  215. suexec_is_shared.patch 100% 622 194.1KB/s 00:00
  216. [20/02/2018 13:28:03 - fincer: ~ ]$ ssh newuser@174.138.2.190 -p 1234 ls -l ./patches
  217. newuser@174.138.2.190's password:
  218. total 196
  219. -rw-r--r-- 1 newuser newuser 12446 Feb 20 11:38 CVE-2016-0736.patch
  220. -rw-r--r-- 1 newuser newuser 4787 Feb 20 11:38 CVE-2016-2161.patch
  221. -rw-r--r-- 1 newuser newuser 666 Feb 20 11:38 CVE-2016-5387.patch
  222. -rw-r--r-- 1 newuser newuser 81900 Feb 20 11:38 CVE-2016-8743.patch
  223. -rw-r--r-- 1 newuser newuser 8922 Feb 20 11:38 CVE-2017-3167.patch
  224. -rw-r--r-- 1 newuser newuser 4663 Feb 20 11:38 CVE-2017-3169.patch
  225. -rw-r--r-- 1 newuser newuser 1746 Feb 20 11:38 CVE-2017-7668.patch
  226. -rw-r--r-- 1 newuser newuser 1925 Feb 20 11:38 CVE-2017-7679.patch
  227. -rw-r--r-- 1 newuser newuser 2252 Feb 20 11:38 CVE-2017-9788.patch
  228. -rw-r--r-- 1 newuser newuser 1172 Feb 20 11:38 CVE-2017-9798.patch
  229. -rw-r--r-- 1 newuser newuser 1981 Feb 20 11:38 build_suexec-custom.patch
  230. -rw-r--r-- 1 newuser newuser 9316 Feb 20 11:38 customize_apxs.patch
  231. -rw-r--r-- 1 newuser newuser 2541 Feb 20 11:38 fhs_compliance.patch
  232. -rw-r--r-- 1 newuser newuser 479 Feb 20 11:38 hostnames_with_underscores.diff
  233. -rw-r--r-- 1 newuser newuser 444 Feb 20 11:38 no_LD_LIBRARY_PATH.patch
  234. -rw-r--r-- 1 newuser newuser 773 Feb 20 11:38 prefork_single_process_crash.patch
  235. -rw-r--r-- 1 newuser newuser 1710 Feb 20 11:38 reproducible_builds.diff
  236. -rw-r--r-- 1 newuser newuser 2356 Feb 20 11:38 suexec-CVE-2007-1742.patch
  237. -rw-r--r-- 1 newuser newuser 5785 Feb 20 11:38 suexec-custom.patch
  238. -rw-r--r-- 1 newuser newuser 622 Feb 20 11:38 suexec_is_shared.patch
  239. [20/02/2018 13:32:01 - fincer: ~ ]$ rm -Rf httpd
  240. ```
  241. **d)** Automate SSH login with public key method
  242. --------------
  243. **Answer:**
  244. 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.
  245. 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.
  246. **NOTE!** Copy public key only, do **NOT** copy the private key!
  247. More about the topic:
  248. [ssh.com - Key Pair - Public and Private](https://www.ssh.com/ssh/public-key-authentication#sec-Key-Pair-Public-and-Private)
  249. 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_'):
  250. ```
  251. AuthenticationMethods publickey
  252. PubkeyAuthentication yes
  253. AuthorizedKeysFile .ssh/authorized_keys
  254. ```
  255. **Extra hint 1:** SSH client settings are generally defined in _/etc/ssh/ssh_config_
  256. **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:
  257. > -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.
  258. 4. Käynnistetään vielä palvelimen SSH-daemon uudelleen komennolla _sudo systemctl restart sshd.service_ (huom! Katkaisee muodostetut SSH-yhteydet)
  259. 5. Testataan julkisen avaimen kirjautumismenetelmää asiakaskoneen käyttäjällä, jolla _ssh-keygen_-komento suoritettiin. Käyttäjän pitäisi päästä SSH-palvelimelle sisään ilman salasanaa.
  260. **EXTRA: Modifying welcome banner**
  261. Muokataan vielä Ubuntun oletuksena olevaa sisäänkirjautumisbanneria seuraavalla bash-skriptillä:
  262. ```
  263. #!/bin/bash
  264. # Muokkaa ssh:n sisäänkirjautumisen yhteydessä olevaa banneria
  265. ## 00-header-tiedosto:
  266. #
  267. 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:
  268. %s\\n\\n" "Server Computer" "$(uptime)"?' /etc/update-motd.d/00-header
  269. ## Seuraavien tiedostojen tiedostopäätettä muutetaan
  270. ## Voitaisiin myös poistaa nämä tiedostot komennolla 'sudo rm <tiedosto>'
  271. #
  272. FILES=( 10-help-text 51-cloudguest 90-updates-available 91-release-upgrade )
  273. cd /etc/update-motd.d/
  274. for file in ${FILES[@]}; do sudo mv $file $file.old; done
  275. cd
  276. ```
  277. Banneritiedostojen sijainti vaihtelee Linux-jakeluilla. Esimerkiksi Arch Linuxilla banneri on tiedosto _etc/motd_.
  278. **j)** 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.
  279. --------------
  280. **Answer:**
  281. 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'
  282. 2. Run [shell-based sysstat script](https://github.com/Fincer-altego/basics-of-a-linux-server-school-course-/blob/master/sysstat_command.sh) which runs sar and pidstat commands two days with 20 second intervals.
  283. **NOTE!** The script could have been opmitized more for the real requirements for the server environment (statistics interval, collection period, etc.)
  284. 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.
  285. Time period: 24. - 26.02.2018
  286. The following sums up some command samples which can be applied to the analytics file.
  287. | File | Description |
  288. |------------------------------------|-------------------------------------------------|
  289. | sar -u -f <analytics-file> | Processor workload statistics |
  290. | sar -v -f <analytics-file> | Inode and file statistics |
  291. | sar -r -f <analytics-file> | Memory consumption statistics |
  292. | sar -n DEV -f <analytics-file> | Network stats: devices |
  293. | sar -n EDEV -f <analytics-file> | Network stats: errors in devices |
  294. | sar -n IP -f <analytics-file> | Network stats: IPv4 traffic |
  295. | sar -n EIP -f <analytics-file> | Network stats: errors in IPv4 traffic |
  296. | sar -n IP6 -f <analytics-file> | Network stats: IPv6 traffic |
  297. | sar -n EIP6 -f <analytics-file> | Network stats: errors in IPv6 traffic |
  298. | sar -n SOCK -f <analytics-file> | Network stats: IPv4 socket |
  299. | sar -n SOCK6 -f <analytics-file> | Network stats: IPv6 socket |
  300. | sar -n TCP -f <analytics-file> | Network stats: TCPv4 protocol traffic |
  301. | sar -n ETCP -f <analytics-file> | Network stats: errors in TCPv4 protocol traffic |
  302. | sar -S -f <analytics-file> | Swap memory consumption |
  303. | sar -w -f <analytics-file> | Process statistics |
  304. | sar -F MOUNT / -f <analytics-file> | File system which is mounted at / |
  305. Statistics can be combined etc, as you can find out with 'man sar' command:
  306. ```
  307. sar -u 2 5
  308. Report CPU utilization for each 2 seconds. 5 lines are displayed.
  309. sar -I 14 -o int14.file 2 10
  310. Report statistics on IRQ 14 for each 2 seconds. 10 lines are displayed. Data are stored in a file called int14.file.
  311. sar -r -n DEV -f /var/log/sysstat/sa16
  312. Display memory and network statistics saved in daily data file 'sa16'.
  313. sar -A
  314. Display all the statistics saved in current daily data file.
  315. ```
  316. 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)
  317. What are inode and swap? Check
  318. - [inode - 1](https://www.cyberciti.biz/tips/understanding-unixlinux-filesystem-inodes.html)
  319. - [inode - 2](https://unix.stackexchange.com/questions/117093/find-where-inodes-are-being-used)
  320. - [Swap](https://wiki.archlinux.org/index.php/swap).
  321. Additionally, the following pidstat files were generated:
  322. | File | Description |
  323. |----------------------------|------------------------------------|
  324. | pidstat_stats_cpu-tasks | Processor workload statistics |
  325. | pidstat_stats_io | I/O statistics |
  326. | pidstat_stats_kerneltables | Statistics of Linux kernel tables |
  327. | pidstat_stats_pagefaults | Page fault statistics |
  328. | pidstat_stats_stacks | Process stack statistics |
  329. (Check. [Stacks](https://stackoverflow.com/questions/8905271/what-is-the-linux-stack), [Page fault](https://en.wikipedia.org/wiki/Page_fault))
  330. Additionally, iostat command was run on the background.
  331. 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.
  332. ------------------------------------------------
  333. **SAR network statistics - IPv4 traffic**
  334. **command: sar -n IP -f sar-stats_2018-02-24_2018-02-26.file**
  335. ![sar-stats-ipv4](https://raw.githubusercontent.com/Fincer-altego/basics-of-a-linux-server-school-course-/master/sar-stats_ipv4.png)
  336. **Observation period:** 24.-26.02.2018
  337. | Field | Description | Average |
  338. |-------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------|
  339. | Left column | Record time | |
  340. | irec/s | The total number of input datagrams received from interfaces per second, including those received in error. | 1.33 |
  341. | 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 |
  342. | idel/s | The total number of input datagrams,successfully,delivered,per,second,to,IP user-protocols (including ICMP). | 1.30 |
  343. | 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 |
  344. | asmrq/s | The number of IP fragments received per second which needed to be reassembled at this entity. | 0.00 |
  345. | asmok/s | The number of IP datagrams successfully re-assembled per second. | 0.00 |
  346. | fragok/s | The number of IP datagrams that,have,been,successfully fragmented at this entity per second. | 0.00 |
  347. | fragcrt/s | The number of IP datagram fragments that have been generated per second as a result of fragmentation at this entity. | 0.00 |
  348. **NOTE!** Descriptions are provided in sysstat package (manpages).
  349. **ANALYSIS - IPV4**
  350. 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.
  351. 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 example).
  352. 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.
  353. Check also
  354. - [MTU - hyperlink 1](http://www.tcpipguide.com/free/t_IPDatagramSizeMaximumTransmissionUnitMTUFragmentat.htm)
  355. - [MTU - hyperlink 2](https://en.wikipedia.org/wiki/Maximum_transmission_unit)
  356. - [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)
  357. - [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)
  358. - [IP fragmentation](https://en.wikipedia.org/wiki/IP_fragmentation)
  359. - Related article: [Linux Tune Network Stack (Buffers Size) To Increase Networking Performance](https://www.cyberciti.biz/faq/linux-tcp-tuning/)
  360. **NOTE!** About datagrams, [quoted from Wikipedia](https://en.wikipedia.org/wiki/Datagram#Internet_Protocol):
  361. > 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".
  362. ------------------------------------------------
  363. **SAR - memory consumption statistics - RAM & SWAP**
  364. **command: sar -r -f sar-stats_2018-02-24_2018-02-26.file**
  365. **command: sar -S -f sar-stats_2018-02-24_2018-02-26.file**
  366. ![sar-stats-memusage](https://raw.githubusercontent.com/Fincer-altego/basics-of-a-linux-server-school-course-/master/sar-stats_memusage.png)
  367. **Observation period:** 24.-26.02.2018
  368. NOTE! Average values are not visible in the attached picture!
  369. | Field | Description | Average |
  370. |-------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------|
  371. | Left column | Record time | |
  372. | kbmemfree | Amount of free memory available in kilobytes. | 87631 KB (~ 87 MB) |
  373. | kbmemused | Amount,of,used,memory in kilobytes. This does not take into account memory used by the kernel itself. | 928 457 KB (~ 928 MB) |
  374. | %memused | Percentage of used memory. | 91.38 % |
  375. | kbbuffers | Amount of memory used as buffers by the kernel in kilobytes. | 77 746 KB (~ 77 MB) |
  376. | kbcached | Amount of memory used to cache data by the kernel in kilobytes. | 644 777 KB (~ 644 MB) |
  377. | 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) |
  378. | %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 % |
  379. | 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) |
  380. | 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) |
  381. | kbdirty | Amount of memory in kilobytes waiting to get written back to the disk. | 254 KB (0.254 MB) |
  382. **NOTE!** Descriptions are provided in sysstat package (manpages).
  383. **ANALYSIS - MEMORY STATISTICS**
  384. The target server memory size:
  385. ```
  386. [newuser@goauldhost: ~ ]$ cat /proc/meminfo | grep -i memtotal
  387. MemTotal: 1016088 kB
  388. ```
  389. i.e. approximately ~ 1016 MB.
  390. 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.
  391. The web server didn't have Swap partition or Swap file. This can be found out by
  392. - 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)
  393. - Or, for example:
  394. ```
  395. [newuser@goauldhost: ~ ]$ cat /etc/fstab
  396. LABEL=cloudimg-rootfs / ext4 defaults 0 0
  397. LABEL=UEFI /boot/efi vfat defaults 0 0
  398. [newuser@goauldhost: ~ ]$ sudo fdisk -l
  399. [sudo] password for newuser:
  400. Disk /dev/vda: 25 GiB, 26843545600 bytes, 52428800 sectors
  401. Units: sectors of 1 * 512 = 512 bytes
  402. Sector size (logical/physical): 512 bytes / 512 bytes
  403. I/O size (minimum/optimal): 512 bytes / 512 bytes
  404. Disklabel type: gpt
  405. Disk identifier: 39DFE5D0-C8FB-44D8-93F8-EBB37A54BDF8
  406. Device Start End Sectors Size Type
  407. /dev/vda1 227328 52428766 52201439 24.9G Linux filesystem
  408. /dev/vda14 2048 10239 8192 4M BIOS boot
  409. /dev/vda15 10240 227327 217088 106M Microsoft basic data
  410. ```
  411. 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 file '/proc/sys/vm/swappiness' in DigitalOcean virtual servers).
  412. ------------------------------------------------
  413. **I/O statistics**
  414. ![sar-iostat](https://raw.githubusercontent.com/Fincer-altego/basics-of-a-linux-server-school-course-/master/sar-iostats.png)
  415. Main command: iostat -dmtx 20
  416. -d Display the device utilization report.
  417. -m Display statistics in megabytes per second.
  418. -t Print the time for each report displayed.
  419. -x Display extended statistics.
  420. 20 20 sec interval.
  421. | Field | Description |
  422. |--------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
  423. | Device | Device or partition defined in system directory '/dev'. |
  424. | rrqm/s | The number of read requests merged per second that were queued to the device. |
  425. | wrqm/s | The percentage of write requests merged together before being sent to the device. |
  426. | r/s | The number (after merges) of read requests completed per second for the device. |
  427. | w/s | The number (after merges) of write requests completed per second for the device. |
  428. | rMB/s | The number of sectors (KB, MB) read from the device per second. |
  429. | wMB/s | The number of sectors (KB, MB) write from the device per second. |
  430. | avgrq-sz (areq-sz) | The average size (in kilobytes) of the I/O requests,that were issued to the device. |
  431. | avgqu-sz (aqu-sz) | The average queue length of the requests that were issued to the device. |
  432. | 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. |
  433. | 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. |
  434. | 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. |
  435. | 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. |
  436. | %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. |
  437. **NOTE!** Descriptions are provided in sysstat package (manpages).
  438. **ANALYSIS - I/O STATISTICS**
  439. 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.
  440. ------------------------------------------------
  441. 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.
  442. **e)** (optional) Change sshd (SSH server process) port
  443. --------------
  444. **Answer:**
  445. Let the following shell script do the job...
  446. ```
  447. #!/bin/bash
  448. # SSH server daemon configuration file in the system
  449. SSH_CONFIG=/etc/ssh/sshd_config
  450. # New SSH server daemon input port as user input value.
  451. NEW_SSH_PORT=$1
  452. [[ -f $SSH_CONFIG ]] \
  453. && sed -i "s/.*Port.*/Port $NEW_SSH_PORT/" $SSH_CONFIG && echo "SSH server: new port $NEW_SSH_PORT is set." \
  454. || echo "SSH server configuration file could not be found!"
  455. if [[ $(cat $SSH_CONFIG | grep -i port | awk '{print $2}') == $NEW_SSH_PORT ]]; then
  456. echo -e "SSH server input port has been changed to $NEW_SSH_PORT.\n \
  457. Restarting SSH server daemon in order to apply the changes (root required)."
  458. sudo systemctl restart sshd.service
  459. if [[ $? == 0 ]]; then
  460. echo "SSH server daemon restarted, new input port is $NEW_SSH_PORT."
  461. else
  462. echo "Something went wrong while restarting SSH server daemon. Execute 'systemctl status sshd.service' \
  463. to get more information about the problem."
  464. fi
  465. fi
  466. ```
  467. Save the above script code in file '$HOME/ssh-port.sh', for example. Change the port with command 'bash $HOME/ssh-port.sh 4312' where the number value is your new SSH port (4312 in this case).
  468. ------------------------------------------------
  469. **EXTRA - Using new port address of SSH server daemon when connecting with a client computer/program**
  470. 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:
  471. ```
  472. [19/02/2018 23:23:49 - fincer: ~ ]$ ssh newuser@174.138.2.190 -p <new-port-number>
  473. ```
  474. ------------------------------------------------
  475. **EXTRA - detecting SSH port change with port scanning techniques (nmap)**
  476. 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.
  477. Port scanning:
  478. ```
  479. nmap -sS -F -v -O 174.138.2.190
  480. ```
  481. 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!):
  482. ```
  483. phelenius@my-machine:~$ sudo nmap -sS -p 1234 -O -v 174.138.2.190
  484. Starting Nmap 7.01 ( https://nmap.org ) at 2018-02-19 20:02 EET
  485. Initiating Ping Scan at 20:02
  486. Scanning 174.138.2.190 [4 ports]
  487. Completed Ping Scan at 19:59, 0.20s elapsed (1 total hosts)
  488. Initiating Parallel DNS resolution of 1 host. at 20:02
  489. Completed Parallel DNS resolution of 1 host. at 20:02, 0.01s elapsed
  490. Initiating SYN Stealth Scan at 20:02
  491. Scanning 174.138.2.190 [1 port]
  492. Completed SYN Stealth Scan at 20:02, 0.20s elapsed (1 total ports)
  493. Initiating OS detection (try #1) against 174.138.2.190
  494. adjust_timeouts2: packet supposedly had rtt of -125997 microseconds. Ignoring time.
  495. adjust_timeouts2: packet supposedly had rtt of -125997 microseconds. Ignoring time.
  496. Retrying OS detection (try #2) against 174.138.2.190
  497. adjust_timeouts2: packet supposedly had rtt of -150518 microseconds. Ignoring time.
  498. adjust_timeouts2: packet supposedly had rtt of -150518 microseconds. Ignoring time.
  499. WARNING: OS didn't match until try #2
  500. Nmap scan report for 174.138.2.190
  501. Host is up (0.00041s latency).
  502. PORT STATE SERVICE
  503. 1234/tcp open unknown
  504. Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
  505. Device type: switch|general purpose|media device
  506. Running: Cisco CatOS 7.X|8.X, HP Tru64 UNIX 5.X, Vantage embedded
  507. 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
  508. 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
  509. Read data files from: /usr/bin/../share/nmap
  510. OS detection performed. Please report any incorrect results at https://nmap.org/submit/ .
  511. Nmap done: 1 IP address (1 host up) scanned in 3.39 seconds
  512. Raw packets sent: 44 (6.312KB) | Rcvd: 18 (1.820KB)
  513. ```
  514. 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):
  515. ```
  516. PORT STATE SERVICE
  517. 22/tcp filtered ssh
  518. ```
  519. Corresponding log entries of targeted SSH server during the nmap scanning (/var/log/auth.log):
  520. ```
  521. Feb 19 18:02:46 goauldhost sshd[30057]: Connection from XXX.XXX.XXX.XXX port 6967 on 174.138.2.190 port 1234
  522. Feb 19 18:02:46 goauldhost sshd[30057]: Did not receive identification string from XXX.XXX.XXX.XXX
  523. Feb 19 18:02:46 goauldhost sshd[30058]: Connection from XXX.XXX.XXX.XXX port 52205 on 174.138.2.190 port 1234
  524. Feb 19 18:02:46 goauldhost sshd[30058]: Did not receive identification string from XXX.XXX.XXX.XXX
  525. Feb 19 18:02:47 goauldhost sshd[30059]: Connection from XXX.XXX.XXX.XXX port 25326 on 174.138.2.190 port 1234
  526. Feb 19 18:02:47 goauldhost sshd[30059]: Did not receive identification string from XXX.XXX.XXX.XXX
  527. Feb 19 18:02:47 goauldhost sshd[30060]: Connection from XXX.XXX.XXX.XXX port 32812 on 174.138.2.190 port 1234
  528. Feb 19 18:02:47 goauldhost sshd[30060]: Did not receive identification string from XXX.XXX.XXX.XXX
  529. Feb 19 18:02:47 goauldhost sshd[30061]: Connection from XXX.XXX.XXX.XXX port 17024 on 174.138.2.190 port 1234
  530. Feb 19 18:02:47 goauldhost sshd[30061]: Did not receive identification string from XXX.XXX.XXX.XXX
  531. Feb 19 18:02:47 goauldhost sshd[30062]: Connection from XXX.XXX.XXX.XXX port 53268 on 174.138.2.190 port 1234
  532. Feb 19 18:02:47 goauldhost sshd[30062]: Did not receive identification string from XXX.XXX.XXX.XXX
  533. Feb 19 18:02:47 goauldhost sshd[30063]: Connection from XXX.XXX.XXX.XXX port 34923 on 174.138.2.190 port 1234
  534. Feb 19 18:02:47 goauldhost sshd[30063]: Did not receive identification string from XXX.XXX.XXX.XXX
  535. Feb 19 18:02:47 goauldhost sshd[30064]: Connection from XXX.XXX.XXX.XXX port 14489 on 174.138.2.190 port 1234
  536. Feb 19 18:02:47 goauldhost sshd[30064]: Did not receive identification string from XXX.XXX.XXX.XXX
  537. Feb 19 18:02:47 goauldhost sshd[30065]: Connection from XXX.XXX.XXX.XXX port 40086 on 174.138.2.190 port 1234
  538. Feb 19 18:02:47 goauldhost sshd[30065]: Did not receive identification string from XXX.XXX.XXX.XXX
  539. Feb 19 18:02:47 goauldhost sshd[30066]: Connection from XXX.XXX.XXX.XXX port 38147 on 174.138.2.190 port 1234
  540. Feb 19 18:02:47 goauldhost sshd[30066]: Did not receive identification string from XXX.XXX.XXX.XXX
  541. Feb 19 18:02:48 goauldhost sshd[30067]: Connection from XXX.XXX.XXX.XXX port 49215 on 174.138.2.190 port 1234
  542. Feb 19 18:02:48 goauldhost sshd[30067]: Did not receive identification string from XXX.XXX.XXX.XXX
  543. Feb 19 18:02:48 goauldhost sshd[30068]: Connection from XXX.XXX.XXX.XXX port 34445 on 174.138.2.190 port 1234
  544. Feb 19 18:02:48 goauldhost sshd[30068]: Did not receive identification string from XXX.XXX.XXX.XXX
  545. Feb 19 18:02:48 goauldhost sshd[30069]: Connection from XXX.XXX.XXX.XXX port 4600 on 174.138.2.190 port 1234
  546. Feb 19 18:02:48 goauldhost sshd[30069]: Did not receive identification string from XXX.XXX.XXX.XXX
  547. Feb 19 18:02:48 goauldhost sshd[30070]: Connection from XXX.XXX.XXX.XXX port 59405 on 174.138.2.190 port 1234
  548. Feb 19 18:02:48 goauldhost sshd[30070]: Did not receive identification string from XXX.XXX.XXX.XXX
  549. Feb 19 18:02:48 goauldhost sshd[30071]: Connection from XXX.XXX.XXX.XXX port 7848 on 174.138.2.190 port 1234
  550. Feb 19 18:02:48 goauldhost sshd[30071]: Did not receive identification string from XXX.XXX.XXX.XXX
  551. Feb 19 18:02:49 goauldhost sshd[30072]: Connection from XXX.XXX.XXX.XXX port 5206 on 174.138.2.190 port 1234
  552. Feb 19 18:02:49 goauldhost sshd[30072]: Did not receive identification string from XXX.XXX.XXX.XXX
  553. Feb 19 18:02:50 goauldhost sshd[30073]: Connection from XXX.XXX.XXX.XXX port 5517 on 174.138.2.190 port 1234
  554. Feb 19 18:02:50 goauldhost sshd[30073]: Did not receive identification string from XXX.XXX.XXX.XXX
  555. Feb 19 18:02:50 goauldhost sshd[30074]: Connection from XXX.XXX.XXX.XXX port 3970 on 174.138.2.190 port 1234
  556. Feb 19 18:02:50 goauldhost sshd[30074]: Did not receive identification string from XXX.XXX.XXX.XXX
  557. Feb 19 18:02:50 goauldhost sshd[30075]: Connection from XXX.XXX.XXX.XXX port 38690 on 174.138.2.190 port 1234
  558. Feb 19 18:02:50 goauldhost sshd[30075]: Did not receive identification string from XXX.XXX.XXX.XXX
  559. Feb 19 18:02:50 goauldhost sshd[30076]: Connection from XXX.XXX.XXX.XXX port 50572 on 174.138.2.190 port 1234
  560. Feb 19 18:02:50 goauldhost sshd[30076]: Did not receive identification string from XXX.XXX.XXX.XXX
  561. Feb 19 18:02:50 goauldhost sshd[30077]: Connection from XXX.XXX.XXX.XXX port 27830 on 174.138.2.190 port 1234
  562. Feb 19 18:02:50 goauldhost sshd[30077]: Did not receive identification string from XXX.XXX.XXX.XXX
  563. Feb 19 18:02:50 goauldhost sshd[30078]: Connection from XXX.XXX.XXX.XXX port 49371 on 174.138.2.190 port 1234
  564. Feb 19 18:02:50 goauldhost sshd[30078]: Did not receive identification string from XXX.XXX.XXX.XXX
  565. Feb 19 18:02:51 goauldhost sshd[30079]: Connection from XXX.XXX.XXX.XXX port 36802 on 174.138.2.190 port 1234
  566. Feb 19 18:02:51 goauldhost sshd[30079]: Did not receive identification string from XXX.XXX.XXX.XXX
  567. Feb 19 18:02:51 goauldhost sshd[30080]: Connection from XXX.XXX.XXX.XXX port 50546 on 174.138.2.190 port 1234
  568. Feb 19 18:02:51 goauldhost sshd[30080]: Did not receive identification string from XXX.XXX.XXX.XXX
  569. Feb 19 18:02:51 goauldhost sshd[30081]: Connection from XXX.XXX.XXX.XXX port 43542 on 174.138.2.190 port 1234
  570. Feb 19 18:02:51 goauldhost sshd[30081]: Did not receive identification string from XXX.XXX.XXX.XXX
  571. Feb 19 18:02:51 goauldhost sshd[30082]: Connection from XXX.XXX.XXX.XXX port 56108 on 174.138.2.190 port 1234
  572. Feb 19 18:02:51 goauldhost sshd[30082]: Did not receive identification string from XXX.XXX.XXX.XXX
  573. Feb 19 18:02:51 goauldhost sshd[30083]: Connection from XXX.XXX.XXX.XXX port 6399 on 174.138.2.190 port 1234
  574. Feb 19 18:02:51 goauldhost sshd[30083]: Did not receive identification string from XXX.XXX.XXX.XXX
  575. Feb 19 18:02:51 goauldhost sshd[30084]: Connection from XXX.XXX.XXX.XXX port 55980 on 174.138.2.190 port 1234
  576. Feb 19 18:02:51 goauldhost sshd[30084]: Did not receive identification string from XXX.XXX.XXX.XXX
  577. Feb 19 18:02:51 goauldhost sshd[30085]: Connection from XXX.XXX.XXX.XXX port 12713 on 174.138.2.190 port 1234
  578. Feb 19 18:02:51 goauldhost sshd[30085]: Did not receive identification string from XXX.XXX.XXX.XXX
  579. Feb 19 18:02:51 goauldhost sshd[30086]: Connection from XXX.XXX.XXX.XXX port 5026 on 174.138.2.190 port 1234
  580. Feb 19 18:02:51 goauldhost sshd[30086]: Did not receive identification string from XXX.XXX.XXX.XXX
  581. ```
  582. 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).
  583. 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.
  584. Another 'nmap' command shows us the following:
  585. ```
  586. phelenius@my-machine:~$ sudo nmap 174.138.2.190 -sV
  587. Starting Nmap 7.01 ( https://nmap.org ) at 2018-02-20 14:50 EET
  588. Nmap scan report for 174.138.2.190
  589. Host is up (0.33s latency).
  590. Not shown: 998 filtered ports
  591. PORT STATE SERVICE VERSION
  592. 1234/tcp open ssh OpenSSH 7.6 (protocol 2.0)
  593. 80/tcp open http
  594. ...
  595. ```
  596. ... 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 example:
  597. ```
  598. ...
  599. PORT STATE SERVICE VERSION
  600. 22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu2.4 (Ubuntu Linux; protocol 2.0)
  601. ...
  602. ```
  603. 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'
  604. **NOTE!** Port scanning does not leave any log traces behind in Apache's access.log file ('/var/log/apache/access.log')!
  605. Check also
  606. - [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)
  607. - [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)
  608. - [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)
  609. - [GitHub - metacloud/openssh - Include the Debian version in our identification](https://github.com/metacloud/openssh/blob/master/debian/patches/package-versioning.patch)
  610. ------------------------------------------------
  611. **EXTRA - Using Port Knocking technique against port scanning**
  612. 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.
  613. **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).
  614. [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):
  615. 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 example, 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.
  616. 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.
  617. [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):
  618. 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.
  619. More about Port Knocking technique:
  620. - [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)
  621. - [OpenWRT:n sivut](https://wiki.openwrt.org/doc/howto/portknock.server)
  622. - [portknocking.org](http://www.portknocking.org/) and practical solutions on [Implementations sub-page](http://www.portknocking.org/view/implementations)
  623. - [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)
  624. **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 example). For SSH which does not require 24/7 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.**
  625. ------------------------------------------------
  626. **EXTRA - ARP Scan and spoofing your MAC address**
  627. 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.
  628. 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-altego/basics-of-a-linux-server-school-course-/blob/master/spoof_mac_address.sh).
  629. Sample results of ARP Scan.
  630. BEFORE:
  631. ```
  632. [20/02/2018 18:52:35 - fincer: ~ ]$ sudo arp-scan --interface=wlan0 --localnet
  633. [sudo] password for fincer:
  634. Interface: wlan0, datalink type: EN10MB (Ethernet)
  635. Starting arp-scan 1.9 with 256 hosts (http://www.nta-monitor.com/tools/arp-scan/)
  636. A.B.C.D f4:0e:22:ad:b8:7d (Unknown)
  637. 1.2.3.4 18:a9:05:4b:61:58 Hewlett-Packard Company
  638. ```
  639. AFTER - IP-osoitteessa 1.2.3.4 olevan palvelinkoneen MAC-osoite muutettu:
  640. ```
  641. [20/02/2018 18:54:28 - fincer: ~ ]$ sudo arp-scan --interface=wlan0 --localnet
  642. Interface: wlan0, datalink type: EN10MB (Ethernet)
  643. Starting arp-scan 1.9 with 256 hosts (http://www.nta-monitor.com/tools/arp-scan/)
  644. A.B.C.D f4:0e:22:ad:b8:7d (Unknown)
  645. 1.2.3.4 aa:0c:9a:fa:7b:d4 (Unknown)
  646. ```
  647. 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:
  648. ```
  649. Warning: Permanently added the ECDSA host key for IP address '[1.2.3.4]:22' to the list of known hosts.
  650. ```
  651. **f)** (optional) Allow SSH login only for users in group 'sshers'. Add your account to this group.
  652. --------------
  653. **Answer:**
  654. 1. Log in to the server computer ('ssh username@server-ip -p <ssh-port>')
  655. 2. Add group 'sshers' with GID number 876 (you don't have to define GID here)
  656. ```
  657. sudo groupadd -g 876 sshers
  658. ```
  659. 3. You can confirm existence of the created group with command 'grep sshers /etc/group'. Output:
  660. ```
  661. sshers:x:876:
  662. ```
  663. 4. Add the current user (read: yourself) _newuser_ into this group
  664. ```
  665. sudo usermod -aG sshers newuser
  666. ```
  667. 5. Command 'grep sshers /etc/group' output now:
  668. ```
  669. sshers:x:876:newuser
  670. ```
  671. You can alternatively check groups of _newuser_ by executing command 'groups' while being that user:
  672. ```
  673. [27/02/2018 10:39:58 - newuser@goauldhost: ~ ]$ groups
  674. sshers newuser sudo
  675. ```
  676. or using command 'sudo -u newuser groups" as any system user who can execute commands with sudo.
  677. **NOTE!** _groups_ -komento antaa oikean stdout:n (outputin) vasta uudelleenkirjautumisen jälkeen.
  678. command 'groups' gives correct output only after re-login.
  679. 6. Allow SSH login only to members of the group 'sshers'.
  680. Manual page of 'sshd_config' ('man sshd_config') describes 'AllowGroups' option as follows:
  681. > AllowGroups
  682. > 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.
  683. Let's apply the following information into SSH server daemon configuration file '/etc/ssh/sshd_config':
  684. ```
  685. PermitRootLogin no
  686. AllowGroups sshers
  687. ```
  688. And comment out the following lines (be careful here!):
  689. ```
  690. # DenyUsers <kayttajatunnuksia>
  691. # AllowUsers <kayttajatunnuksia>
  692. # DenyGroups <ryhmatunnuksia>
  693. ```
  694. If those lines are not defined in the configuration file, it is OK.
  695. You can add multiple groups and users after those keywords, as you like.
  696. 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:
  697. ```
  698. IgnoreRhosts yes
  699. PermitEmptyPasswords no
  700. ChallengeResponseAuthentication yes
  701. UsePAM yes
  702. MaxAuthTries 3
  703. ```
  704. etc. More options and configurations can be found with commands 'man sshd_config' and 'man sshd'
  705. 7. Let's save this configuration and restart SSH server daemon by applying command 'sudo systemctl restart sshd.service' (NOTE! Disconnects already-established SSH connections!)
  706. 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>'
  707. **g)** (optional) Attach a remote network directory with sshfs.
  708. --------------
  709. **Answer:**
  710. 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.
  711. 1. Install 'sshfs' with command sequence 'sudo apt-get update && sudo apt-get -y install sshfs' on a Debian-based Linux system.
  712. 2. Mount remote folder '/home/newuser/public_html/' (server), to path '/home/<current-user>/public_html_ssh_remote' on your client computer.
  713. ```
  714. mkdir $HOME/public_html_ssh_remote && sshfs newuser@174.138.2.190:./public_html $HOME/public_html_ssh_remote -p <ssh-portti>
  715. ```
  716. **NOTE!** If you use public key SSH authentication method, you are not asked for any password.
  717. 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:
  718. ```
  719. index.html
  720. ```
  721. Additionally, check output of command 'mount | grep public_html_ssh_remote':
  722. ```
  723. 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)
  724. ```
  725. 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'.