Skip to content

Commit efab0fd

Browse files
committed
Minor improvements for Esperanto engine
1 parent d45fedf commit efab0fd

7 files changed

Lines changed: 34 additions & 15 deletions

File tree

‎extra/esperanto/__main__.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -607,7 +607,7 @@ def _report(esp, args):
607607
print("[*] current database: %s" % (_scalar(esp, expr) if expr else "n/a"))
608608
if args.tables:
609609
print("[i] fetching tables ...")
610-
print("[*] tables: %s" % ", ".join(esp.enumerate("table", schema=scope) or ["<none>"]))
610+
print("[*] tables: %s" % ", ".join(esp.enumerate("table", limit=1000, schema=scope) or ["<none>"]))
611611
if args.columns:
612612
if not args.tbl:
613613
print("[!] --columns needs -T <table>")
@@ -638,6 +638,8 @@ def _report(esp, args):
638638
tag += " - INEXACT (case/accents may differ)"
639639
print("[*] Table: %s (%d entries%s)" % (args.tbl, len(result["rows"]), tag))
640640
_printTable(result["columns"], result["rows"])
641+
for note in esp.dialect.notes: # degradations (capped/stopped listing, truncation, ...) - never silent
642+
print("[!] %s" % _safeterm(note))
641643

642644

643645
def _banner():

‎extra/esperanto/discovery.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -583,7 +583,6 @@ def _discoverCharset(self):
583583
codec = _charsetCodec(res.value)
584584
if codec:
585585
self.dialect.charset = codec
586-
self.dialect.notes.append("declared charset %r -> %s" % (res.value, codec))
587586
return codec
588587
return None
589588

‎extra/esperanto/enumeration.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,14 @@ def _keysetWalk(self, col, src, where, limit):
173173
self.dialect.notes.append("enumeration stopped: %r holds an unrecoverable character" % name)
174174
break
175175
prev = name
176+
if names and len(names) >= limit:
177+
# hit the cap - one more probe tells "exactly `limit` names" apart from a silently cut listing
178+
beyond = self._beyondSql(col, prev, "text", seen=names)
179+
try:
180+
if beyond is not None and self._ask("(SELECT MIN(%s) FROM %s%s%s%s) IS NOT NULL" % (col, src, where, conj, beyond)):
181+
self.dialect.notes.append("enumeration capped at %d entries (more exist)" % limit)
182+
except OracleUndecided:
183+
pass
176184
return names
177185

178186
def _beyondSql(self, expr, prev, unit, seen=None, boundfn=None):
@@ -270,7 +278,7 @@ def _ensureQuoting(self, table):
270278
self.dialect.identQuote = False # sentinel: probed, none worked
271279
return None
272280

273-
def columns(self, table, schema=None, limit=50):
281+
def columns(self, table, schema=None, limit=1000):
274282
"""Enumerate a table's column names (keyset), optionally scoped to `schema`
275283
(so identically-named tables in different schemas don't merge columns). Falls
276284
back to brute-forcing common column names when no column catalog is usable."""

‎extra/esperanto/handler.py‎

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ def _engine(self):
9090
# primitive) - stop cleanly instead of surfacing an internal traceback
9191
raise SqlmapDataException("Esperanto could not establish reliable data extraction on this target (%s)" % ex)
9292
logger.info("Esperanto identified the back-end SQL dialect: %s" % (esp.identify().get("product") or "unknown"))
93+
logger.debug("Esperanto dialect: %r" % esp.dialect)
9394
esp._progress = lambda value: logger.info("retrieved: %s" % _sanitize(value)) # live feedback (sanitized)
9495
self._esp = esp
9596
self._notesLogged = 0
@@ -125,9 +126,6 @@ def _scopeFor(self, table):
125126
self._scopeCache[table] = scope
126127
return scope
127128

