0

Im trying to write logs in windows server 2012 r2 i can write Application log like this,

Write-EventLog -LogName Application -Source "mysource" other parameters goes here 

its working rightly and write this log in windowslog/application

after that im trying like this for secuirty log

Write-EventLog -LogName Security -Source "Microsoft-Windows-Security-Auditing" other parameters goes here 

return me this error

Write-EventLog : The registry key for the log "Security" for source "Microsoft-Windows-Security-Auditing" could not be
opened.
At line:1 char:1
+ Write-EventLog -LogName Security -Source "Microsoft-Windows-Security-Auditing" - ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (:) [Write-EventLog], Exception
    + FullyQualifiedErrorId : AccessDenied,Microsoft.PowerShell.Commands.WriteEventLogCommand

after that im search and find a function for write security logs AuthzReportSecurityEvent ı guess ı can write my logs using this function, if ı can do that ı have another question how can i use this function in powershell or python ? I guess can i use this function via pywin32 module ? or can i call directly in powershell script ? can you share me any example how can ı call this function and write log in security log using this function.

I can write log in security when I follow the suggestions of @Strive Sun.

Mehmet Başaran
  • 77
  • 2
  • 10
  • The `Write-EventLog` cmdlet fails because you do not have sufficient permissions to write a security audit. Picking a different way to write a security audit will fail for the same reason. You're going to have to learn how security works. – IInspectable Sep 04 '20 at 12:34
  • Im asking to how can i write custom log in this area and you say must learn security works, so this mean its impossible ? if its why AuthzReportSecurityEvent is exist and why ı cant find any example using this api. Thanks for answer – Mehmet Başaran Sep 04 '20 at 13:32

1 Answers1

1

ı guess ı can write my logs using this function, if ı can do that ı have another question how can i use this function in powershell or python ?

The Security log write access limitation was relaxed somewhat in Windows Server 2003 without changing the fundamental design by the introduction of a special set of APIs (see Figure 2). These APIs use Local Procedure Calls (LPCs) internally to interact with LSA, instructing it to generate audit logs on the application's behalf. The mechanism is elegant and simple.

First, the application registers a security event source handle with LSA by calling AuthzRegisterSecurityEventSource. The only parameter that is of interest for this API is the name of the event source, which can be almost anything, subject to a few restrictions. For instance, it cannot be named "Security" because that name is reserved for system use. The security event source handle returned by this call is used in the following steps.

Next, events are generated by calling one of two closely relat-ed APIs: AuthzReportSecurityEvent or AuthzReportSecurityEventFromParams. Finally, when the application shuts down, it unregisters the security event source handle by calling AuthzUnregisterSecurityEventSource.

Refer: The Security log

can you share me any example how can ı call this function and write log in security log using this function.

Code Sample: (C++)

#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: %u\n", 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: %u\n", 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 %d\n", 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 %d\n", err1);
                return_code = -2;
                break;
            }

            i++;
        }

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

Note: A few things you have to do in the Local Security Policy before running the code sample. Steps can refer: https://stackoverflow.com/a/18242724/11128312

After assigning permissions to the current user, please restart the computer to make it effective.

Updated:

Please go to local policies->Audit Policy. Enable "Audit Object Access" for success and failure.

enter image description here

Then you rebuild and debug again, you will find Security logs appear in Event Viewer.

enter image description here

Strive Sun
  • 5,988
  • 1
  • 9
  • 26
  • Fİrstly thank you for answer, ım following your guide and return an output this "Get the specified privilege!" ım check my prıvılages ı have "SeAuditPrivilege" and after that I saw that there is no new record in the security log. Do you have any idae abouth that ? – Mehmet Başaran Sep 08 '20 at 12:52
  • I cant do that "Sorry. One thing I forget to tell you: Go to local policies->Audit Policy. Enable "Audit Object Access" for success and failure." because of this menu is locked so ım create new win server and configure like your last suggestion and promote this server a new domain controller on my existıng domain but its dosnt working, after reboot(promoted domain controller) any suggestions abouth that ? – – Mehmet Başaran Sep 09 '20 at 09:21
  • @ Mehmet Başaran `this menu is locked`, it means you cannot Enable "Audit Object Access"? – Strive Sun Sep 09 '20 at 09:26
  • @Mehmet Başaran Try [this](https://social.technet.microsoft.com/Forums/windowsserver/en-US/9fec38cb-b6eb-4522-a869-c87812d09402/audit-object-access-properties-window-dimmed-out?forum=winservergen). – Strive Sun Sep 09 '20 at 09:42
  • 1
    @Strive_Sun Yes its work after this steps, Im complate delete my all servers and clients and create new ad and new clients and new domain and just follow your guides for policy yes its works now ı can write security log thansk a lot. Also ı have some log format problem but i believe, i will handle it. Thanks again. – Mehmet Başaran Sep 10 '20 at 12:42
  • 1
    I updated my question if you can help me I would be grateful, thank you. – Mehmet Başaran Sep 10 '20 at 14:33
  • @MehmetBaşaran I am very happy to help you solve this problem.Regarding the format of the security log, I will continue to help you research this question. Given that this is a new problem, I think it is a good choice for you to post it as a new thread. This will allow more experienced people to pay attention to it and come up with useful solutions. – Strive Sun Sep 11 '20 at 09:07
  • Thank you again your help, and ım follow your instructions; ım updated this question and remove formatting part and create a new question for formatting security log https://stackoverflow.com/questions/63853858/how-can-i-write-windows-security-log-using-authzreportsecurityevent-function-sam – Mehmet Başaran Sep 11 '20 at 20:24