Here we have a name i.e Cross-site scripting or XSS
Cross-site scripting is a type of security vulnerability that can be found in some web applications.
XSS attacks enable attackers to insert client-side scripts into web pages viewed by other users.
A cross-site scripting vulnerability may be used by attackers to get access controls and get information like username, password or any important Files.
Lets see How attacker inject script from client side or from other platform through API.
<script>/*+anycode*/</script>
<img src=1 onerror='/* anycode */'>
Types of XSS attack
Reflected XSS:- In this the malicious script comes from the current HTTP request.
Stored XSS:- In this the malicious script comes from the website's database.
DOM-based XSS:- In this the vulnerability exists in client-side code rather than server-side code.
Reflected XSS
Lets see how can we check any input has malicious script in API > Controller > method
UserInput is pass through if Condition and this data sent to check whether the data provided by user is malicious .If yes it return with error.
If data provided by user is not malicious it will be processed and inserted to database.
CheckScript checkScript = new CheckScript();
if (!checkScript.IsScript(UserInput))
{
return "Invalid Text!!";
}
CheckScript.cs is my class
public class CheckScript
{
public bool IsScript(string data)
{
if (string.IsNullOrEmpty(data))
return true;
var pattren = new StringBuilder();
//Checks any js events i.e. onKeyUp(), onBlur(), alerts and custom js functions etc.
pattren.Append(@"((alert|on\w+|function\s+\w+)\s*\(\s*(['+\d\w](,?\s*['+\d\w]*)*)*\s*\))");
//Checks any html tags i.e. <script, <embed, <object etc.
pattren.Append(@"|(<(script|iframe|embed|frame|frameset|object|img|applet|body|html|style|layer|link|ilayer|meta|bgsound))");
return !Regex.IsMatch(System.Web.HttpUtility.UrlDecode(data), pattren.ToString(), RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
}
We can also validate input from Client Side to protect malicious attack. Even two or three special characters are responsible for malicious attach ie. <,>,/$ etc
This must be restricted to be input from client side
Basic Rules to Prevent XSS attack
1. Filter input on arrival.
Filteration of data is most important step to be work on for prevention of xss attack.
2. Encode data on output.
Data must be in Encoded State so that attacher cann't guess the actual output condition.
Note:-Don't use Base64 for encoding
3. Use appropriate response headers.
Don't use HTML ,JvaScript in HTTP response.must use
Content-Type and X-Content-Type-Options 4. Content Security Policy.
We must use Content Security Policy (CSP)