Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Log USB Events to Splunk Or Any syslog Server

0.00/5 (No votes)
13 Jul 2016 1  
Creating a Windows service to monitor usb events with splunk

Introduction

This is a project essay of a usb event logger to splunk instance, I have been introduced lately to SIEM and am enjoying working on some projects and this is one of them.

In order to run the solution, unzip both packages1 and packages2 inside LoggerForDirectories\packages.

Background

Use it if you want to monitor the activities on an organisation for usb copy events, it's a Windows service project written in C# with a setup project that logs the copied file along with the IP address, session domain, computer name, current CPU usage, available ram.

Using the Code

This is the listener using System.IO.

FileSystemWatcher watcher;
Stopwatch s = new Stopwatch();
var formatter = new MessageTemplateTextFormatter(
   "{Timestamp:HH:mm} [{Level}] ({ThreadId}) {Message}{NewLine}{Exception}",
   formatProvider: null);

a.Clear();
s.Start();
while (s.Elapsed < TimeSpan.FromSeconds(40))
{
    var drives = DriveInfo.GetDrives()
       .Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);
    if (drives != null)
    {
        foreach (var item in drives)
        {
            watcher = new FileSystemWatcher();
            watcher.Path = item.RootDirectory.ToString();
            watcher.NotifyFilter = NotifyFilters.LastAccess
                                    | NotifyFilters.LastWrite
                                    | NotifyFilters.FileName
                                    | NotifyFilters.DirectoryName;
            watcher.Filter = "*.*";
            watcher.IncludeSubdirectories = true;
            watcher.Created += new FileSystemEventHandler(OnCreate);
            watcher.EnableRaisingEvents = true;
        }
    }

OnCreate is called every time a copy event is detected.

And because the copy events is composed of many events I had to filter events based on files.

public void OnCreate(object source, FileSystemEventArgs e)
    {
        if((a.Capacity-10) != a.Count)
        {
            if (a.Any())
            {
                if (e.Name != null)
                {
                        if (a.Contains(e.Name.ToString()))
                        {  /*Do nothing*/ }
                        else
                        { a.Add(e.Name.ToString()); }
                }
            }
            else
            {
                if (e.Name != null)
                {
                    a.Add(e.Name.ToString());
                }
            }
        }
    }

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here