@agenshield/patcher 0.1.0
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/LICENSE +201 -0
- package/README.md +109 -0
- package/index.d.ts +10 -0
- package/index.d.ts.map +1 -0
- package/index.js +633 -0
- package/install.d.ts +31 -0
- package/install.d.ts.map +1 -0
- package/package.json +25 -0
- package/python/index.d.ts +7 -0
- package/python/index.d.ts.map +1 -0
- package/python/sandbox-profile.d.ts +6 -0
- package/python/sandbox-profile.d.ts.map +1 -0
- package/python/sitecustomize.d.ts +6 -0
- package/python/sitecustomize.d.ts.map +1 -0
- package/python/wrapper.d.ts +6 -0
- package/python/wrapper.d.ts.map +1 -0
- package/types.d.ts +59 -0
- package/types.d.ts.map +1 -0
- package/verify.d.ts +23 -0
- package/verify.d.ts.map +1 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# @agenshield/patcher
|
|
2
|
+
|
|
3
|
+
Python network isolation via `sitecustomize.py` patching and optional macOS seatbelt wrappers. This package installs a Python runtime patch that blocks direct network access and routes selected HTTP traffic through the AgenShield broker.
|
|
4
|
+
|
|
5
|
+
## Purpose
|
|
6
|
+
- Prevent direct outbound network calls from Python code.
|
|
7
|
+
- Route `requests` traffic through the broker HTTP fallback.
|
|
8
|
+
- Optionally wrap Python with `sandbox-exec` on macOS.
|
|
9
|
+
|
|
10
|
+
## Key Components
|
|
11
|
+
- `src/install.ts` - `PythonPatcher` (install/uninstall/isInstalled).
|
|
12
|
+
- `src/verify.ts` - `PythonVerifier` to validate the patch.
|
|
13
|
+
- `src/python/sitecustomize.ts` - Generates patched `sitecustomize.py`.
|
|
14
|
+
- `src/python/wrapper.ts` - Generates a wrapper shell script.
|
|
15
|
+
- `src/python/sandbox-profile.ts` - Generates a macOS seatbelt profile.
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
### Install
|
|
19
|
+
```ts
|
|
20
|
+
import { PythonPatcher } from '@agenshield/patcher';
|
|
21
|
+
|
|
22
|
+
const patcher = new PythonPatcher({
|
|
23
|
+
pythonPath: '/usr/bin/python3',
|
|
24
|
+
brokerHost: 'localhost',
|
|
25
|
+
brokerPort: 5200,
|
|
26
|
+
useSandbox: true,
|
|
27
|
+
workspacePath: '/Users/clawagent/workspace',
|
|
28
|
+
socketPath: '/var/run/agenshield.sock',
|
|
29
|
+
installDir: '/Users/clawagent/bin'
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
const result = await patcher.install();
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
### Verify
|
|
36
|
+
```ts
|
|
37
|
+
import { PythonVerifier } from '@agenshield/patcher';
|
|
38
|
+
|
|
39
|
+
const verifier = new PythonVerifier({ pythonPath: '/usr/bin/python3' });
|
|
40
|
+
const report = await verifier.verify();
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Generate Assets
|
|
44
|
+
```ts
|
|
45
|
+
import { generateSitecustomize, generatePythonWrapper, generateSandboxProfile } from '@agenshield/patcher';
|
|
46
|
+
|
|
47
|
+
const sitecustomize = generateSitecustomize({
|
|
48
|
+
brokerHost: 'localhost',
|
|
49
|
+
brokerPort: 5200,
|
|
50
|
+
logLevel: 'warn',
|
|
51
|
+
enabled: true,
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
const wrapper = generatePythonWrapper({
|
|
55
|
+
pythonPath: '/usr/bin/python3',
|
|
56
|
+
sitecustomizePath: '/path/to/sitecustomize.py',
|
|
57
|
+
useSandbox: true,
|
|
58
|
+
sandboxProfilePath: '/etc/agenshield/seatbelt/python.sb',
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
const profile = generateSandboxProfile({
|
|
62
|
+
workspacePath: '/Users/clawagent/workspace',
|
|
63
|
+
pythonPath: '/usr/bin/python3',
|
|
64
|
+
brokerHost: 'localhost',
|
|
65
|
+
brokerPort: 5200,
|
|
66
|
+
});
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## How the Patch Works
|
|
70
|
+
- `socket.connect` and `socket.create_connection` are overridden to allow only broker connections.
|
|
71
|
+
- `requests.Session.request` is patched to proxy HTTP requests through the broker (`/rpc`).
|
|
72
|
+
- `urllib3` is patched to *block* non-broker connections (it does not proxy).
|
|
73
|
+
- `aiohttp` is patched to *block* non-broker connections.
|
|
74
|
+
|
|
75
|
+
## Environment Variables (sitecustomize)
|
|
76
|
+
- `AGENSHIELD_ENABLED` - `true`/`false` to toggle patching.
|
|
77
|
+
- `AGENSHIELD_BROKER_HOST` - Broker HTTP host.
|
|
78
|
+
- `AGENSHIELD_BROKER_PORT` - Broker HTTP port.
|
|
79
|
+
- `AGENSHIELD_LOG_LEVEL` - `debug|info|warn|error`.
|
|
80
|
+
|
|
81
|
+
## Limitations and Caveats
|
|
82
|
+
- Installs `sitecustomize.py` into the *system* site-packages; requires permissions.
|
|
83
|
+
- Virtual environments are not explicitly supported; `getsitepackages()[0]` may not be the active venv.
|
|
84
|
+
- Only `requests` is proxied through the broker; `urllib3` and `aiohttp` are blocked rather than proxied.
|
|
85
|
+
- macOS-only sandboxing (`sandbox-exec`) is used when `useSandbox` is true.
|
|
86
|
+
- Wrapper scripts do not remove seatbelt profiles on uninstall.
|
|
87
|
+
- The wrapper sets `PYTHONPATH` to a file path; site-packages installation is the primary mechanism.
|
|
88
|
+
|
|
89
|
+
## Roadmap (Ideas)
|
|
90
|
+
- Venv-aware installation and uninstall.
|
|
91
|
+
- Proxy support for `urllib3` and `aiohttp`.
|
|
92
|
+
- Cross-platform sandboxing alternatives.
|
|
93
|
+
- Cleaner wrapper env handling and profile lifecycle management.
|
|
94
|
+
|
|
95
|
+
## Development
|
|
96
|
+
```bash
|
|
97
|
+
# Build
|
|
98
|
+
npx nx build shield-patcher
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Contribution Guide
|
|
102
|
+
- Keep generated Python output minimal and deterministic.
|
|
103
|
+
- Any changes to `sitecustomize.py` should include a verifier update.
|
|
104
|
+
- Ensure new patches fail closed by default.
|
|
105
|
+
|
|
106
|
+
## Agent Notes
|
|
107
|
+
- `PythonPatcher.install()` writes to site-packages and optionally creates a wrapper and seatbelt profile.
|
|
108
|
+
- `PythonVerifier.verify()` uses real network probes; keep timeouts reasonable.
|
|
109
|
+
- `generateSandboxProfile()` emits a restrictive policy; any new paths should be explicit.
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @agenshield/patcher
|
|
3
|
+
*
|
|
4
|
+
* Python network isolation via sitecustomize.py patching.
|
|
5
|
+
*/
|
|
6
|
+
export { PythonPatcher } from './install.js';
|
|
7
|
+
export { PythonVerifier, verifyPython } from './verify.js';
|
|
8
|
+
export { generateSitecustomize, generatePythonWrapper, generateSandboxProfile, } from './python/index.js';
|
|
9
|
+
export type { PatcherConfig, PatcherResult, VerificationResult, } from './types.js';
|
|
10
|
+
//# sourceMappingURL=index.d.ts.map
|
package/index.d.ts.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EACrB,sBAAsB,GACvB,MAAM,mBAAmB,CAAC;AAE3B,YAAY,EACV,aAAa,EACb,aAAa,EACb,kBAAkB,GACnB,MAAM,YAAY,CAAC"}
|
package/index.js
ADDED
|
@@ -0,0 +1,633 @@
|
|
|
1
|
+
// libs/shield-patcher/src/install.ts
|
|
2
|
+
import * as fs from "node:fs/promises";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import { exec } from "node:child_process";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
|
|
7
|
+
// libs/shield-patcher/src/python/sitecustomize.ts
|
|
8
|
+
function generateSitecustomize(config) {
|
|
9
|
+
return `# -*- coding: utf-8 -*-
|
|
10
|
+
"""
|
|
11
|
+
AgenShield Python Network Isolation
|
|
12
|
+
|
|
13
|
+
This module patches Python's networking to route all traffic through
|
|
14
|
+
the AgenShield broker daemon.
|
|
15
|
+
|
|
16
|
+
Generated by @agenshield/patcher
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import os
|
|
20
|
+
import sys
|
|
21
|
+
import socket
|
|
22
|
+
import functools
|
|
23
|
+
|
|
24
|
+
# Configuration
|
|
25
|
+
_AGENSHIELD_ENABLED = ${config.enabled ? "True" : "False"}
|
|
26
|
+
_AGENSHIELD_BROKER_HOST = '${config.brokerHost}'
|
|
27
|
+
_AGENSHIELD_BROKER_PORT = ${config.brokerPort}
|
|
28
|
+
_AGENSHIELD_LOG_LEVEL = '${config.logLevel}'
|
|
29
|
+
|
|
30
|
+
# Override from environment
|
|
31
|
+
if os.environ.get('AGENSHIELD_ENABLED') == 'false':
|
|
32
|
+
_AGENSHIELD_ENABLED = False
|
|
33
|
+
if os.environ.get('AGENSHIELD_BROKER_HOST'):
|
|
34
|
+
_AGENSHIELD_BROKER_HOST = os.environ['AGENSHIELD_BROKER_HOST']
|
|
35
|
+
if os.environ.get('AGENSHIELD_BROKER_PORT'):
|
|
36
|
+
_AGENSHIELD_BROKER_PORT = int(os.environ['AGENSHIELD_BROKER_PORT'])
|
|
37
|
+
if os.environ.get('AGENSHIELD_LOG_LEVEL'):
|
|
38
|
+
_AGENSHIELD_LOG_LEVEL = os.environ['AGENSHIELD_LOG_LEVEL']
|
|
39
|
+
|
|
40
|
+
# Logging
|
|
41
|
+
def _agenshield_log(level, message):
|
|
42
|
+
levels = {'debug': 0, 'info': 1, 'warn': 2, 'error': 3}
|
|
43
|
+
if levels.get(level, 0) >= levels.get(_AGENSHIELD_LOG_LEVEL, 1):
|
|
44
|
+
print(f'[AgenShield] {level.upper()}: {message}', file=sys.stderr)
|
|
45
|
+
|
|
46
|
+
# Mark as patched
|
|
47
|
+
_agenshield_patched = True
|
|
48
|
+
|
|
49
|
+
if _AGENSHIELD_ENABLED:
|
|
50
|
+
_agenshield_log('info', 'Network isolation enabled')
|
|
51
|
+
|
|
52
|
+
# ========================================
|
|
53
|
+
# Socket Patching
|
|
54
|
+
# ========================================
|
|
55
|
+
|
|
56
|
+
_original_socket_connect = socket.socket.connect
|
|
57
|
+
_original_create_connection = socket.create_connection
|
|
58
|
+
|
|
59
|
+
def _agenshield_is_allowed(host, port):
|
|
60
|
+
"""Check if connection to host:port is allowed."""
|
|
61
|
+
# Always allow localhost broker
|
|
62
|
+
if host in ('localhost', '127.0.0.1', '::1') and port == _AGENSHIELD_BROKER_PORT:
|
|
63
|
+
return True
|
|
64
|
+
# Block everything else
|
|
65
|
+
return False
|
|
66
|
+
|
|
67
|
+
def _agenshield_socket_connect(self, address):
|
|
68
|
+
"""Patched socket.connect that blocks non-localhost connections."""
|
|
69
|
+
try:
|
|
70
|
+
host, port = address[:2]
|
|
71
|
+
except (TypeError, ValueError):
|
|
72
|
+
# Unix socket or other format
|
|
73
|
+
return _original_socket_connect(self, address)
|
|
74
|
+
|
|
75
|
+
if not _agenshield_is_allowed(host, port):
|
|
76
|
+
_agenshield_log('warn', f'Blocked connection to {host}:{port}')
|
|
77
|
+
raise ConnectionRefusedError(
|
|
78
|
+
f'AgenShield: Direct connections blocked. '
|
|
79
|
+
f'Use broker at {_AGENSHIELD_BROKER_HOST}:{_AGENSHIELD_BROKER_PORT}'
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
return _original_socket_connect(self, address)
|
|
83
|
+
|
|
84
|
+
def _agenshield_create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
|
|
85
|
+
source_address=None, *, all_errors=False):
|
|
86
|
+
"""Patched socket.create_connection."""
|
|
87
|
+
host, port = address
|
|
88
|
+
|
|
89
|
+
if not _agenshield_is_allowed(host, port):
|
|
90
|
+
_agenshield_log('warn', f'Blocked create_connection to {host}:{port}')
|
|
91
|
+
raise ConnectionRefusedError(
|
|
92
|
+
f'AgenShield: Direct connections blocked. '
|
|
93
|
+
f'Use broker at {_AGENSHIELD_BROKER_HOST}:{_AGENSHIELD_BROKER_PORT}'
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
return _original_create_connection(address, timeout, source_address,
|
|
97
|
+
all_errors=all_errors)
|
|
98
|
+
|
|
99
|
+
# Apply socket patches
|
|
100
|
+
socket.socket.connect = _agenshield_socket_connect
|
|
101
|
+
socket.create_connection = _agenshield_create_connection
|
|
102
|
+
|
|
103
|
+
# ========================================
|
|
104
|
+
# urllib3 Patching (if available)
|
|
105
|
+
# ========================================
|
|
106
|
+
|
|
107
|
+
try:
|
|
108
|
+
import urllib3.connection
|
|
109
|
+
import urllib3.util.connection
|
|
110
|
+
|
|
111
|
+
_original_urllib3_create_connection = urllib3.util.connection.create_connection
|
|
112
|
+
|
|
113
|
+
def _agenshield_urllib3_create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
|
|
114
|
+
source_address=None, socket_options=None):
|
|
115
|
+
"""Patched urllib3 create_connection."""
|
|
116
|
+
host, port = address
|
|
117
|
+
|
|
118
|
+
if not _agenshield_is_allowed(host, port):
|
|
119
|
+
_agenshield_log('warn', f'Blocked urllib3 connection to {host}:{port}')
|
|
120
|
+
raise ConnectionRefusedError(
|
|
121
|
+
f'AgenShield: Direct connections blocked. '
|
|
122
|
+
f'Use broker at {_AGENSHIELD_BROKER_HOST}:{_AGENSHIELD_BROKER_PORT}'
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
return _original_urllib3_create_connection(address, timeout, source_address,
|
|
126
|
+
socket_options)
|
|
127
|
+
|
|
128
|
+
urllib3.util.connection.create_connection = _agenshield_urllib3_create_connection
|
|
129
|
+
_agenshield_log('debug', 'Patched urllib3')
|
|
130
|
+
|
|
131
|
+
except ImportError:
|
|
132
|
+
_agenshield_log('debug', 'urllib3 not available, skipping patch')
|
|
133
|
+
|
|
134
|
+
# ========================================
|
|
135
|
+
# requests Patching (if available)
|
|
136
|
+
# ========================================
|
|
137
|
+
|
|
138
|
+
try:
|
|
139
|
+
import requests
|
|
140
|
+
import json
|
|
141
|
+
|
|
142
|
+
_original_requests_request = requests.Session.request
|
|
143
|
+
|
|
144
|
+
def _agenshield_requests_request(self, method, url, **kwargs):
|
|
145
|
+
"""Patched requests.Session.request that routes through broker."""
|
|
146
|
+
from urllib.parse import urlparse
|
|
147
|
+
|
|
148
|
+
parsed = urlparse(url)
|
|
149
|
+
|
|
150
|
+
# Allow broker connections
|
|
151
|
+
if parsed.netloc == f'{_AGENSHIELD_BROKER_HOST}:{_AGENSHIELD_BROKER_PORT}':
|
|
152
|
+
return _original_requests_request(self, method, url, **kwargs)
|
|
153
|
+
|
|
154
|
+
_agenshield_log('info', f'Routing {method} {url} through broker')
|
|
155
|
+
|
|
156
|
+
# Route through broker
|
|
157
|
+
broker_url = f'http://{_AGENSHIELD_BROKER_HOST}:{_AGENSHIELD_BROKER_PORT}/rpc'
|
|
158
|
+
|
|
159
|
+
# Prepare broker request
|
|
160
|
+
headers = dict(kwargs.get('headers', {}))
|
|
161
|
+
body = kwargs.get('data') or kwargs.get('json')
|
|
162
|
+
if isinstance(body, dict):
|
|
163
|
+
body = json.dumps(body)
|
|
164
|
+
|
|
165
|
+
broker_request = {
|
|
166
|
+
'jsonrpc': '2.0',
|
|
167
|
+
'id': '1',
|
|
168
|
+
'method': 'http_request',
|
|
169
|
+
'params': {
|
|
170
|
+
'url': url,
|
|
171
|
+
'method': method.upper(),
|
|
172
|
+
'headers': headers,
|
|
173
|
+
'body': body,
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
# Make broker request
|
|
178
|
+
response = _original_requests_request(
|
|
179
|
+
self, 'POST', broker_url,
|
|
180
|
+
json=broker_request,
|
|
181
|
+
timeout=kwargs.get('timeout', 30)
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
# Parse broker response
|
|
185
|
+
broker_response = response.json()
|
|
186
|
+
|
|
187
|
+
if 'error' in broker_response:
|
|
188
|
+
raise requests.exceptions.RequestException(
|
|
189
|
+
f"AgenShield: {broker_response['error']['message']}"
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
result = broker_response['result']
|
|
193
|
+
|
|
194
|
+
# Create fake response
|
|
195
|
+
fake_response = requests.models.Response()
|
|
196
|
+
fake_response.status_code = result['status']
|
|
197
|
+
fake_response._content = result['body'].encode('utf-8')
|
|
198
|
+
fake_response.headers = requests.structures.CaseInsensitiveDict(result['headers'])
|
|
199
|
+
fake_response.url = url
|
|
200
|
+
fake_response.request = None
|
|
201
|
+
|
|
202
|
+
return fake_response
|
|
203
|
+
|
|
204
|
+
requests.Session.request = _agenshield_requests_request
|
|
205
|
+
_agenshield_log('debug', 'Patched requests')
|
|
206
|
+
|
|
207
|
+
except ImportError:
|
|
208
|
+
_agenshield_log('debug', 'requests not available, skipping patch')
|
|
209
|
+
|
|
210
|
+
# ========================================
|
|
211
|
+
# aiohttp Patching (if available)
|
|
212
|
+
# ========================================
|
|
213
|
+
|
|
214
|
+
try:
|
|
215
|
+
import aiohttp
|
|
216
|
+
|
|
217
|
+
_original_aiohttp_request = aiohttp.ClientSession._request
|
|
218
|
+
|
|
219
|
+
async def _agenshield_aiohttp_request(self, method, url, **kwargs):
|
|
220
|
+
"""Patched aiohttp request."""
|
|
221
|
+
from urllib.parse import urlparse
|
|
222
|
+
|
|
223
|
+
parsed = urlparse(str(url))
|
|
224
|
+
|
|
225
|
+
# Allow broker connections
|
|
226
|
+
if parsed.netloc == f'{_AGENSHIELD_BROKER_HOST}:{_AGENSHIELD_BROKER_PORT}':
|
|
227
|
+
return await _original_aiohttp_request(self, method, url, **kwargs)
|
|
228
|
+
|
|
229
|
+
_agenshield_log('warn', f'Blocked aiohttp request to {url}')
|
|
230
|
+
raise aiohttp.ClientError(
|
|
231
|
+
f'AgenShield: Direct connections blocked. '
|
|
232
|
+
f'Use broker at {_AGENSHIELD_BROKER_HOST}:{_AGENSHIELD_BROKER_PORT}'
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
aiohttp.ClientSession._request = _agenshield_aiohttp_request
|
|
236
|
+
_agenshield_log('debug', 'Patched aiohttp')
|
|
237
|
+
|
|
238
|
+
except ImportError:
|
|
239
|
+
_agenshield_log('debug', 'aiohttp not available, skipping patch')
|
|
240
|
+
|
|
241
|
+
_agenshield_log('info', 'Network isolation patches applied')
|
|
242
|
+
|
|
243
|
+
else:
|
|
244
|
+
_agenshield_log('info', 'Network isolation disabled')
|
|
245
|
+
`;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// libs/shield-patcher/src/python/wrapper.ts
|
|
249
|
+
function generatePythonWrapper(config) {
|
|
250
|
+
const envVars = Object.entries(config.environmentVariables || {}).map(([key, value]) => `export ${key}="${value}"`).join("\n");
|
|
251
|
+
if (config.useSandbox && config.sandboxProfilePath) {
|
|
252
|
+
return `#!/bin/bash
|
|
253
|
+
# AgenShield Python Wrapper
|
|
254
|
+
# Generated by @agenshield/patcher
|
|
255
|
+
|
|
256
|
+
set -e
|
|
257
|
+
|
|
258
|
+
# Environment setup
|
|
259
|
+
export PYTHONDONTWRITEBYTECODE=1
|
|
260
|
+
${envVars}
|
|
261
|
+
|
|
262
|
+
# Run Python under sandbox-exec
|
|
263
|
+
exec /usr/bin/sandbox-exec -f "${config.sandboxProfilePath}" \\
|
|
264
|
+
"${config.pythonPath}" "$@"
|
|
265
|
+
`;
|
|
266
|
+
}
|
|
267
|
+
return `#!/bin/bash
|
|
268
|
+
# AgenShield Python Wrapper
|
|
269
|
+
# Generated by @agenshield/patcher
|
|
270
|
+
|
|
271
|
+
set -e
|
|
272
|
+
|
|
273
|
+
# Environment setup
|
|
274
|
+
export PYTHONDONTWRITEBYTECODE=1
|
|
275
|
+
${envVars}
|
|
276
|
+
|
|
277
|
+
# Ensure sitecustomize is loaded
|
|
278
|
+
export PYTHONPATH="${config.sitecustomizePath}:\${PYTHONPATH:-}"
|
|
279
|
+
|
|
280
|
+
# Run Python
|
|
281
|
+
exec "${config.pythonPath}" "$@"
|
|
282
|
+
`;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// libs/shield-patcher/src/python/sandbox-profile.ts
|
|
286
|
+
function generateSandboxProfile(config) {
|
|
287
|
+
const additionalReadPaths = (config.additionalReadPaths || []).map((p) => `(allow file-read* (subpath "${p}"))`).join("\n");
|
|
288
|
+
const additionalWritePaths = (config.additionalWritePaths || []).map((p) => `(allow file-write* (subpath "${p}"))`).join("\n");
|
|
289
|
+
return `;;
|
|
290
|
+
;; AgenShield Python Sandbox Profile
|
|
291
|
+
;; Generated by @agenshield/patcher
|
|
292
|
+
;;
|
|
293
|
+
|
|
294
|
+
(version 1)
|
|
295
|
+
(deny default)
|
|
296
|
+
|
|
297
|
+
;; ========================================
|
|
298
|
+
;; System Libraries & Frameworks
|
|
299
|
+
;; ========================================
|
|
300
|
+
(allow file-read*
|
|
301
|
+
(subpath "/System")
|
|
302
|
+
(subpath "/usr/lib")
|
|
303
|
+
(subpath "/usr/share")
|
|
304
|
+
(subpath "/Library/Frameworks")
|
|
305
|
+
(subpath "/private/var/db")
|
|
306
|
+
(subpath "/private/etc"))
|
|
307
|
+
|
|
308
|
+
;; ========================================
|
|
309
|
+
;; Python Installation
|
|
310
|
+
;; ========================================
|
|
311
|
+
(allow file-read*
|
|
312
|
+
(subpath "${config.pythonPath}")
|
|
313
|
+
(subpath "/Library/Frameworks/Python.framework")
|
|
314
|
+
(subpath "/usr/local/lib/python")
|
|
315
|
+
(subpath "/opt/homebrew/lib/python")
|
|
316
|
+
(subpath "/usr/local/Cellar/python"))
|
|
317
|
+
|
|
318
|
+
;; Python needs to read its own files
|
|
319
|
+
(allow file-read*
|
|
320
|
+
(regex #".*\\.py$")
|
|
321
|
+
(regex #".*\\.pyc$")
|
|
322
|
+
(regex #".*\\.pyo$")
|
|
323
|
+
(regex #".*\\.so$")
|
|
324
|
+
(regex #".*\\.dylib$"))
|
|
325
|
+
|
|
326
|
+
;; ========================================
|
|
327
|
+
;; Workspace Access (Read/Write)
|
|
328
|
+
;; ========================================
|
|
329
|
+
(allow file-read* file-write*
|
|
330
|
+
(subpath "${config.workspacePath}"))
|
|
331
|
+
|
|
332
|
+
;; Temp directories
|
|
333
|
+
(allow file-read* file-write*
|
|
334
|
+
(subpath "/tmp")
|
|
335
|
+
(subpath "/private/tmp")
|
|
336
|
+
(subpath "/var/folders"))
|
|
337
|
+
|
|
338
|
+
;; ========================================
|
|
339
|
+
;; Additional Paths
|
|
340
|
+
;; ========================================
|
|
341
|
+
${additionalReadPaths}
|
|
342
|
+
${additionalWritePaths}
|
|
343
|
+
|
|
344
|
+
;; ========================================
|
|
345
|
+
;; Network (RESTRICTED)
|
|
346
|
+
;; ========================================
|
|
347
|
+
|
|
348
|
+
;; Block all network by default
|
|
349
|
+
(deny network*)
|
|
350
|
+
|
|
351
|
+
;; Allow ONLY broker connection
|
|
352
|
+
(allow network-outbound
|
|
353
|
+
(remote tcp "${config.brokerHost}:${config.brokerPort}"))
|
|
354
|
+
|
|
355
|
+
;; Allow localhost loopback for broker
|
|
356
|
+
(allow network-outbound
|
|
357
|
+
(remote tcp "localhost:${config.brokerPort}")
|
|
358
|
+
(remote tcp "127.0.0.1:${config.brokerPort}"))
|
|
359
|
+
|
|
360
|
+
;; ========================================
|
|
361
|
+
;; Process & Signal
|
|
362
|
+
;; ========================================
|
|
363
|
+
(allow process-fork)
|
|
364
|
+
(allow process-exec
|
|
365
|
+
(literal "${config.pythonPath}")
|
|
366
|
+
(literal "/usr/bin/env")
|
|
367
|
+
(literal "/bin/sh")
|
|
368
|
+
(subpath "/usr/local/bin"))
|
|
369
|
+
|
|
370
|
+
(allow signal (target self))
|
|
371
|
+
(allow sysctl-read)
|
|
372
|
+
|
|
373
|
+
;; ========================================
|
|
374
|
+
;; Mach IPC (Limited)
|
|
375
|
+
;; ========================================
|
|
376
|
+
(allow mach-lookup
|
|
377
|
+
(global-name "com.apple.system.opendirectoryd.libinfo")
|
|
378
|
+
(global-name "com.apple.system.notification_center")
|
|
379
|
+
(global-name "com.apple.CoreServices.coreservicesd")
|
|
380
|
+
(global-name "com.apple.SecurityServer"))
|
|
381
|
+
|
|
382
|
+
;; ========================================
|
|
383
|
+
;; User Defaults (Read-only)
|
|
384
|
+
;; ========================================
|
|
385
|
+
(allow user-preference-read)
|
|
386
|
+
`;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// libs/shield-patcher/src/install.ts
|
|
390
|
+
var execAsync = promisify(exec);
|
|
391
|
+
var PythonPatcher = class {
|
|
392
|
+
config;
|
|
393
|
+
constructor(config) {
|
|
394
|
+
this.config = {
|
|
395
|
+
pythonPath: config.pythonPath,
|
|
396
|
+
brokerHost: config.brokerHost || "localhost",
|
|
397
|
+
brokerPort: config.brokerPort || 5200,
|
|
398
|
+
useSandbox: config.useSandbox ?? true,
|
|
399
|
+
workspacePath: config.workspacePath || "/Users/clawagent/workspace",
|
|
400
|
+
socketPath: config.socketPath || "/var/run/agenshield/agenshield.sock",
|
|
401
|
+
installDir: config.installDir
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Install the Python patcher
|
|
406
|
+
*/
|
|
407
|
+
async install() {
|
|
408
|
+
try {
|
|
409
|
+
const sitePackages = await this.getSitePackagesDir();
|
|
410
|
+
const sitecustomizePath = path.join(sitePackages, "sitecustomize.py");
|
|
411
|
+
const sitecustomizeContent = generateSitecustomize({
|
|
412
|
+
brokerHost: this.config.brokerHost,
|
|
413
|
+
brokerPort: this.config.brokerPort,
|
|
414
|
+
logLevel: "warn",
|
|
415
|
+
enabled: true
|
|
416
|
+
});
|
|
417
|
+
await fs.writeFile(sitecustomizePath, sitecustomizeContent, {
|
|
418
|
+
mode: 420
|
|
419
|
+
});
|
|
420
|
+
const result = {
|
|
421
|
+
success: true,
|
|
422
|
+
message: "Python patcher installed successfully",
|
|
423
|
+
paths: {
|
|
424
|
+
sitecustomize: sitecustomizePath
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
if (this.config.installDir) {
|
|
428
|
+
const wrapperPath = path.join(this.config.installDir, "python");
|
|
429
|
+
const wrapperContent = generatePythonWrapper({
|
|
430
|
+
pythonPath: this.config.pythonPath,
|
|
431
|
+
sitecustomizePath,
|
|
432
|
+
useSandbox: this.config.useSandbox,
|
|
433
|
+
sandboxProfilePath: this.config.useSandbox ? "/etc/agenshield/seatbelt/python.sb" : void 0
|
|
434
|
+
});
|
|
435
|
+
await fs.writeFile(wrapperPath, wrapperContent, { mode: 493 });
|
|
436
|
+
result.paths.wrapper = wrapperPath;
|
|
437
|
+
if (this.config.useSandbox) {
|
|
438
|
+
const profilePath = "/etc/agenshield/seatbelt/python.sb";
|
|
439
|
+
const profileDir = path.dirname(profilePath);
|
|
440
|
+
await fs.mkdir(profileDir, { recursive: true });
|
|
441
|
+
const profileContent = generateSandboxProfile({
|
|
442
|
+
workspacePath: this.config.workspacePath,
|
|
443
|
+
pythonPath: this.config.pythonPath,
|
|
444
|
+
brokerHost: this.config.brokerHost,
|
|
445
|
+
brokerPort: this.config.brokerPort
|
|
446
|
+
});
|
|
447
|
+
await fs.writeFile(profilePath, profileContent, { mode: 420 });
|
|
448
|
+
result.paths.sandboxProfile = profilePath;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
return result;
|
|
452
|
+
} catch (error) {
|
|
453
|
+
return {
|
|
454
|
+
success: false,
|
|
455
|
+
message: `Installation failed: ${error.message}`,
|
|
456
|
+
error
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Uninstall the Python patcher
|
|
462
|
+
*/
|
|
463
|
+
async uninstall() {
|
|
464
|
+
try {
|
|
465
|
+
const sitePackages = await this.getSitePackagesDir();
|
|
466
|
+
const sitecustomizePath = path.join(sitePackages, "sitecustomize.py");
|
|
467
|
+
try {
|
|
468
|
+
const content = await fs.readFile(sitecustomizePath, "utf-8");
|
|
469
|
+
if (!content.includes("AgenShield")) {
|
|
470
|
+
return {
|
|
471
|
+
success: false,
|
|
472
|
+
message: "sitecustomize.py does not appear to be AgenShield installation"
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
await fs.unlink(sitecustomizePath);
|
|
476
|
+
} catch (error) {
|
|
477
|
+
if (error.code !== "ENOENT") {
|
|
478
|
+
throw error;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
if (this.config.installDir) {
|
|
482
|
+
const wrapperPath = path.join(this.config.installDir, "python");
|
|
483
|
+
try {
|
|
484
|
+
await fs.unlink(wrapperPath);
|
|
485
|
+
} catch {
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
return {
|
|
489
|
+
success: true,
|
|
490
|
+
message: "Python patcher uninstalled successfully"
|
|
491
|
+
};
|
|
492
|
+
} catch (error) {
|
|
493
|
+
return {
|
|
494
|
+
success: false,
|
|
495
|
+
message: `Uninstallation failed: ${error.message}`,
|
|
496
|
+
error
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* Check if patcher is installed
|
|
502
|
+
*/
|
|
503
|
+
async isInstalled() {
|
|
504
|
+
try {
|
|
505
|
+
const sitePackages = await this.getSitePackagesDir();
|
|
506
|
+
const sitecustomizePath = path.join(sitePackages, "sitecustomize.py");
|
|
507
|
+
const content = await fs.readFile(sitecustomizePath, "utf-8");
|
|
508
|
+
return content.includes("AgenShield");
|
|
509
|
+
} catch {
|
|
510
|
+
return false;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Get Python version
|
|
515
|
+
*/
|
|
516
|
+
async getPythonVersion() {
|
|
517
|
+
const { stdout } = await execAsync(`${this.config.pythonPath} --version`);
|
|
518
|
+
return stdout.trim();
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* Get site-packages directory
|
|
522
|
+
*/
|
|
523
|
+
async getSitePackagesDir() {
|
|
524
|
+
const { stdout } = await execAsync(
|
|
525
|
+
`${this.config.pythonPath} -c "import site; print(site.getsitepackages()[0])"`
|
|
526
|
+
);
|
|
527
|
+
return stdout.trim();
|
|
528
|
+
}
|
|
529
|
+
};
|
|
530
|
+
|
|
531
|
+
// libs/shield-patcher/src/verify.ts
|
|
532
|
+
import { exec as exec2 } from "node:child_process";
|
|
533
|
+
import { promisify as promisify2 } from "node:util";
|
|
534
|
+
var execAsync2 = promisify2(exec2);
|
|
535
|
+
var PythonVerifier = class {
|
|
536
|
+
pythonPath;
|
|
537
|
+
brokerHost;
|
|
538
|
+
brokerPort;
|
|
539
|
+
constructor(options) {
|
|
540
|
+
this.pythonPath = options.pythonPath;
|
|
541
|
+
this.brokerHost = options.brokerHost || "localhost";
|
|
542
|
+
this.brokerPort = options.brokerPort || 5200;
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* Verify the Python patcher installation
|
|
546
|
+
*/
|
|
547
|
+
async verify() {
|
|
548
|
+
const details = [];
|
|
549
|
+
let success = true;
|
|
550
|
+
let pythonVersion = "unknown";
|
|
551
|
+
try {
|
|
552
|
+
const { stdout } = await execAsync2(`${this.pythonPath} --version`);
|
|
553
|
+
pythonVersion = stdout.trim();
|
|
554
|
+
details.push(`Python version: ${pythonVersion}`);
|
|
555
|
+
} catch (error) {
|
|
556
|
+
details.push(`Failed to get Python version: ${error.message}`);
|
|
557
|
+
success = false;
|
|
558
|
+
}
|
|
559
|
+
let sitecustomizeInstalled = false;
|
|
560
|
+
try {
|
|
561
|
+
const { stdout } = await execAsync2(
|
|
562
|
+
`${this.pythonPath} -c "import sitecustomize; print('AgenShield' in dir(sitecustomize) or hasattr(sitecustomize, '_agenshield_patched'))"`
|
|
563
|
+
);
|
|
564
|
+
sitecustomizeInstalled = stdout.trim() === "True";
|
|
565
|
+
details.push(
|
|
566
|
+
sitecustomizeInstalled ? "sitecustomize.py: AgenShield patch found" : "sitecustomize.py: AgenShield patch NOT found"
|
|
567
|
+
);
|
|
568
|
+
} catch {
|
|
569
|
+
details.push("sitecustomize.py: Not installed or error loading");
|
|
570
|
+
}
|
|
571
|
+
let networkBlocked = false;
|
|
572
|
+
try {
|
|
573
|
+
const { stderr } = await execAsync2(
|
|
574
|
+
`${this.pythonPath} -c "import socket; socket.create_connection(('example.com', 80), timeout=5)" 2>&1`,
|
|
575
|
+
{ timeout: 1e4 }
|
|
576
|
+
);
|
|
577
|
+
details.push("Network blocking: DISABLED (direct connections allowed)");
|
|
578
|
+
} catch (error) {
|
|
579
|
+
const message = error.message;
|
|
580
|
+
if (message.includes("AgenShield") || message.includes("Connection refused") || message.includes("blocked")) {
|
|
581
|
+
networkBlocked = true;
|
|
582
|
+
details.push("Network blocking: ENABLED");
|
|
583
|
+
} else {
|
|
584
|
+
details.push(`Network blocking: Unknown (${message})`);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
let brokerAccessible = false;
|
|
588
|
+
try {
|
|
589
|
+
const script = `
|
|
590
|
+
import urllib.request
|
|
591
|
+
import json
|
|
592
|
+
|
|
593
|
+
req = urllib.request.Request(
|
|
594
|
+
'http://${this.brokerHost}:${this.brokerPort}/health',
|
|
595
|
+
method='GET'
|
|
596
|
+
)
|
|
597
|
+
with urllib.request.urlopen(req, timeout=5) as response:
|
|
598
|
+
data = json.loads(response.read())
|
|
599
|
+
print('ok' if data.get('status') == 'ok' else 'error')
|
|
600
|
+
`;
|
|
601
|
+
const { stdout } = await execAsync2(`${this.pythonPath} -c "${script}"`, {
|
|
602
|
+
timeout: 1e4
|
|
603
|
+
});
|
|
604
|
+
brokerAccessible = stdout.trim() === "ok";
|
|
605
|
+
details.push(
|
|
606
|
+
brokerAccessible ? "Broker: Accessible" : "Broker: Not accessible (check if running)"
|
|
607
|
+
);
|
|
608
|
+
} catch {
|
|
609
|
+
details.push("Broker: Not accessible");
|
|
610
|
+
}
|
|
611
|
+
success = sitecustomizeInstalled && networkBlocked && brokerAccessible;
|
|
612
|
+
return {
|
|
613
|
+
success,
|
|
614
|
+
pythonVersion,
|
|
615
|
+
sitecustomizeInstalled,
|
|
616
|
+
networkBlocked,
|
|
617
|
+
brokerAccessible,
|
|
618
|
+
details
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
};
|
|
622
|
+
async function verifyPython(pythonPath) {
|
|
623
|
+
const verifier = new PythonVerifier({ pythonPath });
|
|
624
|
+
return verifier.verify();
|
|
625
|
+
}
|
|
626
|
+
export {
|
|
627
|
+
PythonPatcher,
|
|
628
|
+
PythonVerifier,
|
|
629
|
+
generatePythonWrapper,
|
|
630
|
+
generateSandboxProfile,
|
|
631
|
+
generateSitecustomize,
|
|
632
|
+
verifyPython
|
|
633
|
+
};
|
package/install.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Python Patcher Installation
|
|
3
|
+
*/
|
|
4
|
+
import type { PatcherConfig, PatcherResult } from './types.js';
|
|
5
|
+
export declare class PythonPatcher {
|
|
6
|
+
private config;
|
|
7
|
+
constructor(config: Partial<PatcherConfig> & {
|
|
8
|
+
pythonPath: string;
|
|
9
|
+
});
|
|
10
|
+
/**
|
|
11
|
+
* Install the Python patcher
|
|
12
|
+
*/
|
|
13
|
+
install(): Promise<PatcherResult>;
|
|
14
|
+
/**
|
|
15
|
+
* Uninstall the Python patcher
|
|
16
|
+
*/
|
|
17
|
+
uninstall(): Promise<PatcherResult>;
|
|
18
|
+
/**
|
|
19
|
+
* Check if patcher is installed
|
|
20
|
+
*/
|
|
21
|
+
isInstalled(): Promise<boolean>;
|
|
22
|
+
/**
|
|
23
|
+
* Get Python version
|
|
24
|
+
*/
|
|
25
|
+
getPythonVersion(): Promise<string>;
|
|
26
|
+
/**
|
|
27
|
+
* Get site-packages directory
|
|
28
|
+
*/
|
|
29
|
+
private getSitePackagesDir;
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=install.d.ts.map
|
package/install.d.ts.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"install.d.ts","sourceRoot":"","sources":["../src/install.ts"],"names":[],"mappings":"AAAA;;GAEG;AAMH,OAAO,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAS/D,qBAAa,aAAa;IACxB,OAAO,CAAC,MAAM,CAAgB;gBAElB,MAAM,EAAE,OAAO,CAAC,aAAa,CAAC,GAAG;QAAE,UAAU,EAAE,MAAM,CAAA;KAAE;IAYnE;;OAEG;IACG,OAAO,IAAI,OAAO,CAAC,aAAa,CAAC;IAsEvC;;OAEG;IACG,SAAS,IAAI,OAAO,CAAC,aAAa,CAAC;IA6CzC;;OAEG;IACG,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC;IAYrC;;OAEG;IACG,gBAAgB,IAAI,OAAO,CAAC,MAAM,CAAC;IAKzC;;OAEG;YACW,kBAAkB;CAMjC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@agenshield/patcher",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Python network isolation via sitecustomize.py patching",
|
|
6
|
+
"main": "./index.js",
|
|
7
|
+
"types": "./index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
"./package.json": "./package.json",
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./index.d.ts",
|
|
12
|
+
"import": "./index.js",
|
|
13
|
+
"default": "./index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@agenshield/ipc": "0.1.0"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"@types/node": "^24.0.0",
|
|
22
|
+
"tsx": "^4.21.0",
|
|
23
|
+
"typescript": "^5.9.3"
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/python/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AACrD,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sandbox-profile.d.ts","sourceRoot":"","sources":["../../src/python/sandbox-profile.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAExD,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,oBAAoB,GAAG,MAAM,CA2G3E"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sitecustomize.d.ts","sourceRoot":"","sources":["../../src/python/sitecustomize.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAEvD,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,mBAAmB,GAAG,MAAM,CA8OzE"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wrapper.d.ts","sourceRoot":"","sources":["../../src/python/wrapper.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEjD,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,aAAa,GAAG,MAAM,CAsCnE"}
|
package/types.d.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Python Patcher Types
|
|
3
|
+
*/
|
|
4
|
+
export interface PatcherConfig {
|
|
5
|
+
/** Path to Python executable */
|
|
6
|
+
pythonPath: string;
|
|
7
|
+
/** Broker HTTP host */
|
|
8
|
+
brokerHost: string;
|
|
9
|
+
/** Broker HTTP port */
|
|
10
|
+
brokerPort: number;
|
|
11
|
+
/** Whether to use macOS sandbox */
|
|
12
|
+
useSandbox: boolean;
|
|
13
|
+
/** Workspace directory */
|
|
14
|
+
workspacePath: string;
|
|
15
|
+
/** Broker socket path */
|
|
16
|
+
socketPath: string;
|
|
17
|
+
/** Installation target directory */
|
|
18
|
+
installDir?: string;
|
|
19
|
+
}
|
|
20
|
+
export interface PatcherResult {
|
|
21
|
+
success: boolean;
|
|
22
|
+
message: string;
|
|
23
|
+
paths?: {
|
|
24
|
+
sitecustomize: string;
|
|
25
|
+
wrapper?: string;
|
|
26
|
+
sandboxProfile?: string;
|
|
27
|
+
};
|
|
28
|
+
error?: Error;
|
|
29
|
+
}
|
|
30
|
+
export interface VerificationResult {
|
|
31
|
+
success: boolean;
|
|
32
|
+
pythonVersion: string;
|
|
33
|
+
sitecustomizeInstalled: boolean;
|
|
34
|
+
networkBlocked: boolean;
|
|
35
|
+
brokerAccessible: boolean;
|
|
36
|
+
details: string[];
|
|
37
|
+
}
|
|
38
|
+
export interface SitecustomizeConfig {
|
|
39
|
+
brokerHost: string;
|
|
40
|
+
brokerPort: number;
|
|
41
|
+
logLevel: 'debug' | 'info' | 'warn' | 'error';
|
|
42
|
+
enabled: boolean;
|
|
43
|
+
}
|
|
44
|
+
export interface WrapperConfig {
|
|
45
|
+
pythonPath: string;
|
|
46
|
+
sitecustomizePath: string;
|
|
47
|
+
useSandbox: boolean;
|
|
48
|
+
sandboxProfilePath?: string;
|
|
49
|
+
environmentVariables?: Record<string, string>;
|
|
50
|
+
}
|
|
51
|
+
export interface SandboxProfileConfig {
|
|
52
|
+
workspacePath: string;
|
|
53
|
+
pythonPath: string;
|
|
54
|
+
brokerHost: string;
|
|
55
|
+
brokerPort: number;
|
|
56
|
+
additionalReadPaths?: string[];
|
|
57
|
+
additionalWritePaths?: string[];
|
|
58
|
+
}
|
|
59
|
+
//# sourceMappingURL=types.d.ts.map
|
package/types.d.ts.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,MAAM,WAAW,aAAa;IAC5B,gCAAgC;IAChC,UAAU,EAAE,MAAM,CAAC;IAEnB,uBAAuB;IACvB,UAAU,EAAE,MAAM,CAAC;IAEnB,uBAAuB;IACvB,UAAU,EAAE,MAAM,CAAC;IAEnB,mCAAmC;IACnC,UAAU,EAAE,OAAO,CAAC;IAEpB,0BAA0B;IAC1B,aAAa,EAAE,MAAM,CAAC;IAEtB,yBAAyB;IACzB,UAAU,EAAE,MAAM,CAAC;IAEnB,oCAAoC;IACpC,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,aAAa;IAC5B,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE;QACN,aAAa,EAAE,MAAM,CAAC;QACtB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,cAAc,CAAC,EAAE,MAAM,CAAC;KACzB,CAAC;IACF,KAAK,CAAC,EAAE,KAAK,CAAC;CACf;AAED,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,OAAO,CAAC;IACjB,aAAa,EAAE,MAAM,CAAC;IACtB,sBAAsB,EAAE,OAAO,CAAC;IAChC,cAAc,EAAE,OAAO,CAAC;IACxB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,OAAO,EAAE,MAAM,EAAE,CAAC;CACnB;AAED,MAAM,WAAW,mBAAmB;IAClC,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;IAC9C,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,aAAa;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,UAAU,EAAE,OAAO,CAAC;IACpB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,oBAAoB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC/C;AAED,MAAM,WAAW,oBAAoB;IACnC,aAAa,EAAE,MAAM,CAAC;IACtB,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,mBAAmB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC/B,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;CACjC"}
|
package/verify.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Python Patcher Verification
|
|
3
|
+
*/
|
|
4
|
+
import type { VerificationResult } from './types.js';
|
|
5
|
+
export declare class PythonVerifier {
|
|
6
|
+
private pythonPath;
|
|
7
|
+
private brokerHost;
|
|
8
|
+
private brokerPort;
|
|
9
|
+
constructor(options: {
|
|
10
|
+
pythonPath: string;
|
|
11
|
+
brokerHost?: string;
|
|
12
|
+
brokerPort?: number;
|
|
13
|
+
});
|
|
14
|
+
/**
|
|
15
|
+
* Verify the Python patcher installation
|
|
16
|
+
*/
|
|
17
|
+
verify(): Promise<VerificationResult>;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Quick verification function
|
|
21
|
+
*/
|
|
22
|
+
export declare function verifyPython(pythonPath: string): Promise<VerificationResult>;
|
|
23
|
+
//# sourceMappingURL=verify.d.ts.map
|
package/verify.d.ts.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"verify.d.ts","sourceRoot":"","sources":["../src/verify.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAIrD,qBAAa,cAAc;IACzB,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,UAAU,CAAS;gBAEf,OAAO,EAAE;QACnB,UAAU,EAAE,MAAM,CAAC;QACnB,UAAU,CAAC,EAAE,MAAM,CAAC;QACpB,UAAU,CAAC,EAAE,MAAM,CAAC;KACrB;IAMD;;OAEG;IACG,MAAM,IAAI,OAAO,CAAC,kBAAkB,CAAC;CA8F5C;AAED;;GAEG;AACH,wBAAsB,YAAY,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAGlF"}
|