Can i preventing XSS attack by MySQL REPLACE function? Is this safe and acceptable method?
INSERT INTO persons(Name, Surname) VALUES(REPLACE('<script>alert("Test")</script>', '<script>', ''), 'Sample Value');
Information Security Stack Exchange is a question and answer site for information security professionals. It only takes a minute to sign up.Sign up to join this community
This is a really cack-handed way to attempt protect your application. Never try to transform input like this; it is a very long way from being effective in its objective, it is not maintainable/extensible, it will end up trashing your data.
The golden rule is to validate input and escape output
Check content against a set of rules, reject it and flag a problem for non-compliant data. Whenever data moves from one domain to another (e.g. from PHP or python or PERL to mysql, or from your program to an html stream) then make sure that the representation of the data isolates it from the construct it is being injected into.
There are good libraries for escaping output for a variety of languages and a variety of targets (including SQL and HTML). Start by learning how to use them effectively.
No, you can't, and you shouldn't.
A simple POC to bypass your filter would be:
<img src=x onerror=alert(1)>
There are many more tags and attributes which can lead to XSS. Additionally, you should also be worried about HTML and CSS injection.
If you want an additional filter when retrieving input - which should never be your only line of defense, but which is recommended as defense in depth - you need to adapt it to each input field. Names are difficult, so I wouldn't filter them, but when you know that you only expect eg alphanum, you could filter for that. You could also use some library like HTMLPurifier. But again, I would only recommend it as defense in depth or if you really need some HTML Tags which are parsed (which isn't the case for names; names may contain characters like
' or even
<, but they certainly shouldn't be parsed as HTML by the browser).
This won't prevent reflected XSS. This is not filtering all possible scripts.
In short, this won't prevent XSS.