Need to create a quick script to detect if a credit card number pattern is being written to any file on a Linux server?
Try inotify.
Inotify is a Linux kernel feature that monitors file systems and immediately alerts an attentive application to relevant events, such as a delete, read, write, and even an unmount operation.
The Inotify-tools library provides a pair of command-line utilities to monitor file system activity:
- inotifywait simply blocks to wait for inotify events. You can monitor any set of files and directories and monitor an entire directory tree (a directory, its subdirectories, its sub-subdirectories, and so on). Use inotifywait in shell scripts.
- inotifywatch collects statistics about the watched file system, including how many times each inotify event occurred.
We just need to check two events:
- # IN_CREATE - File/directory created in watched directory
- # IN_MODIFY - File was modified
#!/usr/bin/ruby require 'inotify' require 'find' raise("Specify a directory") if !ARGV[0] directory = ARGV[0] i = Inotify.new t = Thread.new do i.each_event do |event| File.open(directory + "/#{event.name}") do |f| f.grep( /\b(?:\d[ -]*){13,16}\b/) do |line| puts "Detected credit card pattern in directory #{directory}, file #{event.name}\n" end end end end Find.find(directory) do |e| begin i.add_watch(e, Inotify::CREATE | Inotify::MODIFY) rescue puts "Skipping #{directory}: #{$!}" end end t.join
Not too bad for an hour of playing around. It works.
I used the ruby inotify version 0.0.2 from http://raa.ruby-lang.org/project/ruby-inotify/, but if you do that, then you need to fix line 47 - change it to
r = rb_thread_select (fd+1, &rfds, NULL, NULL, NULL);as documented here: http://www.mindbucket.com/2009/02/24/ruby-daemons-verifying-good-behavior/. The code above I modified from the example included with ruby inotify.
- credit card number regex found here: http://www.regular-expressions.info/creditcard.html
- inotify-tools: http://inotify-tools.sourceforge.net/
- ibm inotify tutorial: http://www.ibm.com/developerworks/linux/library/l-ubuntu-inotify/index.html
Trackbacks
Use the following link to trackback from your own site:
http://blog.clearnetsec.com/trackbacks?article_id=1567

You should perform a mod-10(+5) grep on files instead of a simple 16 digit search with/without dashes.
http://en.wikipedia.org/wiki/Luhn_algorithm
This will give you much more accurate results, and a lot less false positives.