Introduction to the Security Toolkit in Dojo

Source: Internet
Author: User
Tags ibm developerworks

Security work has always been a concern in our daily development. For Web development, JavaScript security is a major concern. JavaScript is a scripting language that can run in a variety of browsers, but based on security considerations, almost all browsers provide JavaScript interfaces with limited, especially some security-sensitive interfaces, such as file read/write operations and memory control.
 
In this case, it seems that JavaScript writing is very safe, but it is not. Even in such a restricted environment, there are many vulnerabilities that can be drilled. For example, when your website introduces an Internet JavaScript, it is easy to cause variable conflicts (especially global variables), DOM operations, and so on. If we do not impose some restrictions on this JavaScript, it is difficult to ensure that our website will not be disturbed by some external factors, or even crash is not impossible. The Dojo Security Toolkit provides a set of interface APIs dedicated to solving such a type of security issues. Based on this set of security interfaces, we no longer need to add additional security control code. This article focuses on the functions and usage of the Dojo Security Toolkit.
 
Introduction to the Dojo Secure toolkit
 
When our applications need to work with some external scripts or data, we should inevitably add some additional verification or detection code to ensure the security of our own code and data. In many cases, we may not necessarily consider all possible situations, so our applications may have more or less security risks. Therefore, the Dojo Secure toolkit came into being. The Secure toolkit of Dojo mainly includes some security-related tools that are frequently used in daily use. It encapsulates many security-related APIs. We only need to call them to complete our security detection.
 
Capability Interface
The Capability interface in the Secure toolkit of Dojo is mainly used to verify the validity of the JavaScript script, so as to ensure that the script does not access or modify objects or data beyond its permissions before it is executed. It is easy to use:
 
Dojox. secure. capability. validate (script, safecils, {document: 1, element: 1 })
 
Var safecils = ["isNaN", "isFinite", "parseInt", "parseFloat", "escape", "unescape ",
"EncodeURI", "encodeURIComponent", "decodeURI", "decodeURIComponent ",
"Alert", "confirm", "prompt ",
"Error", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError ",
"Date", "RegExp", "Number", "Object", "Array", "String", "Math ",
"SetTimeout", "setInterval", "clearTimeout", "clearInterval ",
"Dojo", "get", "set", "forEach", "load", "evaluate"
];
Here we mainly use the "validate" method of the "dojox. secure. capability" object. The first parameter is the script string to be executed,
The second parameter "safecils" indicates a security function or object that is allowed. It is defined in the following code, such as "isNaN", "escape", and "confirm ", "setTimeout" is considered safe, while "parent", "_ parent _", "_ proto _", "", "caller" does not exist here. They all have great security risks, that is, they are not recommended. If a method other than "safecils" is called in your JavaScript script, it is detected as illegal.
The third parameter defines the allowed global variables. Here, "document" and "element" are allowed, and others are invalid.
Therefore, when we introduce external third-party JavaScript scripts, we can verify them to ensure security before executing them.
Of course, it also has some general inspection rules:
 
We recommend that you use var to define a method.
We do not recommend that you separate the declarations and values of multiple variables with commas.
These rules are used as the Security Detection factor of Dojo to ensure that the external third-party JavaScript script code we introduce will not affect our applications.
 
DOM APIs
Next, let's take a look at the DOM-related security interfaces. The Secure toolkit of Dojo provides some objects that can help us automatically detect invalid statements in our DOM operations and throw corresponding exceptions. Based on these interfaces and objects, we can safely develop DOM structures and throw the detection work to Dojo. All we have to do is add our own exception handling code.
 
Var div = document. createElement ("div ");
Document. body. appendChild (div );
Div. innerHTML = "Sandboxed div :";
Div. style. position = "absolute ";
Div. style. top = "100px ";
Div. style. left = "100px ";
Div. style. backgroundColor = "red ";
Div. style. color = "white ";
Var container = document. createElement ("div ");
Container. style. backgroundColor = "cyan ";
Container. style. color = "black ";
Div. appendChild (container );
 
 
Wrap = dojox. secure. DOM (container );
SecuredElement = wrap (container );
Console. log ("securedElement", securedElement );
SecuredDoc = securedElement. ownerDocument;
Console. log ("securedDoc", securedDoc );
Here we constructed a simple DOM structure and wrapped it into a "safe" DOM tree: "dojox. secure. DOM (container) ". At this time, we can use the" securedDoc "object to perform the following operations (note that its value is" securedElement. ownerDocument ").
Let's look at several valid examples:
 
