FreeRADIUS with REST

Introduction

Starting from FreeRADIUS v3.x, FreeRADIUS has added support to REST API.

This article will talk about how to configure FreeRADIUS to make authentication by connecting to a remote server using REST.

Prerequisite

Make sure you have Ubuntu 16.04 or higher with FreeRADIUS v3.x installed, but alternative is to upgrade FreeRADIUS independently of Ubuntu version.

Also make sure you have configured your clients.conf file and added your network access server.

Configurations

Open the terminal, and enable root mode using the following command:

$ sudo su

Then go to FreeRADIUS folder using “cd” command:

$ cd /etc/freeradius

If you are in Ubuntu 18.04, then use this command:

$ cd /etc/freeradius/3.0

Use ls command and you will get all the folders in FreeRADIUS.

mods-available folder contain all the modules provided by FreeRADIUS, and mods-enabled folder contains the enabled modules that the FreeRADIUS server will use.

We will use the rest module to configure FreeRADIUS to work with REST.

To use the rest module, we have to enable it first.

To enable it we have to make a soft link of it in mods-enabled folder.
This is done using the following commands:

$ cd mods-enabled
$ ln -s ../mods-available/rest

Now, we will configure the rest module.

$ nano rest

First, replace connect_uri with your HTTP domain.

connect_uri = "http://localhost:8084/RestForRadius"

Then, replace authorize{} section with the below configurations

authorize {
uri = "${..connect_uri}/authorize"
method = 'post'
tls = ${..tls}
body = 'json'
data = '{ "username": "%{User-Name}", "password": "%{User-Password}", "calling-station-id": "%{Calling-Station-Id}" }'
}

Where “authorize” is the name of the web service responsible for authorization.

Also replace the authenticate{} section with the below configurations

authenticate { 
uri = "${..connect_uri}/authenticate"
method = 'post'
body = 'json'
data = '{ "username": "%{User-Name}", "password": "%{User-Password}", "calling-station-id": "%{Calling-Station-Id}" }'
tls = ${..tls}
}

Where “authenticate” is the name of the web service responsible for authentication.

Save the changes and close the rest module.

The next step is to configure the virtual server.
There are two virtual servers enabled: default, and inner-tunnel.

We will configure them both with the same configurations.

Go to /etc/freeradius/sites-enabled and run the following command

$ nano default

This file represent the configurations for the default server.

Go to the authorize{} section and add rest as below:

authorize {
...

rest

...
}

Do the same with authenticate{} section.

authenticate {
...

rest

...
}

Save and exit.

Do the same to inner-tunnel server file.

Now we will start FreeRADIUS in debug mode. Make sure that your remote server (connect_uri) is up and accessible or you will get an error.

$ freeradius -X

If you get Ready to process requests then you have configured it successfully.

References

http://system-eng.blogspot.com/2016/09/sending-freeradius-accounting-data-to.html

https://stackoverflow.com/questions/43698251/freeradius-3-0-13-rlm-rest-restful-api-authentication


JSON Web Tokens (JWTs)

JSON Web Token is an open standard that defines a compact and self-contained way for securely transmitting digitally signed information between parties as a JSON object.

Compact: it can be sent through an URL, POST parameter, or inside an HTTP header.

Self-contained: the payload has all the necessary information about the user.

Structure of JWT

JWTs contain three parts separated by a dot(.) and they are:

  • Header
  • Payload
  • Signature

So the JWT look like this:

hhhhhhhh.pppppppp.sssssssssss

Each part is Base64url encoded.

Header

The header usually has two parts:

  • The type of the token
  • The hashing algorithm used in signing the token

The image below shows an example of a header

alg: is the algorithm used for signing the token, and here it is the HMAC SHA256
typ: is the type of the token which is always JWT

Payload

The second part of the JWT. It contain claims, which are information about an entity and other data.

Claims are three types: registered (predefined claims), public (User defined), and private(custom claims used to share information between parties).

The image below present an example of a payload

