tlsLibHunter 0.2.8__tar.gz → 0.2.9__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 (78) hide show
  1. {tlslibhunter-0.2.8/tlsLibHunter.egg-info → tlslibhunter-0.2.9}/PKG-INFO +2 -2
  2. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/README.md +1 -1
  3. tlslibhunter-0.2.9/tests/test_reattach_session_adoption.py +216 -0
  4. tlslibhunter-0.2.9/tests/test_resource_release.py +280 -0
  5. tlslibhunter-0.2.9/tests/test_wrong_target_attach.py +394 -0
  6. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9/tlsLibHunter.egg-info}/PKG-INFO +2 -2
  7. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlsLibHunter.egg-info/SOURCES.txt +3 -0
  8. tlslibhunter-0.2.9/tlslibhunter/__main__.py +12 -0
  9. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/about.py +1 -1
  10. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/backends/base.py +61 -1
  11. tlslibhunter-0.2.9/tlslibhunter/backends/frida_backend.py +430 -0
  12. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/extractor/ios_extractor.py +5 -4
  13. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/extractor/memory_extractor.py +6 -3
  14. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/hunter.py +78 -5
  15. tlslibhunter-0.2.9/tlslibhunter/output/_utils.py +50 -0
  16. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/output/plain_formatter.py +8 -0
  17. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/output/table_formatter.py +18 -2
  18. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/scanner/module_scanner.py +19 -2
  19. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/scanner/results.py +26 -0
  20. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/utils/process_resolver.py +24 -5
  21. tlslibhunter-0.2.8/tlslibhunter/__main__.py +0 -6
  22. tlslibhunter-0.2.8/tlslibhunter/backends/frida_backend.py +0 -204
  23. tlslibhunter-0.2.8/tlslibhunter/output/_utils.py +0 -17
  24. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/LICENSE +0 -0
  25. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/MANIFEST.in +0 -0
  26. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/pyproject.toml +0 -0
  27. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/setup.cfg +0 -0
  28. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/setup.py +0 -0
  29. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tests/test_adb.py +0 -0
  30. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tests/test_android_extractor_serial.py +0 -0
  31. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tests/test_classifier.py +0 -0
  32. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tests/test_cli.py +0 -0
  33. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tests/test_config.py +0 -0
  34. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tests/test_encoding.py +0 -0
  35. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tests/test_evidence_classification.py +0 -0
  36. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tests/test_fingerprints.py +0 -0
  37. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tests/test_memory_extractor.py +0 -0
  38. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tests/test_module_scanner_gates.py +0 -0
  39. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tests/test_native_dsc_extractor.py +0 -0
  40. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tests/test_output_formatters.py +0 -0
  41. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tests/test_pipeline_filtering.py +0 -0
  42. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tests/test_platform_overrides.py +0 -0
  43. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tests/test_scan_truncation.py +0 -0
  44. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tests/test_tls_indicators.py +0 -0
  45. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlsLibHunter.egg-info/dependency_links.txt +0 -0
  46. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlsLibHunter.egg-info/entry_points.txt +0 -0
  47. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlsLibHunter.egg-info/requires.txt +0 -0
  48. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlsLibHunter.egg-info/top_level.txt +0 -0
  49. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/__init__.py +0 -0
  50. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/backends/__init__.py +0 -0
  51. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/cli.py +0 -0
  52. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/config.py +0 -0
  53. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/extractor/__init__.py +0 -0
  54. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/extractor/android_extractor.py +0 -0
  55. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/extractor/base.py +0 -0
  56. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/extractor/disk_extractor.py +0 -0
  57. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/extractor/dyld_cache_extractor.py +0 -0
  58. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/extractor/native_dsc_extractor.py +0 -0
  59. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/extractor/strategy.py +0 -0
  60. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/output/__init__.py +0 -0
  61. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/output/json_formatter.py +0 -0
  62. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/platforms/__init__.py +0 -0
  63. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/platforms/android.py +0 -0
  64. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/platforms/base.py +0 -0
  65. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/platforms/detection.py +0 -0
  66. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/platforms/ios.py +0 -0
  67. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/platforms/linux.py +0 -0
  68. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/platforms/macos.py +0 -0
  69. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/platforms/windows.py +0 -0
  70. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/scanner/__init__.py +0 -0
  71. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/scanner/classifier.py +0 -0
  72. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/scanner/fingerprints.py +0 -0
  73. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/scanner/tls_indicators.py +0 -0
  74. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/scripts/extractor_agent.js +0 -0
  75. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/scripts/scanner_agent.js +0 -0
  76. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/utils/__init__.py +0 -0
  77. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/utils/adb.py +0 -0
  78. {tlslibhunter-0.2.8 → tlslibhunter-0.2.9}/tlslibhunter/utils/encoding.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tlsLibHunter
