Skip to content

Commit ca783a7

Browse files
committed
Boolean-based blind dump speedup (end-of-string hazard and match model)
1 parent ab8e217 commit ca783a7

4 files changed

Lines changed: 135 additions & 7 deletions

File tree

‎lib/core/option.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2349,9 +2349,12 @@ def _setKnowledgeBaseAttributes(flushAll=True):
23492349
kb.disableHuffman = False
23502350
kb.huffmanProbes = 0
23512351
kb.huffmanEscapes = 0
2352+
kb.huffmanNullEnd = False
23522353
kb.lowCardCache = {}
23532354
kb.dumpCharset = {}
23542355
kb.dumpCharsetStable = {}
2356+
kb.dumpLengths = {}
2357+
kb.dumpMatch = {"history": [], "table": {}, "accuracy": {}}
23552358
kb.litmusCounter = 0
23562359
kb.reliabilityAlarm = False
23572360
kb.httpErrorCodes = {}

‎lib/core/settings.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from thirdparty import six
2020

2121
# sqlmap version (<major>.<minor>.<month>.<monthly commit>)
22-
VERSION = "1.10.11.96"
22+
VERSION = "1.10.11.97"
2323
TYPE = "dev" if VERSION.count('.') > 2 and VERSION.split('.')[-1] != '0' else "stable"
2424
TYPE_COLORS = {"dev": 33, "stable": 90, "pip": 34}
2525
VERSION_STRING = "sqlmap/%s#%s" % ('.'.join(VERSION.split('.')[:-1]) if VERSION.count('.') > 2 and VERSION.split('.')[-1] == '0' else VERSION, TYPE)
@@ -665,6 +665,13 @@
665665
# the speculative restricted-search-then-escalate cost.
666666
DUMP_CHARSET_STABLE_ROWS = 3
667667

668+
# Context length of the (PAQ-style) match model used in blind dumps: the character that followed the most
669+
# recent earlier occurrence of the last this-many retrieved characters is favored in the Huffman tree
670+
DUMP_MATCH_ORDER = 3
671+
672+
# Maximum number of characters kept as the match model's history (reset once exceeded)
673+
DUMP_MATCH_HISTORY_LIMIT = 1000000
674+
668675
# Bounds for feeding extracted values back into the predictive-inference pool for their enumeration
669676
# context, so later same-context items that share structure (e.g. wp_posts / wp_users / wp_options ...)
670677
# are predicted faster. MAX_LENGTH keeps large data cells from bloating/polluting the pool (identifiers

‎lib/techniques/blind/inference.py‎

Lines changed: 113 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@
5353
from lib.core.settings import HUFFMAN_PRIOR_WEIGHTS
5454
from lib.core.settings import CATALOG_IDENTIFIERS_PRIOR_PEAK
5555
from lib.core.settings import DUMP_CHARSET_STABLE_ROWS
56+
from lib.core.settings import DUMP_MATCH_HISTORY_LIMIT
57+
from lib.core.settings import DUMP_MATCH_ORDER
5658
from lib.core.settings import LOW_CARDINALITY_MAX_GUESSES
5759
from lib.core.settings import LOW_CARDINALITY_THRESHOLD
5860
from lib.core.settings import NAME_PREDICTION_CONTEXTS
@@ -308,8 +310,8 @@ def recordDumpValue(columnKey, value):
308310
"""
309311
Records a retrieved dump cell into the column's models: low-cardinality cache (frequency-tracked so
310312
the most common values are probed first; bounded so a clearly high-cardinality column stops
311-
accumulating) and observed character set. Guarded by the prediction lock because value-parallel
312-
dump workers update these concurrently.
313+
accumulating), observed character set, length histogram and the match model's history. Guarded by
314+
the prediction lock because value-parallel dump workers update these concurrently.
313315
"""
314316

315317
ordinals = set(ord(_) for _ in value if ord(_) < 128)
@@ -328,6 +330,18 @@ def recordDumpValue(columnKey, value):
328330
# never triggers the restricted search, so it is never charged the miss-then-escalate cost.
329331
kb.dumpCharsetStable[columnKey] = 0 if grew else kb.dumpCharsetStable.get(columnKey, 0) + 1
330332

