Last active
December 27, 2024 16:32
Silent privilege escalation in Swift (password is needed)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To run this from anywhere (even a function not in the main thread) you can do something like this: