Quantcast
Channel: Madhuka
Viewing all 213 articles
Browse latest View live

Installing NodeJS in CentOS

$
0
0

It is fast and quick, just only two steps

1. Get the setup

curl --silent --location https://rpm.nodesource.com/setup_4.x | bash -

Note

--location

If the server reports that the requested page has moved to a different location this option will make curl redo the request on the new place.

--silent

Makes curl mute (silent mode). Don't show progress meter or error messages but it will still output the requested data

2. Install nodeJS

yum -y install nodejs

 

image


dhis2-android-dashboard Build from Source

$
0
0

DHIS 2 [1] is health management information system and DHIS Mobile covers the wide area of mobile development related to DHIS2, with focus on a wide portfolio of solutions for utilizing mobile technology.

Let build dhis2-android-dashboard from source [2].

1. Get git clone from source [2]. (You can use ‘legacy’ branch for build for now, No breaks)

2. Get SDK version and package for the build from Android SDK Manger.

Preferred SDK versions

  • targetSdkVersion 22
  • compileSdkVersion 22
  • buildToolsVersion 22.0.1

‘dhis2-android-dashboard:api’  is required  Android Support Repository. Better you install if you have not install it from Android SDK Manager.

If you have not set ANDROID_HOME, set it first.

set ANDROID_HOME=D:\Program Files (x86)\Android\android-studio\sdk

3. It comes with gradlew, There is nothing to do. 

Run the ‘gradlew.bat

image

If you like UI you can try ‘gradlew –gui’

image

 

Some tips for ‘gradle’

--offline : The build should operate without accessing network resources
--info : Set log level to info
--recompile-scripts : Forces scripts to be recompiled, bypassing caching
--refresh-dependencies : Refresh the state of dependencies
--profile : Build execution report
--all : Shows additional detail in the task listing

 

[1] https://www.dhis2.org/documentation

[2] https://github.com/dhis2/dhis2-android-dashboard

Node.JS with Express Session

$
0
0

In here we will try to mange session in node application.

Here are the dependencies which is used in this sample

"dependencies":

    {
        "express": "^4.8.7",
        "express-session": "^1.7.6"
    }

express-session module needs express. Therefore you have to add express in your project also.

var express = require('express');
var session = require('express-session');
var app = express();

session can be initialized by below code. Here ‘secret‘ is used for cookie handling

app.use(session({secret: 'secret cat'}));

After creating Session, Session variables can be introduced as 'appsession.username'.

var appsession;
app.get('/',function(req,res){
    appsession=req.session;
    appsession.username;
});

 

[1] https://github.com/expressjs/body-parser

[2] https://github.com/expressjs/session

CROS in Node

$
0
0

This post how to enable CORS in Node. CORS means cross-domain requests.

Simply using below line of code in the application respond level will solve CORS issue.

res.header("Access-Control-Allow-Origin", "*");

By below lines enable CORS for all the routes in that server.

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

you can add this for resources files as well.

app.get('/test', function(req, res){
  var file = __dirname + '/MyFile.zip';
  res.download(file); // Set disposition and send it.
});

Here is sample full code.

var express = require('express');

var app = express();
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', function (req, res) {
  var data = {
    "Fruits": [
      "apple",
      "orange"    ]
  };

  res.json(data);
});

app.get('/test', function(req, res){
  var file = __dirname + '/ZipFile.zip';
  res.download(file); // Set disposition and send it.
});

JavaScript references with setTimeout() and setInterval()

$
0
0

In this post contains some tips on using the setTimeout() and setInterval() functions in nested manner and using JavaScript reference in those.

  • setTimeout() is used to call function after period of time.
  • setInterval() is used to call function in a loop of time.

There is function x(){} which need to called after 30 seconds.
setTimeout(x(), 30000);

Now I need to call this function x() in 10 seconds loop of time and first call must to be call after 30 seconds.

setTimeout(
    setInterval(x(), 10000);
}, 30000);

setInterval is executed in a global context, If function x() is declared inside another context with setInterval(). This will call function x() only for one time. it will not loop

setTimeout(
    setInterval(x(), 10000);
}, 30000);

 

JavaScript reference to function with parameters

Better way is calling with reference in such context.

setTimeout(
    setInterval(x, 10000);
}, 30000);

Function x(){} upgraded with function parameter such as function x (a){}.

setTimeout(function() {
    console.log("Starting functions");
    x = x('foo');
    setInterval(x, 10000);
}, 30000);

 

Context change will avoid the looping x function. Here is the best way to achieve this.

setTimeout(function() {
    refx = testme('foo');
}, 5000);

function testme(a) {
    setInterval( function (){x(a);}, 10000);
}

OSSEC service for Centos7

$
0
0

OSSEC can be called as Log-based Intrusion Detection System (LIDS). You will need nano / vim and wget install in CentOS. You can used below command to install them.

yum install wget
yum install nano

1. Let’s download OSSEC

wget -U ossec http://www.ossec.net/files/ossec-hids-2.8.2.tar.gz

2. unzip it
tar xf ossec-hids-2.8.2.tar.gz

3. Open host-deny.sh

vim active-response/host-deny.sh


4. Remove spaces in below location
eg:
TMP_FILE = "
TMP_FILE="

image

5. Install

sudo ./install.sh

 

6. Start ossec

/var/ossec/bin/ossec-control start

image

You can used below command to see the status of OSSEC

/var/ossec/bin/ossec-control status

 

NOTE
Usage: /var/ossec/bin/ossec-control {start|stop|restart|status|enable|disable}

Adding agent for OSSIM from OSSEC

$
0
0

Need to install OSSEC and OSSIM in you network.

 

First we extract key from OSSIM

1. Go to OSSIM web UI and navigate to 'environment' => 'detection'
2. Click on 'Agents'
3. Pick agent and click on key icon for 'Extract Key'

image

 

Add agent for OSSEC

1. From below command we can find agents

/var/ossec/bin/manage_agents -l

2. Open “manage agents”
/var/ossec/bin/manage_agents

it will ask few questions

    * A name for the new agent: test
   * The IP Address of the new agent: 192.168.100.18
   * An ID for the new agent[001]: 002

3. Add agent for OSSEC

/var/ossec/bin/manage_agents –i <key>

Now I will check that agent is added

image

Python make life easy

$
0
0

I need rename some files in dir after processing some regex on there files names and files types. I was looking for terminal / cmd command for this. Put I just wrote python script in few minutes (2 mins)  and it works. It make my life easy with my PC.

In the directory there are huge amount of files with name that contains (some text).doc

eg:

Jane goes - (year 2010).mp3–> mydoc.mp3

02. feel like home- (uni).m–> 02. feel like home.mp3

 

python Code

import os
import re

files = os.listdir('.')
for file in files:
    str = ''+file
    new_name = re.sub(' - (.*).mp3$', '.mp3',str)
    os.renames(file,new_name);


module.exports VS exports

$
0
0

module.exports is the object that's actually returned as the result of a require call. Modules use exports to make things available.

The exports variable is initially set to that same object

You can create nodejs application and include below codes for package.json

{
  "name": "tutorial",
  "version": "1.0.0",
  "scripts": {
    "start": "node server.js"
  }
}

Then create two js files

  • hello.js
  • server.js

Let is create the simplest Module

//hello.js

console.log('Hello World');

//server.js

require('./hello.js');

image

 

It is not really good way develop a module. There are some patterns on creating modules for app. (Now I will go with app.js which was server.js in last sample and foo.js which will be our modules)

 

Pattern 1: Define a Global

// foo.js
foo = function () {
   console.log('foo!');
}

// app.js
require('./foo.js');
foo();

 

image

Global scope need to clean and nice. Pattern 01 is not much recommended

 

Pattern 2: Export an Anonymous Function

// foo.js

module.exports = function () {

console.log('foo!');

}

 

// app.js

var foo = require('./foo.js');

foo();

 

Pattern 3: Export an Named Function

// foo.js

exports.foo = function () {

console.log('foo!');

}

 

// app.js

var foo = require('./foo.js').foo;

foo();

 

Pattern 4: Export an Anonymous Object

// foo.js

var Foo = function () {};

Foo.prototype.log = function () {

console.log('foo!');

};

module.exports = new Foo();

 

// app.js

var foo = require('./foo.js');

foo.log();

 

Pattern 5: Export an Named Object

// foo.js

var Foo = function () {};

Foo.prototype.log = function () {

console.log('foo!');

};

exports.Foo = new Foo();

 

// app.js

var foo = require('./foo.js').Foo;

foo.log();

 

Pattern 6: Export an Anonymous Prototype

// foo.js

var Foo = function () {};

Foo.prototype.log = function () {

console.log('foo!');

}

module.exports = Foo;

// app.js

var Foo = require('./foo.js');

var foo = new Foo();

foo.log();

 

Pattern 7: Export an Named Prototype

// foo.js

var Foo = function () {};

Foo.prototype.log = function () {

console.log('baz!');

};

exports.Foo = Foo;

// app.js

var Foo = require('./foo.js').Foo;

var foo = new Foo();

foo.log();

OSSIM components

$
0
0

This post explain the steps to enable both OSSEC and SSH plugins in OSSIM.

First we enable the plugins.

1. Update the ossim configuration variables at /etc/ossim/ossim_setup.conf

  • Add ossec and ssh into the ‘detectors’

image

2. As config is updated and now we run ossim-reconfig by

  • ossim-reconfig -c -v –d

2.1 In SSH and OSSEC plugin config can be found in ‘etc/ossim/agent/plugins/ssh.cfg’, component / plugin  type and log location can found in the config as below

[config]
type=detector
enable=true
source=log
location=/var/log/auth.log

3. Then check the ossim-agent process is reading the log files

  • lsof +d /var/ossec/logs/alerts/ | grep alerts.log
  • lsof +d /var/log/ | grep auth.log

image


Let is test the plugin that we enabled.

Let is try to login with incorrect pass word and non existing user.

image

You can tail the log files and find the log record below

  • tail -f /var/log/auth.log
  • tail -f /var/ossec/logs/alerts/alerts.log

This alerts can be found in OSSIM GUI as well. (analysis --> security_events)

Make filter user name that we try for testing.

image

Event details can be found in as below

image

Reading a custom log file from OSSIM

$
0
0

Let write OSSIM plugin read hello log (which is my custom log file for this post). For this post I will call my plugin as ‘hello’ and it read log file called ‘hello. log’.

Creating the plugin configuration file – hello.cfg

CFG file contains fields called 'DEFAULT', 'config', translation and rules

Plugins can be found in below location. we have to move to that directory.  There you can see all the ossim plugins

/etc/ossim/agent/plugins

In Default section, we have to add the plugin_id field (Range is 9001 to 10000)
plugin_id=9002

Destination ip and port if it is there, But for us no
dst_ip=\_CFG(plugin-defaults,sensor)
dst_port=22

In config section, we have to add type of the plugin and the location for to read log files (I will have mail server logs for to read as named hello log)
(/var/log/custom.log)

Create new translation table for hello log.

Adding custom log file

Make sure you have added the custom log that you need to read.

Adding log file to /var/log/hello.log

 

Create DB for hello plugin

In here we have to consider our translation in cfg

check 'plugin' table is there any plugin with plug_id = 9002 (which here we are using). Do the same for 'plugin_sid' table.

Then insert below data to the tables

INSERT INTO plugin (id,type,name,description) VALUES (9002,1,'hello','Hello log reader');

Add translation  cfg to table as below

INSERT INTO plugin_sid (plugin_id,sid,category_id,class_id,name,priority,reliability) VALUES (9002,1,NULL,NULL,'hello:HELO',3,2);

Tip

Finding ossim MYSQL user name and pass word from grep if you do not the grep.

grep ^pass= /etc/ossim/ossim_setup.conf
grep ^user= /etc/ossim/ossim_setup.conf

 

Before testing you have to enable the plugin that we create now.  Please referee by last post on ossim.

Make sure you have restart the OSSIM

 

Testing the hello plugin

Check is our log file is reading by ossim

lsof +d /var/log/ | grep hello.log

image

Let check is our data source plug in menu

image

Let check our new event from hello is reading in web UI.

analysis -> security events (SIEM)

Here is our 'Hello' data source pick it.

image

Let check our log in hello in UI

image

Here are them.

Now add new log record to log file from terminal as below.

sed -i '$ a\2016-05-27 09:10:16 220.247.242.83 36A42160 SMTPSVC1 MEE-PDC 192.168.1.23 0 MAIL - +FROM:+<madhuka@test.com> 230 0 45 65 0 SMTP - - - -' hello.log

Then tail it and see that record is there. Then check on web UI

Here it is!!

image

Making OSSIM Alarm from Event

$
0
0

This post we will going to genrate alarm from ossim when custom event (attack or interested event) is occurred in our system. I will be using custom plug  that we built. 

1. Go to the “Data source”
configuration -> threat_intelligence -> data_source

2. Then pick our custom data source (hello) which we created. (How to create OSSIM custom data source)

image

3. Create new Event type by click button  ‘Insert new event type’

4. Fill the form for new event and pick ‘Alarm’ for Category

image

5. Then click on ‘Apply changes’

image

6. Let test this by adding new log record with ‘exe’. (you can used this python script to feed log to the custom log file)

