How to Reset WordPress Admin Password via MySQL Command Prompt

Sometimes, a WordPress user, with one of the following capabilities, such as administrator, editor, author, contributor or subscriber, forgets its login credentials, especially the password.

WordPress password can be easily changed via “Lost password” WordPress login form. However, if the WordPress account has no way of accessing his email address, changing the password using this mechanism can be impossible. In such cases, the job of updating a WordPress account password can only be managed by a system administrator with full privileges to MySQL database daemon.

In this guide we will show you how to reset a WordPress account password via MySQL command line in Linux.

Before logging in to MySQL/MariaDB database service, first create a MD5 Hash version of the new password that will be assigned to the account, by issuing the below command.


Replace the “newpass” string used in this example with your own strong password. Copy the password MD5 hash to a file in order to later paste the hash to MySQL user password field.

# echo -n "newpass" | md5sum
Create MD5 WordPress Password

Create MD5 WordPress Password

After you’ve generated the new password MD5 hash, log in to MySQL database with root privileges and issue the below command in order to identify and select the WordPress database. In this case the WordPress database is named “wordpress”.

# mysql -u root -p
MariaDB [(none)]> show databases;
MariaDB [(none)]> use wordpress;
Connect and Select WordPress Database

Connect and Select WordPress Database

Next, execute the below command to identify the table responsible for storing WordPress user accounts. Usually the table that stores all user information is wp_users.

Query wp_users table to retrieve all users ID, login name and password and identify the username ID field of the account that needs the password changed.
The username ID value will be used to further update the password.

MariaDB [(none)]> show tables;
MariaDB [(none)]> SELECT ID, user_login, user_pass FROM wp_users;
List All WordPress Users in MySQL

List All WordPress Users in MySQL

After you’ve correctly identified the ID of the user that needs the password changed, issue the below command to update his password. Replace the user ID and password MD5 Hash accordingly.

In this case the user ID is 1 and the new password hash is: e6053eb8d35e02ae40beeeacef203c1a.

MariaDB [(none)]> UPDATE wp_users SET user_pass= "e6053eb8d35e02ae40beeeacef203c1a" WHERE ID = 1;
Reset WordPress Admin Password in MySQL

Reset WordPress Admin Password in MySQL

In case you don’t have an already MD5 hashed password, you can execute MySQL UPDATE command with the password written in plain text, as shown in the below example.

In this case we’ll use MySQL MD5() function to calculate the MD5 hash of the password string.

MariaDB [(none)]> UPDATE wp_users SET user_pass = MD5('the_new_password') WHERE ID=1;

After the password has been updated, query wp_users table with the ID of the user that you’ve changed the password in order to retrieve this user database information.

MariaDB [(none)]> SELECT ID, user_login, user_pass FROM wp_users WHERE ID = 1;

That’s all! Now, inform the user that his password has been updated and it should be able to log in to WordPress with the new password.

How to View Colored Man Pages in Linux

In Unix-like operating systems, a man page (in full manual page) is a documentation for a terminal-based program/too/utility (commonly known as a command). It contains the name of the command, syntax for using it, a description, options available, author, copyright, related commands etc.

Read Also: ccat – Show ‘cat Command’ Output with Syntax Highlighting or Colorizing

You can read the manual page for a Linux command as follows; this will display the man page for the df command:

$ man df 
df Command Man Page

df Command Man Page

By default, the man program normally uses a terminal pager program such as more or less to format its output, and the default view is normally in white color for every kind of text (bold, underlined etc..).


You can make some tweaks to your ~/.bashrc file to get nicely colored man pages by specifying a color scheme using various LESS_TERMCAP variables.

$ vi ~/.bashrc

Add following color scheme variables.

export LESS_TERMCAP_mb=$'\e[1;32m'
export LESS_TERMCAP_md=$'\e[1;32m'
export LESS_TERMCAP_me=$'\e[0m'
export LESS_TERMCAP_se=$'\e[0m'
export LESS_TERMCAP_so=$'\e[01;33m'
export LESS_TERMCAP_ue=$'\e[0m'
export LESS_TERMCAP_us=$'\e[1;4;31m'

Following are the color codes that we used in the above configuration.

  • 31 – red
  • 32 – green
  • 33 – yellow

And here are the meanings of the escape codes used in the above configuration.

  • 0 – reset/normal
  • 1 – bold
  • 4 – underlined

You can additionally reset your terminal by typing reset or even start up another shell. Now when you try to view a man page df command, it should look like this, nicer than the default view.

Colored Man Page

Colored Man Page

Alternatively, you can use the MOST paging program, which works on Unix-like operating systems and supports multiple windows and can scroll left and right.

$ sudo apt install most #Debian/Ubuntu # yum install most #RHEL/CentOS
# dnf install most #Fedora 22+

Next, add the line below in your ~/.bashrc file, then source the file like before and possibly reset your terminal.

export PAGER="most"
Most Paging Program for Linux

Most Paging Program for Linux

Read Also: How to Customize Bash Colors and Content in Linux Terminal Prompt

In this article, we showed you how to display beautifully colored man pages in Linux. To send us any queries or share any useful Linux shell tips/tricks, use the comment section below.

ccat – Show ‘cat Command’ Output with Syntax Highlighting or Colorizing

