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

Potentially problematic release.


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

@@ -0,0 +1 @@
1
+ r"""usbkey core package."""
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
usbkey_guard/acl.py ADDED
@@ -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
usbkey_guard/audit.py ADDED
@@ -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)
usbkey_guard/cli.py ADDED
@@ -0,0 +1,349 @@
1
+ r"""usbkey command-line interface. Use `usbkey-tui` for the interactive menu."""
2
+ import argparse
3
+ import json
4
+ import sys
5
+ import time
6
+ from pathlib import Path
7
+
8
+ from . import audit as audit_mod
9
+ from . import config, enforce, keystore, paths, procs, setup_app, snapshot, vault
10
+ from .errors import UsbKeyError
11
+ from .journal import Journal
12
+ from .log import get_log
13
+
14
+ _log = get_log("cli")
15
+
16
+
17
+ def runbook_text() -> str:
18
+ return """USBKEY MANUAL RECOVERY
19
+ ======================
20
+
21
+ Your files are encrypted with AES-GCM. Without the USB key AND your passphrase
22
+ nobody can read them - including an administrator. Keep this page offline.
23
+
24
+ 1. Plug in the USB stick and open the TUI, choose Unlock, enter your passphrase.
25
+ 2. If the tool is broken, reinstall it, then run:
26
+ usbkey vault attach <path-to-your-vault-folder>
27
+ usbkey-tui -> Unlock
28
+ 3. If the stick is lost, there is no recovery without the passphrase.
29
+ 4. For ACL-protected folders (legacy), two commands restore access as admin:
30
+ icacls "D:\\SomeFolder" /remove:d "BUILTIN\\Users" /t /c
31
+ icacls "D:\\SomeFolder" /setowner "%USERDOMAIN%\\%USERNAME%" /t /c
32
+
33
+ LIMITS: this is protection at rest, not against a keylogger or a copied unlocked file.
34
+ """
35
+
36
+
37
+ def _confirm(args) -> bool:
38
+ return args.dry_run or args.yes or input("Type YES to continue: ").strip().upper() == "YES"
39
+
40
+
41
+ def cmd_doctor(args) -> int:
42
+ print("usbkey doctor")
43
+ print(" python :", sys.version.split()[0])
44
+ print(" state root :", config.STATE_ROOT)
45
+ print(" install root :", config.INSTALL_ROOT)
46
+ print(" admin token :", setup_app.is_admin())
47
+ print(" ACL roots :", len(enforce.load_config()["roots"]))
48
+ print(" vaults :", len(vault.list_vaults()))
49
+ print(" identity :", "enrolled" if enforce.load_config().get("identity") else "NOT ENROLLED")
50
+ pending = Journal().unreconciled()
51
+ print(" journal :", f"{len(pending)} unreconciled")
52
+ return 4 if pending else 0
53
+
54
+
55
+ def cmd_status(args) -> int:
56
+ cfg = enforce.load_config()
57
+ identity = cfg.get("identity")
58
+ print("STATUS: key", "PRESENT on " + str(keystore.find_key(identity)) if identity and keystore.find_key(identity) else "ABSENT")
59
+ for root in cfg["roots"]:
60
+ print(f" ACL {root['id']} locked={root.get('locked')} {root['path']}")
61
+ for line in vault.status():
62
+ print(" VAULT", line)
63
+ return 0
64
+
65
+
66
+ def cmd_enroll(args) -> int:
67
+ cfg = enforce.load_config()
68
+ if cfg.get("identity") and not args.replace:
69
+ print("Already enrolled. Use --replace to re-enroll (existing vaults must be re-attached).")
70
+ return 1
71
+ result = keystore.enroll(args.drive)
72
+ cfg["identity"] = result["identity"]
73
+ enforce.save_config(cfg)
74
+ print("Enrolled:", result["identity"])
75
+ print("Key file:", result["key_file"])
76
+ return 0
77
+
78
+
79
+ def cmd_audit(args) -> int:
80
+ report = audit_mod.audit(args.path)
81
+ print(audit_mod.format_report(report))
82
+ return 0 if report["passed"] else 7
83
+
84
+
85
+ def cmd_protect(args) -> int:
86
+ if args.action == "list":
87
+ for r in enforce.load_config()["roots"]:
88
+ print(r["id"], "locked=", r.get("locked"), r["path"])
89
+ return 0
90
+ if args.action == "remove":
91
+ enforce.remove_root(args.target)
92
+ print("Removed", args.target)
93
+ return 0
94
+ if not args.i_have_a_backup:
95
+ print("Refusing: pass --i-have-a-backup")
96
+ return 7
97
+ root = enforce.add_root(args.target)
98
+ print("Protected:", root["path"], "id=", root["id"])
99
+ return 0
100
+
101
+
102
+ def cmd_lock(args) -> int:
103
+ if not _confirm(args):
104
+ return 1
105
+ cfg = enforce.load_config()
106
+ if not args.now:
107
+ print("Processes:", procs.stop_protected_processes(
108
+ [r["path"] for r in cfg["roots"]], cfg["settings"]["shutdown_grace_seconds"]))
109
+ for line in enforce.lock_all(dry_run=args.dry_run):
110
+ print(line)
111
+ if not args.dry_run:
112
+ for line in vault.lock_all():
113
+ print("vault:", line)
114
+ return 0
115
+
116
+
117
+ def cmd_unlock(args) -> int:
118
+ cfg = enforce.load_config()
119
+ drive = keystore.find_key(cfg.get("identity") or {})
120
+ if not args.force and not drive:
121
+ print("Key absent. Insert USB or use --force as admin.")
122
+ return 2
123
+ if not _confirm(args):
124
+ return 1
125
+ for line in enforce.unlock_all(dry_run=args.dry_run, force=args.force,
126
+ stick_dir=drive if not args.dry_run else None):
127
+ print(line)
128
+ return 0
129
+
130
+
131
+ def cmd_verify(args) -> int:
132
+ problems = enforce.verify() + vault.verify()
133
+ if problems:
134
+ print("DRIFT DETECTED:")
135
+ for p in problems:
136
+ print(" -", p)
137
+ return 6
138
+ print("OK")
139
+ return 0
140
+
141
+
142
+ def cmd_journal(args) -> int:
143
+ j = Journal()
144
+ if args.action == "replay":
145
+ for note in enforce.replay():
146
+ print(note)
147
+ return 0
148
+ for r in j.records()[-args.n:]:
149
+ print(json.dumps(r, sort_keys=True, default=str))
150
+ print("unreconciled:", len(j.unreconciled()))
151
+ return 0
152
+
153
+
154
+ def cmd_log(args) -> int:
155
+ f = config.STATE_ROOT / "logs" / "usbkey.log"
156
+ if not f.exists():
157
+ print("no log yet")
158
+ return 0
159
+ print("\n".join(f.read_text(encoding="utf-8", errors="replace").splitlines()[-args.n:]))
160
+ return 0
161
+
162
+
163
+ def cmd_export_recovery(args) -> int:
164
+ dest = Path(args.dir)
165
+ dest.mkdir(parents=True, exist_ok=True)
166
+ (dest / "RUNBOOK.md").write_text(runbook_text(), encoding="utf-8")
167
+ for root in enforce.load_config()["roots"]:
168
+ rid = root["id"]
169
+ if snapshot.exists(rid):
170
+ snap = snapshot.load(rid)
171
+ (dest / f"acl-{rid}-sddl.txt").write_text(snap["sddl"], encoding="utf-8")
172
+ (dest / f"acl-{rid}-restore.cmd").write_text(
173
+ snapshot.raw_commands(root["path"], snap), encoding="utf-8")
174
+ for v in vault.list_vaults():
175
+ m = vault._manifest(v)
176
+ (dest / f"vault-{v['id']}-manifest.json").write_text(
177
+ json.dumps(m, indent=2, sort_keys=True), encoding="utf-8")
178
+ print("Recovery bundle:", dest)
179
+ print("Keep it somewhere OTHER than the encrypted machine.")
180
+ return 0
181
+
182
+
183
+ def cmd_vault(args) -> int:
184
+ if args.action == "convert":
185
+ if not args.yes:
186
+ print("Pass --yes after confirming your backup.")
187
+ return 1
188
+ m = vault.convert(args.work_dir, args.vault_dir, passphrase=args.passphrase, yes=True)
189
+ print("Vault id:", m["id"], "files:", len(m["files"]))
190
+ return 0
191
+ if args.action == "attach":
192
+ m = vault.attach(args.vault_dir)
193
+ print("Attached vault:", m["id"])
194
+ return 0
195
+ if args.action == "status":
196
+ print("\n".join(vault.status()))
197
+ return 0
198
+ if args.action == "verify":
199
+ problems = vault.verify()
200
+ print("OK" if not problems else "\n".join(problems))
201
+ return 0 if not problems else 6
202
+ if args.action == "lock":
203
+ for line in vault.lock_all():
204
+ print(line)
205
+ return 0
206
+ if args.action == "unlock":
207
+ for line in vault.unlock(args.vault_id, passphrase=args.passphrase):
208
+ print("restored:", line)
209
+ return 0
210
+ return 1
211
+
212
+
213
+ def cmd_service(args) -> int:
214
+ return {"install": setup_app.install, "uninstall": setup_app.uninstall,
215
+ "status": setup_app.status}[args.action]()
216
+
217
+
218
+ def cmd_monitor(args) -> int:
219
+ cfg = enforce.load_config()
220
+ identity = cfg.get("identity")
221
+ if not identity:
222
+ print("not enrolled")
223
+ return 2
224
+ for note in enforce.replay():
225
+ print("replay:", note)
226
+ grace = cfg["settings"]["grace_seconds"]
227
+ was_present = None
228
+ while True:
229
+ drive = keystore.find_key(identity)
230
+ present = drive is not None
231
+ if present != was_present:
232
+ print("key", "PRESENT" if present else "ABSENT", time.strftime("%H:%M:%S"))
233
+ if present:
234
+ for line in enforce.unlock_all(stick_dir=drive):
235
+ print(line)
236
+ else:
237
+ time.sleep(grace)
238
+ if keystore.find_key(identity) is None:
239
+ current = enforce.load_config()
240
+ print("Processes:", procs.stop_protected_processes(
241
+ [r["path"] for r in current["roots"]],
242
+ current["settings"]["shutdown_grace_seconds"]))
243
+ for line in enforce.lock_all():
244
+ print(line)
245
+ for line in vault.lock_all():
246
+ print("vault:", line)
247
+ was_present = present
248
+ if args.once:
249
+ break
250
+ time.sleep(1)
251
+ return 0
252
+
253
+
254
+ def cmd_gate(args) -> int:
255
+ cfg = enforce.load_config()
256
+ if not keystore.find_key(cfg.get("identity") or {}):
257
+ print("usbkey: key absent - launch denied:", args.exe)
258
+ return 2
259
+ import subprocess
260
+ return subprocess.call([args.exe] + args.rest)
261
+
262
+
263
+ def build_parser() -> argparse.ArgumentParser:
264
+ p = argparse.ArgumentParser(prog="usbkey", description="USB-key-gated encrypted vault")
265
+ sub = p.add_subparsers(dest="command", required=True)
266
+
267
+ sub.add_parser("doctor").set_defaults(func=cmd_doctor)
268
+ sub.add_parser("status").set_defaults(func=cmd_status)
269
+ sub.add_parser("verify").set_defaults(func=cmd_verify)
270
+
271
+ e = sub.add_parser("enroll")
272
+ e.add_argument("--drive", required=True)
273
+ e.add_argument("--replace", action="store_true")
274
+ e.set_defaults(func=cmd_enroll)
275
+
276
+ a = sub.add_parser("audit")
277
+ a.add_argument("path")
278
+ a.set_defaults(func=cmd_audit)
279
+
280
+ pr = sub.add_parser("protect")
281
+ pr.add_argument("action", choices=["add", "remove", "list"])
282
+ pr.add_argument("target", nargs="?")
283
+ pr.add_argument("--i-have-a-backup", action="store_true")
284
+ pr.set_defaults(func=cmd_protect)
285
+
286
+ lk = sub.add_parser("lock")
287
+ lk.add_argument("--dry-run", action="store_true")
288
+ lk.add_argument("--now", action="store_true")
289
+ lk.add_argument("--yes", action="store_true")
290
+ lk.set_defaults(func=cmd_lock)
291
+
292
+ ul = sub.add_parser("unlock")
293
+ ul.add_argument("--dry-run", action="store_true")
294
+ ul.add_argument("--force", action="store_true")
295
+ ul.add_argument("--yes", action="store_true")
296
+ ul.set_defaults(func=cmd_unlock)
297
+
298
+ jr = sub.add_parser("journal")
299
+ jr.add_argument("action", choices=["show", "replay"])
300
+ jr.add_argument("-n", type=int, default=50)
301
+ jr.set_defaults(func=cmd_journal)
302
+
303
+ lg = sub.add_parser("log")
304
+ lg.add_argument("-n", type=int, default=50)
305
+ lg.set_defaults(func=cmd_log)
306
+
307
+ ex = sub.add_parser("export-recovery")
308
+ ex.add_argument("dir")
309
+ ex.set_defaults(func=cmd_export_recovery)
310
+
311
+ va = sub.add_parser("vault")
312
+ va.add_argument("action", choices=["convert", "attach", "unlock", "lock", "status", "verify"])
313
+ va.add_argument("--work-dir")
314
+ va.add_argument("--vault-dir")
315
+ va.add_argument("--vault-id")
316
+ va.add_argument("--passphrase")
317
+ va.add_argument("--yes", action="store_true")
318
+ va.set_defaults(func=cmd_vault)
319
+
320
+ sv = sub.add_parser("service")
321
+ sv.add_argument("action", choices=["install", "uninstall", "status"])
322
+ sv.set_defaults(func=cmd_service)
323
+
324
+ mo = sub.add_parser("monitor")
325
+ mo.add_argument("--once", action="store_true")
326
+ mo.set_defaults(func=cmd_monitor)
327
+
328
+ gt = sub.add_parser("gate")
329
+ gt.add_argument("--exe", required=True)
330
+ gt.add_argument("rest", nargs=argparse.REMAINDER)
331
+ gt.set_defaults(func=cmd_gate)
332
+ return p
333
+
334
+
335
+ def main(argv=None) -> int:
336
+ args = build_parser().parse_args(argv)
337
+ try:
338
+ return int(args.func(args))
339
+ except UsbKeyError as exc:
340
+ print(f"ERROR({exc.code}): {exc}")
341
+ return exc.code
342
+ except Exception as exc:
343
+ _log.exception("unhandled")
344
+ print(f"ERROR: {type(exc).__name__}: {exc}")
345
+ return 1
346
+
347
+
348
+ if __name__ == "__main__":
349
+ sys.exit(main())
usbkey_guard/config.py ADDED
@@ -0,0 +1,20 @@
1
+ r"""Site-specific paths. All overridable by environment variables."""
2
+ import os
3
+ from pathlib import Path
4
+
5
+ APP_NAME = "usbkey"
6
+ TASK_NAME = "usbkey-enforcer"
7
+
8
+ PROGRAMDATA = Path(os.environ.get("PROGRAMDATA", r"C:\ProgramData"))
9
+ PROGRAM_FILES = Path(os.environ.get("ProgramFiles", r"C:\Program Files"))
10
+
11
+ STATE_ROOT = Path(
12
+ os.environ.get("USBKEY_STATE", str(PROGRAMDATA / APP_NAME))
13
+ ).expanduser().resolve()
14
+ INSTALL_ROOT = Path(
15
+ os.environ.get("USBKEY_INSTALL", str(PROGRAM_FILES / APP_NAME))
16
+ ).expanduser().resolve()
17
+ PACKAGE_ROOT = Path(__file__).resolve().parent
18
+
19
+ KEY_FILENAME = "key.dat"
20
+ VAULT_SUFFIX = ".vault"