You Let Each Branch Edit Its Own Email Template and str.format Printed the Server's Environment
Every branch wanted its own wording on the "order ready" email. Fair enough. So the admin screen got a template box. Hi {customer.name}, order {order.number} is ready at {branch.name}. And the code was one line: bod
Every branch
wanted its own wording
on the "order ready" email.
Fair enough.
So the admin screen
got a template box.
Hi {customer.name},
order {order.number}
is ready at {branch.name}.
And the code
was one line:
body = template.format(
customer=customer, order=order, branch=branch)
It looked like
a mail merge.
It was not one.
Python's format
does more
than fill in names.
It follows dots.
It follows square brackets.
On any object
you hand it.
So a branch admin,
curious,
or angry,
or just borrowed,
saved this template:
{order.init.globals[os].environ}
The test email arrived
with the database password,
the payment key
and everything else
the server had been started with.
Here is the mechanism.
order is an object.
Its init
is a Python function.
Every Python function
carries globals,
the variables of the module
it was written in.
That module
imported os.
os.environ
is the process environment.
Four dots
and two brackets
from a mail merge
to your secrets.
No code ran.
No injection
in the usual sense.
format did exactly
what it is documented to do.
The template box
was a programming language
nobody had meant to ship.
It can also
just hurt you:
{customer.name:>999999999}
asks for a field
a billion characters wide.
Armin Ronacher
wrote about this in 2016.
It is still
one line away
in most codebases
that let customers
customise anything.
Here is the fix.
Never let users
write the format string.
If they need templates,
give them string.Template.
from string import Template
body = Template(template).safe_substitute(
name=customer.name, number=order.number)
$name only.
No dots.
No brackets.
No attributes.
If you need loops and conditions,
use Jinja2's
SandboxedEnvironment,
which refuses
the underscore attributes.
And whatever you pass,
pass plain strings,
never the objects
behind them.
Then search the codebase
for .format(
on anything
that came from a database.
A template a user writes
is input.
format treats it
as a map
of your process.
– Serguey Asael Shinder
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.