Microsoft Azure Monitor (im_azuremonitor)

This module fetches logs from Azure services using the Azure Monitor Log Analytics API.

Configuring a Microsoft Azure AD application

You must first create a Microsoft Azure AD application to use any Microsoft API. You will need the following details to configure the im_azuremonitor module:

  • An Application (client) ID

  • The Directory (tenant) ID

  • A client secret or a certificate and private key pair.

See Add credentials on Microsoft Docs for more information.

Register an Azure application

First, follow the instructions to Register an application on Microsoft Learn. Once you have created the new application, take note of the Application (client) ID and the Directory (tenant) ID from the application Overview page.

Microsoft Azure AD application overview

Generate an X.509 certificate

To use certificate-based authentication to authenticate with Microsoft’s APIs, you need an X.509 certificate and the private key used to generate the certificate. The following instructions guide you through creating the private key pair using OpenSSL.

  1. Save the following script in a file named gencertkey.sh

    #!/bin/sh
    
    openssl req -new -nodes -newkey rsa:2048 -x509 -days 730 -keyout certkey.pem -out cert.pem
    #openssl pkcs12 -export -out cert.pfx -inkey certkey.pem -in cert.pem
    openssl x509 -outform der -in cert.pem -out cert.der
    cat cert.der |openssl dgst -binary -sha1 | openssl base64 >cert.base64thumb
    THUMBPRINT=`cat cert.base64thumb`
    echo "ThumbPrint:$THUMBPRINT"
    
    UUID=`uuidgen`
    CERT=`cat cert.pem | grep -v "\-\-\-\-"| tr -d '\n'`
    
    cat <<EOF
    "keyCredentials": [
         {
            "customKeyIdentifier":"$THUMBPRINT",
            "keyId":"$UUID",
            "type":"AsymmetricX509Cert",
            "usage":"Verify",
            "value":"$CERT"
         }
    ],
    EOF
  2. The script depends on the openssl toolkit and the uuidgen program. Install the corresponding packages if necessary.

    On Debian-based platforms:

    # apt install openssl uuid-runtime

    On Centos/Red Hat platforms:

    # yum install openssl util-linux
  3. Execute gencertkey.sh on the computer where NXLog Agent is installed to generate the certificate.

    $ ./gencertkey.sh

    The output:

    Generating a RSA private key
    ............+++++
    ................................................+++++
    writing new private key to 'certkey.pem'
    -----
    You are about to be asked to enter information that will be incorporated
    into your certificate request.
    What you are about to enter is what is called a Distinguished Name or a DN.
    There are quite a few fields but you can leave some blank
    For some fields there will be a default value,
    If you enter '.', the field will be left blank.
    -----
    Country Name (2 letter code) [AU]:
    State or Province Name (full name) [Some-State]:
    Locality Name (eg, city) []:
    Organization Name (eg, company) [Internet Widgits Pty Ltd]:
    Organizational Unit Name (eg, section) []:
    Common Name (e.g. server FQDN or YOUR name) []:
    Email Address []:
    ThumbPrint:0nFt3fB0JP7zuSmHaRQtmsFNYqo=
    "keyCredentials": [
    {
        "customKeyIdentifier":"0nFt3fB0JP7zuSmHaRQtmsFNYqo=",
        "keyId":"629ab88d-1059-454b-b258-4ca05b46dee4",
        "type":"AsymmetricX509Cert",
        "usage":"Verify",
        "value":"MIIDXTCCAkWgAwIBAgIJAP+XrnwhAxjOMA0GCSqGSIb3DQEBCwUAMEUxCzAJB..."
    }
    ],
    --------
    +
    Take note of the `ThumbPrint` and `KeyCredentials` values.
  4. Go to the Microsoft Azure AD application registration page, select Manifest on the left, and click Download.

    Microsoft Azure AD application manifest download
  5. Edit the downloaded manifest file and replace the KeyCredentials value with the value from the previous step.

    "keyCredentials": [
    {
        "customKeyIdentifier":"0nFt3fB0JP7zuSmHaRQtmsFNYqo=",
        "keyId":"629ab88d-1059-454b-b258-4ca05b46dee4",
        "type":"AsymmetricX509Cert",
        "usage":"Verify",
        "value":"MIIDXTCCAkWgAwIBAgIJAP+XrnwhAxjOMA0GCSqGSIb3DQEBCwUAMEUxCzAJB..."
    }
    ],
  6. Save the changes and upload the manifest to Microsoft Azure.

    Microsoft Azure AD application manifest upload

Pagination

The module polls the API every PollInterval seconds and fetches all new records. We use the TimeGenerated field to detect new records. Because there is usually a delay between when the event is sent to the server and when it’s available through the API, we poll for events between now() - PollInterval*2 and now() - PollInterval. At startup, the module waits for PollInterval*2 before it polls the API.

Configuration

The im_azuremonitor module accepts the following directives in addition to the common module directives.

Required directives

The following directives are required for the module to start.

CertKeyFile

Specifies the path of the private key file that was used to generate the certificate specified by the CertThumbprint directive. This directive is mutually exclusive with the ClientSecret directive.

CertThumbprint

This optional directive, supported only on Windows, specifies the thumbprint of the certificate that will be presented to the remote server during the HTTPS handshake. The hexadecimal fingerprint string can be copied from Windows Certificate Manager (certmgr.msc). Whitespaces are automatically removed. The certificate must be imported to the Local Computer\Personal certificate store in PFX format for NXLog Agent to find it. Run the following command to create a PFX file from the certificate and private key using OpenSSL:

$ openssl pkcs12 -export -out server.pfx -inkey server.key -in server.pem

When the global directive UseCNGCertificates is set to FALSE the private key associated with the certificate must be exportable.

  • If you generate the certificate request using Windows Certificate Manager, enable the Make private key exportable option from the certificate properties.

  • If you import the certificate with the Windows Certificate Import Wizard, make sure that the Mark this key as exportable option is enabled.

  • If you migrate the certificate and associated private key from one Windows machine to another, select Yes, export the private key when exporting from the source machine.

On the contrary, when the global directive UseCNGCertificates is set to TRUE the private key associated with the certificate does not have to be exportable. In cases like TPM modules, the private key is always nonexportable.

The usage of the directive is the same in all cases:

CertThumbprint    7c2cc5a5fb59d4f46082a510e74df17da95e2152

This directive is mutually exclusive with the ClientSecret directive.

ClientId

This directive specifies the ID of the application that will be used to authenticate with Microsoft Entra ID.

ClientSecret

Specifies the Microsoft Azure App client secret. This directive is mutually exclusive with the CertThumbprint and CertKeyFile directives.

TableName

The name of the Azure Monitor table to collect logs from.

TenantId

This directive specifies the ID of the Microsoft Entra ID tenant to connect to.

WorkspaceId

The ID of the workspace that owns the table.

HTTP(S) directives

The following directives are for configuring HTTP(S) connection settings.

AddHeader

This optional directive can be specified multiple times to add custom headers to each HTTP request.

Compression

This optional directive can be used to enable HTTP compression for outgoing HTTP messages. The possible values are none, gzip, and deflate. By default, compression is disabled. Please note that some HTTP servers may not accept compressed HTTP requests. If a server doesn’t support a specific compression method, it may return 415 Unsupported Media Type errors in response to compressed requests.

HTTPBasicAuthPassword

HTTP basic authorization password.

HTTP authorization works only when both HTTPBasicAuthUser and HTTPBasicAuthPassword parameters are set.

HTTPBasicAuthUser

HTTP basic authorization username.

HTTP authorization works only when both HTTPBasicAuthUser and HTTPBasicAuthPassword parameters are set.

HTTPSAllowExpired

Specifies if the connection should be allowed with an expired certificate. If set to TRUE, the remote host will be able to connect with an expired certificate. The default is FALSE: the certificate must not be expired.

