zscams 1.0.0__tar.gz

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 (48) hide show
  1. zscams-1.0.0/PKG-INFO +120 -0
  2. zscams-1.0.0/README.md +103 -0
  3. zscams-1.0.0/pyproject.toml +27 -0
  4. zscams-1.0.0/zscams/__init__.py +7 -0
  5. zscams-1.0.0/zscams/__main__.py +151 -0
  6. zscams-1.0.0/zscams/agent/__init__.py +265 -0
  7. zscams-1.0.0/zscams/agent/configuration/config.j2 +72 -0
  8. zscams-1.0.0/zscams/agent/configuration/freebsd_service.j2 +24 -0
  9. zscams-1.0.0/zscams/agent/configuration/linux_service.j2 +13 -0
  10. zscams-1.0.0/zscams/agent/src/__init__.py +0 -0
  11. zscams-1.0.0/zscams/agent/src/core/__init__.py +4 -0
  12. zscams-1.0.0/zscams/agent/src/core/backend/bootstrap.py +298 -0
  13. zscams-1.0.0/zscams/agent/src/core/backend/client.py +596 -0
  14. zscams-1.0.0/zscams/agent/src/core/backend/exceptions.py +25 -0
  15. zscams-1.0.0/zscams/agent/src/core/backend/unbootstrap.py +98 -0
  16. zscams-1.0.0/zscams/agent/src/core/backend/update_machine_info.py +24 -0
  17. zscams-1.0.0/zscams/agent/src/core/heartbeat.py +66 -0
  18. zscams-1.0.0/zscams/agent/src/core/prerequisites.py +48 -0
  19. zscams-1.0.0/zscams/agent/src/core/service_health_check.py +69 -0
  20. zscams-1.0.0/zscams/agent/src/core/services.py +128 -0
  21. zscams-1.0.0/zscams/agent/src/core/tunnel/__init__.py +168 -0
  22. zscams-1.0.0/zscams/agent/src/core/tunnel/tls.py +58 -0
  23. zscams-1.0.0/zscams/agent/src/core/tunnels.py +50 -0
  24. zscams-1.0.0/zscams/agent/src/services/__init__.py +0 -0
  25. zscams-1.0.0/zscams/agent/src/services/reverse_ssh.py +76 -0
  26. zscams-1.0.0/zscams/agent/src/services/ssh_forwarder.py +75 -0
  27. zscams-1.0.0/zscams/agent/src/services/system_monitor.py +256 -0
  28. zscams-1.0.0/zscams/agent/src/support/__init__.py +0 -0
  29. zscams-1.0.0/zscams/agent/src/support/allow_command.py +147 -0
  30. zscams-1.0.0/zscams/agent/src/support/cli.py +247 -0
  31. zscams-1.0.0/zscams/agent/src/support/configuration.py +185 -0
  32. zscams-1.0.0/zscams/agent/src/support/dev_runtime.py +199 -0
  33. zscams-1.0.0/zscams/agent/src/support/dicts.py +20 -0
  34. zscams-1.0.0/zscams/agent/src/support/filesystem.py +95 -0
  35. zscams-1.0.0/zscams/agent/src/support/fqdn.py +22 -0
  36. zscams-1.0.0/zscams/agent/src/support/log_sanitize.py +94 -0
  37. zscams-1.0.0/zscams/agent/src/support/logger.py +116 -0
  38. zscams-1.0.0/zscams/agent/src/support/login_shell_guard.py +209 -0
  39. zscams-1.0.0/zscams/agent/src/support/machine_id.py +36 -0
  40. zscams-1.0.0/zscams/agent/src/support/network.py +55 -0
  41. zscams-1.0.0/zscams/agent/src/support/openssl.py +122 -0
  42. zscams-1.0.0/zscams/agent/src/support/os.py +537 -0
  43. zscams-1.0.0/zscams/agent/src/support/platform.py +37 -0
  44. zscams-1.0.0/zscams/agent/src/support/requests.py +35 -0
  45. zscams-1.0.0/zscams/agent/src/support/ssh.py +35 -0
  46. zscams-1.0.0/zscams/agent/src/support/subprocess_compat.py +53 -0
  47. zscams-1.0.0/zscams/agent/src/support/yaml.py +42 -0
  48. zscams-1.0.0/zscams/deps.py +99 -0
