Ejemplo n.º 1
0
// throw std::exception on error
AuthorizationRef & GetAuth()
{
    if (!_auth)
    {
        OSStatus res;
        QString msg = "Safejumper requires to make some modifications to your network settings.\n\n";
        QByteArray ba = msg.toUtf8();
        AuthorizationItem environmentItems[] = {
        {kAuthorizationEnvironmentPrompt, ba.size(), (void*)ba.data(), 0},
    //	        {kAuthorizationEnvironmentIcon, iconPathLength, (void*)iconPathC, 0}
        };
        AuthorizationEnvironment myEnvironment = {1, environmentItems};
        AuthorizationFlags myFlags = kAuthorizationFlagDefaults;
        res = AuthorizationCreate(NULL, &myEnvironment, myFlags, &_AuthorizationRef);
        if (res != errAuthorizationSuccess)
            throw std::runtime_error(("AuthorizationCreate() fails with result: " + QString::number(res)).toStdString());

        AuthorizationItem myItems = {kAuthorizationRightExecute, 0, NULL, 0};
        AuthorizationRights myRights = {1, &myItems};
        myFlags = kAuthorizationFlagDefaults |
            kAuthorizationFlagInteractionAllowed |
    //		kAuthorizationFlagPreAuthorize |
            kAuthorizationFlagExtendRights;

        res = AuthorizationCopyRights(_AuthorizationRef, &myRights, &myEnvironment, myFlags, NULL);
        if (res != errAuthorizationSuccess)
            throw std::runtime_error(("AuthorizationCopyRights() fails with result: " + QString::number(res)).toStdString());
        _auth = true;
    }
    return _AuthorizationRef;
}
Ejemplo n.º 2
0
static OSStatus GetAuthorization (void) {
    static Boolean              sIsAuthorized = false;
    AuthorizationRights         ourAuthRights;
    AuthorizationFlags          ourAuthFlags;
    AuthorizationItem           ourAuthRightsItem[RIGHTS_COUNT];
    AuthorizationEnvironment    ourAuthEnvironment;
    AuthorizationItem           ourAuthEnvItem[1];
    char                        prompt[] = "BOINC needs to have certain permissions set up.\n\n";
    OSStatus                    err = noErr;

    if (sIsAuthorized)
        return noErr;
        
    ourAuthRights.count = 0;
    ourAuthRights.items = NULL;

    err = AuthorizationCreate (&ourAuthRights, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &gOurAuthRef);
    if (err != noErr) {
        ShowSecurityError("AuthorizationCreate returned error %d", err);
        return err;
    }
     
    ourAuthRightsItem[0].name = kAuthorizationRightExecute;
    ourAuthRightsItem[0].value = dsclPath;
    ourAuthRightsItem[0].valueLength = strlen (dsclPath);
    ourAuthRightsItem[0].flags = 0;

    ourAuthRightsItem[1].name = kAuthorizationRightExecute;
    ourAuthRightsItem[1].value = chmodPath;
    ourAuthRightsItem[1].valueLength = strlen (chmodPath);
    ourAuthRightsItem[1].flags = 0;

    ourAuthRightsItem[2].name = kAuthorizationRightExecute;
    ourAuthRightsItem[2].value = chownPath;
    ourAuthRightsItem[2].valueLength = strlen (chownPath);
    ourAuthRightsItem[2].flags = 0;

    ourAuthRights.count = RIGHTS_COUNT;
    ourAuthRights.items = ourAuthRightsItem;

    ourAuthEnvItem[0].name = kAuthorizationEnvironmentPrompt;
    ourAuthEnvItem[0].value = prompt;
    ourAuthEnvItem[0].valueLength = strlen (prompt);
    ourAuthEnvItem[0].flags = 0;

    ourAuthEnvironment.count = 1;
    ourAuthEnvironment.items = ourAuthEnvItem;

    ourAuthFlags = kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights;
    
    // When this is called from the installer, the installer has already authenticated.  
    // In that case we are already running with full root privileges so AuthorizationCopyRights() 
    // does not request a password from the user again.
    err = AuthorizationCopyRights (gOurAuthRef, &ourAuthRights, &ourAuthEnvironment, ourAuthFlags, NULL);
    
    if (err == noErr)
        sIsAuthorized = true;
    
    return err;
}
Ejemplo n.º 3
0
/**
 * Execute with administrative rights.
 */
bool MacUninstallApp::ElevatedUninstall(const wxString &pkg, const wxString &pkgid)
{
    // If we are already root, do the uninstall directly
    if (geteuid() == 0)
        return DoUninstall(pkg, pkgid);

    wxString msg = wxString::Format(
            _("In order to uninstall %s, administrative rights are required.\n\n"),
            pkg.c_str());
    char *prompt = strdup(msg.utf8_str());

    OSStatus st;
    AuthorizationFlags aFlags = kAuthorizationFlagDefaults;
    AuthorizationRef aRef;
    AuthorizationItem promptItem = {
        kAuthorizationEnvironmentPrompt, strlen(prompt), prompt, 0
    };
    AuthorizationEnvironment aEnv = { 1, &promptItem };

    st = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment,
            kAuthorizationFlagDefaults, &aRef);
    if (errAuthorizationSuccess != st) {
        ::wxLogError(_("Authorization could not be created: %s"), MacAuthError(st).c_str());
        return true;
    }
    AuthorizationItem aItems = { kAuthorizationRightExecute, 0, NULL, 0 };
    AuthorizationRights aRights = { 1, &aItems };
    aFlags = kAuthorizationFlagDefaults |
        kAuthorizationFlagInteractionAllowed |
        kAuthorizationFlagPreAuthorize |
        kAuthorizationFlagExtendRights;
    st = AuthorizationCopyRights(aRef, &aRights, &aEnv, aFlags, NULL );
    bool ret = true;
    if (errAuthorizationSuccess == st) {
        char *executable = strdup(m_sSelfPath.utf8_str());
        char *args[] = { "--batch", NULL };
        FILE *pout = NULL;

        if (!::wxGetEnv(wxT("TMPDIR"), NULL))
            ::wxSetEnv(wxT("TMPDIR"), wxFileName::GetTempDir());
        ::wxSetEnv(wxT("MACUNINST_ELEVATION_PID"), wxString::Format(wxT("%d"), ::wxGetProcessId()));
        st = AuthorizationExecuteWithPrivileges(aRef,
                executable, kAuthorizationFlagDefaults, args, &pout);
        if (errAuthorizationSuccess == st) {
            int status;
            fscanf(pout, "%d %lu %lu", &status, &failed_files, &failed_dirs);
            ret = (0 == status);
        } else
            ::wxLogError(_("Could not execute with administrative rights:\n%s"), MacAuthError(st).c_str());
    } else {
        if (st) {
            m_bCancelled = (errAuthorizationCanceled == st);
            if (!m_bCancelled)
                ::wxLogError(_("Authorization failed: %s"), MacAuthError(st).c_str());
        }
    }
    AuthorizationFree(aRef, kAuthorizationFlagDefaults);
    return ret;
}
Ejemplo n.º 4
0
static AuthorizationRef
IdAuthCreate(void)
{
   /*
    * Bug 195868: If thread credentials are in use, we need to fork.
    * Otherwise, avoid forking, as it breaks Apple's detection of
    * whether the calling process is a GUI process.
    *
    * This is needed because AuthorizationRefs created by GUI
    * processes can be passed to non-GUI processes to allow them to
    * prompt for authentication with a dialog that automatically
    * steals focus from the current GUI app.  (This is how the Mac UI
    * and VMX work today.)
    *
    * TODO: How should we handle single-threaded apps where uid !=
    * euid or gid != egid?  Some callers may expect us to check
    * against euid, others may expect us to check against uid.
    */

   uid_t thread_uid;
   gid_t thread_gid;
   int ret;

   ret = syscall(SYS_gettid, &thread_uid, &thread_gid);

   if (ret != -1) {
      /*
       * We have per-thread UIDs in use, so Apple's authorization
       * APIs don't work.  Fork so we can use them.
       */

      return IdAuthCreateWithFork();
   } else {
      if (errno != ESRCH) {
         Warning("%s: gettid failed, error %d.\n", __func__, errno);

         return NULL;
      } else {
          // Per-thread identities are not in use in this thread.
         AuthorizationRef auth;
         OSStatus ret;

         ret = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment,
                                   kAuthorizationFlagDefaults, &auth);

         if (ret == errAuthorizationSuccess) {
            return auth;
         } else {
            ASSERT_ON_COMPILE(sizeof ret == sizeof (int32));
            Warning("%s: AuthorizationCreate failed, error %d.\n",
                    __func__, (int32)ret);

            return NULL;
         }
      }
   }
}
Ejemplo n.º 5
0
// Based on http://developer.apple.com/documentation/Security/Conceptual/authorization_concepts/03authtasks/authtasks.html#//apple_ref/doc/uid/TP30000995-CH206-TPXREF33
// Note that I tried to implement this in managed code using p/invokes, but I kept
// getting kPOSIXErrorENOENT errors on the call to AuthorizationCreate. Not sure
// why but opensnoop shows very different behavior between the managed and
// unmanaged code.
int main(int argc, char* argv[])
{
	OSStatus err;
	AuthorizationRef cookie;
	
	err = AuthorizationCreate(
		NULL,
		kAuthorizationEmptyEnvironment,
		kAuthorizationFlagDefaults,
		&cookie);
		
	if (err != errAuthorizationSuccess)
	{
		fprintf(stderr, "AuthorizationCreate failed with error %ld\n", err);
		return err;
	}
	
	do
	{
		{
			AuthorizationItem items = {kAuthorizationRightExecute, 0, NULL, 0};
			AuthorizationRights rights = {1, &items};
			AuthorizationFlags flags =
				kAuthorizationFlagDefaults |
				kAuthorizationFlagInteractionAllowed |
				kAuthorizationFlagPreAuthorize |
				kAuthorizationFlagExtendRights;
			
			err = AuthorizationCopyRights(cookie, &rights, NULL, flags, NULL);
			if (err != errAuthorizationSuccess)
			{
				fprintf(stderr, "AuthorizationCopyRights failed with error %ld\n", err);
				break;
			}
		}
		
		{
			char* args[] = {argv[1], argv[2], NULL};
			
			err = AuthorizationExecuteWithPrivileges(
				cookie,
				"/bin/cp",
				kAuthorizationFlagDefaults,
				args,
				NULL);
			if (err != errAuthorizationSuccess)
			{
				fprintf(stderr, "AuthorizationExecuteWithPrivileges failed with error %ld\n", err);
				break;
			}
		}
	} while (0);
	
	AuthorizationFree(cookie, kAuthorizationFlagDefaults);
	
	return err;
}
Ejemplo n.º 6
0
/*
 * Launches an executable as root on MacOS X.
 * 
 * The executable and arguments must be provided on the command line.
 *
 * This code is heavily inspired from the example at
 * http://developer.apple.com/documentation/Security/Conceptual/authorization_concepts/03authtasks/chapter_3_section_4.html
 *
 */
