-2

I was wondering if someone searched "alert(1)" on my website and I want to handle this search query from being executed without putting the XSS-protection or CSP headers. (just for the test purpose)

like this = if alert -> then do something
pandaish
  • 7
  • 1
  • well your example should be `window.addEventListener('load', function () {});` – epascarello Nov 04 '22 at 18:14
  • no clue what "searching" `"alert(1)"` means. If a person is able to run JavaScript on your page through a search parameter, you have a bigger issue. Capturing it would not solve the big issue. – epascarello Nov 04 '22 at 18:14
  • Can you please elaborate "_someone searched "alert(1)"_"? How is the given example code related to this "search"? – Teemu Nov 04 '22 at 18:15
  • If you want to override alert you can make it run something. Still not sure how you think it would prevent XSS `const oAlert = window.alert; const updatedAlert = function(x) { console.log('x', x); oAlert(x); }; window.alert = updatedAlert; alert('hello');` – epascarello Nov 04 '22 at 18:30
  • Also see: OWASP [XSS Filter Evasion Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/XSS_Filter_Evasion_Cheat_Sheet.html) – Yogi Nov 04 '22 at 18:32
  • Down vote because this question is unhelpful. Proxying the alert is not an effective XSS prevention. Worse, it might even hide vulnerabilities from security scanners. – Yogi Nov 04 '22 at 19:02
  • i know but i was making a CTF(capture the flag) kind of challange and i was planning like this, 1 set csp xss'able header then whenever i detect an alert i will print the flag, that was my hole intiution – pandaish Nov 04 '22 at 20:07
  • @pandaish Whatever you're doing you should be putting minimal reproducible code, this way no one can know if you're using Bootstrap or you're doing it from 0... – str1ng Nov 04 '22 at 22:00

1 Answers1

2

This will NOT prevent XSS attacks! XSS attacks don't typically use alerts. To prevent XSS attacks, you need to sanitize all inputs.

If you still want to check for alerts for whatever reason:

You could check if the window lost focus, but that's about all you can do to detect alerts with vanilla JS.

function doAlert() {
  alert("hi!!");
}

document.body.addEventListener('focusout', (event) => {
  console.log("out");
});
<button onclick="doAlert();">alert</button>

This will only execute after the alert has been dismissed though as alerts pause JavaScript. It also detects whenever you switch tabs or open another app.

ethry
  • 731
  • 6
  • 17
  • As this user didn't pasted any of the code, minimal reprod. this should be satisfying needs... However, if anyone is using Bootstrap, you can run following code in order to check if modal is shown up (considering that most of the people look at the modals like popups): `$("element"). data('bs.modal')?. _isShown` – str1ng Nov 04 '22 at 21:58