Tuesday, March 15, 2016

Augmentation and Inheritance

JavaScript, we have prototype-based inheritance. That means an object has a reference to another certain object, its prototype. Whenever a property of an object is accessed, the prototype chain is searched for this property. So if the the object does not have this property itself, its prototype is inspected for this property and so on.
+------------+    +-------------+
|  Instance  |    |  Prototype  |
| __proto__ -+--->|  __proto__ -+-->...
| foo        |    |  bar        |
+------------+    +-------------+
Instance has both, the foo and bar properties.
Now, if you have a constructor function, you can create many instances (objects) referring to the same prototype. When you now add a new property to that prototype, all instances will have this property too (due to the prototype chain).
This is often done to dynamically extend instances but it is only one consequence of prototype inheritance, it is not inheritance itself.
What is the difference between augmentation and inheritance?
Inheritance would be to set the prototype of an object to a certain object so that it is in the prototype chain. Augmentation is just copying properties. The object would own that property then:

+------------+
|  Instance  | 
| __proto__ -+--->...
| foo        |    
| bar        |
+------------+

Thursday, March 10, 2016

parentController, childController & myService with Same reference objects


angularjs parent child controller communication


An angular app App having a service myService, which holding an object data that is used by two Controllers, parentCtrl and childCtrl.

Here parentCtrl is parent of childCtrl, childCtrl inherits scope of parentCtrl.If we reference data within parentCtrl like

 $scope.data = myService.getData()

which also makes it accessible from childCtrl.

Here data defined in the closure of myService, hence $scope.data is just a reference to data.

Now, If we altered data's properties within the child controller and everyone, myService, parentCrl and childCtrl will be aware of these changes.

If we want to overwrite the entire data object we need to invoke myServices method setData. If you invoke this method in parentCtrl, myService, parentCrl and childCtrl will be aware of these changes. If you did the same within childCtrl it is not notified to all.

To solve this Issue we can use $broadcast and $on

More information refer http://frontendx.blogspot.in/2016/02/angularjs-provides-on-emit-and.html

This is the setData function of myService


function setData(newData) {
    data = newData;
}

Update this function as below reffered

function setData(newData) {
    data = newData;
    $rootScope.$broadcast('dataHasChanged', {data : data});
}

Now in parentCtrl

$scope.$on('dataHasChanged', function(evt, args) {
  $scope.data = args.data;
});

Here both myService and parentCtrl is notified when ever setData function is called.

This scenario helps to notify the modification to all when modification done outside of these three items(myService,parentCtrl,childCtrl).

Firing $watch event manually in angularjs


Firing $watch event manually in angularjs


We have few options:

  1. Use $scope.$apply() to run the digest loop which call all of the watch expressions.
  2. Put you inner watch code inside a function and call it manually.
  3. Change messages.

Explanation for second one:


var watchFunc = function(){
    // the code
}

$scope.$watch('message',watchFunc);

watchFunc();

Monday, March 7, 2016

SQL Injection - I

SQL Injection:

SQL injection is a technique where malicious users can inject SQL commands into an SQL statement, via web page input.
Injected SQL commands can alter SQL statement and compromise the security of a web application.

SQL injection errors occur when:

Data enters a program from an untrusted source.
The data used to dynamically construct a SQL query.

Types:

First Order Attack:

The attacker can simply enter a malicious string and cause the modified code to be executed immediately.

Examples of First Order SQL Injection Attack:

1.UNIONS added to an existing statement to execute a second statement

2.Subquery added to an existing statement

3.Existing SQL short-circuited to bring back all the data (for example, adding a query condition such as OR 1=1)


Second Order Attack:

The attacker injects into persistent storage (such as a table row) which is deemed as a trusted source. An attack is subsequently executed by another activity.

Examples of Second Order SQL Injection Attack:

1.Suppose you have a Web-based application which stores usernames alongside other session information. Given a session identifier such as a cookie you want to retrieve the
current username and then use it in turn to retrieve some user information. You might therefore have code for an "Update User Profile" screen somewhat similar to the following:

execute immediate 'SELECT username FROM sessiontable WHERE session
='''||sessionid||'''' into username;

execute immediate 'SELECT ssn FROM users WHERE
username='''||username||'''' into ssn;

2.This will be injectable if the attacker had earlier on the "Create Account" screen created a username such as:
XXX' OR username='JANE

Which creates the query:
SELECT ssn FROM users WHERE username='XXX’ OR username='JANE'

If the user XXX does not exist, the attacker has successfully retrieved Jane’s social security number.

3.The attacker can create malicious database objects such as a function called as part of an API, or a maliciously named table by using double quotation marks to introduce dangerous constructs.

