231 lines
15 KiB
JavaScript
231 lines
15 KiB
JavaScript
import crypto from 'node:crypto';
|
|
import http from 'node:http';
|
|
import https from 'node:https';
|
|
|
|
const panelURL = process.env.SEA_PANEL_URL?.trim();
|
|
const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim();
|
|
const consoleURL = process.env.SEA_CONSOLE_URL?.trim();
|
|
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
|
|
if (!panelURL || !panelAPIKey || !consoleURL) process.exit(2);
|
|
const panelBase = new URL(panelURL);
|
|
const consoleBase = new URL(consoleURL);
|
|
const panelClient = panelBase.protocol === 'https:' ? https : http;
|
|
const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined;
|
|
const md5 = (value) => crypto.createHash('md5').update(value).digest('hex');
|
|
const q = (value) => `'${value.replaceAll("'", "'\\''")}'`;
|
|
const suffix = crypto.randomBytes(6).toString('hex');
|
|
const email = `certificate-${suffix}@seavhost.test`;
|
|
const password = `Sv-${crypto.randomBytes(18).toString('base64url')}9c`;
|
|
const dnsSecret = `svh-cloudflare-token-${crypto.randomBytes(18).toString('base64url')}`;
|
|
const dnsSecretUpdated = `svh-cloudflare-updated-${crypto.randomBytes(18).toString('base64url')}`;
|
|
const zoneID = crypto.randomBytes(16).toString('hex');
|
|
const runDirectory = `certificate-${suffix}`;
|
|
|
|
function authFields() {
|
|
const requestTime = Math.floor(Date.now() / 1000).toString();
|
|
return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) };
|
|
}
|
|
|
|
function panelForm(pathname, values) {
|
|
const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString());
|
|
return new Promise((resolve, reject) => {
|
|
const request = panelClient.request(new URL(pathname, panelBase), {
|
|
method: 'POST', agent: panelAgent, timeout: 30_000,
|
|
headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length },
|
|
}, (response) => {
|
|
let data = '';
|
|
response.setEncoding('utf8');
|
|
response.on('data', (chunk) => { data += chunk; });
|
|
response.on('end', () => {
|
|
if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`));
|
|
try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); }
|
|
});
|
|
});
|
|
request.on('timeout', () => request.destroy(new Error('panel request timed out')));
|
|
request.on('error', reject);
|
|
request.end(body);
|
|
});
|
|
}
|
|
|
|
async function runShell(name, shell, marker, attempts = 120) {
|
|
const task = await panelForm('/crontab', {
|
|
action: 'AddCrontab', name, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0',
|
|
sType: 'toShell', sBody: shell, sName: 'Temporary Sea vHost certificate verification', save: '0', backupTo: 'localhost',
|
|
});
|
|
if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary task');
|
|
const taskID = Number(task.id);
|
|
try {
|
|
const execution = await panelForm('/crontab', { action: 'StartTask', id: String(taskID) });
|
|
if (execution?.status === false || execution?.status === 'false') throw new Error('panel did not start temporary task');
|
|
let log = '';
|
|
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) });
|
|
log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log;
|
|
if (log.includes(marker) || log.includes('★[')) break;
|
|
}
|
|
if (!log.includes(marker)) throw new Error(`temporary task failed:\n${log.trim()}`);
|
|
return log;
|
|
} finally {
|
|
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
|
|
}
|
|
}
|
|
|
|
async function api(pathname, { method = 'GET', body, cookie, expected = [200], timeout = 30_000 } = {}) {
|
|
const response = await fetch(new URL(pathname, consoleBase), {
|
|
method, redirect: 'manual', signal: AbortSignal.timeout(timeout),
|
|
headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(cookie ? { Cookie: cookie } : {}) },
|
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
});
|
|
const text = await response.text();
|
|
let payload;
|
|
try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; }
|
|
if (!expected.includes(response.status)) throw new Error(`${method} ${pathname} returned HTTP ${response.status}: ${text.slice(0, 160)}`);
|
|
return { response, payload, text };
|
|
}
|
|
|
|
function cookieFrom(response) {
|
|
const header = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie');
|
|
return header?.split(';', 1)[0];
|
|
}
|
|
|
|
const dbParts = [
|
|
'mapfile -t control_db < <(python3 -c \'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\\(([^:]+):(\\d+)\\)/([^?]+)(?:\\?.*)?", d); assert m; print("\\n".join(m.groups()))\')',
|
|
'control_user="${control_db[0]}"; control_password="${control_db[1]}"; control_host="${control_db[2]}"; control_port="${control_db[3]}"; control_name="${control_db[4]}"',
|
|
'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi',
|
|
].join('\n');
|
|
|
|
const seedMarker = `certificate-seeded-${suffix}`;
|
|
const seedShell = [
|
|
'set -euo pipefail', `email=${q(email)}`, `password=${q(password)}`,
|
|
'php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; password_hash="$(TEST_PASSWORD="$password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"',
|
|
dbParts,
|
|
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\'; INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$email\',\'$email\',\'Certificate verification\',\'$password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"',
|
|
`printf '%s\n' ${q(seedMarker)}`,
|
|
].join('\n');
|
|
const cleanupMarker = `certificate-cleaned-${suffix}`;
|
|
const cleanupShell = [
|
|
'set -euo pipefail', `email=${q(email)}`, `run_directory=${q(runDirectory)}`, dbParts,
|
|
'project_root="$(MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --batch --skip-column-names --execute="SELECT root_path FROM projects ORDER BY id LIMIT 1")"; case "$project_root" in /www/wwwroot/seavHost/vHost/sv??????????) rmdir -- "$project_root/$run_directory" 2>/dev/null || true ;; *) exit 1 ;; esac',
|
|
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\';"',
|
|
`printf '%s\n' ${q(cleanupMarker)}`,
|
|
].join('\n');
|
|
|
|
function decodeLogValue(log, name) {
|
|
const value = log.match(new RegExp(`(?:^|\\n)${name}=([A-Za-z0-9+/=]+)`))?.[1];
|
|
if (!value) throw new Error(`certificate generator omitted ${name}`);
|
|
return Buffer.from(value, 'base64').toString('utf8');
|
|
}
|
|
|
|
let seeded = false;
|
|
let cookie;
|
|
let project;
|
|
let site;
|
|
let dnsCredentialID;
|
|
try {
|
|
await runShell(`Sea vHost certificate seed ${suffix}`, seedShell, seedMarker);
|
|
seeded = true;
|
|
const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: email, password } });
|
|
cookie = cookieFrom(login.response);
|
|
project = (await api('/api/v1/projects', { cookie })).payload?.projects?.[0];
|
|
if (!project?.id) throw new Error('temporary tenant has no project');
|
|
const created = await api(`/api/v1/projects/${project.id}/sites`, {
|
|
method: 'POST', cookie, expected: [201],
|
|
body: { name: `certificate-${suffix}`, runtime: 'PHP', version: project.version, runPath: `/${runDirectory}`, customDomain: '', autoSSL: false },
|
|
});
|
|
site = created.payload?.site;
|
|
if (!site?.id || !site?.domain) throw new Error('temporary certificate site was not created');
|
|
|
|
const generatedMarker = `certificate-generated-${suffix}`;
|
|
const generationShell = [
|
|
'set -euo pipefail', `domain=${q(site.domain)}`, 'work="$(mktemp -d /tmp/sea-vhost-certificate.XXXXXX)"; trap \'rm -rf -- "$work"\' EXIT',
|
|
'openssl ecparam -name prime256v1 -genkey -noout -out "$work/key.pem"; openssl req -x509 -new -key "$work/key.pem" -days 2 -subj "/CN=$domain" -addext "subjectAltName=DNS:$domain" -addext "basicConstraints=critical,CA:FALSE" -addext "keyUsage=critical,digitalSignature" -addext "extendedKeyUsage=serverAuth" -out "$work/cert.pem" >/dev/null 2>&1',
|
|
'openssl ecparam -name prime256v1 -genkey -noout -out "$work/wrong-domain-key.pem"; openssl req -x509 -new -key "$work/wrong-domain-key.pem" -days 2 -subj "/CN=wrong.example.invalid" -addext "subjectAltName=DNS:wrong.example.invalid" -addext "basicConstraints=critical,CA:FALSE" -addext "keyUsage=critical,digitalSignature" -addext "extendedKeyUsage=serverAuth" -out "$work/wrong-domain-cert.pem" >/dev/null 2>&1',
|
|
'openssl ecparam -name prime256v1 -genkey -noout -out "$work/wrong-key.pem"',
|
|
'printf "CERT_B64=%s\\n" "$(base64 -w0 "$work/cert.pem")"; printf "KEY_B64=%s\\n" "$(base64 -w0 "$work/key.pem")"; printf "WRONG_CERT_B64=%s\\n" "$(base64 -w0 "$work/wrong-domain-cert.pem")"; printf "WRONG_DOMAIN_KEY_B64=%s\\n" "$(base64 -w0 "$work/wrong-domain-key.pem")"; printf "WRONG_KEY_B64=%s\\n" "$(base64 -w0 "$work/wrong-key.pem")"',
|
|
`printf '%s\n' ${q(generatedMarker)}`,
|
|
].join('\n');
|
|
const generated = await runShell(`Sea vHost certificate generate ${suffix}`, generationShell, generatedMarker);
|
|
const certificate = decodeLogValue(generated, 'CERT_B64');
|
|
const privateKey = decodeLogValue(generated, 'KEY_B64');
|
|
const wrongCertificate = decodeLogValue(generated, 'WRONG_CERT_B64');
|
|
const wrongDomainKey = decodeLogValue(generated, 'WRONG_DOMAIN_KEY_B64');
|
|
const wrongKey = decodeLogValue(generated, 'WRONG_KEY_B64');
|
|
const manualPath = `/api/v1/projects/${project.id}/sites/${site.id}/certificate/manual`;
|
|
await api(manualPath, { method: 'PUT', cookie, expected: [422], body: { certificate: 'not-a-certificate', privateKey } });
|
|
await api(manualPath, { method: 'PUT', cookie, expected: [422], body: { certificate: wrongCertificate, privateKey: wrongDomainKey } });
|
|
await api(manualPath, { method: 'PUT', cookie, expected: [422], body: { certificate, privateKey: wrongKey } });
|
|
await api(manualPath, { method: 'PUT', cookie, expected: [422], body: { certificate, privateKey: '' } });
|
|
const installed = await api(manualPath, { method: 'PUT', cookie, body: { certificate, privateKey } });
|
|
if (installed.payload?.site?.sslStatus !== 'active') throw new Error('valid manual certificate did not become active');
|
|
await api(`/api/v1/projects/${project.id}/sites/${site.id}/certificate`, { method: 'DELETE', cookie });
|
|
|
|
const autoResult = await api(`/api/v1/projects/${project.id}/sites/${site.id}/certificate/auto`, {
|
|
method: 'POST', cookie, expected: [200, 422], timeout: 180_000,
|
|
});
|
|
const automation = await api(`/api/v1/projects/${project.id}/sites/${site.id}/certificate`, { cookie });
|
|
const autoSucceeded = autoResult.response.status === 200;
|
|
const http01FailureStatePersisted = autoSucceeded || (automation.payload?.automation?.mode === 'http-01' && Boolean(automation.payload?.automation?.lastError));
|
|
if (autoSucceeded) await api(`/api/v1/projects/${project.id}/sites/${site.id}/certificate`, { method: 'DELETE', cookie });
|
|
|
|
const createdCredential = await api('/api/v1/dns-credentials', {
|
|
method: 'POST', cookie, expected: [201], body: {
|
|
label: `Cloudflare test ${suffix}`, provider: 'cloudflare', zoneName: 'example.invalid', credential: { apiToken: dnsSecret, zoneId: zoneID },
|
|
},
|
|
});
|
|
dnsCredentialID = createdCredential.payload?.credential?.id;
|
|
if (!dnsCredentialID) throw new Error('DNS credential was not created');
|
|
const listed = await api('/api/v1/dns-credentials', { cookie });
|
|
if (listed.text.includes(dnsSecret) || listed.text.includes(zoneID) || !listed.payload?.credentials?.some((item) => item.id === dnsCredentialID)) {
|
|
throw new Error('DNS credential list leaked or omitted credential data');
|
|
}
|
|
const encryptedMarker = `dns-encrypted-${suffix}`;
|
|
const encryptedShell = [
|
|
'set -euo pipefail', `credential_id=${dnsCredentialID}`, `secret=${q(dnsSecret)}`, dbParts,
|
|
'found="$(MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --batch --skip-column-names --execute="SELECT IF(LOCATE(HEX(\'$secret\'),HEX(credential_ciphertext))=0,0,1) FROM dns_credentials WHERE id=$credential_id")"; test "$found" = 0',
|
|
`printf '%s\n' ${q(encryptedMarker)}`,
|
|
].join('\n');
|
|
await runShell(`Sea vHost DNS encryption ${suffix}`, encryptedShell, encryptedMarker);
|
|
|
|
const failedTest = await api(`/api/v1/dns-credentials/${dnsCredentialID}/test`, { method: 'POST', cookie, expected: [422], timeout: 60_000 });
|
|
if (failedTest.text.includes(dnsSecret) || failedTest.text.includes(zoneID)) throw new Error('DNS test failure leaked credentials');
|
|
const cooldown = await api(`/api/v1/dns-credentials/${dnsCredentialID}/test`, { method: 'POST', cookie, expected: [429] });
|
|
if (!cooldown.response.headers.get('retry-after')) throw new Error('DNS test cooldown omitted Retry-After');
|
|
const updated = await api(`/api/v1/dns-credentials/${dnsCredentialID}`, {
|
|
method: 'PUT', cookie, body: {
|
|
label: `Cloudflare updated ${suffix}`, provider: 'cloudflare', zoneName: 'example.invalid', credential: { apiToken: dnsSecretUpdated, zoneId: zoneID },
|
|
},
|
|
});
|
|
if (updated.payload?.credential?.testStatus !== 'untested' || updated.text.includes(dnsSecretUpdated)) throw new Error('DNS credential update was not safely reset');
|
|
await api(`/api/v1/dns-credentials/${dnsCredentialID}`, { method: 'DELETE', cookie, expected: [204] });
|
|
dnsCredentialID = undefined;
|
|
|
|
console.log(JSON.stringify({ status: http01FailureStatePersisted ? 'passed' : 'failed', checks: {
|
|
malformedCertificateRejected: true,
|
|
hostnameMismatchRejected: true,
|
|
mismatchedPrivateKeyRejected: true,
|
|
incompletePairRejected: true,
|
|
validManualCertificateInstalled: true,
|
|
manualCertificateDisabled: true,
|
|
http01AttemptCompleted: true,
|
|
http01FailureStatePersisted,
|
|
http01Issued: autoSucceeded,
|
|
dnsCredentialEncryptedAtRest: true,
|
|
dnsCredentialSecretsOmittedFromAPI: true,
|
|
dnsCredentialFailureDoesNotLeakSecret: true,
|
|
dnsCredentialCooldownEnforced: true,
|
|
dnsCredentialUpdateAndDelete: true,
|
|
}, http01Result: autoSucceeded ? 'issued' : 'failed_in_current_port_forwarding_environment' }, null, 2));
|
|
if (!http01FailureStatePersisted) process.exitCode = 1;
|
|
} finally {
|
|
if (dnsCredentialID && cookie) {
|
|
try { await api(`/api/v1/dns-credentials/${dnsCredentialID}`, { method: 'DELETE', cookie, expected: [204, 404] }); } catch { process.exitCode = 1; }
|
|
}
|
|
if (site?.id && project?.id && cookie) {
|
|
try { await api(`/api/v1/projects/${project.id}/sites/${site.id}`, { method: 'DELETE', cookie, expected: [204] }); } catch { process.exitCode = 1; }
|
|
}
|
|
if (seeded) {
|
|
try { await runShell(`Sea vHost certificate cleanup ${suffix}`, cleanupShell, cleanupMarker, 90); } catch { process.exitCode = 1; }
|
|
}
|
|
}
|