Welcome!

Linux Authors: Sandi Mappic, Roger Strukhoff, Lori MacVittie, Elizabeth White, Esmeralda Swartz

Related Topics: Linux

Linux: Blog Post

Create Linux User Login Monitor on Monitis

Monitis provides the ability to monitor almost any operation on your server

Monitis provides the ability to monitor almost any operation on your server.  Using simple Linux tools and scripts you are able to monitor each time a user logs into the server and capture various information, including username, host address and login service.  Using pam_script and bash scripts, you are able to transmit information to a Custom Monitor with this information.

API Access

The first thing you will need in order to create this monitor is the Monitis API Key and Secret Key.  The API Key is a alphanumeric code that allows you to access the Monitis API url’s and transmit or receive data about your Monitis services.  The Secret Key is an alphanumeric code that allows you to digitally sign your information to ensure that only you can transmit data to your Monitis account.  Your API Key may be disclosed to anyone, but your Secret Key must be maintained private and should not be shared nor transmitted.  To obtain your Monitis API Key and Secret Key, log into your account and from the top menu bar, go to Tools then API then API Key, it will display both your API Key and your Secret Key.

Now let’s test your API access.  You should be able to connect and get an Auth Token:

curl 'http://www.monitis.com/api?action=authToken&apikey=[API Key]&secretkey=[Secret Key]&version=2'

In the above command you should replace [API Key] and [Secret Key] with your API Key and Secret Key.  We are using curl in order to connect to http://www.monitis.com and access the API to get a Auth Token.  The return value is json and sends back something similar to:

{"authToken":"3TVQN32TIP1DN71OB4GOML1D7N"}

Where the alphanumeric code will be your Auth Token.  You can use your Auth Token to validate against the API later.   However sending your Secret Key is not extremely secure, others could possibly  obtain your Secret Key this way.  The more secure method of authenticating is to send your data using POST instead of GET and using a Base64-encoded RFC 2104-compliant HMAC signature to sign the post data.  The signature is sent in the checksum parameter of the POST data.  To calculate the checksum you must follow these rules:
  1. sort all parameters alphabetically by name (excluding the checksum parameter)
  2. concat all parameter names and values like this: name1value1name2value2…
  3. create Base64-encoded RFC 2104-compliant HMAC signature using Secret Key

The final rule can be calculated using openssl:

echo -en “name1value1name2value2” | openssl dgst -sha1 -hmac [Secret Key] -binary | openssl enc -base64

Creating a Custom Monitor

