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.

507 lines
22 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. Linux servers - Exercice 7
  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)** Solve a previously published final major test of this school course (You can find them with DuckDuckGo or Google).
  7. --------------
  8. **Answer:**
  9. Let's pick up our previous major test [ict4tn021-1 autumn 2016](http://terokarvinen.com/2016/arvioitava-laboratorioharjoitus-%e2%80%93-linux-palvelimet-ict4tn021-1-uusi-ops-alkusyksylla-2016).
  10. ----------------------------
  11. **Initial set-up for remote control of a server**
  12. _Prepare to control the server from abroad. Secure the server with firewall_
  13. We shall install SSH server daemon to the targeted server computer. It is assumed that local or other direct access to the server command line is available since SSH server daemon is not yet installed, thus preventing direct, remote SSH control of the server.
  14. Once having access to the server command line, we shall test that the computer can reach the internet. Test the following commands:
  15. ```
  16. ifconfig
  17. ping www.duckduckgo.com
  18. ip -br link show
  19. ```
  20. Command explanations:
  21. - [ifconfig](https://www.linux.fi/wiki/Ifconfig) = Has IP address determined to a network interface on the server?
  22. - [ping](https://fi.wikipedia.org/wiki/Ping) = Does a site respond to ICMP requests?
  23. - ip = Is the network interface, which should have connection to the internet, up and active (UP)?
  24. When the internet connection is established, we shall proceed by installing the following packages, assuming that the server uses a Debian-based Linux distribution: openssh-server, openssh-sftp-server, openssh-client
  25. On some distributions, those packages can be installed simply issuing:
  26. ```
  27. sudo apt-get update
  28. sudo apt-get -y install ssh
  29. ```
  30. We shall confirm that the SSH server daemon starts during the server boot-up. We shall also confirm that the SSH server daemon is up and running and its status is 'active':
  31. ```
  32. sudo systemctl enable ssh.service
  33. systemctl status ssh.service
  34. ```
  35. **NOTE!** Alternative commands can also be used, like:
  36. ```
  37. sudo systemctl enable sshd
  38. systemctl is-active sshd
  39. ```
  40. etc.
  41. Has our firewall program installed on the system?
  42. ```
  43. which ufw
  44. which iptables
  45. ```
  46. If both of those executable files ('ufw' and 'iptables') are found on the system, we shall accept network traffic to port 22, protocol TCP (INPUT 22/TCP). Let's apply these rules to our firewall:
  47. ```
  48. sudo ufw allow 22/tcp
  49. ```
  50. Make sure our firewall program 'ufw' (Uncomplicated Firewall) is enabled and turned on:
  51. ```
  52. sudo ufw enable
  53. sudo systemctl enable ufw.service
  54. ```
  55. **NOTE!** By default, Linux firewall blocks all input traffic. Therefore, SSH input traffic must separately be allowed like described above.
  56. ----------------------------
  57. **Security set-up for a company**
  58. _Install remotely working security tools for our company. (In this assignment, you can assume that installing a package or packages from our repository is secure)_
  59. The following commands have been pre-determined in the assignment:
  60. - download .deb installer file with 'wget' command
  61. - install the downloaded .deb package with command 'sudo dpkg -i' which extract a new repository file 'terorep.list' into '/etc/apt/sources.list.d/')
  62. - update package databases with command 'sudo apt-get update'
  63. - install package 'terowatch' which is made available by the new repository. The package is available for Ubuntu distribution, version 16.04 LTS. The repository file itself contains string 'deb http://terokarvinen.com/qrs/terorep/ precise main'
  64. **NOTE!** 'terowatch' package uses network interface 'eth0' by default. However, we haven't defined such interface in our system configuration (this can be fixed by adding 'net.ifnames=0' in udev rules/kernel boot parameters in syslinux or grub). Instead, we use network interface 'enp4s0'.
  65. Proper fix to this issue would be patching the code and applying the patch into the deb package. Another solution would be making the proper fix directly to the source code. In this assignment, we directly modify the executable file, written in Python. This method is not recommended but for the extent of this assignment, it is sufficient solution to proceed.
  66. ```
  67. dpkg -L terowatch
  68. sudo sed -i 's/eth0/enp4s0/g' /usr/bin/qrsc
  69. ```
  70. Command _terowatch_ gives desired text output “TeroWatch is installed” (the string is defined in shell executable '/usr/bin/terowatch')
  71. ----------------------------
  72. **Statistics**
  73. _Collect workload statistics of various system resources (CPU, RAM) while doing the assignment. The data collection must be started before proceeding in the assignment. Write a short analysis of the collected statistics after you've finished other parts of the assignment._
  74. We shall install 'sysstat':
  75. ```
  76. sudo apt-get update && sudo apt-get -y install sysstat
  77. ```
  78. Let's run 'sar' command in 2 second interval for undefined time period. Print output of the command to file '$HOME/sysstat.file'
  79. ```
  80. sar 2 -o $HOME/sysstat.file
  81. ```
  82. The file can be analyzed afterwards with 'sar' command in the end of the assignment.
  83. ![sysstat_cpu-mem](https://github.com/Fincer/linux_server_setup/blob/master/images/sar_stats_cpu-ram.png)
  84. Short analysis, based on the picture above:
  85. - CPU (command: 'sar 10 -f $HOME/sysstat.file'): CPU has been in moderate workload. User processes have not depleted resources that much, in contrast to system processes which stress the CPU many times more. 'iowait' value tells us that the processor has waited for mass memory device. During the data collection, some data was transferred from a hard disk to another. CPU capacity limits were not reached.
  86. - Mem/RAM (command: 'sar -r 10 -f $HOME/sysstat.file'): Memory consumption has been significant during the data collection period ('%memused' and '%commit'). The system has 4GB DDR3 memory of which majority has been in use. Amount of free memory has been 100MB. Two main operations have affected the memory usage level: web browser usage and file transfer/copy operations which were performed during the data collection period. Active memory was used 2,5GB on average, passive (inactive) memory usage was 700MB. Amount of memory which has waited for to be written varies between 5MB-200MB ('kbdirty').
  87. ----------------------------
  88. **PHP from remote countries**
  89. _Install us necessary tools for remote PHP website development._
  90. - SSH server daemon has already been installed, port 22 is opened -> OK
  91. - We shall install HTTP daemon (Apache web server) and open the default port 80 for it in our firewall. Additionally, we shall install necessary PHP (7.0) packages:
  92. ```
  93. sudo apt-get update && sudo apt-get -y install apache2 php7.0 libapache2-mod-php7.0 && sudo ufw allow 80/tcp
  94. ```
  95. Let's enable Apache server daemon, check the status of it (must be 'active') and tell the system that Apache should automatically be started during the server boot-up:
  96. ```
  97. systemctl status apache2.service
  98. sudo systemctl enable apache2.service
  99. ```
  100. Let's check that the port 80 is opened in our firewall:
  101. ```
  102. xubuntu@xubuntu:/home$ sudo ufw status
  103. Status: active
  104. To Action From
  105. -- ------ ----
  106. 22/tcp ALLOW Anywhere
  107. 80/tcp ALLOW Anywhere
  108. 22/tcp (v6) ALLOW Anywhere (v6)
  109. 80/tcp (v6) ALLOW Anywhere (v6)
  110. ```
  111. (you don't need to execute command 'sudo systemctl start apache2.service' after the Apache installation because the Apache web server daemon is automatically enabled during the server boot-up by default. This information can be found with command 'systemctl status apache2.service')
  112. We shall enable Apache's PHP module while using module 'userdir'. This can be done by commenting the lines between <IfModule mod_userdir.c> tags in file '/etc/apache2/mods-available/php7.0.conf'. Right after we should enable Apache's 'userdir' module and restart the Apache web server:
  113. ```
  114. sudo a2enmod userdir
  115. sudo systemctl restart apache2.service
  116. ```
  117. Let's check that Apache web server is still up and running by issuing command 'systemctl status apache2.service'. Let's check that we can access our default localhost website (IP address 127.0.0.1) which indicates whether the Apache server works as intended:
  118. ```
  119. xdg-open http://localhost
  120. ```
  121. 'xdg-open' command definition:
  122. ```
  123. [12/03/2018 22:31:11 - fincer: ~ ]$ whatis xdg-open
  124. xdg-open (1) - opens a file or URL in the user's preferred application
  125. ```
  126. We must check that we can access our website from a remote network. In a test laboratory, this test would be done checking output of command 'ifconfig', looking for a relevant IP address and login to the server from another computer using the grabbed IP address and SSH client program (command syntax using default SSH port 22 would be: 'ssh server-user@server-ip'). In order to access the server from a remote network, the relevant IP address for connecting the server must be known, and confirmation for succeeded remote access must exist. Any router & NAT/PAT configurations between a client and the server must work.
  127. _Our users are as follows: Maija Mehilälinen, Peter Ö, Oskar Jäärä, John Do, Verner Vrij, Mikko Möttönen, Jalmari Ähkä, Håkan Swarz and Maija Maitoparta. Create a sample website for each user with PHP._
  128. _List all user accounts and passwords in file lab.txt (“/home/*/lab.txt”). Protect the file so that other users can not read it._
  129. We shall generate all required passwords (9 for users + admin) with 'pwgen'. Password length is 20 characters, randomized, at least one uppercase character included and secure parameter for the command is used:
  130. ```
  131. sudo apt-get update && sudo apt-get install pwgen
  132. pwgen 20 10 -sc1
  133. ```
  134. We shall store additional admin password into a separate, secure place (of your choice). Admin account (or user) username is 'admin'.
  135. We haven't created admin user 'admin' yet. Let's do it. We shall also grant 'sudo' group permissions to this new administration user:
  136. ```
  137. sudo adduser admin
  138. sudo usermod -aG sudo admin
  139. su admin
  140. ```
  141. The last command 'su admin' switched our shell view to the user's 'admin' shell. We should lock the server root account by issuing command 'sudo usermod --lock root' (which adds an exclamation mark right before root's password in file '/etc/shadow'). We could increase system's overall security by blocking usage of various TTY sessions (commenting out lines in file '/etc/securetty') and by adding more restrictions to the system's PAM policy.
  142. For securing our SSH connections, we shall add the following line in '/etc/ssh/sshd_config' file (use 'sudoedit' or 'sudo nano' command):
  143. ```
  144. PermitRootLogin no
  145. ```
  146. After having altered '/etc/ssh/sshd_config', restart SSH server daemon by issuing command
  147. ```
  148. sudo systemctl restart sshd
  149. ```
  150. Create file $HOME/lab.txt (where $HOME=/home/admin) with the following contents:
  151. ```
  152. mmehilal RWjM8r2fyq8gQq3wnzq0 # Maija Mehilälinen
  153. po a5B60cmTyrwPLS2mJ9uQ # Peter Ö
  154. ojaara P1KkLl0XaV5JpqntxdJG # Oskar Jäärä
  155. jdo ZgMb5TrU4Ee3bT48eCff # John Do
  156. vvrij RWjM8r2fyq8gQq3wnzq0 # Verner Vrij
  157. mmottone GpuyZqp2pGsmPINJPO1h # Mikko Möttönen
  158. jahka nFTellIyRjwiC0YKtPwq # Jalmari Ähkä
  159. hswarz u5qfJCC2jZMGQPWwPZLV # Håkan Swarz
  160. mmaitopa OCeBmKYWWgFIXubdFc6j # Maija Maitoparta
  161. ```
  162. Restrict permissions for this file by issuing the following command (as user 'admin'):
  163. ```
  164. chmod og-rwx,u-x $HOME/lab.txt
  165. ```
  166. Output:
  167. ```
  168. admin@xubuntu:~$ ls -l lab.txt
  169. -rw------- 1 admin admin 407 Mar 12 11:42 lab.txt
  170. ```
  171. Let's create a generic, pretty simple PHP file 'index.php' into the home directory of the user 'admin', and as the user 'admin'.
  172. ```
  173. nano /home/admin/index.php
  174. ```
  175. Add the following contents:
  176. ```
  177. <?php
  178. phpinfo();
  179. ?>
  180. ```
  181. **NOTE!** Make sure you have enabled php & userdir modules on Apache at this point!
  182. After that, we shall copy the PHP file for each user into a user-specific subdirectory 'public_html' ('/home/*/public_html').
  183. The user-specific directory 'public_html' and contents of it should have correct permissions set up for each user.
  184. On Debian-based Linux distributions, a perl script '[adduser](https://alioth.debian.org/plugins/scmgit/cgi-bin/gitweb.cgi?p=adduser/adduser.git;a=tree)' is provided for creating new users. Let's do the following:
  185. - 1) Create required user accounts with the generated passwords
  186. - 2) Copy the pre-created index.php file into each user's $HOME/public_html folder
  187. - 3) For each user, test that their index.php is showing expected and correct output
  188. Run the following with any system user who belongs to the 'sudo' group:
  189. ```
  190. sudo apt-get update && sudo apt-get -y install curl && \
  191. for user in mmehilal po ojaara jdo vvrij mmottone jahka hswarz mmaitopa; do echo -e "User is: $user\n" && sudo adduser $user && sudo mkdir -p /home/$user/public_html/ && sudo cp /home/admin/index.php /home/$user/public_html/ && sudo chown -R $user:$user /home/$user && [[ $(curl -s http://localhost/~${user}/index.php | grep -i "404 not found" | wc -l) -ne 0 ]] && echo -e "\nPHP test site not found for '${user}'\n" || echo -e "\nPHP test site is OK for user\n"; done
  192. ```
  193. **NOTE!** To test site on a graphical web browser, you need to keep in mind that user 'xubuntu' is the only user having access to graphical display on X server right now (see '.Xauthority' and environment variable DISPLAY for details). Thus, the following commands should be used in our current setup:
  194. ```
  195. sudo passwd xubuntu
  196. su xubuntu
  197. for user in mmehilal po ojaara jdo vvrij mmottone jahka hswarz mmaitopa; do xdg-open http://localhost/~${user}; done
  198. ```
  199. **NOTE!** We can exit the shell view of the user 'admin' simply issuing command 'exit' on that shell view.
  200. **NOTE!** Consider the following in a production environment, instead of doing nasty things with administration users:
  201. - You can (but don't have to) modify the current user, grant administration rights, modify username, home directory and groups ('usermod' command) instead of adding a separate account for an administrator
  202. - You can create a new main/admin user and remove an old one (in our case, we should delete 'xubuntu' account). You can delete users with command 'userdel'.
  203. - You can have clearly restricted and well named groups to separate users with various permissions on a system. Apply your user and group policy so that specific users belong to the right groups.
  204. - Check usage of various environment variables in your shell view
  205. Screenshot of user-specific PHP sites on the configured server environment:
  206. ![apache-php-multiple](https://github.com/Fincer/linux_server_setup/blob/master/images/apache_phpinfo_multiple.png)
  207. Checking permissions for each index.php files & public_html directories:
  208. ```
  209. for user in mmehilal po ojaara jdo vvrij mmottone jahka hswarz mmaitopa; do ls -lR /home/$user | sed '/total [0-9]/d'; done
  210. ```
  211. Output:
  212. ```
  213. /home/mmehilal:
  214. drwxr-xr-x 2 mmehilal mmehilal 60 Mar 12 11:50 public_html
  215. /home/mmehilal/public_html:
  216. -rw-r--r-- 1 mmehilal mmehilal 20 Mar 12 12:00 index.php
  217. /home/po:
  218. drwxr-xr-x 2 po po 60 Mar 12 12:00 public_html
  219. /home/po/public_html:
  220. -rw-r--r-- 1 po po 20 Mar 12 12:00 index.php
  221. /home/ojaara:
  222. drwxr-xr-x 2 ojaara ojaara 60 Mar 12 12:01 public_html
  223. /home/ojaara/public_html:
  224. -rw-r--r-- 1 ojaara ojaara 20 Mar 12 12:01 index.php
  225. /home/jdo:
  226. drwxr-xr-x 2 jdo jdo 60 Mar 12 12:01 public_html
  227. /home/jdo/public_html:
  228. -rw-r--r-- 1 jdo jdo 20 Mar 12 12:01 index.php
  229. /home/vvrij:
  230. drwxr-xr-x 2 vvrij vvrij 60 Mar 12 12:01 public_html
  231. /home/vvrij/public_html:
  232. -rw-r--r-- 1 vvrij vvrij 20 Mar 12 12:01 index.php
  233. /home/mmottone:
  234. drwxr-xr-x 2 mmottone mmottone 60 Mar 12 12:01 public_html
  235. /home/mmottone/public_html:
  236. -rw-r--r-- 1 mmottone mmottone 20 Mar 12 12:01 index.php
  237. /home/jahka:
  238. drwxr-xr-x 2 jahka jahka 60 Mar 12 12:02 public_html
  239. /home/jahka/public_html:
  240. -rw-r--r-- 1 jahka jahka 20 Mar 12 12:02 index.php
  241. /home/hswarz:
  242. drwxr-xr-x 2 hswarz hswarz 60 Mar 12 12:02 public_html
  243. /home/hswarz/public_html:
  244. -rw-r--r-- 1 hswarz hswarz 20 Mar 12 12:02 index.php
  245. /home/mmaitopa:
  246. drwxr-xr-x 2 mmaitopa mmaitopa 60 Mar 12 12:02 public_html
  247. /home/mmaitopa/public_html:
  248. -rw-r--r-- 1 mmaitopa mmaitopa 20 Mar 12 12:02 index.php
  249. ```
  250. ----------------------------
  251. **iot12tools**
  252. _Install and configure metapackage 'iot12tools' for us. The metapackage should install the following development tools for 'Internet of Things': arduino IDE, gedit (text editor), gedit-plugins, curl (CLI browser) and Python 3 programming language._
  253. Run the following commands as the user 'admin':
  254. ```
  255. sudo apt-get update && sudo apt-get -y install equivs
  256. mkdir ~/iot12tools
  257. cd ~/iot12tools
  258. equivs-control iot12tools
  259. ```
  260. Edit contents of file 'io12tools' to look like the following:
  261. ```
  262. ### Commented entries have reasonable defaults.
  263. ### Uncomment to edit them.
  264. Section: misc
  265. Priority: optional
  266. Standards-Version: 3.9.2
  267. Package: iot12tools
  268. Version: 0.1
  269. Maintainer: Pekka Helenius <fincer89@hotmail.com>
  270. Depends: arduino, gedit, gedit-plugins, curl, python3
  271. Architecture: all
  272. Description: A meta package which provides basic IoT development tools
  273. Installs Gedit text editor, Gedit plugins, Arduino IDE and Python 3
  274. ```
  275. Run the following command in directory '~/iot12tools':
  276. ```
  277. equivs-build iot12tools
  278. ```
  279. Install the generated metapackage (which installs required packages for us):
  280. ```
  281. sudo apt install -f ./iot12tools_0.1_all.deb
  282. ```
  283. ----------------------------
  284. **Hello Python 3**
  285. _Jalmari want to develop in Python 3. Create a simple Python 3 file in his home root directory. The file should print output 'Hello World'._
  286. Install necessary python3 packages as the user 'admin':
  287. ```
  288. sudo apt-get update && sudo apt-get install -y python3
  289. ```
  290. Switch your shell view to user 'jahka' (Jalmari Ähkä) and go to his home directory:
  291. ```
  292. su jahka
  293. cd
  294. ```
  295. **NOTE!** We can make sure that we are in his home directory ('/home/jahka') by issuing command 'pwd'.
  296. Let's create a new file '~/helloworld.py' with the following contents:
  297. ```
  298. #!/usr/bin/env python3
  299. print("Hello World");
  300. ```
  301. Modify file permissions, grant executable permission for the user 'jahka', remove from others (including the group who owns the file):
  302. ```
  303. chmod u+x,og-x helloworld.py
  304. ```
  305. The file permissions are now:
  306. ```
  307. -rwxrw-r-- 1 jahka jahka 47 Mar 12 12:59 helloworld.py
  308. ```
  309. Test the code:
  310. ```
  311. jahka@xubuntu:~$ python3 ~/helloworld.py
  312. Hello World
  313. ```
  314. The output is as desired, 'Hello World', indicating that we have successfully installed Python3 development environment for the required user.
  315. **c)** (optional) Use Linux outside the course scope.
  316. --------------
  317. **Answer:**
  318. The following pictures demonstrate [Arch Linux ARM](https://archlinuxarm.org/platforms/armv6/raspberry-pi) running on my Raspberry Pi 1 Model B. The solution is quite rushed but it works technically:
  319. ![rpi1b_archlinux-1](https://github.com/Fincer/linux_server_setup/blob/master/images/rpi1b_archlinux_1.jpg)
  320. ![rpi1b_archlinux-2](https://github.com/Fincer/linux_server_setup/blob/master/images/rpi1b_archlinux_2.jpg)
  321. - Display: [Lilliput 869GL](http://www.lilliputuk.com/monitors/hdmi/869gl/)
  322. - SDHC card: Transcend 16GB
  323. - HDD: 750GB in [Icy Box IB-3640SU3](http://www.raidsonic.de/products/external_cases/external_cases_35/index_en.php?we_objectID=480) hard disk external case.
  324. - Desktop environment: LxQt
  325. About my Linux usage:
  326. My first touch to Linux world was back in early spring, 2011. The first Linux distribution I installed was Ubuntu 10.04 LTS, and after that I have tried out many distributions, including Linux Mint, Fedora, OpenSUSE and Arch Linux.
  327. The first computer I ever had a Linux installation was [Asus Eee PC 1215N](https://www.asus.com/Laptops/Eee_PC_1215N/) mini laptop. My primary operating system on that laptop was [EasyPeasy](https://sourceforge.net/projects/ubuntu-eee/), a variant of Ubuntu 10.04 LTS which uses Gnome 2 desktop environment and additional customization package 'ubuntu-netbook-launcher' (known as [Linux Netbook Remix](https://en.wikipedia.org/wiki/Ubuntu_Netbook_Edition)), predecessor of Canonical's Unity desktop.
  328. After the Asus Eee PC 1215N broke, I moved to [Asus N56JR laptop](https://www.asus.com/Laptops/N56JR/) for which I installed Linux Mint with Cinnamon desktop environment at first. Soon after I moved to Arch Linux where I used Cinnamon desktop for a short while, as well. I moved quickly from Cinnamon to KDE desktop because I Cinnamon desktop had mysterious and unacceptable freeze events on my personal use.
  329. Why did I choose KDE desktop over multiple alternatives, such as XFCE, LXDE, Mate, Gnome 3, Budgie, Pantheon or LxQt? I consider several things when choosing a desktop environment: stability, long-term development history, suitability for efficient multitasking and configuration possibilities (source code + GUI + conf files). I have been happy Arch Linux + KDE desktop user for many years - and I still am. Of course, I have tested various other desktop environments but always returned to KDE.
  330. In general, I have multiple Linux distributions, MS Windows 7 and Android on Virtual Machines for various purposes.
  331. More or less, I have participated in various open source project and done Windows software testing on Wine. I like to create scripts for daily usage, mainly to automate routine-like, boring tasks and processes. One of my key interests have been in digital image processing and raw image analysis, for which both Linux suits very well, offering a solid, adaptable and cost-effective platform. I set up my first LAMP server several years back from now on my Raspberry Pi 1 Model B.