forked from assafdori/bypass-mdm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbypass-mdm-v2.sh
More file actions
430 lines (366 loc) · 15 KB
/
Copy pathbypass-mdm-v2.sh
File metadata and controls
430 lines (366 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
#!/bin/bash
set -o pipefail
# Define color codes
RED='\033[1;31m'
GRN='\033[1;32m'
BLU='\033[1;34m'
YEL='\033[1;33m'
PUR='\033[1;35m'
CYAN='\033[1;36m'
NC='\033[0m'
PB=/usr/libexec/PlistBuddy
# Error handling function
error_exit() {
echo -e "${RED}ERROR: $1${NC}" >&2
exit 1
}
# Warning function
warn() {
echo -e "${YEL}WARNING: $1${NC}"
}
# Success function
success() {
echo -e "${GRN}✓ $1${NC}"
}
# Info function
info() {
echo -e "${BLU}ℹ $1${NC}"
}
# Validation function for username
validate_username() {
local username="$1"
# Check if username is empty
if [ -z "$username" ]; then
echo "Username cannot be empty"
return 1
fi
# Check length (1-31 characters for macOS)
if [ ${#username} -gt 31 ]; then
echo "Username too long (max 31 characters)"
return 1
fi
# Check for valid characters (alphanumeric, underscore, hyphen)
if ! [[ "$username" =~ ^[a-zA-Z0-9_-]+$ ]]; then
echo "Username can only contain letters, numbers, underscore, and hyphen"
return 1
fi
# Check if starts with letter or underscore
if ! [[ "$username" =~ ^[a-zA-Z_] ]]; then
echo "Username must start with a letter or underscore"
return 1
fi
return 0
}
# Validation function for password
validate_password() {
local password="$1"
# Check if password is empty
if [ -z "$password" ]; then
echo "Password cannot be empty"
return 1
fi
# Check minimum length (macOS allows any length, but recommend 4+)
if [ ${#password} -lt 4 ]; then
echo "Password too short (minimum 4 characters recommended)"
return 1
fi
return 0
}
# Check if user already exists
check_user_exists() {
local dscl_path="$1"
local username="$2"
if dscl -f "$dscl_path" localhost -read "/Local/Default/Users/$username" 2>/dev/null; then
return 0 # User exists
else
return 1 # User doesn't exist
fi
}
# Find available UID
find_available_uid() {
local dscl_path="$1"
local uid=501
# Check UIDs from 501-599
while [ $uid -lt 600 ]; do
if ! dscl -f "$dscl_path" localhost -search /Local/Default/Users UniqueID $uid 2>/dev/null | grep -q "UniqueID"; then
echo $uid
return 0
fi
uid=$((uid + 1))
done
echo "501" # Default fallback
return 1
}
# Locate the Data volume by APFS role and unlock it if FileVault-locked
# (ported from bypass-mdm-v3 / PR #170). Echoes the real mount point on
# stdout; all chatter goes to stderr.
step() { echo -e "${CYAN}▸ $1${NC}"; }
resolve_data_volume() {
local id data_dev mount_pt
step "Locating the Data volume by APFS role..." >&2
# Position-independent: on the (Data)-role line, pull the diskNsM token by
# PATTERN, not column (diskutil draws "|" tree chars that shift columns).
id=$(diskutil apfs list 2>/dev/null \
| awk '/\(Data\)/{for(i=1;i<=NF;i++) if($i ~ /^disk[0-9]+s[0-9]+$/){print $i; exit}}')
# Fallback 1: a volume literally named "Data" in `diskutil list`.
if [ -z "$id" ]; then
id=$(diskutil list 2>/dev/null \
| awk '/[[:space:]]Data[[:space:]]/{for(i=1;i<=NF;i++) if($i ~ /^disk[0-9]+s[0-9]+$/) v=$i} END{print v}')
fi
# Fallback 2: ask the user, showing the disk layout.
if [ -z "$id" ] || ! diskutil info "/dev/$id" >/dev/null 2>&1; then
warn "Could not auto-detect the Data volume. Your disks:" >&2
diskutil list >&2
echo "" >&2
read -p "Type the Data volume identifier (e.g. disk3s1): " id </dev/tty
id="${id#/dev/}"
fi
[ -n "$id" ] || error_exit "No Data volume identifier provided."
data_dev="/dev/$id"
diskutil info "$data_dev" >/dev/null 2>&1 || error_exit "Not a valid disk: $data_dev"
info "Data volume device: $data_dev" >&2
_mp() { diskutil info "$data_dev" 2>/dev/null | awk -F': *' '/Mount Point/{print $2}' | sed 's/[[:space:]]*$//'; }
mount_pt=$(_mp)
if [ -z "$mount_pt" ] || [ ! -d "$mount_pt" ]; then
# Try a plain mount first (works for non-encrypted volumes).
diskutil mount "$data_dev" >&2 2>/dev/null
mount_pt=$(_mp)
fi
if [ -z "$mount_pt" ] || [ ! -d "$mount_pt" ]; then
# Still not mounted -> almost certainly FileVault-locked. Unlock it.
warn "Data volume appears FileVault-locked — unlocking." >&2
echo -e "${YEL}Enter the password of an account on this Mac (or its FileVault recovery key):${NC}" >&2
diskutil apfs unlockVolume "$data_dev" >&2 \
|| error_exit "Failed to unlock the Data volume. Re-run and enter a valid account password / recovery key."
mount_pt=$(_mp)
fi
[ -d "$mount_pt" ] || error_exit "Data volume mount point not found after mount/unlock."
# Sanity: the dslocal node must exist on this volume.
[ -d "$mount_pt/private/var/db/dslocal/nodes/Default" ] \
|| error_exit "This does not look like a macOS Data volume (no dslocal node at $mount_pt)."
success "Data volume mounted at: $mount_pt" >&2
echo "$mount_pt"
}
# Locate + mount (FileVault-unlock if needed) the Data volume at startup
data_mount=$(resolve_data_volume) || exit 1
data_volume=$(basename "$data_mount")
# Display header
echo ""
echo -e "${CYAN}╔═══════════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║ Bypass MDM By Assaf Dori (assafdori.com) ║${NC}"
echo -e "${CYAN}╚═══════════════════════════════════════════════╝${NC}"
echo ""
success "Data Volume: $data_mount"
echo ""
# Prompt user for choice
PS3='Please enter your choice: '
options=("Bypass MDM from Recovery" "Reboot & Exit")
select opt in "${options[@]}"; do
case $opt in
"Bypass MDM from Recovery")
echo ""
echo -e "${YEL}═══════════════════════════════════════${NC}"
echo -e "${YEL} Starting MDM Bypass Process${NC}"
echo -e "${YEL}═══════════════════════════════════════${NC}"
echo ""
# Data volume already located + mounted (FileVault-unlocked if needed)
# by resolve_data_volume(); data_mount is its real mount point.
info "Validating paths..."
data_path="$data_mount"
if [ ! -d "$data_path" ]; then
error_exit "Data volume path does not exist: $data_path"
fi
dscl_path="$data_path/private/var/db/dslocal/nodes/Default"
if [ ! -d "$dscl_path" ]; then
error_exit "Directory Services path does not exist: $dscl_path"
fi
success "All system paths validated"
echo ""
# Create Temporary User
echo -e "${CYAN}Creating Temporary Admin User${NC}"
echo -e "${NC}Press Enter to use defaults (recommended)${NC}"
# Get and validate real name
read -p "Enter Temporary Fullname (Default is 'Apple'): " realName
realName="${realName:=Apple}"
# Get and validate username
while true; do
read -p "Enter Temporary Username (Default is 'Apple'): " username
username="${username:=Apple}"
if validation_msg=$(validate_username "$username"); then
break
else
warn "$validation_msg"
echo -e "${YEL}Please try again or press Ctrl+C to exit${NC}"
fi
done
# Check if user already exists
if check_user_exists "$dscl_path" "$username"; then
warn "User '$username' already exists in the system"
read -p "Do you want to use a different username? (y/n): " response
if [[ "$response" =~ ^[Yy]$ ]]; then
while true; do
read -p "Enter a different username: " username
if [ -z "$username" ]; then
warn "Username cannot be empty"
continue
fi
if validation_msg=$(validate_username "$username"); then
if ! check_user_exists "$dscl_path" "$username"; then
break
else
warn "User '$username' also exists. Try another name."
fi
else
warn "$validation_msg"
fi
done
else
warn "Continuing with existing user '$username' (may cause conflicts)"
fi
fi
# Get and validate password
while true; do
read -p "Enter Temporary Password (Default is '1234'): " passw
passw="${passw:=1234}"
if validation_msg=$(validate_password "$passw"); then
break
else
warn "$validation_msg"
echo -e "${YEL}Please try again or press Ctrl+C to exit${NC}"
fi
done
echo ""
# Find available UID
info "Checking for available UID..."
available_uid=$(find_available_uid "$dscl_path")
if [ $? -eq 0 ] && [ "$available_uid" != "501" ]; then
info "UID 501 is in use, using UID $available_uid instead"
else
available_uid="501"
fi
success "Using UID: $available_uid"
echo ""
# Create User with error handling
info "Creating user account: $username"
if ! dscl -f "$dscl_path" localhost -create "/Local/Default/Users/$username" 2>/dev/null; then
error_exit "Failed to create user account"
fi
dscl -f "$dscl_path" localhost -create "/Local/Default/Users/$username" UserShell "/bin/zsh" || warn "Failed to set user shell"
dscl -f "$dscl_path" localhost -create "/Local/Default/Users/$username" RealName "$realName" || warn "Failed to set real name"
dscl -f "$dscl_path" localhost -create "/Local/Default/Users/$username" UniqueID "$available_uid" || warn "Failed to set UID"
dscl -f "$dscl_path" localhost -create "/Local/Default/Users/$username" PrimaryGroupID "20" || warn "Failed to set GID"
user_home="$data_path/Users/$username"
if [ ! -d "$user_home" ]; then
if mkdir -p "$user_home" 2>/dev/null; then
success "Created user home directory"
else
error_exit "Failed to create user home directory: $user_home"
fi
else
warn "User home directory already exists: $user_home"
fi
dscl -f "$dscl_path" localhost -create "/Local/Default/Users/$username" NFSHomeDirectory "/Users/$username" || warn "Failed to set home directory"
if ! dscl -f "$dscl_path" localhost -passwd "/Local/Default/Users/$username" "$passw" 2>/dev/null; then
error_exit "Failed to set user password"
fi
if ! dscl -f "$dscl_path" localhost -append "/Local/Default/Groups/admin" GroupMembership "$username" 2>/dev/null; then
error_exit "Failed to add user to admin group"
fi
success "User account created successfully"
echo ""
# Block MDM enrollment domains (SSV-aware; also blocks the org's own MDM
# host read from the DEP record, plus IPv6). Reads the record here, before
# it is removed later in this flow.
info "Blocking MDM enrollment domains..."
hosts_file="$data_path/private/etc/hosts"
record_found="$data_path/private/var/db/ConfigurationProfiles/Settings/.cloudConfigRecordFound"
mdm_host="" org=""
if [ -f "$record_found" ]; then
mdm_host=$(plutil -convert xml1 -o - "$record_found" 2>/dev/null \
| grep -ioE 'https?://[a-z0-9._-]+' | sed -E 's#https?://##' \
| sort -u | grep -viE '(^|\.)apple\.com$' | head -1)
org=$(plutil -convert xml1 -o - "$record_found" 2>/dev/null \
| grep -iA1 OrganizationName | tail -1 | sed -E 's/.*<string>(.*)<\/string>.*/\1/')
[ -n "$org" ] && info "This device is assigned in Apple Business Manager to: $org"
[ -n "$mdm_host" ] && info "Org MDM server host: $mdm_host (will also be blocked)"
else
info "No activation record currently present."
fi
echo ""
# --- Block the DEP / enrollment domains on the DATA volume's hosts file ---
step "Blocking DEP enrollment domains (Data-volume hosts file)"
[ -f "$hosts_file" ] || { mkdir -p "$(dirname "$hosts_file")"; touch "$hosts_file"; }
# iprofiles.apple.com = the device-side activation-record fetch (THE essential one).
# device/mdm-enrollment = server-side DEP API (harmless to include).
# acmdm = Apple cert/MDM endpoint. We deliberately DO NOT block:
# gdmf.apple.com (breaks Software Update) or albert.apple.com (breaks iMessage/FaceTime).
block_domains=(iprofiles.apple.com deviceenrollment.apple.com mdmenrollment.apple.com acmdm.apple.com)
[ -n "$mdm_host" ] && block_domains+=("$mdm_host")
grep -q "Added by bypass-mdm" "$hosts_file" 2>/dev/null || {
echo "" >>"$hosts_file"
echo "# Added by bypass-mdm — DEP enrollment block" >>"$hosts_file"
}
for d in "${block_domains[@]}"; do
grep -qiE "[[:space:]]$d(\$|[[:space:]])" "$hosts_file" 2>/dev/null && { info "$d already blocked"; continue; }
printf '0.0.0.0 %s\n:: %s\n' "$d" "$d" >>"$hosts_file"
success "blocked $d"
done
echo ""
# Remove configuration profiles
info "Configuring MDM bypass settings..."
config_path="$data_path/private/var/db/ConfigurationProfiles/Settings"
# Create config directory if it doesn't exist
if [ ! -d "$config_path" ]; then
if mkdir -p "$config_path" 2>/dev/null; then
success "Created configuration directory"
else
warn "Could not create configuration directory"
fi
fi
# Mark setup as done
touch "$data_path/private/var/db/.AppleSetupDone" 2>/dev/null && success "Marked setup as complete" || warn "Could not mark setup as complete"
# Remove activation records
rm -rf "$config_path/.cloudConfigHasActivationRecord" 2>/dev/null && success "Removed activation record" || info "No activation record to remove"
rm -rf "$config_path/.cloudConfigRecordFound" 2>/dev/null && success "Removed cloud config record" || info "No cloud config record to remove"
# Create bypass markers
touch "$config_path/.cloudConfigProfileInstalled" 2>/dev/null && success "Created profile installed marker" || warn "Could not create profile marker"
touch "$config_path/.cloudConfigRecordNotFound" 2>/dev/null && success "Created record not found marker" || warn "Could not create not found marker"
# Disable the enrollment daemon via a launchd override (durable: lives on
# the Data volume, so it survives the System-volume reseal a macOS update
# performs). macOS 26 moved this work to com.apple.ManagedClient.enroll.
info "Disabling the enrollment daemon (durable override on Data volume)..."
launchd_disabled="$data_path/private/var/db/com.apple.xpc.launchd/disabled.plist"
mkdir -p "$(dirname "$launchd_disabled")" 2>/dev/null
[ -f "$launchd_disabled" ] || printf '<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict/></plist>\n' >"$launchd_disabled"
for label in com.apple.ManagedClient.enroll com.apple.mdmclient.daemon.runatboot; do
"$PB" -c "Add :$label bool true" "$launchd_disabled" 2>/dev/null \
|| "$PB" -c "Set :$label true" "$launchd_disabled" 2>/dev/null
done
if [ -f "$launchd_disabled" ]; then
success "Enrollment daemon disabled via $launchd_disabled"
else
warn "Could not write launchd override (daemon not disabled)"
fi
echo ""
echo -e "${GRN}╔═══════════════════════════════════════════════╗${NC}"
echo -e "${GRN}║ MDM Bypass Completed Successfully! ║${NC}"
echo -e "${GRN}╚═══════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${CYAN}Next steps:${NC}"
echo -e " 1. Close this terminal window"
echo -e " 2. Reboot your Mac"
echo -e " 3. Login with username: ${YEL}$username${NC} and password: ${YEL}$passw${NC}"
echo ""
break
;;
"Reboot & Exit")
echo ""
info "Rebooting system..."
reboot
break
;;
*)
echo -e "${RED}Invalid option $REPLY${NC}"
;;
esac
done