GO KALI FREE
IntermediateSecurity Operations

How to Analyze Logs: A Beginner's Guide to Linux, Windows & Web Log Analysis

Learn how to analyze logs step by step: read Linux and Windows logs, search with grep and journalctl, and investigate a real brute-force attack in auth.log.

#how to analyze logs#what is log analysis#linux log analysis#log analysis tools#log analysis cheat sheet#journalctl#grep log analysis#security log analysis

What Is Log Analysis?

Log analysis is the process of reading, filtering, and comparing records from systems, applications, and network devices to understand what happened. You start with a question, narrow the records to a relevant time window, and check whether different sources support the same explanation. It helps troubleshoot failures and investigate suspicious activity.

What a Log Line Contains

An illustrative application log might look like this:

2026-11-29T09:12:04Z lab-vm account-service[2101] WARN login rejected user=labuser reason=bad_password
  • Timestamp: When the event occurred. The Z means UTC. Some logs omit the year or offset, so verify those before building a timeline. A collector's receipt time may be different from the event time.
  • Source: Where the event came from. Here the source includes the host, service, and process ID. In Windows, look for the computer, channel, and event provider.
  • Severity: The importance the producer assigned to the event. DEBUG gives diagnostic detail, INFO records routine activity, WARN flags an unexpected condition, ERROR marks a failure, and FATAL typically means the application cannot continue. Names and thresholds vary by source.
  • Message: What the producer observed. Fields such as a username, status code, or request ID are usually better search terms than a broad word like error.
  • Why Log Analysis Matters

    An authentication log can tell you that a service accepted a password. A firewall log can tell you which connection reached it. Neither tells you on its own who was at the keyboard or what they did afterward. Logs are especially valuable when each source answers a different part of the question. Do not overlook routine records: an INFO event for a new session may matter more than hundreds of warnings.

    Log management covers collection, storage, access, and retention. Log analysis asks questions of those records. A SIEM, or security information and event management platform, centralizes selected data so teams can search, correlate, and alert across sources. You can start investigating a single host without one.

    How to Analyze Logs in 5 Steps

    Prerequisites

    Use a host, lab VM, or evidence export you are authorized to inspect. The Linux commands assume a shell and common command-line tools; the journal commands require systemd. For Windows use Event Viewer or PowerShell. You will need read access to the relevant file or channel, and jq is optional for the JSON examples. Start by writing down the hostname, the symptom, and the approximate time.

    1. Find the Right Log

    Identify the event producer first. For an SSH sign-in, start with the host's authentication log or SSH service journal, not the web access log. Check which files are present and when they were last updated.

    ls -lh /var/log/
    

    2. Read It Live or Search It

    Read a few records before writing a filter. Check how the log represents time, username, and outcome. For a just-reported issue, the end of the active file is a good start; for an older issue, check retained files or a time-bounded journal query.

    tail -n 30 /var/log/auth.log
    

    3. Filter to the Signal

    Search for a specific message and keep the line numbers. Here the question is whether SSH recorded failed passwords. Once you have matches, narrow them by host, time, account, or source IP rather than treating every line as part of the same incident.

    grep -nF 'Failed password' /var/log/auth.log
    

    4. Correlate Across Sources

    Pull a bounded view of the service events, then compare it with an independent source such as a firewall or identity log. The journal and the flat file may contain copies of the same SSH message; two copies are not two observations.

    journalctl -u ssh.service --since '2026-11-29 09:10:00 UTC' --until '2026-11-29 09:20:00 UTC' --utc --no-pager
    

    5. Act on What You Found

    Document the evidence, your confidence, and what remains unknown. Escalate an unexpected successful login; for a routine outage, pass the affected service and time window to its owner. If you already have an approved evidence snapshot, record its checksum so a recipient can verify they have the same copy.

    sha256sum ./evidence/auth.log.snapshot
    

    Where Logs Live

    Linux Syslog and Flat Files

    A syslog daemon can route messages to text files by facility, severity, or local rules. The paths below are common, not guaranteed. A minimal VM or container may have no local syslog daemon, and a service can send its output to the journal or a remote collector instead.

    Common locationWhat to look for
    /var/log/syslog on Debian/Ubuntu or /var/log/messages on RHELGeneral system and service messages when file-based syslog is configured.
    /var/log/auth.log on Debian/Ubuntu or /var/log/secure on RHELAuthentication and authorization messages, including SSH and often sudo.
    /var/log/kern.logKernel messages where separately configured. Also check the kernel journal.
    /var/log/dmesgA boot-time kernel snapshot on systems that write this file. The dmesg command reads the current kernel ring buffer.
    /var/log/dpkg.logPackage installations, upgrades, and removals on systems using dpkg.
    /var/log/apache2/ and /var/log/nginx/Web access and error logs. Individual sites may have separate paths.
    /var/log/faillogA binary failed-login database where maintained. Use faillog rather than grep; it is not a complete SSH attempt history.

    For an existing lab account on a system that maintains the database, use the display-only form:

    faillog -u labuser
    

    The systemd Journal

    Journald stores binary records. The standard persistent location is /var/log/journal; the volatile location is /run/log/journal, which is lost at reboot. On systems where /var/run points to /run, /var/run/log/journal is equivalent to the volatile path; /var/run/journal is not the standard location. Read both types with journalctl, not a text editor.

    Windows and macOS

    In Windows Event Viewer, Windows Logs contains Security for auditing, System for operating system and service events, and Application for application events. Applications and Services Logs contains provider-specific channels such as Microsoft > Windows > PowerShell > Operational. Security log access requires appropriate permissions.

    On macOS, start with Console or run log show --last 1h to query the unified log for the past hour.

    Reading Logs: tail, less and the Journal

    Read the End or Follow a File

    Plain tail prints the last ten lines by default. Use -n to choose a larger sample before deciding whether a problem is still active.

    tail /var/log/auth.log
    tail -n 50 /var/log/auth.log
    

    Use tail -f to follow new writes. Press Ctrl+C to stop. If the daemon rotates the log by renaming it and opening a replacement, GNU tail -F follows the filename and retries; plain -f can stay attached to the old file.

    tail -f /var/log/auth.log
    
    tail -F /var/log/auth.log
    

    Navigate With less

    less lets you inspect a large text log without opening it in an editor. Open the file, type /Failed password, then use n and N to move through matches. Press g for the beginning, G for the end, and q to quit. To display only matching lines, type &Failed password; enter & with no pattern to clear the filter.

    less /var/log/auth.log
    

    Read the Journal or Kernel Buffer

    Plain journalctl reads the available journal in chronological order. Use -r for newest first, -f to follow new events, or -n to limit the number of records. Add --no-pager when piping output or running a bounded query you want printed directly.

    journalctl
    journalctl -r
    journalctl -n 30 --no-pager
    
    journalctl -f
    

    dmesg reads the current kernel ring buffer, which is useful for driver, disk, and hardware messages. The journal's -k filter is useful when you need kernel records with journal timestamps. If either source is restricted, use an approved account or export rather than weakening access controls.

    dmesg --level=err,warn
    journalctl -k -b -n 40 --no-pager
    

    Searching Logs with grep, awk and sed

    Search for a Phrase, Context, or Date

    Use -F for a literal phrase. Use -i for case-insensitive matching, and -C 3 for three lines of context on either side. Context is useful when a nearby record explains an error, but those neighboring lines are not necessarily part of the same request.

    grep -nF 'Failed password' /var/log/auth.log
    grep -in 'error' /var/log/syslog
    grep -nC 3 -F 'Failed password' /var/log/auth.log
    

    Use recursive search when you do not know which text file contains the event. Start with a service directory if you know it. The include pattern below selects files ending in .log, not compressed archives or binary journals.

    grep -rnF --include='*.log' 'Failed password' /var/log
    

    grep has no --since option. Pipe the latest lines from tail for a quick recent sample, or follow new lines and filter as they arrive. The last 500 lines are not a fixed time interval: on a busy host they might cover only seconds.

    tail -n 500 /var/log/auth.log | grep -F 'Failed password'
    tail -F /var/log/auth.log | grep --line-buffered -F 'Failed password'
    

    If a flat file uses classic syslog timestamps, you can match a date and hour as text. The expression below assumes the file's local clock and a Nov 29 09: timestamp prefix. For an exact UTC interval, use the journal's time filters or parse the file's timestamps explicitly.

    grep -E '^Nov[[:space:]]+29 09:' /var/log/auth.log | grep -F 'Failed password'
    

    Extract Fields and Edit Display Output

    This awk example extracts the client IP and HTTP status from a standard Apache combined access log. Splitting on quotes keeps the spaces inside the request and user-agent from shifting the status field. This simple parser assumes six delimiter quotes and skips lines that do not fit; verify the format and use a format-aware parser for escaped quotes or custom fields.

    awk -F '"' 'NF==7 { split($1,h," "); split($3,s," "); if (s[1] ~ /^[0-9][0-9][0-9]$/) print h[1],s[1] }' /var/log/apache2/access.log
    

    Use sed -n to print selected lines or mask a known value in output for a lab note. Neither command edits the original. Masking one address is not enough to anonymize a log that still contains usernames, URLs, or other identifiers.

    sed -n '1,12p' /var/log/auth.log
    grep -F 'Failed password' /var/log/auth.log |
      sed -E 's/from 203[.]0[.]113[.]45 port /from [lab-ip] port /g'
    

    Count the Top Source IPs and Usernames

    sort puts identical values next to one another so uniq -c can count them. sort -nr ranks those counts. For typical OpenSSH messages, the IP appears between from and port; extracting it by those markers is less brittle than taking the last field.

    grep -F 'Failed password' /var/log/auth.log |
      awk '{ for (i=1; i+2<=NF; i++) if ($i=="from" && $(i+2)=="port") { print $(i+1); break } }' |
      sort | uniq -c | sort -nr | head -n 10
    

    To count attempted usernames instead, account for both Failed password for and Failed password for invalid user. Compare counts from the same time window, and inspect raw matches before relying on any parser.

    sed -nE 's/.*Failed password for (invalid user )?([^[:space:]]+) from .*/\2/p' /var/log/auth.log |
      sort | uniq -c | sort -nr | head -n 10
    

    The systemd Journal: journalctl Deep Dive

    Filter by Service and Priority

    Use -u to select a unit. OpenSSH commonly uses ssh.service on Debian or Ubuntu and sshd.service on RHEL. Check the local unit name rather than assuming that an empty query means there was no activity. The Nginx unit may contain startup and error messages without containing the access log.

    systemctl list-unit-files 'ssh*.service'
    journalctl -u ssh.service -n 30 --no-pager
    journalctl -u sshd.service -n 30 --no-pager
    journalctl -u nginx.service -n 30 --no-pager
    

    -p err includes errors and more severe priorities. It is useful for finding a failed service startup, but do not use it as your only authentication filter.

    journalctl -p err -b -n 50 --no-pager
    

    Select a Boot or Time Window

    Use -b for the current boot, -b -1 for the previous retained boot, and --list-boots to see which boots are present. If you are investigating why a machine restarted, inspect the end of the previous boot as well as the beginning of the current one.

    journalctl --list-boots
    journalctl -b -n 30 --no-pager
    journalctl -b -1 -n 50 --no-pager
    

    Use --since and --until for an incident window. The explicit UTC suffixes set how the input times are interpreted; --utc makes the output display UTC. Include a little context before and after the reported event so you do not cut off the first failure or recovery.

    journalctl -u nginx.service --since '2026-11-29 09:00:00 UTC' --until '2026-11-29 09:30:00 UTC' --utc --no-pager
    

    Choose an Output Format

    -o short gives a readable, syslog-style view. -o json emits one JSON object per record so you can select fields by name instead of parsing spaces in a message. Not every record has every field.

    journalctl -u ssh.service -n 10 -o short --no-pager
    
    journalctl -u ssh.service -n 10 -o json --no-pager |
      jq -r '[._HOSTNAME, ._SYSTEMD_UNIT, .MESSAGE] | @tsv'
    

    Check Disk Usage and Enable Persistence if Authorized

    Check the journal's space usage before changing its storage. Retention depends on configured limits and available disk space, not just on whether the journal is persistent.

    journalctl --disk-usage
    

    The next commands change system state and are not part of the read-only lab. With Storage=auto, creating the persistent directory allows journald to use it. If configuration forces volatile storage, an administrator can set Storage=persistent in an approved /etc/systemd/journald.conf.d/ drop-in under [Journal]. After reviewing retention limits, an authorized administrator can prepare the directory, restart the service, and flush the current volatile journal to disk:

    sudo mkdir -p /var/log/journal
    sudo systemd-tmpfiles --create --prefix=/var/log/journal
    sudo systemctl restart systemd-journald.service
    sudo journalctl --flush
    

    Verify the result with journalctl --disk-usage and check retained boots after a planned reboot. Enabling persistence cannot recover journal records that were already lost.

    Worked Example: Investigating a Brute-Force Attack in auth.log

    This is a read-only investigation on a lab VM you own. No login attempts need to be generated. Every output below is illustrative. The source under investigation, 203.0.113.45, is from the TEST-NET-3 documentation range; the comparison address is also reserved for documentation. The names labuser and labguest are lab accounts or attempted lab usernames, and root is the built-in account name.

    Assume the lab uses OpenSSH, writes the same SSH messages to /var/log/auth.log and the journal, and uses UTC. The classic flat-file timestamps omit the year and offset; for this sample they are November 29, 2026, UTC.

    Illustrative auth.log excerpt:

    Nov 29 09:12:04 lab-vm sshd[2101]: Failed password for invalid user labguest from 203.0.113.45 port 51410 ssh2
    Nov 29 09:12:09 lab-vm sshd[2102]: Failed password for root from 203.0.113.45 port 51411 ssh2
    Nov 29 09:12:15 lab-vm sshd[2103]: Failed password for labuser from 198.51.100.24 port 50110 ssh2
    Nov 29 09:12:25 lab-vm sshd[2104]: Failed password for root from 203.0.113.45 port 51412 ssh2
    Nov 29 09:12:51 lab-vm sshd[2105]: Failed password for labuser from 203.0.113.45 port 51413 ssh2
    Nov 29 09:13:03 lab-vm sshd[2106]: Failed password for invalid user labguest from 203.0.113.45 port 51414 ssh2
    Nov 29 09:13:18 lab-vm sshd[2107]: Failed password for labuser from 203.0.113.45 port 51415 ssh2
    Nov 29 09:14:02 lab-vm sshd[2108]: Accepted password for labuser from 203.0.113.45 port 51416 ssh2
    

    1. Count Failed Passwords by IP

    In this sample, each failure ends with from IP port NUMBER ssh2, so $(NF-3) prints the IP. Confirm that suffix before using the shortcut. On a live host, restrict the time window and account for rotations; this pipeline counts matching records in the active file, not unique users or incidents.

    grep "Failed password" /var/log/auth.log | awk '{print $(NF-3)}' | sort | uniq -c | sort -nr | head
    

    Illustrative sample output:

          6 203.0.113.45
          1 198.51.100.24
    

    The top source has six failed-password events spread across several names in a short interval. That pattern is consistent with repeated guessing. A count alone does not distinguish an attack from, for example, an administrator or automation repeatedly using stale credentials.

    2. Check for Successful Authentication

    Search for accepted passwords from the exact source field, including the surrounding words so you do not match a longer address. On a real host, check other available methods as well: an Accepted publickey record will not show up in an Accepted password search.

    grep "Accepted password" /var/log/auth.log |
      grep -F 'from 203.0.113.45 port '
    

    Illustrative sample output:

    Nov 29 09:14:02 lab-vm sshd[2108]: Accepted password for labuser from 203.0.113.45 port 51416 ssh2
    

    Here SSH recorded successful password authentication for labuser after the burst. That raises the priority of the investigation, but it does not establish who controlled the source IP, whether a shell opened, or what happened afterward. Check whether the login was expected and look for session records. Conversely, no match means you found no matching record in that data, not that no login occurred.

    3. Establish the First and Last Observed Failures

    Use a slightly wider journal interval than the burst and keep the view in chronological order. Use the lab's actual unit name if it differs from ssh.service. This reads the same events with explicit date and offset; do not add the journal matches to the flat-file count.

    journalctl -u ssh.service --since '2026-11-29 09:10:00 UTC' --until '2026-11-29 09:20:00 UTC' --utc -o short-iso --no-pager |
      grep -F 'from 203.0.113.45 port ' |
      grep -F 'Failed password' |
      awk 'NR==1 {print "first:",$0} {last=$0} END {if (NR) print "last:",last}'
    

    Illustrative sample output:

    first: 2026-11-29T09:12:04+0000 lab-vm sshd[2101]: Failed password for invalid user labguest from 203.0.113.45 port 51410 ssh2
    last: 2026-11-29T09:13:18+0000 lab-vm sshd[2107]: Failed password for labuser from 203.0.113.45 port 51415 ssh2
    

    These are the first and last failures in the selected records, not necessarily the start and end of the incident. Expand the window or check older retained logs if either boundary is close to the edge of your search.

    4. Check Which Accounts Were Targeted

    Extract usernames only from this source's failed-password events. The optional invalid user prefix should not be counted as part of a name.

    grep -F 'from 203.0.113.45 port ' /var/log/auth.log |
      sed -nE 's/.*Failed password for (invalid user )?([^[:space:]]+) from .*/\2/p' |
      sort | uniq -c | LC_ALL=C sort -k1,1nr -k2,2
    

    Illustrative sample output:

          2 labguest
          2 labuser
          2 root
    

    The source tried root twice, but the failures do not show that root login was enabled or that root access was obtained. The only accepted record shown is for labuser. Review session, privilege-use, and account-change records for that account if the login is unexpected.

    5. Document the Finding and Harden After Review

    The evidence supports this finding: one source produced six failures between 09:12:04 and 09:13:18 UTC, then SSH accepted a password for labuser at 09:14:02 UTC. Whether the successful authentication was unauthorized is unresolved. In a real incident, preserve the time window and escalate the unexpected success before making changes that could affect evidence or access.

    After reviewing the finding, an administrator can consider key-only SSH, with password and keyboard-interactive settings reviewed and a recovery path tested before enforcement. Fail2ban can temporarily block repeated failures if it monitors the correct log source; consider shared addresses and legitimate users before setting a policy. A non-standard port may reduce background scanning noise, but it is not an access control. None of these hardening measures substitutes for investigating the accepted login.

    Windows Event Logs

    In Event Viewer, filter the Security log by time and Event ID, then open Details to inspect named fields. Read the provider and channel along with the ID. For example, 4104 belongs to a PowerShell operational channel, not the Security channel.

    Event IDMeaningWhat to verify
    4624Successful logonAccount, logon type, source address if present, and target logon ID.
    4625Failed logonTarget account, source if present, failure status, and logon type.
    4634LogoffMatch the logon ID to a session on the same host.
    4672Special privileges assigned to a new logonCheck the account and privileges against the expected role.
    4688Process creationReview the executable and parent; command-line capture requires separate configuration.
    4698Scheduled task createdCheck the creator, task name, and action. Creation does not prove execution.
    4720User account createdDistinguish the account that performed the action from the new account.
    4732Member added to a security-enabled local groupIdentify the group, added member, and actor; verify authorization.
    4104PowerShell script block loggingReview script block text and context in the appropriate operational channel.

    Query the Security Log With PowerShell

    Get-WinEvent -FilterHashtable selects events at the source instead of loading the full channel into a pipeline. Keep the time limit when adapting this query to account creation or process creation.

    Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4625; StartTime=(Get-Date).AddHours(-24)} -MaxEvents 40 |
      Select-Object TimeCreated, Id, MachineName, Message |
      Format-List
    

    Use -FilterXPath when you want an event XML query. This example pulls both successful and failed logons from the last hour; timediff compares against the event timestamp in milliseconds.

    Get-WinEvent -LogName Security -FilterXPath '*[System[(EventID=4624 or EventID=4625) and TimeCreated[timediff(@SystemTime) <= 3600000]]]' -MaxEvents 100
    

    A burst of 4625 events followed by a 4624 for the same target account deserves review, but compare the logon type and source first. Type 2 is interactive, type 3 is network, and type 10 is remote interactive. A network logon is not proof that someone opened a desktop. For a successful logon, the logon ID can help connect 4624, 4672, and 4634 on the same host. Do not force the failed records into that session if they have no matching target logon ID.

    Prefer named XML fields over parsing localized message text. An empty source IP is a coverage limitation, not evidence that the logon was local.

    $filter = @{LogName='Security'; Id=4625; StartTime=(Get-Date).AddHours(-1)}
    Get-WinEvent -FilterHashtable $filter -MaxEvents 200 | ForEach-Object {
        $xml = [xml]$_.ToXml()
        $data = @{}
        foreach ($node in $xml.Event.EventData.Data) {
            $data[$node.GetAttribute('Name')] = $node.InnerText
        }
        [pscustomobject]@{
            TimeUtc   = $_.TimeCreated.ToUniversalTime().ToString('o')
            Account   = $data['TargetUserName']
            SourceIp  = $data['IpAddress']
            LogonType = $data['LogonType']
            Status    = $data['Status']
        }
    }
    

    Export Events and Review Script Blocks

    From an approved evidence directory, export a copy with wevtutil epl. The command does not clear the source log. Restrict the exported file as carefully as you would the live Security log.

    wevtutil epl Security .\lab-security.evtx
    Get-WinEvent -Path .\lab-security.evtx -MaxEvents 20
    

    When script block logging is enabled, Windows PowerShell records 4104 events in its Operational channel. Check the locally configured PowerShell channel if you use a different edition. Script text helps explain what was processed, but it does not prove that each operation completed, and it can contain sensitive values.

    Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; Id=4104; StartTime=(Get-Date).AddHours(-1)} -MaxEvents 25
    

    Web Server Logs

    Read a Combined Access Log Line

    Apache and Nginx can both write combined-style access logs. Check your server configuration before applying field numbers, particularly behind a reverse proxy or when logs use JSON. Here is an illustrative combined entry:

    203.0.113.45 - - [29/Nov/2026:09:14:29 +0000] "GET /login HTTP/1.1" 200 1842 "-" "lab-client/1.0"
    
    FieldMeaning in the example
    Client IP203.0.113.45 is the address recorded by the server. Behind a proxy, verify how the client address is derived.
    IdentThe first - is the unused ident field in this layout.
    Authenticated userThe second - means no authenticated user was recorded in this field.
    TimestampThe server logged the request on November 29 at 09:14:29 with a UTC offset of +0000.
    RequestThe client requested /login using GET and HTTP/1.1. The request target can include a query string.
    StatusHTTP 200 is the response status. For this request it does not indicate a successful sign-in.
    BytesThe response body was logged as 1842 bytes, excluding headers in this layout.
    ReferrerThe quoted "-" means no referrer was recorded.
    User-agentlab-client/1.0 is client-supplied text, not a verified identity.

    A combined line does not normally include the request body, per-request duration, or application authentication outcome. Use trusted proxy configuration rather than treating any client-supplied forwarding header as the source IP.

    Find Top Paths and 404 Spikes

    Strip the query string when counting paths, so variations of one URL do not dominate the list. Run the counts on comparable windows when checking for spikes.

    awk -F '"' 'NF==7 {split($2,r," "); sub(/[?].*$/,"",r[2]); if (r[2]!="") print r[2]}' /var/log/apache2/access.log |
      sort | uniq -c | sort -nr | head -n 10
    

    Pair 404 responses with their source addresses. Many unrelated missing paths from one source in a short window can suggest scanning; many users requesting the same missing asset after a deployment suggests a broken link instead.

    awk -F '"' 'NF==7 {split($3,s," "); if (s[1]==404) {split($1,h," "); split($2,r," "); sub(/[?].*$/,"",r[2]); print h[1],r[2]}}' /var/log/apache2/access.log |
      sort | uniq -c | sort -nr | head -n 10
    

    Triage Suspicious Request Strings

    Search the logged request field for indicators such as UNION SELECT and OR 1=1. This filter covers a few common ways those fragments can appear in access logs, not every variant. Legitimate search terms can match, and data absent from the log cannot be searched.

    awk -F '"' 'NF==7 && tolower($2) ~ /(union([[:space:]]|[+]|%20)+select|or([[:space:]]|[+]|%20)+1(=|%3d)1)/' /var/log/apache2/access.log
    

    An HTTP 500 near a suspicious request helps prioritize review, but it does not show that SQL injection succeeded. A 200 does not settle the question either. Use application, web application firewall, and database audit records to look for unexpected operations associated with the request. Do not replay suspicious traffic to interpret a log entry.

    Check Login Failures and Response Times

    If the application uses 401, 403, or 429 for rejected or rate-limited requests, count those responses for POST /login. Some applications return 200 or redirect after a failed login, so compare access logs with application or identity-provider outcomes before labeling a source as brute-forcing.

    awk -F '"' 'NF==7 {split($1,h," "); split($2,r," "); split($3,s," "); sub(/[?].*$/,"",r[2]); if (r[1]=="POST" && r[2]=="/login" && (s[1]==401 || s[1]==403 || s[1]==429)) print h[1],s[1]}' /var/log/nginx/access.log |
      sort | uniq -c | sort -nr | head -n 10
    

    Measure latency only if it was recorded. This example assumes a custom Nginx log ends each record with rt= followed by $request_time in seconds. Apache's %D, by contrast, records microseconds. Compare the same endpoint under similar conditions; two seconds is an example threshold, not a universal definition of slow.

    awk '$NF ~ /^rt=[0-9]+([.][0-9]+)?$/ {if (substr($NF,4)+0 >= 2) print}' /var/log/nginx/access-timed.log
    

    DNS Log Analysis

    A DNS log shows what a resolver or sensor observed: typically a client, query name, record type, and response code. To interpret a spike, establish whether the source field identifies the endpoint or an upstream resolver shared by many clients.

  • DGA domains: Domain generation algorithms can produce many unfamiliar names. Look for repeated queries to distinct generated-looking names, especially when many return NXDOMAIN. One strange name is weak evidence.
  • Long subdomains and possible tunneling: Look for many unique, unusually long labels under the same parent domain, repeated queries from one client, or shifts in record types and volume. Legitimate services also use long labels and TXT records.
  • Unusual top-level domains: A TLD such as .tk or .ml may be uncommon in your environment. Compare it with your baseline and current threat intelligence rather than treating the TLD itself as malicious.
  • Fast-flux behavior: Frequent changes in returned A or AAAA records and short TTLs can justify a closer look. CDNs and load balancing can also change addresses rapidly. You need answer records over time, not just query names, to check this pattern.
  • Check for Long Labels With grep and awk

    Suppose an approved text export has five whitespace-separated fields: UTC timestamp, client IP, query name, query type, and response code. These are illustrative input records:

    2026-11-29T09:15:00Z 198.51.100.24 updates.lab.example. A NOERROR
    2026-11-29T09:15:07Z 198.51.100.24 abcdefghijklmnopqrstuvwxabcdefghijklmnopqrstuvwx.lab.example. TXT NOERROR
    

    Select a few common query types, split the query name at each dot, and report the first label at least 45 characters long. Measure labels individually so several short labels in a long name do not trigger the check.

    grep -E '[[:space:]](A|AAAA|TXT)[[:space:]]' ./evidence/dns-queries.log |
      awk '{n=split($3,label,"[.]"); for (i=1; i<=n; i++) if (length(label[i])>=45) {print $1,$2,$3,$4,length(label[i]); break}}'
    

    Illustrative sample output:

    2026-11-29T09:15:07Z 198.51.100.24 abcdefghijklmnopqrstuvwxabcdefghijklmnopqrstuvwx.lab.example. TXT 48
    

    The first query does not match; the second contains a 48-character label. Next check how often the client queried that parent domain, whether other clients do the same, and which process made the requests if you have endpoint telemetry. Label length is a triage threshold, not proof of tunneling.

    Cloud Service Logs

    Cloud trails help answer who made a request, what resource they targeted, and whether the service reported an error. Start by identifying the account or tenant, region where relevant, and time range your export covers. Use the provider's event time for the timeline; delivery and indexing can lag.

    AWS CloudTrail

    Monitor CreateUser for new IAM users, PutUserPolicy for an inline user policy change, and AuthorizeSecurityGroupIngress for added inbound rules. Check the actor or assumed role, request parameters, target resource, and reported outcome. A security group rule change is worth reviewing, but its name alone does not tell you whether a workload is now reachable.

    For a CloudTrail log file with a top-level Records array, use jq to select those events. If your input comes from another export or API, inspect the JSON first; different exports can wrap the same records differently.

    jq -r '.Records[]
      | select(.eventName == "CreateUser" or .eventName == "PutUserPolicy" or .eventName == "AuthorizeSecurityGroupIngress")
      | [.eventTime, .eventName, (.userIdentity.arn // .userIdentity.principalId // "unknown"), .sourceIPAddress, (.errorCode // "no error recorded"), .eventID]
      | @tsv' ./evidence/cloudtrail.json
    

    Console sign-ins give you a separate authentication view. The sourceIPAddress field can contain a service value rather than an IP, so do not assume it always identifies a client.

    jq -r '.Records[] | select(.eventName == "ConsoleLogin")
      | [.eventTime, .userIdentity.arn, .sourceIPAddress, .responseElements.ConsoleLogin] | @tsv' ./evidence/cloudtrail.json
    

    Azure Monitor and Microsoft Entra Logs

    Use Entra sign-in logs to examine failed sign-ins, unexpected locations, or unfamiliar applications. For a Microsoft Graph sign-in export with a top-level value array, a nonzero status.errorCode indicates a sign-in that did not succeed. Read the code and related policy details before classifying it as a bad password. Make sure the export includes all pages you intend to analyze.

    jq -r '.value[]
      | select(.status.errorCode != null and (.status.errorCode | tostring) != "0")
      | [.createdDateTime, .userPrincipalName, .ipAddress, .status.errorCode, .correlationId]
      | @tsv' ./evidence/entra-signins.json
    

    If the data is routed to Azure Monitor Logs, use KQL to filter SigninLogs. For suspected privilege escalation, check audit records for role assignments and other privilege changes. A successful sign-in is not itself a role change.

    SigninLogs
    | where TimeGenerated > ago(24h)
    | where isnotempty(ResultType) and tostring(ResultType) != "0"
    | project TimeGenerated, UserPrincipalName, IPAddress, AppDisplayName, ResultType, CorrelationId
    | order by TimeGenerated desc
    
    AuditLogs
    | where TimeGenerated > ago(24h)
    | where Category == "RoleManagement"
    | project TimeGenerated, OperationName, Result, InitiatedBy, TargetResources, CorrelationId
    | order by TimeGenerated desc
    

    For a role change, verify the initiating identity, the target identity, the role scope, and any approved change record. Keep the event or correlation ID in your notes so another analyst can retrieve the original event.

    Correlation Techniques

    Time-Based vs. Session-Based Correlation

    Time-based correlation puts events from different sources in order. Normalize timestamps to UTC for comparison, preserve the original timestamp and offset, and check whether the clocks were synchronized through NTP or your organization's time service. A clock that is correct now may have been wrong during the incident. If you find a historical offset, document the adjustment rather than editing the source records.

    timedatectl status
    
    w32tm /query /status
    

    Session-based correlation groups records using an identifier such as a request ID, a Windows logon ID scoped to a host and boot, or the network connection tuple: source and destination addresses, ports, and protocol. Include time because connections and identifiers can be reused. If traffic passed through NAT or a proxy, you may need translation or proxy records before those fields can be joined reliably.

    Build One Timeline From SSH, Web, and Firewall Logs

    Continue the lab example with a saved firewall export that records source and destination fields. Filter for the documentation IP and destination port 22; the regular expressions keep the field matches exact. Use the web log's first field only after confirming that it is the recorded client address.

    grep -E '(^|[[:space:]])SRC=203[.]0[.]113[.]45([[:space:]]|$)' ./evidence/firewall.log |
      grep -E '(^|[[:space:]])DPT=22([[:space:]]|$)'
    
    awk '$1=="203.0.113.45"' /var/log/nginx/access.log
    

    Illustrative timeline, with all events shown in UTC:

    TimeSourceObservation
    09:12:03FirewallAllowed TCP from 203.0.113.45:51410 to the lab VM at 192.0.2.10:22.
    09:12:04auth.logFirst observed failed password from 203.0.113.45:51410, for labguest.
    09:14:01FirewallAllowed TCP from the same source IP, now port 51416, to 192.0.2.10:22.
    09:14:02auth.logAccepted password for labuser from source port 51416.
    09:14:29Web access logRecorded GET /login from the same IP with HTTP 200.

    The SSH and firewall records can be joined by address, port, host mapping, and time. The web request shares an IP and is close in time, but is a separate connection. It does not establish that the same person made both requests or that anyone signed in to the web application.

    Hand Off to a SIEM

    Forward events that help reconstruct activity: authentication successes and failures, privilege and account changes, selected process events, web access and error logs, DNS queries, firewall decisions, and cloud sign-in and control-plane events. Avoid forwarding only errors or only blocked traffic; successful actions often answer the most important questions.

    Map equivalent fields to a shared schema: event time in UTC, ingestion time, host, source and destination, actor, target, action, outcome, provider, and event ID. Keep a reference to the original event. A missing value is unknown, not a successful outcome. Test a sample from each source: confirm the timestamp, verify that the actor and target were not swapped, and check that duplicate copies of one observation are not inflating alerts. Include the exact scope and filters used when you hand an investigation to another analyst.

    Log Analysis Tools Compared

    For log analysis on Kali Linux, start with the tools that fit the source. You do not need to deploy a SIEM to read one host's authentication history; central tooling becomes useful when you need to retain and compare events across systems.

    ToolWhen to use itWhat to account for
    grep, awk, and sedQuick searches, extraction, and counts on known text formats.Verify delimiters and sample matches before trusting counts.
    journalctlService, boot, priority, and time filters on a systemd host.Visibility depends on retention and permissions.
    PowerShellQuery Windows event channels or saved EVTX files.Filter at the source and read named XML fields for repeatable queries.
    lnavBrowse or search several local logs interactively.Confirm that it recognized the format and parsed timestamps as expected.
    SplunkSearch indexed data across hosts and build dashboards or alerts.Plan source onboarding, field extraction, and access controls.
    WazuhCentralize endpoint security events and review rule-based alerts.Verify agent coverage and that the selected log sources are collected.
    ELK StackBuild a pipeline with Elasticsearch, Logstash, and Kibana for indexing and visualization.Plan ingestion, schema, and index retention.
    GraylogCentralized log search and routing.Validate inputs and parsing before relying on cross-source queries.

    If lnav is installed and you can read both files, open them together. Verify their timezones before comparing events.

    lnav /var/log/auth.log /var/log/nginx/access.log
    

    Log Analysis Cheat Sheet

    Commands Quick Reference

    TaskCommandReminder
    Read the latest 50 linestail -n 50 /var/log/auth.logA line limit is not a time limit.
    Follow a rotating logtail -F /var/log/auth.logFollows the filename and retries on GNU systems.
    Find failed passwordsgrep -nF 'Failed password' /var/log/auth.logPrints matching line numbers.
    Extract web client addressesawk '{print $1}' /var/log/nginx/access.logAssumes the first field is the address.
    Read the recent SSH journaljournalctl -u ssh.service --since '1 hour ago' --no-pagerUse the locally configured unit name.
    Query recent Windows failuresGet-WinEvent -FilterHashtable @{LogName='Security'; Id=4625} -MaxEvents 20Returns the newest matches up to the cap, not all failures in a fixed window.

    What to Look For

    SignalStart withVerify next
    Failed logonsSSH failures or Windows 4625Group by source, account, and time; look for unexpected successes.
    New usersWindows 4720, CloudTrail CreateUser, or local account-management logsIdentify who created the account, whether it was approved, and what access was assigned.
    404 spikesWeb access logs grouped by source and pathCompare diverse missing paths with a repeated missing asset after a deployment.
    Long DNS labelsResolver query logsCheck repeated unique labels, the parent domain, and the client baseline.
    Privilege useWindows 4672, sudo records, or cloud audit eventsCheck the actor and expected role; distinguish privilege assignment from its use.

    Troubleshooting Log Analysis Problems

    ProblemWhat to check
    Log file is empty or rotatedRun ls -lt /var/log/auth.log*. Check the active file and any retained .1 archive. For a compressed archive that exists, use zgrep -nF 'Failed password' /var/log/auth.log.2.gz. Check for overlap before adding counts.
    journalctl shows nothingVerify permissions, the local unit name, and the time filter. Check journalctl --list-boots for retained history. In a container, service logs may be collected by the host or runtime.
    grep finds nothingInspect a few raw lines with tail -n 20. Check the file, case, spelling, rotation, and whether the pattern should be literal. Try grep -inF if capitalization varies.
    Timestamps do not line upCompare source offsets, NTP status, and known events. Distinguish event time from ingest time, and check whether a classic syslog date omitted the year or timezone.
    Too many resultsNarrow to one host and service, then add time, outcome, and account or request ID. Sample the remaining raw lines before writing an aggregation.
    Log file is too big to openUse less or a bounded tail for inspection, and stream filters over the relevant file. Search compressed archives directly rather than decompressing them in place.
    Windows events are missingUse Get-WinEvent -ListLog Security to inspect the channel. Verify auditing policy, permissions, retention, and whether the event was recorded on a different host or provider channel.
    Cloud logs are delayedConfirm the account or tenant, region, export route, and time range. Compare event and ingest times and recheck after delivery before concluding the event is absent.

    Common Mistakes

  • Searching only for errors. Account creation, successful sign-ins, and privilege assignments may be routine from the producer's perspective. Start with the event that would answer your question, not with a severity cutoff.
  • Treating missing logs as proof that nothing happened. Check whether the event was ever configured to be logged, whether the producer was healthy, and whether the time window is still retained. Record any gaps you cannot resolve.
  • Counting rows as people or sessions. One person can retry repeatedly, a shared IP can represent many clients, and two collectors can store copies of the same record. Say exactly what your count represents.
  • Sorting timestamp strings from different systems as if they were equivalent. Normalize offsets and verify clock skew first. Note when timestamp precision is too low to order two nearby events confidently.
  • Treating a correlation as proof of cause. A shared IP or an HTTP 500 is a reason to check another source, not a verdict. Prefer a request or session identifier and evidence that directly records the suspected outcome.
  • Relying on a parser you have not tested. Confirm extraction against both expected and unusual records. Check custom log formats, quoted values, and records with missing fields before you rank or compare counts.
  • Editing or oversharing the evidence. Avoid in-place edits. Keep approved originals or exports intact, and redact unrelated account names, tokens, and personal data from working notes before sharing them.
  • Best Practices

  • Define the question and scope. Record the affected host or tenant, expected actor, event type, and bounded time window. Keep the query and any limits with the result so another analyst can reproduce it.
  • Maintain synchronized clocks. Use monitored time synchronization, retain the original offset, and use UTC in shared timelines. Check known events across sources when a clock shift might change the sequence.
  • Collect structured fields when possible. Preserve request IDs, logon IDs, status codes, and separate actor and target fields. Validate normalization against raw records whenever a producer changes its format.
  • Protect the records. Grant least-privilege access, protect stored copies and transfers, and set retention by investigation needs and policy. Keep evidence exports in an approved location, not on a shared scratch drive.
  • Compare like with like. Baseline traffic by service, role, and time of day. Include relevant changes such as deployments or approved administrative jobs before deciding that a change in volume is suspicious.
  • Test collection and handoff. Verify that a known event arrives with the right time, host, and outcome. Assign ownership for missing feeds and alerts, and include both supporting evidence and unresolved questions when escalating.
  • Is Log Analysis Legal?

    Reading your own logs or logs you are authorized to analyze is generally fine within the agreed scope. Do not read other people's logs without permission, even if a file or dashboard is technically accessible. At work, follow the organization's access, handling, and incident reporting rules.

    IP addresses can be personal data in some jurisdictions. Limit what you collect or share, restrict access, and follow applicable retention and privacy requirements.

    Summary

  • Start with a question, then find the event producer and a defensible time window.
  • Use tail and less to read text logs, grep and awk to filter and count them, and journalctl or Get-WinEvent for structured sources.
  • Check outcomes as well as failures. In the lab, the six rejected passwords mattered, but the later accepted password changed the investigation's priority.
  • Normalize time, then use session identifiers or connection fields to corroborate activity. A shared IP alone does not establish identity.
  • Preserve evidence, document coverage gaps, and escalate only the conclusions the records support.
  • Knowledge Check

  • Where would you look for SSH authentication records on Debian or Ubuntu versus RHEL?
  • Why is tail -n 500 not equivalent to querying the last hour, and which journal option sets a start time?
  • Does journalctl -p err include more severe entries or only entries at exactly err?
  • Which Windows event IDs indicate successful and failed logons, and where do you look for 4104?
  • What does an Accepted password line establish, and what does it not establish?
  • Does an HTTP 500 after a suspicious request demonstrate successful SQL injection?
  • What should you check after finding a DNS label above your length threshold?
  • How does session-based correlation differ from time-based correlation, and why do synchronized clocks matter?
  • Answers: 1. Try /var/log/auth.log on Debian or Ubuntu and /var/log/secure on RHEL; check the SSH journal if the file is absent or incomplete. 2. Five hundred lines cover different amounts of time at different log rates; use journalctl --since for a start time. 3. It includes err and more severe priorities. 4. 4624 is success, 4625 is failure, and 4104 is in the relevant PowerShell operational channel. 5. SSH recorded successful password authentication for that account; it does not prove who authenticated, that a shell opened, or what happened afterward. 6. No. Check application, WAF, and database evidence for the actual outcome. 7. Review recurrence, unique labels under the same parent domain, query types, and the client's normal behavior. 8. Session-based correlation groups records by a shared session ID or connection tuple; time-based correlation orders records by timestamp. Synchronized clocks help establish the sequence and keep joins within the correct time window.

    Keep Learning

  • SIEM Fundamentals: Security Information and Event Management
  • Security Monitoring: Building Detection Capabilities
  • Incident Response: Structured Approach to Security Breaches
  • Detection Engineering: Creating Security Alerts and Rules
  • Threat Hunting for Beginners: What It Is & How to Start Your First Hunt
  • Splunk
  • Wireshark
  • Wazuh
  • Nmap
  • Frequently Asked Questions

    What are the most important Windows Security Event IDs for log analysis?

    Key Windows event IDs include 4624 (successful logon), 4625 (failed logon), 4688 (process creation), 4672 (special privileges), 4720 (account created), 4732 (user added to group), and 4104 (PowerShell script block). These events provide visibility into authentication, execution, and privilege changes.

    Why is time synchronization critical for log analysis?

    Time synchronization via NTP ensures events from different systems can be accurately correlated in timelines. Without synchronized clocks, events from firewalls, servers, and endpoints cannot be ordered correctly, breaking attack chain reconstruction and incident investigation.

    What suspicious DNS patterns indicate malicious activity?

    Suspicious DNS patterns include DGA (algorithmically generated) domains, unusually long subdomain names (potential tunneling), rare TLDs like .tk or .ml, fast-flux DNS with rapidly changing records, and queries to domains matching threat intelligence feeds.

    What information is in a standard Apache combined log format entry?

    A combined log format entry contains: client IP address, identity, authenticated user, timestamp, request method/URL/protocol, HTTP status code, bytes sent, referrer URL, and user-agent string. This provides a complete picture of each HTTP request.

    How do you detect SQL injection attempts in web logs?

    Search web access logs for suspicious patterns like 'UNION SELECT', 'OR 1=1', 'DROP TABLE', single quotes, double dashes, and encoded payloads in URL parameters. Combine with HTTP 500 errors to identify successful injection attempts.

    What are the key Linux log files for security analysis?

    Critical Linux logs include /var/log/auth.log (authentication events), /var/log/syslog (system messages), /var/log/kern.log (kernel events), /var/log/apache2/ (web server logs), and /var/log/nginx/ (Nginx logs). Use journalctl on systemd systems for structured querying.

    What is the difference between time-based and session-based log correlation?

    Time-based correlation aligns events from multiple sources by timestamp to reconstruct attack chains. Session-based correlation groups events by connection tuple or session ID. Time-based reveals attack sequences; session-based tracks individual communication sessions.

    How do you analyze cloud service logs for security threats?

    For AWS CloudTrail, monitor IAM user creation, security group changes, and console logins. For Azure Monitor, track failed sign-ins and privilege escalations. Use jq or KQL queries to filter events and detect anomalies in API call patterns and access behavior.

    What is log normalization and why does it matter?

    Log normalization converts different log formats (Windows Event Logs, Syslog, web logs) into a common schema for unified analysis. Without normalization, a SIEM cannot correlate events from different sources, creating blind spots in detection capabilities.

    What tools are commonly used for log analysis?

    Common log analysis tools include Splunk and ELK Stack for enterprise SIEM, grep/awk/sed for command-line analysis, PowerShell for Windows events, journalctl for systemd logs, and lnav for advanced log file navigation. The choice depends on scale and infrastructure.

    How do I analyze logs?

    Find the log that records the event you care about, then read it live or search a specific time window. Filter for relevant records, compare them with another source, and act on what the evidence supports by documenting, escalating, or resolving the issue.

    What is log analysis?

    Log analysis is the process of reading, filtering, and comparing records from systems, applications, and devices to understand what happened. It helps you troubleshoot failures, identify suspicious activity, and test explanations against evidence from more than one source.

    How do I read logs in Linux?

    For text logs, use tail -n to read the latest entries, tail -f to watch new ones, and grep to search for a message or account. On a systemd host, use journalctl to read the journal and filter by service, boot, or time window.

    What are the best log analysis tools for Kali Linux?

    Start with grep, awk, and sed for text logs, journalctl for the systemd journal, and lnav for interactive browsing across files. For ongoing monitoring across multiple hosts, forward selected records to a central platform such as Wazuh or Splunk.

    How do I analyze logs for a brute-force attack?

    On systems you are authorized to investigate, grep auth.log for 'Failed password', count records by source IP, and check which accounts were targeted in the relevant time window. Look for 'Accepted password' or other successful authentication records from the same source, then verify any unexpected success against session and account activity.

    Continue Learning

    Security Operations · Intermediate

    Threat Hunting for Beginners: What It Is & How to Start Your First Hunt

    Learn threat hunting for beginners: what it is, how to start with a hypothesis, your first lab hunt with Sysmon and Splunk queries, tools, and a cheat sheet.

    Security Operations · Advanced

    Digital Forensics Basics: Collecting and Analyzing Evidence

    Learn digital forensics fundamentals including evidence collection, forensic imaging, memory analysis, timeline analysis, and proper chain of custody procedures for investigations.

    Security Operations · Advanced

    Incident Response: Structured Approach to Security Breaches

    Learn the incident response lifecycle including preparation, detection, containment, eradication, recovery, and lessons learned with practical frameworks and real-world scenarios.

    Security Operations · Advanced

    Detection Engineering: Creating Security Alerts and Rules

    Learn detection engineering principles including rule development, Sigma rules, testing methodologies, false positive management, and building a detection program for security operations.

    Related Security Tools

    Sniffing & Spoofing

    Wireshark

    Wireshark tutorial for beginners: capture packets, read the three panes, filter traffic and follow TCP streams — a hands-on guide to the world's foremost network protocol analyzer.

    Information Gathering

    Nmap

    Learn how to use Nmap, the free open-source network scanner: run your first port scan, discover live hosts, detect services and operating systems, and check for vulnerabilities with NSE scripts — a beginner tutorial for Kali Linux.

    Sniffing & Spoofing

    tcpdump

    tcpdump is a powerful, lightweight command-line packet analyzer that allows users to capture, parse, and filter TCP/IP and other packets transmitted or received over a network.

    Forensics

    Binwalk

    Learn how to use Binwalk to scan a firmware image, read the signature table, extract embedded filesystems, and spot encrypted regions — a beginner tutorial for Kali Linux.

    Written by GO KALI FREE Team