| 1 | |
| 2 | |
| 3 | #import <Foundation/Foundation.h> |
| 4 | #import <OpenDirectory/OpenDirectory.h> |
| 5 | #include <pwd.h> |
| 6 | #include <sys/file.h> |
| 7 | #include <sys/stat.h> |
| 8 | #include <sys/sysctl.h> |
| 9 | #include <unistd.h> |
| 10 | |
| 11 | static NSString *const directory = @"/var/db/cage-initial-setup"; |
| 12 | static NSString *const setup = @"cagesetup"; |
| 13 | |
| 14 | static void require(BOOL ok, const char *reason) { |
| 15 | if (!ok) { fprintf(stderr, "%s\n", reason); exit(1); } |
| 16 | } |
| 17 | |
| 18 | static NSArray *users(ODNode *node, NSString *name) { |
| 19 | ODQuery *q = [ODQuery queryWithNode:node forRecordTypes:kODRecordTypeUsers |
| 20 | attribute:kODAttributeTypeRecordName matchType:kODMatchEqualTo queryValues:name |
| 21 | returnAttributes:@[kODAttributeTypeGUID, kODAttributeTypeUniqueID] maximumResults:2 error:NULL]; |
| 22 | NSArray *results = [q resultsAllowingPartial:NO error:NULL]; |
| 23 | require(results != nil && results.count <= 1, "Cannot identify the local guest user."); |
| 24 | return results; |
| 25 | } |
| 26 | |
| 27 | static void save(NSDictionary *d, NSURL *file) { |
| 28 | NSData *data = [NSJSONSerialization dataWithJSONObject:d options:0 error:NULL]; |
| 29 | require(data && [data writeToURL:file options:NSDataWritingAtomic error:NULL], "Cannot persist the guest setup receipt."); |
| 30 | } |
| 31 | |
| 32 | static BOOL member(ODRecord *group, ODRecord *user) { |
| 33 | NSError *err = nil; |
| 34 | BOOL result = [group isMemberRecord:user error:&err]; |
| 35 | require(!err, "Cannot inspect guest administrator privileges."); |
| 36 | return result; |
| 37 | } |
| 38 | |
| 39 | static void setMember(ODRecord *group, ODRecord *user, BOOL expected) { |
| 40 | if (member(group, user) == expected) return; |
| 41 | require(expected ? [group addMemberRecord:user error:NULL] : [group removeMemberRecord:user error:NULL], |
| 42 | expected ? "Cannot grant temporary setup privileges." : "Cannot revoke setup administrator privileges."); |
| 43 | require([group synchronizeAndReturnError:NULL], "Cannot synchronize guest administrator privileges."); |
| 44 | |
| 45 | |
| 46 | for (int attempt = 0; attempt < 50; attempt++) { |
| 47 | if (member(group, user) == expected) return; |
| 48 | usleep(100000); |
| 49 | } |
| 50 | require(NO, expected ? "Guest setup privileges were not applied." : "The setup user still has administrator privileges."); |
| 51 | } |
| 52 | |
| 53 | static BOOL disabled(ODRecord *record) { |
| 54 | NSError *error = nil; |
| 55 | BOOL allowed = [record authenticationAllowedAndReturnError:&error]; |
| 56 | return !allowed && [error.domain isEqual:ODFrameworkErrorDomain] && error.code == kODErrorCredentialsAccountDisabled; |
| 57 | } |
| 58 | |
| 59 | static NSString *readPassword(void) { |
| 60 | char buf[258] = {0}; |
| 61 | require(fgets(buf,sizeof(buf),stdin) != NULL, "Missing virtual Mac password."); |
| 62 | size_t len = strcspn(buf,"\r\n"); |
| 63 | require(len >= 8 && len <= 256 && buf[len] == '\n', "Invalid virtual Mac password."); |
| 64 | for (size_t i = 0; i < len; i++) require(buf[i] >= 32 && buf[i] <= 126, "Unsupported virtual Mac password character."); |
| 65 | NSString *pw = [[NSString alloc] initWithBytes:buf length:len encoding:NSUTF8StringEncoding]; |
| 66 | memset_s(buf,sizeof(buf),0,sizeof(buf)); |
| 67 | require(pw != nil, "Invalid password encoding."); |
| 68 | return pw; |
| 69 | } |
| 70 | |
| 71 | static void updatePassword(ODRecord *record, NSString *old, NSString *target) { |
| 72 | if ([record verifyPassword:target error:NULL]) return; |
| 73 | require([record verifyPassword:old error:NULL] && [record changePassword:old toPassword:target error:NULL] && |
| 74 | [record verifyPassword:target error:NULL], "Cannot synchronize the guest account password."); |
| 75 | } |
| 76 | |
| 77 | |
| 78 | |
| 79 | static NSString *securityToken(NSString *value) { |
| 80 | return [NSString stringWithFormat:@"\"%@\"", [[value stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"] |
| 81 | stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""]]; |
| 82 | } |
| 83 | |
| 84 | static void synchronize(ODRecord *ordinary, ODRecord *setupRecord, NSDictionary *receipt, NSString *name) { |
| 85 | NSString *old = readPassword(), *target = readPassword(); |
| 86 | NSString *home = [ordinary valuesForAttribute:kODAttributeTypeNFSHomeDirectory error:NULL].firstObject; |
| 87 | require([home isEqual:[@"/Users/" stringByAppendingString:name]], "Unexpected guest home directory."); |
| 88 | NSString *domain = @"/Library/Preferences/com.apple.loginwindow"; |
| 89 | NSDictionary *preferences = [NSDictionary dictionaryWithContentsOfFile:[domain stringByAppendingString:@".plist"]]; |
| 90 | require(!preferences[@"autoLoginUser"] || [preferences[@"autoLoginUser"] isEqual:name], "Automatic login belongs to another guest user."); |
| 91 | struct stat st; |
| 92 | require(lstat("/etc/kcpassword",&st) != 0 ? errno == ENOENT : S_ISREG(st.st_mode) && st.st_uid == 0, |
| 93 | "Invalid system automatic login file."); |
| 94 | |
| 95 | |
| 96 | NSString *keychainPath = [home stringByAppendingString:@"/Library/Keychains/login.keychain-db"]; |
| 97 | if (lstat(keychainPath.fileSystemRepresentation,&st) == 0) { |
| 98 | require(S_ISREG(st.st_mode), "Invalid guest login keychain."); |
| 99 | NSString *commands = [NSString stringWithFormat:@"set-keychain-password -o %@ -p %@ %@\nunlock-keychain -p %@ %@\n", |
| 100 | securityToken(old),securityToken(target),securityToken(keychainPath),securityToken(target),securityToken(keychainPath)]; |
| 101 | NSPipe *input = [NSPipe pipe]; |
| 102 | NSTask *security = [[NSTask alloc] init]; |
| 103 | security.executableURL = [NSURL fileURLWithPath:@"/usr/bin/security"]; |
| 104 | security.arguments = @[@"-i"]; |
| 105 | security.standardInput = input; |
| 106 | security.standardOutput = security.standardError = [NSFileHandle fileHandleWithNullDevice]; |
| 107 | require([security launchAndReturnError:NULL], "Cannot invoke the guest keychain tool."); |
| 108 | [input.fileHandleForWriting writeData:[commands dataUsingEncoding:NSUTF8StringEncoding]]; |
| 109 | [input.fileHandleForWriting closeFile]; |
| 110 | [security waitUntilExit]; |
| 111 | require(security.terminationStatus == 0, "Cannot synchronize the guest login keychain; existing data was retained."); |
| 112 | } else require(errno == ENOENT, "Cannot inspect the guest login keychain."); |
| 113 | updatePassword(ordinary,old,target); |
| 114 | if ([receipt[@"state"] isEqual:@"ready"]) { |
| 115 | require(setupRecord && !disabled(setupRecord), "The initial setup account is unavailable."); |
| 116 | updatePassword(setupRecord,old,target); |
| 117 | } |
| 118 | unsigned char key[] = {0x7d,0x89,0x52,0x23,0xd2,0xbc,0xdd,0xea,0xa3,0xb9,0x1f}; |
| 119 | NSMutableData *encoded = [[target dataUsingEncoding:NSUTF8StringEncoding] mutableCopy]; |
| 120 | [encoded increaseLengthBy:1]; |
| 121 | while (encoded.length % 12) [encoded increaseLengthBy:1]; |
| 122 | unsigned char *bytes = encoded.mutableBytes; |
| 123 | for (NSUInteger i=0; i<encoded.length; i++) bytes[i] ^= key[i % sizeof(key)]; |
| 124 | require([encoded writeToFile:@"/etc/kcpassword" options:NSDataWritingAtomic error:NULL] && chmod("/etc/kcpassword",0600) == 0, |
| 125 | "Cannot synchronize automatic login."); |
| 126 | |
| 127 | NSTask *task = [[NSTask alloc] init]; |
| 128 | task.executableURL = [NSURL fileURLWithPath:@"/usr/bin/defaults"]; |
| 129 | task.arguments = @[@"write", domain, @"autoLoginUser", @"-string", name]; |
| 130 | require([task launchAndReturnError:NULL], "Cannot configure automatic login."); |
| 131 | [task waitUntilExit]; require(task.terminationStatus == 0, "Cannot persist automatic login user."); |
| 132 | } |
| 133 | |
| 134 | static void retire(ODNode *node, ODRecord *admin, ODRecord *record) { |
| 135 | setMember(admin, record, NO); |
| 136 | if (!disabled(record)) { |
| 137 | |
| 138 | |
| 139 | NSString *replacement = [@"Z9!" stringByAppendingString:NSUUID.UUID.UUIDString]; |
| 140 | require([record changePassword:nil toPassword:replacement error:NULL], "Cannot clear the temporary guest credential."); |
| 141 | require([record setValue:@"/usr/bin/false" forAttribute:kODAttributeTypeUserShell error:NULL], "Cannot close the temporary login shell."); |
| 142 | NSTask *task = [[NSTask alloc] init]; |
| 143 | task.executableURL = [NSURL fileURLWithPath:@"/usr/bin/pwpolicy"]; |
| 144 | task.arguments = @[@"-n", @"/Local/Default", @"-u", setup, @"-disableuser"]; |
| 145 | require([task launchAndReturnError:NULL], "Cannot invoke the guest account policy tool."); |
| 146 | [task waitUntilExit]; |
| 147 | require(task.terminationStatus == 0, "Cannot disable the temporary guest user."); |
| 148 | } |
| 149 | ODRecord *current = users(node, setup).firstObject; |
| 150 | require(current && disabled(current) && !member(admin, current) && |
| 151 | [[current valuesForAttribute:kODAttributeTypeUserShell error:NULL].firstObject isEqual:@"/usr/bin/false"], |
| 152 | "The temporary guest login remains available."); |
| 153 | } |
| 154 | |
| 155 | int main(int argc, const char **argv) { |
| 156 | @autoreleasepool { |
| 157 | BOOL prepare = (argc == 3 || argc == 4) && strcmp(argv[1], "prepare") == 0; |
| 158 | BOOL password = argc == 4 && strcmp(argv[1], "password") == 0; |
| 159 | require(prepare || password || argc == 1, "Invalid first setup operation."); |
| 160 | char model[128] = {0}; |
| 161 | size_t size = sizeof(model); |
| 162 | struct stat st; |
| 163 | require(getuid() == 0 && sysctlbyname("hw.model", model, &size, NULL, 0) == 0 && |
| 164 | strncmp(model, "VirtualMac", 10) == 0 && lstat("/var/db/cage-guest-os", &st) == 0 && |
| 165 | S_ISREG(st.st_mode) && st.st_uid == 0 && !(st.st_mode & 022) && |
| 166 | [[NSString stringWithContentsOfFile:@"/var/db/cage-guest-os" encoding:NSUTF8StringEncoding error:NULL] isEqual:@"macos\n"], |
| 167 | "Run as root in the selected Cage virtual Mac."); |
| 168 | umask(077); |
| 169 | if (prepare && mkdir(directory.fileSystemRepresentation, 0700) != 0) require(errno == EEXIST, "Cannot create private receipt directory."); |
| 170 | require(lstat(directory.fileSystemRepresentation, &st) == 0 && S_ISDIR(st.st_mode) && st.st_uid == 0 && !(st.st_mode & 077), |
| 171 | "Invalid private setup directory."); |
| 172 | NSString *lockPath = [directory stringByAppendingPathComponent:@"lock"]; |
| 173 | int lock = open(lockPath.fileSystemRepresentation, O_NOFOLLOW|O_CREAT|O_RDWR, 0600); |
| 174 | require(lock >= 0 && flock(lock, LOCK_EX|LOCK_NB) == 0, "Another first setup operation is running."); |
| 175 | NSURL *file = [NSURL fileURLWithPath:[directory stringByAppendingPathComponent:@"account.json"]]; |
| 176 | NSData *data = nil; |
| 177 | if (lstat(file.fileSystemRepresentation, &st) == 0) { |
| 178 | require(S_ISREG(st.st_mode) && st.st_uid == 0 && !(st.st_mode & 077) && st.st_size > 0 && st.st_size <= 2048, |
| 179 | "Invalid guest setup receipt."); |
| 180 | data = [NSData dataWithContentsOfURL:file]; require(data != nil,"Unreadable guest setup receipt."); |
| 181 | } else require(errno == ENOENT && prepare, "Missing guest setup receipt."); |
| 182 | ODNode *node = [ODNode nodeWithSession:[ODSession defaultSession] name:@"/Local/Default" error:NULL]; |
| 183 | ODRecord *admin = [node recordWithRecordType:kODRecordTypeGroups name:@"admin" attributes:nil error:NULL]; |
| 184 | ODRecord *record = users(node, setup).firstObject; |
| 185 | NSString *install = prepare || password ? @(argv[2]) : nil; |
| 186 | if (install) require([[NSUUID alloc] initWithUUIDString:install] != nil, "Invalid fresh guest installation ID."); |
| 187 | NSMutableDictionary *receipt; |
| 188 | if (data) { |
| 189 | receipt = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:NULL]; |
| 190 | require([receipt isKindOfClass:NSMutableDictionary.class] && |
| 191 | [[NSUUID alloc] initWithUUIDString:receipt[@"guid"]] && [receipt[@"uid"] intValue] >= 502 && |
| 192 | [[NSUUID alloc] initWithUUIDString:receipt[@"installation"]] && (!install || [receipt[@"installation"] isEqual:install]), |
| 193 | "The setup account belongs to a different installation."); |
| 194 | } else { |
| 195 | require(!record && !getpwnam("cagesetup"), "A user already has the setup name; no account was modified."); |
| 196 | int uid = 502; |
| 197 | while (uid < 1000 && getpwuid(uid)) uid++; |
| 198 | require(uid < 1000, "No free local setup UID."); |
| 199 | receipt = [@{@"installation":install, @"guid":NSUUID.UUID.UUIDString, @"uid":@(uid), @"state":@"creating"} mutableCopy]; |
| 200 | } |
| 201 | NSString *ordinaryName = argc == 4 ? @(argv[3]) : receipt[@"user"] ?: @"cage"; |
| 202 | NSRegularExpression *userPattern = [NSRegularExpression regularExpressionWithPattern:@"^[a-z][a-z0-9_]{0,30}$" options:0 error:NULL]; |
| 203 | require([userPattern numberOfMatchesInString:ordinaryName options:0 range:NSMakeRange(0,ordinaryName.length)] == 1 && |
| 204 | ![@[@"root",@"cagesetup",@"cageprovision"] containsObject:ordinaryName], "Invalid ordinary guest username."); |
| 205 | require(!data || [ordinaryName isEqual:receipt[@"user"] ?: @"cage"], "The receipt belongs to another ordinary account."); |
| 206 | ODRecord *ordinary = users(node, ordinaryName).firstObject; |
| 207 | require(node && admin && ordinary && !member(admin, ordinary), "The regular Cage user must not be a guest administrator."); |
| 208 | NSString *ordinaryGUID = [ordinary valuesForAttribute:kODAttributeTypeGUID error:NULL].firstObject; |
| 209 | require(ordinaryGUID && (!receipt[@"ordinary_guid"] || [receipt[@"ordinary_guid"] isEqual:ordinaryGUID]), "The ordinary guest account has changed."); |
| 210 | receipt[@"user"] = ordinaryName; receipt[@"ordinary_guid"] = ordinaryGUID; |
| 211 | if (prepare) save(receipt,file); |
| 212 | NSString *uid = [receipt[@"uid"] stringValue]; |
| 213 | if (record) { |
| 214 | NSString *guid = [record valuesForAttribute:kODAttributeTypeGUID error:NULL].firstObject; |
| 215 | NSString *actualUID = [record valuesForAttribute:kODAttributeTypeUniqueID error:NULL].firstObject; |
| 216 | require(guid && [guid caseInsensitiveCompare:receipt[@"guid"]] == NSOrderedSame && [actualUID isEqual:uid], |
| 217 | "Refusing to modify an unrelated guest user."); |
| 218 | } |
| 219 | NSString *phase = receipt[@"state"]; |
| 220 | require([@[@"creating",@"ready",@"retiring",@"retired"] containsObject:phase], "Unknown guest setup state."); |
| 221 | if (password) { |
| 222 | require(![phase isEqual:@"creating"] && ![phase isEqual:@"retiring"], "Finish guest account preparation before changing its password."); |
| 223 | synchronize(ordinary,record,receipt,ordinaryName); |
| 224 | save(receipt,file); close(lock); return 0; |
| 225 | } |
| 226 | if (prepare) { |
| 227 | require([phase isEqual:@"creating"] || [phase isEqual:@"ready"], "Initial setup has already closed."); |
| 228 | NSString *pw = readPassword(); |
| 229 | if (!record) { |
| 230 | require([phase isEqual:@"creating"] && !getpwuid([receipt[@"uid"] intValue]), "Setup account disappeared or its UID is in use."); |
| 231 | record = [node createRecordWithRecordType:kODRecordTypeUsers name:setup attributes:@{ |
| 232 | kODAttributeTypeGUID:@[receipt[@"guid"]], kODAttributeTypeUniqueID:@[uid], |
| 233 | kODAttributeTypePrimaryGroupID:@[@"20"], kODAttributeTypeFullName:@[@"Cage Setup"], |
| 234 | kODAttributeTypeNFSHomeDirectory:@[@"/var/empty"], kODAttributeTypeUserShell:@[@"/bin/sh"], |
| 235 | @"dsAttrTypeNative:IsHidden":@[@"1"] |
| 236 | } error:NULL]; |
| 237 | require(record != nil, "Cannot create the dedicated temporary guest account."); |
| 238 | } |
| 239 | if ([phase isEqual:@"creating"]) |
| 240 | require([record changePassword:nil toPassword:pw error:NULL], "Cannot initialize the temporary password."); |
| 241 | require([record verifyPassword:pw error:NULL], "The stored credential does not match this guest."); |
| 242 | |
| 243 | |
| 244 | |
| 245 | if ([[record valuesForAttribute:kODAttributeTypeUserShell error:NULL].firstObject isEqual:@"/usr/bin/false"]) |
| 246 | require([record setValue:@"/bin/sh" forAttribute:kODAttributeTypeUserShell error:NULL], "Cannot repair the temporary account's login shell."); |
| 247 | setMember(admin, record, YES); |
| 248 | receipt[@"state"] = @"ready"; |
| 249 | } else { |
| 250 | require(![phase isEqual:@"creating"], "The temporary account has not completed setup."); |
| 251 | if (![phase isEqual:@"retired"]) { |
| 252 | receipt[@"state"] = @"retiring"; save(receipt,file); |
| 253 | } |
| 254 | |
| 255 | |
| 256 | if (record) retire(node, admin, record); |
| 257 | require(!member(admin,ordinary), "The regular Cage user is a guest administrator."); |
| 258 | receipt[@"state"] = @"retired"; |
| 259 | } |
| 260 | save(receipt,file); |
| 261 | close(lock); |
| 262 | return 0; |
| 263 | } |
| 264 | } |