SecuredElement. innerHTML = "Hi there ";
T. assertEqual ("Hi there", securedElement. data _. innerHTML );
 
 
SecuredDoc. write ("<div style = 'color: red'> written </div> ");
SecuredDoc. close ();
T. t (securedElement. data _. innerHTML. match (/written /));
 
 
Var newDiv = securedDoc. createElement ("div ");
NewDiv. innerHTML = "inner div ";
NewDiv. style. color = "blue ";
SecuredElement. appendChild (newDiv );
T. t (securedElement. data _. innerHTML. match (/inner /));
 
 
SecuredElement. addEventListener ("click", function (event ){
Alert ('per click handler ');
});
Some valid operations are listed here, such as "innerHTML", "write", new DIV, and associated events. The operation method is the same as the normal DOM operation. However, once there are some insecure operations or data, an exception will be thrown. Let's look at several unsafe examples to understand:
 
T. f (securedElement. parentNode );
"ParentNode" is not allowed in safe DOM operations because it may damage upper-level nodes, and its upper-level nodes may not be within its permitted range.
There are also insecure operations on the "script" tag:
 
Try {
SecuredElement. innerHTML = "<script> bad = true </script> ";
} Catch (e ){}
T. t (typeof bad = 'undefined ');
 
 
Try {
SecuredElement. innerHTML = '</script> <script> bad = true ;//';
} Catch (e ){}
T. t (typeof bad = 'undefined ');
 
 
Try {
SecuredDoc. write ("<script> bad = true; </script> ");
} Catch (e ){}
T. t (typeof bad = 'undefined ');
 
 
Try {
Var script = securedDoc. createElement ('script ');
Script. appendChild (securedDoc. createTextNode (
'Bad = true '));
SecuredElement. appendChild (script );
}
Catch (e ){}
T. t (typeof bad = 'undefined ');
The script "bad = true" does not have "var", which is an insecure global variable.
The Script tag is not safe to write.
The "write" method cannot escape security detection.
It is not feasible to construct nodes.
For CSS, the Dojo Secure package also performs security detection:
 
If (dojo. isIE ){
SecuredElement. innerHTML =
'<Div id = "oDiv" style = "left: expression (bad = true), 0)"> Example DIV </div> ';
T. t (typeof bad = 'undefined ');
} Else {
Try {
SecuredElement. innerHTML = '<input style = \'-moz-binding: url (
"Http://www.mozilla.org/xbl/htmlBindings.xml#checkbox"); \ '> ';
} Catch (e ){}
T. f (securedElement. innerHTML. match (/mozilla /))
}
 
If (dojo. isIE ){
SecuredElement. style. left = 'Expression (alert ("hello"), 0 )';
T. f (securedElement. style. left. match (/alert /));
} Else {
Try {
SecuredElement. style. constraint binding =
'Url ("http://www.mozilla.org/xbl/htmlBindings.xml#checkbox ")';
} Catch (e ){}
}
 
If (dojo. isIE ){
SecuredElement. style. behavior = 'url (a1.htc )';
T. f (securedElement. style. behavior );
}
Dojo considers that the node CSS style contains the following operators as insecure: "behavior: | content: | javascript: | binding | expression | @ import ". This is also reasonable, because the CSS operator here will affect the entire page. Because the example in Listing 6 contains "expression", "binding", and "behavior", they all throw an exception.
Next, let's take a look at its event binding Security Detection:
 
SecuredElement. innerHTML = "<a href = 'javascript: alert (3) '> illegal link </a> ";
 
 
Try {
SecuredElement. innerHTML = "<div onclick = 'alert (4) '> illegal link </div> ";
} Catch (e ){}
T. f (securedElement. innerHTML. match (/alert /));
The above two methods have security risks, and Dojo will determine it as an insecure script and throw an exception.
Finally, Dojo intercepts irregular HTML:
 
Try {
SecuredElement. innerHTML = '<div x = "\">
"> </div> ';
} Catch (e ){}
T. f (securedElement. innerHTML. match (/alert /));
 
 
Try {
SecuredElement. innerHTML = '<iframe/src = "javascript: alert (42)"> </iframe> ';
} Catch (e ){}
T. f (securedElement. innerHTML. match (/alert /));
 
 
Try {
SecuredElement. innerHTML = '<iframe/"onload = alert (/XSS/)> </iframe> ';
} Catch (e ){}
T. f (securedElement. innerHTML. match (/alert /));
The three examples here are obviously non-standard HTML. In these cases, Dojo will throw an exception. Some people may think that the error tolerance mechanism of HTML can be used to "translate" it into the correct HTML, but this method will often cause "Translation" errors, in addition, some special tags may cause greater security risks.
 
JSON-related
JSON data processing in JavaScript is also an important part of Web development. Therefore, the security of JSON data processing is also important. The Dojo Secure toolkit provides interfaces for securely processing JSON data:
 
