File: service.cpp

package info (click to toggle)
openvpn3-client 25%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 19,276 kB
  • sloc: cpp: 190,085; python: 7,218; ansic: 1,866; sh: 1,361; java: 402; lisp: 81; makefile: 17
file content (434 lines) | stat: -rw-r--r-- 12,242 bytes parent folder | download | duplicates (2)
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//  OpenVPN 3 Linux client -- Next generation OpenVPN client
//
//  SPDX-License-Identifier: AGPL-3.0-only
//
//  Copyright (C) 2017-  OpenVPN Inc <sales@openvpn.net>
//  Copyright (C) 2024-  Răzvan Cojocaru <razvan.cojocaru@openvpn.com>
//

#include <chrono>
#include <fstream>
#include <iostream>
#include <memory>
#include <set>

#include <openvpn/common/string.hpp>
#include "constants.hpp"
#include "modules/built-in.hpp"
#include "modulehandler.hpp"
#include "service.hpp"


namespace DevPosture {

Handler::Handler(DBus::Connection::Ptr dbuscon,
                 DBus::Object::Manager::Ptr object_manager,
                 LogWriter::Ptr logwr,
                 uint8_t log_level)
    : DBus::Object::Base(PATH_DEVPOSTURE, INTERFACE_DEVPOSTURE),
      object_manager_(object_manager)
{
    signals_ = DevPosture::Log::Create(dbuscon,
                                       LogGroup::EXTSERVICE,
                                       GetPath(),
                                       logwr);
    signals_->SetLogLevel(log_level);
    RegisterSignals(signals_);

    auto grm_args = AddMethod("GetRegisteredModules",
                              [this](DBus::Object::Method::Arguments::Ptr args)
                              {
                                  method_get_registered_modules(args);
                              });

    grm_args->AddOutput("paths", "ao");

    auto pl_args = AddMethod("ProtocolLookup",
                             [this](DBus::Object::Method::Arguments::Ptr args)
                             {
                                 method_protocol_lookup(args);
                             });

    pl_args->AddInput("enterprise_profile", glib2::DataType::DBus<std::string>());
    pl_args->AddOutput("protocol", glib2::DataType::DBus<std::string>());

    auto rc_args = AddMethod("RunChecks",
                             [this](DBus::Object::Method::Arguments::Ptr args)
                             {
                                 method_run_checks(args);
                             });

    rc_args->AddInput("protocol", glib2::DataType::DBus<std::string>());
    rc_args->AddInput("request", glib2::DataType::DBus<std::string>());
    rc_args->AddOutput("result", glib2::DataType::DBus<std::string>());
}


const bool Handler::Authorize(const DBus::Authz::Request::Ptr authzreq)
{
    return true;
}


void Handler::LoadProtocolProfiles(const std::string &profile_dir)
{
    namespace fs = std::filesystem;

    try
    {
        for (const auto &entry : fs::directory_iterator(profile_dir))
        {
            auto p = entry.path();

            if (p.extension() == ".json")
            {
                std::ifstream profile_stream(p, std::ios::in | std::ios::binary);
                Json::Value profile_json;

                profile_stream >> profile_json;

                profiles_[p.stem()] = profile_json;
            }
        }
    }
    catch (const std::exception &e)
    {
        using namespace std::string_literals;

        signals_->LogError("Error parsing protocol profiles: "s + e.what());
    }
}


Json::Value Handler::compose_json(const Module::Dictionary &dict, const Json::Value &result_mapping) const
{
    Json::Value ret;

    for (auto it = result_mapping.begin(); it != result_mapping.end(); ++it)
    {
        if (!it->isObject())
        {
            std::string val;
            auto dict_it = dict.find(it->asString());

            if (dict_it != dict.end())
                val = dict_it->second;

            ret[it.key().asString()] = val;
        }
        else
        {
            ret[it.key().asString()] = compose_json(dict, *it);
        }
    }

    return ret;
}


void Handler::method_get_registered_modules(DBus::Object::Method::Arguments::Ptr args) const
{
    DBus::Object::Path::List paths;

    for (const auto &[path, object] : object_manager_->GetAllObjects())
    {
        // Don't return the root module.
        if (std::dynamic_pointer_cast<ModuleHandler>(object))
        {
            paths.push_back(path);
        }
    }

    args->SetMethodReturn(glib2::Value::CreateTupleWrapped(paths));
}


void Handler::method_protocol_lookup(DBus::Object::Method::Arguments::Ptr args) const
{
    GVariant *params = args->GetMethodParameters();
    auto enterprise_profile = glib2::Value::Extract<std::string>(params, 0);

    std::string retval;
    auto it = profiles_.find(enterprise_profile);

    if (it == profiles_.end())
    {
        const std::string err_msg = "ProtocolLookup(): Could not find the appcontrol_id for enterprise profile '"
                                    + enterprise_profile + "'";

        signals_->LogError(err_msg);
        throw DBus::Object::Method::Exception(err_msg);
    }

    retval = it->second["appcontrol_id"].asString();
    args->SetMethodReturn(glib2::Value::CreateTupleWrapped(retval));
}


void Handler::method_run_checks(DBus::Object::Method::Arguments::Ptr args) const
{
    using namespace std::chrono;

    GVariant *params = args->GetMethodParameters();

    const auto protocol = glib2::Value::Extract<std::string>(params, 0);
    const auto request = glib2::Value::Extract<std::string>(params, 1);

    std::string ret_string;
    Json::Value request_json;

    Json::CharReaderBuilder builder;
    builder["collectComments"] = false;

    std::string errors;
    std::istringstream instr(request);

    if (!Json::parseFromStream(builder, instr, &request_json, &errors))
    {
        throw DBus::Object::Method::Exception("devposture: invalid request JSON: " + request);
    }

    std::string correlation_id;
    std::string version;

    std::set<std::string> checks;

    const auto &req_data = request_json["dpc_request"];

    for (auto cit = req_data.begin(); cit != req_data.end(); ++cit)
    {
        const std::string key = cit.key().asString();

        if (key == "correlation_id")
        {
            correlation_id = cit->asString();
        }
        else if (key == "ver")
        {
            version = cit->asString();
        }
        else if (key != "timestamp")
        {
            if (cit->isBool() && cit->asBool())
            {
                checks.insert(key);
            }
        }
    }

    Json::Value ret_json;
    Json::Value ret_payload_json;
    bool protocol_found = false;
    bool version_matches = false;

    for (auto &&[enterprise_id, json_representation] : profiles_)
    {
        auto protocols =
            openvpn::string::split(json_representation["appcontrol_id"].asString(), ':');

        if (std::find(protocols.begin(), protocols.end(), protocol) == protocols.end())
        {
            continue;
        }

        protocol_found = true;

        if (json_representation["ver"].asString() != version)
        {
            continue;
        }

        version_matches = true;

        const auto &mappings = json_representation["control_mapping"];

        for (auto it = mappings.begin(); it != mappings.end(); ++it)
        {
            const auto &mapping_data = *it;
            Json::Value result_json;

            if (checks.find(it.key().asString()) != checks.end())
            {
                if (mapping_data.isArray())
                {
                    result_json = create_merged_mapped_json(mapping_data);
                }
                else
                {
                    result_json = create_mapped_json(mapping_data);
                }

                ret_payload_json[it.key().asString()] = result_json;
            }
        }

        if (!ret_payload_json.empty())
        {
            auto &dpc_response = ret_json["dpc_response"];

            dpc_response["ver"] = version;
            dpc_response["correlation_id"] = correlation_id;
            dpc_response["timestamp"] = generate_timestamp();

            for (auto it = ret_payload_json.begin(); it != ret_payload_json.end(); ++it)
            {
                dpc_response[it.key().asString()] = *it;
            }

            Json::StreamWriterBuilder builder;
            builder.settings_["indentation"] = "";
            ret_string = Json::writeString(builder, ret_json);
        }

        break;
    }

    if (!protocol_found || !version_matches || !ret_json)
    {
        signals_->Debug("Could not handle dpc_request: " + request);
    }

    if (!protocol_found)
    {
        const std::string err_msg = "protocol '" + protocol
                                    + "' not supported [correlation_id: "
                                    + correlation_id + "]";

        signals_->LogError("RunChecks(): " + err_msg);
        throw DBus::Object::Method::Exception(err_msg);
    }

    if (!version_matches)
    {
        const std::string err_msg = "requested version '" + version
                                    + "' not supported [correlation_id: "
                                    + correlation_id + "]";

        signals_->LogError("RunChecks(): " + err_msg);
        throw DBus::Object::Method::Exception(err_msg);
    }

    if (!ret_json)
    {
        const std::string err_msg = "no supported checks found [correlation_id: "
                                    + correlation_id + "]";

        signals_->LogError("RunChecks(): " + err_msg);
        throw DBus::Object::Method::Exception(err_msg);
    }

    signals_->LogVerb2("RunChecks(\"" + protocol + "\", \"" + request + "\") -> \""
                       + ret_string + "\"");

    args->SetMethodReturn(glib2::Value::CreateTupleWrapped(ret_string));
}


std::string Handler::generate_timestamp()
{
    using namespace std::chrono;

    const auto now = system_clock::now();
    const auto now_time_t = system_clock::to_time_t(now);
    const auto ms = time_point_cast<milliseconds>(now).time_since_epoch().count() % 1000;

    tm utc_time{};

    gmtime_r(&now_time_t, &utc_time);

    std::stringstream ss;

    ss << std::put_time(&utc_time, "%a %b %d %T.") << std::setfill('0')
       << std::setw(3) << ms << std::put_time(&utc_time, " %Y");

    return ss.str();
}


Json::Value Handler::create_mapped_json(const Json::Value &mapping_data) const
{
    const std::string module_path = mapping_data["module"].asString();
    const auto module_object = object_manager_->GetObject<ModuleHandler>(module_path);

    if (module_object)
    {
        const auto dict = module_object->Run({});

        return compose_json(dict, mapping_data["result_mapping"]);
    }

    return {};
}


Json::Value Handler::create_merged_mapped_json(const Json::Value &arr_mapping_data) const
{
    Json::Value ret;

    for (const auto &elem : arr_mapping_data)
    {
        const Json::Value mapped_json = create_mapped_json(elem);

        if (!mapped_json.empty())
        {
            for (auto it = mapped_json.begin(); it != mapped_json.end(); ++it)
            {
                ret[it.key().asString()] = *it;
            }
        }
    }

    return ret;
}


Service::Service(DBus::Connection::Ptr dbuscon, LogWriter::Ptr logwr, uint8_t log_level)
    : DBus::Service(dbuscon, SERVICE_DEVPOSTURE), dbuscon_(dbuscon),
      logwr_(std::move(logwr)), log_level_(log_level)
{
    try
    {
        logsrvprx_ = LogServiceProxy::AttachInterface(dbuscon, INTERFACE_DEVPOSTURE);
        handler_ = CreateServiceHandler<Handler>(dbuscon_, GetObjectManager(), logwr_, log_level_);
    }
    catch (const DBus::Exception &excp)
    {
        logwr_->Write(LogGroup::CONFIGMGR,
                      LogCategory::CRIT,
                      excp.GetRawError());
    }
}


Service::~Service() noexcept
{
    if (logsrvprx_)
    {
        logsrvprx_->Detach(INTERFACE_DEVPOSTURE);
    }
}


void Service::LoadProtocolProfiles(const std::string &profile_dir)
{
    handler_->LoadProtocolProfiles(profile_dir);
}


void Service::BusNameAcquired(const std::string &busname)
{
    auto object_manager = GetObjectManager();

    object_manager->CreateObject<ModuleHandler>(Module::Create<PlatformModule>(), false);
    object_manager->CreateObject<ModuleHandler>(Module::Create<DateTimeModule>(), false);
}


void Service::BusNameLost(const std::string &busname)
{
    throw DBus::Service::Exception(
        "openvpn3-service-devposture lost the '" + busname
        + "' registration on the D-Bus");
}

} // end of namespace DevPosture