Sanitizing Output
hasky created web application which like data management. it take data from user and save to database and show to user or we can say user write data using browser and in node or any backend Technology save that data in Database and when user want that data then user can see that data in browser.
but if user is malicious and that user enter some malicious thing like enter javascript or HTML then what happened it cause XSS (cross side scripting)or HTML Injection. for XSS we talk in incoming time. HTML injection is like you are injecting HTML tag. more about HTML injection.
You can modify and escape your data before saving to the database, or in between by retrieving and outputting it to the browser. This depends on how your data is edited and used. For example, if the user is editing the data later, it makes more sense to save as-is and sanitize upon output.
Suppose a user submits the following JavaScript snippet to your application, which then saves it for outputting later:
<script>alert('I am not sanitized!');</script>
If you don’t sanitize this code before echoing it to the browser, the malicious JavaScript will run as if you wrote it yourself. In this case, it’s a harmless alert()
, but a hacker won’t be nearly as kind.
You may choose to handle this yourself. The html-escape library provides a function that will be your best friend when displaying data. Simply call the escape()
method on your data to replace it with properly escaped HTML:
we use here html-escaping because we are rendering to html code. if we need to render in javascript then we need to use javascript escaping this is semilar to html escaping you can see in MDN doc for javascript escaping. also xml escaping is useful when dealing with xml data , MDN doc for xml escaping.
Don’t forget to sanitize the output of any command-line script you are running. A great library for this is shell-escape
.
This is used the same way as html-escape
. Use the shellescape()
function to escape any commands you are calling. This prevents arbitrary commands from being executed on the command-line. shellescape()
wraps arguments. This ensures that they are escaped correctly and don’t open your application up to structural manipulation of the commands.
Try running the output in the terminal. You will get the expected escaped output.
Continue to Secure Authentication Development Method ..