Merge pull request #255 from CrossDarwin/build/macos-account-identity

feat(macos): separate administrator names and private credential input
This commit is contained in:
RinnRei
2026-11-15 00:22:33 +09:00
committed by GitHub
Unverified
4 changed files with 123 additions and 10 deletions
+3 -1
View File
@@ -172,7 +172,9 @@ Seed creation options:
| --- | --- |
| `--skip-setup` | Marks Setup Assistant done |
| `--user NAME:PASSWORD` | Adds a local administrator and its home |
| `--auto-login` | Logs the `--user` account in at boot. For unattended tests; requires `--user` |
| `--real-name NAME` | Sets the displayed administrator name; the short account name and `/Users/NAME` remain unchanged |
| `--user-stdin` | Reads `{"name":"unixnu","password":"..."}` from standard input instead of `--user` |
| `--auto-login` | Logs the account in at boot. For unattended tests; requires `--user` or `--user-stdin` |
| `--keyboard-type PRODUCT-VENDOR-COUNTRY=TYPE` | Records a keyboard layout type, so Keyboard Setup Assistant does not ask |
| `--volume-uuid UUID` | Gives the Data volume a fixed UUID, so a new seed replaces an older one without a kernel build |
+3 -1
View File
@@ -161,7 +161,9 @@ sudo python3 scripts/make-macos-data-seed.py \
| --- | --- |
| `--skip-setup` | 把设置助理标记为已完成 |
| `--user NAME:PASSWORD` | 添加本地管理员及其主目录 |
| `--auto-login` | 开机自动登录 `--user` 指定的账户。供无人值守测试使用,需要 `--user` |
| `--real-name NAME` | 设置管理员的显示名称,短用户名与 `/Users/NAME` 路径保持不变 |
| `--user-stdin` | 从标准输入读取 `{"name":"unixnu","password":"..."}`,代替 `--user` |
| `--auto-login` | 开机自动登录指定账户。供无人值守测试使用,需要 `--user` 或 `--user-stdin` |
| `--keyboard-type PRODUCT-VENDOR-COUNTRY=TYPE` | 记录键盘布局类型,键盘设置助理不再询问 |
| `--volume-uuid UUID` | 为 Data 卷指定固定 UUID,新 seed 可以替换旧 seed 而无需重新构建内核 |
+42 -8
View File
@@ -18,13 +18,15 @@ blocks of the replaced files. --volume-uuid gives the Data volume the UUID the k
(CONFIG_XNU_OWNER_DATA_VOLUME_UUID), so a new seed can replace an older one without a kernel build.
sudo python3 scripts/make-macos-data-seed.py OS OUTPUT --gib N [--skip-setup] [--user NAME:PASSWORD [--auto-login]]
[--volume-uuid UUID]
[--real-name DISPLAY_NAME] [--volume-uuid UUID]
--skip-setup marks Setup Assistant done (/private/var/db/.AppleSetupDone: loginwindow shows its login window instead of Language
Chooser and Setup Assistant, which would also ask to activate the Mac) and writes a managed SkipSetupItems, so a new user's first
login skips Setup Assistant's per-user panes. --user adds a local administrator (uid 501, staff and admin, SALTED-SHA512-PBKDF2
shadow hash) to the directory (/private/var/db/dslocal), as macOS-DroidVM's stage-gpu-plugin.py does; loginwindow creates its home
on the first login. With --user the seed also holds that user's home, made from the user template, with .skipbuddy in it: a home that
on the first login. --real-name sets its display name without changing its short name or home. --user-stdin reads a JSON object
with name and password fields instead of --user, so a calling tool need not place credentials in its process arguments. With --user
the seed also holds that user's home, made from the user template, with .skipbuddy in it: a home that
loginwindow makes on the first login gets Setup Assistant's MiniBuddy (MiniLauncherPlugin sets MiniBuddyLaunch), which with every
pane skipped never finishes, so loginwindow never starts the Dock and Finder (macOS-DroidVM makes the home with a boot job for the
same reason; macOS run42: black screen behind the first MiniBuddy pane). --keyboard-type PRODUCT-VENDOR-COUNTRY=TYPE (decimal, may
@@ -39,6 +41,7 @@ import json
import os
from pathlib import Path
import plistlib
import re
import stat
import struct
import subprocess
@@ -73,15 +76,20 @@ def main():
parser.add_argument('--gib', type=int, required=True)
parser.add_argument('--skip-setup', action='store_true',
help='mark Setup Assistant done (/private/var/db/.AppleSetupDone)')
parser.add_argument('--user', help='NAME:PASSWORD of a local administrator to add')
account = parser.add_mutually_exclusive_group()
account.add_argument('--user', help='NAME:PASSWORD of a local administrator to add')
account.add_argument('--user-stdin', action='store_true',
help='read a JSON object with name and password from standard input')
parser.add_argument('--real-name', help='display name of the administrator (default: account name)')
parser.add_argument('--keyboard-type', action='append', default=[], metavar='PRODUCT-VENDOR-COUNTRY=TYPE',
help='a keyboard whose layout type is known (40 = ANSI); may repeat')
parser.add_argument('--auto-login', action='store_true',
help='log the --user in at boot (unattended test seeds only)')
help='log the selected account in at boot (unattended test seeds only)')
parser.add_argument('--volume-uuid', type=uuid.UUID, help='the Data volume UUID (default: a new one)')
args = parser.parse_args()
read_account(parser, args)
if args.auto_login and not args.user:
parser.error('--auto-login needs --user')
parser.error('--auto-login needs --user or --user-stdin')
if os.geteuid() != 0:
parser.error('run as root: the Data template keeps its owners')
if args.os.is_file():
@@ -91,6 +99,32 @@ def main():
build(parser, args, args.os)
def read_account(parser, args):
"""Keep the short account name separate from its display name and home path."""
if args.user_stdin:
try:
record = json.load(sys.stdin)
name, password = record['name'], record['password']
if not isinstance(name, str) or not isinstance(password, str):
raise ValueError('name and password must be strings')
if ':' in name:
raise ValueError('the account name cannot contain a colon')
args.user = name + ':' + password
except (ValueError, KeyError, TypeError):
parser.error('--user-stdin needs a JSON object with string name and password fields')
if args.real_name is not None and not args.user:
parser.error('--real-name needs --user or --user-stdin')
if not args.user:
return
name, separator, password = args.user.partition(':')
if not separator or not password or '\0' in password:
parser.error('the account needs a nonempty password without NUL characters')
if not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_.-]{0,31}', name) or name.lower() in ('root', 'daemon', 'nobody'):
parser.error('invalid short account name')
if args.real_name is not None and (not args.real_name.strip() or any(ord(c) < 32 for c in args.real_name)):
parser.error('the display name must be nonempty and contain no control characters')
@contextlib.contextmanager
def os_mount(image):
# As build-boot-runtime.py: reuse an existing read-only attachment of this image and leave it attached.
@@ -182,7 +216,7 @@ def write_root(path, data, mode):
path.chmod(mode)
def add_user(dslocal, name, password, uid=501):
def add_user(dslocal, name, password, uid=501, real_name=None):
"""A local administrator as System Settings writes one: the user record and its admin and staff memberships."""
salt, iterations = os.urandom(32), 50000
entropy = hashlib.pbkdf2_hmac('sha512', password.encode(), salt, iterations, 128)
@@ -190,7 +224,7 @@ def add_user(dslocal, name, password, uid=501):
fmt=plistlib.FMT_BINARY)
guid = str(uuid.uuid4()).upper()
write_root(dslocal / 'users' / (name + '.plist'), plistlib.dumps({
'name': [name], 'realname': [name], 'uid': [str(uid)], 'gid': ['20'], 'home': ['/Users/' + name], 'shell': ['/bin/zsh'],
'name': [name], 'realname': [real_name or name], 'uid': [str(uid)], 'gid': ['20'], 'home': ['/Users/' + name], 'shell': ['/bin/zsh'],
'generateduid': [guid], 'passwd': ['********'], 'authentication_authority': [';ShadowHash;HASHLIST:<SALTED-SHA512-PBKDF2>'],
'ShadowHashData': [shadow], '_writers_passwd': [name], '_writers_realname': [name], '_writers_hint': [name]},
fmt=plistlib.FMT_BINARY), 0o600)
@@ -340,7 +374,7 @@ def build(parser, args, os_mount):
os.chown(done, 0, 0)
done.chmod(0o644)
if args.user:
add_user(scratch / DSLOCAL, *args.user.split(':', 1))
add_user(scratch / DSLOCAL, *args.user.split(':', 1), real_name=args.real_name)
link_template_directories(scratch)
kept, linked = link_template_files(scratch)
if args.skip_setup: # after the links: Library/Managed Preferences is not kept as real files otherwise
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env python3
"""Check administrator identity and credential input without attaching images."""
import argparse
import contextlib
import importlib.util
import io
import json
from pathlib import Path
import plistlib
import sys
import tempfile
import types
import unittest
from unittest.mock import patch
SOURCE = Path(__file__).resolve().parents[2] / 'scripts/make-macos-data-seed.py'
SPEC = importlib.util.spec_from_file_location('data_seed', SOURCE)
SEED = importlib.util.module_from_spec(SPEC)
# Image packing is outside this host fixture; the account functions are unchanged.
with patch.dict(sys.modules, {'packed_ramdisk': types.ModuleType('packed_ramdisk')}):
SPEC.loader.exec_module(SEED)
class AccountTest(unittest.TestCase):
def options(self, user=None, stdin=False, real_name=None):
return argparse.Namespace(user=user, user_stdin=stdin, real_name=real_name)
def test_private_input_and_colon_password(self):
args = self.options(stdin=True, real_name='UniXNU')
with patch.object(sys, 'stdin', io.StringIO(json.dumps({'name': 'unixnu', 'password': 'a:b c'}))):
SEED.read_account(argparse.ArgumentParser(), args)
self.assertEqual(args.user, 'unixnu:a:b c')
def test_invalid_accounts_and_redacted_errors(self):
for user in ('../escape:secret', 'root:secret', 'unixnu:', 'unixnu', 'unixnu:a\0b'):
with self.subTest(user=user), contextlib.redirect_stderr(io.StringIO()) as errors:
with self.assertRaises(SystemExit):
SEED.read_account(argparse.ArgumentParser(), self.options(user=user))
self.assertNotIn('secret', errors.getvalue())
def test_invalid_json(self):
for data in ('{}', '[]', 'null', '{"name":2,"password":"secret"}',
'{"name":"bad:name","password":"secret"}', 'not json'):
with self.subTest(data=data), patch.object(sys, 'stdin', io.StringIO(data)):
with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
SEED.read_account(argparse.ArgumentParser(), self.options(stdin=True))
def test_display_name_requires_account(self):
with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
SEED.read_account(argparse.ArgumentParser(), self.options(real_name='UniXNU'))
def test_record_display_name_and_auto_login_use_separate_fields(self):
with tempfile.TemporaryDirectory() as directory, patch.object(SEED.os, 'chown'):
root = Path(directory)
node = root / SEED.DSLOCAL
(node / 'groups').mkdir(parents=True)
for group in ('admin', 'staff'):
(node / 'groups' / (group + '.plist')).write_bytes(plistlib.dumps({'users': ['existing']}))
SEED.add_user(node, 'unixnu', 'test-only-password', real_name='UniXNU')
SEED.add_auto_login(root, 'unixnu', 'test-only-password')
user = plistlib.loads((node / 'users/unixnu.plist').read_bytes())
self.assertEqual(user['name'], ['unixnu'])
self.assertEqual(user['realname'], ['UniXNU'])
self.assertEqual(user['home'], ['/Users/unixnu'])
login = plistlib.loads((root / SEED.LOGINWINDOW_PREFS).read_bytes())
self.assertEqual(login['autoLoginUser'], 'unixnu')
self.assertNotIn(b'test-only-password', (node / 'users/unixnu.plist').read_bytes())
for group in ('admin', 'staff'):
record = plistlib.loads((node / 'groups' / (group + '.plist')).read_bytes())
self.assertEqual(record['users'], ['existing', 'unixnu'])
self.assertEqual((root / SEED.KCPASSWORD).stat().st_mode & 0o777, 0o600)
if __name__ == '__main__':
unittest.main()