Var I, mediumDataSet = [];
For (I = 0; I <20; I ++ ){
MediumDataSet. push ({
Prop1: null,
Prop2: true,
Prop3: false,
Prop4: 3.4325222223332266-I,
Prop5: 10003 + I,
Prop6: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean semper ",
Prop7: "sagittis velit. Cras in mi. Duis porta mauris ut ligula. Proin porta rutrum ",
Prop8: "lacus. Etiam consequat scelerisque quam. Nulla facilisi. Maecenas luctus ",
Prop9: "venenatis nulla. In sit amet dui non mi semper iaculis. Sed molestie ",
Prop10 :"
Tortor at ipsum. Morbi dictum rutrum magna. Sed vitae risus. "+" Aliquam vitae enim ."
});
}
Var mediumJson = dojo. toJson (mediumDataSet );
 
 
// Secure JSON Processing
Dojox. secure. fromJson (mediumJson );
 
 
// Insecure JSON processing www.2cto.com
Dojo. fromJson (mediumJson );
Here we construct a JSON data and provide two JSON Data Processing Methods: "dojox. secure. fromJson" and "dojo. fromJson". Why is the former secure? The answer is simple: "dojo. fromJson" directly calls "eval" to parse JSON data. "dojox. secure. fromJson" is parsed through Character Analysis. Everyone knows that "eval" is insecure and inefficient. Imagine if we do not know whether the obtained data strictly complies with the JSON format, and if it is a string of JavaScript script code, what are the consequences of calling "eval" without thinking about it? Therefore, we strongly recommend that you use "dojox. secure. fromJson ".
 
SandBox
Finally, let's take a look at SandBox (SandBox), which is a mode that can safely run external objects, especially cross-origin pages, JSON, and JavaScript scripts. Dojo's Secure provides this interface, similar to "eval". The difference is that it ensures that the code to be executed will not cause any security issues to your existing applications.
 
Var div = document. createElement ("div ");
Document. body. appendChild (div );
Div. innerHTML = "Sandboxed div :";
Div. style. position = "absolute ";
Div. style. top = "100px ";
Div. style. left = "100px ";
Div. style. backgroundColor = "red ";
Div. style. color = "white ";
Container = document. createElement ("div ");
Container. style. backgroundColor = "cyan ";
Container. style. color = "black ";
Div. appendChild (container );
 
 
// Security
Dojox. secure. evaluate ("element. innerHTML = 'Hi there';", container );
T. assertEqual ("Hi there", container. innerHTML );
 
 
Dojox. secure. evaluate ("
Document. write (\ "<div style = 'color: red'> written </div> \"); ", container );
T. t (container. innerHTML. match (/written /));
 
 
// Insecure
T. f (dojox. secure. evaluate ("document. body", container ));
 
 
Try {
Dojox. secure. evaluate ("bad = true", container );
} Catch (e ){}
T. t (typeof bad = 'undefined ');
Here we construct a DOM structure on the page and execute the corresponding code respectively. Note: Here, security restrictions are imposed according to the sandbox mode: any code you execute is "isolated", that is, you cannot affect any node or script other than "container. Based on these restrictions, the "element. innerHTML "and" document. write "is safe, and" document. both body and bad = true (global variables) are insecure because they may affect things other than container.
Let's take a look at how to execute code across domains to ensure security:
 
Var sandbox = dojox. secure. sandbox (document. getElementById ("sandbox "));
 
 
// Local Mode
Try {
Sandbox. evaluate (input );
} Catch (e ){
Alert (e. message | e );
}
 
// Cross-origin Mode
Var input = document. getElementById ("jsFile"). value;
Sandbox. loadJS (input). addErrback (function (result ){
Alert (result );
});
 
Var input = document. getElementById ("htmlFile"). value;
Sandbox. loadHTML (input). addErrback (function (result ){
Alert (result );
});
As listed above, the local interface is simple: "sandbox. evaluate", which is similar to the previous basic interface. The cross-origin mode is based on the asynchronous mode. Here you only need to add the Exception Handling Code through "addErrback. Note: Here, "loadJS" and "loadHTML" are used to execute JavaScript and HTML code respectively. Their input values should be a URL, for example, "Callback" or "Callback ".
 
Conclusion
This article introduces some features of the Security Toolkit in Dojo, explains various excuses for the Security Toolkit of Dojo, and why we need these interfaces. First, we introduced the Capability interface, that is, how to check the security of our code. Then, it expands to DOM and JSON-related interfaces, that is, which operation is safe. Finally, the SandBox interface is used to introduce how to safely execute related code through the Dojo interface in both local and cross-domain situations. This article mainly describes the usage of these interfaces based on actual code examples, which is concise and intuitive. It is recommended that you provide more reference in daily development.
 
 
This article is first published on IBM Developerworks: http://www.ibm.com/developerworks/cn/web/1204_zhouxiang_dojosecure/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.