import Add from '@mui/icons-material/Add' import Block from '@mui/icons-material/Block' import Delete from '@mui/icons-material/Delete' import Download from '@mui/icons-material/Download' import Edit from '@mui/icons-material/Edit' import Refresh from '@mui/icons-material/Refresh' import Settings from '@mui/icons-material/Settings' import Key from '@mui/icons-material/Key' import UploadFile from '@mui/icons-material/UploadFile' import { Alert, Box, Button, Chip, IconButton, MenuItem, Stack, Tab, Table, TableBody, TableCell, TableHead, TableRow, Tabs, TextField, Tooltip, Typography, } from '@mui/material' import { useCallback, useEffect, useState } from 'react' import { when } from './BackupSummary.tsx' import CertificateDialog from './CertificateDialog.tsx' import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx' import ImportDialog from './ImportDialog.tsx' import IssuingCaDialog from './IssuingCaDialog.tsx' import TemplateDialog from './TemplateDialog.tsx' import Toolbar from './Toolbar.tsx' import EkuDialog from './EkuDialog.tsx' import PkiSettingsDialog, { PUBLISH_LABELS, ROOT_SOURCE_LABELS } from './PkiSettingsDialog.tsx' import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx' import { Pairs, Section } from './ServerPanel.tsx' import ServerCertificatePanel from './ServerCertificatePanel.tsx' import SetupCodeDialog from './SetupCodeDialog.tsx' import { ApiError, BUNDLE_SHAPE, CA_IMPORTED_SHAPE, CRL_IMPORTED_SHAPE, CSR_SHAPE, ISSUED_SHAPE, PFX_SHAPE, PKI_SETTINGS_SHAPE, PKI_SHAPE, REVOKED_SHAPE, TOKEN_SHAPE, BUILTIN_TEMPLATES, REVOKE_REASONS, request, type Pki, type PkiCertificate, type PkiIssuingCa, type PkiTemplate, } from './api.ts' import { saveFile } from './saveFile.ts' /** The tabs of the page: the server's HTTPS (ServerCertificatePanel), the root and the general information, the * templates, the extended key usages, the issuing CAs. */ type View = 'server' | 'root' | 'templates' | 'usages' | 'issuing' /** The localStorage keys of the layouts of the Root and the Issuing CAs tabs. */ const ROOT_LAYOUT_KEY = 'linux-manager-ui.certificates-root-layout' const ISSUING_LAYOUT_KEY = 'linux-manager-ui.certificates-issuing-layout' /** The CAs above the issuing CAs, whose certificates the Issuing CAs tab leaves out. */ const UPPER_CAS = ['root', 'upstream'] /** Where the root CRL came from. */ const CRL_SOURCE_LABELS: Record = { signed: 'signed by the server', uploaded: 'uploaded', fetched: 'fetched from Simple CA' } /** The note shown after a change, which the server applies when linux-manager-setup has run again. */ const APPLIED = 'The server applies the change in the background.' /** The colour of each state of an issuing CA and of a certificate. */ const STATE_COLORS: Record = { active: 'success', valid: 'success', pending: 'warning', off: 'default', missing: 'error', expired: 'default', revoked: 'error', } /** The labels of the revocation reasons. */ const REASON_LABELS: Record = { unspecified: 'Unspecified', key_compromise: 'Key compromise', affiliation_changed: 'Affiliation changed', superseded: 'Superseded', cessation_of_operation: 'Cessation of operation', privilege_withdrawn: 'Privilege withdrawn', } /** * The server's certificates in tabs: Server, the server's HTTPS (ServerCertificatePanel), shown first and also * while the PKI cannot be read; Root, the root CA with the general settings and the certificates of the issuing CAs; * Templates, the certificate templates, which are added, changed, removed and reset there; Extended key usages, the * built-in ones and the custom ones, which are added, changed and removed there; Issuing CAs, the built-in p2s, s2s and * servers and the custom CAs, which are added, changed and removed there, with the certificates of all of them, filtered * by CA. The warnings are above the tabs, and so are Issue and Settings but on the Server tab, whose Refresh reads it * again. Settings edits the pki section, Issue issues a certificate from a CSR or into a PFX file, a * certificate of another system or of the server is revoked, an issuing CA waiting for the offline root gives its CSR * and takes its signed certificate, the offline root takes its certificate and a CRL signed offline, and a Simple CA * root takes a setup code for a new token. The panels of the Root and the Issuing CAs tabs are on a PanelBoard per tab * whose layout is kept in the browser. */ export default function CertificatesPanel() { const [pki, setPki] = useState(null) const [error, setError] = useState(null) const [unavailable, setUnavailable] = useState(false) const [note, setNote] = useState(null) const [busy, setBusy] = useState(false) const [editing, setEditing] = useState(false) const [authority, setAuthority] = useState<{ name?: string } | null>(null) const [template, setTemplate] = useState<{ name?: string } | null>(null) const [usage, setUsage] = useState<{ name?: string } | null>(null) const [issuing, setIssuing] = useState(false) const [importing, setImporting] = useState(null) const [uploading, setUploading] = useState(false) const [entering, setEntering] = useState(false) const [confirm, setConfirm] = useState(null) const [filter, setFilter] = useState('') const [view, setView] = useState('server') const [serverRead, setServerRead] = useState(0) const rootBoard = useBoard(ROOT_LAYOUT_KEY) const issuingBoard = useBoard(ISSUING_LAYOUT_KEY) const refresh = useCallback(async () => { setBusy(true) try { setPki(await request('GET', '/ca', PKI_SHAPE)) setError(null) setUnavailable(false) } catch (caught) { const failure = caught as ApiError setPki(null) setUnavailable(failure.status === 404) setError(failure.message) } finally { setBusy(false) } }, []) useEffect(() => { void refresh() }, [refresh]) /** Saves the certificates a client trusts the CA with: the root alone, or an issuing CA followed by the root. */ async function downloadBundle(name: string) { try { const { pem } = await request<{ name: string; pem: string }>('GET', `/ca/bundle/${name}`, BUNDLE_SHAPE) saveFile(name === 'root' ? 'root-ca.pem' : `${name}-ca-bundle.pem`, pem, 'application/x-pem-file') setError(null) } catch (caught) { setError((caught as Error).message) } } async function downloadCsr(name: string) { try { const { csr, extensions } = await request<{ csr: string; extensions: string }>('GET', `/ca/issuing/${name}/csr`, CSR_SHAPE) saveFile(`${name}.csr`, csr, 'application/pkcs10') saveFile(`${name}-extensions.cnf`, extensions, 'text/plain') setError(null) } catch (caught) { setError((caught as Error).message) } } /** Writes the general-purpose issuing CAs: the current ones with name set to values, or without it when values is null. */ async function saveAuthority(name: string, values: PkiIssuingCa | null) { const { [name]: _current, ...others } = pki?.settings.issuing_cas ?? {} await request('PUT', '/ca', PKI_SETTINGS_SHAPE, { issuing_cas: values === null ? others : { ...others, [name]: values } }) setNote(APPLIED) await refresh() } /** Writes the templates of pki.templates: the current ones with name set to values, or without it when values is * null, which removes a template of the server's own or brings a built-in one back to its defaults. */ async function saveTemplate(name: string, values: PkiTemplate | null) { const { [name]: _current, ...others } = pki?.settings.templates ?? {} await request('PUT', '/ca', PKI_SETTINGS_SHAPE, { templates: values === null ? others : { ...others, [name]: values } }) setNote(APPLIED) await refresh() } /** Writes the custom extended key usages: the current ones with name set to oid, or without it when oid is null. */ async function saveUsage(name: string, oid: string | null) { const { [name]: _current, ...others } = pki?.settings.extended_key_usages ?? {} await request('PUT', '/ca', PKI_SETTINGS_SHAPE, { extended_key_usages: oid === null ? others : { ...others, [name]: oid } }) setNote(APPLIED) await refresh() } function removeUsage(name: string) { setConfirm({ title: 'Remove extended key usage', message: `Remove extended key usage ${name}? The server refuses while a template gives it; certificates issued with it keep it.`, confirmLabel: 'Remove', destructive: true, onCancel: () => setConfirm(null), onConfirm: () => { setConfirm(null) setBusy(true) saveUsage(name, null) .then(() => setError(null)) .catch((caught: Error) => setError(caught.message)) .finally(() => setBusy(false)) }, }) } function removeTemplate(name: string, builtin: boolean) { setConfirm({ title: builtin ? 'Reset template' : 'Remove template', message: builtin ? `Bring template ${name} back to its built-in options? The certificates issued afterwards follow them.` : `Remove template ${name}? The server refuses while an issuing CA issues it; certificates issued with it stay valid.`, confirmLabel: builtin ? 'Reset' : 'Remove', destructive: !builtin, onCancel: () => setConfirm(null), onConfirm: () => { setConfirm(null) setBusy(true) saveTemplate(name, null) .then(() => setError(null)) .catch((caught: Error) => setError(caught.message)) .finally(() => setBusy(false)) }, }) } function removeAuthority(name: string) { setConfirm({ title: 'Remove issuing CA', message: `Remove issuing CA ${name}? The server retires it. ${{ local: 'It revokes its certificate on the root CRL.', offline: 'Its certificate is revoked on the root CRL signed offline.', 'simple-ca': 'Its certificate is revoked in Simple CA.', }[pki?.settings.root ?? 'local']} Its certificates stay valid until they expire or are revoked.`, confirmLabel: 'Remove', destructive: true, onCancel: () => setConfirm(null), onConfirm: () => { setConfirm(null) setBusy(true) saveAuthority(name, null) .then(() => setError(null)) .catch((caught: Error) => setError(caught.message)) .finally(() => setBusy(false)) }, }) } function revoke(certificate: PkiCertificate) { let reason: string = REVOKE_REASONS[0] setConfirm({ title: 'Revoke certificate', message: `Revoke certificate ${certificate.serial} of ${certificate.subject}? The CRL of ${certificate.ca} lists it at once.${certificate.kind === 'router' ? ' The server issues itself a new one.' : ''}`, confirmLabel: 'Revoke', destructive: true, children: ( { reason = event.target.value }} > {REVOKE_REASONS.map((item) => {REASON_LABELS[item]})} ), onCancel: () => setConfirm(null), onConfirm: () => { setConfirm(null) setBusy(true) request<{ reissue: boolean }>('POST', `/ca/certificates/${certificate.serial}/revoke`, REVOKED_SHAPE, { reason }) .then((revoked) => { setError(null) setNote(revoked.reissue ? APPLIED : null) }) .catch((caught: Error) => setError(caught.message)) .finally(() => void refresh()) }, }) } const root = pki?.status.root const authorities = pki?.status.authorities ?? [] const authorityNames = [...new Set([...authorities.map((authority) => authority.name), ...(pki?.certificates ?? []).map((certificate) => certificate.ca).filter((name) => !UPPER_CAS.includes(name))])] const issuedCertificates = (pki?.certificates ?? []) .filter((certificate) => !UPPER_CAS.includes(certificate.ca) && (filter === '' || certificate.ca === filter)) /** The actions of an issuing CA waiting for the offline root: download its CSR and import its signed certificate. */ const pendingActions = (name: string) => ( <> void downloadCsr(name)}> setImporting(name)}> ) /** The active issuing CA a certificate the root issued belongs to, matched by its subject and expiry. */ const authorityOf = (certificate: PkiCertificate) => certificate.kind === 'ca' && certificate.state === 'valid' ? pki?.status.authorities.find((item) => item.state === 'active' && item.subject === certificate.subject && item.expires === certificate.expires) : undefined /** A table of certificates with their state and, for one of another system or of the server, Revoke; for an active * issuing CA, the download of its CA bundle. */ const certificateTable = (list: PkiCertificate[]) => ( Serial CA Kind Template Subject Alternative names Expires State Actions {list.length === 0 && ( None. )} {list.map((certificate) => ( {certificate.serial} {certificate.ca} {certificate.kind} {certificate.template ?? '-'} {certificate.subject} {certificate.sans.join(', ') || '-'} {when(certificate.expires)} {authorityOf(certificate) && ( void downloadBundle(authorityOf(certificate)!.name)}> )} {(certificate.kind === 'external' || certificate.kind === 'router') && certificate.state === 'valid' && ( revoke(certificate)}> )} ))}
) const rootPanels: BoardPanel[] = pki ? [ { id: 'root', title: 'Root CA', content: ( <> {root && ( <> ], ['Subject', root.subject ?? '-'], ['Expires', when(root.expires)], ['CRL valid until', when(root.crl_next_update)], ['CRL', CRL_SOURCE_LABELS[root.crl_source ?? ''] ?? '-'], ...(root.upstream ? [ ['Simple CA issuing CA', `${root.upstream.name}: ${root.upstream.subject}`], ['Its expiry', when(root.upstream.expires)], ['Its CRL valid until', when(root.upstream.crl_next_update)], ] as [string, string][] : []), ...(root.source === 'simple-ca' ? [['Token valid until', root.token_expires ? when(root.token_expires) : 'no token']] as [string, string][] : []), ]} /> {root.state === 'pending' && root.source === 'local' && ( The server creates it once a platform is chosen. )} {root.state === 'active' && ( )} {root.source === 'offline' && root.state === 'pending' && ( )} {root.source === 'offline' && root.state === 'active' && ( )} {root.source === 'simple-ca' && ( )} )} ), }, { id: 'general', title: 'General', content: ( PUBLISH_LABELS[item] ?? item).join('; ') || 'nowhere'], ['CA key', pki.settings.key], ['Lifetimes', `root ${pki.settings.root_days} days, issuing CAs ${pki.settings.ca_days} days`], ['CRLs', `issuing CAs ${pki.settings.crl_days} days, root ${pki.settings.root_crl_days} days`], ]} /> ), }, { id: 'certificates', title: 'Issuing CA certificates', wide: true, content: ( <> {certificateTable(pki.certificates.filter((certificate) => certificate.ca === 'root' || certificate.ca === 'upstream'))} {pki.status.retired.length > 0 && ( {`Retired: ${pki.status.retired.map((retired) => `${retired.name} (${when(retired.retired)})`).join(', ')}`} )} ), }, ] : [] const issuingPanels: BoardPanel[] = pki ? [ { id: 'authorities', title: 'Issuing CAs', wide: true, content: ( <> Name Common name State Expires CRL valid until Templates ACME Actions {authorities.map((authority) => ( {authority.name} {authority.builtin && } {authority.subject ?? authority.common_name} {when(authority.expires)} {when(authority.crl_next_update)} {authority.templates.join(', ')} {authority.acme_url ?? (authority.acme ? 'waits for the certificate' : '-')} {authority.state === 'pending' && pki.settings.root === 'offline' && pendingActions(authority.name)} {authority.state === 'active' && ( void downloadBundle(authority.name)}> )} {!authority.builtin && ( <> setAuthority({ name: authority.name })}> removeAuthority(authority.name)}> )} ))}
), }, { id: 'certificates', title: 'Certificates issued', wide: true, content: ( <> setFilter(event.target.value)}> All {authorityNames.map((name) => {name})} {certificateTable(issuedCertificates)} ), }, ] : [] return ( {view !== 'server' && ( <> )} {view === 'root' && } {view === 'issuing' && } {error && {error}} {note && setNote(null)}>{note}} {pki?.status.warnings.map((warning) => {warning})} setView(next)} sx={{ mb: 2, borderBottom: 1, borderColor: 'divider' }}> {pki && } {pki && } {pki && } {pki && } {view === 'server' && } {pki && view === 'root' && } {pki && view === 'templates' && (
Name Key Days Subject Key usage Extended key usage Alternative names Policies Issued by Actions {Object.entries(pki.templates).map(([name, values]) => { const builtin = (BUILTIN_TEMPLATES as readonly string[]).includes(name) const changed = pki.settings.templates[name] !== undefined return ( {name} {builtin && } {values.key} {values.days} {values.subject} {values.key_usage.join(', ')} {values.extended_key_usage.join(', ') || '-'} {values.sans.join(', ') || '-'} {values.policies.join(', ') || '-'} {pki.status.authorities.filter((item) => item.templates.includes(name)).map((item) => item.name).join(', ') || '-'} setTemplate({ name })}> {(!builtin || changed) && ( removeTemplate(name, builtin)}> {builtin ? : } )} ) })}
)} {pki && view === 'usages' && (
Name OID Given by Actions {Object.entries(pki.extended_key_usages).map(([name, usage]) => ( {name} {usage.builtin && } {usage.oid} {Object.entries(pki.templates).filter(([, values]) => values.extended_key_usage.includes(name)).map(([template]) => template).join(', ') || '-'} {!usage.builtin && ( <> setUsage({ name })}> removeUsage(name)}> )} ))}
)} {pki && view === 'issuing' && } {editing && pki && ( setEditing(false)} onSave={async (settings) => { await request('PUT', '/ca', PKI_SETTINGS_SHAPE, settings) setEditing(false) setNote(APPLIED) await refresh() }} /> )} {usage && pki && ( setUsage(null)} onSave={async (name, oid) => { await saveUsage(name, oid) setUsage(null) }} /> )} {template && pki && ( setTemplate(null)} onSave={async (name, values) => { await saveTemplate(name, values) setTemplate(null) }} /> )} {authority && pki && ( setAuthority(null)} onSave={async (name, values) => { await saveAuthority(name, values) setAuthority(null) }} /> )} {issuing && pki && ( setIssuing(false)} onSave={async (issue) => { if ('csr' in issue) { const issued = await request<{ serial: string; certificate: string; chain: string }>('POST', '/ca/certificates', ISSUED_SHAPE, issue) saveFile(`${issued.serial}.pem`, issued.certificate + issued.chain, 'application/x-pem-file') } else { const issued = await request<{ serial: string; pfx: string }>('POST', '/ca/certificates', PFX_SHAPE, issue) saveFile(`${issue.subject}.pfx`, Uint8Array.from(atob(issued.pfx), (character) => character.charCodeAt(0)), 'application/x-pkcs12') } setIssuing(false) await refresh() }} /> )} {importing && ( setImporting(null)} onSave={async (certificate) => { await request('PUT', importing === 'root' ? '/ca/root/certificate' : `/ca/issuing/${importing}/certificate`, CA_IMPORTED_SHAPE, { certificate }) setImporting(null) setNote(APPLIED) await refresh() }} /> )} {uploading && ( setUploading(false)} onSave={async (crl) => { await request('PUT', '/ca/root/crl', CRL_IMPORTED_SHAPE, { crl }) setUploading(false) await refresh() }} /> )} {entering && root && ( setEntering(false)} onSave={async (code) => { await request('PUT', '/ca/root/setup-code', TOKEN_SHAPE, { code }) setEntering(false) setNote(APPLIED) await refresh() }} /> )} {confirm && }
) }