333+
lengths = kb.dumpLengths.setdefault(columnKey, {})
334+
lengths[len(value)] = lengths.get(len(value), 0) + 1
335+
336+
history, table = kb.dumpMatch["history"], kb.dumpMatch["table"]
337+
if len(history) > DUMP_MATCH_HISTORY_LIMIT: # Note: plain reset (a sliding window would keep more on huge dumps)
338+
del history[:]
339+
table.clear()
340+
for char in value + "\0":
341+
if len(history) >= DUMP_MATCH_ORDER:
342+
table["".join(history[-DUMP_MATCH_ORDER:])] = len(history)
343+
history.append(char)
344+
331345
def bisection(payload, expression, length=None, charsetType=None, firstChar=None, lastChar=None, dump=False):
332346
"""
333347
Bisection algorithm that can be used to perform blind SQL injection
@@ -614,6 +628,50 @@ def _check():
614628

615629
return _check()
616630

631+
matchState = {"ptr": None, "length": 0, "position": None}
632+
633+
def matchPredict():
634+
"""
635+
PAQ-style match model over the values retrieved so far in this dump (separated by "\\0"): returns
636+
the ordinal that followed the most recent earlier occurrence of the current context (0 meaning
637+
end-of-string), following that occurrence for as long as it keeps predicting right (copies like
638+
a username inside an email, repeated addresses, dictionary words). None if there is nothing.
639+
"""
640+
641+
history = kb.dumpMatch["history"]
642+
ptr, length = matchState["ptr"], matchState["length"]
643+
644+
if ptr is not None and matchState["position"] == len(partialValue) - 1 and ptr < len(history) and history[ptr] == partialValue[-1]:
645+
ptr, length = ptr + 1, length + 1
646+
else:
647+
context = ("".join(history[-DUMP_MATCH_ORDER:]) + partialValue)[-DUMP_MATCH_ORDER:]
648+
ptr, length = kb.dumpMatch["table"].get(context), 0
649+
650+
matchState.update(ptr=ptr, length=length, position=len(partialValue))
651+
652+
try:
653+
ordinal = ord(history[ptr]) if ptr is not None else None
654+
except IndexError: # history was reset in the meantime
655+
ordinal = None
656+
657+
return ordinal if ordinal is not None and ordinal < 128 else None
658+
659+
def learnMatch(predicted, actual):
660+
if predicted is not None:
661+
accuracyKey = (columnKey, min(matchState["length"], 12))
662+
with kb.locks.prediction:
663+
hits, tries = kb.dumpMatch["accuracy"].get(accuracyKey, (1, 2))
664+
kb.dumpMatch["accuracy"][accuracyKey] = (hits + (actual == predicted), tries + 1)
665+
666+
def endProbe(idx):
667+
"""
668+
Returns whether there is a character at the given position ('>0' with the classic template)
669+
"""
670+
671+
result = Request.queryPage(safeStringFormat(payload, (expressionUnescaped, idx, 0)), timeBasedCompare=timeBasedCompare, raise404=False)
672+
incrementCounter(getTechnique())
673+
return result
674+
617675
def huffmanChar(idx):
618676
"""
619677
Adaptive retrieval of a single character using set-membership ("... IN (...)")
@@ -640,11 +698,50 @@ def huffmanChar(idx):
640698
# the model - even raced under threads - only ever affects speed, never the returned value.
641699
context = partialValue[-huffmanOrder:] if huffmanOrder > 0 else ""
642700
weights = contextWeights(model, huffmanPrior, huffmanOrder, partialValue)
701+
leaves = [weights.get(_, 0) + HUFFMAN_PRIOR_WEIGHTS.get(_, 1) for _ in xrange(128)]
702+
predicted = None
703+
704+
# Sequential dump retrieval only. End-of-string hazard: probability that the value ends at this
705+
# position given that it reached it, from the column's length histogram (fixed-length values like
706+
# hashes/dates end in ~1 request instead of the deep, never-learned 0 leaf). Match model: favor
707+
# the character predicted by matchPredict() as much as it has proven right for this column.
708+
if columnKey is not None and numThreads == 1:
709+
predicted = matchPredict()
710+
if predicted is not None:
711+
accuracyKey = (columnKey, min(matchState["length"], 12))
712+
with kb.locks.prediction:
713+
hits, tries = kb.dumpMatch["accuracy"].get(accuracyKey, (1, 2))
714+
probability = float(hits) / tries
715+
leaves[predicted] = max(leaves[predicted], probability / (1 - probability) * (sum(leaves) - leaves[predicted]))
716+
717+
position = len(partialValue)
718+
with kb.locks.prediction:
719+
lengths = dict(kb.dumpLengths.get(columnKey) or ())
720+
atLeast = sum(count for length_, count in lengths.items() if length_ >= position)
721+
if atLeast:
722+
hazard = (lengths.get(position, 0) + 0.1) / (atLeast + 0.2)
723+
leaves[0] = max(hazard / (1 - hazard) * (sum(leaves) - leaves[0]), 0.001)
724+
725+
# A likely end is asked directly ('>0' is false both for 0 and for the NULL that e.g. Microsoft
726+
# SQL Server and Oracle return past the end, which no "IN (...)" can match). At a hazard of
727+
# 1/2 or more this costs the same as the 0 leaf at the root of the tree
728+
if hazard >= 0.5:
729+
if not endProbe(idx):
730+
learnMatch(predicted, 0)
731+
return None
732+
leaves[0] = 0
733+
734+
escape = max(weights.get(ESCAPE, 0), 1)
735+
736+
# Back-end returning NULL past the end: the 0 leaf can never match, so its (end-of-string) weight
737+
# goes to the escape leaf, which is then told apart from a non-ASCII character by a single '>0'
738+
if kb.huffmanNullEnd:
739+
escape, leaves[0] = escape + leaves[0], 0
643740