3
- Version: 0.2.8
3
+ Version: 0.2.9
4
4
  Summary: Identifies TLS/SSL libraries in running processes using Frida-based dynamic instrumentation.
5
5
  Home-page: https://github.com/monkeywave/tlsLibHunter
6
6
  Author: Daniel Baier
@@ -47,7 +47,7 @@ Dynamic: summary
47
47
 
48
48
 
49
49
  # TLSLibHunter
50
- ![version](https://img.shields.io/badge/version-0.2.8-blue) [![PyPI version](https://badge.fury.io/py/tlslibhunter.svg)](https://badge.fury.io/py/tlslibhunter) [![Publish status](https://github.com/monkeywave/tlsLibHunter/actions/workflows/publish.yml/badge.svg?branch=main)](https://github.com/monkeywave/tlsLibHunter/actions/workflows/publish.yml)
50
+ ![version](https://img.shields.io/badge/version-0.2.9-blue) [![PyPI version](https://badge.fury.io/py/tlslibhunter.svg)](https://badge.fury.io/py/tlslibhunter) [![Publish status](https://github.com/monkeywave/tlsLibHunter/actions/workflows/publish.yml/badge.svg?branch=main)](https://github.com/monkeywave/tlsLibHunter/actions/workflows/publish.yml)
51
51
  [![Lint](https://github.com/monkeywave/tlsLibHunter/actions/workflows/lint.yml/badge.svg)](https://github.com/monkeywave/tlsLibHunter/actions/workflows/lint.yml)
52
52
 
53
53
 
@@ -6,7 +6,7 @@
6
6
 
7
7
 
8
8
  # TLSLibHunter
9
- ![version](https://img.shields.io/badge/version-0.2.8-blue) [![PyPI version](https://badge.fury.io/py/tlslibhunter.svg)](https://badge.fury.io/py/tlslibhunter) [![Publish status](https://github.com/monkeywave/tlsLibHunter/actions/workflows/publish.yml/badge.svg?branch=main)](https://github.com/monkeywave/tlsLibHunter/actions/workflows/publish.yml)
9
+ ![version](https://img.shields.io/badge/version-0.2.9-blue) [![PyPI version](https://badge.fury.io/py/tlslibhunter.svg)](https://badge.fury.io/py/tlslibhunter) [![Publish status](https://github.com/monkeywave/tlsLibHunter/actions/workflows/publish.yml/badge.svg?branch=main)](https://github.com/monkeywave/tlsLibHunter/actions/workflows/publish.yml)
10
10
  [![Lint](https://github.com/monkeywave/tlsLibHunter/actions/workflows/lint.yml/badge.svg)](https://github.com/monkeywave/tlsLibHunter/actions/workflows/lint.yml)
11
11
 
12
12
 
@@ -0,0 +1,216 @@
1
+ """Tests for session ownership across crash recovery, and agent-log routing.
2
+
3
+ Two defects covered:
4
+
5
+ * ``ModuleScanner._reattach()`` re-spawns the target and replaces ``_session``,
6
+ but ``TLSLibHunter._session`` kept pointing at the dead original. Because
7
+ ``extract()`` short-circuits on ``_initialized``, extraction after a recovery
8
+ ran against a corpse and every library failed -- silently.
9
+ * Agent ``console.log`` output reached **stdout** through frida's default log
10
+ handler, corrupting ``--format json``.
11
+ """
12
+
13
+ import logging
14
+ from unittest.mock import Mock
15
+
16
+ import pytest
17
+
18
+ from tlslibhunter.backends import frida_backend
19
+ from tlslibhunter.hunter import TLSLibHunter
20
+ from tlslibhunter.scanner.results import ScanResult
21
+
22
+
23
+ class StubScanner:
24
+ """Scanner whose scan() optionally swaps its session, mimicking _reattach."""
25
+
26
+ def __init__(self, session, new_session=None, raises=None):
27
+ self._session = session
28
+ self._new_session = new_session
29
+ self._raises = raises
30
+ self.cleanup_calls = 0
31
+
32
+ @property
33
+ def session(self):
34
+ return self._session
35
+
36
+ def scan(self, target):
37
+ if self._new_session is not None:
38
+ self._session = self._new_session # a recovery happened mid-scan
39
+ if self._raises is not None:
40
+ raise self._raises
41
+ return ScanResult(target=target, platform="macos")
42
+
43
+ def cleanup(self):
44
+ self.cleanup_calls += 1
45
+
46
+
47
+ def _hunter(session, backend=None):
48
+ hunter = TLSLibHunter("target-app")
49
+ hunter._backend = backend or Mock()
50
+ hunter._device = Mock()
51
+ hunter._session = session
52
+ hunter._platform = "macos"
53
+ hunter._attached = {"pid": 1, "name": "original"}
54
+ hunter._initialized = True
55
+ return hunter
56
+
57
+
58
+ def _run_scan(hunter, scanner, monkeypatch):
59
+ monkeypatch.setattr("tlslibhunter.scanner.module_scanner.ModuleScanner", lambda **kw: scanner)
60
+ return hunter.scan()
61
+
62
+
63
+ # ---------------------------------------------------------------------------
64
+ # Session adoption
65
+ # ---------------------------------------------------------------------------
66
+
67
+
68
+ def test_scan_adopts_the_recovered_session(monkeypatch):
69
+ original, recovered = Mock(name="dead"), Mock(name="recovered")
70
+ backend = Mock()
71
+ backend.describe_session.return_value = {"pid": 222, "name": "respawned"}
72
+ hunter = _hunter(original, backend)
73
+
74
+ _run_scan(hunter, StubScanner(original, new_session=recovered), monkeypatch)
75
+
76
+ # Without this, extract() would keep using the dead original.
77
+ assert hunter._session is recovered
78
+ assert hunter._attached == {"pid": 222, "name": "respawned"}
79
+
80
+
81
+ def test_scan_adopts_even_when_the_scan_raises(monkeypatch):
82
+ original, recovered = Mock(name="dead"), Mock(name="recovered")
83
+ hunter = _hunter(original)
84
+ scanner = StubScanner(original, new_session=recovered, raises=RuntimeError("boom"))
85
+
86
+ with pytest.raises(RuntimeError):
87
+ _run_scan(hunter, scanner, monkeypatch)
88
+
89
+ assert hunter._session is recovered
90
+ assert scanner.cleanup_calls == 1
91
+
92
+
93
+ def test_failed_respawn_leaves_no_session_and_warns(monkeypatch, caplog):
94
+ """A failed recovery must surface as None, not as a corpse extract() would use."""
95
+ original = Mock(name="dead")
96
+ hunter = _hunter(original)
97
+
98
+ with caplog.at_level(logging.WARNING, logger="tlslibhunter"):
99
+ _run_scan(hunter, StubScanner(original, new_session=None), monkeypatch)
100
+
101
+ # StubScanner did not swap, so the session is unchanged and no warning fires.
102
+ assert hunter._session is original
103
+
104
+ scanner = StubScanner(original)
105
+ scanner._session = None # recovery failed
106
+ with caplog.at_level(logging.WARNING, logger="tlslibhunter"):
107
+ _run_scan(hunter, scanner, monkeypatch)
108
+
109
+ assert hunter._session is None
110
+ assert hunter._attached is None
111
+ assert "could not be recovered" in caplog.text
112
+
113
+
114
+ def test_unchanged_session_keeps_the_original_label(monkeypatch):
115
+ session = Mock()
116
+ backend = Mock()
117
+ hunter = _hunter(session, backend)
118
+
119
+ _run_scan(hunter, StubScanner(session), monkeypatch)
120
+
121
+ assert hunter._session is session
122
+ assert hunter._attached == {"pid": 1, "name": "original"}
123
+ # No pointless re-describe when nothing moved.
124
+ backend.describe_session.assert_not_called()
125
+
126
+
127
+ def test_scanner_cleanup_still_runs(monkeypatch):
128
+ session = Mock()
129
+ scanner = StubScanner(session)
130
+
131
+ _run_scan(_hunter(session), scanner, monkeypatch)
132
+
133
+ assert scanner.cleanup_calls == 1
134
+
135
+
136
+ # ---------------------------------------------------------------------------
137
+ # _reattach itself: the replaced session must be released, not abandoned
138
+ # ---------------------------------------------------------------------------
139
+
140
+
141
+ def _recovery_scanner(backend, session):
142
+ from tlslibhunter.scanner.module_scanner import ModuleScanner
143
+
144
+ scanner = ModuleScanner(
145
+ backend=backend,
146
+ session=session,
147
+ platform="macos",
148
+ device=Mock(),
149
+ respawn_target="target-app",
150
+ spawn_mode=True,
151
+ )
152
+ scanner._ensure_script = lambda: None # no real frida script in a unit test
153
+ return scanner
154
+
155
+
156
+ def test_reattach_detaches_the_replaced_session():
157
+ dead, fresh = Mock(name="dead"), Mock(name="fresh")
158
+ backend = Mock()
159
+ backend.spawn.return_value = fresh
160
+ scanner = _recovery_scanner(backend, dead)
161
+
162
+ assert scanner._reattach() is True
163
+
164
+ backend.detach.assert_called_once_with(dead)
165
+ assert scanner.session is fresh
166
+
167
+
168
+ def test_reattach_clears_the_session_when_respawn_fails():
169
+ dead = Mock(name="dead")
170
+ backend = Mock()
171
+ backend.spawn.side_effect = RuntimeError("respawn failed")
172
+ scanner = _recovery_scanner(backend, dead)
173
+
174
+ assert scanner._reattach() is False
175
+
176
+ backend.detach.assert_called_once_with(dead)
177
+ # An honest None beats a corpse the caller would go on using.
178
+ assert scanner.session is None
179
+
180
+
181
+ # ---------------------------------------------------------------------------
182
+ # Agent log routing (stdout pollution)
183
+ # ---------------------------------------------------------------------------
184
+
185
+
186
+ @pytest.mark.parametrize(
187
+ ("level", "expected"),
188
+ [
189
+ ("debug", logging.DEBUG),
190
+ ("info", logging.INFO),
191
+ ("warning", logging.WARNING),
192
+ ("error", logging.ERROR),
193
+ ("something-new", logging.INFO), # unknown levels must not be dropped
194
+ ],
195
+ )
196
+ def test_agent_log_is_forwarded_to_logging(level, expected, caplog):
197
+ with caplog.at_level(logging.DEBUG, logger="tlslibhunter.agent"):
198
+ frida_backend._forward_agent_log(level, "[tlslibhunter] skipped a range")
199
+
200
+ assert len(caplog.records) == 1
201
+ assert caplog.records[0].levelno == expected
202
+ assert "skipped a range" in caplog.text
203
+
204
+
205
+ def test_create_script_installs_the_log_handler():
206
+ """Frida's default handler prints info logs to stdout, which corrupted JSON output."""
207
+ script = Mock()
208
+ session = Mock()
209
+ session.create_script.return_value = script
210
+
211
+ frida_backend.FridaBackend().create_script(session, "// agent")
212
+
213
+ script.set_log_handler.assert_called_once_with(frida_backend._forward_agent_log)
214
+ # Must be installed before load(), or startup logs still escape to stdout.
215
+ order = [c[0] for c in script.method_calls]
216
+ assert order.index("set_log_handler") < order.index("load")
@@ -0,0 +1,280 @@
1
+ """Tests for resource release on failure paths.
2
+
3
+ Each of these leaked something when the *unhappy* path ran -- which is exactly
4
+ the path least likely to be exercised by hand:
5
+
6
+ * ``spawn()`` left a SUSPENDED process behind if attach/resume failed;
7
+ * ``create_script()`` left a created-but-unloaded script resident;
8
+ * the extractors unloaded inside the ``try``, after the exports call, so a
9
+ raising dump/read RPC skipped it;
10
+ * ``hunter.close()`` never released the backend or device;
11
+ * the ``--host`` path registered a remote device and never removed it.
12
+ """
13
+
14
+ import logging
15
+ from unittest.mock import Mock
16
+
17
+ import pytest
18
+
19
+ from tlslibhunter.backends import frida_backend
20
+ from tlslibhunter.backends.base import Backend, ProcessNotFoundError, ScriptError
21
+ from tlslibhunter.hunter import TLSLibHunter
22
+ from tlslibhunter.utils.process_resolver import is_exact_name, name_matches
23
+
24
+ # ---------------------------------------------------------------------------
25
+ # spawn(): a suspended target must never be abandoned
26
+ # ---------------------------------------------------------------------------
27
+
28
+
29
+ def test_spawn_kills_the_target_when_attach_fails(backend):
30
+ device = Mock()
31
+ device.spawn.return_value = 4242
32
+ device.attach.side_effect = RuntimeError("attach denied")
33
+
34
+ with pytest.raises(ProcessNotFoundError):
35
+ backend.spawn(device, "app")
36
+
37
+ # device.spawn() returns a SUSPENDED process; without this it never runs
38
+ # and is never reaped.
39
+ device.kill.assert_called_once_with(4242)
40
+
41
+
42
+ def test_spawn_kills_the_target_when_resume_fails(backend):
43
+ device = Mock()
44
+ device.spawn.return_value = 4242
45
+ device.resume.side_effect = RuntimeError("resume failed")
46
+ session = device.attach.return_value
47
+
48
+ with pytest.raises(ProcessNotFoundError):
49
+ backend.spawn(device, "app")
50
+
51
+ device.kill.assert_called_once_with(4242)
52
+ session.detach.assert_called_once() # the session opened before the failure
53
+
54
+
55
+ def test_spawn_does_not_kill_when_spawn_itself_failed(backend):
56
+ device = Mock()
57
+ device.spawn.side_effect = RuntimeError("no such executable")
58
+
59
+ with pytest.raises(ProcessNotFoundError):
60
+ backend.spawn(device, "app")
61
+
62
+ # Nothing was created, so there is no PID -- kill(None) would be a bug.
63
+ device.kill.assert_not_called()
64
+
65
+
66
+ def test_spawn_survives_a_kill_that_fails(backend, caplog):
67
+ device = Mock()
68
+ device.spawn.return_value = 4242
69
+ device.attach.side_effect = RuntimeError("attach denied")
70
+ device.kill.side_effect = RuntimeError("already gone")
71
+
72
+ caplog.set_level(logging.WARNING, logger="tlslibhunter.backends.frida")
73
+ with pytest.raises(ProcessNotFoundError): # original error, not the kill's
74
+ backend.spawn(device, "app")
75
+
76
+ assert "Could not kill orphaned spawn" in caplog.text
77
+
78
+
79
+ # ---------------------------------------------------------------------------
80
+ # create_script(): a script that failed to load is still resident
81
+ # ---------------------------------------------------------------------------
82
+
83
+
84
+ def test_create_script_unloads_when_load_fails(backend):
85
+ script = Mock()
86
+ script.load.side_effect = RuntimeError("syntax error in agent")
87
+ session = Mock()
88
+ session.create_script.return_value = script
89
+
90
+ with pytest.raises(ScriptError):
91
+ backend.create_script(session, "// bad")
92
+
93
+ script.unload.assert_called_once()
94
+
95
+
96
+ def test_create_script_tolerates_failure_before_the_script_exists(backend):
97
+ session = Mock()
98
+ session.create_script.side_effect = RuntimeError("session dead")
99
+
100
+ with pytest.raises(ScriptError):
101
+ backend.create_script(session, "// agent") # must not raise TypeError on None
102
+
103
+
104
+ def test_unload_script_is_safe_on_none_and_on_a_dead_script(backend):
105
+ backend.unload_script(None) # no-op, no exception
106
+
107
+ script = Mock()
108
+ script.unload.side_effect = RuntimeError("script already destroyed")
109
+ backend.unload_script(script) # swallowed: must never mask the real error
110
+
111
+
112
+ # ---------------------------------------------------------------------------
113
+ # Extractors: unload belongs in a finally
114
+ # ---------------------------------------------------------------------------
115
+
116
+
117
+ def _library(tmp_path):
118
+ from tlslibhunter.scanner.results import DetectedLibrary
119
+
120
+ return DetectedLibrary(
121
+ name="libssl.dylib",
122
+ path=str(tmp_path / "libssl.dylib"),
123
+ size=1024,
124
+ library_type="openssl",
125
+ classification="system",
126
+ )
127
+
128
+
129
+ @pytest.mark.parametrize(
130
+ ("module_path", "cls_name", "rpc"),
131
+ [
132
+ ("tlslibhunter.extractor.memory_extractor", "MemoryExtractor", "dump_module_chunks"),
133
+ ("tlslibhunter.extractor.ios_extractor", "IOSExtractor", "read_file_chunks"),
134
+ ],
135
+ )
136
+ def test_extractor_unloads_the_script_when_the_rpc_raises(module_path, cls_name, rpc, tmp_path):
137
+ import importlib
138
+
139
+ module = importlib.import_module(module_path)
140
+ extractor = getattr(module, cls_name)()
141
+
142
+ script = Mock()
143
+ setattr(script.exports_sync, rpc, Mock(side_effect=RuntimeError("agent died")))
144
+ backend = Mock()
145
+ backend.create_script.return_value = script
146
+
147
+ result = extractor.extract(_library(tmp_path), str(tmp_path / "out.bin"), backend, Mock())
148
+
149
+ assert result.success is False
150
+ # The leak: this used to be skipped whenever the exports call raised.
151
+ backend.unload_script.assert_called_once_with(script)
152
+
153
+
154
+ # ---------------------------------------------------------------------------
155
+ # hunter.close(): release the backend and device, and stay re-openable
156
+ # ---------------------------------------------------------------------------
157
+
158
+
159
+ def test_close_releases_backend_and_device():
160
+ hunter = TLSLibHunter("app")
161
+ backend, session = Mock(), Mock()
162
+ hunter._backend, hunter._session, hunter._device = backend, session, Mock()
163
+ hunter._attached = {"pid": 1, "name": "app"}
164
+ hunter._initialized = True
165
+
166
+ hunter.close()
167
+
168
+ backend.detach.assert_called_once_with(session)
169
+ backend.close.assert_called_once()
170
+ assert hunter._session is None
171
+ assert hunter._backend is None
172
+ assert hunter._device is None
173
+ assert hunter._attached is None
174
+ assert hunter._initialized is False
175
+
176
+
177
+ def test_close_is_idempotent():
178
+ hunter = TLSLibHunter("app")
179
+ backend = Mock()
180
+ hunter._backend, hunter._session, hunter._device = backend, Mock(), Mock()
181
+ hunter._initialized = True
182
+
183
+ hunter.close()
184
+ hunter.close() # must not raise on the now-empty state
185
+
186
+ backend.close.assert_called_once()
187
+
188
+
189
+ def test_close_still_releases_the_backend_without_a_session():
190
+ hunter = TLSLibHunter("app")
191
+ backend = Mock()
192
+ hunter._backend, hunter._session = backend, None
193
+
194
+ hunter.close()
195
+
196
+ backend.detach.assert_not_called()
197
+ backend.close.assert_called_once()
198
+
199
+
200
+ # ---------------------------------------------------------------------------
201
+ # Remote devices: remove only what we added
202
+ # ---------------------------------------------------------------------------
203
+
204
+
205
+ def test_close_removes_a_remote_device_we_added(backend, monkeypatch):
206
+ manager = Mock()
207
+ fake_frida = Mock()
208
+ fake_frida.get_device_manager.return_value = manager
209
+ monkeypatch.setattr(frida_backend, "_import_frida", lambda: fake_frida)
210
+
211
+ backend.get_device(host="10.0.0.1:27042")
212
+ backend.close()
213
+
214
+ manager.remove_remote_device.assert_called_once_with("10.0.0.1:27042")
215
+
216
+
217
+ def test_close_leaves_a_remote_device_we_did_not_add(backend, monkeypatch):
218
+ """add_remote_device failing means someone else owns it -- do not remove it."""
219
+ manager = Mock()
220
+ manager.add_remote_device.side_effect = RuntimeError("already registered")
221
+ fake_frida = Mock()
222
+ fake_frida.get_device_manager.return_value = manager
223
+ monkeypatch.setattr(frida_backend, "_import_frida", lambda: fake_frida)
224
+
225
+ backend.get_device(host="10.0.0.1:27042")
226
+ backend.close()
227
+
228
+ manager.remove_remote_device.assert_not_called()
229
+
230
+
231
+ def test_a_shared_remote_device_is_not_removed_while_another_backend_uses_it(monkeypatch):
232
+ """frida's DeviceManager is process-global -- removing the device out from
233
+ under a second live hunter would kill its scan mid-run."""
234
+ manager = Mock()
235
+ fake_frida = Mock()
236
+ fake_frida.get_device_manager.return_value = manager
237
+ monkeypatch.setattr(frida_backend, "_import_frida", lambda: fake_frida)
238
+
239
+ first = frida_backend.FridaBackend()
240
+ second = frida_backend.FridaBackend()
241
+ first.get_device(host="10.0.0.1:27042")
242
+ # The second registration fails ("already registered") but still takes a ref.
243
+ manager.add_remote_device.side_effect = RuntimeError("already registered")
244
+ second.get_device(host="10.0.0.1:27042")
245
+
246
+ first.close()
247
+ manager.remove_remote_device.assert_not_called() # second is still scanning
248
+
249
+ second.close()
250
+ manager.remove_remote_device.assert_called_once_with("10.0.0.1:27042")
251
+
252
+
253
+ def test_close_is_a_noop_for_a_local_backend(backend):
254
+ backend.close()
255
+ backend.close() # idempotent, nothing registered
256
+
257
+
258
+ def test_abc_defaults_keep_other_backends_working():
259
+ assert Backend.close(object()) is None
260
+ assert Backend.unload_script(object(), None) is None
261
+
262
+
263
+ # ---------------------------------------------------------------------------
264
+ # The name-matching rule now has a single definition
265
+ # ---------------------------------------------------------------------------
266
+
267
+
268
+ @pytest.mark.parametrize(
269
+ ("candidate", "target", "exact", "loose"),
270
+ [
271
+ ("Finder", "Finder", True, True),
272
+ ("Finder", "finder", True, True),
273
+ ("QLMarkdown Preview Extension (Finder)", "Finder", False, True),
274
+ ("Google Chrome Helper", "chrome", False, True),
275
+ ("systemd", "Finder", False, False),
276
+ ],
277
+ )
278
+ def test_shared_name_matching_rules(candidate, target, exact, loose):
279
+ assert is_exact_name(candidate, target) is exact
280
+ assert name_matches(candidate, target) is loose