Search code examples
sparqlcode-injectionsesame

How to protect my system, which runs the Sesame triplestore, from injections when querying using SPARQL?


Title says it all. Is there something equivalent to SQL's prepared statements?


Solution

  • (assuming you are using a recent version of RDF4J, and not Sesame)

    To prevent vulnerabilities due to injection, a simple approach is to use a prepared query, and use Query#setBinding to inject actual user input values into your query. For example:

    // some input keyword to inject
    String keyword = "foobar";
    
    TupleQuery query = con.prepareTupleQuery(
           "PREFIX ex: <htt://example.org/> " 
         + "SELECT ?document WHERE { ?document ex:keyword ?keyword . }");
    
    // inject the input keyword
    query.setBinding("keyword", factory.createLiteral(keyword));
    
    // execute the query
    TupleQueryResult result = query.evaluate();
    

    For more advanced control, RDF4J also has a SparqlBuilder, a fluent API for creating SPARQL queries in Java, for this purpose. For example:

    String keyword = "foobar";
    
    Prefix ex = SparqlBuilder.prefix("ex", Rdf.iri("http://example.org/"));
    Variable document = SparqlBuilder.var("document");
    
    SelectQuery query = Queries.SELECT().prefix(ex).select(document)
            .where(GraphPatterns.tp(document, ex.iri("keyword"), Rdf.literalOf(keyword));