Install and Secure phpMyAdmin on Debian 12 – OrcaCore

Posted on

Install and Secure phpMyAdmin on Debian 12 - OrcaCore

Install and Secure phpMyAdmin on Debian 12 – OrcaCore

This tutorial will guide you through the process of Install and Secure phpMyAdmin on Debian 12 Bookworm using a LAMP (Linux, Apache, MySQL/MariaDB, PHP) stack. phpMyAdmin provides a user-friendly graphical interface for managing your databases, such as MariaDB and MySQL. Follow the steps below, originally presented on the Orcacore website, to successfully Install and Secure phpMyAdmin on Debian 12.

Before diving into the installation process, let’s outline the necessary prerequisites.

Requirements for phpMyAdmin Setup

  1. Non-Root User with Sudo Privileges and Basic Firewall: Ensure you’re logged in to your server as a non-root user with sudo privileges and have set up a basic firewall for security. You can refer to this guide on Orcacore: Initial Server Setup with Debian 12 Bookworm.

  2. LAMP Stack Installation: A fully functional LAMP stack is required for phpMyAdmin to operate. If you haven’t already, install the LAMP stack by following this guide on Orcacore: How To Install LAMP Stack on Debian 12.

  3. Domain Name (Optional): While not strictly required, having a domain name pointed to your server’s IP address will make accessing phpMyAdmin more convenient.

Once you’ve met these requirements, proceed with the following steps to Install and Secure phpMyAdmin on Debian 12.

Step 1 – Install PHP Extensions for phpMyAdmin

First, update your APT package lists and upgrade installed packages to their latest versions:

# sudo apt update
# sudo apt upgrade -y

Next, install the necessary PHP extensions that phpMyAdmin relies on:

sudo apt install php-mbstring php-zip php-gd php-xml -y

These extensions provide functionalities for multi-byte string handling, ZIP archive support, image manipulation, and XML parsing, all of which are used by phpMyAdmin.

Step 2 – Download Latest phpMyAdmin From Source

Visit the phpMyAdmin Downloads page and locate the download link for the latest version. Copy the link ending with tar.gz.

Note: This article uses the all-languages package. If you prefer the English-only package, remember to adjust the links and file names in the following commands accordingly.

Use the wget command to download the phpMyAdmin tarball:

sudo wget https://files.phpmyadmin.net/phpMyAdmin/5.2.1/phpMyAdmin-5.2.1-all-languages.tar.gz

Extract the downloaded file:

sudo tar xvf phpMyAdmin-5.2.1-all-languages.tar.gz

Move the extracted phpMyAdmin directory to the /usr/share/ directory and rename it to phpmyadmin:

sudo mv phpMyAdmin-5.2.1-all-languages/ /usr/share/phpmyadmin

Step 3 – How To Manually Configure phpMyAdmin on Debian 12?

Since you installed phpMyAdmin from source, manual configuration is required.

Create a directory for phpMyAdmin to store temporary files:

sudo mkdir -p /var/lib/phpmyadmin/tmp

Set the correct ownership for the temporary directory:

sudo chown -R www-data:www-data /var/lib/phpmyadmin

Copy the sample configuration file to create your main configuration file:

sudo cp /usr/share/phpmyadmin/config.sample.inc.php /usr/share/phpmyadmin/config.inc.php

Open the configuration file using a text editor (e.g., vi):

sudo vi /usr/share/phpmyadmin/config.inc.php

Find the $cfg['blowfish_secret'] line and enter a string of 32 random characters between the single quotes:

. . .
$cfg['blowfish_secret'] = 'THIRTYTWORSTRINGOFANDOMCHARACTERS'; /* YOU MUST FILL IN THIS FOR COOKIE AUTH! */
. . .

Uncomment the controluser and controlpass directives and set a secure password for the controlpass:

. . .
/* User used to manipulate with storage */
// $cfg['Servers'][$i]['controlhost'] = '';
// $cfg['Servers'][$i]['controlport'] = '';
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = 'password';
. . .

Uncomment all lines under the /* Storage database and tables */ section:

. . .
/* Storage database and tables */
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['bookmarktable'] = 'pma__bookmark';
$cfg['Servers'][$i]['relation'] = 'pma__relation';
$cfg['Servers'][$i]['table_info'] = 'pma__table_info';
$cfg['Servers'][$i]['table_coords'] = 'pma__table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma__pdf_pages';
$cfg['Servers'][$i]['column_info'] = 'pma__column_info';
$cfg['Servers'][$i]['history'] = 'pma__history';
$cfg['Servers'][$i]['table_uiprefs'] = 'pma__table_uiprefs';
$cfg['Servers'][$i]['tracking'] = 'pma__tracking';
$cfg['Servers'][$i]['userconfig'] = 'pma__userconfig';
$cfg['Servers'][$i]['recent'] = 'pma__recent';
$cfg['Servers'][$i]['favorite'] = 'pma__favorite';
$cfg['Servers'][$i]['users'] = 'pma__users';
$cfg['Servers'][$i]['usergroups'] = 'pma__usergroups';
$cfg['Servers'][$i]['navigationhiding'] = 'pma__navigationhiding';
$cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches';
$cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
$cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
$cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';
. . .

Add the following line at the end of the file to define the temporary directory:

. . .
$cfg['TempDir'] = '/var/lib/phpmyadmin/tmp';

Save and close the file.

Step 4 – Create phpMyAdmin storage database and tables on Debian 12

Use the create_tables.sql file to create the phpMyAdmin configuration storage database and tables:

sudo mariadb < /usr/share/phpmyadmin/sql/create_tables.sql

Open the MariaDB console:

sudo mariadb -u root -p

Create the administrative pma user and grant necessary privileges. Remember to replace <password> with the password you defined in the config.inc.php file:

MariaDB [(none)]> GRANT SELECT, INSERT, UPDATE, DELETE ON phpmyadmin.* TO 'pma'@'localhost' IDENTIFIED BY 'password';

Create another user for logging into phpMyAdmin, replacing <orca> with your desired username and <password> with a strong password:

MariaDB [(none)]> GRANT ALL PRIVILEGES ON *.* TO 'orca'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;

Flush the privileges and exit from the MariaDB shell:

MariaDB [(none)]> FLUSH PRIVILEGES;
MariaDB [(none)]> EXIT;

Step 5 – Apache Configuration for phpMyAdmin on Debian 12

Create a file named phpmyadmin.conf in the /etc/apache2/conf-available directory:

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

Add the following content to the file:

# phpMyAdmin default Apache configuration

Alias /phpmyadmin /usr/share/phpmyadmin

<Directory /usr/share/phpmyadmin>
    Options SymLinksIfOwnerMatch
    DirectoryIndex index.php

    <IfModule mod_php5.c>
        <IfModule mod_mime.c>
            AddType application/x-httpd-php .php
        </IfModule>
        <FilesMatch ".+.php$">
            SetHandler application/x-httpd-php
        </FilesMatch>

        php_value include_path .
        php_admin_value upload_tmp_dir /var/lib/phpmyadmin/tmp
        php_admin_value open_basedir /usr/share/phpmyadmin/:/etc/phpmyadmin/:/var/lib/phpmyadmin/:/usr/share/php/php-gettext/:/usr/share/php/php-php-gettext/:/usr/share/javascript/:/usr/share/php/tcpdf/:/usr/share/doc/phpmyadmin/:/usr/share/php/phpseclib/
        php_admin_value mbstring.func_overload 0
    </IfModule>
    <IfModule mod_php.c>
        <IfModule mod_mime.c>
            AddType application/x-httpd-php .php
        </IfModule>
        <FilesMatch ".+.php$">
            SetHandler application/x-httpd-php
        </FilesMatch>

        php_value include_path .
        php_admin_value upload_tmp_dir /var/lib/phpmyadmin/tmp
        php_admin_value open_basedir /usr/share/phpmyadmin/:/etc/phpmyadmin/:/var/lib/phpmyadmin/:/usr/share/php/php-gettext/:/usr/share/php/php-php-gettext/:/usr/share/javascript/:/usr/share/php/tcpdf/:/usr/share/doc/phpmyadmin/:/usr/share/php/phpseclib/
        php_admin_value mbstring.func_overload 0
    </IfModule>

</Directory>

# Authorize for setup
<Directory /usr/share/phpmyadmin/setup>
    <IfModule mod_authz_core.c>
        <IfModule mod_authn_file.c>
            AuthType Basic
            AuthName "phpMyAdmin Setup"
            AuthUserFile /etc/phpmyadmin/htpasswd.setup
        </IfModule>
        Require valid-user
    </IfModule>
</Directory>

# Disallow web access to directories that don't need it
<Directory /usr/share/phpmyadmin/templates>
    Require all denied
</Directory>
<Directory /usr/share/phpmyadmin/libraries>
    Require all denied
</Directory>
<Directory /usr/share/phpmyadmin/setup/lib>
    Require all denied
</Directory>

Save and close the file.

Enable the configuration:

sudo a2enconf phpmyadmin.conf

Reload Apache to apply the changes:

sudo systemctl reload apache2

Step 6 – Access phpMyAdmin Web Interface

Access the phpMyAdmin login screen by navigating to your domain name or IP address followed by /phpmyadmin:

http://your_domain_or_IP/phpmyadmin

Enter the MariaDB user credentials you configured earlier and click "Login."

Step 7 – How To Secure phpMyAdmin on Debian 12?

To protect phpMyAdmin from unauthorized access, implement Apache’s .htaccess authentication.

Open the Apache configuration file for phpMyAdmin:

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

Add the AllowOverride All directive within the <Directory /usr/share/phpmyadmin> section:

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

    <IfModule mod_php5.c>
    . . .

Save and close the file.

Restart Apache to apply the changes:

sudo systemctl restart apache2

Create the .htaccess file in the phpMyAdmin directory:

sudo vi /usr/share/phpmyadmin/.htaccess

Add the following content to the .htaccess file:

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

Save and close the file.

Create the .htpasswd file with an initial user:

sudo htpasswd -c /usr/share/phpmyadmin/.htpasswd username

Enter a new password when prompted.

To add additional users, run:

sudo htpasswd /etc/phpmyadmin/.htpasswd additionaluser

Now, accessing phpMyAdmin through your browser will require Apache authentication before reaching the phpMyAdmin login screen.

Conclusion

You have now successfully Install and Secure phpMyAdmin on Debian 12 using the LAMP stack and secured it with Apache’s .htaccess authentication. You can now effectively manage your databases through the phpMyAdmin interface.

Alternative Solutions for Securing phpMyAdmin

While the provided method utilizes .htaccess for basic authentication, here are two alternative and potentially more robust solutions for securing your phpMyAdmin installation:

1. IP Whitelisting:

Instead of relying on password-based authentication at the Apache level, you can restrict access to phpMyAdmin based on the client’s IP address. This is particularly useful if you only need to access phpMyAdmin from a specific location or a limited set of known IP addresses.

  • Explanation: This method involves modifying the Apache configuration file for phpMyAdmin to only allow access from specific IP addresses or ranges. Any requests originating from other IP addresses will be denied.

  • Implementation:

    Open the phpMyAdmin Apache configuration file:

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

    Within the <Directory /usr/share/phpmyadmin> section, add the following lines, replacing 192.168.1.100 and 10.0.0.0/24 with your allowed IP addresses or CIDR ranges:

    <Directory /usr/share/phpmyadmin>
        Options FollowSymLinks
        DirectoryIndex index.php
        Order Deny,Allow
        Deny from all
        Allow from 192.168.1.100
        Allow from 10.0.0.0/24
    </Directory>

    Save and close the file, then restart Apache:

    sudo systemctl restart apache2

    This configuration will now only allow access to phpMyAdmin from the specified IP addresses.

2. Using a Reverse Proxy with Authentication (e.g., Nginx):

A reverse proxy, such as Nginx, sits in front of your Apache web server and handles incoming requests. By configuring authentication on the reverse proxy level, you can add an extra layer of security before requests even reach Apache and phpMyAdmin. This is a more advanced solution offering greater flexibility and control.

  • Explanation: Nginx will act as the gatekeeper. It will authenticate users before forwarding their requests to Apache, which hosts phpMyAdmin. This centralizes authentication and allows for more sophisticated authentication methods (e.g., multi-factor authentication).

  • Implementation (Conceptual Example):

    This example assumes you have Nginx installed and configured to proxy requests to your Apache server.

    1. Configure Nginx Authentication:

      Create an Nginx configuration file for phpMyAdmin (e.g., /etc/nginx/conf.d/phpmyadmin.conf):

      server {
          listen 80; # Or 443 for HTTPS
          server_name your_domain_or_ip;
      
          location /phpmyadmin {
              auth_basic "Restricted Access";
              auth_basic_user_file /etc/nginx/.htpasswd; # Create this file with htpasswd
              proxy_pass http://127.0.0.1:80; # Assuming Apache listens on port 80
              proxy_set_header Host $host;
              proxy_set_header X-Real-IP $remote_addr;
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          }
      }

      Create the /etc/nginx/.htpasswd file using the htpasswd utility (similar to the Apache example).

      Enable the Nginx configuration and restart Nginx.

    2. Optionally, Restrict Direct Access to Apache:

      For increased security, configure Apache to only listen on localhost (127.0.0.1) so that it’s only accessible through the Nginx reverse proxy.

    This setup provides a robust security layer, separating authentication from the phpMyAdmin application itself and allowing for more advanced authentication configurations in Nginx.

Leave a Reply

Your email address will not be published. Required fields are marked *