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
// Copyright (C) 2022-2024 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Kea Hooks Basic
// Commercial End User License Agreement v2.0. See COPYING file in the premium/
// directory.

#include <config.h>

#include <rbac.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <rbac_config.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <rbac_log.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <cc/command_interpreter.h>
#include <exceptions/exceptions.h>
#include <hooks/hooks.h>
#include <http/post_request_json.h>
#include <process/daemon.h>

using namespace isc;
using namespace isc::config;
using namespace isc::data;
using namespace isc::hooks;
using namespace isc::http;
using namespace isc::log;
using namespace isc::process;
using namespace isc::rbac;
using namespace std;

// Functions accessed by the hooks framework use C linkage to avoid the name
// mangling that accompanies use of the C++ compiler as well as to avoid
// issues related to namespaces.
extern "C" {

/// @brief This function is called when the library is loaded.
///
/// @param handle library handle.
/// @return 0 when initialization is successful, 1 otherwise.
int
load(LibraryHandle& handle) {
    try {
        // Make the hook library loadable only by the control agent.
        const string& proc_name = Daemon::getProcName();
        if (proc_name != "kea-ctrl-agent") {
            isc_throw(Unexpected, "Bad process name: " << proc_name
                      << ", expected kea-ctrl-agent");
        }

        // Load the configuration.
        ConstElementPtr config = handle.getParameters();
        rbacConfig.init();
        Config::parse(config);
    } catch (const std::exception& ex) {
        LOG_ERROR(rbac_logger, RBAC_LOAD_FAILED)
            .arg(ex.what());
        return (1);
    }

    LOG_INFO(rbac_logger, RBAC_LOAD_OK);
    return (0);
}

/// @brief This function is called when the library is unloaded.
///
/// @return always 0.
int
unload() {
    if (roleAssign) {
        roleAssign->setup(false);
    }
    roleAssign.reset();
    roleConfigTable.clear();
    defaultRoleConfig.reset();
    unknownRoleConfig.reset();
    aclTable.clear();
    apiTable.clear();
    apiAccesses.clear();
    apiHooks.clear();
    responseFilterTable.clear();

    LOG_INFO(rbac_logger, RBAC_UNLOAD_OK);
    return (0);
}

/// @brief This function is called to retrieve the multi-threading compatibility.
///
/// @return 1 which means compatible with multi-threading.
int multi_threading_compatible() {
    return (1);
}

/// @brief This callout is called at the "auth" hook.
///
/// @param handle CalloutHandle.
/// @return 0 upon success, non-zero otherwise.
int
auth(CalloutHandle& handle) {
    if (!roleAssign) {
        LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC, RBAC_TRACE_AUTH_DISABLED);
        return (0);
    }

    // Get the parameters.
    HttpRequestPtr request;
    HttpResponseJsonPtr response;<--- Shadow variable
    handle.getArgument("request", request);
    handle.getArgument("response", response);

    if (response) {
        LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC, RBAC_TRACE_AUTH_RESPONSE)
            .arg(response->toBriefString());
        return (0);
    }

    auto status_code = HttpStatusCode::FORBIDDEN;
    bool updated = false;
    try {
        // Most errors will be caught later.
        if (!request) {
            LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC,
                      RBAC_TRACE_AUTH_NO_REQUEST);
            return (0);
        }
        // Check TLS.
        if (rbacConfig.getRequireTls() && !Role::requireTls(request)) {
            LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC,
                      RBAC_TRACE_AUTH_NO_TLS_REJECT);
            status_code = HttpStatusCode::UNAUTHORIZED;
            response = RoleConfig::createReject(request, status_code);
            LOG_INFO(rbac_logger, RBAC_AUTH_RESPONSE)
                .arg(response->toBriefString());
            handle.setArgument("response", response);
            return (0);
        }
        PostHttpRequestJsonPtr request_json =
            boost::dynamic_pointer_cast<PostHttpRequestJson>(request);
        if (!request_json) {
            LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC,
                      RBAC_TRACE_AUTH_NO_JSON);
            return (0);
        }
        ConstElementPtr body = request_json->getBodyAsJson();
        if (!body) {
            LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC,
                      RBAC_TRACE_AUTH_EMPTY_BODY);
            return (0);
        }
        if (body->getType() != Element::map) {
            LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC,
                      RBAC_TRACE_AUTH_BAD_BODY_TYPE);
            return (0);
        }
        ConstElementPtr elem = body->get(CONTROL_COMMAND);
        if (!elem) {
            LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC,
                      RBAC_TRACE_AUTH_NO_COMMAND);
            return (0);
        }
        if (elem->getType() != Element::string) {
            LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC,
                      RBAC_TRACE_AUTH_BAD_COMMAND_TYPE);
            return (0);
        }
        string command = elem->stringValue();
        LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC, RBAC_TRACE_AUTH_COMMAND)
            .arg(command);

        // Assign role.
        const string& role = roleAssign->assign(request);
        LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC, RBAC_TRACE_AUTH_ROLE)
            .arg(role);
        RoleConfigPtr role_config = RoleConfig::getConfig(role);
        if (!role_config) {
            isc_throw(Unexpected, "can't find a role configuration");
        }

        // Filter command.
        if (role_config->match(command)) {
            LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC, RBAC_TRACE_AUTH_ACCEPT)
                .arg(role_config->name_)
                .arg(role)
                .arg(command);
            if ((command == "config-set") || (command == "config-reload")) {
                // Ask the handle to be reset so the hook can be unloaded
                // without keeping a pointer to its address space...
                handle.setStatus(CalloutHandle::NEXT_STEP_SKIP);
            } else if (!role_config->response_filters_.empty()) {
                // Save values in the context for the response callout.
                handle.setContext("command", command);
                handle.setContext("role_config", role_config);
            }
        } else {
            LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC, RBAC_TRACE_AUTH_REJECT)
                .arg(role_config->name_)
                .arg(role)
                .arg(command);
            response = RoleConfig::createReject(request, status_code);
            updated = true;
        }
    } catch (const std::exception& ex) {
        LOG_ERROR(rbac_logger, RBAC_AUTH_ERROR)
            .arg(ex.what());
        status_code = HttpStatusCode::INTERNAL_SERVER_ERROR;
        response = RoleConfig::createReject(request, status_code);
        updated = true;
    }

    // Set parameters.
    if (updated) {
        LOG_INFO(rbac_logger, RBAC_AUTH_RESPONSE)
            .arg(response->toBriefString());
        handle.setArgument("response", response);
    }

    return (0);
}