For example, an attacker can create a table using a table name such as "tab') or 1=1--", which can be exploited later in a second order SQL injection attack.


Lateral SQL Injection:

The attacker can manipulate the implicit function To_Char() by changing the values of the environment variables, NLS_Date_Format or NLS_Numeric_Characters.

Examples of Lateral SQL Injection Attack:

1.Using Lateral SQL Injection, an attacker can exploit a PL/SQL procedure that does not even take user input. When a variable whose data type is date or number is concatenated into the text of a SQL statement, then, contrary to popular belief, there still is a risk of injection. The implicit function TO_CHAR() can be manipulated by using NLS_Date_Format or NLS_Numeric_Characters, respectively. You can include arbitrary text in the format model, and you do not need to include any of the “structured” elements such as Mon, hh24, and so on. Here's the “normal” use of that flexibility:

SQL> SET SERVEROUTPUT ON
     ALTER session SET NLS_Date_Format = '"The time is"... hh24:mi'

Session altered.

SQL> SELECT TO_CHAR(SYSDATE) d FROM Dual D
--------------------

The time is... 19:49

SQL> DECLARE
     d DATE := TO_DATE('The time is... 23:15');
     BEGIN
     -- Implicit To_Char()
     DBMS_OUTPUT.PUT_LINE(d);
     END;

The time is... 23:15
PL/SQL procedure successfully completed.


More Explanation:

SQL Injection Based on 1=1 is Always True:

Comes in to First Order Attack.
Lets assume your SQL query

SELECT * FROM Users WHERE UserId = Username

When username recieved in request is proper value (username), then everything works fine.

If username is something like this

"diffusername or 1=1"

Then your SQL statement becames like

SELECT * FROM Users WHERE UserId = 105 or 1=1

If you sending overall object as response from server thats it story ends. Here the hacker got all user table.

I seen in many websites people returning hash_code (which is the hashed password), If you do that hacker can decode hashed code, there are thousands of decoders available on net.

If hacker decided to collaspe all your client business, He will send username as "diffusername ; DROP TABLE USERS"

SELECT * FROM Users WHERE UserId = 105 or 1=1

If this statement got executed no more users ,no more logins and
no more business. Main triggers on particular queries is another best way.


Ref:

download.oracle.com/oll/tutorials/SQLInjection/html/lesson1/les01_tm_attacks.htm
https://www.owasp.org/index.php/SQL_Injection
http://www.slideshare.net/RespaPeter/types-of-sql-injection-attacks

Still there are many interesting things about SQL Injection, If you people interested I will update in my next Post.
   Next >>>

Monday, February 1, 2016

you can secure your WebSocket connections using OAuth. Kaazing WebSocket Gateway

