One place for hosting & domains

      Server

      Install Plex Media Server on Ubuntu 18.04 Using Salt Masterless


      Updated by Linode Contributed by Linode

      Plex is a media server that allows you to stream video and audio content that you own to many different types of devices. In this guide you will learn how to use a masterless Salt minion to set up a Plex server, attach and use a Block Storage Volume, and how to connect to your media server to stream content to your devices.

      Before You Begin

      1. Familiarize yourself with our Getting Started guide and complete the steps for setting your Linode’s hostname and timezone.

      2. Follow the steps in the How to Secure Your Server guide.

      3. Update your system:

        sudo apt-get update && sudo apt-get upgrade
        
      4. You will need to create a Block Storage Volume and attach it to your Linode. You will format and mount the drive as part of this guide. This volume will be used to store your media, so you should pick a size that’s appropriate for your media collection, though you can resize the volume later if you need more storage. For more on Block Storage, see our How to Use Block Storage guide.

      5. Plex requires an account to use their service. Visit the Plex website to sign up for an account if you do not already have one.

      Note

      The steps in this guide require root privileges. Be sure to run the steps below with the sudo prefix. For more information on privileges, see our Users and Groups guide.

      Prepare the Salt Minion

      1. On your Linode, create the /srv/salt and /srv/pillar directories. These are where the Salt state files and Pillar files will be housed.

        mkdir /srv/salt && mkdir /srv/pillar
        
      2. Install salt-minion via the Salt bootstrap script:

        curl -L https://bootstrap.saltstack.com -o bootstrap_salt.sh
        sudo sh bootstrap_salt.sh
        
      3. The Salt minion will use the official Plex Salt Formula, which is hosted on the SaltStack GitHub repository. In order to use a Salt formula hosted on an external repository, you will need GitPython installed. Install GitPython:

        sudo apt-get install python-git
        

      Modify the Salt Minion Configuration

      1. Because the Salt minion is running in masterless mode, you will need to modify the minion configuration file (/etc/salt/minion) to instruct Salt to look for state files locally. Open the minion configuration file in a text editor, uncomment the line #file_client: remote, and set it to local:

        /etc/salt/minion
        1
        2
        3
        4
        5
        6
        7
        8
        9
        
        ...
        
        # Set the file client. The client defaults to looking on the master server for
        # files, but can be directed to look at the local file directory setting
        # defined below by setting it to "local". Setting a local file_client runs the
        # minion in masterless mode.
        file_client: local
        
        ...
      2. There are some configuration values that do not normally exist in /etc/salt/minion which you will need to add in order to run your minion in masterless mode. Copy the following lines into the end of /etc/salt/minion:

        /etc/salt/minion
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        
        ...
        
        fileserver_backend:
          - roots
          - gitfs
        
        gitfs_remotes:
          - https://github.com/saltstack-formulas/plex-formula.git
        
        gitfs_provider: gitpython

        The fileserver_backend block instructs the Salt minion to look for Salt configuration files in two places. First, it tells Salt to look for Salt state files in our minion’s roots backend (/srv/salt). Secondly, it instructs Salt to use the Git Fileserver (gitfs) to look for Salt configuration files in any Git remote repositories that have been named in the gitfs_remotes section. The address for the Plex Salt formula’s Git repository is included in the gitfs_remotes section.

        Note

        It is best practice to create a fork of the Plex formula’s Git repository on GitHub and to add your fork’s Git repository address in the gitfs_remotes section. This will ensure that any further changes to the upstream Plex formula which might break your current configuration can be reviewed and handled accordingly, before applying them.

        Lastly, GitPython is specified as the gitfs_provider.

      Create the Salt State Tree

      1. Create a Salt state top file at /srv/salt/top.sls and copy in the following configuration. This file tells Salt to look for state files in the plex folder of the Plex formula’s Git repository, and for a state files named disk.sls and directory.sls, which you will create in the next steps.

        /srv/salt/top.sls
        1
        2
        3
        4
        5
        
        base:
          '*':
            - plex
            - disk
            - directory
      2. Create the disk.sls file in /srv/salt:

        /srv/salt/disk.sls
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        
        disk.format:
          module.run:
            - device: /dev/disk/by-id/scsi-0Linode_Volume_{{ pillar['volume_name'] }}
            - fs_type: ext4
        
        /mnt/plex:
          mount.mounted:
            - device: /dev/disk/by-id/scsi-0Linode_Volume_{{ pillar['volume_name'] }}
            - fstype: ext4
            - mkmnt: True
            - persist: True

        This file instructs Salt to prepare your Block Storage Volume for use with Plex. It first formats your Block Storage Volume with the ext4 filesystem type by using the disk.format Salt module, which can be run in a state file using module.run. Then disk.sls instructs Salt to mount your volume at /mnt/plex, creating the mount target if it does not already exist with mkmnt, and persisting the mount to /etc/fstab so that the volume is always mounted at boot.

      3. Create the directory.sls file in /srv/salt:

        /srv/salt/directory.sls
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        
        /mnt/plex/plex-media:
          file.directory:
            - require:
              - mount: /mnt/plex
            - user: username
            - group: plex
        
        /mnt/plex/plex-media/movies:
          file.directory:
            - require:
              - mount: /mnt/plex
            - user: username
            - group: plex
        
        /mnt/plex/plex-media/television:
          file.directory:
            - require:
              - mount: /mnt/plex
            - user: username
            - group: plex

        The directories that are created during this step are for organizational purposes, and will house your media. Make sure you replace username with the name of the limited user account you created when following the How to Secure Your Server guide. The location of the directories is the volume you mounted in the previous step. If you wish to add more directories, perhaps one for your music media, you can do so here, just be sure to include the - require block, as this prevents Salt from trying to create the directory before the Block Storage Volume has been mounted.

      4. Go to the Plex Media Server download page and note the most recent version of their Linux distribution. At the time of writing, the most recent version is 1.13.9.5456-ecd600442. Create the plex.sls Pillar file in /srv/pillar and change the Plex version number and the name of your Block Storage Volume as necessary:

        /srv/pillar/plex.sls
        1
        2
        3
        
        plex:
          version: 1.13.9.5456-ecd600442
        volume_name: plex
      5. Create the Salt Pillar top file in /srv/pillar. This file will instruct Salt to look for the plex.sls Pillar file you created in the previous step.

        /srv/pillar/top.sls
      6. Apply your Salt state locally using salt-call:

        salt-call --local state.apply
        

        You should see a list of the changes Salt applied to your system. You have successfully installed Plex using Salt.

      Set Up Plex

      Initial Configuration

      1. You’ll need to create an SSH tunnel to your Linode to connect to Plex’s web UI. On your local computer, run the following command, replacing <your_ip_address> with your Plex server’s IP address.:

        ssh username@<your_ip_address> -L 8888:localhost:32400
        
      2. In a browser, navigate to http://localhost:8888/web/.

      3. Sign in with your Plex username and password.

      4. Name your media server. This example uses the name linode-plex. Be sure to check the box that reads Allow me to access my media outside my home and then click Next.

        Name your media server

      Organize Your Media

      1. Click on the Add Library button:

        Click on Add Media

      2. Select Movies and click Next:

        Select Movies and click next

      3. Click Browse for Media Folder and select the appropriate folder at /mnt/plex/plex-media/movies. Then click Add:

        Select the appropriate folder

      4. Repeat the process to add your ‘Television’ folder.

      5. When you are done adding your libraries, click Add Library.

      6. To continue the configuration process, click Next.

      7. Click on Get Plex Apps to download the appropriate Plex client for your device. Then click Done.

        Download the appropriate client for your device

      8. In the future you can add more libraries by hovering over the menu and clicking the plus sign (+) next to LIBRARIES.

        Add more libraries

      DLNA is a protocol that incorporates Universal Plug and Play (or UPnP) standards for digital media sharing across devices. If you do not wish to make use of it, it’s recommended that you disable this feature, as it is openly connectable on port 1900. From the Plex web interface, click the wrench icon in the upper right corner, and navigate to the DLNA section under SETTINGS. Uncheck Enable the DLNA server, and click Save Changes:

      Disable DLNA

      Connect to Your Plex Server

      1. Visit the Plex Apps download page or the app store on your device to download Plex Media Player if you have not already done so.

      2. Open your Plex app. The example provided here will use the Plex Media Player for macOS.

      3. Sign in to Plex.

      4. On the left there’s a dropdown menu where you can select your server by the name you chose. Select your server.

        Connect to your Plex Server

      5. You are now able to stream your content with Plex.

        Plex's macOS App

      1. You can use SCP to transfer media to your server from your local computer. Replace your username and 123.456.7.8 with the IP address of your Linode.

        scp example_video.mp4 username@123.456.7.8:/mnt/plex/plex-media/movies
        
      2. Once you’ve transferred files to your Plex media server, you may need to scan for new files before they show up in your Library. Click on the ellipsis next to a Library and select Scan Library Files.

        Scan your Library for new files

      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.

      Find answers, ask questions, and help others.

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



      Source link

      How to Install and Configure pgAdmin 4 in Server Mode


      Introduction

      pgAdmin is an open-source administration and development platform for PostgreSQL and its related database management systems. Written in Python and jQuery, it supports all the features found in PostgreSQL. You can use pgAdmin to do everything from writing basic SQL queries to monitoring your databases and configuring advanced database architectures.

      In this tutorial, we’ll walk through the process of installing and configuring the latest version of pgAdmin onto an Ubuntu 18.04 server, accessing pgAdmin through a web browser, and connecting it to a PostgreSQL database on your server.

      Prerequisites

      To complete this tutorial, you will need:

      Step 1 — Installing pgAdmin and its Dependencies

      As of this writing, the most recent version of pgAdmin is pgAdmin 4, while the most recent version available through the official Ubuntu repositories is pgAdmin 3. pgAdmin 3 is no longer supported though, and the project maintainers recommend installing pgAdmin 4. In this step, we will go over the process of installing the latest version of pgAdmin 4 within a virtual environment (as recommended by the project’s development team) and installing its dependencies using apt.

      To begin, update your server’s package index if you haven’t done so recently:

      Next, install the following dependencies. These include libgmp3-dev, a multiprecision arithmetic library; libpq-dev, which includes header files and a static library that helps communication with a PostgreSQL backend; and libapache2-mod-wsgi-py3, an Apache module that allows you to host Python-based web applications within Apache:

      • sudo apt install libgmp3-dev libpq-dev libapache2-mod-wsgi-py3

      Following this, create a few directories where pgAdmin will store its sessions data, storage data, and logs:

      • sudo mkdir -p /var/lib/pgadmin4/sessions
      • sudo mkdir /var/lib/pgadmin4/storage
      • sudo mkdir /var/log/pgadmin4

      Then, change ownership of these directories to your non-root user and group. This is necessary because they are currently owned by your root user, but we will install pgAdmin from a virtual environment owned by your non-root user, and the installation process involves creating some files within these directories. After the installation, however, we will change the ownership over to the www-data user and group so it can be served to the web:

      • sudo chown -R sammy:sammy /var/lib/pgadmin4
      • sudo chown -R sammy:sammy /var/log/pgadmin4

      Next, open up your virtual environment. Navigate to the directory your programming environment is in and activate it. Following the naming conventions of the prerequisite Python 3 tutorial, we’ll go to the environments directory and activate the my_env environment:

      • cd environments/
      • source my_env/bin/activate

      Following this, download the pgAdmin 4 source code onto your machine. To find the latest version of the source code, navigate to the pgAdmin 4 (Python Wheel) Download page and click the link for the latest version (v3.4, as of this writing). This will take you to a Downloads page on the PostgreSQL website. Once there, copy the file link that ends with .whl — the standard built-package format used for Python distributions. Then go back to your terminal and run the following wget command, making sure to replace the link with the one you copied from the PostgreSQL site, which will download the .whl file to your server:

      • wget https://ftp.postgresql.org/pub/pgadmin/pgadmin4/v3.4/pip/pgadmin4-3.4-py2.py3-none-any.whl

      Next install the wheel package, the reference implementation of the wheel packaging standard. A Python library, this package serves as an extension for building wheels and includes a command line tool for working with .whl files:

      • python -m pip install wheel

      Then install pgAdmin 4 package with the following command:

      • python -m pip install pgadmin4-3.4-py2.py3-none-any.whl

      That takes care of installing pgAdmin and its dependencies. Before connecting it to your database, though, there are a few changes you’ll need to make to the program’s configuration.

      Step 2 — Configuring pgAdmin 4

      Although pgAdmin has been installed on your server, there are still a few steps you must go through to ensure it has the permissions and configurations needed to allow it to correctly serve the web interface.

      pgAdmin’s main configuration file, config.py, is read before any other configuration file. Its contents can be used as a reference point for further configuration settings that can be specified in pgAdmin’s other config files, but to avoid unforeseen errors, you should not edit the config.py file itself. We will add some configuration changes to a new file, named config_local.py, which will be read after the primary one.

      Create this file now using your preferred text editor. Here, we will use nano:

      • nano my_env/lib/python3.6/site-packages/pgadmin4/config_local.py

      In your editor, add the following content:

      environments/my_env/lib/python3.6/site-packages/pgadmin4/config_local.py

      LOG_FILE = '/var/log/pgadmin4/pgadmin4.log'
      SQLITE_PATH = '/var/lib/pgadmin4/pgadmin4.db'
      SESSION_DB_PATH = '/var/lib/pgadmin4/sessions'
      STORAGE_DIR = '/var/lib/pgadmin4/storage'
      SERVER_MODE = True
      

      Here are what these five directives do:

      • LOG_FILE: this defines the file in which pgAdmin’s logs will be stored.
      • SQLITE_PATH: pgAdmin stores user-related data in an SQLite database, and this directive points the pgAdmin software to this configuration database. Because this file is located under the persistent directory /var/lib/pgadmin4/, your user data will not be lost after you upgrade.
      • SESSION_DB_PATH: specifies which directory will be used to store session data.
      • STORAGE_DIR: defines where pgAdmin will store other data, like backups and security certificates.
      • SERVER_MODE: setting this directive to True tells pgAdmin to run in Server mode, as opposed to Desktop mode.

      Notice that each of these file paths point to the directories you created in Step 1.

      After adding these lines, save and close the file (press CTRL + X, followed by Y and then ENTER). With those configurations in place, run the pgAdmin setup script to set your login credentials:

      • python my_env/lib/python3.6/site-packages/pgadmin4/setup.py

      After running this command, you will see a prompt asking for your email address and a password. These will serve as your login credentials when you access pgAdmin later on, so be sure to remember or take note of what you enter here:

      Output

      . . . Enter the email address and password to use for the initial pgAdmin user account: Email address: sammy@example.com Password: Retype password:

      Following this, deactivate your virtual environment:

      Recall the file paths you specified in the config_local.py file. These files are held within the directories you created in Step 1, which are currently owned by your non-root user. They must, however, be accessible by the user and group running your web server. By default on Ubuntu 18.04, these are the www-data user and group, so update the permissions on the following directories to give www-data ownership over both of them:

      • sudo chown -R www-data:www-data /var/lib/pgadmin4/
      • sudo chown -R www-data:www-data /var/log/pgadmin4/

      With that, pgAdmin is fully configured. However, the program isn't yet being served from your server, so it remains inaccessible. To resolve this, we will configure Apache to serve pgAdmin so you can access its user interface through a web browser.

      Step 3 — Configuring Apache

      The Apache web server uses virtual hosts to encapsulate configuration details and host more than one domain from a single server. If you followed the prerequisite Apache tutorial, you may have set up an example virtual host file under the name example.com.conf, but in this step we will create a new one from which we can serve the pgAdmin web interface.

      To begin, make sure you're in your root directory:

      Then create a new file in your /sites-available/ directory called pgadmin4.conf. This will be your server’s virtual host file:

      • sudo nano /etc/apache2/sites-available/pgadmin4.conf

      Add the following content to this file, being sure to update the highlighted parts to align with your own configuration:

      /etc/apache2/sites-available/pgadmin4.conf

      <VirtualHost *>
          ServerName your_server_ip
      
          WSGIDaemonProcess pgadmin processes=1 threads=25 python-home=/home/sammy/environments/my_env
          WSGIScriptAlias / /home/sammy/environments/my_env/lib/python3.6/site-packages/pgadmin4/pgAdmin4.wsgi
      
          <Directory "/home/sammy/environments/my_env/lib/python3.6/site-packages/pgadmin4/">
              WSGIProcessGroup pgadmin
              WSGIApplicationGroup %{GLOBAL}
              Require all granted
          </Directory>
      </VirtualHost>
      

      Save and close the virtual host file. Next, use the a2dissite script to disable the default virtual host file, 000-default.conf:

      • sudo a2dissite 000-default.conf

      Note: If you followed the prerequisite Apache tutorial, you may have already disabled 000-default.conf and set up an example virtual host configuration file (named example.com.conf in the prerequisite). If this is the case, you will need to disable the example.com.conf virtual host file with the following command:

      • sudo a2dissite example.com.conf

      Then use the a2ensite script to enable your pgadmin4.conf virtual host file. This will create a symbolic link from the virtual host file in the /sites-available/ directory to the /sites-enabled/ directory:

      • sudo a2ensite pgadmin4.conf

      Following this, test that your configuration file’s syntax is correct:

      If your configuration file is all in order, you will see Syntax OK. If you see an error in the output, reopen the pgadmin4.conf file and double check that your IP address and file paths are all correct, then rerun the configtest.

      Once you see Syntax OK in your output, restart the Apache service so it reads your new virtual host file:

      • sudo systemctl restart apache2

      pgAdmin is now fully installed and configured. Next, we'll go over how to access pgAdmin from a browser before connecting it to your PostgreSQL database.

      Step 4 — Accessing pgAdmin

      On your local machine, open up your preferred web browser and navigate to your server’s IP address:

      http://your_server_ip
      

      Once there, you’ll be presented with a login screen similar to the following:

      pgAdmin login screen

      Enter the login credentials you defined in Step 2, and you’ll be taken to the pgAdmin Welcome Screen:

      pgAdmin Welcome Page

      Now that you've confirmed you can access the pgAdmin interface, all that's left to do is to connect pgAdmin to your PostgreSQL database. Before doing so, though, you'll need to make one minor change to your PostgreSQL superuser's configuration.

      Step 5 — Configuring your PostgreSQL User

      If you followed the prerequisite PostgreSQL tutorial, you should already have PostgreSQL installed on your server with a new superuser role and database set up.

      By default in PostgreSQL, you authenticate as database users using the "Identification Protocol," or "ident," authentication method. This involves PostgreSQL taking the client's Ubuntu username and using it as the allowed database username. This can allow for greater security in many cases, but it can also cause issues in instances where you'd like an outside program, such as pgAdmin, to connect to one of your databases. To resolve this, we will set a password for this PostgreSQL role which will allow pgAdmin to connect to your database.

      From your terminal, open the PostgreSQL prompt under your superuser role:

      From the PostgreSQL prompt, update the user profile to have a strong password of your choosing:

      • ALTER USER sammy PASSWORD 'password';

      Then exit the PostgreSQL prompt:

      Next, go back to the pgAdmin 4 interface in your browser, and locate the Browser menu on the left hand side. Right-click on Servers to open a context menu, hover your mouse over Create, and click Server….

      Create Server context menu

      This will cause a window to pop up in your browser in which you'll enter info about your server, role, and database.

      In the General tab, enter the name for this server. This can be anything you'd like, but you may find it helpful to make it something descriptive. In our example, the server is named Sammy-server-1.

      Create Server - General tab

      Next, click on the Connection tab. In the Host name/address field, enter localhost. The Port should be set to 5432 by default, which will work for this setup, as that's the default port used by PostgreSQL.

      In the Maintenance database field, enter the name of the database you'd like to connect to. Note that this database must already be created on your server. Then, enter the PostgreSQL username and password you configured previously in the Username and Password fields, respectively.

      Create Server - Connection tab

      The empty fields in the other tabs are optional, and it's only necessary that you fill them in if you have a specific setup in mind in which they're required. Click the Save button, and the database will appear under the Servers in the Browser menu.

      You've successfully connected pgAdmin4 to your PostgreSQL database. You can do just about anything from the pgAdmin dashboard that you would from the PostgreSQL prompt. To illustrate this, we will create an example table and populate it with some sample data through the web interface.

      Step 6 — Creating a Table in the pgAdmin Dashboard

      From the pgAdmin dashboard, locate the Browser menu on the left-hand side of the window. Click on the plus sign (+) next to Servers (1) to expand the tree menu within it. Next, click the plus sign to the left of the server you added in the previous step (Sammy-server-1 in our example), then expand Databases, the name of the database you added (sammy, in our example), and then Schemas (1). You should see a tree menu like the following:

      Expanded Browser tree menu

      Right-click the Tables list item, then hover your cursor over Create and click Table….

      Create Table context menu

      This will open up a Create-Table window. Under the General tab of this window, enter a name for the table. This can be anything you'd like, but to keep things simple we'll refer to it as table-01.

      Create Table - General tab

      Then navigate to the Columns tab and click the + sign in the upper right corner of the window to add some columns. When adding a column, you're required to give it a Name and a Data type, and you may need to choose a Length if it's required by the data type you've selected.

      Additionally, the official PostgreSQL documentation states that adding a primary key to a table is usually best practice. A primary key is a constraint that indicates a specific column or set of columns that can be used as a special identifier for rows in the table. This isn't a requirement, but if you'd like to set one or more of your columns as the primary key, toggle the switch at the far right from No to Yes.

      Click the Save button to create the table.

      Create Table - Columns Tab with Primary Key turned on

      By this point, you've created a table and added a couple columns to it. However, the columns don't yet contain any data. To add data to your new table, right-click the name of the table in the Browser menu, hover your cursor over Scripts and click on INSERT Script.

      INSERT script context menu

      This will open a new panel on the dashboard. At the top you'll see a partially-completed INSERT statement, with the appropriate table and column names. Go ahead and replace the question marks (?) with some dummy data, being sure that the data you add aligns with the data types you selected for each column. Note that you can also add multiple rows of data by adding each row in a new set of parentheses, with each set of parentheses separated by a comma as shown in the following example.

      If you'd like, feel free to replace the partially-completed INSERT script with this example INSERT statement:

      INSERT INTO public."table-01"(
          col1, col2, col3)
          VALUES ('Juneau', 14, 337), ('Bismark', 90, 2334), ('Lansing', 51, 556);
      

      Example INSERT statement

      Click on the lightning bolt icon () to execute the INSERT statement. To view the table and all the data within it, right-click the name of your table in the Browser menu once again, hover your cursor over View/Edit Data, and select All Rows.

      View/Edit Data, All Rows context menu

      This will open another new panel, below which, in the lower panel's Data Output tab, you can view all the data held within that table.

      View Data - example data output

      With that, you've successfully created a table and populated it with some data through the pgAdmin web interface. Of course, this is just one method you can use to create a table through pgAdmin. For example, it's possible to create and populate a table using SQL instead of the GUI-based method described in this step.

      Conclusion

      In this guide, you learned how to install pgAdmin 4 from a Python virtual environment, configure it, serve it to the web with Apache, and how to connect it to a PostgreSQL database. Additionally, this guide went over one method that can be used to create and populate a table, but pgAdmin can be used for much more than just creating and editing tables.

      For more information on how to get the most out of all of pgAdmin's features, we encourage you to review the project's documentation. You can also learn more about PostgreSQL through our Community tutorials on the subject.



      Source link

      How to Set Up an IKEv2 VPN Server with StrongSwan on Ubuntu 18.04


      Introduction

      A virtual private network, or VPN, allows you to securely encrypt traffic as it travels through untrusted networks, such as those at the coffee shop, a conference, or an airport.

      IKEv2, or Internet Key Exchange v2, is a protocol that allows for direct IPSec tunneling between the server and client. In IKEv2 VPN implementations, IPSec provides encryption for the network traffic. IKEv2 is natively supported on some platforms (OS X 10.11+, iOS 9.1+, and Windows 10) with no additional applications necessary, and it handles client hiccups quite smoothly.

      In this tutorial, you’ll set up an IKEv2 VPN server using StrongSwan on an Ubuntu 18.04 server and connect to it from Windows, macOS, Ubuntu, iOS, and Android clients.

      Prerequisites

      To complete this tutorial, you will need:

      Step 1 — Installing StrongSwan

      First, we’ll install StrongSwan, an open-source IPSec daemon which we’ll configure as our VPN server. We’ll also install the public key infrastructure component so that we can create a certificate authority to provide credentials for our infrastructure.

      Update the local package cache and install the software by typing:

      • sudo apt update
      • sudo apt install strongswan strongswan-pki

      Now that everything’s installed, let’s move on to creating our certificates.

      Step 2 — Creating a Certificate Authority

      An IKEv2 server requires a certificate to identify itself to clients. To help us create the certificate required, the strongswan-pki package comes with a utility to generate a certificate authority and server certificates. To begin, let’s create a few directories to store all the assets we’ll be working on. The directory structure matches some of the directories in /etc/ipsec.d, where we will eventually move all of the items we create. We’ll lock down the permissions so that our private files can’t be seen by other users:

      • mkdir -p ~/pki/{cacerts,certs,private}
      • chmod 700 ~/pki

      Now that we have a directory structure to store everything, we can generate a root key. This will be a 4096-bit RSA key that will be used to sign our root certificate authority.

      Execute these commands to generate the key:

      • ipsec pki --gen --type rsa --size 4096 --outform pem > ~/pki/private/ca-key.pem

      Now that we have a key, we can move on to creating our root certificate authority, using the key to sign the root certificate:

      • ipsec pki --self --ca --lifetime 3650 --in ~/pki/private/ca-key.pem
      • --type rsa --dn "CN=VPN root CA" --outform pem > ~/pki/cacerts/ca-cert.pem

      You can change the distinguished name (DN) values to something else to if you would like. The common name here is just the indicator, so it doesn’t have to match anything in your infrastructure.

      Now that we’ve got our root certificate authority up and running, we can create a certificate that the VPN server will use.

      Step 3 — Generating a Certificate for the VPN Server

      We’ll now create a certificate and key for the VPN server. This certificate will allow the client to verify the server’s authenticity using the CA certificate we just generated.

      First, create a private key for the VPN server with the following command:

      • ipsec pki --gen --type rsa --size 4096 --outform pem > ~/pki/private/server-key.pem

      Now, create and sign the VPN server certificate with the certificate authority’s key you created in the previous step. Execute the following command, but change the Common Name (CN) and the Subject Alternate Name (SAN) field to your VPN server’s DNS name or IP address:

      • ipsec pki --pub --in ~/pki/private/server-key.pem --type rsa
      • | ipsec pki --issue --lifetime 1825
      • --cacert ~/pki/cacerts/ca-cert.pem
      • --cakey ~/pki/private/ca-key.pem
      • --dn "CN=server_domain_or_IP" --san "server_domain_or_IP"
      • --flag serverAuth --flag ikeIntermediate --outform pem
      • > ~/pki/certs/server-cert.pem

      Now that we’ve generated all of the TLS/SSL files StrongSwan needs, we can move the files into place in the /etc/ipsec.d directory by typing:

      • sudo cp -r ~/pki/* /etc/ipsec.d/

      In this step, we’ve created a certificate pair that would be used to secure communications between the client and the server. We’ve also signed the certificates with the CA key, so the client will be able to verify the authenticity of the VPN server using the CA certificate. Now that have all of the certificates ready, we’ll move on to configuring the software.

      Step 4 — Configuring StrongSwan

      StrongSwan has a default configuration file with some examples, but we will have to do most of the configuration ourselves. Let’s back up the file for reference before starting from scratch:

      • sudo mv /etc/ipsec.conf{,.original}

      Create and open a new blank configuration file by typing:

      • sudo nano /etc/ipsec.conf

      First, we’ll tell StrongSwan to log daemon statuses for debugging and allow duplicate connections. Add these lines to the file:

      /etc/ipsec.conf

      config setup
          charondebug="ike 1, knl 1, cfg 0"
          uniqueids=no
      

      Then, we’ll create a configuration section for our VPN. We’ll also tell StrongSwan to create IKEv2 VPN Tunnels and to automatically load this configuration section when it starts up. Append the following lines to the file:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          auto=add
          compress=no
          type=tunnel
          keyexchange=ikev2
          fragmentation=yes
          forceencaps=yes
      

      We’ll also configure dead-peer detection to clear any “dangling” connections in case the client unexpectedly disconnects. Add these lines:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          . . .
          dpdaction=clear
          dpddelay=300s
          rekey=no
      

      Then, we’ll configure the server (left) side IPSec parameters. Add this to the file:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          . . .
          left=%any
          leftid=@server_domain_or_IP
          leftcert=server-cert.pem
          leftsendcert=always
          leftsubnet=0.0.0.0/0
      

      Note: When configuring the server ID (leftid), only include the @ character if your VPN server will be identified by a domain name:

          leftid=@vpn.example.com
      

      If the server will be identified by its IP address, just put the IP address in:

          leftid=203.0.113.7
      

      Next, we can configure the client (right) side IPSec parameters, like the private IP address ranges and DNS servers to use:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          . . .
          right=%any
          rightid=%any
          rightauth=eap-mschapv2
          rightsourceip=10.10.10.0/24
          rightdns=8.8.8.8,8.8.4.4
          rightsendcert=never
      

      Finally, we’ll tell StrongSwan to ask the client for user credentials when they connect:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          . . .
          eap_identity=%identity
      

      The configuration file should look like this:

      /etc/ipsec.conf

      config setup
          charondebug="ike 1, knl 1, cfg 0"
          uniqueids=no
      
      conn ikev2-vpn
          auto=add
          compress=no
          type=tunnel
          keyexchange=ikev2
          fragmentation=yes
          forceencaps=yes
          dpdaction=clear
          dpddelay=300s
          rekey=no
          left=%any
          leftid=@server_domain_or_IP
          leftcert=server-cert.pem
          leftsendcert=always
          leftsubnet=0.0.0.0/0
          right=%any
          rightid=%any
          rightauth=eap-mschapv2
          rightsourceip=10.10.10.0/24
          rightdns=8.8.8.8,8.8.4.4
          rightsendcert=never
          eap_identity=%identity
      

      Save and close the file once you’ve verified that you’ve configured things as shown.

      Now that we’ve configured the VPN parameters, let’s move on to creating an account so our users can connect to the server.

      Step 5 — Configuring VPN Authentication

      Our VPN server is now configured to accept client connections, but we don’t have any credentials configured yet. We’ll need to configure a couple things in a special configuration file called ipsec.secrets:

      • We need to tell StrongSwan where to find the private key for our server certificate, so the server will be able to authenticate to clients.
      • We also need to set up a list of users that will be allowed to connect to the VPN.

      Let’s open the secrets file for editing:

      • sudo nano /etc/ipsec.secrets

      First, we’ll tell StrongSwan where to find our private key:

      /etc/ipsec.secrets

      : RSA "server-key.pem"
      

      Then, we’ll define the user credentials. You can make up any username or password combination that you like:

      /etc/ipsec.secrets

      your_username : EAP "your_password"
      

      Save and close the file. Now that we’ve finished working with the VPN parameters, we’ll restart the VPN service so that our configuration is applied:

      • sudo systemctl restart strongswan

      Now that the VPN server has been fully configured with both server options and user credentials, it’s time to move on to configuring the most important part: the firewall.

      Step 6 — Configuring the Firewall & Kernel IP Forwarding

      With the StrongSwan configuration complete, we need to configure the firewall to forward and allow VPN traffic through.

      If you followed the prerequisite tutorial, you should have a very basic UFW firewall enabled. If you don’t yet have UFW configured, you can create a baseline configuration and enable it by typing:

      • sudo ufw allow OpenSSH
      • sudo ufw enable

      Now, add a rule to allow UDP traffic to the standard IPSec ports, 500 and 4500:

      • sudo ufw allow 500,4500/udp

      Next, we will open up one of UFW’s configuration files to add a few low-level policies for routing and forwarding IPSec packets. Before we do, we need to find which network interface on our server is used for internet access. We can find that by querying for the interface associated with the default route:

      Your public interface should follow the word "dev". For example, this result shows the interface named eth0, which is highlighted below:

      Output

      default via 203.0.113.7 dev eth0 proto static

      When you have your public network interface, open the /etc/ufw/before.rules file in your text editor:

      • sudo nano /etc/ufw/before.rules

      Near the top of the file (before the *filter line), add the following configuration block:

      /etc/ufw/before.rules

      *nat
      -A POSTROUTING -s 10.10.10.0/24 -o eth0 -m policy --pol ipsec --dir out -j ACCEPT
      -A POSTROUTING -s 10.10.10.0/24 -o eth0 -j MASQUERADE
      COMMIT
      
      *mangle
      -A FORWARD --match policy --pol ipsec --dir in -s 10.10.10.0/24 -o eth0 -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1361:1536 -j TCPMSS --set-mss 1360
      COMMIT
      
      *filter
      :ufw-before-input - [0:0]
      :ufw-before-output - [0:0]
      :ufw-before-forward - [0:0]
      :ufw-not-local - [0:0]
      . . .
      

      Change each instance of eth0 in the above configuration to match the interface name you found with ip route. The *nat lines create rules so that the firewall can correctly route and manipulate traffic between the VPN clients and the internet. The *mangle line adjusts the maximum packet segment size to prevent potential issues with certain VPN clients.

      Next, after the *filter and chain definition lines, add one more block of configuration:

      /etc/ufw/before.rules

      . . .
      *filter
      :ufw-before-input - [0:0]
      :ufw-before-output - [0:0]
      :ufw-before-forward - [0:0]
      :ufw-not-local - [0:0]
      
      -A ufw-before-forward --match policy --pol ipsec --dir in --proto esp -s 10.10.10.0/24 -j ACCEPT
      -A ufw-before-forward --match policy --pol ipsec --dir out --proto esp -d 10.10.10.0/24 -j ACCEPT
      

      These lines tell the firewall to forward ESP (Encapsulating Security Payload) traffic so the VPN clients will be able to connect. ESP provides additional security for our VPN packets as they're traversing untrusted networks.

      When you're finished, save and close the file.

      Before we restart the firewall, we'll change some network kernel parameters to allow routing from one interface to another. Open UFW's kernel parameters configuration file:

      • sudo nano /etc/ufw/sysctl.conf

      We'll need to configure a few things here:

      • First, we'll enable IPv4 packet forwarding.
      • We'll disable Path MTU discovery to prevent packet fragmentation problems.
      • We also won't accept ICMP redirects nor send ICMP redirects to prevent man-in-the-middle attacks.

      The changes you need to make to the file are highlighted in the following code:

      /etc/ufw/sysctl.conf

      
      . . .
      
      # Enable forwarding
      # Uncomment the following line
      net/ipv4/ip_forward=1
      
      . . .
      
      # Do not accept ICMP redirects (prevent MITM attacks)
      # Ensure the following line is set
      net/ipv4/conf/all/accept_redirects=0
      
      # Do not send ICMP redirects (we are not a router)
      # Add the following lines
      net/ipv4/conf/all/send_redirects=0
      net/ipv4/ip_no_pmtu_disc=1
      

      Save the file when you are finished. UFW will apply these changes the next time it starts.

      Now, we can enable all of our changes by disabling and re-enabling the firewall:

      • sudo ufw disable
      • sudo ufw enable

      You'll be prompted to confirm the process. Type Y to enable UFW again with the new settings.

      Step 7 – Testing the VPN Connection on Windows, iOS, and macOS

      Now that you have everything set up, it's time to try it out. First, you'll need to copy the CA certificate you created and install it on your client device(s) that will connect to the VPN. The easiest way to do this is to log into your server and output the contents of the certificate file:

      • cat /etc/ipsec.d/cacerts/ca-cert.pem

      You'll see output similar to this:

      Output

      -----BEGIN CERTIFICATE----- MIIFQjCCAyqgAwIBAgIIFkQGvkH4ej0wDQYJKoZIhvcNAQEMBQAwPzELMAkGA1UE . . . EwbVLOXcNduWK2TPbk/+82GRMtjftran6hKbpKGghBVDPVFGFT6Z0OfubpkQ9RsQ BayqOb/Q -----END CERTIFICATE-----

      Copy this output to your computer, including the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- lines, and save it to a file with a recognizable name, such as ca-cert.pem. Ensure the file you create has the .pem extension.

      Alternatively, use SFTP to transfer the file to your computer.

      Once you have the ca-cert.pem file downloaded to your computer, you can set up the connection to the VPN.

      Connecting from Windows

      First, import the root certificate by following these steps:

      1. Press WINDOWS+R to bring up the Run dialog, and enter mmc.exe to launch the Windows Management Console.
      2. From the File menu, navigate to Add or Remove Snap-in, select Certificates from the list of available snap-ins, and click Add.
      3. We want the VPN to work with any user, so select Computer Account and click Next.
      4. We're configuring things on the local computer, so select Local Computer, then click Finish.
      5. Under the Console Root node, expand the Certificates (Local Computer) entry, expand Trusted Root Certification Authorities, and then select the Certificates entry:
        Certificates view

      6. From the Action menu, select All Tasks and click Import to display the Certificate Import Wizard. Click Next to move past the introduction.

      7. On the File to Import screen, press the Browse button and select the certificate file that you've saved. Then click Next.

      8. Ensure that the Certificate Store is set to Trusted Root Certification Authorities, and click Next.

      9. Click Finish to import the certificate.

      Then configure the VPN with these steps:

      1. Launch Control Panel, then navigate to the Network and Sharing Center.
      2. Click on Set up a new connection or network, then select Connect to a workplace.
      3. Select Use my Internet connection (VPN).
      4. Enter the VPN server details. Enter the server's domain name or IP address in the Internet address field, then fill in Destination name with something that describes your VPN connection. Then click Done.

      Your new VPN connection will be visible under the list of networks. Select the VPN and click Connect. You'll be prompted for your username and password. Type them in, click OK, and you'll be connected.

      Connecting from macOS

      Follow these steps to import the certificate:

      1. Double-click the certificate file. Keychain Access will pop up with a dialog that says "Keychain Access is trying to modify the system keychain. Enter your password to allow this."
      2. Enter your password, then click on Modify Keychain
      3. Double-click the newly imported VPN certificate. This brings up a small properties window where you can specify the trust levels. Set IP Security (IPSec) to Always Trust and you'll be prompted for your password again. This setting saves automatically after entering the password.

      Now that the certificate is important and trusted, configure the VPN connection with these steps:

      1. Go to System Preferences and choose Network.
      2. Click on the small "plus" button on the lower-left of the list of networks.
      3. In the popup that appears, Set Interface to VPN, set the VPN Type to IKEv2, and give the connection a name.
      4. In the Server and Remote ID field, enter the server's domain name or IP address. Leave the Local ID blank.
      5. Click on Authentication Settings, select Username, and enter your username and password you configured for your VPN user. Then click OK.

      Finally, click on Connect to connect to the VPN. You should now be connected to the VPN.

      Connecting from Ubuntu

      To connect from an Ubuntu machine, you can set up and manage StrongSwan as a service or use a one-off command every time you wish to connect. Instructions are provided for both.

      Managing StrongSwan as a Service

      1. Update your local package cache: sudo apt update
      2. Install StrongSwan and the related software sudo apt install strongswan libcharon-extra-plugins
      3. Copy the CA certificate to the /etc/ipsec.d/cacerts directory: sudo cp /tmp/ca-cert.pem /etc/ipsec.d/cacerts
      4. Disable StrongSwan so that the VPN doesn't start automatically: sudo systemctl disable --now strongswan
      5. Configure your VPN username and password in the /etc/ipsec.secrets file: your_username : EAP "your_password"
      6. Edit the /etc/ipsec.conf file to define your configuration.

      /etc/ipsec.conf

      config setup
      
      conn ikev2-rw
          right=server_domain_or_IP
          # This should match the `leftid` value on your server's configuration
          rightid=server_domain_or_IP
          rightsubnet=0.0.0.0/0
          rightauth=pubkey
          leftsourceip=%config
          leftid=username
          leftauth=eap-mschapv2
          eap_identity=%identity
          auto=start
      

      To connect to the VPN, type:

      • sudo systemctl start strongswan

      To disconnect again, type:

      • sudo systemctl stop strongswan

      Using a Simple Client for One-Off Connections

      1. Update your local package cache: sudo apt update
      2. Install charon-cmd and related software sudo apt install charon-cmd libcharon-extra-plugins
      3. Move to the directory where you copied the CA certificate: cd <^>/path/to/ca-cert.pem
      4. Connect to the VPN server with charon-cmd using the server's CA certificate, the VPN server's IP address, and the username you configured: sudo charon-cmd --cert ca-cert.pem --host vpn_domain_or_IP --identity your_username
      5. When prompted, provide the VPN user's password.

      You should now be connected to the VPN. To disconnect, press CTRL+C and wait for the connection to close.

      Connecting from iOS

      To configure the VPN connection on an iOS device, follow these steps:

      1. Send yourself an email with the root certificate attached.
      2. Open the email on your iOS device and tap on the attached certificate file, then tap Install and enter your passcode. Once it installs, tap Done.
      3. Go to Settings, General, VPN and tap Add VPN Configuration. This will bring up the VPN connection configuration screen.
      4. Tap on Type and select IKEv2.
      5. In the Description field, enter a short name for the VPN connection. This could be anything you like.
      6. In the Server and Remote ID field, enter the server's domain name or IP address. The Local ID field can be left blank.
      7. Enter your username and password in the Authentication section, then tap Done.
      8. Select the VPN connection that you just created, tap the switch on the top of the page, and you'll be connected.

      Connecting from Android

      Follow these steps to import the certificate:

      1. Send yourself an email with the CA certificate attached. Save the CA certificate to your downloads folder.
      2. Download the StrongSwan VPN client from the Play Store.
      3. Open the app. Tap the "more" icon in the upper-right corner (the three dots icon) and select CA certificates.
      4. Tap the "more" icon in the upper-right corner again. Select Import certificate.
      5. Browse to the CA certificate file in your downloads folder and select it to import it into the app.

      Now that the certificate is imported into the StrongSwan app, you can configure the VPN connection with these steps:

      1. In the app, tap ADD VPN PROFILE at the top.
      2. Fill out the Server with your VPN server's domain name or public IP address.
      3. Make sure IKEv2 EAP (Username/Password) is selected as the VPN Type.
      4. Fill out the Username and Password with the credentials you defined on the server.
      5. Deselect Select automatically in the CA certificate section and click Select CA certificate.
      6. Tap the IMPORTED tab at the top of the screen and choose the CA you imported (it will be named "VPN root CA" if you didn't change the "DN" earlier).
      7. If you'd like, fill out Profile name (optional) with a more descriptive name.

      When you wish to connect to the VPN, click on profile you just created in the StrongSwan application.

      Troubleshooting Connections

      If you are unable to import the certificate, ensure the file has the .pem extension, and not .pem.txt.

      If you're unable to connect to the VPN, check the server name or IP address you used. The server's domain name or IP address must match what you've configured as the common name (CN) while creating the certificate. If they don't match, the VPN connection won't work. If you set up a certificate with the CN of vpn.example.com, you must use vpn.example.com when you enter the VPN server details. Double-check the command you used to generate the certificate, and the values you used when creating your VPN connection.

      Finally, double-check the VPN configuration to ensure the leftid value is configured with the @ symbol if you're using a domain name:

          leftid=@vpn.example.com
      

      And if you're using an IP address, ensure that the @ symbol is omitted.

      Conclusion

      In this tutorial, you've built a VPN server that uses the IKEv2 protocol. Now you can be assured that your online activities will remain secure wherever you go!

      To add or remove users, just take a look at Step 5 again. Each line is for one user, so adding or removing users is as simple as editing the file.

      From here, you might want to look into setting up a log file analyzer, because StrongSwan dumps its logs into syslog. The tutorial  How To Install and Use Logwatch Log Analyzer and Reporter on a VPS has more information on setting that up.

      You might also be interested in this guide from the EFF about online privacy.



      Source link