问题
I am developing a RESTful API in scala that sends SPARQL-queries to a triplestore. I read an article about the threat of SPARQL-injections when user defined params (URL params in a HTTP get request) are directly put in the SPARQL (e.g. in a fulltext search).
I saw some Jena specific solutions (using its Java API) that are not useful for me.
Is there some kind of standard regex search and replace pattern to escape malicious characters in a string that should be integrated in a SPARQL-query?
回答1:
If the user input goes into a string literal within the query:
- Use the triple-quote form:
"""..."""
or'''...'''
- Prepend any backslash, single quote or double quote in the user input with a backslash
ES6 example:
const escapeForTurtle: s => s.replace(/(["'\\])/g, '\\$1')
const query = `SELECT * { ?x :name """${escapeForTurtle(name)}""" }`
This is enough to prevent injection and syntax errors from unusual user input.
Depending on the triple store, some extra work might be required if you want to make sure that absolutely every possible user input arrives in the store without any lost characters or extra backslashes. The input \\u0022
is a good test case. If that goes through without modification, you should be safe and done.
来源:https://stackoverflow.com/questions/29601839/standard-regex-to-prevent-sparql-injection