You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The sudo command provides a mechanism for granting administrator privileges, ordinarily only available to the root user, to normal users. This guide will show you the easiest way to create a new user with sudo access on Ubuntu, without having to modify your server's sudoers file. If you want to configure sudo for an existing user, simply skip to step 3.
Steps to Create a New Sudo User
Log in to your server as the root user.
ssh root@server_ip_address
Use the adduser command to add a new user to your system.
Be sure to replace username with the user that you want to create.
adduser username
Set and confirm the new user's password at the prompt. A strong password is highly recommended!
Set password prompts:Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
Follow the prompts to set the new user's information. It is fine to accept the defaults to leave all of this information blank.
User information prompts:Changing the user information for username
Enter the new value, or press ENTER for the default
Full Name []:
Room Number []:
Work Phone []:
Home Phone []:
Other []:
Is the information correct? [Y/n]
Use the usermod command to add the user to the sudo group.
usermod -aG sudo username
By default, on Ubuntu, members of the sudo group have sudo privileges.
Test sudo access on new user account
Use the su command to switch to the new user account.
su - username
As the new user, verify that you can use sudo by prepending "sudo" to the command that you want to run with superuser privileges.
sudo command_to_run
For example, you can list the contents of the /root directory, which is normally only accessible to the root user.
sudo ls -la /root
The first time you use sudo in a session, you will be prompted for the password of the user account. Enter the password to proceed.
Output:
[sudo] password for username:
If your user is in the proper group and you entered the password correctly, the command that you issued with sudo should run with root privileges.
MySQL is an open-source database management system, commonly installed as part of the popular LAMP (Linux, Apache, MySQL, PHP/Python/Perl) stack. It uses a relational database and SQL (Structured Query Language) to manage its data.
The short version of the installation is simple: update your package index, install the mysql-server package, and then run the included security script.
This tutorial will explain how to install MySQL version 5.7 on an Ubuntu 18.04 server. However, if you're looking to update an existing MySQL installation to version 5.7, you can read this MySQL 5.7 update guide instead.
Prerequisites
To follow this tutorial, you will need:
One Ubuntu 18.04 server set up by following this initial server setup guide, including a non-root user with sudo privileges and a firewall.
Step 1 — Installing MySQL
On Ubuntu 18.04, only the latest version of MySQL is included in the APT package repository by default. At the time of writing, that's MySQL 5.7
To install it, update the package index on your server with apt:
sudo apt update
Then install the default package:
sudo apt install mysql-server
This will install MySQL, but will not prompt you to set a password or make any other configuration changes. Because this leaves your installation of MySQL insecure, we will address this next.
Step 2 — Configuring MySQL
For fresh installations, you'll want to run the included security script. This changes some of the less secure default options for things like remote root logins and sample users. On older versions of MySQL, you needed to initialize the data directory manually as well, but this is done automatically now.
Run the security script:
sudo mysql_secure_installation
This will take you through a series of prompts where you can make some changes to your MySQL installation’s security options. The first prompt will ask whether you’d like to set up the Validate Password Plugin, which can be used to test the strength of your MySQL password. Regardless of your choice, the next prompt will be to set a password for the MySQL root user. Enter and then confirm a secure password of your choice.
From there, you can press Y and then ENTER to accept the defaults for all the subsequent questions. This will remove some anonymous users and the test database, disable remote root logins, and load these new rules so that MySQL immediately respects the changes you have made.
To initialize the MySQL data directory, you would use mysql_install_db for versions before 5.7.6, and mysqld --initialize for 5.7.6 and later. However, if you installed MySQL from the Debian distribution, as described in Step 1, the data directory was initialized automatically; you don't have to do anything. If you try running the command anyway, you'll see the following error:
Note that even though you’ve set a password for the root MySQL user, this user is not configured to authenticate with a password when connecting to the MySQL shell. If you’d like, you can adjust this setting by following Step 3.
Step 3 — (Optional) Adjusting User Authentication and Privileges
In Ubuntu systems running MySQL 5.7 (and later versions), the root MySQL user is set to authenticate using the auth_socket plugin by default rather than with a password. This allows for some greater security and usability in many cases, but it can also complicate things when you need to allow an external program (e.g., phpMyAdmin) to access the user.
In order to use a password to connect to MySQL as root, you will need to switch its authentication method from auth_socket to mysql_native_password. To do this, open up the MySQL prompt from your terminal:
sudo mysql
Next, check which authentication method each of your MySQL user accounts use with the following command:
SELECT user,authentication_string,plugin,host FROM mysql.user;
In this example, you can see that the root user does in fact authenticate using the auth_socket plugin. To configure the root account to authenticate with a password, run the following ALTER USER command. Be sure to change password to a strong password of your choosing, and note that this command will change the root password you set in Step 2:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
Then, run FLUSH PRIVILEGES which tells the server to reload the grant tables and put your new changes into effect:
FLUSH PRIVILEGES;
Check the authentication methods employed by each of your users again to confirm that root no longer authenticates using the auth_socket plugin:
SELECT user,authentication_string,plugin,host FROM mysql.user;
You can see in this example output that the root MySQL user now authenticates using a password. Once you confirm this on your own server, you can exit the MySQL shell:
exit
Alternatively, some may find that it better suits their workflow to connect to MySQL with a dedicated user. To create such a user, open up the MySQL shell once again:
sudo mysql
Note: If you have password authentication enabled for root, as described in the preceding paragraphs, you will need to use a different command to access the MySQL shell. The following will run your MySQL client with regular user privileges, and you will only gain administrator privileges within the database by authenticating:
mysql -u root -p
From there, create a new user and give it a strong password:
CREATE USER 'sammy'@'localhost' IDENTIFIED BY 'password';
Then, grant your new user the appropriate privileges. For example, you could grant the user privileges to all tables within the database, as well as the power to add, change, and remove user privileges, with this command:
GRANT ALL PRIVILEGES ON *.* TO 'sammy'@'localhost' WITH GRANT OPTION;
Note that, at this point, you do not need to run the FLUSH PRIVILEGES command again. This command is only needed when you modify the grant tables using statements like INSERT, UPDATE, or DELETE. Because you created a new user, instead of modifying an existing one, FLUSH PRIVILEGES is unnecessary here.
Following this, exit the MySQL shell:
exit
Finally, let's test the MySQL installation.
Step 4 — Testing MySQL
Regardless of how you installed it, MySQL should have started running automatically. To test this, check its status.
systemctl status mysql.service
You'll see output similar to the following:
Output
● mysql.service - MySQL Community Server
Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: en
Active: active (running) since Wed 2018-04-23 21:21:25 UTC; 30min ago
Main PID: 3754 (mysqld)
Tasks: 28
Memory: 142.3M
CPU: 1.994s
CGroup: /system.slice/mysql.service
└─3754 /usr/sbin/mysqld
If MySQL isn't running, you can start it with sudo systemctl start mysql.
For an additional check, you can try connecting to the database using the mysqladmin tool, which is a client that lets you run administrative commands. For example, this command says to connect to MySQL as root (-u root), prompt for a password (-p), and return the version.
sudo mysqladmin -p -u root version
You should see output similar to this:
Output
mysqladmin Ver 8.42 Distrib 5.7.21, for Linux on x86_64
Copyright (c) 2000, 2018, 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.
Server version 5.7.21-1ubuntu1
Protocol version 10
Connection Localhost via UNIX socket
UNIX socket /var/run/mysqld/mysqld.sock
Uptime: 30 min 54 sec
Threads: 1 Questions: 12 Slow queries: 0 Opens: 115 Flush tables: 1 Open tables: 34 Queries per second avg: 0.006
Now open the default server block with a text editor:
sudo vi /etc/nginx/sites-available/default
Replace the contents of the file with the following code block. Be sure to replace the the highlighted parts with the appropriate username and application name:
Save and exit. This configures Nginx as a reverse proxy, so HTTP requests get forwarded to the Unicorn application server via a Unix socket. Feel free to make any changes as you see fit.
Restart Nginx to put the changes into effect:
sudo service nginx restart
Now the production environment of your Rails application is accessible via your server's public IP address or FQDN. To access the Tasks controller that we created earlier, visit your application server in a web browser:
http://server_public_IP/tasks
You should see the same page that you saw the first time you tested your application, but now it's being served through Nginx and Unicorn.
A previous version of this tutorial was written by Justin Ellingwood
Introduction
Redis is an in-memory key-value store known for its flexibility, performance, and wide language support. This tutorial demonstrates how to install, configure, and secure Redis on an Ubuntu 18.04 server.
Prerequisites
To complete this guide, you will need access to an Ubuntu 18.04 server that has a non-root user with sudo privileges and a basic firewall configured. You can set this up by following our Initial Server Setup guide.
When you are ready to begin, log in to your Ubuntu 18.04 server as your sudo user and continue below.
Step 1 — Installing and Configuring Redis
In order to get the latest version of Redis, we will use apt to install it from the official Ubuntu repositories.
Update your local apt package cache and install Redis by typing:
sudo apt update
sudo apt install redis-server
This will download and install Redis and its dependencies. Following this, there is one important configuration change to make in the Redis configuration file, which was generated automatically during the installation.
Open this file with your preferred text editor:
sudo nano /etc/redis/redis.conf
Inside the file, find the supervised directive. This directive allows you to declare an init system to manage Redis as a service, providing you with more control over its operation. The supervised directive is set to no by default. Since you are running Ubuntu, which uses the systemd init system, change this to systemd:
/etc/redis/redis.conf
. . .
# If you run Redis from upstart or systemd, Redis can interact with your
# supervision tree. Options:
# supervised no - no supervision interaction
# supervised upstart - signal upstart by putting Redis into SIGSTOP mode
# supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET
# supervised auto - detect upstart or systemd method based on
# UPSTART_JOB or NOTIFY_SOCKET environment variables
# Note: these supervision methods only signal "process is ready."
# They do not enable continuous liveness pings back to your supervisor.
supervised systemd
. . .
That’s the only change you need to make to the Redis configuration file at this point, so save and close it when you are finished. Then, restart the Redis service to reflect the changes you made to the configuration file:
sudo systemctl restart redis.service
With that, you’ve installed and configured Redis and it’s running on your machine. Before you begin using it, though, it’s prudent to first check whether Redis is functioning correctly.
Step 2 — Testing Redis
As with any newly-installed software, it’s a good idea to ensure that Redis is functioning as expected before making any further changes to its configuration. We will go over a handful of ways to check that Redis is working correctly in this step.
Start by checking that the Redis service is running:
sudo systemctl status redis
If it is running without any errors, this command will produce output similar to the following:
Output● redis-server.service - Advanced key-value store
Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2018-06-27 18:48:52 UTC; 12s ago
Docs: http://redis.io/documentation,
man:redis-server(1)
Process: 2421 ExecStop=/bin/kill -s TERM $MAINPID (code=exited, status=0/SUCCESS)
Process: 2424 ExecStart=/usr/bin/redis-server /etc/redis/redis.conf (code=exited, status=0/SUCCESS)
Main PID: 2445 (redis-server)
Tasks: 4 (limit: 4704)
CGroup: /system.slice/redis-server.service
└─2445 /usr/bin/redis-server 127.0.0.1:6379
. . .
Here, you can see that Redis is running and is already enabled, meaning that it is set to start up every time the server boots.
Note: This setting is desirable for many common use cases of Redis. If, however, you prefer to start up Redis manually every time your server boots, you can configure this with the following command:
sudo systemctl disable redis
To test that Redis is functioning correctly, connect to the server using the command-line client:
redis-cli
In the prompt that follows, test connectivity with the ping command:
ping
Output:
PONG
This output confirms that the server connection is still alive. Next, check that you’re able to set keys by running:
set test "It's working!"
Output:
OK
Retrieve the value by typing:
get test
Assuming everything is working, you will be able to retrieve the value you stored:
Output:
"It's working!"
After confirming that you can fetch the value, exit the Redis prompt to get back to the shell:
exit
As a final test, we will check whether Redis is able to persist data even after it’s been stopped or restarted. To do this, first restart the Redis instance:
sudo systemctl restart redis
Then connect with the command-line client once again and confirm that your test value is still available:
redis-cli
get test
The value of your key should still be accessible:
Output:
"It's working!"
Exit out into the shell again when you are finished:
exit
With that, your Redis installation is fully operational and ready for you to use. However, some of its default configuration settings are insecure and provide malicious actors with opportunities to attack and gain access to your server and its data. The remaining steps in this tutorial cover methods for mitigating these vulnerabilities, as prescribed by the official Redis website. Although these steps are optional and Redis will still function if you choose not to follow them, it is strongly recommended that you complete them in order to harden your system’s security.
Step 3 — Binding to localhost
By default, Redis is only accessible from localhost. However, if you installed and configured Redis by following a different tutorial than this one, you might have updated the configuration file to allow connections from anywhere. This is not as secure as binding to localhost.
To correct this, open the Redis configuration file for editing:
sudo nano /etc/redis/redis.conf
Locate this line and make sure it is uncommented (remove the # if it exists):
/etc/redis/redis.conf
bind 127.0.0.1 ::1
Save and close the file when finished (press CTRL + X, Y, then ENTER).
Then, restart the service to ensure that systemd reads your changes:
sudo systemctl restart redis
To check that this change has gone into effect, run the following netstat command:
This output shows that the redis-server program is bound to localhost (127.0.0.1), reflecting the change you just made to the configuration file. If you see another IP address in that column (0.0.0.0, for example), then you should double check that you uncommented the correct line and restart the Redis service again.
Now that your Redis installation is only listening in on localhost, it will be more difficult for malicious actors to make requests or gain access to your server. However, Redis isn’t currently set to require users to authenticate themselves before making changes to its configuration or the data it holds. To remedy this, Redis allows you to require users to authenticate with a password before making changes via the Redis client (redis-cli).
Step 4 — Configuring a Redis Password
Configuring a Redis password enables one of its two built-in security features — the auth command, which requires clients to authenticate to access the database. The password is configured directly in Redis's configuration file, /etc/redis/redis.conf, so open that file again with your preferred editor:
sudo nano /etc/redis/redis.conf
Scroll to the SECURITY section and look for a commented directive that reads:
/etc/redis/redis.conf
# requirepass foobared
Uncomment it by removing the #, and change foobared to a secure password.
Note: Above the requirepass directive in the redis.conf file, there is a commented warning:
# Warning: since Redis is pretty fast an outside user can try up to
# 150k passwords per second against a good box. This means that you should
# use a very strong password otherwise it will be very easy to break.
#
Thus, it’s important that you specify a very strong and very long value as your password. Rather than make up a password yourself, you can use the openssl command to generate a random one, as in the following example. By piping the output of the first command to the second openssl command, as shown here, it will remove any line breaks produced by that the first command:
After setting the password, save and close the file, then restart Redis:
sudo systemctl restart redis.service
To test that the password works, access the Redis command line:
redis-cli
The following shows a sequence of commands used to test whether the Redis password works. The first command tries to set a key to a value before authentication:
set key1 10
That won't work because you didn’t authenticate, so Redis returns an error:
Output
(error) NOAUTH Authentication required.
The next command authenticates with the password specified in the Redis configuration file:
auth your_redis_password
Redis acknowledges:
Output:
OK
After that, running the previous command again will succeed:
set key1 10
Output:
OK
get key1 queries Redis for the value of the new key.
get key1
Output:
"10"
After confirming that you’re able to run commands in the Redis client after authenticating, you can exit the redis-cli:
quit
Next, we'll look at renaming Redis commands which, if entered by mistake or by a malicious actor, could cause serious damage to your machine.
Step 5 — Renaming Dangerous Commands
The other security feature built into Redis involves renaming or completely disabling certain commands that are considered dangerous.
When run by unauthorized users, such commands can be used to reconfigure, destroy, or otherwise wipe your data. Like the authentication password, renaming or disabling commands is configured in the same SECURITY section of the /etc/redis/redis.conf file.
Some of the commands that are considered dangerous include: FLUSHDB, FLUSHALL, KEYS, PEXPIRE, DEL, CONFIG, SHUTDOWN, BGREWRITEAOF, BGSAVE, SAVE, SPOP, SREM, RENAME, and DEBUG. This is not a comprehensive list, but renaming or disabling all of the commands in that list is a good starting point for enhancing your Redis server’s security.
Whether you should disable or rename a command depends on your specific needs or those of your site. If you know you will never use a command that could be abused, then you may disable it. Otherwise, it might be in your best interest to rename it.
To enable or disable Redis commands, open the configuration file once more:
sudo nano /etc/redis/redis.conf
Warning: The following steps showing how to disable and rename commands are examples. You should only choose to disable or rename the commands that make sense for you. You can review the full list of commands for yourself and determine how they might be misused at redis.io/commands.
To disable a command, simply rename it to an empty string (signified by a pair of quotation marks with no characters between them), as shown below:
/etc/redis/redis.conf
. . .
# It is also possible to completely kill a command by renaming it into
# an empty string:
#
rename-command FLUSHDB ""
rename-command FLUSHALL ""
rename-command DEBUG ""
. . .
To rename a command, give it another name as shown in the examples below. Renamed commands should be difficult for others to guess, but easy for you to remember:
After renaming a command, apply the change by restarting Redis:
sudo systemctl restart redis.service
To test the new command, enter the Redis command line:
redis-cli
Then, authenticate:
auth your_redis_password
Output:
OK
Let’s assume that you renamed the CONFIG command to ASC12_CONFIG, as in the preceding example. First, try using the original CONFIG command. It should fail, because you’ve renamed it:
config get requirepass
Output:
(error) ERR unknown command 'config'
Calling the renamed command, however, will be successful. It is not case-sensitive:
asc12_config get requirepass
Output
1) "requirepass"
2) "your_redis_password"
Finally, you can exit from redis-cli:
exit
Note that if you're already using the Redis command line and then restart Redis, you'll need to re-authenticate. Otherwise, you'll get this error if you type a command:
Output
NOAUTH Authentication required.
Regarding the practice of renaming commands, there's a cautionary statement at the end of the SECURITY section in /etc/redis/redis.conf which reads:
Please note that changing the name of commands that are logged into the AOF file or transmitted to slaves may cause problems.
Note:The Redis project chooses to use the terms “master” and “slave,” while DigitalOcean generally prefers the alternatives “primary” and “secondary.” In order to avoid confusion we’ve chosen to use the terms used in the Redis documentation here.
That means if the renamed command is not in the AOF file, or if it is but the AOF file has not been transmitted to slaves, then there should be no problem.
So, keep that in mind when you're trying to rename commands. The best time to rename a command is when you're not using AOF persistence, or right after installation, that is, before your Redis-using application has been deployed.
The commands are logged to the AOF and replicated to the slave the same way they are sent, so if you try to replay the AOF on an instance that doesn't have the same renaming, you may face inconsistencies as the command cannot be executed (same for slaves).
Thus, the best way to handle renaming in cases like that is to make sure that renamed commands are applied to all instances in master-slave installations.
An easy way to do this is to add it to your application's Gemfile. Open the Gemfile in your favorite editor (make sure you are in your application's root directory):
vi Gemfile
At the end of the file, add the Unicorn gem with this line:
gem 'unicorn'
Save and exit.
To install Unicorn, and any outstanding dependencies, run Bundler:
bundle
Unicorn is now installed, but we need to configure it.
Configure Unicorn
Let's add our Unicorn configuration to config/unicorn.rb. Open the file in a text editor:
vi config/unicorn.rb
Copy and paste this configuration into the file:
# set path to application
app_dir = File.expand_path("../..", __FILE__)
tmp_dir = "#{app_dir}/tmp"
working_directory app_dir
# Set unicorn options
worker_processes 2
preload_app true
timeout 30
# Set up socket location
listen "#{tmp_dir}/sockets/unicorn.sock", :backlog => 64
# Logging
stderr_path "#{app_dir}/log/unicorn.stderr.log"
stdout_path "#{app_dir}/log/unicorn.stdout.log"
# Set master PID location
pid "#{tmp_dir}/pids/unicorn.pid"
Save and exit. This configures Unicorn with the location of your application, and the location of its socket, logs, and PIDs. Feel free to modify the file, or add any other options that you require.
Create Unicorn Init Script
Let's create an init script so we can easily start and stop Unicorn, and ensure that it will start on boot.
Create a script and open it for editing with this command (replace the highlighted part with your application name, if you wish):
sudo vi /etc/init.d/unicorn
Copy and paste the following code block into it, and be sure to substitute USER and APP_NAME (highlighted) with the appropriate values:
#!/bin/sh
### BEGIN INIT INFO
# Provides: unicorn
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: starts the unicorn app server
# Description: starts unicorn using start-stop-daemon
### END INIT INFO
set -e
USAGE="Usage: $0 <start|stop|restart|upgrade|rotate|force-stop>"
# app settings
USER="deploy"
APP_NAME="appname"
APP_ROOT="/home/$USER/$APP_NAME"
ENV="production"
# environment settings
CMD="cd $APP_ROOT && bundle exec unicorn -c config/unicorn.rb -E $ENV -D"
PID="$APP_ROOT/tmp/pids/unicorn.pid"
OLD_PID="$PID.oldbin"
# make sure the app exists
cd $APP_ROOT || exit 1
sig () {
test -s "$PID" && kill -$1 `cat $PID`
}
oldsig () {
test -s $OLD_PID && kill -$1 `cat $OLD_PID`
}
case $1 in
start)
sig 0 && echo >&2 "Already running" && exit 0
echo "Starting $APP_NAME"
su - $USER -c "$CMD"
;;
stop)
echo "Stopping $APP_NAME"
sig QUIT && exit 0
echo >&2 "Not running"
;;
force-stop)
echo "Force stopping $APP_NAME"
sig TERM && exit 0
echo >&2 "Not running"
;;
restart|reload|upgrade)
sig USR2 && echo "reloaded $APP_NAME" && exit 0
echo >&2 "Couldn't reload, starting '$CMD' instead"
$CMD
;;
rotate)
sig USR1 && echo rotated logs OK && exit 0
echo >&2 "Couldn't rotate logs" && exit 1
;;
*)
echo >&2 $USAGE
exit 1
;;
esac
Save and exit. This will allow you to use service unicorn_appname to start and stop your Unicorn and your Rails application.
Update the script's permissions and enable Unicorn to start on boot:
Now your Rails application's production environment is running under Unicorn, and it's listening on the tmp/sockets/unicorn.sock socket. Before your application will be accessible to an outside user, you must set up the Nginx reverse proxy.