Subversion Repositories vnag

Rev

Rev 2 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
4 daniel-mar 1
<?php /* <ViaThinkSoftSignature>
2
akRkqMquPkfxpwy3lnAlcQ1qVAUdTJBHZNOG+o13yNrgyHRqadEskkSxmItifQzCE
3
NCOBCXf4QUqo8xtFT0uxyzv/R0ZrB8H0dF+2LslQ6eYj+IrPgbiQoFY4FoxAS24ZC
4
pH8v+GYD4lq/UmU+c7eggeNGtv9ZYkQaz2ZUS4hT0nrP7qO2quF1dpm+8dsB5pKj9
5
iY/ujHP9iEWzn3d8BhgkaSed+GBkqurqY1lc+2l2tCsT1ZPEOR41uWLeSya1WGwEA
6
Wy6/2ih4x5dG3lsNgKRcJyDdcDYw+mhXq3vxPeqcMWFiplq6cF9XxxY3NHOk6HcIO
7
7qR52jOkU7Kvy31CPso0C12h0xFgo9fvj3BJUJWZvSw00I1SqRMJn2o2+KtVCWSfM
8
GJ5brgRCMNdHDiCCbkFaRtElsv1q0ewTLotrRohZxJpRwoOK7dEDsR+V0hhOfYzZ/
9
zRaNqG/LPIqSeBsZhA7km8IpZlwSbUom2PKKWdL8YBwSdqjtgM9Z3B0TQDkhSvU17
10
mICuIgjQfeMwxyaUHFYvA+yqofcy9g2GQHTj15B2s39gnW9pKgVK35lRKOCoQ6rYp
11
tBfHUXH02VjSLqcFgoV7cOamBftfC55+RRpvfZURQUvgWbBIYtQ3HDeze775vdbr8
12
5HL6ADKA2Rdd/HSG1E+GMuXUokcWOxg80ih+HnnrGqfFcohmfs1qy6ZZtYQBnJszF
13
ZATsMF+AdztxJahbVf7lrM36Zl22kXpkz8lX2lp382bBvBBYwWUaf3j+UBLWHoFfn
14
Ojc1BnxECvuAIlgiD7mRIYIx/WQxlF1MU3ByrVuIzfOR2j3Xy+Iv0ettCVNSQdCnN
15
+B2WV/Hqtj1qLsXgZcxdYatlqDKLytyk2bSyX/WLnRj5xnjWEGDPAoblIjknHz9Bi
16
DWRYNdSqZ1skixKIZTbynhqWrG9dKSPvDfdXpvguRB6tSWK3/70aOfWf3TnmTBHXS
17
3/NvGzV+3WtZfujCXTxBSCuV6ReTIuqUbKoVT/rCX5sMNMDuElsbHjg031VKNyqjx
18
3L9F/fMopue8G1vu2QCsjiGU59EwtakcrobMyopZwV8eqe3/By7SjVVL11MquTEV+
19
qIWV3gNtlFFroCO+ztVdKj1+FMsZtZfDhHkxeHG/sx64CW7B1mw5pPCr3FriDScWy
20
3XfD29ah1Tx0/6AsHMViLNCMK65bP5ttp7BBb2vnGX68vc9qMNCBCIhR9lOwPobtz
21
B4MpVAHX6dEn/3XVhkoW7O7jcz3CkgZOZJv8ymKE4SUw7s/ns6w/m4wyujDdp9343
22
WuALsxrxXMswqiTx7v1hmeJccT9dRMJYGQ7DRnB8Z1K+px6FALfwMg7OMcbQh+wiw
23
g==
24
</ViaThinkSoftSignature> */ ?>
2 daniel-mar 25
<?php
26
 
27
/*
28
 * VNag - Nagios Framework for PHP
29
 * Developed by Daniel Marschall, ViaThinkSoft <www.viathinksoft.com>
30
 * Licensed under the terms of the Apache 2.0 license
31
 *
32
 * Revision 2018-11-03
33
 *
34
 * Changelog:
35
 * 2018-08-01   1.0   Initial release
36
 * 2018-09-02   1.1   Added argument -e|--emptyok
37
 *                    Output a warning if the Linux user does not exist.
38
 * 2018-10-01   1.2   Fixed a bug where too many unnecessary requests were sent to ipinfo.io
39
 *                    Cache file location ~/.last_ipcache is now preferred
40
 *                    A token for ipinfo.io can now be provided
41
 * 2018-11-03   1.2.1 "system boot" lines are now excluded
42
 */
43
 
44
// QUE: should we allow usernames to have wildcards, regexes or comma separated?
45
 
46
declare(ticks=1);
47
 
48
class LastCheck extends VNag {
49
        private $argUser = null;
50
        private $argRegex = null;
51
        private $argWtmpFiles = null;
52
        private $argEmptyOk = null;
53
        private $argIpInfoToken = null;
54
 
55
        private $cache = null;
56
        private $cacheFile = null;
57
        private $cacheDirty = false;
58
 
59
        protected function getIpCacheFile() {
60
                $homedir = @getenv('HOME');
61
                if ($homedir) {
62
                        $try = "${homedir}/.last_ipcache";
63
                        if (file_exists($try)) return $try;
64
                        if (@touch($try)) return $try;
65
                }
66
 
67
                $user = posix_getpwuid(posix_geteuid());
68
                if (isset($user['dir'])) {
69
                        $homedir = $user['dir'];
70
                        $try = "${homedir}/.last_ipcache";
71
                        if (file_exists($try)) return $try;
72
                        if (@touch($try)) return $try;
73
                }
74
 
75
                if (isset($user['name'])) {
76
                        $username = $user['name'];
77
                        $try = "/tmp/ipcache_${username}.tmp";
78
                        if (file_exists($try)) return $try;
79
                        if (@touch($try)) return $try;
80
                }
81
 
82
                return false; // should usually never happen
83
        }
84
 
85
        public function __construct() {
86
                parent::__construct();
87
 
88
                if ($this->is_http_mode()) {
89
                        // Don't allow the standard arguments via $_REQUEST
90
                        $this->registerExpectedStandardArguments('');
91
                } else {
92
                        $this->registerExpectedStandardArguments('Vhtv');
93
                }
94
 
95
                $this->addExpectedArgument($this->argUser = new VNagArgument('u', 'user', VNagArgument::VALUE_REQUIRED, 'user', 'The Linux username. If the argument is missing, all users will be checked.', null));
96
                $this->addExpectedArgument($this->argRegex = new VNagArgument('R', 'regex', VNagArgument::VALUE_REQUIRED, 'regex', 'The regular expression (in PHP: preg_match) which is applied on IP, Hostname, Country, AS number or ISP name. If the regular expression matches, the login will be accepted, otherweise an alert will be triggered. Example: /DE/ismU or /Telekom/ismU', null));
97
                $this->addExpectedArgument($this->argWtmpFiles = new VNagArgument('f', 'wtmpfile', VNagArgument::VALUE_REQUIRED, 'wtmpfile', 'Filemask of the wtmp file (important if you use logrotate), e.g. \'/var/log/wtmp*\'', '/var/log/wtmp*'));
98
                $this->addExpectedArgument($this->argEmptyOk = new VNagArgument('e', 'emptyok', VNagArgument::VALUE_FORBIDDEN, null, 'Treat an empty result (e.g. empty wtmp file after rotation) as success; otherwise treat it as status "Unknown"', null));
99
                $this->addExpectedArgument($this->argIpInfoToken = new VNagArgument(null, 'ipInfoToken', VNagArgument::VALUE_REQUIRED, 'token', 'If you have a token for ipinfo.io, please enter it here. Without token, you can query the service approx 1,000 times per day (which should be enough)', null));
100
 
101
                $this->getHelpManager()->setPluginName('vnag_last');
102
                $this->getHelpManager()->setVersion('1.2');
103
                $this->getHelpManager()->setShortDescription('This plugin checks the logs of the tool "LAST" an warns when users have logged in with an unexpected IP/Country/ISP.');
104
                $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.');
105
                $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-v] [-e] [-u username] [-R regex] [--ipInfoToken token]');
106
                $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com');
107
 
108
                $this->cacheFile = $this->getIpCacheFile();
109
                $this->cache = $this->cacheFile ? json_decode(file_get_contents($this->cacheFile),true) : array();
110
        }
111
 
112
        public function __destruct() {
113
                if ($this->cacheFile && $this->cacheDirty) {
114
                        @file_put_contents($this->cacheFile, json_encode($this->cache));
115
                }
116
        }
117
 
118
        private function getCountryAndOrg($ip) {
119
                if (isset($this->cache[$ip])) return $this->cache[$ip];
120
 
121
                $url = 'https://ipinfo.io/'.urlencode($ip).'/json';
122
                $token = $this->argIpInfoToken->getValue();
123
                if ($token) $url .= '?token='.urlencode($token);
124
 
125
                // fwrite(STDERR, "Note: Will query $url\n");
126
                $cont = file_get_contents($url);
127
                if (!$cont) return array();
128
                if (!($data = @json_decode($cont, true))) return array();
129
                if (isset($data['error'])) return array();
130
 
131
                if (isset($data['bogon']) && ($data['bogon'])) {
132
                        // Things like 127.0.0.1 do not belong to anyone
133
                        $res = array();
134
                } else {
135
                        $res = array();
136
                        if (isset($data['hostname'])) $res[] = $data['hostname'];
137
                        if (isset($data['country'])) $res[] = $data['country'];
138
                        list($as, $orgName) = explode(' ', $data['org'], 2);
139
                        $res[] = $as;
140
                        $res[] = $orgName;
141
                }
142
 
143
                $this->cache[$ip] = $res;
144
                $this->cacheDirty = true;
145
                return $res;
146
        }
147
 
148
        private function getLastLoginIPs($username) {
149
                $cont = '';
150
                $files = glob($this->argWtmpFiles->getValue());
151
                foreach ($files as $file) {
152
                        if (trim($username) == '') {
153
                                $cont .= shell_exec('last -f '.escapeshellarg($file).' -F -w '); // all users
154
                        } else {
155
                                $cont .= shell_exec('last -f '.escapeshellarg($file).' -F -w '.escapeshellarg($username));
156
                        }
157
                }
158
                preg_match_all('@^(\S+)\s+(\S+)\s+(\S+)\s+(.+)$@ismU', $cont, $m, PREG_SET_ORDER);
159
                foreach ($m as $key => &$a) {
160
                        if (($a[2] === 'system') && ($a[3] === 'boot')) {
161
                                // reboot   system boot  4.9.0-8-amd64    Fri Oct 12 02:10   still running
162
                                unset($m[$key]);
163
                        } else if ($a[2] === 'begins') {
164
                                // wtmp.1 begins Fri Oct 12 02:10:43 2018
165
                                unset($m[$key]);
166
                        } else {
167
                                array_shift($a);
168
                        }
169
                }
170
                return $m;
171
        }
172
 
173
        protected function cbRun() {
174
                if (!`which which`) {
175
                        throw new VNagException("Program 'which' is not installed on your system");
176
                }
177
 
178
                if (!`which last`) {
179
                        throw new VNagException("Program 'last' (usually included in package smartmontools) is not installed on your system");
180
                }
181
 
182
                $username = $this->argUser->available() ? $this->argUser->getValue() : '';
183
                $regex = $this->argRegex->available() ? $this->argRegex->getValue() : null;
184
 
185
                if (($username != '') && function_exists('posix_getpwnam') && !posix_getpwnam($username)) {
186
                        $this->setStatus(VNag::STATUS_WARNING);
187
                        $this->addVerboseMessage("WARNING: Currently, there is no Linux user with name '$username'.", VNag::VERBOSITY_SUMMARY);
188
                }
189
 
190
                $count_total = 0;
191
                $count_ok = 0;
192
                $count_warning = 0;
193
 
194
                foreach ($this->getLastLoginIPs($username) as list($username, $pts, $ip, $times)) {
195
                        $count_total++;
196
 
197
                        $fields = $this->getCountryAndOrg($ip);
198
                        $fields[] = $ip;
199
 
200
                        if (is_null($regex)) {
201
                                // No regex. Just show the logins for information (status stays VNag::STATUS_UNKNOWN)
202
                                $this->addVerboseMessage("INFO: ".implode(' ',$fields)." @ $username, $pts $times", VNag::VERBOSITY_ADDITIONAL_INFORMATION);
203
                        } else {
204
                                $match = false;
205
                                foreach ($fields as $f) {
206
                                        if (preg_match($regex, $f, $dummy)) {
207
                                                $match = true;
208
                                                break;
209
                                        }
210
                                }
211
 
212
                                if ($match) {
213
                                        $count_ok++;
214
                                        $this->addVerboseMessage("OK: ".implode(' ',$fields)." @ $username $pts $times", VNag::VERBOSITY_ADDITIONAL_INFORMATION);
215
                                        $this->setStatus(VNag::STATUS_OK);
216
                                } else {
217
                                        $count_warning++;
218
                                        $this->addVerboseMessage("WARNING: ".implode(' ',$fields)." @ $username $pts $times", VNag::VERBOSITY_SUMMARY);
219
                                        $this->setStatus(VNag::STATUS_WARNING);
220
                                }
221
                        }
222
                }
223
 
224
                if (is_null($regex)) {
225
                        $this->setHeadline("Checked $count_total logins (No checks done because argument 'Regex' is missing)");
226
                } else {
227
                        if (($count_total == 0) && ($this->argEmptyOk->count() > 0)) {
228
                                $this->setStatus(VNag::STATUS_OK);
229
                        }
230
                        $this->setHeadline("Checked $count_total logins ($count_ok OK, $count_warning Warning)");
231
                }
232
        }
233
}