Yes you can secure your WebSocket connections using OAuth. Kaazing WebSocket Gateway (http://kaazing.com) has an elegant architecture for authentication and authorization using a variety of methods (token-based, HTTP-based, or cookie-based).
Moreover it is done in a way that is secure over the Web where you may be dealing with untrusted clients. (Or at least, you should always assume you are dealing with untrusted clients.)
When a client attempts a WebSocket connection, the Gateway receives the request. If the particular service (i.e. URL) has been configured to be protected, the client will be challenged.
Upon receiving the challenge the client needs to then supply a token (assuming that's what has been configured in this case). If the client already has the token -- because they've previously signed on to some other system or web page -- then great. If not then it must be obtain one. This depends entirely on your choice of security. In this case it contacts the OAuth token provider to obtain a token. That may mean the user having to provide credentials.
Once the client has a token it sends it to the Gateway as a response to the challenge. The Gateway supports the standard JAAS architecture so you can plug in login modules to perform the necessary authentication. In this case it may send the token to the token provider in order to determine if it's a valid token.
If it is, the WebSocket connection is opened and can continue. If not, the request is rejected and the connection is closed.
This has the benefit of protecting your back-end applications -- only valid users will pass through the Gateway. Furthermore, because Kaazing WebSocket Gateway can live in the DMZ, un-authenticated users never even enter the trusted network within your main firewall. They fail fast on the outside.
This architecture is powerful because it doesn't matter what security framework you have chosen, Kaazing's Gateway will plug in to it, rather than imposing its own security mechanism on you. Also, in the case of OAUth or OAuth2, it does not need to understand or decode the token. The token provider is the only one that needs to understand it. But if your token provider wants to specify a duration for the session, that can be included along with the token and the Gateway will honor it.
If browser-based applications are unsafe, I could live with that, but I want to make sure that at least the web-based applications have a secure way to access the websocket.
Web-based and browser-based applications can be made safe with the right architecture and implementation. At Kaazing we always operate under the assumption that you are dealing with untrusted clients on the Web and construct our architecture accordingly.
Here are couple sections of the documentation that have a high-level description:

http://tech.kaazing.com/documentation/html5/3.5

A credentials grant is only as secure as the authentication performed before handing out the access token. That's outside the specification they say. So that depends on whatever authentication regime you decide to put in front of giving out tokens in response to credential grants.
Now, let's assume you've set up a nice secure way to get your credentials grant, or get an access token into your browser via a regular OAuth2 request.
Under the OAuth2 specification you are free to MAC-digest portions, encrypt portions or protect the data within that token in any number of ways. The security of the access token in the browser depends on what information it contains - often times people design it to contain minimal information (userid, expiration-time, version, digest) and make it self-verifiable by your server (hence the digest). The contents of the token are virtually arbitrary. Some systems even give out access "codes" as proxies for the token.
Now let's assume you have a protected "secure format" access token, with a time restriction. Lets consider a real-world example: Facebook and their OAuth2 implementation. Be it a full access token or an access code for server-side credential retrieval (each with time restrictions) you can send the token (or code) from the browser to secure access to a WebSocket, using the Kaazing Gateway.
One of the things I've taken away from working with Kaazing's gateway is that OAUth2 really doesn't secure anything - you are free to hand out access tokens of arbitrary form. It's a good idea to make sure your credential-authentication scheme, the access_token format and the access_token lifetime are all good policy decisions - then you get security.

The Kaazing Gateway will let you send arbitrary tokens into the Gateway and validate them with a JAAS login module that you write to verify them. The security of the regime is up to you and policy decisions.

AngularJS - $on, $emit, and $broadcast

AngularJS provides $on, $emit, and $broadcast services for event-based communication between controllers.

$emit

It dispatches an event name upwards through the scope hierarchy and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $emit was called. The event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Broadcasting</title>
  5. <script src="lib/angular.js"></script>
  6. <script>
  7. var app = angular.module('app', []);
  8.  
  9. app.controller("firstCtrl", function ($scope) {
  10. $scope.$on('eventName', function (event, args) {
  11. $scope.message = args.message;
  12. console.log($scope.message);
  13. });
  14. });
  15.  
  16. app.controller("secondCtrl", function ($scope) {
  17. $scope.handleClick = function (msg) {
  18. $scope.$emit('eventName', { message: msg });
  19. };
  20. });
  21.  
  22. </script>
  23. </head>
  24. <body ng-app="app">
  25. <div ng-controller="firstCtrl" style="border:2px solid #E75D5C; padding:5px;">
  26. <h1>Parent Controller</h1>
  27. <p>Emit Message : {{message}}</p>
  28. <br />
  29. <div ng-controller="secondCtrl" style="border:2px solid #428bca;padding:5px;">
  30. <h1>Child Controller</h1>
  31. <input ng-model="msg">
  32. <button ng-click="handleClick(msg);">Emit</button>
  33. </div>
  34. </div>
  35. </body>
  36. </html>

How it works..

$broadcast

It dispatches an event name downwards to all child scopes (and their children) and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $broadcast was called. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards toward the child scopes and calls all registered listeners along the way. The event cannot be canceled.
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Broadcasting</title>
  5. <script src="lib/angular.js"></script>
  6. <script>
  7. var app = angular.module('app', []);
  8.  
  9. app.controller("firstCtrl", function ($scope) {
  10. $scope.handleClick = function (msg) {
  11. $scope.$broadcast('eventName', { message: msg });
  12. };
  13. });
  14.  
  15. app.controller("secondCtrl", function ($scope) {
  16. $scope.$on('eventName', function (event, args) {
  17. $scope.message = args.message;
  18. console.log($scope.message);
  19. });
  20. });
  21.  
  22. </script>
  23. </head>
  24. <body ng-app="app">
  25. <div ng-controller="firstCtrl" style="border:2px solid #E75D5C; padding:5px;">
  26. <h1>Parent Controller</h1>
  27. <input ng-model="msg">
  28. <button ng-click="handleClick(msg);">Broadcast</button>
  29. <br /><br />
  30. <div ng-controller="secondCtrl" style="border:2px solid #428bca;padding:5px;">
  31. <h1>Child Controller</h1>
  32. <p>Broadcast Message : {{message}}</p>
  33. </div>
  34. </div>
  35. </body>
  36. </html>

How it works..

$on

It listen on events of a given type. It can catch the event dispatched by $broadcast and $emit.

Note

  1. If there is no parent-child relation between your scopes you can inject $rootScope into the controller and broadcast the event to all child scopes but you cannot emit your event.
  2. You can emit your event only when you have parent-child relation and event propagation is initiated by child. However, $emit can fire an event only for all $rootScope.$on listeners.