res_pjsip_endpoint_identifier_ip: Fix parsing of match value with CIDR
[asterisk/asterisk.git] / res / res_pjsip_endpoint_identifier_ip.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, Digium, Inc.
5  *
6  * Mark Michelson <mmichelson@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*** MODULEINFO
20         <depend>pjproject</depend>
21         <depend>res_pjsip</depend>
22         <support_level>core</support_level>
23  ***/
24
25 #include "asterisk.h"
26
27 #include <pjsip.h>
28
29 #include "asterisk/res_pjsip.h"
30 #include "asterisk/res_pjsip_cli.h"
31 #include "asterisk/module.h"
32 #include "asterisk/acl.h"
33 #include "asterisk/manager.h"
34 #include "res_pjsip/include/res_pjsip_private.h"
35
36 /*** DOCUMENTATION
37         <configInfo name="res_pjsip_endpoint_identifier_ip" language="en_US">
38                 <synopsis>Module that identifies endpoints via source IP address</synopsis>
39                 <configFile name="pjsip.conf">
40                         <configObject name="identify">
41                                 <synopsis>Identifies endpoints via source IP address</synopsis>
42                                 <configOption name="endpoint">
43                                         <synopsis>Name of Endpoint</synopsis>
44                                 </configOption>
45                                 <configOption name="match">
46                                         <synopsis>IP addresses or networks to match against</synopsis>
47                                         <description><para>
48                                                 The value is a comma-delimited list of IP addresses. IP addresses may
49                                                 have a subnet mask appended. The subnet mask may be written in either
50                                                 CIDR or dot-decimal notation. Separate the IP address and subnet
51                                                 mask with a slash ('/')
52                                         </para></description>
53                                 </configOption>
54                                 <configOption name="type">
55                                         <synopsis>Must be of type 'identify'.</synopsis>
56                                 </configOption>
57                         </configObject>
58                 </configFile>
59         </configInfo>
60  ***/
61
62 /*! \brief Structure for an IP identification matching object */
63 struct ip_identify_match {
64         /*! \brief Sorcery object details */
65         SORCERY_OBJECT(details);
66         /*! \brief Stringfields */
67         AST_DECLARE_STRING_FIELDS(
68                 /*! The name of the endpoint */
69                 AST_STRING_FIELD(endpoint_name);
70         );
71         /*! \brief Networks or addresses that should match this */
72         struct ast_ha *matches;
73 };
74
75 /*! \brief Destructor function for a matching object */
76 static void ip_identify_destroy(void *obj)
77 {
78         struct ip_identify_match *identify = obj;
79
80         ast_string_field_free_memory(identify);
81         ast_free_ha(identify->matches);
82 }
83
84 /*! \brief Allocator function for a matching object */
85 static void *ip_identify_alloc(const char *name)
86 {
87         struct ip_identify_match *identify = ast_sorcery_generic_alloc(sizeof(*identify), ip_identify_destroy);
88
89         if (!identify || ast_string_field_init(identify, 256)) {
90                 ao2_cleanup(identify);
91                 return NULL;
92         }
93
94         return identify;
95 }
96
97 /*! \brief Comparator function for a matching object */
98 static int ip_identify_match_check(void *obj, void *arg, int flags)
99 {
100         struct ip_identify_match *identify = obj;
101         struct ast_sockaddr *addr = arg;
102         int sense;
103
104         sense = ast_apply_ha(identify->matches, addr);
105         if (sense != AST_SENSE_ALLOW) {
106                 ast_debug(3, "Source address %s matches identify '%s'\n",
107                                 ast_sockaddr_stringify(addr),
108                                 ast_sorcery_object_get_id(identify));
109                 return CMP_MATCH | CMP_STOP;
110         } else {
111                 ast_debug(3, "Source address %s does not match identify '%s'\n",
112                                 ast_sockaddr_stringify(addr),
113                                 ast_sorcery_object_get_id(identify));
114                 return 0;
115         }
116 }
117
118 static struct ast_sip_endpoint *ip_identify(pjsip_rx_data *rdata)
119 {
120         struct ast_sockaddr addr = { { 0, } };
121         RAII_VAR(struct ao2_container *, candidates, NULL, ao2_cleanup);
122         RAII_VAR(struct ip_identify_match *, match, NULL, ao2_cleanup);
123         struct ast_sip_endpoint *endpoint;
124
125         /* If no possibilities exist return early to save some time */
126         if (!(candidates = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "identify", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL)) ||
127                 !ao2_container_count(candidates)) {
128                 ast_debug(3, "No identify sections to match against\n");
129                 return NULL;
130         }
131
132         ast_sockaddr_parse(&addr, rdata->pkt_info.src_name, PARSE_PORT_FORBID);
133         ast_sockaddr_set_port(&addr, rdata->pkt_info.src_port);
134
135         if (!(match = ao2_callback(candidates, 0, ip_identify_match_check, &addr))) {
136                 ast_debug(3, "'%s' did not match any identify section rules\n",
137                                 ast_sockaddr_stringify(&addr));
138                 return NULL;
139         }
140
141         endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", match->endpoint_name);
142         if (endpoint) {
143                 ast_debug(3, "Retrieved endpoint %s\n", ast_sorcery_object_get_id(endpoint));
144         } else {
145                 ast_log(LOG_WARNING, "Identify section '%s' points to endpoint '%s' but endpoint could not be looked up\n",
146                                 ast_sorcery_object_get_id(match), match->endpoint_name);
147         }
148
149         return endpoint;
150 }
151
152 static struct ast_sip_endpoint_identifier ip_identifier = {
153         .identify_endpoint = ip_identify,
154 };
155
156 /*! \brief Custom handler for match field */
157 static int ip_identify_match_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
158 {
159         struct ip_identify_match *identify = obj;
160         char *input_string = ast_strdupa(var->value);
161         char *current_string;
162
163         while ((current_string = strsep(&input_string, ","))) {
164                 struct ast_sockaddr *addrs;
165                 int num_addrs = 0, error = 0, i;
166                 char *mask = strrchr(current_string, '/');
167
168                 if (mask) {
169                         identify->matches = ast_append_ha("d", current_string, identify->matches, &error);
170
171                         if (!identify->matches || error) {
172                                 ast_log(LOG_ERROR, "Failed to add address '%s' to ip endpoint identifier '%s'\n",
173                                         current_string, ast_sorcery_object_get_id(obj));
174                                 return -1;
175                         }
176
177                         continue;
178                 }
179
180                 num_addrs = ast_sockaddr_resolve(&addrs, current_string, PARSE_PORT_FORBID, AST_AF_UNSPEC);
181                 if (!num_addrs) {
182                         ast_log(LOG_ERROR, "Address '%s' provided on ip endpoint identifier '%s' did not resolve to any address\n",
183                                 var->value, ast_sorcery_object_get_id(obj));
184                         return -1;
185                 }
186
187                 for (i = 0; i < num_addrs; ++i) {
188                         /* We deny what we actually want to match because there is an implicit permit all rule for ACLs */
189                         identify->matches = ast_append_ha("d", ast_sockaddr_stringify_addr(&addrs[i]), identify->matches, &error);
190
191                         if (!identify->matches || error) {
192                                 ast_log(LOG_ERROR, "Failed to add address '%s' to ip endpoint identifier '%s'\n",
193                                         ast_sockaddr_stringify_addr(&addrs[i]), ast_sorcery_object_get_id(obj));
194                                 error = -1;
195                                 break;
196                         }
197                 }
198
199                 ast_free(addrs);
200
201                 if (error) {
202                         return -1;
203                 }
204         }
205
206         return 0;
207 }
208
209
210 static int match_to_str(const void *obj, const intptr_t *args, char **buf)
211 {
212         RAII_VAR(struct ast_str *, str, ast_str_create(MAX_OBJECT_FIELD), ast_free);
213         const struct ip_identify_match *identify = obj;
214
215         ast_ha_join(identify->matches, &str);
216         *buf = ast_strdup(ast_str_buffer(str));
217         return 0;
218 }
219
220 static int match_to_var_list(const void *obj, struct ast_variable **fields)
221 {
222         char str[MAX_OBJECT_FIELD];
223         const struct ip_identify_match *identify = obj;
224         struct ast_variable *head = NULL;
225         struct ast_ha *ha = identify->matches;
226
227         for (; ha; ha = ha->next) {
228                 const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&ha->addr));
229                 snprintf(str, MAX_OBJECT_FIELD, "%s%s/%s", ha->sense == AST_SENSE_ALLOW ? "!" : "",
230                         addr, ast_sockaddr_stringify_addr(&ha->netmask));
231
232                 ast_variable_list_append(&head, ast_variable_new("match", str, ""));
233
234         }
235
236         if (head) {
237                 *fields = head;
238         }
239
240         return 0;
241 }
242
243 static int sip_identify_to_ami(const struct ip_identify_match *identify,
244                                struct ast_str **buf)
245 {
246         return ast_sip_sorcery_object_to_ami(identify, buf);
247 }
248
249 static int find_identify_by_endpoint(void *obj, void *arg, int flags)
250 {
251         struct ip_identify_match *identify = obj;
252         const char *endpoint_name = arg;
253
254         return strcmp(identify->endpoint_name, endpoint_name) ? 0 : CMP_MATCH;
255 }
256
257 static int format_ami_endpoint_identify(const struct ast_sip_endpoint *endpoint,
258                                         struct ast_sip_ami *ami)
259 {
260         RAII_VAR(struct ao2_container *, identifies, NULL, ao2_cleanup);
261         RAII_VAR(struct ip_identify_match *, identify, NULL, ao2_cleanup);
262         RAII_VAR(struct ast_str *, buf, NULL, ast_free);
263
264         identifies = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "identify",
265                 AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
266         if (!identifies) {
267                 return -1;
268         }
269
270         identify = ao2_callback(identifies, 0, find_identify_by_endpoint,
271                 (void *) ast_sorcery_object_get_id(endpoint));
272         if (!identify) {
273                 return 1;
274         }
275
276         if (!(buf = ast_sip_create_ami_event("IdentifyDetail", ami))) {
277                 return -1;
278         }
279
280         if (sip_identify_to_ami(identify, &buf)) {
281                 return -1;
282         }
283
284         ast_str_append(&buf, 0, "EndpointName: %s\r\n",
285                 ast_sorcery_object_get_id(endpoint));
286
287         astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
288         ami->count++;
289
290         return 0;
291 }
292
293 struct ast_sip_endpoint_formatter endpoint_identify_formatter = {
294         .format_ami = format_ami_endpoint_identify
295 };
296
297 static int cli_populate_container(void *obj, void *arg, int flags)
298 {
299         ao2_link(arg, obj);
300
301         return 0;
302 }
303
304 static int cli_iterator(void *container, ao2_callback_fn callback, void *args)
305 {
306         const struct ast_sip_endpoint *endpoint = container;
307         struct ao2_container *identifies;
308
309         struct ast_variable fields = {
310                 .name = "endpoint",
311                 .value = ast_sorcery_object_get_id(endpoint),
312                 .next = NULL,
313         };
314
315         identifies = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "identify",
316                 AST_RETRIEVE_FLAG_MULTIPLE, &fields);
317         if (!identifies) {
318                 return -1;
319         }
320
321         ao2_callback(identifies, OBJ_NODATA, callback, args);
322
323         return 0;
324 }
325
326 static int cli_endpoint_gather_identifies(void *obj, void *arg, int flags)
327 {
328         struct ast_sip_endpoint *endpoint = obj;
329         struct ao2_container *container = arg;
330
331         cli_iterator(endpoint, cli_populate_container, container);
332
333         return 0;
334 }
335
336 static struct ao2_container *cli_get_container(void)
337 {
338         RAII_VAR(struct ao2_container *, parent_container, NULL, ao2_cleanup);
339         RAII_VAR(struct ao2_container *, s_parent_container, NULL, ao2_cleanup);
340         struct ao2_container *child_container;
341
342         parent_container =  ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "endpoint",
343                 AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
344         if (!parent_container) {
345                 return NULL;
346         }
347
348         s_parent_container = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
349                 ast_sorcery_object_id_sort, ast_sorcery_object_id_compare);
350         if (!s_parent_container) {
351                 return NULL;
352         }
353
354         if (ao2_container_dup(s_parent_container, parent_container, 0)) {
355                 return NULL;
356         }
357
358         child_container = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
359                 ast_sorcery_object_id_sort, ast_sorcery_object_id_compare);
360         if (!child_container) {
361                 return NULL;
362         }
363
364         ao2_callback(s_parent_container, OBJ_NODATA, cli_endpoint_gather_identifies, child_container);
365
366         return child_container;
367 }
368
369 static void *cli_retrieve_by_id(const char *id)
370 {
371         return ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "identify", id);
372 }
373
374 static int cli_print_header(void *obj, void *arg, int flags)
375 {
376         struct ast_sip_cli_context *context = arg;
377         int indent = CLI_INDENT_TO_SPACES(context->indent_level);
378         int filler = CLI_MAX_WIDTH - indent - 14;
379
380         ast_assert(context->output_buffer != NULL);
381
382         ast_str_append(&context->output_buffer, 0,
383                 "%*s:  <MatchList%*.*s>\n",
384                 indent, "Identify", filler, filler, CLI_HEADER_FILLER);
385
386         return 0;
387 }
388
389 static int cli_print_body(void *obj, void *arg, int flags)
390 {
391         RAII_VAR(struct ast_str *, str, ast_str_create(MAX_OBJECT_FIELD), ast_free);
392         struct ip_identify_match *ident = obj;
393         struct ast_sip_cli_context *context = arg;
394
395         ast_assert(context->output_buffer != NULL);
396
397         ast_str_append(&context->output_buffer, 0, "%*s:  ",
398                 CLI_INDENT_TO_SPACES(context->indent_level), "Identify");
399         ast_ha_join_cidr(ident->matches, &str);
400         ast_str_append(&context->output_buffer, 0, "%s\n", ast_str_buffer(str));
401
402         return 0;
403 }
404
405 static struct ast_sip_cli_formatter_entry *cli_formatter;
406
407 static int load_module(void)
408 {
409         ast_sorcery_apply_config(ast_sip_get_sorcery(), "res_pjsip_endpoint_identifier_ip");
410         ast_sorcery_apply_default(ast_sip_get_sorcery(), "identify", "config", "pjsip.conf,criteria=type=identify");
411
412         if (ast_sorcery_object_register(ast_sip_get_sorcery(), "identify", ip_identify_alloc, NULL, NULL)) {
413                 return AST_MODULE_LOAD_DECLINE;
414         }
415
416         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "identify", "type", "", OPT_NOOP_T, 0, 0);
417         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "identify", "endpoint", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ip_identify_match, endpoint_name));
418         ast_sorcery_object_field_register_custom(ast_sip_get_sorcery(), "identify", "match", "", ip_identify_match_handler, match_to_str, match_to_var_list, 0, 0);
419         ast_sorcery_reload_object(ast_sip_get_sorcery(), "identify");
420
421         ast_sip_register_endpoint_identifier(&ip_identifier);
422         ast_sip_register_endpoint_formatter(&endpoint_identify_formatter);
423
424         cli_formatter = ao2_alloc(sizeof(struct ast_sip_cli_formatter_entry), NULL);
425         if (!cli_formatter) {
426                 ast_log(LOG_ERROR, "Unable to allocate memory for cli formatter\n");
427                 return -1;
428         }
429         cli_formatter->name = "identify";
430         cli_formatter->print_header = cli_print_header;
431         cli_formatter->print_body = cli_print_body;
432         cli_formatter->get_container = cli_get_container;
433         cli_formatter->iterate = cli_iterator;
434         cli_formatter->get_id = ast_sorcery_object_get_id;
435         cli_formatter->retrieve_by_id = cli_retrieve_by_id;
436
437         ast_sip_register_cli_formatter(cli_formatter);
438
439         return AST_MODULE_LOAD_SUCCESS;
440 }
441
442 static int reload_module(void)
443 {
444         ast_sorcery_reload_object(ast_sip_get_sorcery(), "identify");
445
446         return 0;
447 }
448
449 static int unload_module(void)
450 {
451         ast_sip_unregister_cli_formatter(cli_formatter);
452         ast_sip_unregister_endpoint_formatter(&endpoint_identify_formatter);
453         ast_sip_unregister_endpoint_identifier(&ip_identifier);
454
455         return 0;
456 }
457
458 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP IP endpoint identifier",
459                 .support_level = AST_MODULE_SUPPORT_CORE,
460                 .load = load_module,
461                 .reload = reload_module,
462                 .unload = unload_module,
463                 .load_pri = AST_MODPRI_APP_DEPEND,
464                );