One place for hosting & domains


      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

      How to Use One-Time Passwords for Two-Factor Authentication with SSH on Ubuntu 18.04 LTS

      Updated by Linode

      Contributed by

      In this guide, you’ll learn how to use one-time passwords for two-factor authentication with SSH on Ubuntu 18.04 LTS. No matter what kind of data you’re hosting, securing access to your Linode is a critical step in preventing your information from being compromised. By default, you will need a password to log in, and you may also configure an authentication key-pair for even greater security. However, another option exists to complement these methods: time-based one-time passwords (TOTPs).

      TOTPs allow you to enable two-factor authentication for SSH with single-use passwords that change every 30 seconds. By combining this method with a regular password or publickey (or both), you can add an extra layer of security, further ensuring your server is sufficiently protected.

      This guide will explain how to install the necessary software, configure your system to use two-factor authentication (2FA), and use your new time-based one-time password (TOTP) in combination with existing security features.

      Before You Begin

      1. This guide is meant to be used with a Linode running Ubuntu 18.04 LTS. Familiarize yourself with our Getting Started guide and complete the steps for setting your Linode’s hostname, updating your system’s hosts file, and setting the timezone.

      2. Complete the sections of our Securing Your Server guide to create a standard user account, and remove unnecessary network services. This guide will explain a different way to harden SSH access, but you can also use public key authentication in addition for even greater protection. That method will be covered in the optional section, Combine Two-Factor and Public Key Authentication.


      3. You will need a smartphone or another client device with an authenticator application such as Google Authenticator or Authy. Many other options exist, and this guide should be compatible with nearly all of them.

      4. Update your system:

        sudo apt-get update && sudo apt-get upgrade


        This guide is written for a non-root user. Commands that require elevated privileges are prefixed with sudo. If you’re not familiar with the sudo command, you can check our Users and Groups guide.

      Install Google Authenticator

      In this section, we’ll install the Google Authenticator package, which is included in the default repository of Ubuntu 18.04 LTS. This software will generate keys on your Linode, which will then be paired with an app on a client device (often a smartphone) to generate single-use passwords that expire after a set period of time.

      1. Install Google Authenticator:

        sudo apt-get install libpam-google-authenticator

        Although we are using the Google Authenticator package, the keys it generates are compatible with other authentication apps.

      Generate a Key

      Now that you’ve installed the Google Authenticator package, you’ll use it to generate keys. These keys are then used by software on client devices to generate time-based one-time passwords (TOTPs). To understand the difference between these passwords and the ones you already use, let’s break down the concept of a TOTP:

      • Time-based – The generated password will change every 30-60 seconds. This means that if an attacker tries to use brute force, they’ll almost certainly run out of time before new credentials are needed to gain access.
      • One-time – The password will be valid for a single authentication only, thus minimizing the risk of a replay attack. Even if your TOTP is intercepted upon sending it to the server, it will no longer be valid after you’ve logged in.

      The following instructions will generate a password for the user running the commands. If you are configuring two-factor authentication for multiple users, perform these steps for each user.


      Be sure to have your phone or mobile device ready, since this is where you’ll add the password to your authenticator app. If you haven’t downloaded an authenticator app, do so before proceeding.
      1. Run the google-authenticator program. A prompt will appear asking you to specify whether you’d like to use a time-based authentication (as opposed to one-time or counter-based). Choose “yes” by entering y at the prompt.

      2. You should see a QR code in your terminal:

        The Google Authenticator QR Code and keys on Ubuntu 18.04.

        Using the authenticator app on your phone or mobile device, scan the code. A new entry should be added to your authenticator app in the format [email protected].

        You’ll also see a “secret key” below the QR code. You may enter this into the app manually, instead of scanning the QR code, to add your account.

      3. Record your emergency scratch codes in a secure location. These codes can be used for authentication if you lose your device, but be aware that each code is only valid once.

      4. You’ll be prompted to answer the following questions:

        Do you want me to update your "/home/exampleuser/.google_authenticator" file (y/n)

        This specifies whether the authentication settings will be set for this user. Answer y to create the file that stores these settings.

        Do you want to disallow multiple uses of the same authentication
        token? This restricts you to one login about every 30s, but it increases
        your chances to notice or even prevent man-in-the-middle attacks (y/n)

        This makes your token a true one-time password, preventing the same password from being used twice. For example, if you set this to “no,” and your password was intercepted while you logged in, someone may be able to gain entry to your server by entering it before the time expires. We strongly recommend answering y.

        By default, a new token is generated every 30 seconds by the mobile app.
        In order to compensate for possible time-skew between the client and the server,
        we allow an extra token before and after the current time. This allows for a
        time skew of up to 30 seconds between authentication server and client. If you
        experience problems with poor time synchronization, you can increase the window
        from its default size of 3 permitted codes (one previous code, the current
        code, the next code) to 17 permitted codes (the 8 previous codes, the current
        code, and the 8 next codes). This will permit for a time skew of up to 4 minutes
        between client and server.
        Do you want to do so (y/n)

        This setting accounts for time syncing issues across devices. Unless you have reason to believe that your phone or device may not sync properly, answer n.

        If the computer that you are logging into isn't hardened against brute-force
        login attempts, you can enable rate-limiting for the authentication module.
        By default, this limits attackers to no more than 3 login attempts every 30s.
        Do you want to enable rate-limiting (y/n)

        This setting prevents attackers from using brute force to guess your token. Although the time limit should be enough to prevent most attacks, this will ensure that an attacker only has three chances per 30 seconds to guess your password. We recommend answering y.

      5. Before you log out, review the next section carefully to avoid getting locked out of your Linode.

      You have finished generating your key and adding it to your client, but some additional configuration is needed before these settings will go into effect. Carefully read the following section in this guide for instructions on how to require two-factor authentication for all SSH login attempts.

      Configure Authentication Settings

      The TOTP authentication methods in this guide use PAM, or Pluggable Authentication Modules. PAM integrates low-level authentication mechanisms into modules that can be configured for different applications and services. Because you’re using additional software (i.e., programs that aren’t built into the Linux distro), you’ll need to configure PAM to properly authenticate users.


      • It is strongly recommended that you have another terminal session open while configuring your authentication settings. This way, if you disconnect to test authentication and something is not properly configured, you won’t be locked out of your Linode. You can also use Lish to regain access.

      • If you or a user on your system use this method, be sure that the SSH key and authenticator app are on different devices. This way, if one device is lost or compromised, your credentials will still be separate and the security of two-factor authentication will remain intact.

      1. Open /etc/pam.d/sshd with sudo privileges, and add the following lines to the end of the file:

        auth    required     no_warn try_first_pass
        auth    required

        The first line tells PAM to authenticate with a normal Unix user password before other methods. The second line specifies an additional method of authentication, which in this case, is the TOTP software we installed earlier.

      2. Edit /etc/ssh/sshd_config to include the following lines, replacing example-user with any system user for which you’d like to enable two-factor authentication. Comments (preceded by #) are included here, but should not be added to your actual configuration file:

        # This line already exists in the file, and should be changed from 'no' to 'yes'
        ChallengeResponseAuthentication yes
        # These lines should be added to the end of the file
        Match User example-user
            AuthenticationMethods keyboard-interactive

        If you created TOTPs for multiple users, and you’d like to have them all use two-factor authentication, create additional Match User blocks for each user, duplicating the command format shown above.


        If you want to enforce two-factor authentication globally, you can use the AuthenticationMethods directive by itself, outside of a Match User block. However, this should not be done until two-factor credentials have been provided to all users.

      3. Restart the SSH daemon to apply these changes:

        sudo systemctl restart ssh

        Two-factor authentication is now enabled. When you connect to your Linode via SSH, the authentication process will proceed as shown in the diagram.

        Two-factor authentication with SSH login.

      4. Open a new terminal session and test your configuration by connecting to your Linode via SSH. You will be prompted to enter in your standard user account’s password and then, you will be prompted to enter in a Verification Code. Open your authorization app, select the account you created in the Generate a Key section and enter in the password that is displayed. You should authenticate successfully and gain access to your Linode.


      If your SSH client disconnects before you can enter your two-factor token, check if PAM is enabled for SSH. You can do this by editing /etc/ssh/sshd_config: look for UsePAM and set it to yes. Don’t forget to restart the SSH daemon.

      Combine Two-Factor and Public Key Authentication (Optional)

      This section is optional. If you’d like to use public key authentication instead of a password authentication with TOTP, follow the steps in this section.


      1. Set PasswordAuthentication to no and modify the AuthenticationMethods line in /etc/ssh/sshd_config to include publickey:

        PasswordAuthentication no
        Match User example-user
            AuthenticationMethods publickey,keyboard-interactive

        Configure this setting in the AuthenticationMethods directive for each user as appropriate. When any of these users log in, they will need to provide their SSH key and they will be authenticated via TOTP, as well.

      2. Restart your SSH daemon to apply these changes.

        sudo systemctl restart ssh
      3. Next, you’ll need to make changes to your PAM configuration. Comment out or omit the following lines in your /etc/pam.d/sshd file:

        # @include common-auth
        # auth    required     no_warn try_first_pass

        You should now be able to log in using your SSH key as the first method of authentication and your verification code as the second. To test your configuration, log out and try to log in again via SSH. You should be asked for your 6-digit verification code only, since the key authentication will not produce a prompt.

      Next Steps

      First, be sure you have followed our guide to Securing Your Server. Although there is no single, foolproof method to protecting your data, firewalls and services like Fail2Ban are a great way to minimize risk.

      When you use two-factor authentication with TOTPs, an important point to consider is the physical security of the device on which you’ve configured your authenticator app. Be sure your phone or device is secured with a passphrase, so that even if it falls into the wrong hands, it can’t easily be used to compromise your server. If you lose the phone or device that stores your credentials, you can use Lish to access your Linode and disable two-factor authentication. If this happens, you should switch to a different, hardened method of SSH access, such as public key authentication, in the interim.

      While two-factor authentication may be a valuable security feature, total security is an ongoing process, not an end goal that can be achieved by adding extra layers of authentication. To provide the best protection for your data, take care to follow security best practices at all times.

      More Information

      You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

      This guide is published under a CC BY-ND 4.0 license.

      Source link