In order to create a custom monitor, you must send a POST request to the API.  This POST request must contain several parameters: action, name, resultsParams, and tag (refer to http://monitis.com/api/api.html#addCustomMonitor for specifications).  We will use the following specifications for the params:

  • action=addMonitor
  • name=Login Monitor
  • resultsParam=user_login:Login Name:logins:3;host:Host Address:hostaddress:3;srv:Service:service:3
  • tag=loginMonitor

There is other necessary information in order to communicate with the API:

  • apikey=[API Key]
  • timestamp=[Current UTC time]
  • version=2
In order to create our new monitor called Login Monitor we would post this data plus a checksum to http://monitis.com/customMonitorApi which is the Custom Monitor API url.  Here is a simple script that will accomplish this:

#!/bin/bash
# create a Custom Monitor for Monitis
# Be sure to modify the API Key and Secret Key
ACTION="addMonitor"
APIKEY="[API Key]"
NAME="login monitor"
RESULTPARAMS="user_login:Login Name:logins:3;host:Host Address:hostaddress:3;srv:Service:service:3"
TAG="loginMonitor"
TIMESTAMP=`date -u +"%F %T"`
VERSION="2"
SECRETKEY="[Secret Key]"
URL="http://monitis.com/customMonitorApi"

# Create Checksum
CHECKSUM_STR="action"$ACTION"apikey"$APIKEY"name"$NAME"resultParams"$RESULTPARAMS"tag"$ TAG"timestamp"$TIMESTAMP"version"$VERSION
CHECKSUM=$(echo -en $CHECKSUM_STR | openssl dgst -sha1 -hmac $SECRETKEY -binary | openssl enc -base64 )

# Post Data to API
POSTDATA="--data-urlencode \"action="$ACTION"\" --data-urlencode \"apikey="$APIKEY"\" --data-urlencode \"name="$NAME"\" --data-urlencode \"resultParams="$RESULTPARAMS"\" --data-urlencode \"tag="$TAG"\" --data-urlencode \"timestamp=$TIMESTAMP\" --data-urlencode \"version="$VERSION"\" --data-urlencode \"checksum="$CHECKSUM"\""

eval "curl ${POSTDATA} $URL"

Save the above script into a file called monitis_create_monitor.sh, be sure not to change the order of the variables in the checksum calculation as they must be in alphabetical order.  Ensure to make this file executable:

chmod 755 monitis_create_monitor.sh

Now run it:
./monitis_create_monitor.sh

The output should look similar to this:

{"status":"ok","data":305}

This is showing us that the monitor was successfully created and that the id of the resulting monitor is 305.  If you go to your Monitis account now, you will be able to access this monitor.  From the top level menu, go to Monitors then Manage Monitors and then Custom Monitors.  Here you should find the Login Monitor.  Click the check box next to the title and then click Add to Window.  A window will pop up below the Custom Monitors dialog box.  Close the Custom Monitors dialog box and you will see your new monitor there.  But no data has been sent to it, so it is not that interesting.

Sending Data to Custom Monitor

In order to send data to your Custom Monitor, you must provide the action, monitorId, checktime, and results (refer to http://monitis.com/api/api.html#addCustomMonitorResult for specifications).  The action is addResult, the monitorId is the id that was returned to us in the previous example (If you forgot the id, don’t worry we will get it back), the checktime is the timestamp of the results data, and the results is a string of the parameters and values in this format: name1value1;name2value2

The following script will send data to your Custom Monitor:

# add result to Custom Monitor for Monitis

#!/bin/bash
usage()
{
cat << EOF
usage: $0 options

This script will add results to a Custom Monitis Monitor.

OPTIONS:
-h Show this message
-a api key
-s secret key
-m monitor tag
-i monitor id
-t timestamp (defaults to utc now)
-r results name:value[;name2:value2...]
EOF
}

APIKEY=
VERSION="2"
SECRETKEY=
URL="http://monitis.com/customMonitorApi"
OUTPUT="xml"
MONITOR=
ID=
CHECKTIME=`date -u +"%s"000`
TIMESTAMP=`date -u +"%F %T"`
RESULTS=
SESSIONACTION=

while getopts "ha:s:m:i:t:r:s:" OPTION
do
case $OPTION in

h)
usage
exit 1
;;
a)
APIKEY=$OPTARG
;;
s)
SECRETKEY=$OPTARG
;;
m)
MONITOR=$OPTARG
;;
i)
ID=$OPTARG
;;
t)
CHECKTIME=$OPTARG
;;
r)
RESULTS=$OPTARG
;;
esac
done

if [[ -z $APIKEY ]] || [[ -z $SECRETKEY ]] || [[ -z $MONITOR$ID ]] || [[ -z $RESULTS ]] || [[ -z $CHECKTIME ]]
then
usage
exit 1
fi

