drizzle
C++ MySQL-protocol-compatible database server
Loading...
Searching...
No Matches
plugin/regex_policy/module.cc
1/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2 * vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3 *
4 * Copyright (C) 2010 Monty Taylor <[email protected]>
5 * Copyright (C) 2011 Canonical, Ltd.
6 * Author: Clint Byrum <[email protected]>
7 *
8 * Copied from simple_user_policy
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; version 2 of the License.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23
24#include <config.h>
25
26#include <unordered_set>
27#include <boost/thread/locks.hpp>
28
29#include <drizzled/item.h>
30#include <drizzled/plugin/authorization.h>
32
33#include "policy.h"
34
35#include <fstream>
36
37namespace po= boost::program_options;
38
39using namespace std;
40using namespace drizzled;
41
42namespace regex_policy
43{
44
45uint64_t max_cache_buckets= DEFAULT_MAX_CACHE_BUCKETS;
46uint64_t max_lru_length= DEFAULT_MAX_LRU_LENGTH;
47bool updatePolicyFile(Session *, set_var *);
48bool parsePolicyFile(std::string, PolicyItemList&, PolicyItemList&, PolicyItemList&);
49Policy *policy= NULL;
50
51bool updatePolicyFile(Session *, set_var* var)
52{
53 if (not var->value->str_value.empty())
54 {
55 std::string newPolicyFile(var->value->str_value.data());
56 if (policy->setPolicyFile(newPolicyFile))
57 return false; //success
58 else
59 return true; // error
60 }
61 errmsg_printf(error::ERROR, _("regex_policy file cannot be NULL"));
62 return true; // error
63}
64
65bool parsePolicyFile(std::string new_policy_file, PolicyItemList& table_policies_dummy, PolicyItemList& schema_policies_dummy, PolicyItemList& process_policies_dummy)
66{
67 ifstream file(new_policy_file.c_str());
68 boost::regex comment_re;
69 boost::regex empty_re;
70 boost::regex table_matches_re;
71 boost::regex process_matches_re;
72 boost::regex schema_matches_re;
73 table_policies_dummy.clear();
74 schema_policies_dummy.clear();
75 process_policies_dummy.clear();
76
77 try
78 {
79 comment_re= comment_regex;
80 empty_re= empty_regex;
81 table_matches_re= table_match_regex;
82 process_matches_re= process_match_regex;
83 schema_matches_re= schema_match_regex;
84 }
85 catch (const std::exception &e)
86 {
87 errmsg_printf(error::ERROR, _("parsePolicyFile() %s"), e.what());
88 return false;
89 }
90
91 if (! file.is_open())
92 {
93 errmsg_printf(error::ERROR, _("Unable to open regex policy file: %s"), new_policy_file.c_str());
94 return false;
95 }
96
97 try
98 {
99 for (string line; getline(file, line); )
100 {
101 if (boost::regex_match(line, comment_re))
102 {
103 continue;
104 }
105 if (boost::regex_match(line, empty_re))
106 {
107 continue;
108 }
109 boost::smatch matches;
110 PolicyItemList *policies;
111 if (boost::regex_match(line, matches, table_matches_re, boost::match_extra))
112 {
113 policies= &table_policies_dummy;
114 }
115 else if (boost::regex_match(line, matches, process_matches_re, boost::match_extra))
116 {
117 policies= &process_policies_dummy;
118 }
119 else if (boost::regex_match(line, matches, schema_matches_re, boost::match_extra))
120 {
121 policies= &schema_policies_dummy;
122 }
123 else
124 {
125 throw std::exception();
126 }
127 string user_regex= matches[MATCH_REGEX_USER_POS];
128 string object_regex= matches[MATCH_REGEX_OBJECT_POS];
129 string action= matches[MATCH_REGEX_ACTION_POS];
130 try
131 {
132 policies->push_back(new PolicyItem(user_regex, object_regex, action));
133 }
134 catch (const std::exception &e)
135 {
136 errmsg_printf(error::ERROR, _("Bad policy item: user= %s object= %s action %s"), user_regex.c_str(), object_regex.c_str(), action.c_str());
137 throw std::exception();
138 }
139 }
140 return true;
141 }
142 catch (const std::exception &e)
143 {
144 /* On any non-EOF break, unparseable line */
145 errmsg_printf(error::ERROR, _("Unable to parse policy file %s:%s"), new_policy_file.c_str(), e.what());
146 return false;
147 }
148
149}
150
151static int init(module::Context &context)
152{
153 const module::option_map &vm= context.getOptions();
154
155 max_cache_buckets= vm["max-cache-buckets"].as<uint64_t>();
156 if (max_cache_buckets < 1)
157 {
158 errmsg_printf(error::ERROR, _("max-cache-buckets is too low, must be greater than 0"));
159 return 1;
160 }
161 max_lru_length= vm["max-lru-length"].as<uint64_t>();
162 if (max_lru_length < 1)
163 {
164 errmsg_printf(error::ERROR, _("max-lru-length is too low, must be greater than 0"));
165 return 1;
166 }
167 policy= new Policy(vm["policy"].as<string>());
168 if (!policy->setPolicyFile(policy->getPolicyFile()))
169 {
170 errmsg_printf(error::ERROR, _("Could not load regex policy file: %s\n"),
171 (policy ? policy->getError().str().c_str() : _("Unknown")));
172 delete policy;
173 return 1;
174 }
175 context.add(policy);
176 context.registerVariable(new sys_var_std_string("policy", policy->getPolicyFile(), NULL, &updatePolicyFile));
177
178 return 0;
179}
180
181static void init_options(drizzled::module::option_context &context)
182{
183 context("policy",
184 po::value<string>()->default_value(DEFAULT_POLICY_FILE.string()),
185 N_("File to load for regex authorization policies"));
186 context("max-cache-buckets",
187 po::value<uint64_t>()->default_value(DEFAULT_MAX_CACHE_BUCKETS),
188 N_("Maximum buckets for authorization cache"));
189 context("max-lru-length",
190 po::value<uint64_t>()->default_value(DEFAULT_MAX_LRU_LENGTH),
191 N_("Maximum number of LRU entries to track at once"));
192}
193
194void Policy::setPolicies(PolicyItemList new_table_policies, PolicyItemList new_schema_policies, PolicyItemList new_process_policies)
195{
196 policy->clearPolicies();
197
198 for (PolicyItemList::iterator it= new_table_policies.begin(); it!= new_table_policies.end(); it++)
199 table_policies.push_back(*it);
200
201 for (PolicyItemList::iterator it= new_schema_policies.begin(); it!= new_schema_policies.end(); it++)
202 schema_policies.push_back(*it);
203
204 for (PolicyItemList::iterator it= new_process_policies.begin(); it!= new_process_policies.end(); it++)
205 process_policies.push_back(*it);
206}
207
208std::string& Policy::getPolicyFile()
209{
210 return sysvar_policy_file;
211}
212
213bool Policy::setPolicyFile(std::string &new_policy_file)
214{
215 if (new_policy_file.empty())
216 {
217 errmsg_printf(error::ERROR, _("regex_policy file cannot be an empty string"));
218 return false; // error
219 }
220
221 PolicyItemList new_table_policies;
222 PolicyItemList new_schema_policies;
223 PolicyItemList new_process_policies;
224 if(parsePolicyFile(new_policy_file, new_table_policies, new_schema_policies, new_process_policies))
225 {
226 policy->setPolicies(new_table_policies, new_schema_policies, new_process_policies);
227 sysvar_policy_file= new_policy_file;
228 fs::path newPolicyFile(getPolicyFile());
229 policy_file= newPolicyFile;
230 return true; // success
231 }
232 return false; // error
233}
234
235static void clearPolicyItemList(PolicyItemList& policies)
236{
237 for (PolicyItem* x : policies)
238 {
239 delete x;
240 }
241}
242
243Policy::~Policy()
244{
245 clearPolicyItemList(table_policies);
246 clearPolicyItemList(process_policies);
247 clearPolicyItemList(schema_policies);
248}
249
250/*
251This function will be called when the policy file needs to be reloaded.
252This deletes all the policies stored and cached.
253*/
254void Policy::clearPolicies()
255{
256 table_policies.clear();
257 process_policies.clear();
258 schema_policies.clear();
259 table_check_cache.clear();
260 process_check_cache.clear();
261 schema_check_cache.clear();
262}
263
264
265bool Policy::restrictObject(const drizzled::identifier::User &user_ctx,
266 const string &obj, const PolicyItemList &policies,
267 CheckMap &check_cache)
268{
269 CheckItem c(user_ctx.username(), obj, check_cache);
270 if (!c.hasCachedResult())
271 {
272 PolicyItemList::const_iterator m= find_if(policies.begin(), policies.end(), c);
273 if (m != policies.end())
274 {
275 c.setCachedResult((*m)->isRestricted());
276 }
277 else
278 {
279 /* TODO: make default action configurable */
280 c.setCachedResult(false);
281 }
282 }
283 return c.getCachedResult();
284}
285
287 const drizzled::identifier::Schema& schema)
288{
289 return restrictObject(user_ctx, schema.getSchemaName(), schema_policies, schema_check_cache);
290}
291
293 const drizzled::identifier::User &session_ctx)
294{
295 return restrictObject(user_ctx, session_ctx.username(), process_policies, process_check_cache);
296}
297
299 const drizzled::identifier::Table& table)
300{
301 return restrictObject(user_ctx, table.getTableName(), table_policies, table_check_cache);
302}
303
304bool CheckItem::operator()(PolicyItem *p)
305{
306 if (p->userMatches(user))
307 {
308 errmsg_printf(error::INSPECT, _("User %s matches regex\n"), user.c_str());
309 if (p->objectMatches(object))
310 {
311 errmsg_printf(error::INSPECT, _("Object %s matches regex %s (%s)\n"),
312 object.c_str(),
313 p->getObject().c_str(),
314 p->getAction());
315 return true;
316 }
317 errmsg_printf(error::INSPECT, _("Object %s NOT restricted by regex %s (%s)\n"),
318 object.c_str(),
319 p->getObject().c_str(),
320 p->getAction());
321 }
322 return false;
323}
324
325CheckItem::CheckItem(const std::string &user_in, const std::string &obj_in, CheckMap &check_cache_in)
326 : user(user_in), object(obj_in), has_cached_result(false), check_cache(check_cache_in)
327{
328 key= user + "_" + object;
329
330 if (bool* check_val= check_cache.find(key))
331 {
332 /* It was in the cache, no need to do any more lookups */
333 cached_result= *check_val;
334 has_cached_result= true;
335 }
336}
337
338bool* CheckMap::find(std::string const &k)
339{
340 /* tack on to LRU list */
341 boost::mutex::scoped_lock lock(lru_mutex);
342 lru.push_back(k);
343 if (lru.size() > max_lru_length)
344 {
345 /* Fold all of the oldest entries into a single list at the front */
346 uint64_t size_halfway= lru.size() / 2;
347 LruList::iterator halfway= lru.begin();
348 halfway += size_halfway;
349 std::unordered_set<std::string> uniqs;
350 uniqs.insert(lru.begin(), halfway);
351
352 /* If we can save space, drop the oldest half */
353 if (size_halfway < uniqs.size())
354 {
355 lru.erase(lru.begin(), halfway);
356
357 /* Re-add set elements to front */
358 lru.insert(lru.begin(), uniqs.begin(), uniqs.end());
359 }
360 }
361 lock.unlock();
362 boost::shared_lock<boost::shared_mutex> map_lock(map_mutex);
363 return find_ptr(map, k);
364}
365
366void CheckMap::insert(std::string const &k, bool v)
367{
368 boost::unique_lock<boost::shared_mutex> map_lock(map_mutex);
369 /* add our new hotness to the map */
370 map[k]=v;
371 /* Now prune if necessary */
372 if (map.bucket_count() > max_cache_buckets)
373 {
374 /* Determine LRU key by running through the LRU list */
375 std::unordered_set<std::string> found;
376
377 /* Must unfortunately lock the LRU list while we traverse it */
378 boost::mutex::scoped_lock lock(lru_mutex);
379 for (LruList::reverse_iterator x= lru.rbegin(); x < lru.rend(); ++x)
380 {
381 if (found.find(*x) == found.end())
382 {
383 /* Newly found key */
384 if (found.size() >= max_cache_buckets)
385 {
386 /* Since found is already as big as the cache can be, anything else
387 is LRU */
388 map.erase(*x);
389 }
390 else
391 {
392 found.insert(*x);
393 }
394 }
395 }
396 if (map.bucket_count() > max_cache_buckets)
397 {
398 /* Still too big. */
399 if (lru.size())
400 {
401 /* Just delete the oldest item */
402 map.erase(*(lru.begin()));
403 }
404 else
405 {
406 /* Nothing to delete, warn */
407 errmsg_printf(error::WARN,
408 _("Unable to reduce size of cache below max buckets (current buckets=%" PRIu64 ")"),
409 static_cast<uint64_t>(map.bucket_count()));
410 }
411 }
412 lru.clear();
413 lock.unlock();
414 }
415}
416
417void CheckItem::setCachedResult(bool result)
418{
419 check_cache.insert(key, result);
420 has_cached_result= true;
421 cached_result= result;
422}
423
424} /* namespace regex_policy */
425
426DRIZZLE_DECLARE_PLUGIN
427{
428 DRIZZLE_VERSION_ID,
429 "regex_policy",
430 "2.1",
431 "Clint Byrum",
432 N_("Authorization using a regex-matched policy file"),
433 PLUGIN_LICENSE_GPL,
434 regex_policy::init,
435 NULL,
436 regex_policy::init_options
437}
438DRIZZLE_DECLARE_PLUGIN_END;
String str_value
Definition item.h:109
A set of Session members describing the current authenticated user.
virtual bool restrictSchema(const drizzled::identifier::User &user_ctx, const drizzled::identifier::Schema &schema)
virtual bool restrictTable(const drizzled::identifier::User &user_ctx, const drizzled::identifier::Table &table)
virtual bool restrictProcess(const drizzled::identifier::User &user_ctx, const drizzled::identifier::User &session_ctx)
TODO: Rename this file - func.h is stupid.
STL namespace.
An Proxy Wrapper around boost::program_options::variables_map.