HTTPSAllowUntrusted

Specifies if the connection should be allowed without certificate verification. If set to TRUE, the connection will be allowed even if the remote host presents an unknown or self-signed certificate. The default value is FALSE: the remote host must present a trusted certificate.

HTTPSCADir

The path to a directory containing certificate authority (CA) certificates. These certificates will be used to verify the certificate presented by the remote host. The certificate files must be named using the OpenSSL hashed format, i.e. the hash of the certificate followed by .0, .1 etc. To find the hash of a certificate using OpenSSL:

$ openssl x509 -hash -noout -in ca.crt

For example, if the certificate hash is e2f14e4a, then the certificate filename should be e2f14e4a.0. If there is another certificate with the same hash then it should be named e2f14e4a.1 and so on.

A remote host’s self-signed certificate (which is not signed by a CA) can also be trusted by including a copy of the certificate in this directory.

The default operating system root certificate store will be used if this directive is not specified. Unix-like operating systems commonly store root certificates in /etc/ssl/certs. Windows operating systems use the Windows Certificate Store, while macOS uses the Keychain Access Application as the default certificate store. See Certification Authority (CA) certificates in the NXLog Platform User Guide for more information on using this directive.

In addition, Microsoft’s PKI repository contains root certificates for Microsoft services.

HTTPSCAFile

The path of the certificate authority (CA) certificate that will be used to verify the certificate presented by the remote host. A remote host’s self-signed certificate (which is not signed by a CA) can be trusted by specifying the remote host certificate itself. In case of certificates signed by an intermediate CA, the certificate specified must contain the complete certificate chain (certificate bundle).

HTTPSCertFile

The path of the certificate file that will be presented to the remote host during the HTTPS handshake.

HTTPSCertKeyFile

The path of the private key file that was used to generate the certificate specified by the HTTPSCertFile directive. This is used for the HTTPS handshake.

Proxy

This optional directive is used to specify the protocol, IP address (or hostname) and port number of the HTTP or SOCKS proxy host to be used. The format is protocol://hostname:port.

Reconnect

This optional directive sets the reconnect interval in seconds. If it is set, the module attempts to reconnect in every defined second. If it is not set, the reconnect interval will start at 1 second and double with every attempt. If the duration of the successful connection is greater than the current reconnect interval, then the reconnect interval will be reset to 1 sec.

The Reconnect directive must be used with caution. If it is used on multiple systems, it can send reconnect requests simultaneously to the same destination, potentially overloading the destination system. It may also cause NXLog Agent to use unusually high system resources or cause NXLog Agent to become unresponsive.

ReconnectOnData

This optional directive defines the behavior when the connection with the remote host is lost. When set to TRUE, the module only attempts to reconnect when it has data to send. The default value is FALSE; it will always keep a connection open with the remote host.

Optional directives

AuthURL

The URL for authenticating with the API. The default value is https://login.microsoftonline.com.

Columns

Specify a comma-separated list of table columns to retrieve. Column names are case-sensitive. If not specified, the module retrieves all columns.

Filter

One or more Where clauses delimited by the | character used to filter the data. For example:

'Where Message !has "test" | Where Message has "abc"'

The queries must comply with the Kusto Query Language (KQL). Any queries not starting with the Where clause are ignored and a warning is logged in the NXLog Agent log file.

LogConnections

Use this boolean directive to turn on connection logging. Since connections can be very frequent, it could generate a lot of noise. However, it helps troubleshoot connection issues. The default is FALSE.

PollInterval

This optional directive specifies how frequently the module will check for new events in seconds. The default is 60 seconds. This value must be a positive integer greater than or equal to 1.

ReadFromLast

This optional boolean directive instructs the module to only read logs that arrive after NXLog Agent is started. This directive comes into effect if a saved position is not found, for example on the first start, or when the SavePos directive is FALSE. When the SavePos directive is TRUE and a previously saved position is found, the module will always resume reading from the saved position. If ReadFromLast is FALSE, the module will read all the available logs. This can result in a lot of messages and is usually not the expected behavior. If this directive is not specified, it defaults to TRUE.

The following matrix shows the outcome of this directive in conjunction with the SavePos directive:

ReadFromLast SavePos SavedPosition Outcome

TRUE

TRUE

No

Reads events that are logged after NXLog Agent is started.

TRUE

TRUE

Yes

Reads events from the saved position.

TRUE

FALSE

No

Reads events that are logged after NXLog Agent is started.

TRUE

FALSE

Yes

Reads events that are logged after NXLog Agent is started.

FALSE

TRUE

No

Reads all events.

FALSE

TRUE

Yes

Reads events from the saved position.

FALSE

FALSE

No

Reads all events.

FALSE

FALSE

Yes

Reads all events.

SavePos

If this boolean directive is set to TRUE, the timestamp of the last read event will be saved when NXLog Agent exits. The timestamp will be read from the cache file upon startup. The default is TRUE, the last timestamp will be saved if this directive is not specified. This directive affects the outcome of the ReadFromLast directive. The SavePos directive can be overridden by the global NoCache directive.

StartFrom

This optional directive specifies the time of the first event to pull in RFC3339 format. If this directive is not set, the module reads events according to the ReadFromLast directive.

URL

The URL of the Azure Monitor Log Analytics API. The default value is https://api.loganalytics.azure.com.

Creating and populating fields

When the im_azuremonitor module reads log records from the Azure Monitor Log Analytics API, it creates and populates fields according to the returned Columns. You can use the fields for further processing or to convert the log record to a different output format, such as JSON or XML. Additionally, the $raw_event core field is populated as follows:

TimeGenerated Hostname Severity field1=value1 field2=value2 EventType=TableName

The EventType field is populated with the TableName.

If the EventTime, Hostname, and Severity fields are not returned as part of the log record, the following default values are used:

Hostname

The value returned by the hostname() function.

Severity

INFO

Examples

Example 1. Collecting logs from Azure Monitor with minimal configuration

This configuration collects logs from a table named MyLogs. im_azuremonitor receives records from the Log Analytics API in JSON format, which it then parses into structured data and writes each record as a list of key-value pairs to the $raw_event field.

nxlog.conf
<Input azure_table>
    Module         im_azuremonitor

    ClientId        azure_ad_app_id
    TenantId        azure_ad_tenant_id
    ClientSecret    azure_app_client_secret

    WorkspaceId     workspace_id
    TableName       MyLogs
</Input>

The following is a log record after it was processed by NXLog Agent.

Output sample
2024-11-15 12:23:15 nxlog-server INFO MessageSourceAddress="192.168.0.123" SourceModuleName="tcp_listen" SourceModule="im_tcp" Message:"Connection accepted from 192.168.1.200" TenantId="c1580b88-581a-4cd0-a5c8-a3dd46241740" Type="MyLogs" _ResourceId="" EventType="MyLogs"
Example 2. Filtering logs in Azure Monitor

This configuration collects logs from a table named MyLogs. It specifies a Filter to retrieve only logs containing "test" in the Message field.

im_azuremonitor receives records from the Log Analytics API in JSON format, which it then parses into structured data and writes each record as a list of key-value pairs to the $raw_event field.

nxlog.conf
<Input azure_table>
    Module         im_azuremonitor

    ClientId        azure_ad_app_id
    TenantId        azure_ad_tenant_id
    ClientSecret    azure_app_client_secret

    WorkspaceId     workspace_id
    TableName       MyLogs
    Filter          'Where Message has "test"'
</Input>

The following is a matching log record after it was processed by NXLog Agent.

Output sample
2024-11-15 12:23:15 nxlog-server INFO MessageSourceAddress="192.168.0.123" SourceModuleName="tcp_listen" SourceModule="im_tcp" Message:"This is a test message" TenantId="c1580b88-581a-4cd0-a5c8-a3dd46241740" Type="MyLogs" _ResourceId="" EventType="MyLogs"