Mahalanobis.pm untested

filter: Statementstmt 0.0% 0 / 181 Branchbran 0.0% 0 / 16 Conditioncond 0.0% 0 / 16 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 15 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 245 CC 9 SCAR 26.5
CC
9
Cov
0%
test
42.0
add
12.0
load
6.0
CRAP 14.1
1 package IDS::Algorithm::Mahalanobis;
2 use base qw(IDS::Algorithm);
3 $IDS::Algorithm::Mahalanobis::VERSION = "1.0";
4  
5 =head1 NAME
6  
7 Mahalanobis - An IDS algorithm implementing an approximation of the IDS
8 by Wang and Stolfo (See the L</SEE ALSO> section for the reference).
9  
10 =head1 SYNOPSIS
11  
12 A usage synopsis would go here. Since it is not here, read on.
13  
14 =head1 DESCRIPTION
15  
16 DIFFERENCE: Wang and Stolfo correlated packet length with character
17 frequencies. Since my data does not have original packets, I am
18 applying their method to the whole request (which often comes in a
19 single packet).
20  
21 See IDS::Algorithm.pm docs for any functions not described here
22  
23 ASSUMPTION: characters are 0..255; unicode (etc) not yet supported.
24  
25 =cut
26  
27 use strict;
28 use warnings;
29 use Carp qw(cluck carp confess);
30 use IDS::Utils qw(to_fh);
31 use bytes;
32  
33 =head2 Parameters
34  
35 Parameters are:
36  
37 =over
38  
39 =item WS_verbose
40  
41 Turn on extra messages as the algorithm runs.
42  
43 =item alpha
44  
45 The value of the constant alpha in the simplified Mahalanobis distance.
46 See page 7 in the Wang and Stolfo paper.
47  
48 =item ids_state
49  
50 The file to load the saved state from.
51  
52 =back
53  
54 =head2 Methods
55  
56 Most of these methods are required by L<IDS::Algorithm>; see
57 documentation there for additional information.
58  
59 =over
60  
61 =item default_parameters()
62  
63 Sets all of the default values for the parameters. Normally called by
64 new() or one of its descendents.
65  
66 =item param_options()
67  
68 Provides the parameters to use with Getopt::Long.
69  
70 =back
71  
72 =cut
73  
74 sub default_parameters {
75 my $self = shift;
76  
77 %{$self->{"params"}} = (
78 "verbose" => 0,
79 "alpha" => 0.001, # guessed value; the whole alpha concept in
80 # the paper seems to me to be a kludge
81 "state_file" => 0,
82 );
83 }
84  
85 sub param_options {
86 my $self = shift;
87  
88 return (
89 "WS_verbose=i" => \${$self->{"params"}}{"verbose"},
90 "alpha=f" => \${$self->{"params"}}{"alpha"},
91 "ids_state=s" => \${$self->{"params"}}{"state_file"},
92 );
93 }
94  
95 =over
96  
97 =item initialize()
98  
99 Called by Super::new(). We set up the data structures here for storing
100 the mean, mean**2, and number of observations for each character.
101  
102 =back
103  
104 =cut
105  
106 sub initialize {
107 my $self = shift;
108  
109 map { ${$self->{"observations"}}[$_] = 0 } 0..255;
110 map { ${$self->{"mean"}}[$_] = 0 } 0..255;
111 map { ${$self->{"mean2"}}[$_] = 0 } 0..255;
112 }
113  
114 =over
115  
116 =item save(fn)
117  
118 Save the current state to the file or filehandle provided. find_fname
119 (in IDS::Algorithm) handles figuring out the destination.
120  
121 =back
122  
123 =cut
124  
125 sub save {
126 my $self = shift;
127 my $fname = $self->find_fname(shift);
128 defined($fname) && $fname or
129 confess *save{PACKAGE} . "::save missing filename";
130 my $fh = to_fh($fname, ">");
131  
132 my ($i);
133  
134 for ($i=0; $i<256; $i++) {
135 print $fh "$i; ", ${$self->{"observations"}}[$i], "; ",
136 ${$self->{"mean"}}[$i], "; ",
137 ${$self->{"mean2"}}[$i], "\n";
138 }
139 }
140  
141 =over
142  
143 =item load(fn)
144  
145 Load the current state from the file or filehandle provided. find_fname
146 (in IDS::Algorithm) handles figuring out the source.
147  
148 =back
149  
150 =cut
151  
152 sub load {
153 my $self = shift;
154 my $fname = $self->find_fname(shift);
155 $fname or
156 confess *load{PACKAGE} . "::load missing filename";
157 my $fh = to_fh($fname, "<");
158  
159 my $verbose = ${$self->{"params"}}{"verbose"};
160  
161 my ($n, $i, $mean, $mean2, $obs);
162  
163 $n = 0;
164 while (<$fh>) {
165 chomp;
166 ($i, $obs, $mean, $mean2) = split(/; /);
167 ${$self->{"observations"}}[$i] = $obs;
168 ${$self->{"mean"}}[$i] = $mean;
169 ${$self->{"mean2"}}[$i] = $mean2;
170 $n++;
171 }
172 warn "Duplicate data loaded from $fname"
173 if $n != scalar(@{$self->{"mean"}});
174 }
175  
176 =over
177  
178 =item add(tokenref, string, n)
179  
180 Update the character frequency statistics. For calculating the
181 Mahalanobis distance, these stats are the mean and the mean**2, as well
182 as a count of the number of observations. The array is indexed by
183 ord(chr) to improve performance.
184  
185 =begin latex
186  
187 The mean and $\mbox{mean}^2$ are for character frequencies. This means that
188  
189 \[
190 1 = \sum_c f(c)
191 \]
192 for the freqency $f$ over all characters $c$.
193  
194 We keep the mean current without having to remember all prior values (which
195 cause us to run out of memory for large training sets) by using the observation
196 by Knuth that when we have a new $x_{N+1}$ to add in,
197 \[
198 \overline{x}' = \overline{x} + \frac{x_{N+1} - \overline{x}}{N+1}
199 \]
200  
201 By storing the mean, $\mbox{mean}^2$, and number of observations, we can support
202 the incremental learning as described in Section 3.3 of the Wang and
203 Stolfo paper.
204  
205 =end latex
206  
207 This function only uses the string version of the data. The tokens and
208 instance are ignored.
209  
210 =back
211  
212 =cut
213  
214 sub add {
215 my $self = shift;
216 my $tref = shift; # not used
217 my $data = shift or
218 confess "bug: missing data to ", *add{PACKAGE} . "::add";
219 my $verbose = ${$self->{"params"}}{"verbose"};
220  
221 my ($i, @freqs);
222  
223 print "Data: '$data'\n" if $verbose > 1;
224  
225 @freqs = ();
226 $self->freq_calc($data, \@freqs);
227  
228 if ($verbose) {
229 print "Freqs:\n";
230 map { print "$_: $freqs[$_]\n"; } 0 .. 255;
231 }
232  
233 for ($i = 0; $i<256; $i++) {
234 ${$self->{"observations"}}[$i]++;
235 ${$self->{"mean"}}[$i] += ($freqs[$i] - ${$self->{"mean"}}[$i]) /
236 ${$self->{"observations"}}[$i];
237 ${$self->{"mean2"}}[$i] += ($freqs[$i]**2 - ${$self->{"mean2"}}[$i]) /
238 ${$self->{"observations"}}[$i];
239 }
240  
241 # wasteful during training, but required for adaptive testing
242 $self->calc_stddev;
243 }
244  
245 =over
246  
247 =item freq_calc(data, freqref)
248  
249 Calculate character frequencies in the data string provided. The result
250 is returned in the array referenced by freqref.
251  
252 =back
253  
254 =cut
255  
256 sub freq_calc {
257 my $self = shift;
258 my $data = shift or
259 confess "bug: missing data to ", *freq_calc{PACKAGE} . "::add";
260 my $freqref = shift or
261 confess "bug: missing freqref to ", *freq_calc{PACKAGE} . "::add";
262  
263 my ($i, $byte, $chr, $length);
264  
265 $length = length($data);
266  
267 # init
268 map { ${$freqref}[$_] = 0 } 0..255;
269  
270 # count
271 map { ${$freqref}[ord($_)]++; } split(//, $data);
272
273 # scale
274 map { ${$freqref}[$_] /= $length } 0..255;
275 }
276  
277 =over
278  
279 =item test(tokenref, string, n)
280  
281 Test the string to see how similar its character distribution is to the
282 distribution we have learned. This function only uses the string version
283 of the data. The tokens and instance are ignored.
284  
285 =begin latex
286  
287 \providecommand{\abs}[1]{\mid #1 \mid}
288  
289 From training, we have $n_c$ is the number of observations for a character
290 $c$, $y_{c,i}$ is the frequency with which character $c$ in the $i$th
291 observation occurred in the training data,
292 $ \overline{y_c} = \sum_{i = 0}^{n_c} \frac{y_{c,i}}{n_c}$, and
293 $ \overline{y_c^2} = \sum_{i = 0}^{n_c} \frac{y_{c,i}^2}{n_c}$.
294 We have a $\overline{y}$ and $\overline{y^2}$ for each character.
295  
296 Given a set of character frequencies $X$ for a test item and
297 $\sigma_c = \sqrt{\overline{y_c^2} - \overline{y_c}^2}$, then
298 the simplified Mahalanobis distance per Wang and Stolfo is:
299 \[
300 d = \sum_{c} \frac{\abs{x_c - \overline{y_c}}}{\sigma_c + \alpha}
301 \]
302 where $c$ is an index across all characters, and $x_c \in X$.
303 Note that $\alpha$ is the constant from the Wang and Stolfo paper,
304 and in this code, it is the parameter \texttt{alpha}.
305  
306 We differ from Wang and Stolfo in mapping the distance $d \in
307 [0,\infty)$ into $[0,1]$ by producing a result $r \in [0,1] $.
308 \[
309 r = \left\{ \begin{array}{ll}
310 1 & \mbox{if $d \le 1$}\\[0.5em]
311 \frac{1}{\log{(d - 1 + e)}} & \mbox{if $d > 1$}\\
312 \end{array}
313 \right.
314 \]
315 $e$ is the base of the natural logarithms. This (or a similar) mapping
316 is required because IDS::Algorithm requires that the result of testing
317 be in $[0,1]$. The mapping for values $\le 1$ is justified because the
318 larger the distance, the more abnormal the data item. Experience shows
319 that most normal requests have a distance $> 1$.
320  
321 =end latex
322  
323 =back
324  
325 =cut
326  
327 sub test {
328 my $self = shift;
329 my $tref = shift; # not used
330 my $data = shift;
331  
332 my (@freq, $dist, $i, $chr, $stddev, $result, $d, $e);
333 my $alpha = ${$self->{"params"}}{"alpha"};
334 my $verbose = ${$self->{"params"}}{"verbose"};
335  
336 exists($self->{"stddev"}) or $self->calc_stddev;
337  
338 print "data '$data'\n" if $verbose;
339  
340 # calculate the frequency distribution for this datum
341 @freq = ();
342 $self->freq_calc($data, \@freq);
343  
344 print "Freq: ", join(", ", @freq), "\n" if $verbose > 1;
345  
346 # compare with simplified Mahalanobis distance
347 $dist = 0;
348 for ($i=0; $i<256; $i++) {
349 $d = abs($freq[$i] - ${$self->{"mean"}}[$i] ) / (${$self->{"stddev"}}[$i] + $alpha);
350 $dist += $d;
351 print "stddev[$i] = ", ${$self->{"stddev"}}[$i], ", dist $d\n" if $verbose > 1;
352 }
353 # distance is potentially (nearly) unbounded. Since we need it to
354 # be in [0,1] with 1 meaning close, we use the following function:
355 $e = exp(1);
356 $result = $dist <= 1 ? 1 : (1.0 / log($dist + $e - 1));
357 print "dist $dist result $result\n", if $verbose;
358 return $result;
359 }
360  
361 sub calc_stddev {
362 my $self = shift;
363 my ($i);
364  
365 $self->{"stddev"}= [];
366 for ($i=0; $i<256; $i++) {
367 ${$self->{"stddev"}}[$i] = sqrt(abs(${$self->{"mean2"}}[$i] - ${$self->{"mean"}}[$i]**2));
368 }
369 }
370  
371 =head1 AUTHOR INFORMATION
372  
373 Copyright 2005-2007, Kenneth Ingham. All rights reserved.
374  
375 This library is free software; you can redistribute it and/or modify
376 it under the same terms as Perl itself.
377  
378 Address bug reports and comments to: ids_test at i-pi.com. When
379 sending bug reports, please provide the versions of IDS::Test.pm,
380 IDS::Algorithm.pm, IDS::DataSource.pm, the version of Perl, and the
381 name and version of the operating system you are using. Since Kenneth
382 is a PhD student, the speed of the response depends on how the research
383 is proceeding.
384  
385 =head1 BUGS
386  
387 Please report them.
388  
389 =head1 SEE ALSO
390  
391 L<IDS::Test>, L<IDS::DataSource>, L<IDS::Algorithm>
392  
393 "Anomalous Payload-based Network Intrusion Detection" by Ke Wang and
394 Salvatore J. Stolfo, pages 203--222 in Recent Advances in Intrusion
395 Detection: 7th International Symposium, RAID 2004, Sophia Antipolis,
396 France, September 15-17, 2004. Proceedings. Published as Lecture Notes
397 in Computer Science 3224, ISBN 3-540-23123-4.
398  
399 =cut
400  
401 1;