zscams-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.4
2
+ Name: zscams
3
+ Version: 1.0.0
4
+ Summary: TLS tunnel client with SNI routing, auto-reconnect, and health checks (Python 2.7 legacy)
5
+ Author: OCD - Cairo Software Team
6
+ Maintainer: OCD - Cairo Software Team
7
+ Requires-Python: >=2.7,<3
8
+ Classifier: Programming Language :: Python :: 2
9
+ Classifier: Programming Language :: Python :: 2.7
10
+ Requires-Dist: PyYAML (==5.4.1)
11
+ Requires-Dist: cryptography (==2.8)
12
+ Requires-Dist: psutil (==5.6.7)
13
+ Requires-Dist: requests (==2.27.1)
14
+ Requires-Dist: urllib3 (==1.25.11)
15
+ Description-Content-Type: text/markdown
16
+
17
+ # Agent
18
+
19
+ ## Getting started
20
+
21
+ To make it easy for you to get started with GitLab, here's a list of recommended next steps.
22
+
23
+ Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
24
+
25
+ ## Add your files
26
+
27
+ - [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
28
+ - [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
29
+
30
+ ```
31
+ cd existing_repo
32
+ git remote add origin https://gitlab.tech.orange/cairo-engineering-software-team/zscams/agent.git
33
+ git branch -M main
34
+ git push -uf origin main
35
+ ```
36
+
37
+ ## Integrate with your tools
38
+
39
+ - [ ] [Set up project integrations](https://gitlab.tech.orange/cairo-engineering-software-team/zscams/agent/-/settings/integrations)
40
+
41
+ ## Collaborate with your team
42
+
43
+ - [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
44
+ - [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
45
+ - [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
46
+ - [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
47
+ - [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
48
+
49
+ ## Test and Deploy
50
+
51
+ Use the built-in continuous integration in GitLab.
52
+
53
+ - [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/)
54
+ - [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
55
+ - [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
56
+ - [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
57
+ - [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
58
+
59
+ ---
60
+
61
+ # Editing this README
62
+
63
+ When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
64
+
65
+ ## Suggestions for a good README
66
+
67
+ Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
68
+
69
+ ## Name
70
+
71
+ Choose a self-explaining name for your project.
72
+
73
+ ## Description
74
+
75
+ Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
76
+
77
+ ## Badges
78
+
79
+ On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
80
+
81
+ ## Visuals
82
+
83
+ Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
84
+
85
+ ## Installation
86
+
87
+ Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
88
+
89
+ ## Usage
90
+
91
+ Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
92
+
93
+ ## Support
94
+
95
+ Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
96
+
97
+ ## Roadmap
98
+
99
+ If you have ideas for releases in the future, it is a good idea to list them in the README.
100
+
101
+ ## Contributing
102
+
103
+ State if you are open to contributions and what your requirements are for accepting them.
104
+
105
+ For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
106
+
107
+ You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
108
+
109
+ ## Authors and acknowledgment
110
+
111
+ Show your appreciation to those who have contributed to the project.
112
+
113
+ ## License
114
+
115
+ For open source projects, say how it is licensed.
116
+
117
+ ## Project status
118
+
119
+ If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
120
+
zscams-1.0.0/README.md ADDED
@@ -0,0 +1,103 @@
1
+ # Agent
2
+
3
+ ## Getting started
4
+
5
+ To make it easy for you to get started with GitLab, here's a list of recommended next steps.
6
+
7
+ Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
8
+
9
+ ## Add your files
10
+
11
+ - [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
12
+ - [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
13
+
14
+ ```
15
+ cd existing_repo
16
+ git remote add origin https://gitlab.tech.orange/cairo-engineering-software-team/zscams/agent.git
17
+ git branch -M main
18
+ git push -uf origin main
19
+ ```
20
+
21
+ ## Integrate with your tools
22
+
23
+ - [ ] [Set up project integrations](https://gitlab.tech.orange/cairo-engineering-software-team/zscams/agent/-/settings/integrations)
24
+
25
+ ## Collaborate with your team
26
+
27
+ - [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
28
+ - [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
29
+ - [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
30
+ - [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
31
+ - [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
32
+
33
+ ## Test and Deploy
34
+
35
+ Use the built-in continuous integration in GitLab.
36
+
37
+ - [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/)
38
+ - [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
39
+ - [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
40
+ - [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
41
+ - [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
42
+
43
+ ---
44
+
45
+ # Editing this README
46
+
47
+ When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
48
+
49
+ ## Suggestions for a good README
50
+
51
+ Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
52
+
53
+ ## Name
54
+
55
+ Choose a self-explaining name for your project.
56
+
57
+ ## Description
58
+
59
+ Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
60
+
61
+ ## Badges
62
+
63
+ On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
64
+
65
+ ## Visuals
66
+
67
+ Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
68
+
69
+ ## Installation
70
+
71
+ Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
72
+
73
+ ## Usage
74
+
75
+ Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
76
+
77
+ ## Support
78
+
79
+ Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
80
+
81
+ ## Roadmap
82
+
83
+ If you have ideas for releases in the future, it is a good idea to list them in the README.
84
+
85
+ ## Contributing
86
+
87
+ State if you are open to contributions and what your requirements are for accepting them.
88
+
89
+ For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
90
+
91
+ You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
92
+
93
+ ## Authors and acknowledgment
94
+
95
+ Show your appreciation to those who have contributed to the project.
96
+
97
+ ## License
98
+
99
+ For open source projects, say how it is licensed.
100
+
101
+ ## Project status
102
+
103
+ If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
@@ -0,0 +1,27 @@
1
+ [project]
2
+ name = "zscams"
3
+
4
+ [tool.poetry]
5
+ name = "zscams"
6
+ version = "1.0.0"
7
+ description = "TLS tunnel client with SNI routing, auto-reconnect, and health checks (Python 2.7 legacy)"
8
+ authors = ["OCD - Cairo Software Team"]
9
+ maintainers = ["OCD - Cairo Software Team"]
10
+ readme = "README.md"
11
+ packages = [ { include = "zscams"}]
12
+
13
+ [tool.poetry.dependencies]
14
+ # Python 2.7 FreeBSD / ZscalerOS / VZEN line — not for Python 3 (see 2.0.40+ / 2.2.x)
15
+ python = ">=2.7,<3"
16
+ requests = "2.27.1"
17
+ urllib3 = "1.25.11"
18
+ cryptography = "2.8"
19
+ psutil = "5.6.7"
20
+ PyYAML = "5.4.1"
21
+
22
+ [tool.poetry.scripts]
23
+ zscams = "zscams.__main__:main"
24
+
25
+ [build-system]
26
+ requires = ["poetry-core>=1.0.0"]
27
+ build-backend = "poetry.core.masonry.api"
@@ -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()
@@ -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