One place for hosting & domains

      phpMyAdmin

      How To Install and Secure phpMyAdmin with Nginx on an Ubuntu 20.04 Server


      Introduction

      When developing a website or web application, many users need the functionality of a database system like MySQL. However, interacting with the system solely from the MySQL command-line client requires familiarity with Structured Query Language — more commonly referred to as SQL — which can present a major hurdle for some users.

      phpMyAdmin was created to allow users to interact with MySQL through an intuitive web interface, running alongside a PHP development environment. This guide will walk you through installing phpMyAdmin on top of an Nginx server.

      Note: phpMyAdmin runs on a database server, handles database credentials, and allows users to execute SQL statements on the database. Combined with the fact that it’s a widely-deployed PHP application, this means that phpMyAdmin is frequently targeted for attack. If you install and configure phpMyAdmin without taking the proper steps to secure it from malicious actors, you run the risk of your data being lost or stolen.

      In addition to installing the application, this tutorial will go over several measures you can take to harden your phpMyAdmin installation’s security. It will also explain each measure in detail so that you can make informed decisions and protect your system.

      Prerequisites

      In order to complete this guide, you will need:

      Additionally, because phpMyAdmin handles authentication using MySQL credentials, we strongly recommend that you install an SSL/TLS certificate to enable encrypted traffic between server and client. If you do not have an existing domain configured with a valid certificate, follow this guide on securing Nginx with Let’s Encrypt on Ubuntu 20.04 to set this up.

      Warning: If you don’t have an SSL/TLS certificate installed on the server and you still want to proceed, please consider enforcing access via SSH Tunnels as explained in Step 5 of this guide.

      Once you have these prerequisites in place, you can begin following Step 1 of this guide.

      Step 1 — Installing phpMyAdmin

      You can install phpMyAdmin by using APT to download the phpmyadmin package from the default Ubuntu repositories.

      Begin by updating the server’s package index:

      Now you can install phpMyAdmin by running the following command:

      • sudo apt install phpmyadmin

      During the installation process, you will be prompted to choose a web server (either Apache or Lighttpd) to configure. phpMyAdmin can automatically make a number of configuration changes to ensure that it works correctly with either of these web servers upon installation. However, because you are using Nginx as a web server you shouldn’t choose either of these options. Instead, press TAB to highlight the <Ok> and then press ENTER to continue the installation process.

      Next, you’ll be prompted whether to use dbconfig-common for configuring the application database. Select <Yes>. This will set up the internal database and administrative user for phpMyAdmin. You will be asked to define a new password for the phpmyadmin MySQL user, but because this isn’t a password you need to remember you can leave it blank and let phpMyAdmin randomly create a password.

      Note: 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 the phpMyAdmin installation process attempts to set a password for the phpmyadmin user:

      phpMyAdmin password validation error

      To resolve this, select the abort option to stop the installation process. Then, open up your MySQL prompt:

      Or, if you enabled password authentication for the root MySQL user, run this command and then enter your password when prompted:

      From the MySQL 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:

      • UNINSTALL COMPONENT "file://component_validate_password";

      Following that, you can close the MySQL client:

      Then try installing the phpmyadmin package again and it will work as expected:

      • sudo apt install phpmyadmin

      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:

      • INSTALL COMPONENT "file://component_validate_password";

      Once the apt install command completes, phpMyAdmin will be fully installed. However, for the Nginx web server to find and serve the phpMyAdmin files correctly, you’ll need to create a symbolic link from the installation files to Nginx’s document root directory. If you followed the prerequisite LEMP stack tutorial, your Nginx installation’s document root is /var/www/your_domain/

      • sudo ln -s /usr/share/phpmyadmin /var/www/your_domain/phpmyadmin

      Your phpMyAdmin installation is now operational. To access the interface, go to your server’s domain name or public IP address followed by /phpmyadmin in your web browser:

      https://server_domain_or_IP/phpmyadmin
      

      phpMyAdmin login screen

      As mentioned before, phpMyAdmin handles authentication using MySQL credentials. This means that to log into phpMyAdmin, you use the same username and password you would normally use to connect to the database using the command line or with an API. If you need help creating MySQL users, check out this guide on How To Manage an SQL Database.

      Note: Logging into phpMyAdmin as the root MySQL user is discouraged because it represents a significant security risk. This guide will outline how to disable logins as the root MySQL user in Step 3 of this guide.

      Your phpMyAdmin installation is completely functional at this point. However, by installing a web interface, you’ve exposed your MySQL database server to the outside world. Because of phpMyAdmin’s popularity, and the potential for it to provide access to large amounts of sensitive data, installations like these are common targets for attacks. In the following sections of this guide, we’ll go over a few different methods by which you can make your phpMyAdmin installation more secure.

      Step 2 — Changing phpMyAdmin’s Default Location

      One way to protect your phpMyAdmin installation is by making it harder to find. Bots will scan for common paths, like /phpmyadmin, /pma, /admin, /mysql, and other similar names. Changing the interface’s URL from /phpmyadmin to something non-standard will make it much harder for automated scripts to find your phpMyAdmin installation and attempt brute-force attacks.

      In the previous step, you created a symbolic link in your Nginx web document root pointing to /usr/share/phpmyadmin, where the actual phpMyAdmin application files are located. You can rename this symbolic link to change phpMyAdmin’s interface URL.

      To do this, navigate to the Nginx document root directory:

      Then run the following ls command to list the files in the document root directory to get a better sense of the change you’ll make. This command includes the -l option, which tells the command to use the “long listing” format. This will instruct ls to return more information than it would otherwise:

      Your output will contain a line like the following:

      Output

      . . . lrwxrwxrwx 1 root root 22 Jan 15 21:09 phpmyadmin -> /usr/share/phpmyadmin/ . . .

      This line indicates that you have a symbolic link named phpmyadmin in this directory. You can change this link name to whatever you’d like, and doing so will in turn change the URL where you can access phpMyAdmin. This will help to obscure the endpoint from bots performing automated searches of common endpoint names.

      Choose a name that hides the purpose of the endpoint. This guide will name the endpoint /hiddenlink and use this name in examples throughout, but you should choose an alternate name.

      Rename the symbolic link with the mv command:

      • sudo mv phpmyadmin hiddenlink

      After running this command, run the ls -l command again to confirm that the symbolic link was renamed correctly:

      This time, the output will indicate that the listing for the symbolic link has been updated with its new name:

      Output

      total 8 . . . lrwxrwxrwx 1 root root 22 Jan 15 21:09 hiddenlink -> /usr/share/phpmyadmin/ . . .

      Now when you go to the URL you previously used to access phpMyAdmin, you’ll get a 404 error:

      https://server_domain_or_IP/phpmyadmin
      

      phpMyAdmin 404 error

      You can instead access your phpMyAdmin interface at the new URL you just configured:

      https://server_domain_or_IP/hiddenlink
      

      phpMyAdmin login screen

      By obscuring phpMyAdmin’s real location on the server, you’re securing its interface against automated scans and manual brute-force attempts.

      Step 3 — Disabling Root Login

      On MySQL, as well as within regular Linux systems, the root account is a special administrative account with unrestricted access to the system. In addition to being a privileged account, it’s a known login name, which makes it an obvious target for brute-force attacks. To minimize these risks, this step will outline how to configure phpMyAdmin to deny any login attempts coming from the root MySQL user. This way, even if you provide valid credentials for the user root, you’ll still get an Access denied! error and won’t be allowed to log in.

      Because you selected dbconfig-common to configure and store phpMyAdmin settings, the application’s default configuration is currently stored within your MySQL database. You’ll need to create a new config.inc.php file in phpMyAdmin’s configuration directory to define your custom settings. Even though phpMyAdmin’s PHP scripts are located inside the /usr/share/phpmyadmin directory, the application’s configuration files are located in /etc/phpmyadmin.

      Create a new custom settings file inside the /etc/phpmyadmin/conf.d directory and name it pma_secure.php:

      • sudo nano /etc/phpmyadmin/conf.d/pma_secure.php

      Then add the following content to the new file:

      /etc/phpmyadmin/conf.d/pma_secure.php

      <?php
      
      # PhpMyAdmin Settings
      # This should be set to a random string of at least 32 chars
      $cfg['blowfish_secret'] = 'CHANGE_THIS_TO_A_STRING_OF_32_RANDOM_CHARACTERS';
      
      $i=0;
      $i++;
      
      $cfg['Servers'][$i]['auth_type'] = 'cookie';
      $cfg['Servers'][$i]['AllowNoPassword'] = false;
      $cfg['Servers'][$i]['AllowRoot'] = false;
      
      ?>
      

      By including the AllowNoPassword and AllowRoot directives and setting both of them to false, this configuration file disables passwordless logins and logins by the root MySQL user, respectively.

      Note that the auth_type setting configures phpMyAdmin to use the cookie authentication method. phpMyAdmin uses the cookie authentication method by default, which allows you to log in to phpMyAdmin as any valid MySQL user with the help of cookies. With this method, the MySQL user password is stored and encrypted with the Advanced Encryption Standard (AES) algorithm in a temporary cookie.

      Historically, phpMyAdmin instead used the Blowfish algorithm for this purpose. However, it still looks for a directive named blowfish_secret, which points to passphrase to be used internally by the AES algorithm. This isn’t a passphrase you need to remember, so any string containing 32 random characters will work here.

      Update the line that reads 'CHANGE_THIS_TO_A_STRING_OF_32_RANDOM_CHARACTERS' to a random string containing at least 32 characters.

      Note: If the passphrase you enter here is shorter than 32 characters in length, it will result in the encrypted cookies being less secure. Entering a string longer than 32 characters, though, won’t cause any harm.

      To generate a truly random string of characters, you can install and use the pwgen program with APT:

      By default, pwgen creates easily pronounceable, though less secure, passwords. However, by including the -s flag, as in the following command, you can create a completely random, difficult-to-memorize password. Note the final two arguments to this command: 32, which dictates how long the password string pwgen will generate should be; and 1 which tells pwgen how many strings it should generate:

      Copy this command’s resulting output and add it to the pma_secure.php file, replacing 'CHANGE_THIS_TO_A_STRING_OF_32_RANDOM_CHARACTERS'.

      Save and close the file when you’re done editing it. If you used nano, do so by pressing CTRL + X, Y to confirm the changes, and then ENTER to return to the bash prompt.

      The changes will apply automatically. If you reload the login page now and try to log in as root, you will get an Access denied! error:

      access denied

      Logins by the root MySQL user are now prohibited on your phpMyAdmin installation. This security measure will block brute-force scripts from trying to guess the root database user’s password on your server. Moreover, it will enforce the usage of less-privileged MySQL accounts for accessing phpMyAdmin’s web interface, which by itself is an important security practice.

      Step 4 — Creating an Authentication Gateway

      Hiding your phpMyAdmin installation in an unusual location might sidestep some automated bots scanning the network, but it’s useless against targeted attacks. To better protect a web application with restricted access, it’s generally more effective to stop attackers before they can even reach the application. This way, they’ll be unable to use generic exploits and brute-force attacks to guess access credentials.

      In the specific case of phpMyAdmin, it’s even more important to keep the login interface locked away. By keeping it open to the world, you’re offering a brute-force platform for attackers to guess your database credentials.

      This step outlines how to add an extra authentication layer to your phpMyAdmin installation so as to increase the security of your MySQL databases. Most web servers, including Nginx, provide this capability natively. By completing this step, anyone who tries to access your phpMyAdmin installation’s login screen will first be required to pass through an HTTP authentication prompt by entering a valid username and password.

      To set this up, you first need to create a password file to store the authentication credentials. Nginx requires that passwords be encrypted using the crypt() function. The OpenSSL suite, which should be installed on your Ubuntu server by default, includes this functionality.

      To create an encrypted password, type:

      You will be prompted to enter and confirm the password that you wish to use. The utility will then display an encrypted version of the password that will look something like this:

      Output

      9YHV.p60.Cg6I

      Copy this value, as you will need to include it in the authentication file you are about to create.

      Now, create an authentication file. For the purposes of this guide, we’ll call this file pma_pass and place it in the Nginx configuration directory:

      • sudo nano /etc/nginx/pma_pass

      In this file, specify the username you would like to use, followed by a colon (:) and then the encrypted version of the password you received from the openssl passwd utility.

      In this example the user is named sammy, but you can choose any username you’d like. This doesn’t need to be the name of an existing user profile on your Ubuntu server or that of a MySQL user.

      After adding your chosen username and the encrypted password you copied earlier, the file will look like this:

      /etc/nginx/pma_pass

      sammy:9YHV.p60.Cg6I
      

      Save and close the file when finished.

      Next, you’ll need to modify the Nginx configuration file. Again, this guide follows the conventions established in the prerequisite LEMP tutorial, so the configuration file used in the following examples is /etc/nginx/sites-available/your_domain. Be sure that you use the relevant Nginx configuration file for the web location where your phpMyAdmin installation is currently hosted.

      Open your Nginx configuration file in your preferred text editor to get started:

      • sudo nano /etc/nginx/sites-available/your_domain

      Locate the server block, and the location / section within it. You need to create a new location section below this location / block to match phpMyAdmin’s current path on the server.

      Recall that in Step 2 of this guide you changed the name of phpMyAdmin’s location by renaming the symbolic link (hiddenlink in our example). Here, you need to enter the name you used for this symbolic link. You don’t need to include the full file path, just the name of the symbolic link relative to the Nginx document root directory:

      /etc/nginx/sites-available/your_domain

      server {
              . . .
      
              location / {
                      try_files $uri $uri/ =404;
              }
      
              location ^~ /hiddenlink {
      
              }
      
              . . .
      }
      

      Within this block, set up two directives: auth_basic, which defines the message that will be displayed on the authentication prompt, and auth_basic_user_file, pointing to the authentication file you just created. Add both of these directives to the new location section:

      /etc/nginx/sites-available/your_domain

      server {
              . . .
              location / {
                      try_files $uri $uri/ =404;
              }
      
              location ^~ /hiddenlink {
                      auth_basic "Admin Login";
                      auth_basic_user_file /etc/nginx/pma_pass;
              }
              . . .
      }
      

      Lastly, notice that this block has a ^~ selector before the new location definition. This is to make sure Nginx won’t bypass your access rules when it matches the rule for PHP files, which are typically defined as a regular expression in order to catch all .php files. In Nginx configuration files, regular expression definitions have a higher precedence over standard location definitions. This means that if you we don’t use the ^~ selector at the beginning of the location, users will still be able to bypass the authentication prompt by navigating to http://server_domain_or_ip/hiddenlink/index.php in their browser.

      The ^~ selector at the beginning of the location definition tells Nginx to ignore other matches when it finds a match for this location. This means that any subdirectories or files within /hiddenlink/ will be matched with this rule. However, because the definition to parse PHP files will be skipped as a result of the ^~ selector usage, we’ll need to include a new PHP location block inside the /hiddenlink definition. This will make sure PHP files inside this location are properly parsed; otherwise they will be sent to the browser as download content.

      Add the following highlighted lines within the location block you just added:

      /etc/nginx/sites-available/your_domain

      server {
              . . .
      
              location / {
                      try_files $uri $uri/ =404;
              }
      
              location ^~ /hiddenlink/ {
                      auth_basic "Admin Login";
                      auth_basic_user_file /etc/nginx/pma_pass;
      
                      location ~ .php$ {
                              include snippets/fastcgi-php.conf;
                              fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
                      }
              }
          . . .
      }
      

      Remember to replace hiddenlink with the actual path where phpMyAdmin can be found. You should also double check the location of your PHP-FPM socket file, which will vary depending on which version of PHP you currently have installed. In this example, we use php7.4-fpm.sock which is valid for PHP 7.4, the version that is installed on Ubuntu 20.04 via the default APT repositories.

      Save and close the file when you’re done. To check whether the configuration file is valid, run the following command:

      The following output indicates that the configuration file’s syntax is valid:

      Output

      nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful

      To activate the new authentication gate, reload Nginx:

      • sudo systemctl reload nginx

      Now when you visit the phpMyAdmin URL in your web browser, you will be prompted for the username and password you added to the pma_pass file:

      https://server_domain_or_IP/hiddenlink
      

      Nginx authentication popup

      Once you enter your credentials, you’ll be taken to the standard phpMyAdmin login page.

      Note: The authentication prompt may not appear if you have accessed phpMyAdmin recently. To force the prompt to appear, you may have to refresh the page, clear your cache, or open a different browser session.

      In addition to providing an extra layer of security, this gateway will help keep your MySQL logs clean of spammy authentication attempts.

      Step 5 — Setting Up Access via Encrypted Tunnels

      For increased security, it is possible to lock down your phpMyAdmin installation to authorized hosts only. You can limit access to phpMyAdmin by specifying individual authorized hosts in your Nginx configuration file. This way, any request coming from an IP address that is not on the list will be denied.

      Even though this feature alone can be enough in some use cases, it’s not always the best long-term solution, mainly due to the fact that most people don’t access the internet from static IP addresses. As soon as you get a new IP address from your internet provider, you’ll be unable to get to the phpMyAdmin interface until you update the Nginx configuration file with your new IP address.

      For a more robust long-term solution, you can use IP-based access control to create a setup in which users will only have access to your phpMyAdmin interface if they’re accessing from either an authorized IP address or localhost via SSH tunneling. We’ll go over how to set up both of these access controls in the sections below.

      Combining IP-based access control with SSH tunneling greatly increases security because it fully blocks access coming from the public internet (except for authorized IPs), in addition to providing a secure channel between the user and the server through the use of encrypted tunnels.

      Setting Up IP-Based Access Control on Nginx

      On Nginx, IP-based access control can be defined in the corresponding location block of a given site, using the directives allow and deny. For instance, if you want to only allow requests coming from a given host, you would include the following two lines, in this order, inside the relevant location block for the site you would like to protect:

      allow hostname_or_IP;
      deny all;
      

      You can allow as many hosts as you want, and you only need to include one allow line for each authorized host/IP inside the respective location block for the site you’re protecting. The directives will be evaluated in the same order as they are listed until a match is found or the request is finally denied due to the deny all directive.

      In this step, you’ll configure Nginx to only allow requests coming from localhost or your current IP address. First, you’ll need to know the current public IP address your local machine is using to connect to the internet. There are various ways to obtain this information; for simplicity, this guide will use the service provided by ipinfo.io. You can either open the URL https://ipinfo.io/ip in your browser, or run the following command from your local machine:

      • curl https://ipinfo.io/ip

      This command will return an IP address, like this:

      Output

      203.0.113.0

      The value returned by this command is your local machine’s current public IP address. You’ll configure phpMyAdmin’s location block to only allow requests coming from that IP or locally from the server itself.

      To do this, once again open your site’s Nginx configuration file using your preferred text editor:

      • sudo nano /etc/nginx/sites-available/your_domain

      Because you already have an access rule within your current configuration, you need to combine it with IP-based access control using the directive satisfy all. This way, you can keep the current HTTP authentication prompt for increased security.

      Add the following highlighted lines to your phpMyAdmin configuration’s location block:

      /etc/nginx/sites-available/your_domain

      server {
              . . .
      
              location ^~ /hiddenlink/ {
                      satisfy all; #requires both conditions
      
                      allow 203.0.113.0; #allow your IP
                      allow 127.0.0.1; #allow localhost via SSH tunnels
                      deny all; #deny all other sources
      
                      auth_basic "Admin Login";
                      auth_basic_user_file /etc/nginx/pma_pass;
      
                      location ~ .php$ {
                              include snippets/fastcgi-php.conf;
                              fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
                      }
              }
      
              . . .
      }
      

      This is how the file will look after adding these new directives. Remember to replace hiddenlink with the actual path where phpMyAdmin can be found, and the highlighted IP address with your local machine’s current public IP address:

      /etc/nginx/sites-available/your_domain

      server {
              . . .
      
              location ^~ /hiddenlink/ {
                      satisfy all; #requires both conditions
      
                      allow 203.0.113.0; #allow your IP
                      allow 127.0.0.1; #allow localhost via SSH tunnels
                      deny all; #deny all other sources
      
                      auth_basic "Admin Login";
                      auth_basic_user_file /etc/nginx/pma_pass;
      
                      location ~ .php$ {
                              include snippets/fastcgi-php.conf;
                              fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
                      }
              }
      
              . . .
      }
      

      Save and close the file when you’re done. To check if the configuration file is valid, you can run:

      The following output is expected:

      Output

      nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful

      Now reload the web server so the changes take effect:

      • sudo systemctl reload nginx

      Because your IP address is explicitly listed as an authorized host, your access shouldn’t be disturbed. Anyone else trying to access your phpMyAdmin installation, however, will now get a 403 Forbidden error:

      https://server_domain_or_IP/hiddenlink
      

      Nginx 403 error

      The next subsection of this guide will provide details on how to use SSH tunneling to access the web server through local requests. This way, you’ll still be able to access phpMyAdmin’s interface even when your IP address changes.

      Accessing phpMyAdmin Through an Encrypted Tunnel

      SSH tunneling works as a way of redirecting network traffic through encrypted channels. By running an ssh command similar to what you would use to log into a server, you can create a secure “tunnel” between your local machine and that server. After establishing a tunnel, all traffic coming in on a given local port can be redirected through the encrypted tunnel, using the remote server as a proxy before reaching out to the internet. This is similar to what happens when you use a virtual private network (VPN), but SSH tunnels generally require less configuration to set up.

      You can use SSH tunneling to proxy your requests to the remote web server running phpMyAdmin. By creating a tunnel between your local machine and the server where phpMyAdmin is installed, you can redirect local requests to the remote web server. More importantly, traffic will be encrypted and requests will reach Nginx as if they’re coming from localhost. This way, no matter what IP address you’re connecting from, you’ll be able to securely access phpMyAdmin’s interface.

      Because the traffic between your local machine and the remote web server will be encrypted, this is a safe alternative for situations where you can’t have an SSL/TLS certificate installed on the web server running phpMyAdmin.

      From your local machine, run this command whenever you need access to phpMyAdmin:

      • ssh user@server_domain_or_IP -L 8000:localhost:80 -L 8443:localhost:443 -N

      Let’s examine each part of the command:

      • user: the Ubuntu user profile to connect to on the server where phpMyAdmin is running
      • server_domain_or_IP: SSH host where phpMyAdmin is running
      • -L 8000:localhost:80 redirects HTTP traffic on port 8000
      • -L 8443:localhost:443 redirects HTTPS traffic on port 8443
      • -N: prevents the execution of remote commands

      Note: This command will block the terminal until you interrupt it by pressing CTRL+C, in which case it will end the SSH connection and stop the packet redirection. If you’d prefer to run this command in background mode, you can include the SSH option -f.

      Now, go to your browser and replace server_domain_or_IP with localhost:PORT, where PORT is either 8000 for HTTP or 8443 for HTTPS:

      http://localhost:8000/hiddenlink
      
      https://localhost:8443/hiddenlink
      

      phpMyAdmin login screen

      Note: If you’re accessing phpMyAdmin via HTTPS, you might get an alert message questioning the security of the SSL certificate. This happens because the domain name you’re using (localhost) doesn’t match the address registered within the certificate (that is, the domain where phpMyAdmin is actually being served). Rest assured that it is safe to proceed.

      Also, be aware that you may need to refresh your browser session or double check the URL if you’ve set up any redirects in your Nginx configuration file.

      All requests on localhost:8000 (HTTP) and localhost:8443 (HTTPS) are now being redirected through a secure tunnel to your remote phpMyAdmin application. Not only have you increased security by disabling public access to your phpMyAdmin, you also protected all traffic between your local computer and the remote server by using an encrypted tunnel to send and receive data.

      If you’d like to enforce the usage of SSH tunneling to anyone who wants access to your phpMyAdmin interface (including you), you can do that by removing any other authorized IPs from the Nginx configuration file, leaving 127.0.0.1 as the only host allowed to access that location. Considering nobody will be able to make direct requests to phpMyAdmin, it is safe to remove HTTP authentication in order to simplify your setup. This is how your configuration file would look like in such a scenario:

      /etc/nginx/sites-available/your_domain

      server {
              . . .
      
              location ^~ /hiddenlink/ {      
                      allow 127.0.0.1; #allow localhost via SSH tunnels
                      deny all; #deny all other sources
      
                      location ~ .php$ {
                              include snippets/fastcgi-php.conf;
                              fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
                      }
              }
      
              . . .
      }
      

      Once you reload Nginx’s configuration with sudo systemctl reload nginx, your phpMyAdmin installation will be locked down and users will be required to use SSH tunnels in order to access phpMyAdmin’s interface via redirected requests.

      Conclusion

      By following this tutorial, you installed phpMyAdmin on Ubuntu 20.04 running Nginx as the web server. You also learned about several advanced methods to secure a phpMyAdmin installation on Ubuntu, such as disabling root login, creating an extra layer of authentication, and using SSH tunneling to access a phpMyAdmin installation via local requests only.

      After completing this tutorial, you can manage your MySQL databases from a reasonably secure web interface. This user interface exposes most of the functionality available via the MySQL command line. You can browse databases and schema, execute queries, and create new data sets and structures.

      If you’d like to learn more about working with MySQL, we encourage you to check out this introduction to queries in MySQL. For a deeper understanding of SQL beyond just queries, you may also be interested in our How To Use SQL tutorial series.



      Source link

      Cara Menginstal dan Mengamankan phpMyAdmin pada Ubuntu 20.04


      Versi tutorial sebelumnya ditulis oleh Brennan Bearnes.

      Pengantar

      Walaupun banyak pengguna membutuhkan fungsionalitas dari sistem manajemen basis data seperti MySQL, mereka mungkin tidak merasa nyaman berinteraksi dengan sistem hanya dari prompt MySQL.

      phpMyAdmin diciptakan sehingga pengguna dapat berinteraksi dengan MySQL melalui antarmuka web. Dalam panduan ini, kita akan membahas cara menginstal dan mengamankan phpMyAdmin sehingga Anda dapat menggunakannya secara aman untuk mengelola basis data Anda pada sistem Ubuntu 20.04.

      Prasyarat

      Agar bisa menyelesaikan panduan ini, Anda membutuhkan:

      Selain itu, ada pertimbangan keamanan penting saat menggunakan perangkat lunak seperti phpMyAdmin, karena perangkat lunak tersebut:

      • Berkomunikasi secara langsung dengan instalasi MySQL Anda
      • Menangani autentikasi dengan menggunakan kredensial MySQL
      • Menjalankan dan memberikan hasil untuk kueri SQL arbitrer

      Karena alasan-alasan ini, dan karena aplikasi PHP yang digunakan secara luas sering menjadi target penyerangan, Anda jangan pernah menjalankan phpMyAdmin pada sistem jarak jauh melalui koneksi HTTP biasa.

      Jika Anda tidak memiliki domain yang sudah dikonfigurasi dengan sertifikat SSL/TLS, Anda dapat mengikuti panduan mengamankan Apache dengan Let’s Encrypt pada Ubuntu 20.04 ini. Ini akan mengharuskan Anda untuk mendaftarkan nama domain, menciptakan catatan DNS untuk server Anda, dan menyiapkan Hos Virtual Apache.

      Langkah 1 — Menginstal phpMyAdmin

      Anda dapat menggunakan APT untuk menginstal phpMyAdmin dari repositori Ubuntu asali.

      Sebagai pengguna sudo non-root Anda, perbarui indeks paket server Anda:

      Setelah itu, Anda dapat menginstal paket phpmyadmin. Bersama dengan paket ini, dokumentasi resmi juga menganjurkan Anda menginstal beberapa ekstensi PHP ke server Anda untuk mengaktifkan fungsionalitas tertentu dan meningkatkan kinerja.

      Jika Anda mengikuti prasyarat tutorial tumpukan LAMP, beberapa dari modul-modul ini akan telah terinstal bersama dengan paket php. Namun, Anda disarankan untuk menginstal paket-paket ini juga:

      • php-mbstring: Modul untuk mengelola string non-ASCII dan mengubah string menjadi pengodean yang berbeda-beda
      • php-zip: Ekstensi ini mendukung pengunggahan berkas .zip ke phpMyAdmin
      • php-gd: Mengaktifkan dukungan untuk Pustaka Grafis GD
      • php-json: Menyediakan PHP dengan dukungan untuk serialisasi JSON
      • php-curl: Mengizinkan PHP untuk berinteraksi dengan berbagai jenis server menggunakan protokol yang berbeda-beda

      Jalankan perintah berikut untuk menginstal paket-paket ini ke sistem Anda. Namun, harap dicatat, bahwa proses instalasi mengharuskan Anda untuk membuat beberapa pilihan untuk mengonfigurasi phpMyAdmin dengan benar. Kita akan membahas opsi-opsi ini segera:

      • sudo apt install phpmyadmin php-mbstring php-zip php-gd php-json php-curl

      Berikut ini adalah opsi yang Anda harus pilih saat diminta untuk mengonfigurasi instalasi Anda dengan benar:

      • Untuk pilihan server, pilih apache2

        Peringatan: Ketika prompt muncul, “apache2” disorot, tetapi tidak dipilih. Jika Anda tidak menekan bilah SPACE untuk memilih Apache, penginstal tidak akan memindahkan berkas yang diperlukan selama instalasi. Tekan SPACE, TAB, lalu ENTER untuk memilih Apache.
      • Pilih Yes saat Anda ditanya apakah ingin menggunakan dbconfig-common untuk menyiapkan basis data
      • Lalu, Anda akan diminta untuk memilih dan mengonfirmasi kata sandi aplikasi MySQL untuk phpMyAdmin

      Catatan: Dengan asumsi Anda telah menginstal MySQL dengan mengikuti Langkah 2 dari tutorial prasyarat tumpukan LAMP, Anda mungkin telah memutuskan untuk mengaktifkan plugin Validate Password. Saat penulisan dokumen ini, mengaktifkan komponen ini akan memicu kesalahan saat Anda mencoba mengatur kata sandi untuk pengguna phpmyadmin:

      Kesalahan validasi kata sandi phpMyAdmin

      Untuk menyelesaikan ini, pilih opsi abort untuk menghentikan proses instalasi. Lalu, buka prompt MySQL Anda:

      Atau, jika Anda mengaktifkan autentikasi kata sandi untuk pengguna MSQL root, jalankan perintah ini lalu masukkan kata sandi Anda saat diminta:

      Dari prompt, jalankan perintah berikut untuk menonaktifkan komponen Validate Password. Perhatikan bahwa ini tidak benar-benar akan menghapus instalasinya, tetapi hanya menghentikan komponen dimuat pada server MySQL Anda:

      • UNINSTALL COMPONENT "file://component_validate_password";

      Setelah itu, Anda dapat menutup klien MySQL:

      Lalu, coba instal paket phpmyadmin lagi dan proses akan bekerja seperti yang diharapkan:

      • sudo apt install phpmyadmin

      Setelah phpMyAdmin terinstal, Anda dapat membuka prompt MySQL sekali lagi dengan sudo mysql atau mysql -u root -u -p lalu jalankan perintah berikut untuk mengaktifkan kembali komponen Validate Password:

      • INSTALL COMPONENT "file://component_validate_password";

      Proses instalasi ini menambahkan berkas konfigurasi phpMyAdmin Apache ke dalam direktori /etc/apache2/conf-enabled/, di mana berkas konfigurasi tersebut terbaca secara otomatis. Untuk menyelesaikan konfigurasi Apache dan PHP untuk bekerja dengan phpMyAdmin, tugas yang tersisa dalam bagian tutorial ini adalah untuk secara eksplisit mengaktifkan ekstensi PHP mbstring, yang dapat Anda lakukan dengan mengetik:

      Setelah itu, mulai ulang Apache supaya perubahan Anda dapat dikenali:

      • sudo systemctl restart apache2

      phpMyAdmin sekarang sudah terinstal dan dikonfigurasi untuk bekerja dengan Apache. Namun, sebelum Anda dapat log masuk dan mulai berinteraksi dengan basis data MySQL Anda, Anda perlu memastikan bahwa pengguna MySQL Anda memiliki privilese yang dibutuhkan untuk berinteraksi dengan program ini.

      Langkah 2 — Menyesuaikan Autentikasi dan Privilese Pengguna

      Saat Anda menginstal phpMyAdmin ke server Anda, proses ini secara otomatis menciptakan pengguna basis data yang disebut phpmyadmin, yang menjalankan proses mendasar tertentu untuk program. Alih-alih log masuk sebagai pengguna dengan kata sandi administratif yang Anda atur selama instalasi, Anda disarankan untuk log masuk sebagai pengguna MYSQL root atau sebagai pengguna yang dikhususkan untuk mengelola basis data melalui antarmuka phpMyAdmin.

      Mengonfigurasi Akses Kata Sandi untuk Akun Root MySQL

      Dalam sistem Ubuntu yang menjalankan MySQL 5.7 (dan versi lebih baru), pengguna MySQL root ditetapkan untuk melakukan autentikasi dengan menggunakan plugin auth_socket secara asali alih-alih dengan kata sandi. Ini mengizinkan keamanan dan kebergunaan yang lebih besar dalam banyak kasus, tetapi juga dapat memperumit keadaan saat Anda perlu untuk mengizinkan program eksternal — seperti phpMyAdmin — untuk mengakses pengguna.

      Untuk log masuk ke phpMyAdmin sebagai pengguna MySQL root, Anda perlu mengganti metode autentikasi dari auth_socket menjadi salah satu metode yang memanfaatkan kata sandi, jika Anda belum melakukan itu. Untuk melakukan ini, buka prompt MySQL dari terminal Anda:

      Selanjutnya, periksa metode autentikasi mana yang masing-masing akun pengguna MySQL Anda gunakan dengan perintah berikut:

      • SELECT user,authentication_string,plugin,host FROM mysql.user;

      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)

      Pada contoh ini, Anda dapat melihat bahwa pengguna root memang mengautentikasi dengan menggunakan plugin auth_socket. Untuk mengonfigurasi akun root agar mengautentikasi dengan kata sandi, jalankan perintah ALTER USER berikut. Pastikan untuk mengubah password menjadi kata sandi yang kuat pilihan Anda:

      • ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'password';

      Catatan: Pernyataan ALTER USER sebelumnya telah menetapkan pengguna MYSQL root untuk mengautentikasi dengan plugin caching_sha2_password. Sesuai dokumentasi MySQL resmi, caching_sha2_password adalah plugin autentikasi MySQL yang lebih disukai, karena plugin ini menyediakan enkripsi kata sandi yang lebih aman daripada mysql_native_password yang lebih tua tetapi masih digunakan secara luas.

      Namun, beberapa versi PHP tidak berfungsi secara andal dengan caching_sha2_password. PHP telah melaporkan bahwa isu ini sudah diperbaiki pada PHP 7.4, tetapi jika Anda menjumpai kesalahan saat mencoba log masuk ke phpMyAdmin nantinya, Anda mungkin ingin mengatur root untuk mengautentikasi dengan mysql_native_password sebagai gantinya:

      • ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

      Lalu, periksa lagi metode autentikasi yang digunakan oleh setiap pengguna Anda untuk mengonfirmasi bahwa root tidak lagi mengautentikasi dengan menggunakan plugin auth_socket:

      • SELECT user,authentication_string,plugin,host FROM mysql.user;

      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)

      Anda dapat melihat dari keluaran ini bahwa pengguna root akan mengautentikasi dengan menggunakan kata sandi. Anda kini dapat log masuk ke antarmuka phpMyAdmin sebagai pengguna root Anda dengan kata sandi yang Anda sudah atur untuk itu di sini.

      Mengonfigurasi Akses Kata Sandi untuk Pengguna MySQL Khusus

      Selain itu, sebagian orang mungkin menganggap bahwa terhubung ke phpMyAdmin dengan pengguna khusus terasa lebih cocok dengan alur kerja mereka. Untuk melakukan ini, buka shell MySQL sekali lagi:

      Jika Anda memiliki autentikasi kata sandi yang diaktifkan untuk pengguna root Anda, seperti yang dijelaskan di bagian sebelumnya, Anda perlu menjalankan perintah berikut dan memasukkan kata sandi Anda saat diminta agar terhubung:

      Dari sana, ciptakan pengguna baru dan beri kata sandi yang kuat:

      • CREATE USER 'sammy'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'password';

      Catatan: Sekali lagi, tergantung versi PHP yang telah Anda instal, Anda mungkin ingin mengatur pengguna baru Anda untuk mengautentikasi dengan mysql_native_password alih-alih caching_sha2_password:

      • ALTER USER 'sammy'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

      Lalu, beri privilese yang sesuai kepada pengguna baru Anda. Sebagai contoh, Anda dapat memberikan privilese kepada pengguna untuk semua tabel di dalam basis data, serta kekuasaan untuk menambah, mengubah, dan menghapus privilese pengguna, dengan perintah ini:

      • GRANT ALL PRIVILEGES ON *.* TO 'sammy'@'localhost' WITH GRANT OPTION;

      Setelah itu, keluarlah dari shell MySQL:

      Anda kini dapat mengakses antarmuka web dengan mengunjungi nama domain atau alamat IP publik server Anda yang diikuti dengan /phpmyadmin:

      https://your_domain_or_IP/phpmyadmin
      

      Layar log masuk phpMyAdmin

      Lakukan log masuk ke antarmuka, baik sebagai root atau dengan nama pengguna dan kata sandi baru yang baru saja Anda konfigurasikan.

      Saat Anda log masuk, Anda akan melihat antarmuka pengguna, yang akan terlihat seperti ini:

      Antarmuka pengguna phpMyAdmin

      Karena Anda sekarang dapat terhubung dan berinteraksi dengan phpMyAdmin, yang tersisa hanyalah memperkuat keamanan sistem Anda untuk melindunginya dari penyerang.

      Langkah 3 — Mengamankan Instans phpMyAdmin Anda

      Karena sangat umum digunakan di mana-mana, phpMyAdmin adalah target populer bagi penyerang, dan Anda harus lebih berhati-hati untuk mencegah akses yang tidak sah. Salah satu cara melakukan ini adalah dengan menempatkan gateway di depan seluruh aplikasi dengan menggunakan fungsionalitas autentikasi dan otorisasi .htaccess bawaan dari Apache.

      Untuk melakukan ini, Anda harus terlebih dahulu mengaktifkan penggunaan dari penimpaan berkas .htaccess dengan mengedit berkas konfigurasi Apache dari instalasi phpMyAdmin Anda.

      Gunakan editor teks khusus yang Anda sukai untuk mengedit berkas phpmyadmin.conf yang telah ditempatkan di dalam direktori konfigurasi Apache Anda. Di sini, kita akan menggunakan nano:

      • sudo nano /etc/apache2/conf-available/phpmyadmin.conf

      Tambahkan arahan AllowOverride All di dalam bagian <Directory /usr/share/phpmyadmin> dari berkas konfigurasi, seperti ini:

      /etc/apache2/conf-available/phpmyadmin.conf

      <Directory /usr/share/phpmyadmin>
          Options FollowSymLinks
          DirectoryIndex index.php
          AllowOverride All
          . . .
      

      Saat Anda telah menambahkan baris ini, simpan dan tutup berkas. Jika Anda menggunakan nano untuk mengedit berkas, lakukan itu dengan menekan CTRL + X, Y, lalu ENTER.

      Untuk menerapkan perubahan yang Anda buat, mulai ulang Apache:

      • sudo systemctl restart apache2

      Karena sekarang Anda telah mengaktifkan penggunaan berkas .htaccess untuk aplikasi Anda, Anda perlu menciptakan satu berkas untuk benar-benar menerapkan keamanan.

      Agar ini berhasil, berkas tersebut harus diciptakan di dalam direktori aplikasi. Anda dapat menciptakan berkas yang diperlukan dan membukanya di dalam editor teks Anda dengan privilese root dengan mengetik:

      • sudo nano /usr/share/phpmyadmin/.htaccess

      Dalam berkas ini, masukkan informasi berikut ini:

      /usr/share/phpmyadmin/.htaccess

      AuthType Basic
      AuthName "Restricted Files"
      AuthUserFile /etc/phpmyadmin/.htpasswd
      Require valid-user
      

      Berikut ini adalah makna dari masing-masing baris ini:

      • AuthType Basic: Baris ini menentukan tipe autentikasi yang Anda sedang terapkan. Jenis ini akan menerapkan autentikasi kata sandi dengan menggunakan berkas kata sandi.
      • AuthName: Ini menetapkan pesan untuk kotak dialog autentikasi. Anda harus menjaga ini tetap generik sehingga pengguna yang tidak sah tidak akan mendapatkan informasi tentang apa yang dilindungi.
      • AuthUserFile: Ini menetapkan lokasi berkas kata sandi yang akan digunakan untuk autentikasi. Ini harus berada di luar direktori yang sedang dilayani. Kita akan segera membuat berkas ini.
      • Require valid-user: Ini menentukan bahwa hanya pengguna terautentikasi yang diberi akses ke sumber daya ini. Inilah yang sebenarnya menghentikan masuknya pengguna yang tidak sah.

      Setelah Anda selesai, simpan dan tutup berkas.

      Lokasi yang Anda sudah pilih untuk berkas kata sandi Anda adalah /etc/phpmyadmin/.htpasswd. Anda kini dapat menciptakan berkas ini dan memberikannya kepada pengguna awal dengan utilitas htpasswd:

      • sudo htpasswd -c /etc/phpmyadmin/.htpasswd username

      Anda akan diminta untuk memilih dan mengonfirmasi kata sandi untuk pengguna yang Anda buat. Setelah itu, berkas dibuat dengan kata sandi yang telah melalui proses hash yang Anda masukkan.

      Jika Anda ingin memasukkan pengguna tambahan, Anda perlu melakukannya tanpa bendera -c, seperti ini:

      • sudo htpasswd /etc/phpmyadmin/.htpasswd additionaluser

      Sekarang, saat Anda mengakses subdirektori phpMyAdmin Anda, Anda akan diminta nama akun dan kata sandi tambahan yang Anda baru saja konfigurasikan:

      https://domain_name_or_IP/phpmyadmin
      

      Kata sandi apache phpMyAdmin

      Setelah memasukkan autentikasi Apache, Anda akan dibawa ke laman autentikasi phpMyAdmin reguler untuk memasukkan kredensial MySQL Anda. Dengan menambahkan set kredensial non-MySQL ekstra, Anda memberikan basis data Anda suatu lapisan keamanan tambahan. Ini adalah sesuatu yang baik karena sejak dulu phpMyAdmin rentan terhadap ancaman keamanan.

      Kesimpulan

      Anda seharusnya kini telah memiliki phpMyAdmin yang terkonfigurasi dan siap digunakan pada server Ubuntu 20.04 Anda. Menggunakan antarmuka ini, Anda dapat menciptakan basis data, pengguna, dan tabel, serta melakukan operasi biasa seperti menghapus serta memodifikasi struktur dan data.



      Source link

      Comment installer et sécuriser Secure phpMyAdmin sur Ubuntu 20.04


      Une version antérieure de ce tutoriel a été écrite par Brennan Bearnes.

      Introduction

      Si de nombreux utilisateurs ont besoin des fonctionnalités d’un système de gestion de base de données comme MySQL, ils peuvent ne pas se sentir à l’aise pour interagir avec le système uniquement à partir de l’invite MySQL.

      phpMyAdmin a été créé pour que les utilisateurs puissent interagir avec MySQL via une interface web. Dans ce guide, nous allons voir comment installer et sécuriser phpMyAdmin afin que vous puissiez l’utiliser en toute sécurité pour gérer vos bases de données sur un système Ubuntu 20.04.

      Conditions préalables

      Afin de compléter ce guide, il vous faudra :

      De plus, il y a des considérations de sécurité importantes lors de l’utilisation de logiciels comme phpMyAdmin, puisque celui-ci :

      • communique directement avec votre installation MySQL
      • gère l’authentification à l’aide des identifiants MySQL
      • exécute et renvoie des résultats pour des requêtes SQL arbitraires

      Pour ces raisons, et parce qu’il s’agit d’une application PHP largement déployée qui est fréquemment la cible d’attaques, vous ne devriez jamais exécuter phpMyAdmin sur des systèmes distants via une simple connexion HTTP.

      Si vous n’avez pas de domaine existant configuré avec un certificat SSL/TLS, vous pouvez suivre ce guide sur la sécurisation d’Apache avec Let’s Encrypt sur Ubuntu 20.04. Pour cela, vous devrez enregistrer un nom de domaine, créer des enregistrements DNS pour votre serveur et mettre en place un hôte virtuel Apache. 

      Étape 1 — Installer Django

      Vous pouvez utiliser APT pour installer phpMyAdmin à partir des dépôts Ubuntu par défaut.

      En tant qu’utilisateur non root sudo, mettez à jour l’index des paquets de votre serveur :

      Ensuite, vous pouvez installer le paquet phpmyadmin. Parallèlement à ce paquet, la documentation officielle recommande également d’installer quelques extensions PHP sur votre serveur afin d’activer certaines fonctionnalités et d’améliorer les performances.

      Si vous avez suivi le tutoriel préalable sur la pile LAMP, plusieurs de ces modules auront été installés en même temps que le paquet php.   Toutefois, il est recommandé d’installer également ces paquets :

      • php-mbstring : Un module pour gérer les chaînes non ASCII et convertir les chaînes en différents encodages
      • php-zip : Cette extension permet de télécharger des fichiers .zip vers phpMyAdmin
      • php-gd : Permet de prendre en charge la bibliothèque graphique GD
      • php-json : Fournit à PHP un support pour la sérialisation JSON
      • php-curl : Permet à PHP d’interagir avec différents types de serveurs utilisant différents protocoles

      Exécutez la commande suivante pour installer ces paquets sur votre système. Veuillez noter, cependant, que le processus d’installation nécessite que vous fassiez certains choix pour configurer correctement phpMyAdmin. Nous allons bientôt passer en revue ces options :

      • sudo apt install phpmyadmin php-mbstring php-zip php-gd php-json php-curl

      Voici les options que vous devez choisir lorsque vous y êtes invité afin de configurer correctement votre installation :

      • Pour la sélection du serveur, choisissez apache2

        Warning: Lorsque l’invite apparaît, « apache2 » est mis en évidence, mais n’est pas sélectionné. Si vous ne tapez pas sur SPACE pour sélectionner Apache, l’installateur ne déplacera* pas *les fichiers nécessaires pendant l’installation. Appuyez sur SPACE, TAB, puis ENTER pour sélectionner Apache.
      • Sélectionnez Yes quand il est demandé s’il faut utiliser dbconfig-common pour créer la base de données
      • Il vous sera ensuite demandé de choisir et de confirmer un mot de passe d’application MySQL pour phpMyAdmin

      Note : En supposant que vous ayez installé MySQL en suivant l’étape 2 du tutoriel préalable sur la pile LAMP, vous avez peut-être décidé d’activer le plugin Validate Password plugin. A partir de ce moment, l’activation de ce composant déclenchera une erreur lorsque vous tenterez de définir un mot de passe pour l’utilisateur phpmyadmin :

      Erreur de validation du mot de passe phpMyAdmin

      Pour résoudre ce problème, sélectionnez l’option d’annulation pour arrêter le processus d’installation. Ensuite, ouvrez votre prompt MySQL :

      Ou, si vous avez activé l’authentification par mot de passe pour l’utilisateur MySQL root, exécutez cette commande et entrez ensuite votre mot de passe lorsque vous y êtes invité :

      À l’invite, exécutez la commande suivante pour désactiver le composant Validate Password. Notez que cela ne le désinstallera pas réellement, mais empêchera simplement le composant d’être lancé sur votre serveur MySQL :

      • UNINSTALL COMPONENT "file://component_validate_password";

      Ensuite, vous pouvez fermer le client MySQL :

      Essayez ensuite d’installer le paquet phpmyadmin et il fonctionnera comme prévu :

      • sudo apt install phpmyadmin

      Une fois que phpMyAdmin est installé, vous pouvez ouvrir l’invite MySQL une nouvelle fois avec sudo mysql ou mysql -u root -p et ensuite exécuter la commande suivante pour réactiver le composant Validate Password : 

      • INSTALL COMPONENT "file://component_validate_password";

      Le processus d’installation ajoute le fichier de configuration Apache de phpMyAdmin dans le répertoire /etc/apache2/conf-enabled/, où il est lu automatiquement. Pour finir de configurer Apache et PHP afin qu’ils fonctionnent avec phpMyAdmin, la seule tâche qui reste à accomplir dans cette section du tutoriel est d’activer explicitement l’extension PHP mbstring, ce que vous pouvez faire en tapant :

      Ensuite, redémarrez Apache pour que vos modifications soient reconnues :

      • sudo systemctl restart apache2

      phpMyAdmin est maintenant installé et configuré pour fonctionner avec Apache. Toutefois, avant de pouvoir vous connecter et de commencer à interagir avec vos bases de données MySQL, vous devrez vous assurer que vos utilisateurs MySQL disposent des privilèges requis pour interagir avec le programme.

      Étape 2 – Ajustement de l’authentification et des privilèges des utilisateurs

      Lorsque vous avez installé phpMyAdmin sur votre serveur, il a automatiquement créé un utilisateur de base de données appelé phpmyadmin qui effectue certains processus sous-jacents pour le programme. Plutôt que de vous connecter en tant qu’utilisateur avec le mot de passe administratif que vous avez défini lors de l’installation, il est recommandé de vous connecter soit en tant que root user MySQL, soit en tant qu’dedicated user à la gestion des bases de données via l’interface phpMyAdmin.

      Configuration du mot de passe d’accès au compte root MySQL

      Dans les systèmes Ubuntu fonctionnant sous MySQL 5.7 (et versions ultérieures), l’utilisateur MySQL root est configuré pour s’authentifier en utilisant le plugin auth_socket par défaut plutôt qu’avec un mot de passe. Cela permet une plus grande sécurité et facilité d’utilisation dans de nombreux cas, mais cela peut également compliquer les choses lorsque vous devez autoriser un programme externe – comme phpMyAdmin – pour accéder à l’utilisateur.

      Afin de vous connecter à phpMyAdmin en tant qu’utilisateur MySQL root, vous devrez changer sa méthode d’authentification de auth_socket à une méthode qui utilise un mot de passe, si vous ne l’avez pas déjà fait. Pour ce faire, ouvrez l’invite MySQL depuis votre terminal :

      Ensuite, vérifiez la méthode d’authentification utilisée par chacun de vos comptes utilisateurs MySQL à l’aide de la commande suivante :

      • SELECT user,authentication_string,plugin,host FROM mysql.user;

      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)

      Dans cet exemple, vous pouvez voir que l’utilisateur root s’authentifie effectivement en utilisant le plugin auth_socket. Pour configurer le compte root afin qu’il s’authentifie avec un mot de passe, exécutez la commande ALTER USER suivante.   Assurez-vous de changer password par un mot de passe fort de votre choix :

      • ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'password';

      Remarque : L’instruction ALTER USER précédente définit l’utilisateur MySQL root pour s’authentifier avec le plugin caching_sha2_password. Selon la documentation officielle de MySQL, caching_sha2_password est le plugin d’authentification préféré de MySQL, car il fournit un cryptage de mot de passe plus sûr que l’ancien, mais encore largement utilisé, mysql_native_password.

      Cependant, certaines versions de PHP ne fonctionnent pas de manière fiable avec caching_sha2_password. PHP a signalé que ce problème a été corrigé à partir de PHP 7.4, mais si vous rencontrez une erreur en essayant de vous connecter à phpMyAdmin plus tard, vous pourriez vouloir définir root pour vous authentifier avec mysql_native_password à la place :

      • ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

      Ensuite, vérifiez à nouveau les méthodes d’authentification employées par chacun de vos utilisateurs pour confirmer que le root ne s’authentifie plus à l’aide du plugin auth_socket :

      • SELECT user,authentication_string,plugin,host FROM mysql.user;

      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)

      Vous pouvez voir à partir de cette sortie que le root user s’authentifiera à l’aide d’un mot de passe. Vous pouvez maintenant vous connecter à l’interface phpMyAdmin en tant que root user avec le mot de passe que vous lui avez attribué ici.

      Configuration de l’accès par mot de passe pour un utilisateur MySQL dédié

      Alternativement, certains peuvent trouver qu’il est plus adapté à leur travail de se connecter à phpMyAdmin avec un dedicated user. Pour ce faire, ouvrez à nouveau le shell MySQL :

      Si vous avez activé l’authentification par mot de passe pour votre root user, comme décrit dans la section précédente, vous devrez exécuter la commande suivante et saisir votre mot de passe lorsque vous y serez invité afin de vous connecter :

      De là, créez un nouvel utilisateur et attribuez-lui un mot de passe fort :

      • CREATE USER 'sammy'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'password';

      Note : Encore une fois, selon la version de PHP que vous avez installée, vous voudrez peut-être configurer votre nouvel utilisateur pour qu’il s’authentifie avec le mot de passe mysql_native_password au lieu du mot de passe caching_sha2_password :

      • ALTER USER 'sammy'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

      Ensuite, accordez à votre nouvel utilisateur les privilèges appropriés. Par exemple, vous pourriez accorder les privilèges d’utilisateur à toutes les tables de la base de données, ainsi que le pouvoir d’ajouter, de modifier et de supprimer des privilèges d’utilisateur, avec cette commande :

      • GRANT ALL PRIVILEGES ON *.* TO 'sammy'@'localhost' WITH GRANT OPTION;

      Ensuite, quittez le shell MySQL :

      Vous pouvez maintenant accéder à l’interface web en visitant le nom de domaine ou l’adresse IP publique de votre serveur suivi de /phpmyadmin :

      https://your_domain_or_IP/phpmyadmin
      

      Écran de connexion à phpMyAdmin

      Connectez-vous à l’interface, soit commeroot ou avec le nouveau nom d’utilisateur et le nouveau mot de passe que vous venez de configurer. 

      Lorsque vous vous connecterez, vous verrez l’interface utilisateur, qui ressemblera à ceci :

      Interface utilisateur de phpMyAdmin

      Maintenant que vous êtes capable de vous connecter et d’interagir avec phpMyAdmin, il ne vous reste plus qu’à renforcer la sécurité de votre système pour le protéger des attaques.

      Étape 3 – Sécuriser votre instance phpMyAdmin

      En raison de son ubiquité, phpMyAdmin est une cible populaire pour les attaquants, et vous devriez faire très attention à empêcher tout accès non autorisé. Une façon de procéder consiste à placer une passerelle devant l’ensemble de l’application en utilisant les fonctionnalités d’authentification et d’autorisation .htaccess intégrées à Apache.

      Pour ce faire, vous devez d’abord activer l’utilisation des fichiers .htaccess en modifiant le fichier de configuration Apache de votre installation de phpMyAdmin.

      Utilisez votre éditeur de texte favori pour modifier le fichier phpmyadmin.conf qui a été placé dans votre répertoire de configuration Apache. Ici, nous utiliserons nano :

      • sudo nano /etc/apache2/conf-available/phpmyadmin.conf

      Ajoutez une directive AllowOverride All dans la section <Directory /usr/share/phpmyadmin> du fichier de configuration, comme ceci :

      /etc/apache2/conf-available/phpmyadmin.conf

      <Directory /usr/share/phpmyadmin>
          Options FollowSymLinks
          DirectoryIndex index.php
          AllowOverride All
          . . .
      

      Lorsque vous avez ajouté cette ligne, enregistrez et fermez le fichier. Si vous avez utilisé nano pour éditer le fichier, faites-le en appuyant sur CTRL + X, Y, puis ENTER

      Pour mettre en œuvre les modifications que vous avez apportées, redémarrez Apache :

      • sudo systemctl restart apache2

      Maintenant que vous avez autorisé l’utilisation de fichiers .htaccess pour votre application, vous devez en créer un pour mettre en place une certaine sécurité. 

      Pour que cela soit possible, le fichier doit être créé dans le répertoire de l’application. Vous pouvez créer le fichier nécessaire et l’ouvrir dans votre éditeur de texte avec les privilèges root en tapant :

      • sudo nano /usr/share/phpmyadmin/.htaccess

      Dans ce fichier, entrez les informations suivantes :

      /usr/share/phpmyadmin/.htaccess

      AuthType Basic
      AuthName "Restricted Files"
      AuthUserFile /etc/phpmyadmin/.htpasswd
      Require valid-user
      

      Voici ce que signifie chacune de ces lignes :

      • AuthType Basic : Cette ligne précise le type d’authentification que vous mettez en œuvre. Ce type mettra en œuvre l’authentification par mot de passe à l’aide d’un fichier de mots de passe.
      • AuthName : Définit le message pour la boîte de dialogue d’authentification. Vous devez conserver ce générique afin que les utilisateurs non autorisés n’obtiennent aucune information sur ce qui est protégé.
      • AuthUserFile : permet de définir l’emplacement du fichier de mots de passe qui sera utilisé pour l’authentification. Cela doit se faire en dehors des répertoires qui sont desservis. Nous allons créer ce dossier prochainement.
      • Require valid-user : Ceci spécifie que seuls les utilisateurs authentifiés doivent avoir accès à cette ressource. C’est ce qui empêche en fait les utilisateurs non autorisés d’entrer.

      Lorsque vous avez terminé, enregistrez et fermez le fichier.

      L’emplacement que vous avez choisi pour votre fichier de mots de passe était /etc/phpmyadmin/.htpasswd. Vous pouvez maintenant créer ce fichier et le transmettre à un utilisateur initial avec l’utilitaire htpasswd :

      • sudo htpasswd -c /etc/phpmyadmin/.htpasswd username

      Vous serez invité à sélectionner et à confirmer un mot de passe pour l’utilisateur que vous créez. Ensuite, le fichier est créé avec le mot de passe haché que vous avez entré.

      Si vous voulez entrer un utilisateur supplémentaire, vous devez le faire sans le drapeau -c, comme ceci :

      • sudo htpasswd /etc/phpmyadmin/.htpasswd additionaluser

      Maintenant, lorsque vous accédez à votre sous-répertoire phpMyAdmin, il vous sera demandé le nom de compte et le mot de passe supplémentaires que vous venez de configurer :

      https://domain_name_or_IP/phpmyadmin
      

      Mot de passe apache de phpMyAdmin

      Après avoir entré l’authentification Apache, vous serez dirigé vers la page d’authentification phpMyAdmin habituelle pour entrer vos identifiants MySQL. En ajoutant un ensemble supplémentaire d’identifiants non-MySQL, vous apportez à votre base de données une couche de sécurité supplémentaire. Ceci est souhaitable, puisque phpMyAdmin a été vulnérable aux menaces de sécurité par le passé.

      Conclusion

      Vous devriez maintenant avoir configuré phpMyAdmin et être prêt à l’utiliser sur votre serveur Ubuntu 20.04. Cette interface vous permet de créer des bases de données, des utilisateurs et des tableaux, ainsi que d’effectuer les opérations habituelles comme la suppression et la modification de structures et de données.



      Source link