I am using Apache Freemarker as my template engine.
I have a security issue with it that I am not sure how to handle: admin users are able to modify the templates, but in case they will set an input like:
`<#assign ex = "freemarker.template.utility.Execute"?new()>${ ex("pwd")}`.
Then the code will call:
freemarker.core.Environment.process()
And the command "pwd" will be executed.
How can I avoid it?
In my use case, I was retrieving Freemarker templates and merging the template with Java code like this:
String templateName = "Whatever from any variable"
StringTemplateLoader stringLoader = new StringTemplateLoader();
stringLoader.putTemplate(templateName, templateContent);
Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
cfg.setTemplateLoader(stringLoader);
// Create Template class object & get the Template
Template template = cfg.getTemplate(templateName);
// Render the template into a Writer, here a StringWriter
StringWriter writer = new StringWriter();
// Merge the model & template
template.process(dataModel, writer);
and this was subject to the same attack as the OP.
My solution was to set the SAFER_RESOLVER as said in the comments but by setting the value in the template instance itself like this:
template.setSetting("new_builtin_class_resolver", "safer");
After adding that line in my code (just after the template instanciation) my code was safe.
It is very important to know that even you implement this, you will be safer if you also keep the api_builtin_enabled to false (default value)
like explained in the doc.
This article shows that even with the more strict resolver ALLOWS_NOTHING_RESOLVER if the api_builtin_enabled is set to true, you can still have the vulnerability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With