Email: info@zenconix.com

Write Secure Javascript for Project.

Published on: 06/14/14 6:12 AM

Category:Javascript

Best Practices to Write Secure Javasctript Code.

javascript_logo

XSS

In order to evaluate the code for Cross-Site Scripting, usage of keywords outlined at https://www.owasp.org/index.php/JavaScript/Web_2.0_Keywords_and_Pointers so one need to avoid use of keywords given in above link

Some general Keywords which onc uses in coding

Keyword Security Concern

document.body

These elements help creating the dynamic content and may result in unsafe code. Complete file contents need to be checked to validate and make sure about security considerations. 

document.createElement

eval(

It may execute arbitrary code in the context of the page and hence can be gate for cross site scripting. If the code under eval is using user input then it must be redesigned as it pose a security risk.

location.href

Location of new URL provided by the user is vulnerable to security breach.

window.attachEvent

It can allow mouse events to be tracked even on minimized window. This has been reported on Internet Explorer and compromise even virtual keyboards. Please check the link

http://www.spider.io/blog/2012/12/internet-explorer-data-leakage/

window.location

Any intrusion that changes the window.location value in the website database can result in end user browsing a malicious site 

General Guidlines

1) It is expected that a var will be declared only once, and that it will be declared before it is used.

2) Events should not handled before defined.

3) Variables should not defined after being used.

4) Try to avoid Unused parameters and variables are found in the code.

5) Do not use Un-Escaped character sequence.

6) Do not use Un-Expected tokens  in the code.

Always use JSLint to varify your JavaScript File

JSLint is a JavaScript program that looks for problems in JavaScript programs. It does not prove that your program is correct. It just provides another set of eyes to help spot problems. For details refer: http://www.jslint.com/lint.html

General Errors in JSLint Scanning

Missing ‘use strict’ statement.

Solution –  Insert keyword ‘use strict’ before defining variables in javascript. The purpose of “use strict” is to indicate that the code should be executed in “strict mode”.

For more details visit here.

‘$’ was used before it was defined.

If using jquery in javascript file then it will show above error, because JSLint dont understand Jquery.

Solution – Write following line of code in start of your Javascript file

/*jslint browser: true*/

/*global $, jQuery */

Expected ‘;’ and instead saw ‘$’.

Solution– Function should be end with ‘;’
Ex
function someFunction() {
//some code
};

 Expected ‘===’ and instead saw ‘==’.

Solution– Try to use strict equal operator wheneven needed. If dont want to use strict equel operator then write following code snippet at the start of your Javascript code

/*jslint eqeq: true */

use knockout and any other js library

If want to use Knockout or any other library in the file, JSLint will show error. So need to define that libraries globaly.
Solution- Add following line of code at the start of Javascript file
/*jslint browser: true*/
/*global $, jQuery, alert, Swiper, ko*/
where ko and Swiper are js libraries which usign in the file

‘localStorage’ was used before it was defined.

If you are using LocalStorage to store and retrive data then it will show above error

solution – To resolve this error write following code at the start of javascript file. 
/*global localStorage: false, console: false, $: false */

Unexpected (

Dont use ‘(‘ when ever not needed

Ex– return(emi);
Solution-  return emi;

Unexpected use of typeof

typeof should be use without brackets ‘()’

Ex– typeof(someValue); // wrong method
Solution-  typeof someValue;

Unnecessary ‘else’ after disruption.

If using if- else loop, and returning some value in else loop then above error will be occure.

Ex-
     if( someCondition){
 //some code
        } else {
return 0;
       }

Solution – 

    if(someCondition){
       // somecode —
     }

return 0; 

Only one space should be there after } and else

 Ex-
 if( someCondition){
//Some code here
}
else{
return 0;
}
Solution-
 if( someCondition){
//Some code here
} else {
//Some code here
}

missing radix parameter

Ex- 

imageIndex = parseInt(id.substring(id.length -1))-1;

Solution

It always a good practice to pass radix with parseInt –

parseInt(string, radix)

For decimal –

parseInt(id.substring(id.length -1),10)

If the radix parameter is omitted, JavaScript assumes the following:

 

  • If the string begins with “0x”, the radix is 16 (hexadecimal)
  • If the string begins with “0”, the radix is 8 (octal). This feature is deprecated
  • If the string begins with any other value, the radix is 10 (decimal)

Always should have ; after ending a line

Always should have ; after ending of ko function.

Don’t declare variables in a loop.

 


Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Gets a username from SharePoint’s User profile service

Here is script of “How to get username from user id from Active directory”   [code language=”css”] // get user name from id function getUserFromId(userid) { // var userid = _spPageContextInfo.userId; var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")"; var requestHeaders = { "accept": "application/json;odata=verbose" }; $.ajax({ url: requestUri, async: false, contentType: "application/json;odata=verbose", […]

Get the User ID of Active Directory name in SharePoint by Javascript

How to get User Id from Site User if you have User’s active directory name [code language=”css”] //Get the id of user from AD name. function getADNameId(adName) { var UserData; $.ajax({ url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/SiteUsers?$Select=Id,Title&$filter=Title eq ‘" + adName + "’", type: "GET", async: false, headers: { "accept": "application/json;odata=verbose", "content-type": "application/json;odata=verbose" }, success: function (data) { […]

Get selected element Id from Task List

“Very BAD practices !!!”  Sometimes situation comes that you don’t have any other options but you have to work on it and get work done. If this situation comes then you are just searching for any possible solution (many times you know that it is wrong approch to do so…).  I have come across the situation, […]