fix: SMB share enumeration fallback + manual share entry

- Replace non-existent smbclient.listshares() with proper enumeration:
  tries smbclient CLI, then impacket, then falls back gracefully
- When enumeration fails or returns empty, show manual share name input
  instead of a dead end
- fbConnect now goes straight to browsing if share name is already filled
- Always reset SMB session before connecting to avoid stale auth cache
This commit is contained in:
TailScan Bot committed 2026-04-02 15:54:08 +00:00
1 parent 90059807e9
commit 0ff3d81b5d
2 files changed
+96 -18

No files matched your search

+69 -8
View File
@@ -105,21 +105,82 @@ def ftp_delete(host: str, port: int, username: str, password: str,
def _smb_conn(host: str, username: str, password: str, port: int = 445):
import smbclient
# Always reset the session for this host so stale/bad sessions don't linger
try:
smbclient.delete_session(host, port=port)
except Exception:
pass
smbclient.register_session(
host,
username=username or "guest",
password=password or "",
username=username if username else None,
password=password if password else None,
port=port,
)
def smb_list_shares(host: str, username: str, password: str, port: int = 445) -> list:
import smbclient
_smb_conn(host, username, password, port)
shares = []
for share in smbclient.listshares(host):
shares.append({"name": share, "type": "share"})
return shares
"""
Enumerate SMB shares via smbclient CLI (net utility) or impacket if available.
Falls back to asking the user to enter the share name manually.
"""
# Try smbclient CLI (net/smbclient command line tool)
import subprocess
creds = []
if username:
creds += ["-U", f"{username}%{password}" if password else username]
else:
creds += ["-N"] # no auth / guest
try:
result = subprocess.run(
["smbclient", "-L", f"//{host}", "--port", str(port)] + creds,
capture_output=True, text=True, timeout=10
)
shares = []
in_list = False
for line in result.stdout.splitlines():
if "Sharename" in line:
in_list = True
continue
if in_list:
if line.strip() == "" or line.startswith("\t-"):
continue
if line.startswith("\t") or line.startswith(" "):
parts = line.split(None, 2)
if parts:
name = parts[0].strip()
stype = parts[1].strip() if len(parts) > 1 else ""
if stype not in ("IPC", "Printer"):
shares.append({"name": name, "type": "share"})
else:
in_list = False
if shares:
return shares
except (FileNotFoundError, subprocess.TimeoutExpired):
pass
# Try impacket if installed
try:
from impacket.smbconnection import SMBConnection
smb = SMBConnection(host, host, sess_port=port)
if username:
smb.login(username, password or "")
else:
smb.login("", "")
shares = []
for share in smb.listShares():
name = share["shi1_netname"].get_value().rstrip("\x00")
stype = share["shi1_type"].get_value()
if stype == 0: # DISK
shares.append({"name": name, "type": "share"})
smb.logoff()
return shares
except ImportError:
pass
except Exception as e:
log.debug("impacket share enum failed: %s", e)
# Nothing worked — return empty so the UI falls back to manual entry
return []
def smb_list(host: str, username: str, password: str,
+27 -10
View File
@@ -1002,12 +1002,16 @@ function fbBreadcrumb() {
}
async function fbConnect() {
const user = document.getElementById('fb-user').value;
const pass = document.getElementById('fb-pass').value;
fbState.user = user;
fbState.pass = pass;
fbState.user = document.getElementById('fb-user').value;
fbState.pass = document.getElementById('fb-pass').value;
const shareVal = document.getElementById('fb-share').value.trim();
if (fbState.proto === 'smb') {
await fbLoadShares();
if (shareVal) {
// Share already entered — go straight to browsing it
fbSelectShare(shareVal);
} else {
await fbLoadShares();
}
} else {
await fbNav('/');
}
@@ -1015,20 +1019,33 @@ async function fbConnect() {
async function fbLoadShares() {
fbStatus('Loading shares...');
const { host, port, user='', pass='' } = fbState;
const { host, port } = fbState;
const user = fbState.user || '';
const pass = fbState.pass || '';
try {
const r = await fetch(`/api/smb/shares?host=${encodeURIComponent(host)}&port=${port}&username=${encodeURIComponent(user||'')}&password=${encodeURIComponent(pass||'')}`);
if (!r.ok) { const e = await r.json().catch(()=>({detail:r.statusText})); fbStatus(e.detail||r.statusText, true); return; }
const r = await fetch(`/api/smb/shares?host=${encodeURIComponent(host)}&port=${port}&username=${encodeURIComponent(user)}&password=${encodeURIComponent(pass)}`);
if (!r.ok) { const e = await r.json().catch(()=>({detail:r.statusText})); fbStatus(e.detail||r.statusText, true); fbShowManualShare(); return; }
const shares = await r.json();
fbStatus('');
const list = document.getElementById('fb-list');
if (!shares.length) { list.innerHTML = '<div style="padding:24px;text-align:center;color:#6b7280">No accessible shares</div>'; return; }
if (!shares.length) { fbShowManualShare(); return; }
list.innerHTML = shares.map(s => `
<div class="fb-row" onclick="fbSelectShare('${escHtml(s.name)}')">
<span class="fb-icon">&#128191;</span>
<span class="fb-name">${escHtml(s.name)}</span>
</div>`).join('');
} catch(e) { fbStatus(String(e), true); }
} catch(e) { fbStatus(String(e), true); fbShowManualShare(); }
}
function fbShowManualShare() {
const shareInput = document.getElementById('fb-share');
document.getElementById('fb-share-wrap').style.display = '';
shareInput.focus();
const list = document.getElementById('fb-list');
list.innerHTML = `<div style="padding:20px 16px;color:#9ca3af;font-size:13px;">
Share enumeration not available. Enter the share name above and press
<strong style="color:#fdba74">Connect</strong> to browse it.
</div>`;
}
function fbSelectShare(share) {