Skip to content

Instantly share code, notes, and snippets.

@Pamblam
Created January 4, 2023 17:22
Show Gist options
  • Save Pamblam/58a817c552347d6ee9f3fa15ec771817 to your computer and use it in GitHub Desktop.
Save Pamblam/58a817c552347d6ee9f3fa15ec771817 to your computer and use it in GitHub Desktop.
/**
* Remove <script> tags from a string
* We cannot use regex to remove them because regex does not
* account for false closing script tags, and therefore a regex solution is exploitable.
* This loops through each char and removes script tags fully accounting for
* false closes that may occur in quotes.
*/
function stripScriptTags(str){
if(typeof str !== 'string') {
return false;
}
var opened_quote_type = null;
var in_script_tag = false;
var string_buffer = [];
for (let i = 0; i < str.length; i++) {
if(opened_quote_type === null && ["'", '"', '`'].includes(str[i])){
opened_quote_type = str[i];
}else if(opened_quote_type === str[i]){
opened_quote_type = null;
}
if(str.length > i+7 && str.toUpperCase().substring(i, i+7) === '<SCRIPT'){
i += 7;
in_script_tag = true;
}
if(in_script_tag &&
opened_quote_type === null &&
str.length > i+9 &&
str.toUpperCase().substring(i, i+9) === '</SCRIPT>'
){
i += 9;
in_script_tag = false;
}
if(!in_script_tag){
string_buffer.push(str[i]);
}
}
return string_buffer.join('');
}
function decodeHTMLEntities(str){
if(typeof str !== 'string') {
return false;
}
var element = document.createElement('div');
return str.replace(/&[^;]*;/gmi, entity=>{
if(entity.toUpperCase().includes(`<SCRIPT`)) return entity;
element.innerHTML = entity;
return element.textContent;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment