Find us on facebook

Oct 29, 2016

CISCO Meraki Splash Page Configuration - Basic - With Lumen

First access CISCO Meraki dashboard and setup Splash URL.

When wireless client open the browser and makes HTTP request , it will be automatically redirected to this URL with some useful parameters. If we redirect this to lumen, It would be like,

    /**
     * [click - click through splash page].
     *
     * @param Request $request
     *
     * @return [type]
     */
    public function click(Request $request)
    {
        $baseGrantUrl = $request->input('base_grant_url');
        $userContinueUrl = $request->input('user_continue_url');
        $nodeMac = $request->input('node_mac');
        $clientIp = $request->input('client_ip');
        $clientMac = $request->input('client_mac');
        $data = array('baseGrantUrl' => $baseGrantUrl,
                      'userContinueUrl' => $userContinueUrl,
                      'nodeMac' => $nodeMac,
                      'clientIp' => $clientIp,
                      'clientMac' => $clientMac);
        return view('splash.click_through', ['data' => $data]);
    }

click_through.blade.php

        <form action="/api/v1/splash/signin" method="post" class="form col-md-12 center-block">
        <input type="hidden" name="baseGrantUrl" value="{{$data['baseGrantUrl']}}">
        <input type="hidden" name="userContinueUrl" value="{{$data['userContinueUrl']}}">
        <div class="form-group">
          <input class="form-control input-lg" placeholder="Email" type="text" name="email" required>
        </div>

        <div class="form-group">
          <button class="btn btn-primary btn-lg btn-block">Sign In</button>
        </div>
        </form>

signin

    /**
     * [signin - splash page signin].
     *
     * @param Request $request
     *
     * @return [type]
     */
    public function signin(Request $request)
    {
        $url = $request->input('baseGrantUrl')."?continue_url="."http://xxxx.xxxx.com/api/v1/splash/success"."&duration=300";
        return view('splash.signin', ['url' => $url]);
    }

signin.blade.php

      <h1>Login</h1>
      <a href="{{$url}}">Click here to Continue....</p>

success

    /**
     * [success - splash page success].
     *
     * @param Request $request
     *
     * @return [type]
     */
    public function success(Request $request)
    {
        return view('splash.success');
    }

success.blade.php

     <h1>Success</h1>
 

Send pushnote to device with AWS Lambda Nodejs

var params = {'PlatformApplicationArn':platformApplicationArn,'Token': token};

sns.createPlatformEndpoint(params,function(err,EndPointResult)
    {
        if(EndPointResult != null){
          var clientArn = EndPointResult["EndpointArn"];
          sns.publish(
            {
              TargetArn: clientArn,
              Message: JSON.stringify(clientMessage),
              Subject: JSON.stringify(subject),
              MessageStructure: 'json'
            },
            function(err,data){
              if (err) {
                  console.log("Error sending a message "+err+JSON.stringify(params.Token));
                  if(err == "EndpointDisabled: Endpoint is disabled"){
                    sns.deleteEndpoint({'EndpointArn': clientArn}, function(err, data) {
                      if (err) console.log("Error removing Endpoint Arn: "+err);
                    });
                    message.deleteMessage(function(err, data) {
                      if(err){
                        console.log("Error deleting message: "+err);
                      }
                      message.next();
                    });
                  }
                  message.next();
              } else {
                  var messagedate = new Date();
                  console.log("Sent message: "+data.MessageId+messagedate+JSON.stringify(params));
                  sns.deleteEndpoint({'EndpointArn': clientArn}, function(err, data) {
                    if (err) console.log("Error removing Endpoint Arn: "+err);
                  });
                  message.deleteMessage(function(err, data) {
                    if(err){
                      console.log("Error deleting message: "+err);
                    }
                    message.next();
                  });
              }
            }
          );
        }
        if(EndPointResult == null){
          message.next();
        }
       
    });

Send message to a queue with AWS Lambda Nodejs

Following parameters need to be passed.
var params = {
            MessageBody: JSON.stringify({"platformApplicationArn":arn,
              'token':token_id,
              'message': messageBody,
              'subject':subject,
             }),
            QueueUrl: "https://sqs.ap-region-x.amazonaws.com/xxxxxxxxxxxx/2ndqueue"
      };

Send message to the queue.
sqs.sendMessage(params, function(err, data) {
    if (err){
      console.log(err, err.stack);
     
    }
    else {
      console.log(data);
    }
});

Connection pool and query within Lambda nodejs runtime

var pool = openConnectionToDB(host,username,password,database);

pool.getConnection(function(err,connection){
console.log('connected as id ' + connection.threadId);
        //Query
connection.query("SELECT * FROM ?? WHERE ?? = ? AND deleted_at IS NULL",['table_name','id',subject],function(err,rows){
           if(!err) {
             if(typeof rows[0] == 'undefined'){
               connection.release();
               connection.destroy();
             }
           }
 });
});

