diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5a5f80a --- /dev/null +++ b/.gitignore @@ -0,0 +1,32 @@ + +#Ignore thumbnails created by Windows +Thumbs.db +#Ignore files built by Visual Studio +*.obj +*.exe +*.pdb +*.user +*.aps +*.pch +*.vspscc +*_i.c +*_p.c +*.ncb +*.suo +*.tlb +*.tlh +*.bak +*.cache +*.ilk +*.log +[Bb]in +[Dd]ebug*/ +*.lib +*.sbr +obj/ +[Rr]elease*/ +_ReSharper*/ +[Tt]est[Rr]esult* +.vs/ +#Nuget packages folder +packages/ diff --git a/Buffer.cpp b/Buffer.cpp new file mode 100644 index 0000000..ed40669 --- /dev/null +++ b/Buffer.cpp @@ -0,0 +1,192 @@ +#include +#include +#include "ORADAD.h" + +extern HANDLE g_hHeap; + +// +// Public functions +// +BOOL +BufferInitialize ( + _Out_ PBUFFER_DATA pBuffer, + _In_z_ LPWSTR szFilename +) +{ + ZeroMemory(pBuffer, sizeof(BUFFER_DATA)); + + pBuffer->hOutputFile = CreateFile(szFilename, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, NULL, 0); + + if (pBuffer->hOutputFile == INVALID_HANDLE_VALUE) + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_ERROR, + "Unable to open outfile %S (error %u).", szFilename, GetLastError() + ); + return FALSE; + } + + pBuffer->BufferSize = 1024 * 1024; + pBuffer->pbData = (PBYTE)_HeapAlloc(pBuffer->BufferSize); + _tcscpy_s(pBuffer->szFileName, MAX_PATH, szFilename); + + if (GetLastError() == ERROR_ALREADY_EXISTS) + { + SetFilePointer(pBuffer->hOutputFile, 0, 0, FILE_END); + } + else + { + // Write UTF-16 BOM + BYTE pbBomUTF16LE[2] = { 0xFF, 0xFE }; + BufferWrite(pBuffer, pbBomUTF16LE, 2); + } + + return TRUE; +} + +BOOL +BufferClose ( + _Out_ PBUFFER_DATA pBuffer +) +{ + BufferSave(pBuffer); + _SafeHeapRelease(pBuffer->pbData); + CloseHandle(pBuffer->hOutputFile); + + return TRUE; +} + +DWORD +BufferWrite ( + _Out_ PBUFFER_DATA pBuffer, + _In_reads_bytes_(dwNumberOfBytesToWrite) LPVOID pvData, + _In_ DWORD dwNumberOfBytesToWrite +) +{ + if (pBuffer == NULL) + return 0; + + if (pBuffer->pbData == NULL) + return 0; + + if (dwNumberOfBytesToWrite >= pBuffer->BufferSize) + { + // Can't write data bigger than buffer size + return 0; + } + else if ((pBuffer->BufferSize - pBuffer->Position) >= dwNumberOfBytesToWrite) + { + // Copy data to buffer + memcpy(pBuffer->pbData + pBuffer->Position, pvData, dwNumberOfBytesToWrite); + pBuffer->Position += dwNumberOfBytesToWrite; + return dwNumberOfBytesToWrite; + } + else + { + BOOL bResult; + + // Save buffer + bResult = BufferSave(pBuffer); + + // Copy data to buffer + memcpy(pBuffer->pbData + pBuffer->Position, pvData, dwNumberOfBytesToWrite); + pBuffer->Position += dwNumberOfBytesToWrite; + return dwNumberOfBytesToWrite; + } +} + +DWORD +BufferWrite ( + _Out_ PBUFFER_DATA pBuffer, + _Inout_opt_ LPWSTR szString +) +{ + size_t StringSize; + + if (pBuffer == NULL) + return FALSE; + + if (pBuffer->pbData == NULL) + return FALSE; + + if (szString == NULL) + return TRUE; + + StringSize = wcslen(szString); + RemoveSpecialChars(szString); + + if (StringSize == ((size_t)(-1))) + return FALSE; + else if (StringSize == 0) + return TRUE; + else + return BufferWrite(pBuffer, szString, (DWORD)(StringSize * sizeof(WCHAR))); +} + +DWORD +BufferWriteHex ( + _Out_ PBUFFER_DATA pBuffer, + _In_reads_(dwDataSize) PBYTE pbData, + _In_ DWORD dwDataSize +) +{ + DWORD dwDataSizeSum = 0; + + for (DWORD i = 0; i < dwDataSize; i++) + { + WCHAR szChar[3]; + + swprintf_s(szChar, 3, L"%02x", pbData[i]); + dwDataSizeSum += BufferWrite(pBuffer, szChar, 4); + } + + return dwDataSizeSum; +} + +DWORD +BufferWriteLine ( + _Out_ PBUFFER_DATA pBuffer +) +{ + return BufferWrite(pBuffer, (LPVOID)L"\r\n", 2 * sizeof(WCHAR)); +} + +DWORD +BufferWriteTab ( + _Out_ PBUFFER_DATA pBuffer +) +{ + return BufferWrite(pBuffer, (LPVOID)L"\t", 2); +} + +DWORD +BufferWriteSemicolon ( + _Out_ PBUFFER_DATA pBuffer +) +{ + return BufferWrite(pBuffer, (LPVOID)L";", 2); +} + +BOOL +BufferSave ( + _In_ PBUFFER_DATA pBuffer +) +{ + BOOL bReturn = FALSE; + BOOL bResult; + DWORD dwBytesWritten; + + if (pBuffer == NULL) + return FALSE; + + // + // Write buffer to file without modification + // + bResult = WriteFile(pBuffer->hOutputFile, pBuffer->pbData, pBuffer->Position, &dwBytesWritten, NULL); + bReturn = bResult; + + // Reset buffer position + pBuffer->Position = 0; + + return TRUE; +} \ No newline at end of file diff --git a/Constants.h b/Constants.h new file mode 100644 index 0000000..d532357 --- /dev/null +++ b/Constants.h @@ -0,0 +1,176 @@ +#include // cUserAccountControl +#include // cTrustAttributes + +#define CONST_MAX_SIZE 1024 +#define SIZE_NUMBER_TXT 12 + +#define ADS_UF_NO_AUTH_DATA_REQUIRED 0x2000000 +#define ADS_UF_PARTIAL_SECRETS_ACCOUNT 0x4000000 +CONST_TXT cUserAccountControl[] = +{ + { ADS_UF_ACCOUNTDISABLE, L"DISABLE" }, + { ADS_UF_LOCKOUT, L"LOCKOUT" }, + { ADS_UF_PASSWD_NOTREQD, L"PASSWD_NOTREQD" }, + { ADS_UF_PASSWD_CANT_CHANGE, L"PASSWD_CANT_CHANGE" }, + { ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED, L"TEXT_PASSWORD" }, + { ADS_UF_PASSWORD_EXPIRED, L"PASSWORD_EXPIRED" }, + { ADS_UF_DONT_EXPIRE_PASSWD, L"DONT_EXPIRE_PASSWD" }, + + { ADS_UF_DONT_REQUIRE_PREAUTH, L"DONT_REQUIRE_PREAUTH" }, + { ADS_UF_SMARTCARD_REQUIRED, L"SMARTCARD_REQUIRED" }, + { ADS_UF_USE_DES_KEY_ONLY, L"USE_DES_KEY_ONLY" }, + { ADS_UF_NOT_DELEGATED, L"NOT_DELEGATED" }, + { ADS_UF_TRUSTED_FOR_DELEGATION, L"TRUSTED_FOR_DELEGATION" }, + { ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION, L"T2A4F" }, + + { ADS_UF_TEMP_DUPLICATE_ACCOUNT, L"TEMP_DUPLICATE_ACCOUNT" }, + { ADS_UF_NORMAL_ACCOUNT, L"NORMAL_ACCOUNT" }, + { ADS_UF_INTERDOMAIN_TRUST_ACCOUNT, L"INTERDOMAIN_ACCOUNT" }, + { ADS_UF_WORKSTATION_TRUST_ACCOUNT, L"WORKSTATION_ACCOUNT" }, + { ADS_UF_SERVER_TRUST_ACCOUNT, L"SERVER_ACCOUNT" }, + { ADS_UF_PARTIAL_SECRETS_ACCOUNT, L"PARTIAL_SECRETS_ACCOUNT" }, + + { ADS_UF_MNS_LOGON_ACCOUNT, L"MNS_LOGON_ACCOUNT" }, + { ADS_UF_NO_AUTH_DATA_REQUIRED, L"NO_AUTH_DATA_REQUIRED" }, + { ADS_UF_SCRIPT, L"SCRIPT" }, + { ADS_UF_HOMEDIR_REQUIRED, L"HOMEDIR_REQUIRED" }, + + { FILTER_FLAG, NULL } +}; + +#define FLAG_ATTR_REQ_PARTIAL_SET_MEMBER 0x00000002 +#define FLAG_ATTR_IS_OPERATIONAL 0x00000008 +#define FLAG_SCHEMA_BASE_OBJECT 0x00000010 +#define FLAG_ATTR_IS_RDN 0x00000020 +#define FLAG_DISALLOW_MOVE_ON_DELETE 0x02000000 +CONST_TXT cSystemFlags [] = +{ + { ADS_SYSTEMFLAG_ATTR_NOT_REPLICATED, L"NOT_REPLICATED/NC" }, + { FLAG_ATTR_REQ_PARTIAL_SET_MEMBER, L"PARTIAL_SET_MEMBER/DOMAIN" }, + { ADS_SYSTEMFLAG_ATTR_IS_CONSTRUCTED, L"CONSTRUCTED/NOT_GC_REPLICATED" }, + { FLAG_ATTR_IS_OPERATIONAL, L"OPERATIONAL" }, + { FLAG_SCHEMA_BASE_OBJECT, L"BASE_OBJECT" }, + { FLAG_ATTR_IS_RDN, L"RDN" }, + + { FLAG_DISALLOW_MOVE_ON_DELETE, L"DISALLOW_MOVE_ON_DELETE" }, + { ADS_SYSTEMFLAG_DOMAIN_DISALLOW_MOVE, L"DISALLOW_MOVE" }, + { ADS_SYSTEMFLAG_DOMAIN_DISALLOW_RENAME, L"DISALLOW_RENAME" }, + { ADS_SYSTEMFLAG_CONFIG_ALLOW_LIMITED_MOVE, L"ALLOW_LIMITED_MOVE" }, + { ADS_SYSTEMFLAG_CONFIG_ALLOW_MOVE, L"ALLOW_MOVE" }, + { ADS_SYSTEMFLAG_CONFIG_ALLOW_RENAME, L"ALLOW_RENAME" }, + { ADS_SYSTEMFLAG_DISALLOW_DELETE, L"DISALLOW_DELETE" }, + + { FILTER_FLAG, NULL } +}; + +#define fATTINDEX 0x1 +#define fPDNTATTINDEX 0x2 +#define fANR 0x4 +#define fPRESERVEONDELETE 0x8 +#define fCOPY 0x10 +#define fTUPLEINDEX 0x20 +#define fSUBTREEATTINDEX 0x40 +#define fCONFIDENTIAL 0x80 +#define fNEVERVALUEAUDIT 0x100 +#define fRODCFilteredAttribute 0x200 +#define fEXTENDEDLINKTRACKING 0x400 +#define fBASEONLY 0x800 +#define fPARTITIONSECRET 0x1000 +CONST_TXT cSearchFlags[] = +{ + { fATTINDEX, L"ATTINDEX" }, + { fPDNTATTINDEX, L"PDNTATTINDEX" }, + { fANR, L"ANR" }, + { fPRESERVEONDELETE, L"PRESERVEONDELETE" }, + { fCOPY, L"COPY" }, + { fTUPLEINDEX, L"TUPLEINDEX" }, + { fSUBTREEATTINDEX, L"SUBTREEATTINDEX" }, + { fCONFIDENTIAL, L"CONFIDENTIAL" }, + { fNEVERVALUEAUDIT, L"NEVERVALUEAUDIT" }, + { fRODCFilteredAttribute, L"RODCFilteredAttribute" }, + { fEXTENDEDLINKTRACKING, L"EXTENDEDLINKTRACKING" }, + { fBASEONLY, L"BASEONLY" }, + { fPARTITIONSECRET, L"PARTITIONSECRET" }, + { FILTER_FLAG, NULL } +}; + +#define FLAG_ATTR_IS_CRITICAL 0x1 +CONST_TXT cSchemaFlagsEx[] = +{ + { FLAG_ATTR_IS_CRITICAL, L"IS_CRITICAL" }, + { FILTER_FLAG, NULL } +}; + +#define GROUP_TYPE_BUILTIN_LOCAL_GROUP 0x1 +#define GROUP_TYPE_ACCOUNT_GROUP 0x2 +#define GROUP_TYPE_RESOURCE_GROUP 0x4 +#define GROUP_TYPE_UNIVERSAL_GROUP 0x8 +#define GROUP_TYPE_APP_BASIC_GROUP 0x10 +#define GROUP_TYPE_APP_QUERY_GROUP 0x20 +#define GROUP_TYPE_SECURITY_ENABLED 0x80000000 +CONST_TXT cGroupType[] = +{ + { GROUP_TYPE_BUILTIN_LOCAL_GROUP, L"BUILTIN_LOCAL" }, + { GROUP_TYPE_ACCOUNT_GROUP, L"ACCOUNT" }, + { GROUP_TYPE_RESOURCE_GROUP, L"RESOURCE" }, + { GROUP_TYPE_UNIVERSAL_GROUP, L"UNIVERSAL" }, + { GROUP_TYPE_APP_BASIC_GROUP, L"APP_BASIC" }, + { GROUP_TYPE_APP_QUERY_GROUP, L"APP_QUERY" }, + { GROUP_TYPE_SECURITY_ENABLED, L"SECURITY_ENABLED" }, + { FILTER_FLAG, NULL } +}; + +#define DES_CBC_CRC 0x1 +#define DES_CBC_MD5 0x2 +#define RC4_HMAC 0x4 +#define AES128_CTS_HMAC_SHA1_96 0x8 +#define AES256_CTS_HMAC_SHA1_96 0x10 +#define FAST_supported 0x10000 +#define Compound_identity_supported 0x20000 +#define Claims_supported 0x40000 +#define Resource_SID_compression_disabled 0x80000 +CONST_TXT cSupportedEncryptionTypes[] = +{ + { DES_CBC_CRC, L"DES_CRC" }, + { DES_CBC_MD5, L"DES_MD5" }, + { RC4_HMAC, L"RC4" }, + { AES128_CTS_HMAC_SHA1_96, L"AES128" }, + { AES256_CTS_HMAC_SHA1_96, L"AES256" }, + { Compound_identity_supported, L"Compound" }, + { FAST_supported, L"FAST" }, + { Claims_supported, L"Claims" }, + { Resource_SID_compression_disabled, L"SID_compression_disabled" }, + { FILTER_FLAG, NULL } +}; + +#define TRUST_ATTRIBUTE_USES_RC4_ENCRYPTION 0x00000080 +CONST_TXT cTrustAttributes[] = +{ + { TRUST_ATTRIBUTE_NON_TRANSITIVE, L"NON_TRANSITIVE" }, + { TRUST_ATTRIBUTE_UPLEVEL_ONLY, L"UPLEVEL_ONLY" }, + { TRUST_ATTRIBUTE_QUARANTINED_DOMAIN, L"QUARANTINED_DOMAIN" }, + { TRUST_ATTRIBUTE_FOREST_TRANSITIVE, L"FOREST_TRANSITIVE" }, + { TRUST_ATTRIBUTE_CROSS_ORGANIZATION, L"CROSS_ORGANIZATION" }, + { TRUST_ATTRIBUTE_WITHIN_FOREST, L"WITHIN_FOREST" }, + { TRUST_ATTRIBUTE_TREAT_AS_EXTERNAL, L"TREAT_AS_EXTERNAL" }, + { TRUST_ATTRIBUTE_USES_RC4_ENCRYPTION, L"USES_RC4_ENCRYPTION" }, + { TRUST_ATTRIBUTE_CROSS_ORGANIZATION_NO_TGT_DELEGATION, L"CROSS_ORGANIZATION_NO_TGT_DELEGATION" }, + { TRUST_ATTRIBUTE_PIM_TRUST, L"PIM_TRUST" }, + { FILTER_FLAG, NULL } +}; + +CONST_TXT cTrustDirection[] = +{ + { TRUST_DIRECTION_INBOUND, L"INBOUND" }, + { TRUST_DIRECTION_OUTBOUND, L"OUTBOUND" }, + { TRUST_DIRECTION_BIDIRECTIONAL, L"BIDIRECTIONAL" }, + { FILTER_TYPE, NULL } +}; + +CONST_TXT cTrustType[] = +{ + { TRUST_TYPE_DOWNLEVEL, L"DOWNLEVEL" }, + { TRUST_TYPE_UPLEVEL, L"UPLEVEL" }, + { TRUST_TYPE_MIT, L"MIT" }, + { FILTER_TYPE, NULL } +}; diff --git a/Engine.cpp b/Engine.cpp new file mode 100644 index 0000000..8832797 --- /dev/null +++ b/Engine.cpp @@ -0,0 +1,408 @@ +#include +#include +#include +#include +#include "ORADAD.h" + +extern HANDLE g_hHeap; + +BOOL +pLocateDc( + _In_z_ LPWSTR szDomainName, + _Out_ LPWSTR *szServer +); + +BOOL +pProcessDomain( + _In_ PGLOBAL_CONFIG pGlobalConfig, + _Inout_ PROOTDSE_CONFIG pRootDse, + _In_z_ LPWSTR szDirectory, + _In_z_ LPWSTR szServer, + _In_z_ LPWSTR szRootDns, + _In_ BOOL bRequestLdap, + _In_ BOOL bWriteTableInfo +); + +BOOL +Process ( + _In_ PGLOBAL_CONFIG pGlobalConfig +) +{ + BOOL bResult, bReturn = FALSE; + WCHAR szDirectory[MAX_PATH]; + LPWSTR szRootDns = NULL; + LPWSTR szServer = NULL; + + ROOTDSE_CONFIG RootDse = { 0 }; + + // + // Get server by DC Locator, if needed + // + if (wcscmp(pGlobalConfig->szServer, L"[dsgetdc]") == 0) + { + bResult = pLocateDc(NULL, &szServer); + if (bResult == FALSE) + return FALSE; + } + else + { + DuplicateString(pGlobalConfig->szServer, &szServer); + } + + // + // Get rootDSE + // + bResult = LdapGetRootDse(pGlobalConfig, szServer, &RootDse); + if (bResult == FALSE) + goto End; + + szRootDns = ConvertDnToDns(RootDse.rootDomainNamingContext); + + // + // Create subdirectories (root and forest) + // + swprintf( + szDirectory, MAX_PATH, + L"%s\\%s", + pGlobalConfig->szOutDirectory, + szRootDns + ); + bResult = CreateDirectory(szDirectory, NULL); + if ((bResult == FALSE) && (GetLastError() != ERROR_ALREADY_EXISTS)) + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_CRITICAL, + "Unable to create directory '%S' (error %u).", + szDirectory, GetLastError() + ); + return FALSE; + } + + swprintf( + szDirectory, MAX_PATH, + L"%s\\%s\\%s", + pGlobalConfig->szOutDirectory, + szRootDns, + pGlobalConfig->szSystemTime + ); + CreateDirectory(szDirectory, NULL); + + swprintf( + szDirectory, MAX_PATH, + L"%s\\%s\\%s\\%s", + pGlobalConfig->szOutDirectory, + szRootDns, + pGlobalConfig->szSystemTime, + STR_DOMAIN + ); + CreateDirectory(szDirectory, NULL); + + swprintf( + szDirectory, MAX_PATH, + L"%s\\%s\\%s\\%s", + pGlobalConfig->szOutDirectory, + szRootDns, + pGlobalConfig->szSystemTime, + STR_CONFIGURATION + ); + CreateDirectory(szDirectory, NULL); + + swprintf( + szDirectory, MAX_PATH, + L"%s\\%s\\%s\\%s", + pGlobalConfig->szOutDirectory, + szRootDns, + pGlobalConfig->szSystemTime, + STR_SCHEMA + ); + CreateDirectory(szDirectory, NULL); + + swprintf( + szDirectory, MAX_PATH, + L"%s\\%s\\%s\\%s", + pGlobalConfig->szOutDirectory, + szRootDns, + pGlobalConfig->szSystemTime, + STR_DOMAIN_DNS + ); + CreateDirectory(szDirectory, NULL); + + swprintf( + szDirectory, MAX_PATH, + L"%s\\%s\\%s\\%s", + pGlobalConfig->szOutDirectory, + szRootDns, + pGlobalConfig->szSystemTime, + STR_FOREST_DNS + ); + CreateDirectory(szDirectory, NULL); + + // + // Open table file + // + swprintf( + szDirectory, MAX_PATH, + L"%s\\%s\\%s\\tables.tsv", + pGlobalConfig->szOutDirectory, + szRootDns, + pGlobalConfig->szSystemTime + ); + pGlobalConfig->hTableFile = CreateFile(szDirectory, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); + + if (pGlobalConfig->hTableFile == INVALID_HANDLE_VALUE) + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_CRITICAL, + "Unable to open table file '%S' (error %u).", + szDirectory, GetLastError() + ); + return FALSE; + } + + // Write base name (always first line) + WriteTextFile(pGlobalConfig->hTableFile, "%S_%S\n", szRootDns, pGlobalConfig->szSystemTime); + + // + // Process all forest global partition + // + for (DWORD i = 0; i < pGlobalConfig->dwRequestCount; i++) + { + if (pGlobalConfig->pRequests[i].dwBase & BASE_CONFIGURATION) + { + LdapProcessRequest(pGlobalConfig, szServer, RootDse.bIsLocalAdmin, szRootDns, STR_CONFIGURATION, NULL, RootDse.configurationNamingContext, &pGlobalConfig->pRequests[i], TRUE, TRUE); + } + + if (pGlobalConfig->pRequests[i].dwBase & BASE_SCHEMA) + { + LdapProcessRequest(pGlobalConfig, szServer, RootDse.bIsLocalAdmin, szRootDns, STR_SCHEMA, NULL, RootDse.schemaNamingContext, &pGlobalConfig->pRequests[i], TRUE, TRUE); + } + + if (pGlobalConfig->pRequests[i].dwBase & BASE_FOREST_DNS) + { + LdapProcessRequest(pGlobalConfig, szServer, RootDse.bIsLocalAdmin, szRootDns, STR_FOREST_DNS, NULL, RootDse.forestDnsNamingContext, &pGlobalConfig->pRequests[i], TRUE, TRUE); + } + } + + // + // Domains (our domain and all in forest if requested) + // + if (pGlobalConfig->bAllDomainsInForest == FALSE) + { + ROOTDSE_CONFIG pRootDse = { 0 }; + + pProcessDomain(pGlobalConfig, &pRootDse, szDirectory, szServer, szRootDns, TRUE, TRUE); + _SafeHeapRelease(szServer); + } + else + { + DWORD dwResult; + PDS_DOMAIN_TRUSTS pTrust; + ULONG ulDomainCount; + + dwResult = DsEnumerateDomainTrusts(NULL, DS_DOMAIN_IN_FOREST, &pTrust, &ulDomainCount); + if (dwResult != ERROR_SUCCESS) + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_ERROR, + "Unable to enumerate trust (error %u).", dwResult + ); + } + else + { + PROOTDSE_CONFIG pRootDse; + + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_INFORMATION, + "Find %u domains in forest.", ulDomainCount + ); + + pRootDse = (PROOTDSE_CONFIG)_HeapAlloc(sizeof(ROOTDSE_CONFIG) * ulDomainCount); + if (pRootDse == NULL) + return FALSE; + + for (ULONG i = 0; i < ulDomainCount; i++) + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_INFORMATION, + "Domain in forest: %S (Attribute: %u / Type: %u)", + pTrust[i].DnsDomainName, pTrust[i].TrustAttributes, pTrust[i].TrustType + ); + + if (pTrust[i].DnsDomainName != NULL) + { + bResult = pLocateDc(pTrust[i].DnsDomainName, &szServer); + if (bResult == FALSE) + continue; + + pProcessDomain(pGlobalConfig, &pRootDse[i], szDirectory, szServer, szRootDns, TRUE, FALSE); + _SafeHeapRelease(szServer); + } + } + + // + // Write table infos into table file (FALSE, TRUE) + // Done only after all requests (TRUE, FALSE) to be sure to have max text size for all domains + // + for (ULONG i = 0; i < ulDomainCount; i++) + { + if (pTrust[i].DnsDomainName != NULL) + pProcessDomain(pGlobalConfig, &pRootDse[i], szDirectory, szServer, szRootDns, FALSE, TRUE); + } + + _SafeHeapRelease(pRootDse); + } + NetApiBufferFree(pTrust); + } + + bReturn = TRUE; + +End: + _SafeHeapRelease(szRootDns); + if (pGlobalConfig->hTableFile != NULL) + CloseHandle(pGlobalConfig->hTableFile); + + return bReturn; +} + +// +// Private functions +// +BOOL +pLocateDc ( + _In_z_ LPWSTR szDomainName, + _Out_ LPWSTR *szServer +) +{ + DWORD dwResult; + PDOMAIN_CONTROLLER_INFO pDomainControllerInfo; + + dwResult = DsGetDcName( + NULL, szDomainName, NULL, NULL, + DS_ONLY_LDAP_NEEDED | DS_RETURN_DNS_NAME | DS_WRITABLE_REQUIRED, + &pDomainControllerInfo + ); + + if (dwResult != ERROR_SUCCESS) + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_ERROR, + "Unable to locate DC for domain '%S' (error %u).", szDomainName, dwResult + ); + return FALSE; + } + + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_VERBOSE, + "DC Locator: DC: %S (flags 0x%x), Domain: %S, Forest: %S", + pDomainControllerInfo->DomainControllerName, + pDomainControllerInfo->Flags, + pDomainControllerInfo->DomainName, + pDomainControllerInfo->DnsForestName + ); + + // +2 to remove '\\' prefix + DuplicateString(pDomainControllerInfo->DomainControllerName + 2, szServer); + + NetApiBufferFree(pDomainControllerInfo); + + return TRUE; +} + +BOOL +pProcessDomain ( + _In_ PGLOBAL_CONFIG pGlobalConfig, + _Inout_ PROOTDSE_CONFIG pRootDse, + _In_z_ LPWSTR szDirectory, + _In_z_ LPWSTR szServer, + _In_z_ LPWSTR szRootDns, + _In_ BOOL bRequestLdap, + _In_ BOOL bWriteTableInfo +) +{ + BOOL bResult; + + LPTSTR szDomainDns; + + if (bRequestLdap == TRUE) + { + // + // Get rootDSE + // + bResult = LdapGetRootDse(pGlobalConfig, szServer, pRootDse); + if (bResult == FALSE) + return FALSE; + + szDomainDns = ConvertDnToDns(pRootDse->defaultNamingContext); + + // + // Create subdirectories (domain) + // + swprintf( + szDirectory, MAX_PATH, + L"%s\\%s\\%s\\%s\\%s", + pGlobalConfig->szOutDirectory, + szRootDns, + pGlobalConfig->szSystemTime, + STR_DOMAIN, + szDomainDns + ); + CreateDirectory(szDirectory, NULL); + + swprintf( + szDirectory, MAX_PATH, + L"%s\\%s\\%s\\%s\\%s", + pGlobalConfig->szOutDirectory, + szRootDns, + pGlobalConfig->szSystemTime, + STR_DOMAIN_DNS, + szDomainDns + ); + CreateDirectory(szDirectory, NULL); + } + else + { + szDomainDns = ConvertDnToDns(pRootDse->defaultNamingContext); + } + + // + // Process + // + for (DWORD i = 0; i < pGlobalConfig->dwRequestCount; i++) + { + if (pGlobalConfig->pRequests[i].dwBase & BASE_ROOTDSE) + { + LdapProcessRequest(pGlobalConfig, szServer, pRootDse->bIsLocalAdmin, szRootDns, NULL, NULL, NULL, &pGlobalConfig->pRequests[i], bRequestLdap, bWriteTableInfo); + } + + if (pGlobalConfig->pRequests[i].dwBase & BASE_DOMAIN) + { + LdapProcessRequest(pGlobalConfig, szServer, pRootDse->bIsLocalAdmin, szRootDns, STR_DOMAIN, szDomainDns, pRootDse->defaultNamingContext, &pGlobalConfig->pRequests[i], bRequestLdap, bWriteTableInfo); + } + + if (pGlobalConfig->pRequests[i].dwBase & BASE_DOMAIN_DNS) + { + LdapProcessRequest(pGlobalConfig, szServer, pRootDse->bIsLocalAdmin, szRootDns, STR_DOMAIN_DNS, szDomainDns, pRootDse->domainDnsNamingContext, &pGlobalConfig->pRequests[i], bRequestLdap, bWriteTableInfo); + } + + /* + // DEBUG CODE + for (DWORD j = 0; j < pGlobalConfig->dwRequestCount; j++) + { + if (wcscmp(pGlobalConfig->pRequests[j].szName, L"computer") == 0) + { + wprintf(L"%u[%s]: ", j, pGlobalConfig->pRequests[j].szName); + for (DWORD k = 0; k < pGlobalConfig->pRequests[j].dwAttributesCount; k++) + { + if (wcscmp((*pGlobalConfig->pRequests[j].pAttributes[k]).szName, L"cn") == 0) + wprintf(L" %s:%u", (*pGlobalConfig->pRequests[j].pAttributes[k]).szName, pGlobalConfig->pRequests[j].pdwStrintMaxLength[k]); + } + printf("\n"); + } + } + */ + } + + _SafeHeapRelease(szDomainDns); + + return TRUE; +} \ No newline at end of file diff --git a/Filters.cpp b/Filters.cpp new file mode 100644 index 0000000..fe57f9b --- /dev/null +++ b/Filters.cpp @@ -0,0 +1,380 @@ +#include +#include +#include +#include "ORADAD.h" +#include "Constants.h" + +extern HANDLE g_hHeap; + +#define NEVER_VALUE 9223372036854775808 +#define STR_UNABLE_CONVERT_SID L"Unable to convert SID" +#define STR_NEVER L"Never" + +// +// Filter functions +// +BOOL +pFilterFlagsType( + _In_ PVOID pvData, + _In_ PVOID pvParam, + _Outptr_ LPWSTR *szResult +); + +BOOL +pFilterSid( + _In_ PVOID pvData, + _In_ PVOID pvParam, + _Outptr_ LPWSTR *szResult +); + +BOOL +pFilterFiletime( + _In_ PVOID pvData, + _In_ PVOID pvParam, + _Outptr_ LPWSTR *szResult +); + +BOOL +pFilterNegFiletime( + _In_ PVOID pvData, + _In_ PVOID pvParam, + _Outptr_ LPWSTR *szResult +); + +// +// Private functions +// +LPWSTR +pHeapAllocAndCopyString( + _In_z_ LPCWSTR szString +); + +BOOL +GetFilter ( + _Inout_ PATTRIBUTE_CONFIG pAttributes, + _In_z_ LPCWSTR szFilter +) +{ + if (_wcsicmp(szFilter, L"userAccountControl") == 0) + { + pAttributes->fFilter = (tFilter)pFilterFlagsType; + pAttributes->pvFilterData = cUserAccountControl; + } + else if (_wcsicmp(szFilter, L"supportedEncryptionTypes") == 0) + { + pAttributes->fFilter = (tFilter)pFilterFlagsType; + pAttributes->pvFilterData = cSupportedEncryptionTypes; + } + else if (_wcsicmp(szFilter, L"groupType") == 0) + { + pAttributes->fFilter = (tFilter)pFilterFlagsType; + pAttributes->pvFilterData = cGroupType; + } + else if (_wcsicmp(szFilter, L"trustAttributes") == 0) + { + pAttributes->fFilter = (tFilter)pFilterFlagsType; + pAttributes->pvFilterData = cTrustAttributes; + } + else if (_wcsicmp(szFilter, L"trustDirection") == 0) + { + pAttributes->fFilter = (tFilter)pFilterFlagsType; + pAttributes->pvFilterData = cTrustDirection; + } + else if (_wcsicmp(szFilter, L"trustType") == 0) + { + pAttributes->fFilter = (tFilter)pFilterFlagsType; + pAttributes->pvFilterData = cTrustType; + } + else if (_wcsicmp(szFilter, L"systemFlags") == 0) + { + pAttributes->fFilter = (tFilter)pFilterFlagsType; + pAttributes->pvFilterData = cSystemFlags; + } + else if (_wcsicmp(szFilter, L"searchFlags") == 0) + { + pAttributes->fFilter = (tFilter)pFilterFlagsType; + pAttributes->pvFilterData = cSearchFlags; + } + else if (_wcsicmp(szFilter, L"schemaFlagsEx") == 0) + { + pAttributes->fFilter = (tFilter)pFilterFlagsType; + pAttributes->pvFilterData = cSchemaFlagsEx; + } + else if (_wcsicmp(szFilter, L"sid") == 0) + { + pAttributes->fFilter = (tFilter)pFilterSid; + pAttributes->pvFilterData = NULL; + } + else if (_wcsicmp(szFilter, L"Filetime") == 0) + { + pAttributes->fFilter = (tFilter)pFilterFiletime; + pAttributes->pvFilterData = NULL; + } + else if (_wcsicmp(szFilter, L"NegFiletime") == 0) + { + pAttributes->fFilter = (tFilter)pFilterNegFiletime; + pAttributes->pvFilterData = NULL; + } + else + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_ERROR, + "Unknown filter '%S'.", szFilter + ); + return FALSE; + } + + return TRUE; +} + +LPWSTR +ApplyFilter ( + _In_ PATTRIBUTE_CONFIG pAttributes, + _In_z_ PVOID pvData +) +{ + BOOL bResult; + LPWSTR szResult = NULL; + + if (pvData == NULL) + return NULL; + + if (pAttributes->fFilter == NULL) + return NULL; + + bResult = pAttributes->fFilter(pvData, pAttributes->pvFilterData, &szResult); + if (bResult == FALSE) + { + _SafeHeapRelease(szResult); + return NULL; + } + else + return szResult; +} + +// +// Filter functions +// +BOOL +pFilterFlagsType ( + _In_ PVOID pvData, + _In_ PVOID pvParam, + _Outptr_ LPWSTR *szResult +) +{ + BOOL bFirst = TRUE; + DWORD dwValue; + DWORD dwRest; + LPWSTR szOut; + + PCONST_TXT pFlagsList; + DWORD dwFilterMode; + + szOut = (LPWSTR)_HeapAlloc(CONST_MAX_SIZE * sizeof(WCHAR)); + if (szOut == NULL) + return FALSE; + + dwValue = *(PDWORD)pvData; + dwRest = dwValue; + pFlagsList = (PCONST_TXT)pvParam; + + // + // Pass 1: Get filter Mode + // + pFlagsList = (PCONST_TXT)pvParam; + while (pFlagsList->szTxt) + { + pFlagsList++; + } + dwFilterMode = pFlagsList->dwConst; + + // + // Pass 2: Apply filter + // + pFlagsList = (PCONST_TXT)pvParam; + switch (dwFilterMode) + { + case FILTER_FLAG: + { + while (pFlagsList->szTxt) + { + if (pFlagsList->dwConst & dwValue) + { + if (bFirst) + bFirst = FALSE; + else + wcscat_s(szOut, CONST_MAX_SIZE, L" | "); + wcscat_s(szOut, CONST_MAX_SIZE, pFlagsList->szTxt); + dwRest &= ~pFlagsList->dwConst; + } + pFlagsList++; + } + + // + // Add remaining flags + // + if (dwRest) + { + WCHAR szRest[SIZE_NUMBER_TXT]; + swprintf_s(szRest, SIZE_NUMBER_TXT, L"%lu", dwRest); + + if (!bFirst) + wcscat_s(szOut, CONST_MAX_SIZE, L" | "); + + wcscat_s(szOut, CONST_MAX_SIZE, szRest); + } + } + break; + + case FILTER_TYPE: + { + while (pFlagsList->szTxt) + { + if (pFlagsList->dwConst == dwValue) + { + wcscpy_s(szOut, CONST_MAX_SIZE, pFlagsList->szTxt); + break; + } + pFlagsList++; + } + } + break; + } + + *szResult = szOut; + return TRUE; +} + +BOOL +pFilterSid ( + _In_ PVOID pvData, + _In_ PVOID pvParam, + _Outptr_ LPWSTR *szResult +) +{ + BOOL bResult; + LPWSTR szSid; + + bResult = ConvertSidToStringSid(pvData, &szSid); + if (bResult == TRUE) + { + *szResult = pHeapAllocAndCopyString(szSid); + LocalFree(szSid); + } + else + { + *szResult = pHeapAllocAndCopyString(STR_UNABLE_CONVERT_SID); + } + + return TRUE; +} + +BOOL +pFilterFiletime ( + _In_ PVOID pvData, + _In_ PVOID pvParam, + _Outptr_ LPWSTR *szResult +) +{ + LONGLONG llValue; + + *szResult = NULL; + + llValue = *(PLONGLONG)pvData; + + if (llValue == 0) + *szResult = NULL; + else + { + LONGLONG llDay; + LONG lHour; + LONG lMinute; + LONG lSeconde; + + llValue = llValue / 10000000; + + llDay = llValue / 86400; + llValue = llValue - (llDay * 86400); + + lHour = (LONG)(llValue / 3600); + llValue = llValue - (lHour * 3600); + + lMinute = (LONG)(llValue / 60); + llValue = llValue - (lMinute * 60); + + lSeconde = (LONG)(llValue / 60); + llValue = llValue - (lSeconde * 60); + + *szResult = (LPWSTR)_HeapAlloc(15 * sizeof(WCHAR)); + swprintf_s(*szResult, 15, L"%llu:%02u:%02u:%02u", llDay, lHour, lMinute, lSeconde); + } + + return TRUE; +} + +BOOL +pFilterNegFiletime ( + _In_ PVOID pvData, + _In_ PVOID pvParam, + _Outptr_ LPWSTR *szResult +) +{ + LONGLONG llValue; + + *szResult = NULL; + + llValue = -(*(PLONGLONG)pvData); + + if (llValue == 0) + *szResult = NULL; + else if (llValue == NEVER_VALUE) + *szResult = pHeapAllocAndCopyString(STR_NEVER); + else + { + LONGLONG llDay; + LONG lHour; + LONG lMinute; + LONG lSeconde; + + llValue = llValue / 10000000; + + llDay = llValue / 86400; + llValue = llValue - (llDay * 86400); + + lHour = (LONG)(llValue / 3600); + llValue = llValue - (lHour * 3600); + + lMinute = (LONG)(llValue / 60); + llValue = llValue - (lMinute * 60); + + lSeconde = (LONG)(llValue / 60); + llValue = llValue - (lSeconde * 60); + + *szResult = (LPWSTR)_HeapAlloc(15 * sizeof(WCHAR)); + swprintf_s(*szResult, 15, L"%llu:%02u:%02u:%02u", llDay, lHour, lMinute, lSeconde); + } + + return TRUE; +} + +// +// Private functions +// +LPWSTR +pHeapAllocAndCopyString ( + _In_z_ LPCWSTR szString +) +{ + LPWSTR szReturn; + size_t SizeString; + + SizeString = wcslen(szString); + SizeString++; // NULL char + szReturn = (LPWSTR)_HeapAlloc(SizeString * sizeof(WCHAR)); + if (szReturn != NULL) + { + wcscpy_s(szReturn, SizeString, szString); + } + + return szReturn; +} \ No newline at end of file diff --git a/Functions.h b/Functions.h new file mode 100644 index 0000000..0a9acbc --- /dev/null +++ b/Functions.h @@ -0,0 +1,151 @@ +// +// XML.cpp +// +PVOID +XmlReadConfigFile( + _In_z_ LPTSTR szConfigPath, + _In_ PGLOBAL_CONFIG pGlobalConfig +); + +// +// Engine.cpp +// +BOOL +Process( + _In_ PGLOBAL_CONFIG pGlobalConfig +); + +// +// LDAP.cpp +// +BOOL +LdapGetRootDse( + _In_ PGLOBAL_CONFIG pGlobalConfig, + _In_z_ LPWSTR szServerName, + _Outptr_ PROOTDSE_CONFIG pRootDse +); + +BOOL +LdapProcessRequest( + _In_ PGLOBAL_CONFIG pGlobalConfig, + _In_z_ LPWSTR szServer, + _In_ BOOL bIsLocalAdmin, + _In_z_ LPWSTR szRootDns, + _In_z_ LPCWSTR szPath1, + _In_opt_z_ LPCWSTR szPath2, + _In_z_ LPWSTR szLdapBase, + _In_ PREQUEST_CONFIG pRequest, + _In_ BOOL bRequestLdap, + _In_ BOOL bWriteTableInfo +); + +// +// Util.cpp +// +VOID +Log( + _In_z_ LPCSTR szFile, + _In_z_ LPCSTR szFunction, + _In_ DWORD dwLine, + _In_ DWORD dwLevel, + _In_z_ LPCSTR szFormat, + ... +); + +VOID +DuplicateString( + _In_z_ LPWSTR szInput, + _Out_ LPWSTR *szOutput +); + +LPWSTR +ConvertDnToDns( + _In_z_ LPWSTR szString +); + +VOID +RemoveSpecialChars( + _In_z_ LPWSTR szString +); + +BOOL +WriteTextFile( + _In_ HANDLE hFile, + _In_z_ LPCSTR szFormat, + ... +); + +LPSTR +LPWSTRtoLPSTR( + _In_opt_z_ LPWSTR szToConvert +); + +// +// Buffer.cpp +// +BOOL +BufferInitialize +( + _Out_ PBUFFER_DATA pBuffer, + _In_z_ LPWSTR szFilename +); + +BOOL +BufferClose( + _Out_ PBUFFER_DATA pBuffer +); + +DWORD +BufferWrite( + _Out_ PBUFFER_DATA pBuffer, + _In_reads_bytes_(dwNumberOfBytesToWrite) LPVOID pvData, + _In_ DWORD dwNumberOfBytesToWrite +); + +DWORD +BufferWrite( + _Out_ PBUFFER_DATA pBuffer, + _Inout_opt_ LPWSTR szString +); + +DWORD +BufferWriteHex( + _Out_ PBUFFER_DATA pBuffer, + _In_reads_(dwDataSize) PBYTE pbData, + _In_ DWORD dwDataSize +); + +DWORD +BufferWriteLine( + _Out_ PBUFFER_DATA pBuffer +); + +DWORD +BufferWriteTab( + _Out_ PBUFFER_DATA pBuffer +); + +DWORD +BufferWriteSemicolon( + _Out_ PBUFFER_DATA pBuffer +); + +BOOL +BufferSave( + _In_ PBUFFER_DATA pBuffer +); + +// +// Filters.cpp +// +BOOL +GetFilter( + _Inout_ PATTRIBUTE_CONFIG pAttributes, + _In_z_ LPCWSTR szFilter +); + +LPWSTR +ApplyFilter( + _In_ PATTRIBUTE_CONFIG pAttributes, + _In_z_ PVOID pvData +); \ No newline at end of file diff --git a/LDAP.cpp b/LDAP.cpp new file mode 100644 index 0000000..7076c33 --- /dev/null +++ b/LDAP.cpp @@ -0,0 +1,1499 @@ +#include +#include +#include // For LDAP Extended Controls +#include +#include +#include +#include +#include "ORADAD.h" + +#define MAX_ATTRIBUTE_NAME 64 + +extern GLOBAL_CONFIG g_GlobalConfig; +extern HANDLE g_hHeap; + +// +// Private functions +// +LDAP* +pLdapOpenConnection( + _In_ PGLOBAL_CONFIG pGlobalConfig, + _In_z_ LPWSTR szServerName +); + +BOOL +pWriteTableInfo( + _In_ PGLOBAL_CONFIG pGlobalConfig, + _In_ PREQUEST_CONFIG pRequest, + _In_ BOOL bIsTop, + _In_ BOOL bIsRootDSE, + _In_z_ LPWSTR szRelativePath, + _In_z_ LPWSTR szTableName, + _In_z_ LPWSTR szTableNameNoDomain, + _In_ DWORD dwAttributesCount, + _In_ PATTRIBUTE_CONFIG *pAttributes +); + +BOOL +pHasAttributeWithRange( + _In_ LDAP *pLdapHandle, + _In_ LDAPMessage *pEntry, + _In_z_ LPWSTR szDn +); + +BOOL +pParseRange( + _In_ LDAP *pLdapHandle, + _In_ LDAPMessage *pEntry, + _In_z_ LPWSTR szAttribute, + _Out_ LPWSTR *pszAttrName, + _Out_ PDWORD pdwEnd +); + +LPWSTR* +pGetRangedAttribute( + _In_ LDAP* pLdapHandle, + _In_ LPWSTR szDn, + _In_ LPWSTR szAttribute, + _In_ PDWORD pdwRangeStart +); + +// +// Public functions +// +BOOL +LdapGetRootDse ( + _In_ PGLOBAL_CONFIG pGlobalConfig, + _In_z_ LPWSTR szServerName, + _Outptr_ PROOTDSE_CONFIG pRootDse +) +{ + ULONG ulResult; + + LDAP* pLdapHandle; + LDAPMessage *pLdapMessage = NULL; + LDAPMessage* pEntry = NULL; + PWCHAR pAttribute = NULL; + BerElement* pBer = NULL; + + LPCWSTR szAttrsSearch[] = { + L"dnsHostName" , L"serverName" , + L"defaultNamingContext", L"rootDomainNamingContext", L"configurationNamingContext", L"schemaNamingContext", L"namingContexts", + L"domainControllerFunctionality", L"domainFunctionality", L"forestFunctionality", + L"tokenGroups", // Constructed rootDse attribute. Must be explicitly requested. + NULL + }; + + pLdapHandle = pLdapOpenConnection(pGlobalConfig, szServerName); + if (pLdapHandle == NULL) + return FALSE; + + ulResult = ldap_search_s(pLdapHandle, NULL, LDAP_SCOPE_BASE, NULL, (PZPWSTR)szAttrsSearch, FALSE, &pLdapMessage); + if (ulResult != LDAP_SUCCESS) + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_INFORMATION, + "Error in ldap_search_s() (error %u: %s).", ulResult, ldap_err2stringA(ulResult) + ); + return FALSE; + } + + pEntry = ldap_first_entry(pLdapHandle, pLdapMessage); + pAttribute = ldap_first_attribute(pLdapHandle, pEntry, &pBer); + + pRootDse->bIsLocalAdmin = FALSE; + + while (pAttribute != NULL) + { + PWCHAR *ppValue = NULL; + + ppValue = ldap_get_values(pLdapHandle, pEntry, pAttribute); + + if (ppValue != NULL) + { + ULONG ulValues; + + if ((wcscmp(pAttribute, L"dnsHostName") == 0) && (wcslen(pAttribute) > 0)) + DuplicateString(ppValue[0], &pRootDse->dnsHostName); + else if ((wcscmp(pAttribute, L"serverName") == 0) && (wcslen(pAttribute) > 0)) + DuplicateString(ppValue[0], &pRootDse->serverName); + else if ((wcscmp(pAttribute, L"defaultNamingContext") == 0) && (wcslen(pAttribute) > 0)) + DuplicateString(ppValue[0], &pRootDse->defaultNamingContext); + else if ((wcscmp(pAttribute, L"rootDomainNamingContext") == 0) && (wcslen(pAttribute) > 0)) + DuplicateString(ppValue[0], &pRootDse->rootDomainNamingContext); + else if ((wcscmp(pAttribute, L"configurationNamingContext") == 0) && (wcslen(pAttribute) > 0)) + DuplicateString(ppValue[0], &pRootDse->configurationNamingContext); + else if ((wcscmp(pAttribute, L"schemaNamingContext") == 0) && (wcslen(pAttribute) > 0)) + DuplicateString(ppValue[0], &pRootDse->schemaNamingContext); + else if ((wcscmp(pAttribute, L"domainControllerFunctionality") == 0) && (wcslen(pAttribute) > 0)) + DuplicateString(ppValue[0], &pRootDse->domainControllerFunctionality); + else if ((wcscmp(pAttribute, L"domainFunctionality") == 0) && (wcslen(pAttribute) > 0)) + DuplicateString(ppValue[0], &pRootDse->domainFunctionality); + else if ((wcscmp(pAttribute, L"forestFunctionality") == 0) && (wcslen(pAttribute) > 0)) + DuplicateString(ppValue[0], &pRootDse->forestFunctionality); + else if ((wcscmp(pAttribute, L"namingContexts") == 0) && (wcslen(pAttribute) > 0)) + { + ulValues = ldap_count_values(ppValue); + + for (ULONG i = 0; i < ulValues; i++) + { + if (wcsstr(ppValue[i], L"DC=ForestDnsZones,") == ppValue[i]) + DuplicateString(ppValue[i], &pRootDse->forestDnsNamingContext); + else if(wcsstr(ppValue[i], L"DC=DomainDnsZones,") == ppValue[i]) + DuplicateString(ppValue[i], &pRootDse->domainDnsNamingContext); + } + } + else if ((wcscmp(pAttribute, L"tokenGroups") == 0) && (wcslen(pAttribute) > 0)) + { + berval **ppval = NULL; + + ppval = ldap_get_values_len(pLdapHandle, pEntry, pAttribute); + + if (ppval != NULL) + { + ulValues = ldap_count_values_len(ppval); + + for (ULONG j = 0; j < ulValues; j++) + { + BOOL bResult; + LPTSTR szSid; + + bResult = ConvertSidToStringSid(ppval[j]->bv_val, &szSid); + + if (bResult == TRUE) + { + if (wcscmp(szSid, L"S-1-5-32-544") == 0) // Administrators + { + pRootDse->bIsLocalAdmin = TRUE; + } + LocalFree(szSid); + } + } + } + ldap_value_free_len(ppval); + } + ldap_value_free(ppValue); + } + + ldap_memfree(pAttribute); + pAttribute = ldap_next_attribute(pLdapHandle, pEntry, pBer); + } + + if (pBer != NULL) + { + ber_free(pBer, 0); + pBer = NULL; + } + + ulResult = ldap_msgfree(pLdapMessage); + ulResult = ldap_unbind(pLdapHandle); + + return TRUE; +} + +BOOL +LdapProcessRequest ( + _In_ PGLOBAL_CONFIG pGlobalConfig, + _In_z_ LPWSTR szServer, + _In_ BOOL bIsLocalAdmin, + _In_z_ LPWSTR szRootDns, + _In_opt_z_ LPCWSTR szPath1, + _In_opt_z_ LPCWSTR szPath2, + _In_opt_z_ LPWSTR szLdapBase, + _In_ PREQUEST_CONFIG pRequest, + _In_ BOOL bRequestLdap, + _In_ BOOL bWriteTableInfo +) +{ + BOOL bResult; + WCHAR szFilename[MAX_PATH]; + WCHAR szRelativePath[MAX_PATH]; + WCHAR szTableName[MAX_PATH]; + WCHAR szTableNameNoDomain[MAX_PATH]; + + DWORD dwAttributesCount; + PATTRIBUTE_CONFIG *pAttributes; + + BOOL bIsRootDSE; + BOOL bIsTop = FALSE; + + ULONG ulResult; + ULONG ulReturnCode; + ULONG ulEntriesCount; + + if (szLdapBase == NULL) + { + bIsRootDSE = TRUE; + dwAttributesCount = pGlobalConfig->dwRootDSEAttributesCount; + + // pRootDSEAttributes is array of attributes + // pAttributes is array of pointers to attributes. Create temporary array. + pAttributes = (PATTRIBUTE_CONFIG*)_HeapAlloc(dwAttributesCount * sizeof(PATTRIBUTE_CONFIG)); + for (DWORD i = 0; i < dwAttributesCount; i++) + { + pAttributes[i] = &(pGlobalConfig->pRootDSEAttributes[i]); + } + } + else + { + bIsRootDSE = FALSE; + dwAttributesCount = pRequest->dwAttributesCount; + pAttributes = pRequest->pAttributes; + } + + if (_wcsicmp(pRequest->szName, L"top") == 0) + bIsTop = TRUE; + + // + // Initialize names + // + if ((szPath1 != NULL) && (szPath2 != NULL)) + { + swprintf_s( + szFilename, MAX_PATH, + L"%s\\%s\\%s\\%s\\%s\\%s.tsv", + pGlobalConfig->szOutDirectory, + szRootDns, + pGlobalConfig->szSystemTime, + szPath1, + szPath2, + pRequest->szName + ); + + swprintf_s( + szRelativePath, MAX_PATH, + L"%s\\%s\\%s.tsv", + szPath1, + szPath2, + pRequest->szName + ); + + swprintf_s( + szTableName, MAX_PATH, + L"%s_%s_%s", + szPath1, + szPath2, + pRequest->szName + ); + + swprintf_s( + szTableNameNoDomain, MAX_PATH, + L"%s_%s", + szPath1, + pRequest->szName + ); + } + else if ((szPath1 != NULL) && (szPath2 == NULL)) + { + swprintf_s( + szFilename, MAX_PATH, + L"%s\\%s\\%s\\%s\\%s.tsv", + pGlobalConfig->szOutDirectory, + szRootDns, + pGlobalConfig->szSystemTime, + szPath1, + pRequest->szName + ); + + swprintf_s( + szRelativePath, MAX_PATH, + L"%s\\%s.tsv", + szPath1, + pRequest->szName + ); + + swprintf_s( + szTableName, MAX_PATH, + L"%s_%s", + szPath1, + pRequest->szName + ); + + swprintf_s( + szTableNameNoDomain, MAX_PATH, + L"%s_%s", + szPath1, + pRequest->szName + ); + } + else if ((szPath1 == NULL) && (szPath2 == NULL)) + { + swprintf_s( + szFilename, MAX_PATH, + L"%s\\%s\\%s\\%s.tsv", + pGlobalConfig->szOutDirectory, + szRootDns, + pGlobalConfig->szSystemTime, + pRequest->szName + ); + + swprintf_s( + szRelativePath, MAX_PATH, + L"%s.tsv", + pRequest->szName + ); + + swprintf_s( + szTableName, MAX_PATH, + L"%s", + pRequest->szName + ); + + swprintf_s( + szTableNameNoDomain, MAX_PATH, + L"%s", + pRequest->szName + ); + } + else + { + return FALSE; + } + + if (bRequestLdap == TRUE) + { + BUFFER_DATA Buffer; + PBUFFER_DATA pBuffer; + + LDAP* pLdapHandle; + LDAPMessage *pLdapMessage = NULL; + + LPWSTR *pszAttributes; + + PLDAPControl pLdapControl = NULL; + PLDAPControl controlArray[3] = { 0 }; // 0: paging, 1:LDAP_SERVER_SD_FLAGS_OID, 2: NULL + + LDAPMessage* pEntry = NULL; + + LDAP_BERVAL LdapCookie = { 0, NULL }; + PLDAP_BERVAL pLdapNewCookie = NULL; + PLDAPControl *currControls = NULL; + + berval *pBerVal = NULL; + + DWORD dwStartTime, dwEndTime; + + dwStartTime = GetTickCount(); + + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_VERBOSE, + "Start dump '%S/%S/%S/%S'.", szRootDns, szPath1, szPath2, pRequest->szName + ); + + // + // Create output buffer + // + bResult = BufferInitialize(&Buffer, szFilename); + if (bResult == FALSE) + { + return FALSE; + } + + pBuffer = &Buffer; + + // + // Write header into output file if requested by configuration + // + if (pGlobalConfig->bWriteHeader == TRUE) + { + if (bIsRootDSE == TRUE) + BufferWrite(pBuffer, (LPWSTR)L"server"); + else + BufferWrite(pBuffer, (LPWSTR)L"dn"); + + if (bIsTop == TRUE) + { + BufferWriteTab(pBuffer); + BufferWrite(pBuffer, (LPWSTR)L"shortname"); + BufferWriteTab(pBuffer); + BufferWrite(pBuffer, (LPWSTR)L"shortdn"); + } + + for (DWORD i = 0; i < dwAttributesCount; i++) + { + if (((*pAttributes[i]).Type == TYPE_INT) || ((*pAttributes[i]).Type == TYPE_INT64)) + { + if ((*pAttributes[i]).fFilter == NULL) + { + // No filter: int only + BufferWriteTab(pBuffer); + BufferWrite(pBuffer, (*pAttributes[i]).szName); + } + else + { + // Filter: text + int + BufferWriteTab(pBuffer); + BufferWrite(pBuffer, (*pAttributes[i]).szName); + + BufferWriteTab(pBuffer); + BufferWrite(pBuffer, (*pAttributes[i]).szName); + BufferWrite(pBuffer, (LPWSTR)L"_int"); + } + } + else + { + BufferWriteTab(pBuffer); + BufferWrite(pBuffer, (*pAttributes[i]).szName); + } + } + + BufferWriteLine(pBuffer); + } + + // + // Process + // + pLdapHandle = pLdapOpenConnection(pGlobalConfig, szServer); + if (pLdapHandle == NULL) + return FALSE; + + ulResult = ldap_create_page_control( + pLdapHandle, + 900, + &LdapCookie, + TRUE, + &pLdapControl + ); + + controlArray[0] = pLdapControl; + + if (bIsTop == TRUE) + { + // For 'top' requests, we ask for Security Descriptor (nTSecurityDescriptor). By default, all parts are requested, including SACL. + // We request SACL only if we are local administrator. Overwise, nothing is return. + LDAPControl LdapControlSdFlag; + BerElement *pBerElmt = NULL; + + pBerElmt = ber_alloc_t(LBER_USE_DER); + if (bIsLocalAdmin == TRUE) + ber_printf(pBerElmt, (PSTR)"{i}", (OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION)); + else + ber_printf(pBerElmt, (PSTR)"{i}", (OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION)); + ber_flatten(pBerElmt, &pBerVal); + + LdapControlSdFlag.ldctl_iscritical = TRUE; + LdapControlSdFlag.ldctl_oid = (LPWSTR)LDAP_SERVER_SD_FLAGS_OID_W; + LdapControlSdFlag.ldctl_value.bv_val = pBerVal->bv_val; + LdapControlSdFlag.ldctl_value.bv_len = pBerVal->bv_len; + + controlArray[1] = &LdapControlSdFlag; + + ber_free(pBerElmt, 1); + } + + // + // Format pszAttributes list + // Note: dn can't be requested in attribute list. We get it by ldap_get_dn(). + // + pszAttributes = (LPWSTR*)_HeapAlloc((dwAttributesCount + 1) * sizeof(LPWSTR)); // +1 for NULL (list terminator) + for (DWORD i = 0; i < dwAttributesCount; i++) + pszAttributes[i] = (*pAttributes[i]).szName; + + // + // Process searches + // + Loop: + ulResult = ldap_search_ext_s( + pLdapHandle, + szLdapBase, + pRequest->dwScope, + pRequest->szFilter, + pszAttributes, // attrs + 0, // attrsonly + controlArray, // ServerControls + NULL, // ClientControls + 0, // timeout + 0, // SizeLimit + &pLdapMessage + ); + if (ulResult != LDAP_SUCCESS) + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_INFORMATION, + "Error in ldap_search_ext_s() (error %u: %s).", ulResult, ldap_err2stringA(ulResult) + ); + goto End; + } + + ulEntriesCount = ldap_count_entries( + pLdapHandle, + pLdapMessage + ); + + for (ULONG i = 0; i < ulEntriesCount; i++) + { + LPWSTR szDn; + BOOL bHasRange; + + if (i == 0) + pEntry = ldap_first_entry(pLdapHandle, pLdapMessage); + else + pEntry = ldap_next_entry(pLdapHandle, pEntry); + + szDn = ldap_get_dn(pLdapHandle, pEntry); + + if (bIsRootDSE == TRUE) + { + // For RootDSE, dwStrintMaxLengthShortName is used for 'server' max size + _CallWriteAndGetMax(BufferWrite(pBuffer, szServer), pRequest->dwStrintMaxLengthShortName); + BufferWriteTab(pBuffer); + } + else + { + LPWSTR *ppValue = NULL; + + // + // For all files, 'dn' is first column + // + if (szDn != NULL) + { + _CallWriteAndGetMax(BufferWrite(pBuffer, szDn), pRequest->dwStrintMaxLengthDn); + } + BufferWriteTab(pBuffer); + } + + // + // Two more columns for 'top' + // + if (bIsTop == TRUE) + { + WCHAR szShortName[MAX_PATH]; + + // + // Short name + // + if (szPath2 != NULL) + swprintf_s(szShortName, MAX_PATH, L"%s/%s", szPath1, szPath2); + else + swprintf_s(szShortName, MAX_PATH, L"%s/%s", szPath1, szRootDns); + _CallWriteAndGetMax(BufferWrite(pBuffer, szShortName), pRequest->dwStrintMaxLengthShortName); + BufferWriteTab(pBuffer); + + // + // Short DN + // + if (szDn != NULL) + { + LPWSTR szBasePosition; + + // Compute short DN + szBasePosition = wcsstr(szDn, szLdapBase); + if ((szBasePosition != NULL) && (szBasePosition != szDn)) + { + *(szBasePosition - 1) = 0; // -1 to remove ',' + _CallWriteAndGetMax(BufferWrite(pBuffer, szDn), pRequest->dwStrintMaxLengthShortDn); + } + BufferWriteTab(pBuffer); + } + else + { + BufferWriteTab(pBuffer); + } + } + + // + // Check range + // + bHasRange = pHasAttributeWithRange(pLdapHandle, pEntry, szDn); + + // + // Other attributes + // + for (DWORD j = 0; j < dwAttributesCount; j++) + { + LPWSTR pAttribute = NULL; + LPWSTR *ppValue = NULL; + berval **ppval = NULL; + + ppval = NULL; + pAttribute = pszAttributes[j]; + + switch ((*pAttributes[j]).Type) + { + case TYPE_STR: + case TYPE_INT: + case TYPE_INT64: + { + ppValue = ldap_get_values(pLdapHandle, pEntry, pAttribute); + + if (ppValue != NULL) + { + if (((*pAttributes[j]).Type == TYPE_INT) && ((*pAttributes[j]).fFilter != NULL)) + { + // INT + filter + LPWSTR szText; + LONG lValue = 0; + + swscanf_s(ppValue[0], L"%li", &lValue); + + szText = ApplyFilter(&(*pAttributes[j]), &lValue); + _CallWriteAndGetMax(BufferWrite(pBuffer, szText), pRequest->pdwStrintMaxLength[j]); + _SafeHeapRelease(szText); + + BufferWriteTab(pBuffer); + BufferWrite(pBuffer, ppValue[0]); + } + else if (((*pAttributes[j]).Type == TYPE_INT64) && ((*pAttributes[j]).fFilter != NULL)) + { + // INT64 + filter + LPWSTR szText; + LONGLONG llValue = 0; + + swscanf_s(ppValue[0], L"%lli", &llValue); + + szText = ApplyFilter(&(*pAttributes[j]), &llValue); + _CallWriteAndGetMax(BufferWrite(pBuffer, szText), pRequest->pdwStrintMaxLength[j]); + _SafeHeapRelease(szText); + + BufferWriteTab(pBuffer); + BufferWrite(pBuffer, ppValue[0]); + } + else + { + // STR + _CallWriteAndGetMax(BufferWrite(pBuffer, ppValue[0]), pRequest->pdwStrintMaxLength[j]); + } + } + else if ((((*pAttributes[j]).Type == TYPE_INT) || ((*pAttributes[j]).Type == TYPE_INT64)) && ((*pAttributes[j]).fFilter != NULL)) + { + _CallWriteAndGetMax(BufferWriteTab(pBuffer), pRequest->pdwStrintMaxLength[j]); + } + } + break; + + case TYPE_STRS: + { + ppValue = ldap_get_values(pLdapHandle, pEntry, pAttribute); + + if (ppValue != NULL) + { + if (*ppValue != NULL) + { + DWORD dwTotalSize = 0; + ULONG ulValues; + + ulValues = ldap_count_values(ppValue); + + for (ULONG k = 0; k < ulValues; k++) + { + if (k == 0) + { + dwTotalSize += BufferWrite(pBuffer, ppValue[k]); + } + else + { + dwTotalSize += BufferWriteSemicolon(pBuffer); + dwTotalSize += BufferWrite(pBuffer, ppValue[k]); + } + } + + pRequest->pdwStrintMaxLength[j] = __max(pRequest->pdwStrintMaxLength[j], dwTotalSize); + } + else if (bHasRange == TRUE) + { + // + // Error: attribute is present but with no value. This may be a value with range. + // + DWORD dwTotalSize = 0; + DWORD dwRangeEnd; + LPWSTR szRangeAttrName; + + bResult = pParseRange(pLdapHandle, pEntry, pAttribute, &szRangeAttrName, &dwRangeEnd); + + if ((bResult == TRUE) && (szRangeAttrName != NULL)) + { + LPWSTR *ppValueRange = NULL; + + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_VERBOSE, + "'%S' has attribute '%S' with range.", + szDn, szRangeAttrName + ); + + // + // This is an attribute with range. Write current request. + // + ppValueRange = ldap_get_values(pLdapHandle, pEntry, szRangeAttrName); + if (ppValueRange != NULL) + { + DWORD dwTotalSize = 0; + ULONG ulValues; + + ulValues = ldap_count_values(ppValueRange); + + for (ULONG k = 0; k < ulValues; k++) + { + if (k == 0) + { + dwTotalSize += BufferWrite(pBuffer, ppValueRange[k]); + } + else + { + dwTotalSize += BufferWriteSemicolon(pBuffer); + dwTotalSize += BufferWrite(pBuffer, ppValueRange[k]); + } + } + + ldap_value_free(ppValueRange); + } + + // + // Ask remaining parts + // + do + { + LPWSTR *ppValueRange = NULL; + ULONG ulValues; + + dwRangeEnd++; + ppValueRange = pGetRangedAttribute(pLdapHandle, szDn, pAttribute, &dwRangeEnd); + + if (ppValueRange != NULL) + { + ulValues = ldap_count_values(ppValueRange); + + for (ULONG k = 0; k < ulValues; k++) + { + dwTotalSize += BufferWriteSemicolon(pBuffer); + dwTotalSize += BufferWrite(pBuffer, ppValueRange[k]); + } + + ldap_value_free(ppValueRange); + } + else + break; + + if (dwRangeEnd == 0) // This was the final part of the range + break; + } while (TRUE); + } + + pRequest->pdwStrintMaxLength[j] = __max(pRequest->pdwStrintMaxLength[j], dwTotalSize); + } + else + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_WARNING, + "ldap_get_values(%S, %s) has no value but is not with range.", szDn, pAttribute + ); + } + } + } + break; + + case TYPE_SID: + { + ppval = ldap_get_values_len(pLdapHandle, pEntry, pAttribute); + + if (ppval) + { + BOOL bResult; + LPWSTR szSid; + + bResult = ConvertSidToStringSid(ppval[0]->bv_val, &szSid); + if (bResult == TRUE) + { + _CallWriteAndGetMax(BufferWrite(pBuffer, szSid), pRequest->pdwStrintMaxLength[j]); + LocalFree(szSid); + } + else + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_ERROR, + "Unable to convert SID." + ); + } + } + } + break; + + case TYPE_SD: + { + ppval = ldap_get_values_len(pLdapHandle, pEntry, pAttribute); + + if (ppval) + { + DWORD dwSize; + + dwSize = BufferWriteHex(pBuffer, (PBYTE)ppval[0]->bv_val, ppval[0]->bv_len); + pRequest->pdwStrintMaxLength[j] = __max(pRequest->pdwStrintMaxLength[j], dwSize); + } + } + break; + + case TYPE_DACL: + { + ppval = ldap_get_values_len(pLdapHandle, pEntry, pAttribute); + + if (ppval) + { + BOOL bResult; + LPWSTR szSddl; + + // + // DACL_SECURITY_INFORMATION + // + bResult = ConvertSecurityDescriptorToStringSecurityDescriptor( + ppval[0]->bv_val, + SDDL_REVISION_1, + DACL_SECURITY_INFORMATION, + &szSddl, + NULL + ); + + if (bResult == TRUE) + { + _CallWriteAndGetMax(BufferWrite(pBuffer, szSddl), pRequest->pdwStrintMaxLength[j]); + LocalFree(szSddl); + } + else + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_ERROR, + "Unable to convert SDDL." + ); + } + } + } + break; + + case TYPE_GUID: + { + ppval = ldap_get_values_len(pLdapHandle, pEntry, pAttribute); + + if (ppval) + { + LPWSTR szGuid = NULL; + + UuidToString((UUID*)ppval[0]->bv_val, (RPC_WSTR*)&szGuid); + + if (szGuid != NULL) + { + BufferWrite(pBuffer, szGuid);; + RpcStringFree((RPC_WSTR*)&szGuid); + } + } + } + break; + + case TYPE_DATE: + { + ppValue = ldap_get_values(pLdapHandle, pEntry, pAttribute); + + if (ppValue != NULL) + { + WCHAR szDate[20]; + + szDate[0] = ppValue[0][0]; + szDate[1] = ppValue[0][1]; + szDate[2] = ppValue[0][2]; + szDate[3] = ppValue[0][3]; + szDate[4] = 0x2d; // L"-"; + szDate[5] = ppValue[0][4]; + szDate[6] = ppValue[0][5]; + szDate[7] = 0x2d; // L"-"; + szDate[8] = ppValue[0][6]; + szDate[9] = ppValue[0][7]; + szDate[10] = 0x20; // L" "; + szDate[11] = ppValue[0][8]; + szDate[12] = ppValue[0][9]; + szDate[13] = 0x3a; // L":"; + szDate[14] = ppValue[0][10]; + szDate[15] = ppValue[0][11]; + szDate[16] = 0x3a; // L":"; + szDate[17] = ppValue[0][12]; + szDate[18] = ppValue[0][13]; + szDate[19] = 0; + + BufferWrite(pBuffer, szDate); + } + } + break; + + case TYPE_DATEINT64: + { + ppValue = ldap_get_values(pLdapHandle, pEntry, pAttribute); + + if (ppValue != NULL) + { + LONG64 llTimeStamp; + + swscanf_s(ppValue[0], L"%lli", &llTimeStamp); + if (llTimeStamp == 0x7fffffffffffffff) + { + BufferWrite(pBuffer, (LPWSTR)L"2999-12-12 23:59:59"); + } + else if (llTimeStamp != 0) + { + SYSTEMTIME st; + WCHAR szDate[20]; + + FileTimeToSystemTime((FILETIME *)&llTimeStamp, &st); + swprintf_s( + szDate, 20, + L"%04u-%02u-%02u %02u:%02u:%02u", + st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond + ); + BufferWrite(pBuffer, szDate); + } + } + } + break; + + case TYPE_BOOL: + { + ppValue = ldap_get_values(pLdapHandle, pEntry, pAttribute); + + if (ppValue != NULL) + { + if (_wcsicmp(ppValue[0], L"TRUE") == 0) + BufferWrite(pBuffer, (LPWSTR)L"1"); + else if (_wcsicmp(ppValue[0], L"FALSE") == 0) + BufferWrite(pBuffer, (LPWSTR)L"0"); + else + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_ERROR, + "Unknwon boolean value ('%S').", ppValue[0] + ); + } + } + break; + + case TYPE_BIN: + { + // TODO: Range + ppval = ldap_get_values_len(pLdapHandle, pEntry, pAttribute); + + if (ppval != NULL) + { + DWORD dwTotalSize = 0; + ULONG ulValues; + + ulValues = ldap_count_values_len(ppval); + + for (ULONG k = 0; k < ulValues; k++) + { + if (k != 0) + dwTotalSize += BufferWriteSemicolon(pBuffer); + + if ((*pAttributes[j]).fFilter != NULL) + { + LPWSTR szText; + + szText = ApplyFilter(&(*pAttributes[j]), (PBYTE)ppval[k]->bv_val); + dwTotalSize += BufferWrite(pBuffer, szText); + _SafeHeapRelease(szText); + } + else + { + dwTotalSize += BufferWriteHex(pBuffer, (PBYTE)ppval[k]->bv_val, ppval[k]->bv_len); + } + } + pRequest->pdwStrintMaxLength[j] = __max(pRequest->pdwStrintMaxLength[j], dwTotalSize); + } + } + break; + } + + if ((j + 1) < dwAttributesCount) + BufferWriteTab(pBuffer); + + if (ppValue != NULL) + { + ldap_value_free(ppValue); + } + if (ppval != NULL) + { + ldap_value_free_len(ppval); + } + } + + BufferWriteLine(pBuffer); + + ldap_memfree(szDn); + } + + // RootDSA has always 1 entry + if (bIsRootDSE == TRUE) + goto End; + + ulResult = ldap_parse_result( + pLdapHandle, + pLdapMessage, + &ulReturnCode, + NULL, + NULL, + NULL, + &currControls, + FALSE + ); + if (ulResult != LDAP_SUCCESS) + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_INFORMATION, + "Error in ldap_parse_result() (error %u: %s).", ulResult, ldap_err2stringA(ulResult) + ); + goto End; + } + + ulResult = ldap_parse_page_control(pLdapHandle, currControls, NULL, (berval**)&pLdapNewCookie); + if (ulResult != LDAP_SUCCESS) + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_INFORMATION, + "Error in ldap_parse_page_control() (error %u: %s).", ulResult, ldap_err2stringA(ulResult) + ); + goto End; + } + + if ((pLdapNewCookie->bv_len == 0) || (pLdapNewCookie->bv_val == 0)) + goto End; + + controlArray[0] = NULL; + + ulResult = ldap_create_page_control( + pLdapHandle, + 900, + pLdapNewCookie, + TRUE, + &controlArray[0] + ); + if (ulResult != LDAP_SUCCESS) + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_INFORMATION, + "Error in ldap_create_page_control() (error %u: %s).", ulResult, ldap_err2stringA(ulResult) + ); + goto End; + } + + ldap_msgfree(pLdapMessage); + + // + // Wait if requested by config + // + if (g_GlobalConfig.dwSleepTime > 0) + Sleep(g_GlobalConfig.dwSleepTime); + + goto Loop; + + End: + if (bIsTop == TRUE) + ber_bvfree(pBerVal); + + ber_bvfree(pLdapNewCookie); + + ulResult = ldap_control_free(pLdapControl); + ulResult = ldap_msgfree(pLdapMessage); + ulResult = ldap_unbind(pLdapHandle); + + BufferClose(&Buffer); + + dwEndTime = GetTickCount(); + + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_INFORMATION, + "Dump '%S/%S/%S/%S' finished (elapsed time: %u seconds).", + szRootDns, szPath1, szPath2, pRequest->szName, + (dwEndTime - dwStartTime) / 1000 + ); + } + + if (bWriteTableInfo == TRUE) + { + pWriteTableInfo(pGlobalConfig, pRequest, bIsTop, bIsRootDSE, szRelativePath, szTableName, szTableNameNoDomain, dwAttributesCount, pAttributes); + } + + if (bIsRootDSE == TRUE) + _SafeHeapRelease(pAttributes); + + return TRUE; +} + +// +// Private functions +// +LDAP* +pLdapOpenConnection ( + _In_ PGLOBAL_CONFIG pGlobalConfig, + _In_z_ LPWSTR szServerName +) +{ + ULONG ulResult; + ULONG ulVersion = LDAP_VERSION3; + void *pvValue = NULL; + + LDAP* pLdapHandle = NULL; + + if (pGlobalConfig->ulLdapPort == 0) + pGlobalConfig->ulLdapPort = LDAP_PORT; + + pLdapHandle = ldap_open(szServerName, (pGlobalConfig->ulLdapPort == 0) ? LDAP_PORT : pGlobalConfig->ulLdapPort); + if (pLdapHandle == NULL) + { + ulResult = LdapGetLastError(); + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_ERROR, + "Unable to open LDAP connection to %S (error %u: %s).", szServerName, ulResult, ldap_err2stringA(ulResult) + ); + return NULL; + } + + ulResult = ldap_connect(pLdapHandle, NULL); + if (ulResult != LDAP_SUCCESS) + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_ERROR, + "Unable to connect to LDAP server (error %u: %s).", ulResult, ldap_err2stringA(ulResult) + ); + ldap_unbind(pLdapHandle); + return NULL; + } + + ulResult = ldap_set_option(pLdapHandle, LDAP_OPT_PROTOCOL_VERSION, (void*)&ulVersion); + pvValue = LDAP_OPT_OFF; + ulResult = ldap_set_option(pLdapHandle, LDAP_OPT_REFERRALS, &pvValue); + + if (pGlobalConfig->szUsername == NULL) + { + ulResult = ldap_bind_s(pLdapHandle, NULL, NULL, LDAP_AUTH_NEGOTIATE); + } + else + { + SEC_WINNT_AUTH_IDENTITY Auth = { 0 }; + + Auth.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; + Auth.User = (USHORT*)pGlobalConfig->szUsername; + Auth.Domain = (USHORT*)pGlobalConfig->szUserDomain; + Auth.Password = (USHORT*)pGlobalConfig->szUserPassword; + Auth.UserLength = wcslen(pGlobalConfig->szUsername); + Auth.DomainLength = wcslen(pGlobalConfig->szUserDomain); + Auth.PasswordLength = wcslen(pGlobalConfig->szUserPassword); + + ulResult = ldap_bind_s(pLdapHandle, NULL, (PWCHAR)&Auth, LDAP_AUTH_NEGOTIATE); + } + + if (ulResult != LDAP_SUCCESS) + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_ERROR, + "Unable to bind to LDAP server (error %u: %s).", ulResult, ldap_err2stringA(ulResult) + ); + ldap_unbind(pLdapHandle); + return NULL; + } + + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_VERBOSE, + "Successfully bind to %S.", szServerName + ); + + return pLdapHandle; +} + +BOOL +pWriteTableInfo ( + _In_ PGLOBAL_CONFIG pGlobalConfig, + _In_ PREQUEST_CONFIG pRequest, + _In_ BOOL bIsTop, + _In_ BOOL bIsRootDSE, + _In_z_ LPWSTR szRelativePath, + _In_z_ LPWSTR szTableName, + _In_z_ LPWSTR szTableNameNoDomain, + _In_ DWORD dwAttributesCount, + _In_ PATTRIBUTE_CONFIG *pAttributes +) +{ + DWORD dwColumsCount; + + // Results of RootDSE are merged in the same file. + // Be sure to write table info only once + if ((bIsRootDSE == TRUE) && (pRequest->bTableInfoWritten == TRUE)) + return TRUE; + else + pRequest->bTableInfoWritten = TRUE; + + // + // Count columns + // + if (bIsTop == TRUE) + dwColumsCount = dwAttributesCount + 3; // dn/server + shortname + shortdn + else + dwColumsCount = dwAttributesCount + 1; // dn/server + + for (DWORD i = 0; i < dwAttributesCount; i++) + { + if ((((*pAttributes[i]).Type == TYPE_INT) || ((*pAttributes[i]).Type == TYPE_INT64)) && ((*pAttributes[i]).fFilter != NULL)) + { + dwColumsCount++; // text + int + } + } + + // + // Write columns infos + // + // Relative path + WriteTextFile(pGlobalConfig->hTableFile, "%S\t", szRelativePath); + + // Table names + WriteTextFile(pGlobalConfig->hTableFile, "%S\t", szTableName); + WriteTextFile(pGlobalConfig->hTableFile, "%S\t", szTableNameNoDomain); + + WriteTextFile(pGlobalConfig->hTableFile, "%u\t", dwColumsCount); + + // Columns + if (bIsRootDSE == TRUE) + { + // For RootDSE, dwStrintMaxLengthShortName is used for 'server' max size + WriteTextFile(pGlobalConfig->hTableFile, "server\tnvarchar(%u)", (pRequest->dwStrintMaxLengthShortName / 2) + 1); + } + else + { + WriteTextFile(pGlobalConfig->hTableFile, "dn\tnvarchar(%u)", (pRequest->dwStrintMaxLengthDn / 2) + 1); + } + + if (bIsTop == TRUE) + { + // +1 to be sure to round to upper value (even) and avoid nvarchar(0) + WriteTextFile(pGlobalConfig->hTableFile, "\tshortname\tnvarchar(%u)", (pRequest->dwStrintMaxLengthShortName / 2) + 1); + WriteTextFile(pGlobalConfig->hTableFile, "\tshortdn\tnvarchar(%u)", (pRequest->dwStrintMaxLengthShortDn / 2) + 1); + } + + // + // Other columns + // + for (DWORD i = 0; i < dwAttributesCount; i++) + { + DWORD dwStrintMaxLength; + + // +1 to be sure to round to upper value (even) and avoid nvarchar(0) + dwStrintMaxLength = (pRequest->pdwStrintMaxLength[i] / 2) + 1; + + if ((*pAttributes[i]).Type == TYPE_INT) + { + if ((*pAttributes[i]).fFilter == NULL) + { + WriteTextFile(pGlobalConfig->hTableFile, "\t%S\tint", (*pAttributes[i]).szName); + } + else + { + WriteTextFile(pGlobalConfig->hTableFile, "\t%S\tnvarchar(%u)", (*pAttributes[i]).szName, dwStrintMaxLength); + WriteTextFile(pGlobalConfig->hTableFile, "\t%S_int\tint", (*pAttributes[i]).szName); + } + } + else if ((*pAttributes[i]).Type == TYPE_INT64) + { + if ((*pAttributes[i]).fFilter == NULL) + { + WriteTextFile(pGlobalConfig->hTableFile, "\t%S\tbigint", (*pAttributes[i]).szName); + } + else + { + WriteTextFile(pGlobalConfig->hTableFile, "\t%S\tnvarchar(%u)", (*pAttributes[i]).szName, dwStrintMaxLength); + WriteTextFile(pGlobalConfig->hTableFile, "\t%S_int\tbigint", (*pAttributes[i]).szName); + } + } + else + { + switch ((*pAttributes[i]).Type) + { + case TYPE_STR: + case TYPE_STRS: + { + // nvarchar(n) n must be from 1 through 4000 + if (dwStrintMaxLength < 4000) + WriteTextFile(pGlobalConfig->hTableFile, "\t%S\tnvarchar(%u)", (*pAttributes[i]).szName, dwStrintMaxLength); + else + WriteTextFile(pGlobalConfig->hTableFile, "\t%S\tnvarchar(max)", (*pAttributes[i]).szName); + break; + } + + case TYPE_SID: + case TYPE_SD: + case TYPE_DACL: + case TYPE_BIN: + { + // varchar(n) n must be from 1 through 8000 + if (dwStrintMaxLength < 8000) + WriteTextFile(pGlobalConfig->hTableFile, "\t%S\tvarchar(%u)", (*pAttributes[i]).szName, dwStrintMaxLength); + else + WriteTextFile(pGlobalConfig->hTableFile, "\t%S\tvarchar(max)", (*pAttributes[i]).szName); + break; + } + + case TYPE_GUID: + WriteTextFile(pGlobalConfig->hTableFile, "\t%S\tuniqueidentifier", (*pAttributes[i]).szName); + break; + + case TYPE_DATE: + case TYPE_DATEINT64: + WriteTextFile(pGlobalConfig->hTableFile, "\t%S\tdatetime2", (*pAttributes[i]).szName); + break; + + case TYPE_BOOL: + WriteTextFile(pGlobalConfig->hTableFile, "\t%S\ttinyint", (*pAttributes[i]).szName); + break; + + default: + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_ERROR, + "Data type unknown." + ); + return FALSE; + } + } + } + } + WriteTextFile(pGlobalConfig->hTableFile, "\n"); + + return TRUE; +} + +BOOL +pHasAttributeWithRange ( + _In_ LDAP *pLdapHandle, + _In_ LDAPMessage *pEntry, + _In_z_ LPWSTR szDn +) +{ + BOOL bReturn = FALSE; + LPWSTR szAttrName; + BerElement *berElt = NULL; + + // Search for attributes with range + szAttrName = ldap_first_attribute(pLdapHandle, pEntry, &berElt); + while (szAttrName != NULL) + { + if (wcsstr(szAttrName, L";range=") != 0) + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_VERBOSE, + "'%S' has attribute '%S' with range.", + szDn, szAttrName + ); + bReturn = TRUE; + break; + } + szAttrName = ldap_next_attribute(pLdapHandle, pEntry, berElt); + } + + ber_free(berElt, 0); + + return bReturn; +} + +BOOL +pParseRange ( + _In_ LDAP *pLdapHandle, + _In_ LDAPMessage *pEntry, + _In_z_ LPWSTR szAttribute, + _Out_ LPWSTR *pszAttrName, + _Out_ PDWORD pdwEnd +) +{ + BOOL bFound = FALSE; + BerElement *berElt = NULL; + LPWSTR szAttrName; + WCHAR szRangeAttrName[MAX_ATTRIBUTE_NAME]; + DWORD dwStart; + + // Search for attributes with range + szAttrName = ldap_first_attribute(pLdapHandle, pEntry, &berElt); + while (szAttrName != NULL) + { + if (_wcsicmp(szAttrName, L";range=") != 0) + { + int r; + + r = swscanf_s(szAttrName, L"%[a-zA-z0-9_-];range=%u-%u", szRangeAttrName, MAX_ATTRIBUTE_NAME - 1, &dwStart, pdwEnd); + + if (r == 3) + { + if (_wcsicmp(szAttribute, szRangeAttrName) == 0) + { + // This is our attribute with range + *pszAttrName = szAttrName; + bFound = TRUE; + break; + } + } + } + szAttrName = ldap_next_attribute(pLdapHandle, pEntry, berElt); + } + + ber_free(berElt, 0); + + return bFound; +} + +LPWSTR* +pGetRangedAttribute ( + _In_ LDAP* pLdapHandle, + _In_ LPWSTR szDn, + _In_ LPWSTR szAttribute, + _In_ PDWORD pdwRangeStart +) +{ + BOOL bResult; + ULONG ulResult; + + LDAPMessage *pLdapMessage = NULL; + LDAPMessage *pEntry = NULL; + + LPWSTR ptRangeAttributes[2] = { NULL }; + WCHAR szRangeAttrName[MAX_ATTRIBUTE_NAME + 20] = { 0 }; // 20: ';range=%d-*' + PWCHAR* ppValue = NULL; + LPWSTR szNewAttributeName = NULL; + + swprintf_s(szRangeAttrName, MAX_ATTRIBUTE_NAME + 20, L"%s;range=%d-*", szAttribute, *pdwRangeStart); + + ptRangeAttributes[0] = szRangeAttrName; + + ulResult = ldap_search_s( + pLdapHandle, + szDn, + LDAP_SCOPE_BASE, + (PWSTR)L"(objectClass=*)", + ptRangeAttributes, // attrs + 0, // attrsonly + &pLdapMessage + ); + + if (ulResult != LDAP_SUCCESS) + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_INFORMATION, + "Error in ldap_search_s() (error %u: %s).", ulResult, ldap_err2stringA(ulResult) + ); + goto End; + } + + pEntry = ldap_first_entry(pLdapHandle, pLdapMessage); + if (pEntry == NULL) + goto End; + + ppValue = ldap_get_values(pLdapHandle, pEntry, szRangeAttrName); + if (ppValue == NULL) + { + bResult = pParseRange(pLdapHandle, pEntry, szAttribute, &szNewAttributeName, pdwRangeStart); + if ((bResult == TRUE) && (szNewAttributeName != NULL)) + { + ppValue = ldap_get_values(pLdapHandle, pEntry, szNewAttributeName); + } + else + { + ldap_value_free(ppValue); + ppValue = NULL; + } + } + else + { + *pdwRangeStart = 0; + } + +End: + ldap_msgfree(pLdapMessage); + + return ppValue; +} \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Main.cpp b/Main.cpp new file mode 100644 index 0000000..70dcbf3 --- /dev/null +++ b/Main.cpp @@ -0,0 +1,101 @@ +#include +#include +#include +#include "ORADAD.h" + +#pragma comment(lib, "msxml6.lib") +#pragma comment(lib, "wldap32.lib") +#pragma comment(lib, "rpcrt4.lib") +#pragma comment(lib, "NetApi32.lib") + +HANDLE g_hHeap = NULL; +HANDLE g_hLogFile = NULL; + +GLOBAL_CONFIG g_GlobalConfig = { 0 }; + +int +wmain ( + int argc, + wchar_t *argv[] +) +{ + HRESULT hr; + SYSTEMTIME st; + IXMLDOMDocument2 *pXMLDoc = NULL; + + // + // Check command line parameters + // + if (argc != 2) + { + fprintf_s(stderr, "Usage: oradad.exe \n"); + return EXIT_FAILURE; + } + + // + // Start logging + // + g_hLogFile = CreateFile(TEXT("oradad.log"), GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, 0, NULL); + if (g_hLogFile == INVALID_HANDLE_VALUE) + { + fprintf_s(stderr, "[!] Unable to open log file. Exit.\n"); + return EXIT_FAILURE; + } + SetFilePointer(g_hLogFile, 0, 0, FILE_END); + + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_INFORMATION, + "Starting." + ); + + // + // Initialization + // + g_hHeap = HeapCreate(0, 0, 0); + if (g_hHeap == NULL) + { + return EXIT_FAILURE; + } + hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); + + // + // Read configuration + // + pXMLDoc = (IXMLDOMDocument2 *)XmlReadConfigFile((LPTSTR)TEXT("config-oradad.xml"), &g_GlobalConfig); + if (pXMLDoc == NULL) + goto End; + + // + // Main process + // + DuplicateString(argv[1], &g_GlobalConfig.szOutDirectory); + + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_VERBOSE, + "Output directory is '%S'.", g_GlobalConfig.szOutDirectory + ); + + GetSystemTime(&st); + swprintf_s( + g_GlobalConfig.szSystemTime, 17, + L"%04u%02u%02u-%02u%02u%02u", + st.wYear, st.wMonth, st.wDay, + st.wHour, st.wMinute, st.wSecond + ); + + Process(&g_GlobalConfig); + + // + // Release + // +End: + _SafeHeapRelease(g_GlobalConfig.szOutDirectory); + HeapDestroy(g_hHeap); + + _SafeCOMRelease(pXMLDoc); + CoUninitialize(); + + CloseHandle(g_hLogFile); + + return EXIT_SUCCESS; +} \ No newline at end of file diff --git a/ORADAD.h b/ORADAD.h new file mode 100644 index 0000000..58a973c --- /dev/null +++ b/ORADAD.h @@ -0,0 +1,11 @@ +#include "Structures.h" +#include "Functions.h" + +// +// Macros +// +#define _HeapAlloc(x) HeapAlloc(g_hHeap, HEAP_ZERO_MEMORY, (x)) +#define _SafeHeapRelease(x) { if (NULL != x) { HeapFree(g_hHeap, 0, x); x = NULL; } } +#define _SafeCOMRelease(x) { if (NULL != x) { x->Release(); x = NULL; } } + +#define _CallWriteAndGetMax(x, y) do { DWORD dwTempSizeResult; dwTempSizeResult = x; if (dwTempSizeResult>y) y=dwTempSizeResult; } while(FALSE) \ No newline at end of file diff --git a/ORADAD.rc b/ORADAD.rc new file mode 100644 index 0000000..ea5f006 Binary files /dev/null and b/ORADAD.rc differ diff --git a/ORADAD.sln b/ORADAD.sln new file mode 100644 index 0000000..754f790 --- /dev/null +++ b/ORADAD.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2035 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ORADAD", "ORADAD.vcxproj", "{81A611C5-6450-4A60-B6FD-8B4031B44E6E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {81A611C5-6450-4A60-B6FD-8B4031B44E6E}.Debug|x64.ActiveCfg = Debug|x64 + {81A611C5-6450-4A60-B6FD-8B4031B44E6E}.Debug|x64.Build.0 = Debug|x64 + {81A611C5-6450-4A60-B6FD-8B4031B44E6E}.Debug|x86.ActiveCfg = Debug|Win32 + {81A611C5-6450-4A60-B6FD-8B4031B44E6E}.Debug|x86.Build.0 = Debug|Win32 + {81A611C5-6450-4A60-B6FD-8B4031B44E6E}.Release|x64.ActiveCfg = Release|x64 + {81A611C5-6450-4A60-B6FD-8B4031B44E6E}.Release|x64.Build.0 = Release|x64 + {81A611C5-6450-4A60-B6FD-8B4031B44E6E}.Release|x86.ActiveCfg = Release|Win32 + {81A611C5-6450-4A60-B6FD-8B4031B44E6E}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A1F3AECE-F96E-4BAC-A2C6-30F493596973} + EndGlobalSection +EndGlobal diff --git a/ORADAD.vcxproj b/ORADAD.vcxproj new file mode 100644 index 0000000..08dbfe2 --- /dev/null +++ b/ORADAD.vcxproj @@ -0,0 +1,173 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 15.0 + {81A611C5-6450-4A60-B6FD-8B4031B44E6E} + Win32Proj + ORADAD + 10.0.17134.0 + + + + Application + true + v141 + Unicode + + + Application + false + v141 + true + Unicode + + + Application + true + v141 + Unicode + + + Application + false + v141 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + Level3 + Disabled + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + MultiThreadedDebug + + + true + Console + $(OutDir)$(TargetName)-x86$(TargetExt) + + + + + Level3 + Disabled + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + MultiThreadedDebug + + + true + Console + + + + + Level3 + MaxSpeed + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + MultiThreaded + + + true + true + true + Console + $(OutDir)$(TargetName)-x86$(TargetExt) + + + + + Level3 + MaxSpeed + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + MultiThreaded + + + true + true + true + Console + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ORADAD.vcxproj.filters b/ORADAD.vcxproj.filters new file mode 100644 index 0000000..2297f45 --- /dev/null +++ b/ORADAD.vcxproj.filters @@ -0,0 +1,62 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Fichiers sources + + + Fichiers sources + + + Fichiers sources + + + Fichiers sources + + + Fichiers sources + + + Fichiers sources + + + Fichiers sources + + + + + Fichiers d%27en-tête + + + Fichiers d%27en-tête + + + Fichiers d%27en-tête + + + Fichiers d%27en-tête + + + Fichiers d%27en-tête + + + + + Fichiers de ressources + + + \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..963e768 --- /dev/null +++ b/README.md @@ -0,0 +1,12 @@ +# ORADAD +Outil de Récupération Automatique des Données de l'Active Directory + +## Configuration + +Voir les parties `` dans le fichier `config-oradad.xml`. + +## Lancement + +`ORADAD.exe ` + +La configuration est lue depuis le fichier `config-oradad.xml` qui doit se trouver dans le même repertoire qu'`ORADAD.exe`. diff --git a/Structures.h b/Structures.h new file mode 100644 index 0000000..6ad23fd --- /dev/null +++ b/Structures.h @@ -0,0 +1,181 @@ +// +// Log levels +// +#define LOG_LEVEL_NONE 0 // Tracing is not on +#define LOG_LEVEL_CRITICAL 1 // Abnormal exit or termination +#define LOG_LEVEL_ERROR 2 // Severe errors that need logging +#define LOG_LEVEL_WARNING 3 // Warnings such as allocation failure +#define LOG_LEVEL_INFORMATION 4 // Includes non-error cases(e.g.,Entry-Exit) +#define LOG_LEVEL_VERBOSE 5 // Detailed traces from intermediate steps +#define LOG_LEVEL_VERYVERBOSE 6 + +// +// Naming context +// +#define STR_ROOTDSE L"rootDSE" +#define STR_DOMAIN L"domain" +#define STR_CONFIGURATION L"configuration" +#define STR_SCHEMA L"schema" +#define STR_DOMAIN_DNS L"domaindns" +#define STR_FOREST_DNS L"forestdns" + +// +// Filters +// +typedef +BOOL +(*tFilter)( + _In_ PVOID pvData, + _In_ PVOID pvParam, + _Outptr_ LPWSTR *szResult + ); + +// +// Constants +// +typedef struct _CONST_TXT { + DWORD dwConst; // If szTxt==NULL, dwConst indicates filter mode (Flag or Type) + LPCWSTR szTxt; +} CONST_TXT, *PCONST_TXT; + +// +// Configuration +// +typedef enum _BASE_TYPE +{ + BASE_ROOTDSE = 1, + BASE_DOMAIN = 2, + BASE_CONFIGURATION = 4, + BASE_SCHEMA = 8, + BASE_DOMAIN_DNS = 16, + BASE_FOREST_DNS = 32 +} BASE_TYPE; + +typedef enum _ATTRIBUTE_TYPE +{ + TYPE_STR = 1, + TYPE_STRS, + TYPE_SID, + TYPE_SD, + TYPE_DACL, + TYPE_GUID, + TYPE_DATE, + TYPE_DATEINT64, + TYPE_INT, + TYPE_INT64, + TYPE_BOOL, + TYPE_BIN +} ATTRIBUTE_TYPE; + +typedef enum _FILTER_MODE +{ + FILTER_FLAG = 1, + FILTER_TYPE = 2 +} FILTER_MODE; + +typedef struct _ATTRIBUTE_CONFIG +{ + LPWSTR szName; + DWORD dwLevel; + ATTRIBUTE_TYPE Type; + tFilter fFilter; + PVOID pvFilterData; +} ATTRIBUTE_CONFIG, *PATTRIBUTE_CONFIG; + +typedef struct _CLASS_CONFIG +{ + LPWSTR szName; + LPWSTR szAuxiliaryClass; + LPWSTR szSystemAuxiliaryClass; + + DWORD dwAttributesCount; + PATTRIBUTE_CONFIG *pAttributes; +} CLASS_CONFIG, *PCLASS_CONFIG; + +typedef struct _ROOTDSE_CONFIG +{ + LPWSTR dnsHostName; + LPWSTR serverName; + + LPWSTR defaultNamingContext; + LPWSTR rootDomainNamingContext; + LPWSTR configurationNamingContext; + LPWSTR schemaNamingContext; + LPWSTR domainDnsNamingContext; + LPWSTR forestDnsNamingContext; + + LPWSTR domainControllerFunctionality; + LPWSTR domainFunctionality; + LPWSTR forestFunctionality; + + BOOL bIsLocalAdmin; +} ROOTDSE_CONFIG, *PROOTDSE_CONFIG; + +typedef struct _CONTROL_LDAP +{ + LPWSTR szOid; + LPWSTR szValue; + BOOL isCritical; +} CONTROL_LDAP, *PCONTROL_LDAP; + +typedef struct _REQUEST_CONFIG +{ + LPWSTR szName; + DWORD dwBase; + DWORD dwScope; + LPWSTR szFilter; + + DWORD dwAttributesCount; + PATTRIBUTE_CONFIG *pAttributes; + + DWORD dwControlsCount; + PCONTROL_LDAP pControls; + + DWORD dwStrintMaxLengthShortName; + DWORD dwStrintMaxLengthDn; + DWORD dwStrintMaxLengthShortDn; + + // Per request atttribute text max size + PDWORD pdwStrintMaxLength; + + BOOL bTableInfoWritten; +} REQUEST_CONFIG, *PREQUEST_CONFIG; + +typedef struct _GLOBAL_CONFIG +{ + WCHAR szSystemTime[17]; + + LPWSTR szOutDirectory; + HANDLE hTableFile; + BOOL bWriteHeader; + + LPWSTR szServer; + ULONG ulLdapPort; + LPWSTR szUsername; + LPWSTR szUserDomain; + LPWSTR szUserPassword; + + DWORD dwLevel; + BOOL bAllDomainsInForest; + BOOL dwSleepTime; + + DWORD dwRequestCount; + PREQUEST_CONFIG pRequests; + + DWORD dwRootDSEAttributesCount; + DWORD dwAttributesCount; + PATTRIBUTE_CONFIG pRootDSEAttributes; + PATTRIBUTE_CONFIG pAttributes; +} GLOBAL_CONFIG, *PGLOBAL_CONFIG; + +// +// Buffer +// +typedef struct _BUFFER_DATA +{ + SIZE_T BufferSize; + SIZE_T Position; + PBYTE pbData; + HANDLE hOutputFile; + TCHAR szFileName[MAX_PATH]; +} BUFFER_DATA, *PBUFFER_DATA; \ No newline at end of file diff --git a/Util.cpp b/Util.cpp new file mode 100644 index 0000000..d701f5e --- /dev/null +++ b/Util.cpp @@ -0,0 +1,214 @@ +#include +#include +#include +#include "ORADAD.h" + +#define MSG_MAX_SIZE 8192 +#define INFO_MAX_SIZE MSG_MAX_SIZE + 256 // 256: "%04u/%02u/%02u - %02u:%02u:%02u.%03u\t%d\t%s\t%s\t%d\t" + ... + "\r\n", + +extern HANDLE g_hHeap; +extern HANDLE g_hLogFile; + +VOID +Log ( + _In_z_ LPCSTR szFile, + _In_z_ LPCSTR szFunction, + _In_ DWORD dwLine, + _In_ DWORD dwLevel, + _In_z_ LPCSTR szFormat, + ... +) +{ + int r; + + CHAR szMessage[MSG_MAX_SIZE]; + SYSTEMTIME st; + + va_list argptr; + va_start(argptr, szFormat); + + GetLocalTime(&st); + + r = vsprintf_s(szMessage, MSG_MAX_SIZE, szFormat, argptr); + if (r == -1) + { + return; + } + + if (dwLevel <= LOG_LEVEL_INFORMATION) + printf("%s\n", szMessage); + + if (dwLevel <= LOG_LEVEL_VERBOSE) + { + DWORD dwDataSize, dwDataWritten; + CHAR szLine[INFO_MAX_SIZE]; + + sprintf_s( + szLine, INFO_MAX_SIZE, + "%04u/%02u/%02u - %02u:%02u:%02u.%03u\t%d\t%s\t%s\t%d\t%s\r\n", + st.wYear, st.wMonth, st.wDay, + st.wHour, st.wMinute, st.wSecond, st.wMilliseconds, + dwLevel, szFile, szFunction, dwLine, + szMessage + ); + + dwDataSize = (DWORD)strnlen_s(szLine, INFO_MAX_SIZE); + WriteFile(g_hLogFile, szLine, dwDataSize, &dwDataWritten, NULL); + } +} + +VOID +DuplicateString ( + _In_z_ LPWSTR szInput, + _Out_ LPWSTR *szOutput +) +{ + size_t InputSize; + + if ((szInput == NULL) || (szOutput == NULL)) + return; + + InputSize = wcslen(szInput); + *szOutput = (LPWSTR)_HeapAlloc((InputSize + 1) * sizeof(WCHAR)); + memcpy(*szOutput, szInput, InputSize * sizeof(WCHAR)); +} + +// +// Convert "DC=domain,DC=tld" to "domain.tld" +// +LPWSTR +ConvertDnToDns ( + _In_z_ LPWSTR szString +) +{ + LPWSTR szCurrent; + LPWSTR szNext; + LPWSTR szReturn; + size_t SizeString; + DWORD dwPosition = 0; + + SizeString = wcslen(szString); + szReturn = (LPWSTR)_HeapAlloc((SizeString + 1) * sizeof(WCHAR)); + if (szReturn == NULL) + return NULL; + + szCurrent = szString; + szCurrent += 3; // Bypass first 'DC=' (3 chars) + szNext = wcsstr(szCurrent, L",DC="); + + while ((szCurrent != NULL) && (szNext != NULL) && (szCurrent < (szString + SizeString))) + { + DWORD dwSize; + + dwSize = szNext - szCurrent; + memcpy(szReturn + dwPosition, szCurrent, dwSize * sizeof(WCHAR)); + memset(szReturn + dwPosition + dwSize, 0, sizeof(WCHAR)); // Null terminates szReturn (otherwise wcscat_s failed) + wcscat_s(szReturn, SizeString, L"."); + dwPosition += (dwSize + 1); // +1 for '.' + + szCurrent = szNext; + szCurrent += 4; // Bypass ',DC=' (4 chars) + szNext = wcsstr(szCurrent, L",DC="); + } + + wcscat_s(szReturn, SizeString, szCurrent); + + return szReturn; +} + +VOID +RemoveSpecialChars ( + _In_z_ LPWSTR szString +) +{ + // Remove \r \n \t + if (szString) + { + while (*szString) + { + if (*szString == 0x0a) + *szString = 0x20; + else if (*szString == 0x0d) + *szString = 0x20; + else if (*szString == 0x09) + *szString = 0x20; + szString++; + } + } +} + +BOOL +WriteTextFile ( + _In_ HANDLE hFile, + _In_z_ LPCSTR szFormat, + ... +) +{ + BOOL bReturn; + DWORD dwDataSize, dwDataWritten; + CHAR szMessage[MSG_MAX_SIZE]; + + va_list argptr; + va_start(argptr, szFormat); + + vsprintf_s(szMessage, MSG_MAX_SIZE, szFormat, argptr); + + dwDataSize = (DWORD)strnlen_s(szMessage, MSG_MAX_SIZE); + bReturn = WriteFile(hFile, szMessage, dwDataSize, &dwDataWritten, NULL); + + return bReturn; +} + +LPSTR +LPWSTRtoLPSTR ( + _In_opt_z_ LPWSTR szToConvert +) +{ + LPSTR szResult; + int iSize; + + if (szToConvert == NULL) + return NULL; + + iSize = WideCharToMultiByte( + CP_ACP, + 0, + szToConvert, + -1, + NULL, 0, + NULL, NULL + ); + + if (iSize == 0) + goto Fail; + + szResult = (LPSTR)HeapAlloc(g_hHeap, HEAP_ZERO_MEMORY, iSize + 1); + + if (szResult == NULL) + goto Fail; + + iSize = WideCharToMultiByte( + CP_ACP, + 0, + szToConvert, + -1, + szResult, iSize, + NULL, NULL + ); + + if (iSize == 0) + { + _SafeHeapRelease(szResult); + goto Fail; + } + + return szResult; + +Fail: + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_ERROR, 0, + "LPWSTRtoLPSTR(%S) failed.", szToConvert + ); + + return NULL; +} diff --git a/XML.cpp b/XML.cpp new file mode 100644 index 0000000..f2c9395 --- /dev/null +++ b/XML.cpp @@ -0,0 +1,817 @@ +#include +#include +#include +#include "ORADAD.h" + +extern HANDLE g_hHeap; + +// +// Private functions +// +BOOL +pReadAttributes( + _In_ IXMLDOMDocument2 *pXMLDoc, + _In_z_ LPCWSTR szXPath, + _Outptr_ PDWORD dwAttributesCount, + _Outptr_ PATTRIBUTE_CONFIG *pAttributes +); + +BOOL +pReadAttributeString( + _In_ IXMLDOMNamedNodeMap *pXmlAttributeMap, + _In_z_ LPWSTR szAttributeName, + _Out_ LPWSTR *szValue +); + +BOOL +pReadAttributeInterger( + _In_ IXMLDOMNamedNodeMap *pXmlAttributeMap, + _In_z_ LPWSTR szAttributeName, + _Out_ PDWORD pdwValue +); + +BOOL +pAddClassAttributes( + _In_ IXMLDOMDocument2 *pXMLDoc, + _In_z_ LPWSTR szClassName, + _In_z_ PCLASS_CONFIG pClass, + _In_ DWORD dwAttributesCount, + _In_ PATTRIBUTE_CONFIG pAttributes +); + +BOOL +pAddClassesToRequest( + _In_ IXMLDOMDocument2 *pXMLDoc, + _In_z_ LPWSTR szClassName, + PREQUEST_CONFIG pRequest, + _In_ PGLOBAL_CONFIG pGlobalConfig +); + +PATTRIBUTE_CONFIG +pFindAttribute( + _In_ DWORD dwAttributesCount, + _In_ PATTRIBUTE_CONFIG pAttributes, + _In_z_ LPWSTR szName +); + +BOOL +pXmlParseRequest( + _In_ IXMLDOMDocument2 *pXMLDoc, + IXMLDOMNode *pXmlNodeRequet, + PREQUEST_CONFIG pRequests, + _In_ PGLOBAL_CONFIG pGlobalConfig +); + +DWORD +pReadUInteger( + _In_opt_z_ LPCWSTR szValue +); + +BOOL +pReadBoolean( + _In_opt_z_ LPCWSTR szValue +); + +// +// Public functions +// +// Note: we return PVOID to avoid include msxml.h in all files. +PVOID +XmlReadConfigFile ( + _In_z_ LPTSTR szConfigPath, + _In_ PGLOBAL_CONFIG pGlobalConfig +) +{ + BOOL bResult; + HRESULT hr; + VARIANT_BOOL bSuccess = false; + + IXMLDOMDocument2 *pXMLDoc = NULL; + IXMLDOMNode *pXMLNode = NULL; + IXMLDOMNodeList *pXMLNodeList = NULL; + + long lLength; + + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_VERBOSE, + "Read config file." + ); + + hr = CoCreateInstance(CLSID_FreeThreadedDOMDocument60, NULL, CLSCTX_INPROC_SERVER, IID_IXMLDOMDocument2, (void**)&pXMLDoc); + if ((hr != S_OK) || (pXMLDoc == NULL)) + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_CRITICAL, + "Unable to create XML object (error 0x%08x).", hr + ); + return NULL; + } + + hr = pXMLDoc->put_async(VARIANT_FALSE); + //hr = pXMLDoc->setProperty(L"SelectionLanguage", L"XPath"); + + // + // Load file + // + hr = pXMLDoc->load(CComVariant(szConfigPath), &bSuccess); + + if ((hr != S_OK) || (bSuccess == FALSE)) + { + IXMLDOMParseError *pXmlParseError = NULL; + BSTR strError; + LPSTR szError; + + hr = pXMLDoc->get_parseError(&pXmlParseError); + hr = pXmlParseError->get_reason(&strError); + + RemoveSpecialChars(strError); + szError = LPWSTRtoLPSTR(strError); + + if (szError != NULL) + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_CRITICAL, + "Unable to parse XML (%s).", szError + ); + _SafeHeapRelease(szError); + } + + _SafeCOMRelease(pXmlParseError); + _SafeCOMRelease(pXMLDoc); + return NULL; + } + + // + // Read Main Config + // + hr = pXMLDoc->selectSingleNode((BSTR)TEXT("/configORADAD/config"), &pXMLNode); + hr = pXMLNode->get_childNodes(&pXMLNodeList); + hr = pXMLNodeList->get_length(&lLength); + + for (long i = 0; i < lLength; i++) + { + IXMLDOMNode *pXmlNodeConfig = NULL; + BSTR strNodeName; + BSTR strNodeText; + + hr = pXMLNodeList->get_item(i, &pXmlNodeConfig); + hr = pXmlNodeConfig->get_nodeName(&strNodeName); + hr = pXmlNodeConfig->get_text(&strNodeText); + + if ((wcscmp(strNodeName, L"server") == 0) && (wcslen(strNodeText) > 0)) + pGlobalConfig->szServer = strNodeText; + if ((wcscmp(strNodeName, L"port") == 0) && (wcslen(strNodeText) > 0)) + pGlobalConfig->ulLdapPort = pReadUInteger(strNodeText); + else if ((wcscmp(strNodeName, L"username") == 0) && (wcslen(strNodeText) > 0)) + pGlobalConfig->szUsername = strNodeText; + else if ((wcscmp(strNodeName, L"userdomain") == 0) && (wcslen(strNodeText) > 0)) + pGlobalConfig->szUserDomain = strNodeText; + else if ((wcscmp(strNodeName, L"userpassword") == 0) && (wcslen(strNodeText) > 0)) + pGlobalConfig->szUserPassword = strNodeText; + else if ((wcscmp(strNodeName, L"allDomainsInForest") == 0) && (wcslen(strNodeText) > 0)) + pGlobalConfig->bAllDomainsInForest = pReadBoolean(strNodeText); + else if ((wcscmp(strNodeName, L"level") == 0) && (wcslen(strNodeText) > 0)) + pGlobalConfig->dwLevel = pReadUInteger(strNodeText); + else if ((wcscmp(strNodeName, L"sleepTime") == 0) && (wcslen(strNodeText) > 0)) + pGlobalConfig->dwSleepTime = pReadUInteger(strNodeText); + else if ((wcscmp(strNodeName, L"writeHeader") == 0) && (wcslen(strNodeText) > 0)) + pGlobalConfig->bWriteHeader = pReadBoolean(strNodeText); + + _SafeCOMRelease(pXmlNodeConfig); + } + + _SafeCOMRelease(pXMLNodeList); + _SafeCOMRelease(pXMLNode); + + // + // Read Attributes + // + bResult = pReadAttributes(pXMLDoc, L"/configORADAD/schema/rootDSEAttributes/attribute", &pGlobalConfig->dwRootDSEAttributesCount, &pGlobalConfig->pRootDSEAttributes); + if (bResult == FALSE) + return NULL; + bResult = pReadAttributes(pXMLDoc, L"/configORADAD/schema/attributes/attribute", &pGlobalConfig->dwAttributesCount, &pGlobalConfig->pAttributes); + if (bResult == FALSE) + return NULL; + + // + // Read Requests + // + hr = pXMLDoc->selectNodes((BSTR)TEXT("/configORADAD/requests/request"), &pXMLNodeList); + hr = pXMLNodeList->get_length(&lLength); + + pGlobalConfig->dwRequestCount = lLength; + pGlobalConfig->pRequests = (PREQUEST_CONFIG)_HeapAlloc(lLength * sizeof(REQUEST_CONFIG)); + + for (long i = 0; i < lLength; i++) + { + BOOL bResult; + + IXMLDOMNode *pXmlNodeRequet = NULL; + IXMLDOMNodeList *pXmlNodeListRequet = NULL; + + hr = pXMLNodeList->get_item(i, &pXmlNodeRequet); + + bResult = pXmlParseRequest(pXMLDoc, pXmlNodeRequet, &pGlobalConfig->pRequests[i], pGlobalConfig); + if (bResult == FALSE) + return NULL; + + if (pGlobalConfig->pRequests[i].dwBase & BASE_ROOTDSE) + { + // RootDSE can only be RootDSE. Disable other types + pGlobalConfig->pRequests[i].dwBase = BASE_ROOTDSE; + + // Allocate per request max attribute text size + pGlobalConfig->pRequests[i].pdwStrintMaxLength = (PDWORD)_HeapAlloc(sizeof(DWORD) * pGlobalConfig->dwRootDSEAttributesCount); + } + else + { + // Allocate per request max attribute text size + pGlobalConfig->pRequests[i].pdwStrintMaxLength = (PDWORD)_HeapAlloc(sizeof(DWORD) * pGlobalConfig->pRequests[i].dwAttributesCount); + } + + // Free COM + _SafeCOMRelease(pXmlNodeListRequet); + _SafeCOMRelease(pXmlNodeRequet); + } + + _SafeCOMRelease(pXMLNodeList); + + // + // Display requests and attributes for debug + // + /* + for (DWORD i = 0; i < pGlobalConfig->dwRequestCount; i++) + { + wprintf_s(L"%s\n", pGlobalConfig->pRequests[i].szName); + for (DWORD j = 0; j < pGlobalConfig->pRequests[i].dwAttributesCount; j++) + { + wprintf_s(L" %s\n", pGlobalConfig->pRequests[i].pAttributes[j]->szName); + } + wprintf_s(L"\n"); + } + */ + + return pXMLDoc; +} + +// +// Private functions +// +BOOL +pReadAttributes ( + _In_ IXMLDOMDocument2 *pXMLDoc, + _In_z_ LPCWSTR szXPath, + _Outptr_ PDWORD dwAttributesCount, + _Outptr_ PATTRIBUTE_CONFIG *pAttributes +) +{ + HRESULT hr; + + IXMLDOMNodeList *pXMLNodeList = NULL; + + long lLength; + + hr = pXMLDoc->selectNodes((BSTR)szXPath, &pXMLNodeList); + + hr = pXMLNodeList->get_length(&lLength); + + *dwAttributesCount = lLength; + *pAttributes = (PATTRIBUTE_CONFIG)_HeapAlloc(lLength * sizeof(ATTRIBUTE_CONFIG)); + + for (long i = 0; i < lLength; i++) + { + LPWSTR szType; + LPWSTR szFilter; + + IXMLDOMNode *pXmlNodeAttribute = NULL; + IXMLDOMNamedNodeMap *pXmlAttributeMap = NULL; + + hr = pXMLNodeList->get_item(i, &pXmlNodeAttribute); + hr = pXmlNodeAttribute->get_attributes(&pXmlAttributeMap); + + pReadAttributeString(pXmlAttributeMap, (LPWSTR)L"name", &(*pAttributes)[i].szName); + pReadAttributeInterger(pXmlAttributeMap, (LPWSTR)L"level", &(*pAttributes)[i].dwLevel); + pReadAttributeString(pXmlAttributeMap, (LPWSTR)L"type", &szType); + pReadAttributeString(pXmlAttributeMap, (LPWSTR)L"filter", &szFilter); + + if (szFilter != NULL) + { + BOOL bResult; + + bResult = GetFilter(&(*pAttributes)[i], szFilter); + if (bResult == FALSE) + return FALSE; + } + + if (_wcsicmp(szType, L"STR") == 0) + (*pAttributes)[i].Type = TYPE_STR; + else if (_wcsicmp(szType, L"STRS") == 0) + (*pAttributes)[i].Type = TYPE_STRS; + else if (_wcsicmp(szType, L"SID") == 0) + (*pAttributes)[i].Type = TYPE_SID; + else if (_wcsicmp(szType, L"SD") == 0) + (*pAttributes)[i].Type = TYPE_SD; + else if (_wcsicmp(szType, L"DACL") == 0) + (*pAttributes)[i].Type = TYPE_DACL; + else if (_wcsicmp(szType, L"GUID") == 0) + (*pAttributes)[i].Type = TYPE_GUID; + else if (_wcsicmp(szType, L"DATE") == 0) + (*pAttributes)[i].Type = TYPE_DATE; + else if (_wcsicmp(szType, L"DATEINT64") == 0) + (*pAttributes)[i].Type = TYPE_DATEINT64; + else if (_wcsicmp(szType, L"INT") == 0) + (*pAttributes)[i].Type = TYPE_INT; + else if (_wcsicmp(szType, L"INT64") == 0) + (*pAttributes)[i].Type = TYPE_INT64; + else if (_wcsicmp(szType, L"BOOL") == 0) + (*pAttributes)[i].Type = TYPE_BOOL; + else if (_wcsicmp(szType, L"BIN") == 0) + (*pAttributes)[i].Type = TYPE_BIN; + else + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_CRITICAL, + "Unknown type (%S).", szType + ); + return FALSE; + } + + _SafeCOMRelease(pXmlAttributeMap); + _SafeCOMRelease(pXmlNodeAttribute); + } + + _SafeCOMRelease(pXMLNodeList); + + return TRUE; +} + +BOOL +pReadAttributeString ( + _In_ IXMLDOMNamedNodeMap *pXmlAttributeMap, + _In_z_ LPWSTR szAttributeName, + _Out_ LPWSTR *szValue +) +{ + HRESULT hr; + IXMLDOMNode *pXmlNodeAttribute = NULL; + BSTR strName; + + hr = pXmlAttributeMap->getNamedItem((BSTR)szAttributeName, &pXmlNodeAttribute); + if (hr == S_OK) + { + hr = pXmlNodeAttribute->get_text(&strName); + *szValue = (LPTSTR)strName; + + _SafeCOMRelease(pXmlNodeAttribute); + } + else + *szValue = NULL; + + return TRUE; +} + +BOOL +pReadAttributeInterger ( + _In_ IXMLDOMNamedNodeMap *pXmlAttributeMap, + _In_z_ LPWSTR szAttributeName, + _Out_ PDWORD pdwValue +) +{ + HRESULT hr; + int r; + IXMLDOMNode *pXmlNodeAttribute = NULL; + BSTR strName; + DWORD dwValue; + + hr = pXmlAttributeMap->getNamedItem((BSTR)szAttributeName, &pXmlNodeAttribute); + hr = pXmlNodeAttribute->get_text(&strName); + + r = swscanf_s(strName, L"%u", &dwValue); + *pdwValue = dwValue; + + _SafeCOMRelease(pXmlNodeAttribute); + + return TRUE; +} + +BOOL +pAddClassAttributes ( + _In_ IXMLDOMDocument2 *pXMLDoc, + _In_z_ LPWSTR szClassName, + _In_z_ PCLASS_CONFIG pClass, + _In_ DWORD dwAttributesCount, + _In_ PATTRIBUTE_CONFIG pAttributes +) +{ + HRESULT hr; + WCHAR szXPath[MAX_PATH]; + IXMLDOMNodeList *pXMLNodeList = NULL; + + DWORD dwInitialLength; + long lLength; + + BOOL bAttributeNotFound = FALSE; + + swprintf_s(szXPath, MAX_PATH, L"/configORADAD/schema/classes/class[@name=\"%s\"]/attribute", szClassName); + + hr = pXMLDoc->selectNodes(szXPath, &pXMLNodeList); + hr = pXMLNodeList->get_length(&lLength); + if (lLength == 0) + { + return TRUE; + } + + dwInitialLength = pClass->dwAttributesCount; + pClass->dwAttributesCount += lLength; + + if (dwInitialLength == 0) + { + pClass->pAttributes = (PATTRIBUTE_CONFIG*)_HeapAlloc(pClass->dwAttributesCount * sizeof(ATTRIBUTE_CONFIG)); + } + else + { + pClass->pAttributes = (PATTRIBUTE_CONFIG*)HeapReAlloc(g_hHeap, HEAP_ZERO_MEMORY, pClass->pAttributes, pClass->dwAttributesCount * sizeof(ATTRIBUTE_CONFIG)); + } + + for (long i = 0; i < lLength; i++) + { + LPWSTR szAttributeName; + PATTRIBUTE_CONFIG pAttribute; + + IXMLDOMNode *pXmlNode = NULL; + IXMLDOMNamedNodeMap *pXmlClassMap = NULL; + + hr = pXMLNodeList->get_item(i, &pXmlNode); + hr = pXmlNode->get_attributes(&pXmlClassMap); + + pReadAttributeString(pXmlClassMap, (LPWSTR)L"name", &szAttributeName); + + pAttribute = pFindAttribute(dwAttributesCount, pAttributes, szAttributeName); + if (pAttribute == NULL) + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_CRITICAL, + "Attribute not found (%S).", szAttributeName + ); + bAttributeNotFound = TRUE; + } + + pClass->pAttributes[dwInitialLength + i] = pAttribute; + + _SafeCOMRelease(pXmlClassMap); + _SafeCOMRelease(pXmlNode); + } + + _SafeCOMRelease(pXMLNodeList); + + if (bAttributeNotFound == TRUE) + return FALSE; + else + return TRUE; +} + +_Outptr_result_maybenull_ +PATTRIBUTE_CONFIG +pFindAttribute ( + _In_ DWORD dwAttributesCount, + _In_ PATTRIBUTE_CONFIG pAttributes, + _In_z_ LPWSTR szName +) +{ + for (DWORD i = 0; i < dwAttributesCount; i++) + { + if (_wcsicmp(pAttributes[i].szName, szName) == 0) + return &pAttributes[i]; + } + + return NULL; +} + +BOOL +pGetAttributeByNameForRequest ( + _In_z_ LPWSTR szAttributeName, + _Outptr_ PATTRIBUTE_CONFIG *pAttributes, + _In_ PGLOBAL_CONFIG pGlobalConfig +) +{ + for (DWORD i = 0; i < pGlobalConfig->dwAttributesCount; i++) + { + if (_wcsicmp(szAttributeName, pGlobalConfig->pAttributes[i].szName) == 0) + { + *pAttributes = &pGlobalConfig->pAttributes[i]; + return TRUE; + } + } + + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_CRITICAL, + "Attribute '%S' not found.", szAttributeName + ); + return FALSE; +} + +BOOL +pAddClassToRequest ( + _In_ IXMLDOMDocument2 *pXMLDoc, + _In_z_ LPWSTR szClassName, + PREQUEST_CONFIG pRequest, + _In_ PGLOBAL_CONFIG pGlobalConfig +) +{ + HRESULT hr; + BOOL bReturn = TRUE; + + WCHAR szXPath[MAX_PATH]; + long lLength; + + IXMLDOMNodeList *pXMLNodeListClass = NULL; + IXMLDOMNodeList *pXMLNodeListAttributes = NULL; + IXMLDOMNode *pXmlNode = NULL; + IXMLDOMNamedNodeMap *pXmlClassMap = NULL; + + DWORD dwAttributesCount = 0; + DWORD dwNewAttributes = 0; + LPWSTR *szAttributes; + LPWSTR szSubClasses; + + PATTRIBUTE_CONFIG *pNewAttributes; + + // + // Find class + // + swprintf_s(szXPath, MAX_PATH, L"/configORADAD/schema/classes/class[@name=\"%s\"]", szClassName); + + hr = pXMLDoc->selectNodes(szXPath, &pXMLNodeListClass); + hr = pXMLNodeListClass->get_length(&lLength); + if (lLength != 1) + { + Log( + __FILE__, __FUNCTION__, __LINE__, LOG_LEVEL_CRITICAL, + "Class '%S' not found for request '%S'.", szClassName, pRequest->szName + ); + return FALSE; + } + + hr = pXMLNodeListClass->get_item(0, &pXmlNode); + hr = pXmlNode->get_attributes(&pXmlClassMap); + + pReadAttributeString(pXmlClassMap, (LPWSTR)L"auxiliaryClass", &szSubClasses); + if (szSubClasses != NULL) + pAddClassesToRequest(pXMLDoc, szSubClasses, pRequest, pGlobalConfig); + pReadAttributeString(pXmlClassMap, (LPWSTR)L"systemAuxiliaryClass", &szSubClasses); + if (szSubClasses != NULL) + pAddClassesToRequest(pXMLDoc, szSubClasses, pRequest, pGlobalConfig); + + hr = pXmlNode->get_childNodes(&pXMLNodeListAttributes); + pXMLNodeListAttributes->get_length(&lLength); + + szAttributes = (LPWSTR*)_HeapAlloc(lLength * sizeof(LPWSTR)); + + for (long i = 0; i < lLength; i++) + { + BSTR AttributeName; + IXMLDOMNode *pXmlSubNode = NULL; + + hr = pXMLNodeListAttributes->get_item(i, &pXmlSubNode); + hr = pXmlSubNode->get_nodeName(&AttributeName); + + if (_wcsicmp(AttributeName, L"attribute") == 0) + { + IXMLDOMNamedNodeMap *pXmlNodeAttributeAttributes = NULL; + IXMLDOMNode *pXmlNodeAttributeName = NULL; + BSTR szName; + + hr = pXmlSubNode->get_attributes(&pXmlNodeAttributeAttributes); + hr = pXmlNodeAttributeAttributes->getNamedItem((BSTR)L"name", &pXmlNodeAttributeName); + hr = pXmlNodeAttributeName->get_text(&szName); + szAttributes[i] = (LPWSTR)szName; + dwAttributesCount++; + + _SafeCOMRelease(pXmlNodeAttributeName); + _SafeCOMRelease(pXmlNodeAttributeAttributes); + } + + _SafeCOMRelease(pXmlSubNode); + } + + _SafeCOMRelease(pXmlClassMap); + _SafeCOMRelease(pXmlNode); + _SafeCOMRelease(pXMLNodeListAttributes); + _SafeCOMRelease(pXMLNodeListClass); + + // + // First pass: count new attributes + // + DWORD dwClassNewAttributes; + + dwClassNewAttributes = dwAttributesCount; + + for (DWORD j = 0; j < dwAttributesCount; j++) + { + for (DWORD k = 0; k < pRequest->dwAttributesCount; k++) + { + if (_wcsicmp(szAttributes[j], (*pRequest->pAttributes[k]).szName) == 0) + dwClassNewAttributes--; + } + } + + dwNewAttributes += dwClassNewAttributes; + + // + // Second pass: add new attributes + // + if (dwNewAttributes > 0) + { + if (pRequest->pAttributes == NULL) + { + pNewAttributes = (PATTRIBUTE_CONFIG*)HeapAlloc( + g_hHeap, + HEAP_ZERO_MEMORY, + dwNewAttributes * sizeof(PATTRIBUTE_CONFIG) + ); + } + else + { + pNewAttributes = (PATTRIBUTE_CONFIG*)HeapReAlloc( + g_hHeap, + HEAP_ZERO_MEMORY, + pRequest->pAttributes, + (pRequest->dwAttributesCount + dwNewAttributes) * sizeof(PATTRIBUTE_CONFIG) + ); + } + pRequest->pAttributes = pNewAttributes; + + for (DWORD j = 0; j < dwAttributesCount; j++) + { + BOOL bAddAttribute = TRUE; + + for (DWORD k = 0; k < pRequest->dwAttributesCount; k++) + { + if (_wcsicmp(szAttributes[j], (*pRequest->pAttributes[k]).szName) == 0) + { + bAddAttribute = FALSE; + } + } + + if (bAddAttribute == TRUE) + { + BOOL bResult; + + bResult = pGetAttributeByNameForRequest(szAttributes[j], &pRequest->pAttributes[pRequest->dwAttributesCount], pGlobalConfig); + if (bResult == FALSE) + bReturn = FALSE; + else + pRequest->dwAttributesCount++; + } + } + } + + return bReturn; +} + +BOOL +pAddClassesToRequest ( + _In_ IXMLDOMDocument2 *pXMLDoc, + _In_z_ LPWSTR szClassName, + PREQUEST_CONFIG pRequest, + _In_ PGLOBAL_CONFIG pGlobalConfig +) +{ + LPWSTR szToken; + LPWSTR szTokenContext = NULL; + + if (szClassName == NULL) + return TRUE; + + szToken = wcstok_s(szClassName, L",", &szTokenContext); + while (szToken != NULL) + { + BOOL bResult; + + bResult = pAddClassToRequest(pXMLDoc, szToken, pRequest, pGlobalConfig); + if (bResult == FALSE) + return FALSE; + + szToken = wcstok_s(NULL, L",", &szTokenContext); + } + + return TRUE; +} + +BOOL +pXmlParseRequest ( + _In_ IXMLDOMDocument2 *pXMLDoc, + IXMLDOMNode *pXmlNodeRequet, + PREQUEST_CONFIG pRequest, + _In_ PGLOBAL_CONFIG pGlobalConfig +) +{ + HRESULT hr; + IXMLDOMNodeList *pXmlNodeListRequet = NULL; + + long lLength; + + hr = pXmlNodeRequet->get_childNodes(&pXmlNodeListRequet); + + hr = pXmlNodeListRequet->get_length(&lLength); + + for (long i = 0; i < lLength; i++) + { + IXMLDOMNode *pXmlNode = NULL; + + BSTR strNodeName; + BSTR strNodeText; + + hr = pXmlNodeListRequet->get_item(i, &pXmlNode); + hr = pXmlNode->get_nodeName(&strNodeName); + hr = pXmlNode->get_text(&strNodeText); + + if ((_wcsicmp(strNodeName, L"name") == 0) && (wcslen(strNodeText) > 0)) + pRequest->szName = strNodeText; + else if ((_wcsicmp(strNodeName, L"filter") == 0) && (wcslen(strNodeText) > 0)) + pRequest->szFilter = strNodeText; + else if ((_wcsicmp(strNodeName, L"scope") == 0) && (wcslen(strNodeText) > 0)) + { + if (_wcsicmp(strNodeText, L"base") == 0) + pRequest->dwScope = 0; // LDAP_SCOPE_BASE; + else if (_wcsicmp(strNodeText, L"onelevel") == 0) + pRequest->dwScope = 1; // LDAP_SCOPE_ONELEVEL; + else if (_wcsicmp(strNodeText, L"subtree") == 0) + pRequest->dwScope = 2; // LDAP_SCOPE_SUBTREE; + } + else if ((_wcsicmp(strNodeName, L"base") == 0) && (wcslen(strNodeText) > 0)) + { + LPWSTR szToken; + LPWSTR szTokenContext = NULL; + + szToken = wcstok_s(strNodeText, L",", &szTokenContext); + while (szToken != NULL) + { + if (_wcsicmp(szToken, STR_ROOTDSE) == 0) + pRequest->dwBase |= BASE_ROOTDSE; + else if (_wcsicmp(szToken, STR_DOMAIN) == 0) + pRequest->dwBase |= BASE_DOMAIN; + else if (_wcsicmp(szToken, STR_CONFIGURATION) == 0) + pRequest->dwBase |= BASE_CONFIGURATION; + else if (_wcsicmp(szToken, STR_SCHEMA) == 0) + pRequest->dwBase |= BASE_SCHEMA; + else if (_wcsicmp(szToken, STR_DOMAIN_DNS) == 0) + pRequest->dwBase |= BASE_DOMAIN_DNS; + else if (_wcsicmp(szToken, STR_FOREST_DNS) == 0) + pRequest->dwBase |= BASE_FOREST_DNS; + + szToken = wcstok_s(NULL, L",", &szTokenContext); + } + } + else if ((_wcsicmp(strNodeName, L"classes") == 0) && (wcslen(strNodeText) > 0)) + { + BOOL bResult; + + bResult = pAddClassesToRequest(pXMLDoc, strNodeText, pRequest, pGlobalConfig); + + if (bResult == FALSE) + return FALSE; + } + + _SafeCOMRelease(pXmlNode); + } + + _SafeCOMRelease(pXmlNodeListRequet); + + return TRUE; +} + +DWORD +pReadUInteger ( + _In_opt_z_ LPCWSTR szValue +) +{ + DWORD dwResult; + + if (szValue == NULL) + return 0; + + if (wcslen(szValue)==0) + return 0; + + if (swscanf_s(szValue, L"%u", &dwResult) == 1) + return dwResult; + else + return 0; +} + +BOOL +pReadBoolean ( + _In_opt_z_ LPCWSTR szValue +) +{ + if (szValue == NULL) + return FALSE; + + if (_wcsicmp(szValue, L"true") == 0) + return TRUE; + else if (wcscmp(szValue, L"1") == 0) + return TRUE; + else + return FALSE; +} \ No newline at end of file diff --git a/config-oradad.xml b/config-oradad.xml new file mode 100644 index 0000000..0b893fa --- /dev/null +++ b/config-oradad.xml @@ -0,0 +1,932 @@ + + + + [dsgetdc] + + + + + 1 + 2 + 0 + 0 + + + + + rootDSE + rootDSE information + rootDSE + + + + user + All users from domain + domain + subtree + (&(objectClass=user)(!(|(objectClass=computer)(objectClass=msDS-ManagedServiceAccount)(objectClass=msDS-GroupManagedServiceAccount)))) + person,organizationalPerson,user + + + group + All groups from domain + domain + subtree + (objectClass=group) + group + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/resource.h b/resource.h new file mode 100644 index 0000000..b28be42 --- /dev/null +++ b/resource.h @@ -0,0 +1,14 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by ORADAD.rc + +// Valeurs par défaut suivantes des nouveaux objets +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif