From 88ad55ddafa9ab972bad8fc8572ebc74ba530424 Mon Sep 17 00:00:00 2001 From: Nathan Muir Date: Fri, 10 Aug 2018 11:55:48 +1000 Subject: [PATCH] templates: add env & minjson filters - Escape for systemd envfiles with `env` - Minify a JSON block with `minjson` --- credsmash/templates.py | 4 +++- credsmash/util.py | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/credsmash/templates.py b/credsmash/templates.py index 607d175..daa0fb2 100644 --- a/credsmash/templates.py +++ b/credsmash/templates.py @@ -11,7 +11,7 @@ import jinja2.sandbox import credsmash.api -from .util import read_many, shell_quote, parse_manifest, detect_format, ItemNotFound +from .util import read_many, minjson, envfile_quote, shell_quote, parse_manifest, detect_format, ItemNotFound from .cli import main logger = logging.getLogger(__name__) @@ -206,4 +206,6 @@ def _make_env(): ) env.filters['sh'] = shell_quote env.filters['jsonify'] = json.dumps + env.filters['minjson'] = minjson + env.filters['env'] = envfile_quote return env diff --git a/credsmash/util.py b/credsmash/util.py index 335900b..5f5e268 100644 --- a/credsmash/util.py +++ b/credsmash/util.py @@ -5,6 +5,7 @@ import logging import re import os +from collections import OrderedDict import six from six.moves import configparser @@ -198,3 +199,18 @@ def shell_quote(s): return "'" + s.replace("'", "'\"'\"'") + "'" + +def envfile_quote(s): + """Return a envfile-escaped version of the string *s*.""" + if not s: + return '""' + s = s.replace('\\', '\\\\') + s = s.replace('\n', '\\n\\\n') + s = s.replace('"', '\\"') + return '"' + s + '"' + + +def minjson(s): + """A filter to parse & re-minify json""" + o = json.loads(s, object_pairs_hook=OrderedDict) + return json.dumps(o)