5353from lib .core .settings import HUFFMAN_PRIOR_WEIGHTS
5454from lib .core .settings import CATALOG_IDENTIFIERS_PRIOR_PEAK
5555from 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
5658from lib .core .settings import LOW_CARDINALITY_MAX_GUESSES
5759from lib .core .settings import LOW_CARDINALITY_THRESHOLD
5860from 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+
331345def 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).
0 commit comments