Securing database with command line linux
Author: Mohanad Aly
Group : Cyber Security Engineering (C11)
Page Created: 18 February 2016
Last modified: 02 June 2016
Aim of this page
- Control the Command Line environment.
- What database mean ?
- Database Threats.
- Securing Database using the command line method.
General Information about command line
- Before starting there is a short course of command line in code academy website Code Academy
- After finishing the command line exercises, user need to remember a few useful commands.
cdthe command that make the user navigate everywhere in the command line environment.
pwdthe command that always make user know his location in the system.
- User need this command
whoamito know he is the root user or not.
sudo -sswitch ordinary user to the root user that control everything in the system.
apt-get updateAlways update repositories and useful before install anything.
apt-get installAfter user become super user, user will need this command to install packages.
apt-get UpgradeFor upgrading the system.
nanoNano always good for beginners, easy to edit or write file in command line.
lsWhich user already know from the code academy, it's for listing all the files and folder in the directory.
What database mean ?
A database is an organized collection of data. It is the collection of schemas, tables, queries, reports, views and other objects. The data are typically organized to model aspects of reality in a way that supports processes requiring information, such as modelling the availability of rooms in hotels in a way that supports finding a hotel with vacancies.
An attacker can target and compromise a database server in a number of ways by exploiting a variety of configuration and application level vulnerabilities. 
The main threats to a database server are:
- SQL injection
- Network eavesdropping
- Unauthorized server access
- Password cracking
- With a SQL injection attack, the attacker exploits vulnerabilities in the application's input validation and data access code to run arbitrary commands in the database using the security context of the Web application.
- Vulnerabilities exploited by SQL injection include:
- Poor input validation in the Web applications
- Unsafe, dynamically constructed SQL commands
- Over-privileged application logins to the database
- Weak permissions that fail to restrict the application's login to the database
- To counter SQL injection attacks:
- The application should constrain and sanitize input data before using it in SQL queries.
- Use type safe SQL parameters for data access. These can be used with stored procedures or dynamically constructed SQL command strings. *Using SQL parameters ensures that input data is subject to type and length checks and also that injected code is treated as literal *data, not as executable statements in the database.
- Use a SQL Server login that has restricted permissions in the database. Ideally, user should grant execute permissions only to selected *stored procedures in the database and provide no direct table access.
- The deployment architecture of most applications includes a physical separation of the data access code from the database server. As a result, sensitive data, such as application-specific data or database login credentials, must be protected from network eavesdroppers.
Vulnerabilities Vulnerabilities that increase the likelihood of network eavesdropping include:
- Insecure communication channels
Passing credentials in clear text to the database for example
- Using SQL authentication instead of Windows authentication
- Using SQL authentication without a server certificate
Countermeasures To counter network eavesdropping:
- Use Windows authentication to connect to the database server to avoid sending credentials over the network.
- Install a server certificate on the database server. This results in the automatic encryption of SQL credentials over the network.
- Use an SSL connection between the Web server and database server to protect sensitive application data. This requires a database server certificate.
- Use an IPSec encrypted channel between Web and database server.
Unauthorized Server Access
Direct access to user database server should be restricted to specific client computers to prevent unauthorized server access.
Vulnerabilities Vulnerabilities that make the database server susceptible to unauthorized server access include:
- Failure to block the SQL Server port at the perimeter firewall
- Lack of IPSec or TCP/IP filtering policies
Attacks Direct connection attacks exist for both authenticated users and those without a user name and password; for example
- Tools such as Query Analyzer (Isqlw.exe) or the command line equivalent (Osql.exe) are used to establish a direct connection to SQL Server and issue commands.
- Server information, such as software version, is revealed to an attacker who sends carefully constructed packets to listening ports.
Countermeasures To counter these attacks:
- Make sure that SQL Server ports are not visible from outside of the perimeter network.
- Within the perimeter, restrict direct access by unauthorized hosts, for example, by using IPSec or TCP/IP filters.
- A common first line of attack is to try to crack the passwords of well known account names, such as sa (the SQL Server administrator account).
Vulnerabilities Common vulnerabilities that lead to password cracking are:
- Weak or blank passwords
- Passwords that contain everyday words
Attacks Common password cracking attacks include:
- Dictionary attacks
- Manual password guessing
Countermeasures To counter these attacks:
- Create passwords for SQL Server login accounts that meet complexity requirements.
- Avoid passwords that contain common words found in the dictionary.
Starting to install MySQL database
- There are many implementations of the SQL database language available on Linux and Unix-like systems. MySQL and MariaDB are two popular options for deploying relational databases in server environments.
- However, like most software, these tools can be security liabilities if they are configured incorrectly. This tutorial will guide user through some basic steps, user can take to secure MariaDB or MySQL databases, and ensure that they are not an open door into VPS.
- For the sake of simplicity and illustration, using the MySQL server on an Ubuntu 12.04 VPS instance. However, these techniques can be applied to other Linux distributions and can be used with MariaDB as well. 
- MySQL gives user an opportunity to take the first step towards security during installation. It will request that user set a root password.
sudo apt-get install mysql-server
User can always set the root password at a later time, but there is no reason to skip this step, so user should secure his administrator account from the very beginning.
Once the installation is complete, user should run a few included scripts. First, user will use the "mysql_install_db" script to create a directory layout for our databases.
Next, run the script called "mysql_secure_installation". This will guide through some procedures that will remove some defaults that are dangerous to use in a production environment.
it will first prompt user for the root password user set up during installation. Immediately following, user will be asked a series of questions, beginning with if you'd like to change the root password.
This is another opportunity to change user password to something secure if user have not done so already.
User should answer "Y" (for yes) to all of the remaining questions.
This will remove the ability for anyone to log into MySQL by default, disable logging in remotely with the administrator account, remove some test databases that are insecure, and update the running MySQL instance to reflect these changes.
The overarching theme of securing MySQL (and almost any other system) is that access should be granted only when absolutely necessary. User data safety sometimes comes down to a balance between convenience and security.
In this Wiki, user will learn on the side of security, although user specific usage of the database software may lead user to pick and choose from these options.
Security Through the My.cnf File
The main configuration file for MySQL is a file called "my.cnf" that is located in the "/etc/mysql/" directory on Ubuntu and the "/etc/" directory on some other VPS.
First changing some settings in this file to lock down user MySQL instance.
Open the file with root privileges. Change the directory path as needed if user are following this tutorial on a different system
sudo nano /etc/mysql/my.cnf
The first setting that should check is the "bind-address" setting within the "[mysqld]" section. This setting should be set to user local loopback network device, which is "127.0.0.1".
bind-address = 127.0.0.1
- This makes sure that MySQL is not accepting connections from anywhere except for the local machine.
- If user need to access this database from another machine, consider connecting through SSH to do user database querying and administration locally and sending the results through the ssh tunnel.
- The next hole will patch is a function that allows access to the underlying filesystem from within MySQL. This can have severe security implications and should be shut off unless user absolutely need it.
In the same section of the file, user will add a directive to disable this ability to load local files:
This will disable loading files from the file system for users without file level privileges to the database.
If the owner have enough space and are not operating a huge database, it can be helpful to log additional information to keep an eye on suspicious activity.
Logging too much can create a performance hit, so this is something user need to weigh carefully.
User can set the log variable within the same "[mysqld]" section that we've been adding to.
User have to make sure that the MySQL log, error log, and mysql log directory are not world readable
sudo ls -l /var/log/mysql*
Securing MySQL From Within
- There are a number of steps user can take while using MySQL to improve security.
- User will be inputting the commands in this section into the MySQL prompt interface, so user need to log in.
mysql -u root -p
User will be asked for the root password that set up earlier.
Securing Passwords and Host Associations
SELECT User,Host,Password FROM mysql.user;
As user can see, in this example set up, the user "demo-user" has no password and is valid regardless of what host he is on. This is very insecure.
User can set a password for the user with this command. Change "newPassWord" to reflect the password that user wish to assign.
UPDATE mysql.user SET Password=PASSWORD('newPassWord') WHERE User="demo-user";
Checking the User table again, user will see that the demo user now has a password.
SELECT User,Host,Password FROM mysql.user;
If user look in the "Host" field, user will see that still have a "%", which is a wildcard that means any host. This is not what want to be. Let's change that to be "local-host".
UPDATE mysql.user SET Host='localhost' WHERE User="demo-user";
Checking again, user table now has the appropriate fields set.
SELECT User,Host,Password FROM mysql.user;
If the table contains any blank users (it should not at this point since ran "mysql_secure_installation", but it will cover this anyways), user should remove them.
To do this, the root user can use the following call to delete blank users from the access table.
DELETE FROM mysql.user WHERE User="";
After the root user are done modifying the User table, user need to input the following command to implement the new permissions.
Implementing Application-Specific Users
Similar to the practice of running processes within Linux as an isolated user, MySQL benefits from the same kind of isolation.
Each application that uses MySQL should have its own user that only has limited privileges and only has access to the databases it needs to run.
When the root user configure a new application to use MySQL, user should create the databases needed by that application.
create database testDB;
Query OK, 1 row affected (0.00 sec)
Next, the database owner should create a user to manage that database, and assign it only the privileges it needs. This will vary by application, and some uses need more open privileges than others.
To create a new user, use the following command.
CREATE USER 'demo-user'@'localhost' IDENTIFIED BY 'password';
User can grant the new user privileges on the new table with the following command. See the tutorial on how to create a new user and grant permissions in MySQL to learn more about specific privileges. 
GRANT SELECT,UPDATE,DELETE ON testDB.* TO 'demo-user'@'localhost';
As an example, if the user later need to revoke update privileges from the account, user could use the following command.
REVOKE UPDATE ON testDB.* FROM 'demo-user'@'localhost';
If user need all privileges on a certain database he can specify that with the following.
GRANT ALL ON testDB.* TO 'demo-user'@'localhost';
To show the current privileges of a user, user first must implement the privileges that specified using the "flush privileges" command. Then, and query what grants a user has:
show grants for 'demo-user'@'localhost';
Always flush privileges when the root user are finished making changes.
Changing the Root User
One additional step that the root user may want to take is to change the root login name. If an attacker is trying to access the root MySQL login, they will need to perform the additional step of finding the user-name.
The root login can be changed with the following command.
rename user 'root'@'localhost' to 'newAdminUser'@'localhost';
User can see the change by using the same query that been used for the User database.
select user,host,password from mysql.user;
Again!!, user must flush privileges for these changes to happen.
User have to remember that to log into MySQL as the newly created username from now on when user wish to perform administrative tasks.
mysql -u newAdminUser -p
Database is always at risk, cause one small mistake and the hacker can access to the database from different ways with different methods, user should now have a general understanding about databases and how to create a secure database. present article was for beginners that try to gain an understanding of databases security. Databases are not like most other files and require a little bit of thought in order for user to understand the concept of securing the database.