2009-09-13 235 views
6

我正在制作一个简单的应用程序,让您快速输入要运行的shell命令。 它完美的工作,但是有sudo命令的问题。 目前,它检测到一个sudo命令,然后尝试让它为用户的密码显示一个授权窗口,就像您在安装程序中看到的一样。在Mac应用程序中提升为管理员权限

下面的代码,一旦检测到它是一个sudo命令:

SFAuthorization *authorization = [[SFAuthorization alloc] initWithFlags:kAuthorizationFlagPreAuthorize rights:NULL environment:kAuthorizationEmptyEnvironment]; 
if ([authorization obtainWithRight:"com.mycompany.myapplication" flags:kAuthorizationFlagPreAuthorize error:nil]){ 
    //authorized, now run the command using NSTask. 
}else{ 
    //fail 
} 

现在,据我所知,这是完全和完全错误的。这正是我从文档中拼凑出来的东西。有任何想法吗?

回答

1

安全性很难。我可以解释文档并提供代码片段,但我很可能是错的。更糟糕的是,即使我的高层描述是正确的,在代码片段中很可能会有一个微小的错误,这会导致安全性丧失。

如果您打算提起特权升级,最好的方法是阅读文档并使用提供的示例。

https://developer.apple.com/mac/library/documentation/Security/Conceptual/authorization_concepts/01introduction/introduction.html#//apple_ref/doc/uid/TP30000995-CH204-TP1

1

你想使用AuthorizationExecuteWithPrivileges功能,像这样:

- (IBAction)touch: (id) sender { 

    NSString * filepath = [_filepathfield stringValue]; 
    FILE *commpipe = NULL; 
    OSStatus execstatus; 


    NSLog(@"file path is %@", filepath); 

    char *args[] = {[filepath cString], NULL}; 


    SFAuthorization * authorization = [SFAuthorization authorization]; 

    execstatus = AuthorizationExecuteWithPrivileges([authorization authorizationRef], 
                "/usr/bin/touch", 
                kAuthorizationFlagDefaults, 
                args, 
                &commpipe); 

    if (execstatus == errAuthorizationSuccess) 
    NSlog(@"Toot! It worked"); 
    else 
    NSLog(@"No dice"); 

} 

由于BSD是一个微妙而脾气暴躁的花,我建议你不要让用户从执行任意命令该应用程序为根。

/讲座

从您的示例代码是的去,如果你想从它自己的用户限制自己的程序的功能方式的开端。例如,您可能有一个应用程序只允许某些用户更改已保存文件的数据。因此,您应该在安全数据库'com.mycompany.LibraryApp.AlterData'中创建一个条目,并检查用户在尝试更改数据时是否具有该特权。但这是一个完全不同的话题...

希望有帮助, -p。

+0

但是这不会执行NSTask。任何想法如何使用权限执行NSTask? – 2012-08-27 15:48:33

1

我知道这是一个非常古老的问题,但对于那些仍在寻找答案的人来说,这里就是这样。 (它使用的AppleScript)

NSAppleScript *script = [[NSAppleScript alloc] initWithSource:@"do shell script \"[YOUR SCRIPT HERE]\" with administrator privileges"]; 

,当然,替换[脚本的位置]与你的脚本,并确保逃避串,可可方式。

NSDictionary *errorInfo; 
[script executeAndReturnError:&errorInfo]; 

如需进一步解释,请评论。

相关问题