I am working on a .NET project that uses CAML queries to retrieve data from a sharepoint. These CAML queries are generated at run time as following: string query = "<Field Name='ID'>" + userinput + </Field>
. I have a feeling that generating queries like this makes them vulnerable for injection attacks.
For SQL queries it is possible to use prepared statements to prevent this. Do prepared statements, or other methods to prevent code injection, exist for CAML queries?
After spending more time trying to find an answer, I could not find anything about prepared statements, but I think a similar effect can be achieved as following:
XmlDocument doc = new XmlDocument();
doc.Load(filepath);
doc.innerXml = doc.InnerXml.replace("@firstParam", XmlEncode(userinput));
First the existing CAML query is parsed, and only after parsing the user input is added. This should prevent user input from being interpreted as legitimate XML. To be completely safe, the user input can be XML encoded as well.