The information contained in the payload are protected against tampering and modification, but they can be read by anyone because they are encoded not encrypted. So you should not put any secret information in the payload unless you encrypt them.

Signature

The signature is the third part of the JWT. it can be created by taking the base64 encoded header, the base64 encoded payload, a secret, the algorithm specified in the header and sign that.

Example:

{
HMACSHA256 (base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret)
}

The algorithm used in the previous example is the HMAC SHA256.

An Asymmetric hashing algorithm with a public/private key pair can also be used like RSA.

How JWT work

The image below describes how the JWT is used in authentication.

Implementation

There are libraries for implementing JWT in many different programming language. Every programming language has multiple libraries, and they differ in the syntax.

Java JWT example

The code below show how JWT can be created and verified. The library used in this example is jjwt. The signing was done using RS256 algorithm.

// import the necessary packages
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys

// specifying the algorithm and the public/private key pairs
KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256)

// creating the signed JWT
String jws = Jwts.builder()
.setHeaderParam("typ", "JWT")
.claim("Name", "Najy")
.claim("admin", true)
.signWith(keyPair.getPrivate())
.compact();




// Verifying the JWT
try{
Jws jws1;
jws1 = Jwts.parser()
.setSigningKey(keyPair.getPublic())
.parseClaimsJws(jws);
out.println("Signature verified, The JWT can be trusted");
out.println("Header: " + jws1.getHeader());
out.println("Payload: " + jws1.getBody());

} catch (Exception ex){ // in case JWT was altered
  out.println("Error: " + ex.getMessage());
}

References

https://jwt.io/introduction/

https://auth0.com/learn/json-web-tokens/

https://en.wikipedia.org/wiki/JSON_Web_Token

https://github.com/jwtk/jjwt

Couchbase

Couchbase Server  is an open source NoSQL document based database that is optimized for interactive web applications. It provides programmatic access to Couchbase server through the SDKs of the different programming languages.

It has a query language known as N1QL, which has a structure composed of statements, expressions, and comments.

Installation

To install latest version of Couchbase in Ubuntu 16.04 (xenial):

First, download Couchbase server from here. Make sure you choose ubuntu 16.04 as the operating system.

Then reload the local package database.

Install Couchbase Server using the following command:

where ./ is the path to the Couchbase server package and * is the version of the package that you have downloaded.

If dpkg reports any errors about missing dependencies, run the following command to download and install them:

Once installation is complete, Couchbase Server will start automatically.

Getting started with Couchbase

Open this link to access the Couchbase Server Web Console.

Enter the username and password that you have provided during installation and click sign in.

Cluster Dashboard

After signing in successfully, you will be forwarded to Cluster Dashboard.

The Cluster Dashboard provides a graphical summary of the current state of your Couchbase cluster.

Click on Buckets in the left-hand navigation bar to go to the bucket screen. On the bucket screen, click on “Add Bucket” to add a new bucket.

Give it a name and determine memory quota then click “Add Bucket”

After adding a bucket, go to “Query” screen to create primary index for your bucket. Use the following query:

CREATE PRIMARY INDEX ON `bucket_name` USING GSI;

Replace `bucket_name` with the name that you have given to your bucket. Then Execute.

You have successfully created your first bucket.


Using Java SDK with a java application

First, download Java SDK from here.

Then extract the zip file and add the following jars to your project:

  • couchbase-java-client:2.6.2
  • couchbase-core-io:1.6.2
  • rxjava:1.3.7
  • opentracing-api:0.31.0

The code segment below describes how the Java SDK can be used for some common operations (described in comments):

import com.couchbase.client.java.*; import com.couchbase.client.java.document.*; import com.couchbase.client.java.document.json.*; import com.couchbase.client.java.query.*;

public class Example {
  public static void main(String[] args) throws Exception {

// Initialize the Connection
  Cluster cluster = CouchbaseCluster.create("localhost");
cluster.authenticate("username", "password"); Bucket bucket = cluster.openBucket("bucketname");


// Create a JSON Document JsonObject arthur = JsonObject.create() .put("name", "Arthur") .put("email", "kingarthur@couchbase.com") .put("interests", JsonArray.from("Reading", "Sport"));

// Store the Document bucket.upsert(JsonDocument.create("u:king_arthur", arthur));


// Load the Document and print it
// Prints Content and Metadata of the stored Document
System.out.println(bucket.get("u:king_arthur"));


// Create a N1QL Primary Index (but ignore if it exists) bucket.bucketManager().createN1qlPrimaryIndex(true, false);


// Perform a N1QL Query
N1qlQueryResult result = bucket.query(N1qlQuery.parameterized("SELECT name FROM `bucketname` WHERE $1 IN interests", JsonArray.from("Sport")));

// Print each found Row
for (N1qlQueryRow row : result) {

// Prints {"name":"Arthur"}
System.out.println(row);

   }
  }
}

References

https://docs.couchbase.com/server/current/install/ubuntu-debian-install.html

https://docs.couchbase.com/server/current/manage/manage-buckets/create-bucket.html

https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/createprimaryindex.html

https://docs.couchbase.com/java-sdk/2.7/start-using-sdk.html


ServiceCheck

Service Check is a 64-bit Linux command line tool to check background services/applications and run it if it is not working

it stores configuration for applications to be checked in checklist.ini file in the same directory of servicecheck tool.

example of configuration for application called goagent located in /home/user/go/

checklist.ini contents:

goagent /home/user/go/goagent

Metabase BI Tool

Metabase is the easy, open source way for everyone in your company to ask questions and learn from data.

Installing and Running Metabase:

Metabase is built and packaged as a Java jar file and can be run anywhere that Java is available. Below we provide detailed instructions on how to install and run Metabase in a variety of common configurations.

How to download it?

From www.metabase.com

How to Running on Java 8:

Running on Java 8 is the easiest path to running Metabase. There are no additional parameters required, if launching from a Jar the below invocation will work:

Java -jar metabase.jar
 

How to Gathering your database info:

At this point you’ll need to gather some information about the database you want to use with Metabase. We won’t be able to connect to your database without it, but you’d like to deal with all of this later, that’s okay: just click I’ll add my data later.

If you’re ready to connect, here’s what you’ll need:

  • The hostname of the server where your database lives
  • The port the database server uses
  • The database name
  • The username you use for the database
  • The password you use for the database
 

How to connect database:

adddatabase

Here in this screen you add the above information about the database.

Asking a new question:

But, enough about that — let’s get to asking questions. For the next few examples, we’ll be using the Sample Dataset that comes with Metabase.

Go ahead and click New Question at the top of the screen. Now we’re on the new question page. The bar that you see going across the page is what you’ll use to ask your questions. The “Select a table” dropdown should already be open, showing you a list of your database(s) and the tables within them.

Query Builder

Our first question:

We’re going to ask a question about the Orders table in the Sample Dataset database, so we’ll click on Orders in the dropdown. The Orders table has a bunch of fake data in it about product orders for a made up company. If you just want to see everything that’s in this table, you can click Run query and see all the raw data.

Orders

Let’s start with a simple question: how many orders have been placed with a subtotal (before tax) greater than $40? More precisely, this question translates to, “How many records (or rows) are in the table ‘Orders’ with a value greater than 40 in the Subtotal column?”

To find out, we want to filter the data by the field we’re interested in, which is Subtotal. Since each row in this table represents one order, counting how many rows there are after we’ve filtered them will give us the answer we want.

Subtotal

So, after we select Subtotal from the Filter dropdown we’ll get some options for the filter, and we’ll choose Greater than, type the number 40 in the box, and click Add Filter.

Add Filter

Next we need to tell Metabase what we want to see. Under the View dropdown, we’ll select Count, because, like we said, we want to count the total number of rows that match our filter. If we left the View set to Raw Data, that would just show us a list of all the rows, which doesn’t answer our question.

Count

And our first answer:

 We’re ready to ask our question, so let’s click the Run query button!

