preface

I recently read an article about the danger of the input box being attacked by injected code. I did a small example and found that there was indeed such a case.

The sample

Let’s start with a small example, a simple message function, input a message in the input box, and then insert the message into the page:

Effect of the page

The key code

<body>
	<div id="content"></div>
	<input id='input'>
	<input type="button" id='button' value="Submit">
</body>
<script>
	const btn = document.getElementById('button');
	const myInput = document.getElementById('input');
	const content = document.getElementById('content');
	btn.onclick = (a)= > {
            content.innerHTML = myInput.value
	};
</script>
Copy the code

There are several ways code injection input boxes can trigger attacks

The HTML code is injected into the input box

<script>The label is injected into the input box

Type , and then commit. You’ll notice that there are no pop-ups, and the reason there is no JavaScript program executed here is that the

Others do not pass<script>Tags to performJavaScriptThe program’s code is injected into the input box

To guard against

Since the input box is at risk of being attacked, we should take precautions. Fortunately, Vue has taken the best precautions for us. If you’re not using Vue, there are workarounds in place.

Vue defense principle

When Vue inserts elements dynamically, it will convert the < and > tags into escape characters < and > to avoid the execution of JavaScript programs. After using Vue to insert code through the input box, the code of the inserted page will be escaped as follows:

Unguarded, insert the following code into the page:

Native JavaScript defense methods

We can use the same prevention method as Vue, replacing symbols such as <, >, &, ‘and “with escape characters to avoid risks. Here we use the method written by zhangxiangliang in the article” 30 seconds a day ⏱ let’s get arrested together “to deal with it:

// Replace the symbol with an escape character by regeting the string in the input box
const escapeHTML = str= >
    str.replace(/[&<>'"]/g, tag => ({
        '&': '& '.'<': '< '.'>': '> '."'": '& # 39; '.'"': '" '
    }[tag] || tag));
Copy the code

conclusion

While there are ways to attack that can mess up pages even after console editing, it’s better not to cause problems for work or company if we have a risk-averse approach.

The resources

30 seconds per day ⏱ Let’s get arrested: juejin.cn/post/684490… MDN element.innerHTML:developer.mozilla.org/zh-CN/docs/…