|
5 | 5 | See the file 'LICENSE' for copying permission |
6 | 6 | """ |
7 | 7 |
|
8 | | -try: |
9 | | - import cPickle as pickle |
10 | | -except: |
11 | | - import pickle |
12 | | - |
13 | 8 | import base64 |
14 | 9 | import binascii |
15 | 10 | import codecs |
| 11 | +import datetime |
| 12 | +import decimal |
16 | 13 | import json |
17 | 14 | import re |
18 | 15 | import sys |
|
26 | 23 | from lib.core.settings import IS_TTY |
27 | 24 | from lib.core.settings import IS_WIN |
28 | 25 | from lib.core.settings import NULL |
29 | | -from lib.core.settings import PICKLE_PROTOCOL |
30 | 26 | from lib.core.settings import SAFE_HEX_MARKER |
31 | 27 | from lib.core.settings import UNICODE_ENCODING |
32 | 28 | from thirdparty import six |
|
41 | 37 |
|
42 | 38 | htmlEscape = _escape |
43 | 39 |
|
44 | | -def base64pickle(value): |
| 40 | +# Safe (no arbitrary code execution) serialization used for the session store (HashDB) |
| 41 | +# and BigArray disk chunks. The former serializer could execute code while loading, so |
| 42 | +# deserializing sqlmap's own (locally writable) session/cache files was a recurring |
| 43 | +# report magnet. This codec serializes to plain JSON with explicit type tags, so nothing |
| 44 | +# is ever executed on load. |
| 45 | +# |
| 46 | +# JSON natively covers only str/int/float/bool/None/list, and silently loses the rest |
| 47 | +# (int/tuple dict keys become strings, set/tuple/bytes are rejected). The tagged wrappers |
| 48 | +# below preserve every type sqlmap actually stores: bytes, tuple, set/frozenset, dict with |
| 49 | +# arbitrary (non-string) keys, DB-driver scalars (Decimal/datetime/...), and the handful of |
| 50 | +# sqlmap's own classes below. Reconstruction of classes is limited to that explicit |
| 51 | +# allowlist (no module/namespace wildcard), so no dangerous callable is ever reachable. |
| 52 | + |
| 53 | +# reserved wrapper key; data mappings are encoded as tagged pair-lists (never as bare JSON |
| 54 | +# objects), so any decoded JSON object is one of our wrappers and this key can never collide |
| 55 | +_SERIALIZE_TAG = "$T" |
| 56 | + |
| 57 | +# fully-qualified names of the ONLY classes that may be reconstructed on deserialization |
| 58 | +_SERIALIZE_CLASSES = frozenset(( |
| 59 | + "lib.core.datatype.AttribDict", |
| 60 | + "lib.core.datatype.InjectionDict", |
| 61 | + "lib.utils.har.RawPair", |
| 62 | +)) |
| 63 | + |
| 64 | +def _serializeEncode(value): |
45 | 65 | """ |
46 | | - Serializes (with pickle) and encodes to Base64 format supplied (binary) value |
47 | | -
|
48 | | - >>> base64unpickle(base64pickle([1, 2, 3])) == [1, 2, 3] |
49 | | - True |
50 | | - >>> isinstance(base64unpickle(base64pickle(BigArray([1, 2, 3]))), BigArray) |
51 | | - True |
| 66 | + Turns a Python value into a JSON-serializable (tagged) structure |
52 | 67 | """ |
53 | 68 |
|
54 | | - retVal = None |
| 69 | + if value is None or isinstance(value, bool) or isinstance(value, float) or isinstance(value, six.integer_types): |
| 70 | + return value |
| 71 | + |
| 72 | + if isinstance(value, six.text_type): |
| 73 | + return value |
| 74 | + |
| 75 | + # Note: on Python 2 'str' is binary; base64-tagging it (rather than emitting a native JSON |
| 76 | + # string that would round-trip as 'unicode') keeps the exact byte type across versions |
| 77 | + if isinstance(value, (six.binary_type, bytearray)): |
| 78 | + raw = bytes(value) if isinstance(value, bytearray) else value |
| 79 | + return {_SERIALIZE_TAG: "b", "v": encodeBase64(raw, binary=False), "a": 1 if isinstance(value, bytearray) else 0} |
| 80 | + |
| 81 | + if isinstance(value, memoryview): |
| 82 | + return {_SERIALIZE_TAG: "b", "v": encodeBase64(value.tobytes(), binary=False), "a": 0} |
55 | 83 |
|
56 | 84 | try: |
57 | | - retVal = encodeBase64(pickle.dumps(value, PICKLE_PROTOCOL), binary=False) |
58 | | - except: |
59 | | - warnMsg = "problem occurred while serializing " |
60 | | - warnMsg += "instance of a type '%s'" % type(value) |
61 | | - singleTimeWarnMessage(warnMsg) |
| 85 | + if isinstance(value, buffer): # noqa: F821 # Python 2 only |
| 86 | + return {_SERIALIZE_TAG: "b", "v": encodeBase64(bytes(value), binary=False), "a": 0} |
| 87 | + except NameError: |
| 88 | + pass |
| 89 | + |
| 90 | + # Note: BigArray is a 'list' subclass, so it must be matched before the plain-list branch |
| 91 | + # (otherwise it would round-trip as a plain list, losing its type) |
| 92 | + if isinstance(value, BigArray): |
| 93 | + return {_SERIALIZE_TAG: "ba", "v": [_serializeEncode(_) for _ in value]} |
| 94 | + |
| 95 | + if isinstance(value, list): |
| 96 | + return [_serializeEncode(_) for _ in value] |
| 97 | + |
| 98 | + if isinstance(value, tuple): |
| 99 | + return {_SERIALIZE_TAG: "t", "v": [_serializeEncode(_) for _ in value]} |
| 100 | + |
| 101 | + if isinstance(value, frozenset): |
| 102 | + return {_SERIALIZE_TAG: "f", "v": [_serializeEncode(_) for _ in value]} |
| 103 | + |
| 104 | + if isinstance(value, (set, _collections.Set)): |
| 105 | + return {_SERIALIZE_TAG: "s", "v": [_serializeEncode(_) for _ in value]} |
| 106 | + |
| 107 | + if isinstance(value, dict): |
| 108 | + name = "%s.%s" % (value.__class__.__module__, value.__class__.__name__) |
| 109 | + if name in _SERIALIZE_CLASSES: |
| 110 | + return {_SERIALIZE_TAG: "o", "c": name, "d": [[_serializeEncode(k), _serializeEncode(v)] for (k, v) in value.items()], "s": _serializeEncode(dict(value.__dict__))} |
| 111 | + elif value.__class__ is dict: |
| 112 | + return {_SERIALIZE_TAG: "m", "v": [[_serializeEncode(k), _serializeEncode(v)] for (k, v) in value.items()]} |
| 113 | + else: |
| 114 | + return _serializeUnknown(value, name) |
62 | 115 |
|
63 | | - try: |
64 | | - retVal = encodeBase64(pickle.dumps(value), binary=False) |
65 | | - except: |
66 | | - raise |
| 116 | + if isinstance(value, decimal.Decimal): |
| 117 | + return {_SERIALIZE_TAG: "dec", "v": getUnicode(value)} |
| 118 | + |
| 119 | + if isinstance(value, datetime.datetime): |
| 120 | + return {_SERIALIZE_TAG: "dt", "v": [value.year, value.month, value.day, value.hour, value.minute, value.second, value.microsecond]} |
| 121 | + |
| 122 | + if isinstance(value, datetime.date): |
| 123 | + return {_SERIALIZE_TAG: "date", "v": [value.year, value.month, value.day]} |
| 124 | + |
| 125 | + if isinstance(value, datetime.time): |
| 126 | + return {_SERIALIZE_TAG: "time", "v": [value.hour, value.minute, value.second, value.microsecond]} |
| 127 | + |
| 128 | + if isinstance(value, datetime.timedelta): |
| 129 | + return {_SERIALIZE_TAG: "td", "v": [value.days, value.seconds, value.microseconds]} |
| 130 | + |
| 131 | + name = "%s.%s" % (value.__class__.__module__, value.__class__.__name__) |
| 132 | + if name in _SERIALIZE_CLASSES: |
| 133 | + return {_SERIALIZE_TAG: "o", "c": name, "s": _serializeEncode(dict(value.__dict__))} |
| 134 | + |
| 135 | + return _serializeUnknown(value, name) |
| 136 | + |
| 137 | +def _serializeUnknown(value, name): |
| 138 | + """ |
| 139 | + Fallback for a type not explicitly handled by the serializer |
| 140 | + """ |
| 141 | + |
| 142 | + # sqlmap's own (or bundled) classes MUST be added to the allowlist explicitly - fail loudly |
| 143 | + # (caught by the regression tests) rather than silently store something that cannot be restored |
| 144 | + if (name or "").split(".")[0] in ("lib", "plugins", "thirdparty"): |
| 145 | + raise TypeError("serialization of type '%s' is not supported" % name) |
| 146 | + |
| 147 | + # a foreign/exotic scalar (e.g. an unusual DB-driver value): degrade to its textual form rather |
| 148 | + # than crash a user's session - session values are only ever rendered (getUnicode) downstream |
| 149 | + singleTimeWarnMessage("serializing value of unsupported type '%s' as text" % name) |
| 150 | + return getUnicode(value) |
| 151 | + |
| 152 | +def _serializeDecode(struct): |
| 153 | + """ |
| 154 | + Restores a Python value from a JSON-deserialized (tagged) structure |
| 155 | + """ |
| 156 | + |
| 157 | + if struct is None or isinstance(struct, bool) or isinstance(struct, float) or isinstance(struct, six.integer_types): |
| 158 | + return struct |
| 159 | + |
| 160 | + if isinstance(struct, six.text_type): |
| 161 | + return struct |
| 162 | + |
| 163 | + if isinstance(struct, six.binary_type): # defensive - json.loads() yields text, not bytes |
| 164 | + return getUnicode(struct) |
| 165 | + |
| 166 | + if isinstance(struct, list): |
| 167 | + return [_serializeDecode(_) for _ in struct] |
| 168 | + |
| 169 | + if isinstance(struct, dict): |
| 170 | + tag = struct.get(_SERIALIZE_TAG) |
| 171 | + |
| 172 | + if tag == "b": |
| 173 | + raw = decodeBase64(struct["v"], binary=True) |
| 174 | + return bytearray(raw) if struct.get("a") else raw |
| 175 | + elif tag == "t": |
| 176 | + return tuple(_serializeDecode(_) for _ in struct["v"]) |
| 177 | + elif tag == "f": |
| 178 | + return frozenset(_serializeDecode(_) for _ in struct["v"]) |
| 179 | + elif tag == "ba": |
| 180 | + return BigArray([_serializeDecode(_) for _ in struct["v"]]) |
| 181 | + elif tag == "s": |
| 182 | + return set(_serializeDecode(_) for _ in struct["v"]) |
| 183 | + elif tag == "m": |
| 184 | + return dict((_serializeDecode(k), _serializeDecode(v)) for (k, v) in struct["v"]) |
| 185 | + elif tag == "dec": |
| 186 | + return decimal.Decimal(struct["v"]) |
| 187 | + elif tag == "dt": |
| 188 | + return datetime.datetime(*struct["v"]) |
| 189 | + elif tag == "date": |
| 190 | + return datetime.date(*struct["v"]) |
| 191 | + elif tag == "time": |
| 192 | + return datetime.time(*struct["v"]) |
| 193 | + elif tag == "td": |
| 194 | + return datetime.timedelta(struct["v"][0], struct["v"][1], struct["v"][2]) |
| 195 | + elif tag == "o": |
| 196 | + return _serializeDecodeObject(struct) |
| 197 | + elif tag is None: # defensive - a bare mapping should never occur |
| 198 | + return dict((_serializeDecode(k), _serializeDecode(v)) for (k, v) in struct.items()) |
| 199 | + else: |
| 200 | + raise ValueError("unsupported serialized tag '%s'" % tag) |
| 201 | + |
| 202 | + raise ValueError("unsupported serialized structure of type '%s'" % type(struct)) |
| 203 | + |
| 204 | +def _serializeResolveClass(name): |
| 205 | + """ |
| 206 | + Resolves an allowlisted class name to its class (nothing else may be reconstructed) |
| 207 | + """ |
| 208 | + |
| 209 | + if name not in _SERIALIZE_CLASSES: |
| 210 | + raise ValueError("deserialization of class '%s' is forbidden" % name) |
| 211 | + |
| 212 | + if name == "lib.utils.har.RawPair": |
| 213 | + from lib.utils.har import RawPair |
| 214 | + return RawPair |
| 215 | + else: |
| 216 | + from lib.core.datatype import AttribDict, InjectionDict |
| 217 | + return InjectionDict if name.endswith("InjectionDict") else AttribDict |
| 218 | + |
| 219 | +def _serializeDecodeObject(struct): |
| 220 | + """ |
| 221 | + Reconstructs an allowlisted class instance from its serialized form |
| 222 | + """ |
| 223 | + |
| 224 | + _class = _serializeResolveClass(struct.get("c")) |
| 225 | + retVal = _class.__new__(_class) |
| 226 | + |
| 227 | + if isinstance(retVal, dict): |
| 228 | + for pair in (struct.get("d") or []): |
| 229 | + dict.__setitem__(retVal, _serializeDecode(pair[0]), _serializeDecode(pair[1])) |
| 230 | + |
| 231 | + state = _serializeDecode(struct.get("s") or {}) |
| 232 | + if isinstance(state, dict): |
| 233 | + retVal.__dict__.update(state) |
67 | 234 |
|
68 | 235 | return retVal |
69 | 236 |
|
70 | | -def base64unpickle(value): |
| 237 | +def serializeValue(value): |
71 | 238 | """ |
72 | | - Decodes value from Base64 to plain format and deserializes (with pickle) its content |
| 239 | + Safely serializes a Python value to its canonical serialized form (JSON text), without any |
| 240 | + code-execution risk |
73 | 241 |
|
74 | | - >>> type(base64unpickle('gAJjX19idWlsdGluX18Kb2JqZWN0CnEBKYFxAi4=')) == object |
| 242 | + Note: the output is pure ASCII text, so it is stored verbatim in the (TEXT) session store - no |
| 243 | + Base64 (or any base-N) wrapping is needed (that was only required by the former binary |
| 244 | + serialization), which also keeps the stored form as small as possible. Callers that need raw |
| 245 | + bytes (e.g. a compressed BigArray disk chunk) simply encode the returned text. |
| 246 | +
|
| 247 | + >>> deserializeValue(serializeValue({1: 'a', 'b': (2, 3), 'c': {4, 5}})) == {1: 'a', 'b': (2, 3), 'c': {4, 5}} |
| 248 | + True |
| 249 | + >>> deserializeValue(serializeValue([1, 2, (3, {4: b'5'})])) == [1, 2, (3, {4: b'5'})] |
75 | 250 | True |
76 | 251 | """ |
77 | 252 |
|
78 | | - retVal = None |
| 253 | + return json.dumps(_serializeEncode(value), ensure_ascii=True, separators=(',', ':')) |
79 | 254 |
|
80 | | - try: |
81 | | - retVal = pickle.loads(decodeBase64(value)) |
82 | | - except TypeError: |
83 | | - retVal = pickle.loads(decodeBase64(bytes(value))) |
| 255 | +def deserializeValue(value): |
| 256 | + """ |
| 257 | + Restores a Python value from its serialized form (accepts the serialized data as either text or |
| 258 | + bytes) |
| 259 | + """ |
84 | 260 |
|
85 | | - return retVal |
| 261 | + return _serializeDecode(json.loads(getText(value))) |
86 | 262 |
|
87 | 263 | def htmlUnescape(value): |
88 | 264 | """ |
|
0 commit comments