LAMP and WordPress with HTTPS Certification Cloud Installation on Ubuntu - NETSEC

Latest

Learning, Sharing, Creating

Cybersecurity Memo

Saturday, September 30, 2017

LAMP and WordPress with HTTPS Certification Cloud Installation on Ubuntu

I have selected Ubuntu as OS platform to install my php, wordpress and mysql. It gave me lots of learning experience on Linux. Here is many steps I recorded during working on my 51sec.org blog site.

For Windows: WAMP and Wordpress Install on AWS Free Tier Windows 2012 R2
For Ubuntu: LAMP and WordPress Installation on Ubuntu

1. Basic Ubuntu Configuration (Not in Cloud)
1.1 Configure Interfaces

Welcome to Ubuntu 15.10 (GNU/Linux 4.2.0-16-generic x86_64)

 * Documentation:  https://help.ubuntu.com/

48 packages can be updated.
37 updates are security updates.

Last login: Sat Feb 13 20:16:03 2016 from 192.168.2.62
john@ubuntu15:~$ cd /etc/network
john@ubuntu15:/etc/network$ sudo vi interfaces
[sudo] password for john: 

# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface -- use DHCP 
auto eth0

iface eth0 inet dhcp

# The secondart network interface -- use static ip address
auto ens160
iface ens160 inet static
address 192.168.2.22
netmask 255.255.255.0
gateway 192.168.2.1
dns-nameserver 8.8.8.8
~

~
john@ubuntu15:/etc/network$sudo /etc/init.d/networking restart


1.2. System Software Update

sudo apt-get update        # Fetches the list of available updates
sudo apt-get upgrade       # Strictly upgrades the current packages
sudo apt-get dist-upgrade  # Installs updates (new ones)


#Following commands are not necessage. You can run them after intalled apache later. 

sudo nano /etc/apache2/apache2.conf   #add a single line "ServerName server_domain_or_IP "to the biottom of  /etc/apache2/apache2.conf file to suppress a warning message. 

sudo apache2ctl configtest
sudo systemctl restart apache2

Check Firewall to make sure allow inbound traffic for 80 and 443

ubuntu@ip-10-10-0-60:~$ sudo ufw app list
sudo: unable to resolve host ip-10-10-0-60
Available applications:
  Apache
  Apache Full
  Apache Secure
  OpenSSH
ubuntu@ip-10-10-0-60:~$ sudo ufw app info "Apache Full"
sudo: unable to resolve host ip-10-10-0-60
Profile: Apache Full
Title: Web Server (HTTP,HTTPS)
Description: Apache v2 is the next generation of the omnipresent Apache web
server.

Ports:
  80,443/tcp
ubuntu@ip-10-10-0-60:~$ sudo ufw allow in "Apache Full"
sudo: unable to resolve host ip-10-10-0-60
Rules updated
Rules updated (v6)
ubuntu@ip-10-10-0-60:~$ sudo ufw app info "Apache Full"
sudo: unable to resolve host ip-10-10-0-60
Profile: Apache Full
Title: Web Server (HTTP,HTTPS)
Description: Apache v2 is the next generation of the omnipresent Apache web
server.

Ports:

  80,443/tcp



john@ubuntu15:/etc/network$ cat /etc/*-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=15.10
DISTRIB_CODENAME=wily
DISTRIB_DESCRIPTION="Ubuntu 15.10"
NAME="Ubuntu"
VERSION="15.10 (Wily Werewolf)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 15.10"
VERSION_ID="15.10"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"
john@ubuntu15:/etc/network$ 

john@ubuntu15:/etc/network$ uname -a

Linux ubuntu15 4.2.0-16-generic #19-Ubuntu SMP Thu Oct 8 15:35:06 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux


2. Launch Instance in the AWS cloud 

Please check my previous post :

Rather than launch a 'Amazon Linux 2017.03.1 (HVM), SSD Volume Type Instance', you will need to launch 'Ubuntu Server 16.04 LTS (HVM), SSD Volume Type' AMI. 

Note: At different region, AMI has different name. It is not same AMI name for all regions. 


After logged into Ubuntu instance with username ubuntu and your private key, you will need to enter following commands to update your Ubuntu. Of course before that, you will set up your VPC, Subnets,  internet gateway, default route, security group and public IP (EIP) properly. 
sudo apt-get update        # Fetches the list of available updates
sudo apt-get upgrade       # Strictly upgrades the current packages
sudo apt-get dist-upgrade  # Installs updates (new ones)

3. Install LAMP

3.1. Install Apache

To install Apache you must install the Metapackage apache2. This can be done by searching for and installing in the Software Centre, or by running the following command.

sudo apt-get install apache2

3.2. Install MySQL (Optional for local MySql Server)
To install MySQL you must install the Metapackage mysql-server. This can be done by searching for and installing in the Software Centre, or by running the following command.
sudo apt-get install mysql-server
sudo mysql_install_db
sudo mysql_secure_installation


3.3. Install PHP

To install PHP you must install the Metapackages php5 and libapache2-mod-php5. This can be done by searching for and installing in the Software Centre, or by running the following command.
sudo apt-get install php libapache2-mod-php php-mcrypt php-mysql


3.4. Restart Server
Your server should restart Apache automatically after the installation of both MySQL and PHP. If it doesn't, execute this command.
sudo /etc/init.d/apache2 restart

3.5. Check Apache

Open a web browser and navigate tohttp://localhost/. You should see a message saying It works!

3.6. Check PHP

You can check your PHP by executing any PHP file from within /var/www/. Alternatively you can execute the following command, which will make PHP run the code without the need for creating a file .
john@ubuntu15:/etc/network$ php -r 'echo "\n\nYour PHP installation is working fine.\n\n\n";'

Your PHP installation is working fine.


ubuntu@ip-10-10-0-60:~$php -i

ubuntu@ip-10-10-0-60:~$sudo nano /var/www/html/info.php
<?php
phpinfo();
?>

Open you browser to open page: http://your_server_IP_address/info.php


4. Install Phpmyadmin (Optional)

$ sudo apt-get install phpmyadmin

follow configuration wizard to finish the configuration, such as choosing :
  • apache2 for your web server
  • yes for Configure database for phpmyadmin with dbconfig-common?
  • MySQL application password for phpmyadmin:
  • password for root user Password of the database's administrative user:  


5. Install Wordpress
5.1 Install
cd ~
wget http://wordpress.org/latest.tar.gz
tar xzvf latest.tar.gz
sudo apt-get update
sudo apt-get install php5-gd libssh2-php


5.2 Configure
ubuntu@ip-10-10-0-60:~$ cd ~/wordpress
ubuntu@ip-10-10-0-60:~/wordpress$ cp wp-config-sample.php wp-config.php
ubuntu@ip-10-10-0-60:~/wordpress$ curl -s https://api.wordpress.org/secret-key/1.1/salt/
define('AUTH_KEY',         '/c|BO/-!OU8+unm:*{r.iZD/7.Ayge],.Unawgno^!%(=p@#U7fdW#3Q<hcq<&/e');
define('SECURE_AUTH_KEY',  '5d;:+VIC&Lh6-F>IoYk6eQag=n,;/KB9^589o|Ou)_N-_yb;Bo7$t,}?Uc 4rtgO');
define('LOGGED_IN_KEY',    '=/lVrQ?h6yt(yYi9VS=1kZehJ67z4o]bg{dO-jIXl*r8h~3qeUd9BK6!3|#@;.!2');
define('NONCE_KEY',        'HuHK`7HwsW7|jvAXY(AXWFYcWmbvW2-xwNw[HXM0nu?4P.GATiYXZhLsAiaqoF<N');
define('AUTH_SALT',        '!qV`*1GT;dRH-Zf6Ylwa*I]]|Y/seeoHqc*-:N11xi.!<d8X|<bA`4ot-2oJrmNO');
define('SECURE_AUTH_SALT', '+TgB6l[^8LgLp65);+PtT2DYideMa>UD=SJZ2jD`Aaqz_dR1E@2r>;i:X1JLU{`g');
define('LOGGED_IN_SALT',   'R`~Rhkuzz}v|OM|<$JSjkBd,~y/fsePw[q6:hH>GR{u``I/pmRa_]BkG%g(@K36x');
define('NONCE_SALT',       'C305sfDZGO5~J3XLDp|QLw2]4QYZ1B/#UM[pC6Lt+tvkBi]9pl-k^]e6Cw$,DM1(');
ubuntu@ip-10-10-0-60:~/wordpress$ 
ubuntu@ip-10-10-0-60:~/wordpress$ nano wp-config.php


Replace same section with above outputs in wp-config.php file.
5.3 Connect database
Change :
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'wordpress');

/** MySQL database username */
define('DB_USER', 'wordpressuser');

/** MySQL database password */
define('DB_PASSWORD', 'password');


5.4 Copy Files to /var/www/html and Change Permission

This step will help you to set up right permission on the files and folder under /var/www/html. Else  you will get a ftp credential prompt when you try to do updates or install a plugin

Wordpress Update FTP Error
.
sudo rsync -avP ~/wordpress/ /var/www/html/
cd /var/www/html

sudo chown -R ubuntu:www-data *
mkdir /var/www/html/wp-content/uploads
sudo chown -R :www-data /var/www/html/wp-content/uploads

Or:
cd /var/www/html
sudo chown www-data:www-data * -R 
sudo usermod -a -G www-data www-data


or:
sudo chown -R www-data:www-data /var/www
sudo find /var/www/ -type d -exec chmod 755 {} \;
sudo find /var/www/ -type f -exec chmod 644 {} \;





The other change we need to make is to set the method that WordPress should use to write to the file system. Since we've given the web server permission to write where it needs to, we can explicitly set the file system method to "direct". Failure to set this with our current settings would result in WordPress prompting for FTP credentials when we perform some actions. This setting can be added below the database connection settings, or anywhere else in the file:
/var/www/html/wp-config.php
. . .

define('DB_NAME', 'WP_DB');

/** MySQL database username */
define('DB_USER', 'WP_USER');

/** MySQL database password */
define('DB_PASSWORD', 'P@ssw0rd');

. . .

define('FS_METHOD', 'direct');
Save and close the file when you are finished.

5.5 Web Interface Installation

You will need to change default apache2 index.html file name.

johnyan_ca@wp-php:/var/www/html$ mv index.html apache.html
 

Use your browser to open http://your_server_IP_address/. You should get a wordpress wizard page. If you are still getting a Apache page, you may want to remove the file index.html under /var/www/html. That will make index.php become the first file to launch at site http://your_server_IP_address/.

Follow the wordpress wizard, you enter your site information. After complete it, your site is up and running.

6. Allow Remote Wordpress Connection to Mysql (Option)
6.1 Change MySql bind interface:

ubuntu@ip-10-1-1-50:/etc/mysql/mysql.conf.d$ netstat -ntlp | grep 3306
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      -               
ubuntu@ip-10-1-1-50:/etc/mysql/mysql.conf.d$ sudo vi mysqld.cnf
.....
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
# bind-address          = 127.0.0.1
bind-address            = 0.0.0.0
#
.....

ubuntu@ip-10-1-1-50:/etc/mysql/mysql.conf.d$ sudo /etc/init.d/mysql restart
sudo: unable to resolve host ip-10-1-1-50
Restarting mysql (via systemctl): mysql.service.
ubuntu@ip-10-1-1-50:/etc/mysql/mysql.conf.d$ netstat -ntlp | grep 3306
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      -   

6.2 Allow a new user with remote machine name or public ip to access Mysql DB

ubuntu@ip-10-1-1-50:/etc/mysql/mysql.conf.d$ sudo mysql -u root -p mysql
sudo: unable to resolve host ip-10-1-1-50
Enter password: 
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 74
Server version: 5.7.19-0ubuntu0.16.04.1 (Ubuntu)

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.


mysql> create user 'remotewordpressuser'@'ec2-34-215-22-243.us-west-2.compute.amazonaws.com' identified by '1234567890';
ERROR 1396 (HY000): Operation CREATE USER failed for 'remoteuser'@'ec2-34-215-22-243.us-west-2.compute.amazonaws.com'


mysql> GRANT ALL ON *.* to remoteordpressuser@'ec2-34-215-22-243.us-west-2.compute.amazonaws.com' identified by '1234567890';
Query OK, 0 rows affected, 1 warning (0.00 sec)


mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)

mysql> exit
Bye
ubuntu@ip-10-1-1-50:/etc/mysql/mysql.conf.d$ 







[root@ip-10-10-0-50 html]# mysql -h 50.40.50.80 -u remotewordpressuser -p
Enter password: 
ERROR 1130 (HY000): Host 'ec2-34-215-22-243.us-west-2.compute.amazonaws.com' is not allowed to connect to this MySQL server
[root@ip-10-10-0-50 html]# 
[root@ip-10-10-0-50 html]# mysql -h 50.40.50.80 -u remotewordpressuser -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 82
Server version: 5.7.19-0ubuntu0.16.04.1 (Ubuntu)

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 


[root@ip-10-10-0-50 html]# cp wp-config.php wp-config.php.old
[root@ip-10-10-0-50 html]# vi wp-config.php

<?php
/**
 * The base configuration for WordPress
 *
 * The wp-config.php creation script uses this file during the
 * installation. You don't have to use the web site, you can
 * copy this file to "wp-config.php" and fill in the values.
 *
 * This file contains the following configurations:
 *
 * * MySQL settings
 * * Secret keys
 * * Database table prefix
 * * ABSPATH
 *
 * @link https://codex.wordpress.org/Editing_wp-config.php
 *
 * @package WordPress
 */

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'wordpress');

/** MySQL database username */
define('DB_USER', 'remotewordpressuser');

/** MySQL database password */
define('DB_PASSWORD', '1234567890');

/** MySQL hostname */
define('DB_HOST', '50.40.50.80');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8mb4');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');

/**#@+






Note:
a. Stop Mysql service and Disable it Auto Run when rebooted

ubuntu@ip-10-10-0-55:/var/log/apache2$ vmstat -s
      1014648 K total memory
       310308 K used memory
       390732 K active memory
       143836 K inactive memory
       414364 K free memory
        15576 K buffer memory
       274400 K swap cache
            0 K total swap
            0 K used swap
            0 K free swap
          675 non-nice user cpu ticks
            0 nice user cpu ticks
          608 system cpu ticks
       157804 idle cpu ticks
         1517 IO-wait cpu ticks
            0 IRQ cpu ticks
           15 softirq cpu ticks
          527 stolen cpu ticks
       205823 pages paged in
        23372 pages paged out
            0 pages swapped in
            0 pages swapped out
        97824 interrupts
       160060 CPU context switches
   1506783521 boot time
         1623 forks
ubuntu@ip-10-10-0-55:/var/log/apache2$ sudo service mysql stop
sudo: unable to resolve host ip-10-10-0-55
ubuntu@ip-10-10-0-55:/var/log/apache2$ vmstat -s
      1014648 K total memory
       154184 K used memory
       235852 K active memory
       132412 K inactive memory
       581604 K free memory
        15648 K buffer memory
       263212 K swap cache
            0 K total swap
            0 K used swap
            0 K free swap
          696 non-nice user cpu ticks
            0 nice user cpu ticks
          612 system cpu ticks
       167728 idle cpu ticks
         1523 IO-wait cpu ticks
            0 IRQ cpu ticks
           15 softirq cpu ticks
          528 stolen cpu ticks
       207123 pages paged in
        23868 pages paged out
            0 pages swapped in
            0 pages swapped out
       101681 interrupts
       167164 CPU context switches
   1506783521 boot time
         1657 forks
ubuntu@ip-10-10-0-55:/var/log/apache2$ sudo nano /etc/init/mysql.conf
sudo: unable to resolve host ip-10-10-0-55

  GNU nano 2.5.3                                                     File: /etc/init/mysql.conf                                                                                                                

description     "MySQL 5.7 Server"
author          "Mario Limonciello <[email protected]>"

#start on runlevel [2345]
stop on starting rc RUNLEVEL=[016]

respawn
respawn limit 2 5

env HOME=/etc/mysql
umask 007

# The default of 5 seconds is too low for mysql which needs to flush buffers
kill timeout 300


b. Stop Apache2 Service and Disable it Auto Run when rebooted
  1. systemctl command – Only works on systemd based Ubuntu like version 16.04 LTS and above.
  2. /etc/init.d/apache2 – A sys v init style script to start / stop / restart the Apache2 service under Debian or Ubuntu Linux.
  3. service command – This command work in most Linux distributions including Debian and Ubuntu.
  4. upstart command – Only works on certain version of Ubuntu.
  5. apache2ctl command – This method should work on all Linux and Unix likeoperating systems.
$ lsb_release -a
$ sudo systemctl stop apache2.service
$ sudo systemctl status apache2.service



$ sudo apt-get install rcconf
$ sudo rcconf


7. Install free https certificate 
https://letsencrypt.org/ provides free ssl/tls certificate for popular application platform using Certbot ACME client to simplify the whole process.


$ sudo apt-get update
$ sudo apt-get install software-properties-common
$ sudo add-apt-repository ppa:certbot/certbot
$ sudo apt-get update
$ sudo apt-get install python-certbot-apache 





$ sudo certbot --apache

$ sudo certbot renew --dry-run

Note 1. It may need to run it a couple of times to get a new certificate installed. If dry-run appears to be working correctly, you can arrange for automatic renewal by adding a cron or systemd job to run 'certbot renew' automatically.

Note 2. If you are having multiple servers running for one domain, when you trying to use certbot to enable https for your apache, it may fail because of name resolution not matching your public ip. In that case, you will need delete you other public ip's A record from your DNS provider to make sure your public ip is match DNS name resolution.


8. Troubleshooting 

8.1 Wordpress PermaLinks Issue

I met this issue when installed a new Ubuntu and wordpress. Here is the solution I found from this post:

There can be multiple things preventing the rewrite rule from working. My ubuntu server needed 3 things changed to get permalinks working.
In newer versions of apache2, you need to enable the module:
sudo a2enmod rewrite
sudo service apache2 restart
You may also need to modify the apache2.conf file.
sudo nano /etc/apache2/apache2.conf
Change your web directory override rule to AllowOverride All.
<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>
After that, restart the service again.
The .htaccess file in the WordPress install directory needs to be owned or readable/modifiable by the webserver.
This can be accomplished by changing owner to www-data (usually the webserver user), or changing permissions.
sudo chown www-data /var/www/wordpress-install/.htaccess 
OR
sudo chmod 664 /var/www/wordpress-install/.htaccess
Login to your Wordpress admin backend and save the permalink settings, and they should hopefully be working.


Reference:




No comments:

Post a Comment