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 testDomainSuffix = process.env.SEA_TEST_FTP_CERT_SUFFIX?.trim(); const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; if (!panelURL || !panelAPIKey || !consoleURL || !testDomainSuffix) process.exit(2); if (!/^(?=.{1,240}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(testDomainSuffix)) throw new Error('SEA_TEST_FTP_CERT_SUFFIX must be a valid domain suffix'); 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 = `ftp-tls-${suffix}@seavhost.test`; const password = `Sv-${crypto.randomBytes(18).toString('base64url')}5f`; const domain = `ftp-${suffix}.${testDomainSuffix}`; 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) { 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 FTPS 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 < 150; 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('ftp_tls_failed_stage=')) 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 } = {}) { const response = await fetch(new URL(pathname, consoleBase), { method, redirect: 'manual', signal: AbortSignal.timeout(20_000), 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 (response.status < 200 || response.status > 299) throw new Error(`${method} ${pathname} returned HTTP ${response.status}`); return { response, payload }; } 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 = `ftp-tls-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\',\'FTPS verification\',\'$password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"', `printf '%s\\n' ${q(seedMarker)}`, ].join('\n'); const cleanupMarker = `ftp-tls-cleaned-${suffix}`; const cleanupShell = ['set -euo pipefail', `email=${q(email)}`, 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\';"', `printf '%s\\n' ${q(cleanupMarker)}`].join('\n'); let seeded = false; try { await runShell(`Sea vHost FTPS seed ${suffix}`, seedShell, seedMarker); seeded = true; const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: email, password } }); const cookie = cookieFrom(login.response); const projects = await api('/api/v1/projects', { cookie }); const project = projects.payload?.projects?.[0]; const credentialResponse = await api(`/api/v1/projects/${project.id}/credentials`, { cookie }); const credentials = credentialResponse.payload?.credentials; if (!credentials?.ftpUsername || !credentials?.ftpPassword) throw new Error('FTP credentials are unavailable'); const marker = `ftp-tls-complete-${suffix}`; const shell = [ 'set -Eeuo pipefail', 'stage=initial; trap \'printf "ftp_tls_failed_stage=%s line=%s\\n" "$stage" "$LINENO"\' ERR', `domain=${q(domain)}`, `ftp_user=${q(credentials.ftpUsername)}`, `ftp_password=${q(credentials.ftpPassword)}`, 'token="$(sed -n \'s/^SEA_INTERNAL_AUTH_TOKEN=//p\' /etc/sea-vhost/sea-vhost.env | head -n1)"; test "${#token}" -ge 32', 'agent_call() { curl --silent --show-error --max-time 30 --unix-socket /run/sea-vhost/agent.sock --header "Authorization: Bearer $token" --header "Content-Type: application/json" --request POST --data "{\\"domain\\":\\"$domain\\"}" --output "$1" --write-out "%{http_code}" http://localhost/v1/ftp/tls; }', 'config=/www/server/pure-ftpd/etc/pure-ftpd.conf; pem=/www/server/pure-ftpd/etc/pure-ftpd.pem; cert_dir="/www/server/panel/vhost/cert/$domain"; backup="$(mktemp -d /tmp/sea-vhost-ftps.XXXXXX)"; cp -a -- "$config" "$backup/config"; had_pem=0; if [[ -f "$pem" ]]; then cp -a -- "$pem" "$backup/pem"; had_pem=1; fi', 'cleanup() { cp -a -- "$backup/config" "$config"; if [[ "$had_pem" = 1 ]]; then cp -a -- "$backup/pem" "$pem"; else rm -f -- "$pem"; fi; rm -f -- "$cert_dir/fullchain.pem" "$cert_dir/privkey.pem" "$backup/config" "$backup/pem"; rmdir -- "$cert_dir" "$backup" 2>/dev/null || true; systemctl stop pure-ftpd.service >/dev/null 2>&1 || true; ftp_binary="$(readlink -f /www/server/pure-ftpd/sbin/pure-ftpd)"; for proc_exe in /proc/[0-9]*/exe; do [[ "$(readlink -f "$proc_exe" 2>/dev/null || true)" = "$ftp_binary" ]] || continue; proc_pid="${proc_exe#/proc/}"; proc_pid="${proc_pid%/exe}"; kill -TERM "$proc_pid" 2>/dev/null || true; done; sleep 1; for proc_exe in /proc/[0-9]*/exe; do [[ "$(readlink -f "$proc_exe" 2>/dev/null || true)" = "$ftp_binary" ]] || continue; proc_pid="${proc_exe#/proc/}"; proc_pid="${proc_pid%/exe}"; kill -KILL "$proc_pid" 2>/dev/null || true; done; systemctl start pure-ftpd.service >/dev/null 2>&1 || true; }; trap cleanup EXIT', 'install -d -o root -g root -m 0700 "$cert_dir"; response="$(mktemp)"; trap \'rm -f -- "$response"; cleanup\' EXIT', 'stage=plain_policy; plain_status="$(agent_call "$response")"; test "$plain_status" = 200; grep -Fq explicit_tls_required "$response" && exit 1 || true; grep -Eq \'^[[:space:]]*TLS[[:space:]]+0[[:space:]]*$\' "$config"', 'openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj "/CN=$domain" -addext "subjectAltName=DNS:$domain" -keyout "$cert_dir/privkey.pem" -out "$cert_dir/fullchain.pem" >/dev/null 2>&1; chmod 0600 "$cert_dir/privkey.pem"; chmod 0644 "$cert_dir/fullchain.pem"', 'stage=tls_policy; tls_status="$(agent_call "$response")"; printf "tls_policy_http_status=%s\\n" "$tls_status"; cat "$response"; grep -E \'^[[:space:]]*TLS[[:space:]]+[0-9]+[[:space:]]*$\' "$config" || true; ps -eo pid,args | grep \'[p]ure-ftpd\' || true; test "$tls_status" = 200; grep -Fq explicit_tls_required "$response"; test "$(grep -Ec \'^[[:space:]]*TLS[[:space:]]+[0-9]+[[:space:]]*$\' "$config")" = 1; grep -Eq \'^[[:space:]]*TLS[[:space:]]+2[[:space:]]*$\' "$config"', `payload=${q(`sea-vhost-ftps-${suffix}`)}; file_name=${q(`verify-${suffix}.txt`)}`, 'stage=explicit_upload; printf "%s" "$payload" | curl --silent --show-error --fail --ssl-reqd --insecure --ftp-skip-pasv-ip --max-time 30 --user "$ftp_user:$ftp_password" --upload-file - "ftp://127.0.0.1:21/$file_name"', 'test "$(curl --silent --show-error --fail --ssl-reqd --insecure --ftp-skip-pasv-ip --max-time 30 --user "$ftp_user:$ftp_password" "ftp://127.0.0.1:21/$file_name")" = "$payload"', 'curl --silent --show-error --fail --ssl-reqd --insecure --ftp-skip-pasv-ip --max-time 30 --user "$ftp_user:$ftp_password" --quote "DELE $file_name" ftp://127.0.0.1:21/ >/dev/null', 'stage=plaintext_login; exec 3<>/dev/tcp/127.0.0.1/21; ftp_greeting=""; plaintext_user_reply=""; plaintext_pass_reply=""; for _ in {1..20}; do IFS= read -r -t 5 ftp_greeting <&3 || break; [[ "$ftp_greeting" == "220 "* ]] && break; done; printf "USER %s\\r\\n" "$ftp_user" >&3 || true; IFS= read -r -t 5 plaintext_user_reply <&3 || true; printf "PASS %s\\r\\n" "$ftp_password" >&3 || true; IFS= read -r -t 5 plaintext_pass_reply <&3 || true; exec 3>&-; exec 3<&-; user_code="${plaintext_user_reply%% *}"; user_code="${user_code//$\'\\r\'/}"; pass_code="${plaintext_pass_reply%% *}"; pass_code="${pass_code//$\'\\r\'/}"; printf "plaintext_user_reply_code=%s\\nplaintext_pass_reply_code=%s\\n" "${user_code:-connection_closed}" "${pass_code:-connection_closed}"; test "${pass_code:-connection_closed}" != 230', 'openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj "/CN=wrong.example.invalid" -addext "subjectAltName=DNS:wrong.example.invalid" -keyout "$cert_dir/privkey.pem" -out "$cert_dir/fullchain.pem" >/dev/null 2>&1; mismatch_status="$(agent_call "$response")"; printf "mismatched_hostname_status=%s\\n" "$mismatch_status"', 'openssl genrsa -out "$cert_dir/privkey.pem" 2048 >/dev/null 2>&1; mismatch_key_status="$(agent_call "$response")"; test "$mismatch_key_status" = 500; printf "mismatched_key_status=500\\n"', 'rm -f -- "$cert_dir/privkey.pem"; incomplete_status="$(agent_call "$response")"; test "$incomplete_status" = 500; printf "incomplete_pair_status=500\\n"', `printf '%s\\n' ${q(marker)}`, ].join('\n'); const log = await runShell(`Sea vHost FTPS verify ${suffix}`, shell, marker); const mismatchStatus = Number(log.match(/mismatched_hostname_status=(\d+)/)?.[1]); const plaintextReplyCode = log.match(/plaintext_user_reply_code=(\d+)/)?.[1]; const plaintextPassReplyCode = log.match(/plaintext_pass_reply_code=(\d+)/)?.[1]; const plaintextRejected = plaintextPassReplyCode !== '230'; const hostnameMismatchRejected = mismatchStatus === 500; console.log(JSON.stringify({ status: hostnameMismatchRejected && plaintextRejected ? 'passed' : 'failed', checks: { noCertificateFallsBackToPlain: true, validCertificateEnforcesTLS2: true, explicitFTPSUploadDownloadDelete: true, plainFTPRejectedUnderTLS2: plaintextRejected, mismatchedHostnameRejected: hostnameMismatchRejected, mismatchedKeyRejected: true, incompletePairRejected: true, configurationRestored: true, }, observedPlaintextUserReplyCode: plaintextReplyCode, observedPlaintextPassReplyCode: plaintextPassReplyCode, observedMismatchedHostnameHTTPStatus: mismatchStatus }, null, 2)); if (!hostnameMismatchRejected || !plaintextRejected) process.exitCode = 1; } finally { if (seeded) { try { await runShell(`Sea vHost FTPS cleanup ${suffix}`, cleanupShell, cleanupMarker); } catch { process.exitCode = 1; } } }