# Get id of monitor if not provided
if [[ -z $ID ]]
then
XMLID=$(curl -s "$URL?apikey=$APIKEY&output=$OUTPUT&version=$VERSION&action=getMonitors&tag=$MONITOR" | xpath -q -e /monitors/monitor/id)
ID=${XMLID//[^0-9]/}
fi

# Add monitor result
ACTION="addResult"
# Create Checksum
CHECKSUM_STR="action"$ACTION"apikey"$APIKEY"checktime"$CHECKTIME"monitorId"$ID"results"$ RESULTS"timestamp"$TIMESTAMP"version"$VERSION
CHECKSUM=$(echo -en $CHECKSUM_STR | openssl dgst -sha1 -hmac $SECRETKEY -binary | openssl enc -base64 )
# Post Data to API

POSTDATA="--data-urlencode \"action="$ACTION"\" --data-urlencode \"apikey="$APIKEY"\" --data-urlencode \"checktime="$CHECKTIME"\" --data-urlencode \"monitorId="$ID"\" --data-urlencode \"results="$RESULTS"\" --data-urlencode \"timestamp=$TIMESTAMP\" --data-urlencode \"version="$VERSION"\" --data-urlencode \"checksum="$CHECKSUM"\""

eval "curl ${POSTDATA} $URL"

Save this file to monitis_add_result.sh and make executable.  You can run it with no parameters to get a help menu, that should be self-explanatory.  You can either provide the API Key and Secret Key on the command-line or fill in the script to contain it.  The script will provide you with the monitorId if you forget yours, but you will have to know the tag name you gave to your Custom Monitor when you created it.  Therefore, either your tag or your monitorId is required to run this script.

Capturing Information on Login

Now that we have a script to send data to the Custom Monitor, we need to have data to send.  This script could easily be run from .bashrc or /etc/bashrc – and that would work fine, if we knew that no user would be deleting their .bashrc.  Since we cannot guarantee that, we will use PAM (Pluggable Authentication Module) to control how and when we send information to the Custom Monitor.  Since no user without root access will be able to alter PAM, this is a secure way to guarantee login information.  Also since sshd, sftp, ftp, and most other programs utilize PAM for authentication, this will monitor all logins to the server, not just shell logins.

PAM offers many options and modules, we will be utilizing a module called pam_script.  pam_script allows you to execute a script on session open, session close, and/or on auth.  You must download and install pam_script first:

wget 'http://freshmeat.net/urls/47ddad89e38001dbe0dc50424e36987b' -O libpam-script.tar.gz
tar -xzvf libpam-script.tar.gz
cd libpam-script-x.x.x #x.x.x is the version that you just download, apparent from tar output
make
sudo cp pam_script.so /lib/security/
sudo chown root:root /lib/security/pam_script.so
sudo chmod 755 /lib/security/pam_script.so

pam_script is now installed, but not configured.  There are three files associated with pam_script, /etc/security/onsessionopen /etc/security/onsessionclose /etc/security/onauth  The first two files will work on a session and the last will work for a successful auth.  Since we want to monitor successful auths, we will create the onauth file:

#!/bin/sh
# onauth for Monitis Custom Login Monitor
USER=$1
SERVICE=$2
HOST=$PAM_RHOST

/etc/security/monitis_add_data.sh -m loginMonitor -r "user_login:$USER;host:$HOST;srv:$SERVICE"

This script will require that you move the monitis_add_data.sh script to /etc/security and make it and the onauth script executable by root and owned by root:

sudo mv monitis_add_data.sh /etc/security
sudo chmod 700 /etc/security/monitis_add_data.sh
sudo chown root:root /etc/security/monitis_add_data.sh
sudo chmod 700 /etc/security/onauth
sudo chown root:root /etc/security/onauth

Now we need to set PAM to utilize the pam_script module.  Depending on your system this will vary, but you need to edit the /etc/pam.d/common-auth file or something similar on your system.  You should add the following line:

# require the scripts to run at auth
auth required   pam_script.so  runas=root expose=rhost

Here we are telling module to run as root and to expose the rhost variable, which will contain the remote host information that we utilize in the above script with the $PAM_RHOST variable

Testing the Monitor

Now we have a setup that will log all usernames, remote hosts, and service that they logged in from to our Custom Monitor.  Give it a try, ssh to your machine several times.  You will see the values appear in your account’s Custom Monitor.

 

Read the original blog entry...

More Stories By Hovhannes Avoyan

Hovhannes Avoyan is the CEO of Monitis, Inc., a provider of on-demand systems management and monitoring software to 50,000 users spanning small businesses and Fortune 500 companies.

Prior to Monitis, he served as General Manager and Director of Development at prominent web portal Lycos Europe, where he grew the Lycos Armenia group from 30 people to over 200, making it the company's largest development center. Prior to Lycos, Avoyan was VP of Technology at Brience, Inc. (based in San Francisco and acquired by Syniverse), which delivered mobile internet content solutions to companies like Cisco, Ingram Micro, Washington Mutual, Wyndham Hotels , T-Mobile , and CNN. Prior to that, he served as the founder and CEO of CEDIT ltd., which was acquired by Brience. A 24 year veteran of the software industry, he also runs Sourcio cjsc, an IT consulting company and startup incubator specializing in web 2.0 products and open-source technologies.

Hovhannes is a senior lecturer at the American Univeristy of Armenia and has been a visiting lecturer at San Francisco State University. He is a graduate of Bertelsmann University.

@ThingsExpo Stories
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money! Speaker Bio: Esmeralda Swartz, CMO of MetraTech, has spent 16 years as a marketing, product management, and busin...
Samsung VP Jacopo Lenzi, who headed the company's recent SmartThings acquisition under the auspices of Samsung's Open Innovaction Center (OIC), answered a few questions we had about the deal. This interview was in conjunction with our interview with SmartThings CEO Alex Hawkinson. IoT Journal: SmartThings was developed in an open, standards-agnostic platform, and will now be part of Samsung's Open Innovation Center. Can you elaborate on your commitment to keep the platform open? Jacopo Lenzi: Samsung recognizes that true, accelerated innovation cannot be driven from one source, but requires a...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at Internet of @ThingsExpo, Robin Raymond, Chief Architect at Hookflash Inc., will walk through the shifting landscape of traditional telephone a...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic • Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it’s a mix of architectural style...
SYS-CON Events announced today that SOA Software, an API management leader, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. SOA Software is a leading provider of API Management and SOA Governance products that equip business to deliver APIs and SOA together to drive their company to meet its business strategy quickly and effectively. SOA Software’s technology helps businesses to accelerate their digital channels with APIs, drive partner adoption, monetize their assets, and achieve a...
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
SYS-CON Events announced today that Utimaco will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Utimaco is a leading manufacturer of hardware based security solutions that provide the root of trust to keep cryptographic keys safe, secure critical digital infrastructures and protect high value data assets. Only Utimaco delivers a general-purpose hardware security module (HSM) as a customizable platform to easily integrate into existing software solutions, embed business logic and build s...
Connected devices are changing the way we go about our everyday life, from wearables to driverless cars, to smart grids and entire industries revolutionizing business opportunities through smart objects, capable of two-way communication. But what happens when objects are given an IP-address, and we rely on that connection, sometimes with our lives? How do we secure those vast data infrastructures and safe-keep the privacy of sensitive information? This session will outline how each and every connected device can uphold a core root of trust via a unique cryptographic signature – a “bir...
Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at Internet of @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, will discuss how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.

SUNNYVALE, Calif., Oct. 20, 2014 /PRNewswire/ -- Spansion Inc. (NYSE: CODE), a global leader in embedded systems, today added 96 new products to the Spansion® FM4 Family of flexible microcontrollers (MCUs). Based on the ARM® Cortex®-M4F core, the new MCUs boast a 200 MHz operating frequency and support a diverse set of on-chip peripherals for enhanced human machine interfaces (HMIs) and machine-to-machine (M2M) communications. The rich set of periphera...

SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
Predicted by Gartner to add $1.9 trillion to the global economy by 2020, the Internet of Everything (IoE) is based on the idea that devices, systems and services will connect in simple, transparent ways, enabling seamless interactions among devices across brands and sectors. As this vision unfolds, it is clear that no single company can accomplish the level of interoperability required to support the horizontal aspects of the IoE. The AllSeen Alliance, announced in December 2013, was formed with the goal to advance IoE adoption and innovation in the connected home, healthcare, education, aut...