-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmount-security.ts
More file actions
274 lines (249 loc) · 7.54 KB
/
mount-security.ts
File metadata and controls
274 lines (249 loc) · 7.54 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
/**
* Mount Security — validates additional mounts against an allowlist stored
* OUTSIDE the project root, preventing container agents from modifying
* security configuration.
*
* Allowlist location: ~/.config/hybridclaw/mount-allowlist.json
*/
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { MOUNT_ALLOWLIST_PATH } from '../config/config.js';
import { logger } from '../logger.js';
import type {
AdditionalMount,
AllowedRoot,
MountAllowlist,
} from '../types/security.js';
// Cache the allowlist in memory — only reloads on process restart
let cachedAllowlist: MountAllowlist | null = null;
let allowlistLoadError: string | null = null;
const DEFAULT_BLOCKED_PATTERNS = [
'.ssh',
'.gnupg',
'.gpg',
'.aws',
'.azure',
'.gcloud',
'.kube',
'.docker',
'credentials',
'.env',
'.netrc',
'.npmrc',
'.pypirc',
'id_rsa',
'id_ed25519',
'private_key',
'.secret',
];
/**
* Load the mount allowlist from the external config location.
* Returns null if the file doesn't exist or is invalid.
* Result is cached in memory for the lifetime of the process.
*/
export function loadMountAllowlist(): MountAllowlist | null {
if (cachedAllowlist !== null) return cachedAllowlist;
if (allowlistLoadError !== null) return null;
try {
if (!fs.existsSync(MOUNT_ALLOWLIST_PATH)) {
allowlistLoadError = `Mount allowlist not found at ${MOUNT_ALLOWLIST_PATH}`;
logger.warn(
{ path: MOUNT_ALLOWLIST_PATH },
'Mount allowlist not found — additional mounts will be BLOCKED. Create the file to enable additional mounts.',
);
return null;
}
const content = fs.readFileSync(MOUNT_ALLOWLIST_PATH, 'utf-8');
const allowlist = JSON.parse(content) as MountAllowlist;
if (!Array.isArray(allowlist.allowedRoots)) {
throw new Error('allowedRoots must be an array');
}
if (!Array.isArray(allowlist.blockedPatterns)) {
throw new Error('blockedPatterns must be an array');
}
// Merge with default blocked patterns
allowlist.blockedPatterns = [
...new Set([...DEFAULT_BLOCKED_PATTERNS, ...allowlist.blockedPatterns]),
];
cachedAllowlist = allowlist;
logger.info(
{
path: MOUNT_ALLOWLIST_PATH,
allowedRoots: allowlist.allowedRoots.length,
blockedPatterns: allowlist.blockedPatterns.length,
},
'Mount allowlist loaded',
);
return cachedAllowlist;
} catch (err) {
allowlistLoadError = err instanceof Error ? err.message : String(err);
logger.error(
{ path: MOUNT_ALLOWLIST_PATH, error: allowlistLoadError },
'Failed to load mount allowlist — additional mounts will be BLOCKED',
);
return null;
}
}
function expandPath(p: string): string {
const homeDir = process.env.HOME || os.homedir();
if (p.startsWith('~/')) return path.join(homeDir, p.slice(2));
if (p === '~') return homeDir;
return path.resolve(p);
}
function getRealPath(p: string): string | null {
try {
return fs.realpathSync(p);
} catch {
return null;
}
}
function matchesBlockedPattern(
realPath: string,
blockedPatterns: string[],
): string | null {
const pathParts = realPath.split(path.sep);
for (const pattern of blockedPatterns) {
for (const part of pathParts) {
if (part === pattern || part.includes(pattern)) return pattern;
}
if (realPath.includes(pattern)) return pattern;
}
return null;
}
function findAllowedRoot(
realPath: string,
allowedRoots: AllowedRoot[],
): AllowedRoot | null {
for (const root of allowedRoots) {
const realRoot = getRealPath(expandPath(root.path));
if (realRoot === null) continue;
const relative = path.relative(realRoot, realPath);
if (!relative.startsWith('..') && !path.isAbsolute(relative)) return root;
}
return null;
}
function isValidContainerPath(containerPath: string): boolean {
if (containerPath.includes('..')) return false;
if (containerPath.startsWith('/')) return false;
if (!containerPath || containerPath.trim() === '') return false;
return true;
}
export interface MountValidationResult {
allowed: boolean;
reason: string;
realHostPath?: string;
resolvedContainerPath?: string;
effectiveReadonly?: boolean;
}
/**
* Validate a single additional mount against the allowlist.
*/
export function validateMount(mount: AdditionalMount): MountValidationResult {
const allowlist = loadMountAllowlist();
if (allowlist === null) {
return {
allowed: false,
reason: `No mount allowlist configured at ${MOUNT_ALLOWLIST_PATH}`,
};
}
const containerPath = mount.containerPath || path.basename(mount.hostPath);
if (!isValidContainerPath(containerPath)) {
return {
allowed: false,
reason: `Invalid container path: "${containerPath}" — must be relative, non-empty, and not contain ".."`,
};
}
const expandedPath = expandPath(mount.hostPath);
const realPath = getRealPath(expandedPath);
if (realPath === null) {
return {
allowed: false,
reason: `Host path does not exist: "${mount.hostPath}" (expanded: "${expandedPath}")`,
};
}
const blockedMatch = matchesBlockedPattern(
realPath,
allowlist.blockedPatterns,
);
if (blockedMatch !== null) {
return {
allowed: false,
reason: `Path matches blocked pattern "${blockedMatch}": "${realPath}"`,
};
}
const allowedRoot = findAllowedRoot(realPath, allowlist.allowedRoots);
if (allowedRoot === null) {
return {
allowed: false,
reason: `Path "${realPath}" is not under any allowed root. Allowed roots: ${allowlist.allowedRoots.map((r) => expandPath(r.path)).join(', ')}`,
};
}
// Determine effective readonly status
let effectiveReadonly = true;
if (mount.readonly === false && allowedRoot.allowReadWrite) {
effectiveReadonly = false;
} else if (mount.readonly === false && !allowedRoot.allowReadWrite) {
logger.info(
{ mount: mount.hostPath, root: allowedRoot.path },
'Mount forced to read-only — root does not allow read-write',
);
}
return {
allowed: true,
reason: `Allowed under root "${allowedRoot.path}"${allowedRoot.description ? ` (${allowedRoot.description})` : ''}`,
realHostPath: realPath,
resolvedContainerPath: containerPath,
effectiveReadonly,
};
}
/**
* Validate all additional mounts.
* Returns only mounts that passed validation; logs warnings for rejected ones.
*/
export function validateAdditionalMounts(mounts: AdditionalMount[]): Array<{
hostPath: string;
expandedHostPath: string;
containerPath: string;
readonly: boolean;
}> {
const validated: Array<{
hostPath: string;
expandedHostPath: string;
containerPath: string;
readonly: boolean;
}> = [];
for (const mount of mounts) {
const result = validateMount(mount);
if (
result.allowed &&
result.realHostPath &&
result.effectiveReadonly !== undefined
) {
validated.push({
hostPath: result.realHostPath,
expandedHostPath: expandPath(mount.hostPath),
containerPath: `/workspace/extra/${result.resolvedContainerPath}`,
readonly: result.effectiveReadonly,
});
logger.debug(
{
hostPath: result.realHostPath,
containerPath: result.resolvedContainerPath,
readonly: result.effectiveReadonly,
},
'Mount validated',
);
} else {
logger.warn(
{
requestedPath: mount.hostPath,
containerPath: mount.containerPath,
reason: result.reason,
},
'Additional mount REJECTED',
);
}
}
return validated;
}