int main(int argc, const char** argv)
{
    // Check that we have enough arguments
    if (argc < 3)
    {
        return -1;
    }
    
    
    // Grab an authorization reference
    OSStatus status;
    AuthorizationFlags flags = kAuthorizationFlagDefaults;
    AuthorizationRef authRef;
    status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, flags, &authRef);
    if (status != errAuthorizationSuccess)
    {
        return status;
    }
    
    // Set up the authorization rights
    AuthorizationItem authItems = { kAuthorizationRightExecute, 0, NULL, 0 };
    AuthorizationRights authRights = { 1, &authItems };
    flags = kAuthorizationFlagDefaults |
            kAuthorizationFlagInteractionAllowed |
            kAuthorizationFlagPreAuthorize |
            kAuthorizationFlagExtendRights;
    status = AuthorizationCopyRights(authRef, &authRights, NULL, flags, NULL);    
    if (status != errAuthorizationSuccess) 
    {
        return status;
    }
    
    // Prepare the executable + arguments, from the command-line arguments
    int i;
    const char* executable = argv[1];
    char** arguments = (char**) malloc(sizeof(char*) * (argc - 1));
    for (i = 0; i < (argc - 2); ++i)
    {
        arguments[i] = (char*) argv[i + 2];
    }
    arguments[argc - 2] = NULL;
    
    // Run!
    flags = kAuthorizationFlagDefaults;
    status = AuthorizationExecuteWithPrivileges(authRef, executable, flags,
                                                arguments, NULL);
    if (status != errAuthorizationSuccess) 
    {
        return status;
    }
    
    // Cleanup
    AuthorizationFree(authRef, kAuthorizationFlagDefaults);
    return 0;
}
Ejemplo n.º 7
0
JNIEXPORT jboolean JNICALL Java_com_five_onair_server_utils_FileUtils_copyDirectoryLikeRoot
(JNIEnv *env, jclass m_class, jstring _from, jstring _dest){

    OSStatus myStatus;
    AuthorizationFlags myFlags = kAuthorizationFlagDefaults;              // 1
    AuthorizationRef myAuthorizationRef;                                  // 2
    
    myStatus = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment,  // 3
                                   
                                   myFlags, &myAuthorizationRef);
    
    if (myStatus != errAuthorizationSuccess)
        return myStatus;
    
    AuthorizationItem myItems = {kAuthorizationRightExecute, 0,NULL, 0};
    
    AuthorizationRights myRights = {1, &myItems};                 //
    
    myFlags = kAuthorizationFlagDefaults |                         // 6
    kAuthorizationFlagInteractionAllowed |
    kAuthorizationFlagPreAuthorize |
    kAuthorizationFlagExtendRights;
    
    myStatus = AuthorizationCopyRights (myAuthorizationRef, &myRights, NULL, myFlags, NULL );
    
    if (myStatus == errAuthorizationSuccess){
       
        char *from = NULL,*dest = NULL,*flag=NULL;
    
        strcpy(from, env->GetStringUTFChars(_from, NULL));
        strcpy(dest, env->GetStringUTFChars(_dest, NULL));
        strcpy(flag, "-r");
        
        char myToolPath[] = "/bin/cp";
        char *myArguments[] = { flag, from, dest, NULL };
        FILE *myCommunicationsPipe = NULL;
        
        
        
        
        myFlags = kAuthorizationFlagDefaults;                          // 8
        
        myStatus = AuthorizationExecuteWithPrivileges(myAuthorizationRef, myToolPath, myFlags, myArguments,&myCommunicationsPipe);
        
        
        if (myStatus == errAuthorizationSuccess){
            return true;
        }
        return false;
        
    }
    
    AuthorizationFree (myAuthorizationRef, kAuthorizationFlagDefaults); // 10
    
}
Ejemplo n.º 8
0
int myInitAuthCommand(void)
{
    
	// AuthorizationItem right = { "com.alxsoft.iCooked.loader", 0, NULL, 0 };
    //AuthorizationRights rightSet = { 1, &right };
    OSStatus status;
    
    //AuthorizationFlags flags = kAuthorizationFlagDefaults | kAuthorizationFlagPreAuthorize
	//     | kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights;
	
	
    /* Create a new authorization reference which will later be passed to the tool. */
    
    status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &authorizationRef);
	
    if (status != errAuthorizationSuccess)
    {
        if(myDebug) fprintf(stderr, "Failed to create the authref: %ld.\n", status);
        return kMyAuthorizedCommandInternalError;
    }
    
    /* This shows how AuthorizationCopyRights() can be used in order to pre-authorize the user before
	 attempting to perform the privileged operation.  Pre-authorization is optional but can be useful in
	 certain situations.  For example, in the Installer application, the user is asked to pre-authorize before
	 configuring the installation because it would be a waste of time to let the user proceed through the
	 entire installation setup, only to be denied at the final stage because they weren't the administrator. */
    
	// status = AuthorizationCopyRights(authorizationRef, &rightSet, kAuthorizationEmptyEnvironment, flags, NULL);
    status = errAuthorizationSuccess;
	
    if (status == errAuthorizationSuccess)
    {
        
		
        
        /* Specifying the kAuthorizationFlagDestroyRights causes the granted rights to be destroyed so
		 they can't be shared between sessions and used again.  Rights will automatically timeout by default
		 after 5 minutes, but the timeout value can be changed by editing the file located at /etc/authorization. 
		 The config file gives System Administrators the ability to enforce a stricter security policy, and it's
		 recommended that you test with a zero second timeout enabled to make sure your application continues
		 to behave as expected. */
        
        //AuthorizationFree(authorizationRef, kAuthorizationFlagDestroyRights);
    }
    else
    {
        if(myDebug) fprintf(stderr, "Pre-authorization failed, giving up.\n");
        return kMyAuthorizedCommandInternalError;
    }
    
    return 0;
}
Ejemplo n.º 9
0
bool taskport_auth(void) {
	OSStatus stat;
	AuthorizationItem taskport_item[] = {{"system.privilege.taskport:"}};
	AuthorizationRights rights = {1, taskport_item}, *out_rights = NULL;
	AuthorizationRef author;

	AuthorizationFlags auth_flags = kAuthorizationFlagExtendRights | kAuthorizationFlagPreAuthorize | kAuthorizationFlagInteractionAllowed | (1 << 5);

	stat = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, auth_flags, &author);
	if(stat != errAuthorizationSuccess) {
		return false;
	}

	stat = AuthorizationCopyRights(author, &rights, kAuthorizationEmptyEnvironment, auth_flags, &out_rights);
	if(stat != errAuthorizationSuccess) {
		return false;
	}
	return true;
}
int main(__unused int ac, const char *av[])
{
    uint32_t hostType = AUTHHOST_TYPE_AGENT;
    AuthorizationItem item = { AGENT_HINT_IMMEDIATE_LAUNCH, sizeof(hostType), &hostType, 0 };
    AuthorizationEnvironment hints = { 1, &item };
    const char *hostTypeStr;

    plan_tests(1);

    switch(hostType)
    {
        case AUTHHOST_TYPE_AGENT: hostTypeStr = "SecurityAgent"; break;
        case AUTHHOST_TYPE_PRIVILEGED: hostTypeStr = "authorizationhost"; break;
        default: hostTypeStr = "unknown host type"; break;
    }
    ok_status(AuthorizationCreate(NULL, &hints, kAuthorizationFlagDefaults, NULL), "force immediate agent launch");

    return 0;
}
Ejemplo n.º 11
0
CFDictionaryRef xpcEngineUpdate(CFTypeRef target, uint flags, CFDictionaryRef context)
{
	Message msg("update");
	// target can be NULL, a CFURLRef, a SecRequirementRef, or a CFNumberRef
	if (target) {
		if (CFGetTypeID(target) == CFNumberGetTypeID())
			xpc_dictionary_set_uint64(msg, "rule", cfNumber<int64_t>(CFNumberRef(target)));
		else if (CFGetTypeID(target) == CFURLGetTypeID())
			xpc_dictionary_set_string(msg, "url", cfString(CFURLRef(target)).c_str());
		else if (CFGetTypeID(target) == SecRequirementGetTypeID()) {
			CFRef<CFDataRef> data;
			MacOSError::check(SecRequirementCopyData(SecRequirementRef(target), kSecCSDefaultFlags, &data.aref()));
			xpc_dictionary_set_data(msg, "requirement", CFDataGetBytePtr(data), CFDataGetLength(data));
		} else
			MacOSError::throwMe(errSecCSInvalidObjectRef);
	}
	xpc_dictionary_set_int64(msg, "flags", flags);
	CFRef<CFMutableDictionaryRef> ctx = makeCFMutableDictionary();
	if (context)
		CFDictionaryApplyFunction(context, copyCFDictionary, ctx);
	AuthorizationRef localAuthorization = NULL;
	if (CFDictionaryGetValue(ctx, kSecAssessmentUpdateKeyAuthorization) == NULL) {	// no caller-provided authorization
		MacOSError::check(AuthorizationCreate(NULL, NULL, kAuthorizationFlagDefaults, &localAuthorization));
		AuthorizationExternalForm extForm;
		MacOSError::check(AuthorizationMakeExternalForm(localAuthorization, &extForm));
		CFDictionaryAddValue(ctx, kSecAssessmentUpdateKeyAuthorization, CFTempData(&extForm, sizeof(extForm)));
	}
	CFRef<CFDataRef> contextData = makeCFData(CFDictionaryRef(ctx));
	xpc_dictionary_set_data(msg, "context", CFDataGetBytePtr(contextData), CFDataGetLength(contextData));
	
	msg.send();

	if (localAuthorization)
		AuthorizationFree(localAuthorization, kAuthorizationFlagDefaults);
	
	if (int64_t error = xpc_dictionary_get_int64(msg, "error"))
		MacOSError::throwMe(error);
	
	size_t resultLength;
	const void *resultData = xpc_dictionary_get_data(msg, "result", &resultLength);
	return makeCFDictionaryFrom(resultData, resultLength);
}
Ejemplo n.º 12
0
bool create_symlinks() {
	AuthorizationFlags flags = kAuthorizationFlagDefaults;
	AuthorizationRef ref;

	OSStatus status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, flags, &ref);
	if (status != errAuthorizationSuccess)
		return false;

	AuthorizationItem items = {kAuthorizationRightExecute, 0, NULL, 0};
	AuthorizationRights rights = { 1, &items };
	flags = kAuthorizationFlagDefaults |
		kAuthorizationFlagInteractionAllowed |
		kAuthorizationFlagPreAuthorize |
		kAuthorizationFlagExtendRights;
	status = AuthorizationCopyRights(ref, &rights, NULL, flags, NULL);
	if (status != errAuthorizationSuccess) {
		AuthorizationFree(ref, kAuthorizationFlagDefaults);
		return false;
	}
	std::string bundlePath = mitsuba::__mts_bundlepath();
	std::string path = bundlePath + "/Contents/MacOS/symlinks_install";
	std::ostringstream oss;
	oss << getuid();
	std::string uid = oss.str();
	char *args[] = { const_cast<char *>(bundlePath.c_str()), const_cast<char *>(uid.c_str()), NULL };
	FILE *pipe = NULL;
	flags = kAuthorizationFlagDefaults;
	status = AuthorizationExecuteWithPrivileges(ref, const_cast<char *>(path.c_str()), flags, args, &pipe);
	if (status != errAuthorizationSuccess) {
		AuthorizationFree(ref, kAuthorizationFlagDefaults);
		return false;
	}
	char buffer[128];
	for (;;) {
		int bytesRead = read(fileno(pipe), buffer, sizeof(buffer));
		if (bytesRead<1)
			break;
		write(fileno(stdout), buffer, bytesRead);
	}
	AuthorizationFree(ref, kAuthorizationFlagDefaults);
	return true;
}
Ejemplo n.º 13
0
//private operations
jboolean executeCommandWithRoot(char *tool_path,char **arguments){
    OSStatus myStatus;
    AuthorizationFlags myFlags = kAuthorizationFlagDefaults;              // 1
    AuthorizationRef myAuthorizationRef;                                  // 2
    
    myStatus = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment,  // 3
                                   
                                   myFlags, &myAuthorizationRef);
    
    if (myStatus != errAuthorizationSuccess)
        return myStatus;
    
    AuthorizationItem myItems = {kAuthorizationRightExecute, 0,NULL, 0};
    
    AuthorizationRights myRights = {1, &myItems};                 //
    
    myFlags = kAuthorizationFlagDefaults |                         // 6
    kAuthorizationFlagInteractionAllowed |
    kAuthorizationFlagPreAuthorize |
    kAuthorizationFlagExtendRights;
    
    myStatus = AuthorizationCopyRights (myAuthorizationRef, &myRights, NULL, myFlags, NULL );
    
    if (myStatus == errAuthorizationSuccess){
       
        FILE *myCommunicationsPipe = NULL;
        myFlags = kAuthorizationFlagDefaults;                          // 8
        
        myStatus = AuthorizationExecuteWithPrivileges(myAuthorizationRef, tool_path, myFlags, arguments,&myCommunicationsPipe);
        
        AuthorizationFree (myAuthorizationRef, kAuthorizationFlagDefaults);
        if (myStatus == errAuthorizationSuccess){
            return JNI_TRUE;
        }
        return JNI_FALSE;
        
    }
    
    AuthorizationFree (myAuthorizationRef, kAuthorizationFlagDefaults);
    return JNI_FALSE;
}
Ejemplo n.º 14
0
bool InstallChecker::installPackage( const QString &filePath, bool reducedUI )
{
	QString path = mountPackage( filePath );
	if( path.isEmpty() )
		return false;

	if( reducedUI )
	{
		AuthorizationRef ref;
		OSStatus status = AuthorizationCreate( NULL, kAuthorizationEmptyEnvironment,
			kAuthorizationFlagDefaults, &ref );

		QByteArray conv = path.toUtf8();
		char *args[] = { (char*)"-pkg", conv.data(), (char*)"-target", (char*)"/", NULL };
		FILE *pipe = NULL;
		status = AuthorizationExecuteWithPrivileges( ref, "/usr/sbin/installer",
			kAuthorizationFlagDefaults, args, &pipe );
		bool result = false;
		if( status != errAuthorizationSuccess )
			qWarning() << "Authorization error:" << status;
		else
			result = true;

		if( pipe )
		{
			QFile log;
			log.open( pipe, QFile::ReadOnly );
			qWarning() << log.readAll();
			log.close();
			fclose( pipe );
		}

		status = AuthorizationFree( ref, kAuthorizationFlagDestroyRights );
		QProcess::execute( "hdiutil", QStringList() << "unmount" << path << "-force" );
		return result;
	}
	else
		return !QProcess::execute( "open", QStringList() << "/System/Library/CoreServices/Installer.app" << path );
}
Ejemplo n.º 15
0
//
// Perform update authorization processing.
// Throws an exception if authorization is denied.
//
static void authorizeUpdate(SecAssessmentFlags flags, CFDictionaryRef context)
{
	AuthorizationRef authorization = NULL;
	
	if (context)
		if (CFTypeRef authkey = CFDictionaryGetValue(context, kSecAssessmentUpdateKeyAuthorization))
			if (CFGetTypeID(authkey) == CFDataGetTypeID()) {
				CFDataRef authdata = CFDataRef(authkey);
				MacOSError::check(AuthorizationCreateFromExternalForm((AuthorizationExternalForm *)CFDataGetBytePtr(authdata), &authorization));
			}
	if (authorization == NULL)
		MacOSError::check(AuthorizationCreate(NULL, NULL, kAuthorizationFlagDefaults, &authorization));
	
	AuthorizationItem right[] = {
		{ "com.apple.security.assessment.update", 0, NULL, 0 }
	};
	AuthorizationRights rights = { sizeof(right) / sizeof(right[0]), right };
	MacOSError::check(AuthorizationCopyRights(authorization, &rights, NULL,
		kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed, NULL));
	
	MacOSError::check(AuthorizationFree(authorization, kAuthorizationFlagDefaults));
}
OSStatus EnsureToolInstalled(void)
// Make sure that the tool is installed in the right place, with the right privs, and the right version.
{
	CFURLRef		bundleURL;
	pid_t			toolPID;
	int				status;
	OSStatus		err = noErr;
	const char		*args[] = { kToolPath, "0", "V", NULL };
	char			toolSourcePath[PATH_MAX] = {};
	char			toolInstallerPath[PATH_MAX] = {};

	if (gToolApproved) 
		return noErr;

	// Check version of installed tool
	toolPID = execTool(args);
	if (toolPID > 0)
	{
		waitpid(toolPID, &status, 0);
		if (WIFEXITED(status) && WEXITSTATUS(status) == PRIV_OP_TOOL_VERS)
			return noErr;
	}

	// Locate our in-bundle copy of privop tool
	bundleURL = CFBundleCopyBundleURL(CFBundleGetBundleWithIdentifier(CFSTR("com.apple.preference.bonjour")) );
	if (bundleURL != NULL)
	{
		CFURLGetFileSystemRepresentation(bundleURL, false, (UInt8*) toolSourcePath, sizeof toolSourcePath);
		if (strlcat(toolSourcePath,    "/Contents/Resources/" kToolName,      sizeof toolSourcePath   ) >= sizeof toolSourcePath   ) return(-1);
		CFURLGetFileSystemRepresentation(bundleURL, false, (UInt8*) toolInstallerPath, sizeof toolInstallerPath);
		if (strlcat(toolInstallerPath, "/Contents/Resources/" kToolInstaller, sizeof toolInstallerPath) >= sizeof toolInstallerPath) return(-1);
	}
	else
		return coreFoundationUnknownErr;
	
	// Obtain authorization and run in-bundle copy as root to install it
	{
		AuthorizationItem		aewpRight = { kAuthorizationRightExecute, strlen(toolInstallerPath), toolInstallerPath, 0 };
		AuthorizationItemSet	rights = { 1, &aewpRight };
		AuthorizationRef		authRef;
		
		err = AuthorizationCreate(&rights, (AuthorizationEnvironment*) NULL,
					kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights | 
					kAuthorizationFlagPreAuthorize, &authRef);
		if (err == noErr)
		{
			char *installerargs[] = { toolSourcePath, NULL };
			err = AuthorizationExecuteWithPrivileges(authRef, toolInstallerPath, 0, installerargs, (FILE**) NULL);
			if (err == noErr) {
				int pid = wait(&status);
				if (pid > 0 && WIFEXITED(status)) {
					err = WEXITSTATUS(status);
					if (err == noErr) {
						gToolApproved = true;
					}
				} else {
					err = -1;
				}
			}
			(void) AuthorizationFree(authRef, kAuthorizationFlagDefaults);
		}
	}

	return err;
}
Ejemplo n.º 17
0
FILE * run_tool(const char *if_name, const char *tool_name)
{
	OSStatus auth_status;
	FILE *fp = NULL;
	char *args[] = {NULL, NULL, NULL};
	int ret;
	char path_buffer[256];
	AuthorizationFlags auth_flags;
	AuthorizationRef auth_ref;
	AuthorizationItem auth_items[1];
	AuthorizationRights auth_rights;
	CFBundleRef bundle_ref;
	CFURLRef url_ref;
	CFStringRef path_str;
	CFStringRef tool_name_str;
	char c;

	bundle_ref = CFBundleGetMainBundle();
	if(bundle_ref == NULL) {
		return NULL;
	}

	tool_name_str = CFStringCreateWithCString(NULL, tool_name,
						  kCFStringEncodingUTF8);

	url_ref = CFBundleCopyResourceURL(bundle_ref, tool_name_str,
					 NULL, NULL);
	CFRelease(tool_name_str);

	if(url_ref == NULL) {
		return NULL;
	}

	path_str = CFURLCopyFileSystemPath(url_ref, kCFURLPOSIXPathStyle);
	CFRelease(url_ref);

	if(path_str == NULL) {
		return NULL;
	}

	if(!CFStringGetCString(path_str, path_buffer, sizeof(path_buffer),
			       kCFStringEncodingUTF8)) {
		CFRelease(path_str);
		return NULL;
	}
	CFRelease(path_str);

	args[0] = (char *)tool_name;
	args[1] = (char *)if_name;
  
	auth_flags = kAuthorizationFlagExtendRights |
		kAuthorizationFlagInteractionAllowed |
		kAuthorizationFlagPreAuthorize;
 
	auth_items[0].name = "system.privilege.admin";
	auth_items[0].valueLength = 0;
	auth_items[0].value = NULL;
	auth_items[0].flags = 0;

	auth_rights.count = sizeof (auth_items) / sizeof (auth_items[0]);
	auth_rights.items = auth_items;
  
	auth_status = AuthorizationCreate(&auth_rights,
					  kAuthorizationEmptyEnvironment,
					  auth_flags,
					  &auth_ref);
  
	if (auth_status != errAuthorizationSuccess) {
		fprintf(stderr, "%s: AuthorizationCreate() failed.\n",
			__func__);
		return NULL;
	}

	auth_status = AuthorizationExecuteWithPrivileges(auth_ref,
							 path_buffer,
							 kAuthorizationFlagDefaults,
							 args + 1,
							 &fp);

	if (auth_status != errAuthorizationSuccess) {
		fprintf(stderr, "%s: AuthorizationExecWithPrivileges() failed.\n", 
			__func__);
		return NULL;
	}

	if(fread(&c, 1, 1, fp) != 1) {
	  fclose(fp);
	  return NULL;
	}

	return fp;
}
Ejemplo n.º 18
0
static OSStatus
acquireticket_ui(KLPrincipal inPrincipal,
		 KLLoginOptions inLoginOptions,
		 KLPrincipal *outPrincipal,
		 char **outCredCacheName)
{
    AuthorizationRef auth;
    OSStatus ret;
    char *princ = NULL;
    CFDataRef d = NULL;
    
    LOG_ENTRY();

    if (outPrincipal)
	*outPrincipal = NULL;
    if (outCredCacheName)
	*outCredCacheName = NULL;

    if (inPrincipal) {
	ret = heim_krb5_unparse_name(milcontext, inPrincipal, &princ);
	if (ret)
	    return ret;
    }
    

    ret = AuthorizationCreate(NULL, NULL, kAuthorizationFlagDefaults, &auth);
    if (ret) {
	free(princ);
	return ret;
    }
    
    AuthorizationItem rightItems[1] = { kCoreAuthPanelKerberosRight, 0, NULL, 0 };
    AuthorizationRights rights = { sizeof(rightItems[0])/sizeof(rightItems) , rightItems };
    AuthorizationItem envItems[3];
    AuthorizationEnvironment env = { 0 , envItems };
    AuthorizationFlags authFlags = kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights;

    if (princ) {
	envItems[env.count].name = kCoreAuthPanelKerberosPrincipal;
	envItems[env.count].valueLength = strlen(princ);
	envItems[env.count].value = princ;
	envItems[env.count].flags = 0;
	env.count++;
    }

    if (inLoginOptions && inLoginOptions->opt) {
	CFMutableDictionaryRef dict;

	dict = CFDictionaryCreateMutable(NULL, 1,
					 &kCFTypeDictionaryKeyCallBacks,
					 &kCFTypeDictionaryValueCallBacks);
	if (dict == NULL)
	    goto out;
	
	if (inLoginOptions->opt->renew_life) {
	    CFStringRef t;
	    t = CFStringCreateWithFormat(NULL, 0, CFSTR("%ld"),(long)inLoginOptions->opt->renew_life);
	    CFDictionarySetValue(dict, CFSTR("renewTime"), t);
	    CFRelease(t);
	}

	d = CFPropertyListCreateData(NULL, dict, kCFPropertyListBinaryFormat_v1_0,
				     0, NULL);
	CFRelease(dict);

	envItems[env.count].name = kCoreAuthPanelKerberosOptions;
	envItems[env.count].valueLength = CFDataGetLength(d);
	envItems[env.count].value = (void *)CFDataGetBytePtr(d);
	envItems[env.count].flags = 0;
	env.count++;
    }
    
    ret = AuthorizationCopyRights(auth, &rights, &env, authFlags, NULL);

    if (ret == 0 && outPrincipal) {
	AuthorizationItemSet *info;
	UInt32 i;
	ret = AuthorizationCopyInfo(auth, NULL, &info);
	if (ret)
	    goto out;
	for(i = 0; i < info->count; i++) {
	    if (strcmp(info->items[i].name, "out-principal") == 0) {
		char *str;
		asprintf(&str, "%.*s", (int)info->items[i].valueLength, (char *)info->items[i].value);
		heim_krb5_parse_name(milcontext, str, outPrincipal);
	    } else if (strcmp(info->items[i].name, "out-cache-name") == 0) {
		asprintf(outCredCacheName, "%.*s", (int)info->items[i].valueLength, (char *)info->items[i].value);
	    }
	}
	AuthorizationFreeItemSet(info);
	if (*outPrincipal == NULL)
	    ret = EINVAL;
    }
out:
    if (d)
	CFRelease(d);
    AuthorizationFree(auth, kAuthorizationFlagDestroyRights);
    free(princ);
    return ret;
}
Ejemplo n.º 19
0
int main (int argc, const char * argv[]) {
	
    OSStatus myStatus;
    AuthorizationFlags myFlags = kAuthorizationFlagDefaults;              // 1
    AuthorizationRef myAuthorizationRef;                                  // 2
	
    myStatus = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment,  // 3
								   myFlags, &myAuthorizationRef);
    if (myStatus != errAuthorizationSuccess)
        return myStatus;
	
    do
    {
        {
            AuthorizationItem myItems = {kAuthorizationRightExecute, 0,    // 4
				NULL, 0};
            AuthorizationRights myRights = {1, &myItems};                  // 5
			
            myFlags = kAuthorizationFlagDefaults |                         // 6
			kAuthorizationFlagInteractionAllowed |
			kAuthorizationFlagPreAuthorize |
			kAuthorizationFlagExtendRights;
            myStatus = AuthorizationCopyRights (myAuthorizationRef,       // 7
												&myRights, NULL, myFlags, NULL );
        }
		
        if (myStatus != errAuthorizationSuccess) break;
		
        {
			// Grab the arguent length
			int size = strlen(argv[1]);
			
			// Grab the first argument
			char myToolPath[size];
			strcpy(myToolPath,argv[1]);
			char **myArguments = (char **)&argv[2];
			
            FILE *myCommunicationsPipe = NULL;
            char myReadBuffer[128];
			
            myFlags = kAuthorizationFlagDefaults;                          // 8
            myStatus = AuthorizationExecuteWithPrivileges                  // 9
			(myAuthorizationRef, myToolPath, myFlags, myArguments,
			 &myCommunicationsPipe);
			// Any compile warnings here come from the sample apple code.
            if (myStatus == errAuthorizationSuccess)
                for(;;)
                {
                    int bytesRead = read (fileno (myCommunicationsPipe),
										  myReadBuffer, sizeof (myReadBuffer));
                    if (bytesRead < 1) break;
					write (fileno (stdout), myReadBuffer, bytesRead);
                }
        }
    } while (0);
	
    AuthorizationFree (myAuthorizationRef, kAuthorizationFlagDefaults);    // 10
	
    if (myStatus) printf("Status: %ld\n", myStatus);
    return myStatus;
}
Ejemplo n.º 20
0
int
main(int argc, char **argv)
{
	const char		*command	= argv[0];
	extern int		optind;
	int			opt;
	CFStringRef		current		= NULL;
	int			currentMatched	= 0;
	CFStringRef		newSet		= NULL;	/* set key */
	CFStringRef		newSetUDN	= NULL;	/* user defined name */
	CFStringRef		prefix;
	SCPreferencesRef	prefs;
	CFDictionaryRef		sets;
	CFIndex			nSets;
	const void		**setKeys	= NULL;
	const void		**setVals	= NULL;
	CFIndex			i;

#if	!TARGET_OS_IPHONE
	AuthorizationRef	authorization	= NULL;
	AuthorizationFlags	flags		= kAuthorizationFlagDefaults;
	CFMutableDictionaryRef	options;
	OSStatus		status;
#endif	// !TARGET_OS_IPHONE

	/* process any arguments */

	while ((opt = getopt_long(argc, argv, "dvn", longopts, NULL)) != -1) {
		switch(opt) {
			case 'd':
				_sc_debug = TRUE;
				_sc_log   = FALSE;	/* enable framework logging */
				break;
			case 'v':
				_sc_verbose = TRUE;
				break;
			case 'n':
				apply = FALSE;
				break;
			case '?':
			default :
				usage(command);
		}
	}
	argc -= optind;
	argv += optind;

	prefix = CFStringCreateWithFormat(NULL, NULL, CFSTR("/%@/"), kSCPrefSets);

	if (argc == 1) {
		newSet = CFStringCreateWithCString(NULL, argv[0], kCFStringEncodingMacRoman);

		/* check if a full path to the new "set" was specified */
		if ((CFStringGetLength(newSet) > 0) && CFStringHasPrefix(newSet, prefix)) {
			CFRange			range;
			CFMutableStringRef	str;

			str = CFStringCreateMutableCopy(NULL, 0, newSet);
			CFRelease(newSet);

			CFStringDelete(str, CFRangeMake(0, CFStringGetLength(prefix)));
			newSet = CFStringCreateCopy(NULL, newSet);
			CFRelease(str);

			range = CFStringFind(newSet, CFSTR("/"), 0);
			if (range.location != kCFNotFound) {
				SCPrint(TRUE, stderr, CFSTR("Set \"%@\" not available\n."), newSet);
				exit (1);
			}
		}
	} else {
		newSet = CFRetain(CFSTR(""));
	}

#if	!TARGET_OS_IPHONE
	status = AuthorizationCreate(NULL,
				     kAuthorizationEmptyEnvironment,
				     flags,
				     &authorization);
	if (status != errAuthorizationSuccess) {
		SCPrint(TRUE,
			stderr,
			CFSTR("AuthorizationCreate() failed: status = %d\n"),
			(int)status);
		exit (1);
	}

	options = CFDictionaryCreateMutable(NULL,
					    0,
					    &kCFTypeDictionaryKeyCallBacks,
					    &kCFTypeDictionaryValueCallBacks);
	CFDictionarySetValue(options, kSCPreferencesOptionChangeNetworkSet, kCFBooleanTrue);
	prefs = SCPreferencesCreateWithOptions(NULL, CFSTR("scselect"), NULL, authorization, options);
	CFRelease(options);
	if (prefs == NULL) {
		SCPrint(TRUE, stderr, CFSTR("SCPreferencesCreate() failed\n"));
		exit (1);
	}
#else	// !TARGET_OS_IPHONE
	prefs = SCPreferencesCreate(NULL, CFSTR("scselect"), NULL);
	if (prefs == NULL) {
		SCPrint(TRUE, stderr, CFSTR("SCPreferencesCreate() failed\n"));
		exit (1);
	}
#endif	// !TARGET_OS_IPHONE

	sets = SCPreferencesGetValue(prefs, kSCPrefSets);
	if (sets == NULL) {
		SCPrint(TRUE, stderr, CFSTR("No network sets defined.\n"));
		exit (1);
	}

	current = SCPreferencesGetValue(prefs, kSCPrefCurrentSet);
	if (current != NULL) {
		if (CFStringHasPrefix(current, prefix)) {
			CFMutableStringRef	tmp;

			tmp = CFStringCreateMutableCopy(NULL, 0, current);
			CFStringDelete(tmp, CFRangeMake(0, CFStringGetLength(prefix)));
			current = tmp;
		} else {
			CFRetain(current);
			currentMatched = -1;	/* not prefixed */
		}
	} else {
		current = CFRetain(CFSTR(""));
		currentMatched = -2;	/* not defined */
	}

	nSets = CFDictionaryGetCount(sets);
	if (nSets > 0) {
		setKeys = CFAllocatorAllocate(NULL, nSets * sizeof(CFStringRef), 0);
		setVals = CFAllocatorAllocate(NULL, nSets * sizeof(CFDictionaryRef), 0);
		CFDictionaryGetKeysAndValues(sets, setKeys, setVals);
	}

	/* check for set with matching name */
	for (i = 0; i < nSets; i++) {
		CFStringRef	key  = (CFStringRef)    setKeys[i];
		CFDictionaryRef	dict = (CFDictionaryRef)setVals[i];

		if ((currentMatched >= 0) && CFEqual(key, current)) {
			currentMatched++;
		}

		if (CFEqual(newSet, key)) {
			newSetUDN = CFDictionaryGetValue(dict, kSCPropUserDefinedName);
			if (newSetUDN != NULL) CFRetain(newSetUDN);
			goto found;
		}
	}

	/* check for set with matching user-defined name */
	for (i = 0; i < nSets; i++) {
		CFStringRef	key  = (CFStringRef)    setKeys[i];
		CFDictionaryRef	dict = (CFDictionaryRef)setVals[i];

		newSetUDN = CFDictionaryGetValue(dict, kSCPropUserDefinedName);
		if ((newSetUDN != NULL) && CFEqual(newSet, newSetUDN)) {
			CFRelease(newSet);
			newSet = CFRetain(key);
			CFRetain(newSetUDN);
			goto found;
		}
	}

	if (argc == 1) {
		SCPrint(TRUE, stderr, CFSTR("Set \"%@\" not available.\n"), newSet);
		exit(1);
	}

	SCPrint(TRUE, stdout,
		CFSTR("Defined sets include:%s\n"),
		(currentMatched > 0) ? " (* == current set)" : "");

	for (i = 0; i < nSets; i++) {
		CFStringRef	key  = (CFStringRef)    setKeys[i];
		CFDictionaryRef	dict = (CFDictionaryRef)setVals[i];
		CFStringRef	udn  = CFDictionaryGetValue(dict, kSCPropUserDefinedName);

		SCPrint(TRUE, stdout,
			CFSTR(" %s %@\t(%@)\n"),
			((currentMatched > 0) && CFEqual(key, current)) ? "*" : " ",
			key,
			udn ? udn : CFSTR(""));
	}

	switch (currentMatched) {
		case -2 :
			SCPrint(TRUE, stdout, CFSTR("\nCurrent set not defined.\n"));
			break;
		case -1 :
			SCPrint(TRUE, stdout, CFSTR("\nCurrent set \"%@\" may not be valid\n"), current);
			break;
		case  0 :
			SCPrint(TRUE, stdout, CFSTR("\nCurrent set \"%@\" not valid\n"), current);
			break;
		default :
			break;
	}

	CFRelease(prefix);
	exit (0);

    found :

	CFRelease(current);
	current = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@%@"), prefix, newSet);

	if (!SCPreferencesSetValue(prefs, kSCPrefCurrentSet, current)) {
		SCPrint(TRUE, stderr,
			CFSTR("SCPreferencesSetValue(...,%@,%@) failed: %s\n"),
			kSCPrefCurrentSet,
			current,
			SCErrorString(SCError()));
		exit (1);
	}

	if (!SCPreferencesCommitChanges(prefs)) {
		int	sc_status	= SCError();

		if (sc_status == kSCStatusAccessError) {
			SCPrint(TRUE, stderr,
				CFSTR("Only local console users and administrators can change locations\n"));
			exit (EX_NOPERM);
		} else {
			SCPrint(TRUE, stderr,
				CFSTR("SCPreferencesCommitChanges() failed: %s\n"),
				SCErrorString(sc_status));
			exit (1);
		}
	}

	if (apply) {
		if (!SCPreferencesApplyChanges(prefs)) {
			SCPrint(TRUE, stderr,
				CFSTR("SCPreferencesApplyChanges() failed %s\n"),
				SCErrorString(SCError()));
			exit (1);
		}
	}

	SCPrint(TRUE, stdout,
		CFSTR("%@ updated to %@ (%@)\n"),
		kSCPrefCurrentSet,
		newSet,
		newSetUDN ? newSetUDN : CFSTR(""));

	CFRelease(current);
	CFRelease(newSet);
	if (newSetUDN != NULL)	CFRelease(newSetUDN);
	CFRelease(prefix);
	CFRelease(prefs);

#if	!TARGET_OS_IPHONE
	AuthorizationFree(authorization, kAuthorizationFlagDefaults);
//	AuthorizationFree(authorization, kAuthorizationFlagDestroyRights);
#endif	/* !TARGET_OS_IPHONE */

	exit (0);
	return 0;
}
OSStatus
SecPasswordAction(SecPasswordRef itemRef, CFTypeRef message, UInt32 flags, UInt32 *length, const void **data)
{
    BEGIN_SECAPI

    Password passwordRef = PasswordImpl::required(itemRef);
    
    void *passwordData = NULL;
    UInt32 passwordLength = 0;
	bool gotPassword = false;

    // no flags has no meaning, and there is no apparent default
    assert( flags );
    
    // fail can only be combined with get or new
    assert( (flags & kSecPasswordFail) ? ((flags & kSecPasswordGet) || (flags & kSecPasswordNew)) : true );

    // XXX/cs replace this with our CFString->UTF8 conversion
    const char *messageData = NULL;
    auto_array<char> messageBuffer;
    
    if (message && (CFStringGetTypeID() == CFGetTypeID(message)))
    {
        messageData = CFStringGetCStringPtr(static_cast<CFStringRef>(message), kCFStringEncodingUTF8);

        if (messageData == NULL)
        {
            CFIndex maxLen = CFStringGetMaximumSizeForEncoding(CFStringGetLength(static_cast<CFStringRef>(message)), kCFStringEncodingUTF8) + 1;

            messageBuffer.allocate(maxLen);
            if (CFStringGetCString(static_cast<CFStringRef>(message), messageBuffer.get(), maxLen, kCFStringEncodingUTF8))
                messageData = messageBuffer.get();
        }
    }
    
    if (passwordRef->useKeychain() && !(flags & kSecPasswordNew) && !(flags & kSecPasswordFail))
    {
            // Pull out data and if it's successful return it
            if (flags & kSecPasswordGet)
            {
            
                // XXX/cs if there are unsaved changes this doesn't work
                //        so doing a Get followed by a Get|Set will do the wrong thing
            
                // check mItem whether it's got data
                if (passwordRef->getData(length, data))
                    return errSecSuccess;
            }
            
            // User might cancel here, immediately return that too (it will be thrown)            
    }

    // If we're still here we're not using the keychain or it wasn't there yet
    
    // Do the authorization call to get the password, unless only kSecPasswordSet is specified)
    if ((flags & kSecPasswordNew) || (flags & kSecPasswordGet))
    {
        AuthorizationRef authRef;
        OSStatus status = AuthorizationCreate(NULL,NULL,0,&authRef);
        if (status != errSecSuccess)
        {
            MacOSError::throwMe(status);
        }
        
        AuthorizationItem right = { NULL, 0, NULL, 0 };
        AuthorizationItemSet rightSet = { 1, &right };
        uint32_t reason, tries;
        bool keychain = 0, addToKeychain = 0;

        if (passwordRef->useKeychain())
        {
            keychain = 1;
            addToKeychain = passwordRef->rememberInKeychain();
        }
		else
		{
            keychain = 0;
            addToKeychain = 0;
		}
        
        // Get|Fail conceivable would have it enabled, but since the effect is that it will get overwritten
        // we'll make the user explicitly do it       
        if (flags & kSecPasswordGet)
            addToKeychain = 0; // turn it off for old items that weren't successfully retrieved from the keychain

        if (flags & kSecPasswordFail) // set up retry to reflect failure
        {
	        tries = 1;
            if (flags & kSecPasswordNew)
                reason = 34; // passphraseUnacceptable = 34 passphrase unacceptable for some other reason
            else
                reason = 21; // invalidPassphrase = 21 passphrase was wrong
        }
        else
		{
			reason = 0;
			tries = 0;
		}

        if (flags & kSecPasswordNew) // pick new passphrase
            right.name = "com.apple.builtin.generic-new-passphrase";
        else
            right.name = "com.apple.builtin.generic-unlock";

        bool showPassword = false;
        
        AuthorizationItem envRights[6] = { { AGENT_HINT_RETRY_REASON, sizeof(reason), &reason, 0 },
                                            { AGENT_HINT_TRIES, sizeof(tries), &tries, 0 },
                                            { AGENT_HINT_CUSTOM_PROMPT, messageData ? strlen(messageData) : 0, const_cast<char*>(messageData), 0 },
                                            { AGENT_HINT_ALLOW_SHOW_PASSWORD, showPassword ? strlen("YES") : strlen("NO"), const_cast<char *>(showPassword ? "YES" : "NO"), 0 },
                                            { AGENT_HINT_SHOW_ADD_TO_KEYCHAIN, keychain ? strlen("YES") : strlen("NO"), const_cast<char *>(keychain ? "YES" : "NO"), 0 },
                                            { AGENT_ADD_TO_KEYCHAIN, addToKeychain ? strlen("YES") : strlen("NO"), const_cast<char *>(addToKeychain ? "YES" : "NO"), 0 } };
                                            
        AuthorizationItemSet envSet = { sizeof(envRights) / sizeof(*envRights), envRights };

	    secdebug("SecPassword", "dialog(%s)%s%s%s.", right.name, tries?" retry":"", keychain?" show-add-keychain":"", addToKeychain?" save-to-keychain":"");

        status = AuthorizationCopyRights(authRef, &rightSet, &envSet, kAuthorizationFlagDefaults|kAuthorizationFlagInteractionAllowed|kAuthorizationFlagExtendRights, NULL);
        
        if (status)
        {
            AuthorizationFree(authRef, 0);
            return status;
        }
        
        // if success pull the data
        AuthorizationItemSet *returnedInfo;
        status = AuthorizationCopyInfo(authRef, NULL, &returnedInfo);
        
        if (status)
        {
            AuthorizationFree(authRef, 0);
            
            return status;
        }
        
        if (returnedInfo && (returnedInfo->count > 0))
        {
            for (uint32_t index = 0; index < returnedInfo->count; index++)
            {
                AuthorizationItem &item = returnedInfo->items[index];
                
                if (!strcmp(AGENT_PASSWORD, item.name))
                {
					gotPassword = true;
                    passwordLength = (UInt32)item.valueLength;

                    if (passwordLength)
                    {
                        Allocator &allocator = Allocator::standard();
                        passwordData = allocator.malloc(passwordLength);
                        if (passwordData)
                            memcpy(passwordData, item.value, passwordLength);
                    }
                    
                    if (length)
                        *length = passwordLength;
                    if (data) 
                        *data = passwordData;
						
					secdebug("SecPassword", "Got password (%u,%p).", (unsigned int)passwordLength, passwordData);
                }
                else if (!strcmp(AGENT_ADD_TO_KEYCHAIN, item.name))
                {
                    bool remember = (item.value && item.valueLength == strlen("YES") && !memcmp("YES", static_cast<char *>(item.value), item.valueLength));
					passwordRef->setRememberInKeychain(remember);
					if (remember)
						secdebug("SecPassword", "User wants to add the password to the Keychain.");
                }
            }
        }
        
        AuthorizationFreeItemSet(returnedInfo);
        AuthorizationFree(authRef, 0);
        
    }

    // If we're still here the use gave us his password, store it if keychain is in use
    if (passwordRef->useKeychain())
    {
        if (passwordRef->rememberInKeychain()) {
            if (gotPassword)
				passwordRef->setData(passwordLength, passwordData);
			if (flags & kSecPasswordSet)
            {
				passwordRef->save();
                gotPassword = true;
            }
		}
    }

    if (!gotPassword)
    {
        return errAuthorizationDenied;
    }
    
    END_SECAPI
}
Ejemplo n.º 22
0
bool launcherApplication::Elevate(const StringArray& commandLineArray)
{
#if defined(JUCE_LINUX) || defined(JUCE_BSD)
    if (geteuid() == 0) {
        return true;
    }

    String parameters("--user root /usr/bin/env ");

    const char *var = getenv("DISPLAY");
    if (var) {
        String s("DISPLAY=" + String(var).quoted());
        parameters += s + " ";
    }

    var = getenv("XAUTHORITY");
    if (var) {
        String s("XAUTHORITY=" + String(var).quoted());
        parameters += s + " ";
    }

    String launcher(File::getSpecialLocation(
                File::currentExecutableFile).getFullPathName());
    if (launcher.contains(" ")) {
        launcher = launcher.quoted();
    }

    parameters += String(" ") + launcher;
    for (int i = 0; i < commandLineArray.size(); i++)
    {
        parameters += " ";
        if (commandLineArray[i].contains(" "))
            parameters += commandLineArray[i].quoted();
        else
            parameters += commandLineArray[i];
    }

    File pkexec("/usr/bin/pkexec");
    if (pkexec.exists() && pkexec.startAsProcess(parameters)) {
        quit();
    }

    pkexec = "/usr/local/bin/pkexec";
    if (pkexec.exists() && pkexec.startAsProcess(parameters)) {
        quit();
    }

#elif defined(JUCE_WINDOWS)
    BOOL fIsRunAsAdmin = FALSE;
    DWORD dwError = ERROR_SUCCESS;
    PSID pAdministratorsGroup = NULL;

    SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
    if (!AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,
                DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pAdministratorsGroup)) {
        dwError = GetLastError();
        goto cleanup;
    }

    if (!CheckTokenMembership(NULL, pAdministratorsGroup, &fIsRunAsAdmin)) {
        dwError = GetLastError();
        goto cleanup;
    }

