diff --git a/.env.example b/.env.example index 74d32fa..4b8060e 100755 --- a/.env.example +++ b/.env.example @@ -86,6 +86,10 @@ OPENCODE_API_KEY= # `hermes` CLI (`hermes setup --portal` for OAuth login). NOUS_API_KEY= +# morse: https://console.trymorse.ai — uncensored open-weight models +# with native tool calling. No prompt/reply storage. +MORSE_API_KEY= + # ollama: local, no key needed. Override the endpoint if not default: #OLLAMA_BASE_URL=http://localhost:11434/v1 @@ -148,6 +152,25 @@ TYPESAFE_API_KEY= #NEUROSPLOIT_TUNNEL_PORT=8080 #NEUROSPLOIT_TUNNEL_BIND=127.0.0.1 +# ------------------------------------------------------------------ +# Docker / PostgreSQL (used by docker-compose.yml) +POSTGRES_USER=neurosploit +POSTGRES_PASSWORD= # auto-generated by install.sh +POSTGRES_DB=neurosploit + +# ------------------------------------------------------------------ +# Web Console Authentication +NS_JWT_SECRET= # auto-generated by install.sh +NS_DEFAULT_USER=neurosploit # default login username +NS_DEFAULT_PASSWORD= # auto-generated by install.sh; change after first login +NS_PORT=8787 +NS_BIND_ADDR=127.0.0.1 # 0.0.0.0 to listen on all interfaces + +# ------------------------------------------------------------------ +# Sandbox / Worker +NS_SANDBOX=required # required | optional | off +NS_WORKER_IMAGE=neurosploit-kali:local + # ------------------------------------------------------------------ # Output budgets. These are ceilings, not usage. Raise/lower per provider. #NEUROSPLOIT_MAX_TOKENS= diff --git a/web/public/app.js b/web/public/app.js index 292d5da..41f5205 100644 --- a/web/public/app.js +++ b/web/public/app.js @@ -68,8 +68,25 @@ function jsq(s) { const lit = "'" + String(s ?? '').replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'"; return lit.replace(/&/g, '&').replace(/"/g, '"').replace(/ ({})); throw new Error(body.error || `${path} → ${res.status}`); @@ -1072,6 +1089,15 @@ function attachLiveJob(id, target, name, pinnedAgents) { es.addEventListener('graph', (e) => { const d = sseJson(e); if (d) updateGraphTab(d); }); es.addEventListener('planner', (e) => { const d = sseJson(e); if (d) updatePlannerTab(d); }); es.addEventListener('noise', (e) => { const d = sseJson(e); if (d) updateNoiseTab(d); }); + es.addEventListener('exploration', (e) => { + const d = sseJson(e); + if (d && state.currentJob) { + state.currentJob.exploration = d; + const lbl = d.complete ? `✓ Explored ${d.round} round(s), +${d.totalExtra} findings` : + `Round ${d.round} · ${d.skillsThisRound || '?'} skills · +${d.totalExtra || 0} findings`; + appendLog(`🧭 ${lbl}`); + } + }); es.addEventListener('snapshot', (e) => { const d = sseJson(e); if (d) applySnapshot(d); }); es.addEventListener('done', (e) => { const d = sseJson(e); diff --git a/web/public/login.html b/web/public/login.html new file mode 100644 index 0000000..db2a3be --- /dev/null +++ b/web/public/login.html @@ -0,0 +1,333 @@ + + + + + + +NeuroSploit — Login + + + + + + + + +
+
+
+
+ +
+
+
+ +
+
+ +
+
NeuroSploit
+
Autonomous Pentest Engine
+
+ + + + + +
+ + Invalid credentials +
+ + +
+
+ +
+ + +
+
+ +
+ +
+ + + +
+
+ + + +
+
+ Encrypted session · 24h token +
+
+ + +
+
+
+ + + + + + diff --git a/web/server.js b/web/server.js index 77f7cee..d375f16 100644 --- a/web/server.js +++ b/web/server.js @@ -481,6 +481,8 @@ const PROVIDERS = [ models: ['anthropic/claude-opus-5-5', 'anthropic/claude-opus-4-8', 'z-ai/glm-5.3', 'qwen/qwen3.8-max', 'deepseek/deepseek-v4.1-flash-1017', 'deepseek/deepseek-v4.1-flash', 'deepseek/deepseek-v4-pro', 'meta-llama/llama-3.3-70b-instruct'] }, { key: 'orcarouter', label: 'OrcaRouter', kind: 'api', envKey: 'ORCAROUTER_API_KEY', models: ['orcarouter/auto', 'orcarouter/free', 'orcarouter/fusion', 'deepseek/deepseek-v4.1-flash', 'deepseek/deepseek-v4-pro', 'deepseek/deepseek-chat'] }, + { key: 'morse', label: 'Morse', kind: 'api', envKey: 'MORSE_API_KEY', + models: ['z-ai/glm-5.3-uncensored', 'deepseek-ai/deepseek-v4.1-flash-uncensored', 'moonshotai/kimi-k3.1-pro-uncensored', 'qwen/qwen3.8-27b-uncensored', 'z-ai/glm-5.3-flash-uncensored', 'deepseek/deepseek-v4-pro'] }, { key: 'azure', label: 'Azure OpenAI', kind: 'api', envKey: 'AZURE_OPENAI_API_KEY', models: ['gpt-4o', 'gpt-4o-mini', 'gpt-5.1', 'o4-mini'] }, { key: 'bedrock', label: 'AWS Bedrock', kind: 'api', envKey: 'AWS_ACCESS_KEY_ID', @@ -2031,6 +2033,24 @@ function ingestLine(job, rawLine) { if (/candidate\(s\)/.test(lown) && /^(exploit|test|analyze|review)\b/.test(lown)) job.agentsDone += 1; + // Exploration loop events — skill-based chaining rounds + if (low.includes('exploration round')) { + job.phase = 'exploring'; + const roundMatch = norm.match(/exploration round (\d+)/); + const countMatch = norm.match(/(\d+) skill\(s\) triggered/); + const findingsMatch = norm.match(/(\d+) new finding/); + if (!job.exploration) job.exploration = { round: 0, totalExtra: 0, skills: [] }; + if (roundMatch) job.exploration.round = parseInt(roundMatch[1]); + if (countMatch) job.exploration.skillsThisRound = parseInt(countMatch[1]); + if (findingsMatch) job.exploration.totalExtra += parseInt(findingsMatch[1]); + job.push({ type: 'exploration', data: { ...job.exploration } }); + } + if (low.includes('exploration complete')) { + const extraMatch = norm.match(/(\d+) extra finding/); + if (job.exploration && extraMatch) job.exploration.totalExtra = parseInt(extraMatch[1]); + job.push({ type: 'exploration', data: { ...job.exploration, complete: true } }); + } + const fj = norm.match(/^finding_json:\s*(.+)$/); if (fj) { try { @@ -2847,8 +2867,107 @@ const MIME = { '.md': 'text/plain; charset=utf-8', }; +// --------------------------------------------------------------------------- +// Authentication layer — JWT + scrypt, zero external deps. +// When NS_JWT_SECRET is set, every /api/* request (except /api/auth/*) must +// carry a valid Bearer token. When unset, auth is disabled (local dev mode). +// --------------------------------------------------------------------------- +const AUTH_ENABLED = !!process.env.NS_JWT_SECRET; +const JWT_SECRET = process.env.NS_JWT_SECRET || 'dev-insecure-do-not-use'; +const JWT_EXPIRY_HOURS = 24; +const AUTH_FILE = path.join(CONFIG_DIR, 'auth-users.json'); +const AUTH_RATE = new Map(); // ip -> { count, resetAt } +const AUTH_RATE_MAX = 10; +const AUTH_RATE_WINDOW = 60_000; + +async function hashPassword(plain) { + return new Promise((resolve, reject) => { + const salt = crypto.randomBytes(16); + crypto.scrypt(plain, salt, 64, (err, dk) => { + if (err) return reject(err); + resolve(salt.toString('hex') + ':' + dk.toString('hex')); + }); + }); +} +async function verifyPassword(plain, stored) { + const [saltHex, dkHex] = stored.split(':'); + const salt = Buffer.from(saltHex, 'hex'); + return new Promise((resolve, reject) => { + crypto.scrypt(plain, salt, 64, (err, dk) => { + if (err) return reject(err); + resolve(crypto.timingSafeEqual(dk, Buffer.from(dkHex, 'hex'))); + }); + }); +} +function jwtSign(payload) { + const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url'); + const body = Buffer.from(JSON.stringify({ ...payload, iat: Math.floor(Date.now() / 1000), exp: Math.floor(Date.now() / 1000) + JWT_EXPIRY_HOURS * 3600 })).toString('base64url'); + const sig = crypto.createHmac('sha256', JWT_SECRET).update(`${header}.${body}`).digest('base64url'); + return `${header}.${body}.${sig}`; +} +function jwtVerify(token) { + const parts = token.split('.'); + if (parts.length !== 3) return null; + const sig = crypto.createHmac('sha256', JWT_SECRET).update(`${parts[0]}.${parts[1]}`).digest('base64url'); + if (!crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(parts[2]))) return null; + try { + const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString()); + if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) return null; + return payload; + } catch { return null; } +} +async function loadAuthUsers() { + try { return JSON.parse(await fsp.readFile(AUTH_FILE, 'utf8')); } + catch { return []; } +} +async function saveAuthUsers(users) { + await ensureConfigDir(); + await fsp.writeFile(AUTH_FILE, JSON.stringify(users, null, 2)); +} +async function ensureDefaultUser() { + const users = await loadAuthUsers(); + if (users.length > 0) return; + const username = process.env.NS_DEFAULT_USER || 'neurosploit'; + const plainPass = process.env.NS_DEFAULT_PASSWORD || crypto.randomBytes(12).toString('base64url'); + const hashed = await hashPassword(plainPass); + users.push({ username, password: hashed, role: 'admin', firstLogin: true, createdAt: new Date().toISOString() }); + await saveAuthUsers(users); + if (!process.env.NS_DEFAULT_PASSWORD) { + console.log(`\n Default credentials → ${username} / ${plainPass}\n Change after first login.\n`); + } +} +function authRateCheck(ip) { + const now = Date.now(); + let entry = AUTH_RATE.get(ip); + if (!entry || now > entry.resetAt) { entry = { count: 0, resetAt: now + AUTH_RATE_WINDOW }; AUTH_RATE.set(ip, entry); } + entry.count++; + return entry.count <= AUTH_RATE_MAX; +} +function extractToken(req) { + const auth = req.headers.authorization || ''; + if (auth.startsWith('Bearer ')) return auth.slice(7); + const cookie = req.headers.cookie || ''; + const m = cookie.match(/(?:^|;\s*)ns_token=([^;]+)/); + return m ? m[1] : null; +} +function requireAuth(req, res) { + if (!AUTH_ENABLED) return { username: 'operator', role: 'admin' }; + const token = extractToken(req); + if (!token) { sendJson(res, 401, { error: 'authentication required' }); return null; } + const payload = jwtVerify(token); + if (!payload) { sendJson(res, 401, { error: 'invalid or expired token' }); return null; } + return payload; +} + async function serveStatic(req, res, urlPath) { let rel = urlPath === '/' ? '/index.html' : urlPath; + // Auth gate for the SPA: redirect to /login.html when no valid token + if (AUTH_ENABLED && (rel === '/index.html' || rel === '/')) { + const token = extractToken(req); + if (!token || !jwtVerify(token)) { + rel = '/login.html'; + } + } const full = path.join(PUBLIC_DIR, rel); if (!full.startsWith(PUBLIC_DIR)) { res.writeHead(403); res.end(); return; } try { @@ -2889,6 +3008,65 @@ const server = http.createServer(async (req, res) => { return serveStatic(req, res, p); } + // ---- auth endpoints (unauthenticated) ---- + if (p.startsWith('/api/auth/')) { + const ip = req.headers['x-forwarded-for']?.split(',')[0]?.trim() || req.socket.remoteAddress || ''; + if (req.method === 'GET' && p === '/api/auth/status') { + const users = await loadAuthUsers(); + return sendJson(res, 200, { enabled: AUTH_ENABLED, firstLogin: users.length > 0 && users[0].firstLogin === true, hasUsers: users.length > 0 }); + } + if (req.method === 'POST' && p === '/api/auth/login') { + if (!authRateCheck(ip)) return sendJson(res, 429, { error: 'too many attempts, try again later' }); + const body = await readBody(req); + const { username, password } = body; + if (!username || !password) return sendJson(res, 400, { error: 'username and password required' }); + const users = await loadAuthUsers(); + const user = users.find(u => u.username === username); + if (!user) return sendJson(res, 401, { error: 'invalid credentials' }); + const ok = await verifyPassword(password, user.password); + if (!ok) return sendJson(res, 401, { error: 'invalid credentials' }); + user.lastLogin = new Date().toISOString(); + await saveAuthUsers(users); + const token = jwtSign({ username: user.username, role: user.role }); + res.setHeader('Set-Cookie', `ns_token=${token}; HttpOnly; Path=/; SameSite=Strict; Max-Age=${JWT_EXPIRY_HOURS * 3600}`); + return sendJson(res, 200, { token, username: user.username, role: user.role, firstLogin: !!user.firstLogin }); + } + if (req.method === 'POST' && p === '/api/auth/change-password') { + const auth = requireAuth(req, res); if (!auth) return; + const body = await readBody(req); + const { currentPassword, newPassword } = body; + if (!newPassword || newPassword.length < 8) return sendJson(res, 400, { error: 'new password must be at least 8 characters' }); + const users = await loadAuthUsers(); + const user = users.find(u => u.username === auth.username); + if (!user) return sendJson(res, 404, { error: 'user not found' }); + if (currentPassword) { + const ok = await verifyPassword(currentPassword, user.password); + if (!ok) return sendJson(res, 401, { error: 'current password is wrong' }); + } + user.password = await hashPassword(newPassword); + user.firstLogin = false; + await saveAuthUsers(users); + const token = jwtSign({ username: user.username, role: user.role }); + res.setHeader('Set-Cookie', `ns_token=${token}; HttpOnly; Path=/; SameSite=Strict; Max-Age=${JWT_EXPIRY_HOURS * 3600}`); + return sendJson(res, 200, { ok: true, token }); + } + if (req.method === 'POST' && p === '/api/auth/verify') { + const auth = requireAuth(req, res); if (!auth) return; + return sendJson(res, 200, { valid: true, username: auth.username, role: auth.role }); + } + if (req.method === 'POST' && p === '/api/auth/logout') { + res.setHeader('Set-Cookie', 'ns_token=; HttpOnly; Path=/; SameSite=Strict; Max-Age=0'); + return sendJson(res, 200, { ok: true }); + } + return sendJson(res, 404, { error: 'not found' }); + } + + // ---- auth gate: everything below /api/ requires a valid token ---- + if (AUTH_ENABLED && p.startsWith('/api/')) { + const auth = requireAuth(req, res); if (!auth) return; + req.authUser = auth; + } + // ---- agents / lead board ---- if (req.method === 'GET' && p === '/api/agents') { return sendJson(res, 200, await loadAgents()); @@ -4174,6 +4352,7 @@ const server = http.createServer(async (req, res) => { loadPersistedJobs(); loadKeys(); +ensureDefaultUser().catch(e => console.error('auth init error:', e.message)); // NEUROSPLOIT_WEB_HOST pins the bind address (the installer's launcher uses // 127.0.0.1); unset keeps the historical all-interfaces bind.