One place for hosting & domains

      How To Set Up and Configure a Certificate Authority (CA) On CentOS 8


      A Certificate Authority (CA) is an entity responsible for issuing digital certificates to verify identities on the internet. Although public CAs are a popular choice for verifying the identity of websites and other services that are provided to the general public, private CAs are typically used for closed groups and private services.

      Building a private Certificate Authority will enable you to configure, test, and run programs that require encrypted connections between a client and a server. With a private CA, you can issue certificates for users, servers, or individual programs and services within your infrastructure.

      Some examples of programs on Linux that use their own private CA are OpenVPN and Puppet . You can also configure your web server to use certificates issued by a private CA in order to make development and staging environments match production servers that use TLS to encrypt connections.

      In this guide, we’ll learn how to set up a private Certificate Authority on a CentOS 8 server, and how to generate and sign a testing certificate using your new CA. You will also learn how to import the CA server’s public certificate into your operating system’s certificate store so that you can verify the chain of trust between the CA and remote servers or users. Finally you will learn how to revoke certificates and distribute a Certificate Revocation List to make sure only authorized users and systems can use services that rely on your CA.


      To follow this tutorial, you will need a CentOS 8 server with a sudo enabled, non-root user, and a firewall set up with firewalld. You can follow our Initial Server Setup with CentOS 8 guide to complete that set up.

      This server will be referred to as the CA Server in this tutorial.

      Ensure that the CA Server is a standalone system. It will only be used to import, sign, and revoke certificate requests. It should not run any other services, and ideally it will be offline or completely shut down when you are not actively working with your CA.

      Note: The last section of this tutorial is optional if you would like to learn about signing and revoking certificates. If you choose to complete those practice steps, you will need a second CentOS 8 server or you can also use your own local Linux computer running CentOS 8, Fedora or a RedHat derivative.

      Step 1 — Installing Easy-RSA

      The first task in this tutorial is to install the easy-rsa set of scripts on your CA Server. easy-rsa is a Certificate Authority management tool that you will use to generate a private key, and public root certificate, which you will then use to sign requests from clients and servers that will rely on your CA.

      The easy-rsa package is not available by default in CentOS 8, so you will need to enable the Extra Packages for Enterprise Linux (EPEL) repository. EPEL is managed by the Fedora Project and contains non-standard but popular packages for Fedora, CentOS, and other Linux distributions that use the RPM package format. Login to your CA Server as the non-root sudo user that you created during the initial setup steps and run the following:

      • sudo dnf install epel-release

      You will be prompted to download the package and install it. Press y to confirm you want to install the package.

      Now install the easy-rsa package, again entering y at the prompt:

      • sudo dnf install easy-rsa

      At this point you have everything you need set up and ready to use Easy-RSA. In the next step you will create a Public Key Infrastructure, and then start building your Certificate Authority.

      Step 2 — Preparing a Public Key Infrastructure Directory

      Now that you have installed easy-rsa, it is time to create a skeleton Public Key Infrastructure (PKI) on the CA Server. Ensure that you are still logged in as your non-root user and create an easy-rsa directory. Make sure that you do not use sudo to run any of the following commands, since your normal user should manage and interact with the CA without elevated privileges.

      This will create a new directory called easy-rsa in your home folder. We’ll use this directory to create symbolic links pointing to the easy-rsa package files that we’ve installed in the previous step. These files are located in the /usr/share/easy-rsa/3 folder on the CA Server.

      Create the symlinks with the ln command:

      • ln -s /usr/share/easy-rsa/3/* ~/easy-rsa/

      Note: While other guides might instruct you to copy the easy-rsa package files into your PKI directory, this tutorial adopts a symlink approach. As a result, any updates to the easy-rsa package will be automatically reflected in your PKI’s scripts.

      To restrict access to your new PKI directory, ensure that only the owner can access it using the chmod command:

      • chmod 700 /home/sammy/easy-rsa

      Finally, initialize the PKI inside the easy-rsa directory:

      • cd ~/easy-rsa
      • ./easyrsa init-pki


      init-pki complete; you may now create a CA or requests. Your newly created PKI dir is: /home/sammy/easy-rsa/pki

      After completing this section you have a directory that contains all the files that are needed to create a Certificate Authority. In the next section you will create the private key and public certificate for your CA.

      Step 3 — Creating a Certificate Authority

      Before you can create your CA’s private key and certificate, you need to create and populate a file called vars with some default values. First you will cd into the easy-rsa directory, then you will create and edit the vars file with nano or your preferred text editor.

      The default text editor that comes with CentOS 8 is vi. vi is an extremely powerful text editor, but it can be somewhat obtuse for users who lack experience with it. You might want to install a more user-friendly editor such as nano to facilitate editing configuration files on your CentOS 8 server:

      When you are prompted to install nano enter y to continue with the installation steps. Now you are ready to edit the vars file:

      Once the file is opened, paste in the following lines and edit each highlighted value to reflect your own organization info. The important part here is to ensure that you do not leave any of the values blank:


      set_var EASYRSA_REQ_COUNTRY "US" set_var EASYRSA_REQ_PROVINCE "NewYork" set_var EASYRSA_REQ_CITY "New York City" set_var EASYRSA_REQ_ORG "DigitalOcean" set_var EASYRSA_REQ_EMAIL "" set_var EASYRSA_REQ_OU "Community"

      When you are finished, save and close the file. If you are using nano, you can do so by pressing CTRL+X, then Y and ENTER to confirm. You are now ready to build your CA.

      To create the root public and private key pair for your Certificate Authority, run the ./easy-rsa command again, this time with the build-ca option:

      In the output, you’ll see some lines about the OpenSSL version and you will be prompted to enter a passphrase for your key pair. Be sure to choose a strong passphrase, and note it down somewhere safe. You will need to input the passphrase any time that you need to interact with your CA, for example to sign or revoke a certificate.

      You will also be asked to confirm the Common Name (CN) for your CA. The CN is the name used to refer to this machine in the context of the Certificate Authority. You can enter any string of characters for the CA’s Common Name but for simplicity’s sake, press ENTER to accept the default name.


      . . . Enter New CA Key Passphrase: Re-Enter New CA Key Passphrase: . . . Common Name (eg: your user, host, or server name) [Easy-RSA CA]: CA creation complete and you may now import and sign cert requests. Your new CA certificate file for publishing is at: /home/sammy/easy-rsa/pki/ca.crt

      Note: If you don’t want to be prompted for a password every time you interact with your CA, you can run the build-ca command with the nopass option, like this:

      • ./easyrsa build-ca nopass

      You now have two important files — ~/easy-rsa/pki/ca.crt and ~/easy-rsa/pki/private/ca.key — which make up the public and private components of a Certificate Authority.

      • ca.crt is the CA’s public certificate file. Users, servers, and clients will use this certificate to verify that they are part of the same web of trust. Every user and server that uses your CA will need to have a copy of this file. All parties will rely on the public certificate to ensure that someone is not impersonating a system and performing a Man-in-the-middle attack.

      • ca.key is the private key that the CA uses to sign certificates for servers and clients. If an attacker gains access to your CA and, in turn, your ca.key file, you will need to destroy your CA. This is why your ca.key file should only be on your CA machine and that, ideally, your CA machine should be kept offline when not signing certificate requests as an extra security measure.

      With that, your CA is in place and it is ready to be used to sign certificate requests, and to revoke certificates.

      Step 4 — Distributing your Certificate Authority’s Public Certificate

      Now your CA is configured and ready to act as a root of trust for any systems that you want to configure to use it. You can add the CA’s certificate to your OpenVPN servers, web servers, mail servers, and so on. Any user or server that needs to verify the identity of another user or server in your network should have a copy of the ca.crt file imported into their operating system’s certificate store.

      To import the CA’s public certificate into a second Linux system like another server or a local computer, first obtain a copy of the ca.crt file from your CA server. You can use the cat command to output it in a terminal, and then copy and paste it into a file on the second computer that is importing the certificate. You can also use tools like scp, rsync to transfer the file between systems. However we’ll use copy and paste with nano in this step since it will work on all systems.

      As your non-root user on the CA Server, run the following command:

      • cat ~/easy-rsa/pki/ca.crt

      There will be output in your terminal that is similar to the following:



      Copy everything, including the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- lines and the dashes.

      On your second Linux system use nano or your preferred text editor to open a file called /tmp/ca.crt:

      Paste the contents that you just copied from the CA Server into the editor. When you are finished, save and close the file. If you are using nano, you can do so by pressing CTRL+X, then Y and ENTER to confirm.

      Now that you have a copy of the ca.crt file on your second Linux system, it is time to import the certificate into its operating system certificate store.

      On CentOS, Fedora, or other RedHat derived Linux systems run the following commands to import the certificate:

      CentOS, Fedora, RedHat distributions

      • sudo cp /tmp/ca.crt /etc/pki/ca-trust/source/anchors/
      • update-ca-trust

      To import the CA Server’s certificate on a Debian or Ubuntu based system, copy and paste the file contents onto the system just like in the previous example in a file called /tmp/ca.crt. Next, copy the certificate into /usr/local/share/ca-certificates/, then run the update-ca-certificates command.

      Debian and Ubuntu derived distributions

      • sudo cp /tmp/ca.crt /usr/local/share/ca-certificates/
      • update-ca-certificates

      Now your second Linux system will trust any certificate that has been signed by the CA server.

      Note: If you are using your CA with web servers and use Firefox as a browser you will need to import the public ca.crt certificate into Firefox directly. Firefox does not use the local operating system’s certificate store. For details on how to add your CA’s certificate to Firefox please see this support article from Mozilla on Setting Up Certificate Authorities (CAs) in Firefox.

      If you are using your CA to integrate with a Windows environment or desktop computers, please see the documentation on how to use certutil.exe to install a CA certificate.

      If you are using this tutorial as a prerequisite for another tutorial, or are familiar with how to sign and revoke certificates you can stop here. If you would like to learn more about how to sign and revoke certificates, then the following optional section will explain each process in detail.

      (Optional) — Creating Certificate Signing Requests and Revoking Certificates

      The following sections of the tutorial are optional. If you have completed all the previous steps then you have a fully configured and working Certificate Authority that you can use as a prerequisite for other tutorials. You can import your CA’s ca.crt file and verify certificates in your network that have been signed by your CA.

      If you would like to practice and learn more about how to sign certificate requests, and how to revoke certificates, then these optional sections will explain how both processes work.

      (Optional) — Creating and Signing a Practice Certificate Request

      Now that you have a CA ready to use, you can practice generating a private key and certificate request to get familiar with the signing and distribution process.

      A Certificate Signing Request (CSR) consists of three parts: a public key, identifying information about the requesting system, and a signature of the request itself, which is created using the requesting party’s private key. The private key will be kept secret, and will be used to encrypt information that anyone with the signed public certificate can then decrypt.

      The following steps will be run on your second Linux system running CentOS, Fedora, or another RedHat derived Linux distribution. It can be another remote server, or a local Linux machine like a laptop or a desktop computer. Since easy-rsa is not available by default on all systems, we’ll use the openssl tool to create a practice private key and certificate.

      openssl is usually installed by default on most Linux distributions, but just to be certain, run the following on your system:

      When you are prompted to install openssl enter y to continue with the installation steps. Now you are ready to create a practice CSR with openssl.

      The first step that you need to complete to create a CSR is generating a private key. To create a private key using openssl, create a practice-csr directory and then generate a key inside it. We will make this request for a fictional server called sammy-server, as opposed to creating a certificate that is used to identify a user or another CA.

      • mkdir ~/practice-csr
      • cd ~/practice-csr
      • openssl genrsa -out sammy-server.key


      Generating RSA private key, 2048 bit long modulus (2 primes) . . . . . . e is 65537 (0x010001)

      Now that you have a private key you can create a corresponding CSR, again using the openssl utility. You will be prompted to fill out a number of fields like Country, State, and City. You can enter a . if you’d like to leave a field blank, but be aware that if this were a real CSR, it is best to use the correct values for your location and organization:

      • openssl req -new -key sammy-server.key -out sammy-server.req


      . . . ----- Country Name (2 letter code) [XX]:US State or Province Name (full name) []:New York Locality Name (eg, city) [Default City]:New York City Organization Name (eg, company) [Default Company Ltd]:DigitalOcean Organizational Unit Name (eg, section) []:Community Common Name (eg, your name or your server's hostname) []:sammy-server Email Address []: Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []: An optional company name []:

      If you would like to automatically add those values as part of the openssl invocation instead of via the interactive prompt, you can pass the -subj argument to OpenSSL. Be sure to edit the highlighted values to match your practice location, organization, and server name:

      • openssl req -new -key sammy-server.key -out sammy-server.req -subj
      • /C=US/ST=New York/L=New York City/O=DigitalOcean/OU=Community/CN=sammy-server

      To verify the contents of a CSR, you can read in a request file with openssl and examine the fields inside:

      • openssl req -in sammy-server.req -noout -subject


      subject=C = US, ST = New York, L = New York City, O = DigitalOcean, OU = Community, CN = sammy-server

      Once you’re happy with the subject of your practice certificate request, copy the sammy-server.req file to your CA server using scp:

      • scp sammy-server.req sammy@your_ca_server_ip:/tmp/sammy-server.req

      In this step you generated a Certificate Signing Request for a fictional server called sammy-server. In a real-world scenario, the request could be from something like a staging or development web server that needs a TLS certificate for testing; or it could come from an OpenVPN server that is requesting a certificate so that users can connect to a VPN. In the next step, we’ll proceed to signing the certificate signing request using the CA Server’s private key.

      (Optional) — Signing a CSR

      In the previous step, you created a practice certificate request and key for a fictional server. You copied it to the /tmp directory on your CA server, emulating the process that you would use if you had real clients or servers sending you CSR requests that need to be signed.

      Continuing with the fictional scenario, now the CA Server needs to import the practice certificate and sign it. Once a certificate request is validated by the CA and relayed back to a server, clients that trust the Certificate Authority will also be able to trust the newly issued certificate.

      Since we will be operating inside the CA’s PKI where the easy-rsa utility is available, the signing steps will use the easy-rsa utility to make things easier, as opposed to using the openssl directly like we did in the previous example.

      The first step to sign the fictional CSR is to import the certificate request using the easy-rsa script:

      • cd ~/easy-rsa
      • ./easyrsa import-req /tmp/sammy-server.req sammy-server


      . . . The request has been successfully imported with a short name of: sammy-server You may now use this name to perform signing operations on this request.

      Now you can sign the request by running the easyrsa script with the sign-req option, followed by the request type and the Common Name that is included in the CSR. The request type can either be one of client, server, or ca. Since we’re practicing with a certificate for a fictional server, be sure to use the server request type:

      • ./easyrsa sign-req server sammy-server

      In the output, you’ll be asked to verify that the request comes from a trusted source. Type yes then press ENTER to confirm this:


      You are about to sign the following certificate. Please check over the details shown below for accuracy. Note that this request has not been cryptographically verified. Please be sure it came from a trusted source or that you have verified the request checksum with the sender. Request subject, to be signed as a server certificate for 3650 days: subject= commonName = sammy-server Type the word 'yes' to continue, or any other input to abort. Confirm request details: yes . . . Certificate created at: /home/sammy/easy-rsa/pki/issued/sammy-server.crt

      If you encrypted your CA key, you’ll be prompted for your password at this point.

      With those steps complete, you have signed the sammy-server.req CSR using the CA Server’s private key in /home/sammy/easy-rsa/pki/private/ca.key. The resulting sammy-server.crt file contains the practice server’s public encryption key, as well as a new signature from the CA Server. The point of the signature is to tell anyone who trusts the CA that they can also trust the sammy-server certificate.

      If this request was for a real server like a web server or VPN server, the last step on the CA Server would be to distribute the new sammy-server.crt and ca.crt files from the CA Server to the remote server that made the CSR request:

      • scp pki/issued/sammy-server.crt sammy@your_server_ip:/tmp
      • scp pki/ca.crt sammy@your_server_ip:/tmp

      At this point, you would be able to use the issued certificate with something like a web server, a VPN, configuration management tool, database system, or for client authentication purposes.

      (Optional) — Revoking a Certificate

      Occasionally, you may need to revoke a certificate to prevent a user or server from using it. Perhaps someone’s laptop was stolen, a web server was compromised, or an employee or contractor has left your organization.

      To revoke a certificate, the general process follows these steps:

      1. Revoke the certificate with the ./easyrsa revoke client_name command.
      2. Generate a new CRL with the ./easyrsa gen-crl command.
      3. Transfer the updated crl.pem file to the server or servers that rely on your CA, and on those systems copy it to the required directory or directories for programs that refer to it.
      4. Restart any services that use your CA and the CRL file.

      You can use this process to revoke any certificates that you’ve previously issued at any time. We’ll go over each step in detail in the following sections, starting with the revoke command.

      Revoking a Certificate

      To revoke a certificate, navigate to the easy-rsa directory on your CA server:

      Next, run the easyrsa script with the revoke option, followed by the client name you wish to revoke. Following the practice example above, the Common Name of the certificate is sammy-server:

      • ./easyrsa revoke sammy-server

      This will ask you to confirm the revocation by entering yes:


      Please confirm you wish to revoke the certificate with the following subject: subject= commonName = sammy-server Type the word 'yes' to continue, or any other input to abort. Continue with revocation: yes . . . Revoking Certificate 8348B3F146A765581946040D5C4D590A . . .

      Note the highlighted value on the Revoking Certificate line. This value is the unique serial number of the certificate that is being revoked. If you want to examine the revocation list in the last step of this section to verify that the certificate is in it, you’ll need this value.

      After confirming the action, the CA will revoke the certificate. However, remote systems that rely on the CA have no way to check whether any certificates have been revoked. Users and servers will still be able to use the certificate until the CA’s Certificate Revocation List (CRL) is distributed to all systems that rely on the CA.

      In the next step you’ll generate a CRL or update an existing crl.pem file.

      Generating a Certificate Revocation List

      Now that you have revoked a certificate, it is important to update the list of revoked certificates on your CA server. Once you have an updated revocation list you will be able to tell which users and systems have valid certificates in your CA.

      To generate a CRL, run the easy-rsa command with the gen-crl option while still inside the ~/easy-rsa directory:

      If you have used a passphrase when creating your ca.key file, you will be prompted to enter it. The gen-crl command will generate a file called crl.pem, containing the updated list of revoked certificates for that CA.

      Next you’ll need to transfer the updated crl.pem file to all servers and clients that rely on this CA each time you run the gen-crl command. Otherwise, clients and systems will still be able to access services and systems that use your CA, since those services need to know about the revoked status of the certificate.

      Transferring a Certificate Revocation List

      Now that you have generated a CRL on your CA server, you need to transfer it to remote systems that rely on your CA. To transfer this file to your servers, you can use the scp command.

      Note: This tutorial explains how to generate and distribute a CRL manually. While there are more robust and automated methods to distribute and check revocation lists like OCSP-Stapling, configuring those methods is beyond the scope of this article.

      Ensure you are logged into your CA server as your non-root user and run the following, substituting in your own server IP or DNS name in place of your_server_ip:

      • scp ~/easy-rsa/pki/crl.pem sammy@your_server_ip:/tmp

      Now that the file is on the remote system, the last step is to update any services with the new copy of the revocation list.

      Updating Services that Support a CRL

      Listing the steps that you need to use to update services that use the crl.pem file is beyond the scope of this tutorial. In general you will need to copy the crl.pem file into the location that the service expects and then restart it using systemctl.

      Once you have updated your services with the new crl.pem file, your services will be able to reject connections from clients or servers that are using a revoked certificate.

      Examining and Verifying the Contents of a CRL

      If you would like to examine a CRL file, for example to confirm a list of revoked certificates, use the following openssl command from within your easy-rsa directory on your CA server:

      • cd ~/easy-rsa
      • openssl crl -in pki/crl.pem -noout -text

      You can also run this command on any server or system that has the openssl tool installed with a copy of the crl.pem file. For example, if you transferred the crl.pem file to your second system and want to verify that the sammy-server certificate is revoked, you can use an openssl command like the following, substituting the serial number that you noted earlier when you revoked the certificate in place of the highlighted one here:

      • openssl crl -in /tmp/crl.pem -noout -text |grep -A 1 8348B3F146A765581946040D5C4D590A


      Serial Number: 8348B3F146A765581946040D5C4D590A Revocation Date: Apr 1 20:48:02 2020 GMT

      Notice how the grep command is used to check for the unique serial number that you noted in the revocation step. Now you can verify the contents of your Certificate Revocation List on any system that relies on it to restrict access to users and services.


      In this tutorial you created a private Certificate Authority using the Easy-RSA package on a standalone CentOS 8 server. You learned how the trust model works between parties that rely on the CA. You also created and signed a Certificate Signing Request (CSR) for a practice server and then learned how to revoke a certificate. Finally, you learned how to generate and distribute a Certificate Revocation List (CRL) for any system that relies on your CA to ensure that users or servers that should not access services are prevented from doing so.

      Now you can issue certificates for users and use them with services like OpenVPN. You can also use your CA to configure development and staging web servers with certificates to secure your non-production environments. Using a CA with TLS certificates during development can help ensure that your code and environments match your production environment as closely as possible.

      If you would like to learn more about how to use OpenSSL, our OpenSSL Essentials: Working with SSL Certificates, Private Keys and CSRs tutorial has lots of additional information to help you become more familiar with OpenSSL fundamentals.

      Source link

      How To Run Multiple PHP Versions on One Server Using Apache and PHP-FPM on Ubuntu 18.04

      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.


      The Apache web server uses virtual hosts to manage multiple domains on a single instance. Similarly, PHP-FPM uses a daemon to manage multiple PHP versions on a single instance. Together, you can use Apache and PHP-FPM to host multiple PHP web-applications, each using a different version of PHP, all on the same server, and all at the same time. This is useful because different applications may require different versions of PHP, but some server stacks, like a regularly configured LAMP stack, can only manage one. Combining Apache with PHP-FPM is also a more cost-efficient solution than hosting each application on its own instance.

      PHP-FPM also offers configuration options for stderr and stdout logging, emergency restarts, and adaptive process spawning, which is useful for heavy-loaded sites. In fact, using Apache with PHP-FPM is one of the best stacks for hosting PHP applications, especially when it comes to performance.

      In this tutorial you will set up two PHP sites on a single instance. Each site will use its own domain, and each domain will deploy its own version of PHP. The first, site1.your_domain, will deploy PHP 7.0. The second, site2.your_domain, will deploy PHP 7.2.


      Step 1 — Installing PHP Versions 7.0 and 7.2 with PHP-FPM

      With the prerequisites completed, you will now install PHP versions 7.0 and 7.2, as well as PHP-FPM and several additional extensions. But to accomplish this, you will first need to add the Ondrej PHP repository to your system.

      Execute the apt-get command to install software-properties-common:

      • sudo apt-get install software-properties-common -y

      The software-properties-common package provides the apt-add-repository command-line utility, which you will use to add the ondrej/php PPA (Personal Package Archive) repository.

      Now add the ondrej/php repository to your system. The ondrej/php PPA will have more up-to-date versions of PHP than the official Ubuntu repositories, and it will also allow you to install multiple versions of PHP in the same system:

      • sudo add-apt-repository ppa:ondrej/php

      Update the repository:

      Next, install php7.0, php7.0-fpm, php7.0-mysql, libapache2-mod-php7.0, and libapache2-mod-fcgid with the following commands:

      • sudo apt-get install php7.0 php7.0-fpm php7.0-mysql libapache2-mod-php7.0 libapache2-mod-fcgid -y
      • php7.0 is a metapackage used to run PHP applications.
      • php7.0-fpm provides the Fast Process Manager interpreter that runs as a daemon and receives Fast/CGI requests.
      • php7.0-mysql connects PHP to the MySQL database.
      • libapahce2-mod-php7.0 provides the PHP module for the Apache webserver.
      • libapache2-mod-fcgid contains a mod_fcgid that starts a number of CGI program instances to handle concurrent requests.

      Now repeat the process for PHP version 7.2. Install php7.2, php7.2-fpm, php7.2-mysql, and libapache2-mod-php7.2:

      • sudo apt-get install php7.2 php7.2-fpm php7.2-mysql libapache2-mod-php7.2 -y

      After installing both PHP versions, start the php7.0-fpm service:

      • sudo systemctl start php7.0-fpm

      Next, verify the status of the php7.0-fpm service:

      • sudo systemctl status php7.0-fpm

      You’ll see the following output:


      ● php7.0-fpm.service - The PHP 7.0 FastCGI Process Manager Loaded: loaded (/lib/systemd/system/php7.0-fpm.service; enabled; vendor preset: enabled) Active: active (running) since Sun 2020-03-29 12:53:23 UTC; 15s ago Docs: man:php-fpm7.0(8) Process: 20961 ExecStopPost=/usr/lib/php/php-fpm-socket-helper remove /run/php/php-fpm.sock /etc/php/7.0/fpm/pool.d/www.conf 70 (code=exited, Process: 20979 ExecStartPost=/usr/lib/php/php-fpm-socket-helper install /run/php/php-fpm.sock /etc/php/7.0/fpm/pool.d/www.conf 70 (code=exite Main PID: 20963 (php-fpm7.0) Status: "Processes active: 0, idle: 2, Requests: 0, slow: 0, Traffic: 0req/sec" Tasks: 3 (limit: 1150) CGroup: /system.slice/php7.0-fpm.service ├─20963 php-fpm: master process (/etc/php/7.0/fpm/php-fpm.conf) ├─20977 php-fpm: pool www └─20978 php-fpm: pool www

      Repeating this process, now start the php7.2-fpm service:

      • sudo systemctl start php7.2-fpm

      And verify the status of the php7.2-fpm service:

      • sudo systemctl status php7.2-fpm

      You’ll see the following output:


      ● php7.2-fpm.service - The PHP 7.2 FastCGI Process Manager Loaded: loaded (/lib/systemd/system/php7.2-fpm.service; enabled; vendor preset: enabled) Active: active (running) since Sun 2020-03-29 12:53:22 UTC; 45s ago Docs: man:php-fpm7.2(8) Main PID: 20897 (php-fpm7.2) Status: "Processes active: 0, idle: 2, Requests: 0, slow: 0, Traffic: 0req/sec" Tasks: 3 (limit: 1150) CGroup: /system.slice/php7.2-fpm.service ├─20897 php-fpm: master process (/etc/php/7.2/fpm/php-fpm.conf) ├─20909 php-fpm: pool www └─20910 php-fpm: pool www

      Lastly, you must enable several modules so that your Apache2 service can work with multiple PHP versions:

      • sudo a2enmod actions fcgid alias proxy_fcgi
      • actions is used for executing CGI scripts based on media type or request method.

      • fcgid is a high performance alternative to mod_cgi that starts a sufficient number instances of the CGI program to handle concurrent requests.

      • alias provides for the mapping of different parts of the host filesystem in the document tree, and for URL redirection.

      • proxy_fcgi allows Apache to forward requests to PHP-FPM.

      Now restart the Apache service to apply your changes:

      • sudo systemctl restart apache2

      At this point you have installed two PHP versions on your server. Next, you will create a directory structure for each website you want to deploy.

      Step 2 — Creating Directory Structures for Both Websites

      In this section, you will create a document root directory and an index page for each of your two websites.

      First, create document root directories for both site1.your_domain and site2.your_domain:

      • sudo mkdir /var/www/site1.your_domain
      • sudo mkdir /var/www/site2.your_domain

      By default, the Apache webserver runs as a www-data user and www-data group. To ensure that you have the correct ownership and permissions of your website root directories, execute the following commands:

      • sudo chown -R www-data:www-data /var/www/site1.your_domain
      • sudo chown -R www-data:www-data /var/www/site2.your_domain
      • sudo chmod -R 755 /var/www/site1.your_domain
      • sudo chmod -R 755 /var/www/site2.your_domain

      Next you will create an info.php file inside each website root directory. This will display each website’s PHP version information. Begin with site1:

      • sudo nano /var/www/site1.your_domain/info.php

      Add the following line:


      <?php phpinfo(); ?>

      Save and close the file. Now copy the info.php file you created to site2:

      • sudo cp /var/www/site1.your_domain/info.php /var/www/site2.your_domain/info.php

      Your web server should now have the document root directories that each site requires to serve data to visitors. Next, you will configure your Apache web server to work with two different PHP versions.

      Step 3 — Configuring Apache for Both Websites

      In this section, you will create two virtual host configuration files. This will enable your two websites to work simultaneously with two different PHP versions.

      In order for Apache to serve this content, it is necessary to create a virtual host file with the correct directives. Instead of modifying the default configuration file located at /etc/apache2/sites-available/000-default.conf, you’ll create two new ones inside the directory /etc/apache2/sites-available/.

      First create a new virtual host configuration file for the website site1.your_domain. Here you will direct Apache to render content using php7.0:

      • sudo nano /etc/apache2/sites-available/site1.your_domain.conf

      Add the following content. Make sure the website directory path, server name, and PHP version match your setup:


      <VirtualHost *:80>
           ServerAdmin admin@site1.your_domain
           ServerName site1.your_domain
           DocumentRoot /var/www/site1.your_domain
           DirectoryIndex info.php
           <Directory /var/www/site1.your_domain>
              Options Indexes FollowSymLinks MultiViews
              AllowOverride All
              Order allow,deny
              allow from all
          <FilesMatch .php$>
            # For Apache version 2.4.10 and above, use SetHandler to run PHP as a fastCGI process server
            SetHandler "proxy:unix:/run/php/php7.0-fpm.sock|fcgi://localhost"
           ErrorLog ${APACHE_LOG_DIR}/site1.your_domain_error.log
           CustomLog ${APACHE_LOG_DIR}/site1.your_domain_access.log combined

      In this file you updated the DocumentRoot to your new directory and ServerAdmin to an email that the your_domain site administrator can access. You’ve also updated ServerName, which establishes the base domain for this virtual host configuration, and you’ve added a SetHandler directive to run PHP as a fastCGI process server.

      Save and close the file.

      Next, create a new virtual host configuration file for the website site2.your_domain. You will specify this subdomain to deploy php7.2:

      • sudo nano /etc/apache2/sites-available/site2.your_domain.conf

      Add the following content. Again, make sure the website directory path, server name, and PHP version match your unique information:


      <VirtualHost *:80>
           ServerAdmin admin@site2.your_domain
           ServerName site2.your_domain
           DocumentRoot /var/www/site2.your_domain
           DirectoryIndex info.php  
           <Directory /var/www/site2.your_domain>
              Options Indexes FollowSymLinks MultiViews
              AllowOverride All
              Order allow,deny
              allow from all
          <FilesMatch .php$>
            # For Apache version 2.4.10 and above, use SetHandler to run PHP as a fastCGI process server
            SetHandler "proxy:unix:/run/php/php7.2-fpm.sock|fcgi://localhost"
           ErrorLog ${APACHE_LOG_DIR}/site2.your_domain_error.log
           CustomLog ${APACHE_LOG_DIR}/site2.your_domain_access.log combined

      Save and close the file when you are finished. Then check the Apache configuration file for any syntax errors:

      • sudo apachectl configtest

      You’ll see the following output:


      Syntax OK

      Next, enable both virtual host configuration files:

      • sudo a2ensite site1.your_domain
      • sudo a2ensite site2.your_domain

      Now disable the default site, since you won’t need it.:

      • sudo a2dissite 000-default.conf

      Finally, restart the Apache service to implement your changes:

      • sudo systemctl restart apache2

      Now that you have configured Apache to serve each site, you will test them to make sure the proper PHP versions are running.

      Step 4 — Testing Both Websites

      At this point, you have configured two websites to run two different versions of PHP. Now test the results.

      Open your web browser and visit both sites http://site1.your_domain and http://site2.your_domain. You will see two pages that look like this:

      PHP 7.0 info page
      PHP 7.2 info page

      Note the titles. The first page indicates that site1.your_domain deployed PHP version 7.0. The second indicates that site2.your_domain deployed PHP version 7.2.

      Now that you’ve tested your sites, remove the info.php files. Because they contain sensitive information about your server and are accessible to unauthorized users, they pose a security threat. To remove both files, run the following commands:

      • sudo rm -rf /var/www/site1.your_domain/info.php
      • sudo rm -rf /var/www/site2.your_domain/info.php

      You now have a single Ubuntu 18.04 server handling two websites with two different PHP versions. PHP-FPM, however, is not limited to this one application.


      You have now combined virtual hosts and PHP-FPM to serve multiple websites and multiple versions of PHP on a single server. The only practical limit on the number of PHP sites and PHP versions that your Apache service can handle is the processing power of your instance.

      From here you might consider exploring PHP-FPM’s more advanced features, like its adaptive spawning process or how it can log sdtout and stderr. Alternatively, you could now secure your websites. To accomplish this, you can follow our tutorial on how to secure your sites with free TLS/SSL certificates from Let’s Encrypt.

      Source link

      How To Install and Configure SimpleSAMLphp for SAML Authentication on Ubuntu 18.04


      SimpleSAMLphp is an open-source PHP authentication application that provides support for SAML 2.0 as a Service Provider (SP) or Identity Provider (IdP).

      SAML (Security Assertion Markup Language) is a secure XML-based communication mechanism for exchanging authentication and authorization data between organizations and applications. It’s often used to implement Web SSO (Single Sign On). This eliminates the need to maintain multiple authentication credentials across multiple organizations. Simply put, you can use one identity, like a username and password, to access multiple applications.

      An instance of SimpleSAMLphp connects to an authentication source, which is an identity provider like LDAP or a database of users. It authenticates users against this authentication source before granting access to resources made available from linked Service Providers.

      In this tutorial you’ll install SimpleSamlPHP and configure it to use a MySQL database as an authentication source. You’ll store users and encrypted passwords in the MySQL database and test that you can use those users to log in.


      Step 1 — Downloading and Installing SimpleSAMLphp

      Installing SimpleSAMLphp involves a couple of steps. We have to download the software itself as well as a few additional components and prerequisites. We’ll also need to make some changes to our Virtual Host configuration.

      Log in to your server if you’re not logged in already.

      Download SimpleSAMLphp from the project’s website. SimpleSAMLphp always links the latest stable version of their software to the same URL. This means we can get the latest version by typing this:

      • wget

      This will download a compressed file called download?latest which contains SimpleSAMLphp. Extract the contents with the tar command:

      The files will be extracted to a new directory labeled simplesamlphp-1.x.y, where x.y is the current version number. Use the ls command to identify the file:

      You’ll see the filename displayed:



      Now, copy the contents of the directory to /var/simplesamlphp using the cp command. Be sure to replace the version number with the version you have:

      • sudo cp -a simplesamlphp-1.x.y/. /var/simplesamlphp/

      The -a switch ensures that the file permissions are copied along with the files and folders. The dot at the end of the source file ensures everything in the source directory including hidden files gets copied to the destination directory.

      Note: If you need to install the files in a different location, you’ll need to update several files. Refer to SimpleSAMLphp’s official installation documentation for specifics.

      There are a few additional software packages SimpleSAMLphp needs, including PHP extensions to work with XML, multi-byte strings, curl, and LDAP. It also requires memcached. Install these using your package manager.

      First, update your package list:

      Then install the packages:

      • sudo apt install php-xml php-mbstring php-curl php-memcache php-ldap memcached

      Once the installation completes, restart Apache to activate the new PHP extensions:

      • sudo systemctl restart apache2

      Now that SimpleSAMLphp is installed, let’s configure Apache to serve the files.

      Step 2 — Configuring Apache to Serve SimpleSAMLphp

      You’ve already configured a domain and pointed at this server, and you’ve set up a Virtual Host to work with HTTPS by securing Apache with Let’s Encrypt. Let’s use that to serve SimpleSAMLphp.

      The only SimpleSAMLphp directory that needs to be visible to the web is /var/simplesamlphp/www. To expose it to the web, edit the Virtual Host SSL Apache configuration file for your domain.

      If your Virtual Host config file is named your_domain.conf, Let’s Encrypt created a new config file called your_domain-le-ssl.conf that handles HTTPS requests for your domain. Open the SSL config file with the following command to edit the file. Be sure to replace your_domain with the actual name of the file:

      • sudo nano /etc/apache2/sites-available/your_domain-le-ssl.conf

      The file should look like the following, although the actual file may have more descriptive comments:


      <IfModule mod_ssl.c>
      <VirtualHost *:443>
              ServerName your_domain
              ServerAdmin webmaster@localhost
              DocumentRoot /var/www/html
              ErrorLog ${APACHE_LOG_DIR}/error.log
              CustomLog ${APACHE_LOG_DIR}/access.log combined
      SSLCertificateFile /etc/letsencrypt/live/your_domain/fullchain.pem
      SSLCertificateKeyFile /etc/letsencrypt/live/your_domain/privkey.pem
      Include /etc/letsencrypt/options-ssl-apache.conf

      The ServerName directive here defines the base domain that should match for this virtual host definition. This should be the domain name you set up an SSL certificate for in the Prerequisites section. Let’s add an Alias directive that gives control to SimpleSAMLphp for all URLs matching https://your_domain/simplesaml/*. Do that by adding the following line to the config file:


        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html
        Alias /simplesaml /var/simplesamlphp/www

      This means all URLs matching domain_name/simplesaml/* will be directed to the /var/simplesamlphp/www directory giving SimpleSAMLphp control.

      Next, we’ll grant access to the /var/simplesamlphp/www directory by specifying a Require all granted access control for it. This will make the SimpleSAMLphp service accessible over the Web. Do that by adding the following to the config file:


        Alias /simplesaml /var/simplesamlphp/www
        <Directory /var/simplesamlphp/www/>
            Require all granted

      Save and close the file. Restart Apache for the changes to take effect:

      • sudo systemctl restart apache2

      Now that Apache is configured to serve the application files, let’s configure SimpleSAMLphp.

      Step 3 — Configuring SimpleSAMLphp

      Next, we need to make several changes to the core SimpleSAMLphp configuration located at /var/simplesamlphp/config/config.php. Open the file in your editor:

      • nano /var/simplesamlphp/config/config.php

      Set the administrator password by locating the 'auth.adminpassword' line and replacing the default value of 123 with a more secure password. This password lets you access some of the pages in your SimpleSAMLphp installation web interface:


      . . .
      'auth.adminpassword'        => 'your_admin_password',
      . . .

      Next, set a secret salt, which should be a randomly-generated string of characters. Some parts of SimpleSAMLphp use this salt to create cryptographically secure hashes. You’ll get errors if the salt isn’t changed from the default value.

      You can use the OpenSSL rand function to generate a random string to use as your secret salt string. Open a new terminal, connect to your server again, and run the following command to generate this string:

      The -base64 32 option ensures a Base64 encoded string that is 32 characters long.

      Then, in the configuration file, locate the 'secretsalt' entry and replace defaultsecretsalt with the string you generated:


      . . .
      'secretsalt' => 'your_generated_salt',
      . . .

      Then set the technical contact information. This information will be available in the generated metadata, and SimpleSAMLphp will send automatically-generated error reports to the email address you specify. Locate the following section:


      . . .
      'technicalcontact_name'     => 'Administrator',
      'technicalcontact_email'    => '',
      . . .

      Replace Administrator and with appropriate values.

      Then set the timezone you would like to use. Locate this section:


      . . .
      'timezone' => null,
      . . .

      Replace null with a preferred time zone from this list of timezones for PHP. Be sure to enclose the value in quotes:


      . . .
      'timezone' => 'America/New_York',
      . . .

      Save and close the file. You should now be able to access the site in your browser by visiting https://your_domain/simplesaml. You’ll see the following screen in your browser:

      simplesaml web interface

      To make sure your PHP installation meets all requirements for SimpleSAMLphp to run smoothly, select the Configuration tab and click on the Login as administrator link. Then use the administrator password you set in the configuration file in Step 3.

      Once logged in, you’ll see a list of required and optional PHP extensions used by SimpleSAMLphp. Check that you have installed every extension except predis/predis:

      All extensions installed

      If there are any required components missing, review this tutorial and install the missing components before you move on.

      You’ll also see a link that says Sanity check of your SimpleSAMLphp setup. Click this link to get a list of checks applied to your setup to see whether they are successful.

      Let’s move on to configure an authentication source for for SimpleSAMLphp.

      Step 4 — Configuring the Authentication Source

      Now that we have SimpleSAMLphp installed and set up, let’s configure an authentication source so we can authenticate users. We will use a MySQL database to store a list of usernames and passwords to authenticate against.

      To get started, log in to the MySQL root account:

      You will be prompted for the MySQL root account password. Provide it to proceed.

      Next, create a database that will act as the authentication source. We’ll call it auth. Feel free to name yours differently:

      • CREATE DATABASE auth DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

      Now let’s create a separate MySQL user to exclusively operate on our auth database. From a management and security standpoint, it is a good practice to create one-function databases and accounts. We will name our user authuser. Execute the following command to create the user, set a password, and grant it access to our auth database. Remember to provide a strong password here for your new database user.

      • GRANT ALL ON auth.* TO 'authuser'@'localhost' IDENTIFIED BY 'your_mysql_auth_user_password';

      Now create a users table, which will be made up of two fields: username and password. For some additional security, we are going to use the MySQL AES_ENCRYPT() function to encrypt the password string so we don’t store the passwords in plain text. This function encrypts a string and returns a binary string.

      • CREATE TABLE auth.users(username VARCHAR(30), password VARBINARY(30));

      Then insert three users into the newly created table. This is where we’ll use the AES_ENCRYPT() function to encrypt the values for the password field. You need to provide a string that’s used as an encryption key. Make sure to replace this with your own string, which can be any string you’d like, as long as it’s complex.

      • INSERT INTO auth.users(username, password) VALUES
      • ('user1', AES_ENCRYPT('user1pass','your_secret_key')),
      • ('user2', AES_ENCRYPT('user2pass','your_secret_key')),
      • ('user3', AES_ENCRYPT('user3pass','your_secret_key'));

      Use the same key for each user, and be sure to remember the key so you can use it again to create additional users in the future. You’ll also use this secret key in the SimpleSAMLphp configuration so you can decrypt the passwords and compare them with the ones users enter.

      We need to flush the privileges so that the current instance of MySQL knows about the recent privilege changes we’ve made:

      Exit out of the MySQL prompt by typing:

      To enable the identity provider functionality in SimpleSAMLphp, we need to edit the /var/simplesamlphp/config/config.php file. There are several options available but since this guide focuses on SAML 2.0 support, we want to enable the enable.saml20-idp option. To do that, open the /var/simplesamlphp/config/config.phpand enable SAML 2.0 support:

      • nano /var/simplesamlphp/config/config.php

      Locate this section of the file and replace false with true. :


      'enable.saml20-idp' => true,

      Then save the file and exit the editor.

      Now that we have the identity provider functionality enabled, we need to indicate the authentication module to be used. Since we have a users table on a MySQL database, we are going to use the SQL Authentication Module. Open the authsources configuration file:

      • nano /var/simplesamlphp/config/authsources.php

      Locate the following block, which is commented out:


          'example-sql' => array(
              'dsn' => ';port=5432;dbname=simplesaml',
              'username' => 'simplesaml',
              'password' => 'secretpassword',
              'query' => 'SELECT uid, givenName, email, eduPersonPrincipalName FROM users WHERE uid = :username AND password = SHA2(CONCAT((SELECT salt FROM users WHERE uid = :username), :password),256);',

      This code defines a database connection and a query that SimpleSAMLphp can use to look up a user in a database table called users. We need to uncomment it and change the query to look up a user from our table using MySQL’s AES_DECRYPT() function. We’ll need to provide the AES_DECRYPT() function the same key we used to encrypt the passwords in the query.

      Modify the section of the file to specify the database connection details and the query:


          'example-sql' => array(
              'dsn' => 'mysql:host=localhost;port=5432;dbname=auth',
              'username' => 'authuser',
              'password' => 'your_mysql_auth_user_password',
              'query' => 'SELECT username FROM users WHERE username = :username AND AES_DECRYPT(password,"your_secret_key") = :password',

      Be sure to place the secret key you specified in place of your_secret_key.

      Save and close the file. Let’s test our identity provider.

      Step 5 — Testing the Identity Provider with the SAML 2.0 SP Demo

      You can test the MySQL authentication source you just set up by navigating to the Authentication tab and clicking on the Test configured authentication sources link. You will be presented with a list of authentication sources already configured.

      The list of configured authentication sources

      Click example-sql, as this is the provider you configured in the previous step. A prompt to enter a username and password will appear. Enter any of the three test user and password combinations you inserted in the MySQL users table. Try user1 with the password user1pass.

      With a successful attempt, you will be presented with the SAML 2.0 SP Demo Example page:

      The successful Demo page

      If you’re unable to log in and you know the password is correct, ensure that you used the same key with both the AES_ENCRYPT() function when you created the user, and the AES_DECRYPT() function when you looked up the user.

      You can now integrate SimpleSAMLphp with your own applications by following the SimpleSAMLphp API documentation.


      You now have the SimpleSAMLphp application appropriately installed and configured on your Ubuntu 18.04 VPS. SimpleSAMLphp also allows for extensive user interface customization through theming. You can refer to their theming docs for more on that.

      Source link