How can i write windows security log using AuthzReportSecurityEvent function same format system audit log

  authz, c++, logging, winapi, windows-server-2012-r2

I can write security log on windows server 2012 r2 using this code

#include <stdio.h>
#include <iostream>
#include <string>
#include <strsafe.h>
#include <windows.h>
#include <Authz.h>
#include <Ntsecapi.h>


#pragma comment(lib,"Authz.lib")
#pragma comment(lib,"Advapi32.lib")

BOOL SetPrivilege(
    HANDLE hToken,          // access token handle
    LPCTSTR lpszPrivilege,  // name of privilege to enable/disable
    BOOL bEnablePrivilege   // to enable or disable privilege
)
{
    TOKEN_PRIVILEGES tp;
    LUID luid;

    if (!LookupPrivilegeValue(
        NULL,            // lookup privilege on local system
        lpszPrivilege,   // privilege to lookup
        &luid))        // receives LUID of privilege
    {
        printf("LookupPrivilegeValue error: %un", GetLastError());
        return FALSE;
    }

    tp.PrivilegeCount = 1;
    tp.Privileges[0].Luid = luid;
    if (bEnablePrivilege)
        tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    else
        tp.Privileges[0].Attributes = 0;

    // Enable the privilege or disable all privileges.

    if (!AdjustTokenPrivileges(
        hToken,
        FALSE,
        &tp,
        sizeof(TOKEN_PRIVILEGES),
        (PTOKEN_PRIVILEGES)NULL,
        (PDWORD)NULL))
    {
        printf("AdjustTokenPrivileges error: %un", GetLastError());
        return FALSE;
    }

    if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)

    {
        printf("The token does not have the specified privilege. n");
        return FALSE;
    }

    printf("Get the specified privilege! n");

    return TRUE;
}




int main(int argc, const char* argv[])
{
    // Declare and initialize variables.

    BOOL bResult = TRUE;
    DWORD event_id = 4624;
    AUTHZ_SECURITY_EVENT_PROVIDER_HANDLE hEventProvider = NULL;
    PAUDIT_PARAMS p;
    std::string Source_Name = "Test security audit";
    std::wstring ws;
    std::string pbuf = "What is your purpose ?";
    std::wstring ws_buf;
    int return_code = 0;
    int i = 0;
    // Register the audit provider.
    HANDLE token;
    HANDLE hevent_source;
    ws.assign(Source_Name.begin(), Source_Name.end());
    ws_buf.assign(pbuf.begin(), pbuf.end());

    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token))
        return FALSE;

    SetPrivilege(token, L"SeAuditPrivilege", true);

    AUTHZ_SOURCE_SCHEMA_REGISTRATION ar;
    memset(&ar, 0, sizeof(ar));
    ar.dwFlags = AUTHZ_ALLOW_MULTIPLE_SOURCE_INSTANCES;
    ar.szEventSourceName = &ws[0];
    ar.szEventMessageFile = &ws_buf[0];
    ar.szEventSourceXmlSchemaFile = NULL;
    ar.szEventAccessStringsFile = &ws_buf[0];
    ar.szExecutableImagePath = NULL;

    AuthzInstallSecurityEventSource(0, &ar);

    bResult = AuthzRegisterSecurityEventSource(0, ws.c_str(), &hEventProvider);
    int err = GetLastError();
    if (!bResult)
    {
        printf("AuthzRegisterSecurityEventSource failed, error is %dn", err);
        return_code = -1;
    }

    SID id;
    if (hEventProvider)
    {
        // Generate the audit.
        while (i < 10) {
            bResult = AuthzReportSecurityEvent(
                APF_AuditSuccess,
                hEventProvider,
                event_id,
                NULL,
                3,
                APT_String, L"Jay Hamlin",
                APT_String, L"March 21, 1960",
                APT_Ulong, 45);
            int err1 = GetLastError();
            if (!bResult)
            {
                printf("AuthzReportSecurityEvent failed, error is %dn", err1);
                return_code = -2;
                break;
            }

            i++;
        }

        AuthzUnregisterSecurityEventSource(0, &hEventProvider);
        AuthzUninstallSecurityEventSource(0, &ws[0]);
    }
    std::cout << "Exit  : " << return_code << std::endl;
    getchar();

I’m writing this log using the code above, ım just copy from event viewer

Log Name:      Security
Source:        Microsoft-Windows-Security-Auditing-Mhmt
Date:          9/11/2020 12:24:57 PM
Event ID:      4624
Task Category: (3)
Level:         Information
Keywords:      Classic,Audit Success
User:          MHMTTESTAdministrator
Computer:      winserver10.mhmttest.com
Description:
The description for Event ID 4624 from source Microsoft-Windows-Security-Auditing-Mhmt cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.

If the event originated on another computer, the display information had to be saved with the event.

The following information was included with the event: 

blabla
09.09.2020
{3834357b-3934-3236-352d-353437382d34}
45

Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name="Microsoft-Windows-Security-Auditing-Mhmt" />
    <EventID Qualifiers="0">4624</EventID>
    <Level>0</Level>
    <Task>3</Task>
    <Keywords>0x80a0000000000000</Keywords>
    <TimeCreated SystemTime="2020-09-11T19:24:57.978005800Z" />
    <EventRecordID>257542</EventRecordID>
    <Channel>Security</Channel>
    <Computer>winserver10.mhmttest.com</Computer>
    <Security UserID="S-1-5-21-2217028777-1434293377-136569969-500" />
  </System>
  <EventData>
    <Data>blabla</Data>
    <Data>09.09.2020</Data>
    <Data>{3834357b-3934-3236-352d-353437382d34}</Data>
    <Data>45</Data>
  </EventData>
