forked from lucanos/Tripwire
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtripwire.php
472 lines (389 loc) · 13.5 KB
/
tripwire.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
<?php
/*
* Tripwire
* Luke Stevenson <www.lucanos.com>
* and Daniel Walker <polyesterhat@gmail.com>
*
* This is a PHP script which will scan files within a directory (including
* sub-directories), calculate their MD5 Hashes and then compare them against
* a log of the results from the previous execution to determine any files
* which have been added, deleted or modified during that period.
*
* Within the Configuration Settings, exclusions can be set for any files/folders
* which should not be checked.
*
* For best results, this file should be triggered by a cron job at regular intervals.
* Also, be sure to add your email address to the Configuration Settings to ensure
* that you recieve the notifications.
*
* For the email template, I'm using:
* leemunroe.github.io/html-email-template/email.html
* Twig is used to compile the template
*/
class Tripwire
{
protected $config;
/**
* a place to keep the messages before they all get echoed
*
* @var array
*/
protected $messages_buffer = array();
/**
* a place to keep strings
* regarding the files being processed
* before outputting for user
* this is for display, not function
*
* @var array
*/
protected $files_buffer = array();
/**
* arrays to house comparison results
* @var array
*/
protected $files_new = array();
protected $files_modified = array();
protected $files_deleted = array();
/**
* flag to track whether there are differences between
* this run and the last run
* @var boolean
*/
protected $there_were_differences = FALSE;
/**
* a place to store md5s of files
* @var array
*/
protected $listing_now = array();
protected $listing_last = array();
/**
* html for the report
* built out in method: prepare_report()
* @var string
*/
protected $report = '';
public function __construct()
{
$this->load_settings('tripwire_config.ini');
// make a debug shortcut
$this->DEBUG = $this->config['debug'];
// start checking the supplied dirs
$this->check_paths();
$this->run_comparisons();
$this->save_md5_file();
$this->prepare_report();
}
/**
* this is the real meat and potatoes of Tripwire
* 1. first get paths from config file
* 2. traverse them and check for differences in the
* date modified to what we have on file
* 3.
*
* @since 2014-03-17
* @author Daniel.Walker <polyesterhat@gmail.com>
* @return void
*/
protected function check_paths()
{
$paths = $this->config['paths'];
// start a clean copy of the listing
// this is updated in check_path()
$this->listing_now = array();
if (!is_array($paths))
{
$this->add_message('In config, paths should be an array');
$paths = (array) $paths;
}
// If no Directory Specified, Default to the Root
// of the Site the script is executed under
if (empty($paths))
{
$this->add_message('Paths is empty in the config - it shouldn\'t be');
$paths = (array) $_SERVER['DOCUMENT_ROOT'];
}
foreach ($paths as $index => $path)
{
// If last character is a slash, strip it off the end
if( substr( $path , -1 ) == '/' )
{
$path = substr( $path , 0 , -1 );
}
// If the supplied variable is not a Directory, terminate
if (!is_dir($path))
{
$this->add_message("Directory '{$path}' does not exist.");
// go to next path
continue;
}
$this->check_path($path);
}
}
/**
* check just one path from the config file
* this is a recursive function
*
* @since 2014-03-17
* @author Luke Stevenson <www.lucanos.com>
* @author Daniel.Walker <polyesterhat@gmail.com>
* @param string $path the path to the directory
* @return void
*/
protected function check_path($path = '')
{
$this->add_message("Checking directory '{$path}'");
$d = dir($path);
// Loop through the files
while (FALSE !== ($entry = $d->read()))
{
// Full Entry (including Directory)
$entry_full = $path . '/' . $entry;
// Symbolic Link - Excluded
if (is_link($entry))
{
// add symlink to buffer
$this->add_file($path, $entry . ' <- symlink');
continue;
}
// determine whether this file should be excluded
// based on file name or extension
$exclude_file = in_array($entry , $this->config['files']) OR in_array($entry_full , $this->config['files']);
$exclude_extension = in_array(pathinfo($entry , PATHINFO_EXTENSION) , $this->config['extensions']);
// Excluded File/Folder
if ($exclude_file OR $exclude_extension)
{
$this->add_file($path, $entry . ' <- excluded');
continue;
}
if (is_dir($entry_full))
{
// label this file for the output listing
$this->add_file($path, $entry . ' <- directory');
// Recurse
$this->check_path($entry_full);
}
else
{
// a file
// check date
// if different date check md5
$md5 = @md5_file( $entry_full );
$this->add_file($path, $entry);
if (!$md5)
{
$this->add_message("Could not md5: {$entry_full}");
file_put_contents($this->config['unreadable_list'] , "{$entry_full} - Unreadable\n" , FILE_APPEND);
}
else
{
$this->listing_now[$entry_full] = $md5;
}
}
}
$d->close();
}
/**
* opens the file used last time and
* compares line by line with the latest results from check paths
*
* @since 2014-03-18
* @author Luke Stevenson <www.lucanos.com>
* @author Daniel.Walker <polyesterhat@gmail.com>
* @todo make the comparisons faster
* @return void
*/
protected function run_comparisons()
{
$this->listing_last = array();
if (file_exists($this->config['md5_file']))
{
$temp = file_get_contents($this->config['md5_file']);
$this->listing_last = (array)json_decode($temp);
}
// kept Luke's old logic here
// there are probably faster ways to do this
// Perform Comparisons
$keys_now = array_keys($this->listing_now);
$keys_last = array_keys($this->listing_last);
// New Files = Files in $now, but not in $last
$this->files_new = array_diff($keys_now, $keys_last);
// Deleted Files = Files in $last, but not in $now
$this->files_deleted = array_diff($keys_last, $keys_now);
// Changed Files = Files in $last and $now, but with Different MD5 Hashes
$this->files_modified = array_diff_assoc(
array_intersect_key($this->listing_last, $this->listing_now),
array_intersect_key($this->listing_now, $this->listing_last)
);
// this line must have parenthesis
$this->there_were_differences = (count($this->files_new) OR count($this->files_modified) OR count($this->files_deleted));
if($this->DEBUG) {
echo 'Number of files_new: ' . count($this->files_new) . "\n";
echo 'Number of files_modified: ' . count($this->files_modified) . "\n";
echo 'Number of files_delete: ' . count($this->files_deleted). "\n";
echo ($this->there_were_differences ? 'There were differences' : 'There were not any differences') . "\n";
print_r($this->files_modified);
}
}
/**
* simply save the new listing into the file
*
* @since 2014-03-18
* @author Daniel.Walker <polyesterhat@gmail.com>
* @return void
*/
protected function save_md5_file()
{
// write the file if there wasn't already a file
// or there were differences
if (empty($this->listing_last) OR $this->there_were_differences)
{
if ($this->DEBUG) {
echo "Saving MD5 file \n";
}
// json encode is slightly faster than serialize since it
// doesn't have to insert string lengths
file_put_contents($this->config['md5_file'], json_encode($this->listing_now));
}
}
/**
* generate all html to send to the user
* regarding the findings of the tripwire run
* this will include new files, modifications, deletions
* and the time
*
* @since 2014-03-18
* @author Daniel.Walker <polyesterhat@gmail.com>
* @author Luke Stevenson <www.lucanos.com>
* @return void
*/
protected function prepare_report()
{
$vars = array(
'AF' => $this->files_new,
'MF' => $this->files_modified,
'DF' => $this->files_deleted,
'total' => 0,
'title' => 'Tripwire - no changes',
'heading' => 'Tripwire has not detected any changes',
);
// make email subject
$subject = str_replace( '{{X}}' , count( $this->files_new ) , $this->config['subject'] );
// If there was a Filelist from the last run to
// compare against, and changes have occurred then,
// Prepare Report
if (empty($this->listing_last))
{
// First Run
$this->add_message('There were no previous listings - this was a first run.');
$vars['total'] = count($this->files_new);
$vars['title'] = 'Tripwire - First Run';
$vars['heading'] = 'Tripwire has made it\'s first pass of your files';
}
elseif ($this->there_were_differences)
{
$this->add_message('There were previous listings and there are differences.');
// Changes Detected
$vars['total'] = count($this->files_new) + count($this->files_deleted) + count($this->files_modified);
$vars['title'] = 'Tripwire - Changes Detected';
$vars['heading'] = 'Tripwire has detected a number of changes:';
}
else
{
$this->add_message('There were no differences.');
// nothing to do...
return;
}
// Compile the email template with Twig
require_once 'include/twig/lib/Twig/Autoloader.php';
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem('views');
$twig = new Twig_Environment($loader);
$template = $twig->loadTemplate('email_template.html');
$body = $template->render($vars);
$this->email_user($subject, $body);
if ($this->DEBUG)
{
echo $body;
echo "\n\n";
echo "Message Buffer:";
echo "\n\n";
print_r($this->messages_buffer);
}
}
/**
* to maintain a buffer of messages
* this method will simply push a new string onto
* the messages array
*
* @since 2014-03-17
* @author Daniel.Walker <polyesterhat@gmail.com>
* @param string $message a new message
* @return void
*/
protected function add_message($message)
{
array_push($this->messages_buffer, $message);
}
/**
* to keep a running list of
* files
*
* @since 2014-03-18
* @author Daniel.Walker <polyesterhat@gmail.com>
* @param string $path the path to use
* @param string $file a new file
* @return void
*/
protected function add_file($path ='', $file = '')
{
if (!array_key_exists($path, $this->files_buffer))
{
$this->files_buffer[$path] = array();
}
array_push($this->files_buffer[$path], $file);
}
/**
* just send an email using the config settings
* this $this->config
*
* @since 2014-03-17
* @author Daniel.Walker <polyesterhat@gmail.com>
* @param string $subject of the email
* @param string $body of the email
* @return boolean
*/
protected function email_user($subject, $body)
{
$result = FALSE;
if ($this->config['send_email'])
{
$headers = "MIME-Version: 1.0\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Disposition: inline";
// Prepare the recipients
$to = implode(', ' , $this->config['to']);
// Send it
$result = mail(
$to,
$subject,
$body,
$headers
);
}
return $result;
}
/**
* find config file and parse using built in in parser
* load the settings into class variable
*
* @since 2014-03-17
* @author Daniel.Walker <polyesterhat@gmail.com>
* @param string $file_name the name of the config file for tripwire
* @return void
*/
protected function load_settings($file_name)
{
$this->config = parse_ini_file($file_name);
}
}
// Start the Instance
new Tripwire();