cleanup:
    if (pAdministratorsGroup) {
        FreeSid(pAdministratorsGroup);
        pAdministratorsGroup = NULL;
    }

    if (dwError != ERROR_SUCCESS) {
        throw dwError;
    }

    if (fIsRunAsAdmin) {
        return true;
    }

    TCHAR szPath[MAX_PATH];
    if (!GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath))) {
        dwError = GetLastError();
        throw dwError;
    }

    String commandLine;
    for (int i = 0; i < commandLineArray.size(); i++) {
        if (commandLineArray[i].contains(" ")) {
            commandLine += String("\"") + commandLineArray[i] + String("\"");
        } else {
            commandLine += commandLineArray[i];
        }
        if (i + 1 < commandLineArray.size()) {
            commandLine += " ";
        }
    }

    SHELLEXECUTEINFO sei = { 0 };
    sei.cbSize = sizeof(SHELLEXECUTEINFO);
    sei.lpVerb = _T("runas");
    sei.lpFile = szPath;
    sei.lpParameters = commandLine.toUTF8();
    sei.nShow = SW_NORMAL;
    if (ShellExecuteEx(&sei)) {
        _exit(1);
    }

#elif defined(JUCE_MAC)
    if (geteuid() == 0) {
        return true;
    }

    String launcher(File::getSpecialLocation(
                File::currentExecutableFile).getFullPathName());

    const char * execpath = launcher.toRawUTF8();
    char * args[] = { NULL };

    OSStatus           err;
    AuthorizationRef   ref;
    AuthorizationFlags flags;

    flags = kAuthorizationFlagDefaults;
    err   = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, flags, &ref);
    if ( err != errAuthorizationSuccess ) {
        quit();
    }

    AuthorizationItem    _temp = { kAuthorizationRightExecute, 0, NULL, 0 };
    AuthorizationRights rights = { 1, &_temp };

    flags = kAuthorizationFlagDefaults
          | kAuthorizationFlagInteractionAllowed
          | kAuthorizationFlagPreAuthorize
          | kAuthorizationFlagExtendRights;

    err  = AuthorizationCopyRights(ref, &rights, NULL, flags, NULL);
    if ( err != errAuthorizationSuccess ) {
        AuthorizationFree(ref, kAuthorizationFlagDefaults);
        quit();
    }

    flags = kAuthorizationFlagDefaults;
    err  = AuthorizationExecuteWithPrivileges(ref, execpath, flags, args, NULL);
    AuthorizationFree(ref, kAuthorizationFlagDefaults);

    // Probably overkill.
    if ( err != errAuthorizationSuccess ) {
        quit();
    }
#endif // JUCE_MAC

    return false;
}
Ejemplo n.º 23
0
static AuthorizationRef
IdAuthCreateWithFork(void)
{
   int fds[2] = { -1, -1, };
   pid_t child;
   AuthorizationRef auth = NULL;
   struct {
      Bool success;
      AuthorizationExternalForm ext;
   } data;
   uint8 buf;

   /*
    * XXX One more Apple bug related to thread credentials:
    *     AuthorizationCreate() incorrectly uses process instead of thread
    *     credentials. So for this code to properly work in the VMX for
    *     example, we must do this elaborate fork/handshake dance. Fortunately
    *     this function is only called once very early when a process starts.
    */

   if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0) {
      Warning("%s: socketpair() failed.\n", __func__);
      goto out;
   }

   child = fork();
   if (child < 0) {
      Warning("%s: fork() failed.\n", __func__);
      goto out;
   }

   if (child) {
      size_t rcvd;
      int status;
      pid_t result;

      // Parent: use fds[0]

      // Wait until the child has created its process ref to the auth session.
      for (rcvd = 0; rcvd < sizeof data; ) {
         ssize_t actual;

         actual = read(fds[0], (void *)&data + rcvd, sizeof data - rcvd);
         ASSERT(actual <= sizeof data - rcvd);
         if (actual < 0) {
            ASSERT(errno == EPIPE);
            Warning("%s: parent read() failed because child died.\n",
                    __func__);
            data.success = FALSE;
            break;
         }

         rcvd += actual;
      }

      if (data.success) {
         if (AuthorizationCreateFromExternalForm(&data.ext, &auth)
             != errAuthorizationSuccess) {
            Warning("%s: parent AuthorizationCreateFromExternalForm() "
                    "failed.\n", __func__);
         }
      }

      // Tell the child it can now destroy its process ref to the auth session.
      write(fds[0], &buf, sizeof buf);

      // Reap the child, looping if we get interrupted by a signal.
      do {
         result = waitpid(child, &status, 0);
      } while (result == -1 && errno == EINTR);

      ASSERT_NOT_IMPLEMENTED(result == child);
   } else {
      // Child: use fds[1]

      data.success = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment,
                                         kAuthorizationFlagDefaults, &auth)
                     == errAuthorizationSuccess;
      if (data.success) {
         data.success = AuthorizationMakeExternalForm(auth, &data.ext)
                        == errAuthorizationSuccess;
         if (!data.success) {
            Warning("%s: child AuthorizationMakeExternalForm() failed.\n",
                    __func__);
         }
      } else {
         Warning("%s: child AuthorizationCreate() failed.\n", __func__);
      }

      // Tell the parent it can now create a process ref to the auth session.
      if (write(fds[1], &data, sizeof data) == sizeof data) {
         /*
          * Wait until the child can destroy its process ref to the auth
          * session.
          */

         for (;;) {
            ssize_t actual = read(fds[1], &buf, sizeof buf);

            ASSERT(actual <= sizeof buf);
            if (actual) {
               break;
            }
         }
      }

      /*
       * This implicitly:
       * o Destroys the child process ref to the Authorization session.
       * o Closes fds[0] and fds[1]
       */

      exit(0);
   }

out:
   close(fds[0]);
   close(fds[1]);

   return auth;
}
Ejemplo n.º 24
0
int main(int argc, char *argv[])
{

    // install debug message handler
    qInstallMsgHandler(myMessageOutput);


    //  Gain admin privileges on the Mac
#ifdef Q_WS_MAC
    char myPath[PATH_MAX];
    uint32_t pathSize=sizeof(myPath);

    if(geteuid() != 0) {
        AuthorizationItem adminPriv;
        AuthorizationRights adminRights;
        AuthorizationRef adminRightsRef;
        OSStatus result;
        char myPath[MAXPATHLEN];
        uint32_t pathSize = MAXPATHLEN;
        int childStatus;

        adminPriv.name = kAuthorizationRightExecute;
        adminPriv.valueLength = 0;
        adminPriv.value = NULL;
        adminPriv.flags = 0;

        adminRights.count = 1;
        adminRights.items = &adminPriv;

        result = AuthorizationCreate(&adminRights, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults | kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed, &adminRightsRef);

        if(result != errAuthorizationSuccess) {
            fprintf(stderr, "Couldn't Authenticate: %d\n", result);
            exit(1);
        }

        _NSGetExecutablePath(myPath, &pathSize);
        result = AuthorizationExecuteWithPrivileges(adminRightsRef, myPath, kAuthorizationFlagDefaults, NULL, NULL);
        if(result != errAuthorizationSuccess) {
            fprintf(stderr, "Couldn't execute self: %d\n", result);
        }

        waitpid(-1, &childStatus, NULL);
        exit(0);
    }


    _NSGetExecutablePath(myPath,&pathSize);
    char* slash = strrchr(myPath, '/');
    if(slash!=NULL) {
        *slash = '\0';
    }
#endif // Q_WS_MAC



    QApplication a(argc, argv);
    MainWindow w;
#ifdef Q_WS_MAC
    w.setPath(myPath);
#endif
    w.show();

    return a.exec();
}
Ejemplo n.º 25
0
static int				/* O - 0 if available */
					/*     1 if not available */
					/*    -1 error */
cups_local_auth(http_t *http)		/* I - HTTP connection to server */
{
#if defined(WIN32) || defined(__EMX__)
 /*
  * Currently WIN32 and OS-2 do not support the CUPS server...
  */

  return (1);
#else
  int			pid;		/* Current process ID */
  FILE			*fp;		/* Certificate file */
  char			trc[16],	/* Try Root Certificate parameter */
			filename[1024];	/* Certificate filename */
  _cups_globals_t *cg = _cupsGlobals();	/* Global data */
#  if defined(HAVE_AUTHORIZATION_H)
  OSStatus		status;		/* Status */
  AuthorizationItem	auth_right;	/* Authorization right */
  AuthorizationRights	auth_rights;	/* Authorization rights */
  AuthorizationFlags	auth_flags;	/* Authorization flags */
  AuthorizationExternalForm auth_extrn;	/* Authorization ref external */
  char			auth_key[1024];	/* Buffer */
  char			buffer[1024];	/* Buffer */
#  endif /* HAVE_AUTHORIZATION_H */


  DEBUG_printf(("7cups_local_auth(http=%p) hostaddr=%s, hostname=\"%s\"",
                http, httpAddrString(http->hostaddr, filename, sizeof(filename)), http->hostname));

 /*
  * See if we are accessing localhost...
  */

  if (!httpAddrLocalhost(http->hostaddr) &&
      _cups_strcasecmp(http->hostname, "localhost") != 0)
  {
    DEBUG_puts("8cups_local_auth: Not a local connection!");
    return (1);
  }

#  if defined(HAVE_AUTHORIZATION_H)
 /*
  * Delete any previous authorization reference...
  */

  if (http->auth_ref)
  {
    AuthorizationFree(http->auth_ref, kAuthorizationFlagDefaults);
    http->auth_ref = NULL;
  }

  if (!getenv("GATEWAY_INTERFACE") &&
      httpGetSubField2(http, HTTP_FIELD_WWW_AUTHENTICATE, "authkey",
		       auth_key, sizeof(auth_key)))
  {
    status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment,
				 kAuthorizationFlagDefaults, &http->auth_ref);
    if (status != errAuthorizationSuccess)
    {
      DEBUG_printf(("8cups_local_auth: AuthorizationCreate() returned %d (%s)",
		    (int)status, cssmErrorString(status)));
      return (-1);
    }

    auth_right.name        = auth_key;
    auth_right.valueLength = 0;
    auth_right.value       = NULL;
    auth_right.flags       = 0;

    auth_rights.count = 1;
    auth_rights.items = &auth_right;

    auth_flags = kAuthorizationFlagDefaults |
		 kAuthorizationFlagPreAuthorize |
		 kAuthorizationFlagInteractionAllowed |
		 kAuthorizationFlagExtendRights;

    status = AuthorizationCopyRights(http->auth_ref, &auth_rights,
				     kAuthorizationEmptyEnvironment,
				     auth_flags, NULL);
    if (status == errAuthorizationSuccess)
      status = AuthorizationMakeExternalForm(http->auth_ref, &auth_extrn);

    if (status == errAuthorizationSuccess)
    {
     /*
      * Set the authorization string and return...
      */

      httpEncode64_2(buffer, sizeof(buffer), (void *)&auth_extrn,
		     sizeof(auth_extrn));

      httpSetAuthString(http, "AuthRef", buffer);

      DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"",
		    http->authstring));
      return (0);
    }
    else if (status == errAuthorizationCanceled)
      return (-1);

    DEBUG_printf(("9cups_local_auth: AuthorizationCopyRights() returned %d (%s)",
		  (int)status, cssmErrorString(status)));

  /*
   * Fall through to try certificates...
   */
  }
#  endif /* HAVE_AUTHORIZATION_H */

#  if defined(SO_PEERCRED) && defined(AF_LOCAL)
 /*
  * See if we can authenticate using the peer credentials provided over a
  * domain socket; if so, specify "PeerCred username" as the authentication
  * information...
  */

  if (
#    ifdef HAVE_GSSAPI
      _cups_strncasecmp(http->fields[HTTP_FIELD_WWW_AUTHENTICATE], "Negotiate", 9) &&
#    endif /* HAVE_GSSAPI */
#    ifdef HAVE_AUTHORIZATION_H
      !httpGetSubField2(http, HTTP_FIELD_WWW_AUTHENTICATE, "authkey",
		        auth_key, sizeof(auth_key)) &&
#    endif /* HAVE_AUTHORIZATION_H */
      http->hostaddr->addr.sa_family == AF_LOCAL &&
      !getenv("GATEWAY_INTERFACE"))	/* Not via CGI programs... */
  {
   /*
    * Verify that the current cupsUser() matches the current UID...
    */

    struct passwd	*pwd;		/* Password information */
    const char		*username;	/* Current username */

    username = cupsUser();

    if ((pwd = getpwnam(username)) != NULL && pwd->pw_uid == getuid())
    {
      httpSetAuthString(http, "PeerCred", username);

      DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"",
		    http->authstring));

      return (0);
    }
  }
