Passed
Push — master ( 1e7e1e...fa42da )
by Kris
01:37
created

ApiHandler::clearAddress()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 8
rs 10
cc 2
nc 2
nop 1
1
<?php declare(strict_types=1);
2
3
/**
4
 *     _    _                    ___ ____  ____  ____
5
 *    / \  | |__  _   _ ___  ___|_ _|  _ \|  _ \| __ )
6
 *   / _ \ | '_ \| | | / __|/ _ \| || |_) | | | |  _ \
7
 *  / ___ \| |_) | |_| \__ \  __/| ||  __/| |_| | |_) |
8
 * /_/   \_\_.__/ \__,_|___/\___|___|_|   |____/|____/
9
 *
10
 * This file is part of Kristuff\AbsuseIPDB.
11
 *
12
 * (c) Kristuff <[email protected]>
13
 *
14
 * For the full copyright and license information, please view the LICENSE
15
 * file that was distributed with this source code.
16
 *
17
 * @version    0.9.8
18
 * @copyright  2020-2021 Kristuff
19
 */
20
21
namespace Kristuff\AbuseIPDB;
22
23
/**
24
 * Class ApiHandler
25
 * 
26
 * The main class to work with the AbuseIPDB API v2 
27
 */
28
class ApiHandler extends ApiBase
29
{
30
    /**
31
     * Curl helper functions
32
     */
33
    use CurlTrait;
34
35
    /**
36
     * The ips to remove from report messages
37
     * Generally you will add to this list yours ipv4 and ipv6, hostname, domain names
38
     * 
39
     * @access protected
40
     * @var array  
41
     */
42
    protected $selfIps = []; 
43
44
    /**
45
     * Constructor
46
     * 
47
     * @access public
48
     * @param string  $apiKey     The AbuseIPDB api key
49
     * @param array   $myIps      The Ips/domain name you don't want to display in report messages
50
     * 
51
     */
52
    public function __construct(string $apiKey, array $myIps = [])
53
    {
54
        $this->aipdbApiKey = $apiKey;
55
        $this->selfIps = $myIps;
56
    }
57
58
    /**
59
     * Get the current configuration in a indexed array
60
     * 
61
     * @access public
62
     * 
63
     * @return array
64
     */
65
    public function getConfig(): array
66
    {
67
        return array(
68
            'apiKey'  => $this->aipdbApiKey,
69
            'selfIps' => $this->selfIps,
70
        );
71
    }
72
73
    /**
74
     * Performs a 'report' api request
75
     * 
76
     * Result, in json format will be something like this:
77
     *  {
78
     *       "data": {
79
     *         "ipAddress": "127.0.0.1",
80
     *         "abuseConfidenceScore": 52
81
     *       }
82
     *  }
83
     * 
84
     * @access public
85
     * @param string    $ip             The ip to report
86
     * @param string    $categories     The report category(es)
87
     * @param string    $message        The report message
88
     *
89
     * @return ApiResponse
90
     * @throws \RuntimeException
91
     * @throws \InvalidArgumentException
92
     */
93
    public function report(string $ip, string $categories, string $message): ApiResponse
94
    {
95
         // ip must be set
96
        if (empty($ip)){
97
            throw new \InvalidArgumentException('Ip was empty');
98
        }
99
100
        // categories must be set
101
        if (empty($categories)){
102
            throw new \InvalidArgumentException('Categories list was empty');
103
        }
104
105
        // message must be set
106
        if (empty($message)){
107
            throw new \InvalidArgumentException('Report message was empty');
108
        }
109
110
        // validates categories, clean message 
111
        $cats = $this->validateReportCategories($categories);
112
        $msg  = $this->cleanMessage($message);
113
114
        // AbuseIPDB request
115
        return $this->apiRequest(
116
            'report', [
117
                'ip'            => $ip,
118
                'categories'    => $cats,
119
                'comment'       => $msg
120
            ],
121
            'POST'
122
        );
123
    }
124
125
    /**
126
     * Performs a 'bulk-report' api request
127
     * 
128
     * Result, in json format will be something like this:
129
     *   {
130
     *     "data": {
131
     *       "savedReports": 60,
132
     *       "invalidReports": [
133
     *         {
134
     *           "error": "Duplicate IP",
135
     *           "input": "41.188.138.68",
136
     *           "rowNumber": 5
137
     *         },
138
     *         {
139
     *           "error": "Invalid IP",
140
     *           "input": "127.0.foo.bar",
141
     *           "rowNumber": 6
142
     *         },
143
     *         {
144
     *           "error": "Invalid Category",
145
     *           "input": "189.87.146.50",
146
     *           "rowNumber": 8
147
     *         }
148
     *       ]
149
     *     }
150
     *   }
151
     *  
152
     * @access public
153
     * @param string    $filePath       The CSV file path. Could be an absolute or relative path.
154
     *
155
     * @return ApiResponse
156
     * @throws \RuntimeException
157
     * @throws \InvalidArgumentException
158
     */
159
    public function bulkReport(string $filePath): ApiResponse
160
    {
161
        // check file exists
162
        if (!file_exists($filePath) || !is_file($filePath)){
163
            throw new \InvalidArgumentException('The file [' . $filePath . '] does not exist.');
164
        }
165
166
        // check file is readable
167
        if (!is_readable($filePath)){
168
            throw new InvalidPermissionException('The file [' . $filePath . '] is not readable.');
169
        }
170
171
        return $this->apiRequest('bulk-report', [], 'POST', $filePath);
172
    }
173
174
    /**
175
     * Perform a 'clear-address' api request
176
     * 
177
     *  Sample response:
178
     * 
179
     *    {
180
     *      "data": {
181
     *        "numReportsDeleted": 0
182
     *      }
183
     *    }
184
     * 
185
     * @access public
186
     * @param string    $ip             The IP to clear reports
187
     * 
188
     * @return ApiResponse
189
     * @throws \RuntimeException
190
     * @throws \InvalidArgumentException    When ip value was not set. 
191
     */
192
    public function clearAddress(string $ip): ApiResponse
193
    {
194
        // ip must be set
195
        if (empty($ip)){
196
            throw new \InvalidArgumentException('IP argument must be set.');
197
        }
198
199
        return $this->apiRequest('clear-address',  ['ipAddress' => $ip ], "DELETE") ;
200
    }
201
202
    /**
203
     * Perform a 'check' api request
204
     * 
205
     * @access public
206
     * @param string    $ip             The ip to check
207
     * @param int       $maxAgeInDays   Max age in days. Default is 30.
208
     * @param bool      $verbose        True to get the full response (last reports and countryName). Default is false
209
     * 
210
     * @return ApiResponse
211
     * @throws \RuntimeException
212
     * @throws \InvalidArgumentException    when maxAge is less than 1 or greater than 365, or when ip value was not set. 
213
     */
214
    public function check(string $ip, int $maxAgeInDays = 30, bool $verbose = false): ApiResponse
215
    {
216
        // max age must be less or equal to 365
217
        if ($maxAgeInDays > 365 || $maxAgeInDays < 1){
218
            throw new \InvalidArgumentException('maxAgeInDays must be between 1 and 365 (' . $maxAgeInDays . ' was given)');
219
        }
220
221
        // ip must be set
222
        if (empty($ip)){
223
            throw new \InvalidArgumentException('ip argument must be set (empty value given)');
224
        }
225
226
        // minimal data
227
        $data = [
228
            'ipAddress'     => $ip, 
229
            'maxAgeInDays'  => $maxAgeInDays,  
230
        ];
231
232
        // option
233
        if ($verbose){
234
           $data['verbose'] = true;
235
        }
236
237
        return $this->apiRequest('check', $data, 'GET') ;
238
    }
239
240
    /**
241
     * Perform a 'check-block' api request
242
     * 
243
     * 
244
     * Sample json response for 127.0.0.1/24
245
     * 
246
     * {
247
     *    "data": {
248
     *      "networkAddress": "127.0.0.0",
249
     *      "netmask": "255.255.255.0",
250
     *      "minAddress": "127.0.0.1",
251
     *      "maxAddress": "127.0.0.254",
252
     *      "numPossibleHosts": 254,
253
     *      "addressSpaceDesc": "Loopback",
254
     *      "reportedAddress": [
255
     *        {
256
     *          "ipAddress": "127.0.0.1",
257
     *          "numReports": 631,
258
     *          "mostRecentReport": "2019-03-21T16:35:16+00:00",
259
     *          "abuseConfidenceScore": 0,
260
     *          "countryCode": null
261
     *        },
262
     *        {
263
     *          "ipAddress": "127.0.0.2",
264
     *          "numReports": 16,
265
     *          "mostRecentReport": "2019-03-12T20:31:17+00:00",
266
     *          "abuseConfidenceScore": 0,
267
     *          "countryCode": null
268
     *        },
269
     *        ...
270
     *      ]
271
     *    }
272
     *  }
273
     * 
274
     * 
275
     * @access public
276
     * @param string    $network        The network to check
277
     * @param int       $maxAgeInDays   The Max age in days, must 
278
     * 
279
     * @return ApiResponse
280
     * @throws \RuntimeException
281
     * @throws \InvalidArgumentException    when $maxAgeInDays is less than 1 or greater than 365, or when $network value was not set. 
282
     */
283
    public function checkBlock(string $network, int $maxAgeInDays = 30): ApiResponse
284
    {
285
        // max age must be between 1 and 365
286
        if ($maxAgeInDays > 365 || $maxAgeInDays < 1){
287
            throw new \InvalidArgumentException('maxAgeInDays must be between 1 and 365 (' . $maxAgeInDays . ' was given)');
288
        }
289
290
        // ip must be set
291
        if (empty($network)){
292
            throw new \InvalidArgumentException('network argument must be set (empty value given)');
293
        }
294
295
        // minimal data
296
        $data = [
297
            'network'       => $network, 
298
            'maxAgeInDays'  => $maxAgeInDays,  
299
        ];
300
301
        return $this->apiRequest('check-block', $data, 'GET');
302
    }
303
304
    /**
305
     * Perform a 'blacklist' api request
306
     * 
307
     * @access public
308
     * @param int       $limit              The blacklist limit. Default is 10000 (the api default limit) 
309
     * @param bool      $plainText          True to get the response in plaintext list. Default is false
310
     * @param int       $confidenceMinimum  The abuse confidence score minimum (subscribers feature). Default is 100.
311
     *                                      The confidence minimum must be between 25 and 100.
312
     *                                      This parameter is subscriber feature (not honored otherwise).
313
     * 
314
     * @return ApiResponse
315
     * @throws \RuntimeException
316
     * @throws \InvalidArgumentException    When maxAge is not a numeric value, when $limit is less than 1. 
317
     */
318
    public function blacklist(int $limit = 10000, bool $plainText = false, int $confidenceMinimum = 100): ApiResponse
319
    {
320
        if ($limit < 1){
321
            throw new \InvalidArgumentException('limit must be at least 1 (' . $limit . ' was given)');
322
        }
323
324
        // minimal data
325
        $data = [
326
            'confidenceMinimum' => $confidenceMinimum, 
327
            'limit'             => $limit,
328
        ];
329
330
        // plaintext paremeter has no value and must be added only when true 
331
        // (set plaintext=false won't work)
332
        if ($plainText){
333
            $data['plaintext'] = $plainText;
334
        }
335
336
        return $this->apiRequest('blacklist', $data, 'GET');
337
    }
338
  
339
    /**
340
     * Perform a cURL request       
341
     * 
342
     * @access protected
343
     * @param string    $path           The api end path 
344
     * @param array     $data           The request data 
345
     * @param string    $method         The request method. Default is 'GET' 
346
     * @param string    $csvFilePath    The file path for csv file. When not empty, $data parameter is ignored and in place,
347
     *                                  the content of the given file if passed as csv. Default is empty string. 
348
     * 
349
     * @return ApiResponse
350
     * @throws \RuntimeException
351
     */
352
    protected function apiRequest(string $path, array $data, string $method = 'GET', string $csvFilePath = ''): ApiResponse
353
    {
354
        // set api url
355
        $url = $this->aipdbApiEndpoint . $path; 
356
357
        // set the wanted format, JSON (required to prevent having full html page on error)
358
        // and the AbuseIPDB API Key as a header
359
        $headers = [
360
            'Accept: application/json;',
361
            'Key: ' . $this->aipdbApiKey,
362
        ];
363
364
        // open curl connection
365
        $ch = curl_init(); 
366
  
367
        // for csv
368
        if (!empty($csvFilePath)){
369
            $cfile = new \CurlFile($csvFilePath,  'text/csv', 'csv');
370
            //curl file itself return the realpath with prefix of @
371
            $data = array('csv' => $cfile);
372
        }
373
374
        // set the method and data to send
375
        if ($method == 'POST') {
376
            $this->setCurlOption($ch, CURLOPT_POST, true);
0 ignored issues
show
Bug introduced by
It seems like $ch can also be of type CurlHandle; however, parameter $ch of Kristuff\AbuseIPDB\ApiHandler::setCurlOption() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

376
            $this->setCurlOption(/** @scrutinizer ignore-type */ $ch, CURLOPT_POST, true);
Loading history...
377
            $this->setCurlOption($ch, CURLOPT_POSTFIELDS, $data);
378
        
379
        } else {
380
            $this->setCurlOption($ch, CURLOPT_CUSTOMREQUEST, $method);
381
            $url .= '?' . http_build_query($data);
382
        }
383
384
        // set the url to call
385
        $this->setCurlOption($ch, CURLOPT_URL, $url);
386
        $this->setCurlOption($ch, CURLOPT_RETURNTRANSFER, 1); 
387
        $this->setCurlOption($ch, CURLOPT_HTTPHEADER, $headers);
388
    
389
        // execute curl call
390
        $result = curl_exec($ch);
391
    
392
        // close connection
393
        curl_close($ch);
394
  
395
        return new ApiResponse($result !== false ? $result : '');
0 ignored issues
show
Bug introduced by
It seems like $result !== false ? $result : '' can also be of type true; however, parameter $plaintext of Kristuff\AbuseIPDB\ApiResponse::__construct() does only seem to accept null|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

395
        return new ApiResponse(/** @scrutinizer ignore-type */ $result !== false ? $result : '');
Loading history...
396
    }
397
398
    /** 
399
     * Clean message in case it comes from fail2ban <matches>
400
     * Remove backslashes and sensitive information from the report
401
     * @see https://wiki.shaunc.com/wikka.php?wakka=ReportingToAbuseIPDBWithFail2Ban
402
     * 
403
     * @access public
404
     * @param string      $message           The original message 
405
     *  
406
	 * @return string
407
     */
408
    public function cleanMessage(string $message): string
409
    {
410
        // Remove backslashes
411
        $message = str_replace('\\', '', $message);
412
413
        // Remove self ips
414
        foreach ($this->selfIps as $ip){
415
            $message = str_replace($ip, '*', $message);
416
        }
417
418
        // If we're reporting spam, further munge any email addresses in the report
419
        $emailPattern = "/[^@\s]*@[^@\s]*\.[^@\s]*/";
420
        $message = preg_replace($emailPattern, "*", $message);
421
        
422
        // Make sure message is less 1024 chars
423
        return substr($message, 0, 1024);
424
    }
425
}