Exemplo n.º 1
0
int main(int argc, char **argv)
{
  char mypath[MAXPATHLEN];
  unsigned long mypath_size= sizeof(mypath);
  OSStatus status;
  AuthorizationRef auth;
  int bytesRead;
  BrokerCtlCommand command;
  
  if (_NSGetExecutablePath(mypath, &mypath_size) < 0)
  {
    DEBUG("could not get my path");
    exit(BrokerCtlCommandInternalError);
  }
  
  AuthorizationExternalForm extAuth;
    
  // read bytestream with Auth data
  if (read(0, &extAuth, sizeof(extAuth)) != sizeof(extAuth))
    exit(BrokerCtlCommandInternalError);
    
  // bytestream --*poof*--> auth
  if (AuthorizationCreateFromExternalForm(&extAuth, &auth))
    exit(BrokerCtlCommandInternalError);
    
  // if we're not being ran as root, spawn a copy that will make us suid root
  if (geteuid() != 0)
  {
    printf("I'm not suided\n");
    exit(-1);
  }
  
  /* Read a command object from stdin. */
  bytesRead = read(0, &command, sizeof(BrokerCtlCommand));
  
  if (bytesRead == sizeof(BrokerCtlCommand))
  {
    const char *rightName = rightNameForCommand(&command);
    AuthorizationItem right = { rightName, 0, NULL, 0 } ;
    AuthorizationRights rights = { 1, &right };
    AuthorizationFlags flags = kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed
    | kAuthorizationFlagExtendRights;
    
    if (status = AuthorizationCopyRights(auth, &rights, kAuthorizationEmptyEnvironment, flags, NULL))
    {
      DEBUG("failed authorization in helper: %ld.\n", status);
      exit(BrokerCtlCommandAuthFailed);
    }
    
    /* Peform the requested command */
    if (!performCommand(&command))
      exit(BrokerCtlCommandOperationFailed);
  }
  else
  {
    exit(BrokerCtlCommandChildError);
  }
  
  return BrokerCtlCommandSuccess;
}
Exemplo 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;
}
Exemplo n.º 3
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;
}
Exemplo n.º 4
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;
}
Exemplo 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;
}
Exemplo n.º 6
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
    
}
Exemplo n.º 7
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;
}
Exemplo n.º 8
0
Bool
Id_AuthCheck(char const *right,                // IN
             char const *localizedDescription, // IN: UTF-8
             Bool showDialogIfNeeded)          // IN
{
   AuthorizationRef auth;
   AuthorizationItem rightsItems[1] = { { 0 } };
   AuthorizationRights rights;
   AuthorizationItem environmentItems[1] = { { 0 } };
   AuthorizationEnvironment environmentWithDescription = { 0 };
   const AuthorizationEnvironment *environment =
                                              kAuthorizationEmptyEnvironment;

   auth = IdAuthGet();
   if (!auth) {
      return FALSE;
   }

   rightsItems[0].name = right;
   rights.items = rightsItems;
   rights.count = ARRAYSIZE(rightsItems);

   /*
    * By default, the API displays a dialog saying "APPLICATIONNAME
    * requires that you type your password" (if you're an admin; the
    * message is different if you're not).
    *
    * If the localized description is present, the API uses that
    * description and appends a space followed by the above string.
    */

   if (localizedDescription) {
      environmentItems[0].name = kAuthorizationEnvironmentPrompt;
      environmentItems[0].valueLength = strlen(localizedDescription);
      environmentItems[0].value = (void *)localizedDescription;
      environmentWithDescription.items = environmentItems;
      environmentWithDescription.count = ARRAYSIZE(environmentItems);
      environment = &environmentWithDescription;
   }

   /*
    * TODO: Is this actually thread-safe when multiple threads act on
    * the same AuthorizationRef?  Apple's documentation doesn't
    * actually say whether it is or is not.
    */

   return AuthorizationCopyRights(auth, &rights, environment,
             (showDialogIfNeeded ? kAuthorizationFlagInteractionAllowed |
                                   kAuthorizationFlagDefaults :
                                   kAuthorizationFlagDefaults) |
             kAuthorizationFlagExtendRights,
             NULL) == errAuthorizationSuccess;
}
Exemplo 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;
}
Exemplo n.º 10
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;
}
Exemplo n.º 11
0
inline Bool16 OSXAuthenticate(StrPtrLen *keyStrPtr)
{
#if __MacOSX__
//  Authorization: AuthRef QWxhZGRpbjpvcGVuIHNlc2FtZQ==
    Bool16 result = false;
    
    if (keyStrPtr == NULL || keyStrPtr->Len  == 0)
        return result;
    
    char *encodedKey = keyStrPtr->GetAsCString();
    OSCharArrayDeleter encodedKeyDeleter(encodedKey);

    char *decodedKey = NEW char[Base64decode_len(encodedKey) + 1];
    OSCharArrayDeleter decodedKeyDeleter(decodedKey);

    (void) Base64decode(decodedKey, encodedKey);

    AuthorizationExternalForm  *receivedExtFormPtr = (AuthorizationExternalForm  *) decodedKey;
    AuthorizationRef  receivedAuthorization;
    OSStatus status = AuthorizationCreateFromExternalForm(receivedExtFormPtr, &receivedAuthorization);

    if (status != errAuthorizationSuccess) 
        return result;
        
    status = AuthorizationCopyRights(receivedAuthorization, &sRightSet, kAuthorizationEmptyEnvironment, kAuthorizationFlagExtendRights , NULL);
    if (status == errAuthorizationSuccess)
    {
        result = true;
    }

    AuthorizationFree(receivedAuthorization, kAuthorizationFlagDestroyRights);

    return result;

#else

    return false;

#endif

}
Exemplo n.º 12
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;
}
Exemplo n.º 13
0
STATIC Boolean
authorization_is_valid(const void * auth_data, int auth_data_length)
{
    AuthorizationExternalForm *	auth_ext_p;
    AuthorizationRef 		authorization;
    AuthorizationFlags		flags;
    AuthorizationItem		item;
    AuthorizationRights		rights;
    OSStatus			status;
    
    if (auth_data == NULL
	|| auth_data_length != sizeof(auth_ext_p->bytes)) {
	syslog(LOG_ERR, "eapolcfg_auth: authorization NULL/invalid size");
	return (FALSE);
    }
    auth_ext_p = (AuthorizationExternalForm *)auth_data;
    status = AuthorizationCreateFromExternalForm(auth_ext_p, &authorization);
    if (status != errAuthorizationSuccess) {
	syslog(LOG_ERR, "eapolcfg_auth: authorization is invalid (%d)",
	       (int)status);
	return (FALSE);
    }
    rights.count = 1;
    rights.items = &item;
    item.name = "system.preferences";
    item.value = NULL;
    item.valueLength = 0;
    item.flags = 0;
    flags = kAuthorizationFlagDefaults;
    flags |= kAuthorizationFlagExtendRights;
    flags |= kAuthorizationFlagInteractionAllowed;
    status = AuthorizationCopyRights(authorization,
				     &rights,
				     kAuthorizationEmptyEnvironment,
				     flags,
				     NULL);
    AuthorizationFree(authorization, kAuthorizationFlagDefaults);
    return (status == errAuthorizationSuccess);
}
Exemplo n.º 14
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));
}
Exemplo n.º 15
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;
}
Exemplo n.º 16
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__ */
}
Exemplo n.º 17
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;
}
Exemplo n.º 18
0
DAReturn DAAuthorize( DASessionRef        session,
                      _DAAuthorizeOptions options,
                      DADiskRef           disk,
                      uid_t               userUID,
                      gid_t               userGID,
                      const char *        right )
{
    DAReturn status;

    status = kDAReturnNotPrivileged;

    if ( status )
    {
        if ( ( options & _kDAAuthorizeOptionIsOwner ) )
        {
            uid_t diskUID;

            diskUID = DADiskGetUserUID( disk );

            if ( diskUID == userUID )
            {
                status = kDAReturnSuccess;
            }
        }
    }

    if ( status )
    {
        AuthorizationRef authorization;

        authorization = DASessionGetAuthorization( session );

        if ( authorization )
        {
            AuthorizationFlags  flags;
            AuthorizationItem   item;
            char *              name;
            AuthorizationRights rights;

            flags = kAuthorizationFlagExtendRights;

            if ( ( options & _kDAAuthorizeOptionAuthenticateAdministrator ) )
            {
                flags |= kAuthorizationFlagInteractionAllowed;

                asprintf( &name, "system.volume.workgroup.%s", right );
            }
            else
            {
                if ( DADiskGetDescription( disk, kDADiskDescriptionVolumeNetworkKey ) == kCFBooleanTrue )
                {
                    asprintf( &name, "system.volume.network.%s", right );
                }
                else
                {
                    CFTypeRef object;

                    object = DADiskGetDescription( disk, kDADiskDescriptionDeviceProtocolKey );

                    if ( object && CFEqual( object, CFSTR( kIOPropertyPhysicalInterconnectTypeVirtual ) ) )
                    {
                        asprintf( &name, "system.volume.virtual.%s", right );
                    }
                    else
                    {
                        if ( DADiskGetDescription( disk, kDADiskDescriptionMediaRemovableKey ) == kCFBooleanTrue )
                        {
                            if ( DADiskGetDescription( disk, kDADiskDescriptionMediaTypeKey ) )
                            {
                                asprintf( &name, "system.volume.optical.%s", right );
                            }
                            else
                            {
                                asprintf( &name, "system.volume.removable.%s", right );
                            }
                        }
                        else
                        {
                            if ( DADiskGetDescription( disk, kDADiskDescriptionDeviceInternalKey ) == kCFBooleanTrue )
                            {
                                asprintf( &name, "system.volume.internal.%s", right );
                            }
                            else
                            {
                                asprintf( &name, "system.volume.external.%s", right );
                            }
                        }
                    }
                }
            }

            if ( name )
            {
                item.flags       = 0;
                item.name        = name;
                item.value       = NULL;
                item.valueLength = 0;

                rights.count = 1;
                rights.items = &item;

                status = AuthorizationCopyRights( authorization, &rights, NULL, flags, NULL );

                if ( status )
                {
                    status = kDAReturnNotPrivileged;
                }

                free( name );
            }
        }
    }

    return status;
}
Exemplo n.º 19
0
int
main(int argc, char *argv[])
{
    OSStatus status;
    AuthorizationRef auth;
    char *path;
    struct stat statbuf;
    char *typeAsString;
    
    AuthorizationExternalForm extAuth;
    
    // Is this process running as root?
    if (geteuid() != 0) {
        fprintf(stderr, "Not running as root\n");
        exit(-1);
    }
    
    // Was there one argument?
    if (argc != 2) {
        fprintf(stderr, "Usage: remove_statter <dir>\n");
        exit(-1);
    }
    
    // Get the path
    path = argv[1];
    
    // Read the Authorization "byte blob" from our input pipe. 
    if (fread(&extAuth, sizeof(extAuth), 1, stdin) != 1) {
        fprintf(stderr, "Unable to read authorization\n");
        exit(-1);
    }
    
    // Restore the externalized Authorization back to an AuthorizationRef 
        if (AuthorizationCreateFromExternalForm(&extAuth, &auth)) {
            fprintf(stderr, "Unable to parse authorization data\n");
            exit(-1);
        }
    
    // Create the rights structure
    AuthorizationItem right = { RIGHT, 0, NULL, 0 };
    AuthorizationRights rights = { 1, &right };
    AuthorizationFlags flags = kAuthorizationFlagDefaults | 
        kAuthorizationFlagExtendRights;
    
    fprintf(stderr, "Tool authorizing right %s for command.\n", RIGHT);
    
    // Check the authorization
    if (status = AuthorizationCopyRights(auth, &rights, 
                                         kAuthorizationEmptyEnvironment, flags, NULL)) {
        fprintf(stderr, "Tool failed authorization: %ld.\n", 
                status);
        exit(-1);
    }
    // Stat the path
    if (stat(path, &statbuf)) {
        fprintf(stderr, "Unable to stat %s", path);
        exit(-1);
    }
    
    // Write out stat info
    if (S_ISDIR(statbuf.st_mode))
        typeAsString = "NSFileTypeDirectory";
    else
        typeAsString = "NSFileTypeRegular";
    
    fprintf(stdout, "%s\n%lu", typeAsString, (unsigned long)statbuf.st_size);
    
    
    
    
    fclose(stdout);
    
    // Terminate
    exit(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
}
Exemplo n.º 21
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;
}
Exemplo n.º 22
0
__private_extern__ DAReturn _DAAuthorize( DASessionRef session, _DAAuthorizeOptions options, DADiskRef disk, const char * right )
{
    DAReturn status;

    status = kDAReturnNotPrivileged;

    if ( status )
    {
        if ( ( options & _kDAAuthorizeOptionIsOwner ) )
        {
            uid_t diskUID;

            status = _DAServerDiskGetUserUID( _DADiskGetSessionID( disk ), _DADiskGetID( disk ), &diskUID );

            if ( status )
            {
                return status;
            }

            status = kDAReturnNotPrivileged;

            if ( diskUID == geteuid( ) )
            {
                status = kDAReturnSuccess;
            }
        }
    }

    if ( status )
    {
        AuthorizationRef authorization;

        authorization = _DASessionGetAuthorization( session );

        if ( authorization )
        {
            CFDictionaryRef description;

            description = DADiskCopyDescription( disk );

            if ( description )
            {
                AuthorizationFlags  flags;
                AuthorizationItem   item;
                char *              name;
                AuthorizationRights rights;

                flags = kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed | kAuthorizationFlagPreAuthorize;

                {
                    CFTypeRef object;

                    object = CFDictionaryGetValue( description, kDADiskDescriptionDeviceProtocolKey );

                    if ( object && CFEqual( object, CFSTR( kIOPropertyPhysicalInterconnectTypeVirtual ) ) )
                    {
                        asprintf( &name, "system.volume.virtual.%s", right );
                    }
                    else
                    {
                        if ( CFDictionaryGetValue( description, kDADiskDescriptionMediaRemovableKey ) == kCFBooleanTrue )
                        {
                            asprintf( &name, "system.volume.removable.%s", right );
                        }
                        else
                        {
                            if ( CFDictionaryGetValue( description, kDADiskDescriptionDeviceInternalKey ) == kCFBooleanTrue )
                            {
                                asprintf( &name, "system.volume.internal.%s", right );
                            }
                            else
                            {
                                asprintf( &name, "system.volume.external.%s", right );
                            }
                        }
                    }
                }

                if ( name )
                {
                    item.flags       = 0;
                    item.name        = name;
                    item.value       = NULL;
                    item.valueLength = 0;

                    rights.count = 1;
                    rights.items = &item;

                    status = AuthorizationCopyRights( authorization, &rights, NULL, flags, NULL ); 

                    if ( status )
                    {
                        status = kDAReturnNotPrivileged;
                    }

                    free( name );
                }

                CFRelease( description );
            }
        }
    }

    return status;
}