NXLog Docs

Microsoft 365 (im_ms365)

Microsoft offers various methods to collect Microsoft 365 logs, including:

  • Microsoft Graph offers a unified reporting API to retrieve information on your Microsoft 365 and Windows environment.

  • The Office 365 Management API provides a single platform for managing and auditing Office 365, including Azure Active Directory, Exchange, and SharePoint.

  • The older Office 365 Reporting web service provides information on Exchange Online, including mailboxes, spam, and antivirus, and Lync Online conferences and sessions.

This module can be used to collect logs from the Microsoft Graph Reports API, Office 365 Management Activity API, and the Office 365 Reporting web service.

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_ms365 module:

  • An Application (client) ID

  • The Directory (tenant) ID

  • Your Microsoft Azure AD domain, e.g., contoso.onmicrosoft.com

  • 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 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

Assign Azure application permissions

Follow the instructions to Grant permissions on Microsoft Learn. The following permissions are required for each log type:

Log type Azure AD permissions

ActivityReports

DirectoryAudits

  • AuditLog.Read.All

  • Directory.Read.All

SignIns

  • AuditLog.Read.All

  • Directory.Read.All

DeviceManagement

AuditEvents

  • ManagedTenant.Read.All or

  • ManagedTenant.ReadWrite.All

IdentityAndAccessReports

AzureADApplicationSignInDetailSummary

  • Reports.Read.All

IdentityProtection

RiskDetection

  • IdentityRiskEvent.Read.All

RiskyUser

  • IdentityRiskyUser.Read.All

ServicePrincipalRiskDetections

  • IdentityRiskEvent.Read.All

RiskyServicePrincipal

  • IdentityRiskyServicePrincipal.Read.All or

  • IdentityRiskyServicePrincipal.ReadWrite.All

ManagementActivity

AzureActiveDirectory

  • ActivityFeed.Read

Exchange

  • ActivityFeed.Read

SharePoint

  • ActivityFeed.Read

PrivilegedIdentityManagement

UnifiedRoleAssignment

One of the following:

  • RoleAssignmentSchedule.Read.Directory

  • RoleManagement.Read.Directory

  • RoleManagement.Read.All

  • RoleAssignmentSchedule.ReadWrite.Directory

  • RoleManagement.ReadWrite.Directory

UnifiedRoleEligibility

One of the following:

  • RoleEligibilitySchedule.Read.Directory

  • RoleManagement.Read.Directory

  • RoleManagement.Read.All

  • RoleEligibilitySchedule.ReadWrite.Directory

  • RoleManagement.ReadWrite.Directory

ReportingWebService

MessageTrace

  • ReportingWebService.Read.All

Plus one of the following roles to the application:

  • Global Reader (recommended)

  • Global Administrator

  • Exchange Administrator

ServiceCommunications

HealthOverviews

  • ServiceHealth.Read.All

HealthOverviewsWithServiceHealthIssues

  • ServiceHealth.Read.All

ServiceHealthIssues

  • ServiceHealth.Read.All

ServiceUpdateMessages

  • ServiceMessage.Read.All

Once you add the permissions and grant admin consent, your application permissions should look similar to the following:

Microsoft Azure AD application permissions

Configuration

The im_ms365 module accepts the following directives in addition to the common module directives. The ClientId, TenantId, TenantDomain directives, and either Secret or a combination of CertThumbprint and CertKeyFile are required.

Required directives

The following directives are required for the module to start.

CertPattern

This optional directive, supported only on Windows, defines a pattern for identifying a corresponding certificate and its thumbprint within the native Windows Certificate Storage. The pattern must follow PCRE2 rules and use the format "SUBJECT=, CN=, DN=, SAN=" where DN is "CN=, O=, OU=, L=, ST=, C=". The certificate must be imported in PFX format into the Local Computer\Personal certificate store for NXLog to locate it. During configuration, this directive is resolved into the corresponding CertThumbprint value. The first found thumbprint will be chosen if multiple certificates match the pattern. We recommend ensuring that the used certificate storage is well-maintained for optimal performance. This feature is not dynamic; the agent must be restarted if the certificate changes. This directive is mutually exclusive with the CertThumbprint directive.

Configuration examples:

CertPattern    $hostname + 'Cert'

or

CertPattern    DN=CN=Client\.example\.com;.*?SAN=DNS:Client\.example\.com

A normal log output example would look like as follows:

matching pattern [DN=CN=Client\.example\.com;.*?SAN=DNS:Client\.example\.com] to certificate [SUBJECT=US, ClientState, ClientCity, ClientCompany, ClientUnit, Client.example.com, CN=Client.example.com; DN=CN=Client.example.com, O=ClientCompany, OU=ClientUnit, L=ClientCity, ST=ClientState, C=US; SAN=DNS:Client.example.com; DNS:www.Client.example.com; IP:127.0.0.3; ]

CertThumbprint

This optional directive 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 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 Secret directive.

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 Secret directive.

ClientId

This mandatory directive specifies the Microsoft Azure App Application (client) ID.

TenantId

This mandatory directive specifies the Microsoft Azure App Directory (tenant) ID.

TenantDomain

This mandatory directive specifies the Microsoft Azure AD domain, e.g., contoso.onmicrosoft.com.

Secret

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

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.

HTTPBasicAuthUser

HTTP basic authorization username. You must also set the HTTPBasicAuthPassword directive to use HTTP authorization.

HTTPBasicAuthPassword

HTTP basic authorization password. You must also set the HTTPBasicAuthUser directive to use HTTP authorization.

HTTPSAllowExpired

This boolean directive specifies whether 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. This directive is only valid if HTTPSRequireCert is set to TRUE.

HTTPSAllowUntrusted

This boolean directive specifies that 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

This directive specifies a 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 NXLog TLS/SSL configuration in the User Guide for more information on using this directive.

HTTPSCAFile

This specifies 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 the case of certificates signed by an intermediate CA, the certificate specified must contain the complete certificate chain (certificate bundle).

HTTPSCertFile

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

HTTPSCertKeyFile

This specifies 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 server 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 doubles on 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.

API URLs directives

The following group directives are for changing the default authentication and data collection URLs for Microsoft services.

MsGraph

Optional group directive to change the default authentication and data collection URLs for the Microsoft Graph REST API v1.0 endpoint. These URLs will be used to retrieve ActivityReports, ServiceCommunications, PrivilegedIdentityManagement, and IdentityProtection RiskDetection and RiskyUser logs.

AuthURL

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

URL

This directive specifies the URL for retrieving data. The default value is https://graph.microsoft.com.

Version

The API version to use. The accepted values are 1.0 and Beta. The default value is 1.0.

MsGraphBeta

Optional group directive to change the default authentication and data collection URLs for the Microsoft Graph REST API beta endpoint. These URLs will be used to retrieve DeviceManagement, IdentityAndAccessReports, and IdentityProtection ServicePrincipalRiskDetections and RiskyServicePrincipal logs.

AuthURL

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

URL

This directive specifies the URL for retrieving data. The default value is https://graph.microsoft.com.

Version

The API version to use. The accepted values are 1.0 and Beta. The default value is Beta.

Office365

Optional group directive to change the default authentication and data collection URLs for the Office 365 Management Activity API. These URLs will be used to retrieve ManagementActivity logs.

AuthURL

This directive specifies the URL for authenticating with the API. The default value is https://login.windows.net.

URL

This directive specifies the URL for retrieving data. The default value is https://manage.office.com/api.

Version

The API version to use. The accepted values are 1.0 and Beta. The default value is 1.0.

Outlook365

Optional group directives to change the default authentication and data collection URLs for the Office 365 Reporting web service. These URLs will be used to retrieve ReportingWebService logs.

AuthURL

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

URL

This directive specifies the URL for retrieving data. The default value is https://reports.office365.com.

Optional directives

ActivityReports

Comma-separated list of Azure AD activity logs to collect. Based on the Azure data retention policy, only the last 30 days of data are available. The accepted values are DirectoryAudits and SignIns.

DeviceManagement

Comma-separated list of device and app management logs to collect. Currently, only AuditEvents is supported.

EndDate

This optional directive specifies the date of the last event to pull. The accepted values are now, yesterday, week-ago, month-ago, or an absolute date-time in YYYY-MM-DD HH:MM:SS format. The default is now.

IdentityAndAccessReports