/// @brief This callout is called at the "response" hook.
///
/// @param handle CalloutHandle.
/// @return 0 upon success, non-zero otherwise.
int
response(CalloutHandle& handle) {<--- Shadowed declaration<--- Parameter 'handle' can be declared as reference to const
    if (!roleAssign) {
        LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC,
                  RBAC_TRACE_RESPONSE_DISABLED);
        return (0);
    }

    // Get the parameters.
    HttpRequestPtr request;
    HttpResponseJsonPtr response;
    handle.getArgument("request", request);
    handle.getArgument("response", response);

    if (!request || !response) {
        LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC,
                  RBAC_TRACE_RESPONSE_NO_ARGUMENTS);
        return (0);
    }

    // Decode response.
    ConstElementPtr body = response->getBodyAsJson();
    if (!body) {
        LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC,
                  RBAC_TRACE_RESPONSE_EMPTY_BODY);
        return (0);
    }
    if (body->getType() != Element::list) {
        // Should be an error response, anyway nothing to filter.
        LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC,
                  RBAC_TRACE_RESPONSE_BAD_BODY_TYPE);
        return (0);
    }
    if (body->size() < 1) {
        LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC,
                  RBAC_TRACE_RESPONSE_EMPTY_BODY_LIST);
        return (0);
    }

    // Recover command and role config;
    string command;
    RoleConfigPtr role_config;
    handle.getContext("command", command);
    handle.getContext("role_config", role_config);
    if (!role_config || (role_config->response_filters_.empty())) {
        return (0);
    }
    LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC, RBAC_TRACE_RESPONSE_CONTEXT)
        .arg(command)
        .arg(role_config->name_);

    // Apply filters on each list item.
    bool modified = false;
    for (auto const& answer : body->listValue()) {
        if (role_config->filter(command, answer)) {
            modified = true;
        }
    }
    if (modified) {
        LOG_DEBUG(rbac_logger, DBGLVL_TRACE_BASIC,
                  RBAC_TRACE_RESPONSE_MODIFIED);
        response->setBodyAsJson(body);
    }

    return (0);
}

}