int get_username_and_domain(os_event *event)
{
	int result = 0;
	DWORD user_length = 0;
	DWORD domain_length = 0;
	SID_NAME_USE account_type;
	LPTSTR StringSid = NULL;

	/* Try to convert SID to a string. This isn't necessary to make
	 * things work but it is nice to have for error and debug logging.
	 */
	if (!ConvertSidToStringSid(event->uid, &StringSid))
	{
		debug1(
			"%s: WARN: Could not convert SID to string which returned (%lu)",
			ARGV0,
			GetLastError()
		);

		StringSid = "unknown";
	}

	debug1(
		"%s: DEBUG: Performing a LookupAccountSid() on (%s)",
		ARGV0,
		StringSid
	);

	/* Make initial call to get buffer size */
	result = LookupAccountSid(
		NULL,
		event->uid,
		NULL,
		&user_length,
		NULL,
		&domain_length,
		&account_type
	);

	if (result == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
	{
		if ((event->user = calloc(user_length, sizeof(char))) == NULL)
		{
			log2file(
				"%s: ERROR: Could not lookup SID (%s) due to calloc() failure on user which returned [(%d)-(%s)]",
				ARGV0,
				StringSid,
				errno,
				strerror(errno)
			);

			goto error;
		}

		if ((event->domain = calloc(domain_length, sizeof (char))) == NULL)
		{
			log2file(
				"%s: ERROR: Could not lookup SID (%s) due to calloc() failure on domain which returned [(%d)-(%s)]",
				ARGV0,
				StringSid,
				errno,
				strerror(errno)
			);

			goto error;
		}

		result = LookupAccountSid(
			NULL,
			event->uid,
			event->user,
			&user_length,
			event->domain,
			&domain_length,
			&account_type
		);

		if (result == FALSE)
		{
			log2file(
				"%s: ERROR: Could not LookupAccountSid() for (%s) which returned (%lu)",
				ARGV0,
				StringSid,
				GetLastError()
			);

			goto error;
		}
	}

	LocalFree(StringSid);

	/* success */
	return(1);

error:
	event->user = NULL;
	event->domain = NULL;
	LocalFree(StringSid);

	return(0);
}
예제 #2
0
/**
* @brief Enumerate all the events in the result set.
* @param eventHandle A handle to an event.
*
* @return returns Print event status.
*/
DWORD EventLogReader::PrintEvent(EVT_HANDLE eventHandle)
{
    EVT_HANDLE context = nullptr;
    PEVT_VARIANT renderedValues = nullptr;
    DWORD status = ERROR_SUCCESS;
    do
    {
        // Identify the components of the event that you want to render. In this case,
        // render the system section of the event.
        context = EvtCreateRenderContext(0, nullptr, EvtRenderContextSystem);
        if (context == nullptr)
        {
            status = GetLastError();
            break;
        }
        // When you render the user data or system section of the event, you must specify
        // the EvtRenderEventValues flag. The function returns an array of variant values
        // for each element in the user data or system section of the event. For user data
        // or event data, the values are returned in the same order as the elements are
        // defined in the event. For system data, the values are returned in the order defined
        // in the EVT_SYSTEM_PROPERTY_ID enumeration.
        DWORD bufferSize = 0;
        DWORD bufferUsed = 0;
        DWORD propertyCount = 0;
        if (!EvtRender(context, eventHandle, EvtRenderEventValues, bufferSize, renderedValues, &bufferUsed, &propertyCount))
        {
            status = GetLastError();
            if (status == ERROR_INSUFFICIENT_BUFFER)
            {
                bufferSize = bufferUsed;
                renderedValues = (PEVT_VARIANT)malloc(bufferSize);
                if (renderedValues != nullptr)
                {
                    EvtRender(context, eventHandle, EvtRenderEventValues, bufferSize, renderedValues, &bufferUsed, &propertyCount);
                    status = GetLastError();
                }
                else
                {
                    status = ERROR_OUTOFMEMORY;
                    break;
                }
            }
            if (status != ERROR_SUCCESS)
                break;
        }
        std::map<std::string, std::string> eventData;

        std::wstring tempBuf = (renderedValues[EvtSystemProviderName].StringVal) ? renderedValues[EvtSystemProviderName].StringVal : L"";
        eventData["providername"] = base::wstring_to_string(tempBuf);
        if (renderedValues[EvtSystemProviderGuid].GuidVal != nullptr)
        {
            WCHAR guid[50] = {0};
            StringFromGUID2(*(renderedValues[EvtSystemProviderGuid].GuidVal), guid, sizeof(guid) / sizeof(WCHAR));
            eventData["providerguid"] = base::wstring_to_string(guid);
        }

        DWORD eventId = renderedValues[EvtSystemEventID].UInt16Val;
        if (renderedValues[EvtSystemQualifiers].Type == EvtVarTypeNull)
            eventId = MAKELONG(renderedValues[EvtSystemEventID].UInt16Val, renderedValues[EvtSystemQualifiers].UInt16Val);
        char buf[1024] = { 0 };
        snprintf(buf, sizeof(buf), "%lu", eventId);
        eventData["eventid"] = buf;

        snprintf(buf, sizeof(buf), "%u", (renderedValues[EvtSystemVersion].Type == EvtVarTypeNull) ? 0 : renderedValues[EvtSystemVersion].ByteVal);
        eventData["version"] = buf;

        snprintf(buf, sizeof(buf), "%u", (renderedValues[EvtSystemLevel].Type == EvtVarTypeNull) ? 0 : renderedValues[EvtSystemLevel].ByteVal);
        eventData["level"] = buf;

        snprintf(buf, sizeof(buf), "%hu", (renderedValues[EvtSystemTask].Type == EvtVarTypeNull) ? 0 : renderedValues[EvtSystemTask].ByteVal);
        eventData["task"] = buf;

        snprintf(buf, sizeof(buf), "%u", (renderedValues[EvtSystemOpcode].Type == EvtVarTypeNull) ? 0 : renderedValues[EvtSystemOpcode].UInt16Val);
        eventData["opcode"] = buf;

        snprintf(buf, sizeof(buf), "%0x%I64x", (renderedValues[EvtSystemKeywords].Type == EvtVarTypeNull) ? 0 : renderedValues[EvtSystemOpcode].UInt64Val);
        eventData["keywords"] = buf;

        ULONGLONG ullTimeStamp = renderedValues[EvtSystemTimeCreated].FileTimeVal;
        FILETIME ft;
        ft.dwHighDateTime = (DWORD)((ullTimeStamp >> 32) & 0xFFFFFFFF);
        ft.dwLowDateTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
        SYSTEMTIME st;
        FileTimeToSystemTime(&ft, &st);
        ULONGLONG ullNanoseconds = (ullTimeStamp % 10000000) * 100; // Display nanoseconds instead of milliseconds for higher resolution
        snprintf(buf, sizeof(buf), "%02d/%02d/%02d %02d:%02d:%02d.%I64u", st.wMonth, st.wDay, st.wYear, st.wHour, st.wMinute, st.wSecond, ullNanoseconds);
        eventData["timecreated"] = buf;

        snprintf(buf, sizeof(buf), "%I64u", renderedValues[EvtSystemEventRecordId].UInt64Val);
        eventData["eventrecordid"] = buf;

        if (renderedValues[EvtSystemActivityID].Type != EvtVarTypeNull)
        {
            WCHAR guid[50] = { 0 };
            StringFromGUID2(*(renderedValues[EvtSystemActivityID].GuidVal), guid, sizeof(guid) / sizeof(WCHAR));;
            eventData["activityid"] = base::wstring_to_string(guid);
        }

        if (renderedValues[EvtSystemRelatedActivityID].Type != EvtVarTypeNull)
        {
            WCHAR guid[50] = { 0 };
            StringFromGUID2(*(renderedValues[EvtSystemRelatedActivityID].GuidVal), guid, sizeof(guid) / sizeof(WCHAR));;
            eventData["relatedactivityid"] = base::wstring_to_string(guid);
        }

        snprintf(buf, sizeof(buf), "%lu", renderedValues[EvtSystemProcessID].UInt32Val);
        eventData["processid"] = buf;

        snprintf(buf, sizeof(buf), "%lu", renderedValues[EvtSystemThreadID].UInt32Val);
        eventData["threadid"] = buf;

        tempBuf = (renderedValues[EvtSystemChannel].Type == EvtVarTypeNull) ? renderedValues[EvtSystemChannel].StringVal : L"";
        eventData["channel"] = base::wstring_to_string(tempBuf);

        eventData["computer"] = base::wstring_to_string(renderedValues[EvtSystemComputer].StringVal);

        if (renderedValues[EvtSystemUserID].Type != EvtVarTypeNull)
        {
            LPWSTR pwsSid = nullptr;
            if (ConvertSidToStringSid(renderedValues[EvtSystemUserID].SidVal, &pwsSid))
            {
                eventData["secuserid"] = base::wstring_to_string(pwsSid);
                LocalFree(pwsSid);
            }
        }
        // Get the handle to the provider's metadata that contains the message strings.
        EVT_HANDLE providerMetadata = EvtOpenPublisherMetadata(nullptr, renderedValues[EvtSystemProviderName].StringVal, nullptr, 0, 0);
        if (providerMetadata == nullptr)
            break;
        eventData["message"] = GetMessageString(providerMetadata, eventHandle);
        _printResultsCallback(eventData);
    } while (false);

    if (context)
        EvtClose(context);
    if (renderedValues)
        free(renderedValues);
    return status;
}
예제 #3
0
void CALLBACK kuhl_m_vault_list_descItem_PINLogonOrPicturePasswordOrBiometric(const VAULT_GUID_STRING * pGuidString, PVOID enumItem, PVOID getItem, BOOL is8)
{
	PVAULT_ITEM_8 enumItem8 = (PVAULT_ITEM_8) enumItem, getItem8 = (PVAULT_ITEM_8) getItem;
	PWSTR name, domain, sid, bgPath = NULL;
	UNICODE_STRING uString;
	DWORD i, dwError, szNeeded;
	PVAULT_PICTURE_PASSWORD_ELEMENT pElements;
	PVAULT_BIOMETRIC_ELEMENT bElements;
	PWCHAR bufferStart;
	HKEY hPicturePassword, hUserPicturePassword;

	if(enumItem8->Identity && (enumItem8->Identity->Type == ElementType_ByteArray))
	{
		if(kull_m_token_getNameDomainFromSID((PSID) enumItem8->Identity->data.ByteArray.Value, &name, &domain, NULL))
		{
			kprintf(L"\t\tUser            : %s\\%s\n", domain, name);
			LocalFree(name);
			LocalFree(domain);
		} else PRINT_ERROR_AUTO(L"kull_m_token_getNameDomainFromSID");

		if(pGuidString->guid.Data1 == 0x0b4b8a12b)
		{
			dwError = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Authentication\\LogonUI\\PicturePassword", 0, KEY_ENUMERATE_SUB_KEYS, &hPicturePassword);
			if(dwError == STATUS_SUCCESS)
			{
				if(ConvertSidToStringSid((PSID) enumItem8->Identity->data.ByteArray.Value, &sid))
				{
					dwError = RegOpenKeyEx(hPicturePassword, sid, 0, KEY_QUERY_VALUE, &hUserPicturePassword);
					if(dwError == STATUS_SUCCESS)
					{
						dwError = RegQueryValueEx(hUserPicturePassword, L"bgPath", NULL, NULL, NULL, &szNeeded);
						if(dwError == STATUS_SUCCESS)
						{
							if(bgPath = (PWSTR) LocalAlloc(LPTR, szNeeded))
							{
								dwError = RegQueryValueEx(hUserPicturePassword, L"bgPath", NULL, NULL, (LPBYTE) bgPath, &szNeeded);
								if(dwError != STATUS_SUCCESS)
								{
									PRINT_ERROR(L"RegQueryValueEx 2 : %08x\n", dwError);
									bgPath = (PWSTR) LocalFree(bgPath);
								}
							}
						}
						else PRINT_ERROR(L"RegQueryValueEx 1 : %08x\n", dwError);
						RegCloseKey(hUserPicturePassword);
					}
					else PRINT_ERROR(L"RegOpenKeyEx SID : %08x\n", dwError);
					LocalFree(sid);
				}
				else PRINT_ERROR_AUTO(L"ConvertSidToStringSid");
				RegCloseKey(hPicturePassword);
			}
			else PRINT_ERROR(L"RegOpenKeyEx PicturePassword : %08x\n", dwError);
		}
	}

	if(getItem8 && getItem8->Authenticator && (getItem8->Authenticator->Type == ElementType_ByteArray))
	{
		uString.Length = uString.MaximumLength = (USHORT) getItem8->Authenticator->data.ByteArray.Length;
		uString.Buffer = (PWSTR) getItem8->Authenticator->data.ByteArray.Value;
		kprintf(L"\t\tPassword        : "******"%s", uString.Buffer);
		else 
			kull_m_string_wprintf_hex(uString.Buffer, uString.Length, 1);
		kprintf(L"\n");
	}

	if(enumItem8->Properties && (enumItem8->cbProperties > 0) && enumItem8->Properties + 0)
	{
		switch(pGuidString->guid.Data1)
		{
		case 0x0b2e033f5:	// pin
			if((enumItem8->Properties + 0)->Type == ElementType_UnsignedShort)
				kprintf(L"\t\tPIN Code        : %04hu\n", (enumItem8->Properties + 0)->data.UnsignedShort);
			break;
		case 0x0b4b8a12b:	// picture
			if((enumItem8->Properties + 0)->Type == ElementType_ByteArray)
			{
				pElements = (PVAULT_PICTURE_PASSWORD_ELEMENT) (enumItem8->Properties + 0)->data.ByteArray.Value;
				if(bgPath)
				{
					kprintf(L"\t\tBackground path : %s\n", bgPath);
					LocalFree(bgPath);
				}
				kprintf(L"\t\tPicture password (grid is 150*100)\n");

				for(i = 0; i < 3; i++)
				{
					kprintf(L"\t\t [%u] ", i);
					switch(pElements[i].Type)
					{
					case PP_Point:
						kprintf(L"point  (x = %3u ; y = %3u)", pElements[i].point.coord.x, pElements[i].point.coord.y);
						break;
					case PP_Circle:
						kprintf(L"circle (x = %3u ; y = %3u ; r = %3u) - %s", pElements[i].circle.coord.x, pElements[i].circle.coord.y, pElements[i].circle.size, (pElements[i].circle.clockwise ? L"clockwise" : L"anticlockwise"));
						break;
					case PP_Line:
						kprintf(L"line   (x = %3u ; y = %3u) -> (x = %3u ; y = %3u)", pElements[i].line.start.x, pElements[i].line.start.y, pElements[i].line.end.x, pElements[i].line.end.y);
						break;
					default:
						kprintf(L"%u\n", pElements[i].Type);
					}
					kprintf(L"\n");
				}
			}
			break;
		case 0x0fec87291:	// biometric
			if((enumItem8->Properties + 0)->Type == ElementType_ByteArray)
			{
				bElements = (PVAULT_BIOMETRIC_ELEMENT) (enumItem8->Properties + 0)->data.ByteArray.Value;
				bufferStart = (PWCHAR) ((PBYTE) bElements + bElements->headersize);
				kprintf(L"\t\tProperty        : ");
				if(bElements->domainnameLength > 1)
					kprintf(L"%.*s\\", bElements->domainnameLength - 1, bufferStart + bElements->usernameLength);
				if(bElements->usernameLength > 1)
					kprintf(L"%.*s", bElements->usernameLength - 1, bufferStart);
				kprintf(L"\n");
			}
			break;
		default:
			kprintf(L"todo ?\n");
		}
	}
}
예제 #4
0
파일: expand_path.c 프로젝트: aosm/Heimdal
/*
 *  Expand a %{USERID} token
 *
 *  The %{USERID} token expands to the string representation of the
 *  user's SID.  The user account that will be used is the account
 *  corresponding to the current thread's security token.  This means
 *  that:
 *
 *  - If the current thread token has the anonymous impersonation
 *    level, the call will fail.
 *
 *  - If the current thread is impersonating a token at
 *    SecurityIdentification level the call will fail.
 *
 */
static int
_expand_userid(krb5_context context, PTYPE param, const char *postfix, char **ret)
{
    int rv = EINVAL;
    HANDLE hThread = NULL;
    HANDLE hToken = NULL;
    PTOKEN_OWNER pOwner = NULL;
    DWORD len = 0;
    LPTSTR strSid = NULL;

    hThread = GetCurrentThread();

    if (!OpenThreadToken(hThread, TOKEN_QUERY,
			 FALSE,	/* Open the thread token as the
				   current thread user. */
			 &hToken)) {

	DWORD le = GetLastError();

	if (le == ERROR_NO_TOKEN) {
	    HANDLE hProcess = GetCurrentProcess();

	    le = 0;
	    if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken))
		le = GetLastError();
	}

	if (le != 0) {
	    if (context)
		krb5_set_error_message(context, rv,
				       "Can't open thread token (GLE=%d)", le);
	    goto _exit;
	}
    }

    if (!GetTokenInformation(hToken, TokenOwner, NULL, 0, &len)) {
	if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
	    if (context)
		krb5_set_error_message(context, rv,
				       "Unexpected error reading token information (GLE=%d)",
				       GetLastError());
	    goto _exit;
	}

	if (len == 0) {
	    if (context)
		krb5_set_error_message(context, rv,
				      "GetTokenInformation() returned truncated buffer");
	    goto _exit;
	}

	pOwner = malloc(len);
	if (pOwner == NULL) {
	    if (context)
		krb5_set_error_message(context, rv, "Out of memory");
	    goto _exit;
	}
    } else {
	if (context)
	    krb5_set_error_message(context, rv, "GetTokenInformation() returned truncated buffer");
	goto _exit;
    }

    if (!GetTokenInformation(hToken, TokenOwner, pOwner, len, &len)) {
	if (context)
	    krb5_set_error_message(context, rv, "GetTokenInformation() failed. GLE=%d", GetLastError());
	goto _exit;
    }

    if (!ConvertSidToStringSid(pOwner->Owner, &strSid)) {
	if (context)
	    krb5_set_error_message(context, rv, "Can't convert SID to string. GLE=%d", GetLastError());
	goto _exit;
    }

    *ret = strdup(strSid);
    if (*ret == NULL && context)
	krb5_set_error_message(context, rv, "Out of memory");

    rv = 0;

 _exit:
    if (hToken != NULL)
	CloseHandle(hToken);

    if (pOwner != NULL)
	free (pOwner);

    if (strSid != NULL)
	LocalFree(strSid);

    return rv;
}
예제 #5
0
JNIEXPORT void JNICALL
Java_org_apache_harmony_auth_module_NTSystem_load
(JNIEnv * jenv, jobject thiz)
{
	DWORD i; /* tmp */

	DWORD dwError = -1; /* presume unknown error */
	LPCSTR errMsg = NULL;
	DWORD dwSaveError = -1;

	HANDLE hUser = INVALID_HANDLE_VALUE;
	HANDLE iToken= INVALID_HANDLE_VALUE;

	LPVOID lpUserData = NULL, lpGroupData = NULL, lpAllGroupsData = NULL;
	LPSTR lpStr0 = NULL, lpStr1 = NULL, lpStr2 = NULL;
	LPSTR lpUserSid = NULL, lpDomainName = NULL;
	PSID domainSid = NULL;

	SID_IDENTIFIER_AUTHORITY sia = SECURITY_NT_AUTHORITY;

	TOKEN_USER * ptu = NULL;
	PSID userSid = NULL;

	jclass jkl = NULL;
	jmethodID ctor = NULL;

	jstring jstrSid = NULL;
	jstring jstrUser = NULL;
	jstring jstrDomain = NULL;
	jobject obj = NULL;

	jstring jstrDomainSid = NULL;

	PTOKEN_PRIMARY_GROUP ptpg = NULL;
	PSID groupSid = NULL;

	jclass jklassPrimaryGroup = NULL;
	jobject jobj = NULL;

	PTOKEN_GROUPS ptgs = NULL;

	jclass klassGroup = NULL;
	jmethodID groupCtor3 = NULL;
	jmethodID groupCtor1 = NULL;
	jobjectArray jgroups = NULL;

	jobject jobj1 = NULL;

	//
	// Get the token for the user currently running this Thread
	//
	if( !OpenThreadToken(GetCurrentThread(), TOKEN_QUERY|TOKEN_DUPLICATE, TRUE, &hUser) ) {
		// failed to open thread token. well, let's try process' one
		if( !OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &hUser) ) {
			errMsg = "Unable to obtain user token";
			goto exit;
		}
	}

	//
	// Obtain the User's info
	//
	if( NULL == (lpUserData = (TOKEN_USER*)QueryInfo(jenv, hUser, TokenUser)) ) {
		errMsg = "Unable to obtain user's token info";
		goto exit;
	}

	ptu = (TOKEN_USER*)lpUserData;

	if( !IsValidSid(ptu->User.Sid) ) {
		errMsg = "Got invalid user's SID";
		goto exit;
	}

	userSid = ptu->User.Sid;

	ConvertSidToStringSid(userSid, &lpStr0);
	lpUserSid = lpStr0;
	lpStr0 = NULL;

	//
    // step +n:  Retrieve user name and domain name basing on user's SID.
	//
	if( !GetInfo(jenv, userSid, &lpStr0, &lpStr1) ) {
		errMsg = "Unable to retrieve user's name and domain";
		goto exit;
	};

	jkl = (*jenv)->FindClass (jenv, "org/apache/harmony/auth/NTSidUserPrincipal");
	if( NULL == jkl || (*jenv)->ExceptionCheck (jenv) ) {
		errMsg = "Could not find class NTSidUserPrincipal";
		goto exit;
	}
	ctor = (*jenv)->GetMethodID (jenv, jkl, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
	if( NULL == ctor || (*jenv)->ExceptionCheck (jenv) ) {
		errMsg = "Could not find ctor at NTSidUserPrincipal class";
		goto exit;
	}

	jstrSid = (*jenv)->NewStringUTF (jenv, lpUserSid);
	jstrUser = (*jenv)->NewStringUTF (jenv, lpStr0);
	jstrDomain = (*jenv)->NewStringUTF (jenv, lpStr1);
	obj = (*jenv)->NewObject (jenv, jkl, ctor, jstrSid, jstrUser, jstrDomain);
	if( (*jenv)->ExceptionCheck (jenv) ) {
		goto exit;
	}
	(*jenv)->SetObjectField (jenv, thiz, jf_user, obj);
	if( (*jenv)->ExceptionCheck (jenv) ) {
		goto exit;
	}
	
	LocalFree(lpStr0); lpStr0 = NULL;
	lpDomainName = lpStr1; 
	lpStr1 = NULL;

	//
	// Step +1: Obtain domain SID
	//
	if( !AllocateAndInitializeSid(
		&sia, 4, 
		*GetSidSubAuthority(userSid, 0), 
		*GetSidSubAuthority(userSid, 1), 
		*GetSidSubAuthority(userSid, 2),
		*GetSidSubAuthority(userSid, 3), 
		0, 0, 0, 0, 
		&domainSid)) {

		errMsg = "Unable to allocate domain SID";
		goto exit;
	}

	if( !IsValidSid(domainSid) ) {
		errMsg = "Got invalid domain SID";
		goto exit;
	}

	ConvertSidToStringSid(domainSid, &lpStr0);

	jstrDomainSid = (*jenv)->NewStringUTF (jenv, lpStr0);
	(*jenv)->SetObjectField (jenv, thiz, jf_domainSid, jstrDomainSid);
	if( (*jenv)->ExceptionCheck (jenv) ) {
		goto exit;
	}
	LocalFree(lpStr0); lpStr0 = NULL;

	//
	// step +1: get primary group sid
	//
	if( NULL == (lpGroupData = QueryInfo(jenv, hUser, TokenPrimaryGroup)) ) {
		errMsg = "Unable to get primary group";
		goto exit;
	};

	ptpg = (PTOKEN_PRIMARY_GROUP)lpGroupData;
	groupSid = ptpg->PrimaryGroup;

	if( !IsValidSid(groupSid) ) {
		errMsg = "Got invalid primary groups' SID";
		goto exit;
	}

	if( !GetInfo(jenv, groupSid, &lpStr0, &lpStr1) ) {
		errMsg = "Unable to get primary group's info";
		goto exit;
	}
	ConvertSidToStringSid(groupSid, &lpStr2);

	jklassPrimaryGroup = (*jenv)->FindClass (jenv, "org/apache/harmony/auth/NTSidPrimaryGroupPrincipal");
	if( NULL == jklassPrimaryGroup || (*jenv)->ExceptionCheck (jenv) ) {
		errMsg = "Could not find class NTSidPrimaryGroupPrincipal";
		goto exit;
	}

	ctor = (*jenv)->GetMethodID (jenv, jklassPrimaryGroup, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
	if( NULL == ctor ) {
		errMsg = "Could not find appropriate ctor at NTSidPrimaryGroupPrincipal";
		goto exit;
	}

	jobj = (*jenv)->NewObject (jenv, jklassPrimaryGroup, ctor, 
		(*jenv)->NewStringUTF (jenv, lpStr2), (*jenv)->NewStringUTF (jenv, lpStr0), (*jenv)->NewStringUTF (jenv, lpStr1));

	LocalFree(lpStr0); lpStr0 = NULL;
	LocalFree(lpStr1); lpStr1 = NULL;
	LocalFree(lpStr2); lpStr2 = NULL;


	if( (*jenv)->ExceptionCheck (jenv) ) {
		goto exit;
	}
	(*jenv)->SetObjectField (jenv, thiz, jf_mainGroup, jobj);

	//
	// step +1: get groups
	//
	if( NULL== (lpAllGroupsData = QueryInfo(jenv, hUser, TokenGroups)) ) {
		errMsg = "Unable to query user's groups";
		goto exit;
	}

	ptgs = (PTOKEN_GROUPS)lpAllGroupsData;

	klassGroup = (*jenv)->FindClass (jenv, "org/apache/harmony/auth/NTSidGroupPrincipal");
	if( NULL == klassGroup || (*jenv)->ExceptionCheck (jenv) ) {
		errMsg = "Could not find NTSidGroupPrincipal";
		goto exit;
	};

	groupCtor3 = (*jenv)->GetMethodID (jenv, klassGroup, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
	if( NULL == groupCtor3 || (*jenv)->ExceptionCheck (jenv) ) {
		errMsg = "Could not find appropriate ctor with 3 Strings at NTSidGroupPrincipal";
		goto exit;
	};
	groupCtor1 = (*jenv)->GetMethodID (jenv, klassGroup, "<init>", "(Ljava/lang/String;)V");
	if( NULL == groupCtor1 || (*jenv)->ExceptionCheck (jenv) ) {
		errMsg = "Could not find appropriate ctor at NTSidGroupPrincipal";
		goto exit;
	};

	// allocate an array 
	jgroups = (*jenv)->NewObjectArray (jenv, ptgs->GroupCount, klassGroup, NULL);

	if( NULL == jgroups || (*jenv)->ExceptionCheck (jenv) ) {
		errMsg = "Could not create array of NTSidGroupPrincipal";
		goto exit;
	};

	for( i=0; i<ptgs->GroupCount; i++ ) {

		ConvertSidToStringSid(ptgs->Groups[i].Sid, &lpStr2);

		if( !GetInfo(jenv, ptgs->Groups[i].Sid, &lpStr0, &lpStr1) ) {
			jobj1 = (*jenv)->NewObject (jenv, klassGroup, groupCtor1, (*jenv)->NewStringUTF (jenv, lpStr2));
			//printf("SET_FIELD: %d] Simple Group: %s\n", i, lpStr2 );
		}
		else {
			jobj1 = (*jenv)->NewObject (jenv, klassGroup, groupCtor3, 
				(*jenv)->NewStringUTF (jenv, lpStr2), (*jenv)->NewStringUTF (jenv, lpStr0), (*jenv)->NewStringUTF (jenv, lpStr1));
//			printf("SET_FIELD: %d] Group: %s@%s \n\t %s\n", i, lpStr0, lpStr1, lpStr2 );
		}
		if( NULL != lpStr0 ) { LocalFree(lpStr0); lpStr0 = NULL; }
		if( NULL != lpStr1 ) { LocalFree(lpStr1); lpStr1 = NULL; }
		if( NULL != lpStr2 ) { LocalFree(lpStr2); lpStr2 = NULL; }
		if( NULL == jobj1 || (*jenv)->ExceptionCheck (jenv) ) {
			goto exit;
		}
		(*jenv)->SetObjectArrayElement (jenv, jgroups, i, jobj1);
		if( (*jenv)->ExceptionCheck (jenv) ) {
			goto exit;
		}
	};
	(*jenv)->SetObjectField (jenv, thiz, jf_groups, jgroups);
	if( (*jenv)->ExceptionCheck (jenv) ) {
		goto exit;
	}

	//
	// step +1: get itoken
	//

	//FIXME: on NT 'SecurityImpersonation'  is not supported. 
	// Check whether we support NT - just to be sure.
	if (!DuplicateToken (hUser, SecurityImpersonation, &iToken)) {
		errMsg = "Unable to duplicate impersonation token";
		goto exit;
	};

	// printf("_SET_FIELD: iToken: %d \n", ((long)iToken) );
	(*jenv)->SetLongField (jenv, thiz, jf_token, ((jlong)iToken));
	if( (*jenv)->ExceptionCheck (jenv) ) {
		goto exit;
	}

	dwError = 0;
exit:
	dwSaveError = GetLastError();

	if( NULL != lpUserData )		LocalFree(lpUserData);
	if( NULL != lpGroupData )		LocalFree(lpGroupData);
	if( NULL != lpAllGroupsData )	LocalFree(lpAllGroupsData);
	if( NULL != lpStr0 )			LocalFree(lpStr0);
	if( NULL != lpStr1 )			LocalFree(lpStr1);
	if( NULL != lpStr2 )			LocalFree(lpStr2);
	if( NULL != lpUserSid )			LocalFree(lpUserSid);
	if( NULL != lpDomainName)		LocalFree(lpDomainName);
	//
	if( NULL != domainSid )			FreeSid(domainSid);

	if( INVALID_HANDLE_VALUE != hUser ) CloseHandle(hUser);

	if( (*jenv)->ExceptionCheck (jenv) ) {
		(*jenv)->ExceptionDescribe (jenv);
	}
	else {
		if( (0 != dwError) || (NULL!=errMsg) ) {
			if( dwError == -1 ) {
				dwError = dwSaveError;
			}
			error((LPVOID)jenv, (LPCSTR)errMsg, dwError);
		}
	}
	return;
}
예제 #6
0
/* returns TRUE if a user profile was destroyed; otherwise, FALSE. 
It's private because it does not change the state of the profile 
object, so even though the profile object may think it is loaded,
in reality, it's completely gone. This is directly remedied by 
the code surrounding it, at its invocation. */
BOOL
OwnerProfile::destroy () const {

    dprintf ( D_FULLDEBUG, "In OwnerProfile::destroy()\n" );

    DWORD       last_error      = 0;
    priv_state  priv            = PRIV_UNKNOWN;
    PSID        user_sid        = NULL;
    LPSTR       user_sid_string = NULL;
    BOOL        got_user_sid    = FALSE,
                got_sid_string  = FALSE,
                profile_deleted = FALSE,
                ok              = FALSE;

    __try {

        /* we must do the following as condor */
        priv = set_condor_priv ();

        /* load the user's SID */
        got_user_sid = LoadUserSid ( 
            user_token_, 
            &user_sid );

        dprintf ( 
            D_FULLDEBUG, 
            "UserProfile::destroy: Loading %s's SID "
            "%s. (last-error = %u)\n", 
            user_name_,
            got_user_sid ? "succeeded" : "failed", 
            got_user_sid ? 0 : GetLastError () );

        if ( !got_user_sid ) {
            __leave;
        }

        /* convert the SID to a string */
        got_sid_string = ConvertSidToStringSid (
            user_sid,
            &user_sid_string );

        dprintf ( 
            D_FULLDEBUG, 
            "UserProfile::destroy: Converting SID to a string "
            "%s. (last-error = %u)\n", 
            got_sid_string ? "succeeded" : "failed", 
            got_sid_string ? 0 : GetLastError () );
        
        if ( !got_sid_string ) {
            __leave;
        }

        /* let Windows remove the profile for us */
        profile_deleted = DeleteProfile ( 
            user_sid_string,
            profile_directory_,
            NULL /* local computer */ );

        dprintf ( 
            D_FULLDEBUG, 
            "UserProfile::destroy: Removing %s's profile "
            "directory %s. (last-error = %u)\n", 
            user_name_,
            profile_deleted ? "succeeded" : "failed", 
            profile_deleted ? 0 : GetLastError () );
        
        if ( !profile_deleted ) {
            __leave;
        }

#if 0
        /* just make sure we have the profile's directory */
        if ( NULL == profile_directory_ ) {
            __leave;
        }

        /* if we have have a profile directory, let's blow it away */
        profile_deleted = 
            CondorRemoveDirectory ( profile_directory_ );

        dprintf ( 
            D_FULLDEBUG, 
            "UserProfile::destroy: Removing %s's profile "
            "directory %s. (last-error = %u)\n", 
            user_name_,
            profile_deleted ? "succeeded" : "failed", 
            profile_deleted ? 0 : GetLastError () );

        if ( !profile_deleted ) {
            __leave;
        }
#endif

        /* if we got here, all is well */
        ok = TRUE;
    
    }
    __finally {

        /* return to previous privilege level */
        set_priv ( priv );

        if ( user_sid ) {
            UnloadUserSid ( user_sid );
        }
        if ( user_sid_string ) {
            LocalFree ( user_sid_string );
        }

    }

    return ok;

}
예제 #7
0
void CreateNamespaceForUser(LPCWSTR account_name)
{
  BYTE sid_bytes[MAX_SID_SIZE];
  WCHAR domain[256];
  SID_NAME_USE name_use;
  DWORD sid_size = MAX_SID_SIZE;
  DWORD domain_size = _countof(domain);

  if (!LookupAccountName(nullptr, account_name, (PSID)sid_bytes, &sid_size, domain, &domain_size, &name_use))
  {
    printf("[ERROR] getting SId for account %ls: %d\n", account_name, GetLastError());
    return;
  }

  LPWSTR sid_str;
  ConvertSidToStringSid((PSID)sid_bytes, &sid_str);

  std::wstring boundary_name = L"IEUser_";
  boundary_name += sid_str;
  boundary_name += L"_MicrosoftEdge";

  BoundaryDescriptor boundry;
  if (!boundry.Initialize(boundary_name.c_str()))
  {
    printf("[ERROR] initializing boundary descriptor: %d\n", GetLastError());
    return;
  }

  PSECURITY_DESCRIPTOR psd;
  ULONG sd_size = 0;
  std::wstring sddl = L"D:(A;OICI;GA;;;WD)(A;OICI;GA;;;AC)(A;OICI;GA;;;WD)(A;OICI;GA;;;S-1-0-0)";
  sddl += L"(A;OICI;GA;;;" + GetCurrentUserSid() + L")";
  sddl += L"(A;OICI;GA;;;" + GetCurrentLogonSid() + L")";
  sddl += L"S:(ML;OICI;NW;;;S-1-16-0)";

  if (!ConvertStringSecurityDescriptorToSecurityDescriptor(sddl.c_str(), SDDL_REVISION_1, &psd, &sd_size))
  {
    printf("[ERROR] converting SDDL: %d\n", GetLastError());
    return;
  }
  std::unique_ptr<void, LocalFreeDeleter> sd_buf(psd);

  SECURITY_ATTRIBUTES secattr = {};
  secattr.nLength = sizeof(secattr);
  secattr.lpSecurityDescriptor = psd;

  private_namespace ns(CreatePrivateNamespace(&secattr, boundry.boundry_desc(), boundary_name.c_str()));
  if (!ns)
  {
    printf("[ERROR] creating private namespace - %ls: %d\n", boundary_name.c_str(), GetLastError());
    return;
  }

  printf("[SUCCESS] Created Namespace %ls, start Edge as other user\n", boundary_name.c_str());
  
  std::wstring section_name = boundary_name + L"\\!PrivacIE!SharedMem!Settings";

  while (true)
  {
    HANDLE hMapping = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, section_name.c_str());
    if (hMapping)
    {
      printf("[SUCCESS] Opened other user's !PrivacIE!SharedMem!Settings section for write access\n");
      return;
    }
    Sleep(1000);
  }
}
예제 #8
0
int main(int argc, char * argv[]) {


	COLUMNLIST *columnList = NULL;
	COLUMNLIST *listHead = (COLUMNLIST *)malloc(sizeof(COLUMNLIST));

	ANCESTORSLIST *ancestorsList = (ANCESTORSLIST *)malloc(sizeof(ANCESTORSLIST));

	int PDNT, DNT, RDNtyp;
	wchar_t* DN = L"toto";
	wchar_t Name[256];

	JET_ERR err;
	JET_INSTANCE instance = JET_instanceNil;
	JET_SESID sesid;
	JET_DBID dbid;
	JET_TABLEID tableid ;


	JET_COLUMNDEF _columndefid;
	JET_COLUMNDEF _columndeftype;
	JET_COLUMNDEF _columndeftypecol;
	JET_COLUMNDEF _columndefname;
	JET_COLUMNDEF _columndefobjid;

	JET_COLUMNDEF *columndefid = &_columndefid;
	JET_COLUMNDEF *columndeftype = &_columndeftype;
	JET_COLUMNDEF *columndeftypecol = &_columndeftypecol;
	JET_COLUMNDEF *columndefname = &_columndefname;
	JET_COLUMNDEF *columndefobjid = &_columndefobjid;

	unsigned long a,b,c,d,e;
	long bufferid[16];
	char buffertype[256];
	char buffertypecol[8];
	char buffername[NAME_SIZE];
	long bufferobjid[8];

	//Actually max buffer size should depend on the page size but it doesn't. Further investigation required.
	unsigned char jetBuffer[JET_BUFFER_SIZE];
	unsigned long jetSize;

	char *baseName = argv[2];
	char *targetTable;
	char *tableName;
	unsigned int datatableId = 0xffffffff;
	unsigned int i;

	FILE *dump;
	char dumpFileName[64];
	//SYSTEMTIME lt;

	RPC_WSTR Guid = NULL;

	LPWSTR stringSid = NULL;
	long long sd_id = 0;

	listHead->next = NULL;
	columnList = listHead;

	ancestorsList->prev = NULL;
	ancestorsList->DN = L"";
	ancestorsList->DNT = 2;

	if( argc < 3)
		PrintUsage();

	if(!strcmp(argv[1],"ad") || !strcmp(argv[1],"sid") || !strcmp(argv[1],"att") || !strcmp(argv[1],"cat") || !strcmp(argv[1],"users"))
		targetTable = "datatable";
	else if(!strcmp(argv[1],"ace"))
		targetTable = "sd_table";
	else
		PrintUsage();

	if(!strcmp(argv[1],"sid"))
	{
		printf("To dump Exchange Mailbox security descriptors, \nenter the ATT value for your specific Exchange Schema:\n(msDS-IntId value for msExchMailboxSecurityDescriptor, \nfound in 'esent_dump att' results)\n");
		printf("Otherwise just input anything and press enter\n");
		scanf_s("%s",&exchangeMailboxSDCol[4], 28);
	}

	//Our result file, don't modify if you want to use auto import scripts from dbbrowser
	//GetLocalTime(&lt);
	//sprintf_s(dumpFileName, 64, "%s_ntds_%02d-%02d-%04d_%02dh%02d.csv",argv[1], lt.wDay, lt.wMonth, lt.wYear, lt.wHour, lt.wMinute);
	sprintf_s(dumpFileName, 64, "%s-ntds.dit-dump.csv", argv[1]);
	fopen_s(&dump, dumpFileName, "w");
	if (dump == 0)
	{
		printf("Could not open csv file for writing\n");
		return(-1);
	}

	if(!strcmp(argv[1],"ace"))
		fprintf(dump, "sd_id\tPrimaryOwner\tPrimaryGroup\tACEType\tACEFlags\tAccessMask\tFlags\tObjectType\tInheritedObjectType\tTrusteeSID\n");

	// Initialize ESENT. 
	// See http://msdn.microsoft.com/en-us/library/windows/desktop/gg269297(v=exchg.10).aspx for error codes

	err = JetSetSystemParameter(0, JET_sesidNil, JET_paramDatabasePageSize, 8192, NULL);

	err = JetCreateInstance(&instance, "blabla");

	err = JetInit(&instance);

	err = JetBeginSession(instance, &sesid, 0, 0);

	err = JetAttachDatabase(sesid, baseName, JET_bitDbReadOnly);	
	if (err != 0)
	{
		printf("JetAttachDatabase : %i\n", err);
		return(-1);
	}

	err = JetOpenDatabase(sesid, baseName, 0, &dbid, 0);
	if (err != 0)
	{
		printf("JetOpenDatabase : %i\n", err);
		return(-1);
	}


	//Let's enumerate the metadata about datatable (AD table)

	tableName = "MSysObjects";

	err = JetOpenTable(sesid, dbid, tableName, 0, 0, JET_bitTableReadOnly, &tableid);

	printf("[*]Opened table: %s\n", tableName);

	//Obtain structures with necessary information to retrieve column values

	err = JetGetColumnInfo(sesid, dbid, tableName, "Id", columndefid, sizeof(JET_COLUMNDEF), JET_ColInfo);

	err = JetGetColumnInfo(sesid, dbid, tableName, "Type", columndeftype, sizeof(JET_COLUMNDEF), JET_ColInfo);

	err = JetGetColumnInfo(sesid, dbid, tableName, "ColtypOrPgnoFDP", columndeftypecol, sizeof(JET_COLUMNDEF), JET_ColInfo);

	err = JetGetColumnInfo(sesid, dbid, tableName, "Name", columndefname, sizeof(JET_COLUMNDEF), JET_ColInfo);

	err = JetGetColumnInfo(sesid, dbid, tableName, "ObjIdTable", columndefobjid, sizeof(JET_COLUMNDEF), JET_ColInfo);




	//printf("Type de colonne :%d, de longueur : %d", columndef->coltyp, columndef->cbMax);


	//Position the cursor at the first record
	JetMove(sesid, tableid, JET_MoveFirst, 0);
	//Retrieve columns metadata	
	do
	{
		JetRetrieveColumn(sesid, tableid, columndefid->columnid, 0, 0, &a, 0, 0);
		JetRetrieveColumn(sesid, tableid, columndefid->columnid, bufferid, a, 0, 0, 0);

		JetRetrieveColumn(sesid, tableid, columndeftype->columnid, 0, 0, &b, 0, 0);
		JetRetrieveColumn(sesid, tableid, columndeftype->columnid, buffertype, b, 0, 0, 0);

		JetRetrieveColumn(sesid, tableid, columndeftypecol->columnid, 0, 0, &e, 0, 0);
		JetRetrieveColumn(sesid, tableid, columndeftypecol->columnid, buffertypecol, e, 0, 0, 0);

		JetRetrieveColumn(sesid, tableid, columndefname->columnid, 0, 0, &c, 0, 0);
		JetRetrieveColumn(sesid, tableid, columndefname->columnid, buffername, c, 0, 0, 0);
		buffername[c]='\0';
		if(datatableId == 0xffffffff && !strcmp(buffername, targetTable))
		{
			//We found the target table in the metadata, pickup its id and make another pass
			datatableId = bufferid[0];
			printf("[*]%s tableID found : %d\n", buffername, datatableId);
			JetMove(sesid, tableid, JET_MoveFirst, 0);
			continue;
		}

		JetRetrieveColumn(sesid, tableid, columndefobjid->columnid, 0, 0, &d, 0, 0);
		JetRetrieveColumn(sesid, tableid, columndefobjid->columnid, bufferobjid, d, 0, 0, 0);


		//We got the correct type and table id, let's dump the column name and add it to the column list
		if(buffertype[0] == 2 && bufferobjid[0] == datatableId) 
		{
			unsigned int j;
			columnList->next = (COLUMNLIST *)malloc(sizeof(COLUMNLIST));
			if(!columnList->next) {
				printf("Memory allocation failed during metadata dump\n");
				return(-1);
			}
			columnList = columnList->next;
			columnList->next = NULL;

			for(j=0;j<c;j++)
				columnList->name[j] = buffername[j];
			columnList->name[c] = '\0';
			columnList->type = buffertypecol[0];
			columnList->id = bufferid[0];
		}
	}while(JetMove(sesid, tableid, JET_MoveNext, 0) == JET_errSuccess);

	JetCloseTable(sesid, tableid);


	//Let's use our metadata to dump the whole AD schema
	tableName = targetTable;

	err = JetOpenTable(sesid, dbid, tableName, 0, 0, JET_bitTableReadOnly, &tableid);
	printf("[*]Opened table: %s\n", tableName);


	printf("Dumping %s column names...\n", tableName);
	columnList = listHead;
	while(columnList->next)
	{
		columnList = columnList->next;
		if(!strcmp("ad",argv[1]))
			fprintf(dump,"%d:%s\t",columnList->type,columnList->name);
		else
			if(ValidateColumn(argv[1], columnList->name))
				fprintf(dump, "%s\t", translateATT(columnList->name));
	};
	fprintf(dump,"Distinguished-Name\n");

	printf("Dumping content...\n");

	JetMove(sesid, tableid, JET_MoveFirst, 0);
	do
	{
		DNT = 0;
		PDNT = 0;
		RDNtyp = 0;
		columnList = listHead;
		while(columnList->next)
		{
			columnList = columnList->next;

			if(ValidateColumn(argv[1], columnList->name))
			{
				//NOTE that this approach implies post processing multi valued columns if you re-use this code...
				err = JetRetrieveColumn(sesid, tableid, columnList->id, 0, 0, &jetSize, 0, 0);

#ifdef _DEBUG 
				//positive are warnings, -1047 is invalid buffer size which is expected here
				if (err < 0 && err != -1047) {
					printf("JetRetrieveColumn error : %i, jetSize : %d\n", err, jetSize);
					return(-2);
				}

				if (jetSize > JET_BUFFER_SIZE) {
					printf("Jet Buffer incorrect size preset: %d bytes are needed\n",jetSize);
					return(-2);
				}
#endif

			
				memset(jetBuffer,0,JET_BUFFER_SIZE);

				switch(columnList->type) {
					//signed int types
				case 4:
					JetRetrieveColumn(sesid, tableid, columnList->id, jetBuffer, jetSize, 0, 0, 0);
					//DNT
					if(!strcmp("DNT_col",columnList->name))
						DNT = *(int *)jetBuffer;
					if(!strcmp("PDNT_col",columnList->name))
						PDNT = *(int *)jetBuffer;
					if(!strcmp("RDNtyp_col",columnList->name))
						RDNtyp = *(int *)jetBuffer;
					//Specific useraccountcontrol code, currently dead code
					/*
					if(!strcmp("users",argv[1]) && !strcmp("ATTj589832",columnList->name))
					{
						if(jetBuffer[0] & ADS_UF_ACCOUNTDISABLE)
							fprintf(dump,"disabled ");
						if(jetBuffer[0] & ADS_UF_DONT_EXPIRE_PASSWD)
							fprintf(dump,"dontexpire ");
						if(jetBuffer[0] & ADS_UF_LOCKOUT)
							fprintf(dump,"lockedout ");
						if(jetBuffer[0] & ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED)
							fprintf(dump,"reversiblepwd ");
					}
					else
						*/
						fprintf(dump,"%d",*(int *)jetBuffer);
					/*
					fprintf(dump,"%u_",*(unsigned int *)jetBuffer);
					for(unsigned int i=0;i<jetSize;i++)
					fprintf(dump,"%.2X",jetBuffer[i]);
					*/
					break;
					//signed long long type
				case 5:
					JetRetrieveColumn(sesid, tableid, columnList->id, jetBuffer, jetSize, 0, 0, 0);
					if(!strcmp("sd_id",columnList->name))
						sd_id = *(long long *)jetBuffer;
					else
						fprintf(dump,"%lld",*(long long *)jetBuffer);
					break;
					//Raw binary types
				case 9:
					JetRetrieveColumn(sesid, tableid, columnList->id, jetBuffer, jetSize, 0, 0, 0);
					for(i=0;i<jetSize;i++)
						fprintf(dump,"%.2X",jetBuffer[i]);
					break;
				case 11:
					/* We check matches on security descriptor, then SID
					*  to display accordingly, otherwise hex dump
					*/
					JetRetrieveColumn(sesid, tableid, columnList->id, jetBuffer, jetSize, 0, 0, 0);

					if(!strcmp("sd_value",columnList->name) && IsValidSecurityDescriptor(jetBuffer))
					{
						//Correct sd_id because sd_id column is before sd_value column in sd_table
						DumpACE(sd_id, jetBuffer, dump);
					}
					else if(!strcmp("ATTr589970",columnList->name) && IsValidSid(jetBuffer))
					{
						//AD SID storage swaps endianness in RID bytes (yeah !) 
						unsigned char temp;
						temp = jetBuffer[24];
						jetBuffer[24] = jetBuffer[27];
						jetBuffer[27] = temp;
						temp = jetBuffer[25];
						jetBuffer[25] = jetBuffer[26];
						jetBuffer[26] = temp;

						ConvertSidToStringSid((PSID)jetBuffer, &stringSid);
						fwprintf(dump, L"%s", stringSid);
						LocalFree(stringSid);
						stringSid = NULL;
					}
					//NT Security Descriptor index to lookup in sd_table
					else if(!strcmp("sid",argv[1]) && ( !strcmp("ATTp131353",columnList->name) || !strcmp(exchangeMailboxSDCol,columnList->name) ))
					{
						fprintf(dump,"%d",*(int *)jetBuffer);
					}
					//Schema-Id-Guid
					else if(!strcmp("sid",argv[1]) && !strcmp("ATTk589972",columnList->name) )
					{
						UuidToString((UUID *)jetBuffer, &Guid);
						fwprintf(dump,L"%s",Guid);
						RpcStringFree(&Guid);
						Guid = NULL;
					}
					else //hex dump
						for(i=0;i<jetSize;i++)
							fprintf(dump,"%.2X",jetBuffer[i]);

					/* dumping type 11 as int (?)
						else
						{
						fprintf(dump,"%d",*(int *)jetBuffer);
						printf("dump type 11 as int : %d\n", *(int *)jetBuffer);
						}
						*/
						
					break;
					//widechar text types
				case 10:
				case 12:
					JetRetrieveColumn(sesid, tableid, columnList->id, jetBuffer, jetSize, 0, 0, 0);
					//CN/OU/O/DC
					if(jetSize && !strcmp("ATTm589825",columnList->name))
						//!strcmp("ATTm3",columnList->name) || !strcmp("ATTm10",columnList->name) ||!strcmp("ATTm11",columnList->name) ||!strcmp("ATTm1376281",columnList->name) ))
						wcscpy_s(Name, 256, (wchar_t*)jetBuffer);

					for(i=0;i<jetSize/2;i++)
						if((wchar_t)jetBuffer[2*i] != '\t' && (wchar_t)jetBuffer[2*i] != '\n' && (wchar_t)jetBuffer[2*i] != '\r')
							fwprintf(dump,L"%c",(wchar_t)jetBuffer[2*i]);
					break;
				};

				if(strcmp("ace",argv[1]))
					fprintf(dump,"\t");
			}
		}

		//Resolve DN and add DNT to ancestors chain
		if(DNT >= 4)
		{			
			DN = DNFromAncestors(PDNT, ancestorsList);
			//wprintf(L"Name: %s, PDNT: %d, DNT: %d, ancestors DN: %s\n",Name, PDNT, DNT, DN);
			ancestorsList = UpdateAncestorsList(DNT, DN, RDNtyp, Name, ancestorsList);
		}
		fwprintf(dump,L"%s",ancestorsList->DN);

		//DumpACE generates its own newlines
		if(strcmp("ace",argv[1]))
			fprintf(dump,"\n");
	}while(JetMove(sesid, tableid, JET_MoveNext, 0) == JET_errSuccess);

	// cleanup
	printf("cleaning...\n");

	JetCloseTable(sesid, tableid);
	JetEndSession(sesid, 0);
	JetTerm(instance);
	fclose(dump);
	return 0;
}
예제 #9
0
/* Dump ACE to file line per line in the following format:
*  ownerSID, groupSID, ACEType, ACEFlags, AccessMask, (Flags), (ObjectType guid), (InheritedObjectType guid), TrusteeSID
*/
void DumpACE(
	IN long long sd_id,
	IN unsigned char *buffer,
	IN FILE *dump
	)
{

	BOOL daclPresent, daclDefaulted;
	PACL dacl;

	PSID owner, group;
	BOOL ownerDefaulted, groupDefaulted;
	LPVOID ace;

	LPWSTR stringOwner = NULL;
	LPWSTR stringGroup = NULL;
	LPWSTR stringTrustee = NULL;
	RPC_WSTR OTGuid = NULL;
	RPC_WSTR IOTGuid = NULL;

	unsigned int i;


	GetSecurityDescriptorOwner(buffer, &owner, &ownerDefaulted);
	ConvertSidToStringSid(owner, &stringOwner);

	GetSecurityDescriptorGroup(buffer, &group, &groupDefaulted);
	ConvertSidToStringSid(group, &stringGroup);

	GetSecurityDescriptorDacl(buffer, &daclPresent, &dacl, &daclDefaulted);


	for(i = 0 ; GetAce(dacl, i, &ace) ; i++)
	{
		//Remove inherited ACE
		if((((ACE_HEADER *)ace)->AceFlags & INHERITED_ACE) != INHERITED_ACE)
		{
			fwprintf(dump,L"\n");			
			
			//Standard allow&deny ACE
			if(((ACE_HEADER *)ace)->AceType < 0x5)
			{	
				ConvertSidToStringSid((PSID)&(((ACCESS_ALLOWED_ACE *)ace)->SidStart), &stringTrustee);
				fwprintf_s(dump, L"%lld\t%s\t%s\t%.2X\t%.2X\t%d\t\t\t\t%s",
					sd_id,
					stringOwner,
					stringGroup,
					((ACE_HEADER *)ace)->AceType, 
					((ACE_HEADER *)ace)->AceFlags, 
					((ACCESS_ALLOWED_ACE *)ace)->Mask,
					stringTrustee 
					);

			}
			//Object ACE
			else
			{
				switch(((ACCESS_ALLOWED_OBJECT_ACE *)ace)->Flags)
				{
					//not any OT
				case 0x0:
					{
						ConvertSidToStringSid((PSID)((DWORD)&(((ACCESS_ALLOWED_OBJECT_ACE *)ace)->SidStart) - 2 * sizeof(GUID)), 
							&stringTrustee
							);
						break;
					}

					//Only OT
				case 0x1:
					{
						UuidToString(&(((ACCESS_ALLOWED_OBJECT_ACE *)ace)->ObjectType), &OTGuid);
						ConvertSidToStringSid((PSID)((DWORD)&(((ACCESS_ALLOWED_OBJECT_ACE *)ace)->SidStart) - sizeof(GUID)), 
							&stringTrustee
							);
						break;
					}
					//Only IOT
				case 0x2:
					{
						UuidToString(&(((ACCESS_ALLOWED_OBJECT_ACE *)ace)->InheritedObjectType), &IOTGuid);
						ConvertSidToStringSid((PSID)((DWORD)&(((ACCESS_ALLOWED_OBJECT_ACE *)ace)->SidStart) - sizeof(GUID)), 
							&stringTrustee
							);
						break;

					}
					//both
				case 0x3:
					{
						UuidToString(&(((ACCESS_ALLOWED_OBJECT_ACE *)ace)->ObjectType), &OTGuid);
						UuidToString(&(((ACCESS_ALLOWED_OBJECT_ACE *)ace)->InheritedObjectType), &IOTGuid);
						ConvertSidToStringSid((PSID)&(((ACCESS_ALLOWED_OBJECT_ACE *)ace)->SidStart), 
							&stringTrustee
							);
						break;
					}
				}

				fwprintf_s(dump, L"%lld\t%s\t%s\t%.2X\t%.2X\t%d\t%d\t%s\t%s\t%s",
					sd_id,
					stringOwner,
					stringGroup,
					((ACE_HEADER *)ace)->AceType,
					((ACE_HEADER *)ace)->AceFlags,
					((ACCESS_ALLOWED_OBJECT_ACE *)ace)->Mask, 
					((ACCESS_ALLOWED_OBJECT_ACE *)ace)->Flags,
					OTGuid,
					IOTGuid,
					stringTrustee 
					);
			}

			LocalFree(stringTrustee);
			stringTrustee = NULL;

			RpcStringFree(&OTGuid);
				OTGuid = NULL;
				
			RpcStringFree(&IOTGuid);
				IOTGuid = NULL;

		}	

	}

	LocalFree(stringOwner);
	stringOwner = NULL;

	LocalFree(stringGroup);
	stringGroup = NULL;

}
예제 #10
0
파일: WUser.cpp 프로젝트: qyqx/ConEmu
// *ppszSID - must be LocalFree'd
bool GetLogonSID (HANDLE hToken, wchar_t **ppszSID)
{
	bool bSuccess = false;
	//DWORD dwIndex;
	DWORD dwLength = 0;
	TOKEN_USER user;
	PTOKEN_USER ptu = &user;
	BOOL bFreeToken = FALSE;

	// Verify the parameter passed in is not NULL.
	if (NULL == ppszSID)
		goto Cleanup;
	*ppszSID = NULL;

	if (!hToken)
		bFreeToken = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken);

	// Get required buffer size and allocate the TOKEN_GROUPS buffer.
	if (!GetTokenInformation(
		hToken,         // handle to the access token
		TokenUser,      // get information about the token's user account
		(LPVOID) ptu,   // pointer to TOKEN_USER buffer
		0,              // size of buffer
		&dwLength       // receives required buffer size
	))
	{
		if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
			goto Cleanup;

		ptu = (PTOKEN_USER)calloc(dwLength,1);

		if (ptu == NULL)
			goto Cleanup;
	}

	// Get the token group information from the access token.

	if (!GetTokenInformation(
		hToken,         // handle to the access token
		TokenUser,      // get information about the token's user account
		(LPVOID) ptu,   // pointer to TOKEN_USER buffer
		dwLength,       // size of buffer
		&dwLength       // receives required buffer size
	))
	{
		goto Cleanup;
	}

	if (!ConvertSidToStringSid(ptu->User.Sid, ppszSID) || (*ppszSID == NULL))
		goto Cleanup;

	bSuccess = true;

Cleanup:

	// Free the buffer for the token groups.
	if ((ptu != NULL) && (ptu != &user))
		free(ptu);
	if (bFreeToken && hToken)
		CloseHandle(hToken);

	return bSuccess;
}
예제 #11
0
void RegistryLogAceSidStart(PSID SidStart)
{
	LogIncIndent();

	if (FALSE == IsValidSid(SidStart))
	{
		LOG(L"Invalid Sid given, cannot parse\n");
		LogDecIndent();
		return;
	}
	LPTSTR stringSid = NULL;
	if(FALSE == ConvertSidToStringSid(SidStart,&stringSid))
	{
		LOG(L"Could not convert SID to SIDString\n");
		LogDecIndent();
		return;
	}
	LOG(L"SID = %s\n",stringSid);

	PSID_IDENTIFIER_AUTHORITY sidia = GetSidIdentifierAuthority(SidStart);

	PUCHAR pSubAuthorityCount = GetSidSubAuthorityCount(SidStart);

	UCHAR counter = 0;
	for(; counter < *pSubAuthorityCount ; counter++)
	{
		PDWORD pSidSubAuthority = GetSidSubAuthority(SidStart,counter);
		BYTE nullauthorityValue[6] = SECURITY_NULL_SID_AUTHORITY;
		BYTE worldauthorityValue[6] = SECURITY_WORLD_SID_AUTHORITY;
		BYTE localauthorityValue[6] = SECURITY_LOCAL_SID_AUTHORITY;
		BYTE creatorauthorityValue[6] = SECURITY_CREATOR_SID_AUTHORITY;
		BYTE ntauthorityValue[6] = SECURITY_NT_AUTHORITY;

		if(memcmp(sidia->Value,nullauthorityValue,6) == 0)
		{
			switch(*pSidSubAuthority)
			{
			case SECURITY_NULL_RID:
				LOG(L"SECURITY_NULL\n");
				break;
			default:
				RegistryLogGeneralRIDS(L"SECURITY_NULL_SID_AUTHORITY",*pSidSubAuthority);
				break;
			};
		}
		else if (memcmp(sidia->Value,worldauthorityValue,6) == 0)
		{
			switch(*pSidSubAuthority)
			{
			case SECURITY_WORLD_RID:
				LOG(L"EVERYONE\n");
				break;	
			default:
				RegistryLogGeneralRIDS(L"SECURITY_WORLD_SID_AUTHORITY",*pSidSubAuthority);
				break;
			};
		}
		else if (memcmp(sidia->Value,localauthorityValue,6) == 0)
		{
			switch(*pSidSubAuthority)
			{	
			case SECURITY_LOCAL_RID:
				LOG(L"SECURITY_LOCAL_SID_AUTHORITY SECURITY_LOCAL_RID\n");
				break;
			case SECURITY_LOCAL_LOGON_RID:
				LOG(L"SECURITY_LOCAL_SID_AUTHORITY SECURITY_LOCAL_LOGON_RID\n");
				break;		
			default:
				RegistryLogGeneralRIDS(L"SECURITY_LOCAL_SID_AUTHORITY",*pSidSubAuthority);
				break;
			};
		}
		else if (memcmp(sidia->Value,creatorauthorityValue,6) == 0)
		{
			switch(*pSidSubAuthority)
			{	
			case SECURITY_CREATOR_OWNER_RID:
				LOG(L"CREATOR_OWNER\n");
				//LOG(L"SECURITY_CREATOR_SID_AUTHORITY SECURITY_CREATOR_OWNER_RID\n");
				break;
			case SECURITY_CREATOR_GROUP_RID:
				LOG(L"CREATOR_GROUP\n");
				//LOG(L"SECURITY_CREATOR_SID_AUTHORITY SECURITY_CREATOR_GROUP_RID\n");
				break;		
			default:
				RegistryLogGeneralRIDS(L"SECURITY_CREATOR_SID_AUTHORITY",*pSidSubAuthority);
				break;
			};
		}
		else if (memcmp(sidia->Value,ntauthorityValue,6) == 0)
		{
			switch(*pSidSubAuthority)
			{	
			case SECURITY_DIALUP_RID:
				LOG(L"DIALUP\n");
				//LOG(L"SECURITY_NT_AUTHORITY SECURITY_DIALUP_RID: Users who log on to terminals using a dial-up modem. This is a group identifier\n");
				break;
			case SECURITY_NETWORK_RID:
				LOG(L"NETWORK\n");
				//LOG(L"SECURITY_NT_AUTHORITY SECURITY_NETWORK_RID: Users who log on across a network. This is a group identifier\n");
				break;		
			case SECURITY_BATCH_RID:
				LOG(L"BATCH\n");
				//LOG(L"SECURITY_NT_AUTHORITY SECURITY_BATCH_RID: Users who log on using a batch queue facility. This is a group identifier\n");
				break;
			case SECURITY_INTERACTIVE_RID:
				LOG(L"INTERACTIVE\n");
				//LOG(L"SECURITY_NT_AUTHORITY SECURITY_INTERACTIVE_RID: Users who log on for interactive operation. This is a group identifier\n");
				break;	
			case SECURITY_LOGON_IDS_RID:
				LOG(L"LOGON_IDS\n");
				//LOG(L"SECURITY_NT_AUTHORITY SECURITY_LOGON_IDS_RID: A logon session\n");
				break;
			case SECURITY_SERVICE_RID:
				LOG(L"SERVICE\n");
				//LOG(L"SECURITY_NT_AUTHORITY SECURITY_SERVICE_RID: Accounts authorized to log on as a service. This is a group identifier\n");
				break;		
			case SECURITY_ANONYMOUS_LOGON_RID:
				LOG(L"ANONYMOUS\n");
				//LOG(L"SECURITY_NT_AUTHORITY SECURITY_ANONYMOUS_LOGON_RID: Anonymous logon, or null session logon\n");
				break;
			case SECURITY_PROXY_RID:
				LOG(L"PROXY\n");
				//LOG(L"SECURITY_NT_AUTHORITY SECURITY_PROXY_RID: Proxy\n");
				break;	
			case SECURITY_ENTERPRISE_CONTROLLERS_RID:
				LOG(L"ENTERPRISE_CONTROLLERS\n");
				//LOG(L"SECURITY_NT_AUTHORITY SECURITY_ENTERPRISE_CONTROLLERS_RID: Enterprise controllers\n");
				break;
			case SECURITY_PRINCIPAL_SELF_RID:
				LOG(L"PRINCIPAL_SELF\n");
				//LOG(L"SECURITY_NT_AUTHORITY SECURITY_PRINCIPAL_SELF_RID: The PRINCIPAL_SELF security identifier\n");
				break;		
			case SECURITY_AUTHENTICATED_USER_RID:
				LOG(L"AUTHENTICATED_USER\n");
				//LOG(L"SECURITY_NT_AUTHORITY SECURITY_AUTHENTICATED_USER_RID: The authenticated users\n");
				break;
			case SECURITY_RESTRICTED_CODE_RID:
				LOG(L"RESTRICTED_CODE\n");
				//LOG(L"SECURITY_NT_AUTHORITY SECURITY_RESTRICTED_CODE_RID: Restricted code\n");
				break;	
			case SECURITY_TERMINAL_SERVER_RID:
				LOG(L"TERMINAL_SERVER\n");
				//LOG(L"SECURITY_NT_AUTHORITY SECURITY_TERMINAL_SERVER_RID: Terminal Services\n");
				break;
			case SECURITY_LOCAL_SYSTEM_RID:
				LOG(L"LOCAL_SYSTEM\n");
				//LOG(L"SECURITY_NT_AUTHORITY SECURITY_LOCAL_SYSTEM_RID: A special account used by the operating system\n");
				break;		
			case SECURITY_NT_NON_UNIQUE:
				LOG(L"NT_NON_UNIQUE\n");
				//LOG(L"SECURITY_NT_AUTHORITY SECURITY_NT_NON_UNIQUE: SIDS are not unique\n");
				break;
			case SECURITY_BUILTIN_DOMAIN_RID:
				LOG(L"BUILTIN_DOMAIN\n");
				//LOG(L"SECURITY_NT_AUTHORITY SECURITY_BUILTIN_DOMAIN_RID: Buildin Domain\n");
				break;	
			default:
				RegistryLogGeneralRIDS(L"SECURITY_NT_AUTHORITY",*pSidSubAuthority);
				break;
			};
		}
	}
	LogDecIndent();
}
예제 #12
0
void wmain( int argc, wchar_t *argv[ ])
{

//Handle the command line arguments.
LPOLESTR pszBuffer = NULL;
pszBuffer = new OLECHAR[MAX_PATH*2];
if(pszBuffer == NULL)
    goto ret;
if (argv[1] == NULL)
{
	wprintf(L"This program finds a user in the current Window 2000 domain\n");
	wprintf(L"and displays its objectSid property in string form.\n");
	wprintf(L"This program demonstrates reading a property of type octet string.\n\n");
	
	wprintf(L"Enter Common Name of the user to find:");
	if ( !_getws_s(pszBuffer, MAX_PATH*2))
	{
		delete [] pszBuffer;
		wprintf(L"String exceeded buffer size.\n\n");
		return;
	}
}
else
   if ( !wcscpy_s(pszBuffer, MAX_PATH*2, argv[1]))
   {
	    delete [] pszBuffer;
		wprintf(L"String exceeded buffer size.\n\n");
		return;
   }
//if empty string, exit.
if (0==wcscmp(L"", pszBuffer))
   goto ret;
	
wprintf(L"\nFinding user: %s...\n",pszBuffer);
	
//Intialize COM
CoInitialize(NULL);
HRESULT hr = S_OK;
//Get rootDSE and the domain container's DN.
IADs *pObject = NULL;
IDirectorySearch *pDS = NULL;
LPOLESTR szPath = NULL;
szPath = new OLECHAR[MAX_PATH];
if(szPath == NULL)
    goto ret;

VARIANT var;
hr = ADsOpenObject(L"LDAP://rootDSE",
				 NULL,
				 NULL,
				 ADS_SECURE_AUTHENTICATION, //Use Secure Authentication
				 IID_IADs,
				 (void**)&pObject);
if (FAILED(hr))
{
   wprintf(L"Not Found. Could not bind to the domain.\n");
   if (pObject)
     pObject->Release();
   goto ret;
}

VariantInit(&var);
hr = pObject->Get(L"defaultNamingContext",&var);
if (SUCCEEDED(hr))
{
	wcscpy_s(szPath,MAX_PATH,L"LDAP://");
	wcscat_s(szPath,MAX_PATH,var.bstrVal);
	VariantClear(&var);
	if (pObject)
	{
	   pObject->Release();
	   pObject = NULL;
	}
	//Bind to the root of the current domain.
	hr = ADsOpenObject(szPath,
					 NULL,
					 NULL,
					 ADS_SECURE_AUTHENTICATION, //Use Secure Authentication
					 IID_IDirectorySearch,
					 (void**)&pDS);
	if (SUCCEEDED(hr))
	{
		hr =  FindUserByName(pDS, //Container to search
						   pszBuffer, //Name of user to find.
						   &pObject); //Return a pointer to the user
		if (SUCCEEDED(hr))
		{
			//Get the objectSid property
			hr = pObject->Get(L"objectSid", &var);
			if (SUCCEEDED(hr))
			{
				LPBYTE pByte = NULL;
				wprintf (L"----------------------------------------------\n");
				wprintf (L"----------Call GetLPBYTEtoOctetString---------\n");
				wprintf (L"----------------------------------------------\n");
				hr = GetLPBYTEtoOctetString(&var, //IN. Pointer to variant containing the octetstring.
							   &pByte //OUT. Return LPBYTE to the data represented in octetstring.
							   );

				PSID pObjectSID = (PSID)pByte;
				//Convert SID to string.
				LPOLESTR szSID = NULL;
				ConvertSidToStringSid(pObjectSID, &szSID);
				wprintf(L"objectSid:%s\n",szSID);
				LocalFree(szSID);
				//Free the buffer.
				CoTaskMemFree(pByte);
			}
			else
				wprintf(L"Get method failed with hr: %x\n",hr);
			VariantClear(&var);
		}
		else
		{
            wprintf(L"User \"%s\" not Found.\n",pszBuffer);
			wprintf (L"FindUserByName failed with the following HR: %x\n", hr);
		}
		if (pObject)
			pObject->Release();
	}

	if (pDS)
	   pDS->Release();
}
ret:
    if(pszBuffer) delete pszBuffer;
    if(szPath)     delete szPath;
//Uninitalize COM
CoUninitialize();

	return;
}