2

After launching Xcode I select File / New / Project / macOS / Command Line Tool / Next and run the following code:

import SecurityFoundation

do {
  // Authorize for privileged operations
  guard
    let authorization = SFAuthorization.authorization() as? SFAuthorization,
    let right = NSString(string: kAuthorizationRuleAuthenticateAsAdmin).utf8String
  else {
    throw CocoaError(.fileWriteNoPermission)
  }
  try authorization.obtain(withRight: right, flags: [.extendRights, .interactionAllowed])
  defer { authorization.invalidateCredentials() }

  // Rename MyApp.app into MyApp-Renamed.app
  let sourceFileURL = URL(fileURLWithPath: "/Applications/MyApp.app")
  let destFileURL = sourceFileURL.deletingLastPathComponent().appendingPathComponent("MyApp-Renamed.app")
  try FileManager.default.moveItem(at: sourceFileURL, to: destFileURL)

} catch {
  print(error)
}

Unfortunately, this program does not work:

Error Domain=NSCocoaErrorDomain Code=513 "“MyApp” couldn’t be moved because you don’t have permission to access “Applications”." UserInfo={NSSourceFilePathErrorKey=/Applications/MyApp.app, NSUserStringVariant=( Move ), NSDestinationFilePath=/Applications/MyApp-Renamed.app, NSFilePath=/Applications/MyApp.app, NSUnderlyingError=0x100617380 {Error Domain=NSPOSIXErrorDomain Code=13 "Permission denied"}}

The app is not Sandboxed. How to fix the issue?

Vadim
  • 9,383
  • 7
  • 36
  • 58

1 Answers1

2

‪If I understand correctly, obtaining an authorization does not elevate your process. You just get an authorization reference to verify it or for use with another API that would let you perform a privileged operation. Like launching a privileged process or passing it to a privileged helper tool.‬

‪Authorization Services Tasks

pointum
  • 2,987
  • 24
  • 31
  • How about an authorization right? I don’t understand what exactly happens when we ‘copy’ rights. The macOS is apparently asking for credentials, so how can we use them later? I just cannot believe that `SMJobBless` is the only way to perform a privileged operation. Is it? – Vadim Jan 16 '20 at 20:09
  • @Vadim apparently only SMJobBless and deprecated AuthorizationExecuteWithPrivileges are suitable for such operations – pointum Jan 16 '20 at 20:30
  • I so hoped for magic… The most likely Finder uses a helper tool with root access, right? – Vadim Jan 16 '20 at 20:34