Configured a baseline installation of Amazon Lightsail Linux Server To host Web Applications. secured the server from a number of attack, installed and configured a database server, and deploy one of my existing web applications onto it.
IP ADDRESS : 13.232.118.216
SSH PORT: 2200
URL : http://13.232.118.216.xip.io/
Grader's SSH KEY LOCATION: /home/grader/.ssh
Login command for Grader : ssh [email protected] -i ~/.ssh/graderKeyPair -p 2200
- Log in to Lightsail
- Create an instance
- First, choose "OS Only" (rather than "Apps + OS"). Second, choose Ubuntu as the operating system.
- Choose your instance plan
- Give your instance a hostname
- Wait for it to start up
- Once your instance has started up, you can log into it with
Connect using SSh
public IP
address of the instance is displayed along with itsUser name
- Download
private key
of SSH KEY PAIR. - save this .pem file to
~/.ssh
directory
- Use these commands to SSH into your server from your console
ssh [email protected] -i ~/.ssh/LightsailDefaultPrivateKey.pem
- Use these commands to update installed packages
sudo apt-get update sudo apt-get upgrade
- If *** System restart required *** is displayed at login, run:
sudo reboot
-
Firstly, Open port 2200 in
Lightsail > Networkind > Firewall
to avoid locking yourself out by adding:Application Protocol Port range Custom TCP 2200
-
Open
/etc/ssh/sshd_config
file using :sudo nano /etc/ssh/sshd_config
-
Change the line
Port 22
toPort 2200
-
Then restart the SSH service:
sudo service ssh restart
-
New command to login to the server:
ssh [email protected] -i ~/.ssh/LightsailDefaultPrivateKey.pem -p 2200
Allow incoming connections for SSH (port 2200), HTTP (port 80), and NTP (port 123)
- Check UFW status
sudo ufw status
- Block all incoming connections on all ports
sudo ufw default deny incoming
- Allow outgoing connection on all ports
sudo ufw default allow outgoing
- Allow incoming connection for SSH on port 2200
sudo ufw allow 2200/tcp
- Allow incoming connections for HTTP on port 80
sudo ufw allow www
- Allow incoming connection for NTP on port 123
sudo ufw allow ntp
- check the rules that have been added before enabling the firewall
sudo ufw show added
- enable the firewall
sudo ufw enable
- Check UFW status again
sudo ufw status
Giving grader
access to log in to my server for reviewing my project.
- Create user
grader
sudo adduser grader
- If you are signed in using a non-root user with sudo privileges, type
sudo visudo
- Search for the line that looks like this:
root ALL=(ALL:ALL) ALL
- Below this line, copy the format you see here, changing only the word
"root" to reference the new user that you would like to give sudo privileges to:
root ALL=(ALL:ALL) ALL newuser ALL=(ALL:ALL) ALL
- Sign In to user
grader
sudo su - grader
- Sign Out of user
grader
exit
Enable Key Based Authentication
-
Generate SSH Key Pairs locally on your system using application
ssh-keygen
, type:ssh-keygen
-
Enter file in which to save the key (/home/user/ .ssh/id_rsa):
/home/user/.ssh/graderKeyPair
-
Two Files will be created inside
~/.ssh/
i.egraderKeyPair
graderKeyPair.pub
-
Place the Public Key on our remote server so that SSH can use it to log in
-
make .ssh dir inside
/home/grader/
sudo mkdir /home/grader/.ssh
-
create
authorized_keys
file inside/home/grader/.ssh
sudo touch /home/grader/.ssh/authorized_keys
this is a special file will store all the public keys this account is allowed to use for authentication.
-
Copy the contents of
/home/user/.ssh/graderKeyPair.pub
from the local machine -
open
authorized_keys
file inside/home/grader/.ssh
sudo nano /home/grader/.ssh/authorized_keys
-
paste Copied Content into
/home/grader/.ssh/authorized_keys
file
-
-
Set permission of
.ssh
&authorized_keys
so that other user can not gain access to your accountsudo chmod 700 /home/grader/.ssh sudo chmod 644 /home/grader/.ssh/authorized_keys
-
Changer ownership of
.ssh
&authorized_keys
grader so that grader can gain access to these filesudo chmod 700 /home/grader/.ssh sudo chmod 644 /home/grader/.ssh/authorized_keys
- Check the timezone
date
- If it's not UTC change it to UTC using:
sudo timedatectl set-timezone UTC
-
Install Apache:
sudo apt-get install apache2
-
Install the
libapache2-mod-wsgi
package:sudo apt-get install libapache2-mod-wsgi
It configure Apache to hand-off certain requests to an application handler - mod_wsgi
- If project is built using
Python 3
use this instead:sudo apt-get install libapache2-mod-wsgi-py3
- If project is built using
-
configure Apache to handle requests using the WSGI module by editing
/etc/apache2/sites-enabled/000-default.conf
file.- open
/etc/apache2/sites-enabled/000-default.conf
filesudo nano /etc/apache2/sites-enabled/000-default.conf
- add the following line at the end of the
<VirtualHost *:80>
block, right before the closing</VirtualHost>
line:WSGIScriptAlias / /var/www/html/myapp.py
- Finally, restart Apache
sudo apache2ctl restart
-
To test if you have your Apache configuration correct you can write a very basic WSGI application :
WSGI is a specification that describes how a web server communicates with web applications. Most Python web frameworks are WSGI compliant including Flask and Django. Despite having the extension .wsgi, these are just Python applications
- defined the name of the file you need to write within your Apache configuration by using the
WSGIScriptAlias
directivewhich is already done in above stepWSGIScriptAlias /test_wsgi /var/www/html/test_wsgi.py
- Create the /var/www/html/myapp.wsgi file using the command :
sudo nano /var/www/html/test_wsgi.py
- Within this file, write the following application:
def application(environ, start_response): status = '200 OK' output = 'Hello World From WSGI!' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output]
- Finally, restart Apache
sudo apache2ctl restart
- If everything goes as expected, open your favorite web browser and type the URL
http://your-server-ip/test_wsgi
and hitEnter
, You will get the newly created application:
- defined the name of the file you need to write within your Apache configuration by using the
- open
- Install PostgreSQL with:
sudo apt-get install postgresql postgresql-contrib
-
Do not allow remote connections
A simple way to remove a potential attack vector is to not allow remote connections to the database. This is the current default when installing PostgreSQL from the Ubuntu repositories.
-
Open the postgres config file
sudo nano /etc/postgresql/9.5/main/pg_hba.conf
-
double check that no remote connections are allowed by looking in the host based authentication file:
-
As you can see, the first two security lines specify "local" as the scope that they apply to. This means they are using Unix/Linux domain sockets.
-
The second two declarations are remote, but if we look at the hosts that they apply to (127.0.0.1/32 and ::1/128), we see that these are interfaces that specify the local machine.
-
-
Create a new database user named
catalog
that has limited permissions to your catalog application database.-
Create a linux user named
catalog
sudo adduser catalog
-
Create a PostgreSQL user(role) called
catalog
with:sudo -u postgres createuser -P catalog
you are
Prompted
for a password(-P). This creates a normal user that can't create databases, roles (users). -
create the database
catalog
withcatalog
as owner.sudo -u postgres createdb -O catalog catalog
-
-
To Check If Databse and User Created Successfully:
- Log into PostgreSQL using:
sudo su - postgres psql
- List all the current Owners(Role) and their attributes by typing:
\du
- Login to Owner(Role)
catalog
by typing UNIX command:psql -h localhost -U user_name -p <port>
- If you don't know the port, you can always get it by running the following, as the postgres user,
SHOW port;
- Show all databases having
catalog
as owner:\l
- Select Database
catalog
:\c catalog
- Show all tables within
catalog
database:\c dt
- Log out PostgreSQL to follow along with this section:
sudo su - postgres psql
- Log into PostgreSQL using:
-
- Install git using command:
sudo apt-get install git
STEP 13 : Clone and setup your Catalog project from the Github repository you created earlier in this Nanodegree program
- Clone the Repository
- Go to the www dirrectory and create a directory catalog:
cd /var/www/
sudo mkdir catalog
cd catalog
- use git clone to download Catalog Project & rename it to catalog
sudo git clone https://github.com/shubhamPrakashJha/Cricket-Player-Info.git
sudo mkdir catalog
sudo mv Cricket-Player-Info/* catalog
sudo rm -r Cricket-Player-Info/
cd catalog/
- Go to the www dirrectory and create a directory catalog:
- Setup the Repository
- change
application.py
toinit.py
sudo mv application.py __init__.py
- Edit engine in
init.py
,database_setup.py
andlotsofplayerswithuser.py
- use
$ sudo nano
on each of the mentioned files, and find the line.engine = create_engine('sqlite:///teamplayerwithuser.db')
- and replace them with
engine = create_engine('postgresql://catalog:grader@localhost/catalog')
password
is not shown for security reasons. - use
- Modify init.py so Google+ login works.
- Open
__init__.py
sudo nano /var/www/catalog/catalog/__init__.py
- find any reference to
client_secrets.json
and replace it with its full path name/var/www/catalog/catalog/client_secrets.json
- find the line
app.debug = True
and delete it.
- Open
- Update the Google OAuth
client_secrets
file- go to your Google Console
- select your project
- Select
API & Services
>credentials
- Select Your project Client ID
- In
Authorized JavaScript origins
add followingurl
http://13.232.118.216 http://13.232.118.216.xip.io
- In
Authorized redirect URIs
add:http://13.232.118.216.xip.io/login http://13.232.118.216.xip.io/gconnect
- Click
Save
- Click on
DOWNLOAD JSON
to download updatedclient_secret
file - Replace the content of old
client_secret
file with the content of downloadedclient_secret
file.
- change
STEP 14 : Set it up in your server so that it functions correctly when visiting your server’s IP address in a browser. Make sure that your .git
directory is not publicly accessible via a browser!
-
Install packages: Flask and SQLAlchemy using following command:
sudo apt-get install python-psycopg2 python-flask sudo apt-get install python-sqlalchemy python-pip sudo pip install oauth2client sudo pip install requests sudo pip install httplib2 sudo pip install flask-seasurf
-
create your database
python database_setup.py python lotsofplayerswithuser.py
-
Create .wsgi file
cd /var/www/catalog sudo nano catalog.wsgi
and paste the following
#!/usr/bin/python import sys import logging logging.basicConfig(stream=sys.stderr) sys.path.insert(0,"/var/www/catalog/") from catalog import app as application application.secret_key = 'some_secret'
-
Create a Virtual Host
To serve the catalog app using the Apache2 web server, you need to create a virtual host configuration file.
sudo nano /etc/apache2/sites-available/catalog.conf
and paste the following
<VirtualHost *:80> ServerName 13.232.118.216 ServerAdmin [email protected] WSGIScriptAlias / /var/www/catalog/catalog.wsgi <Directory /var/www/catalog/catalog/> Order allow,deny Allow from all </Directory> Alias /static /var/www/catalog/catalog/static <Directory /var/www/catalog/catalog/static/> Order allow,deny Allow from all </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>
-
Disable the default virtual host
sudo a2dissite 000-default.conf
-
Enable the virtual host just created
sudo a2ensite catalog.conf
-
To make these changes live restart Apache2
sudo service apache2 restart
-
Make .git file inaccessable
sudo nano .htaccess
add line
RedirectMatch 404 /\.git
-
To Disable root login
- oprn
/etc/ssh/sshd_config
:
sudo nano /etc/ssh/sshd_config
- Replace
PermitRootLogin without-password
to :
PermitRootLogin no
- uncomment the following line
PasswordAuthentication no
- Restart SSH Service
sudo service ssh restart
- oprn
-
Default public network ports open for specific instance images
-
How To Create, Remove, & Manage Tables in PostgreSQL on a Cloud Server
-
How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu 14.04
-
How To Install Linux, Nginx, MySQL, PHP (LEMP) stack on Ubuntu 14.04
-
How To Use Roles and Manage Grant Permissions in PostgreSQL on a VPS