minaki 0.1.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.
- minaki/__init__.py +5 -0
- minaki/__main__.py +7 -0
- minaki/cli.py +111 -0
- minaki/plugin.py +105 -0
- minaki/plugins/__init__.py +8 -0
- minaki/plugins/grub/__init__.py +23 -0
- minaki/plugins/grub/checks.py +407 -0
- minaki/plugins/grub/cli.py +99 -0
- minaki/sdk.py +83 -0
- minaki-0.1.0.dist-info/METADATA +243 -0
- minaki-0.1.0.dist-info/RECORD +16 -0
- minaki-0.1.0.dist-info/WHEEL +5 -0
- minaki-0.1.0.dist-info/entry_points.txt +5 -0
- minaki-0.1.0.dist-info/licenses/LICENSE +202 -0
- minaki-0.1.0.dist-info/licenses/NOTICE +4 -0
- minaki-0.1.0.dist-info/top_level.txt +1 -0
minaki/__init__.py
ADDED
minaki/__main__.py
ADDED
minaki/cli.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# Copyright 2026 MinakiLabs LLC
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""The minaki command: global flags and the subcommand only.
|
|
4
|
+
|
|
5
|
+
Everything after ``minaki <command>`` is handed to that plugin unchanged.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .plugin import discover, load
|
|
12
|
+
from .sdk import API_VERSION, print_json
|
|
13
|
+
|
|
14
|
+
EXIT_USAGE = 2
|
|
15
|
+
|
|
16
|
+
USAGE = "usage: minaki [--version] [--help] [--plugins [--json]] COMMAND [ARGS...]"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _help(out):
|
|
20
|
+
out.write(USAGE + "\n\n")
|
|
21
|
+
out.write("MinakiLabs command-line tools. No network, no background service, no account.\n\n")
|
|
22
|
+
plugins = discover()
|
|
23
|
+
out.write("commands:\n")
|
|
24
|
+
if not plugins:
|
|
25
|
+
out.write(" (none installed)\n")
|
|
26
|
+
width = max([len(p.name) for p in plugins] + [8])
|
|
27
|
+
for p in plugins:
|
|
28
|
+
try:
|
|
29
|
+
summary = load(p).summary
|
|
30
|
+
except Exception as e: # a broken third-party plugin must not break --help
|
|
31
|
+
summary = "(cannot load %s: %s: %s)" % (p.value, type(e).__name__, e)
|
|
32
|
+
if p.dist != "minaki":
|
|
33
|
+
summary += " [from %s]" % p.dist
|
|
34
|
+
out.write(" %-*s %s\n" % (width, p.name, summary))
|
|
35
|
+
if p.conflict:
|
|
36
|
+
out.write(" %-*s (also registered by %s; not used)\n" % (width, "", p.conflict))
|
|
37
|
+
out.write("\nRun 'minaki COMMAND --help' for a command's options.\n")
|
|
38
|
+
out.write("Write your own: see the plugin guide at https://github.com/MinakiLabs-Official/minaki/blob/main/docs/PLUGINS.md\n")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _plugins(as_json):
|
|
42
|
+
"""List every registered plugin and whether it loads. For plugin authors."""
|
|
43
|
+
rows = []
|
|
44
|
+
for p in discover():
|
|
45
|
+
row = {"name": p.name, "entry_point": p.value, "distribution": p.dist, "conflict": p.conflict}
|
|
46
|
+
try:
|
|
47
|
+
obj = load(p)
|
|
48
|
+
row.update(status="ok", summary=obj.summary, api_version=getattr(obj, "api_version", 1))
|
|
49
|
+
except Exception as e:
|
|
50
|
+
row.update(status="error", error="%s: %s" % (type(e).__name__, e))
|
|
51
|
+
rows.append(row)
|
|
52
|
+
if as_json:
|
|
53
|
+
print_json({"tool": "minaki", "version": __version__, "api_version": API_VERSION, "plugins": rows})
|
|
54
|
+
else:
|
|
55
|
+
sys.stdout.write("minaki %s, plugin API %d\n" % (__version__, API_VERSION))
|
|
56
|
+
for r in rows:
|
|
57
|
+
where = "%s from %s" % (r["entry_point"], r["distribution"])
|
|
58
|
+
state = "ok" if r["status"] == "ok" else "ERROR " + r["error"]
|
|
59
|
+
sys.stdout.write(" %-10s %s [%s]\n" % (r["name"], where, state))
|
|
60
|
+
if not rows:
|
|
61
|
+
sys.stdout.write(" (none installed)\n")
|
|
62
|
+
return 0 if all(r["status"] == "ok" for r in rows) else 1
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _usage_error(msg):
|
|
66
|
+
sys.stderr.write("minaki: %s\n%s\n" % (msg, USAGE))
|
|
67
|
+
return EXIT_USAGE
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def main(argv=None):
|
|
71
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
72
|
+
if not argv:
|
|
73
|
+
_help(sys.stderr)
|
|
74
|
+
return EXIT_USAGE
|
|
75
|
+
first = argv[0]
|
|
76
|
+
if first in ("-h", "--help", "help"):
|
|
77
|
+
_help(sys.stdout)
|
|
78
|
+
return 0
|
|
79
|
+
if first in ("-V", "--version"):
|
|
80
|
+
sys.stdout.write("minaki %s\n" % __version__)
|
|
81
|
+
return 0
|
|
82
|
+
if first == "--plugins":
|
|
83
|
+
rest = argv[1:]
|
|
84
|
+
if rest not in ([], ["--json"]):
|
|
85
|
+
return _usage_error("--plugins takes only --json")
|
|
86
|
+
return _plugins(bool(rest))
|
|
87
|
+
if first.startswith("-"):
|
|
88
|
+
return _usage_error("unknown option %s" % first)
|
|
89
|
+
|
|
90
|
+
match = [p for p in discover() if p.name == first]
|
|
91
|
+
if not match:
|
|
92
|
+
return _usage_error("unknown command %r (see 'minaki --help')" % first)
|
|
93
|
+
try:
|
|
94
|
+
plugin = load(match[0])
|
|
95
|
+
except Exception as e:
|
|
96
|
+
sys.stderr.write("minaki: cannot load %r from %s: %s: %s\n" % (first, match[0].dist, type(e).__name__, e))
|
|
97
|
+
return EXIT_USAGE
|
|
98
|
+
try:
|
|
99
|
+
code = plugin.run(argv[1:])
|
|
100
|
+
except SystemExit as e: # argparse inside a plugin
|
|
101
|
+
code = e.code if isinstance(e.code, int) else (0 if e.code is None else EXIT_USAGE)
|
|
102
|
+
except KeyboardInterrupt:
|
|
103
|
+
return 130
|
|
104
|
+
except Exception as e:
|
|
105
|
+
sys.stderr.write("minaki %s: internal error: %s: %s\n" % (first, type(e).__name__, e))
|
|
106
|
+
return EXIT_USAGE
|
|
107
|
+
return code if isinstance(code, int) else EXIT_USAGE
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
if __name__ == "__main__":
|
|
111
|
+
sys.exit(main())
|
minaki/plugin.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# Copyright 2026 MinakiLabs LLC
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""The plugin slot.
|
|
4
|
+
|
|
5
|
+
A plugin is an object registered on the entry-point group ``minaki.plugins``.
|
|
6
|
+
The entry-point name is the subcommand (``minaki grub ...``). The object has:
|
|
7
|
+
|
|
8
|
+
name: str the subcommand, same as the entry-point name
|
|
9
|
+
summary: str one line for ``minaki --help``
|
|
10
|
+
run(argv) -> int everything after ``minaki <name>``; returns the exit code
|
|
11
|
+
|
|
12
|
+
Exit codes: 0 ok, 1 the thing checked is bad, 2 could not check (bad usage,
|
|
13
|
+
a missing tool, not applicable).
|
|
14
|
+
|
|
15
|
+
Plugins do not share a config file, a daemon or a network client. Third parties
|
|
16
|
+
can publish a package that depends on ``minaki`` and registers on the same
|
|
17
|
+
group. Nothing here downloads, installs or updates plugins.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
import sys
|
|
21
|
+
from typing import List, NamedTuple, Optional
|
|
22
|
+
|
|
23
|
+
try: # Python 3.8+
|
|
24
|
+
from typing import Protocol
|
|
25
|
+
except ImportError: # pragma: no cover
|
|
26
|
+
Protocol = object # type: ignore
|
|
27
|
+
|
|
28
|
+
if sys.version_info >= (3, 8):
|
|
29
|
+
from importlib import metadata as _metadata
|
|
30
|
+
else: # pragma: no cover
|
|
31
|
+
_metadata = None
|
|
32
|
+
|
|
33
|
+
from .sdk import API_VERSION, ENTRY_POINT_GROUP
|
|
34
|
+
|
|
35
|
+
GROUP = ENTRY_POINT_GROUP
|
|
36
|
+
OWN_DIST = "minaki"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Plugin(Protocol):
|
|
40
|
+
name: str
|
|
41
|
+
summary: str
|
|
42
|
+
|
|
43
|
+
def run(self, argv: List[str]) -> int:
|
|
44
|
+
...
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Found(NamedTuple):
|
|
48
|
+
name: str # entry-point name = subcommand
|
|
49
|
+
value: str # "module:attr"
|
|
50
|
+
dist: str # distribution that registered it
|
|
51
|
+
entry_point: object
|
|
52
|
+
conflict: Optional[str] # another registration of the same name that lost
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _dist_name(dist):
|
|
56
|
+
try:
|
|
57
|
+
return dist.metadata["Name"] or "?"
|
|
58
|
+
except Exception:
|
|
59
|
+
return "?"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def discover():
|
|
63
|
+
"""Every plugin registered on GROUP, by name. Loads nothing.
|
|
64
|
+
|
|
65
|
+
Walks distributions directly (works the same on Python 3.8 to 3.14). If two
|
|
66
|
+
distributions register the same name, the one in the minaki package wins and
|
|
67
|
+
the other is reported as a conflict.
|
|
68
|
+
"""
|
|
69
|
+
found = {}
|
|
70
|
+
for dist in _metadata.distributions():
|
|
71
|
+
try:
|
|
72
|
+
eps = dist.entry_points
|
|
73
|
+
except Exception:
|
|
74
|
+
continue
|
|
75
|
+
dname = _dist_name(dist)
|
|
76
|
+
for ep in eps:
|
|
77
|
+
if ep.group != GROUP:
|
|
78
|
+
continue
|
|
79
|
+
prev = found.get(ep.name)
|
|
80
|
+
if prev is None:
|
|
81
|
+
found[ep.name] = Found(ep.name, ep.value, dname, ep, None)
|
|
82
|
+
elif prev.value == ep.value:
|
|
83
|
+
continue # the same package seen twice on sys.path
|
|
84
|
+
elif dname == OWN_DIST and prev.dist != OWN_DIST:
|
|
85
|
+
found[ep.name] = Found(ep.name, ep.value, dname, ep, "%s (%s)" % (prev.value, prev.dist))
|
|
86
|
+
else:
|
|
87
|
+
found[ep.name] = prev._replace(conflict="%s (%s)" % (ep.value, dname))
|
|
88
|
+
return [found[k] for k in sorted(found)]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def load(found):
|
|
92
|
+
"""Load one plugin and check it has the slot's shape. Raises on anything wrong."""
|
|
93
|
+
obj = found.entry_point.load()
|
|
94
|
+
for attr in ("name", "summary", "run"):
|
|
95
|
+
if not hasattr(obj, attr):
|
|
96
|
+
raise TypeError("%s has no %r" % (found.value, attr))
|
|
97
|
+
if not callable(obj.run):
|
|
98
|
+
raise TypeError("%s.run is not callable" % found.value)
|
|
99
|
+
if obj.name != found.name:
|
|
100
|
+
raise TypeError("%s says its name is %r but is registered as %r" % (found.value, obj.name, found.name))
|
|
101
|
+
wants = getattr(obj, "api_version", 1)
|
|
102
|
+
if not isinstance(wants, int) or wants > API_VERSION:
|
|
103
|
+
raise TypeError("%s needs plugin API %r; this minaki has API %d (upgrade minaki)"
|
|
104
|
+
% (found.value, wants, API_VERSION))
|
|
105
|
+
return obj
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Copyright 2026 MinakiLabs LLC
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Plugins maintained by MinakiLabs, bundled in the minaki package.
|
|
4
|
+
|
|
5
|
+
Each one is registered on the "minaki.plugins" entry-point group in
|
|
6
|
+
pyproject.toml. The core finds them through that group only; it never imports
|
|
7
|
+
a plugin by name.
|
|
8
|
+
"""
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Copyright 2026 MinakiLabs LLC
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""The grub plugin: minaki grub check | pin.
|
|
4
|
+
|
|
5
|
+
Read-only. Never writes to /boot, never runs update-grub or grub-mkconfig,
|
|
6
|
+
never touches the network.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
from ...sdk import Plugin
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class GrubPlugin(Plugin):
|
|
14
|
+
name = "grub"
|
|
15
|
+
summary = "Read-only GRUB check: is /boot/grub/grub.cfg bootable? (check, pin)"
|
|
16
|
+
|
|
17
|
+
def run(self, argv):
|
|
18
|
+
from .cli import main # loaded only when the command runs
|
|
19
|
+
|
|
20
|
+
return main(argv)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
plugin = GrubPlugin()
|
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
# Copyright 2026 MinakiLabs LLC
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""minaki grub: read-only checks on a GRUB config, and the last-good copy.
|
|
4
|
+
|
|
5
|
+
Nothing in this module writes outside the state directory, and nothing in it
|
|
6
|
+
writes to /boot. ``pin`` refuses a state directory that resolves under /boot.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import errno
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import shutil
|
|
15
|
+
import subprocess
|
|
16
|
+
import tempfile
|
|
17
|
+
import time
|
|
18
|
+
|
|
19
|
+
from ... import __version__
|
|
20
|
+
|
|
21
|
+
DEFAULT_CONFIG = "/boot/grub/grub.cfg"
|
|
22
|
+
DEFAULT_STATE_DIR = "/var/lib/minaki"
|
|
23
|
+
LAST_NAME = "grub.cfg.last"
|
|
24
|
+
META_NAME = "grub.cfg.last.json"
|
|
25
|
+
DEFAULT_MIN_SIZE = 1 # non-empty; --min-size raises the floor
|
|
26
|
+
MAX_READ = 64 * 1024 * 1024
|
|
27
|
+
SCRIPT_CHECK_TIMEOUT = 60
|
|
28
|
+
|
|
29
|
+
EXIT_OK = 0
|
|
30
|
+
EXIT_FAILED = 1
|
|
31
|
+
EXIT_ERROR = 2
|
|
32
|
+
|
|
33
|
+
# status of one check
|
|
34
|
+
PASS, FAIL, SKIP, ERROR = "pass", "fail", "skip", "error"
|
|
35
|
+
# overall status
|
|
36
|
+
OK, FAILED, TOOL_ERROR, NOT_APPLICABLE = "ok", "failed", "error", "not_applicable"
|
|
37
|
+
|
|
38
|
+
_MENUENTRY = re.compile(r"^[ \t]*menuentry[ \t]", re.MULTILINE)
|
|
39
|
+
_BEGIN = re.compile(r"^### BEGIN (\S+) ###[ \t]*$")
|
|
40
|
+
_END = re.compile(r"^### END (\S+) ###[ \t]*$")
|
|
41
|
+
_GENERATED = "It is automatically generated by grub-mkconfig"
|
|
42
|
+
_WRITERS = ("grub-mkconfig", "grub2-mkconfig", "update-grub", "update-grub2")
|
|
43
|
+
_SCRIPT_CHECK_NAMES = ("grub-script-check", "grub2-script-check")
|
|
44
|
+
_STD_DIRS = ("/usr/bin", "/usr/sbin", "/bin", "/sbin", "/usr/local/bin", "/usr/local/sbin")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _join(root, path):
|
|
48
|
+
"""Place an absolute path under root (root '/' leaves it as is)."""
|
|
49
|
+
if not root or root == "/":
|
|
50
|
+
return path
|
|
51
|
+
return os.path.join(root, path.lstrip("/"))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _utc(ts):
|
|
55
|
+
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(ts))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def check_entry(name, status, detail, **extra):
|
|
59
|
+
entry = {"name": name, "status": status, "detail": detail}
|
|
60
|
+
entry.update(extra)
|
|
61
|
+
return entry
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def find_script_check(root="/", override=None):
|
|
65
|
+
"""Return the path of grub-script-check, or None."""
|
|
66
|
+
if override:
|
|
67
|
+
return override if os.access(override, os.X_OK) else None
|
|
68
|
+
for name in _SCRIPT_CHECK_NAMES:
|
|
69
|
+
if root in ("", "/"):
|
|
70
|
+
found = shutil.which(name)
|
|
71
|
+
if found:
|
|
72
|
+
return found
|
|
73
|
+
for d in _STD_DIRS:
|
|
74
|
+
cand = _join(root, os.path.join(d, name))
|
|
75
|
+
if os.path.isfile(cand) and os.access(cand, os.X_OK):
|
|
76
|
+
return cand
|
|
77
|
+
return None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def detect_systemd_boot(root="/"):
|
|
81
|
+
"""Return the path that shows systemd-boot is installed, or None.
|
|
82
|
+
|
|
83
|
+
Looks only at files on the usual ESP mount points. Never runs bootctl.
|
|
84
|
+
"""
|
|
85
|
+
for esp in ("/boot/efi", "/efi", "/boot"):
|
|
86
|
+
base = _join(root, esp)
|
|
87
|
+
for rel in ("EFI/systemd/systemd-bootx64.efi", "EFI/systemd/systemd-bootaa64.efi",
|
|
88
|
+
"loader/loader.conf"):
|
|
89
|
+
cand = os.path.join(base, rel)
|
|
90
|
+
if os.path.isfile(cand):
|
|
91
|
+
return cand
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def grub_installed(root="/"):
|
|
96
|
+
"""True if this system looks like it boots with GRUB (files only)."""
|
|
97
|
+
if os.path.isdir(_join(root, "/boot/grub")):
|
|
98
|
+
return True
|
|
99
|
+
for d in ("/usr/sbin", "/sbin", "/usr/bin"):
|
|
100
|
+
for name in ("grub-mkconfig", "update-grub", "grub-install"):
|
|
101
|
+
if os.path.isfile(_join(root, os.path.join(d, name))):
|
|
102
|
+
return True
|
|
103
|
+
return False
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def running_writers(root="/"):
|
|
107
|
+
"""List GRUB config writers running now: [{'pid': int, 'cmd': str}]. Reads /proc only."""
|
|
108
|
+
proc = _join(root, "/proc")
|
|
109
|
+
found = []
|
|
110
|
+
try:
|
|
111
|
+
pids = [p for p in os.listdir(proc) if p.isdigit()]
|
|
112
|
+
except OSError:
|
|
113
|
+
return found
|
|
114
|
+
me = str(os.getpid())
|
|
115
|
+
for pid in pids:
|
|
116
|
+
if pid == me:
|
|
117
|
+
continue
|
|
118
|
+
try:
|
|
119
|
+
with open(os.path.join(proc, pid, "cmdline"), "rb") as f:
|
|
120
|
+
raw = f.read(4096)
|
|
121
|
+
except OSError:
|
|
122
|
+
continue
|
|
123
|
+
argv = [a.decode("utf-8", "replace") for a in raw.split(b"\0") if a]
|
|
124
|
+
# argv[0] is the program, or a shell running the script (sh /usr/sbin/grub-mkconfig).
|
|
125
|
+
for arg in argv[:2]:
|
|
126
|
+
if os.path.basename(arg) in _WRITERS:
|
|
127
|
+
found.append({"pid": int(pid), "cmd": " ".join(argv)[:200]})
|
|
128
|
+
break
|
|
129
|
+
found.sort(key=lambda w: w["pid"])
|
|
130
|
+
return found
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def check_sections(text):
|
|
134
|
+
"""Check generated '### BEGIN x ###' / '### END x ###' markers pair up in order."""
|
|
135
|
+
opened = None
|
|
136
|
+
count = 0
|
|
137
|
+
for lineno, line in enumerate(text.splitlines(), 1):
|
|
138
|
+
b = _BEGIN.match(line)
|
|
139
|
+
if b:
|
|
140
|
+
if opened:
|
|
141
|
+
return check_entry("sections", FAIL, "section %s (line %d) is not closed before %s starts "
|
|
142
|
+
"at line %d" % (opened[0], opened[1], b.group(1), lineno))
|
|
143
|
+
opened = (b.group(1), lineno)
|
|
144
|
+
continue
|
|
145
|
+
e = _END.match(line)
|
|
146
|
+
if e:
|
|
147
|
+
if not opened or opened[0] != e.group(1):
|
|
148
|
+
return check_entry("sections", FAIL, "END marker for %s at line %d has no matching BEGIN"
|
|
149
|
+
% (e.group(1), lineno))
|
|
150
|
+
opened = None
|
|
151
|
+
count += 1
|
|
152
|
+
if opened:
|
|
153
|
+
return check_entry("sections", FAIL, "section %s (line %d) never closes: the file is cut short"
|
|
154
|
+
% opened)
|
|
155
|
+
if count == 0:
|
|
156
|
+
if _GENERATED in text:
|
|
157
|
+
return check_entry("sections", FAIL, "grub-mkconfig header but no sections: the file is cut short")
|
|
158
|
+
return check_entry("sections", SKIP, "no grub-mkconfig section markers (not a generated file)")
|
|
159
|
+
return check_entry("sections", PASS, "%d generated sections, all closed" % count, sections=count)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def run_script_check(exe, data):
|
|
163
|
+
"""Run grub-script-check on the snapshot bytes via stdin."""
|
|
164
|
+
if not exe:
|
|
165
|
+
return check_entry("grub-script-check", ERROR,
|
|
166
|
+
"grub-script-check not found (Debian/Ubuntu package grub-common)")
|
|
167
|
+
try:
|
|
168
|
+
p = subprocess.run([exe], input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
169
|
+
timeout=SCRIPT_CHECK_TIMEOUT)
|
|
170
|
+
except subprocess.TimeoutExpired:
|
|
171
|
+
return check_entry("grub-script-check", ERROR, "%s timed out after %ds" % (exe, SCRIPT_CHECK_TIMEOUT))
|
|
172
|
+
except OSError as e:
|
|
173
|
+
return check_entry("grub-script-check", ERROR, "could not run %s: %s" % (exe, e.strerror or e))
|
|
174
|
+
out = (p.stderr + p.stdout).decode("utf-8", "replace").strip()
|
|
175
|
+
lines = [l.strip() for l in out.splitlines() if l.strip()]
|
|
176
|
+
if p.returncode == 0:
|
|
177
|
+
return check_entry("grub-script-check", PASS, "%s exit 0" % exe, tool=exe, exit_code=0)
|
|
178
|
+
# The last line is the useful one ("Syntax error at line 12", "contains no commands").
|
|
179
|
+
why = lines[-1] if lines else "no output"
|
|
180
|
+
return check_entry("grub-script-check", FAIL, "exit %d: %s" % (p.returncode, why),
|
|
181
|
+
tool=exe, exit_code=p.returncode, output=lines[-8:])
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def read_snapshot(path):
|
|
185
|
+
"""Read the file once. Returns (data, stat, error_entry)."""
|
|
186
|
+
try:
|
|
187
|
+
with open(path, "rb") as f:
|
|
188
|
+
st = os.fstat(f.fileno())
|
|
189
|
+
data = f.read(MAX_READ + 1)
|
|
190
|
+
except OSError as e:
|
|
191
|
+
return None, None, e
|
|
192
|
+
return data, st, None
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def last_good(state_dir):
|
|
196
|
+
"""Describe the pinned copy, or None if there is none (or it cannot be seen)."""
|
|
197
|
+
path = os.path.join(state_dir, LAST_NAME)
|
|
198
|
+
if not os.path.isfile(path):
|
|
199
|
+
return None
|
|
200
|
+
info = {"path": path}
|
|
201
|
+
try:
|
|
202
|
+
info["size"] = os.path.getsize(path)
|
|
203
|
+
with open(os.path.join(state_dir, META_NAME)) as f:
|
|
204
|
+
meta = json.load(f)
|
|
205
|
+
for k in ("sha256", "pinned_at", "source", "tool_version"):
|
|
206
|
+
if k in meta:
|
|
207
|
+
info[k] = meta[k]
|
|
208
|
+
except (OSError, ValueError):
|
|
209
|
+
pass
|
|
210
|
+
return info
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def check(config=None, min_size=DEFAULT_MIN_SIZE, root="/", state_dir=None, script_check=None,
|
|
214
|
+
_keep_data=False):
|
|
215
|
+
"""Run every check. Returns a result dict (see README for the JSON shape)."""
|
|
216
|
+
config = config or _join(root, DEFAULT_CONFIG)
|
|
217
|
+
state_dir = state_dir or _join(root, DEFAULT_STATE_DIR)
|
|
218
|
+
result = {
|
|
219
|
+
"tool": "minaki",
|
|
220
|
+
"plugin": "grub",
|
|
221
|
+
"version": __version__,
|
|
222
|
+
"command": "check",
|
|
223
|
+
"config": {"path": config},
|
|
224
|
+
"checks": [],
|
|
225
|
+
"warnings": [],
|
|
226
|
+
}
|
|
227
|
+
checks = result["checks"]
|
|
228
|
+
add = checks.append
|
|
229
|
+
|
|
230
|
+
# Signs that a writer is busy right now. Reported, never acted on.
|
|
231
|
+
writers = running_writers(root)
|
|
232
|
+
if writers:
|
|
233
|
+
result["warnings"].append(
|
|
234
|
+
"%d GRUB config writer(s) running now (%s): results may reflect a file mid-write"
|
|
235
|
+
% (len(writers), ", ".join("pid %d" % w["pid"] for w in writers)))
|
|
236
|
+
if len(writers) > 1:
|
|
237
|
+
result["warnings"].append("two or more writers at once: this is the race that can "
|
|
238
|
+
"leave grub.cfg empty or cut short")
|
|
239
|
+
result["writers"] = writers
|
|
240
|
+
if os.path.exists(config + ".new"):
|
|
241
|
+
result["warnings"].append("%s.new exists: grub-mkconfig is running now or an earlier run "
|
|
242
|
+
"was interrupted" % config)
|
|
243
|
+
|
|
244
|
+
data, st, err = read_snapshot(config)
|
|
245
|
+
if err is not None and err.errno == errno.ENOENT:
|
|
246
|
+
sdboot = detect_systemd_boot(root)
|
|
247
|
+
if sdboot or not grub_installed(root):
|
|
248
|
+
why = ("systemd-boot found at %s" % sdboot) if sdboot else "no GRUB installation found"
|
|
249
|
+
add(check_entry("exists", SKIP, "%s not present; %s" % (config, why)))
|
|
250
|
+
result["status"] = NOT_APPLICABLE
|
|
251
|
+
result["detail"] = "not applicable: %s, so there is no GRUB config to check" % why
|
|
252
|
+
return _finish(result, state_dir)
|
|
253
|
+
add(check_entry("exists", FAIL, "%s is missing, but GRUB is installed" % config))
|
|
254
|
+
return _finish(result, state_dir)
|
|
255
|
+
if err is not None:
|
|
256
|
+
status = ERROR
|
|
257
|
+
detail = "cannot read %s: %s" % (config, err.strerror or err)
|
|
258
|
+
if err.errno in (errno.EACCES, errno.EPERM):
|
|
259
|
+
detail += " (run as root)"
|
|
260
|
+
elif err.errno == errno.EISDIR:
|
|
261
|
+
status = FAIL
|
|
262
|
+
add(check_entry("exists", status, detail))
|
|
263
|
+
return _finish(result, state_dir)
|
|
264
|
+
|
|
265
|
+
size = len(data)
|
|
266
|
+
digest = hashlib.sha256(data).hexdigest()
|
|
267
|
+
result["config"].update(size=size, sha256=digest, mtime=_utc(st.st_mtime))
|
|
268
|
+
if size > MAX_READ:
|
|
269
|
+
add(check_entry("exists", FAIL, "%s is larger than %d bytes; not a GRUB config" % (config, MAX_READ)))
|
|
270
|
+
return _finish(result, state_dir)
|
|
271
|
+
add(check_entry("exists", PASS, "%d bytes, modified %s" % (size, _utc(st.st_mtime))))
|
|
272
|
+
|
|
273
|
+
if size == 0:
|
|
274
|
+
add(check_entry("size", FAIL, "the file is empty"))
|
|
275
|
+
elif size < min_size:
|
|
276
|
+
add(check_entry("size", FAIL, "%d bytes, below the minimum of %d" % (size, min_size)))
|
|
277
|
+
else:
|
|
278
|
+
add(check_entry("size", PASS, "%d bytes, not empty" % size if min_size <= 1
|
|
279
|
+
else "%d >= %d bytes" % (size, min_size)))
|
|
280
|
+
|
|
281
|
+
nul = data.find(b"\0")
|
|
282
|
+
if nul < 0:
|
|
283
|
+
add(check_entry("no-nul-bytes", PASS, "no NUL bytes"))
|
|
284
|
+
else:
|
|
285
|
+
add(check_entry("no-nul-bytes", FAIL, "NUL byte at offset %d (zero-filled after a crash?)" % nul))
|
|
286
|
+
|
|
287
|
+
text = data.decode("utf-8", "replace")
|
|
288
|
+
n = len(_MENUENTRY.findall(text))
|
|
289
|
+
if n:
|
|
290
|
+
add(check_entry("menuentry", PASS, "%d menuentry line%s" % (n, "" if n == 1 else "s"), count=n))
|
|
291
|
+
else:
|
|
292
|
+
add(check_entry("menuentry", FAIL, "no menuentry: GRUB would have nothing to boot", count=0))
|
|
293
|
+
|
|
294
|
+
add(check_sections(text))
|
|
295
|
+
add(run_script_check(find_script_check(root, script_check), data))
|
|
296
|
+
|
|
297
|
+
if _keep_data:
|
|
298
|
+
result["_data"] = data
|
|
299
|
+
return _finish(result, state_dir)
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _finish(result, state_dir):
|
|
303
|
+
statuses = [c["status"] for c in result["checks"]]
|
|
304
|
+
if result.get("status") == NOT_APPLICABLE:
|
|
305
|
+
code = EXIT_ERROR
|
|
306
|
+
elif FAIL in statuses:
|
|
307
|
+
result["status"] = FAILED
|
|
308
|
+
code = EXIT_FAILED
|
|
309
|
+
elif ERROR in statuses:
|
|
310
|
+
result["status"] = TOOL_ERROR
|
|
311
|
+
code = EXIT_ERROR
|
|
312
|
+
else:
|
|
313
|
+
result["status"] = OK
|
|
314
|
+
code = EXIT_OK
|
|
315
|
+
result["failed"] = [c["name"] for c in result["checks"] if c["status"] == FAIL]
|
|
316
|
+
result["errors"] = [c["name"] for c in result["checks"] if c["status"] == ERROR]
|
|
317
|
+
result["exit_code"] = code
|
|
318
|
+
lg = last_good(state_dir)
|
|
319
|
+
if lg and result["config"].get("sha256"):
|
|
320
|
+
lg["matches_current"] = lg.get("sha256") == result["config"]["sha256"]
|
|
321
|
+
result["last_good"] = lg
|
|
322
|
+
return result
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _under(path, parent):
|
|
326
|
+
path, parent = os.path.realpath(path), os.path.realpath(parent)
|
|
327
|
+
return path == parent or path.startswith(parent.rstrip("/") + "/")
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _write_atomic(dirpath, name, data):
|
|
331
|
+
fd, tmp = tempfile.mkstemp(prefix="." + name + ".", dir=dirpath)
|
|
332
|
+
try:
|
|
333
|
+
os.fchmod(fd, 0o600)
|
|
334
|
+
with os.fdopen(fd, "wb") as f:
|
|
335
|
+
f.write(data)
|
|
336
|
+
f.flush()
|
|
337
|
+
os.fsync(f.fileno())
|
|
338
|
+
os.replace(tmp, os.path.join(dirpath, name))
|
|
339
|
+
except BaseException:
|
|
340
|
+
try:
|
|
341
|
+
os.unlink(tmp)
|
|
342
|
+
except OSError:
|
|
343
|
+
pass
|
|
344
|
+
raise
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def pin(config=None, min_size=DEFAULT_MIN_SIZE, root="/", state_dir=None, script_check=None):
|
|
348
|
+
"""Copy the config to the state dir, only if every check passes.
|
|
349
|
+
|
|
350
|
+
The bytes written are the exact bytes that were checked (one read), so a writer
|
|
351
|
+
changing the file in between cannot slip an unchecked copy in.
|
|
352
|
+
"""
|
|
353
|
+
state_dir = state_dir or _join(root, DEFAULT_STATE_DIR)
|
|
354
|
+
result = check(config, min_size, root, state_dir, script_check, _keep_data=True)
|
|
355
|
+
result["command"] = "pin"
|
|
356
|
+
data = result.pop("_data", None)
|
|
357
|
+
result["pinned"] = False
|
|
358
|
+
if result["exit_code"] != EXIT_OK:
|
|
359
|
+
result["pin_detail"] = "not pinned: check did not pass"
|
|
360
|
+
return result
|
|
361
|
+
|
|
362
|
+
def tool_error(msg):
|
|
363
|
+
result.update(status=TOOL_ERROR, exit_code=EXIT_ERROR, pin_detail=msg)
|
|
364
|
+
return result
|
|
365
|
+
|
|
366
|
+
for boot in ("/boot", _join(root, "/boot")):
|
|
367
|
+
if _under(state_dir, boot):
|
|
368
|
+
return tool_error("refusing state directory %s: it is under %s, which this tool never writes"
|
|
369
|
+
% (state_dir, boot))
|
|
370
|
+
lg = result.get("last_good")
|
|
371
|
+
if lg and lg.get("sha256") == result["config"]["sha256"] and lg.get("size") == len(data):
|
|
372
|
+
result["pin_detail"] = "unchanged: last-good copy already matches"
|
|
373
|
+
result["unchanged"] = True
|
|
374
|
+
return result
|
|
375
|
+
try:
|
|
376
|
+
if os.path.islink(state_dir):
|
|
377
|
+
return tool_error("refusing state directory %s: it is a symlink" % state_dir)
|
|
378
|
+
os.makedirs(state_dir, mode=0o700, exist_ok=True)
|
|
379
|
+
st = os.lstat(state_dir)
|
|
380
|
+
if st.st_uid != os.geteuid():
|
|
381
|
+
return tool_error("refusing state directory %s: owned by uid %d, not us" % (state_dir, st.st_uid))
|
|
382
|
+
os.chmod(state_dir, 0o700) # the copy can hold GRUB password hashes
|
|
383
|
+
_write_atomic(state_dir, LAST_NAME, data)
|
|
384
|
+
meta = {
|
|
385
|
+
"sha256": result["config"]["sha256"],
|
|
386
|
+
"size": len(data),
|
|
387
|
+
"source": result["config"]["path"],
|
|
388
|
+
"source_mtime": result["config"].get("mtime"),
|
|
389
|
+
"pinned_at": _utc(time.time()),
|
|
390
|
+
"tool_version": __version__,
|
|
391
|
+
}
|
|
392
|
+
_write_atomic(state_dir, META_NAME, (json.dumps(meta, indent=2) + "\n").encode())
|
|
393
|
+
dfd = os.open(state_dir, os.O_RDONLY)
|
|
394
|
+
try:
|
|
395
|
+
os.fsync(dfd)
|
|
396
|
+
finally:
|
|
397
|
+
os.close(dfd)
|
|
398
|
+
except OSError as e:
|
|
399
|
+
msg = "could not write %s: %s" % (state_dir, e.strerror or e)
|
|
400
|
+
if e.errno in (errno.EACCES, errno.EPERM, errno.EROFS):
|
|
401
|
+
msg += " (pin needs root)" if e.errno != errno.EROFS else ""
|
|
402
|
+
return tool_error(msg)
|
|
403
|
+
result["pinned"] = True
|
|
404
|
+
result["pin_detail"] = "pinned to %s" % os.path.join(state_dir, LAST_NAME)
|
|
405
|
+
result["last_good"] = last_good(state_dir)
|
|
406
|
+
result["last_good"]["matches_current"] = True
|
|
407
|
+
return result
|