usbkey-guard 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.

Potentially problematic release.


This version of usbkey-guard might be problematic. Click here for more details.

Files changed (35) hide show
  1. usbkey_guard-1.0.0/LICENSE +21 -0
  2. usbkey_guard-1.0.0/PKG-INFO +49 -0
  3. usbkey_guard-1.0.0/README.md +32 -0
  4. usbkey_guard-1.0.0/pyproject.toml +31 -0
  5. usbkey_guard-1.0.0/setup.cfg +4 -0
  6. usbkey_guard-1.0.0/src/usbkey_guard/__init__.py +1 -0
  7. usbkey_guard-1.0.0/src/usbkey_guard/__main__.py +3 -0
  8. usbkey_guard-1.0.0/src/usbkey_guard/acl.py +149 -0
  9. usbkey_guard-1.0.0/src/usbkey_guard/audit.py +82 -0
  10. usbkey_guard-1.0.0/src/usbkey_guard/cli.py +349 -0
  11. usbkey_guard-1.0.0/src/usbkey_guard/config.py +20 -0
  12. usbkey_guard-1.0.0/src/usbkey_guard/enforce.py +229 -0
  13. usbkey_guard-1.0.0/src/usbkey_guard/errors.py +42 -0
  14. usbkey_guard-1.0.0/src/usbkey_guard/journal.py +125 -0
  15. usbkey_guard-1.0.0/src/usbkey_guard/keystore.py +93 -0
  16. usbkey_guard-1.0.0/src/usbkey_guard/log.py +35 -0
  17. usbkey_guard-1.0.0/src/usbkey_guard/paths.py +151 -0
  18. usbkey_guard-1.0.0/src/usbkey_guard/privs.py +53 -0
  19. usbkey_guard-1.0.0/src/usbkey_guard/procs.py +83 -0
  20. usbkey_guard-1.0.0/src/usbkey_guard/setup_app.py +96 -0
  21. usbkey_guard-1.0.0/src/usbkey_guard/snapshot.py +124 -0
  22. usbkey_guard-1.0.0/src/usbkey_guard/tui.py +314 -0
  23. usbkey_guard-1.0.0/src/usbkey_guard/vault.py +282 -0
  24. usbkey_guard-1.0.0/src/usbkey_guard.egg-info/PKG-INFO +49 -0
  25. usbkey_guard-1.0.0/src/usbkey_guard.egg-info/SOURCES.txt +33 -0
  26. usbkey_guard-1.0.0/src/usbkey_guard.egg-info/dependency_links.txt +1 -0
  27. usbkey_guard-1.0.0/src/usbkey_guard.egg-info/entry_points.txt +4 -0
  28. usbkey_guard-1.0.0/src/usbkey_guard.egg-info/requires.txt +5 -0
  29. usbkey_guard-1.0.0/src/usbkey_guard.egg-info/top_level.txt +1 -0
  30. usbkey_guard-1.0.0/tests/test_journal.py +33 -0
  31. usbkey_guard-1.0.0/tests/test_no_destructive_ops.py +77 -0
  32. usbkey_guard-1.0.0/tests/test_paths.py +27 -0
  33. usbkey_guard-1.0.0/tests/test_replay.py +61 -0
  34. usbkey_guard-1.0.0/tests/test_roundtrip.py +40 -0
  35. usbkey_guard-1.0.0/tests/test_vault_ids.py +32 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 usbkey-guard contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.4
