Till Brehm
2014-08-25 cb1221013251b4e9cba8e129edc6b8dbd8fd5145
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
<?php
/**
 * PHPIDS
 *
 * Requirements: PHP5, SimpleXML
 *
 * Copyright (c) 2008 PHPIDS group (https://phpids.org)
 *
 * PHPIDS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, version 3 of the License, or
 * (at your option) any later version.
 *
 * PHPIDS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with PHPIDS. If not, see <http://www.gnu.org/licenses/>.
 *
 * PHP version 5.1.6+
 *
 * @category Security
 * @package  PHPIDS
 * @author   Mario Heiderich <mario.heiderich@gmail.com>
 * @author   Christian Matthies <ch0012@gmail.com>
 * @author   Lars Strojny <lars@strojny.net>
 * @license  http://www.gnu.org/licenses/lgpl.html LGPL
 * @link     http://php-ids.org/
 */
namespace IDS\Filter;
 
use IDS\Init;
use IDS\Caching\CacheFactory;
 
/**
 * Filter Storage
 *
 * This class provides various default functions for gathering filter patterns
 * to be used later on by the detection mechanism. You might extend this class
 * to your requirements.
 *
 * @category  Security
 * @package   PHPIDS
 * @author    Christian Matthies <ch0012@gmail.com>
 * @author    Mario Heiderich <mario.heiderich@gmail.com>
 * @author    Lars Strojny <lars@strojny.net>
 * @copyright 2007-2009 The PHPIDS Group
 * @license   http://www.gnu.org/licenses/lgpl.html LGPL
 * @link      http://php-ids.org/
 */
class Storage
{
    /**
     * Filter source file
     *
     * @var string
     */
    protected $source = null;
 
    /**
     * Holds caching settings
     *
     * @var array
     */
    protected $cacheSettings = null;
 
    /**
     * Cache container
     *
     * @var object IDS_Caching wrapper
     */
    protected $cache = null;
 
    /**
     * Filter container
     *
     * @var array
     */
    protected $filterSet = array();
 
    /**
     * Constructor
     *
     * Loads filters based on provided IDS_Init settings.
     *
     * @param object $init IDS_Init instance
     *
     * @throws \InvalidArgumentException if unsupported filter type is given
     * @return void
     */
    final public function __construct(Init $init)
    {
        if ($init->config) {
 
            $caching      = isset($init->config['Caching']['caching']) ? $init->config['Caching']['caching'] : 'none';
 
            $type         = $init->config['General']['filter_type'];
            $this->source = $init->getBasePath(). $init->config['General']['filter_path'];
 
            if ($caching && $caching !== 'none') {
                $this->cacheSettings = $init->config['Caching'];
                $this->cache = CacheFactory::factory($init, 'storage');
            }
 
            switch ($type) {
                case 'xml':
                    return $this->getFilterFromXML();
                case 'json':
                    return $this->getFilterFromJson();
                default:
                    throw new \InvalidArgumentException('Unsupported filter type.');
            }
        }
    }
 
    /**
     * Sets the filter array
     *
     * @param array $filterSet array containing multiple IDS_Filter instances
     *
     * @return object $this
     */
    final public function setFilterSet($filterSet)
    {
        foreach ($filterSet as $filter) {
            $this->addFilter($filter);
        }
 
        return $this;
    }
 
    /**
     * Returns registered filters
     *
     * @return array
     */
    final public function getFilterSet()
    {
        return $this->filterSet;
    }
 
    /**
     * Adds a filter
     *
     * @param object $filter IDS_Filter instance
     *
     * @return object $this
     */
    final public function addFilter(\IDS\Filter $filter)
    {
        $this->filterSet[] = $filter;
 
        return $this;
    }
 
    /**
     * Checks if any filters are cached
     *
     * @return mixed $filters cached filters or false
     */
    private function isCached()
    {
        $filters = false;
 
        if ($this->cacheSettings) {
            if ($this->cache) {
                $filters = $this->cache->getCache();
            }
        }
 
        return $filters;
    }
 
