-
-
Notifications
You must be signed in to change notification settings - Fork 203
Expand file tree
/
Copy pathsecurity.ts
More file actions
451 lines (408 loc) · 11.4 KB
/
Copy pathsecurity.ts
File metadata and controls
451 lines (408 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/* eslint-disable @typescript-eslint/no-explicit-any */
/*
* Copyright 2017 Teppo Kurki <teppo.kurki@iki.fi>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Request, Response } from 'express'
import { PartialOIDCConfig } from './oidc/types'
import {
chmodSync,
existsSync,
readFileSync,
Stats,
statSync,
writeFile,
writeFileSync
} from 'fs'
import _ from 'lodash'
import path from 'path'
import { generate } from 'selfsigned'
import { Mode } from 'stat-mode'
import { WithConfig } from './app'
import { createDebug } from './debug'
import dummysecurity from './dummysecurity'
import { ICallback } from './types'
const debug = createDebug('signalk-server:security')
export interface WithSecurityStrategy {
securityStrategy: SecurityStrategy
}
export type AnonymousApplicationDataAccess = 'none' | 'readonly' | 'readwrite'
export interface LoginStatusResponse {
status: string // 'loggedIn' 'notLoggedIn'
readOnlyAccess?: boolean
authenticationRequired?: boolean
allowNewUserRegistration?: boolean
allowDeviceAccessRequests?: boolean
anonymousApplicationDataAccess?: AnonymousApplicationDataAccess
userLevel?: any
username?: string
}
export interface ACL {
context: string
resources: Array<{
paths?: string[]
sources?: string[]
permissions: Array<{
subject: string
permission: string
}>
}>
}
export interface OIDCUserIdentifier {
sub: string
issuer: string
/** User's email from OIDC claims */
email?: string
/** User's display name from OIDC claims */
name?: string
/** User's groups from OIDC claims (used for permission mapping) */
groups?: string[]
}
export function isOIDCUserIdentifier(
value: unknown
): value is OIDCUserIdentifier {
return (
typeof value === 'object' &&
value !== null &&
typeof (value as OIDCUserIdentifier).sub === 'string' &&
typeof (value as OIDCUserIdentifier).issuer === 'string'
)
}
export interface User {
username: string
type: string
password?: string
oidc?: OIDCUserIdentifier
}
export interface UserData {
userId: string
type: string
}
export interface UserDataUpdate {
type?: string
password?: string
}
export interface UserWithPassword {
userId: string
type: string
password: string
}
export interface Device {
clientId: string
permissions: string
config: any
description: string
requestedPermissions: string
tokenExpiry?: number
}
export interface DeviceDataUpdate {
permissions?: string
description?: string
}
export interface OIDCSecurityConfig {
enabled: boolean
issuer: string
clientId: string
clientSecret: string
redirectUri?: string
scope?: string
defaultPermission?: 'readonly' | 'readwrite' | 'admin'
autoCreateUsers?: boolean
}
export interface SecurityConfig {
immutableConfig: boolean
allow_readonly: boolean
allowNewUserRegistration: boolean
allowDeviceAccessRequests: boolean
allowedCorsOrigins?: string
expiration: string
devices: Device[]
secretKey: string
users: User[]
acls?: ACL[]
oidc?: OIDCSecurityConfig
}
export interface RequestStatusData {
expiration: string
permissions: any
config: any
}
export interface SecurityStrategy {
isDummy: () => boolean
allowReadOnly: () => boolean
shouldFilterDeltas: () => boolean
filterReadDelta: (user: any, delta: any) => any
configFromArguments: boolean
securityConfig: any
requestAccess: (config: any, request: any, ip: any, updateCb?: any) => any
getConfiguration: () => any
setAccessRequestStatus: (
theConfig: SecurityConfig,
identifier: string,
status: string,
body: RequestStatusData,
cb: ICallback<SecurityConfig>
) => void
getAccessRequestsResponse: any
getLoginStatus: (req: Request) => LoginStatusResponse
allowRestart: (req: Request) => boolean
allowConfigure: (req: Request) => boolean
getConfig: (ss: SecurityConfig) => Omit<SecurityConfig, 'secretKey' | 'users'>
setConfig: (prev: SecurityConfig, next: SecurityConfig) => SecurityConfig
validateConfiguration: (config: any) => void
getDevices: (theConfig: SecurityConfig) => Device[]
updateDevice: (
theConfig: SecurityConfig,
clientId: string,
updates: DeviceDataUpdate,
cb: ICallback<SecurityConfig>
) => void
deleteDevice: (
theConfig: SecurityConfig,
clientId: string,
cb: ICallback<SecurityConfig>
) => void
generateToken: (
req: Request,
res: Response,
next: any,
id: string,
expiration: string
) => void
getUsers: (theConfig: SecurityConfig) => UserData[]
addUser: (
theConfig: SecurityConfig,
user: User,
cb: ICallback<SecurityConfig>
) => void
updateUser: (
theConfig: SecurityConfig,
username: string,
userDataUpdate: UserDataUpdate,
cb: ICallback<SecurityConfig>
) => void
deleteUser: (
theConfig: SecurityConfig,
username: string,
cb: ICallback<SecurityConfig>
) => void
setPassword: (
theConfig: SecurityConfig,
username: string,
password: string,
cb: ICallback<SecurityConfig>
) => void
shouldAllowPut: (
req: Request,
context: string,
source: any,
path: string
) => boolean
addAdminMiddleware: (path: string) => void
/** Update OIDC config in memory (optional - only available when token security is active) */
updateOIDCConfig?: (newOidcConfig: PartialOIDCConfig) => void
}
export class InvalidTokenError extends Error {
constructor(...args: any[]) {
super(...args)
Error.captureStackTrace(this, InvalidTokenError)
}
}
export function startSecurity(
app: WithSecurityStrategy & WithConfig,
securityConfig: any
) {
let securityStrategyModuleName =
process.env.SECURITYSTRATEGY ||
_.get(app, 'config.settings.security.strategy')
if (securityStrategyModuleName) {
if (securityStrategyModuleName === 'sk-simple-token-security') {
console.log(
'The sk-simple-token-security security strategy is depricated, please update to @signalk/sk-simple-token-security'
)
process.exit(1)
} else if (
securityStrategyModuleName === '@signalk/sk-simple-token-security'
) {
securityStrategyModuleName = './tokensecurity'
}
const config = securityConfig || getSecurityConfig(app, true)
// eslint-disable-next-line @typescript-eslint/no-require-imports
app.securityStrategy = require(securityStrategyModuleName)(app, config)
if (securityConfig) {
app.securityStrategy.configFromArguments = true
app.securityStrategy.securityConfig = securityConfig
}
} else {
app.securityStrategy = dummysecurity()
}
}
export function getSecurityConfig(
app: WithConfig & WithSecurityStrategy,
forceRead = false
) {
if (!forceRead && app.securityStrategy?.configFromArguments) {
return app.securityStrategy.securityConfig
} else {
try {
const optionsAsString = readFileSync(pathForSecurityConfig(app), 'utf8')
return JSON.parse(optionsAsString)
} catch (e: any) {
console.error(
'Could not parse security config at %s: %s',
pathForSecurityConfig(app),
e.message
)
return {}
}
}
}
export function pathForSecurityConfig(app: WithConfig) {
return path.join(app.config.configPath, 'security.json')
}
export function saveSecurityConfig(
app: WithSecurityStrategy & WithConfig,
data: any,
callback: any
) {
if (app.securityStrategy.configFromArguments) {
app.securityStrategy.securityConfig = data
if (callback) {
callback(null)
}
} else {
//const config = JSON.parse(JSON.stringify(data))
const configPath = pathForSecurityConfig(app)
writeFile(configPath, JSON.stringify(data, null, 2), (err) => {
if (!err) {
chmodSync(configPath, '600')
}
if (callback) {
callback(err)
}
})
}
}
export function getCertificateOptions(app: WithConfig, cb: any) {
let certLocation
if (!app.config.configPath || existsSync('./settings/ssl-cert.pem')) {
certLocation = './settings'
} else {
certLocation = app.config.configPath
}
const certFile = path.join(certLocation, 'ssl-cert.pem')
const keyFile = path.join(certLocation, 'ssl-key.pem')
const chainFile = path.join(certLocation, 'ssl-chain.pem')
if (existsSync(certFile) && existsSync(keyFile)) {
if (!hasStrictPermissions(statSync(keyFile))) {
cb(
new Error(
`${keyFile} must be accessible only by the user that is running the server, refusing to start`
)
)
return
}
if (!hasStrictPermissions(statSync(certFile))) {
cb(
new Error(
`${certFile} must be accessible only by the user that is running the server, refusing to start`
)
)
return
}
let ca
if (existsSync(chainFile)) {
debug('Found ssl-chain.pem')
ca = getCAChainArray(chainFile)
debug(JSON.stringify(ca, null, 2))
}
debug(`Using certificate ssl-key.pem and ssl-cert.pem in ${certLocation}`)
cb(null, {
key: readFileSync(keyFile),
cert: readFileSync(certFile),
ca
})
} else {
createCertificateOptions(app, certFile, keyFile, cb)
}
}
function hasStrictPermissions(stat: Stats) {
if (process.platform === 'win32') {
return true
} else {
return /^-r[-w][-x]------$/.test(new Mode(stat).toString())
}
}
export function getCAChainArray(filename: string) {
let chainCert = new Array<string>()
return readFileSync(filename, 'utf8')
.split('\n')
.reduce((ca, line) => {
chainCert.push(line)
if (line.match(/-END CERTIFICATE-/)) {
ca.push(chainCert.join('\n'))
chainCert = []
}
return ca
}, new Array<string>())
}
export function createCertificateOptions(
app: WithConfig,
certFile: string,
keyFile: string,
cb: any
) {
const location = app.config.configPath ? app.config.configPath : './settings'
debug(`Creating certificate files in ${location}`)
generate(
[{ name: 'commonName', value: 'localhost' }],
{ days: 3650 },
function (err, pems) {
writeFileSync(keyFile, pems.private)
chmodSync(keyFile, '600')
writeFileSync(certFile, pems.cert)
chmodSync(certFile, '600')
cb(null, {
key: pems.private,
cert: pems.cert
})
}
)
}
export function requestAccess(
app: WithSecurityStrategy & WithConfig,
request: any,
ip: any,
updateCb: any
) {
const config = getSecurityConfig(app)
return app.securityStrategy.requestAccess(config, request, ip, updateCb)
}
export type SecurityConfigSaver = (
app: any,
securityConfig: any,
cb: (err: any) => void
) => void
export type SecurityConfigGetter = (app: any) => any
/**
* When Express trust proxy is enabled:
* - req.ip will reflect the client IP and we don't want rateLimit to
* validate the presence of x-forwarded-for.
* - trustProxy: false prevents ERR_ERL_PERMISSIVE_TRUST_PROXY warnings
*/
export function getRateLimitValidationOptions(app: WithConfig) {
return app.config?.settings?.trustProxy &&
app.config.settings.trustProxy !== 'false'
? { xForwardedForHeader: false, trustProxy: false }
: undefined
}