xref: /freebsd/sys/netpfil/ipfw/ip_fw_eaction.c (revision dd41de95a84d979615a2ef11df6850622bf6184e)
1 /*-
2  * Copyright (c) 2016-2017 Yandex LLC
3  * Copyright (c) 2016-2017 Andrey V. Elsukov <ae@FreeBSD.org>
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/malloc.h>
33 #include <sys/kernel.h>
34 #include <sys/hash.h>
35 #include <sys/lock.h>
36 #include <sys/rwlock.h>
37 #include <sys/rmlock.h>
38 #include <sys/socket.h>
39 #include <sys/socketvar.h>
40 #include <sys/queue.h>
41 
42 #include <net/if.h>	/* ip_fw.h requires IFNAMSIZ */
43 #include <net/pfil.h>
44 #include <netinet/in.h>
45 #include <netinet/ip_var.h>	/* struct ipfw_rule_ref */
46 #include <netinet/ip_fw.h>
47 
48 #include <netpfil/ipfw/ip_fw_private.h>
49 
50 #include "opt_ipfw.h"
51 
52 /*
53  * External actions support for ipfw.
54  *
55  * This code provides KPI for implementing loadable modules, that
56  * can provide handlers for external action opcodes in the ipfw's
57  * rules.
58  * Module should implement opcode handler with type ipfw_eaction_t.
59  * This handler will be called by ipfw_chk() function when
60  * O_EXTERNAL_ACTION opcode is matched. The handler must return
61  * value used as return value in ipfw_chk(), i.e. IP_FW_PASS,
62  * IP_FW_DENY (see ip_fw_private.h).
63  * Also the last argument must be set by handler. If it is zero,
64  * the search continues to the next rule. If it has non zero value,
65  * the search terminates.
66  *
67  * The module that implements external action should register its
68  * handler and name with ipfw_add_eaction() function.
69  * This function will return eaction_id, that can be used by module.
70  *
71  * It is possible to pass some additional information to external
72  * action handler using O_EXTERNAL_INSTANCE and O_EXTERNAL_DATA opcodes.
73  * Such opcodes should be next after the O_EXTERNAL_ACTION opcode.
74  * For the O_EXTERNAL_INSTANCE opcode the cmd->arg1 contains index of named
75  * object related to an instance of external action.
76  * For the O_EXTERNAL_DATA opcode the cmd contains the data that can be used
77  * by external action handler without needing to create named instance.
78  *
79  * In case when eaction module uses named instances, it should register
80  * opcode rewriting routines for O_EXTERNAL_INSTANCE opcode. The
81  * classifier callback can look back into O_EXTERNAL_ACTION opcode (it
82  * must be in the (ipfw_insn *)(cmd - 1)). By arg1 from O_EXTERNAL_ACTION
83  * it can deteremine eaction_id and compare it with its own.
84  * The macro IPFW_TLV_EACTION_NAME(eaction_id) can be used to deteremine
85  * the type of named_object related to external action instance.
86  *
87  * On module unload handler should be deregistered with ipfw_del_eaction()
88  * function using known eaction_id.
89  */
90 
91 struct eaction_obj {
92 	struct named_object	no;
93 	ipfw_eaction_t		*handler;
94 	char			name[64];
95 };
96 
97 #define	EACTION_OBJ(ch, cmd)			\
98     ((struct eaction_obj *)SRV_OBJECT((ch), (cmd)->arg1))
99 
100 #if 0
101 #define	EACTION_DEBUG(fmt, ...)	do {			\
102 	printf("%s: " fmt "\n", __func__, ## __VA_ARGS__);	\
103 } while (0)
104 #else
105 #define	EACTION_DEBUG(fmt, ...)
106 #endif
107 
108 const char *default_eaction_typename = "drop";
109 static int
110 default_eaction(struct ip_fw_chain *ch, struct ip_fw_args *args,
111     ipfw_insn *cmd, int *done)
112 {
113 
114 	*done = 1; /* terminate the search */
115 	return (IP_FW_DENY);
116 }
117 
118 /*
119  * Opcode rewriting callbacks.
120  */
121 static int
122 eaction_classify(ipfw_insn *cmd, uint16_t *puidx, uint8_t *ptype)
123 {
124 
125 	EACTION_DEBUG("opcode %d, arg1 %d", cmd->opcode, cmd->arg1);
126 	*puidx = cmd->arg1;
127 	*ptype = 0;
128 	return (0);
129 }
130 
131 static void
132 eaction_update(ipfw_insn *cmd, uint16_t idx)
133 {
134 
135 	cmd->arg1 = idx;
136 	EACTION_DEBUG("opcode %d, arg1 -> %d", cmd->opcode, cmd->arg1);
137 }
138 
139 static int
140 eaction_findbyname(struct ip_fw_chain *ch, struct tid_info *ti,
141     struct named_object **pno)
142 {
143 	ipfw_obj_ntlv *ntlv;
144 
145 	if (ti->tlvs == NULL)
146 		return (EINVAL);
147 
148 	/* Search ntlv in the buffer provided by user */
149 	ntlv = ipfw_find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx,
150 	    IPFW_TLV_EACTION);
151 	if (ntlv == NULL)
152 		return (EINVAL);
153 	EACTION_DEBUG("name %s, uidx %u, type %u", ntlv->name,
154 	    ti->uidx, ti->type);
155 	/*
156 	 * Search named object with corresponding name.
157 	 * Since eaction objects are global - ignore the set value
158 	 * and use zero instead.
159 	 */
160 	*pno = ipfw_objhash_lookup_name_type(CHAIN_TO_SRV(ch),
161 	    0, IPFW_TLV_EACTION, ntlv->name);
162 	if (*pno == NULL)
163 		return (ESRCH);
164 	return (0);
165 }
166 
167 static struct named_object *
168 eaction_findbykidx(struct ip_fw_chain *ch, uint16_t idx)
169 {
170 
171 	EACTION_DEBUG("kidx %u", idx);
172 	return (ipfw_objhash_lookup_kidx(CHAIN_TO_SRV(ch), idx));
173 }
174 
175 static struct opcode_obj_rewrite eaction_opcodes[] = {
176 	{
177 		.opcode = O_EXTERNAL_ACTION,
178 		.etlv = IPFW_TLV_EACTION,
179 		.classifier = eaction_classify,
180 		.update = eaction_update,
181 		.find_byname = eaction_findbyname,
182 		.find_bykidx = eaction_findbykidx,
183 	},
184 };
185 
186 static int
187 create_eaction_obj(struct ip_fw_chain *ch, ipfw_eaction_t handler,
188     const char *name, uint16_t *eaction_id)
189 {
190 	struct namedobj_instance *ni;
191 	struct eaction_obj *obj;
192 
193 	IPFW_UH_UNLOCK_ASSERT(ch);
194 
195 	ni = CHAIN_TO_SRV(ch);
196 	obj = malloc(sizeof(*obj), M_IPFW, M_WAITOK | M_ZERO);
197 	obj->no.name = obj->name;
198 	obj->no.etlv = IPFW_TLV_EACTION;
199 	obj->handler = handler;
200 	strlcpy(obj->name, name, sizeof(obj->name));
201 
202 	IPFW_UH_WLOCK(ch);
203 	if (ipfw_objhash_lookup_name_type(ni, 0, IPFW_TLV_EACTION,
204 	    name) != NULL) {
205 		/*
206 		 * Object is already created.
207 		 * We don't allow eactions with the same name.
208 		 */
209 		IPFW_UH_WUNLOCK(ch);
210 		free(obj, M_IPFW);
211 		EACTION_DEBUG("External action with typename "
212 		    "'%s' already exists", name);
213 		return (EEXIST);
214 	}
215 	if (ipfw_objhash_alloc_idx(ni, &obj->no.kidx) != 0) {
216 		IPFW_UH_WUNLOCK(ch);
217 		free(obj, M_IPFW);
218 		EACTION_DEBUG("alloc_idx failed");
219 		return (ENOSPC);
220 	}
221 	ipfw_objhash_add(ni, &obj->no);
222 	IPFW_WLOCK(ch);
223 	SRV_OBJECT(ch, obj->no.kidx) = obj;
224 	IPFW_WUNLOCK(ch);
225 	obj->no.refcnt++;
226 	IPFW_UH_WUNLOCK(ch);
227 
228 	if (eaction_id != NULL)
229 		*eaction_id = obj->no.kidx;
230 	return (0);
231 }
232 
233 static void
234 destroy_eaction_obj(struct ip_fw_chain *ch, struct named_object *no)
235 {
236 	struct namedobj_instance *ni;
237 	struct eaction_obj *obj;
238 
239 	IPFW_UH_WLOCK_ASSERT(ch);
240 
241 	ni = CHAIN_TO_SRV(ch);
242 	IPFW_WLOCK(ch);
243 	obj = SRV_OBJECT(ch, no->kidx);
244 	SRV_OBJECT(ch, no->kidx) = NULL;
245 	IPFW_WUNLOCK(ch);
246 	ipfw_objhash_del(ni, no);
247 	ipfw_objhash_free_idx(ni, no->kidx);
248 	free(obj, M_IPFW);
249 }
250 
251 /*
252  * Resets all eaction opcodes to default handlers.
253  */
254 static void
255 reset_eaction_rules(struct ip_fw_chain *ch, uint16_t eaction_id,
256     uint16_t instance_id, bool reset_rules)
257 {
258 	struct named_object *no;
259 	int i;
260 
261 	IPFW_UH_WLOCK_ASSERT(ch);
262 
263 	no = ipfw_objhash_lookup_name_type(CHAIN_TO_SRV(ch), 0,
264 	    IPFW_TLV_EACTION, default_eaction_typename);
265 	if (no == NULL)
266 		panic("Default external action handler is not found");
267 	if (eaction_id == no->kidx)
268 		panic("Wrong eaction_id");
269 
270 	EACTION_DEBUG("Going to replace id %u with %u", eaction_id, no->kidx);
271 	IPFW_WLOCK(ch);
272 	/*
273 	 * Reset eaction objects only if it is referenced by rules.
274 	 * But always reset objects for orphaned dynamic states.
275 	 */
276 	if (reset_rules) {
277 		for (i = 0; i < ch->n_rules; i++) {
278 			/*
279 			 * Refcount on the original object will be just
280 			 * ignored on destroy. Refcount on default_eaction
281 			 * will be decremented on rule deletion, thus we
282 			 * need to reference default_eaction object.
283 			 */
284 			if (ipfw_reset_eaction(ch, ch->map[i], eaction_id,
285 			    no->kidx, instance_id) != 0)
286 				no->refcnt++;
287 		}
288 	}
289 	/*
290 	 * Reset eaction opcodes for orphaned dynamic states.
291 	 * Since parent rules are already deleted, we don't need to
292 	 * reference named object of default_eaction.
293 	 */
294 	ipfw_dyn_reset_eaction(ch, eaction_id, no->kidx, instance_id);
295 	IPFW_WUNLOCK(ch);
296 }
297 
298 /*
299  * Initialize external actions framework.
300  * Create object with default eaction handler "drop".
301  */
302 int
303 ipfw_eaction_init(struct ip_fw_chain *ch, int first)
304 {
305 	int error;
306 
307 	error = create_eaction_obj(ch, default_eaction,
308 	    default_eaction_typename, NULL);
309 	if (error != 0)
310 		return (error);
311 	IPFW_ADD_OBJ_REWRITER(first, eaction_opcodes);
312 	EACTION_DEBUG("External actions support initialized");
313 	return (0);
314 }
315 
316 void
317 ipfw_eaction_uninit(struct ip_fw_chain *ch, int last)
318 {
319 	struct namedobj_instance *ni;
320 	struct named_object *no;
321 
322 	ni = CHAIN_TO_SRV(ch);
323 
324 	IPFW_UH_WLOCK(ch);
325 	no = ipfw_objhash_lookup_name_type(ni, 0, IPFW_TLV_EACTION,
326 	    default_eaction_typename);
327 	if (no != NULL)
328 		destroy_eaction_obj(ch, no);
329 	IPFW_UH_WUNLOCK(ch);
330 	IPFW_DEL_OBJ_REWRITER(last, eaction_opcodes);
331 	EACTION_DEBUG("External actions support uninitialized");
332 }
333 
334 /*
335  * Registers external action handler to the global array.
336  * On success it returns eaction id, otherwise - zero.
337  */
338 uint16_t
339 ipfw_add_eaction(struct ip_fw_chain *ch, ipfw_eaction_t handler,
340     const char *name)
341 {
342 	uint16_t eaction_id;
343 
344 	eaction_id = 0;
345 	if (ipfw_check_object_name_generic(name) == 0) {
346 		create_eaction_obj(ch, handler, name, &eaction_id);
347 		EACTION_DEBUG("Registered external action '%s' with id %u",
348 		    name, eaction_id);
349 	}
350 	return (eaction_id);
351 }
352 
353 /*
354  * Deregisters external action handler with id eaction_id.
355  */
356 int
357 ipfw_del_eaction(struct ip_fw_chain *ch, uint16_t eaction_id)
358 {
359 	struct named_object *no;
360 
361 	IPFW_UH_WLOCK(ch);
362 	no = ipfw_objhash_lookup_kidx(CHAIN_TO_SRV(ch), eaction_id);
363 	if (no == NULL || no->etlv != IPFW_TLV_EACTION) {
364 		IPFW_UH_WUNLOCK(ch);
365 		return (EINVAL);
366 	}
367 	reset_eaction_rules(ch, eaction_id, 0, (no->refcnt > 1));
368 	EACTION_DEBUG("External action '%s' with id %u unregistered",
369 	    no->name, eaction_id);
370 	destroy_eaction_obj(ch, no);
371 	IPFW_UH_WUNLOCK(ch);
372 	return (0);
373 }
374 
375 int
376 ipfw_reset_eaction(struct ip_fw_chain *ch, struct ip_fw *rule,
377     uint16_t eaction_id, uint16_t default_id, uint16_t instance_id)
378 {
379 	ipfw_insn *cmd, *icmd;
380 	int l;
381 
382 	IPFW_UH_WLOCK_ASSERT(ch);
383 	IPFW_WLOCK_ASSERT(ch);
384 
385 	/*
386 	 * Return if there is not O_EXTERNAL_ACTION or its id is
387 	 * different.
388 	 */
389 	cmd = ipfw_get_action(rule);
390 	if (cmd->opcode != O_EXTERNAL_ACTION ||
391 	    cmd->arg1 != eaction_id)
392 		return (0);
393 	/*
394 	 * Check if there is O_EXTERNAL_INSTANCE opcode, we need
395 	 * to truncate the rule length.
396 	 *
397 	 * NOTE: F_LEN(cmd) must be 1 for O_EXTERNAL_ACTION opcode,
398 	 *  and rule length should be enough to keep O_EXTERNAL_INSTANCE
399 	 *  opcode, thus we do check for l > 1.
400 	 */
401 	l = rule->cmd + rule->cmd_len - cmd;
402 	if (l > 1) {
403 		MPASS(F_LEN(cmd) == 1);
404 		icmd = cmd + 1;
405 		if (icmd->opcode == O_EXTERNAL_INSTANCE &&
406 		    instance_id != 0 && icmd->arg1 != instance_id)
407 			return (0);
408 		/*
409 		 * Since named_object related to this instance will be
410 		 * destroyed, truncate the chain of opcodes to remove
411 		 * the rest of cmd chain just after O_EXTERNAL_ACTION
412 		 * opcode.
413 		 */
414 		EACTION_DEBUG("truncate rule %d: len %u -> %u",
415 		    rule->rulenum, rule->cmd_len,
416 		    rule->cmd_len - F_LEN(icmd));
417 		rule->cmd_len -= F_LEN(icmd);
418 		MPASS(((uint32_t *)icmd -
419 		    (uint32_t *)rule->cmd) == rule->cmd_len);
420 	}
421 
422 	cmd->arg1 = default_id; /* Set to default id */
423 	/*
424 	 * Return 1 when reset successfully happened.
425 	 */
426 	return (1);
427 }
428 
429 /*
430  * This function should be called before external action instance is
431  * destroyed. It will reset eaction_id to default_id for rules, where
432  * eaction has instance with id == kidx.
433  */
434 int
435 ipfw_reset_eaction_instance(struct ip_fw_chain *ch, uint16_t eaction_id,
436     uint16_t kidx)
437 {
438 	struct named_object *no;
439 
440 	IPFW_UH_WLOCK_ASSERT(ch);
441 	no = ipfw_objhash_lookup_kidx(CHAIN_TO_SRV(ch), eaction_id);
442 	if (no == NULL || no->etlv != IPFW_TLV_EACTION)
443 		return (EINVAL);
444 
445 	reset_eaction_rules(ch, eaction_id, kidx, 0);
446 	return (0);
447 }
448 
449 int
450 ipfw_run_eaction(struct ip_fw_chain *ch, struct ip_fw_args *args,
451     ipfw_insn *cmd, int *done)
452 {
453 
454 	return (EACTION_OBJ(ch, cmd)->handler(ch, args, cmd, done));
455 }
456