    /**
     * Loads filters from XML using SimpleXML
     *
     * This function parses the provided source file and stores the result.
     * If caching mode is enabled the result will be cached to increase
     * the performance.
     *
     * @throws \InvalidArgumentException if source file doesn't exist
     * @throws \RuntimeException if problems with fetching the XML data occur
     * @return object    $this
     */
    public function getFilterFromXML()
    {
        if (extension_loaded('SimpleXML')) {
 
            /*
             * See if filters are already available in the cache
             */
            $filters = $this->isCached();
 
            /*
             * If they aren't, parse the source file
             */
            if (!$filters) {
 
                if (!file_exists($this->source)) {
                    throw new \InvalidArgumentException(
                        sprintf('Invalid config: %s doesn\'t exist.', $this->source)
                    );
                }
 
                if (LIBXML_VERSION >= 20621) {
                    $filters = simplexml_load_file($this->source, null, LIBXML_COMPACT);
                } else {
                    $filters = simplexml_load_file($this->source);
                }
            }
 
            /*
             * In case we still don't have any filters loaded and exception
             * will be thrown
             */
            if (empty($filters)) {
                throw new \RuntimeException(
                    'XML data could not be loaded.' .
                    ' Make sure you specified the correct path.'
                );
            }
 
            /*
             * Now the storage will be filled with IDS_Filter objects
             */
            $nocache = $filters instanceof \SimpleXMLElement;
            
            if ($nocache)
            {
                // build filters and cache them for re-use on next run
                $data    = array();
                $filters = $filters->filter;
                
                foreach ($filters as $filter) {
                    $id          = (string) $filter->id;
                    $rule        = (string) $filter->rule;
                    $impact      = (string) $filter->impact;
                    $tags        = array_values((array) $filter->tags);
                    $description = (string) $filter->description;
                
                    $this->addFilter(
                            new \IDS\Filter(
                                    $id,
                                    $rule,
                                    $description,
                                    (array) $tags[0],
                                    (int) $impact
                            )
                    );
                
                    $data[] = array(
                            'id'          => $id,
                            'rule'        => $rule,
                            'impact'      => $impact,
                            'tags'        => $tags,
                            'description' => $description
                    );
                }
                
                /*
                 * If caching is enabled, the fetched data will be cached
                */
                if ($this->cacheSettings) {
                    $this->cache->setCache($data);
                }
                
            } else {
            
                // build filters from cached content
                $this->addFiltersFromArray($filters);
            }
 
            return $this;
        }
 
        throw new \RuntimeException('SimpleXML is not loaded.');
    }
 
    /**
     * Loads filters from Json file using ext/Json
     *
     * This function parses the provided source file and stores the result.
     * If caching mode is enabled the result will be cached to increase
     * the performance.
     *
     * @throws \RuntimeException if problems with fetching the JSON data occur
     * @return object    $this
     */
    public function getFilterFromJson()
    {
 
        if (extension_loaded('Json')) {
 
            /*
             * See if filters are already available in the cache
             */
            $filters = $this->isCached();
 
            /*
             * If they aren't, parse the source file
             */
            if (!$filters) {
                if (!file_exists($this->source)) {
                    throw new \InvalidArgumentException(
                        sprintf('Invalid config: %s doesn\'t exist.', $this->source)
                    );
                }
                $filters = json_decode(file_get_contents($this->source));
            }
 
            if (!$filters) {
                throw new \RuntimeException('JSON data could not be loaded. Make sure you specified the correct path.');
            }
 
            /*
             * Now the storage will be filled with IDS_Filter objects
             */
            $nocache = !is_array($filters);
            
            if ($nocache) {
                
                // build filters and cache them for re-use on next run
                $data    = array();
                $filters = $filters->filters->filter;
                
                foreach ($filters as $filter) {
 
                    $id          = (string) $filter->id;
                    $rule        = (string) $filter->rule;
                    $impact      = (string) $filter->impact;
                    $tags        = array_values((array) $filter->tags);
                    $description = (string) $filter->description;
    
                    $this->addFilter(
                        new \IDS\Filter(
                            $id,
                            $rule,
                            $description,
                            (array) $tags[0],
                            (int) $impact
                        )
                    );
    
                    $data[] = array(
                        'id'          => $id,
                        'rule'        => $rule,
                        'impact'      => $impact,
                        'tags'        => $tags,
                        'description' => $description
                    );
                }
    
                /*
                 * If caching is enabled, the fetched data will be cached
                 */
                if ($this->cacheSettings) {
                    $this->cache->setCache($data);
                }
                
            } else {
                
                // build filters from cached content
                $this->addFiltersFromArray($filters);
            }
 
            return $this;
        }
 
        throw new \RuntimeException('json extension is not loaded.');
    }
    
    /**
     * This functions adds an array of filters to the IDS_Storage object.
     * Each entry within the array is expected to be an simple array containing all parts of the filter.
     * 
     * @param array $filters
     */
    private function addFiltersFromArray(array $filters)
    {
        foreach ($filters as $filter) {
        
            $id          = $filter['id'];
            $rule        = $filter['rule'];
            $impact      = $filter['impact'];
            $tags        = $filter['tags'];
            $description = $filter['description'];
        
            $this->addFilter(
                new \IDS\Filter(
                    $id,
                    $rule,
                    $description,
                    (array) $tags[0],
                    (int) $impact
                )
            );
        }
    }
}