Exemplo n.º 1
0
static void ExecAsRootMac(const QString & cmd, char * const * argv)
{
    //execute
#ifdef Q_OS_MAC
    AuthorizationRef & ra = GetAuth();
    OSStatus res = AuthorizationExecuteWithPrivileges(ra,
         cmd.toStdString().c_str()	//myToolPath
         , kAuthorizationFlagDefaults,
         argv									//myArguments
         , NULL);							// pipes

    // handle misterious errors with auth service
    for (int k = 1; k < 6 && errAuthorizationToolEnvironmentError == res; ++k)		// 1500ms  total
    {
        int ms = k * 100;
        log::logt("Auth - got errAuthorizationToolEnvironmentError, sleep " + QString::number(ms) + "ms");
        QThread::msleep(ms);
        res = AuthorizationExecuteWithPrivileges(ra,
                 cmd.toStdString().c_str()	//myToolPath
                 , kAuthorizationFlagDefaults,
                 argv									//myArguments
                 , NULL);							// pipes
    }

    if (res != errAuthorizationSuccess)
        throw std::runtime_error(("AuthorizationExecuteWithPrivileges() fails with result: "
            + QString::number(res) + " cmd = " + cmd).toStdString());
#endif	// Q_OS_MAC
}
Exemplo n.º 2
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.º 3
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.º 4
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.º 5
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.º 6
0
OSStatus DoPrivilegedExec(const char *pathToTool, char *arg1, char *arg2, char *arg3, char *arg4, char *arg5, char *arg6) {
    short               i;
    char                *args[8];
    OSStatus            err;
    FILE                *ioPipe = NULL;
    char                *p, junk[256];

    err = GetAuthorization();
    if (err != noErr) {
        if (err == errAuthorizationCanceled)
            return err;
        ShowSecurityError("GetAuthorization returned error %d", err);
    } else {
        for (i=0; i<5; i++) {       // Retry 5 times if error
            args[0] = arg1;
            args[1] = arg2;
            args[2] = arg3;
            args[3] = arg4;
            args[4] = arg5;
            args[5] = arg6;
            args[6] = NULL;

            err = AuthorizationExecuteWithPrivileges (gOurAuthRef, pathToTool, 0, args, &ioPipe);
            if (ioPipe) {
                // We use the pipe to signal us when the command has completed
                do {
                    p = fgets(junk, sizeof(junk), ioPipe);
                } while (p);
                
                fclose (ioPipe);
            }

            // AuthorizationExecuteWithPrivileges() does a fork() and so 
            // leaves a zombie process.  Clear these so we don't exceed 
            // the system-imposed limit of processes per user (MAXUPRC).
            while (waitpid(-1, 0, WNOHANG) > 0);
#if 0
            if (strcmp(arg2, "-R") == 0)
                SleepTicks(DELAY_TICKS_R);
            else
                SleepTicks(DELAY_TICKS);
#endif
            if (err == noErr)
                break;
        }
    }
    if (err != noErr)
        ShowSecurityError("\"%s %s %s %s %s %s\" returned error %d", pathToTool, 
                            arg1 ? arg1 : "", arg2 ? arg2 : "", arg3 ? arg3 : "", 
                            arg4 ? arg4 : "", arg5 ? arg5 : "", err);

       return err;
}
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.º 8
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.º 9
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 );
}
Exemplo n.º 10
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();
}
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;
}
Exemplo n.º 12
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;
}
    const AuthorizationFlags flags = kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed
        | kAuthorizationFlagPreAuthorize | kAuthorizationFlagExtendRights;

    status = AuthorizationCopyRights(authorizationRef, &rights, kAuthorizationEmptyEnvironment,
        flags, 0);
    if (status != errAuthorizationSuccess)
        return false;

    QVector<char *> args;
    QVector<QByteArray> utf8Args;
    foreach (const QString &argument, arguments) {
        utf8Args.push_back(argument.toUtf8());
        args.push_back(utf8Args.last().data());
    }
    args.push_back(0);

    const QByteArray utf8Program = program.toUtf8();
    status = AuthorizationExecuteWithPrivileges(authorizationRef, utf8Program.data(),
        kAuthorizationFlagDefaults, args.data(), 0);

    AuthorizationFree(authorizationRef, kAuthorizationFlagDestroyRights);
    return status == errAuthorizationSuccess;
}

bool AdminAuthorization::hasAdminRights()
{
    return geteuid() == 0;
}

} // namespace QInstaller
Exemplo n.º 14
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.º 15
-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;
}
Exemplo n.º 16
-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
}