#  endif /* SO_PEERCRED && AF_LOCAL */

 /*
  * Try opening a certificate file for this PID.  If that fails,
  * try the root certificate...
  */

  pid = getpid();
  snprintf(filename, sizeof(filename), "%s/certs/%d", cg->cups_statedir, pid);
  if ((fp = fopen(filename, "r")) == NULL && pid > 0)
  {
   /*
    * No certificate for this PID; see if we can get the root certificate...
    */

    DEBUG_printf(("9cups_local_auth: Unable to open file %s: %s",
                  filename, strerror(errno)));

#  ifdef HAVE_GSSAPI
    if (!_cups_strncasecmp(http->fields[HTTP_FIELD_WWW_AUTHENTICATE], "Negotiate", 9))
    {
     /*
      * Kerberos required, don't try the root certificate...
      */

      return (1);
    }
#  endif /* HAVE_GSSAPI */

#  ifdef HAVE_AUTHORIZATION_H
    if (httpGetSubField2(http, HTTP_FIELD_WWW_AUTHENTICATE, "authkey",
		         auth_key, sizeof(auth_key)))
    {
     /*
      * Don't use the root certificate as a replacement for an authkey...
      */

      return (1);
    }
#  endif /* HAVE_AUTHORIZATION_H */
    if (!httpGetSubField2(http, HTTP_FIELD_WWW_AUTHENTICATE, "trc", trc,
	                  sizeof(trc)))
    {
     /*
      * Scheduler doesn't want us to use the root certificate...
      */

      return (1);
    }

    snprintf(filename, sizeof(filename), "%s/certs/0", cg->cups_statedir);
    fp = fopen(filename, "r");
  }

  if (fp)
  {
   /*
    * Read the certificate from the file...
    */

    char	certificate[33],	/* Certificate string */
		*certptr;		/* Pointer to certificate string */

    certptr = fgets(certificate, sizeof(certificate), fp);
    fclose(fp);

    if (certptr)
    {
     /*
      * Set the authorization string and return...
      */

      httpSetAuthString(http, "Local", certificate);

      DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"",
		    http->authstring));

      return (0);
    }
  }

  return (1);
#endif /* WIN32 || __EMX__ */
}
Ejemplo n.º 26
-1
bool OSXPlatform::run_privileged()
{
  AuthorizationRef   auth = NULL;
  OSStatus           err;
  AuthorizationFlags flags;
  
  const char *path = this->path().c_str();
  
  flags = kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed;
  
  err = AuthorizationCreate(NULL, NULL, flags, &auth);          
  if (err != errAuthorizationSuccess)
    throw runtime_error(str(boost::format("osx_run_privileged: AuthorizationCreate() failed: %ld.") % (long int)err));
  
  char *args[] = { "--fix-permissions", NULL };
  
  err = AuthorizationExecuteWithPrivileges(auth, path, kAuthorizationFlagDefaults, args, NULL);
  AuthorizationFree(auth, kAuthorizationFlagDefaults);
  if (err == errAuthorizationCanceled)
    return false;
  else if (err != errAuthorizationSuccess)
    throw runtime_error(str(boost::format("osx_run_privileged: AuthorizationExecuteWithPrivileges() failed: %ld") % (long int)err));
  else {
    int child;
    wait(&child);
  }
  
  return true;
}
Ejemplo n.º 27
-1
bool JsExtender::cleanTokenCache() const
{
#ifdef Q_OS_MAC
	AuthorizationRef ref;
	AuthorizationCreate( 0, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &ref );
	char *args[] = { (char*)"-c", (char*)"/bin/rm -rf /var/db/TokenCache/tokens/com.apple.tokend.opensc*", 0 };
	FILE *pipe = 0;
	OSStatus status = AuthorizationExecuteWithPrivileges( ref, "/bin/sh",
		kAuthorizationFlagDefaults, args, &pipe );

	if( pipe )
		fclose( pipe );

	AuthorizationFree( ref, kAuthorizationFlagDestroyRights );
	return status == errAuthorizationSuccess;
#else
	return true;
#endif
}