So it looks like there were 12,284 orders, each with a subtotal greater than $40.Another way of saying this is that there were 12,284 records in the table that met the parameters we set.

Visualization Dropdown Menu
Count Answer

How to Changing the visualization:

Luckily enough, Metabase can present the answers to your questions in a variety of ways. To change the visualization, just select one of the options from the Visualization dropdown menu, which is in the top-left of the screen, above the table. Let’s choose Area.

Area Chart

Creating a dashboard:

Unless you went off and did your own thing, you shouldn’t have any dashboards yet, so you’ll see a dialog that prompts you to create a new one and give it a name and description. Name it anything you’d like. We’ll call ours “My First Dashboard.”

Create Dashboard

Dashboards are great when you have a set of questions and answers that you want to view together. Your saved questions will be displayed as cards on the dashboard, which you can resize and move around to your heart’s content.

So, after you click the button to create your dashboard, you should see your fancy saved question as a little card.

If you’re feeling up to it, you can click the edit button in the top-right of the screen (the one that looks like a pencil), and that’ll let you move and resize your saved question so you can get it looking just how you want it. Just click Save in the top-right when you’re done. We’ll make ours a bit wider to let those data points breathe.

Resized Chart

References:

https://www.metabase.com/docs/latest


RADIUS

Before you start learning about Radius, it is important that you understand:

AAA :

Authentication, authorization, and accounting (AAA) is a term for a framework for intelligently controlling access to computer resources, enforcing policies, auditing usage, and providing the information necessary to bill for services. These combined processes are considered important for effective network management and security.

Authentication, authorization, and accounting services are often provided by a dedicated AAA server, a program that performs these functions. A current standard by which network access servers interface with the AAA server is the Remote Authentication Dial-In User Service (RADIUS).

RADIUS(Remote Authentication Dial-In User Service):

Radius is a protocol for carrying information related to authentication, authorization, and configuration between a Network Access Server (NAS) that desires to authenticate its links and a shared Authentication Server.

What is Network Access Server?


The Network Access Server (NAS) is a service element that clients dial in order to get access to the network.

Basic Architecture for NAS / RADIUS / AAA


Features of Radius:

  1. Client/Server Model
  • NAS works as a client for the Radius server.
  • A Radius server can act as a proxy client to other Radius servers.
  1. Network Security
  • Transactions between a client and a server are authenticated through the use of a shared key. This key is never sent over the network.
  • Password is encrypted before sending it over the network.

How to install FreeRADIUS in Ubuntu server:

Installing FreeRADIUS is the easiest part. It can be done with.


$ sudo apt-get install freeradius

Verify FreeRADIUS version


Verify it was installed by checking the version.


$ freeradius -v


FreeRADIUS should be able to run successfully with all the defaults.


Run a quick config check.


$ sudo freeradius –CX

Review the Configuration Files


The FreeRADIUS files are located in /etc:


$ cd /etc/freeradius
$ sudo nano /etc/freeradius/radiusd.conf


Here is where we tell FreeRADIUS to look for authorized clients (authenticators).


$INCLUDE clients.conf

Add Clients


Open the clients.conf file to add your authenticator(s).
And then add these lines


client 192.168.1.1{
hostname = TP_LINK
secret = password@123
}


Add Users


$ sudo nano /etc/freeradius/users


Add an account to the file:


usertest Cleartext-Password := “Password123”

Test Authentication


Run a quick test to see if FreeRADIUS will accept the newly created username and password. Running this from the server means you will have to use the secret configured for the localhost which is defined in the clients.conf file:


$ radtest usertest Password123 127.0.0.1 0 testing123


Start FreeRadius


$ service freeradius start


Stop FreeRadius


$ service freeradius stop

References :

https://www.tutorialspoint.com/radius/aaa_and_nas.htm

https://searchsecurity.techtarget.com/definition/authentication-authorization-and-accounting

https://whatis.techtarget.com/definition/access

https://wiki.freeradius.org/guide/SQL-HOWTO-for-freeradius-3.x-on-Debian-Ubuntu