@lethevimlet/sshift 1.8.0 → 1.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -5
- package/package.json +1 -1
- package/src/server/endpoints/rest/system.js +17 -12
- package/src/server/index.js +26 -140
- package/src/server/utils/certs.js +314 -0
- package/src/webapp/css/style.css +52 -18
- package/src/webapp/index.html +119 -104
- package/src/webapp/js/app.js +96 -2
- package/src/webapp/js/mobile-terminal.js +105 -18
package/README.md
CHANGED
|
@@ -186,19 +186,21 @@ See [Configuration](docs/configuration.md) for details.
|
|
|
186
186
|
|
|
187
187
|
When accessing sshift from a LAN IP (e.g., `https://192.168.1.50:8022`), browsers show "Not Secure" warnings because the self-signed certificate is not trusted. This also blocks PWA installation, which requires a trusted secure context.
|
|
188
188
|
|
|
189
|
-
### Recommended: Trust the Auto-Generated
|
|
189
|
+
### Recommended: Trust the Auto-Generated Local CA
|
|
190
190
|
|
|
191
|
-
sshift
|
|
191
|
+
On first run sshift creates its own small certificate authority (CA) and signs its HTTPS certificate with it. Both live in `~/.local/share/sshift/` and survive updates. Trust the CA once per device and every certificate sshift issues afterwards (new IPs, renewals) is accepted automatically:
|
|
192
192
|
|
|
193
|
-
1. **Download the certificate** — visit `https://<your-sshift-host>:8022/api/cert`
|
|
193
|
+
1. **Download the CA certificate** — click **Download CA Certificate** in Settings → Security & Connection Info, visit `https://<your-sshift-host>:8022/api/cert` (works over plain `http://` too), or copy `~/.local/share/sshift/ssl-ca-cert.pem` from the server
|
|
194
194
|
2. **Add it to your device's trusted root store:**
|
|
195
195
|
- **Windows:** Double-click the file → Install Certificate → Local Machine → Trusted Root Certification Authorities
|
|
196
196
|
- **macOS:** Double-click the file → Add to Keychain → Set "Always Trust" in Keychain Access
|
|
197
197
|
- **Linux:** Copy to `/usr/local/share/ca-certificates/` and run `sudo update-ca-certificates`
|
|
198
|
-
- **Android:** Settings → Security → Install from
|
|
198
|
+
- **Android (Chrome/Brave):** Settings → Security & privacy → More security settings → Encryption & credentials → Install a certificate → **CA certificate** → pick `sshift-ca.crt` from Downloads
|
|
199
199
|
- **iOS:** Send via AirDrop/email → Open → Install profile → Settings → General → About → Certificate Trust Settings → Enable full trust
|
|
200
200
|
|
|
201
|
-
After trusting the
|
|
201
|
+
After trusting the CA, the "Not Secure" warning will disappear and PWA installation will work.
|
|
202
|
+
|
|
203
|
+
> Upgrading from a version before 1.8.1: the old certificate was a plain self-signed one that Android refuses to install as a CA. It is replaced by the CA-signed one on first start, so re-download and install the CA once.
|
|
202
204
|
|
|
203
205
|
### Using Your Own Certificate
|
|
204
206
|
|
package/package.json
CHANGED
|
@@ -6,8 +6,7 @@ const fs = require('fs');
|
|
|
6
6
|
const path = require('path');
|
|
7
7
|
const { getDataDir, getCertPath, getKeyPath, getConfigPath } = require('../../utils/config');
|
|
8
8
|
|
|
9
|
-
const SSL_CERT_FILE = '
|
|
10
|
-
const SSL_KEY_FILE = 'ssl-key.pem';
|
|
9
|
+
const { SSL_CERT_FILE, SSL_KEY_FILE, SSL_CA_CERT_FILE } = require('../../utils/certs');
|
|
11
10
|
const UPDATE_MARKER_FILE = '.updating';
|
|
12
11
|
|
|
13
12
|
/**
|
|
@@ -186,29 +185,32 @@ function registerSystemEndpoints(app, io) {
|
|
|
186
185
|
});
|
|
187
186
|
});
|
|
188
187
|
|
|
189
|
-
// API: Download
|
|
188
|
+
// API: Download the local CA certificate (the file to install on devices).
|
|
189
|
+
// Served as application/x-x509-ca-cert so Android/Brave offer to install
|
|
190
|
+
// it as a CA credential. Also reachable over plain HTTP (see index.js).
|
|
190
191
|
app.get('/api/cert', (req, res) => {
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
192
|
+
if (getCertPath() && getKeyPath()) {
|
|
193
|
+
return res.status(404).json({ error: 'A custom certificate is configured; obtain its CA from your administrator' });
|
|
194
|
+
}
|
|
195
|
+
const caCertPath = path.join(getDataDir(), SSL_CA_CERT_FILE);
|
|
196
|
+
if (!fs.existsSync(caCertPath)) {
|
|
195
197
|
return res.status(404).json({ error: 'Certificate not found' });
|
|
196
198
|
}
|
|
197
199
|
|
|
198
|
-
res.setHeader('Content-Type', 'application/x-
|
|
200
|
+
res.setHeader('Content-Type', 'application/x-x509-ca-cert');
|
|
199
201
|
res.setHeader('Content-Disposition', 'attachment; filename="sshift-ca.crt"');
|
|
200
|
-
|
|
202
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
203
|
+
fs.createReadStream(caCertPath).pipe(res);
|
|
201
204
|
});
|
|
202
205
|
|
|
203
206
|
// API: Get security context info
|
|
204
207
|
app.get('/api/security-info', (req, res) => {
|
|
205
208
|
const dataDir = getDataDir();
|
|
206
|
-
const
|
|
207
|
-
const hasCert = fs.existsSync(
|
|
209
|
+
const usesCustomCert = !!(getCertPath() && getKeyPath());
|
|
210
|
+
const hasCert = !usesCustomCert && fs.existsSync(path.join(dataDir, SSL_CA_CERT_FILE));
|
|
208
211
|
const protocol = req.protocol;
|
|
209
212
|
const isSecure = req.secure || protocol === 'https';
|
|
210
213
|
const isLocalhost = req.hostname === 'localhost' || req.hostname === '127.0.0.1' || req.hostname === '::1';
|
|
211
|
-
const usesCustomCert = !!(getCertPath() && getKeyPath());
|
|
212
214
|
|
|
213
215
|
res.json({
|
|
214
216
|
isSecure,
|
|
@@ -225,6 +227,7 @@ function registerSystemEndpoints(app, io) {
|
|
|
225
227
|
const dataDir = getDataDir();
|
|
226
228
|
const selfSignedCertPath = path.join(dataDir, SSL_CERT_FILE);
|
|
227
229
|
const selfSignedKeyPath = path.join(dataDir, SSL_KEY_FILE);
|
|
230
|
+
const caCertPath = path.join(dataDir, SSL_CA_CERT_FILE);
|
|
228
231
|
const customCertPath = getCertPath();
|
|
229
232
|
const customKeyPath = getKeyPath();
|
|
230
233
|
const usesCustomCert = !!(customCertPath && customKeyPath);
|
|
@@ -234,6 +237,8 @@ function registerSystemEndpoints(app, io) {
|
|
|
234
237
|
dataDir,
|
|
235
238
|
certPath: usesCustomCert ? customCertPath : selfSignedCertPath,
|
|
236
239
|
keyPath: usesCustomCert ? customKeyPath : selfSignedKeyPath,
|
|
240
|
+
caCertPath: usesCustomCert ? null : caCertPath,
|
|
241
|
+
certType: usesCustomCert ? 'Custom' : 'Local CA-signed',
|
|
237
242
|
usesCustomCert
|
|
238
243
|
});
|
|
239
244
|
});
|
package/src/server/index.js
CHANGED
|
@@ -21,11 +21,11 @@ const https = require('https');
|
|
|
21
21
|
const fs = require('fs');
|
|
22
22
|
const path = require('path');
|
|
23
23
|
const socketIO = require('socket.io');
|
|
24
|
-
const
|
|
24
|
+
const { ensureLocalCertificates } = require('./utils/certs');
|
|
25
25
|
const httpolyglot = require('httpolyglot');
|
|
26
26
|
|
|
27
27
|
// Import utilities
|
|
28
|
-
const { ensureConfig, loadConfig, getPort, getBindAddress, getEnableHttps, getHttpRedirect, getCertPath, getKeyPath, getDataDir,
|
|
28
|
+
const { ensureConfig, loadConfig, getPort, getBindAddress, getEnableHttps, getHttpRedirect, getCertPath, getKeyPath, getDataDir, isPasswordSet, USER_INSTALL_DIR, migrateLegacyPackageConfig } = require('./utils/config');
|
|
29
29
|
|
|
30
30
|
// Import services
|
|
31
31
|
const { sshManager, sftpManager } = require('./services');
|
|
@@ -39,14 +39,16 @@ const pluginManager = require('./plugins/plugin-manager');
|
|
|
39
39
|
// Import endpoints
|
|
40
40
|
const { rest, ws } = require('./endpoints');
|
|
41
41
|
|
|
42
|
-
const SSL_CERT_FILE = 'ssl-cert.pem';
|
|
43
|
-
const SSL_KEY_FILE = 'ssl-key.pem';
|
|
44
|
-
|
|
45
42
|
/**
|
|
46
|
-
* Get SSL credentials
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
43
|
+
* Get SSL credentials.
|
|
44
|
+
*
|
|
45
|
+
* Custom certPath/keyPath from config win. Otherwise a local CA and a
|
|
46
|
+
* CA-signed server certificate are kept in the user-space data directory
|
|
47
|
+
* (see utils/certs.js): the CA is created once and survives npm updates
|
|
48
|
+
* and Docker recreation (when /data is a volume); the server certificate
|
|
49
|
+
* is re-issued from it whenever it is missing, self-signed (pre-1.8.1
|
|
50
|
+
* installs), expiring or no longer covers the current hostname/IPs.
|
|
51
|
+
* @returns {Promise<Object>} Certificate chain and private key
|
|
50
52
|
*/
|
|
51
53
|
async function getSSLCredentials() {
|
|
52
54
|
const customCertPath = getCertPath();
|
|
@@ -63,142 +65,23 @@ async function getSSLCredentials() {
|
|
|
63
65
|
};
|
|
64
66
|
} catch (err) {
|
|
65
67
|
console.error('[HTTPS] Failed to read custom certificate files:', err.message);
|
|
66
|
-
console.error('[HTTPS] Falling back to
|
|
68
|
+
console.error('[HTTPS] Falling back to the local CA-signed certificate');
|
|
67
69
|
}
|
|
68
70
|
} else if (customCertPath || customKeyPath) {
|
|
69
|
-
console.warn('[HTTPS] Both certPath and keyPath must be set in config. Only one was provided; falling back to
|
|
71
|
+
console.warn('[HTTPS] Both certPath and keyPath must be set in config. Only one was provided; falling back to the local CA-signed certificate.');
|
|
70
72
|
}
|
|
71
73
|
|
|
72
74
|
const dataDir = getDataDir();
|
|
73
|
-
const
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
if (fs.existsSync(certPath) && fs.existsSync(keyPath)) {
|
|
77
|
-
console.log('[HTTPS] Reusing persisted SSL certificate from', dataDir);
|
|
78
|
-
try {
|
|
79
|
-
const cert = fs.readFileSync(certPath, 'utf8');
|
|
80
|
-
const key = fs.readFileSync(keyPath, 'utf8');
|
|
81
|
-
if (!certIncludesOrg(cert)) {
|
|
82
|
-
console.log('[HTTPS] Existing certificate lacks organizationName, regenerating...');
|
|
83
|
-
} else {
|
|
84
|
-
return { cert, key };
|
|
85
|
-
}
|
|
86
|
-
} catch (err) {
|
|
87
|
-
console.warn('[HTTPS] Failed to read persisted certificate, regenerating:', err.message);
|
|
88
|
-
}
|
|
89
|
-
} else {
|
|
90
|
-
// Migrate from legacy (package) directory if certs exist there
|
|
91
|
-
const legacyDir = getLegacyDataDir();
|
|
92
|
-
if (legacyDir) {
|
|
93
|
-
const legacyCert = path.join(legacyDir, SSL_CERT_FILE);
|
|
94
|
-
const legacyKey = path.join(legacyDir, SSL_KEY_FILE);
|
|
95
|
-
if (fs.existsSync(legacyCert) && fs.existsSync(legacyKey)) {
|
|
96
|
-
console.log('[HTTPS] Migrating SSL certificate from', legacyDir, 'to', dataDir);
|
|
97
|
-
try {
|
|
98
|
-
if (!fs.existsSync(dataDir)) {
|
|
99
|
-
fs.mkdirSync(dataDir, { recursive: true });
|
|
100
|
-
}
|
|
101
|
-
const certData = fs.readFileSync(legacyCert, 'utf8');
|
|
102
|
-
const keyData = fs.readFileSync(legacyKey, 'utf8');
|
|
103
|
-
fs.writeFileSync(certPath, certData, { mode: 0o600 });
|
|
104
|
-
fs.writeFileSync(keyPath, keyData, { mode: 0o600 });
|
|
105
|
-
console.log('[HTTPS] SSL certificate migrated to user-space directory');
|
|
106
|
-
if (certIncludesOrg(certData)) {
|
|
107
|
-
return { cert: certData, key: keyData };
|
|
108
|
-
}
|
|
109
|
-
console.log('[HTTPS] Migrated certificate lacks organizationName, regenerating...');
|
|
110
|
-
} catch (err) {
|
|
111
|
-
console.warn('[HTTPS] Failed to migrate certificate:', err.message);
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
const creds = await generateSelfSignedCert();
|
|
118
|
-
|
|
119
|
-
try {
|
|
120
|
-
if (!fs.existsSync(dataDir)) {
|
|
121
|
-
fs.mkdirSync(dataDir, { recursive: true });
|
|
122
|
-
}
|
|
123
|
-
fs.writeFileSync(certPath, creds.cert, { mode: 0o600 });
|
|
124
|
-
fs.writeFileSync(keyPath, creds.key, { mode: 0o600 });
|
|
125
|
-
console.log('[HTTPS] SSL certificate persisted to', dataDir);
|
|
126
|
-
} catch (err) {
|
|
127
|
-
console.warn('[HTTPS] Failed to persist certificate:', err.message);
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
return creds;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
* Check if a PEM certificate includes an organizationName (O=) attribute.
|
|
135
|
-
* @param {string} certPem - PEM-encoded certificate
|
|
136
|
-
* @returns {boolean} True if O=sshift is present
|
|
137
|
-
*/
|
|
138
|
-
function certIncludesOrg(certPem) {
|
|
139
|
-
try {
|
|
140
|
-
const { X509Certificate } = require('crypto');
|
|
141
|
-
const x509 = new X509Certificate(certPem);
|
|
142
|
-
return /O=sshift/i.test(x509.subject);
|
|
143
|
-
} catch {
|
|
144
|
-
return false;
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/**
|
|
149
|
-
* Generate self-signed SSL certificates using selfsigned package (pure JS, no OpenSSL dependency)
|
|
150
|
-
* @returns {Promise<Object>} Certificate and private key
|
|
151
|
-
*/
|
|
152
|
-
async function generateSelfSignedCert() {
|
|
153
|
-
console.log('[HTTPS] Generating self-signed certificate...');
|
|
154
|
-
|
|
155
|
-
const os = require('os');
|
|
156
|
-
|
|
157
|
-
const interfaces = os.networkInterfaces();
|
|
158
|
-
const localIPs = ['127.0.0.1'];
|
|
159
|
-
|
|
160
|
-
Object.values(interfaces).forEach(iface => {
|
|
161
|
-
iface.forEach(addr => {
|
|
162
|
-
if (addr.family === 'IPv4' && !addr.internal) {
|
|
163
|
-
localIPs.push(addr.address);
|
|
164
|
-
}
|
|
165
|
-
});
|
|
75
|
+
const result = await ensureLocalCertificates(dataDir, {
|
|
76
|
+
log: msg => console.log('[HTTPS]', msg)
|
|
166
77
|
});
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
const altNames = [
|
|
173
|
-
{ type: 2, value: 'localhost' },
|
|
174
|
-
{ type: 2, value: hostname },
|
|
175
|
-
...localIPs.map(ip => ({ type: 7, ip }))
|
|
176
|
-
];
|
|
177
|
-
|
|
178
|
-
try {
|
|
179
|
-
const attrs = [
|
|
180
|
-
{ name: 'commonName', value: hostname },
|
|
181
|
-
{ name: 'organizationName', value: 'sshift' }
|
|
182
|
-
];
|
|
183
|
-
const pems = await selfsigned.generate(attrs, {
|
|
184
|
-
days: 365,
|
|
185
|
-
keySize: 2048,
|
|
186
|
-
algorithm: 'sha256',
|
|
187
|
-
extensions: [{
|
|
188
|
-
name: 'subjectAltName',
|
|
189
|
-
altNames
|
|
190
|
-
}]
|
|
191
|
-
});
|
|
192
|
-
|
|
193
|
-
console.log('[HTTPS] Self-signed certificate generated successfully');
|
|
194
|
-
return {
|
|
195
|
-
cert: pems.cert,
|
|
196
|
-
key: pems.private
|
|
197
|
-
};
|
|
198
|
-
} catch (err) {
|
|
199
|
-
console.error('[HTTPS] Error generating certificate:', err);
|
|
200
|
-
throw err;
|
|
78
|
+
if (result.caCreated) {
|
|
79
|
+
console.log('[HTTPS] NOTE: a new local CA was created. Devices that trusted the previous');
|
|
80
|
+
console.log('[HTTPS] self-signed certificate must install the new CA from /api/cert.');
|
|
81
|
+
} else if (!result.certIssued) {
|
|
82
|
+
console.log('[HTTPS] Reusing persisted local CA and server certificate from', dataDir);
|
|
201
83
|
}
|
|
84
|
+
return { cert: result.cert, key: result.key };
|
|
202
85
|
}
|
|
203
86
|
|
|
204
87
|
// Create Express app
|
|
@@ -282,6 +165,9 @@ async function initializeServer() {
|
|
|
282
165
|
// HTTP to HTTPS redirect middleware (for dual-protocol httpolyglot server)
|
|
283
166
|
if (enableHttpRedirect) {
|
|
284
167
|
app.use((req, res, next) => {
|
|
168
|
+
// The CA download must stay reachable over plain HTTP: a device that
|
|
169
|
+
// does not trust the CA yet cannot fetch it over HTTPS without warnings.
|
|
170
|
+
if (req.path === '/api/cert') return next();
|
|
285
171
|
if (!req.socket.encrypted) {
|
|
286
172
|
const host = req.headers.host ? req.headers.host.split(':')[0] : 'localhost';
|
|
287
173
|
const port = getPort();
|
|
@@ -472,8 +358,8 @@ async function initializeServer() {
|
|
|
472
358
|
console.log(`${ESC}]8;;${protocol}://${address}:${PORT}${ESC}\\Open in browser${ESC}]8;;${ESC}\\`);
|
|
473
359
|
|
|
474
360
|
if (actuallyHttps) {
|
|
475
|
-
console.log('[HTTPS] Note:
|
|
476
|
-
console.log('[HTTPS]
|
|
361
|
+
console.log('[HTTPS] Note: the certificate is issued by sshift\'s local CA. Browsers warn until that CA is trusted.');
|
|
362
|
+
console.log('[HTTPS] Install the CA on each device once: download it from /api/cert (also over plain http://).');
|
|
477
363
|
}
|
|
478
364
|
});
|
|
479
365
|
}
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local certificate authority + CA-signed server certificate.
|
|
3
|
+
*
|
|
4
|
+
* Why a CA instead of a plain self-signed leaf: Android (and Brave/Chrome
|
|
5
|
+
* on Android) will only install a certificate as a trust anchor when it
|
|
6
|
+
* is a real CA certificate (basicConstraints CA:TRUE, keyCertSign). A
|
|
7
|
+
* self-signed leaf without those extensions is rejected or silently
|
|
8
|
+
* ignored by the "Install a certificate → CA certificate" flow, so the
|
|
9
|
+
* "Not Secure" warning never goes away on the phone.
|
|
10
|
+
*
|
|
11
|
+
* Layout (all files live in the user-space data directory, which
|
|
12
|
+
* survives `npm install -g` updates and Docker container recreation when
|
|
13
|
+
* /data is a volume):
|
|
14
|
+
*
|
|
15
|
+
* ssl-ca-cert.pem the local CA, valid 10 years → install THIS on devices
|
|
16
|
+
* ssl-ca-key.pem the CA private key (0600)
|
|
17
|
+
* ssl-cert.pem the server certificate signed by the CA
|
|
18
|
+
* ssl-key.pem the server private key (0600)
|
|
19
|
+
*
|
|
20
|
+
* The CA is generated once and never rotated automatically, so devices
|
|
21
|
+
* only need to trust it once. The server certificate is re-issued from
|
|
22
|
+
* the same CA whenever it is missing, not signed by the CA (old
|
|
23
|
+
* self-signed installs), close to expiry, or no longer lists the
|
|
24
|
+
* machine's current hostname / IPs in its SANs. A re-issued server
|
|
25
|
+
* certificate keeps working on every device that already trusts the CA.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
const fs = require('fs');
|
|
29
|
+
const path = require('path');
|
|
30
|
+
const os = require('os');
|
|
31
|
+
const { X509Certificate } = require('crypto');
|
|
32
|
+
const selfsigned = require('selfsigned');
|
|
33
|
+
|
|
34
|
+
const SSL_CERT_FILE = 'ssl-cert.pem';
|
|
35
|
+
const SSL_KEY_FILE = 'ssl-key.pem';
|
|
36
|
+
const SSL_CA_CERT_FILE = 'ssl-ca-cert.pem';
|
|
37
|
+
const SSL_CA_KEY_FILE = 'ssl-ca-key.pem';
|
|
38
|
+
|
|
39
|
+
const CA_VALID_DAYS = 3650;
|
|
40
|
+
// Apple (and, following it, Chrome) reject leaf certificates valid for
|
|
41
|
+
// longer than 825 days.
|
|
42
|
+
const SERVER_VALID_DAYS = 825;
|
|
43
|
+
// Re-issue the server certificate when it has less than this left.
|
|
44
|
+
const RENEW_BEFORE_DAYS = 30;
|
|
45
|
+
const ORG_NAME = 'sshift';
|
|
46
|
+
|
|
47
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Collect the names the server certificate must be valid for.
|
|
51
|
+
* @returns {{hostname: string, ips: string[]}}
|
|
52
|
+
*/
|
|
53
|
+
function collectLocalNames() {
|
|
54
|
+
const ips = ['127.0.0.1'];
|
|
55
|
+
const interfaces = os.networkInterfaces();
|
|
56
|
+
Object.values(interfaces).forEach(iface => {
|
|
57
|
+
(iface || []).forEach(addr => {
|
|
58
|
+
if (addr.family === 'IPv4' && !addr.internal && !ips.includes(addr.address)) {
|
|
59
|
+
ips.push(addr.address);
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
const hostname = os.hostname() || 'localhost';
|
|
64
|
+
return { hostname, ips };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function daysUntil(dateStr) {
|
|
68
|
+
return (new Date(dateStr).getTime() - Date.now()) / DAY_MS;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function parseCert(pem) {
|
|
72
|
+
try {
|
|
73
|
+
return new X509Certificate(pem);
|
|
74
|
+
} catch {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Returns null when the CA certificate/key pair is usable, otherwise a
|
|
81
|
+
* human-readable reason it must be regenerated.
|
|
82
|
+
* @param {string} caCertPem
|
|
83
|
+
* @param {string} caKeyPem
|
|
84
|
+
* @returns {string|null}
|
|
85
|
+
*/
|
|
86
|
+
function caProblem(caCertPem, caKeyPem) {
|
|
87
|
+
const ca = parseCert(caCertPem);
|
|
88
|
+
if (!ca) return 'CA certificate is not parseable';
|
|
89
|
+
if (!ca.ca) return 'CA certificate is not marked as a CA (basicConstraints CA:TRUE)';
|
|
90
|
+
if (daysUntil(ca.validTo) < RENEW_BEFORE_DAYS) return 'CA certificate has expired or expires soon';
|
|
91
|
+
try {
|
|
92
|
+
const { createPrivateKey } = require('crypto');
|
|
93
|
+
const key = createPrivateKey(caKeyPem);
|
|
94
|
+
if (!ca.checkPrivateKey(key)) return 'CA private key does not match the CA certificate';
|
|
95
|
+
} catch (err) {
|
|
96
|
+
return `CA private key is not usable: ${err.message}`;
|
|
97
|
+
}
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Returns null when the server certificate is usable with this CA and
|
|
103
|
+
* these names, otherwise a human-readable reason it must be re-issued.
|
|
104
|
+
* @param {string} certPem
|
|
105
|
+
* @param {string} keyPem
|
|
106
|
+
* @param {string} caCertPem
|
|
107
|
+
* @param {{hostname: string, ips: string[]}} names
|
|
108
|
+
* @returns {string|null}
|
|
109
|
+
*/
|
|
110
|
+
function serverCertProblem(certPem, keyPem, caCertPem, names) {
|
|
111
|
+
const cert = parseCert(certPem);
|
|
112
|
+
if (!cert) return 'server certificate is not parseable';
|
|
113
|
+
const ca = parseCert(caCertPem);
|
|
114
|
+
if (!ca) return 'CA certificate is not parseable';
|
|
115
|
+
|
|
116
|
+
let issuedByCa = false;
|
|
117
|
+
try {
|
|
118
|
+
issuedByCa = cert.checkIssued(ca) && cert.verify(ca.publicKey);
|
|
119
|
+
} catch {
|
|
120
|
+
issuedByCa = false;
|
|
121
|
+
}
|
|
122
|
+
if (!issuedByCa) return 'server certificate is not signed by the local CA (old self-signed certificate)';
|
|
123
|
+
if (cert.ca) return 'server certificate is marked as a CA';
|
|
124
|
+
if (daysUntil(cert.validTo) < RENEW_BEFORE_DAYS) return 'server certificate has expired or expires soon';
|
|
125
|
+
|
|
126
|
+
try {
|
|
127
|
+
const { createPrivateKey } = require('crypto');
|
|
128
|
+
if (!cert.checkPrivateKey(createPrivateKey(keyPem))) {
|
|
129
|
+
return 'server private key does not match the server certificate';
|
|
130
|
+
}
|
|
131
|
+
} catch (err) {
|
|
132
|
+
return `server private key is not usable: ${err.message}`;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// subjectAltName looks like "DNS:localhost, DNS:host, IP Address:127.0.0.1"
|
|
136
|
+
const san = cert.subjectAltName || '';
|
|
137
|
+
const missing = [];
|
|
138
|
+
if (!new RegExp(`DNS:${escapeRegExp(names.hostname)}(,|$)`).test(san)) missing.push(names.hostname);
|
|
139
|
+
names.ips.forEach(ip => {
|
|
140
|
+
if (!new RegExp(`IP Address:${escapeRegExp(ip)}(,|$)`).test(san)) missing.push(ip);
|
|
141
|
+
});
|
|
142
|
+
if (missing.length) return `server certificate does not cover: ${missing.join(', ')}`;
|
|
143
|
+
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function escapeRegExp(s) {
|
|
148
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Generate the local CA (10 years, RSA 2048, SHA-256).
|
|
153
|
+
* @param {string} hostname - shown in the CA name so several sshift
|
|
154
|
+
* hosts can be told apart in a device's credential list
|
|
155
|
+
* @returns {Promise<{cert: string, key: string}>}
|
|
156
|
+
*/
|
|
157
|
+
async function generateCA(hostname) {
|
|
158
|
+
const notBefore = new Date();
|
|
159
|
+
const notAfter = new Date(notBefore.getTime() + CA_VALID_DAYS * DAY_MS);
|
|
160
|
+
const pems = await selfsigned.generate(
|
|
161
|
+
[
|
|
162
|
+
{ name: 'commonName', value: `sshift Local CA (${hostname})` },
|
|
163
|
+
{ name: 'organizationName', value: ORG_NAME }
|
|
164
|
+
],
|
|
165
|
+
{
|
|
166
|
+
keySize: 2048,
|
|
167
|
+
algorithm: 'sha256',
|
|
168
|
+
notBeforeDate: notBefore,
|
|
169
|
+
notAfterDate: notAfter,
|
|
170
|
+
extensions: [
|
|
171
|
+
{ name: 'basicConstraints', cA: true, critical: true },
|
|
172
|
+
{ name: 'keyUsage', keyCertSign: true, cRLSign: true, critical: true }
|
|
173
|
+
]
|
|
174
|
+
}
|
|
175
|
+
);
|
|
176
|
+
return { cert: pems.cert, key: pems.private };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Issue a server certificate signed by the local CA.
|
|
181
|
+
* @param {{cert: string, key: string}} ca
|
|
182
|
+
* @param {{hostname: string, ips: string[]}} names
|
|
183
|
+
* @returns {Promise<{cert: string, key: string}>}
|
|
184
|
+
*/
|
|
185
|
+
async function generateServerCert(ca, names) {
|
|
186
|
+
const notBefore = new Date();
|
|
187
|
+
const notAfter = new Date(notBefore.getTime() + SERVER_VALID_DAYS * DAY_MS);
|
|
188
|
+
const dnsNames = ['localhost'];
|
|
189
|
+
if (names.hostname && names.hostname !== 'localhost') dnsNames.push(names.hostname);
|
|
190
|
+
const altNames = [
|
|
191
|
+
...dnsNames.map(value => ({ type: 2, value })),
|
|
192
|
+
...names.ips.map(ip => ({ type: 7, ip }))
|
|
193
|
+
];
|
|
194
|
+
const pems = await selfsigned.generate(
|
|
195
|
+
[
|
|
196
|
+
{ name: 'commonName', value: names.hostname },
|
|
197
|
+
{ name: 'organizationName', value: ORG_NAME }
|
|
198
|
+
],
|
|
199
|
+
{
|
|
200
|
+
keySize: 2048,
|
|
201
|
+
algorithm: 'sha256',
|
|
202
|
+
notBeforeDate: notBefore,
|
|
203
|
+
notAfterDate: notAfter,
|
|
204
|
+
ca: { cert: ca.cert, key: ca.key },
|
|
205
|
+
extensions: [
|
|
206
|
+
{ name: 'basicConstraints', cA: false, critical: true },
|
|
207
|
+
{ name: 'keyUsage', digitalSignature: true, keyEncipherment: true, critical: true },
|
|
208
|
+
{ name: 'extKeyUsage', serverAuth: true },
|
|
209
|
+
{ name: 'subjectAltName', altNames }
|
|
210
|
+
]
|
|
211
|
+
}
|
|
212
|
+
);
|
|
213
|
+
return { cert: pems.cert, key: pems.private };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function readPair(certPath, keyPath) {
|
|
217
|
+
if (!fs.existsSync(certPath) || !fs.existsSync(keyPath)) return null;
|
|
218
|
+
try {
|
|
219
|
+
return {
|
|
220
|
+
cert: fs.readFileSync(certPath, 'utf8'),
|
|
221
|
+
key: fs.readFileSync(keyPath, 'utf8')
|
|
222
|
+
};
|
|
223
|
+
} catch {
|
|
224
|
+
return null;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function writePair(certPath, keyPath, pair) {
|
|
229
|
+
fs.mkdirSync(path.dirname(certPath), { recursive: true });
|
|
230
|
+
// Certificates are public (they are served by /api/cert); keys are not.
|
|
231
|
+
fs.writeFileSync(certPath, pair.cert, { mode: 0o644 });
|
|
232
|
+
fs.writeFileSync(keyPath, pair.key, { mode: 0o600 });
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Make sure a usable local CA and a CA-signed server certificate exist in
|
|
237
|
+
* dataDir, creating or re-issuing whatever is missing or stale.
|
|
238
|
+
*
|
|
239
|
+
* @param {string} dataDir
|
|
240
|
+
* @param {object} [opts]
|
|
241
|
+
* @param {{hostname: string, ips: string[]}} [opts.names] - override the
|
|
242
|
+
* names the certificate must cover (tests)
|
|
243
|
+
* @param {(msg: string) => void} [opts.log]
|
|
244
|
+
* @returns {Promise<{cert: string, key: string, caCert: string,
|
|
245
|
+
* caCreated: boolean, certIssued: boolean}>}
|
|
246
|
+
* `cert` is the full chain (server certificate followed by the CA) so
|
|
247
|
+
* TLS clients receive the issuer too.
|
|
248
|
+
*/
|
|
249
|
+
async function ensureLocalCertificates(dataDir, opts = {}) {
|
|
250
|
+
const log = opts.log || (() => {});
|
|
251
|
+
const names = opts.names || collectLocalNames();
|
|
252
|
+
|
|
253
|
+
const caCertPath = path.join(dataDir, SSL_CA_CERT_FILE);
|
|
254
|
+
const caKeyPath = path.join(dataDir, SSL_CA_KEY_FILE);
|
|
255
|
+
const certPath = path.join(dataDir, SSL_CERT_FILE);
|
|
256
|
+
const keyPath = path.join(dataDir, SSL_KEY_FILE);
|
|
257
|
+
|
|
258
|
+
let ca = readPair(caCertPath, caKeyPath);
|
|
259
|
+
let caCreated = false;
|
|
260
|
+
if (ca) {
|
|
261
|
+
const problem = caProblem(ca.cert, ca.key);
|
|
262
|
+
if (problem) {
|
|
263
|
+
log(`Local CA in ${dataDir} is unusable (${problem}); generating a new one`);
|
|
264
|
+
ca = null;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
if (!ca) {
|
|
268
|
+
log('Generating local certificate authority (valid 10 years)...');
|
|
269
|
+
ca = await generateCA(names.hostname);
|
|
270
|
+
writePair(caCertPath, caKeyPath, ca);
|
|
271
|
+
caCreated = true;
|
|
272
|
+
log(`Local CA saved to ${caCertPath} — install this file on your devices (also served at /api/cert)`);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
let server = readPair(certPath, keyPath);
|
|
276
|
+
let certIssued = false;
|
|
277
|
+
if (server) {
|
|
278
|
+
const problem = serverCertProblem(server.cert, server.key, ca.cert, names);
|
|
279
|
+
if (problem) {
|
|
280
|
+
log(`Re-issuing server certificate: ${problem}`);
|
|
281
|
+
server = null;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
if (!server) {
|
|
285
|
+
log(`Issuing server certificate for ${names.hostname}, ${names.ips.join(', ')} (signed by the local CA)`);
|
|
286
|
+
server = await generateServerCert(ca, names);
|
|
287
|
+
writePair(certPath, keyPath, server);
|
|
288
|
+
certIssued = true;
|
|
289
|
+
if (!caCreated) {
|
|
290
|
+
log('The local CA is unchanged: devices that already trust it need no action');
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
return {
|
|
295
|
+
cert: `${server.cert.trim()}\n${ca.cert.trim()}\n`,
|
|
296
|
+
key: server.key,
|
|
297
|
+
caCert: ca.cert,
|
|
298
|
+
caCreated,
|
|
299
|
+
certIssued
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
module.exports = {
|
|
304
|
+
SSL_CERT_FILE,
|
|
305
|
+
SSL_KEY_FILE,
|
|
306
|
+
SSL_CA_CERT_FILE,
|
|
307
|
+
SSL_CA_KEY_FILE,
|
|
308
|
+
collectLocalNames,
|
|
309
|
+
caProblem,
|
|
310
|
+
serverCertProblem,
|
|
311
|
+
generateCA,
|
|
312
|
+
generateServerCert,
|
|
313
|
+
ensureLocalCertificates
|
|
314
|
+
};
|