One place for hosting & domains

      Ubuntu

      Installing Countly Community Edition on Ubuntu 20.04


      The Countly analytics platform offers an alternative to the ubiquitous Google Analytics. In contrast to Google Analytics, Countly puts more emphasis on privacy and an all-in-one feature set. Countly’s data gathering offers compliance with GDPR, HIPAA, and other privacy standards. Meanwhile, it provides not just visitor analytics, but also a wider range of analytics related to marketing.

      This tutorial shows you how to start using Countly for your analytics needs. Countly Community Edition is free to use, and it runs in a self-hosted server environment. Through this guide, you can learn all the steps needed to get your own Countly server up and tracking activity on your applications.

      Before You Begin

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

      2. This guide uses sudo wherever possible. Complete the sections of our
        How to Secure Your Server guide to create a standard user account, harden SSH access, and remove unnecessary network services.

      3. Update your system.

        Debian / Ubuntu

        sudo apt update && sudo apt upgrade

        AlmaLinux / CentOS Stream / Fedora / Rocky Linux

      Note

      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, see the
      Users and Groups guide.

      Countly provides several installation options, which you can review in the link provided at the end of this tutorial.

      This guide covers the method using the Countly server GitHub repository, which tends to be straightforward as a result of the included installation script.

      These instructions are intended for and have been tested on Ubuntu systems. However, they may work on Debian and CentOS as well. Just be sure to make the necessary substitutions where relevant.

      After the steps on installing Countly, the tutorial includes instructions for two optional setup features to potentially improve your Countly experience: DNS and SSL.

      Installing Countly from the GitHub Repository

      These steps show you how to download the Git repository for Countly and use the included installation script. It also includes the steps you need to configure NGINX to properly serve your Countly interface.

      1. Clone the Countly server GitHub repository. This example clones the repository to the current user’s home directory. The process creates a new subdirectory there, countly-server:

        git clone https://github.com/Countly/countly-server.git
      2. The included installation script requires root access for the installation, so you should first switch to a superuser shell:

      3. Navigate to the subdirectory where the script is held:

        cd /home/example-user/countly-server/bin
      4. Run the installation script:

      5. Afterward, you can exit the superuser shell:

      6. Replace the default NGINX configuration with Countly’s
        own NGINX configuration file. Typically, you can find the default configuration file at /etc/nginx/sites-available/default. However, if this is a brand-new installation, you may have to create it:

        sudo mkdir /etc/nginx/sites-available
        sudo nano /etc/nginx/sites-available/default

        Additionally, you should extend the server_name property with the domain name and/or remote IP address you intend to use to access your Countly server. For instance, this example adds the domain name example.com and the remote IP address 192.0.2.0:

        File: /etc/nginx/sites-available/default
        1
        2
        3
        4
        5
        6
        
        server {
            listen   80;
            listen   [::]:80 ipv6only=on;
            server_name  localhost example.com 192.0.2.0;
        
            access_log  off;
      7. Open the HTTP port (80) on your server’s firewall. Typically, the firewalls on Ubuntu and Debian systems are managed with UFW. Using it, you can open the HTTP port with:

        sudo ufw allow http
        sudo ufw reload
      8. Access your Countly instance by navigating to one of the enabled addresses (that is, the server_name values from the NGINX configuration) in your web browser.

      (Optional) Assign Countly DNS

      Countly does not require you to use DNS for your server. However, doing so can make your Countly instance easier to access. It gives you access to your instance via a custom domain name, rather than just the remote IP address.

      To set up DNS on a Linode server, refer to our collection of guides on the
      Linode DNS manager. The process there is straightforward and can have your server running through a DNS quickly.

      (Optional) Assigning Countly TLS via Let’s Encrypt

      Another optional step is giving your Countly instance an SSL certificate. Doing so secures and encrypts its traffic using HTTPS.

      The following steps show you how to apply an SSL certificate to Countly using
      Certbot. Certbot allows you to easily request and download free certificates from
      Let’s Encrypt.

      1. Open the HTTPS port on your system’s firewall. Like above, you can do this using UFW with the HTTPS keyword:

        sudo ufw allow https
        sudo ufw reload
      2. Update the
        Snap app store. Snap provides application bundles that work across major Linux distributions and comes by default with all Ubuntu releases since 16.04:

        sudo snap install core && sudo snap refresh core
      3. Remove any existing Certbot installation:

      4. Install Certbot:

        sudo snap install --classic certbot
      5. Download a certificate using standalone verification. When prompted, accept the terms of service, enter an email address for notifications about certificate renewals, and enter your Countly server’s domain name:

        sudo certbot certonly --standalone

        Certbot outputs the location from which the new certificate can be accessed. Typically, it stores the required files in the following directory, replacing example.com with your domain name: /etc/letsencrypt/live/example.com.

      6. Access the NGINX site configuration again, and make the following modifications to the beginning of the file.

        These changes first add a server for port 80 that redirects traffic to the HTTPS URL. Then they alter the existing server definition to listen on port 443, the HTTPS port, and to use the SSL certificate created above.

        Replace example.com in this example with your server’s domain name:

        File: /etc/nginx/sites-available/default
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        
        server {
                listen      80;
                server_name localhost;
                access_log  off;
                rewrite ^ https://$host$request_uri? permanent;
        }
        
        server {
                listen   443 ssl;
                server_name  localhost example.com;
        
                ssl_certificate      /etc/letsencrypt/live/example.com/fullchain.pem;
                ssl_certificate_key  /etc/letsencrypt/live/example.com/privkey.pem;
        
                access_log  off;

      Now, when navigating to your Countly instance in a web browser, you should be redirected to the HTTPS URL.

      You can optionally also add your server’s remote IP address to the NGINX configuration above and use that as well to access Countly. However, you may receive a certificate warning in your browser. This is because the certificate was issued for your server’s domain name, not its IP address.

      How to Navigate the Countly Server Interface

      With your Countly instance up and running, you are ready to start setting it up for use. This next series of sections first covers the initial setup within the Countly interface.

      Further on, you can set up a Countly client SDK within your application and see it begin gathering your analytics.

      Creating an Administrator Account and Logging In

      When you first access Countly, you’re presented with a form to register an administrator user for your instance. Keep track of the login information you create here, as this user has administrative control within the Countly instance.

      Countly registration page

      Accessing the address for your Countly instance after this initial setup directs you to the login page.

      Countly login page

      Adding an Application to the Countly Dashboard

      Submitting the form to create your administrator account automatically directs you to a page to create a new application for your Countly instance. Here, you are entering the name and some descriptive information about the application.

      Creating a new application in Countly

      You can also reach this form later from the Countly dashboard by selecting the Add new app button in the upper right.

      Later, you can use the application key created by this process to associate a Countly client with your Countly server instance. Doing so then directs analytics from that client to Countly’s dashboard for the application.

      Accessing the Countly Dashboard

      From there you are directed to your Countly dashboard, the same page you land on for subsequent logins.

      Countly dashboard

      Here, you can survey the analytics generated by your Countly instance and manage all aspects of your Countly operations. You can navigate between and create application entries, and within each, view analytics for visits, events, and more.

      How to Set Up the Countly Client for Analytics

      To have Countly start collecting analytics, you need to embed one of its client SDKs within your application.

      Countly has numerous client SDKs available to fit your needs, from web and mobile apps, to the desktop, server, and beyond. You can see Countly’s
      full list of client SDKs for more information on how to download and operate each.

      To get you started and to demonstrate, the rest of this section walks you through an example using Countly’s web application SDK. It covers how you can make the client available for your web application and even includes example code to embed it. If you don’t have a web application ready, follow our guide
      Deploy a Static Site using Hugo and Object Storage.

      1. Ensure your web application’s client-side code includes or has access to the Countly web SDK file. This can be done multiple ways:

        • The SDK is automatically hosted alongside your Countly instance. Assuming your server’s domain is example.com, you can find the SDK at: example.com/sdk/web/countly.min.js.

        • Additionally, the file itself can be found among the Countly server files. Starting from the base Countly server directory, the SDK file is located at frontend/express/public/sdk/web/countly.min.js. You can then copy that file to an appropriate directory with your web application’s client-side code.

        • The Countly SDK can also be accessed from Countly’s own CDN, which you can learn about in their
          web SDK documentation.

        For these steps, it is assumed that you made a copy of the countly.min.js file from Countly’s server files. The steps also assume that you have added that file to a lib subdirectory within your client-side code.

      2. Add the following code to the head section of one of your application’s web pages.

        Replace EXAMPLE_COUNTLY_APP_KEY with the App Key found in your Countly instance. Likewise, replace https://example.com with your Countly server’s URL or IP address (preceded by http://, or ‘https:// if you set up SSL).

        File: index.html
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        
        <!-- [...] -->
        <script type='text/javascript'>
        
        // Initialize variables to be used by the Countly client.
        var Countly = Countly || {};
        Countly.q = Countly.q || [];
        
        // Provide the application key from the Countly dashboard.
        Countly.app_key = 'EXAMPLE_COUNTLY_APP_KEY';
        
        // Provide the URL for your Countly server instance.
        Countly.url = 'https://example.com';
        
        // These next two start pushing function calls to queue. Both
        // are recommended configurations.
        
        // Track sessions automatically.
        Countly.q.push(['track_sessions']);
        // Track web page views automatically.
        Countly.q.push(['track_pageview']);
        
        // Load the Countly script asynchronously.
        (function() {
            var cly = document.createElement('script'); cly.type = 'text/javascript';
            cly.async = true;
        
            // Replace the URL here with the location of your Countly client SDK file.
            cly.src = 'lib/countly.min.js';
            cly.onload = function(){Countly.init()};
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(cly, s);
        })();
        </script>
        <!-- [...] -->

        Note

        Alternatively, you can have Countly automatically generate this code specifically for your applications. Click Management (the wrench icon) in the left-hand toolstrip, then Applications. Choose your application and scroll all the way down to the blue box titled “Need some help with SDK integration?”. Click the Web button and you should be redirected to an address that starts with code.count.ly/integration-web.html. From here, choose where you want to retrieve the countly.min.js file and what features you want to use. When done, click Generate code for code that’s custom-tailored for your application.

      3. Begin incorporating Countly event calls into your application. Here is an example of one such call, used for a button on the pages:

        File: index.html
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        
        <html>
        <head>
        <!-- [...] -->
        <script type='text/javascript'>
        function exampleButtonClicked(ob){
          Countly.q.push(['add_event',{
            key:"asyncButtonClick",
            segmentation: {
              "id": ob.id
            }
          }]);
        }
        </script>
        <!-- [...] -->
        </head>
        <body>
        <!-- [...] -->
        <input type="button" id="exampleButton" onclick="exampleButtonClicked(this)" value="Click This Button">
        <!-- [...] -->
        </body>
        </html>

      Navigating to your web application should now generate page views in Countly. Activating an event, like clicking the button in the above example, similarly now shows in Countly.

      Countly page visitors

      Countly page events

      Conclusion

      You are now ready to run your application’s analytics with Countly. With your own Countly server set up and the client embedded, you can begin diving deeper into your Countly configuration. Take a look through the
      Countly documentation to learn all the possibilities and see more of what Countly is capable of.

      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.



      Source link

      How to Install Chef on Ubuntu 20.04


      Chef is a free and open source Infrastructure as Code (IaC) application. It’s a configuration management system that allows administrators to provision and manage infrastructure using automation. A complete Chef workflow includes one or more Chef Workstations, a Chef Server, and a set of nodes. This guide provides some background on how Chef works, and explains how to install and configure Chef on Ubuntu 20.04.

      What is Chef?

      Chef is a IaC application for automating and streamlining the process of provisioning, configuring, deploying, and managing network nodes. It allows for continuous deployment and an automated environment. Chef can manage many types of components including servers, containers, and networking infrastructure.

      Chef operates using a hub-and-spoke architecture, with the master Chef Server at the center. One or more Chef Workstations interact with the Server, which automates the configuration of one or more Chef nodes. Configuration assets move from the workstation to the server and finally to the nodes. Workstations cannot interact with the nodes directly. The Chef infrastructure consists of the following components.

      • Chef Workstation: A workstation is a server for creating and testing configuration code. The code is then pushed to the Chef Server. Several workstations can interact with the same server, but each workstation only links to one server. The
        Chef Workstation documentation contains more information on how to use the workstation.
      • Chef Server: The Chef Server is the “command center” for the entire system. It stores and maintains all the configuration files, code, and scripts. A Chef Server includes many components, including a web server and PostgreSQL database. It is responsible for pushing the relevant assets to the various nodes and keeping track of the nodes under its management. Each server is highly capable, efficient, and robust, and is capable of managing a large number of nodes.
      • Chef Node: The Chef Server deploys and manages a node using assets developed on the Chef Workstation. Each node is administered by a single Chef Server. Although it is dependent on the server, a Chef Node contains a Chef client. The client queries the server for updates and keeps the node up to date.

      The following illustration indicates the relationship between the three parts of the Chef system.

      The workstations use Chef commands, such as the knife directive, to interact with the server. Chef incorporates extra security and authentication into all of its operations, using public key encryption. However, the Chef system is complex and has a high learning curve.

      Chef uses an idiosyncratic terminology based on cooking vocabulary. Some of the more important terms include the following:

      • Attribute: Specifies a value for an item on a node.
      • Bookshelf: Stores the various cookbooks and assets on a Chef Server using versioning control.
      • Chef-client: Runs on the node, and is responsible for verifying whether the node is up-to-date with the assets stored on the server.
      • Chef-repo: A directory on the Chef Workstation that contains the local cookbooks and configuration files.
      • Cookbook: The primary method of managing nodes. It contains information describing the final state of a node. The Chef server and node use the cookbook to guide configuration. Cookbooks contain recipes, along with attributes, libraries, templates, and scripts. These cookbooks can be developed on the workstation or downloaded from the
        Chef Supermarket.
      • Environment: Collects nodes into groups to better organize them. Similar configurations and scripts can be applied to the entire group.
      • Knife: A Chef Workstation uses the knife tool to correspond with the Chef Server. A knife command usually takes the format knife subcommand [ARGUMENT] (options).
      • Recipe: A recipe is contained within a cookbook. It explains the resources to add, change, or run on the node. Recipes are written in Ruby.
      • Resource: A resource is part of a recipe. It contains a type, name, and list of key-value pairs for a component.
      • Test Kitchen: This is a workstation module to help users test recipes before deployment.

      Linode has a helpful
      Beginner’s Guide to Chef. For detailed information about Chef, see the
      Chef documentation. Chef also makes the
      Learn Chef training resource available.

      Before You Begin

      1. If you have not already done so, create a Linode account and Compute Instance. See our
        Getting Started with Linode and
        Creating a Compute Instance guides.

      2. Follow our
        Setting Up and Securing a Compute Instance guide to update your system. You may also wish to set the timezone, configure your hostname, create a limited user account, and harden SSH access.

      3. At least three Linode systems running Ubuntu 20.04 are required to implement a Chef system. One server is for the Chef Workstation, the second for the Chef Server, while a third represents a node under administration. Due to Chef’s memory demands, the Chef Server requires a 8GB Linode. The other two servers can be 2GB Linodes. Both the Chef Server and Chef Workstation should be configured using the previous instructions. Chef is used to set up the target node.

      4. Ensure all Linode servers are updated using the following command.

        sudo apt update && sudo apt upgrade
      5. Assign a domain name to the Chef Server. For information on domain names and pointing the domain name to a Linode, see the
        Linode DNS Manager guide.

      6. Configure the host name of the Chef Server so it matches the domain name. This allows SSL certificate allocation to proceed normally. To set the host name of a Ubuntu server, use the command sudo hostnamectl set-hostname <hostname>, replacing <hostname> with the actual name of your domain.

      Note

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

      How to Install and Configure the Chef Server

      Because the Chef Server operates as a hub for the entire system, it is best to install and configure it first. The Chef Server uses a high amount of resources, so it is important to use a dedicated Linode with at least 8GB of memory.

      How to Install the Chef Server

      The Chef Server Core can be downloaded using wget. The following steps demonstrate how to download the latest release of Chef for the Ubuntu 20.04 release. For other releases of Ubuntu, see the
      Chef download page. For more detailed instructions, see the
      Chef Server installation page. To install the Chef Server, follow these steps.

      1. Download the Chef Server core using wget.

        wget https://packages.chef.io/files/stable/chef-server/15.1.7/ubuntu/20.04/chef-server-core_15.1.7-1_amd64.deb
      2. Install the server core.

        sudo dpkg -i chef-server-core_*.deb
        Selecting previously unselected package chef-server-core.
        (Reading database ... 108635 files and directories currently installed.)
        Preparing to unpack chef-server-core_15.1.7-1_amd64.deb ...
        Unpacking chef-server-core (15.1.7-1) ...
        Setting up chef-server-core (15.1.7-1) ...
        Thank you for installing Chef Infra Server!
      3. For better security and to preserve server space, remove the downloaded .deb file.

        rm chef-server-core_*.deb
      4. Start the Chef server. Answer yes when prompted to accept the product licenses.

        Note

        The installation process takes several minutes to complete. Upon a successful installation, the message Chef Infra Server Reconfigured! is displayed.

        sudo chef-server-ctl reconfigure

      How to Configure a Chef User and Organization

      To use Chef, configure an organization and at least one user on the Chef Server. This enables server access for workstations and nodes. To create these accounts, follow these steps.

      1. Create a .chef directory to store the keys. This should be a subdirectory located inside the home directory.

      2. Use the chef-server-ctl command to create a user account for the Chef administrator. Additional user accounts can be created later. Replace the USER_NAME, FIRST_NAME, LAST_NAME, EMAIL, and PASSWORD fields with the relevant information. For the --filename argument, replace USER_NAME.pem with the user name used earlier in the command.

        sudo chef-server-ctl user-create USER_NAME FIRST_NAME LAST_NAME EMAIL 'PASSWORD' --filename ~/.chef/USER_NAME.pem
      3. Review the user list and confirm the account now exists.

        sudo chef-server-ctl user-list
        USER_NAME
      4. Create a new organization, also using the chef-server-ctl command. Replace ORG_NAME and ORG_FULL_NAME with the actual name of the organization. The ORG_NAME field must be all lower case. The value for USER_NAME must be the same name used in the user-create command. For the --filename argument, in ORG_NAME.pem, replace ORG_NAME with the organization name used elsewhere in the command.

        sudo chef-server-ctl org-create ORG_NAME "ORG_FULL_NAME" --association_user USER_NAME --filename ~/.chef/ORG_NAME.pem
      5. List the organizations to confirm the new organization is successfully created.

        sudo chef-server-ctl org-list
        ORG_NAME

      How to Install and Configure a Chef Workstation

      A Chef Workstation is for users to create and test recipes. Any Linode with at least 2GB of memory can be used for this task. Unlike the Chef Server, a workstation can also be used for other tasks. However, in a larger organization hosting many users, it is often efficient to centralize workstation activities on one server hosting multiple accounts.

      How to Install a Chef Workstation

      The steps for installing a Chef Workstation are similar to those for installing the Server. Download the correct file using wget, then install it. To install a Chef Workstation, follow these steps.

      1. Download the source files for the Chef Workstation. For different releases of the Workstation, or downloads for earlier releases, see the
        Chef Workstation Downloads page. For more information on the installation process, see the
        Chef Workstation Installation Documentation.

        wget https://packages.chef.io/files/stable/chef-workstation/22.10.1013/ubuntu/20.04/chef-workstation_22.10.1013-1_amd64.deb
      2. Install the Chef Workstation.

        sudo dpkg -i chef-workstation_*.deb
        Thank you for installing Chef Workstation!
      3. Remove the source file.

        rm chef-workstation_*.deb
      4. Confirm the correct release of the Chef Workstation is installed.

        Chef Workstation version: 22.10.1013
        Chef Infra Client version: 17.10.0
        Chef InSpec version: 4.56.20
        Chef CLI version: 5.6.1
        Chef Habitat version: 1.6.521
        Test Kitchen version: 3.3.2
        Cookstyle version: 7.32.1

      How to Configure a Chef Workstation

      A few more items must be configured before the Workstation is operational. Tasks include generating a repository, editing the hosts file, and creating a subdirectory. To fully configure the workstation, follow these steps.

      1. Generate the chef-repo repository. This directory stores the Chef cookbooks and recipes. Enter yes when asked whether to accept the product licenses.

        chef generate repo chef-repo
        Your new Chef Infra repo is ready! Type `cd chef-repo` to enter it.
      2. Edit the /etc/hosts file. This file contains mappings between host names and their IP addresses. Add an entry for the Chef Server, containing the name of the server, which is also the domain name, and its IP address. In this example, this is indicated in the line 192.0.1.0 example.com. There must also be an entry for the local server. This is the 192.0.2.0 chefworkstation line in the example. This entry must contain the local IP address and the hostname of the server hosting the Chef Workstation. The file should resemble the following example.

        File: /etc/hosts
        1
        2
        3
        
        127.0.0.1 localhost
        192.0.1.0 example.com
        192.0.2.0 chefworkstation
      3. Create a .chef subdirectory. This is where the knife file is stored, along with files for encryption and security.

        mkdir ~/chef-repo/.chef
        cd chef-repo

      How to Add RSA Private Keys

      RSA private keys enable better security between the Chef Server and associated workstations through the use of encryption. Earlier, RSA private keys were created on the Chef Server. Copying these keys to a workstation allows it to communicate with the server. To enable encryption using RSA private keys, follow these steps.

      Note

      SSH password authentication must be enabled on the Chef Server to complete the key exchange. If SSH password authentication has been disabled for better security, enable it again before proceeding. After the keys have been retrieved and added to the workstation, SSH password authentication can be disabled again. See the Linode guide to
      How to Secure Your Server for more information.
      1. On the workstation, generate an RSA key pair. This key can be used to initially access the Chef server to copy over the private encryption files.

        Generating public/private rsa key pair.
        Enter file in which to save the key (/home/username/.ssh/id_rsa):
      2. Hit the Enter key to accept the default file names id_rsa and id_rsa.pub. Ubuntu stores these files in the /home/username/.ssh directory.

        Created directory '/home/username/.ssh'.
        Enter passphrase (empty for no passphrase):
      3. Enter a password when prompted, then enter it again. An identifier and public key are saved to the directory.

        Your identification has been saved in /home/username/.ssh/id_rsa
        Your public key has been saved in /home/username/.ssh/id_rsa.pub
      4. Copy the new public key from the workstation to the Chef Server. In the following command, use the account name for the Chef Server along with its IP address.

        ssh-copy-id username@192.0.1.0
      5. Use the scp command to copy the .pem files from the Chef Server to the workstation. In the following example, replace username with the user account for the Chef Server and 192.0.1.0 with the actual Chef Server IP address.

        scp username@192.0.1.0:~/.chef/*.pem ~/chef-repo/.chef/
        Enter passphrase for key '/home/username/.ssh/id_rsa':
        username.pem                                                                       100% 1674     1.7MB/s   00:00
        testcompany.pem                                                                 100% 1678     4.7MB/s   00:00
      6. List the contents of the .chef subdirectory to ensure the .pem files were successfully copied.

        username.pem  testcompany.pem

      How to Configure Git on a Chef Workstation

      A version control system helps the Chef Workstation track any changes to the cookbooks and restore earlier versions if necessary. This example uses Git, which is compatible with the Chef system. The following steps explain how to configure Git, initialize a Git repository, add new files, and commit them.

      1. Configure Git using the git config command. Replace username and user@email.com with your own values.

        git config --global user.name username
        git config --global user.email user@email.com
      2. Add the .chef directory to the .gitignore file. This ensures system and auto-generated files are not shown in the output of git status and other Git commands.

        echo ".chef" > ~/chef-repo/.gitignore
      3. Ensure the chef-repo directory is the current working directory. Add and commit the existing files using git add and git commit.

        cd ~/chef-repo
        git add .
        git commit -m "initial commit"
        [master (root-commit) a3208a3] initial commit
        13 files changed, 343 insertions(+)
        create mode 100644 .chef-repo.txt
        ...
        create mode 100644 policyfiles/README.md
      4. Run the git status command to ensure all files have been committed.

        On branch master
        nothing to commit, working tree clean

      How to Generate a Chef Cookbook

      To generate a new Chef cookbook, use the chef generate command.

      chef generate cookbook my_cookbook

      How to Configure the Knife Utility

      The Chef Knife utility helps a Chef workstation communicate with the server. It provides a method of managing cookbooks, nodes, and the Chef environment. Chef uses the config.rb file in the .chef subdirectory to store the Knife configuration. To configure Knife, follow these steps.

      1. Create a config.rb file in the ~/chef-repo/.chef directory. This example uses vi, but any text editor can be used.

        cd ~/chef-repo/.chef
        vi config.rb
      2. Use the following config.rb file as an example of how to configure Knife. Copy this sample configuration to the file.

        File: ~/chef-repo/.chef/config.rb
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        
        current_dir = File.dirname(__FILE__)
        log_level                :info
        log_location             STDOUT
        node_name                'node_name'
        client_key               "USER.pem"
        validation_client_name   'ORG_NAME-validator'
        validation_key           "ORG_NAME-validator.pem"
        chef_server_url          'https://example.com/organizations/ORG_NAME'
        cache_type               'BasicFile'
        cache_options( :path => "#{ENV['HOME']}/.chef/checksums" )
        cookbook_path            ["#{current_dir}/../cookbooks"]
      3. Make the following changes:

        • node_name must be the name of the user account created when configuring the Chef Server.
        • For client_key, replace USER with the user name associated with the .pem file, followed by .pem.
        • validation_client_name requires the same ORG_NAME used when creating the organization followed by -validator.
        • the validation_key field must contain the name used for ORG_NAME when the organization was created, followed by -validator.pem.
        • For chef_server_url, change example.com to the name of the domain. Follow the domain name with /organizations/ and the ORG_NAME used when creating the organization.
        • Leave the remaining fields unchanged.
      4. Move back to the chef-repo directory and fetch the necessary SSL certificates from the server using the knife fetch command.

        Note

        The SSL certificates were generated when the Chef server was installed. The certificates are self-signed. This means a certificate authority has not verified them. Before fetching the certificates, log in to the Chef server and ensure the hostname and fully qualified domain name (FQDN) are the same. These values can be confirmed using the commands hostname and hostname -f.

        Knife has no means to verify these are the correct certificates. You should verify the authenticity of these certificates after downloading.
        Adding certificate for example.com in /home/username/chef-repo/.chef/trusted_certs/example.com.crt
      5. To confirm the config.rb file is correct, run the knife client list command. The relevant validator name should be displayed.

        testcompany-validator

      How to Bootstrap a Node

      At this point, both the Chef Server and Chef Workstation are configured. They can now be used to bootstrap the node. The bootstrap process installs the chef client on the node and performs validation. The node can then retrieve any necessary updates from the Chef Server. To bootstrap the node, follow these steps.

      1. Log in to the target node, which is the node to be bootstrapped, and edit the /etc/hosts file. Add entries for the node, the Chef server domain name, and the workstation. The file should resemble the following example, using the actual names of the Chef Server, workstation, and the target node, along with their IP addresses.

        File: /etc/hosts
        1
        2
        3
        4
        
        127.0.0.1 localhost
        192.0.100.0 targetnode
        192.0.2.0 chefworkstation
        192.0.1.0 example.com
      2. Return to the Linode hosting the Chef Workstation and change the working directory to ~/chef-repo/.chef.

      3. Bootstrap the node using the knife bootstrap command. Specify the IP address of the target node for node_ip_address. This is the address of the node to bootstrap. In the following example, use the actual user name and password for the account in place of username and password. Enter the name of the node in place of nodename. Answer Y when asked “Are you sure you want to continue connecting”.

        Note

        The option to bootstrap using key-pair authentication no longer appears to be supported.

        knife bootstrap node_ip_address -U username -P password --sudo --use-sudo-password --node-name nodename
      4. Confirm the node has been successfully bootstrapped. List the client nodes using the knife client list command. All bootstrapped nodes should be listed.

        target-node
        testcompany-validator
      5. Add the bootstrapped node to the workstation /etc/hosts file as follows. Replace 192.0.100.0 targetnode with the IP address and name of the bootstrapped node.

        File: /etc/hosts
        1
        2
        3
        4
        
        127.0.0.1 localhost
        192.0.1.0 example.com
        192.0.2.0 chefworkstation
        192.0.100.0 targetnode

      How to Download and Apply a Cookbook (Optional)

      A cookbook is the most efficient way of keeping target nodes up to date. In addition, a cookbook can delete the validation.pem file that was created on the node when it was bootstrapped. It is important to delete this file for security reasons.

      It is not mandatory to download or create cookbooks to use Chef. But this section provides a brief example of how to download a cookbook and apply it to a node.

      1. On the Chef workstation, change to the ~/chef-repo/.chef directory.

      2. Download the cron-delvalidate cookbook from the Chef Supermarket. For more information on the supermarket command see the
        Chef supermarket documentation.

        knife supermarket download cron-delvalidate
        Downloading cron-delvalidate from Supermarket at version 0.1.3 to /home/username/chef-repo/.chef/cron-delvalidate-0.1.3.tar.gz
        Cookbook saved: /home/username/chef-repo/.chef/cron-delvalidate-0.1.3.tar.gz
      3. If the cookbook is downloaded as a .tar.gz file, use the tar command to extract it. Move the extracted directory to the cookbooks directory.

        tar -xf cron-delvalidate-0.1.3.tar.gz
        cp -r  cron-delvalidate ~/chef-repo/cookbooks/
      4. Review the cookbook’s default.rb file to see the recipe. This recipe is written in Ruby and demonstrates how a typical recipe is structured. It contains a cron job named clientrun. This job instantiates a new cron job to run the chef-client command on an hourly basis. It also removes the extraneous validation.pem file.

        File: ~/chef-repo/cookbooks/cron-delvalidate/recipes/default.rb
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        
        #
        # Cookbook Name:: cron-delvalidate
        # Recipe:: Chef-Client Cron & Delete Validation.pem
        #
        #
        cron "clientrun" do
          minute '0'
          hour '*/1'
          command "/usr/bin/chef-client"
          action :create
        end
        
        file "/etc/chef/validation.pem" do
          action :delete
        end
      5. Add the recipe to the run list for the node. In the following command, replace nodename with the name of the node.

        knife node run_list add nodename 'recipe[cron-delvalidate::default]'
        nodename:
          run_list: recipe[cron-delvalidate::default]
      6. Upload the cookbook and its recipes to the Chef Server.

        knife cookbook upload cron-delvalidate
        Uploading cron-delvalidate [0.1.3]
        Uploaded 1 cookbook.
      7. Run the chef-client command on the node using the knife ssh utility. This command causes the node to pull the recipes in its run list from the server. It also determines whether there are any updates. The Chef Server transmits the recipes to the target node. When the recipe runs, it deletes the file and installs a cron job to keep the node up to date in the future. In the following command, replace nodename with the actual name of the target node. Replace username with the name of a user account with sudo access. Enter the password for the account when prompted to do so.

        knife ssh 'name:nodename' 'sudo chef-client' -x username
        nodename Chef Infra Client, version 17.10.3
        nodename Patents: https://www.chef.io/patents
        nodename Infra Phase starting
        nodename Resolving cookbooks for run list: ["cron-delvalidate::default"]
        nodename Synchronizing cookbooks:
        nodename   - cron-delvalidate (0.1.3)
        nodename Installing cookbook gem dependencies:
        nodename Compiling cookbooks...
        nodename Loading Chef InSpec profile files:
        nodename Loading Chef InSpec input files:
        nodename Loading Chef InSpec waiver files:
        nodename Converging 2 resources
        nodename Recipe: cron-delvalidate::default
        nodename   * cron[clientrun] action create
        nodename     - add crontab entry for cron[clientrun]
        nodename   * file[/etc/chef/validation.pem] action delete (up to date)
        nodename
        nodename Running handlers:
        nodename Running handlers complete
        nodename Infra Phase complete, 1/2 resources updated in 03 seconds

      Conclusion

      Chef is an infrastructure as code (IaC) application for automating the deployment and management of infrastructure nodes. The Chef architecture consists of the Chef Server, which stores all the procedures, and a Chef Workstation, where the infrastructure code is developed. The managed nodes communicate with the server to receive updates. To use Chef, install the Chef Server and Chef Workstation software. Share RSA keys between the server and workstation, and install version control and the Chef Knife utility on the workstation. Bootstrap the target nodes using the knife bootstrap utility. After a node is bootstrapped, it is possible to download cookbooks and recipes using the node’s run list. For more information, see the
      Chef documentation.

      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.



      Source link

      How to Install SELinux on Ubuntu 22.04


      According to
      the official Security Enhanced Linux project page, SELinux is a security enhancement to Linux. Linux-based security-sensitive projects largely standardize on it. Ubuntu 22.04 is compatible with SELinux and these instructions make it available on your Ubuntu 22.04 host. The steps in this guide appear as command line instructions. Both physical and virtual machines can be configured for SELinux, but it is not possible to enable SELinux in a Docker container without additional steps not covered here.

      Before You Begin

      1. If you have not already done so, create a Linode account and Compute Instance. See our
        Getting Started with Linode and
        Creating a Compute Instance guides.

      2. Follow our
        Setting Up and Securing a Compute Instance guide to update your system. You may also wish to set the timezone, configure your hostname, create a limited user account, and harden SSH access.

      Note

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

      SELinux Installation

      SELinux’s technical basis is
      access control, meaning how different users can and cannot read, write, update, remove, or otherwise change different resources, and how administrators manage those differences. Over twenty years ago,
      SELinux introduced tools to enhance conventional Linux so these administrative chores are now less complex and more reliable. SELinux is currently implemented as a Mandatory Access Control (MAC) module within the kernel.

      A standard modern Ubuntu distribution includes
      AppArmor, a Linux application security system which emphasizes ease-of-use and routine reliability. Both AppArmor and SELinux work through the
      Linux Security Module (LSM) interface. Since Linux only permits a single LSM to be active, the first step in an SELinux installation is to deactivate AppArmor.

      Caution

      SELinux alters parts of Linux profoundly. An error in its installation can easily render an entire host unresponsive. Make backups, be prepared to dispose or recycle a particular instance, and work with care. Start your SELinux experiments in permissive mode, and make backups again before any switch to enforcing mode. The simplest SELinux installations are somewhat time-consuming, as they affect the entire filesystem. Each reboot takes a while, since SELinux methodically confirms the state of all filesystems and other resources.

      Stop and Remove AppArmor

      1. It’s good practice to begin any Linux installation work by ensuring a consistent package state with:

        sudo apt update && sudo apt upgrade -y
        
      2. Your Ubuntu 22.04 installation probably runs AppArmor by default. To verify its status, request:

        systemctl status apparmor
        

        There are several lines of output, including “&mldr; enabled &mldr; SUCCESS &mldr;”.

      3. Press Q to close the status info.

        Note

        A few Ubuntu 22.04 variants for embedded computing do not run AppArmor. Therefore, if you see “&mldr; apparmor.service could not be found &mldr;” you can safely skip the next paragraphs and go immediately to the “Install SELinux” section below.

      4. In the more common case, where AppArmor is running, stop it:

        sudo systemctl stop apparmor
        
      5. Now disable AppArmor to prevent it from re-enabling:

        sudo systemctl disable apparmor
        

      It is not necessary, or even desirable, to remove AppArmor. Most administrators leave it installed, but stopped and disabled.

      Install SELinux

      1. Install SELinux:

        sudo apt install policycoreutils selinux-basics selinux-utils -y
        
      2. Enable SELinux:

        sudo selinux-activate
        

        Now you see:

        SELinux is activated. You may need to reboot now.

      Do not reboot immediately! First, review the current state of your new SELinux host.

      Verification

      1. To confirm the current status of your installation, use the command:

        getenforce
        

        This shows the one-word response:

        Disabled

      This means that your SELinux is ready to work. It’s “active” but not yet turned on.

      While getenforce provides the current state of SELinux, sestatus is a different command that provides more details.

      1. When you enter:

        sestatus
        

        You see:

        SELinux status:		disabled

      While this output is similar to getenforce, once SELinux is enabled, sestatus reports more fully on the configuration, as detailed later.

      Configuration of Permissions to Allow for Reboot

      SELinux can be enabled in one of two states: permissive or enforcing. Your current SELinux installation remains disabled.

      Caution

      If you connect to your host via SSH, access will be lost once SELinux is enabled. If you’re using a Linode host, you can still login via the LISH console.

      1. Reboot, and the Ubuntu 22.04 host likely comes up with SELinux “on”:

        sudo reboot
        

        Note

        The first reboot with SELinux enabled begins a relabelling process that could take a long time, so be patient.

      2. Verify this through examination of /etc/selinux/config:

        cat /etc/selinux/config
        

        It should include the line:

        SELINUX=permissive

      The presence of /etc/selinux/config is a sign that the host is ready for configuration and the reboot needed to make most configurations effective:

      • Installation creates /etc/selinux/config.
      • Configuration updates /etc/selinux/config.
      • A reboot puts SELinux into action.

      SELinux Management

      SELinux has several options beyond the scope of this guide. Configuration is commonly achieved through configuration files rather than graphical user interface (GUI) or command line applications.

      Enabling SELinux

      Basic configuration of an SELinux installation starts with the SELINUX attribute in /etc/selinux/config.

      1. Open /etc/selinux/config:

        sudo nano /etc/selinux/config
        
      2. Enable SELinux by changing the line:

        SELINUX=permissive
        

        to

        SELINUX=enforcing
        
      3. Press CTRL+X to exit nano.

      4. Press Y to confirm.

      5. Press ENTER to save.

      6. The next time the host is rebooted, it comes up as an enforcing SELinux instance:

        sudo reboot
        
      7. Verify this again via /etc/selinux/config:

        cat /etc/selinux/config
        

        It should include the line:

        SELINUX=enforcing

      SELinux Policies

      /etc/selinux/config controls how an SELinux instance launches. However, it’s possible to adjust the action of SELinux between reboots with setenforce.

      1. Temporarily put SELinux in permissive mode with:

        sudo setenforce 0
        
      2. Check the current status of SELinux with:

        getenforce
        

        This should now display:

        Permissive
      3. Now check the status of SELinux again using sestatus

        sestatus
        

        You not only see the current SELinux mode, but also the config file (boot) mode, and other information:

        SELinux status:                 enabled
        SELinuxfs mount:                /sys/fs/selinux
        SELinux root directory:         /etc/selinux
        Loaded policy name:             default
        Current mode:                   permissive
        Mode from config file:          enforcing
        Policy MLS status:              enabled
        Policy deny_unknown status:     allowed
        Memory protection checking:     requested (insecure)
        Max kernel policy version:      33
      4. Switch SELinux back from permissive to enforcing mode with:

        sudo setenforce 1
        
      5. Check the current status of SELinux again:

        getenforce
        

        This should now display:

        Enforcing
      6. Confirm the status again using sestatus

        sestatus
        

        You can see that setenforce only changes the current mode:

        SELinux status:                 enabled
        SELinuxfs mount:                /sys/fs/selinux
        SELinux root directory:         /etc/selinux
        Loaded policy name:             default
        Current mode:                   enforcing
        Mode from config file:          enforcing
        Policy MLS status:              enabled
        Policy deny_unknown status:     allowed
        Memory protection checking:     requested (insecure)
        Max kernel policy version:      33

      Other possible values for getenforce output are Permissive and Disabled. These values are capitalized, unlike the values permitted within /etc/selinux/config.

      How to disable SELinux

      There are two distinct ways to disable SELinux:

      • Have SELinux immediately stop its enforcement of resource permissions, and continue in the same way until its next reboot, at which point SELinux returns to enforcement.
      • Stop SELinux enforcement permanently, so that SELinux is not in effect after each boot operation.

      It’s common to speak of SELinux’s permissive operation as “disabled”. This first of the two descriptions may be confusing, because, although SELinux is disabled, and users can’t see its action, it remains active. When SELinux runs as Permissive, it logs access violations, but doesn’t enforce them. When SELinux is enabled as enforcing, the only effective way to disable it fully so that it doesn’t log its observations or otherwise act in the background, requires updates of /etc/selinux/config and sudo reboot.

      Conclusion

      Fewer than a couple dozen commands are required to install, enable, and activate SELinux on Ubuntu 22.04. You can quickly have an enforcing SELinux, but refer to other references for details on how to configure your SELinux to achieve specific useful requirements.



      Source link