Comma-separated list of identity and access logs to collect. Currently, only AzureADApplicationSignInDetailSummary is supported.

IdentityProtection

Comma-separated list of identity protection logs to collect. The accepted values are RiskDetection, RiskyUser, ServicePrincipalRiskDetections, and RiskyServicePrincipal.

ManagementActivity

Comma-separated list of Office 365 Management Activity logs to collect. The accepted values are AzureActiveDirectory, Exchange, and SharePoint.

PrivilegedIdentityManagement

Comma-separated list of privileged identity management logs to collect. The accepted values are UnifiedRoleAssignment and UnifiedRoleEligibility.

PaginationDelay

The delay in seconds between pagination requests to avoid hitting the throttling limit. The default value is different for each API, and this directive will change it globally.

QueryPeriod

This optional directive specifies how frequently the module will check for new events in seconds. The default value is 300 seconds.

ReadFromLast

This optional boolean directive instructs the module to only read logs that arrive after NXLog 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 is started.

TRUE

TRUE

Yes

Reads events from the saved position.

TRUE

FALSE

No

Reads events that are logged after NXLog is started.

TRUE

FALSE

Yes

Reads events that are logged after NXLog 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 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.

ReportingWebService:: Comma-separated list of Office 365 reporting web service endpoints to poll. Currently, only MessageTrace is supported. Only the last 30 days of data are available.

RetryPeriod

This optional directive sets the interval in seconds to retry failed tasks. The default value is 300 seconds.

ServiceCommunications:: Comma-separated list of service health and communications logs to collect. The accepted values are HealthOverviews, HealthOverviewsWithServiceHealthIssues, ServiceHealthIssues, and ServiceUpdateMessages.

StartDate

This optional directive specifies the date of the first event to pull. The accepted values are now, yesterday, week-ago, month-ago, or an absolute date-time in YYYY-MM-DD HH:MM:SS format. The default is yesterday.

Fields

The following fields are used by im_ms365.

$raw_event (type: string)

The log record in JSON format for all log sources except ReportingWebService/MessageTrace, which generates XML.

$LogType (type: string)

The name of the log source that generated the record, e.g., ServiceCommunications/ServiceHealthIssues

Examples

Example 1. Collecting Office 365 logs using the default API URLs

This configuration uses the im_ms365 input module to collect logs from all supported APIs. The module will use the default URLs and the top-level authentication details to connect to all APIs.

<Input microsoft_365>
    Module                   im_ms365

    ActivityReports          DirectoryAudits, SignIns
    ServiceCommunications    HealthOverviewsWithServiceHealthIssues
    DeviceManagement         AuditEvents
    ManagementActivity       AzureActiveDirectory, Exchange
    ReportingWebService      MessageTrace

    StartDate                month-ago
    EndDate                  now

    ClientId                 MY_CLIENT_ID (1)
    TenantId                 MY_TENANT_ID (2)
    TenantDomain             mydomain.onmicrosoft.com (3)
    Secret                   MY_CLIENT_SECRET (4)
</Input>
1 The ClientID directive specifies the Azure Application ID.
2 The TenantID directive specifies the Azure Application directory ID.
3 The TenatDomain directive specifies the Azure Active directory domain.
4 Uses the Microsoft Azure Application client Secret for authentication.
Example 2. Changing the default Microsoft Graph API URLs

This configuration collects logs from the Microsoft Graph Reports API with the im_ms365 input module. It uses the MsGraph group directive to specify custom authentication and log collection URLs.

<Input microsoft_365>
    Module                im_ms365

    ActivityReports       DirectoryAudits, SignIns
    IdentityProtection    RiskDetection, RiskyUser

    ClientId              MY_CLIENT_ID (1)
    TenantId              MY_TENANT_ID (2)
    TenantDomain          mydomain.onmicrosoft.com (3)
    Secret                MY_CLIENT_SECRET (4)

    <MsGraph>
        URL        https://example.microsoft.com
        AuthURL    https://example.microsoftonline.com
        Version    1.0
    </MsGraph>
</Input>
1 The ClientID directive specifies the Azure Application ID.
2 The TenantID directive specifies the Azure Application directory ID.
3 The TenatDomain directive specifies the Azure Active directory domain.
4 Uses the Microsoft Azure Application client Secret for authentication.