Using SqsQueueParallel to receive messages parallaly from a queue

var queue = new SqsQueueParallel({
      name: "queue1",
      region:process.env.REGION,
      accessKeyId:process.env.ACCESS_KEY_ID,
      secretAccessKey:process.env.SECRET_ACCESS_KEY,
      maxNumberOfMessages: 10,
      concurrency: 10
});

queue.on('message', function (message)
{
//more code
});

Lambda Function Basic

Create serverless function.
serverless function create functions/Function1/func1 (This command should be given within the project folder)

Within Function1 folder it creates
func1 folder and package.json file

Within func1 folder it creates following files.
event.json
handler.js
s-function.json

In handler.js file, we can include all the functions.

First we need to get required packages as below.

var aws = require('aws-sdk');
var SqsQueueParallel = require('sqs-queue-parallel');
var sqs = new aws.SQS({"accessKeyId":process.env.ACCESS_KEY_ID, "secretAccessKey": process.env.SECRET_ACCESS_KEY, "region": process.env.REGION});

Within handler function we can include the logic we want.

module.exports.handler = function(event, context, cb) {
};

s-function.json structure will be like
{
  "name": "func1",
  "runtime": "nodejs4.3",
  "description": "Serverless Lambda function for project: XXXXX",
  "customName": "func1",
  "customRole": "arn:aws:iam::xxxxxxxxxxxx:role/role",
  "handler": "func1/handler.handler",
  "timeout": 300,
  "memorySize": 128,
  "authorizer": {},
  "custom": {
    "excludePatterns": []
  },
  "endpoints": [],
  "events": [
    {
      "name": "V1Schedule",
      "type": "schedule",
      "config": {
        "schedule": "rate(5 minutes)",
        "enabled": true
      }
    }
  ],
  "environment": {
    "SERVERLESS_PROJECT": "${project}",
    "SERVERLESS_STAGE": "${stage}",
    "SERVERLESS_REGION": "${region}",
    "ACCESS_KEY_ID": "AWSKEYHERE",
    "SECRET_ACCESS_KEY": "AWSSECRETHERE",
    "REGION": "ap-southeast-1",
    "LIMIT": "300"
  },
  "vpc": {
    "securityGroupIds": [],
    "subnetIds": []
  }
}

package.json structure will be like,
{
  "name": "LambdaFunction",
  "version": "0.0.1",
  "description": "A Serverless Project and its Serverless Plugin dependencies.",
  "author": "ishara",
  "license": "MIT",
  "private": false,
  "repository": {
    "type": "git",
    "url": "git://github.com/"
  },
  "dependencies": {
    "async-foreach": "^0.1.3",
    "mysql": "^2.11.1",
    "object-sizeof": "^1.0.10",
    "sqs-queue-parallel": "^0.1.6"
  }
}

Pushnotification proceesor with AWS Lambda

Push Notification Processor is a microservice developed using AWS Lambda Node.js 4.3 runtime. To deploy the Lambda functions to AWS, the serverless framework is used.

Process:
To send bulk pushnotes, we use two SQS queues.
Platform -> 1st queue -> Execute 1st Lambda function -> 2nd queue -> Execute 2nd Lambda function to send pushnote to device

To execute lambda functions, we need a Role that has permission AmazonSQSFullAccess,AmazonSNSFullAccess

We can assign permissions to a role through AWS IAM (Identity Access Management).

In handler.js file, we can include all the functions.

Oct 8, 2016

XSS attack and CSRF attack

Cross-Site Scripting (XSS)

XSS is a code injection attack.The attacker tries to display a code which they control, in the target site. If target site allows HTML characters in a form field, where form field can be entered like "Something<script type="text/javascript" src="http://www.test.com/script.js"></script>" Here, when this field details are displayed in a page, the script too will run. Someone can use this script to grab sensitive information, log the key strokes, etc...

Cross-Site Request Forgery (CSRF)

This is also known as one-click attack or session riding. This is a form of attack where an authenticated user performs an action on a site without knowing it.


Sep 9, 2016

Serverless Apps with AWS Lambda

Serverless Framework

The Serverless Framework is a new cloud computing trend. It is open-source, command line tool and standard syntax that is used to easily build serverless architectures on AWS Lambda, Google Cloud Functions, and Windows Azure Functions.

"Serverless platforms allow developers to build apps without worrying about infrastructure."

Install the Serverless Framework

Make sure you have node and npm installed. You need node 4.0 or greater.

npm install serverless -g

Once the package is installed globally, you can create or download a new project and start working on your Lambda functions in JavaScript (Node.js 0.10 or 4.3) or Python 2.7.

Create project : serverless project create

Create Function : serverless function create function/SubFolder/FunctionName -s dev -r ap-northeast-1 (-s = dev or prod stage -r = aws region)

Deploy Function : serverless function deploy

Deploy Events : serverless event deploy EventName -s dev -r ap-northeast-1