644741
heap = []
645-
for order, ordinal in enumerate(xrange(128)):
646-
heapq.heappush(heap, (weights.get(ordinal, 0) + HUFFMAN_PRIOR_WEIGHTS.get(ordinal, 1), order, (ordinal,)))
647-
heapq.heappush(heap, (max(weights.get(ESCAPE, 0), 1), 128, (ESCAPE,)))
742+
for ordinal in xrange(128):
743+
heapq.heappush(heap, (leaves[ordinal], ordinal, (ordinal,)))
744+
heapq.heappush(heap, (escape, 128, (ESCAPE,)))
648745

649746
counter = 129
650747
while len(heap) > 1:
@@ -696,10 +793,21 @@ def _hasEscape(n):
696793
value = node[0]
697794

698795
if value == ESCAPE:
796+
# Past-the-end NULL (e.g. Microsoft SQL Server, Oracle) fails every membership test too; one
797+
# '>0' tells it apart from a genuine non-ASCII character (saving the whole fallback bisection)
798+
if columnKey is not None and numThreads == 1 and not endProbe(idx):
799+
kb.huffmanNullEnd = True
800+
learnMatch(predicted, 0)
801+
return None
802+
803+
learnMatch(predicted, value)
804+
699805
with kb.locks.prediction:
700806
model.setdefault(context, {})[ESCAPE] = model.setdefault(context, {}).get(ESCAPE, 0) + 1
701807
return _HUFFMAN_FALLBACK
702808

809+
learnMatch(predicted, value)
810+
703811
if value == 0:
704812
# ORD(MID(..)) of an empty (past end-of-string) character is 0; mirror the classic
705813
# bisection and signal end-of-string (do NOT pollute the model with the sentinel).

‎tests/test_techniques.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1594,12 +1594,13 @@ def test_shortcuts_skipped_under_binary_field(self):
15941594

15951595

15961596
class TestRecordDumpValue(unittest.TestCase):
1597-
_KB = ("lowCardCache", "dumpCharset", "dumpCharsetStable")
1597+
_KB = ("lowCardCache", "dumpCharset", "dumpCharsetStable", "dumpLengths", "dumpMatch")
15981598

15991599
def setUp(self):
16001600
self._saved = {k: kb.get(k) for k in self._KB}
16011601
for k in self._KB:
16021602
kb[k] = {}
1603+
kb.dumpMatch = {"history": [], "table": {}, "accuracy": {}}
16031604

16041605
def tearDown(self):
16051606
for k, v in self._saved.items():
@@ -1619,6 +1620,15 @@ def test_counts_follow_frequency(self):
16191620
inf.recordDumpValue("k", value)
16201621
self.assertEqual(kb.lowCardCache["k"], {"US": 3, "HR": 1})
16211622

1623+
def test_lengths_and_match_history(self):
1624+
for value in ("john.smith", "john.smith@gmail.com"):
1625+
inf.recordDumpValue("k", value)
1626+
self.assertEqual(kb.dumpLengths["k"], {10: 1, 20: 1})
1627+
history = kb.dumpMatch["history"]
1628+
self.assertEqual("".join(history), "john.smith\0john.smith@gmail.com\0")
1629+
# most recent occurrence of the context wins: after "ith" comes '@' (second value), not "\0"
1630+
self.assertEqual(history[kb.dumpMatch["table"]["ith"]], "@")
1631+
16221632

16231633
class TestProcessCharHook(_InferenceCase):
16241634
def test_process_char_applied_to_each_char(self):

0 commit comments

Comments
 (0)