ccat is command line similar to cat command in Linux that displays the content of a file with syntax highlighting for the following programming languages: Javascript, Java, Go, Ruby, C, Python and Json.

To install ccat utility in your Linux distribution, first assure that the wget utility is present in your system. If the wget command line is not installed in the system, issue the below command to install it:

# yum install wget [On CentOS/RHEL/Fedora]
# apt-get install wget [On Debian and Ubuntu]

In order to install the latest version of ccat command line via the latest compiled binaries, first download the compressed tarball by issuing the below command. The binary and source code releases archives can be found at the official ccat github webpage.

-------------- On 64-Bit -------------- # wget https://github.com/jingweno/ccat/releases/download/v1.1.0/linux-amd64-1.1.0.tar.gz -------------- On 32-Bit -------------- # wget https://github.com/jingweno/ccat/releases/download/v1.1.0/linux-386-1.1.0.tar.gz 

After archive download completes, list the current working directory to show the files, extract the ccat tarball (the linux-amd64-1.x.x Tarball file) and copy the ccat executable binary from the extracted tarball into a Linux executable system path, such as /usr/local/bin/ path, by issuing the below commands.

# ls
# tar xfz linux-amd64-1.1.0.tar.gz # ls linux-amd64-1.1.0
# cp linux-amd64-1.1.0/ccat /usr/local/bin/
# ls -al /usr/local/bin/
ccat Command Executable Files

ccat Command Executable Files


If for some reasons the ccat file from your executable system path has no executable bit set, issue the below command to set executable permissions for all system users.

# chmod +x /usr/local/bin/ccat

In order to test ccat utility capabilities against a system configuration file, issue the below commands. The content of the displayed files should be highlighted according to file programming language sytnax, as illustrated in the below command examples.

# ccat /etc/sysconfig/network-scripts/ifcfg-ens33 # ccat /etc/fstab 
ccat Command Usage

ccat Command Usage

In order to replace cat command with ccat command system wide, add a bash alias for ccat in system barshrc file, log out from the system and log in back again to apply the configuration.

-------------- On CentOS, RHEL & Fedora -------------- # echo "alias cat='/usr/local/bin/ccat'" >> /etc/bashrc # exit
-------------- On Debiab & Ubuntu -------------- # echo "alias cat='/usr/local/bin/ccat'" >> /etc/profile
# exit

Finally, run cat command against an arbitrary configuration file to test if ccat alias has replaced cat command, as shown in the below example. The output file syntax should be highlighted now.

# cat .bashrc
Replace cat Command with ccat

Replace cat Command with ccat

ccat utility can also be used to concatenate multiple files and display the output in HTML format, as illustrated in the below example.

# ccat --html /etc/fstab /etc/sysconfig/network-scripts/ifcfg-ens33> /var/www/html/ccat.html

However, you will need a web server installed in your system, such as Apache HTTP server or Nginx, to display the content of the HTML file, as illustrated in the below screenshot.

Display File Content in HTML

Display File Content in HTML

For other custom configurations and command options visit ccat official github page.

How to Run Multiple Websites with Different PHP Versions in Nginx

Sometimes PHP developers want to build and run different websites/applications using different versions of PHP on the same web server. As a Linux system administrator, you are required to setup a environment where you can run multiple websites using different PHP version on a single web server i.e. Nginx.

In this tutorial, we will explain you how to install multiple versions of PHP and configure the web server Nginx to work with them via the server blocks (virtual hosts in Apache) in CentOS/RHEL 7 distributions using LEMP stack.

Nginx uses PHP-FPM (stands for FastCGI Process Manager), which is an alternative PHP FastCGI implementation with some extra, useful features for heavily loaded websites.

Testing Environment Setup

  1. A CentOS 7 or RHEL 7 server with minimal installation.
  2. Nginx HTTP Server.
  3. PHP 7.1 (to be used as default version) and 5.6.
  4. MariaDB Database Server.
  5. Server IP address: 192.168.56.10.
  6. Websites: example1.com and example2.com.

Step 1: Installing and Enabling EPEL and Remi Repository

1. First start by installing and enabling the EPEL and Remi repository, which offers the latest versions of the PHP stack on CentOS/RHEL 7 distributions.

# yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
# yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm


2. Next install the yum-utils package, which extends yum’s native functionalities and provides yum-config-manager command, which is used to enable or disable Yum repositories on the system.

# yum install yum-utils

Note: On RHEL 7 you can enable the optional channel for some dependencies using the following command.

# subscription-manager repos --enable=rhel-7-server-optional-rpms

Step 2: Installing Nginx Web Server

3. To install latest version of Nginx, we need to add the official Nginx repository, create a file named /etc/yum.repos.d/nginx.repo.

# vi /etc/yum.repos.d/nginx.repo

Add the following lines to file as per your distribution.

--------------- On CentOS 7 --------------- [nginx] name=nginx repo baseurl=http://nginx.org/packages/centos/7/$basearch/ gpgcheck=0 enabled=1 --------------- On RHEL 7 ---------------
[nginx] name=nginx repo baseurl=http://nginx.org/packages/rhel/7.x/$basearch/ gpgcheck=0 enabled=1 

4. Once nginx repo has been added, you can install Nginx using yum package manager tool as shown.

# yum install nginx

Step 3: Installing MariaDB Database Server

5. To install latest version of MariaDB, we need to add the official MariaDB repository, create a file named /etc/yum.repos.d/mariadb.repo.

# vi /etc/yum.repos.d/mariadb.repo

Add the following lines to file as per your distribution.

--------------- On CentOS 7 --------------- [mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.2/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1
--------------- On RHEL 7 ---------------
[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.2/rhel7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1 

6. Once MariaDB repo has been added, you can install MariaDB using yum package manager tool as shown.

# yum install MariaDB-client MariaDB-server

7. Afterwards, secure the database server installation using the script below. Set a root password and answer y and press [Enter] for the rest of the subsequent questions to disable remote root user login, remove anonymous-user accounts and test database which by default can be accessed by all users, even anonymous users.

# mysql_secure_installation

Read Also: 12 MySQL/MariaDB Security Best Practices for Linux

Step 4: Installing Multiple Versions of PHP

8. To install different versions of PHP for your projects, use yum-config-manager command to install multiple versions of PHP along with most required modules as shown.

Install PHP 7.1 Version

# yum-config-manager --enable remi-php71 [Default]
# yum install php php-common php-fpm
# yum install php-mysql php-pecl-memcache php-pecl-memcached php-gd php-mbstring php-mcrypt php-xml php-pecl-apc php-cli php-pear php-pdo

Install PHP 5.6 Version

# yum install php56 php56-php-common php56-php-fpm
# yum install php56-php-mysql php56-php-pecl-memcache php56-php-pecl-memcached php56-php-gd php56-php-mbstring php56-php-mcrypt php56-php-xml php56-php-pecl-apc php56-php-cli php56-php-pear php56-php-pdo

9. Once installed PHP, you can use following command to check the default version of PHP used on your server.

# php -v
Check Default PHP Version

Check Default PHP Version

Step 5: Configuring PHP-FPM and PHP56-PHP-FPM

10. This is the most interesting part of this tutorial, it explains how you can actually run multiple PHP versions on your server. Here, you will configure the different versions of php-fpm that Nginx will work with. You should define the user/group of the FastCGI processes as well as the ports they will listen on.

These are the following two configuration files that you will going to edit.

  • php-fpm (default 7.1) – /etc/php-fpm.d/www.conf
  • php56-php-fpm – /opt/remi/php56/root/etc/php-fpm.d/www.conf

Open the files above, set the user/group of FastCGI processes.

# vi /etc/php-fpm.d/www.conf [PHP 7.1]
# vi /opt/remi/php56/root/etc/php-fpm.d/www.conf [PHP 5.6] 

The default values should be apache, change them to nginx as shown.

user = nginx
group = nginx

11. Next, find the listen parameters, and define the address:port on which FastCGI requests will be received.

listen = 127.0.0.1:9000 [php-fpm]
listen = 127.0.0.1:9001 [php56-php-fpm]

12. Once all the above configuration done, you need to start and enable Nginx, MariaDB and PHP-FPM to auto-start at system boot.

# systemctl enable nginx # systemctl start nginx # systemctl enable mariadb # systemctl start mariadb ---------------- PHP 7.1 ---------------- # systemctl enable php-fpm # systemctl start php-fpm ---------------- PHP 5.6 ----------------
# systemctl enable php56-fpm # systemctl start php56-php-fpm 

Attention: In case you get any errors while starting the second instance of PHP, php56-php-fpm, a SELinux policy could be blocking it from starting. If SELinux is in enforcing mode, set it to permissive mode, then try starting the service once again.

# getenforce
# setenforce 0 

Step 6: Setup Websites with Permissions

13. At this point, you can now create the necessary directories for your websites under /var/www/html/. You also need to create directories to store logs as follows:

---------------- Website 1 ----------------
# mkdir -p /var/www/html/example1.com/ # mkdir -p /var/www/html/example2.com/ ---------------- Website 2 ----------------
# mkdir -p /var/log/nginx/example1.com/ # mkdir -p /var/log/nginx/example2.com/ 

14. Set the appropriate ownership permissions on all the directories.

---------------- Website 1 ----------------
# chown -R root:nginx /var/www/html/example1.com/ # chmod -R 755 /var/www/html/example1.com/ # chown -R root:nginx /var/log/nginx/example1.com/
# chmod -R 660 /var/log/nginx/example1.com/ ---------------- Website 2 ----------------
# chown -R root:nginx /var/www/html/example2.com/ # chmod -R 755 /var/www/html/example2.com/
# chown -R root:nginx /var/log/nginx/example2.com/ # chmod -R 660 /var/log/nginx/example2.com/

Step 7: Setup Nginx Server Blocks for Websites

15. Now configure how Nginx will process requests to your websites using the server block configuration files which should be located in /etc/nginx/conf.d/.

Create the configuration files for your websites ending with .conf extension.

# vi /etc/nginx/conf.d/example1.com.conf
# vi /etc/nginx/conf.d/example2.com.conf

Then paste the following server block configurations in the respective files.

Website 1

Configuration for example1.com

server {
listen 80;
server_name example1.com www.example1.com;
root /var/www/html/example1.com/;
index index.php index.html index.htm;
#charset koi8-r;
access_log /var/log/nginx/example1.com/example1_access_log;
error_log /var/log/nginx/example1.com/example1_error_log error;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
location ~ \.php$ {
root /var/www/html/example1.com/;
fastcgi_pass 127.0.0.1:9000; #set port for php-fpm to listen on
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
include /etc/nginx/fastcgi_params;
}
}

Website 2

Configuration for example2.com

server {
listen 80;
server_name example2.com www.example2.com;
root /var/www/html/example2.com/;
index index.php index.html index.htm;
#charset koi8-r;
access_log /var/log/nginx/example2.com/example2_access_log;
error_log /var/log/nginx/example2.com/example2_error_log error;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
location ~ \.php$ {
root /var/www/html/example2.com/;
fastcgi_pass 127.0.0.1:9001; #set port for php56-php-fpm to listen on
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
include /etc/nginx/fastcgi_params;
}
}

16. Make sure that you have the following line in the closing part of the http block in /etc/nginx/nginx.conf. It helps to include all configuration files inside the /etc/nginx/conf.d/ directory when Nginx is running.

include /etc/nginx/conf.d/*.conf;

Step 8: Testing Different PHP Versions

17. Finally, you need to test that your server is using the two versions of PHP. You can create a very basic info.php script in the document root directories of your websites as shown.

# echo "<?php phpinfo(); ?>" > /var/www/html/example1.com/info.php
# echo "<?php phpinfo(); ?>" > /var/www/html/example2.com/info.php

18. To apply all the changes you have made above, you need to restart Nginx, php-fpm and php56-php-fpm. But you can first of all check that the Nginx configuration files for any syntax errors before doing so.

# nginx -t # systemctl restart nginx php-fpm php56-php-fpm
Verify Nginx Configuration

Verify Nginx Configuration

19. There is one other last thing to do, especially if you are running your server locally, you need to setup local DNS using /etc/hosts file as shown in the screen shot below.

192.168.56.10 example1.com example1
192.168.56.10 example2.com example2
Add Websites to-Hosts File

Add Websites to-Hosts File

20. Finally, open a web browser and type the following addresses to verify the versions of PHP installed on the system.

http://example1.com/index.php
http://example2.com/index.php
Check PHP 7.1 Version

Check PHP 7.1 Version

Check PHP 5.6 Version

Check PHP 5.6 Version

That’s It! Now you can deploy files and test websites with different PHP versions. If you have any additions to make or questions to put forward, make use of the comment form below.

How to Find a Specific String or Word in Files and Directories

Do you want to find all files that contain a particular word or string of text on your entire Linux system or a given directory. This article will guide you on how to do that, you will learn how to recursively dig through directories to find and list all files that contain a given string of text.

A simple way to work this out is by using grep pattern searching tool, is a powerful, efficient, reliable and most popular command-line utility for finding patterns and words from files or directories on Unix-like systems.

Read Also: 11 Advanced Linux ‘Grep’ Commands on Character Classes and Bracket Expressions

The command below will list all files containing a line with the text “check_root”, by recursively and aggressively searching the ~/bin directory.

$ grep -Rw ~/bin/ -e 'check_root'
Find a Word in Directory

Find a Word in Directory


Where the -R option tells grep to read all files under each directory, recursively, following symbolic links only if they are on the command line and option -w instructs it to select only those lines containing matches that form whole words, and -e is used to specify the string (pattern) to be searched.

You should use the sudo command when searching certain directories or files that require root permissions (unless you are managing your system with the root account).

 $ sudo grep -Rw / -e 'check_root' 

To ignore case distinctions employ the -i option as shown:

$ grep -Riw ~/bin/ -e 'check_root'

If you want to know the exact line where the string of text exist, include the -n option.

$ grep -Rinw ~/bin/ -e 'check_root'
Find String with Line Number

Find String with Line Number

Assuming there are several types of files in a directory you wish to search in, you can also specify the type of files to be searched for instance, by their extension using the --include option.

This example instructs grep to only look through all .sh files.

$ grep -Rnw --include=\*.sh ~/bin/ -e 'check_root'

In addition, it is possible to search for more than one pattern, using the following command.

$ grep -Rinw ~/bin/ -e 'check_root' -e 'netstat'
Find Multiple Words in Files

Find Multiple Words in Files

That’s It! If you know any other command-line trick to find string or word in files, do share with us or ask any questions regarding this topic, use the comment form below.

12 MySQL/MariaDB Security Best Practices for Linux

MySQL is the world’s most popular open source database system and MariaDB (a fork of MySQL) is the world’s fastest growing open source database system. After installing MySQL server, it is insecure in it’s default configuration, and securing it is one of the essential tasks in general database management.

Read Also: Learn MySQL/MariaDB for Beginners – Part 1

This will contribute to hardening and boosting of overall Linux server security, as attackers always scan vulnerabilities in any part of a system, and databases have in the past been key target areas. A common example is the brute-forcing of the root password for the MySQL database.

In this guide, we will explain useful MySQL/MariaDB security best practice for Linux.

1. Secure MySQL Installation


This is the first recommended step after installing MySQL server, towards securing the database server. This script facilitates in improving the security of your MySQL server by asking you to:

  • set a password for the root account, if you didn’t set it during installation.
  • disable remote root user login by removing root accounts that are accessible from outside the local host.
  • remove anonymous-user accounts and test database which by default can be accessed by all users, even anonymous users.
# mysql_secure_installation

After running it, set the root password and answer the series of questions by entering [Yes/Y] and press [Enter].

Secure MySQL Installation

Secure MySQL Installation

2. Bind Database Server To Loopback Address

This configuration will restrict access from remote machines, it tells the MySQL server to only accept connections from within the localhost. You can set it in main configuration file.

# vi /etc/my.cnf [RHEL/CentOS] # vi /etc/mysql/my.conf [Debian/Ubuntu] OR
# vi /etc/mysql/mysql.conf.d/mysqld.cnf [Debian/Ubuntu] 

Add the following line below under [mysqld] section.

bind-address = 127.0.0.1

3. Disable LOCAL INFILE in MySQL

As part of security hardening, you need to disable local_infile to prevent access to the underlying filesystem from within MySQL using the following directive under [mysqld] section.

local-infile=0

4. Change MYSQL Default Port

The Port variable sets the MySQL port number that will be used to listen on TCP/ IP connections. The default port number is 3306 but you can change it under the [mysqld] section as shown.

Port=5000

5. Enable MySQL Logging

Logs are one of the best ways to understand what happens on a server, in case of any attacks, you can easily see any intrusion-related activities from log files. You can enable MySQL logging by adding the following variable under the [mysqld] section.

log=/var/log/mysql.log

6. Set Appropriate Permission on MySQL Files

Ensure that you have appropriate permissions set for all mysql server files and data directories. The /etc/my.conf file should only be writeable to root. This blocks other users from changing database server configurations.

# chmod 644 /etc/my.cnf

7. Delete MySQL Shell History

All commands you execute on MySQL shell are stored by the mysql client in a history file: ~/.mysql_history. This can be dangerous, because for any user accounts that you will create, all usernames and passwords typed on the shell will recorded in the history file.

# cat /dev/null > ~/.mysql_history

8. Don’t Run MySQL Commands from Commandline

As you already know, all commands you type on the terminal are stored in a history file, depending on the shell you are using (for example ~/.bash_history for bash). An attacker who manages to gain access to this history file can easily see any passwords recorded there.

It is strongly not recommended to type passwords on the command line, something like this:

# mysql -u root -ppassword_
Connect MySQL with Password

Connect MySQL with Password

When you check the last section of the command history file, you will see the password typed above.

# history 
Check Command History

Check Command History

The appropriate way to connect MySQL is.

# mysql -u root -p
Enter password:

9. Define Application-Specific Database Users

For each application running on the server, only give access to a user who is in charge of a database for a given application. For example, if you have a wordpress site, create a specific user for the wordpress site database as follows.

# mysql -u root -p
MariaDB [(none)]> CREATE DATABASE osclass_db;
MariaDB [(none)]> CREATE USER 'osclassdmin'@'localhost' IDENTIFIED BY '[email protected]%!2';
MariaDB [(none)]> GRANT ALL PRIVILEGES ON osclass_db.* TO 'osclassdmin'@'localhost';
MariaDB [(none)]> FLUSH PRIVILEGES;
MariaDB [(none)]> exit

and remember to always remove user accounts that are no longer managing any application database on the server.

10. Use Additional Security Plugins and Libraries

MySQL includes a number of security plugins for: authenticating attempts by clients to connect to mysql server, password-validation and securing storage for sensitive information, which are all available in the free version.

You can find more here: https://dev.mysql.com/doc/refman/5.7/en/security-plugins.html

11. Change MySQL Passwords Regularly

This is a common piece of information/application/system security advice. How often you do this will entirely depend on your internal security policy. However, it can prevent “snoopers” who might have been tracking your activity over an long period of time, from gaining access to your mysql server.

MariaDB [(none)]> USE mysql;
MariaDB [(none)]> UPDATE user SET password=PASSWORD('YourPasswordHere') WHERE User='root' AND Host = 'localhost';
MariaDB [(none)]> FLUSH PRIVILEGES;

12. Update MySQL Server Package Regularly

It is highly recommended to upgrade mysql/mariadb packages regularly to keep up with security updates and bug fixes, from the vendor’s repository. Normally packages in default operating system repositories are outdated.

# yum update
# apt update

After making any changes to the mysql/mariadb server, always restart the service.

# systemctl restart mariadb #RHEL/CentOS
# systemctl restart mysql #Debian/Ubuntu

Read Also: 15 Useful MySQL/MariaDB Performance Tuning and Optimization Tips

That’s all! We love to hear from you via the comment form below. Do share with us any MySQL/MariaDB security tips missing in the above list.

Paying it forward at Finland's Aalto Fablab

Originating at MIT, a fab lab is a technology prototyping platform where learning, experimentation, innovation, and invention are encouraged through curiosity, creativity, hands-on making, and most critically, open knowledge sharing. Each fab lab provides a common set of tools (including digital fabrication tools like laser cutters, CNC mills, and 3D printers) and processes, so you can learn how to work in a fab lab anywhere and use those skills at any of the 1,000+ fab labs across the globe. There is probably a fab lab near you.

Fab labs can be found anywhere avant-garde makers and hackers live, but they have also cropped up at libraries and other public spaces. For example, the Aalto Fablab, the first fab lab in Finland, is in the basement of Aalto University’s library, in Espoo. Solomon Embafrash, the studio master, explains, “Aalto Fablab was in the Arabia campus with the School of Arts and Design since 2011. As Aalto decided to move all the activities concentrated in one campus (Otaniemi), we decided that a dedicated maker space would complement the state-of-the-art library in the heart of Espoo.”

The library, which is now a full learning center, sports a maker space that consists of a VR hub, a visual resources center, a studio, and of course, the Fablab. With the expansion of the Helsinki metro to a new station across the street from the Aalto Fablab, everyone in the region now has easy access to it.

The Fab Lab Charter states: “Designs and processes developed in fab labs can be protected and sold however an inventor chooses, but should remain available for individuals to use and learn from.” The “protected” part does not quite meet the requirements set by the Open Source Hardware Association’s definition of open source hardware; however, for those not involved in commercialization of products, the code is available for a wide range of projects created in fab labs (like the FabFi, an open source wireless network).

That means fab labs are effectively feeding the open source ecosystem that allows digitally distributed manufacturing of a wide range of products as many designers choose to release their designs with fully free licenses. Even the code to create a fab lab is also openly shared by the U.S. non-profit Fab Foundation.

All fab labs are required to provide open access to the community; however, some, like the Aalto Fablab, take that requirement one step further. The Aalto Fablab is free to use, but if you wish to use bulk materials from its stock for your project—for example, to make a new chair—you need to pay for them. You are also expected to respect the philosophy of open knowledge-sharing by helping others, documenting your work, and sharing what you have learned. Specifically, the Aalto Fablab asks that you “pay forward” what you have learned to other users, who may be able to build upon your work and help speed development.

All fab labs are required to provide open access to the community.

Embafrash adds, “There is a very old tradition of free services in Finland, like the library service and education. We used to charge users a few cents for the material cost of the 3D prints, but we found that it makes a lot of sense to keep it free, as it encourages people to our core philosophy of Fablab, which is idea sharing and documentation.”

This approach has proven successful, fostering enormous interest in the local community for making and sharing. For example, the Unseen Art project, an open source platform that allows the visually impaired to enjoy 3D printed art, started in the Aalto Fablab.

Fablab members organize local Maker Faire events and work closely with the maker community, local schools, and other organizations. “The Fablab has open days, which are very popular times that people from outside the university get access to the resources, and our students get the exposure to work with people outside the school community,” Embafrash says.

In this way, the more they share, the more their university benefits.

This article was supported by Fulbright Finland, which is currently sponsoring my research in open source scientific hardware in Finland as the Fulbright-Aalto University Distinguished Chair.

How to Check Integrity of File and Directory Using “AIDE” in Linux

In our mega guide to hardening and securing CentOS 7, under the section “protect system internally”, one of the useful security tools we listed for internal system protection against viruses, rootkits, malware, and detection of unauthorized activities is AIDE.

AIDE (Advanced Intrusion Detection Environment) is a small yet powerful, free open source intrusion detection tool, that uses predefined rules to check file and directory integrity in Unix-like operating systems such as Linux. It is an independent static binary for simplified client/server monitoring configurations.

It is feature-rich: uses plain text configuration files and database making it easy to use; supports several message digest algorithms such as but not limited to md5, sha1, rmd160, tiger; supports common file attributes; also supports powerful regular expressions to selectively include or exclude files and directories to be scanned.

Also it can be compiled with exceptional support for Gzip compression, Posix ACL, SELinux, XAttrs and Extended file system attributes.


Aide works by creating a database (which is simply a snapshot of selected parts of the file system), from the regular expression rules defined in the configuration file(s). Once this database is initialized, you can verify the integrity of the system files against it. This guide will show how to install and use aide in Linux.

How to Install AIDE in Linux

Aide is packaged in official repositories of mainstream Linux distributions, to install it run the command for your distribution using a package manager.

# apt install aide [On Debian/Ubuntu]
# yum install aide [On RHEL/CentOS] # dnf install aide [On Fedora 22+]
# zypper install aide [On openSUSE]
# emerge aide [On Gentoo]

After installing it, the main configuration file is /etc/aide.conf. To view the installed version as well as compile time parameters, run the command below on your terminal:

# aide -v
Sample Output
Aide 0.14
Compiled with the following options:
WITH_MMAP
WITH_POSIX_ACL
WITH_SELINUX
WITH_PRELINK
WITH_XATTR
WITH_LSTAT64
WITH_READDIR64
WITH_ZLIB
WITH_GCRYPT
WITH_AUDIT
CONFIG_FILE = "/etc/aide.conf"

You can open the configuration using your favorite editor.

# vi /etc/aide.conf

It has directives that define the database location, report location, default rules, the directories/files to be included in the database.

Understanding Default Aide Rules

AIDE Default Rules

AIDE Default Rules

Using the above default rules, you can define new custom rules in the aide.conf file for example.

PERMS = p+u+g+acl+selinux+xattrs

The PERMS rule is used for access control only, it will detect any changes to file or directories based on file/directory permissions, user, group, access control permissions, SELinux context and file attributes.

This will only check file content and file type.

CONTENT = sha256+ftype

This is an extended version of the previous rule, it checks extended content, file type and access.

CONTENT_EX = sha256+ftype+p+u+g+n+acl+selinux+xattrs

The DATAONLY rule below will help detect any changes in data inside all files/directory.

DATAONLY = p+n+u+g+s+acl+selinux+xattrs+sha256
Configure Aide Rules

Configure Aide Rules

Defining Rules to Watch Files and Directories

Once you have defined rules, you can specify the file and directories to watch. Considering the PERMS rule above, this definition will check permissions for all files in root directory.

/root/\..* PERMS

This will check all files in the /root directory for any changes.

/root/ CONTENT_EX

To help you detect any changes in data inside all files/directory under /etc/, use this.

/etc/ DATAONLY 
Configure Aide Rules for Filesystem

Configure Aide Rules for Filesystem

Using AIDE to Check File and Directory Integrity in Linux

Start by constructing a database against the checks that will be performed using --init flag. This is expected to be done before your system is connected to a network.

The command below will create a database that contains all of the files that you selected in your configuration file.

# aide --init
Initialize Aide Database

Initialize Aide Database

Then rename the database to /var/lib/aide/aide.db.gz before proceeding, using this command.

# mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz

It is recommended to move the database to a secure location possibly in a read-only media or on another machines, but ensure that you update the configuration file to read it from there.

After the database is created, you can now check the integrity of the files and directories using the --check flag.

# aide --check

It will read the snapshot in the database and compares it to the files/directories found you system disk. If it finds changes in places that you might not expect, it generates a report which you can then review.

Run File Integrity Check

Run File Integrity Check

Since no changes have been made to the file system, you will only get an output similar to the one above. Now try to create some files in the file system, in areas defined in the configuration file.

# vi /etc/script.sh
# touch all.txt

Then run a check once more, which should report the files added above. The output of this command depends on the parts of the file system you configured for checking, it can be lengthy overtime.

# aide --check
Check File System Changes

Check File System Changes

You need to run aide checks regularly, and in case of any changes to already selected files or addition of new file definitions in the configuration file, always update the database using the --update option:

# aide --update

After running a database update, to use the new database for future scans, always rename it to /var/lib/aide/aide.db.gz:

# mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz

That’s all for now! But take note of these important points:

  • One characteristic of most intrusion detection systems AIDE inclusive, is that they will not provide solutions to most security loop holes on a system. They however, assist in easing the the intrusion response process by helping system administrators examine any changes to system files/directories. So you should always be vigilant and keep updating your current security measures.
  • It it highly recommended to keep the newly created database, the configuration file and the AIDE binary in a secure location such as read-only media (possible if you install from source).
  • For additional security, consider signing the configuration and/or database.

For additional information and configurations, see its man page or check out the AIDE Homepage: http://aide.sourceforge.net/

A Shell Script to Send Email Alert When Memory Gets Low

A powerful aspect of Unix/Linux shell programs such as bash, is their amazing support for common programming constructs that enable you to make decisions, execute commands repeatedly, create new functions, and so much more. You can write commands in a file known as a shell script and execute them collectively.

This offers you a reliable and effective means of system administration. You can write scripts to automate tasks, for instance daily back ups, system updates etc; create new custom commands/utilities/tools and beyond. You can write scripts to help you keep up with what’s unfolding on a server.

One of the critical components of a server is memory (RAM), it greatly impacts on overall performance of a system.

In this article, we will share a small but useful shell script to send an alert email to one or more system administrator(s), if server memory is running low.


This is script is particularly useful for keeping an eye on Linux VPS (Virtual Private Servers) with small amount of memory, say of about 1GB (approximately 990MB).

Testing Environment Setup

  1. A CentOS/RHEL 7 production server with mailx utility installed with working postfix mail server.

This is how the alertmemory.sh script works: first it checks the free memory size, then determines if amount of free memory is less or equal to a specified size (100 MB for the purpose of this guide), used as a bench mark for the least acceptable free memory size.

If this condition is true, it will generate a list of the top 10 processes consuming server RAM and sends an alert email to specified email addresses.

Note: You will have to make a few changes to script (especially the mail sender utility, use the appropriate flags) to meet your Linux distributions requirements.

Shell Script to Check Server Memory

#!/bin/bash #######################################################################################
#Script Name :alertmemory.sh
#Description :send alert mail when server memory is running low
#Args : #Author :Aaron Kili Kisinga
#Email :[email protected]
#License : GNU GPL-3 #######################################################################################
## declare mail variables
##email subject subject="Server Memory Status Alert"
##sending mail as
from="[email protected]"
## sending mail to
to="[email protected]"
## send carbon copy to
also_to="[email protected]"
## get total free memory size in megabytes(MB) free=$(free -mt | grep Total | awk '{print $4}')
## check if free memory is less or equals to 100MB
if [[ "$free" -le 100 ]]; then
## get top processes consuming system memory and save to temporary file ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head >/tmp/top_proccesses_consuming_memory.txt
file=/tmp/top_proccesses_consuming_memory.txt
## send email if system memory is running low
echo -e "Warning, server memory is running low!\n\nFree memory: $free MB" | mailx -a "$file" -s "$subject" -r "$from" -c "$to" "$also_to"
fi
exit 0

After creating your script /etc/scripts/alertmemory.sh, make it executable and symlink to cron.hourly.

# chmod +x /etc/scripts/alertmemory.sh
# ln -s -t /etc/cron.hourly/alertmemory.sh /etc/scripts/alertmemory.sh

This means that the above script will be run after every 1 hour as long as the server is running.

Tip: You can test if it is working as intended, set the bench mark value a little high to easily trigger an email to be sent, and specify a small interval of about 5 minutes.

Then keep on checking from the command line using the free command provided in the script. Once you confirm that it is working, define the actual values you would like to use.

Below is a screenshot showing a sample alert email.

Linux Memory Email Alert

Linux Memory Email Alert

That’s all! In this article, we explained how to use shell script to send alert emails to system administrators in case server memory (RAM) is running low. You can share any thoughts relating to this topic, with us via the feedback form below.

4 Ways to Speed Up SSH Connections in Linux

SSH is the most popular and secure method for managing Linux servers remotely. One of the challenges with remote server management is connection speeds, especially when it comes to session creation between the remote and local machines.

There are several bottlenecks to this process, one scenario is when you are connecting to a remote server for the first time; it normally takes a few seconds to establish a session. However, when you try to start multiple connections in succession, this causes an overhead (combination of excess or indirect computation time, memory, bandwidth, or other related resources to carry out the operation).

In this article, we will share four useful tips on how to speed up remote SSH connections in Linux.

1. Force SSH Connection Over IPV4

OpenSSH supports both IPv4/IP6, but at times IPv6 connections tend to be slower. So you can consider forcing ssh connections over IPv4 only, using the syntax below:

# ssh -4 [email protected]


Alternatively, use the AddressFamily (specifies the address family to use when connecting) directive in your ssh configuration file /etc/ssh/ssh_config (global configuration) or ~/.ssh/config (user specific file).

The accepted values are “any”, “inet” for IPv4 only, or “inet6”.

$ vi ~.ssh/config 
Disable SSH Connections on ipv6

Disable SSH Connections on ipv6

Here is a useful starter guide on configuring user specific ssh configuration file:

  1. How to Configure Custom SSH Connections to Simplify Remote Access

Additionally, on the remote machine, you can also instruct the sshd daemon to consider connections over IPv4 by using the above directive in the /etc/ssh/sshd_config file.

2. Disable DNS Lookup On Remote Machine

By default, sshd daemon looks up the remote host name, and also checks that the resolved host name for the remote IP address maps back to the very same IP address. This can result into delays in connection establishment or session creation.

The UseDNS directive controls the above functionality; to disable it, search and uncomment it in the /etc/ssh/sshd_config file. If it’s not set, add it with the value no.

UseDNS no
Disable SSH DNS Lookup

Disable SSH DNS Lookup

3. Reuse SSH Connection

An ssh client program is used to establish connections to an sshd daemon accepting remote connections. You can reuse an already-established connection when creating a new ssh session and this can significantly speed up subsequent sessions.

You can enable this in your ~/.ssh/config file.

Host *
ControlMaster auto
ControlPath ~/.ssh/sockets/%[email protected]%h-%p
ControlPersist 600

The above configuration (Host *) will enable connection re-use for all remote servers you connect to using these directives:

  • ControlMaster – enables the sharing of multiple sessions over a single network connection.
  • ControlPath – defines a path to the control socket used for connection sharing.
  • ControlPersist – if used together with ControlMaster, tells ssh to keep the master connection open in the background (waiting for future client connections) once the initial client connection has been closed.
Reuse SSH Connections

Reuse SSH Connections

You can enable this for connections to a specific remote server, for instance:

Host server1
HostName www.example.com
IdentityFile ~/.ssh/webserver.pem
User username_here
ControlMaster auto
ControlPath ~/.ssh/sockets/%[email protected]%h-%p
ControlPersist 600

This way you only suffer the connection overhead for the first connection, and all subsequent connections will be much faster.

4. Use Specific SSH Authentication Method

Another way of speeding up ssh connections is to use a given authentication method for all ssh connections, and here we recommend configuring ssh passwordless login using ssh keygen in 5 easy steps.

Once that is done, use the PreferredAuthentications directive, within ssh_config files (global or user specific) above. This directive defines the order in which the client should try authentication methods (you can specify a command separated list to use more than one method).

PreferredAuthentications=publickey 
SSH Authentication Method

SSH Authentication Method

Optionally, use this syntax below from the command line.

# ssh -o "PreferredAuthentications=publickey" [email protected]

If you prefer password authentication which is deemed unsecure, use this.

# ssh -o "PreferredAuthentications=password" [email protected]

Finally, you need to restart your sshd daemon after making all the above changes.

# systemctl restart sshd #Systemd
# service sshd restart #SysVInit

For more information about the directives used here, see the ssh_config and sshd_config man pages.

# man ssh_config
# man sshd_config 

Also check out these useful guides for securing ssh on Linux systems:

  1. 5 Best Practices to Secure and Protect SSH Server
  2. How to Disconnect Inactive or Idle SSH Connections in Linux

That’s all for now! Do you have any tips/tricks for speeding up SSH connections. We would love to hear of other ways of doing this. Use the comment form below to share with us.