128-
def _db(self):
129-
return self._scopeDb() or "<current>"
130-
131129
def getFingerprint(self):
132130
# concise fingerprint only; the version banner is shown for --banner, not
133131
# printed unbidden on every run (and not re-extracted here)
@@ -146,6 +144,8 @@ def getCurrentUser(self):
146144
expr = self._engine().dialect.identity.get("user")
147145
if expr:
148146
logger.info("fetching current user")
147+
elif conf.getCurrentUser:
148+
logger.warning("Esperanto cannot retrieve the current user on this back-end (no known expression)")
149149
self._identCache["user"] = self._safeExtract(expr) if expr else None
150150
kb.data.currentUser = self._identCache["user"]
151151
return kb.data.currentUser
@@ -156,6 +156,8 @@ def getCurrentDb(self):
156156
expr = self._engine().dialect.identity.get("database")
157157
if expr:
158158
logger.info("fetching current database")
159+
elif conf.getCurrentDb:
160+
logger.warning("Esperanto cannot retrieve the current database name on this back-end (no known expression)")
159161
self._identCache["db"] = self._safeExtract(expr) if expr else None
160162
kb.data.currentDb = self._identCache["db"]
161163
return kb.data.currentDb
@@ -192,17 +194,18 @@ def getTables(self, bruteForce=None):
192194
# isn't polluted with every schema's tables (e.g. information_schema)
193195
db = conf.db or self.getCurrentDb()
194196
lim = conf.limitStop or 100
197+
infoMsg = "fetching tables"
198+
if db:
199+
infoMsg += " for database '%s'" % db
200+
logger.info(infoMsg)
195201
names = self._engine().enumerate("table", limit=lim, schema=db) or []
196202
if not names and not conf.db and db != "public":
197203
# current schema empty (PG-family: login-user schema) -> tables usually
198204
# live in 'public'; broaden rather than report nothing
205+
logger.info("no tables found, trying database 'public'")
199206
pub = self._engine().enumerate("table", limit=lim, schema="public") or []
200207
if pub:
201208
names, db = pub, "public"
202-
infoMsg = "fetching tables"
203-
if db:
204-
infoMsg += " for database '%s'" % db
205-
logger.info(infoMsg)
206209
kb.data.cachedTables = {db or "<current>": names}
207210
self._flushNotes()
208211
return kb.data.cachedTables
@@ -225,7 +228,7 @@ def getColumns(self, onlyColNames=False, colTuple=None, bruteForce=None, dumpMod
225228
def getSchema(self):
226229
esp = self._engine()
227230
# use the EFFECTIVE db that getTables() actually resolved (it may have broadened to
228-
# 'public' when the current schema was empty) - recomputing _db() here would miss
231+
# 'public' when the current schema was empty) - recomputing the scope here would miss
229232
# that and look columns up in the wrong (empty) schema.
230233
tabmap = self.getTables()
231234
effdb, tables = next(iter(tabmap.items()), ("<current>", []))
@@ -280,7 +283,7 @@ def dumpTable(self, foundData=None):
280283
values = [("NULL" if row[i] is None else row[i]) for row in result["rows"]]
281284
width = max([len(name)] + [len(v) for v in values]) if values else len(name)
282285
table_data[name] = {"length": width, "values": values}
283-
table_data["__infos__"] = {"count": len(result["rows"]), "table": conf.tbl, "db": self._db()}
286+
table_data["__infos__"] = {"count": len(result["rows"]), "table": conf.tbl, "db": db or "<current>"}
284287
if not result["complete"]:
285288
logger.warning("Esperanto dump of '%s' may be incomplete" % conf.tbl)
286289
if not result.get("exact", True): # coverage may be complete yet content inexact

‎extra/esperanto/records.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,9 +171,9 @@ def __init__(self):
171171
def __repr__(self):
172172
pick = lambda x: x[0] if x else None
173173
return ("Dialect(concat=%r substring=%r length=%r compare=%r dual=%r "
174-
"catalog=%r product=%r)" % (
174+
"catalog=%r charset=%r product=%r)" % (
175175
pick(self.concat), pick(self.substring), pick(self.length),
176-
self.compare, pick(self.dual), self.catalog,
176+
self.compare, pick(self.dual), self.catalog, self.charset,
177177
self.product or self.family))
178178

179179

‎lib/core/settings.py‎

Lines changed: 1 addition & 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.12.7"
22+
VERSION = "1.10.12.8"
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)

‎tests/test_esperanto.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -687,6 +687,13 @@ def ask(cond):
687687
tabs = set(esp.enumerate("table", limit=10) or [])
688688
self.assertTrue(set(["alpha", "beta"]).issubset(tabs), "enumerate tables: %r" % tabs)
689689

690+
# a listing cut by the limit is flagged; one that ends exactly at the limit is not
691+
self.assertEqual(len(esp.enumerate("table", limit=1)), 1)
692+
self.assertTrue(any("capped at 1 entries" in _ for _ in esp.dialect.notes), esp.dialect.notes)
693+
del esp.dialect.notes[:]
694+
self.assertEqual(len(esp.enumerate("table", limit=2)), 2)
695+
self.assertFalse(any("capped" in _ for _ in esp.dialect.notes), esp.dialect.notes)
696+
690697
def test_dump(self):
691698
# row DATA byte-exact, including commas / quotes / unicode (hex framing keeps intact)
692699
con = sqlite3.connect(":memory:")

0 commit comments

Comments
 (0)