Last active
March 28, 2025 17:32
-
-
Save nmggithub/779563215439beb36692957900d9ec1e to your computer and use it in GitHub Desktop.
Silent privilege escalation in Swift (password is needed)
This file contains hidden or 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 | |
| } |
Author
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: