-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathmcp-server-security.el
More file actions
500 lines (432 loc) · 20 KB
/
Copy pathmcp-server-security.el
File metadata and controls
500 lines (432 loc) · 20 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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
;;; mcp-server-security.el --- Security and Sandboxing for MCP Server -*- lexical-binding: t; -*-
;; Copyright (C) 2025
;; This file is NOT part of GNU Emacs.
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;; Commentary:
;; This module provides security features for the MCP server including
;; input validation, execution sandboxing, permission management, and
;; audit logging.
;;; Code:
(require 'cl-lib)
;;; Variables
(defcustom mcp-server-security-dangerous-functions
'(append-to-file
async-shell-command
browse-url
call-process
copy-file
delete-directory
delete-file
directory-files
directory-files-recursively
dired
eval
find-file
find-file-literally
find-file-noselect
getenv
insert-file-contents
insert-file-contents-literally
kill-emacs
load
make-directory
make-network-process
make-process
open-network-stream
rename-file
save-buffers-kill-emacs
save-buffers-kill-terminal
server-force-delete
server-start
set-file-modes
set-file-times
setenv
shell-command
shell-command-to-string
start-process
url-retrieve
url-retrieve-synchronously
view-file
with-current-buffer
with-temp-file
write-file
write-region)
"List of functions that require permission before execution.
Users can customize this list to add or remove functions that should
prompt for permission when used by the LLM."
:type '(repeat symbol)
:group 'mcp-server)
(defcustom mcp-server-security-allowed-dangerous-functions nil
"List of dangerous functions that are explicitly allowed without prompting.
These functions will bypass the dangerous function protection even if they
are listed in `mcp-server-security-dangerous-functions'.
Use this to whitelist specific functions you trust the LLM to use freely."
:type '(repeat symbol)
:group 'mcp-server)
(defvar mcp-server-security--permission-cache (make-hash-table :test 'equal)
"Cache of granted permissions for current Emacs session.")
(defvar mcp-server-security--audit-log '()
"Audit log of security events.")
(defcustom mcp-server-security-max-execution-time 30
"Maximum execution time for tools in seconds."
:type 'integer
:group 'mcp-server)
(defcustom mcp-server-security-max-memory-usage 100000000
"Maximum memory usage for tools in bytes (100MB)."
:type 'integer
:group 'mcp-server)
(defcustom mcp-server-security-prompt-for-permissions nil
"Whether to prompt user in Emacs for dangerous operations.
When nil (the default), dangerous operations are blocked without prompting.
The MCP client uses tool annotations to determine whether to prompt for
tool-level permission, but the blocklist is always enforced.
Set to t to prompt in the Emacs minibuffer instead of blocking, allowing
users to approve dangerous operations on a case-by-case basis."
:type 'boolean
:group 'mcp-server)
(defcustom mcp-server-security-sensitive-file-patterns
'("~/.authinfo" "~/.authinfo.gpg" "~/.authinfo.gpg~" "~/.authinfo.enc"
"~/.netrc" "~/.netrc.gpg" "~/.netrc.gpg~" "~/.netrc.enc"
"~/.ssh/" "~/.gnupg/" "~/.aws/" "~/.config/gh/"
"~/.docker/config.json" "~/.kube/config" "~/.npmrc"
"~/.pypirc" "~/.gem/credentials" "~/.gitconfig"
"~/.password-store/" "~/.local/share/keyrings/"
"/etc/passwd" "/etc/shadow" "/etc/hosts"
"passwords" "secrets" "credentials" "keys" "tokens")
"List of file patterns that should require permission to access.
Users can customize this list to add or remove sensitive file patterns.
Patterns can be absolute paths, relative paths, or just filenames."
:type '(repeat string)
:group 'mcp-server)
(defcustom mcp-server-security-allowed-sensitive-files nil
"List of sensitive files that are explicitly allowed without prompting.
These files will bypass the sensitive file protection even if they match
patterns in `mcp-server-security-sensitive-file-patterns'.
Use this to whitelist specific credential files you want the LLM to access."
:type '(repeat string)
:group 'mcp-server)
(defcustom mcp-server-security-sensitive-buffer-patterns
'("*Messages*" "*shell*" "*terminal*" "*eshell*"
"*compilation*" "*Async Shell Command*")
"List of buffer patterns that may contain sensitive information."
:type '(repeat string)
:group 'mcp-server)
;;; Permission Management
(defun mcp-server-security-check-permission (operation &optional data)
"Check if OPERATION with DATA is permitted.
Returns t if permitted, nil otherwise."
(let ((cache-key (format "%s:%s" operation data)))
(if (gethash cache-key mcp-server-security--permission-cache)
t
(mcp-server-security--request-permission operation data cache-key))))
(defun mcp-server-security--request-permission (operation data cache-key)
"Request permission for OPERATION with DATA, caching result with CACHE-KEY."
(if mcp-server-security-prompt-for-permissions
(let ((response (mcp-server-security--prompt-permission operation data)))
(pcase response
('always
(puthash cache-key t mcp-server-security--permission-cache)
(mcp-server-security--log-audit operation data 'always)
t)
('yes
(mcp-server-security--log-audit operation data t)
t)
('no
(mcp-server-security--log-audit operation data nil)
nil)))
;; When not prompting, still block dangerous operations
(let ((granted (not (mcp-server-security--is-dangerous-operation operation))))
(puthash cache-key granted mcp-server-security--permission-cache)
(mcp-server-security--log-audit operation data granted)
granted)))
(defun mcp-server-security--prompt-permission (operation data)
"Prompt user for permission for OPERATION with DATA.
Returns 'yes, 'no, or 'always."
(let ((prompt (format "MCP: %s%s (y)es, (n)o, (!) always: "
operation
(if data (format " (%s)" data) ""))))
(pcase (read-char-choice prompt '(?y ?n ?!))
(?y 'yes)
(?n 'no)
(?! 'always))))
(defun mcp-server-security--is-dangerous-operation (operation)
"Check if OPERATION is considered dangerous.
OPERATION is either a symbol (a function name) or a string synthetic ID
such as \"access-sensitive-file:find-file\" produced by the sensitive
file/buffer check paths. String ops prefixed with \"access-sensitive-\"
are always treated as dangerous so they are denied when prompting is off."
(if (stringp operation)
;; Synthetic string IDs from sensitive file/buffer checks are dangerous
(string-prefix-p "access-sensitive-" operation)
;; Symbol: check the allowed list, dangerous list, and name patterns
(unless (member operation mcp-server-security-allowed-dangerous-functions)
(or (member operation mcp-server-security-dangerous-functions)
(string-match-p "delete\\|kill\\|remove\\|destroy"
(symbol-name operation))))))
(defun mcp-server-security--is-sensitive-file (path)
"Check if PATH points to a sensitive file."
(when (stringp path)
(let ((expanded-path (expand-file-name path)))
;; First check if file is explicitly allowed
(unless (cl-some (lambda (allowed-file)
(string-equal (expand-file-name allowed-file) expanded-path))
mcp-server-security-allowed-sensitive-files)
;; Then check if it matches any sensitive patterns.
;;
;; Patterns starting with ~ or / are expanded before comparison so that
;; e.g. "~/.ssh/" correctly matches the expanded path "/home/user/.ssh/id_rsa".
;;
;; Patterns containing * or ? are treated as shell glob wildcards via
;; `wildcard-to-regexp', so "~/.authinfo*" matches "~/.authinfo.gpg" etc.
;;
;; Bare filename patterns (no leading ~ or /) are matched literally
;; against the file's basename only.
(cl-some (lambda (pattern)
(if (string-match-p "^[~/]" pattern)
(let ((expanded-pattern (expand-file-name pattern)))
(if (string-match-p "[*?]" pattern)
(string-match-p (wildcard-to-regexp expanded-pattern)
expanded-path)
(string-prefix-p expanded-pattern expanded-path)))
(string-match-p (regexp-quote pattern)
(file-name-nondirectory expanded-path))))
mcp-server-security-sensitive-file-patterns)))))
(defun mcp-server-security--is-sensitive-buffer (buffer-name)
"Check if BUFFER-NAME is a sensitive buffer."
(when (stringp buffer-name)
(cl-some (lambda (pattern)
(string-match-p pattern buffer-name))
mcp-server-security-sensitive-buffer-patterns)))
(defun mcp-server-security--contains-credentials (content)
"Check if CONTENT contains credential-like patterns."
(when (stringp content)
(or (string-match-p "password\\s-*[=:]\\s-*['\"]?[^\\s]+" content)
(string-match-p "api[_-]?key\\s-*[=:]\\s-*['\"]?[^\\s]+" content)
(string-match-p "secret\\s-*[=:]\\s-*['\"]?[^\\s]+" content)
(string-match-p "token\\s-*[=:]\\s-*['\"]?[^\\s]+" content)
(string-match-p "-----BEGIN [A-Z ]+PRIVATE KEY-----" content))))
;;; Input Validation
(defun mcp-server-security-validate-input (input)
"Validate INPUT for security issues.
Returns the input if safe, signals an error otherwise."
;; Check for suspicious patterns
(when (stringp input)
;; Check for shell command injection
(when (string-match-p "[;&|`$]" input)
(error "Input contains potentially dangerous shell characters"))
;; Check for path traversal
(when (string-match-p "\\.\\./\\|~/" input)
(error "Input contains potentially dangerous path patterns"))
;; Check for excessive length
(when (> (length input) 10000)
(error "Input exceeds maximum length")))
;; Check for suspicious elisp code patterns in strings
(when (and (stringp input)
(string-match-p "(\\s-*\\(?:eval\\|load\\|shell-command\\)" input))
(error "Input contains potentially dangerous elisp patterns"))
input)
(defun mcp-server-security-sanitize-string (str)
"Sanitize STR for safe use."
(when (stringp str)
;; Remove null bytes
(setq str (replace-regexp-in-string "\0" "" str))
;; Limit length
(when (> (length str) 1000)
(setq str (substring str 0 1000))))
str)
;;; Execution Sandboxing
(defun mcp-server-security-safe-eval (form)
"Safely evaluate FORM with security restrictions."
;; Check if form contains dangerous functions
(mcp-server-security--check-form-safety form)
;; Execute with timeout and memory limits
(mcp-server-security--execute-with-limits
(lambda () (eval form))))
(defun mcp-server-security--check-form-safety (form)
"Check if FORM is safe to evaluate."
(cond
;; Check atoms
((symbolp form)
(when (and (member form mcp-server-security-dangerous-functions)
(not (member form mcp-server-security-allowed-dangerous-functions)))
(unless (mcp-server-security-check-permission form)
(error "Security: `%s' is blocked. Add it to `mcp-server-security-allowed-dangerous-functions' \
to allow, or set `mcp-server-security-prompt-for-permissions' to t to prompt" form))))
;; Check lists (function calls)
((listp form)
(when form
(let ((func (car form))
(args (cdr form)))
(when (symbolp func)
;; Check for dangerous functions
(when (and (member func mcp-server-security-dangerous-functions)
(not (member func mcp-server-security-allowed-dangerous-functions)))
(unless (mcp-server-security-check-permission func args)
(error "Security: `%s' is blocked. Add it to `mcp-server-security-allowed-dangerous-functions' \
to allow, or set `mcp-server-security-prompt-for-permissions' to t to prompt" func)))
;; Special checks for file access functions.
;; Each entry maps a function to the 1-based positions of its file-path
;; arguments. Both read and write paths are covered so that sensitive
;; files cannot be read from OR written to, even when the function is
;; listed in `mcp-server-security-allowed-dangerous-functions'.
(let ((file-arg-specs
'((find-file . (1))
(find-file-noselect . (1))
(find-file-literally . (1))
(view-file . (1))
(insert-file-contents . (1))
(insert-file-contents-literally . (1))
(write-file . (1))
(copy-file . (1 2))
(rename-file . (1 2))
(write-region . (3))
(append-to-file . (3)))))
(when-let ((positions (alist-get func file-arg-specs)))
(dolist (pos positions)
(let ((file-path (nth (1- pos) args)))
(when (and file-path (stringp file-path))
(when (mcp-server-security--is-sensitive-file file-path)
(unless (mcp-server-security-check-permission
(format "access-sensitive-file:%s" func) file-path)
(error "Permission denied for sensitive file access: %s"
file-path))))))))
;; Special checks for buffer access functions
(when (memq func '(switch-to-buffer set-buffer with-current-buffer))
(let ((buffer-name (if (eq func 'with-current-buffer)
(car args)
(car args))))
(when (and buffer-name (stringp buffer-name))
(when (mcp-server-security--is-sensitive-buffer buffer-name)
(error "Access denied to sensitive buffer: %s" buffer-name))))))
;; Recursively check arguments
(dolist (arg args)
(mcp-server-security--check-form-safety arg)))))))
(defun mcp-server-security--execute-with-limits (func)
"Execute FUNC with time and memory limits."
(let ((start-time (current-time))
(start-gc-cons-threshold gc-cons-threshold))
;; Set conservative GC threshold for memory monitoring
(setq gc-cons-threshold 1000000)
(unwind-protect
(with-timeout (mcp-server-security-max-execution-time
(error "Execution timeout exceeded"))
(funcall func))
;; Restore GC threshold
(setq gc-cons-threshold start-gc-cons-threshold)
;; Log execution time
(let ((elapsed (float-time (time-subtract (current-time) start-time))))
(when (> elapsed 5.0)
(mcp-server-security--log-audit 'slow-execution elapsed t))))))
;;; Audit Logging
(defun mcp-server-security--log-audit (operation data granted &optional timestamp)
"Log security audit event."
(let ((entry `((timestamp . ,(or timestamp (current-time)))
(operation . ,operation)
(data . ,data)
(granted . ,granted))))
(push entry mcp-server-security--audit-log)
;; Keep only last 1000 entries
(when (> (length mcp-server-security--audit-log) 1000)
(setq mcp-server-security--audit-log
(cl-subseq mcp-server-security--audit-log 0 1000)))))
(defun mcp-server-security-get-audit-log (&optional limit)
"Get audit log entries, optionally limited to LIMIT entries."
(if limit
(cl-subseq mcp-server-security--audit-log 0 (min limit (length mcp-server-security--audit-log)))
mcp-server-security--audit-log))
(defun mcp-server-security-clear-audit-log ()
"Clear the audit log."
(setq mcp-server-security--audit-log '()))
;;; Permission Cache Management
(defun mcp-server-security-clear-permissions ()
"Clear all cached permissions."
(interactive)
(clrhash mcp-server-security--permission-cache)
(mcp-server-security--log-audit 'clear-permissions nil t)
(message "Session permission cache cleared."))
(defun mcp-server-security-grant-permission (operation &optional data)
"Grant permission for OPERATION with optional DATA."
(let ((cache-key (format "%s:%s" operation data)))
(puthash cache-key t mcp-server-security--permission-cache)
(mcp-server-security--log-audit operation data t)))
(defun mcp-server-security-deny-permission (operation &optional data)
"Deny permission for OPERATION with optional DATA."
(let ((cache-key (format "%s:%s" operation data)))
(puthash cache-key nil mcp-server-security--permission-cache)
(mcp-server-security--log-audit operation data nil)))
;;; Configuration
(defun mcp-server-security-set-prompting (enabled)
"Enable or disable permission prompting based on ENABLED."
(setq mcp-server-security-prompt-for-permissions enabled)
(mcp-server-security--log-audit 'set-prompting enabled t))
(defun mcp-server-security-add-dangerous-function (func)
"Add FUNC to the list of dangerous functions."
(unless (member func mcp-server-security-dangerous-functions)
(push func mcp-server-security-dangerous-functions)
(mcp-server-security--log-audit 'add-dangerous-function func t)))
(defun mcp-server-security-remove-dangerous-function (func)
"Remove FUNC from the list of dangerous functions."
(setq mcp-server-security-dangerous-functions
(remove func mcp-server-security-dangerous-functions))
(mcp-server-security--log-audit 'remove-dangerous-function func t))
;;; Initialization and Cleanup
(defun mcp-server-security-init ()
"Initialize the security system."
(clrhash mcp-server-security--permission-cache)
(setq mcp-server-security--audit-log '())
(mcp-server-security--log-audit 'security-init nil t))
(defun mcp-server-security-cleanup ()
"Clean up the security system."
(mcp-server-security--log-audit 'security-cleanup nil t)
(clrhash mcp-server-security--permission-cache)
(setq mcp-server-security--audit-log '()))
;;; Interactive Commands
(defun mcp-server-security-show-audit-log ()
"Display the security audit log."
(interactive)
(with-current-buffer (get-buffer-create "*MCP Security Audit*")
(erase-buffer)
(insert "MCP Security Audit Log\n")
(insert "========================\n\n")
(dolist (entry (reverse mcp-server-security--audit-log))
(insert (format "[%s] %s: %s (%s)\n"
(format-time-string "%Y-%m-%d %H:%M:%S" (alist-get 'timestamp entry))
(alist-get 'operation entry)
(alist-get 'data entry)
(if (alist-get 'granted entry) "GRANTED" "DENIED"))))
(goto-char (point-min))
(pop-to-buffer (current-buffer))))
(defun mcp-server-security-show-permissions ()
"Display cached permissions for this session."
(interactive)
(with-current-buffer (get-buffer-create "*MCP Permissions*")
(erase-buffer)
(insert "MCP Session Permissions\n")
(insert "=======================\n\n")
(let ((count 0))
(maphash
(lambda (key value)
(insert (format " %s: %s\n" key (if value "ALLOWED" "DENIED")))
(cl-incf count))
mcp-server-security--permission-cache)
(when (zerop count)
(insert " (none)\n")))
(goto-char (point-min))
(pop-to-buffer (current-buffer))))
(defun mcp-server-security-remove-permission (key)
"Remove a specific permission by KEY."
(interactive
(list (completing-read "Remove permission: "
(let (keys)
(maphash (lambda (k _v) (push k keys))
mcp-server-security--permission-cache)
keys)
nil t)))
(remhash key mcp-server-security--permission-cache)
(mcp-server-security--log-audit 'remove-permission key t)
(message "Removed permission: %s" key))
(provide 'mcp-server-security)
;;; mcp-server-security.el ends here