zscams 1.0.0__py2.py3-none-any.whl

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.
Files changed (49) hide show
  1. zscams/__init__.py +7 -0
  2. zscams/__main__.py +151 -0
  3. zscams/agent/__init__.py +265 -0
  4. zscams/agent/configuration/config.j2 +72 -0
  5. zscams/agent/configuration/freebsd_service.j2 +24 -0
  6. zscams/agent/configuration/linux_service.j2 +13 -0
  7. zscams/agent/src/__init__.py +0 -0
  8. zscams/agent/src/core/__init__.py +4 -0
  9. zscams/agent/src/core/backend/bootstrap.py +298 -0
  10. zscams/agent/src/core/backend/client.py +596 -0
  11. zscams/agent/src/core/backend/exceptions.py +25 -0
  12. zscams/agent/src/core/backend/unbootstrap.py +98 -0
  13. zscams/agent/src/core/backend/update_machine_info.py +24 -0
  14. zscams/agent/src/core/heartbeat.py +66 -0
  15. zscams/agent/src/core/prerequisites.py +48 -0
  16. zscams/agent/src/core/service_health_check.py +69 -0
  17. zscams/agent/src/core/services.py +128 -0
  18. zscams/agent/src/core/tunnel/__init__.py +168 -0
  19. zscams/agent/src/core/tunnel/tls.py +58 -0
  20. zscams/agent/src/core/tunnels.py +50 -0
  21. zscams/agent/src/services/__init__.py +0 -0
  22. zscams/agent/src/services/reverse_ssh.py +76 -0
  23. zscams/agent/src/services/ssh_forwarder.py +75 -0
  24. zscams/agent/src/services/system_monitor.py +256 -0
  25. zscams/agent/src/support/__init__.py +0 -0
  26. zscams/agent/src/support/allow_command.py +147 -0
  27. zscams/agent/src/support/cli.py +247 -0
  28. zscams/agent/src/support/configuration.py +185 -0
  29. zscams/agent/src/support/dev_runtime.py +199 -0
  30. zscams/agent/src/support/dicts.py +20 -0
  31. zscams/agent/src/support/filesystem.py +95 -0
  32. zscams/agent/src/support/fqdn.py +22 -0
  33. zscams/agent/src/support/log_sanitize.py +94 -0
  34. zscams/agent/src/support/logger.py +116 -0
  35. zscams/agent/src/support/login_shell_guard.py +209 -0
  36. zscams/agent/src/support/machine_id.py +36 -0
  37. zscams/agent/src/support/network.py +55 -0
  38. zscams/agent/src/support/openssl.py +122 -0
  39. zscams/agent/src/support/os.py +537 -0
  40. zscams/agent/src/support/platform.py +37 -0
  41. zscams/agent/src/support/requests.py +35 -0
  42. zscams/agent/src/support/ssh.py +35 -0
  43. zscams/agent/src/support/subprocess_compat.py +53 -0
  44. zscams/agent/src/support/yaml.py +42 -0
  45. zscams/deps.py +99 -0
  46. zscams-1.0.0.dist-info/METADATA +120 -0
  47. zscams-1.0.0.dist-info/RECORD +49 -0
  48. zscams-1.0.0.dist-info/WHEEL +4 -0
  49. zscams-1.0.0.dist-info/entry_points.txt +3 -0
zscams/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ from __future__ import absolute_import, division, print_function
2
+
3
+ __version__ = "1.0.0"
4
+
5
+ from zscams.deps import ensure_native_deps
6
+
7
+ ensure_native_deps()
zscams/__main__.py ADDED
@@ -0,0 +1,151 @@
1
+ """
2
+ Main entry point for ZSCAMs Agent
3
+ """
4
+ from __future__ import absolute_import, division, print_function
5
+
6
+ import os
7
+ import sys
8
+ from zscams.agent.src.core.backend.bootstrap import bootstrap
9
+ from zscams.agent.src.core.backend.unbootstrap import unbootstrap
10
+ from zscams.agent.src.core.backend.update_machine_info import update_machine_info
11
+ from zscams.agent.src.core.backend.client import backend_client
12
+ from zscams.agent.src.support.allow_command import allow_command
13
+ from zscams.agent.src.support.configuration import config
14
+ from zscams.agent.src.support.dev_runtime import (
15
+ apply_runtime_overrides,
16
+ is_dev_mode,
17
+ )
18
+ from zscams.agent.src.support.logger import configure_logging, get_logger, report_error
19
+ from zscams.agent import (
20
+ init_parser,
21
+ ensure_bootstrapped,
22
+ run,
23
+ validate_autonomous_args,
24
+ bootstrap_kwargs,
25
+ auth_kwargs,
26
+ )
27
+ from zscams.agent.src.support.os import ensure_fapolicyd_python_trust, running_as_root
28
+
29
+ logger = get_logger("ZSCAMs")
30
+
31
+
32
+ def _exit_cancelled():
33
+ logger.info("Cancelled.")
34
+ _force_exit(130)
35
+
36
+
37
+ def _force_exit(code):
38
+ """Exit immediately so the process does not hang under debugpy/SystemExit traps."""
39
+ try:
40
+ sys.stdout.flush()
41
+ sys.stderr.flush()
42
+ except Exception:
43
+ pass
44
+ os._exit(code)
45
+
46
+
47
+ def _apply_runtime(args):
48
+ """Apply --dev / config-dir / server overrides and refresh the backend client."""
49
+ applied = apply_runtime_overrides(
50
+ config,
51
+ persist_overlay=True,
52
+ config_dir=getattr(args, "config_dir", None),
53
+ base_url=getattr(args, "base_url", None),
54
+ remote_host=getattr(args, "remote_host", None),
55
+ )
56
+ backend_client.refresh_from_config()
57
+
58
+ if is_dev_mode():
59
+ logger.info(
60
+ "Dev mode: config_dir=%s base_url=%s remote_host=%s",
61
+ config.get("config_dir"),
62
+ config.get("bootstrap.base_url"),
63
+ config.get("remote.host"),
64
+ )
65
+ elif applied:
66
+ logger.info(
67
+ "Runtime overrides applied: %s",
68
+ ", ".join("{0}={1}".format(k, v) for k, v in applied.items()),
69
+ )
70
+
71
+
72
+ def _require_root_unless_dev():
73
+ if is_dev_mode():
74
+ return
75
+ if not running_as_root():
76
+ logger.error("You are NOT running as root.")
77
+ _force_exit(1)
78
+
79
+
80
+ def main():
81
+ """Main function to run the asynchronous main."""
82
+ args = init_parser().parse_args()
83
+ configure_logging(debug=getattr(args, "debug", False))
84
+ validate_autonomous_args(args)
85
+ _apply_runtime(args)
86
+
87
+ if getattr(args, "allow_command", None):
88
+ try:
89
+ allow_command(args.allow_command)
90
+ _force_exit(0)
91
+ except KeyboardInterrupt:
92
+ _exit_cancelled()
93
+ except Exception as exception:
94
+ report_error(logger, exception, context="allow-command failed")
95
+ _force_exit(1)
96
+
97
+ if args.bootstrap:
98
+ try:
99
+ _require_root_unless_dev()
100
+ bootstrap(**bootstrap_kwargs(args))
101
+ _force_exit(0)
102
+ except KeyboardInterrupt:
103
+ _exit_cancelled()
104
+ except Exception as exception:
105
+ report_error(logger, exception, context="Bootstrap failed")
106
+ _force_exit(1)
107
+
108
+ if args.update_machine_info:
109
+ try:
110
+ update_machine_info(**auth_kwargs(args))
111
+ _force_exit(0)
112
+ except KeyboardInterrupt:
113
+ _exit_cancelled()
114
+ except Exception as exception:
115
+ report_error(logger, exception, context="Update machine info failed")
116
+ _force_exit(1)
117
+
118
+ if args.unbootstrap:
119
+ try:
120
+ _require_root_unless_dev()
121
+ unbootstrap(**auth_kwargs(args))
122
+ _force_exit(0)
123
+ except KeyboardInterrupt:
124
+ _exit_cancelled()
125
+ except Exception as exception:
126
+ report_error(logger, exception, context="Unbootstrap failed")
127
+ _force_exit(1)
128
+
129
+ if args.rebootstrap:
130
+ try:
131
+ _require_root_unless_dev()
132
+ unbootstrap(**auth_kwargs(args))
133
+ bootstrap(**bootstrap_kwargs(args))
134
+ _force_exit(0)
135
+ except KeyboardInterrupt:
136
+ _exit_cancelled()
137
+ except Exception as exception:
138
+ report_error(logger, exception, context="Rebootstrap failed")
139
+ _force_exit(1)
140
+
141
+ try:
142
+ ensure_fapolicyd_python_trust()
143
+ ensure_bootstrapped()
144
+ run()
145
+ except KeyboardInterrupt:
146
+ logger.info("Exiting TLS Tunnel Client")
147
+ _force_exit(130)
148
+
149
+
150
+ if __name__ == "__main__":
151
+ main()
@@ -0,0 +1,265 @@
1
+ from __future__ import absolute_import, division, print_function
2
+
3
+ import os
4
+ import sys
5
+ import argparse
6
+ import threading
7
+
8
+ from zscams.agent.src.support.configuration import RemoteConfig, config, CONFIG_PATH
9
+ from zscams.agent.src.support.filesystem import is_file_exists
10
+ from zscams.agent.src.core.tunnel.tls import create_ssl_context
11
+ from zscams.agent.src.core.tunnels import start_all_tunnels
12
+ from zscams.agent.src.core.services import start_all_services
13
+ from zscams.agent.src.core.service_health_check import monitor_services
14
+ from zscams.agent.src.core.heartbeat import run_heartbeat_loop
15
+ from zscams.agent.src.core.backend.client import backend_client
16
+ from zscams.agent.src.support.logger import get_logger
17
+
18
+
19
+ logger = get_logger("tls_tunnel_main")
20
+
21
+ EQUIPMENT_TYPES = ("ZPA", "VZEN", "PSE", "NSS")
22
+
23
+ BOOTSTRAP_AUTONOMOUS_REQUIRED = (
24
+ "username",
25
+ "totp",
26
+ "customer_name",
27
+ "connector_name",
28
+ "equipment_type",
29
+ )
30
+
31
+ AUTH_AUTONOMOUS_REQUIRED = (
32
+ "username",
33
+ "totp",
34
+ )
35
+
36
+
37
+ def init_parser():
38
+ parser = argparse.ArgumentParser(description="ZSCAMs Agent")
39
+ parser.add_argument(
40
+ "--bootstrap",
41
+ action="store_true",
42
+ help="Run bootstrap process and exit",
43
+ )
44
+ parser.add_argument(
45
+ "--rebootstrap",
46
+ action="store_true",
47
+ help="Run unbootstrap and then the bootstrap processes and exit",
48
+ )
49
+ parser.add_argument(
50
+ "--unbootstrap",
51
+ action="store_true",
52
+ help="Run unbootstrap process and exit",
53
+ )
54
+ parser.add_argument(
55
+ "--update-machine-info",
56
+ action="store_true",
57
+ help="Reinitialize machine info",
58
+ )
59
+ parser.add_argument(
60
+ "--autonomous",
61
+ action="store_true",
62
+ help=(
63
+ "Non-interactive mode: require CLI values and fail instead of prompting. "
64
+ "Additive opt-in; without this flag the interactive flow is unchanged."
65
+ ),
66
+ )
67
+ parser.add_argument(
68
+ "--username",
69
+ help="LDAP username (required with --autonomous for bootstrap/auth commands)",
70
+ )
71
+ parser.add_argument(
72
+ "--totp",
73
+ help="One-time password (required with --autonomous for bootstrap/auth commands)",
74
+ )
75
+ parser.add_argument(
76
+ "--customer-name",
77
+ dest="customer_name",
78
+ help="Customer name (required with --autonomous for --bootstrap/--rebootstrap)",
79
+ )
80
+ parser.add_argument(
81
+ "--connector-name",
82
+ dest="connector_name",
83
+ help="Unique connector name (required with --autonomous for --bootstrap/--rebootstrap)",
84
+ )
85
+ parser.add_argument(
86
+ "--equipment-type",
87
+ dest="equipment_type",
88
+ choices=EQUIPMENT_TYPES,
89
+ help="Equipment type: ZPA, VZEN, PSE, or NSS (required with --autonomous for --bootstrap/--rebootstrap)",
90
+ )
91
+ parser.add_argument(
92
+ "--dev",
93
+ action="store_true",
94
+ help=(
95
+ "Local/dev mode: no root, no systemd/user/sudoers changes; "
96
+ "state under <repo>/.dev/zscams (or --config-dir)."
97
+ ),
98
+ )
99
+ parser.add_argument(
100
+ "--config-dir",
101
+ dest="config_dir",
102
+ help="Override config/state directory (certs, machine_id, overlay).",
103
+ )
104
+ parser.add_argument(
105
+ "--base-url",
106
+ dest="base_url",
107
+ help="Optional bootstrap server origin override (e.g. https://host/backend/api).",
108
+ )
109
+ parser.add_argument(
110
+ "--remote-host",
111
+ dest="remote_host",
112
+ help="Optional remote tunnel host IP override.",
113
+ )
114
+ parser.add_argument(
115
+ "--debug",
116
+ action="store_true",
117
+ help="Enable verbose logs, tracebacks, and diagnostic output (includes sensitive data)",
118
+ )
119
+ parser.add_argument(
120
+ "--allow-command",
121
+ dest="allow_command",
122
+ metavar="COMMAND",
123
+ help=(
124
+ "Append COMMAND to the zscams sudoers allowlist "
125
+ "(/etc/sudoers.d/zscams-actions) and exit"
126
+ ),
127
+ )
128
+ return parser
129
+
130
+
131
+ def validate_autonomous_args(args):
132
+ """Fail fast when --autonomous is set but required values are missing."""
133
+ if not args.autonomous:
134
+ return
135
+
136
+ needs_bootstrap_fields = args.bootstrap or args.rebootstrap
137
+ needs_auth_fields = (
138
+ needs_bootstrap_fields or args.unbootstrap or args.update_machine_info
139
+ )
140
+
141
+ if not needs_auth_fields:
142
+ logger.error(
143
+ "--autonomous requires one of --bootstrap, --rebootstrap, "
144
+ "--unbootstrap, or --update-machine-info"
145
+ )
146
+ sys.exit(1)
147
+
148
+ required = (
149
+ BOOTSTRAP_AUTONOMOUS_REQUIRED
150
+ if needs_bootstrap_fields
151
+ else AUTH_AUTONOMOUS_REQUIRED
152
+ )
153
+ missing = [name.replace("_", "-") for name in required if not getattr(args, name)]
154
+ if missing:
155
+ logger.error(
156
+ "--autonomous is missing required flags: %s",
157
+ ", ".join("--{0}".format(name) for name in missing),
158
+ )
159
+ sys.exit(1)
160
+
161
+
162
+ def bootstrap_kwargs(args):
163
+ """Build keyword args for bootstrap() from parsed CLI args."""
164
+ return {
165
+ "autonomous": args.autonomous,
166
+ "username": args.username,
167
+ "totp": args.totp,
168
+ "customer_name": args.customer_name,
169
+ "connector_name": args.connector_name,
170
+ "equipment_type": args.equipment_type,
171
+ "base_url": args.base_url,
172
+ "remote_host": args.remote_host,
173
+ }
174
+
175
+
176
+ def auth_kwargs(args):
177
+ """Build keyword args for auth-only commands from parsed CLI args."""
178
+ return {
179
+ "autonomous": args.autonomous,
180
+ "username": args.username,
181
+ "totp": args.totp,
182
+ }
183
+
184
+
185
+ def ensure_bootstrapped():
186
+ """Ensure the agent is bootstrapped with the backend."""
187
+
188
+ custom_config_path = str(config.get("config_dir", must_resolve=True))
189
+ files_to_ensure = [
190
+ os.path.join(custom_config_path, config.get("remote.ca_cert", must_resolve=True)),
191
+ os.path.join(
192
+ custom_config_path, config.get("remote.client_cert", must_resolve=True)
193
+ ),
194
+ os.path.join(custom_config_path, config.get("remote.client_key", must_resolve=True)),
195
+ ]
196
+
197
+ missing_files = []
198
+
199
+ for file_path in files_to_ensure:
200
+ if not is_file_exists(file_path, logger):
201
+ missing_files.append(file_path)
202
+
203
+ bootstrapped = backend_client.is_bootstrapped()
204
+
205
+ if not bootstrapped or missing_files:
206
+ logger.debug("Agent has entry on server: %s", bootstrapped)
207
+ logger.debug(
208
+ "Missing files: %s",
209
+ ", ".join(str(path) for path in missing_files)
210
+ if missing_files
211
+ else "No missing files",
212
+ )
213
+ logger.error(
214
+ "Agent is not bootstrapped. Please run `zscams --bootstrap` to start the bootstrap process.",
215
+ )
216
+ sys.exit(1)
217
+
218
+
219
+ def run():
220
+ """Start tunnels and services (threaded). Blocks until interrupted."""
221
+
222
+ custom_config_dir = str(config.get("config_dir", must_resolve=True))
223
+
224
+ ssl_context = create_ssl_context(
225
+ config.get("remote", valtyp=RemoteConfig), custom_config_dir
226
+ )
227
+ remote_host = config.get("remote.host")
228
+ remote_port = config.get("remote.port")
229
+
230
+ tunnel_threads = start_all_tunnels(
231
+ config.get("forwards", []), remote_host, remote_port, ssl_context
232
+ )
233
+
234
+ config_dir = os.path.dirname(CONFIG_PATH)
235
+ start_all_services(config.get("services", []), config_dir=config_dir)
236
+
237
+ health_check_interval = config.get("general", {}).get("health_check_interval", 300)
238
+
239
+ monitor_thread = threading.Thread(
240
+ target=monitor_services,
241
+ kwargs={
242
+ "services": config.get("services", []),
243
+ "config_dir": config_dir,
244
+ "interval": health_check_interval,
245
+ },
246
+ )
247
+ monitor_thread.daemon = True
248
+ monitor_thread.start()
249
+
250
+ heartbeat_thread = threading.Thread(
251
+ target=run_heartbeat_loop,
252
+ kwargs={"interval": health_check_interval},
253
+ )
254
+ heartbeat_thread.daemon = True
255
+ heartbeat_thread.start()
256
+
257
+ logger.info("[*] All tunnels and services started. Press Ctrl+C to stop.")
258
+ try:
259
+ while True:
260
+ for t in tunnel_threads:
261
+ t.join(timeout=1.0)
262
+ monitor_thread.join(timeout=0.1)
263
+ heartbeat_thread.join(timeout=0.1)
264
+ except KeyboardInterrupt:
265
+ raise
@@ -0,0 +1,72 @@
1
+ ---
2
+ config_dir: /etc/zscams
3
+ bootstrap:
4
+ base_url: https://81.255.240.214/backend/api
5
+ verify_backend_cert: false
6
+ sni: bootstrap.zscams.orangecyberdefense.com
7
+ cache_dir: .cache
8
+ blacklist_ports: []
9
+ cert_issuer: ZSCAMs
10
+ csr:
11
+ country: FR
12
+ default_common_name: zscams-agent.orangecyberdefense.com
13
+ locality: Paris
14
+ organization: zscams-agent.orangecyberdefense.com
15
+ state: Ile-de-France
16
+ forwards:
17
+ - description: Forward to SSH backend
18
+ local_port: 4422
19
+ sni_hostname: stunnel.zscams.orangecyberdefense.com
20
+ general:
21
+ install_project_deps: false
22
+ health_check_interval: 30
23
+ connector_service_name: ""
24
+ logging:
25
+ level: 20
26
+ remote:
27
+ ca_cert: certificates/ca_chain.pem
28
+ ca_chain: certificates/ca_chain.pem
29
+ client_cert: certificates/client.crt
30
+ client_key: certificates/client.key
31
+ autoport_key: certificates/autoport.key
32
+ host: 81.255.240.214
33
+ port: 443
34
+ verify_cert: false
35
+ services:
36
+ - args: []
37
+ health:
38
+ host: localhost
39
+ port: 22
40
+ name: Reverse SSH
41
+ custom_port_name: "reverse_port"
42
+ params:
43
+ local_port: 4422
44
+ private_key: certificates/autoport.key
45
+ remote_host: localhost
46
+ reverse_port: "{reverse_port}"
47
+ server_ssh_user: zscams
48
+ ssh_options:
49
+ - -o LogLevel=error
50
+ - -o UserKnownHostsFile=/dev/null
51
+ - -o StrictHostKeyChecking=no
52
+ - -o ServerAliveInterval=30
53
+ - -o ServerAliveCountMax=2
54
+ port: 22
55
+ prerequisites:
56
+ files:
57
+ - certificates/autoport.key
58
+ ports:
59
+ - 22
60
+ services: []
61
+ script: src/services/reverse_ssh.py
62
+ - args: []
63
+ name: Monitor Service
64
+ params:
65
+ equipment_name: "{equipment_name}"
66
+ equipment_type: "{equipment_type}"
67
+ service_name: Zscaler-AppConnector
68
+ prerequisites:
69
+ files: []
70
+ ports: []
71
+ services: []
72
+ script: src/services/system_monitor.py
@@ -0,0 +1,24 @@
1
+ #!/bin/sh
2
+ #
3
+ # PROVIDE: zscams
4
+ # REQUIRE: NETWORKING
5
+ # KEYWORD: shutdown
6
+
7
+ . /etc/rc.subr
8
+
9
+ name="zscams"
10
+ rcvar=zscams_enable
11
+
12
+ load_rc_config $name
13
+
14
+ : ${{zscams_enable:="NO"}}
15
+
16
+ zscams_user="{user_to_run_as}"
17
+ zscams_python="{python_exec}"
18
+ zscams_logfile="{logfile}"
19
+
20
+ pidfile="/home/${{zscams_user}}/${{name}}.pid"
21
+ command="/usr/sbin/daemon"
22
+ command_args="-P ${{pidfile}} -r -t ${{name}} -o ${{zscams_logfile}} ${{zscams_python}} -m zscams"
23
+
24
+ run_rc_command "$1"
@@ -0,0 +1,13 @@
1
+ [Unit]
2
+ Description=ZSCAMs Service
3
+ After=network.target
4
+
5
+ [Service]
6
+ ExecStart={python_exec} -m zscams
7
+ Restart=always
8
+ RestartSec=5
9
+ User={user_to_run_as}
10
+ Environment="PYTHONPATH={pythonpath}"
11
+
12
+ [Install]
13
+ WantedBy=multi-user.target
File without changes
@@ -0,0 +1,4 @@
1
+ from __future__ import absolute_import, division, print_function
2
+
3
+ running_services = set()
4
+ service_processes = {}