Calling the python script as below (python log-feed.py <dst_ip> <msg_type>

python log-feed.py 192.168.100.34 EXE

image

image

OSSIM Risk count is calculate with below formulary

Risk=(priority*reliability*Asset)/25


7. Go to Analysis –> alarms

There you will find alarm hits. You can create tags (labels)  for alarm also as below

image

OSSIM Directives

$
0
0

Previous post  discuses about ossim correlation. Now we create new directive targeting our hello log custom plugin.

1. Go to the ‘Directives Page’ configuration -> threat_intelligence -> directives

2. Click on 'New Directive'

3. Follow up the wizard (you can referee previous post to get more understanding about those fields)

image

4. Next you can build the rule

You can find the xml directive in

/etc/ossim/server/{unique_id}/user.xml

 

<?xml version="1.0" encoding="UTF-8"?>

<directive id="500001" name="custom_directive" priority="3">
   <rule type="detector" name="custom_rule" from="192.168.100.188" to="ANY" port_from="ANY" port_to="ANY" reliability="2" occurrence="1" plugin_id="9002" plugin_sid="2"/>
</directive>

 

This plugin_id="9002" is our ‘hello plugin’ and plugin_sid="2" is mapping to MAIL. This directive will hit when there is MAIL event from SRC_IP 192.168.100.188

 

5. Then restart the server from directive page UI

6. Next feed some log to hit the directive

python log-feed2.py 192.168.100.184 MAIL

#event only list not the directive is hit

python log-feed2.py 192.168.100.188 MAIL

#Here directive is hit

image

 

image

Advance Tutorial in OSSIM Directive

$
0
0

Following Event in OSSIM

image

In server if there is flow of above we will need trigger (alert) in our ossim. User make ‘QUIT’ event with following ‘DATA’ event


<directive id="500002" name="Exceeding the email count" priority="4">
   <rule type="detector" name="Exceeding the mail count" from="ANY" to="ANY" port_from="ANY" port_to="ANY" reliability="1" occurrence="1" plugin_id="9002" plugin_sid="4">
      <rules>
         <rule type="detector" name="Test" from="ANY" to="ANY" port_from="ANY" port_to="ANY" reliability="5" occurrence="1" plugin_id="9002" plugin_sid="5"/>
      </rules>
   </rule>
</directive>

Testing the Use case

image

Reading Event in real-time

image

 

Event QUIT is followed by QUIT OR RCPT

image

Alert will trigger only User make ‘QUIT’ event with following ‘DATA’ or ‘RCPT’ event

 

<directive id="500002" name="Exceeding the email count" priority="4">
   <rule type="detector" name="Exceeding the mail count" from="ANY" to="ANY" port_from="ANY" port_to="ANY" reliability="1" occurrence="1" plugin_id="9002" plugin_sid="4,1">
      <rules>
         <rule type="detector" name="Test" from="ANY" to="ANY" port_from="ANY" port_to="ANY" reliability="5" occurrence="1" plugin_id="9002" plugin_sid="5"/>
      </rules>
   </rule>
</directive>

 

Event Occurrence count

image

<directive id="500002" name="Exceeding the email count" priority="4">
   <rule type="detector" name="Exceeding the mail count" from="ANY" to="ANY" port_from="ANY" port_to="ANY" reliability="1" occurrence="1" plugin_id="9002" plugin_sid="4">
      <rules>
         <rule type="detector" name="Test" from="ANY" to="ANY" port_from="ANY" port_to="ANY" reliability="5" occurrence="2" plugin_id="9002" plugin_sid="5"/>
      </rules>
   </rule>
</directive>

Alert will trigger only User make ‘QUIT’ event two times with following ‘DATA’ event

Creating Correlation Rules and Alarms in AlienVault

$
0
0

The goal of a correlation analysis is to see whether two measurement variables co vary, and to quantify the strength of the relationship between the variables.

Correlation is important to make sense out of all that information in the system. Correlation to the rescue and increase evidence of the event and the business impact and the event a false positiveness.

 

Correlation process

image

Features Correlation rules can nest any level AND condition: branch another level OR condition: insert a new rule on same level

 

Risk Formula

Risk=(priority*reliability*Asset)/25

 

Correlation rules

Features Correlation rules can nest any level

  • AND condition: branch another level
  • OR condition: insert a new rule on same level

Threat detection use case

  • Correlate firewall events to detect common DoS and DDoS attacks
  • Prebuilt AlienVault correlation directives cover a lot of those already
  • Modify for your environment
  • Build Security Intelligence

Eg:

Successful SSH login to VIP host Service going down on host Correlation rule will generate an alert.

 

Alarms

  • Reduce false positive alarms

As you collect more events from different external systems, you may run into a scenario that is causing the USM Server to generate more alarms than you want. You can use policies to filter the events to reduce the number of alarms that are created.

  • Sending an email notification

You can create a policy to automatically trigger an email to administrators or others whenever a high-risk alarm occurs.

  • Temporarily hiding true positive alarms

Occasionally, you may need to temporarily disable alarms based on a particular set of events. This makes sense when you want to reduce excessive noise until you have had time to analyze and take corrective or preventative actions.

  • Increasing the importance of a specific event

Sometimes you might want to closely monitor a specific IP address or a specific port.  You can use policies to generate an alarm whenever events occur that include the IP address or that port without writing a correlation rule.


Adding OSSEC client to OSSEC Server

$
0
0

For this you will need two machine, one for OSSEC server and other one for OSSEC client. Post contains mainly two components

  • OSSEC server
  • OSSEC agent (client)

1. Install the server and steps are explain in previous article.   and same way install OSSEC agent in other machine.

2. In server add new agent by

# /var/ossec/bin/manage_agents

(Enter you client IP in here, give unique agent ID number also)

image

3. Extract OSSEC agent key from

# /var/ossec/bin/manage_agents

Enter : e

image

4. Adding key to the client which is given from server. (make sure you copy it correctly). Enter below command in client machine (command is same that is is used to extract key from server machine)

# /var/ossec/bin/manage_agents

image

5. Start the client  and server

# /var/ossec/bin/ossec-control start

image

It is done. As extract point I like to mention that if you having OSSIM in you server side you can find the new agent if you restart the OSSIM config

# ossim-reconfig -c -v -d

Here is our active agent in in OSSIM

Environment->Detection->HIDS->Agents

image

You can remove OSSEN client from below command in client and server you have to remove from OSSEC manager also.

# rm -rf /var/ossec/

Host based firewall in Linux

$
0
0

Linux comes with a host based firewall called Netfilter. 'iptables' is program  linux based firewall and it handles filtering for IPv4, and ip6tables. This post lists most simple iptables solutions required by a new Linux user to secure his or her Linux operating system from intruders.

Displaying the Status of Your Firewall
iptables -L -n -v

-L : List rules
-v : Display detailed information (packet and byte counters)
-n : Display IP address and port in numeric format

Do not use DNS to resolve names. This will speed up listing.

image

Stop / Start / Restart / Save / Delecct the Firewall
service iptables stop
service iptables start
service iptables restart

service iptables save

iptables -F  : Deleting (flushing) all the rules
iptables -X  : Delete chain

Insert Firewall Rules

To insert one or more rules in the selected chain as the given rule number use the following syntax. First find out line numbers, enter:
# iptables -L INPUT -n –line-numbers

iptables -I INPUT 2 -s 192.168.66.26 -j ACCEPT

Then you have to call save iptables

Restore Firewall Rules

To restore firewall rules form a file called /root/madhuka.active.firewall.rules, enter:

# iptables-restore < /root/madhuka.active.firewall.rules


Example - Block Facebook.com Domain
First, find out all ip address of facebook.com, enter:
# host -t a www.facebook.com

whois 31.13.91.36 | grep CIDR

CIDR:           31.13.90.0/63

To prevent outgoing access to www.facebook.com, enter:
# iptables -A OUTPUT -p tcp -d 31.13.90.0/63 -j DROP

You can also use domain name, enter:
# iptables -A OUTPUT -p tcp -d www.facebook.com -j DROP
# iptables -A OUTPUT -p tcp -d facebook.com -j DROP

 

iptables file

you can find the iptables and you can edit it (If you know it well only)
vi /etc/sysconfig/iptables

Testing Log forwarding in OSSEC

$
0
0

OSSEC client and server is connected using UDP port 1514. Need to testing message passing over UDP.

To see ossec network connections is there by below command

# netstat -putan | grep ossec

There must to be results in both server and  client

Here it in server

image 

Here it is client (agent)

image

To check if ossec-server is receiving data on port 1514:

# ngrep -q -d any port 1514

image

Then send message from client side

#logger --server 192.168.100.184 --port 1514 "myserver myprogram: the message from madhuka";

image

You will find it in server side

image

Let check our client is monitored in OSSIM server. I will try to make some login fails for testing and it show in wen interface.

image

image

OSSEC configure to new log file

$
0
0

Finding the logs in my server. I generally use lsof to list what is my server.

lsof | grep log

I check which log are reading by OSSEC

Check cat /var/ossec/etc/ossec.conf  |grep "<location>/"

Add new access log to OSSCE.

/var/ossec/bin/util.sh addfile /var/log/httpd/nic.access_log

OR

Just update “/var/ossec/etc/ossec.conf”

Then add some log or run your server to get some log

echo "123.231.120.128 - - [21/Jun/2016:19:04:41 +0530] \"POST /foosearch.php HTTP/1.1\" 404 35765  \"foo.com\" \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/48.0.2564.82 Chrome/48.0.2564.82 Safari/537.36\"">> access_log

Install OSSIM

$
0
0

1. Download the image file of OSSIM

2. Make bootable pen with OSSIM ISO file

image

3. Boot drive

Make sure you have internet connection

4. Select OSSIM server to install

5. Just follow the the wizard

6. Add the net work details correctly with unique new IP for OSSIM server.

7. After install is completed and go through web interface to setup configuration of the OSSIM

Viewing all 213 articles
Browse latest View live