Skip to content

Instantly share code, notes, and snippets.

@nmggithub
Last active December 27, 2024 16:32
Silent privilege escalation in Swift (password is needed)
import Foundation
/// Run a command as root.
@MainActor // This *will* hang if it is not run on the main thread.
func sudo(_ command: String, username: String = NSUserName(), password: String) throws -> String? {
guard
let script = NSAppleScript(
source:
"""
do shell script "\(command)" user name "\(username)" password "\(password)" with administrator privileges
"""
),
script.compileAndReturnError(nil),
// The return value of this function is documented wrong, so we must cast it to the correct type.
let descriptor = script.executeAndReturnError(nil) as NSAppleEventDescriptor?,
let returnedString = descriptor.stringValue
else { return nil }
return returnedString
}
@nmggithub
Copy link
Author

nmggithub commented Dec 27, 2024

To run this from anywhere (even a function not in the main thread) you can do something like this:

Task.detached { @MainActor in
    let answer = try sudo("whoami", password: "hunter2")
    print(answer)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment