source: nscp/modules/NRPEClient/NRPEClient.cpp @ fe75eff

0.4.00.4.10.4.2
Last change on this file since fe75eff was fe75eff, checked in by Michael Medin <michael@…>, 21 months ago

2011-08-16 MickeM

  • Added support for remote WMI checking using target/username/password options like so:

CheckWMI target=192.168.0.123 user=
foobar password=foobar namespace=root
cimv2 MaxCrit=3 MinWarn=1 "Query:load=Select * from win32_Processor"

  • Added support for looking up targets to CheckWMI CheckWMI target=my_test_xp MaxCrit=3 MinWarn=1 "Query:load=Select * from win32_Processor" Where <target> is defined under /settings/targets as well as /settings/targets/my_test_xp

2011-08-15 MickeM

  • Added support for target in default plugin helpers
  • Added remote WMI commands
  • Added target section under /settings/targets
  • Property mode set to 100644
File size: 14.6 KB
Line 
1/**************************************************************************
2*   Copyright (C) 2004-2007 by Michael Medin <michael@medin.name>         *
3*                                                                         *
4*   This code is part of NSClient++ - http://trac.nakednuns.org/nscp      *
5*                                                                         *
6*   This program is free software; you can redistribute it and/or modify  *
7*   it under the terms of the GNU General Public License as published by  *
8*   the Free Software Foundation; either version 2 of the License, or     *
9*   (at your option) any later version.                                   *
10*                                                                         *
11*   This program is distributed in the hope that it will be useful,       *
12*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
13*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
14*   GNU General Public License for more details.                          *
15*                                                                         *
16*   You should have received a copy of the GNU General Public License     *
17*   along with this program; if not, write to the                         *
18*   Free Software Foundation, Inc.,                                       *
19*   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
20***************************************************************************/
21#include "stdafx.h"
22#include "NRPEClient.h"
23#include <strEx.h>
24#include <time.h>
25#include <config.h>
26#include <strEx.h>
27#include <boost/filesystem.hpp>
28#include <strEx.h>
29#include <nrpe/client/socket.hpp>
30
31#include <settings/client/settings_client.hpp>
32
33
34namespace setting_keys {
35
36        // NSClient Setting headlines
37        namespace nrpe {
38                DEFINE_PATH(SECTION, NRPE_SECTION_PROTOCOL);
39                //DESCRIBE_SETTING(SECTION, "NRPE SECTION", "Section for NRPE (NRPEListener.dll) (check_nrpe) protocol options.");
40
41
42                DEFINE_PATH(CH_SECTION, NRPE_CLIENT_HANDLER_SECTION);
43                //DESCRIBE_SETTING(CH_SECTION, "CLIENT HANDLER SECTION", "...");
44
45                DEFINE_SETTING_S(ALLOWED_HOSTS, NRPE_SECTION_PROTOCOL, GENERIC_KEY_ALLOWED_HOSTS, "");
46                DESCRIBE_SETTING(ALLOWED_HOSTS, "ALLOWED HOST ADDRESSES", "This is a comma-delimited list of IP address of hosts that are allowed to talk to NSClient deamon. If you leave this blank the global version will be used instead.");
47
48                DEFINE_SETTING_I(PORT, NRPE_SECTION_PROTOCOL, "port", 5666);
49                //DESCRIBE_SETTING(PORT, "NSCLIENT PORT NUMBER", "This is the port the NSClientListener.dll will listen to.");
50
51                DEFINE_SETTING_S(BINDADDR, NRPE_SECTION_PROTOCOL, GENERIC_KEY_BIND_TO, "");
52                //DESCRIBE_SETTING(BINDADDR, "BIND TO ADDRESS", "Allows you to bind server to a specific local address. This has to be a dotted ip adress not a hostname. Leaving this blank will bind to all avalible IP adresses.");
53
54                DEFINE_SETTING_I(READ_TIMEOUT, NRPE_SECTION_PROTOCOL, GENERIC_KEY_SOCK_READ_TIMEOUT, 30);
55                //DESCRIBE_SETTING(READ_TIMEOUT, "SOCKET TIMEOUT", "Timeout when reading packets on incoming sockets. If the data has not arrived withint this time we will bail out.");
56
57                DEFINE_SETTING_I(LISTENQUE, NRPE_SECTION_PROTOCOL, GENERIC_KEY_SOCK_LISTENQUE, 0);
58                //DESCRIBE_SETTING_ADVANCED(LISTENQUE, "LISTEN QUEUE", "Number of sockets to queue before starting to refuse new incoming connections. This can be used to tweak the amount of simultaneous sockets that the server accepts.");
59
60                DEFINE_SETTING_I(THREAD_POOL, NRPE_SECTION_PROTOCOL, "thread pool", 10);
61                //DESCRIBE_SETTING_ADVANCED(THREAD_POOL, "THREAD POOL", "");
62
63
64
65                DEFINE_SETTING_B(CACHE_ALLOWED, NRPE_SECTION_PROTOCOL, GENERIC_KEY_SOCK_CACHE_ALLOWED, false);
66                DESCRIBE_SETTING_ADVANCED(CACHE_ALLOWED, "ALLOWED HOSTS CACHING", "Used to cache looked up hosts if you check dynamic/changing hosts set this to false.");
67
68                //DEFINE_SETTING_B(KEYUSE_SSL, NRPE_SECTION_PROTOCOL, GENERIC_KEY_USE_SSL, true);
69                //DESCRIBE_SETTING(KEYUSE_SSL, "USE SSL SOCKET", "This option controls if SSL should be used on the socket.");
70
71                DEFINE_SETTING_I(PAYLOAD_LENGTH, NRPE_SECTION_PROTOCOL, "payload length", 1024);
72                //DESCRIBE_SETTING_ADVANCED(PAYLOAD_LENGTH, "PAYLOAD LENGTH", "Length of payload to/from the NRPE agent. This is a hard specific value so you have to \"configure\" (read recompile) your NRPE agent to use the same value for it to work.");
73
74                //DEFINE_SETTING_B(ALLOW_PERFDATA, NRPE_SECTION, "performance data", true);
75                //DESCRIBE_SETTING_ADVANCED(ALLOW_PERFDATA, "PERFORMANCE DATA", "Send performance data back to nagios (set this to 0 to remove all performance data).");
76
77                //DEFINE_SETTING_I(CMD_TIMEOUT, NRPE_SECTION, "command timeout", 60);
78                //DESCRIBE_SETTING(CMD_TIMEOUT, "COMMAND TIMEOUT", "This specifies the maximum number of seconds that the NRPE daemon will allow plug-ins to finish executing before killing them off.");
79
80                DEFINE_SETTING_B(ALLOW_ARGS, NRPE_SECTION, "allow arguments", false);
81                //DESCRIBE_SETTING(ALLOW_ARGS, "COMMAND ARGUMENT PROCESSING", "This option determines whether or not the NRPE daemon will allow clients to specify arguments to commands that are executed.");
82
83                DEFINE_SETTING_B(ALLOW_NASTY, NRPE_SECTION, "allow nasy characters", false);
84                //DESCRIBE_SETTING(ALLOW_NASTY, "COMMAND ALLOW NASTY META CHARS", "This option determines whether or not the NRPE daemon will allow clients to specify nasty (as in |`&><'\"\\[]{}) characters in arguments.");
85
86        }
87}
88namespace sh = nscapi::settings_helper;
89
90NRPEClient gNRPEClient;
91
92NRPEClient::NRPEClient() : buffer_length_(0) {
93}
94
95NRPEClient::~NRPEClient() {
96}
97
98bool NRPEClient::loadModule() {
99        return false;
100}
101
102bool NRPEClient::loadModuleEx(std::wstring alias, NSCAPI::moduleLoadMode mode) {
103        std::map<std::wstring,std::wstring> commands;
104
105        try {
106
107                //"/settings/NRPE/client/handlers"
108                sh::settings_registry settings(get_settings_proxy());
109                settings.set_alias(_T("NRPE"), alias, _T("client"));
110
111                settings.alias().add_path_to_settings()
112//                      (_T("EXTERNAL SCRIPT SECTION"), _T("Section for external scripts configuration options (CheckExternalScripts)."))
113
114                        (_T("handlers"), sh::fun_values_path(boost::bind(&NRPEClient::add_command, this, _1, _2)),
115                        _T("CLIENT HANDLER SECTION"), _T(""))
116
117                        (_T("servers"), sh::fun_values_path(boost::bind(&NRPEClient::add_server, this, _1, _2)),
118                        _T("REMOTE SERVER DEFINITIONS"), _T(""))
119
120                        ;
121
122                settings.alias().add_key_to_settings()
123
124                        (_T("payload length"),  sh::uint_key(&buffer_length_, 1024),
125                        _T("PAYLOAD LENGTH"), _T("Length of payload to/from the NRPE agent. This is a hard specific value so you have to \"configure\" (read recompile) your NRPE agent to use the same value for it to work."))
126
127                        ;
128
129
130                settings.register_all();
131                settings.notify();
132
133        } catch (...) {
134                NSC_LOG_ERROR_STD(_T("Exception caught: <UNKNOWN EXCEPTION>"));
135                return false;
136        }
137
138        boost::filesystem::wpath p = GET_CORE()->getBasePath() + std::wstring(_T("/security/nrpe_dh_512.pem"));
139        cert_ = p.string();
140        if (boost::filesystem::is_regular(p)) {
141                NSC_DEBUG_MSG_STD(_T("Using certificate: ") + cert_);
142        } else {
143                NSC_LOG_ERROR_STD(_T("Certificate not found: ") + cert_);
144        }
145
146        return true;
147}
148
149void NRPEClient::add_options(po::options_description &desc, nrpe_connection_data &command_data) {
150        desc.add_options()
151                ("host,H", po::wvalue<std::wstring>(&command_data.host), "The address of the host running the NRPE daemon")
152                ("port,p", po::value<int>(&command_data.port), "The port on which the daemon is running (default=5666)")
153                ("command,c", po::wvalue<std::wstring>(&command_data.command), "The name of the command that the remote daemon should run")
154                ("timeout,t", po::value<int>(&command_data.timeout), "Number of seconds before connection times out (default=10)")
155                ("buffer-length,l", po::value<unsigned int>(&command_data.buffer_length), std::string("Length of payload (has to be same as on the server (default=" + to_string(buffer_length_) + ")").c_str())
156                ("no-ssl,n", po::value<bool>(&command_data.no_ssl)->zero_tokens()->default_value(false), "Do not initial an ssl handshake with the server, talk in plaintext.")
157                ("arguments,a", po::wvalue<std::vector<std::wstring> >(&command_data.argument_vector), "list of arguments")
158                ;
159}
160
161void NRPEClient::add_server(std::wstring key, std::wstring args) {
162}
163
164void NRPEClient::add_command(std::wstring key, std::wstring args) {
165        try {
166
167                NRPEClient::nrpe_connection_data command_data;
168                boost::program_options::variables_map vm;
169
170                po::options_description desc("Allowed options");
171                buffer_length_ = SETTINGS_GET_INT(nrpe::PAYLOAD_LENGTH);
172                add_options(desc, command_data);
173
174                po::positional_options_description p;
175                p.add("arguments", -1);
176
177                std::vector<std::wstring> list;
178                //explicit escaped_list_separator(Char e = '\\', Char c = ',',Char q = '\"')
179                boost::escaped_list_separator<wchar_t> sep(L'\\', L' ', L'\"');
180                typedef boost::tokenizer<boost::escaped_list_separator<wchar_t>,std::wstring::const_iterator, std::wstring > tokenizer_t;
181                tokenizer_t tok(args, sep);
182                for(tokenizer_t::iterator beg=tok.begin(); beg!=tok.end();++beg){
183                        list.push_back(*beg);
184                }
185
186                po::wparsed_options parsed = po::basic_command_line_parser<wchar_t>(list).options(desc).positional(p).run();
187                po::store(parsed, vm);
188                po::notify(vm);
189                command_data.parse_arguments();
190
191                NSC_DEBUG_MSG_STD(_T("Added NRPE Client: ") + key.c_str() + _T(" = ") + command_data.toString());
192                commands[key.c_str()] = command_data;
193
194                GET_CORE()->registerCommand(key.c_str(), command_data.toString());
195
196        } catch (boost::program_options::validation_error &e) {
197                NSC_LOG_ERROR_STD(_T("Could not parse: ") + key.c_str() + strEx::string_to_wstring(e.what()));
198        } catch (...) {
199                NSC_LOG_ERROR_STD(_T("Could not parse: ") + key.c_str());
200        }
201}
202
203bool NRPEClient::unloadModule() {
204        return true;
205}
206
207bool NRPEClient::hasCommandHandler() {
208        return true;
209}
210bool NRPEClient::hasMessageHandler() {
211        return false;
212}
213NSCAPI::nagiosReturn NRPEClient::handleCommand(const std::wstring &target, const std::wstring &command, std::list<std::wstring> &arguments, std::wstring &message, std::wstring &perf) {
214        command_list::const_iterator cit = commands.find(strEx::blindstr(command.c_str()));
215        if (cit == commands.end())
216                return NSCAPI::returnIgnored;
217
218        std::wstring args = (*cit).second.arguments;
219        if (SETTINGS_GET_BOOL(nrpe::ALLOW_ARGS) == 1) {
220                int i=1;
221                BOOST_FOREACH(std::wstring arg, arguments)
222                {
223                        if (SETTINGS_GET_INT(nrpe::ALLOW_NASTY) == 0) {
224                                if (arg.find_first_of(NASTY_METACHARS) != std::wstring::npos) {
225                                        NSC_LOG_ERROR(_T("Request string contained illegal metachars!"));
226                                        return NSCAPI::returnIgnored;
227                                }
228                        }
229                        strEx::replace(args, _T("$ARG") + strEx::itos(i++) + _T("$"), arg);
230                }
231        }
232
233        NSC_DEBUG_MSG_STD(_T("Rewrote command arguments: ") + args);
234        nrpe_result_data r = execute_nrpe_command((*cit).second, args);
235        message = r.text;
236        return r.result;
237}
238
239int NRPEClient::commandLineExec(const std::wstring &command, std::list<std::wstring> &arguments, std::wstring &result) {
240        if (command != _T("query") && command != _T("help"))
241                return NSCAPI::returnIgnored;
242        try {
243                NRPEClient::nrpe_connection_data command_data;
244                boost::program_options::variables_map vm;
245
246                po::options_description desc("Allowed options");
247                buffer_length_ = SETTINGS_GET_INT(nrpe::PAYLOAD_LENGTH);
248                add_options(desc, command_data);
249
250                std::vector<std::wstring> vargs(arguments.begin(), arguments.end());
251                po::positional_options_description p;
252                p.add("arguments", -1);
253                po::wparsed_options parsed = po::basic_command_line_parser<wchar_t>(vargs).options(desc).positional(p).run();
254                po::store(parsed, vm);
255                po::notify(vm);
256                command_data.parse_arguments();
257                if (command == _T("help")) {
258                        std::stringstream ss;
259                        ss << "NRPEClient Command line syntax for command: query" << std::endl;;
260                        ss << desc;
261                        result = utf8::cvt<std::wstring>(ss.str());
262                        return NSCAPI::returnOK;
263                }
264
265                nrpe_result_data res = execute_nrpe_command(command_data, command_data.arguments);
266                result = res.text;
267                return res.result;
268        } catch (boost::program_options::validation_error &e) {
269                result = _T("Error: ") + utf8::cvt<std::wstring>(e.what());
270                return NSCAPI::returnUNKNOWN;
271        } catch (...) {
272                result = _T("Unknown exception parsing command line");
273                return NSCAPI::returnUNKNOWN;
274        }
275        return NSCAPI::returnUNKNOWN;
276}
277NRPEClient::nrpe_result_data NRPEClient::execute_nrpe_command(nrpe_connection_data con, std::wstring arguments) {
278        try {
279                nrpe::packet packet;
280                if (!con.no_ssl) {
281#ifdef USE_SSL
282                        packet = send_ssl(con.host, con.port, con.timeout, nrpe::packet::make_request(con.get_cli(arguments), con.buffer_length));
283#else
284                        NSC_LOG_ERROR_STD(_T("SSL not avalible (not compiled with USE_SSL)"));
285                        return nrpe_result_data(NSCAPI::returnUNKNOWN, _T("SSL support not available (compiled without USE_SSL)!"));
286#endif
287                } else
288                        packet = send_nossl(con.host, con.port, con.timeout, nrpe::packet::make_request(con.get_cli(arguments), con.buffer_length));
289                return nrpe_result_data(packet.getResult(), packet.getPayload());
290        } catch (nrpe::nrpe_packet_exception &e) {
291                return nrpe_result_data(NSCAPI::returnUNKNOWN, _T("NRPE Packet errro: ") + e.getMessage());
292        } catch (std::runtime_error &e) {
293                NSC_LOG_ERROR_STD(_T("Socket error: ") + utf8::cvt<std::wstring>(e.what()));
294                return nrpe_result_data(NSCAPI::returnUNKNOWN, _T("Socket error: ") + utf8::cvt<std::wstring>(e.what()));
295        } catch (...) {
296                return nrpe_result_data(NSCAPI::returnUNKNOWN, _T("Unknown error -- REPORT THIS!"));
297        }
298}
299
300
301#ifdef USE_SSL
302nrpe::packet NRPEClient::send_ssl(std::wstring host, int port, int timeout, nrpe::packet packet) {
303        boost::asio::io_service io_service;
304        boost::asio::ssl::context ctx(io_service, boost::asio::ssl::context::sslv23);
305        SSL_CTX_set_cipher_list(ctx.impl(), "ADH");
306        ctx.use_tmp_dh_file(to_string(cert_));
307        ctx.set_verify_mode(boost::asio::ssl::context::verify_none);
308        nrpe::client::ssl_socket socket(io_service, ctx, host, port);
309        socket.send(packet, boost::posix_time::seconds(timeout));
310        nrpe::packet ret = socket.recv(packet, boost::posix_time::seconds(timeout));
311        return ret;
312}
313#endif
314
315nrpe::packet NRPEClient::send_nossl(std::wstring host, int port, int timeout, nrpe::packet packet) {
316        boost::asio::io_service io_service;
317        nrpe::client::socket socket(io_service, host, port);
318        socket.send(packet, boost::posix_time::seconds(timeout));
319        return socket.recv(packet, boost::posix_time::seconds(timeout));
320}
321
322NSC_WRAP_DLL();
323NSC_WRAPPERS_MAIN_DEF(gNRPEClient);
324NSC_WRAPPERS_IGNORE_MSG_DEF();
325NSC_WRAPPERS_HANDLE_CMD_DEF(gNRPEClient);
326NSC_WRAPPERS_CLI_DEF(gNRPEClient);
327
Note: See TracBrowser for help on using the repository browser.