Search code examples
c#regexstringwindowsevent-log

Strings won't write to the console together in C#


I'm super confused. I wrote a script to extract the time, IP, account name, and account domain from a failed login in the Event Log. Individually, the variables write just fine to the console. But, if I try to put the variables next to each other in a string definition, it draws blanks.

Code:

using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;

class Program
{

    static void Main()
    {
        string GetIP(string input)
        {
            Regex regex = new Regex(@"Source Network Address:.*");
            Match match = regex.Match(input);


            if (match.Success)
            {
                string ipAddress = Regex.Replace(match.Value, @"Source Network Address:\s*", "");
                return ipAddress;
            }
            else
            {
                return "No match found.";
            }
        }
        string GetAcc(string input)
        {
            Regex regexAccountName = new Regex(@"Account Name:\s*(\S+)");

            // Find all matches in the input string.
            MatchCollection matches = regexAccountName.Matches(input);

            if (matches.Count >= 2)
            {
                // Extract the value from the second match (index 1).
                string accountName = matches[1].Groups[1].Value;
                return accountName;
            }
            else
            {
                return "No match found.";
            }
        }
        string GetDomain(string input)
        {
            Regex regexAccountName = new Regex(@"Account Domain:\s*(\S+)");

            // Find all matches in the input string.
            MatchCollection matches = regexAccountName.Matches(input);

            if (matches.Count >= 2)
            {
                // Extract the value from the second match (index 1).
                string accountName = matches[1].Groups[1].Value;
                return accountName;
            }
            else
            {
                return "No match found.";
            }
        }
        Console.WriteLine("Date/Time,IP Address,Account Name,Account Domain");

        int targetEventId = 4625;
        string logName = "Security"; // You can change the log name as needed

        EventLog eventLog = new EventLog(logName);

        foreach (EventLogEntry entry in eventLog.Entries)
        {
            if (entry.InstanceId == targetEventId)
            {
                // Console.WriteLine($"Event ID: {entry.InstanceId}");
                // Console.WriteLine($"Time: {entry.TimeGenerated}");
                DateTime Time = Convert.ToDateTime(entry.TimeGenerated);
                Console.WriteLine(Time);
                // Console.WriteLine($"Message: {entry.Message}");
                string message = entry.Message;
                string ip = GetIP(message);
                Console.WriteLine(ip);
                string acc = GetAcc(message);
                Console.WriteLine(acc);
                string domain = GetDomain(message);
                Console.WriteLine(domain);
                string csvOutput = Time+","+ip+","+acc+","+domain;
                Console.WriteLine(csvOutput);
            }
        }

        eventLog.Close();
        Console.WriteLine("End of logs. Press any key to exit.");
        Console.ReadKey();
    }
   
}

Input:

Event ID: 4625
Time: 9/26/2023 10:39:55 AM
Message: An account failed to log on.

Subject:
        Security ID:            S-1-0-0
        Account Name:           -
        Account Domain:         -
        Logon ID:               0x0

Logon Type:                     3

Account For Which Logon Failed:
        Security ID:            S-1-0-0
        Account Name:           abc@def.ghi
        Account Domain:         MicrosoftAccount

Failure Information:
        Failure Reason:         %%2313
        Status:                 0xc000006d
        Sub Status:             0xc000006a

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

Network Information:
        Workstation Name:       DESKTOP-J7O5MEA
        Source Network Address: 192.168.1.198
        Source Port:            0

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

This event is generated when a logon request fails. It is generated on the computer where access was attempted.

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

The Logon Type field indicates the kind of logon that was requested. The most common types are 2 (interactive) and 3 (network).

The Process Information fields indicate which account and process on the system requested the logon.

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

The authentication information fields provide detailed information about this specific logon request.
        - Transited services indicate which intermediate services have participated in this logon request.
        - Package name indicates which sub-protocol was used among the NTLM protocols.
        - Key length indicates the length of the generated session key. This will be 0 if no session key was requested.

Output:

Date/Time,IP Address,Account Name,Account Domain
9/26/2023 10:39:53 AM
192.168.1.198
abc@def.ghi
MicrosoftAccount
,abc@def.ghi,MicrosoftAccount8               // See expected output below
9/26/2023 10:39:55 AM
192.168.1.198
abc@def.ghi
MicrosoftAccount
,abc@def.ghi,MicrosoftAccount8               // See expected output below

Expected output: 9/26/2023 10:39:53 AM,192.168.1.198,abc@def.ghi,MicrosoftAccount

I tried taking each variable, and running .ToString() on them while defining a new string. Didn't work. I also tried string csvOutput = $"{Time},{ip},{acc},{domain}";


Solution

  • Thank you to @devlincarnate for steering me in the right direction! Here's what I did:

    • Thread.Sleep(5000); after writing csvOutput to the console, giving me time to hit break all
    • Went to the immediate window to get the value of ip with ? ip and returned "192.168.1.198\r"
    • So, I changed part of my GetIP function from
                    string ipAddress = Regex.Replace(match.Value, @"Source Network Address:\s*", "");
                    return ipAddress;
    

    To:

                    string ipAddress = Regex.Replace(match.Value, @"Source Network Address:\s*", "");
                    string newIP = ipAddress.Replace("\r", "");
                    return newIP;
    

    All is well, StackOverflow to the rescue once again! :)