-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathsqlite_string.cpp
More file actions
356 lines (312 loc) · 10.6 KB
/
Copy pathsqlite_string.cpp
File metadata and controls
356 lines (312 loc) · 10.6 KB
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
/**
* Copyright (c) 2014-present, The osquery authors
*
* This source code is licensed as defined by the LICENSE file found in the
* root directory of this source tree.
*
* SPDX-License-Identifier: (Apache-2.0 OR GPL-2.0-only)
*/
#include <assert.h>
#ifdef WIN32
#include <ws2tcpip.h>
#else
#include <arpa/inet.h>
#endif
#include <functional>
#include <regex>
#include <string>
#include <vector>
#include <osquery/core/flags.h>
#include <osquery/logger/logger.h>
#include <osquery/utils/conversions/split.h>
#include <sqlite3.h>
namespace osquery {
HIDDEN_FLAG(
uint32,
regex_max_size,
256,
"Defines the maximum size in bytes of a regex that can be used with the "
"regex_match and regex_split functions");
using SplitResult = std::vector<std::string>;
using StringSplitFunction = std::function<SplitResult(
const std::string& input, const std::string& tokens)>;
/**
* @brief A simple SQLite column string split implementation.
*
* Split a column value using a single token and select an expected index.
* If multiple characters are given to the token parameter, each is used to
* split, similar to boost::is_any_of.
*
* Example:
* 1. SELECT ip_address from addresses;
* 192.168.0.1
* 2. SELECT SPLIT(ip_address, ".", 1) from addresses;
* 168
* 3. SELECT SPLIT(ip_address, ".0", 0) from addresses;
* 192
*/
static SplitResult tokenSplit(const std::string& input,
const std::string& tokens) {
return osquery::split(input, tokens);
}
/**
* @brief A regex SQLite column string split implementation.
*
* Split a column value using a single or multi-character token and select an
* expected index. The token input is considered a regex.
*
* Example:
* 1. SELECT ip_address from addresses;
* 192.168.0.1
* 2. SELECT SPLIT(ip_address, "\.", 1) from addresses;
* 168
* 3. SELECT SPLIT(ip_address, "\.0", 0) from addresses;
* 192.168
*/
static SplitResult regexSplit(const std::string& input,
const std::string& token) {
// Split using the token as a regex to support multi-character tokens.
// Exceptions are caught by the caller, as that's where the sql context is
std::vector<std::string> result;
if (token.size() > FLAGS_regex_max_size) {
throw std::regex_error(std::regex_constants::error_complexity);
}
std::regex pattern = std::regex(token);
std::sregex_token_iterator iter_begin(
input.begin(), input.end(), pattern, -1);
std::sregex_token_iterator iter_end;
std::copy(iter_begin, iter_end, std::back_inserter(result));
return result;
}
static void callStringSplitFunc(sqlite3_context* context,
int argc,
sqlite3_value** argv,
StringSplitFunction f) {
assert(argc == 3);
if (SQLITE_NULL == sqlite3_value_type(argv[0]) ||
SQLITE_NULL == sqlite3_value_type(argv[1]) ||
SQLITE_NULL == sqlite3_value_type(argv[2])) {
sqlite3_result_null(context);
return;
}
// Parse and verify the split input parameters.
std::string input((char*)sqlite3_value_text(argv[0]));
std::string token((char*)sqlite3_value_text(argv[1]));
auto index = static_cast<size_t>(sqlite3_value_int(argv[2]));
if (token.empty()) {
// Empty input string is an error
sqlite3_result_error(context, "Invalid input to split function", -1);
return;
}
auto result = f(input, token);
if (index >= result.size()) {
// Could emit a warning about a selected index that is out of bounds.
sqlite3_result_null(context);
return;
}
// Yield the selected index.
const auto& selected = result[index];
sqlite3_result_text(context,
selected.c_str(),
static_cast<int>(selected.size()),
SQLITE_TRANSIENT);
}
static void tokenStringSplitFunc(sqlite3_context* context,
int argc,
sqlite3_value** argv) {
callStringSplitFunc(context, argc, argv, tokenSplit);
}
static void regexStringSplitFunc(sqlite3_context* context,
int argc,
sqlite3_value** argv) {
try {
callStringSplitFunc(context, argc, argv, regexSplit);
} catch (const std::regex_error& e) {
LOG(INFO) << "Invalid regex: " << e.what();
sqlite3_result_error(context, "Invalid regex", -1);
}
}
/**
* @brief Regex match a string
*/
static void regexStringMatchFunc(sqlite3_context* context,
int argc,
sqlite3_value** argv) {
// Ensure we have not-null values
assert(argc == 3);
if (SQLITE_NULL == sqlite3_value_type(argv[0]) ||
SQLITE_NULL == sqlite3_value_type(argv[1]) ||
SQLITE_NULL == sqlite3_value_type(argv[2])) {
sqlite3_result_null(context);
return;
}
const char* regex =
reinterpret_cast<const char*>(sqlite3_value_text(argv[1]));
if (regex == nullptr) {
sqlite3_result_null(context);
return;
}
// parse and verify input parameters
const std::string input(
reinterpret_cast<const char*>(sqlite3_value_text(argv[0])));
std::smatch results;
auto index = static_cast<size_t>(sqlite3_value_int(argv[2]));
bool isMatchFound = false;
if (strnlen(regex, FLAGS_regex_max_size) == FLAGS_regex_max_size &&
regex[FLAGS_regex_max_size] != '\0') {
std::string error = "Invalid regex: too big, max size is " +
std::to_string(FLAGS_regex_max_size) + " bytes";
LOG(INFO) << error;
sqlite3_result_error(context, error.c_str(), -1);
return;
}
try {
isMatchFound = std::regex_search(input, results, std::regex(regex));
} catch (const std::regex_error& e) {
LOG(INFO) << "Invalid regex: " << e.what();
sqlite3_result_error(context, "Invalid regex", -1);
return;
}
if (!isMatchFound) {
sqlite3_result_null(context);
return;
}
if (index >= results.size()) {
sqlite3_result_null(context);
return;
}
sqlite3_result_text(context,
results[index].str().c_str(),
static_cast<int>(results[index].str().size()),
SQLITE_TRANSIENT);
}
static void concatFunc(sqlite3_context* context,
std::string sep,
int starting,
int argc,
sqlite3_value** argv) {
// Nothing to concat, early return
if ((argc - starting) == 0) {
return;
}
std::string output;
for (auto i = starting; i < argc; i++) {
if (SQLITE_NULL == sqlite3_value_type(argv[i])) {
continue;
}
output.append(reinterpret_cast<const char*>(sqlite3_value_text(argv[i])));
if (sep != "" && i + 1 < argc) {
output.append(sep);
}
}
// Give up if the output is so large it's length overflows int
if (output.size() > std::numeric_limits<int>::max()) {
sqlite3_result_error(context, "Too much data for concat_ws", -1);
return;
}
sqlite3_result_text(context,
output.c_str(),
static_cast<int>(output.size()),
SQLITE_TRANSIENT);
}
/**
* @brief Concatenate strings ignoring nulls
*/
static void concatStringFunc(sqlite3_context* context,
int argc,
sqlite3_value** argv) {
concatFunc(context, "", 0, argc, argv);
}
/**
* @brief Concatenate strings ignoring nulls, with separator
*/
static void concatWSStringFunc(sqlite3_context* context,
int argc,
sqlite3_value** argv) {
// First arg is the separator. Error if not present
if (argc == 0) {
sqlite3_result_error(context, "Missing separator to concat_ws", -1);
return;
}
const std::string sep =
(SQLITE_NULL != sqlite3_value_type(argv[0]))
? reinterpret_cast<const char*>(sqlite3_value_text(argv[0]))
: "";
concatFunc(context, sep, 1, argc, argv);
}
/**
* @brief Convert an IPv4 string address to decimal.
*/
static void ip4StringToDecimalFunc(sqlite3_context* context,
int argc,
sqlite3_value** argv) {
assert(argc == 1);
if (SQLITE_NULL == sqlite3_value_type(argv[0])) {
sqlite3_result_null(context);
return;
}
struct sockaddr sa;
std::string address((char*)sqlite3_value_text(argv[0]));
if (address.find(':') != std::string::npos) {
// Assume this is an IPv6 address.
sqlite3_result_null(context);
} else {
auto in4 = (struct sockaddr_in*)&sa;
if (inet_pton(AF_INET, address.c_str(), &(in4->sin_addr)) == 1) {
sqlite3_result_int64(context, ntohl(in4->sin_addr.s_addr));
} else {
sqlite3_result_null(context);
}
}
}
void registerStringExtensions(sqlite3* db) {
sqlite3_create_function(db,
"split",
3,
SQLITE_UTF8 | SQLITE_DETERMINISTIC,
nullptr,
tokenStringSplitFunc,
nullptr,
nullptr);
sqlite3_create_function(db,
"regex_split",
3,
SQLITE_UTF8 | SQLITE_DETERMINISTIC,
nullptr,
regexStringSplitFunc,
nullptr,
nullptr);
sqlite3_create_function(db,
"inet_aton",
1,
SQLITE_UTF8 | SQLITE_DETERMINISTIC,
nullptr,
ip4StringToDecimalFunc,
nullptr,
nullptr);
sqlite3_create_function(db,
"regex_match",
3,
SQLITE_UTF8 | SQLITE_DETERMINISTIC,
nullptr,
regexStringMatchFunc,
nullptr,
nullptr);
sqlite3_create_function(db,
"concat",
-1,
SQLITE_UTF8 | SQLITE_DETERMINISTIC,
nullptr,
concatStringFunc,
nullptr,
nullptr);
sqlite3_create_function(db,
"concat_ws",
-1,
SQLITE_UTF8 | SQLITE_DETERMINISTIC,
nullptr,
concatWSStringFunc,
nullptr,
nullptr);
}
} // namespace osquery