2
+ Name: usbkey-guard
3
+ Version: 1.0.0
4
+ Summary: USB-key-gated AES-GCM vault for Windows (headless, TUI, no GUI)
5
+ License-Expression: MIT
6
+ Classifier: Operating System :: Microsoft :: Windows
7
+ Classifier: Programming Language :: Python :: 3.11
8
+ Classifier: Programming Language :: Python :: 3.12
9
+ Classifier: Topic :: Security
10
+ Requires-Python: >=3.11
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: pywin32>=306; sys_platform == "win32"
14
+ Requires-Dist: psutil>=5.9
15
+ Requires-Dist: cryptography>=42
16
+ Dynamic: license-file
17
+
18
+ # usbkey-guard
19
+
20
+ Headless Windows tool that keeps files locked unless a specific USB stick is inserted.
21
+ Files are encrypted with AES-GCM, so even an administrator cannot read them without
22
+ the USB key **and** your passphrase.
23
+
24
+ Interactive TUI: `usbkey-tui`
25
+ Scriptable CLI: `usbkey`
26
+
27
+ ## Quick start
28
+
29
+ ```powershell
30
+ pip install .
31
+ usbkey-tui
32
+ ```
33
+
34
+ The TUI walks you through:
35
+ 1. selecting and enrolling a USB drive,
36
+ 2. choosing a file or folder to encrypt,
37
+ 3. setting a passphrase,
38
+ 4. unlocking later with the stick + passphrase.
39
+
40
+ See `INSTALL.md`, `QUICKSTART.md` and `LIMITATIONS.md`.
41
+
42
+ ## Safety
43
+
44
+ Encryption is written and verified before any plaintext is removed. Locking never deletes
45
+ a file that changed since unlock. State is journaled with write-ahead records and can be
46
+ reconciled after a crash.
47
+
48
+ This is protection **at rest**. It is not a defence against keyloggers, a copied already-
49
+ unlocked file, or an attacker with your passphrase.
@@ -0,0 +1,32 @@
1
+ # usbkey-guard
2
+
3
+ Headless Windows tool that keeps files locked unless a specific USB stick is inserted.
4
+ Files are encrypted with AES-GCM, so even an administrator cannot read them without
5
+ the USB key **and** your passphrase.
6
+
7
+ Interactive TUI: `usbkey-tui`
8
+ Scriptable CLI: `usbkey`
9
+
10
+ ## Quick start
11
+
12
+ ```powershell
13
+ pip install .
14
+ usbkey-tui
15
+ ```
16
+
17
+ The TUI walks you through:
18
+ 1. selecting and enrolling a USB drive,
19
+ 2. choosing a file or folder to encrypt,
20
+ 3. setting a passphrase,
21
+ 4. unlocking later with the stick + passphrase.
22
+
23
+ See `INSTALL.md`, `QUICKSTART.md` and `LIMITATIONS.md`.
24
+
25
+ ## Safety
26
+
27
+ Encryption is written and verified before any plaintext is removed. Locking never deletes
28
+ a file that changed since unlock. State is journaled with write-ahead records and can be
29
+ reconciled after a crash.
30
+
31
+ This is protection **at rest**. It is not a defence against keyloggers, a copied already-
32
+ unlocked file, or an attacker with your passphrase.
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "usbkey-guard"
7
+ version = "1.0.0"
8
+ description = "USB-key-gated AES-GCM vault for Windows (headless, TUI, no GUI)"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ dependencies = [
14
+ "pywin32>=306; sys_platform == 'win32'",
15
+ "psutil>=5.9",
16
+ "cryptography>=42",
17
+ ]
18
+ classifiers = [
19
+ "Operating System :: Microsoft :: Windows",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Topic :: Security",
23
+ ]
24
+
25
+ [project.scripts]
26
+ usbkey = "usbkey_guard.cli:main"
27
+ usbkey-tui = "usbkey_guard.tui:main"
28
+ usbkey-setup = "usbkey_guard.setup_app:main"
29
+
30
+ [tool.setuptools.packages.find]
31
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1 @@
1
+ r"""usbkey core package."""
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,149 @@
1
+ r"""THE ONLY module that mutates protected filesystem objects.
2
+
3
+ Two mutations, both reversible:
4
+ 1. add one inheritable deny ACE for BUILTIN\Users (S-1-5-32-545)
5
+ 2. change owner to NT AUTHORITY\SYSTEM (S-1-5-18)
6
+
7
+ No content is read or written. No file is created, moved or deleted.
8
+ Never deny Everyone or Authenticated Users: SYSTEM belongs to both and would
9
+ lose its own recovery path.
10
+ """
11
+ from typing import Any
12
+
13
+ import win32con
14
+ import win32security
15
+
16
+ from . import snapshot
17
+ from .log import get_log
18
+ from .privs import enable_privileges
19
+
20
+ USERS_SID = "S-1-5-32-545"
21
+ SYSTEM_SID = "S-1-5-18"
22
+ DENY_SID = win32security.ConvertStringSidToSid(USERS_SID)
23
+ SYSTEM = win32security.ConvertStringSidToSid(SYSTEM_SID)
24
+ DENY_MASK = win32con.GENERIC_ALL
25
+ INHERIT = win32security.OBJECT_INHERIT_ACE | win32security.CONTAINER_INHERIT_ACE
26
+ ACCESS_DENIED = win32security.ACCESS_DENIED_ACE_TYPE
27
+
28
+ _log = get_log("acl")
29
+
30
+
31
+ def _dacl(path: str) -> Any:
32
+ enable_privileges()
33
+ sd = win32security.GetNamedSecurityInfo(
34
+ path, win32security.SE_FILE_OBJECT, win32security.DACL_SECURITY_INFORMATION
35
+ )
36
+ return sd.GetSecurityDescriptorDacl()
37
+
38
+
39
+ def _owner(path: str) -> str:
40
+ enable_privileges()
41
+ sd = win32security.GetNamedSecurityInfo(
42
+ path, win32security.SE_FILE_OBJECT, win32security.OWNER_SECURITY_INFORMATION
43
+ )
44
+ return win32security.ConvertSidToStringSid(sd.GetSecurityDescriptorOwner())
45
+
46
+
47
+ def _our_deny_indices(dacl: Any) -> list[int]:
48
+ indices = []
49
+ for i in range(dacl.GetAceCount()):
50
+ try:
51
+ (ace_type, flags), mask, sid = dacl.GetAce(i)
52
+ except Exception:
53
+ continue
54
+ if (
55
+ int(ace_type) == ACCESS_DENIED
56
+ and win32security.ConvertSidToStringSid(sid) == USERS_SID
57
+ and int(mask) in (DENY_MASK, 0x001F01FF)
58
+ and (int(flags) & INHERIT) in (0, INHERIT)
59
+ ):
60
+ indices.append(i)
61
+ return indices
62
+
63
+
64
+ def is_locked(path: str) -> bool:
65
+ try:
66
+ if _owner(path) != SYSTEM_SID:
67
+ return False
68
+ return len(_our_deny_indices(_dacl(path))) > 0
69
+ except Exception as exc:
70
+ _log.error("is_locked failed for %s: %s", path, exc)
71
+ return False
72
+
73
+
74
+ def apply_lock(path: str, snap: dict[str, Any], dry_run: bool = False) -> None:
75
+ """Add the deny ACE and set owner to SYSTEM. Idempotent."""
76
+ if dry_run:
77
+ _log.info("DRY-RUN lock %s: add deny %s, owner -> %s", path, USERS_SID, SYSTEM_SID)
78
+ return
79
+ enable_privileges()
80
+ if is_locked(path):
81
+ _log.info("already locked, no-op: %s", path)
82
+ return
83
+ dacl = _dacl(path)
84
+ if not _our_deny_indices(dacl):
85
+ dacl.AddAccessDeniedAceEx(win32security.ACL_REVISION_DS, INHERIT, DENY_MASK, DENY_SID)
86
+ win32security.SetNamedSecurityInfo(
87
+ path, win32security.SE_FILE_OBJECT,
88
+ win32security.DACL_SECURITY_INFORMATION, None, None, dacl, None,
89
+ )
90
+ if _owner(path) != SYSTEM_SID:
91
+ win32security.SetNamedSecurityInfo(
92
+ path, win32security.SE_FILE_OBJECT,
93
+ win32security.OWNER_SECURITY_INFORMATION, SYSTEM, None, None, None,
94
+ )
95
+ if not is_locked(path):
96
+ raise RuntimeError("lock verification failed for " + path)
97
+
98
+
99
+ def apply_unlock(path: str, snap: dict[str, Any], dry_run: bool = False) -> None:
100
+ """Restore the authoritative snapshot. Idempotent."""
101
+ if dry_run:
102
+ _log.info("DRY-RUN unlock %s: remove deny %s, owner -> %s", path, USERS_SID, snap["owner"])
103
+ return
104
+ enable_privileges()
105
+ if not is_locked(path):
106
+ _log.info("not locked, no-op: %s", path)
107
+ return
108
+ snapshot.restore(path, snap)
109
+ if is_locked(path):
110
+ raise RuntimeError("unlock verification failed for " + path)
111
+
112
+
113
+ def remove_deny_fallback(path: str) -> None:
114
+ """Last-resort surgical removal when a snapshot is unavailable."""
115
+ enable_privileges()
116
+ dacl = _dacl(path)
117
+ for index in reversed(_our_deny_indices(dacl)):
118
+ dacl.DeleteAce(index)
119
+ win32security.SetNamedSecurityInfo(
120
+ path, win32security.SE_FILE_OBJECT,
121
+ win32security.DACL_SECURITY_INFORMATION, None, None, dacl, None,
122
+ )
123
+
124
+
125
+ def _ace_key(ace: dict[str, Any]) -> tuple[Any, ...]:
126
+ return (ace.get("type"), ace.get("flags"), ace.get("mask"), ace.get("sid"))
127
+
128
+
129
+ def matches_snapshot(path: str, snap: dict[str, Any]) -> bool:
130
+ """Semantic equivalence: owner restored, no deny ACE, no permission lost.
131
+
132
+ Windows may add an explicit owner ACE when ownership is restored, so an
133
+ exact SDDL string comparison is too strict. Extra allow ACEs are tolerated;
134
+ missing ones are not.
135
+ """
136
+ try:
137
+ current = snapshot.capture(path)
138
+ if current["sddl"] == snap["sddl"]:
139
+ return True
140
+ if current["owner"] != snap["owner"]:
141
+ return False
142
+ if _our_deny_indices(_dacl(path)):
143
+ return False
144
+ saved = {_ace_key(a) for a in snap["aces"]}
145
+ now = {_ace_key(a) for a in current["aces"]}
146
+ return saved <= now
147
+ except Exception as exc:
148
+ _log.error("snapshot comparison failed: %s", exc)
149
+ return False
@@ -0,0 +1,82 @@
1
+ r"""Read-only pre-flight analysis. Never mutates anything."""
2
+ import os
3
+ from typing import Any
4
+
5
+ import win32security
6
+
7
+ from . import paths
8
+ from .log import get_log
9
+
10
+ INHERITED_ACE = 0x10
11
+ _log = get_log("audit")
12
+
13
+
14
+ def _inheritance_broken(path: str) -> bool:
15
+ try:
16
+ sd = win32security.GetNamedSecurityInfo(
17
+ path, win32security.SE_FILE_OBJECT, win32security.DACL_SECURITY_INFORMATION
18
+ )
19
+ dacl = sd.GetSecurityDescriptorDacl()
20
+ if dacl is None:
21
+ return False
22
+ return not any(
23
+ int(dacl.GetAce(i)[0][1]) & INHERITED_ACE
24
+ for i in range(dacl.GetAceCount())
25
+ )
26
+ except Exception as exc:
27
+ _log.warning("could not read ACL of %s: %s", path, exc)
28
+ return False
29
+
30
+
31
+ def audit(path: str, allow_dummy: bool = False) -> dict[str, Any]:
32
+ result: dict[str, Any] = {
33
+ "path": os.path.abspath(path),
34
+ "passed": False,
35
+ "refusals": [],
36
+ "warnings": [],
37
+ "stats": {"entries": 0, "inheritance_broken": 0, "reparse_skipped": 0},
38
+ }
39
+ try:
40
+ paths.safe_target(path, allow_dummy=allow_dummy)
41
+ except ValueError as exc:
42
+ result["refusals"].append(str(exc))
43
+ return result
44
+
45
+ sample: list[str] = []
46
+ if os.path.isdir(path):
47
+ for root, dirs, files in os.walk(path, followlinks=False):
48
+ for name in list(dirs):
49
+ full = os.path.join(root, name)
50
+ try:
51
+ if os.lstat(full).st_file_attributes & 0x400:
52
+ dirs.remove(name)
53
+ result["stats"]["reparse_skipped"] += 1
54
+ except (OSError, AttributeError):
55
+ pass
56
+ result["stats"]["entries"] += len(dirs) + len(files)
57
+ for name in dirs[:]:
58
+ full = os.path.join(root, name)
59
+ if _inheritance_broken(full):
60
+ result["stats"]["inheritance_broken"] += 1
61
+ if len(sample) < 10:
62
+ sample.append(full)
63
+ if result["stats"]["entries"] > 100000:
64
+ result["warnings"].append("over 100k entries — verification will be slow")
65
+ break
66
+ if result["stats"]["inheritance_broken"]:
67
+ result["warnings"].append(
68
+ f'{result["stats"]["inheritance_broken"]} descendants have inheritance disabled '
69
+ f"and will NOT be protected: {sample}"
70
+ )
71
+ result["passed"] = not result["refusals"]
72
+ return result
73
+
74
+
75
+ def format_report(report: dict[str, Any]) -> str:
76
+ lines = [f"PATH : {report['path']}", f"RESULT : {'PASS' if report['passed'] else 'REFUSED'}"]
77
+ for r in report["refusals"]:
78
+ lines.append(f"REFUSE : {r}")
79
+ for w in report["warnings"]:
80
+ lines.append(f"WARNING : {w}")
81
+ lines.append("STATS : " + ", ".join(f"{k}={v}" for k, v in report["stats"].items()))
82
+ return "\n".join(lines)