Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ config.json
!/plugins/snapin/
!/plugins/printer/
images
# The agent CA keys and certificates (custom.pkiDir). Never commit the keys.
/pki

################################################
# Dependencies
Expand Down
35 changes: 35 additions & 0 deletions api/controllers/agent/ca-file.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* The public CA files, at the paths FOG 1.6 serves them. The agent downloads
* ca.cert.pem to learn the server's CA (contract 4.4). No session is needed.
*
* The route names the file in its `file` option (config/routes.js):
* root.pem the root CA, PEM
* root.der the root CA, DER
* agent-ca-bundle.pem the agent CA, then the root
* A missing file answers 404.
*/
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');

module.exports = {
friendlyName: 'CA file',
description: 'Serve the root CA or the agent CA bundle.',
exits: {
success: {description: 'The file.'}
},
fn: async function () {
const res = this.res;
const file = this.req.options.file;
const source = file === 'root.der' ? 'root.pem' : file;
let data;
try {
data = fs.readFileSync(path.join(sails.config.custom.pkiDir, source));
if (file === 'root.der') data = new crypto.X509Certificate(data).raw;
} catch (unused) {
return res.sendStatus(404);
}
res.set('Content-Type', file === 'root.der' ? 'application/x-x509-ca-cert' : 'application/x-pem-file');
return res.send(data);
}
};
47 changes: 47 additions & 0 deletions api/helpers/agent/key-fingerprint.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* The key fingerprint of fog-agent enrollment: the lowercase hex sha256 of the
* public key's PEM text ("-----BEGIN PUBLIC KEY-----" ... "-----END PUBLIC
* KEY-----\n"). It is not the hash of the DER bytes. FOG 1.6 and the agent
* both hash the PEM text (contract section 0, item 1), so the same key gives
* the same value on both servers.
*
* Input: a CSR PEM or a certificate PEM.
* Exit invalid: the text is neither.
*
* Usage: let fp = sails.helpers.agent.keyFingerprint(pem) (sync)
*/
const crypto = require('crypto');
const x509 = require('@peculiar/x509');
const pki = require('../../lib/agent-pki');

module.exports = {
friendlyName: 'Key fingerprint',
description: 'Hash the public key PEM of a CSR or certificate with sha256.',
sync: true,
inputs: {
pem: {type: 'string', required: true, description: 'A CSR or a certificate, PEM text.'}
},
exits: {
success: {outputType: 'string', description: 'Lowercase hex sha256.'},
invalid: {description: 'The text is not a CSR or a certificate.'}
},
fn: function ({pem}, exits) {
let publicKey;
try {
if (pki.isCsrPem(pem)) {
// Node has no CSR parser. The SPKI bytes come from @peculiar/x509.
publicKey = crypto.createPublicKey({
key: Buffer.from(new x509.Pkcs10CertificateRequest(pem).publicKey.rawData),
format: 'der',
type: 'spki'
});
} else {
publicKey = new crypto.X509Certificate(pem).publicKey;
}
} catch (unused) {
return exits.invalid();
}
return exits.success(crypto.createHash('sha256')
.update(publicKey.export({type: 'spki', format: 'pem'})).digest('hex'));
}
};
104 changes: 104 additions & 0 deletions api/helpers/agent/sign-csr.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/**
* Sign a fog-agent CSR with the agent CA, as the FOG 1.6 signing helper does
* (fog-sign-node-cert agent): the server sets the subject, the CSR subject is
* ignored, and the certificate carries no SAN. The contract is
* briefs/research/2026-11-10-agent-enroll-contract.md section 4.2.
*
* Inputs:
* csrPem the CSR, PEM text (RSA or ECDSA key)
* hostId the host number, digits only (1 to 10)
*
* Output {leafPem, chainPem}. chainPem is the agent CA only, not the root.
*
* Exits (a caller maps them; the enroll brief maps notConfigured to 503):
* badHostId hostId is not 1 to 10 digits
* badCsr not a CSR, does not parse, or its self-signature fails
* notConfigured a CA file is missing from custom.pkiDir
* signFailed the signing failed, or a result does not verify
*
* The CA key is read from custom.pkiDir on each call.
*
* Usage: let {leafPem, chainPem} = await sails.helpers.agent.signCsr.with({csrPem, hostId})
*/
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const x509 = require('@peculiar/x509');
const pki = require('../../lib/agent-pki');

module.exports = {
friendlyName: 'Sign an agent CSR',
description: 'Issue a 365-day clientAuth certificate for an agent CSR from the agent CA.',
inputs: {
csrPem: {type: 'string', required: true, description: 'The CSR, PEM text.'},
hostId: {type: 'string', required: true, description: 'The host number: 1 to 10 digits.'}
},
exits: {
success: {outputType: 'ref', description: '{leafPem, chainPem}'},
badHostId: {description: 'hostId is not 1 to 10 digits.'},
badCsr: {description: 'The CSR is not valid, or its signature does not verify.'},
notConfigured: {description: 'The agent CA files are missing.'},
signFailed: {description: 'The signing or its self-check failed.'}
},
fn: async function ({csrPem, hostId}) {
// Same check as the 1.6 helper. It also keeps the subject text safe.
if (!/^[0-9]{1,10}$/.test(hostId)) throw 'badHostId';

let csr;
try {
if (!pki.isCsrPem(csrPem)) throw new Error('not a CSR');
csr = new x509.Pkcs10CertificateRequest(csrPem);
// Proof of possession: the CSR is signed by the key it carries.
if (!(await csr.verify())) throw new Error('bad signature');
} catch (unused) {
throw 'badCsr';
}

const dir = sails.config.custom.pkiDir;
const read = (name) => {
try {
return fs.readFileSync(path.join(dir, name), 'utf8');
} catch (unused) {
throw 'notConfigured';
}
};
const rootPem = read('root.pem');
const caPem = read('agent-ca.pem');
const caKeyPem = read('agent-ca.key');

// Do not sign under an agent CA that the root did not issue.
if (!pki.verifies(caPem, rootPem)) throw 'signFailed';

let leafPem;
try {
// The agent CA key signs leaves only, so it is imported with SHA-256.
const caKeys = await pki.importPair(crypto.createPrivateKey(caKeyPem), 'SHA-256');
const ca = new x509.X509Certificate(caPem);
const leaf = await x509.X509CertificateGenerator.create({
serialNumber: pki.randomSerial(),
subject: pki.subjectOf(`fog-agent host ${hostId}`, 'FOG Agent'),
issuer: ca.subjectName,
notBefore: new Date(),
notAfter: new Date(Date.now() + 365 * pki.DAY_MS),
signingAlgorithm: pki.RSA,
publicKey: csr.publicKey,
signingKey: caKeys.privateKey,
extensions: [
new x509.BasicConstraintsExtension(false, undefined, true),
new x509.KeyUsagesExtension(x509.KeyUsageFlags.digitalSignature, true),
new x509.ExtendedKeyUsageExtension([pki.CLIENT_AUTH], false),
await x509.SubjectKeyIdentifierExtension.create(csr.publicKey),
await x509.AuthorityKeyIdentifierExtension.create(ca, false)
]
});
leafPem = leaf.toString('pem') + '\n';
} catch (unused) {
throw 'signFailed';
}

// The 1.6 helper runs `openssl verify` before it returns. This is the same gate.
if (!pki.verifies(leafPem, caPem, true)) throw 'signFailed';

return {leafPem, chainPem: caPem};
}
};
58 changes: 58 additions & 0 deletions api/lib/agent-pki.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/**
* The crypto pieces that the agent PKI shares: tools/setup/pki.js (makes the
* CAs) and api/helpers/agent/* (sign a CSR, fingerprint a key) both use them.
* This is a plain module, not a Sails helper. Sails does not autoload api/lib.
*
* Certificates use @peculiar/x509. It signs through WebCrypto, where an
* imported RSA key carries its hash (see importPair).
*/
const crypto = require('crypto');
const x509 = require('@peculiar/x509');

const DAY_MS = 24 * 60 * 60 * 1000;
const CLIENT_AUTH = '1.3.6.1.5.5.7.3.2';
const RSA = {name: 'RSASSA-PKCS1-v1_5'};
const CSR_HEADER = '-----BEGIN CERTIFICATE REQUEST-----';

// Does the text carry the CSR header? (The 1.6 check, Enrollment.php:304.)
const isCsrPem = (text) => String(text).includes(CSR_HEADER);

// Hex serial: 16 random bytes, never zero, top bit clear so it stays positive.
const randomSerial = () => {
const bytes = crypto.randomBytes(16);
bytes[0] = (bytes[0] & 0x7f) || 1;
return bytes.toString('hex');
};

// The subject is built from typed parts, so no text can add a name component.
const subjectOf = (cn, ou) => new x509.Name([{CN: [cn]}, {O: ['FOG Project']}, {OU: [ou]}]);

// Import the key pair of a Node RSA key object for WebCrypto with one hash.
const importPair = async (privateKey, hash) => {
const alg = {name: RSA.name, hash};
const publicKey = crypto.createPublicKey(privateKey);
return {
privateKey: await crypto.webcrypto.subtle.importKey('pkcs8', privateKey.export({type: 'pkcs8', format: 'der'}), alg, false, ['sign']),
publicKey: await crypto.webcrypto.subtle.importKey('spki', publicKey.export({type: 'spki', format: 'der'}), alg, true, ['verify'])
};
};

/**
* Does `certPem` verify as issued by `issuerPem`? "Verifies" is Node's own
* X509Certificate: it asks whether the certificate was issued by the issuer,
* and checks the signature. For a leaf (`leaf` true) it also needs the
* clientAuth extended key usage and `ca` false. Any parse error is false.
*/
const verifies = (certPem, issuerPem, leaf) => {
try {
const cert = new crypto.X509Certificate(certPem);
const issuer = new crypto.X509Certificate(issuerPem);
if (!cert.checkIssued(issuer) || !cert.verify(issuer.publicKey)) return false;
if (leaf && (cert.ca || !(cert.keyUsage || []).includes(CLIENT_AUTH))) return false;
return true;
} catch (unused) {
return false;
}
};

module.exports = {DAY_MS, CLIENT_AUTH, RSA, isCsrPem, randomSerial, subjectOf, importPair, verifies};
9 changes: 9 additions & 0 deletions config/custom.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,17 @@
* https://sailsjs.com/config/custom
*/

const path = require('path');

module.exports.custom = {

// Certificate authority files for fog-agent enrollment: root.pem/.key,
// agent-ca.pem/.key and agent-ca-bundle.pem. tools/setup/pki.js makes them.
// The CA keys sit here, so the folder must be readable only by the user that
// runs fog-node. path.join keeps it valid on any OS. config/local.js may
// override it (the setup tools carry that override forward).
pkiDir: path.join(__dirname, '..', 'pki'),

// Image store: one folder per image -> <imageStorePath>/<image>/<partition>.img.
// Single source of truth for the deploy streamer, dashboard/hwinfo disk usage,
// and the image-store scan. Matches FOG's storageLocation (default /images).
Expand Down
3 changes: 3 additions & 0 deletions config/policies.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ module.exports.policies = {
// iPXE boot script is public (PXE machines have no session)
'boot': true,

// The CA files are public: the agent fetches them before it has a session
'agent/ca-file': true,

// System info
'system/info': true,
'system/bandwidth': true,
Expand Down
5 changes: 5 additions & 0 deletions config/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,11 @@ module.exports.routes = {
'GET /boot.ipxe': {action: 'boot'},
'GET /boot': {action: 'boot'},

// Public CA files for fog-agent, at the FOG 1.6 paths (the file is in `file`).
'GET /management/other/ca.cert.pem': {action: 'agent/ca-file', file: 'root.pem'},
'GET /management/other/ca.cert.der': {action: 'agent/ca-file', file: 'root.der'},
'GET /management/other/agent-ca-bundle.pem': {action: 'agent/ca-file', file: 'agent-ca-bundle.pem'},

// Host Views
'GET /hosts': {action: 'pages/list/hosts'},
'GET /hosts/create': {action: 'pages/create/hosts'},
Expand Down
Loading
Loading