</Event>

I want to be writing log like this format(I want to be able to log in this format by changing my code accordingly.), this log writing by system(logon windows machine in domain, generating this log)

Log Name:      Security
Source:        Microsoft-Windows-Security-Auditing
Date:          9/10/2020 4:40:10 PM
Event ID:      4624
Task Category: Logon
Level:         Information
Keywords:      Audit Success
User:          N/A
Computer:      winserver10.mhmttest.com
Description:
An account was successfully logged on.

Subject:
    Security ID:        NULL SID
    Account Name:       -
    Account Domain:     -
    Logon ID:       0x0

Logon Type:         3

Impersonation Level:        Delegation

New Logon:
    Security ID:        MHMTTESTtestwin
    Account Name:       testwin
    Account Domain:     MHMTTEST
    Logon ID:       0x11B7DDE
    Logon GUID:     {5a456f07-90c3-b576-b1a0-e67abb3f2435}

Process Information:
    Process ID:     0x0
    Process Name:       -

Network Information:
    Workstation Name:   
    Source Network Address: 10.20.30.40
    Source Port:        62499

Detailed Authentication Information:
    Logon Process:      Kerberos
    Authentication Package: Kerberos
    Transited Services: -
    Package Name (NTLM only):   -
    Key Length:     0

This event is generated when a logon session is created. It is generated on the computer that was accessed.

The subject fields indicate the account on the local system which requested the logon. This is most commonly a service such as the Server service, or a local process such as Winlogon.exe or Services.exe.

The logon type field indicates the kind of logon that occurred. The most common types are 2 (interactive) and 3 (network).

The New Logon fields indicate the account for whom the new logon was created, i.e. the account that was logged on.

The network fields indicate where a remote logon request originated. Workstation name is not always available and may be left blank in some cases.

The impersonation level field indicates the extent to which a process in the logon session can impersonate.

The authentication information fields provide detailed information about this specific logon request.
    - Logon GUID is a unique identifier that can be used to correlate this event with a KDC event.
    - Transited services indicate which intermediate services have participated in this logon request.
    - Package name indicates which sub-protocol was used among the NTLM protocols.
    - Key length indicates the length of the generated session key. This will be 0 if no session key was requested.
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name="Microsoft-Windows-Security-Auditing" Guid="{54849625-5478-4994-A5BA-3E3B0328C30D}" />
    <EventID>4624</EventID>
    <Version>1</Version>
    <Level>0</Level>
    <Task>12544</Task>
    <Opcode>0</Opcode>
    <Keywords>0x8020000000000000</Keywords>
    <TimeCreated SystemTime="2020-09-10T23:40:10.703982200Z" />
    <EventRecordID>189943</EventRecordID>
    <Correlation />
    <Execution ProcessID="516" ThreadID="644" />
    <Channel>Security</Channel>
    <Computer>winserver10.mhmttest.com</Computer>
    <Security />
  </System>
  <EventData>
    <Data Name="SubjectUserSid">S-1-0-0</Data>
    <Data Name="SubjectUserName">-</Data>
    <Data Name="SubjectDomainName">-</Data>
    <Data Name="SubjectLogonId">0x0</Data>
    <Data Name="TargetUserSid">S-1-5-21-2217028777-1434293377-136569969-1607</Data>
    <Data Name="TargetUserName">testwin</Data>
    <Data Name="TargetDomainName">MHMTTEST</Data>
    <Data Name="TargetLogonId">0x11b7dde</Data>
    <Data Name="LogonType">3</Data>
    <Data Name="LogonProcessName">Kerberos</Data>
    <Data Name="AuthenticationPackageName">Kerberos</Data>
    <Data Name="WorkstationName">
    </Data>
    <Data Name="LogonGuid">{5A456F07-90C3-B576-B1A0-E67ABB3F2435}</Data>
    <Data Name="TransmittedServices">-</Data>
    <Data Name="LmPackageName">-</Data>
    <Data Name="KeyLength">0</Data>
    <Data Name="ProcessId">0x0</Data>
    <Data Name="ProcessName">-</Data>
    <Data Name="IpAddress">10.20.30.40</Data>
    <Data Name="IpPort">62499</Data>
    <Data Name="ImpersonationLevel">%%1840</Data>
  </EventData>
</Event>

how can i write like system audit log using my code ?
im writing EventData field in this code part

                APT_String, L"test deneme123",
                APT_String, L"09.09.2020",
                APT_Ulong, 45);

how can ı add "Name" attribute in here
<Data {here}>
original log data field looks like this

<EventData>
    <Data Name="SubjectUserSid">S-1-0-0</Data>

My log EventData field looks like this, and i want to add "Name" key as in the example above

<EventData>
    <Data>test deneme123</Data>

My goal is to convert all fields in the my custom log I created to the same format as the original audit log. Thank you for yours helping.

Source: Windows Questions C++

LEAVE A COMMENT