Input validation and representation problems ares caused by metacharacters, alternate encodings and numeric representations. Security problems result from trusting input. The issues include: "Buffer Overflows," "Cross-Site Scripting" attacks, "SQL Injection," and many others.
@ControllerAdvice
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {
public JsonpAdvice() {
super("callback");
}
}
GET /api/latest.json?callback=myCallbackFunction
, the controller method will generate a response such as:
HTTP/1.1 200 Ok
Content-Type: application/json; charset=utf-8
Date: Tue, 12 Dec 2017 16:16:04 GMT
Server: nginx/1.12.1
Content-Length: 225
Connection: Close
myCallbackFunction({<json>})
Script
tag to load the response from the JSONP endpoint, which will turn into the execution of the myCallbackFunction
function. An attacker could use a different callback name to navigate and interact with the DOM. For example opener.document.body.someElemnt.firstChild.nextElementSibling.submit
could be used to locate a form in the target page and submit it.
def myJSONPService(callback: String) = Action {
val json = getJSONToBeReturned()
Ok(Jsonp(callback, json))
}
GET /api/latest.json?callback=myCallbackFunction
, the controller method described in Example 1
will generate a response such as:
HTTP/1.1 200 Ok
Content-Type: application/json; charset=utf-8
Date: Tue, 12 Dec 2017 16:16:04 GMT
Server: nginx/1.12.1
Content-Length: 225
Connection: Close
myCallbackFunction({<json>})
Script
tag to load the response from the JSONP endpoint, which will turn into the execution of the myCallbackFunction
function. An attacker could use a different callback name to navigate and interact with the DOM. For example opener.document.body.someElemnt.firstChild.nextElementSibling.submit
could be used to locate a form in the target page and submit it.sanitizeValue
to false
allows unsanitized input to lead to vulnerabilities like Cross-Site Scripting.sanitizeValue
property determines whether to run the HTML sanitizer when the value is applied to the HTML markup. The input might come directly from the user and thus can be considered unsafe. The sanitizeValue
property can be set to false
for multiple reasons, such as allowing additional input characters. However, doing so can inadvertently allow unsafe user input to be executed in the code. It is safer to set the sanitizeValue
property to true
, which it is by default.sanitizeValue
property in the SAPUI5 RichTextEditor
to false
:
new RichTextEditor({
sanitizeValue: false,
value: input
}).placeAt("moreContent");
...
lv_uri = request->get_form_field( 'uri' ).
CALL METHOD cl_http_utility=>set_request_uri
EXPORTING
request = lo_request
uri = lv_uri.
...
http
or https
such as:
...
PageReference ref = ApexPages.currentPage();
Map<String,String> params = ref.getParameters();
HttpRequest req = new HttpRequest();
req.setEndpoint(params.get('url'));
HTTPResponse res = new Http().send(req);
http
or https
such as:
string url = Request.Form["url"];
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(url);
http
or https
like:
char *url = maliciousInput();
CURL *curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, url);
CURLcode res = curl_easy_perform(curl);
http
or https
such as:
...
final server = await HttpServer.bind('localhost', 18081);
server.listen((request) async {
final headers = request.headers;
final url = headers.value('url');
final client = IOClient();
final response = await client.get(Uri.parse(url!));
...
}
http
or https
such as:
url := request.Form.Get("url")
res, err =: http.Get(url)
...
http
or https
like:
String url = request.getParameter("url");
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response1 = httpclient.execute(httpGet);
http
or https
like:
var http = require('http');
var url = require('url');
function listener(request, response){
var request_url = url.parse(request.url, true)['query']['url'];
http.request(request_url)
...
}
...
http.createServer(listener).listen(8080);
...
http
or https
like:
val url: String = request.getParameter("url")
val httpclient: CloseableHttpClient = HttpClients.createDefault()
val httpGet = HttpGet(url)
val response1: CloseableHttpResponse = httpclient.execute(httpGet)
http
or https
like:
$url = $_GET['url'];
$c = curl_init();
curl_setopt($c, CURLOPT_POST, 0);
curl_setopt($c,CURLOPT_URL,$url);
$response=curl_exec($c);
curl_close($c);
http
or https
like:
url = request.GET['url']
handle = urllib.urlopen(url)
http
or https
like:
url = req['url']
Net::HTTP.get(url)
http
or https
like:
def getFile(url: String) = Action { request =>
...
val url = request.body.asText.getOrElse("http://google.com")
ws.url(url).get().map { response =>
Ok(s"Request sent to $url")
}
...
}
http
or https
like:Example 2: A few examples of how an attacker that has control over the
POST /checkDetails HTTP/1.1
url=https://example.com/product/1
url
parameter can tamper the request in Example 1
.
POST /checkDetails HTTP/1.1
url=https://localhost.com/admin
POST /checkDetails HTTP/1.1
url=file:///etc/passwd
http
or https
like:'eval'
callswhile(1)
into an eval function, the attacker could trigger excessive resource consumption and severely impact the application availability.'fs'
module. The following payload can enable an attacker to read arbitrary file contents.response.end(require('fs').readFileSync(filename))NoSQL injection
$where
clause using unvalidated user input can be exploited by injecting malicious javascript code to alter the query and extract information from the database or injecting a call to the sleep function and affecting the availability of the application.1';sleep(33333);var%20a='
// Set up the context data
VelocityContext context = new VelocityContext();
context.put( "name", user.name );
// Load the template
String template = getUserTemplateFromRequestBody(request);
RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
StringReader reader = new StringReader(template);
SimpleNode node = runtimeServices.parse(reader, "myTemplate");
template = new Template();
template.setRuntimeServices(runtimeServices);
template.setData(node);
template.initDocument();
// Render the template with the context data
StringWriter sw = new StringWriter();
template.merge( context, sw );
Example 1
uses Velocity
as the template engine. For that engine, an attacker could submit the following template to run arbitrary commands on the server:
$name.getClass().forName("java.lang.Runtime").getRuntime().exec(<COMMAND>)
app.get('/', function(req, res){
var template = _.template(req.params['template']);
res.write("<html><body><h2>Hello World!</h2>" + template() + "</body></html>");
});
Example 1
uses Underscore.js
as the template engine within a Node.js
application. For that engine, an attacker could submit the following template to run arbitrary commands on the server:
<% cp = process.mainModule.require('child_process');cp.exec(<COMMAND>); %>
Jinja2
template engine.
from django.http import HttpResponse
from jinja2 import Template as Jinja2_Template
from jinja2 import Environment, DictLoader, escape
def process_request(request):
# Load the template
template = request.GET['template']
t = Jinja2_Template(template)
name = source(request.GET['name'])
# Render the template with the context data
html = t.render(name=escape(name))
return HttpResponse(html)
Example 1
uses Jinja2
as the template engine. For that engine, an attacker could submit the following template to read arbitrary files from the server:Example 2: The following example shows how a template is retrieved from an HTTP request and rendered using the
template={{''.__class__.__mro__[2].__subclasses__()[40]('/etc/passwd').read()}}
Django
template engine.
from django.http import HttpResponse
from django.template import Template, Context, Engine
def process_request(request):
# Load the template
template = source(request.GET['template'])
t = Template(template)
user = {"name": "John", "secret":getToken()}
ctx = Context(locals())
html = t.render(ctx)
return HttpResponse(html)
Example 2
uses Django
as the template engine. For that engine, an attacker will not be able to execute arbitrary commands, but they will be able to access all the objects in the template context. In this example, a secret token is available in the context and could be leaked by the attacker.@SessionAttributes
will mean Spring replicates changes to model attributes in the session object. If an attacker is able to store arbitrary values within a model attribute, these changes will be replicated in the session object where they may be trusted by the application. If the session attribute is initialized with trusted data which the user should not be able to modify, the attacker may be able to conduct a Session Puzzling attack and abuse the application logic.
@Controller
@SessionAttributes("user")
public class HomeController {
...
@RequestMapping(value= "/auth", method=RequestMethod.POST)
public String authHandler(@RequestParam String username, @RequestParam String password, RedirectAttributes attributes, Model model) {
User user = userService.findByNamePassword(username, password);
if (user == null) {
// Handle error
...
} else {
// Handle success
attributes.addFlashAttribute("user", user);
return "redirect:home";
}
}
...
}
User
instance from the session since the class is annotated with @SessionAttributes("user")
and uses it to verify the reset password question.
@Controller
@SessionAttributes("user")
public class ResetPasswordController {
@RequestMapping(value = "/resetQuestion", method = RequestMethod.POST)
public String resetQuestionHandler(@RequestParam String answerReset, SessionStatus status, User user, Model model) {
if (!user.getAnswer().equals(answerReset)) {
// Handle error
...
} else {
// Handle success
...
}
}
}
user
instance from the session where it was stored during the login process. However Spring will check the request and will try to bind its data into the model user
instance. If the received request contains data that can be bound to the User
class, Spring will merge the received data into the user session attribute. This scenario can be abused by submitting both an arbitrary answer in the answerReset
query parameter and the same value to override the value stored in the session. This way, the attacker may set an arbitrary new password for random users.
...
taintedConnectionStr = request->get_form_field( 'dbconn_name' ).
TRY.
DATA(con) = cl_sql_connection=>get_connection( `R/3*` && taintedConnectionStr ).
...
con->close( ).
CATCH cx_sql_exception INTO FINAL(exc).
...
ENDTRY.
...
sethostid(argv[1]);
...
sethostid()
, unprivileged users may be able to invoke the program. The code in this example allows user input to directly control the value of a system setting. If an attacker provides a malicious value for host ID, the attacker may misidentify the affected machine on the network or cause other unintended behavior.
...
ACCEPT OPT1.
ACCEPT OPT2
COMPUTE OPTS = OPT1 + OPT2.
CALL 'MQOPEN' USING HCONN, OBJECTDESC, OPTS, HOBJ, COMPOCODE REASON.
...
...
<cfset code = SetProfileString(IniPath,
Section, "timeout", Form.newTimeout)>
...
Form.newTimeout
is used to specify a timeout, an attacker may be able to mount a denial of service (DoS) attack against the application by specifying a sufficiently large number.
...
catalog := request.Form.Get("catalog")
path := request.Form.Get("path")
os.Setenv(catalog, path)
...
HttpServletRequest
and sets it as the active catalog for a database Connection
.
...
conn.setCatalog(request.getParamter("catalog"));
...
http.IncomingMessage
request variable and uses it to set additional V8 commnd line flags.
var v8 = require('v8');
...
var flags = url.parse(request.url, true)['query']['flags'];
...
v8.setFlagsFromString(flags);
...
<?php
...
$table_name=$_GET['catalog'];
$retrieved_array = pg_copy_to($db_connection, $table_name);
...
?>
...
catalog = request.GET['catalog']
path = request.GET['path']
os.putenv(catalog, path)
...
Connection
.
def connect(catalog: String) = Action { request =>
...
conn.setCatalog(catalog)
...
}
...
sqlite3(SQLITE_CONFIG_LOG, user_controllable);
...
Request
object and sets it as the active catalog for a database Connection
.
...
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
Dim rsTables As ADODB.Recordset
Dim Catalog As New ADOX.Catalog
Set Catalog.ActiveConnection = conn
Catalog.Create Request.Form("catalog")
...
UTF-8
. The character set (charset) declaration is usually done through a header in the HTTP response or using the HTML <meta> tag. Only the application should control these declarations. If this declaration is controlled through user input, then an attacker can use this feature to modify the charset that the browser uses and modify the interpretation of the contents of the response. This can enable Cross-site Scripting attacks that would otherwise not have succeeded while using UTF-8
encoding.+ADw-script+AD4-alert(document.location)+ADw-/script+AD4
utf-7
encoding, it is interpreted as valid HTML tag and, the script is executed.
myModule.config(function($compileProvider){
$compileProvider.imgSrcSanitizationWhitelist(userInput);
});
/^(http(s)?|javascript):.*/
, the application will then allow the use of inline JavaScript within image source URLs, which may lead to cross-site scripting attacks.ProcessWorkitemRequest.setAction()
call.
void processRequest() {
String workItemId = ApexPages.currentPage().getParameters().get('Id');
String action = ApexPages.currentPage().getParameters().get('Action');
Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
req.setWorkitemId(workItemId);
req.setAction(action);
Approval.ProcessResult res = Approval.process(req);
...
}
var hash = window.location.hash;
var myStartSymbol = decodeURIComponent(hash.substring(1, hash.length));
myModule.config(function($interpolateProvider){
$interpolateProvider.startSymbol(myStartSymbol);
});
...
public String inputValue {
get { return inputValue; }
set { inputValue = value; }
}
...
String queryString = 'SELECT Id FROM Contact WHERE (IsDeleted = false AND Name like \'%' + inputValue + '%\')';
result = Database.query(queryString);
...
SELECT Id FROM Contact WHERE (IsDeleted = false AND Name like '%inputValue%')
inputValue
does not contain a single-quote character. If an attacker enters the string name') OR (Name like '%
for inputValue
, then the query becomes the following:
SELECT Id FROM Contact WHERE (IsDeleted = false AND Name like '%name') OR (Name like '%%')
name') OR (Name like '%
condition causes the where clause to use the LIKE '%%'
condition, which will force the query to output all possible ID values, since it becomes logically equivalent to the much simpler query:
SELECT Id FROM Contact WHERE ... OR (Name like '%%')
...
public String inputValue {
get { return inputValue; }
set { inputValue = value; }
}
...
String queryString = 'Name LIKE \'%' + inputValue + '%\'';
String searchString = 'Acme';
String searchQuery = 'FIND :searchString IN ALL FIELDS RETURNING Contact (Id WHERE ' + queryString + ')';
List<List<SObject>> results = Search.query(searchQuery);
...
String searchQuery = 'FIND :searchString IN ALL FIELDS RETURNING Contact (Id WHERE Name LIKE '%' + inputValue + '%')';
inputValue
does not contain a single-quote character. If an attacker enters the string 1%' OR Name LIKE '
for inputValue
, then the query becomes the following:
String searchQuery = 'FIND :searchString IN ALL FIELDS RETURNING Contact (Id WHERE Name LIKE '%1%' OR Name LIKE '%%')';
OR Name like '%%'
condition causes the where clause to use the LIKE '%%'
condition, which will force the query to output all the records that contain phrase 'map', since it becomes logically equivalent to the much simpler query:
FIND 'map*' IN ALL FIELDS RETURNING Contact (Id WHERE Name LIKE '%%')
String beans = getBeanDefinitionFromUser();
GenericApplicationContext ctx = new GenericApplicationContext();
XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
xmlReader.loadBeanDefinitions(new UrlResource(beans));
ctx.refresh();
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="true">
...
<context-param>
<param-name>defaultHtmlEscape</param-name>
<param-value>false</param-value>
</context-param>
...
</web-app>
...
v_account = request->get_form_field( 'account' ).
v_reference = request->get_form_field( 'ref_key' ).
CONCATENATE `user = '` sy-uname `'` INTO cl_where.
IF v_account IS NOT INITIAL.
CONCATENATE cl_where ` AND account = ` v_account INTO cl_where SEPARATED BY SPACE.
ENDIF.
IF v_reference IS NOT INITIAL.
CONCATENATE cl_where "AND ref_key = `" v_reference "`" INTO cl_where.
ENDIF.
SELECT *
FROM invoice_items
INTO CORRESPONDING FIELDS OF TABLE itab_items
WHERE (cl_where).
...
SELECT *
FROM invoice_items
INTO CORRESPONDING FIELDS OF TABLE itab_items
WHERE user = sy-uname
AND account = <account>
AND ref_key = <reference>.
"abc` OR MANDT NE `+"
for v_reference and string '1000' for v_account, then the query becomes the following:
SELECT *
FROM invoice_items
INTO CORRESPONDING FIELDS OF TABLE itab_items
WHERE user = sy-uname
AND account = 1000
AND ref_key = `abc` OR MANDT NE `+`.
OR MANDT NE `+`
condition causes the WHERE
clause to always evaluate to true because the client field can never be equal to literal +, so query becomes logically equivalent to the much simpler query:
SELECT * FROM invoice_items
INTO CORRESPONDING FIELDS OF TABLE itab_items.
invoice_items
table, regardless of the specified user.
PARAMETERS: p_street TYPE string,
p_city TYPE string.
Data: v_sql TYPE string,
stmt TYPE REF TO CL_SQL_STATEMENT.
v_sql = "UPDATE EMP_TABLE SET ".
"Update employee address. Build the update statement with changed details
IF street NE p_street.
CONCATENATE v_sql "STREET = `" p_street "`".
ENDIF.
IF city NE p_city.
CONCATENATE v_sql "CITY = `" p_city "`".
ENDIF.
l_upd = stmt->execute_update( v_sql ).
"ABC` SALARY = `1000000"
for the parameter p_street, the application lets the database be updated with revised salary!
...
var params:Object = LoaderInfo(this.root.loaderInfo).parameters;
var username:String = String(params["username"]);
var itemName:String = String(params["itemName"]);
var query:String = "SELECT * FROM items WHERE owner = " + username + " AND itemname = " + itemName;
stmt.sqlConnection = conn;
stmt.text = query;
stmt.execute();
...
SELECT * FROM items
WHERE owner = <userName>
AND itemname = <itemName>;
itemName
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for itemName
, then the query becomes the following:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM items;
items
table, regardless of their specified owner.Example 1
. If an attacker with the user name wiley
enters the string "name'; DELETE FROM items; --
" for itemName
, then the query becomes the following two queries:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
--'
Example 1
. If an attacker enters the string "name'); DELETE FROM items; SELECT * FROM items WHERE 'a'='a
", the following three valid statements will be created:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';
owner
matches the user name of the currently-authenticated user.
...
string userName = ctx.getAuthenticatedUserName();
string query = "SELECT * FROM items WHERE owner = '"
+ userName + "' AND itemname = '"
+ ItemName.Text + "'";
sda = new SqlDataAdapter(query, conn);
DataTable dt = new DataTable();
sda.Fill(dt);
...
SELECT * FROM items
WHERE owner = <userName>
AND itemname = <itemName>;
itemName
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for itemName
, then the query becomes the following:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM items;
items
table, regardless of their specified owner.Example 1
. If an attacker with the user name wiley
enters the string "name'); DELETE FROM items; --
" for itemName
, then the query becomes the following two queries:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
--'
Example 1
. If an attacker enters the string "name'); DELETE FROM items; SELECT * FROM items WHERE 'a'='a
", the following three valid statements will be created:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';
Example 2:Alternatively, a similar result could be obtained with SQLite using the following code:
...
ctx.getAuthUserName(&userName); {
CString query = "SELECT * FROM items WHERE owner = '"
+ userName + "' AND itemname = '"
+ request.Lookup("item") + "'";
dbms.ExecuteSQL(query);
...
...
sprintf (sql, "SELECT * FROM items WHERE owner='%s' AND itemname='%s'", username, request.Lookup("item"));
printf("SQL to execute is: \n\t\t %s\n", sql);
rc = sqlite3_exec(db,sql, NULL,0, &err);
...
SELECT * FROM items
WHERE owner = <userName>
AND itemname = <itemName>;
itemName
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for itemName
, then the query becomes the following:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM items;
items
table, regardless of their specified owner.Example 1
. If an attacker with the user name wiley
enters the string "name'); DELETE FROM items; --
" for itemName
, then the query becomes the following two queries:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
--'
Example 1
. If an attacker enters the string "name'); DELETE FROM items; SELECT * FROM items WHERE 'a'='a
", the following three valid statements will be created:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';
...
ACCEPT USER.
ACCEPT ITM.
MOVE "SELECT * FROM items WHERE owner = '" TO QUERY1.
MOVE "' AND itemname = '" TO QUERY2.
MOVE "'" TO QUERY3.
STRING
QUERY1, USER, QUERY2, ITM, QUERY3 DELIMITED BY SIZE
INTO QUERY
END-STRING.
EXEC SQL
EXECUTE IMMEDIATE :QUERY
END-EXEC.
...
SELECT * FROM items
WHERE owner = <userName>
AND itemname = <itemName>;
itemName
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for itm
, then the query becomes the following:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so query becomes logically equivalent to the much simpler query:
SELECT * FROM items;
items
table, regardless of their specified owner.Example 1
. If an attacker with the user name wiley
enters the string "name'; DELETE FROM items; --
" for itemName
, then the query becomes the following two queries:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
--'
Example 1
. If an attacker enters the string "name'); DELETE FROM items; SELECT * FROM items WHERE 'a'='a
", the following three valid statements will be created:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';
...
<cfquery name="matchingItems" datasource="cfsnippets">
SELECT * FROM items
WHERE owner='#Form.userName#'
AND itemId=#Form.ID#
</cfquery>
...
SELECT * FROM items
WHERE owner = <userName>
AND itemId = <ID>;
Form.ID
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for Form.ID
, then the query becomes the following:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemId = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM items;
items
table, regardless of their specified owner.Example 1
. If an attacker with the user name hacker
enters the string "hacker'); DELETE FROM items; --
" for Form.ID
, then the query becomes the following two queries:
SELECT * FROM items
WHERE owner = 'hacker'
AND itemId = 'name';
DELETE FROM items;
--'
Example 1
. If an attacker enters the string "name'); DELETE FROM items; SELECT * FROM items WHERE 'a'='a
", the following three valid statements will be created:
SELECT * FROM items
WHERE owner = 'hacker'
AND itemId = 'name';
DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';
...
final server = await HttpServer.bind('localhost', 18081);
server.listen((request) async {
final headers = request.headers;
final userName = headers.value('userName');
final itemName = headers.value('itemName');
final query = "SELECT * FROM items WHERE owner = '"
+ userName! + "' AND itemname = '"
+ itemName! + "'";
db.query(query);
}
...
SELECT * FROM items
WHERE owner = <userName>
AND itemname = <itemName>;
itemName
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for itemName
, then the query becomes the following:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM items;
items
table, regardless of their specified owner.Example 1
. If an attacker with the user name wiley
enters the string "name'; DELETE FROM items; --
" for itemName
, then the query becomes the following two queries:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
--'
Example 1
. If an attacker enters the string "name'); DELETE FROM items; SELECT * FROM items WHERE 'a'='a
", the following three valid statements will be created:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';
...
rawQuery := request.URL.Query()
username := rawQuery.Get("userName")
itemName := rawQuery.Get("itemName")
query := "SELECT * FROM items WHERE owner = " + username + " AND itemname = " + itemName + ";"
db.Exec(query)
...
SELECT * FROM items
WHERE owner = <userName>
AND itemname = <itemName>;
itemName
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for itemName
, then the query becomes the following:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM items;
items
table, regardless of their specified owner.Example 1
. If an attacker with the user name wiley
enters the string "name'; DELETE FROM items; --
" for itemName
, then the query becomes the following two queries:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
--'
Example 1
. If an attacker enters the string "name'; DELETE FROM items; SELECT * FROM items WHERE 'a'='a
", the following three valid statements are created:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';
...
String userName = ctx.getAuthenticatedUserName();
String itemName = request.getParameter("itemName");
String query = "SELECT * FROM items WHERE owner = '"
+ userName + "' AND itemname = '"
+ itemName + "'";
ResultSet rs = stmt.execute(query);
...
SELECT * FROM items
WHERE owner = <userName>
AND itemname = <itemName>;
itemName
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for itemName
, then the query becomes the following:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM items;
items
table, regardless of their specified owner.Example 1
. If an attacker with the user name wiley
enters the string "name'; DELETE FROM items; --
" for itemName
, then the query becomes the following two queries:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
--'
Example 1
. If an attacker enters the string "name'); DELETE FROM items; SELECT * FROM items WHERE 'a'='a
", the following three valid statements will be created:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';
Example 1
to the Android platform.
...
PasswordAuthentication pa = authenticator.getPasswordAuthentication();
String userName = pa.getUserName();
String itemName = this.getIntent().getExtras().getString("itemName");
String query = "SELECT * FROM items WHERE owner = '"
+ userName + "' AND itemname = '"
+ itemName + "'";
SQLiteDatabase db = this.openOrCreateDatabase("DB", MODE_PRIVATE, null);
Cursor c = db.rawQuery(query, null);
...
...
var username = document.form.username.value;
var itemName = document.form.itemName.value;
var query = "SELECT * FROM items WHERE owner = " + username + " AND itemname = " + itemName + ";";
db.transaction(function (tx) {
tx.executeSql(query);
}
)
...
SELECT * FROM items
WHERE owner = <userName>
AND itemname = <itemName>;
itemName
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for itemName
, then the query becomes the following:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM items;
items
table, regardless of their specified owner.Example 1
. If an attacker with the user name wiley
enters the string "name'; DELETE FROM items; --
" for itemName
, then the query becomes the following two queries:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
--'
Example 1
. If an attacker enters the string "name'); DELETE FROM items; SELECT * FROM items WHERE 'a'='a
", the following three valid statements will be created:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';
...
$userName = $_SESSION['userName'];
$itemName = $_POST['itemName'];
$query = "SELECT * FROM items WHERE owner = '$userName' AND itemname = '$itemName';";
$result = mysql_query($query);
...
SELECT * FROM items
WHERE owner = <userName>
AND itemname = <itemName>;
itemName
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for itemName
, then the query becomes the following:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM items;
items
table, regardless of their specified owner.Example 1
. If an attacker with the user name wiley
enters the string "name'; DELETE FROM items; --
" for itemName
, then the query becomes the following two queries:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
--'
Example 1
. If an attacker enters the string "name'); DELETE FROM items; SELECT * FROM items WHERE 'a'='a
", the following three valid statements will be created:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';
procedure get_item (
itm_cv IN OUT ItmCurTyp,
usr in varchar2,
itm in varchar2)
is
open itm_cv for ' SELECT * FROM items WHERE ' ||
'owner = '''|| usr || '''' ||
' AND itemname = ''' || itm || '''';
end get_item;
SELECT * FROM items
WHERE owner = <userName>
AND itemname = <itemName>;
itemName
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for itm
, then the query becomes the following:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so query becomes logically equivalent to the much simpler query:
SELECT * FROM items;
items
table, regardless of their specified owner.Example 1
. If an attacker with the user name wiley
enters the string "name'; DELETE FROM items; --
" for itemName
, then the query becomes the following two queries:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
--'
Example 1
. If an attacker enters the string "name'); DELETE FROM items; SELECT * FROM items WHERE 'a'='a
", the following three valid statements will be created:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';
- Target fields that are not quoted
- Find ways to bypass the need for certain escaped metacharacters
- Use stored procedures to hide the injected metacharacters
...
userName = req.field('userName')
itemName = req.field('itemName')
query = "SELECT * FROM items WHERE owner = ' " + userName +" ' AND itemname = ' " + itemName +"';"
cursor.execute(query)
result = cursor.fetchall()
...
SELECT * FROM items
WHERE owner = <userName>
AND itemname = <itemName>;
itemName
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for itemName
, then the query becomes the following:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM items;
items
table, regardless of their specified owner.Example 1
. If an attacker with the user name wiley
enters the string "name'; DELETE FROM items; --
" for itemName
, then the query becomes the following two queries:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
--'
Example 1
. If an attacker enters the string "name'); DELETE FROM items; SELECT * FROM items WHERE 'a'='a
", the following three valid statements will be created:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';
...
userName = getAuthenticatedUserName()
itemName = params[:itemName]
sqlQuery = "SELECT * FROM items WHERE owner = '#{userName}' AND itemname = '#{itemName}'"
rs = conn.query(sqlQuery)
...
SELECT * FROM items
WHERE owner = <userName>
AND itemname = <itemName>;
itemName
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for itemName
, then the query becomes the following:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM items;
items
table, regardless of their specified owner.
...
id = params[:id]
itemName = Mysql.escape_string(params[:itemName])
sqlQuery = "SELECT * FROM items WHERE id = #{userName} AND itemname = '#{itemName}'"
rs = conn.query(sqlQuery)
...
SELECT * FROM items WHERE id=<id> AND itemname = <itemName>;
itemName
and seemingly prevented the SQL injection vulnerability. However as Ruby is not a statically typed language, even though we are expecting id
to be an integer of some variety, as this is assigned from user input it won't necessarily be a number. If an attacker can instead change the value of id
to 1 OR id!=1--
, since there is no check that id
is in fact numeric, the SQL query now becomes:
SELECT * FROM items WHERE id=1 OR id!=1-- AND itemname = 'anyValue';
SELECT * FROM items WHERE id=1 OR id!=1;
id
is equal to 1 or not, which of course equates to everything within the table.
def doSQLQuery(value:String) = Action.async { implicit request =>
val result: Future[Seq[User]] = db.run {
sql"select * from users where name = '#$value'".as[User]
}
...
}
SELECT * FROM users
WHERE name = <userName>
userName
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for userName
, then the query becomes the following:
SELECT * FROM users
WHERE name = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM users;
users
table, regardless of their specified user.owner
matches the user name of the currently-authenticated user.
...
let queryStatementString = "SELECT * FROM items WHERE owner='\(username)' AND itemname='\(item)'"
var queryStatement: OpaquePointer? = nil
if sqlite3_prepare_v2(db, queryStatementString, -1, &queryStatement, nil) == SQLITE_OK {
if sqlite3_step(queryStatement) == SQLITE_ROW {
...
}
}
...
SELECT * FROM items
WHERE owner = '<userName>'
AND itemname = '<itemName>'
itemName
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for itemName
, then the query becomes the following:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM items;
items
table, regardless of their specified owner.Example 1
. If an attacker with the user name wiley
enters the string "name'); DELETE FROM items; --
" for itemName
, then the query becomes the following two queries:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
--'
Example 1
. If an attacker enters the string "name'); DELETE FROM items; SELECT * FROM items WHERE 'a'='a
", the following three valid statements will be created:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';
...
username = Session("username")
itemName = Request.Form("itemName")
strSQL = "SELECT * FROM items WHERE owner = '"& userName &"' AND itemname = '" & itemName &"'"
objRecordSet.Open strSQL, strConnect, adOpenDynamic, adLockOptimistic, adCmdText
...
SELECT * FROM items
WHERE owner = <userName>
AND itemname = <itemName>;
itemName
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for itemName
, then the query becomes the following:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM items;
items
table, regardless of their specified owner.Example 1
. If an attacker with the user name wiley
enters the string "name'; DELETE FROM items; --
" for itemName
, then the query becomes the following two queries:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
--'
Example 1
. If an attacker enters the string "name'); DELETE FROM items; SELECT * FROM items WHERE 'a'='a
", the following three valid statements will be created:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';
owner
matches the user name of the currently-authenticated user.
...
string userName = ctx.getAuthenticatedUserName();
string queryString = "SELECT * FROM items WHERE owner = '"
+ userName + "' AND itemname = '"
+ ItemName.Text + "'";
SimpleQuery<Item> queryObject = new SimpleQuery(queryString);
Item[] items = (Item[])queryObject.Execute(query);
...
SELECT * FROM items
WHERE owner = <userName>
AND itemname = <itemName>;
itemName
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for itemName
, then the query becomes the following:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM items;
items
table, regardless of their specified owner.
...
String userName = ctx.getAuthenticatedUserName();
String itemName = request.getParameter("itemName");
String query = "FROM items WHERE owner = '"
+ userName + "' AND itemname = '"
+ itemName + "'";
List items = sess.createQuery(query).list();
...
SELECT * FROM items
WHERE owner = <userName>
AND itemname = <itemName>;
itemName
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for itemName
, then the query becomes the following:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM items;
items
table, regardless of their specified owner.Example 1
. If an attacker with the user name wiley
enters the string "name'; DELETE FROM items; --
" for itemName
, then the query becomes the following two queries:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
--'
Example 1
. If an attacker enters the string "name'); DELETE FROM items; SELECT * FROM items WHERE 'a'='a
", the following three valid statements will be created:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';
#
characters, as follows:
<select id="getItems" parameterClass="MyClass" resultClass="items">
SELECT * FROM items WHERE owner = #userName#
</select>
#
characters around the variable name indicate that iBatis will create a parameterized query with the userName
variable. However, iBatis also allows you to concatenate variables directly to SQL statements using $
characters, opening the door for SQL injection.
<select id="getItems" parameterClass="MyClass" resultClass="items">
SELECT * FROM items WHERE owner = #userName# AND itemname = '$itemName$'
</select>
itemName
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for itemName
, then the query becomes the following:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM items;
items
table, regardless of their specified owner.Example 1
. If an attacker with the user name wiley
enters the string "name'; DELETE FROM items; --
" for itemName
, then the query becomes the following two queries:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
--'
Example 1
. If an attacker enters the string "name'); DELETE FROM items; SELECT * FROM items WHERE 'a'='a
", the following three valid statements will be created:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';
...
String userName = ctx.getAuthenticatedUserName();
String itemName = request.getParameter("itemName");
String sql = "SELECT * FROM items WHERE owner = '"
+ userName + "' AND itemname = '"
+ itemName + "'";
Query query = pm.newQuery(Query.SQL, sql);
query.setClass(Person.class);
List people = (List)query.execute();
...
SELECT * FROM items
WHERE owner = <userName>
AND itemname = <itemName>;
itemName
does not contain a single-quote character. If an attacker with the user name wiley
enters the string "name' OR 'a'='a
" for itemName
, then the query becomes the following:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name' OR 'a'='a';
OR 'a'='a'
condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM items;
items
table, regardless of their specified owner.Example 1
. If an attacker with the user name wiley
enters the string "name'; DELETE FROM items; --
" for itemName
, then the query becomes the following two queries:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
--'
Example 1
. If an attacker enters the string "name'); DELETE FROM items; SELECT * FROM items WHERE 'a'='a
", the following three valid statements will be created:
SELECT * FROM items
WHERE owner = 'wiley'
AND itemname = 'name';
DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';