original source :
참고사항) https://www.tecmint.com/setup-ufw-firewall-on-ubuntu-and-debian/



















pwd
netstat
top
type중에 탭은 자동완성
cd .. 는 상위 폴더로
cd ~ 는 home 디렉토리로
cd / 는 최상위 폴더
man
touch
w
who
ps aux
stdin 0
stdout 1
stderr 2
cat
uniq
grep 검색어 ./*
cat 검색대상화일이름 | uniq 검색대상화일에서 고유한 부분만 되돌린다
cat 검색대상화일이름 | grep 검색어 검색대상화일에서 검색어가 있는 부분 되돌림
cat 화일이름 | cut -d: -f2 화일을 읽고 :를 구분자로 사용한다음 구분자를 기준으로 두번째 내용 되돌림
cat 화일이름 | sort -bf 화일내용을 읽고 첫번째 field를 기준으로 정렬해서 되돌림
cat /etc/issue
.
.
.
.
.
.
.
.
.
.
.
linux 정보 찾기 사이트
http://unix.stackexchange.com/
.
.
.
/etc/apache2/apache.conf 아파치 conf 파일 위치
apache2ctl configtest 아파치 conf 파일 문법 체크
.
sudo apachectl -k restart
tail -n 5 /var/log/apache2/error.log 아파치 세팅 상황출력
.
sudo rm /usr/lib/apache2/modules/mod_wsgi.so 아파치에서 mod_wsgi삭제
This is going to be beyond the scope of the tutorial. However here is how you could install a specific version if needed:
First, install the required libraries:
Copy Copy
Then choose the specific Python from here:
https://www.python.org/ftp/python/
After that go to the /opt
directory and download the archive of the specific version:
Copy Copy
Extract the archive:
Copy Copy
Then cd
into the directory:
Copy Copy
And finally, compile the new version:
Copy Copy
Finally you can create a symlink for that specific Python version so that you could use the binary from anywhere:
Copy Copy
Then you could check if the python3.9
version is available:
Copy Copy
Hope that this helps.
Regards,
Bobby
virtualenv --python=/usr/bin/python2.6 <path/to/new/virtualenv/>
– linux에서 id {사용자명} 하면 어느 그룹에 속해 있는지 등등 사용자 정보 나온다.
– mysql 기본 문법 https://www.educba.com/mysql-commands/
https://medium.com/@mandeepkaur1/a-list-of-mysql-commands-c4d0d244aa5c
– 에러 Access denied for user ‘root’@’localhost’ 처리 방법 https://stackoverflow.com/questions/36864206/sqlstatehy000-1698-access-denied-for-user-rootlocalhost
– mysql 사용자 만들기 https://dev.mysql.com/doc/refman/8.0/en/caching-sha2-pluggable-authentication.html
– 모든 권한 가진 사용자 만들기 https://stackoverflow.com/questions/50177216/how-to-grant-all-privileges-to-root-user-in-mysql-8-0
The Apache web server is among the most popular web servers in the world. It’s well documented, has an active community of users, and has been in wide use for much of the history of the web, which makes it a great choice for hosting a website.
Start by updating the package manager cache. If this is the first time you’re using sudo
within this session, you’ll be prompted to provide your user’s password to confirm you have the right privileges to manage system packages with apt
.
Copy
Then, install Apache with:
Copy
You’ll also be prompted to confirm Apache’s installation by pressing Y
, then ENTER
.
Once the installation is finished, you’ll need to adjust your firewall settings to allow HTTP traffic. UFW has different application profiles that you can leverage for accomplishing that. To list all currently available UFW application profiles, you can run:
Copy
You’ll see output like this:
OutputAvailable applications:
Apache
Apache Full
Apache Secure
OpenSSH
Here’s what each of these profiles mean:
80
(normal, unencrypted web traffic).443
(TLS/SSL encrypted traffic).For now, it’s best to allow only connections on port 80
, since this is a fresh Apache installation and you still don’t have a TLS/SSL certificate configured to allow for HTTPS traffic on your server.
To only allow traffic on port 80
, use the Apache
profile:
Copy
You can verify the change with:
Copy
OutputStatus: active
To Action From
-- ------ ----
OpenSSH ALLOW Anywhere
Apache ALLOW Anywhere
OpenSSH (v6) ALLOW Anywhere (v6)
Apache (v6) ALLOW Anywhere (v6)
Traffic on port 80
is now allowed through the firewall.
You can do a spot check right away to verify that everything went as planned by visiting your server’s public IP address in your web browser (see the note under the next heading to find out what your public IP address is if you do not have this information already):
http://your_server_ip
You’ll see the default Ubuntu 20.04 Apache web page, which is there for informational and testing purposes. It should look something like this:
If you see this page, then your web server is now correctly installed and accessible through your firewall.
How To Find your Server’s Public IP Address
If you do not know what your server’s public IP address is, there are a number of ways you can find it. Usually, this is the address you use to connect to your server through SSH.
There are a few different ways to do this from the command line. First, you could use the iproute2
tools to get your IP address by typing this:
Copy
This will give you two or three lines back. They are all correct addresses, but your computer may only be able to use one of them, so feel free to try each one.
An alternative method is to use the curl
utility to contact an outside party to tell you how it sees your server. This is done by asking a specific server what your IP address is:
Copy
Regardless of the method you use to get your IP address, type it into your web browser’s address bar to view the default Apache page.
Now that you have a web server up and running, you need to install the database system to be able to store and manage data for your site. MySQL is a popular database management system used within PHP environments.
Again, use apt
to acquire and install this software:
Copy
When prompted, confirm installation by typing Y
, and then ENTER
.
When the installation is finished, it’s recommended that you run a security script that comes pre-installed with MySQL. This script will remove some insecure default settings and lock down access to your database system. Start the interactive script by running:
Copy
This will ask if you want to configure the VALIDATE PASSWORD PLUGIN
.
Note: Enabling this feature is something of a judgment call. If enabled, passwords which don’t match the specified criteria will be rejected by MySQL with an error. It is safe to leave validation disabled, but you should always use strong, unique passwords for database credentials.
Answer Y
for yes, or anything else to continue without enabling.
VALIDATE PASSWORD PLUGIN can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD plugin?
Press y|Y for Yes, any other key for No:
If you answer “yes”, you’ll be asked to select a level of password validation. Keep in mind that if you enter 2
for the strongest level, you will receive errors when attempting to set any password which does not contain numbers, upper and lowercase letters, and special characters, or which is based on common dictionary words.
There are three levels of password validation policy:
LOW Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary file
Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 1
Regardless of whether you chose to set up the VALIDATE PASSWORD PLUGIN
, your server will next ask you to select and confirm a password for the MySQL root user. This is not to be confused with the system root. The database root user is an administrative user with full privileges over the database system. Even though the default authentication method for the MySQL root user dispenses the use of a password, even when one is set, you should define a strong password here as an additional safety measure. We’ll talk about this in a moment.
If you enabled password validation, you’ll be shown the password strength for the root password you just entered and your server will ask if you want to continue with that password. If you are happy with your current password, enter Y
for “yes” at the prompt:
Estimated strength of the password: 100
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y
For the rest of the questions, press Y
and hit the ENTER
key at each prompt. 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.
When you’re finished, test if you’re able to log in to the MySQL console by typing:
Copy
This will connect to the MySQL server as the administrative database user root, which is inferred by the use of sudo
when running this command. You should see output like this:
OutputWelcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 22
Server version: 8.0.19-0ubuntu5 (Ubuntu)
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.
mysql>
To exit the MySQL console, type:
Copy
Notice that you didn’t need to provide a password to connect as the root user, even though you have defined one when running the mysql_secure_installation
script. That is because the default authentication method for the administrative MySQL user is unix_socket
instead of password
. Even though this might look like a security concern at first, it makes the database server more secure because the only users allowed to log in as the root MySQL user are the system users with sudo privileges connecting from the console or through an application running with the same privileges. In practical terms, that means you won’t be able to use the administrative database root user to connect from your PHP application. Setting a password for the root MySQL account works as a safeguard, in case the default authentication method is changed from unix_socket
to password
.
For increased security, it’s best to have dedicated user accounts with less expansive privileges set up for every database, especially if you plan on having multiple databases hosted on your server.
Note: At the time of this writing, the native MySQL PHP library mysqlnd
doesn’t support caching_sha2_authentication
, the default authentication method for MySQL 8. For that reason, when creating database users for PHP applications on MySQL 8, you’ll need to make sure they’re configured to use mysql_native_password
instead. We’ll demonstrate how to do that in Step 6.
Your MySQL server is now installed and secured. Next, we’ll install PHP, the final component in the LAMP stack.
You have Apache installed to serve your content and MySQL installed to store and manage your data. PHP is the component of our setup that will process code to display dynamic content to the final user. In addition to the php
package, you’ll need php-mysql
, a PHP module that allows PHP to communicate with MySQL-based databases. You’ll also need libapache2-mod-php
to enable Apache to handle PHP files. Core PHP packages will automatically be installed as dependencies.
To install these packages, run:
Copy
Once the installation is finished, you can run the following command to confirm your PHP version:
Copy
OutputPHP 7.4.3 (cli) (built: Jul 5 2021 15:13:35) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Zend OPcache v7.4.3, Copyright (c), by Zend Technologies
At this point, your LAMP stack is fully operational, but before you can test your setup with a PHP script, it’s best to set up a proper Apache Virtual Host to hold your website’s files and folders. We’ll do that in the next step.
When using the Apache web server, you can create virtual hosts (similar to server blocks in Nginx) to encapsulate configuration details and host more than one domain from a single server. In this guide, we’ll set up a domain called your_domain, but you should replace this with your own domain name.
Note: In case you are using DigitalOcean as DNS hosting provider, you can check our product docs for detailed instructions on how to set up a new domain name and point it to your server.
Apache on Ubuntu 20.04 has one server block enabled by default that is configured to serve documents from the /var/www/html
directory. While this works well for a single site, it can become unwieldy if you are hosting multiple sites. Instead of modifying /var/www/html
, we’ll create a directory structure within /var/www
for the your_domain site, leaving /var/www/html
in place as the default directory to be served if a client request doesn’t match any other sites.
Create the directory for your_domain as follows:
Copy
Next, assign ownership of the directory with the $USER
environment variable, which will reference your current system user:
Copy
Then, open a new configuration file in Apache’s sites-available
directory using your preferred command-line editor. Here, we’ll use nano
:
Copy
This will create a new blank file. Paste in the following bare-bones configuration:
/etc/apache2/sites-available/your_domain.conf
<VirtualHost *:80>
ServerName your_domain
ServerAlias www.your_domain
ServerAdmin webmaster@localhost
DocumentRoot /var/www/your_domain
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Copy
Save and close the file when you’re done. If you’re using nano
, you can do that by pressing CTRL+X
, then Y
and ENTER
.
With this VirtualHost
configuration, we’re telling Apache to serve your_domain
using /var/www/your_domain
as the web root directory. If you’d like to test Apache without a domain name, you can remove or comment out the options ServerName
and ServerAlias
by adding a #
character in the beginning of each option’s lines.
You can now use a2ensite
to enable the new virtual host:
Copy
You might want to disable the default website that comes installed with Apache. This is required if you’re not using a custom domain name, because in this case Apache’s default configuration would overwrite your virtual host. To disable Apache’s default website, type:
Copy
To make sure your configuration file doesn’t contain syntax errors, run:
Copy
Finally, reload Apache so these changes take effect:
Copy
Your new website is now active, but the web root /var/www/your_domain
is still empty. Create an index.html
file in that location so that we can test that the virtual host works as expected:
Copy
Include the following content in this file:
/var/www/your_domain/index.html
<html>
<head>
<title>your_domain website</title>
</head>
<body>
<h1>Hello World!</h1>
<p>This is the landing page of <strong>your_domain</strong>.</p>
</body>
</html>
Copy
Now go to your browser and access your server’s domain name or IP address once again:
http://server_domain_or_IP
You’ll see a page like this:
If you see this page, it means your Apache virtual host is working as expected.
You can leave this file in place as a temporary landing page for your application until you set up an index.php
file to replace it. Once you do that, remember to remove or rename the index.html
file from your document root, as it would take precedence over an index.php
file by default.
A Note About
DirectoryIndex
on Apache
With the default DirectoryIndex
settings on Apache, a file named index.html
will always take precedence over an index.php
file. This is useful for setting up maintenance pages in PHP applications, by creating a temporary index.html
file containing an informative message to visitors. Because this page will take precedence over the index.php
page, it will then become the landing page for the application. Once maintenance is over, the index.html
is renamed or removed from the document root, bringing back the regular application page.
In case you want to change this behavior, you’ll need to edit the /etc/apache2/mods-enabled/dir.conf
file and modify the order in which the index.php
file is listed within the DirectoryIndex
directive:
Copy/etc/apache2/mods-enabled/dir.conf
<IfModule mod_dir.c>
DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
</IfModule>
Copy
After saving and closing the file, you’ll need to reload Apache so the changes take effect:
Copy
In the next step, we’ll create a PHP script to test that PHP is correctly installed and configured on your server.
Now that you have a custom location to host your website’s files and folders, we’ll create a PHP test script to confirm that Apache is able to handle and process requests for PHP files.
Create a new file named info.php
inside your custom web root folder:
Copy
This will open a blank file. Add the following text, which is valid PHP code, inside the file:
/var/www/your_domain/info.php
<?php
phpinfo();
Copy
When you are finished, save and close the file.
To test this script, go to your web browser and access your server’s domain name or IP address, followed by the script name, which in this case is info.php
:
http://server_domain_or_IP/info.php
You’ll see a page similar to this:
This page provides information about your server from the perspective of PHP. It is useful for debugging and to ensure that your settings are being applied correctly.
If you can see this page in your browser, then your PHP installation is working as expected.
After checking the relevant information about your PHP server through that page, it’s best to remove the file you created as it contains sensitive information about your PHP environment and your Ubuntu server. You can use rm
to do so:
Copy
You can always recreate this page if you need to access the information again later.
If you want to test whether PHP is able to connect to MySQL and execute database queries, you can create a test table with dummy data and query for its contents from a PHP script. Before we can do that, we need to create a test database and a new MySQL user properly configured to access it.
At the time of this writing, the native MySQL PHP library mysqlnd
doesn’t support caching_sha2_authentication
, the default authentication method for MySQL 8. We’ll need to create a new user with the mysql_native_password
authentication method in order to be able to connect to the MySQL database from PHP.
We’ll create a database named example_database and a user named example_user, but you can replace these names with different values.
First, connect to the MySQL console using the root account:
Copy
To create a new database, run the following command from your MySQL console:
Copy
Now you can create a new user and grant them full privileges on the custom database you’ve just created.
The following command creates a new user named example_user
, using mysql_native_password
as default authentication method. We’re defining this user’s password as password
, but you should replace this value with a secure password of your own choosing.
Copy
Now we need to give this user permission over the example_database
database:
Copy
This will give the example_user user full privileges over the example_database database, while preventing this user from creating or modifying other databases on your server.
Now exit the MySQL shell with:
Copy
You can test if the new user has the proper permissions by logging in to the MySQL console again, this time using the custom user credentials:
Copy
Notice the -p
flag in this command, which will prompt you for the password used when creating the example_user user. After logging in to the MySQL console, confirm that you have access to the example_database database:
Copy
This will give you the following output:
Output+--------------------+
| Database |
+--------------------+
| example_database |
| information_schema |
+--------------------+
2 rows in set (0.000 sec)
Next, we’ll create a test table named todo_list. From the MySQL console, run the following statement:
Copy
Insert a few rows of content in the test table. You might want to repeat the next command a few times, using different values:
Copy
To confirm that the data was successfully saved to your table, run:
Copy
You’ll see the following output:
Output+---------+--------------------------+
| item_id | content |
+---------+--------------------------+
| 1 | My first important item |
| 2 | My second important item |
| 3 | My third important item |
| 4 | and this one more thing |
+---------+--------------------------+
4 rows in set (0.000 sec)
After confirming that you have valid data in your test table, you can exit the MySQL console:
Copy
Now you can create the PHP script that will connect to MySQL and query for your content. Create a new PHP file in your custom web root directory using your preferred editor. We’ll use nano
for that:
Copy
The following PHP script connects to the MySQL database and queries for the content of the todo_list table, exhibiting the results in a list. If there’s a problem with the database connection, it will throw an exception.
Copy this content into your todo_list.php
script:
/var/www/your_domain/todo_list.php
<?php
$user = "example_user";
$password = "password";
$database = "example_database";
$table = "todo_list";
try {
$db = new PDO("mysql:host=localhost;dbname=$database", $user, $password);
echo "<h2>TODO</h2><ol>";
foreach($db->query("SELECT content FROM $table") as $row) {
echo "<li>" . $row['content'] . "</li>";
}
echo "</ol>";
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
Copy
Save and close the file when you’re done editing.
You can now access this page in your web browser by visiting the domain name or public IP address configured for your website, followed by /todo_list.php
:
http://your_domain_or_IP/todo_list.php
You should see a page like this, showing the content you’ve inserted in your test table:
That means your PHP environment is ready to connect and interact with your MySQL server.
.
.
.
======================================================
======================================================
You can use APT to install phpMyAdmin from the default Ubuntu repositories.
As your non-root sudo user, update your server’s package index:
Copy
Following that you can install the phpmyadmin
package. Along with this package, the official documentation also recommends that you install a few PHP extensions onto your server to enable certain functionalities and improve performance.
If you followed the prerequisite LAMP stack tutorial, several of these modules will have been installed along with the php
package. However, it’s recommended that you also install these packages:
php-mbstring
: A module for managing non-ASCII strings and convert strings to different encodingsphp-zip
: This extension supports uploading .zip
files to phpMyAdminphp-gd
: Enables support for the GD Graphics Libraryphp-json
: Provides PHP with support for JSON serializationphp-curl
: Allows PHP to interact with different kinds of servers using different protocolsRun the following command to install these packages onto your system. Please note, though, that the installation process requires you to make some choices to configure phpMyAdmin correctly. We’ll walk through these options shortly:
Copy
Here are the options you should choose when prompted in order to configure your installation correctly:
apache2
Warning: When the prompt appears, “apache2” is highlighted, but not selected. If you do not hit SPACE
to select Apache, the installer will not move the necessary files during installation. Hit SPACE
, TAB
, and then ENTER
to select Apache.Yes
when asked whether to use dbconfig-common
to set up the databaseNote: Assuming you installed MySQL by following Step 2 of the prerequisite LAMP stack tutorial, you may have decided to enable the Validate Password plugin. As of this writing, enabling this component will trigger an error when you attempt to set a password for the phpmyadmin user:
To resolve this, select the abort option to stop the installation process. Then, open up your MySQL prompt:
Copy
Or, if you enabled password authentication for the root MySQL user, run this command and then enter your password when prompted:
Copy
From the prompt, run the following command to disable the Validate Password component. Note that this won’t actually uninstall it, but just stop the component from being loaded on your MySQL server:
Copy
Following that, you can close the MySQL client:
Copy
Then try installing the phpmyadmin
package again and it will work as expected:
Copy
Once phpMyAdmin is installed, you can open the MySQL prompt once again with sudo mysql
or mysql -u root -p
and then run the following command to re-enable the Validate Password component:
Copy
The installation process adds the phpMyAdmin Apache configuration file into the /etc/apache2/conf-enabled/
directory, where it is read automatically. To finish configuring Apache and PHP to work with phpMyAdmin, the only remaining task in this section of the tutorial is to is explicitly enable the mbstring
PHP extension, which you can do by typing:
Copy
Afterwards, restart Apache for your changes to be recognized:
Copy
phpMyAdmin is now installed and configured to work with Apache. However, before you can log in and begin interacting with your MySQL databases, you will need to ensure that your MySQL users have the privileges required for interacting with the program.
When you installed phpMyAdmin onto your server, it automatically created a database user called phpmyadmin which performs certain underlying processes for the program. Rather than logging in as this user with the administrative password you set during installation, it’s recommended that you log in as either your root MySQL user or as a user dedicated to managing databases through the phpMyAdmin interface.
Configuring Password Access for the MySQL Root Account
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 — like phpMyAdmin — to access the user.
In order to log in to phpMyAdmin as your root MySQL user, you will need to switch its authentication method from auth_socket
to one that makes use of a password, if you haven’t already done so. To do this, open up the MySQL prompt from your terminal:
Copy
Next, check which authentication method each of your MySQL user accounts use with the following command:
Copy
Output+------------------+-------------------------------------------+-----------------------+-----------+
| user | authentication_string | plugin | host |
+------------------+-------------------------------------------+-----------------------+-----------+
| root | | auth_socket | localhost |
| mysql.session | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | caching_sha2_password | localhost |
| mysql.sys | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | caching_sha2_password | localhost |
| debian-sys-maint | *8486437DE5F65ADC4A4B001CA591363B64746D4C | caching_sha2_password | localhost |
| phpmyadmin | *5FD2B7524254B7F81B32873B1EA6D681503A5CA9 | caching_sha2_password | localhost |
+------------------+-------------------------------------------+-----------------------+-----------+
5 rows in set (0.00 sec)
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:
Copy
Note: The previous ALTER USER
statement sets the root MySQL user to authenticate with the caching_sha2_password
plugin. Per the official MySQL documentation, caching_sha2_password
is MySQL’s preferred authentication plugin, as it provides more secure password encryption than the older, but still widely used, mysql_native_password
.
However, some versions of PHP don’t work reliably with caching_sha2_password
. PHP has reported that this issue was fixed as of PHP 7.4, but if you encounter an error when trying to log in to phpMyAdmin later on, you may want to set root to authenticate with mysql_native_password
instead:
Copy
Then, check the authentication methods employed by each of your users again to confirm that root no longer authenticates using the auth_socket
plugin:
Copy
Output+------------------+-------------------------------------------+-----------------------+-----------+
| user | authentication_string | plugin | host |
+------------------+-------------------------------------------+-----------------------+-----------+
| root | *DE06E242B88EFB1FE4B5083587C260BACB2A6158 | caching_sha2_password | localhost |
| mysql.session | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | caching_sha2_password | localhost |
| mysql.sys | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | caching_sha2_password | localhost |
| debian-sys-maint | *8486437DE5F65ADC4A4B001CA591363B64746D4C | caching_sha2_password | localhost |
| phpmyadmin | *5FD2B7524254B7F81B32873B1EA6D681503A5CA9 | caching_sha2_password | localhost |
+------------------+-------------------------------------------+-----------------------+-----------+
5 rows in set (0.00 sec)
You can see from this output that the root user will authenticate using a password. You can now log in to the phpMyAdmin interface as your root user with the password you’ve set for it here.
Configuring Password Access for a Dedicated MySQL User
Alternatively, some may find that it better suits their workflow to connect to phpMyAdmin with a dedicated user. To do this, open up the MySQL shell once again:
Copy
If you have password authentication enabled for your root user, as described in the previous section, you will need to run the following command and enter your password when prompted in order to connect:
Copy
From there, create a new user and give it a strong password:
Copy
Note: Again, depending on what version of PHP you have installed, you may want to set your new user to authenticate with mysql_native_password
instead of caching_sha2_password
:
Copy
Then, grant your new user 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:
Copy
Following that, exit the MySQL shell:
Copy
You can now access the web interface by visiting your server’s domain name or public IP address followed by /phpmyadmin
:
https://your_domain_or_IP/phpmyadmin
Log in to the interface, either as root or with the new username and password you just configured.
When you log in, you’ll see the user interface, which will look something like this:
Now that you’re able to connect and interact with phpMyAdmin, all that’s left to do is harden your system’s security to protect it from attackers.
Because of its ubiquity, phpMyAdmin is a popular target for attackers, and you should take extra care to prevent unauthorized access. One way of doing this is to place a gateway in front of the entire application by using Apache’s built-in .htaccess
authentication and authorization functionalities.
To do this, you must first enable the use of .htaccess
file overrides by editing your phpMyAdmin installation’s Apache configuration file.
Use your preferred text editor to edit the phpmyadmin.conf
file that has been placed in your Apache configuration directory. Here, we’ll use nano
:
Copy
Add an AllowOverride All
directive within the <Directory /usr/share/phpmyadmin>
section of the configuration file, like this:
/etc/apache2/conf-available/phpmyadmin.conf
<Directory /usr/share/phpmyadmin>
Options SymLinksIfOwnerMatch
DirectoryIndex index.php
AllowOverride All
. . .
Copy
When you have added this line, save and close the file. If you used nano
to edit the file, do so by pressing CTRL + X
, Y
, and then ENTER
.
To implement the changes you made, restart Apache:
Copy
Now that you have enabled the use of .htaccess
files for your application, you need to create one to actually implement some security.
In order for this to be successful, the file must be created within the application directory. You can create the necessary file and open it in your text editor with root privileges by typing:
Copy
Within this file, enter the following information:
/usr/share/phpmyadmin/.htaccess
AuthType Basic
AuthName "Restricted Files"
AuthUserFile /etc/phpmyadmin/.htpasswd
Require valid-user
Copy
Here is what each of these lines mean:
AuthType Basic
: This line specifies the authentication type that you are implementing. This type will implement password authentication using a password file.AuthName
: This sets the message for the authentication dialog box. You should keep this generic so that unauthorized users won’t gain any information about what is being protected.AuthUserFile
: This sets the location of the password file that will be used for authentication. This should be outside of the directories that are being served. We will create this file shortly.Require valid-user
: This specifies that only authenticated users should be given access to this resource. This is what actually stops unauthorized users from entering.When you are finished, save and close the file.
The location that you selected for your password file was /etc/phpmyadmin/.htpasswd
. You can now create this file and pass it an initial user with the htpasswd
utility:
Copy
You will be prompted to select and confirm a password for the user you are creating. Afterwards, the file is created with the hashed password that you entered.
If you want to enter an additional user, you need to do so without the -c
flag, like this:
Copy
Then restart Apache to put .htaccess
authentication into effect:
Copy
Now, when you access your phpMyAdmin subdirectory, you will be prompted for the additional account name and password that you just configured:
https://domain_name_or_IP/phpmyadmin
After entering the Apache authentication, you’ll be taken to the regular phpMyAdmin authentication page to enter your MySQL credentials. By adding an extra set of non-MySQL credentials, you’re providing your database with an additional layer of security. This is desirable, since phpMyAdmin has been vulnerable to security threats in the past.
.
.
.
.
========================================================
========================================================
On Ubuntu 20.04, you can install MySQL using the APT package repository. At the time of this writing, the version of MySQL available in the default Ubuntu repository is version 8.0.27.
To install it, update the package index on your server if you’ve not done so recently:
Copy
Then install the mysql-server
package:
Copy
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.
For fresh installations of MySQL, you’ll want to run the DBMS’s included security script. This script changes some of the less secure default options for things like remote root logins and sample users.
Run the security script with sudo
:
Copy
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 password strength of new MySQL users before deeming them valid.
If you elect to set up the Validate Password Plugin, any MySQL user you create that authenticates with a password will be required to have a password that satisfies the policy you select. The strongest policy level — which you can select by entering 2
— will require passwords to be at least eight characters long and include a mix of uppercase, lowercase, numeric, and special characters:
OutputSecuring the MySQL server deployment.
Connecting to MySQL using a blank password.
VALIDATE PASSWORD COMPONENT can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD component?
Press y|Y for Yes, any other key for No: Y
There are three levels of password validation policy:
LOW Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary file
Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG:
2
Regardless of whether you choose to set up the Validate Password Plugin, the next prompt will be to set a password for the MySQL root user. Enter and then confirm a secure password of your choice:
OutputPlease set the password for root here.
New password:
Re-enter new password:
Note that even though you’ve set a password for the root MySQL user, this user is not currently configured to authenticate with a password when connecting to the MySQL shell.
If you used the Validate Password Plugin, you’ll receive feedback on the strength of your new password. Then the script will ask if you want to continue with the password you just entered or if you want to enter a new one. Assuming you’re satisfied with the strength of the password you just entered, enter Y
to continue the script:
OutputEstimated strength of the password: 100
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : Y
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.
Once the script completes, your MySQL installation will be secured. You can now move on to creating a dedicated database user with the MySQL client.
Upon installation, MySQL creates a root user account which you can use to manage your database. This user has full privileges over the MySQL server, meaning it has complete control over every database, table, user, and so on. Because of this, it’s best to avoid using this account outside of administrative functions. This step outlines how to use the root MySQL user to create a new user account and grant it 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 plugin requires that the name of the operating system user that invokes the MySQL client matches the name of the MySQL user specified in the command, so you must invoke mysql
with sudo
privileges to gain access to the root MySQL user:
Copy
Note: If you installed MySQL with another tutorial and enabled password authentication for root, 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:
Copy
Once you have access to the MySQL prompt, you can create a new user with a CREATE USER
statement. These follow this general syntax:
Copy
After CREATE USER
, you specify a username. This is immediately followed by an @
sign and then the hostname from which this user will connect. If you only plan to access this user locally from your Ubuntu server, you can specify localhost
. Wrapping both the username and host in single quotes isn’t always necessary, but doing so can help to prevent errors.
You have several options when it comes to choosing your user’s authentication plugin. The auth_socket
plugin mentioned previously can be convenient, as it provides strong security without requiring valid users to enter a password to access the database. But it also prevents remote connections, which can complicate things when external programs need to interact with MySQL.
As an alternative, you can leave out the WITH authentication_plugin
portion of the syntax entirely to have the user authenticate with MySQL’s default plugin, caching_sha2_password
. The MySQL documentation recommends this plugin for users who want to log in with a password due to its strong security features.
Run the following command to create a user that authenticates with caching_sha2_password
. Be sure to change sammy
to your preferred username and password
to a strong password of your choosing:
Copy
Note: There is a known issue with some versions of PHP that causes problems with caching_sha2_password
. If you plan to use this database with a PHP application — phpMyAdmin, for example — you may want to create a user that will authenticate with the older, though still secure, mysql_native_password
plugin instead:
Copy
If you aren’t sure, you can always create a user that authenticates with caching_sha2_plugin
and then ALTER
it later on with this command:
Copy
After creating your new user, you can grant them the appropriate privileges. The general syntax for granting user privileges is as follows:
Copy
The PRIVILEGE
value in this example syntax defines what actions the user is allowed to perform on the specified database
and table
. You can grant multiple privileges to the same user in one command by separating each with a comma. You can also grant a user privileges globally by entering asterisks (*
) in place of the database and table names. In SQL, asterisks are special characters used to represent “all” databases or tables.
To illustrate, the following command grants a user global privileges to CREATE
, ALTER
, and DROP
databases, tables, and users, as well as the power to INSERT
, UPDATE
, and DELETE
data from any table on the server. It also grants the user the ability to query data with SELECT
, create foreign keys with the REFERENCES
keyword, and perform FLUSH
operations with the RELOAD
privilege. However, you should only grant users the permissions they need, so feel free to adjust your own user’s privileges as necessary.
You can find the full list of available privileges in the official MySQL documentation.
Run this GRANT
statement, replacing sammy
with your own MySQL user’s name, to grant these privileges to your user:
Copy
Note that this statement also includes WITH GRANT OPTION
. This will allow your MySQL user to grant any permissions that it has to other users on the system.
Warning: Some users may want to grant their MySQL user the ALL PRIVILEGES
privilege, which will provide them with broad superuser privileges akin to the root user’s privileges, like so:
Copy
Such broad privileges should not be granted lightly, as anyone with access to this MySQL user will have complete control over every database on the server.
Following this, it’s good practice to run the FLUSH PRIVILEGES
command. This will free up any memory that the server cached as a result of the preceding CREATE USER
and GRANT
statements:
Copy
Then you can exit the MySQL client:
Copy
In the future, to log in as your new MySQL user, you’d use a command like the following:
Copy
The -p
flag will cause the MySQL client to prompt you for your MySQL user’s password in order to authenticate.
Finally, let’s test the MySQL installation.
Regardless of how you installed it, MySQL should have started running automatically. To test this, check its status.
Copy
You’ll see output similar to the following:
Output● mysql.service - MySQL Community Server
Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2020-04-21 12:56:48 UTC; 6min ago
Main PID: 10382 (mysqld)
Status: "Server is operational"
Tasks: 39 (limit: 1137)
Memory: 370.0M
CGroup: /system.slice/mysql.service
└─10382 /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 as a MySQL user named sammy (-u sammy
), prompt for a password (-p
), and return the version. Be sure to change sammy
to the name of your dedicated MySQL user, and enter that user’s password when prompted:
Copy
You should see output similar to this:
Outputmysqladmin Ver 8.0.19-0ubuntu5 for Linux on x86_64 ((Ubuntu))
Copyright (c) 2000, 2020, 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 8.0.19-0ubuntu5
Protocol version 10
Connection Localhost via UNIX socket
UNIX socket /var/run/mysqld/mysqld.sock
Uptime: 10 min 44 sec
Threads: 2 Questions: 25 Slow queries: 0 Opens: 149 Flush tables: 3 Open tables: 69 Queries per second avg: 0.038
This means MySQL is up and running.