xref: /xnu-8792.61.2/bsd/net/content_filter.c (revision 42e220869062b56f8d7d0726fd4c88954f87902c)
1 /*
2  * Copyright (c) 2013-2022 Apple Inc. All rights reserved.
3  *
4  * @APPLE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. Please obtain a copy of the License at
10  * http://www.opensource.apple.com/apsl/ and read it before using this
11  * file.
12  *
13  * The Original Code and all software distributed under the License are
14  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18  * Please see the License for the specific language governing rights and
19  * limitations under the License.
20  *
21  * @APPLE_LICENSE_HEADER_END@
22  */
23 
24 /*
25  * THEORY OF OPERATION
26  *
27  * The socket content filter subsystem provides a way for user space agents to
28  * make filtering decisions based on the content of the data being sent and
29  * received by INET/INET6 sockets.
30  *
31  * A content filter user space agents gets a copy of the data and the data is
32  * also kept in kernel buffer until the user space agents makes a pass or drop
33  * decision. This unidirectional flow of content avoids unnecessary data copies
34  * back to the kernel.
35  *
36  * A user space filter agent opens a kernel control socket with the name
37  * CONTENT_FILTER_CONTROL_NAME to attach to the socket content filter subsystem.
38  * When connected, a "struct content_filter" is created and set as the
39  * "unitinfo" of the corresponding kernel control socket instance.
40  *
41  * The socket content filter subsystem exchanges messages with the user space
42  * filter agent until an ultimate pass or drop decision is made by the
43  * user space filter agent.
44  *
45  * It should be noted that messages about many INET/INET6 sockets can be multiplexed
46  * over a single kernel control socket.
47  *
48  * Notes:
49  * - The current implementation supports all INET/INET6 sockets (i.e. TCP,
50  *   UDP, ICMP, etc).
51  * - The current implementation supports up to two simultaneous content filters
52  *   for iOS devices and eight simultaneous content filters for OSX.
53  *
54  *
55  * NECP FILTER CONTROL UNIT
56  *
57  * A user space filter agent uses the Network Extension Control Policy (NECP)
58  * database to specify which INET/INET6 sockets need to be filtered. The NECP
59  * criteria may be based on a variety of properties like user ID or proc UUID.
60  *
61  * The NECP "filter control unit" is used by the socket content filter subsystem
62  * to deliver the relevant INET/INET6 content information to the appropriate
63  * user space filter agent via its kernel control socket instance.
64  * This works as follows:
65  *
66  * 1) The user space filter agent specifies an NECP filter control unit when
67  *    in adds its filtering rules to the NECP database.
68  *
69  * 2) The user space filter agent also sets its NECP filter control unit on the
70  *    content filter kernel control socket via the socket option
71  *    CFIL_OPT_NECP_CONTROL_UNIT.
72  *
73  * 3) The NECP database is consulted to find out if a given INET/INET6 socket
74  *    needs to be subjected to content filtering and returns the corresponding
75  *    NECP filter control unit  -- the NECP filter control unit is actually
76  *    stored in the INET/INET6 socket structure so the NECP lookup is really simple.
77  *
78  * 4) The NECP filter control unit is then used to find the corresponding
79  *    kernel control socket instance.
80  *
81  * Note: NECP currently supports a single filter control unit per INET/INET6 socket
82  *       but this restriction may be soon lifted.
83  *
84  *
85  * THE MESSAGING PROTOCOL
86  *
87  * The socket content filter subsystem and a user space filter agent
88  * communicate over the kernel control socket via an asynchronous
89  * messaging protocol (this is not a request-response protocol).
90  * The socket content filter subsystem sends event messages to the user
91  * space filter agent about the INET/INET6 sockets it is interested to filter.
92  * The user space filter agent sends action messages to either allow
93  * data to pass or to disallow the data flow (and drop the connection).
94  *
95  * All messages over a content filter kernel control socket share the same
96  * common header of type "struct cfil_msg_hdr". The message type tells if
97  * it's a event message "CFM_TYPE_EVENT" or a action message "CFM_TYPE_ACTION".
98  * The message header field "cfm_sock_id" identifies a given INET/INET6 flow.
99  * For TCP, flows are per-socket.  For UDP and other datagrame protocols, there
100  * could be multiple flows per socket.
101  *
102  * Note the message header length field may be padded for alignment and can
103  * be larger than the actual content of the message.
104  * The field "cfm_op" describe the kind of event or action.
105  *
106  * Here are the kinds of content filter events:
107  * - CFM_OP_SOCKET_ATTACHED: a new INET/INET6 socket is being filtered
108  * - CFM_OP_SOCKET_CLOSED: A INET/INET6 socket is closed
109  * - CFM_OP_DATA_OUT: A span of data is being sent on a INET/INET6 socket
110  * - CFM_OP_DATA_IN: A span of data is being or received on a INET/INET6 socket
111  *
112  *
113  * EVENT MESSAGES
114  *
115  * The CFM_OP_DATA_OUT and CFM_OP_DATA_IN event messages contains a span of
116  * data that is being sent or received. The position of this span of data
117  * in the data flow is described by a set of start and end offsets. These
118  * are absolute 64 bits offsets. The first byte sent (or received) starts
119  * at offset 0 and ends at offset 1. The length of the content data
120  * is given by the difference between the end offset and the start offset.
121  *
122  * After a CFM_OP_SOCKET_ATTACHED is delivered, CFM_OP_DATA_OUT and
123  * CFM_OP_DATA_OUT events are not delivered until a CFM_OP_DATA_UPDATE
124  * action message is sent by the user space filter agent.
125  *
126  * Note: absolute 64 bits offsets should be large enough for the foreseeable
127  * future.  A 64-bits counter will wrap after 468 years at 10 Gbit/sec:
128  *   2E64 / ((10E9 / 8) * 60 * 60 * 24 * 365.25) = 467.63
129  *
130  * They are two kinds of primary content filter actions:
131  * - CFM_OP_DATA_UPDATE: to update pass or peek offsets for each direction.
132  * - CFM_OP_DROP: to shutdown socket and disallow further data flow
133  *
134  * There is also an action to mark a given client flow as already filtered
135  * at a higher level, CFM_OP_BLESS_CLIENT.
136  *
137  *
138  * ACTION MESSAGES
139  *
140  * The CFM_OP_DATA_UPDATE action messages let the user space filter
141  * agent allow data to flow up to the specified pass offset -- there
142  * is a pass offset for outgoing data and a pass offset for incoming data.
143  * When a new INET/INET6 socket is attached to the content filter and a flow is
144  * created, each pass offset is initially set to 0 so no data is allowed to pass by
145  * default.  When the pass offset is set to CFM_MAX_OFFSET via a CFM_OP_DATA_UPDATE
146  * then the data flow becomes unrestricted.
147  *
148  * Note that pass offsets can only be incremented. A CFM_OP_DATA_UPDATE message
149  * with a pass offset smaller than the pass offset of a previous
150  * CFM_OP_DATA_UPDATE message is silently ignored.
151  *
152  * A user space filter agent also uses CFM_OP_DATA_UPDATE action messages
153  * to tell the kernel how much data it wants to see by using the peek offsets.
154  * Just like pass offsets, there is a peek offset for each direction.
155  * When a new INET/INET6 flow is created, each peek offset is initially set to 0
156  * so no CFM_OP_DATA_OUT and CFM_OP_DATA_IN event messages are dispatched by default
157  * until a CFM_OP_DATA_UPDATE action message with a greater than 0 peek offset is sent
158  * by the user space filter agent.  When the peek offset is set to CFM_MAX_OFFSET via
159  * a CFM_OP_DATA_UPDATE then the flow of update data events becomes unrestricted.
160  *
161  * Note that peek offsets cannot be smaller than the corresponding pass offset.
162  * Also a peek offsets cannot be smaller than the corresponding end offset
163  * of the last CFM_OP_DATA_OUT/CFM_OP_DATA_IN message dispatched. Trying
164  * to set a too small peek value is silently ignored.
165  *
166  *
167  * PER FLOW "struct cfil_info"
168  *
169  * As soon as a INET/INET6 socket gets attached to a content filter, a
170  * "struct cfil_info" is created to hold the content filtering state for this
171  * socket.  For UDP and other datagram protocols, as soon as traffic is seen for
172  * each new flow identified by its 4-tuple of source address/port and destination
173  * address/port, a "struct cfil_info" is created.  Each datagram socket may
174  * have multiple flows maintained in a hash table of "struct cfil_info" entries.
175  *
176  * The content filtering state is made of the following information
177  * for each direction:
178  * - The current pass offset;
179  * - The first and last offsets of the data pending, waiting for a filtering
180  *   decision;
181  * - The inject queue for data that passed the filters and that needs
182  *   to be re-injected;
183  * - A content filter specific state in a set of  "struct cfil_entry"
184  *
185  *
186  * CONTENT FILTER STATE "struct cfil_entry"
187  *
188  * The "struct cfil_entry" maintains the information most relevant to the
189  * message handling over a kernel control socket with a user space filter agent.
190  *
191  * The "struct cfil_entry" holds the NECP filter control unit that corresponds
192  * to the kernel control socket unit it corresponds to and also has a pointer
193  * to the corresponding "struct content_filter".
194  *
195  * For each direction, "struct cfil_entry" maintains the following information:
196  * - The pass offset
197  * - The peek offset
198  * - The offset of the last data peeked at by the filter
199  * - A queue of data that's waiting to be delivered to the  user space filter
200  *   agent on the kernel control socket
201  * - A queue of data for which event messages have been sent on the kernel
202  *   control socket and are pending for a filtering decision.
203  *
204  *
205  * CONTENT FILTER QUEUES
206  *
207  * Data that is being filtered is steered away from the INET/INET6 socket buffer
208  * and instead will sit in one of three content filter queues until the data
209  * can be re-injected into the INET/INET6 socket buffer.
210  *
211  * A content filter queue is represented by "struct cfil_queue" that contains
212  * a list of mbufs and the start and end offset of the data span of
213  * the list of mbufs.
214  *
215  * The data moves into the three content filter queues according to this
216  * sequence:
217  * a) The "cfe_ctl_q" of "struct cfil_entry"
218  * b) The "cfe_pending_q" of "struct cfil_entry"
219  * c) The "cfi_inject_q" of "struct cfil_info"
220  *
221  * Note: The sequence (a),(b) may be repeated several times if there is more
222  * than one content filter attached to the INET/INET6 socket.
223  *
224  * The "cfe_ctl_q" queue holds data than cannot be delivered to the
225  * kernel conntrol socket for two reasons:
226  * - The peek offset is less that the end offset of the mbuf data
227  * - The kernel control socket is flow controlled
228  *
229  * The "cfe_pending_q" queue holds data for which CFM_OP_DATA_OUT or
230  * CFM_OP_DATA_IN have been successfully dispatched to the kernel control
231  * socket and are waiting for a pass action message fromn the user space
232  * filter agent. An mbuf length must be fully allowed to pass to be removed
233  * from the cfe_pending_q.
234  *
235  * The "cfi_inject_q" queue holds data that has been fully allowed to pass
236  * by the user space filter agent and that needs to be re-injected into the
237  * INET/INET6 socket.
238  *
239  *
240  * IMPACT ON FLOW CONTROL
241  *
242  * An essential aspect of the content filer subsystem is to minimize the
243  * impact on flow control of the INET/INET6 sockets being filtered.
244  *
245  * The processing overhead of the content filtering may have an effect on
246  * flow control by adding noticeable delays and cannot be eliminated --
247  * care must be taken by the user space filter agent to minimize the
248  * processing delays.
249  *
250  * The amount of data being filtered is kept in buffers while waiting for
251  * a decision by the user space filter agent. This amount of data pending
252  * needs to be subtracted from the amount of data available in the
253  * corresponding INET/INET6 socket buffer. This is done by modifying
254  * sbspace() and tcp_sbspace() to account for amount of data pending
255  * in the content filter.
256  *
257  *
258  * LOCKING STRATEGY
259  *
260  * The global state of content filter subsystem is protected by a single
261  * read-write lock "cfil_lck_rw". The data flow can be done with the
262  * cfil read-write lock held as shared so it can be re-entered from multiple
263  * threads.
264  *
265  * The per INET/INET6 socket content filterstate -- "struct cfil_info" -- is
266  * protected by the socket lock.
267  *
268  * A INET/INET6 socket lock cannot be taken while the cfil read-write lock
269  * is held. That's why we have some sequences where we drop the cfil read-write
270  * lock before taking the INET/INET6 lock.
271  *
272  * It is also important to lock the INET/INET6 socket buffer while the content
273  * filter is modifying the amount of pending data. Otherwise the calculations
274  * in sbspace() and tcp_sbspace()  could be wrong.
275  *
276  * The "cfil_lck_rw" protects "struct content_filter" and also the fields
277  * "cfe_link" and "cfe_filter" of "struct cfil_entry".
278  *
279  * Actually "cfe_link" and "cfe_filter" are protected by both by
280  * "cfil_lck_rw" and the socket lock: they may be modified only when
281  * "cfil_lck_rw" is exclusive and the socket is locked.
282  *
283  * To read the other fields of "struct content_filter" we have to take
284  * "cfil_lck_rw" in shared mode.
285  *
286  * DATAGRAM SPECIFICS:
287  *
288  * The socket content filter supports all INET/INET6 protocols.  However
289  * the treatments for TCP sockets and for datagram (UDP, ICMP, etc) sockets
290  * are slightly different.
291  *
292  * Each datagram socket may have multiple flows.  Each flow is identified
293  * by the flow's source address/port and destination address/port tuple
294  * and is represented as a "struct cfil_info" entry.  For each socket,
295  * a hash table is used to maintain the collection of flows under that socket.
296  *
297  * Each datagram flow is uniquely identified by it's "struct cfil_info" cfi_sock_id.
298  * The highest 32-bits of the cfi_sock_id contains the socket's so_gencnt.  This portion
299  * of the cfi_sock_id is used locate the socket during socket lookup.  The lowest 32-bits
300  * of the cfi_sock_id contains a hash of the flow's 4-tuple.  This portion of the cfi_sock_id
301  * is used as the hash value for the flow hash table lookup within the parent socket.
302  *
303  * Since datagram sockets may not be connected, flow states may not be maintained in the
304  * socket structures and thus have to be saved for each packet.  These saved states will be
305  * used for both outgoing and incoming reinjections.  For outgoing packets, destination
306  * address/port as well as the current socket states will be saved.  During reinjection,
307  * these saved states will be used instead.  For incoming packets, control and address
308  * mbufs will be chained to the data.  During reinjection, the whole chain will be queued
309  * onto the incoming socket buffer.
310  *
311  * LIMITATIONS
312  *
313  * - Support all INET/INET6 sockets, such as TCP, UDP, ICMP, etc
314  *
315  * - Does not support TCP unordered messages
316  */
317 
318 /*
319  *	TO DO LIST
320  *
321  *	Deal with OOB
322  *
323  */
324 
325 #include <sys/types.h>
326 #include <sys/kern_control.h>
327 #include <sys/queue.h>
328 #include <sys/domain.h>
329 #include <sys/protosw.h>
330 #include <sys/syslog.h>
331 #include <sys/systm.h>
332 #include <sys/param.h>
333 #include <sys/mbuf.h>
334 
335 #include <kern/locks.h>
336 #include <kern/zalloc.h>
337 #include <kern/debug.h>
338 
339 #include <net/ntstat.h>
340 #include <net/content_filter.h>
341 #include <net/content_filter_crypto.h>
342 
343 #define _IP_VHL
344 #include <netinet/ip.h>
345 #include <netinet/in_pcb.h>
346 #include <netinet/tcp.h>
347 #include <netinet/tcp_var.h>
348 #include <netinet/udp.h>
349 #include <netinet/udp_var.h>
350 #include <kern/socket_flows.h>
351 
352 #include <string.h>
353 #include <libkern/libkern.h>
354 #include <kern/sched_prim.h>
355 #include <kern/task.h>
356 #include <mach/task_info.h>
357 
358 #define MAX_CONTENT_FILTER 8
359 
360 extern struct inpcbinfo ripcbinfo;
361 struct cfil_entry;
362 
363 /*
364  * The structure content_filter represents a user space content filter
365  * It's created and associated with a kernel control socket instance
366  */
367 struct content_filter {
368 	kern_ctl_ref            cf_kcref;
369 	u_int32_t               cf_kcunit;
370 	u_int32_t               cf_flags;
371 
372 	uint32_t                cf_necp_control_unit;
373 
374 	uint32_t                cf_sock_count;
375 	TAILQ_HEAD(, cfil_entry) cf_sock_entries;
376 
377 	cfil_crypto_state_t cf_crypto_state;
378 };
379 
380 #define CFF_ACTIVE              0x01
381 #define CFF_DETACHING           0x02
382 #define CFF_FLOW_CONTROLLED     0x04
383 #define CFF_PRESERVE_CONNECTIONS 0x08
384 
385 struct content_filter *content_filters[MAX_CONTENT_FILTER];
386 uint32_t cfil_active_count = 0; /* Number of active content filters */
387 uint32_t cfil_sock_attached_count = 0;  /* Number of sockets attachements */
388 uint32_t cfil_sock_attached_stats_count = 0;    /* Number of sockets requested periodic stats report */
389 uint32_t cfil_close_wait_timeout = 1000; /* in milliseconds */
390 
391 static kern_ctl_ref cfil_kctlref = NULL;
392 
393 static LCK_GRP_DECLARE(cfil_lck_grp, "content filter");
394 static LCK_RW_DECLARE(cfil_lck_rw, &cfil_lck_grp);
395 
396 #define CFIL_RW_LCK_MAX 8
397 
398 int cfil_rw_nxt_lck = 0;
399 void* cfil_rw_lock_history[CFIL_RW_LCK_MAX];
400 
401 int cfil_rw_nxt_unlck = 0;
402 void* cfil_rw_unlock_history[CFIL_RW_LCK_MAX];
403 
404 static ZONE_DEFINE(content_filter_zone, "content_filter",
405     sizeof(struct content_filter), ZC_NONE);
406 
407 MBUFQ_HEAD(cfil_mqhead);
408 
409 struct cfil_queue {
410 	uint64_t                q_start; /* offset of first byte in queue */
411 	uint64_t                q_end; /* offset of last byte in queue */
412 	struct cfil_mqhead      q_mq;
413 };
414 
415 /*
416  * struct cfil_entry
417  *
418  * The is one entry per content filter
419  */
420 struct cfil_entry {
421 	TAILQ_ENTRY(cfil_entry) cfe_link;
422 	SLIST_ENTRY(cfil_entry) cfe_order_link;
423 	struct content_filter   *cfe_filter;
424 
425 	struct cfil_info        *cfe_cfil_info;
426 	uint32_t                cfe_flags;
427 	uint32_t                cfe_necp_control_unit;
428 	struct timeval          cfe_last_event; /* To user space */
429 	struct timeval          cfe_last_action; /* From user space */
430 	uint64_t                cfe_byte_inbound_count_reported; /* stats already been reported */
431 	uint64_t                cfe_byte_outbound_count_reported; /* stats already been reported */
432 	struct timeval          cfe_stats_report_ts; /* Timestamp for last stats report */
433 	uint32_t                cfe_stats_report_frequency; /* Interval for stats report in msecs */
434 	boolean_t               cfe_laddr_sent;
435 
436 	struct cfe_buf {
437 		/*
438 		 * cfe_pending_q holds data that has been delivered to
439 		 * the filter and for which we are waiting for an action
440 		 */
441 		struct cfil_queue       cfe_pending_q;
442 		/*
443 		 * This queue is for data that has not be delivered to
444 		 * the content filter (new data, pass peek or flow control)
445 		 */
446 		struct cfil_queue       cfe_ctl_q;
447 
448 		uint64_t                cfe_pass_offset;
449 		uint64_t                cfe_peek_offset;
450 		uint64_t                cfe_peeked;
451 	} cfe_snd, cfe_rcv;
452 };
453 
454 #define CFEF_CFIL_ATTACHED              0x0001  /* was attached to filter */
455 #define CFEF_SENT_SOCK_ATTACHED         0x0002  /* sock attach event was sent */
456 #define CFEF_DATA_START                 0x0004  /* can send data event */
457 #define CFEF_FLOW_CONTROLLED            0x0008  /* wait for flow control lift */
458 #define CFEF_SENT_DISCONNECT_IN         0x0010  /* event was sent */
459 #define CFEF_SENT_DISCONNECT_OUT        0x0020  /* event was sent */
460 #define CFEF_SENT_SOCK_CLOSED           0x0040  /* closed event was sent */
461 #define CFEF_CFIL_DETACHED              0x0080  /* filter was detached */
462 
463 
464 #define CFI_ADD_TIME_LOG(cfil, t1, t0, op)                                                                                      \
465 	        struct timeval64 _tdiff;                                                                                          \
466 	        if ((cfil)->cfi_op_list_ctr < CFI_MAX_TIME_LOG_ENTRY) {                                                         \
467 	                timersub(t1, t0, &_tdiff);                                                                              \
468 	                (cfil)->cfi_op_time[(cfil)->cfi_op_list_ctr] = (uint32_t)(_tdiff.tv_sec * 1000 + _tdiff.tv_usec / 1000);\
469 	                (cfil)->cfi_op_list[(cfil)->cfi_op_list_ctr] = (unsigned char)op;                                       \
470 	                (cfil)->cfi_op_list_ctr ++;                                                                             \
471 	        }
472 
473 /*
474  * struct cfil_info
475  *
476  * There is a struct cfil_info per socket
477  */
478 struct cfil_info {
479 	TAILQ_ENTRY(cfil_info)  cfi_link;
480 	TAILQ_ENTRY(cfil_info)  cfi_link_stats;
481 	struct socket           *cfi_so;
482 	uint64_t                cfi_flags;
483 	uint64_t                cfi_sock_id;
484 	struct timeval64        cfi_first_event;
485 	uint32_t                cfi_op_list_ctr;
486 	uint32_t                cfi_op_time[CFI_MAX_TIME_LOG_ENTRY];    /* time interval in microseconds since first event */
487 	unsigned char           cfi_op_list[CFI_MAX_TIME_LOG_ENTRY];
488 	union sockaddr_in_4_6   cfi_so_attach_faddr;                    /* faddr at the time of attach */
489 	union sockaddr_in_4_6   cfi_so_attach_laddr;                    /* laddr at the time of attach */
490 
491 	int                     cfi_dir;
492 	uint64_t                cfi_byte_inbound_count;
493 	uint64_t                cfi_byte_outbound_count;
494 
495 	boolean_t               cfi_isSignatureLatest;                  /* Indicates if signature covers latest flow attributes */
496 	u_int32_t               cfi_filter_control_unit;
497 	u_int32_t               cfi_debug;
498 	struct cfi_buf {
499 		/*
500 		 * cfi_pending_first and cfi_pending_last describe the total
501 		 * amount of data outstanding for all the filters on
502 		 * this socket and data in the flow queue
503 		 * cfi_pending_mbcnt counts in sballoc() "chars of mbufs used"
504 		 */
505 		uint64_t                cfi_pending_first;
506 		uint64_t                cfi_pending_last;
507 		uint32_t                cfi_pending_mbcnt;
508 		uint32_t                cfi_pending_mbnum;
509 		uint32_t                cfi_tail_drop_cnt;
510 		/*
511 		 * cfi_pass_offset is the minimum of all the filters
512 		 */
513 		uint64_t                cfi_pass_offset;
514 		/*
515 		 * cfi_inject_q holds data that needs to be re-injected
516 		 * into the socket after filtering and that can
517 		 * be queued because of flow control
518 		 */
519 		struct cfil_queue       cfi_inject_q;
520 	} cfi_snd, cfi_rcv;
521 
522 	struct cfil_entry       cfi_entries[MAX_CONTENT_FILTER];
523 	struct soflow_hash_entry *cfi_hash_entry;
524 	SLIST_HEAD(, cfil_entry) cfi_ordered_entries;
525 	os_refcnt_t             cfi_ref_count;
526 } __attribute__((aligned(8)));
527 
528 #define CFIF_DROP               0x0001  /* drop action applied */
529 #define CFIF_CLOSE_WAIT         0x0002  /* waiting for filter to close */
530 #define CFIF_SOCK_CLOSED        0x0004  /* socket is closed */
531 #define CFIF_RETRY_INJECT_IN    0x0010  /* inject in failed */
532 #define CFIF_RETRY_INJECT_OUT   0x0020  /* inject out failed */
533 #define CFIF_SHUT_WR            0x0040  /* shutdown write */
534 #define CFIF_SHUT_RD            0x0080  /* shutdown read */
535 #define CFIF_SOCKET_CONNECTED   0x0100  /* socket is connected */
536 #define CFIF_INITIAL_VERDICT    0x0200  /* received initial verdict */
537 #define CFIF_NO_CLOSE_WAIT      0x0400  /* do not wait to close */
538 
539 #define CFI_MASK_GENCNT         0xFFFFFFFF00000000      /* upper 32 bits */
540 #define CFI_SHIFT_GENCNT        32
541 #define CFI_MASK_FLOWHASH       0x00000000FFFFFFFF      /* lower 32 bits */
542 #define CFI_SHIFT_FLOWHASH      0
543 
544 #define CFI_ENTRY_KCUNIT(i, e) ((uint32_t)(((e) - &((i)->cfi_entries[0])) + 1))
545 
546 static ZONE_DEFINE(cfil_info_zone, "cfil_info",
547     sizeof(struct cfil_info), ZC_NONE);
548 
549 TAILQ_HEAD(cfil_sock_head, cfil_info) cfil_sock_head;
550 TAILQ_HEAD(cfil_sock_head_stats, cfil_info) cfil_sock_head_stats;
551 
552 #define CFIL_QUEUE_VERIFY(x) if (cfil_debug) cfil_queue_verify(x)
553 #define CFIL_INFO_VERIFY(x) if (cfil_debug) cfil_info_verify(x)
554 
555 /*
556  * UDP Socket Support
557  */
558 #define IS_ICMP(so) (so && so->so_proto && (so->so_proto->pr_type == SOCK_RAW || so->so_proto->pr_type == SOCK_DGRAM) && \
559 	                                   (so->so_proto->pr_protocol == IPPROTO_ICMP || so->so_proto->pr_protocol == IPPROTO_ICMPV6))
560 #define IS_RAW(so)  (so && so->so_proto && so->so_proto->pr_type == SOCK_RAW  && so->so_proto->pr_protocol == IPPROTO_RAW)
561 
562 #define OPTIONAL_IP_HEADER(so) (!IS_TCP(so) && !IS_UDP(so))
563 #define GET_SO_PROTOCOL(so) ((so && so->so_proto) ? so->so_proto->pr_protocol : IPPROTO_IP)
564 #define GET_SO_INP_PROTOCOL(so) ((so && sotoinpcb(so)) ? sotoinpcb(so)->inp_ip_p : IPPROTO_IP)
565 #define GET_SO_PROTO(so) ((GET_SO_PROTOCOL(so) != IPPROTO_IP) ? GET_SO_PROTOCOL(so) : GET_SO_INP_PROTOCOL(so))
566 #define IS_INP_V6(inp) (inp && (inp->inp_vflag & INP_IPV6))
567 
568 #define UNCONNECTED(inp) (inp && (((inp->inp_vflag & INP_IPV4) && (inp->inp_faddr.s_addr == INADDR_ANY)) || \
569 	                                                          ((inp->inp_vflag & INP_IPV6) && IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))))
570 #define IS_ENTRY_ATTACHED(cfil_info, kcunit) (cfil_info != NULL && (kcunit <= MAX_CONTENT_FILTER) && \
571 	                                                                                  cfil_info->cfi_entries[kcunit - 1].cfe_filter != NULL)
572 #define IS_DNS(local, remote) (check_port(local, 53) || check_port(remote, 53) || check_port(local, 5353) || check_port(remote, 5353))
573 #define IS_INITIAL_TFO_DATA(so) (so && (so->so_flags1 & SOF1_PRECONNECT_DATA) && (so->so_state & SS_ISCONNECTING))
574 #define NULLADDRESS(addr) ((addr.sa.sa_len == 0) || \
575 	                   (addr.sa.sa_family == AF_INET && addr.sin.sin_addr.s_addr == 0) || \
576 	                   (addr.sa.sa_family == AF_INET6 && IN6_IS_ADDR_UNSPECIFIED(&addr.sin6.sin6_addr)))
577 
578 #define SKIP_FILTER_FOR_TCP_SOCKET(so) \
579     (so == NULL || so->so_proto == NULL || so->so_proto->pr_domain == NULL || \
580      (so->so_proto->pr_domain->dom_family != PF_INET && so->so_proto->pr_domain->dom_family != PF_INET6) || \
581       so->so_proto->pr_type != SOCK_STREAM || \
582       so->so_proto->pr_protocol != IPPROTO_TCP || \
583       (so->so_flags & SOF_MP_SUBFLOW) != 0 || \
584       (so->so_flags1 & SOF1_CONTENT_FILTER_SKIP) != 0)
585 
586 /*
587  * Special handling for 0.0.0.0-faddr TCP flows.  This flows will be changed to loopback addr by TCP and
588  * may result in an immediate TCP RESET and socket close.  This leads to CFIL blocking the owner thread for
589  * 1 sec waiting for ack from user-space provider (ack recevied by CFIL but socket already removed from
590  * global socket list).  To avoid this, identify these flows and do not perform the close-wait blocking.
591  * These flows are identified as destined to Loopback address and were disconnected shortly after connect
592  * (before initial-verdict received).
593  */
594 #define IS_LOOPBACK_FADDR(inp) \
595     (inp && ((IS_INP_V6(inp) && IN6_IS_ADDR_LOOPBACK(&inp->in6p_faddr)) || (ntohl(inp->inp_faddr.s_addr) == INADDR_LOOPBACK)))
596 
597 #define SET_NO_CLOSE_WAIT(inp, cfil_info) \
598     if (inp && cfil_info && !(cfil_info->cfi_flags & CFIF_INITIAL_VERDICT) && IS_LOOPBACK_FADDR(inp)) { \
599 	cfil_info->cfi_flags |= CFIF_NO_CLOSE_WAIT; \
600     }
601 
602 #define IS_NO_CLOSE_WAIT(cfil_info) (cfil_info && (cfil_info->cfi_flags & CFIF_NO_CLOSE_WAIT))
603 
604 os_refgrp_decl(static, cfil_refgrp, "CFILRefGroup", NULL);
605 
606 #define CFIL_INFO_FREE(cfil_info) \
607     if (cfil_info && (os_ref_release(&cfil_info->cfi_ref_count) == 0)) { \
608 	cfil_info_free(cfil_info); \
609     }
610 
611 #define SOCKET_PID(so) ((so->so_flags & SOF_DELEGATED) ? so->e_pid : so->last_pid)
612 #define MATCH_PID(so) (so && (cfil_log_pid == SOCKET_PID(so)))
613 #define MATCH_PORT(inp, local, remote) \
614     ((inp && ntohs(inp->inp_lport) == cfil_log_port) || (inp && ntohs(inp->inp_fport) == cfil_log_port) || \
615 	check_port(local, cfil_log_port) || check_port(remote, cfil_log_port))
616 #define MATCH_PROTO(so) (GET_SO_PROTO(so) == cfil_log_proto)
617 
618 #define DEBUG_FLOW(inp, so, local, remote) \
619     ((cfil_log_port && MATCH_PORT(inp, local, remote)) || (cfil_log_pid && MATCH_PID(so)) || (cfil_log_proto && MATCH_PROTO(so)))
620 
621 /*
622  * Periodic Statistics Report:
623  */
624 static struct thread *cfil_stats_report_thread;
625 #define CFIL_STATS_REPORT_INTERVAL_MIN_MSEC  500   // Highest report frequency
626 #define CFIL_STATS_REPORT_RUN_INTERVAL_NSEC  (CFIL_STATS_REPORT_INTERVAL_MIN_MSEC * NSEC_PER_MSEC)
627 #define CFIL_STATS_REPORT_MAX_COUNT          50    // Max stats to be reported per run
628 
629 /* This buffer must have same layout as struct cfil_msg_stats_report */
630 struct cfil_stats_report_buffer {
631 	struct cfil_msg_hdr        msghdr;
632 	uint32_t                   count;
633 	struct cfil_msg_sock_stats stats[CFIL_STATS_REPORT_MAX_COUNT];
634 };
635 static struct cfil_stats_report_buffer *global_cfil_stats_report_buffers[MAX_CONTENT_FILTER];
636 static uint32_t global_cfil_stats_counts[MAX_CONTENT_FILTER];
637 
638 /*
639  * UDP Garbage Collection:
640  */
641 #define UDP_FLOW_GC_ACTION_TO        10  // Flow Action Timeout (no action from user space) in seconds
642 #define UDP_FLOW_GC_MAX_COUNT        100 // Max UDP flows to be handled per run
643 
644 /*
645  * UDP flow queue thresholds
646  */
647 #define UDP_FLOW_GC_MBUF_CNT_MAX  (2 << MBSHIFT) // Max mbuf byte count in flow queue (2MB)
648 #define UDP_FLOW_GC_MBUF_NUM_MAX  (UDP_FLOW_GC_MBUF_CNT_MAX >> MCLSHIFT) // Max mbuf count in flow queue (1K)
649 #define UDP_FLOW_GC_MBUF_SHIFT    5             // Shift to get 1/32 of platform limits
650 /*
651  * UDP flow queue threshold globals:
652  */
653 static unsigned int cfil_udp_gc_mbuf_num_max = UDP_FLOW_GC_MBUF_NUM_MAX;
654 static unsigned int cfil_udp_gc_mbuf_cnt_max = UDP_FLOW_GC_MBUF_CNT_MAX;
655 
656 /*
657  * CFIL specific mbuf tag:
658  * Save state of socket at the point of data entry into cfil.
659  * Use saved state for reinjection at protocol layer.
660  */
661 struct cfil_tag {
662 	union sockaddr_in_4_6 cfil_faddr;
663 	uint32_t cfil_so_state_change_cnt;
664 	uint32_t cfil_so_options;
665 	int cfil_inp_flags;
666 };
667 
668 /*
669  * Global behavior flags:
670  */
671 #define CFIL_BEHAVIOR_FLAG_PRESERVE_CONNECTIONS 0x00000001
672 static uint32_t cfil_behavior_flags = 0;
673 
674 #define DO_PRESERVE_CONNECTIONS (cfil_behavior_flags & CFIL_BEHAVIOR_FLAG_PRESERVE_CONNECTIONS)
675 
676 /*
677  * Statistics
678  */
679 
680 struct cfil_stats cfil_stats;
681 
682 /*
683  * For troubleshooting
684  */
685 int cfil_log_level = LOG_ERR;
686 int cfil_log_port = 0;
687 int cfil_log_pid = 0;
688 int cfil_log_proto = 0;
689 int cfil_log_data = 0;
690 int cfil_log_stats = 0;
691 int cfil_debug = 1;
692 
693 /*
694  * Sysctls for logs and statistics
695  */
696 static int sysctl_cfil_filter_list(struct sysctl_oid *, void *, int,
697     struct sysctl_req *);
698 static int sysctl_cfil_sock_list(struct sysctl_oid *, void *, int,
699     struct sysctl_req *);
700 
701 SYSCTL_NODE(_net, OID_AUTO, cfil, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "cfil");
702 
703 SYSCTL_INT(_net_cfil, OID_AUTO, log, CTLFLAG_RW | CTLFLAG_LOCKED,
704     &cfil_log_level, 0, "");
705 
706 SYSCTL_INT(_net_cfil, OID_AUTO, log_port, CTLFLAG_RW | CTLFLAG_LOCKED,
707     &cfil_log_port, 0, "");
708 
709 SYSCTL_INT(_net_cfil, OID_AUTO, log_pid, CTLFLAG_RW | CTLFLAG_LOCKED,
710     &cfil_log_pid, 0, "");
711 
712 SYSCTL_INT(_net_cfil, OID_AUTO, log_proto, CTLFLAG_RW | CTLFLAG_LOCKED,
713     &cfil_log_proto, 0, "");
714 
715 SYSCTL_INT(_net_cfil, OID_AUTO, log_data, CTLFLAG_RW | CTLFLAG_LOCKED,
716     &cfil_log_data, 0, "");
717 
718 SYSCTL_INT(_net_cfil, OID_AUTO, log_stats, CTLFLAG_RW | CTLFLAG_LOCKED,
719     &cfil_log_stats, 0, "");
720 
721 SYSCTL_INT(_net_cfil, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_LOCKED,
722     &cfil_debug, 0, "");
723 
724 SYSCTL_UINT(_net_cfil, OID_AUTO, sock_attached_count, CTLFLAG_RD | CTLFLAG_LOCKED,
725     &cfil_sock_attached_count, 0, "");
726 
727 SYSCTL_UINT(_net_cfil, OID_AUTO, active_count, CTLFLAG_RD | CTLFLAG_LOCKED,
728     &cfil_active_count, 0, "");
729 
730 SYSCTL_UINT(_net_cfil, OID_AUTO, close_wait_timeout, CTLFLAG_RW | CTLFLAG_LOCKED,
731     &cfil_close_wait_timeout, 0, "");
732 
733 SYSCTL_UINT(_net_cfil, OID_AUTO, behavior_flags, CTLFLAG_RW | CTLFLAG_LOCKED,
734     &cfil_behavior_flags, 0, "");
735 
736 static int cfil_sbtrim = 1;
737 SYSCTL_UINT(_net_cfil, OID_AUTO, sbtrim, CTLFLAG_RW | CTLFLAG_LOCKED,
738     &cfil_sbtrim, 0, "");
739 
740 SYSCTL_PROC(_net_cfil, OID_AUTO, filter_list, CTLFLAG_RD | CTLFLAG_LOCKED,
741     0, 0, sysctl_cfil_filter_list, "S,cfil_filter_stat", "");
742 
743 SYSCTL_PROC(_net_cfil, OID_AUTO, sock_list, CTLFLAG_RD | CTLFLAG_LOCKED,
744     0, 0, sysctl_cfil_sock_list, "S,cfil_sock_stat", "");
745 
746 SYSCTL_STRUCT(_net_cfil, OID_AUTO, stats, CTLFLAG_RD | CTLFLAG_LOCKED,
747     &cfil_stats, cfil_stats, "");
748 
749 /*
750  * Forward declaration to appease the compiler
751  */
752 static int cfil_action_data_pass(struct socket *, struct cfil_info *, uint32_t, int,
753     uint64_t, uint64_t);
754 static int cfil_action_drop(struct socket *, struct cfil_info *, uint32_t);
755 static int cfil_action_bless_client(uint32_t, struct cfil_msg_hdr *);
756 static int cfil_action_set_crypto_key(uint32_t, struct cfil_msg_hdr *);
757 static int cfil_dispatch_closed_event(struct socket *, struct cfil_info *, int);
758 static int cfil_data_common(struct socket *, struct cfil_info *, int, struct sockaddr *,
759     struct mbuf *, struct mbuf *, uint32_t);
760 static int cfil_data_filter(struct socket *, struct cfil_info *, uint32_t, int,
761     struct mbuf *, uint32_t);
762 static void fill_ip_sockaddr_4_6(union sockaddr_in_4_6 *,
763     struct in_addr, u_int16_t);
764 static void fill_ip6_sockaddr_4_6(union sockaddr_in_4_6 *,
765     struct in6_addr *, u_int16_t, uint32_t);
766 
767 static int cfil_dispatch_attach_event(struct socket *, struct cfil_info *, uint32_t, int);
768 static void cfil_info_free(struct cfil_info *);
769 static struct cfil_info * cfil_info_alloc(struct socket *, struct soflow_hash_entry *);
770 static int cfil_info_attach_unit(struct socket *, uint32_t, struct cfil_info *);
771 static struct socket * cfil_socket_from_sock_id(cfil_sock_id_t, bool);
772 static struct socket * cfil_socket_from_client_uuid(uuid_t, bool *);
773 static int cfil_service_pending_queue(struct socket *, struct cfil_info *, uint32_t, int);
774 static int cfil_data_service_ctl_q(struct socket *, struct cfil_info *, uint32_t, int);
775 static void cfil_info_verify(struct cfil_info *);
776 static int cfil_update_data_offsets(struct socket *, struct cfil_info *, uint32_t, int,
777     uint64_t, uint64_t);
778 static int cfil_acquire_sockbuf(struct socket *, struct cfil_info *, int);
779 static void cfil_release_sockbuf(struct socket *, int);
780 static int cfil_filters_attached(struct socket *);
781 
782 static void cfil_rw_lock_exclusive(lck_rw_t *);
783 static void cfil_rw_unlock_exclusive(lck_rw_t *);
784 static void cfil_rw_lock_shared(lck_rw_t *);
785 static void cfil_rw_unlock_shared(lck_rw_t *);
786 static boolean_t cfil_rw_lock_shared_to_exclusive(lck_rw_t *);
787 static void cfil_rw_lock_exclusive_to_shared(lck_rw_t *);
788 
789 static unsigned int cfil_data_length(struct mbuf *, int *, int *);
790 static struct cfil_info *cfil_sock_udp_get_info(struct socket *, uint32_t, bool, struct soflow_hash_entry *, struct sockaddr *, struct sockaddr *);
791 static errno_t cfil_sock_udp_handle_data(bool, struct socket *, struct sockaddr *, struct sockaddr *,
792     struct mbuf *, struct mbuf *, uint32_t, struct soflow_hash_entry *);
793 static int32_t cfil_sock_udp_data_pending(struct sockbuf *, bool);
794 static void cfil_sock_udp_is_closed(struct socket *);
795 static int cfil_sock_udp_notify_shutdown(struct socket *, int, int, int);
796 static int cfil_sock_udp_shutdown(struct socket *, int *);
797 static void cfil_sock_udp_close_wait(struct socket *);
798 static void cfil_sock_udp_buf_update(struct sockbuf *);
799 static int cfil_filters_udp_attached(struct socket *, bool);
800 static void cfil_get_flow_address_v6(struct soflow_hash_entry *, struct inpcb *,
801     struct in6_addr **, struct in6_addr **,
802     u_int16_t *, u_int16_t *);
803 static void cfil_get_flow_address(struct soflow_hash_entry *, struct inpcb *,
804     struct in_addr *, struct in_addr *,
805     u_int16_t *, u_int16_t *);
806 static void cfil_info_log(int, struct cfil_info *, const char *);
807 void cfil_filter_show(u_int32_t);
808 void cfil_info_show(void);
809 bool cfil_info_action_timed_out(struct cfil_info *, int);
810 bool cfil_info_buffer_threshold_exceeded(struct cfil_info *);
811 struct m_tag *cfil_dgram_save_socket_state(struct cfil_info *, struct mbuf *);
812 boolean_t cfil_dgram_peek_socket_state(struct mbuf *m, int *inp_flags);
813 static void cfil_sock_received_verdict(struct socket *so);
814 static void cfil_fill_event_msg_addresses(struct soflow_hash_entry *, struct inpcb *,
815     union sockaddr_in_4_6 *, union sockaddr_in_4_6 *,
816     boolean_t, boolean_t);
817 static void cfil_stats_report_thread_func(void *, wait_result_t);
818 static void cfil_stats_report(void *v, wait_result_t w);
819 static bool cfil_dgram_gc_needed(struct socket *, struct soflow_hash_entry *, u_int64_t);
820 static bool cfil_dgram_gc_perform(struct socket *, struct soflow_hash_entry *);
821 static bool cfil_dgram_detach_entry(struct socket *, struct soflow_hash_entry *);
822 static bool cfil_dgram_detach_db(struct socket *, struct soflow_db *);
823 bool check_port(struct sockaddr *, u_short);
824 
825 /*
826  * Content filter global read write lock
827  */
828 
829 static void
cfil_rw_lock_exclusive(lck_rw_t * lck)830 cfil_rw_lock_exclusive(lck_rw_t *lck)
831 {
832 	void *lr_saved;
833 
834 	lr_saved = __builtin_return_address(0);
835 
836 	lck_rw_lock_exclusive(lck);
837 
838 	cfil_rw_lock_history[cfil_rw_nxt_lck] = lr_saved;
839 	cfil_rw_nxt_lck = (cfil_rw_nxt_lck + 1) % CFIL_RW_LCK_MAX;
840 }
841 
842 static void
cfil_rw_unlock_exclusive(lck_rw_t * lck)843 cfil_rw_unlock_exclusive(lck_rw_t *lck)
844 {
845 	void *lr_saved;
846 
847 	lr_saved = __builtin_return_address(0);
848 
849 	lck_rw_unlock_exclusive(lck);
850 
851 	cfil_rw_unlock_history[cfil_rw_nxt_unlck] = lr_saved;
852 	cfil_rw_nxt_unlck = (cfil_rw_nxt_unlck + 1) % CFIL_RW_LCK_MAX;
853 }
854 
855 static void
cfil_rw_lock_shared(lck_rw_t * lck)856 cfil_rw_lock_shared(lck_rw_t *lck)
857 {
858 	void *lr_saved;
859 
860 	lr_saved = __builtin_return_address(0);
861 
862 	lck_rw_lock_shared(lck);
863 
864 	cfil_rw_lock_history[cfil_rw_nxt_lck] = lr_saved;
865 	cfil_rw_nxt_lck = (cfil_rw_nxt_lck + 1) % CFIL_RW_LCK_MAX;
866 }
867 
868 static void
cfil_rw_unlock_shared(lck_rw_t * lck)869 cfil_rw_unlock_shared(lck_rw_t *lck)
870 {
871 	void *lr_saved;
872 
873 	lr_saved = __builtin_return_address(0);
874 
875 	lck_rw_unlock_shared(lck);
876 
877 	cfil_rw_unlock_history[cfil_rw_nxt_unlck] = lr_saved;
878 	cfil_rw_nxt_unlck = (cfil_rw_nxt_unlck + 1) % CFIL_RW_LCK_MAX;
879 }
880 
881 static boolean_t
cfil_rw_lock_shared_to_exclusive(lck_rw_t * lck)882 cfil_rw_lock_shared_to_exclusive(lck_rw_t *lck)
883 {
884 	void *lr_saved;
885 	boolean_t upgraded;
886 
887 	lr_saved = __builtin_return_address(0);
888 
889 	upgraded = lck_rw_lock_shared_to_exclusive(lck);
890 	if (upgraded) {
891 		cfil_rw_unlock_history[cfil_rw_nxt_unlck] = lr_saved;
892 		cfil_rw_nxt_unlck = (cfil_rw_nxt_unlck + 1) % CFIL_RW_LCK_MAX;
893 	}
894 	return upgraded;
895 }
896 
897 static void
cfil_rw_lock_exclusive_to_shared(lck_rw_t * lck)898 cfil_rw_lock_exclusive_to_shared(lck_rw_t *lck)
899 {
900 	void *lr_saved;
901 
902 	lr_saved = __builtin_return_address(0);
903 
904 	lck_rw_lock_exclusive_to_shared(lck);
905 
906 	cfil_rw_lock_history[cfil_rw_nxt_lck] = lr_saved;
907 	cfil_rw_nxt_lck = (cfil_rw_nxt_lck + 1) % CFIL_RW_LCK_MAX;
908 }
909 
910 static void
cfil_rw_lock_assert_held(lck_rw_t * lck,int exclusive)911 cfil_rw_lock_assert_held(lck_rw_t *lck, int exclusive)
912 {
913 #if !MACH_ASSERT
914 #pragma unused(lck, exclusive)
915 #endif
916 	LCK_RW_ASSERT(lck,
917 	    exclusive ? LCK_RW_ASSERT_EXCLUSIVE : LCK_RW_ASSERT_HELD);
918 }
919 
920 /*
921  * Return the number of bytes in the mbuf chain using the same
922  * method as m_length() or sballoc()
923  *
924  * Returns data len - starting from PKT start
925  * - retmbcnt - optional param to get total mbuf bytes in chain
926  * - retmbnum - optional param to get number of mbufs in chain
927  */
928 static unsigned int
cfil_data_length(struct mbuf * m,int * retmbcnt,int * retmbnum)929 cfil_data_length(struct mbuf *m, int *retmbcnt, int *retmbnum)
930 {
931 	struct mbuf *m0;
932 	unsigned int pktlen = 0;
933 	int mbcnt;
934 	int mbnum;
935 
936 	// Locate M_PKTHDR and mark as start of data if present
937 	for (m0 = m; m0 != NULL; m0 = m0->m_next) {
938 		if (m0->m_flags & M_PKTHDR) {
939 			m = m0;
940 			break;
941 		}
942 	}
943 
944 	if (retmbcnt == NULL && retmbnum == NULL) {
945 		return m_length(m);
946 	}
947 
948 	pktlen = 0;
949 	mbcnt = 0;
950 	mbnum = 0;
951 	for (m0 = m; m0 != NULL; m0 = m0->m_next) {
952 		pktlen += m0->m_len;
953 		mbnum++;
954 		mbcnt += MSIZE;
955 		if (m0->m_flags & M_EXT) {
956 			mbcnt += m0->m_ext.ext_size;
957 		}
958 	}
959 	if (retmbcnt) {
960 		*retmbcnt = mbcnt;
961 	}
962 	if (retmbnum) {
963 		*retmbnum = mbnum;
964 	}
965 	return pktlen;
966 }
967 
968 static struct mbuf *
cfil_data_start(struct mbuf * m)969 cfil_data_start(struct mbuf *m)
970 {
971 	struct mbuf *m0;
972 
973 	// Locate M_PKTHDR and use it as start of data if present
974 	for (m0 = m; m0 != NULL; m0 = m0->m_next) {
975 		if (m0->m_flags & M_PKTHDR) {
976 			return m0;
977 		}
978 	}
979 	return m;
980 }
981 
982 /*
983  * Common mbuf queue utilities
984  */
985 
986 static inline void
cfil_queue_init(struct cfil_queue * cfq)987 cfil_queue_init(struct cfil_queue *cfq)
988 {
989 	cfq->q_start = 0;
990 	cfq->q_end = 0;
991 	MBUFQ_INIT(&cfq->q_mq);
992 }
993 
994 static inline uint64_t
cfil_queue_drain(struct cfil_queue * cfq)995 cfil_queue_drain(struct cfil_queue *cfq)
996 {
997 	uint64_t drained = cfq->q_start - cfq->q_end;
998 	cfq->q_start = 0;
999 	cfq->q_end = 0;
1000 	MBUFQ_DRAIN(&cfq->q_mq);
1001 
1002 	return drained;
1003 }
1004 
1005 /* Return 1 when empty, 0 otherwise */
1006 static inline int
cfil_queue_empty(struct cfil_queue * cfq)1007 cfil_queue_empty(struct cfil_queue *cfq)
1008 {
1009 	return MBUFQ_EMPTY(&cfq->q_mq);
1010 }
1011 
1012 static inline uint64_t
cfil_queue_offset_first(struct cfil_queue * cfq)1013 cfil_queue_offset_first(struct cfil_queue *cfq)
1014 {
1015 	return cfq->q_start;
1016 }
1017 
1018 static inline uint64_t
cfil_queue_offset_last(struct cfil_queue * cfq)1019 cfil_queue_offset_last(struct cfil_queue *cfq)
1020 {
1021 	return cfq->q_end;
1022 }
1023 
1024 static inline uint64_t
cfil_queue_len(struct cfil_queue * cfq)1025 cfil_queue_len(struct cfil_queue *cfq)
1026 {
1027 	return cfq->q_end - cfq->q_start;
1028 }
1029 
1030 /*
1031  * Routines to verify some fundamental assumptions
1032  */
1033 
1034 static void
cfil_queue_verify(struct cfil_queue * cfq)1035 cfil_queue_verify(struct cfil_queue *cfq)
1036 {
1037 	mbuf_t chain;
1038 	mbuf_t m;
1039 	mbuf_t n;
1040 	uint64_t queuesize = 0;
1041 
1042 	/* Verify offset are ordered */
1043 	VERIFY(cfq->q_start <= cfq->q_end);
1044 
1045 	/*
1046 	 * When queue is empty, the offsets are equal otherwise the offsets
1047 	 * are different
1048 	 */
1049 	VERIFY((MBUFQ_EMPTY(&cfq->q_mq) && cfq->q_start == cfq->q_end) ||
1050 	    (!MBUFQ_EMPTY(&cfq->q_mq) &&
1051 	    cfq->q_start != cfq->q_end));
1052 
1053 	MBUFQ_FOREACH(chain, &cfq->q_mq) {
1054 		size_t chainsize = 0;
1055 		m = chain;
1056 		unsigned int mlen = cfil_data_length(m, NULL, NULL);
1057 		// skip the addr and control stuff if present
1058 		m = cfil_data_start(m);
1059 
1060 		if (m == NULL ||
1061 		    m == (void *)M_TAG_FREE_PATTERN ||
1062 		    m->m_next == (void *)M_TAG_FREE_PATTERN ||
1063 		    m->m_nextpkt == (void *)M_TAG_FREE_PATTERN) {
1064 			panic("%s - mq %p is free at %p", __func__,
1065 			    &cfq->q_mq, m);
1066 		}
1067 		for (n = m; n != NULL; n = n->m_next) {
1068 			if (n->m_type != MT_DATA &&
1069 			    n->m_type != MT_HEADER &&
1070 			    n->m_type != MT_OOBDATA) {
1071 				panic("%s - %p unsupported type %u", __func__,
1072 				    n, n->m_type);
1073 			}
1074 			chainsize += n->m_len;
1075 		}
1076 		if (mlen != chainsize) {
1077 			panic("%s - %p m_length() %u != chainsize %lu",
1078 			    __func__, m, mlen, chainsize);
1079 		}
1080 		queuesize += chainsize;
1081 	}
1082 	OS_ANALYZER_SUPPRESS("81031590") if (queuesize != cfq->q_end - cfq->q_start) {
1083 		panic("%s - %p queuesize %llu != offsetdiffs %llu", __func__,
1084 		    m, queuesize, cfq->q_end - cfq->q_start);
1085 	}
1086 }
1087 
1088 static void
cfil_queue_enqueue(struct cfil_queue * cfq,mbuf_t m,size_t len)1089 cfil_queue_enqueue(struct cfil_queue *cfq, mbuf_t m, size_t len)
1090 {
1091 	CFIL_QUEUE_VERIFY(cfq);
1092 
1093 	MBUFQ_ENQUEUE(&cfq->q_mq, m);
1094 	cfq->q_end += len;
1095 
1096 	CFIL_QUEUE_VERIFY(cfq);
1097 }
1098 
1099 static void
cfil_queue_remove(struct cfil_queue * cfq,mbuf_t m,size_t len)1100 cfil_queue_remove(struct cfil_queue *cfq, mbuf_t m, size_t len)
1101 {
1102 	CFIL_QUEUE_VERIFY(cfq);
1103 
1104 	VERIFY(cfil_data_length(m, NULL, NULL) == len);
1105 
1106 	MBUFQ_REMOVE(&cfq->q_mq, m);
1107 	MBUFQ_NEXT(m) = NULL;
1108 	cfq->q_start += len;
1109 
1110 	CFIL_QUEUE_VERIFY(cfq);
1111 }
1112 
1113 static mbuf_t
cfil_queue_first(struct cfil_queue * cfq)1114 cfil_queue_first(struct cfil_queue *cfq)
1115 {
1116 	return MBUFQ_FIRST(&cfq->q_mq);
1117 }
1118 
1119 static mbuf_t
cfil_queue_next(struct cfil_queue * cfq,mbuf_t m)1120 cfil_queue_next(struct cfil_queue *cfq, mbuf_t m)
1121 {
1122 #pragma unused(cfq)
1123 	return MBUFQ_NEXT(m);
1124 }
1125 
1126 static void
cfil_entry_buf_verify(struct cfe_buf * cfe_buf)1127 cfil_entry_buf_verify(struct cfe_buf *cfe_buf)
1128 {
1129 	CFIL_QUEUE_VERIFY(&cfe_buf->cfe_ctl_q);
1130 	CFIL_QUEUE_VERIFY(&cfe_buf->cfe_pending_q);
1131 
1132 	/* Verify the queues are ordered so that pending is before ctl */
1133 	VERIFY(cfe_buf->cfe_ctl_q.q_start >= cfe_buf->cfe_pending_q.q_end);
1134 
1135 	/* The peek offset cannot be less than the pass offset */
1136 	VERIFY(cfe_buf->cfe_peek_offset >= cfe_buf->cfe_pass_offset);
1137 
1138 	/* Make sure we've updated the offset we peeked at  */
1139 	VERIFY(cfe_buf->cfe_ctl_q.q_start <= cfe_buf->cfe_peeked);
1140 }
1141 
1142 static void
cfil_entry_verify(struct cfil_entry * entry)1143 cfil_entry_verify(struct cfil_entry *entry)
1144 {
1145 	cfil_entry_buf_verify(&entry->cfe_snd);
1146 	cfil_entry_buf_verify(&entry->cfe_rcv);
1147 }
1148 
1149 static void
cfil_info_buf_verify(struct cfi_buf * cfi_buf)1150 cfil_info_buf_verify(struct cfi_buf *cfi_buf)
1151 {
1152 	CFIL_QUEUE_VERIFY(&cfi_buf->cfi_inject_q);
1153 
1154 	VERIFY(cfi_buf->cfi_pending_first <= cfi_buf->cfi_pending_last);
1155 }
1156 
1157 static void
cfil_info_verify(struct cfil_info * cfil_info)1158 cfil_info_verify(struct cfil_info *cfil_info)
1159 {
1160 	int i;
1161 
1162 	if (cfil_info == NULL) {
1163 		return;
1164 	}
1165 
1166 	cfil_info_buf_verify(&cfil_info->cfi_snd);
1167 	cfil_info_buf_verify(&cfil_info->cfi_rcv);
1168 
1169 	for (i = 0; i < MAX_CONTENT_FILTER; i++) {
1170 		cfil_entry_verify(&cfil_info->cfi_entries[i]);
1171 	}
1172 }
1173 
1174 static void
verify_content_filter(struct content_filter * cfc)1175 verify_content_filter(struct content_filter *cfc)
1176 {
1177 	struct cfil_entry *entry;
1178 	uint32_t count = 0;
1179 
1180 	VERIFY(cfc->cf_sock_count >= 0);
1181 
1182 	TAILQ_FOREACH(entry, &cfc->cf_sock_entries, cfe_link) {
1183 		count++;
1184 		VERIFY(cfc == entry->cfe_filter);
1185 	}
1186 	VERIFY(count == cfc->cf_sock_count);
1187 }
1188 
1189 /*
1190  * Kernel control socket callbacks
1191  */
1192 static errno_t
cfil_ctl_connect(kern_ctl_ref kctlref,struct sockaddr_ctl * sac,void ** unitinfo)1193 cfil_ctl_connect(kern_ctl_ref kctlref, struct sockaddr_ctl *sac,
1194     void **unitinfo)
1195 {
1196 	errno_t error = 0;
1197 	struct content_filter *cfc = NULL;
1198 
1199 	CFIL_LOG(LOG_NOTICE, "");
1200 
1201 	cfc = zalloc_flags(content_filter_zone, Z_WAITOK | Z_ZERO | Z_NOFAIL);
1202 
1203 	cfil_rw_lock_exclusive(&cfil_lck_rw);
1204 
1205 	if (sac->sc_unit == 0 || sac->sc_unit > MAX_CONTENT_FILTER) {
1206 		CFIL_LOG(LOG_ERR, "bad sc_unit %u", sac->sc_unit);
1207 		error = EINVAL;
1208 	} else if (content_filters[sac->sc_unit - 1] != NULL) {
1209 		CFIL_LOG(LOG_ERR, "sc_unit %u in use", sac->sc_unit);
1210 		error = EADDRINUSE;
1211 	} else {
1212 		/*
1213 		 * kernel control socket kcunit numbers start at 1
1214 		 */
1215 		content_filters[sac->sc_unit - 1] = cfc;
1216 
1217 		cfc->cf_kcref = kctlref;
1218 		cfc->cf_kcunit = sac->sc_unit;
1219 		TAILQ_INIT(&cfc->cf_sock_entries);
1220 
1221 		*unitinfo = cfc;
1222 		cfil_active_count++;
1223 
1224 		if (cfil_active_count == 1) {
1225 			soflow_feat_set_functions(cfil_dgram_gc_needed, cfil_dgram_gc_perform,
1226 			    cfil_dgram_detach_entry, cfil_dgram_detach_db);
1227 		}
1228 
1229 		// Allocate periodic stats buffer for this filter
1230 		if (global_cfil_stats_report_buffers[cfc->cf_kcunit - 1] == NULL) {
1231 			cfil_rw_unlock_exclusive(&cfil_lck_rw);
1232 
1233 			struct cfil_stats_report_buffer *buf;
1234 
1235 			buf = kalloc_type(struct cfil_stats_report_buffer,
1236 			    Z_WAITOK | Z_ZERO | Z_NOFAIL);
1237 
1238 			cfil_rw_lock_exclusive(&cfil_lck_rw);
1239 
1240 			/* Another thread may have won the race */
1241 			if (global_cfil_stats_report_buffers[cfc->cf_kcunit - 1] != NULL) {
1242 				kfree_type(struct cfil_stats_report_buffer, buf);
1243 			} else {
1244 				global_cfil_stats_report_buffers[cfc->cf_kcunit - 1] = buf;
1245 			}
1246 		}
1247 	}
1248 	cfil_rw_unlock_exclusive(&cfil_lck_rw);
1249 
1250 	if (error != 0 && cfc != NULL) {
1251 		zfree(content_filter_zone, cfc);
1252 	}
1253 
1254 	if (error == 0) {
1255 		OSIncrementAtomic(&cfil_stats.cfs_ctl_connect_ok);
1256 	} else {
1257 		OSIncrementAtomic(&cfil_stats.cfs_ctl_connect_fail);
1258 	}
1259 
1260 	CFIL_LOG(LOG_INFO, "return %d cfil_active_count %u kcunit %u",
1261 	    error, cfil_active_count, sac->sc_unit);
1262 
1263 	return error;
1264 }
1265 
1266 static void
cfil_update_behavior_flags(void)1267 cfil_update_behavior_flags(void)
1268 {
1269 	struct content_filter *cfc = NULL;
1270 
1271 	// Update global flag
1272 	bool preserve_connections = false;
1273 	for (int i = 0; i < MAX_CONTENT_FILTER; i++) {
1274 		cfc = content_filters[i];
1275 		if (cfc != NULL) {
1276 			if (cfc->cf_flags & CFF_PRESERVE_CONNECTIONS) {
1277 				preserve_connections = true;
1278 			} else {
1279 				preserve_connections = false;
1280 				break;
1281 			}
1282 		}
1283 	}
1284 	if (preserve_connections == true) {
1285 		cfil_behavior_flags |= CFIL_BEHAVIOR_FLAG_PRESERVE_CONNECTIONS;
1286 	} else {
1287 		cfil_behavior_flags &= ~CFIL_BEHAVIOR_FLAG_PRESERVE_CONNECTIONS;
1288 	}
1289 	CFIL_LOG(LOG_INFO, "CFIL Preserve Connections - %s",
1290 	    (cfil_behavior_flags & CFIL_BEHAVIOR_FLAG_PRESERVE_CONNECTIONS) ? "On" : "Off");
1291 }
1292 
1293 static errno_t
cfil_ctl_disconnect(kern_ctl_ref kctlref,u_int32_t kcunit,void * unitinfo)1294 cfil_ctl_disconnect(kern_ctl_ref kctlref, u_int32_t kcunit, void *unitinfo)
1295 {
1296 #pragma unused(kctlref)
1297 	errno_t error = 0;
1298 	struct content_filter *cfc;
1299 	struct cfil_entry *entry;
1300 	uint64_t sock_flow_id = 0;
1301 
1302 	CFIL_LOG(LOG_NOTICE, "");
1303 
1304 	if (kcunit > MAX_CONTENT_FILTER) {
1305 		CFIL_LOG(LOG_ERR, "kcunit %u > MAX_CONTENT_FILTER (%d)",
1306 		    kcunit, MAX_CONTENT_FILTER);
1307 		error = EINVAL;
1308 		goto done;
1309 	}
1310 
1311 	cfc = (struct content_filter *)unitinfo;
1312 	if (cfc == NULL) {
1313 		goto done;
1314 	}
1315 
1316 	cfil_rw_lock_exclusive(&cfil_lck_rw);
1317 	if (content_filters[kcunit - 1] != cfc || cfc->cf_kcunit != kcunit) {
1318 		CFIL_LOG(LOG_ERR, "bad unit info %u)",
1319 		    kcunit);
1320 		cfil_rw_unlock_exclusive(&cfil_lck_rw);
1321 		goto done;
1322 	}
1323 	cfc->cf_flags |= CFF_DETACHING;
1324 	/*
1325 	 * Remove all sockets from the filter
1326 	 */
1327 	while ((entry = TAILQ_FIRST(&cfc->cf_sock_entries)) != NULL) {
1328 		cfil_rw_lock_assert_held(&cfil_lck_rw, 1);
1329 
1330 		verify_content_filter(cfc);
1331 		/*
1332 		 * Accept all outstanding data by pushing to next filter
1333 		 * or back to socket
1334 		 *
1335 		 * TBD: Actually we should make sure all data has been pushed
1336 		 * back to socket
1337 		 */
1338 		if (entry->cfe_cfil_info && entry->cfe_cfil_info->cfi_so) {
1339 			struct cfil_info *cfil_info = entry->cfe_cfil_info;
1340 			struct socket *so = cfil_info->cfi_so;
1341 			sock_flow_id = cfil_info->cfi_sock_id;
1342 
1343 			/* Need to let data flow immediately */
1344 			entry->cfe_flags |= CFEF_SENT_SOCK_ATTACHED |
1345 			    CFEF_DATA_START;
1346 
1347 			// Before we release global lock, retain the cfil_info -
1348 			// We attempt to retain a valid cfil_info to prevent any deallocation until
1349 			// we are done.  Abort retain if cfil_info has already entered the free code path.
1350 			if (cfil_info == NULL || os_ref_retain_try(&cfil_info->cfi_ref_count) == false) {
1351 				// Failing to retain cfil_info means detach is in progress already,
1352 				// remove entry from filter list and move on.
1353 				entry->cfe_filter = NULL;
1354 				entry->cfe_necp_control_unit = 0;
1355 				TAILQ_REMOVE(&cfc->cf_sock_entries, entry, cfe_link);
1356 				cfc->cf_sock_count--;
1357 				continue;
1358 			}
1359 
1360 			/*
1361 			 * Respect locking hierarchy
1362 			 */
1363 			cfil_rw_unlock_exclusive(&cfil_lck_rw);
1364 
1365 			// Search for socket from cfil_info sock_flow_id and lock so
1366 			so = cfil_socket_from_sock_id(sock_flow_id, false);
1367 			if (so == NULL || so != cfil_info->cfi_so) {
1368 				cfil_rw_lock_exclusive(&cfil_lck_rw);
1369 
1370 				// Socket has already been disconnected and removed from socket list.
1371 				// Remove entry from filter list and move on.
1372 				if (entry == TAILQ_FIRST(&cfc->cf_sock_entries)) {
1373 					entry->cfe_filter = NULL;
1374 					entry->cfe_necp_control_unit = 0;
1375 					TAILQ_REMOVE(&cfc->cf_sock_entries, entry, cfe_link);
1376 					cfc->cf_sock_count--;
1377 				}
1378 
1379 				goto release_cfil_info;
1380 			}
1381 
1382 			/*
1383 			 * When cfe_filter is NULL the filter is detached
1384 			 * and the entry has been removed from cf_sock_entries
1385 			 */
1386 			if ((so->so_cfil == NULL && so->so_flow_db == NULL) || entry->cfe_filter == NULL) {
1387 				cfil_rw_lock_exclusive(&cfil_lck_rw);
1388 				goto release;
1389 			}
1390 
1391 			(void) cfil_action_data_pass(so, cfil_info, kcunit, 1,
1392 			    CFM_MAX_OFFSET,
1393 			    CFM_MAX_OFFSET);
1394 
1395 			(void) cfil_action_data_pass(so, cfil_info, kcunit, 0,
1396 			    CFM_MAX_OFFSET,
1397 			    CFM_MAX_OFFSET);
1398 
1399 			cfil_rw_lock_exclusive(&cfil_lck_rw);
1400 
1401 			/*
1402 			 * Check again to make sure if the cfil_info is still valid
1403 			 * as the socket may have been unlocked when when calling
1404 			 * cfil_acquire_sockbuf()
1405 			 */
1406 			if (entry->cfe_filter == NULL ||
1407 			    (so->so_cfil == NULL && soflow_db_get_feature_context(so->so_flow_db, sock_flow_id) == NULL)) {
1408 				goto release;
1409 			}
1410 
1411 			/* The filter is now detached */
1412 			entry->cfe_flags |= CFEF_CFIL_DETACHED;
1413 
1414 			if (cfil_info->cfi_debug) {
1415 				cfil_info_log(LOG_INFO, cfil_info, "CFIL: FILTER DISCONNECTED");
1416 			}
1417 
1418 			CFIL_LOG(LOG_NOTICE, "so %llx detached %u",
1419 			    (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit);
1420 			if ((cfil_info->cfi_flags & CFIF_CLOSE_WAIT) &&
1421 			    cfil_filters_attached(so) == 0) {
1422 				CFIL_LOG(LOG_NOTICE, "so %llx waking",
1423 				    (uint64_t)VM_KERNEL_ADDRPERM(so));
1424 				wakeup((caddr_t)cfil_info);
1425 			}
1426 
1427 			/*
1428 			 * Remove the filter entry from the content filter
1429 			 * but leave the rest of the state intact as the queues
1430 			 * may not be empty yet
1431 			 */
1432 			entry->cfe_filter = NULL;
1433 			entry->cfe_necp_control_unit = 0;
1434 
1435 			TAILQ_REMOVE(&cfc->cf_sock_entries, entry, cfe_link);
1436 			cfc->cf_sock_count--;
1437 
1438 			// This is the last filter disconnecting, clear the cfil_info
1439 			// saved control unit so we will be able to drop this flow if
1440 			// a new filter get installed.
1441 			if (cfil_active_count == 1) {
1442 				cfil_info->cfi_filter_control_unit = 0;
1443 			}
1444 release:
1445 			socket_unlock(so, 1);
1446 
1447 release_cfil_info:
1448 			/*
1449 			 * Release reference on cfil_info.  To avoid double locking,
1450 			 * temporarily unlock in case it has been detached and we
1451 			 * end up freeing it which will take the global lock again.
1452 			 */
1453 			cfil_rw_unlock_exclusive(&cfil_lck_rw);
1454 			CFIL_INFO_FREE(cfil_info);
1455 			cfil_rw_lock_exclusive(&cfil_lck_rw);
1456 		}
1457 	}
1458 	verify_content_filter(cfc);
1459 
1460 	/* Free the stats buffer for this filter */
1461 	if (global_cfil_stats_report_buffers[cfc->cf_kcunit - 1] != NULL) {
1462 		kfree_type(struct cfil_stats_report_buffer,
1463 		    global_cfil_stats_report_buffers[cfc->cf_kcunit - 1]);
1464 		global_cfil_stats_report_buffers[cfc->cf_kcunit - 1] = NULL;
1465 	}
1466 	VERIFY(cfc->cf_sock_count == 0);
1467 
1468 	/*
1469 	 * Make filter inactive
1470 	 */
1471 	content_filters[kcunit - 1] = NULL;
1472 	cfil_active_count--;
1473 	cfil_update_behavior_flags();
1474 	cfil_rw_unlock_exclusive(&cfil_lck_rw);
1475 
1476 	if (cfc->cf_crypto_state != NULL) {
1477 		cfil_crypto_cleanup_state(cfc->cf_crypto_state);
1478 		cfc->cf_crypto_state = NULL;
1479 	}
1480 
1481 	zfree(content_filter_zone, cfc);
1482 done:
1483 	if (error == 0) {
1484 		OSIncrementAtomic(&cfil_stats.cfs_ctl_disconnect_ok);
1485 	} else {
1486 		OSIncrementAtomic(&cfil_stats.cfs_ctl_disconnect_fail);
1487 	}
1488 
1489 	CFIL_LOG(LOG_INFO, "return %d cfil_active_count %u kcunit %u",
1490 	    error, cfil_active_count, kcunit);
1491 
1492 	return error;
1493 }
1494 
1495 /*
1496  * cfil_acquire_sockbuf()
1497  *
1498  * Prevent any other thread from acquiring the sockbuf
1499  * We use sb_cfil_thread as a semaphore to prevent other threads from
1500  * messing with the sockbuf -- see sblock()
1501  * Note: We do not set SB_LOCK here because the thread may check or modify
1502  * SB_LOCK several times until it calls cfil_release_sockbuf() -- currently
1503  * sblock(), sbunlock() or sodefunct()
1504  */
1505 static int
cfil_acquire_sockbuf(struct socket * so,struct cfil_info * cfil_info,int outgoing)1506 cfil_acquire_sockbuf(struct socket *so, struct cfil_info *cfil_info, int outgoing)
1507 {
1508 	thread_t tp = current_thread();
1509 	struct sockbuf *sb = outgoing ? &so->so_snd : &so->so_rcv;
1510 	lck_mtx_t *mutex_held;
1511 	int error = 0;
1512 
1513 	/*
1514 	 * Wait until no thread is holding the sockbuf and other content
1515 	 * filter threads have released the sockbuf
1516 	 */
1517 	while ((sb->sb_flags & SB_LOCK) ||
1518 	    (sb->sb_cfil_thread != NULL && sb->sb_cfil_thread != tp)) {
1519 		if (so->so_proto->pr_getlock != NULL) {
1520 			mutex_held = (*so->so_proto->pr_getlock)(so, PR_F_WILLUNLOCK);
1521 		} else {
1522 			mutex_held = so->so_proto->pr_domain->dom_mtx;
1523 		}
1524 
1525 		LCK_MTX_ASSERT(mutex_held, LCK_MTX_ASSERT_OWNED);
1526 
1527 		sb->sb_wantlock++;
1528 		VERIFY(sb->sb_wantlock != 0);
1529 
1530 		msleep(&sb->sb_flags, mutex_held, PSOCK, "cfil_acquire_sockbuf",
1531 		    NULL);
1532 
1533 		VERIFY(sb->sb_wantlock != 0);
1534 		sb->sb_wantlock--;
1535 	}
1536 	/*
1537 	 * Use reference count for repetitive calls on same thread
1538 	 */
1539 	if (sb->sb_cfil_refs == 0) {
1540 		VERIFY(sb->sb_cfil_thread == NULL);
1541 		VERIFY((sb->sb_flags & SB_LOCK) == 0);
1542 
1543 		sb->sb_cfil_thread = tp;
1544 		sb->sb_flags |= SB_LOCK;
1545 	}
1546 	sb->sb_cfil_refs++;
1547 
1548 	/* We acquire the socket buffer when we need to cleanup */
1549 	if (cfil_info == NULL) {
1550 		CFIL_LOG(LOG_ERR, "so %llx cfil detached",
1551 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
1552 		error = 0;
1553 	} else if (cfil_info->cfi_flags & CFIF_DROP) {
1554 		CFIL_LOG(LOG_ERR, "so %llx drop set",
1555 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
1556 		error = EPIPE;
1557 	}
1558 
1559 	return error;
1560 }
1561 
1562 static void
cfil_release_sockbuf(struct socket * so,int outgoing)1563 cfil_release_sockbuf(struct socket *so, int outgoing)
1564 {
1565 	struct sockbuf *sb = outgoing ? &so->so_snd : &so->so_rcv;
1566 	thread_t tp = current_thread();
1567 
1568 	socket_lock_assert_owned(so);
1569 
1570 	if (sb->sb_cfil_thread != NULL && sb->sb_cfil_thread != tp) {
1571 		panic("%s sb_cfil_thread %p not current %p", __func__,
1572 		    sb->sb_cfil_thread, tp);
1573 	}
1574 	/*
1575 	 * Don't panic if we are defunct because SB_LOCK has
1576 	 * been cleared by sodefunct()
1577 	 */
1578 	if (!(so->so_flags & SOF_DEFUNCT) && !(sb->sb_flags & SB_LOCK)) {
1579 		panic("%s SB_LOCK not set on %p", __func__,
1580 		    sb);
1581 	}
1582 	/*
1583 	 * We can unlock when the thread unwinds to the last reference
1584 	 */
1585 	sb->sb_cfil_refs--;
1586 	if (sb->sb_cfil_refs == 0) {
1587 		sb->sb_cfil_thread = NULL;
1588 		sb->sb_flags &= ~SB_LOCK;
1589 
1590 		if (sb->sb_wantlock > 0) {
1591 			wakeup(&sb->sb_flags);
1592 		}
1593 	}
1594 }
1595 
1596 cfil_sock_id_t
cfil_sock_id_from_socket(struct socket * so)1597 cfil_sock_id_from_socket(struct socket *so)
1598 {
1599 	if ((so->so_flags & SOF_CONTENT_FILTER) && so->so_cfil) {
1600 		return so->so_cfil->cfi_sock_id;
1601 	} else {
1602 		return CFIL_SOCK_ID_NONE;
1603 	}
1604 }
1605 
1606 /*
1607  * cfil_socket_safe_lock -
1608  * This routine attempts to lock the socket safely.
1609  *
1610  * The passed in pcbinfo is assumed to be locked and must be unlocked once the
1611  * inp state is safeguarded and before we attempt to lock/unlock the socket.
1612  * This is to prevent getting blocked by socket_lock() while holding the pcbinfo
1613  * lock, avoiding potential deadlock with other processes contending for the same
1614  * resources.  This is also to avoid double locking the pcbinfo for rip sockets
1615  * since rip_unlock() will lock ripcbinfo if it needs to dispose inpcb when
1616  * so_usecount is 0.
1617  */
1618 static bool
cfil_socket_safe_lock(struct inpcb * inp,struct inpcbinfo * pcbinfo)1619 cfil_socket_safe_lock(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1620 {
1621 	struct socket *so = NULL;
1622 
1623 	VERIFY(pcbinfo != NULL);
1624 
1625 	if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) != WNT_STOPUSING) {
1626 		// Safeguarded the inp state, unlock pcbinfo before locking socket.
1627 		lck_rw_done(&pcbinfo->ipi_lock);
1628 
1629 		so = inp->inp_socket;
1630 		socket_lock(so, 1);
1631 		if (in_pcb_checkstate(inp, WNT_RELEASE, 1) != WNT_STOPUSING) {
1632 			return true;
1633 		}
1634 	} else {
1635 		// Failed to safeguarded the inp state, unlock pcbinfo and abort.
1636 		lck_rw_done(&pcbinfo->ipi_lock);
1637 	}
1638 
1639 	if (so) {
1640 		socket_unlock(so, 1);
1641 	}
1642 	return false;
1643 }
1644 
1645 static struct socket *
cfil_socket_from_sock_id(cfil_sock_id_t cfil_sock_id,bool udp_only)1646 cfil_socket_from_sock_id(cfil_sock_id_t cfil_sock_id, bool udp_only)
1647 {
1648 	struct socket *so = NULL;
1649 	u_int64_t gencnt = cfil_sock_id >> 32;
1650 	u_int32_t flowhash = (u_int32_t)(cfil_sock_id & 0x0ffffffff);
1651 	struct inpcb *inp = NULL;
1652 	struct inpcbinfo *pcbinfo = NULL;
1653 
1654 	if (udp_only) {
1655 		goto find_udp;
1656 	}
1657 
1658 	pcbinfo = &tcbinfo;
1659 	lck_rw_lock_shared(&pcbinfo->ipi_lock);
1660 	LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
1661 		if (inp->inp_state != INPCB_STATE_DEAD &&
1662 		    inp->inp_socket != NULL &&
1663 		    inp->inp_flowhash == flowhash &&
1664 		    (inp->inp_socket->so_gencnt & 0x0ffffffff) == gencnt &&
1665 		    inp->inp_socket->so_cfil != NULL) {
1666 			if (cfil_socket_safe_lock(inp, pcbinfo)) {
1667 				so = inp->inp_socket;
1668 			}
1669 			/* pcbinfo is already unlocked, we are done. */
1670 			goto done;
1671 		}
1672 	}
1673 	lck_rw_done(&pcbinfo->ipi_lock);
1674 	if (so != NULL) {
1675 		goto done;
1676 	}
1677 
1678 find_udp:
1679 
1680 	pcbinfo = &udbinfo;
1681 	lck_rw_lock_shared(&pcbinfo->ipi_lock);
1682 	LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
1683 		if (inp->inp_state != INPCB_STATE_DEAD &&
1684 		    inp->inp_socket != NULL &&
1685 		    inp->inp_socket->so_flow_db != NULL &&
1686 		    (inp->inp_socket->so_gencnt & 0x0ffffffff) == gencnt) {
1687 			if (cfil_socket_safe_lock(inp, pcbinfo)) {
1688 				so = inp->inp_socket;
1689 			}
1690 			/* pcbinfo is already unlocked, we are done. */
1691 			goto done;
1692 		}
1693 	}
1694 	lck_rw_done(&pcbinfo->ipi_lock);
1695 	if (so != NULL) {
1696 		goto done;
1697 	}
1698 
1699 	pcbinfo = &ripcbinfo;
1700 	lck_rw_lock_shared(&pcbinfo->ipi_lock);
1701 	LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
1702 		if (inp->inp_state != INPCB_STATE_DEAD &&
1703 		    inp->inp_socket != NULL &&
1704 		    inp->inp_socket->so_flow_db != NULL &&
1705 		    (inp->inp_socket->so_gencnt & 0x0ffffffff) == gencnt) {
1706 			if (cfil_socket_safe_lock(inp, pcbinfo)) {
1707 				so = inp->inp_socket;
1708 			}
1709 			/* pcbinfo is already unlocked, we are done. */
1710 			goto done;
1711 		}
1712 	}
1713 	lck_rw_done(&pcbinfo->ipi_lock);
1714 
1715 done:
1716 	if (so == NULL) {
1717 		OSIncrementAtomic(&cfil_stats.cfs_sock_id_not_found);
1718 		CFIL_LOG(LOG_DEBUG,
1719 		    "no socket for sock_id %llx gencnt %llx flowhash %x",
1720 		    cfil_sock_id, gencnt, flowhash);
1721 	}
1722 
1723 	return so;
1724 }
1725 
1726 static struct socket *
cfil_socket_from_client_uuid(uuid_t necp_client_uuid,bool * cfil_attached)1727 cfil_socket_from_client_uuid(uuid_t necp_client_uuid, bool *cfil_attached)
1728 {
1729 	struct socket *so = NULL;
1730 	struct inpcb *inp = NULL;
1731 	struct inpcbinfo *pcbinfo = &tcbinfo;
1732 
1733 	lck_rw_lock_shared(&pcbinfo->ipi_lock);
1734 	LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
1735 		if (inp->inp_state != INPCB_STATE_DEAD &&
1736 		    inp->inp_socket != NULL &&
1737 		    uuid_compare(inp->necp_client_uuid, necp_client_uuid) == 0) {
1738 			*cfil_attached = (inp->inp_socket->so_cfil != NULL);
1739 			if (cfil_socket_safe_lock(inp, pcbinfo)) {
1740 				so = inp->inp_socket;
1741 			}
1742 			/* pcbinfo is already unlocked, we are done. */
1743 			goto done;
1744 		}
1745 	}
1746 	lck_rw_done(&pcbinfo->ipi_lock);
1747 	if (so != NULL) {
1748 		goto done;
1749 	}
1750 
1751 	pcbinfo = &udbinfo;
1752 	lck_rw_lock_shared(&pcbinfo->ipi_lock);
1753 	LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
1754 		if (inp->inp_state != INPCB_STATE_DEAD &&
1755 		    inp->inp_socket != NULL &&
1756 		    uuid_compare(inp->necp_client_uuid, necp_client_uuid) == 0) {
1757 			*cfil_attached = (inp->inp_socket->so_flow_db != NULL);
1758 			if (cfil_socket_safe_lock(inp, pcbinfo)) {
1759 				so = inp->inp_socket;
1760 			}
1761 			/* pcbinfo is already unlocked, we are done. */
1762 			goto done;
1763 		}
1764 	}
1765 	lck_rw_done(&pcbinfo->ipi_lock);
1766 
1767 done:
1768 	return so;
1769 }
1770 
1771 static void
cfil_info_stats_toggle(struct cfil_info * cfil_info,struct cfil_entry * entry,uint32_t report_frequency)1772 cfil_info_stats_toggle(struct cfil_info *cfil_info, struct cfil_entry *entry, uint32_t report_frequency)
1773 {
1774 	struct cfil_info *cfil = NULL;
1775 	Boolean found = FALSE;
1776 	int kcunit;
1777 
1778 	if (cfil_info == NULL) {
1779 		return;
1780 	}
1781 
1782 	if (report_frequency) {
1783 		if (entry == NULL) {
1784 			return;
1785 		}
1786 
1787 		// Update stats reporting frequency.
1788 		if (entry->cfe_stats_report_frequency != report_frequency) {
1789 			entry->cfe_stats_report_frequency = report_frequency;
1790 			if (entry->cfe_stats_report_frequency < CFIL_STATS_REPORT_INTERVAL_MIN_MSEC) {
1791 				entry->cfe_stats_report_frequency = CFIL_STATS_REPORT_INTERVAL_MIN_MSEC;
1792 			}
1793 			microuptime(&entry->cfe_stats_report_ts);
1794 
1795 			// Insert cfil_info into list only if it is not in yet.
1796 			TAILQ_FOREACH(cfil, &cfil_sock_head_stats, cfi_link_stats) {
1797 				if (cfil == cfil_info) {
1798 					return;
1799 				}
1800 			}
1801 
1802 			TAILQ_INSERT_TAIL(&cfil_sock_head_stats, cfil_info, cfi_link_stats);
1803 
1804 			// Wake up stats thread if this is first flow added
1805 			if (cfil_sock_attached_stats_count == 0) {
1806 				thread_wakeup((caddr_t)&cfil_sock_attached_stats_count);
1807 			}
1808 			cfil_sock_attached_stats_count++;
1809 
1810 			if (cfil_info->cfi_debug && cfil_log_stats) {
1811 				CFIL_LOG(LOG_DEBUG, "CFIL: VERDICT RECEIVED - STATS FLOW INSERTED: <so %llx sockID %llu> stats frequency %d msecs",
1812 				    cfil_info->cfi_so ? (uint64_t)VM_KERNEL_ADDRPERM(cfil_info->cfi_so) : 0,
1813 				    cfil_info->cfi_sock_id,
1814 				    entry->cfe_stats_report_frequency);
1815 			}
1816 		}
1817 	} else {
1818 		// Turn off stats reporting for this filter.
1819 		if (entry != NULL) {
1820 			// Already off, no change.
1821 			if (entry->cfe_stats_report_frequency == 0) {
1822 				return;
1823 			}
1824 
1825 			entry->cfe_stats_report_frequency = 0;
1826 			// If cfil_info still has filter(s) asking for stats, no need to remove from list.
1827 			for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
1828 				if (cfil_info->cfi_entries[kcunit - 1].cfe_stats_report_frequency > 0) {
1829 					return;
1830 				}
1831 			}
1832 		}
1833 
1834 		// No more filter asking for stats for this cfil_info, remove from list.
1835 		if (!TAILQ_EMPTY(&cfil_sock_head_stats)) {
1836 			found = FALSE;
1837 			TAILQ_FOREACH(cfil, &cfil_sock_head_stats, cfi_link_stats) {
1838 				if (cfil == cfil_info) {
1839 					found = TRUE;
1840 					break;
1841 				}
1842 			}
1843 			if (found) {
1844 				cfil_sock_attached_stats_count--;
1845 				TAILQ_REMOVE(&cfil_sock_head_stats, cfil_info, cfi_link_stats);
1846 				if (cfil_info->cfi_debug && cfil_log_stats) {
1847 					CFIL_LOG(LOG_DEBUG, "CFIL: VERDICT RECEIVED - STATS FLOW DELETED: <so %llx sockID %llu> stats frequency reset",
1848 					    cfil_info->cfi_so ? (uint64_t)VM_KERNEL_ADDRPERM(cfil_info->cfi_so) : 0,
1849 					    cfil_info->cfi_sock_id);
1850 				}
1851 			}
1852 		}
1853 	}
1854 }
1855 
1856 static errno_t
cfil_ctl_send(kern_ctl_ref kctlref,u_int32_t kcunit,void * unitinfo,mbuf_t m,int flags)1857 cfil_ctl_send(kern_ctl_ref kctlref, u_int32_t kcunit, void *unitinfo, mbuf_t m,
1858     int flags)
1859 {
1860 #pragma unused(kctlref, flags)
1861 	errno_t error = 0;
1862 	struct cfil_msg_hdr *msghdr;
1863 	struct content_filter *cfc = (struct content_filter *)unitinfo;
1864 	struct socket *so;
1865 	struct cfil_msg_action *action_msg;
1866 	struct cfil_entry *entry;
1867 	struct cfil_info *cfil_info = NULL;
1868 	unsigned int data_len = 0;
1869 
1870 	CFIL_LOG(LOG_INFO, "");
1871 
1872 	if (cfc == NULL) {
1873 		CFIL_LOG(LOG_ERR, "no unitinfo");
1874 		error = EINVAL;
1875 		goto done;
1876 	}
1877 
1878 	if (kcunit > MAX_CONTENT_FILTER) {
1879 		CFIL_LOG(LOG_ERR, "kcunit %u > MAX_CONTENT_FILTER (%d)",
1880 		    kcunit, MAX_CONTENT_FILTER);
1881 		error = EINVAL;
1882 		goto done;
1883 	}
1884 	if (m == NULL) {
1885 		CFIL_LOG(LOG_ERR, "null mbuf");
1886 		error = EINVAL;
1887 		goto done;
1888 	}
1889 	data_len = m_length(m);
1890 
1891 	if (data_len < sizeof(struct cfil_msg_hdr)) {
1892 		CFIL_LOG(LOG_ERR, "too short %u", data_len);
1893 		error = EINVAL;
1894 		goto done;
1895 	}
1896 	msghdr = (struct cfil_msg_hdr *)mbuf_data(m);
1897 	if (msghdr->cfm_version != CFM_VERSION_CURRENT) {
1898 		CFIL_LOG(LOG_ERR, "bad version %u", msghdr->cfm_version);
1899 		error = EINVAL;
1900 		goto done;
1901 	}
1902 	if (msghdr->cfm_type != CFM_TYPE_ACTION) {
1903 		CFIL_LOG(LOG_ERR, "bad type %u", msghdr->cfm_type);
1904 		error = EINVAL;
1905 		goto done;
1906 	}
1907 	if (msghdr->cfm_len > data_len) {
1908 		CFIL_LOG(LOG_ERR, "bad length %u", msghdr->cfm_len);
1909 		error = EINVAL;
1910 		goto done;
1911 	}
1912 
1913 	/* Validate action operation */
1914 	switch (msghdr->cfm_op) {
1915 	case CFM_OP_DATA_UPDATE:
1916 		OSIncrementAtomic(
1917 			&cfil_stats.cfs_ctl_action_data_update);
1918 		break;
1919 	case CFM_OP_DROP:
1920 		OSIncrementAtomic(&cfil_stats.cfs_ctl_action_drop);
1921 		break;
1922 	case CFM_OP_BLESS_CLIENT:
1923 		if (msghdr->cfm_len != sizeof(struct cfil_msg_bless_client)) {
1924 			OSIncrementAtomic(&cfil_stats.cfs_ctl_action_bad_len);
1925 			error = EINVAL;
1926 			CFIL_LOG(LOG_ERR, "bad len: %u for op %u",
1927 			    msghdr->cfm_len,
1928 			    msghdr->cfm_op);
1929 			goto done;
1930 		}
1931 		error = cfil_action_bless_client(kcunit, msghdr);
1932 		goto done;
1933 	case CFM_OP_SET_CRYPTO_KEY:
1934 		if (msghdr->cfm_len != sizeof(struct cfil_msg_set_crypto_key)) {
1935 			OSIncrementAtomic(&cfil_stats.cfs_ctl_action_bad_len);
1936 			error = EINVAL;
1937 			CFIL_LOG(LOG_ERR, "bad len: %u for op %u",
1938 			    msghdr->cfm_len,
1939 			    msghdr->cfm_op);
1940 			goto done;
1941 		}
1942 		error = cfil_action_set_crypto_key(kcunit, msghdr);
1943 		goto done;
1944 	default:
1945 		OSIncrementAtomic(&cfil_stats.cfs_ctl_action_bad_op);
1946 		CFIL_LOG(LOG_ERR, "bad op %u", msghdr->cfm_op);
1947 		error = EINVAL;
1948 		goto done;
1949 	}
1950 	if (msghdr->cfm_len != sizeof(struct cfil_msg_action)) {
1951 		OSIncrementAtomic(&cfil_stats.cfs_ctl_action_bad_len);
1952 		error = EINVAL;
1953 		CFIL_LOG(LOG_ERR, "bad len: %u for op %u",
1954 		    msghdr->cfm_len,
1955 		    msghdr->cfm_op);
1956 		goto done;
1957 	}
1958 	cfil_rw_lock_shared(&cfil_lck_rw);
1959 	if (cfc != (void *)content_filters[kcunit - 1]) {
1960 		CFIL_LOG(LOG_ERR, "unitinfo does not match for kcunit %u",
1961 		    kcunit);
1962 		error = EINVAL;
1963 		cfil_rw_unlock_shared(&cfil_lck_rw);
1964 		goto done;
1965 	}
1966 	cfil_rw_unlock_shared(&cfil_lck_rw);
1967 
1968 	// Search for socket (TCP+UDP and lock so)
1969 	so = cfil_socket_from_sock_id(msghdr->cfm_sock_id, false);
1970 	if (so == NULL) {
1971 		CFIL_LOG(LOG_NOTICE, "bad sock_id %llx",
1972 		    msghdr->cfm_sock_id);
1973 		error = EINVAL;
1974 		goto done;
1975 	}
1976 
1977 	cfil_info = so->so_flow_db != NULL ?
1978 	    soflow_db_get_feature_context(so->so_flow_db, msghdr->cfm_sock_id) : so->so_cfil;
1979 
1980 	// We should not obtain global lock here in order to avoid deadlock down the path.
1981 	// But we attempt to retain a valid cfil_info to prevent any deallocation until
1982 	// we are done.  Abort retain if cfil_info has already entered the free code path.
1983 	if (cfil_info && os_ref_retain_try(&cfil_info->cfi_ref_count) == false) {
1984 		socket_unlock(so, 1);
1985 		goto done;
1986 	}
1987 
1988 	if (cfil_info == NULL) {
1989 		CFIL_LOG(LOG_NOTICE, "so %llx <id %llu> not attached",
1990 		    (uint64_t)VM_KERNEL_ADDRPERM(so), msghdr->cfm_sock_id);
1991 		error = EINVAL;
1992 		goto unlock;
1993 	} else if (cfil_info->cfi_flags & CFIF_DROP) {
1994 		CFIL_LOG(LOG_NOTICE, "so %llx drop set",
1995 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
1996 		error = EINVAL;
1997 		goto unlock;
1998 	}
1999 
2000 	if (cfil_info->cfi_debug) {
2001 		cfil_info_log(LOG_DEBUG, cfil_info, "CFIL: RECEIVED MSG FROM FILTER");
2002 	}
2003 
2004 	entry = &cfil_info->cfi_entries[kcunit - 1];
2005 	if (entry->cfe_filter == NULL) {
2006 		CFIL_LOG(LOG_NOTICE, "so %llx no filter",
2007 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
2008 		error = EINVAL;
2009 		goto unlock;
2010 	}
2011 
2012 	if (entry->cfe_flags & CFEF_SENT_SOCK_ATTACHED) {
2013 		entry->cfe_flags |= CFEF_DATA_START;
2014 	} else {
2015 		CFIL_LOG(LOG_ERR,
2016 		    "so %llx attached not sent for %u",
2017 		    (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit);
2018 		error = EINVAL;
2019 		goto unlock;
2020 	}
2021 
2022 	microuptime(&entry->cfe_last_action);
2023 	CFI_ADD_TIME_LOG(cfil_info, &entry->cfe_last_action, &cfil_info->cfi_first_event, msghdr->cfm_op);
2024 
2025 	action_msg = (struct cfil_msg_action *)msghdr;
2026 
2027 	switch (msghdr->cfm_op) {
2028 	case CFM_OP_DATA_UPDATE:
2029 
2030 		if (cfil_info->cfi_debug) {
2031 			cfil_info_log(LOG_DEBUG, cfil_info, "CFIL: RECEIVED CFM_OP_DATA_UPDATE");
2032 			CFIL_LOG(LOG_DEBUG, "CFIL: VERDICT RECEIVED: <so %llx sockID %llu> <IN peek:%llu pass:%llu, OUT peek:%llu pass:%llu>",
2033 			    (uint64_t)VM_KERNEL_ADDRPERM(so),
2034 			    cfil_info->cfi_sock_id,
2035 			    action_msg->cfa_in_peek_offset, action_msg->cfa_in_pass_offset,
2036 			    action_msg->cfa_out_peek_offset, action_msg->cfa_out_pass_offset);
2037 		}
2038 
2039 		/*
2040 		 * Received verdict, at this point we know this
2041 		 * socket connection is allowed.  Unblock thread
2042 		 * immediately before proceeding to process the verdict.
2043 		 */
2044 		cfil_sock_received_verdict(so);
2045 
2046 		if (action_msg->cfa_out_peek_offset != 0 ||
2047 		    action_msg->cfa_out_pass_offset != 0) {
2048 			error = cfil_action_data_pass(so, cfil_info, kcunit, 1,
2049 			    action_msg->cfa_out_pass_offset,
2050 			    action_msg->cfa_out_peek_offset);
2051 		}
2052 		if (error == EJUSTRETURN) {
2053 			error = 0;
2054 		}
2055 		if (error != 0) {
2056 			break;
2057 		}
2058 		if (action_msg->cfa_in_peek_offset != 0 ||
2059 		    action_msg->cfa_in_pass_offset != 0) {
2060 			error = cfil_action_data_pass(so, cfil_info, kcunit, 0,
2061 			    action_msg->cfa_in_pass_offset,
2062 			    action_msg->cfa_in_peek_offset);
2063 		}
2064 		if (error == EJUSTRETURN) {
2065 			error = 0;
2066 		}
2067 
2068 		// Toggle stats reporting according to received verdict.
2069 		cfil_rw_lock_exclusive(&cfil_lck_rw);
2070 		cfil_info_stats_toggle(cfil_info, entry, action_msg->cfa_stats_frequency);
2071 		cfil_rw_unlock_exclusive(&cfil_lck_rw);
2072 
2073 		break;
2074 
2075 	case CFM_OP_DROP:
2076 		if (cfil_info->cfi_debug) {
2077 			cfil_info_log(LOG_DEBUG, cfil_info, "CFIL: RECEIVED CFM_OP_DROP");
2078 			CFIL_LOG(LOG_DEBUG, "CFIL: VERDICT DROP RECEIVED: <so %llx sockID %llu> <IN peek:%llu pass:%llu, OUT peek:%llu pass:%llu>",
2079 			    (uint64_t)VM_KERNEL_ADDRPERM(so),
2080 			    cfil_info->cfi_sock_id,
2081 			    action_msg->cfa_in_peek_offset, action_msg->cfa_in_pass_offset,
2082 			    action_msg->cfa_out_peek_offset, action_msg->cfa_out_pass_offset);
2083 		}
2084 
2085 		error = cfil_action_drop(so, cfil_info, kcunit);
2086 		cfil_sock_received_verdict(so);
2087 		break;
2088 
2089 	default:
2090 		error = EINVAL;
2091 		break;
2092 	}
2093 unlock:
2094 	CFIL_INFO_FREE(cfil_info)
2095 	socket_unlock(so, 1);
2096 done:
2097 	mbuf_freem(m);
2098 
2099 	if (error == 0) {
2100 		OSIncrementAtomic(&cfil_stats.cfs_ctl_send_ok);
2101 	} else {
2102 		OSIncrementAtomic(&cfil_stats.cfs_ctl_send_bad);
2103 	}
2104 
2105 	return error;
2106 }
2107 
2108 static errno_t
cfil_ctl_getopt(kern_ctl_ref kctlref,u_int32_t kcunit,void * unitinfo,int opt,void * data,size_t * len)2109 cfil_ctl_getopt(kern_ctl_ref kctlref, u_int32_t kcunit, void *unitinfo,
2110     int opt, void *data, size_t *len)
2111 {
2112 #pragma unused(kctlref, opt)
2113 	struct cfil_info *cfil_info = NULL;
2114 	errno_t error = 0;
2115 	struct content_filter *cfc = (struct content_filter *)unitinfo;
2116 
2117 	CFIL_LOG(LOG_NOTICE, "");
2118 
2119 	if (cfc == NULL) {
2120 		CFIL_LOG(LOG_ERR, "no unitinfo");
2121 		return EINVAL;
2122 	}
2123 
2124 	cfil_rw_lock_shared(&cfil_lck_rw);
2125 
2126 	if (kcunit > MAX_CONTENT_FILTER) {
2127 		CFIL_LOG(LOG_ERR, "kcunit %u > MAX_CONTENT_FILTER (%d)",
2128 		    kcunit, MAX_CONTENT_FILTER);
2129 		error = EINVAL;
2130 		goto done;
2131 	}
2132 	if (cfc != (void *)content_filters[kcunit - 1]) {
2133 		CFIL_LOG(LOG_ERR, "unitinfo does not match for kcunit %u",
2134 		    kcunit);
2135 		error = EINVAL;
2136 		goto done;
2137 	}
2138 	switch (opt) {
2139 	case CFIL_OPT_NECP_CONTROL_UNIT:
2140 		if (*len < sizeof(uint32_t)) {
2141 			CFIL_LOG(LOG_ERR, "len too small %lu", *len);
2142 			error = EINVAL;
2143 			goto done;
2144 		}
2145 		if (data != NULL) {
2146 			*(uint32_t *)data = cfc->cf_necp_control_unit;
2147 		}
2148 		break;
2149 	case CFIL_OPT_PRESERVE_CONNECTIONS:
2150 		if (*len < sizeof(uint32_t)) {
2151 			CFIL_LOG(LOG_ERR, "CFIL_OPT_PRESERVE_CONNECTIONS len too small %lu", *len);
2152 			error = EINVAL;
2153 			goto done;
2154 		}
2155 		if (data != NULL) {
2156 			*(uint32_t *)data = (cfc->cf_flags & CFF_PRESERVE_CONNECTIONS) ? true : false;
2157 		}
2158 		break;
2159 	case CFIL_OPT_GET_SOCKET_INFO:
2160 		if (*len != sizeof(struct cfil_opt_sock_info)) {
2161 			CFIL_LOG(LOG_ERR, "len does not match %lu", *len);
2162 			error = EINVAL;
2163 			goto done;
2164 		}
2165 		if (data == NULL) {
2166 			CFIL_LOG(LOG_ERR, "data not passed");
2167 			error = EINVAL;
2168 			goto done;
2169 		}
2170 
2171 		struct cfil_opt_sock_info *sock_info =
2172 		    (struct cfil_opt_sock_info *) data;
2173 
2174 		// Unlock here so that we never hold both cfil_lck_rw and the
2175 		// socket_lock at the same time. Otherwise, this can deadlock
2176 		// because soclose() takes the socket_lock and then exclusive
2177 		// cfil_lck_rw and we require the opposite order.
2178 
2179 		// WARNING: Be sure to never use anything protected
2180 		//     by cfil_lck_rw beyond this point.
2181 		// WARNING: Be sure to avoid fallthrough and
2182 		//     goto return_already_unlocked from this branch.
2183 		cfil_rw_unlock_shared(&cfil_lck_rw);
2184 
2185 		// Search (TCP+UDP) and lock socket
2186 		struct socket *sock =
2187 		    cfil_socket_from_sock_id(sock_info->cfs_sock_id, false);
2188 		if (sock == NULL) {
2189 			CFIL_LOG(LOG_ERR, "CFIL: GET_SOCKET_INFO failed: bad sock_id %llu",
2190 			    sock_info->cfs_sock_id);
2191 			error = ENOENT;
2192 			goto return_already_unlocked;
2193 		}
2194 
2195 		cfil_info = (sock->so_flow_db != NULL) ?
2196 		    soflow_db_get_feature_context(sock->so_flow_db, sock_info->cfs_sock_id) : sock->so_cfil;
2197 
2198 		if (cfil_info == NULL) {
2199 			CFIL_LOG(LOG_INFO, "CFIL: GET_SOCKET_INFO failed: so %llx not attached, cannot fetch info",
2200 			    (uint64_t)VM_KERNEL_ADDRPERM(sock));
2201 			error = EINVAL;
2202 			socket_unlock(sock, 1);
2203 			goto return_already_unlocked;
2204 		}
2205 
2206 		if (sock->so_proto == NULL || sock->so_proto->pr_domain == NULL) {
2207 			CFIL_LOG(LOG_INFO, "CFIL: GET_SOCKET_INFO failed: so %llx NULL so_proto / pr_domain",
2208 			    (uint64_t)VM_KERNEL_ADDRPERM(sock));
2209 			error = EINVAL;
2210 			socket_unlock(sock, 1);
2211 			goto return_already_unlocked;
2212 		}
2213 
2214 		// Fill out family, type, and protocol
2215 		sock_info->cfs_sock_family = sock->so_proto->pr_domain->dom_family;
2216 		sock_info->cfs_sock_type = sock->so_proto->pr_type;
2217 		sock_info->cfs_sock_protocol = GET_SO_PROTO(sock);
2218 
2219 		// Source and destination addresses
2220 		struct inpcb *inp = sotoinpcb(sock);
2221 		if (inp->inp_vflag & INP_IPV6) {
2222 			struct in6_addr *laddr = NULL, *faddr = NULL;
2223 			u_int16_t lport = 0, fport = 0;
2224 
2225 			cfil_get_flow_address_v6(cfil_info->cfi_hash_entry, inp,
2226 			    &laddr, &faddr, &lport, &fport);
2227 			fill_ip6_sockaddr_4_6(&sock_info->cfs_local, laddr, lport, inp->inp_lifscope);
2228 			fill_ip6_sockaddr_4_6(&sock_info->cfs_remote, faddr, fport, inp->inp_fifscope);
2229 		} else if (inp->inp_vflag & INP_IPV4) {
2230 			struct in_addr laddr = {.s_addr = 0}, faddr = {.s_addr = 0};
2231 			u_int16_t lport = 0, fport = 0;
2232 
2233 			cfil_get_flow_address(cfil_info->cfi_hash_entry, inp,
2234 			    &laddr, &faddr, &lport, &fport);
2235 			fill_ip_sockaddr_4_6(&sock_info->cfs_local, laddr, lport);
2236 			fill_ip_sockaddr_4_6(&sock_info->cfs_remote, faddr, fport);
2237 		}
2238 
2239 		// Set the pid info
2240 		sock_info->cfs_pid = sock->last_pid;
2241 		memcpy(sock_info->cfs_uuid, sock->last_uuid, sizeof(uuid_t));
2242 
2243 		if (sock->so_flags & SOF_DELEGATED) {
2244 			sock_info->cfs_e_pid = sock->e_pid;
2245 			memcpy(sock_info->cfs_e_uuid, sock->e_uuid, sizeof(uuid_t));
2246 		} else {
2247 			sock_info->cfs_e_pid = sock->last_pid;
2248 			memcpy(sock_info->cfs_e_uuid, sock->last_uuid, sizeof(uuid_t));
2249 		}
2250 
2251 		socket_unlock(sock, 1);
2252 
2253 		goto return_already_unlocked;
2254 	default:
2255 		error = ENOPROTOOPT;
2256 		break;
2257 	}
2258 done:
2259 	cfil_rw_unlock_shared(&cfil_lck_rw);
2260 
2261 	return error;
2262 
2263 return_already_unlocked:
2264 
2265 	return error;
2266 }
2267 
2268 static errno_t
cfil_ctl_setopt(kern_ctl_ref kctlref,u_int32_t kcunit,void * unitinfo,int opt,void * data,size_t len)2269 cfil_ctl_setopt(kern_ctl_ref kctlref, u_int32_t kcunit, void *unitinfo,
2270     int opt, void *data, size_t len)
2271 {
2272 #pragma unused(kctlref, opt)
2273 	errno_t error = 0;
2274 	struct content_filter *cfc = (struct content_filter *)unitinfo;
2275 
2276 	CFIL_LOG(LOG_NOTICE, "");
2277 
2278 	if (cfc == NULL) {
2279 		CFIL_LOG(LOG_ERR, "no unitinfo");
2280 		return EINVAL;
2281 	}
2282 
2283 	cfil_rw_lock_exclusive(&cfil_lck_rw);
2284 
2285 	if (kcunit > MAX_CONTENT_FILTER) {
2286 		CFIL_LOG(LOG_ERR, "kcunit %u > MAX_CONTENT_FILTER (%d)",
2287 		    kcunit, MAX_CONTENT_FILTER);
2288 		error = EINVAL;
2289 		goto done;
2290 	}
2291 	if (cfc != (void *)content_filters[kcunit - 1]) {
2292 		CFIL_LOG(LOG_ERR, "unitinfo does not match for kcunit %u",
2293 		    kcunit);
2294 		error = EINVAL;
2295 		goto done;
2296 	}
2297 	switch (opt) {
2298 	case CFIL_OPT_NECP_CONTROL_UNIT:
2299 		if (len < sizeof(uint32_t)) {
2300 			CFIL_LOG(LOG_ERR, "CFIL_OPT_NECP_CONTROL_UNIT "
2301 			    "len too small %lu", len);
2302 			error = EINVAL;
2303 			goto done;
2304 		}
2305 		if (cfc->cf_necp_control_unit != 0) {
2306 			CFIL_LOG(LOG_ERR, "CFIL_OPT_NECP_CONTROL_UNIT "
2307 			    "already set %u",
2308 			    cfc->cf_necp_control_unit);
2309 			error = EINVAL;
2310 			goto done;
2311 		}
2312 		cfc->cf_necp_control_unit = *(uint32_t *)data;
2313 		break;
2314 	case CFIL_OPT_PRESERVE_CONNECTIONS:
2315 		if (len < sizeof(uint32_t)) {
2316 			CFIL_LOG(LOG_ERR, "CFIL_OPT_PRESERVE_CONNECTIONS "
2317 			    "len too small %lu", len);
2318 			error = EINVAL;
2319 			goto done;
2320 		}
2321 		uint32_t preserve_connections = *((uint32_t *)data);
2322 		CFIL_LOG(LOG_INFO, "CFIL_OPT_PRESERVE_CONNECTIONS got %d (kcunit %d)", preserve_connections, kcunit);
2323 		if (preserve_connections) {
2324 			cfc->cf_flags |= CFF_PRESERVE_CONNECTIONS;
2325 		} else {
2326 			cfc->cf_flags &= ~CFF_PRESERVE_CONNECTIONS;
2327 		}
2328 
2329 		cfil_update_behavior_flags();
2330 		break;
2331 	default:
2332 		error = ENOPROTOOPT;
2333 		break;
2334 	}
2335 done:
2336 	cfil_rw_unlock_exclusive(&cfil_lck_rw);
2337 
2338 	return error;
2339 }
2340 
2341 
2342 static void
cfil_ctl_rcvd(kern_ctl_ref kctlref,u_int32_t kcunit,void * unitinfo,int flags)2343 cfil_ctl_rcvd(kern_ctl_ref kctlref, u_int32_t kcunit, void *unitinfo, int flags)
2344 {
2345 #pragma unused(kctlref, flags)
2346 	struct content_filter *cfc = (struct content_filter *)unitinfo;
2347 	struct socket *so = NULL;
2348 	int error;
2349 	struct cfil_entry *entry;
2350 	struct cfil_info *cfil_info = NULL;
2351 
2352 	CFIL_LOG(LOG_INFO, "");
2353 
2354 	if (cfc == NULL) {
2355 		CFIL_LOG(LOG_ERR, "no unitinfo");
2356 		OSIncrementAtomic(&cfil_stats.cfs_ctl_rcvd_bad);
2357 		return;
2358 	}
2359 
2360 	if (kcunit > MAX_CONTENT_FILTER) {
2361 		CFIL_LOG(LOG_ERR, "kcunit %u > MAX_CONTENT_FILTER (%d)",
2362 		    kcunit, MAX_CONTENT_FILTER);
2363 		OSIncrementAtomic(&cfil_stats.cfs_ctl_rcvd_bad);
2364 		return;
2365 	}
2366 	cfil_rw_lock_shared(&cfil_lck_rw);
2367 	if (cfc != (void *)content_filters[kcunit - 1]) {
2368 		CFIL_LOG(LOG_ERR, "unitinfo does not match for kcunit %u",
2369 		    kcunit);
2370 		OSIncrementAtomic(&cfil_stats.cfs_ctl_rcvd_bad);
2371 		goto done;
2372 	}
2373 	/* Let's assume the flow control is lifted */
2374 	if (cfc->cf_flags & CFF_FLOW_CONTROLLED) {
2375 		if (!cfil_rw_lock_shared_to_exclusive(&cfil_lck_rw)) {
2376 			cfil_rw_lock_exclusive(&cfil_lck_rw);
2377 		}
2378 
2379 		cfc->cf_flags &= ~CFF_FLOW_CONTROLLED;
2380 
2381 		cfil_rw_lock_exclusive_to_shared(&cfil_lck_rw);
2382 		LCK_RW_ASSERT(&cfil_lck_rw, LCK_RW_ASSERT_SHARED);
2383 	}
2384 	/*
2385 	 * Flow control will be raised again as soon as an entry cannot enqueue
2386 	 * to the kernel control socket
2387 	 */
2388 	while ((cfc->cf_flags & CFF_FLOW_CONTROLLED) == 0) {
2389 		verify_content_filter(cfc);
2390 
2391 		cfil_rw_lock_assert_held(&cfil_lck_rw, 0);
2392 
2393 		/* Find an entry that is flow controlled */
2394 		TAILQ_FOREACH(entry, &cfc->cf_sock_entries, cfe_link) {
2395 			if (entry->cfe_cfil_info == NULL ||
2396 			    entry->cfe_cfil_info->cfi_so == NULL) {
2397 				continue;
2398 			}
2399 			if ((entry->cfe_flags & CFEF_FLOW_CONTROLLED) == 0) {
2400 				continue;
2401 			}
2402 		}
2403 		if (entry == NULL) {
2404 			break;
2405 		}
2406 
2407 		OSIncrementAtomic(&cfil_stats.cfs_ctl_rcvd_flow_lift);
2408 
2409 		cfil_info = entry->cfe_cfil_info;
2410 		so = cfil_info->cfi_so;
2411 
2412 		if (cfil_info == NULL || os_ref_retain_try(&cfil_info->cfi_ref_count) == false) {
2413 			break;
2414 		}
2415 
2416 		cfil_rw_unlock_shared(&cfil_lck_rw);
2417 		socket_lock(so, 1);
2418 
2419 		do {
2420 			error = cfil_acquire_sockbuf(so, cfil_info, 1);
2421 			if (error == 0) {
2422 				error = cfil_data_service_ctl_q(so, cfil_info, kcunit, 1);
2423 			}
2424 			cfil_release_sockbuf(so, 1);
2425 			if (error != 0) {
2426 				break;
2427 			}
2428 
2429 			error = cfil_acquire_sockbuf(so, cfil_info, 0);
2430 			if (error == 0) {
2431 				error = cfil_data_service_ctl_q(so, cfil_info, kcunit, 0);
2432 			}
2433 			cfil_release_sockbuf(so, 0);
2434 		} while (0);
2435 
2436 		CFIL_INFO_FREE(cfil_info);
2437 		socket_lock_assert_owned(so);
2438 		socket_unlock(so, 1);
2439 
2440 		cfil_rw_lock_shared(&cfil_lck_rw);
2441 	}
2442 done:
2443 	cfil_rw_unlock_shared(&cfil_lck_rw);
2444 }
2445 
2446 void
cfil_init(void)2447 cfil_init(void)
2448 {
2449 	struct kern_ctl_reg kern_ctl;
2450 	errno_t error = 0;
2451 	unsigned int mbuf_limit = 0;
2452 
2453 	CFIL_LOG(LOG_NOTICE, "");
2454 
2455 	/*
2456 	 * Compile time verifications
2457 	 */
2458 	_CASSERT(CFIL_MAX_FILTER_COUNT == MAX_CONTENT_FILTER);
2459 	_CASSERT(sizeof(struct cfil_filter_stat) % sizeof(uint32_t) == 0);
2460 	_CASSERT(sizeof(struct cfil_entry_stat) % sizeof(uint32_t) == 0);
2461 	_CASSERT(sizeof(struct cfil_sock_stat) % sizeof(uint32_t) == 0);
2462 
2463 	/*
2464 	 * Runtime time verifications
2465 	 */
2466 	VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_ctl_q_in_enqueued,
2467 	    sizeof(uint32_t)));
2468 	VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_ctl_q_out_enqueued,
2469 	    sizeof(uint32_t)));
2470 	VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_ctl_q_in_peeked,
2471 	    sizeof(uint32_t)));
2472 	VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_ctl_q_out_peeked,
2473 	    sizeof(uint32_t)));
2474 
2475 	VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_pending_q_in_enqueued,
2476 	    sizeof(uint32_t)));
2477 	VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_pending_q_out_enqueued,
2478 	    sizeof(uint32_t)));
2479 
2480 	VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_inject_q_in_enqueued,
2481 	    sizeof(uint32_t)));
2482 	VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_inject_q_out_enqueued,
2483 	    sizeof(uint32_t)));
2484 	VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_inject_q_in_passed,
2485 	    sizeof(uint32_t)));
2486 	VERIFY(IS_P2ALIGNED(&cfil_stats.cfs_inject_q_out_passed,
2487 	    sizeof(uint32_t)));
2488 
2489 	/*
2490 	 * Allocate locks
2491 	 */
2492 	TAILQ_INIT(&cfil_sock_head);
2493 	TAILQ_INIT(&cfil_sock_head_stats);
2494 
2495 	/*
2496 	 * Register kernel control
2497 	 */
2498 	bzero(&kern_ctl, sizeof(kern_ctl));
2499 	strlcpy(kern_ctl.ctl_name, CONTENT_FILTER_CONTROL_NAME,
2500 	    sizeof(kern_ctl.ctl_name));
2501 	kern_ctl.ctl_flags = CTL_FLAG_PRIVILEGED | CTL_FLAG_REG_EXTENDED;
2502 	kern_ctl.ctl_sendsize = 512 * 1024; /* enough? */
2503 	kern_ctl.ctl_recvsize = 512 * 1024; /* enough? */
2504 	kern_ctl.ctl_connect = cfil_ctl_connect;
2505 	kern_ctl.ctl_disconnect = cfil_ctl_disconnect;
2506 	kern_ctl.ctl_send = cfil_ctl_send;
2507 	kern_ctl.ctl_getopt = cfil_ctl_getopt;
2508 	kern_ctl.ctl_setopt = cfil_ctl_setopt;
2509 	kern_ctl.ctl_rcvd = cfil_ctl_rcvd;
2510 	error = ctl_register(&kern_ctl, &cfil_kctlref);
2511 	if (error != 0) {
2512 		CFIL_LOG(LOG_ERR, "ctl_register failed: %d", error);
2513 		return;
2514 	}
2515 
2516 	// Spawn thread for statistics reporting
2517 	if (kernel_thread_start(cfil_stats_report_thread_func, NULL,
2518 	    &cfil_stats_report_thread) != KERN_SUCCESS) {
2519 		panic_plain("%s: Can't create statistics report thread", __func__);
2520 		/* NOTREACHED */
2521 	}
2522 	/* this must not fail */
2523 	VERIFY(cfil_stats_report_thread != NULL);
2524 
2525 	// Set UDP per-flow mbuf thresholds to 1/32 of platform max
2526 	mbuf_limit = MAX(UDP_FLOW_GC_MBUF_CNT_MAX, (nmbclusters << MCLSHIFT) >> UDP_FLOW_GC_MBUF_SHIFT);
2527 	cfil_udp_gc_mbuf_num_max = (mbuf_limit >> MCLSHIFT);
2528 	cfil_udp_gc_mbuf_cnt_max = mbuf_limit;
2529 
2530 	memset(&global_cfil_stats_report_buffers, 0, sizeof(global_cfil_stats_report_buffers));
2531 }
2532 
2533 struct cfil_info *
cfil_info_alloc(struct socket * so,struct soflow_hash_entry * hash_entry)2534 cfil_info_alloc(struct socket *so, struct soflow_hash_entry *hash_entry)
2535 {
2536 	int kcunit;
2537 	struct cfil_info *cfil_info = NULL;
2538 	struct inpcb *inp = sotoinpcb(so);
2539 
2540 	CFIL_LOG(LOG_INFO, "");
2541 
2542 	socket_lock_assert_owned(so);
2543 
2544 	cfil_info = zalloc_flags(cfil_info_zone, Z_WAITOK | Z_ZERO | Z_NOFAIL);
2545 	os_ref_init(&cfil_info->cfi_ref_count, &cfil_refgrp);
2546 
2547 	cfil_queue_init(&cfil_info->cfi_snd.cfi_inject_q);
2548 	cfil_queue_init(&cfil_info->cfi_rcv.cfi_inject_q);
2549 
2550 	for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
2551 		struct cfil_entry *entry;
2552 
2553 		entry = &cfil_info->cfi_entries[kcunit - 1];
2554 		entry->cfe_cfil_info = cfil_info;
2555 
2556 		/* Initialize the filter entry */
2557 		entry->cfe_filter = NULL;
2558 		entry->cfe_flags = 0;
2559 		entry->cfe_necp_control_unit = 0;
2560 		entry->cfe_snd.cfe_pass_offset = 0;
2561 		entry->cfe_snd.cfe_peek_offset = 0;
2562 		entry->cfe_snd.cfe_peeked = 0;
2563 		entry->cfe_rcv.cfe_pass_offset = 0;
2564 		entry->cfe_rcv.cfe_peek_offset = 0;
2565 		entry->cfe_rcv.cfe_peeked = 0;
2566 		/*
2567 		 * Timestamp the last action to avoid pre-maturely
2568 		 * triggering garbage collection
2569 		 */
2570 		microuptime(&entry->cfe_last_action);
2571 
2572 		cfil_queue_init(&entry->cfe_snd.cfe_pending_q);
2573 		cfil_queue_init(&entry->cfe_rcv.cfe_pending_q);
2574 		cfil_queue_init(&entry->cfe_snd.cfe_ctl_q);
2575 		cfil_queue_init(&entry->cfe_rcv.cfe_ctl_q);
2576 	}
2577 
2578 	cfil_rw_lock_exclusive(&cfil_lck_rw);
2579 
2580 	/*
2581 	 * Create a cfi_sock_id that's not the socket pointer!
2582 	 */
2583 
2584 	if (hash_entry == NULL) {
2585 		// This is the TCP case, cfil_info is tracked per socket
2586 		if (inp->inp_flowhash == 0) {
2587 			inp_calc_flowhash(inp);
2588 			ASSERT(inp->inp_flowhash != 0);
2589 		}
2590 
2591 		so->so_cfil = cfil_info;
2592 		cfil_info->cfi_so = so;
2593 		cfil_info->cfi_sock_id =
2594 		    ((so->so_gencnt << 32) | inp->inp_flowhash);
2595 	} else {
2596 		// This is the UDP case, cfil_info is tracked in per-socket hash
2597 		cfil_info->cfi_so = so;
2598 		cfil_info->cfi_hash_entry = hash_entry;
2599 		cfil_info->cfi_sock_id = ((so->so_gencnt << 32) | (hash_entry->soflow_flowhash & 0xffffffff));
2600 	}
2601 
2602 	TAILQ_INSERT_TAIL(&cfil_sock_head, cfil_info, cfi_link);
2603 	SLIST_INIT(&cfil_info->cfi_ordered_entries);
2604 
2605 	cfil_sock_attached_count++;
2606 
2607 	cfil_rw_unlock_exclusive(&cfil_lck_rw);
2608 
2609 	if (cfil_info != NULL) {
2610 		OSIncrementAtomic(&cfil_stats.cfs_cfi_alloc_ok);
2611 	} else {
2612 		OSIncrementAtomic(&cfil_stats.cfs_cfi_alloc_fail);
2613 	}
2614 
2615 	return cfil_info;
2616 }
2617 
2618 int
cfil_info_attach_unit(struct socket * so,uint32_t filter_control_unit,struct cfil_info * cfil_info)2619 cfil_info_attach_unit(struct socket *so, uint32_t filter_control_unit, struct cfil_info *cfil_info)
2620 {
2621 	int kcunit;
2622 	int attached = 0;
2623 
2624 	CFIL_LOG(LOG_INFO, "");
2625 
2626 	socket_lock_assert_owned(so);
2627 
2628 	cfil_rw_lock_exclusive(&cfil_lck_rw);
2629 
2630 	for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
2631 		struct content_filter *cfc = content_filters[kcunit - 1];
2632 		struct cfil_entry *entry;
2633 		struct cfil_entry *iter_entry;
2634 		struct cfil_entry *iter_prev;
2635 
2636 		if (cfc == NULL) {
2637 			continue;
2638 		}
2639 		if (!(cfc->cf_necp_control_unit & filter_control_unit)) {
2640 			continue;
2641 		}
2642 
2643 		entry = &cfil_info->cfi_entries[kcunit - 1];
2644 
2645 		entry->cfe_filter = cfc;
2646 		entry->cfe_necp_control_unit = cfc->cf_necp_control_unit;
2647 		TAILQ_INSERT_TAIL(&cfc->cf_sock_entries, entry, cfe_link);
2648 		cfc->cf_sock_count++;
2649 
2650 		/* Insert the entry into the list ordered by control unit */
2651 		iter_prev = NULL;
2652 		SLIST_FOREACH(iter_entry, &cfil_info->cfi_ordered_entries, cfe_order_link) {
2653 			if (entry->cfe_necp_control_unit < iter_entry->cfe_necp_control_unit) {
2654 				break;
2655 			}
2656 			iter_prev = iter_entry;
2657 		}
2658 
2659 		if (iter_prev == NULL) {
2660 			SLIST_INSERT_HEAD(&cfil_info->cfi_ordered_entries, entry, cfe_order_link);
2661 		} else {
2662 			SLIST_INSERT_AFTER(iter_prev, entry, cfe_order_link);
2663 		}
2664 
2665 		verify_content_filter(cfc);
2666 		attached = 1;
2667 		entry->cfe_flags |= CFEF_CFIL_ATTACHED;
2668 	}
2669 
2670 	cfil_rw_unlock_exclusive(&cfil_lck_rw);
2671 
2672 	return attached;
2673 }
2674 
2675 static void
cfil_info_free(struct cfil_info * cfil_info)2676 cfil_info_free(struct cfil_info *cfil_info)
2677 {
2678 	int kcunit;
2679 	uint64_t in_drain = 0;
2680 	uint64_t out_drained = 0;
2681 
2682 	if (cfil_info == NULL) {
2683 		return;
2684 	}
2685 
2686 	CFIL_LOG(LOG_INFO, "");
2687 
2688 	cfil_rw_lock_exclusive(&cfil_lck_rw);
2689 
2690 	if (cfil_info->cfi_debug) {
2691 		cfil_info_log(LOG_INFO, cfil_info, "CFIL: FREEING CFIL_INFO");
2692 	}
2693 
2694 	for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
2695 		struct cfil_entry *entry;
2696 		struct content_filter *cfc;
2697 
2698 		entry = &cfil_info->cfi_entries[kcunit - 1];
2699 
2700 		/* Don't be silly and try to detach twice */
2701 		if (entry->cfe_filter == NULL) {
2702 			continue;
2703 		}
2704 
2705 		cfc = content_filters[kcunit - 1];
2706 
2707 		VERIFY(cfc == entry->cfe_filter);
2708 
2709 		entry->cfe_filter = NULL;
2710 		entry->cfe_necp_control_unit = 0;
2711 		TAILQ_REMOVE(&cfc->cf_sock_entries, entry, cfe_link);
2712 		cfc->cf_sock_count--;
2713 
2714 		verify_content_filter(cfc);
2715 	}
2716 
2717 	cfil_sock_attached_count--;
2718 	TAILQ_REMOVE(&cfil_sock_head, cfil_info, cfi_link);
2719 
2720 	// Turn off stats reporting for cfil_info.
2721 	cfil_info_stats_toggle(cfil_info, NULL, 0);
2722 
2723 	out_drained += cfil_queue_drain(&cfil_info->cfi_snd.cfi_inject_q);
2724 	in_drain += cfil_queue_drain(&cfil_info->cfi_rcv.cfi_inject_q);
2725 
2726 	for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
2727 		struct cfil_entry *entry;
2728 
2729 		entry = &cfil_info->cfi_entries[kcunit - 1];
2730 		out_drained += cfil_queue_drain(&entry->cfe_snd.cfe_pending_q);
2731 		in_drain += cfil_queue_drain(&entry->cfe_rcv.cfe_pending_q);
2732 		out_drained += cfil_queue_drain(&entry->cfe_snd.cfe_ctl_q);
2733 		in_drain += cfil_queue_drain(&entry->cfe_rcv.cfe_ctl_q);
2734 	}
2735 	cfil_rw_unlock_exclusive(&cfil_lck_rw);
2736 
2737 	if (out_drained) {
2738 		OSIncrementAtomic(&cfil_stats.cfs_flush_out_free);
2739 	}
2740 	if (in_drain) {
2741 		OSIncrementAtomic(&cfil_stats.cfs_flush_in_free);
2742 	}
2743 
2744 	zfree(cfil_info_zone, cfil_info);
2745 }
2746 
2747 /*
2748  * Received a verdict from userspace for a socket.
2749  * Perform any delayed operation if needed.
2750  */
2751 static void
cfil_sock_received_verdict(struct socket * so)2752 cfil_sock_received_verdict(struct socket *so)
2753 {
2754 	if (so == NULL || so->so_cfil == NULL) {
2755 		return;
2756 	}
2757 
2758 	so->so_cfil->cfi_flags |= CFIF_INITIAL_VERDICT;
2759 
2760 	/*
2761 	 * If socket has already been connected, trigger
2762 	 * soisconnected now.
2763 	 */
2764 	if (so->so_cfil->cfi_flags & CFIF_SOCKET_CONNECTED) {
2765 		so->so_cfil->cfi_flags &= ~CFIF_SOCKET_CONNECTED;
2766 		soisconnected(so);
2767 		return;
2768 	}
2769 }
2770 
2771 /*
2772  * Entry point from Sockets layer
2773  * The socket is locked.
2774  *
2775  * Checks if a connected socket is subject to filter and
2776  * pending the initial verdict.
2777  */
2778 boolean_t
cfil_sock_connected_pending_verdict(struct socket * so)2779 cfil_sock_connected_pending_verdict(struct socket *so)
2780 {
2781 	if (so == NULL || so->so_cfil == NULL) {
2782 		return false;
2783 	}
2784 
2785 	if (so->so_cfil->cfi_flags & CFIF_INITIAL_VERDICT) {
2786 		return false;
2787 	} else {
2788 		/*
2789 		 * Remember that this protocol is already connected, so
2790 		 * we will trigger soisconnected() upon receipt of
2791 		 * initial verdict later.
2792 		 */
2793 		so->so_cfil->cfi_flags |= CFIF_SOCKET_CONNECTED;
2794 		return true;
2795 	}
2796 }
2797 
2798 boolean_t
cfil_filter_present(void)2799 cfil_filter_present(void)
2800 {
2801 	return cfil_active_count > 0;
2802 }
2803 
2804 /*
2805  * Entry point from Sockets layer
2806  * The socket is locked.
2807  */
2808 errno_t
cfil_sock_attach(struct socket * so,struct sockaddr * local,struct sockaddr * remote,int dir)2809 cfil_sock_attach(struct socket *so, struct sockaddr *local, struct sockaddr *remote, int dir)
2810 {
2811 	errno_t error = 0;
2812 	uint32_t filter_control_unit;
2813 	int debug = 0;
2814 
2815 	socket_lock_assert_owned(so);
2816 
2817 	if (so->so_flags1 & SOF1_FLOW_DIVERT_SKIP) {
2818 		/*
2819 		 * This socket has already been evaluated (and ultimately skipped) by
2820 		 * flow divert, so it has also already been through content filter if there
2821 		 * is one.
2822 		 */
2823 		goto done;
2824 	}
2825 
2826 	/* Limit ourselves to TCP that are not MPTCP subflows */
2827 	if (SKIP_FILTER_FOR_TCP_SOCKET(so)) {
2828 		goto done;
2829 	}
2830 
2831 	debug = DEBUG_FLOW(sotoinpcb(so), so, local, remote);
2832 	if (debug) {
2833 		CFIL_LOG(LOG_INFO, "CFIL: TCP (dir %d) - debug flow with port %d", dir, cfil_log_port);
2834 	}
2835 
2836 	filter_control_unit = necp_socket_get_content_filter_control_unit(so);
2837 	if (filter_control_unit == 0) {
2838 		goto done;
2839 	}
2840 
2841 	if (filter_control_unit == NECP_FILTER_UNIT_NO_FILTER) {
2842 		goto done;
2843 	}
2844 	if ((filter_control_unit & NECP_MASK_USERSPACE_ONLY) != 0) {
2845 		OSIncrementAtomic(&cfil_stats.cfs_sock_userspace_only);
2846 		goto done;
2847 	}
2848 	if (cfil_active_count == 0) {
2849 		OSIncrementAtomic(&cfil_stats.cfs_sock_attach_in_vain);
2850 		goto done;
2851 	}
2852 	if (so->so_cfil != NULL) {
2853 		OSIncrementAtomic(&cfil_stats.cfs_sock_attach_already);
2854 		CFIL_LOG(LOG_ERR, "already attached");
2855 		goto done;
2856 	} else {
2857 		cfil_info_alloc(so, NULL);
2858 		if (so->so_cfil == NULL) {
2859 			error = ENOMEM;
2860 			OSIncrementAtomic(&cfil_stats.cfs_sock_attach_no_mem);
2861 			goto done;
2862 		}
2863 		so->so_cfil->cfi_dir = dir;
2864 		so->so_cfil->cfi_filter_control_unit = filter_control_unit;
2865 		so->so_cfil->cfi_debug = debug;
2866 	}
2867 	if (cfil_info_attach_unit(so, filter_control_unit, so->so_cfil) == 0) {
2868 		CFIL_LOG(LOG_ERR, "cfil_info_attach_unit(%u) failed",
2869 		    filter_control_unit);
2870 		OSIncrementAtomic(&cfil_stats.cfs_sock_attach_failed);
2871 		goto done;
2872 	}
2873 	CFIL_LOG(LOG_INFO, "so %llx filter_control_unit %u sockID %llx",
2874 	    (uint64_t)VM_KERNEL_ADDRPERM(so),
2875 	    filter_control_unit, so->so_cfil->cfi_sock_id);
2876 
2877 	so->so_flags |= SOF_CONTENT_FILTER;
2878 	OSIncrementAtomic(&cfil_stats.cfs_sock_attached);
2879 
2880 	/* Hold a reference on the socket */
2881 	so->so_usecount++;
2882 
2883 	/*
2884 	 * Save passed addresses for attach event msg (in case resend
2885 	 * is needed.
2886 	 */
2887 	if (remote != NULL && (remote->sa_len <= sizeof(union sockaddr_in_4_6))) {
2888 		memcpy(&so->so_cfil->cfi_so_attach_faddr, remote, remote->sa_len);
2889 	}
2890 	if (local != NULL && (local->sa_len <= sizeof(union sockaddr_in_4_6))) {
2891 		memcpy(&so->so_cfil->cfi_so_attach_laddr, local, local->sa_len);
2892 	}
2893 
2894 	error = cfil_dispatch_attach_event(so, so->so_cfil, 0, dir);
2895 	/* We can recover from flow control or out of memory errors */
2896 	if (error == ENOBUFS || error == ENOMEM) {
2897 		error = 0;
2898 	} else if (error != 0) {
2899 		goto done;
2900 	}
2901 
2902 	CFIL_INFO_VERIFY(so->so_cfil);
2903 done:
2904 	return error;
2905 }
2906 
2907 /*
2908  * Entry point from Sockets layer
2909  * The socket is locked.
2910  */
2911 errno_t
cfil_sock_detach(struct socket * so)2912 cfil_sock_detach(struct socket *so)
2913 {
2914 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
2915 		return 0;
2916 	}
2917 
2918 	if (so->so_cfil) {
2919 		if (so->so_flags & SOF_CONTENT_FILTER) {
2920 			so->so_flags &= ~SOF_CONTENT_FILTER;
2921 			VERIFY(so->so_usecount > 0);
2922 			so->so_usecount--;
2923 		}
2924 		CFIL_INFO_FREE(so->so_cfil);
2925 		so->so_cfil = NULL;
2926 		OSIncrementAtomic(&cfil_stats.cfs_sock_detached);
2927 	}
2928 	return 0;
2929 }
2930 
2931 /*
2932  * Fill in the address info of an event message from either
2933  * the socket or passed in address info.
2934  */
2935 static void
cfil_fill_event_msg_addresses(struct soflow_hash_entry * entry,struct inpcb * inp,union sockaddr_in_4_6 * sin_src,union sockaddr_in_4_6 * sin_dst,boolean_t isIPv4,boolean_t outgoing)2936 cfil_fill_event_msg_addresses(struct soflow_hash_entry *entry, struct inpcb *inp,
2937     union sockaddr_in_4_6 *sin_src, union sockaddr_in_4_6 *sin_dst,
2938     boolean_t isIPv4, boolean_t outgoing)
2939 {
2940 	if (isIPv4) {
2941 		struct in_addr laddr = {0}, faddr = {0};
2942 		u_int16_t lport = 0, fport = 0;
2943 
2944 		cfil_get_flow_address(entry, inp, &laddr, &faddr, &lport, &fport);
2945 
2946 		if (outgoing) {
2947 			fill_ip_sockaddr_4_6(sin_src, laddr, lport);
2948 			fill_ip_sockaddr_4_6(sin_dst, faddr, fport);
2949 		} else {
2950 			fill_ip_sockaddr_4_6(sin_src, faddr, fport);
2951 			fill_ip_sockaddr_4_6(sin_dst, laddr, lport);
2952 		}
2953 	} else {
2954 		struct in6_addr *laddr = NULL, *faddr = NULL;
2955 		u_int16_t lport = 0, fport = 0;
2956 		const u_int32_t lifscope = inp ? inp->inp_lifscope : IFSCOPE_UNKNOWN;
2957 		const u_int32_t fifscope = inp ? inp->inp_fifscope : IFSCOPE_UNKNOWN;
2958 
2959 		cfil_get_flow_address_v6(entry, inp, &laddr, &faddr, &lport, &fport);
2960 		if (outgoing) {
2961 			fill_ip6_sockaddr_4_6(sin_src, laddr, lport, lifscope);
2962 			fill_ip6_sockaddr_4_6(sin_dst, faddr, fport, fifscope);
2963 		} else {
2964 			fill_ip6_sockaddr_4_6(sin_src, faddr, fport, fifscope);
2965 			fill_ip6_sockaddr_4_6(sin_dst, laddr, lport, lifscope);
2966 		}
2967 	}
2968 }
2969 
2970 static boolean_t
cfil_dispatch_attach_event_sign(cfil_crypto_state_t crypto_state,struct cfil_info * cfil_info,struct cfil_msg_sock_attached * msg)2971 cfil_dispatch_attach_event_sign(cfil_crypto_state_t crypto_state,
2972     struct cfil_info *cfil_info,
2973     struct cfil_msg_sock_attached *msg)
2974 {
2975 	struct cfil_crypto_data data = {};
2976 	struct iovec extra_data[1] = { { NULL, 0 } };
2977 
2978 	if (crypto_state == NULL || msg == NULL || cfil_info == NULL) {
2979 		return false;
2980 	}
2981 
2982 	data.sock_id = msg->cfs_msghdr.cfm_sock_id;
2983 	data.direction = msg->cfs_conn_dir;
2984 
2985 	data.pid = msg->cfs_pid;
2986 	data.effective_pid = msg->cfs_e_pid;
2987 	uuid_copy(data.uuid, msg->cfs_uuid);
2988 	uuid_copy(data.effective_uuid, msg->cfs_e_uuid);
2989 	data.socketProtocol = msg->cfs_sock_protocol;
2990 	if (data.direction == CFS_CONNECTION_DIR_OUT) {
2991 		data.remote.sin6 = msg->cfs_dst.sin6;
2992 		data.local.sin6 = msg->cfs_src.sin6;
2993 	} else {
2994 		data.remote.sin6 = msg->cfs_src.sin6;
2995 		data.local.sin6 = msg->cfs_dst.sin6;
2996 	}
2997 
2998 	if (strlen(msg->cfs_remote_domain_name) > 0) {
2999 		extra_data[0].iov_base = msg->cfs_remote_domain_name;
3000 		extra_data[0].iov_len = strlen(msg->cfs_remote_domain_name);
3001 	}
3002 
3003 	// At attach, if local address is already present, no need to re-sign subsequent data messages.
3004 	if (!NULLADDRESS(data.local)) {
3005 		cfil_info->cfi_isSignatureLatest = true;
3006 	}
3007 
3008 	msg->cfs_signature_length = sizeof(cfil_crypto_signature);
3009 	if (cfil_crypto_sign_data(crypto_state, &data, extra_data, sizeof(extra_data) / sizeof(extra_data[0]), msg->cfs_signature, &msg->cfs_signature_length) != 0) {
3010 		msg->cfs_signature_length = 0;
3011 		CFIL_LOG(LOG_ERR, "CFIL: Failed to sign attached msg <sockID %llu>",
3012 		    msg->cfs_msghdr.cfm_sock_id);
3013 		return false;
3014 	}
3015 
3016 	return true;
3017 }
3018 
3019 struct cfil_sign_parameters {
3020 	cfil_crypto_state_t csp_state;
3021 	struct cfil_crypto_data *csp_data;
3022 	uint8_t *csp_signature;
3023 	uint32_t *csp_signature_size;
3024 };
3025 
3026 static void
cfil_sign_with_domain_name(char * domain_name,void * ctx)3027 cfil_sign_with_domain_name(char *domain_name, void *ctx)
3028 {
3029 	struct cfil_sign_parameters *parameters = (struct cfil_sign_parameters *)ctx;
3030 	struct iovec extra_data[1] = { { NULL, 0 } };
3031 
3032 	if (parameters == NULL) {
3033 		return;
3034 	}
3035 
3036 	if (domain_name != NULL) {
3037 		extra_data[0].iov_base = domain_name;
3038 		extra_data[0].iov_len = strlen(domain_name);
3039 	}
3040 
3041 	*(parameters->csp_signature_size) = sizeof(cfil_crypto_signature);
3042 	if (cfil_crypto_sign_data(parameters->csp_state, parameters->csp_data,
3043 	    extra_data, sizeof(extra_data) / sizeof(extra_data[0]),
3044 	    parameters->csp_signature, parameters->csp_signature_size) != 0) {
3045 		*(parameters->csp_signature_size) = 0;
3046 	}
3047 }
3048 
3049 static boolean_t
cfil_dispatch_data_event_sign(cfil_crypto_state_t crypto_state,struct socket * so,struct cfil_info * cfil_info,struct cfil_msg_data_event * msg)3050 cfil_dispatch_data_event_sign(cfil_crypto_state_t crypto_state,
3051     struct socket *so, struct cfil_info *cfil_info,
3052     struct cfil_msg_data_event *msg)
3053 {
3054 	struct cfil_crypto_data data = {};
3055 
3056 	if (crypto_state == NULL || msg == NULL ||
3057 	    so == NULL || cfil_info == NULL) {
3058 		return false;
3059 	}
3060 
3061 	data.sock_id = cfil_info->cfi_sock_id;
3062 	data.direction = cfil_info->cfi_dir;
3063 	data.pid = so->last_pid;
3064 	memcpy(data.uuid, so->last_uuid, sizeof(uuid_t));
3065 	if (so->so_flags & SOF_DELEGATED) {
3066 		data.effective_pid = so->e_pid;
3067 		memcpy(data.effective_uuid, so->e_uuid, sizeof(uuid_t));
3068 	} else {
3069 		data.effective_pid = so->last_pid;
3070 		memcpy(data.effective_uuid, so->last_uuid, sizeof(uuid_t));
3071 	}
3072 	data.socketProtocol = GET_SO_PROTO(so);
3073 
3074 	if (data.direction == CFS_CONNECTION_DIR_OUT) {
3075 		data.remote.sin6 = msg->cfc_dst.sin6;
3076 		data.local.sin6 = msg->cfc_src.sin6;
3077 	} else {
3078 		data.remote.sin6 = msg->cfc_src.sin6;
3079 		data.local.sin6 = msg->cfc_dst.sin6;
3080 	}
3081 
3082 	// At first data, local address may show up for the first time, update address cache and
3083 	// no need to re-sign subsequent data messages anymore.
3084 	if (!NULLADDRESS(data.local)) {
3085 		memcpy(&cfil_info->cfi_so_attach_laddr, &data.local, data.local.sa.sa_len);
3086 		cfil_info->cfi_isSignatureLatest = true;
3087 	}
3088 
3089 	struct cfil_sign_parameters parameters = {
3090 		.csp_state = crypto_state,
3091 		.csp_data = &data,
3092 		.csp_signature = msg->cfd_signature,
3093 		.csp_signature_size = &msg->cfd_signature_length,
3094 	};
3095 	necp_with_inp_domain_name(so, &parameters, cfil_sign_with_domain_name);
3096 
3097 	if (msg->cfd_signature_length == 0) {
3098 		CFIL_LOG(LOG_ERR, "CFIL: Failed to sign data msg <sockID %llu>",
3099 		    msg->cfd_msghdr.cfm_sock_id);
3100 		return false;
3101 	}
3102 
3103 	return true;
3104 }
3105 
3106 static boolean_t
cfil_dispatch_closed_event_sign(cfil_crypto_state_t crypto_state,struct socket * so,struct cfil_info * cfil_info,struct cfil_msg_sock_closed * msg)3107 cfil_dispatch_closed_event_sign(cfil_crypto_state_t crypto_state,
3108     struct socket *so, struct cfil_info *cfil_info,
3109     struct cfil_msg_sock_closed *msg)
3110 {
3111 	struct cfil_crypto_data data = {};
3112 	struct soflow_hash_entry hash_entry = {};
3113 	struct soflow_hash_entry *hash_entry_ptr = NULL;
3114 	struct inpcb *inp = (struct inpcb *)so->so_pcb;
3115 
3116 	if (crypto_state == NULL || msg == NULL ||
3117 	    so == NULL || inp == NULL || cfil_info == NULL) {
3118 		return false;
3119 	}
3120 
3121 	data.sock_id = cfil_info->cfi_sock_id;
3122 	data.direction = cfil_info->cfi_dir;
3123 
3124 	data.pid = so->last_pid;
3125 	memcpy(data.uuid, so->last_uuid, sizeof(uuid_t));
3126 	if (so->so_flags & SOF_DELEGATED) {
3127 		data.effective_pid = so->e_pid;
3128 		memcpy(data.effective_uuid, so->e_uuid, sizeof(uuid_t));
3129 	} else {
3130 		data.effective_pid = so->last_pid;
3131 		memcpy(data.effective_uuid, so->last_uuid, sizeof(uuid_t));
3132 	}
3133 	data.socketProtocol = GET_SO_PROTO(so);
3134 
3135 	/*
3136 	 * Fill in address info:
3137 	 * For UDP, use the cfil_info hash entry directly.
3138 	 * For TCP, compose an hash entry with the saved addresses.
3139 	 */
3140 	if (cfil_info->cfi_hash_entry != NULL) {
3141 		hash_entry_ptr = cfil_info->cfi_hash_entry;
3142 	} else if (cfil_info->cfi_so_attach_faddr.sa.sa_len > 0 ||
3143 	    cfil_info->cfi_so_attach_laddr.sa.sa_len > 0) {
3144 		soflow_fill_hash_entry_from_address(&hash_entry, TRUE, SA(&cfil_info->cfi_so_attach_laddr.sa), FALSE);
3145 		soflow_fill_hash_entry_from_address(&hash_entry, FALSE, SA(&cfil_info->cfi_so_attach_faddr.sa), FALSE);
3146 		hash_entry_ptr = &hash_entry;
3147 	}
3148 	if (hash_entry_ptr != NULL) {
3149 		boolean_t outgoing = (cfil_info->cfi_dir == CFS_CONNECTION_DIR_OUT);
3150 		union sockaddr_in_4_6 *src = outgoing ? &data.local : &data.remote;
3151 		union sockaddr_in_4_6 *dst = outgoing ? &data.remote : &data.local;
3152 		cfil_fill_event_msg_addresses(hash_entry_ptr, inp, src, dst, !IS_INP_V6(inp), outgoing);
3153 	}
3154 
3155 	data.byte_count_in = cfil_info->cfi_byte_inbound_count;
3156 	data.byte_count_out = cfil_info->cfi_byte_outbound_count;
3157 
3158 	struct cfil_sign_parameters parameters = {
3159 		.csp_state = crypto_state,
3160 		.csp_data = &data,
3161 		.csp_signature = msg->cfc_signature,
3162 		.csp_signature_size = &msg->cfc_signature_length
3163 	};
3164 	necp_with_inp_domain_name(so, &parameters, cfil_sign_with_domain_name);
3165 
3166 	if (msg->cfc_signature_length == 0) {
3167 		CFIL_LOG(LOG_ERR, "CFIL: Failed to sign closed msg <sockID %llu>",
3168 		    msg->cfc_msghdr.cfm_sock_id);
3169 		return false;
3170 	}
3171 
3172 	return true;
3173 }
3174 
3175 static void
cfil_populate_attached_msg_domain_name(char * domain_name,void * ctx)3176 cfil_populate_attached_msg_domain_name(char *domain_name, void *ctx)
3177 {
3178 	struct cfil_msg_sock_attached *msg_attached = (struct cfil_msg_sock_attached *)ctx;
3179 
3180 	if (msg_attached == NULL) {
3181 		return;
3182 	}
3183 
3184 	if (domain_name != NULL) {
3185 		strlcpy(msg_attached->cfs_remote_domain_name, domain_name, sizeof(msg_attached->cfs_remote_domain_name));
3186 	}
3187 }
3188 
3189 static bool
cfil_copy_audit_token(pid_t pid,audit_token_t * buffer)3190 cfil_copy_audit_token(pid_t pid, audit_token_t *buffer)
3191 {
3192 	bool success = false;
3193 	proc_t p = proc_find(pid);
3194 	if (p != PROC_NULL) {
3195 		task_t t = proc_task(p);
3196 		if (t != TASK_NULL) {
3197 			audit_token_t audit_token = {};
3198 			mach_msg_type_number_t count = TASK_AUDIT_TOKEN_COUNT;
3199 			if (task_info(t, TASK_AUDIT_TOKEN, (task_info_t)&audit_token, &count) == KERN_SUCCESS) {
3200 				memcpy(buffer, &audit_token, sizeof(audit_token_t));
3201 				success = true;
3202 			}
3203 		}
3204 		proc_rele(p);
3205 	}
3206 	return success;
3207 }
3208 
3209 static int
cfil_dispatch_attach_event(struct socket * so,struct cfil_info * cfil_info,uint32_t kcunit,int conn_dir)3210 cfil_dispatch_attach_event(struct socket *so, struct cfil_info *cfil_info,
3211     uint32_t kcunit, int conn_dir)
3212 {
3213 	errno_t error = 0;
3214 	struct cfil_entry *entry = NULL;
3215 	struct cfil_msg_sock_attached *msg_attached;
3216 	struct content_filter *cfc = NULL;
3217 	struct inpcb *inp = (struct inpcb *)so->so_pcb;
3218 	struct soflow_hash_entry *hash_entry_ptr = NULL;
3219 	struct soflow_hash_entry hash_entry;
3220 
3221 	memset(&hash_entry, 0, sizeof(struct soflow_hash_entry));
3222 
3223 	socket_lock_assert_owned(so);
3224 
3225 	cfil_rw_lock_shared(&cfil_lck_rw);
3226 
3227 	if (so->so_proto == NULL || so->so_proto->pr_domain == NULL) {
3228 		error = EINVAL;
3229 		goto done;
3230 	}
3231 
3232 	if (kcunit == 0) {
3233 		entry = SLIST_FIRST(&cfil_info->cfi_ordered_entries);
3234 	} else {
3235 		entry = &cfil_info->cfi_entries[kcunit - 1];
3236 	}
3237 
3238 	if (entry == NULL) {
3239 		goto done;
3240 	}
3241 
3242 	cfc = entry->cfe_filter;
3243 	if (cfc == NULL) {
3244 		goto done;
3245 	}
3246 
3247 	if ((entry->cfe_flags & CFEF_SENT_SOCK_ATTACHED)) {
3248 		goto done;
3249 	}
3250 
3251 	if (kcunit == 0) {
3252 		kcunit = CFI_ENTRY_KCUNIT(cfil_info, entry);
3253 	}
3254 
3255 	CFIL_LOG(LOG_INFO, "so %llx filter_control_unit %u kcunit %u",
3256 	    (uint64_t)VM_KERNEL_ADDRPERM(so), entry->cfe_necp_control_unit, kcunit);
3257 
3258 	/* Would be wasteful to try when flow controlled */
3259 	if (cfc->cf_flags & CFF_FLOW_CONTROLLED) {
3260 		error = ENOBUFS;
3261 		goto done;
3262 	}
3263 
3264 	msg_attached = kalloc_data(sizeof(struct cfil_msg_sock_attached), Z_WAITOK);
3265 	if (msg_attached == NULL) {
3266 		error = ENOMEM;
3267 		goto done;
3268 	}
3269 
3270 	bzero(msg_attached, sizeof(struct cfil_msg_sock_attached));
3271 	msg_attached->cfs_msghdr.cfm_len = sizeof(struct cfil_msg_sock_attached);
3272 	msg_attached->cfs_msghdr.cfm_version = CFM_VERSION_CURRENT;
3273 	msg_attached->cfs_msghdr.cfm_type = CFM_TYPE_EVENT;
3274 	msg_attached->cfs_msghdr.cfm_op = CFM_OP_SOCKET_ATTACHED;
3275 	msg_attached->cfs_msghdr.cfm_sock_id = entry->cfe_cfil_info->cfi_sock_id;
3276 
3277 	msg_attached->cfs_sock_family = so->so_proto->pr_domain->dom_family;
3278 	msg_attached->cfs_sock_type = so->so_proto->pr_type;
3279 	msg_attached->cfs_sock_protocol = GET_SO_PROTO(so);
3280 	msg_attached->cfs_pid = so->last_pid;
3281 	memcpy(msg_attached->cfs_uuid, so->last_uuid, sizeof(uuid_t));
3282 	if (so->so_flags & SOF_DELEGATED) {
3283 		msg_attached->cfs_e_pid = so->e_pid;
3284 		memcpy(msg_attached->cfs_e_uuid, so->e_uuid, sizeof(uuid_t));
3285 	} else {
3286 		msg_attached->cfs_e_pid = so->last_pid;
3287 		memcpy(msg_attached->cfs_e_uuid, so->last_uuid, sizeof(uuid_t));
3288 	}
3289 
3290 	/*
3291 	 * Fill in address info:
3292 	 * For UDP, use the cfil_info hash entry directly.
3293 	 * For TCP, compose an hash entry with the saved addresses.
3294 	 */
3295 	if (cfil_info->cfi_hash_entry != NULL) {
3296 		hash_entry_ptr = cfil_info->cfi_hash_entry;
3297 	} else if (cfil_info->cfi_so_attach_faddr.sa.sa_len > 0 ||
3298 	    cfil_info->cfi_so_attach_laddr.sa.sa_len > 0) {
3299 		soflow_fill_hash_entry_from_address(&hash_entry, TRUE, SA(&cfil_info->cfi_so_attach_laddr.sa), FALSE);
3300 		soflow_fill_hash_entry_from_address(&hash_entry, FALSE, SA(&cfil_info->cfi_so_attach_faddr.sa), FALSE);
3301 		hash_entry_ptr = &hash_entry;
3302 	}
3303 	if (hash_entry_ptr != NULL) {
3304 		cfil_fill_event_msg_addresses(hash_entry_ptr, inp,
3305 		    &msg_attached->cfs_src, &msg_attached->cfs_dst,
3306 		    !IS_INP_V6(inp), conn_dir == CFS_CONNECTION_DIR_OUT);
3307 	}
3308 	msg_attached->cfs_conn_dir = conn_dir;
3309 
3310 	if (msg_attached->cfs_e_pid != 0) {
3311 		if (!cfil_copy_audit_token(msg_attached->cfs_e_pid, (audit_token_t *)&msg_attached->cfs_audit_token)) {
3312 			CFIL_LOG(LOG_ERR, "CFIL: Failed to get effective audit token for <sockID %llu> ", entry->cfe_cfil_info->cfi_sock_id);
3313 		}
3314 	}
3315 
3316 	if (msg_attached->cfs_pid != 0) {
3317 		if (msg_attached->cfs_pid == msg_attached->cfs_e_pid) {
3318 			memcpy(&msg_attached->cfs_real_audit_token, &msg_attached->cfs_audit_token, sizeof(msg_attached->cfs_real_audit_token));
3319 		} else if (!cfil_copy_audit_token(msg_attached->cfs_pid, (audit_token_t *)&msg_attached->cfs_real_audit_token)) {
3320 			CFIL_LOG(LOG_ERR, "CFIL: Failed to get real audit token for <sockID %llu> ", entry->cfe_cfil_info->cfi_sock_id);
3321 		}
3322 	}
3323 
3324 	necp_with_inp_domain_name(so, msg_attached, cfil_populate_attached_msg_domain_name);
3325 
3326 	if (cfil_info->cfi_debug) {
3327 		cfil_info_log(LOG_INFO, cfil_info, "CFIL: SENDING ATTACH UP");
3328 	}
3329 
3330 	cfil_dispatch_attach_event_sign(entry->cfe_filter->cf_crypto_state, cfil_info, msg_attached);
3331 
3332 	error = ctl_enqueuedata(entry->cfe_filter->cf_kcref,
3333 	    entry->cfe_filter->cf_kcunit,
3334 	    msg_attached,
3335 	    sizeof(struct cfil_msg_sock_attached),
3336 	    CTL_DATA_EOR);
3337 
3338 	kfree_data(msg_attached, sizeof(struct cfil_msg_sock_attached));
3339 
3340 	if (error != 0) {
3341 		CFIL_LOG(LOG_ERR, "ctl_enqueuedata() failed: %d", error);
3342 		goto done;
3343 	}
3344 	microuptime(&entry->cfe_last_event);
3345 	cfil_info->cfi_first_event.tv_sec = entry->cfe_last_event.tv_sec;
3346 	cfil_info->cfi_first_event.tv_usec = entry->cfe_last_event.tv_usec;
3347 
3348 	entry->cfe_flags |= CFEF_SENT_SOCK_ATTACHED;
3349 	OSIncrementAtomic(&cfil_stats.cfs_attach_event_ok);
3350 done:
3351 
3352 	/* We can recover from flow control */
3353 	if (error == ENOBUFS) {
3354 		entry->cfe_flags |= CFEF_FLOW_CONTROLLED;
3355 		OSIncrementAtomic(&cfil_stats.cfs_attach_event_flow_control);
3356 
3357 		if (!cfil_rw_lock_shared_to_exclusive(&cfil_lck_rw)) {
3358 			cfil_rw_lock_exclusive(&cfil_lck_rw);
3359 		}
3360 
3361 		cfc->cf_flags |= CFF_FLOW_CONTROLLED;
3362 
3363 		cfil_rw_unlock_exclusive(&cfil_lck_rw);
3364 	} else {
3365 		if (error != 0) {
3366 			OSIncrementAtomic(&cfil_stats.cfs_attach_event_fail);
3367 		}
3368 
3369 		cfil_rw_unlock_shared(&cfil_lck_rw);
3370 	}
3371 	return error;
3372 }
3373 
3374 static int
cfil_dispatch_disconnect_event(struct socket * so,struct cfil_info * cfil_info,uint32_t kcunit,int outgoing)3375 cfil_dispatch_disconnect_event(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing)
3376 {
3377 	errno_t error = 0;
3378 	struct mbuf *msg = NULL;
3379 	struct cfil_entry *entry;
3380 	struct cfe_buf *entrybuf;
3381 	struct cfil_msg_hdr msg_disconnected;
3382 	struct content_filter *cfc;
3383 
3384 	socket_lock_assert_owned(so);
3385 
3386 	cfil_rw_lock_shared(&cfil_lck_rw);
3387 
3388 	entry = &cfil_info->cfi_entries[kcunit - 1];
3389 	if (outgoing) {
3390 		entrybuf = &entry->cfe_snd;
3391 	} else {
3392 		entrybuf = &entry->cfe_rcv;
3393 	}
3394 
3395 	cfc = entry->cfe_filter;
3396 	if (cfc == NULL) {
3397 		goto done;
3398 	}
3399 
3400 	// Mark if this flow qualifies for immediate close.
3401 	SET_NO_CLOSE_WAIT(sotoinpcb(so), cfil_info);
3402 
3403 	CFIL_LOG(LOG_INFO, "so %llx kcunit %u outgoing %d",
3404 	    (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit, outgoing);
3405 
3406 	/*
3407 	 * Send the disconnection event once
3408 	 */
3409 	if ((outgoing && (entry->cfe_flags & CFEF_SENT_DISCONNECT_OUT)) ||
3410 	    (!outgoing && (entry->cfe_flags & CFEF_SENT_DISCONNECT_IN))) {
3411 		CFIL_LOG(LOG_INFO, "so %llx disconnect already sent",
3412 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
3413 		goto done;
3414 	}
3415 
3416 	/*
3417 	 * We're not disconnected as long as some data is waiting
3418 	 * to be delivered to the filter
3419 	 */
3420 	if (outgoing && cfil_queue_empty(&entrybuf->cfe_ctl_q) == 0) {
3421 		CFIL_LOG(LOG_INFO, "so %llx control queue not empty",
3422 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
3423 		error = EBUSY;
3424 		goto done;
3425 	}
3426 	/* Would be wasteful to try when flow controlled */
3427 	if (cfc->cf_flags & CFF_FLOW_CONTROLLED) {
3428 		error = ENOBUFS;
3429 		goto done;
3430 	}
3431 
3432 	if (cfil_info->cfi_debug) {
3433 		cfil_info_log(LOG_INFO, cfil_info, outgoing ?
3434 		    "CFIL: OUT - SENDING DISCONNECT UP":
3435 		    "CFIL: IN - SENDING DISCONNECT UP");
3436 	}
3437 
3438 	bzero(&msg_disconnected, sizeof(struct cfil_msg_hdr));
3439 	msg_disconnected.cfm_len = sizeof(struct cfil_msg_hdr);
3440 	msg_disconnected.cfm_version = CFM_VERSION_CURRENT;
3441 	msg_disconnected.cfm_type = CFM_TYPE_EVENT;
3442 	msg_disconnected.cfm_op = outgoing ? CFM_OP_DISCONNECT_OUT :
3443 	    CFM_OP_DISCONNECT_IN;
3444 	msg_disconnected.cfm_sock_id = entry->cfe_cfil_info->cfi_sock_id;
3445 	error = ctl_enqueuedata(entry->cfe_filter->cf_kcref,
3446 	    entry->cfe_filter->cf_kcunit,
3447 	    &msg_disconnected,
3448 	    sizeof(struct cfil_msg_hdr),
3449 	    CTL_DATA_EOR);
3450 	if (error != 0) {
3451 		CFIL_LOG(LOG_ERR, "ctl_enqueuembuf() failed: %d", error);
3452 		mbuf_freem(msg);
3453 		goto done;
3454 	}
3455 	microuptime(&entry->cfe_last_event);
3456 	CFI_ADD_TIME_LOG(cfil_info, &entry->cfe_last_event, &cfil_info->cfi_first_event, msg_disconnected.cfm_op);
3457 
3458 	/* Remember we have sent the disconnection message */
3459 	if (outgoing) {
3460 		entry->cfe_flags |= CFEF_SENT_DISCONNECT_OUT;
3461 		OSIncrementAtomic(&cfil_stats.cfs_disconnect_out_event_ok);
3462 	} else {
3463 		entry->cfe_flags |= CFEF_SENT_DISCONNECT_IN;
3464 		OSIncrementAtomic(&cfil_stats.cfs_disconnect_in_event_ok);
3465 	}
3466 done:
3467 	if (error == ENOBUFS) {
3468 		entry->cfe_flags |= CFEF_FLOW_CONTROLLED;
3469 		OSIncrementAtomic(
3470 			&cfil_stats.cfs_disconnect_event_flow_control);
3471 
3472 		if (!cfil_rw_lock_shared_to_exclusive(&cfil_lck_rw)) {
3473 			cfil_rw_lock_exclusive(&cfil_lck_rw);
3474 		}
3475 
3476 		cfc->cf_flags |= CFF_FLOW_CONTROLLED;
3477 
3478 		cfil_rw_unlock_exclusive(&cfil_lck_rw);
3479 	} else {
3480 		if (error != 0) {
3481 			OSIncrementAtomic(
3482 				&cfil_stats.cfs_disconnect_event_fail);
3483 		}
3484 
3485 		cfil_rw_unlock_shared(&cfil_lck_rw);
3486 	}
3487 	return error;
3488 }
3489 
3490 int
cfil_dispatch_closed_event(struct socket * so,struct cfil_info * cfil_info,int kcunit)3491 cfil_dispatch_closed_event(struct socket *so, struct cfil_info *cfil_info, int kcunit)
3492 {
3493 	struct cfil_entry *entry;
3494 	struct cfil_msg_sock_closed msg_closed;
3495 	errno_t error = 0;
3496 	struct content_filter *cfc;
3497 
3498 	socket_lock_assert_owned(so);
3499 
3500 	cfil_rw_lock_shared(&cfil_lck_rw);
3501 
3502 	entry = &cfil_info->cfi_entries[kcunit - 1];
3503 	cfc = entry->cfe_filter;
3504 	if (cfc == NULL) {
3505 		goto done;
3506 	}
3507 
3508 	CFIL_LOG(LOG_INFO, "so %llx kcunit %d",
3509 	    (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit);
3510 
3511 	/* Would be wasteful to try when flow controlled */
3512 	if (cfc->cf_flags & CFF_FLOW_CONTROLLED) {
3513 		error = ENOBUFS;
3514 		goto done;
3515 	}
3516 	/*
3517 	 * Send a single closed message per filter
3518 	 */
3519 	if ((entry->cfe_flags & CFEF_SENT_SOCK_CLOSED) != 0) {
3520 		goto done;
3521 	}
3522 	if ((entry->cfe_flags & CFEF_SENT_SOCK_ATTACHED) == 0) {
3523 		goto done;
3524 	}
3525 
3526 	microuptime(&entry->cfe_last_event);
3527 	CFI_ADD_TIME_LOG(cfil_info, &entry->cfe_last_event, &cfil_info->cfi_first_event, CFM_OP_SOCKET_CLOSED);
3528 
3529 	bzero(&msg_closed, sizeof(struct cfil_msg_sock_closed));
3530 	msg_closed.cfc_msghdr.cfm_len = sizeof(struct cfil_msg_sock_closed);
3531 	msg_closed.cfc_msghdr.cfm_version = CFM_VERSION_CURRENT;
3532 	msg_closed.cfc_msghdr.cfm_type = CFM_TYPE_EVENT;
3533 	msg_closed.cfc_msghdr.cfm_op = CFM_OP_SOCKET_CLOSED;
3534 	msg_closed.cfc_msghdr.cfm_sock_id = entry->cfe_cfil_info->cfi_sock_id;
3535 	msg_closed.cfc_first_event.tv_sec = cfil_info->cfi_first_event.tv_sec;
3536 	msg_closed.cfc_first_event.tv_usec = cfil_info->cfi_first_event.tv_usec;
3537 	memcpy(msg_closed.cfc_op_time, cfil_info->cfi_op_time, sizeof(uint32_t) * CFI_MAX_TIME_LOG_ENTRY);
3538 	memcpy(msg_closed.cfc_op_list, cfil_info->cfi_op_list, sizeof(unsigned char) * CFI_MAX_TIME_LOG_ENTRY);
3539 	msg_closed.cfc_op_list_ctr = cfil_info->cfi_op_list_ctr;
3540 	msg_closed.cfc_byte_inbound_count = cfil_info->cfi_byte_inbound_count;
3541 	msg_closed.cfc_byte_outbound_count = cfil_info->cfi_byte_outbound_count;
3542 
3543 	cfil_dispatch_closed_event_sign(entry->cfe_filter->cf_crypto_state, so, cfil_info, &msg_closed);
3544 
3545 	if (cfil_info->cfi_debug) {
3546 		cfil_info_log(LOG_INFO, cfil_info, "CFIL: SENDING CLOSED UP");
3547 	}
3548 
3549 	/* for debugging
3550 	 *  if (msg_closed.cfc_op_list_ctr > CFI_MAX_TIME_LOG_ENTRY) {
3551 	 *       msg_closed.cfc_op_list_ctr  = CFI_MAX_TIME_LOG_ENTRY;       // just in case
3552 	 *  }
3553 	 *  for (unsigned int i = 0; i < msg_closed.cfc_op_list_ctr ; i++) {
3554 	 *       CFIL_LOG(LOG_ERR, "MD: socket %llu event %2u, time + %u msec", msg_closed.cfc_msghdr.cfm_sock_id, (unsigned short)msg_closed.cfc_op_list[i], msg_closed.cfc_op_time[i]);
3555 	 *  }
3556 	 */
3557 
3558 	error = ctl_enqueuedata(entry->cfe_filter->cf_kcref,
3559 	    entry->cfe_filter->cf_kcunit,
3560 	    &msg_closed,
3561 	    sizeof(struct cfil_msg_sock_closed),
3562 	    CTL_DATA_EOR);
3563 	if (error != 0) {
3564 		CFIL_LOG(LOG_ERR, "ctl_enqueuedata() failed: %d",
3565 		    error);
3566 		goto done;
3567 	}
3568 
3569 	entry->cfe_flags |= CFEF_SENT_SOCK_CLOSED;
3570 	OSIncrementAtomic(&cfil_stats.cfs_closed_event_ok);
3571 done:
3572 	/* We can recover from flow control */
3573 	if (error == ENOBUFS) {
3574 		entry->cfe_flags |= CFEF_FLOW_CONTROLLED;
3575 		OSIncrementAtomic(&cfil_stats.cfs_closed_event_flow_control);
3576 
3577 		if (!cfil_rw_lock_shared_to_exclusive(&cfil_lck_rw)) {
3578 			cfil_rw_lock_exclusive(&cfil_lck_rw);
3579 		}
3580 
3581 		cfc->cf_flags |= CFF_FLOW_CONTROLLED;
3582 
3583 		cfil_rw_unlock_exclusive(&cfil_lck_rw);
3584 	} else {
3585 		if (error != 0) {
3586 			OSIncrementAtomic(&cfil_stats.cfs_closed_event_fail);
3587 		}
3588 
3589 		cfil_rw_unlock_shared(&cfil_lck_rw);
3590 	}
3591 
3592 	return error;
3593 }
3594 
3595 static void
fill_ip6_sockaddr_4_6(union sockaddr_in_4_6 * sin46,struct in6_addr * ip6,u_int16_t port,uint32_t ifscope)3596 fill_ip6_sockaddr_4_6(union sockaddr_in_4_6 *sin46,
3597     struct in6_addr *ip6, u_int16_t port, uint32_t ifscope)
3598 {
3599 	if (sin46 == NULL) {
3600 		return;
3601 	}
3602 
3603 	struct sockaddr_in6 *sin6 = &sin46->sin6;
3604 
3605 	sin6->sin6_family = AF_INET6;
3606 	sin6->sin6_len = sizeof(*sin6);
3607 	sin6->sin6_port = port;
3608 	sin6->sin6_addr = *ip6;
3609 	if (IN6_IS_SCOPE_EMBED(&sin6->sin6_addr)) {
3610 		sin6->sin6_scope_id = ifscope;
3611 		if (in6_embedded_scope) {
3612 			in6_verify_ifscope(&sin6->sin6_addr, sin6->sin6_scope_id);
3613 			if (sin6->sin6_addr.s6_addr16[1] != 0) {
3614 				sin6->sin6_scope_id = ntohs(sin6->sin6_addr.s6_addr16[1]);
3615 				sin6->sin6_addr.s6_addr16[1] = 0;
3616 			}
3617 		}
3618 	}
3619 }
3620 
3621 static void
fill_ip_sockaddr_4_6(union sockaddr_in_4_6 * sin46,struct in_addr ip,u_int16_t port)3622 fill_ip_sockaddr_4_6(union sockaddr_in_4_6 *sin46,
3623     struct in_addr ip, u_int16_t port)
3624 {
3625 	if (sin46 == NULL) {
3626 		return;
3627 	}
3628 
3629 	struct sockaddr_in *sin = &sin46->sin;
3630 
3631 	sin->sin_family = AF_INET;
3632 	sin->sin_len = sizeof(*sin);
3633 	sin->sin_port = port;
3634 	sin->sin_addr.s_addr = ip.s_addr;
3635 }
3636 
3637 static void
cfil_get_flow_address_v6(struct soflow_hash_entry * entry,struct inpcb * inp,struct in6_addr ** laddr,struct in6_addr ** faddr,u_int16_t * lport,u_int16_t * fport)3638 cfil_get_flow_address_v6(struct soflow_hash_entry *entry, struct inpcb *inp,
3639     struct in6_addr **laddr, struct in6_addr **faddr,
3640     u_int16_t *lport, u_int16_t *fport)
3641 {
3642 	if (entry != NULL) {
3643 		*laddr = &entry->soflow_laddr.addr6;
3644 		*faddr = &entry->soflow_faddr.addr6;
3645 		*lport = entry->soflow_lport;
3646 		*fport = entry->soflow_fport;
3647 	} else {
3648 		*laddr = &inp->in6p_laddr;
3649 		*faddr = &inp->in6p_faddr;
3650 		*lport = inp->inp_lport;
3651 		*fport = inp->inp_fport;
3652 	}
3653 }
3654 
3655 static void
cfil_get_flow_address(struct soflow_hash_entry * entry,struct inpcb * inp,struct in_addr * laddr,struct in_addr * faddr,u_int16_t * lport,u_int16_t * fport)3656 cfil_get_flow_address(struct soflow_hash_entry *entry, struct inpcb *inp,
3657     struct in_addr *laddr, struct in_addr *faddr,
3658     u_int16_t *lport, u_int16_t *fport)
3659 {
3660 	if (entry != NULL) {
3661 		*laddr = entry->soflow_laddr.addr46.ia46_addr4;
3662 		*faddr = entry->soflow_faddr.addr46.ia46_addr4;
3663 		*lport = entry->soflow_lport;
3664 		*fport = entry->soflow_fport;
3665 	} else {
3666 		*laddr = inp->inp_laddr;
3667 		*faddr = inp->inp_faddr;
3668 		*lport = inp->inp_lport;
3669 		*fport = inp->inp_fport;
3670 	}
3671 }
3672 
3673 static int
cfil_dispatch_data_event(struct socket * so,struct cfil_info * cfil_info,uint32_t kcunit,int outgoing,struct mbuf * data,unsigned int copyoffset,unsigned int copylen)3674 cfil_dispatch_data_event(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing,
3675     struct mbuf *data, unsigned int copyoffset, unsigned int copylen)
3676 {
3677 	errno_t error = 0;
3678 	struct mbuf *copy = NULL;
3679 	struct mbuf *msg = NULL;
3680 	unsigned int one = 1;
3681 	struct cfil_msg_data_event *data_req;
3682 	size_t hdrsize;
3683 	struct inpcb *inp = (struct inpcb *)so->so_pcb;
3684 	struct cfil_entry *entry;
3685 	struct cfe_buf *entrybuf;
3686 	struct content_filter *cfc;
3687 	struct timeval tv;
3688 	int inp_flags = 0;
3689 
3690 	cfil_rw_lock_shared(&cfil_lck_rw);
3691 
3692 	entry = &cfil_info->cfi_entries[kcunit - 1];
3693 	if (outgoing) {
3694 		entrybuf = &entry->cfe_snd;
3695 	} else {
3696 		entrybuf = &entry->cfe_rcv;
3697 	}
3698 
3699 	cfc = entry->cfe_filter;
3700 	if (cfc == NULL) {
3701 		goto done;
3702 	}
3703 
3704 	data = cfil_data_start(data);
3705 	if (data == NULL) {
3706 		CFIL_LOG(LOG_ERR, "No data start");
3707 		goto done;
3708 	}
3709 
3710 	CFIL_LOG(LOG_INFO, "so %llx kcunit %u outgoing %d",
3711 	    (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit, outgoing);
3712 
3713 	socket_lock_assert_owned(so);
3714 
3715 	/* Would be wasteful to try */
3716 	if (cfc->cf_flags & CFF_FLOW_CONTROLLED) {
3717 		error = ENOBUFS;
3718 		goto done;
3719 	}
3720 
3721 	/* Make a copy of the data to pass to kernel control socket */
3722 	copy = m_copym_mode(data, copyoffset, copylen, M_DONTWAIT,
3723 	    M_COPYM_NOOP_HDR);
3724 	if (copy == NULL) {
3725 		CFIL_LOG(LOG_ERR, "m_copym_mode() failed");
3726 		error = ENOMEM;
3727 		goto done;
3728 	}
3729 
3730 	/* We need an mbuf packet for the message header */
3731 	hdrsize = sizeof(struct cfil_msg_data_event);
3732 	error = mbuf_allocpacket(MBUF_DONTWAIT, hdrsize, &one, &msg);
3733 	if (error != 0) {
3734 		CFIL_LOG(LOG_ERR, "mbuf_allocpacket() failed");
3735 		m_freem(copy);
3736 		/*
3737 		 * ENOBUFS is to indicate flow control
3738 		 */
3739 		error = ENOMEM;
3740 		goto done;
3741 	}
3742 	mbuf_setlen(msg, hdrsize);
3743 	mbuf_pkthdr_setlen(msg, hdrsize + copylen);
3744 	msg->m_next = copy;
3745 	data_req = (struct cfil_msg_data_event *)mbuf_data(msg);
3746 	bzero(data_req, hdrsize);
3747 	data_req->cfd_msghdr.cfm_len = (uint32_t)hdrsize + copylen;
3748 	data_req->cfd_msghdr.cfm_version = 1;
3749 	data_req->cfd_msghdr.cfm_type = CFM_TYPE_EVENT;
3750 	data_req->cfd_msghdr.cfm_op =
3751 	    outgoing ? CFM_OP_DATA_OUT : CFM_OP_DATA_IN;
3752 	data_req->cfd_msghdr.cfm_sock_id =
3753 	    entry->cfe_cfil_info->cfi_sock_id;
3754 	data_req->cfd_start_offset = entrybuf->cfe_peeked;
3755 	data_req->cfd_end_offset = entrybuf->cfe_peeked + copylen;
3756 
3757 	data_req->cfd_flags = 0;
3758 	if (OPTIONAL_IP_HEADER(so)) {
3759 		/*
3760 		 * For non-UDP/TCP traffic, indicate to filters if optional
3761 		 * IP header is present:
3762 		 *      outgoing - indicate according to INP_HDRINCL flag
3763 		 *      incoming - For IPv4 only, stripping of IP header is
3764 		 *                 optional.  But for CFIL, we delay stripping
3765 		 *                 at rip_input.  So CFIL always expects IP
3766 		 *                 frames. IP header will be stripped according
3767 		 *                 to INP_STRIPHDR flag later at reinjection.
3768 		 */
3769 		if ((!outgoing && !IS_INP_V6(inp)) ||
3770 		    (outgoing && cfil_dgram_peek_socket_state(data, &inp_flags) && (inp_flags & INP_HDRINCL))) {
3771 			data_req->cfd_flags |= CFD_DATA_FLAG_IP_HEADER;
3772 		}
3773 	}
3774 
3775 	/*
3776 	 * Copy address/port into event msg.
3777 	 * For non connected sockets need to copy addresses from passed
3778 	 * parameters
3779 	 */
3780 	cfil_fill_event_msg_addresses(cfil_info->cfi_hash_entry, inp,
3781 	    &data_req->cfc_src, &data_req->cfc_dst,
3782 	    !IS_INP_V6(inp), outgoing);
3783 
3784 	if (cfil_info->cfi_debug && cfil_log_data) {
3785 		cfil_info_log(LOG_DEBUG, cfil_info, "CFIL: SENDING DATA UP");
3786 	}
3787 
3788 	if (cfil_info->cfi_isSignatureLatest == false) {
3789 		cfil_dispatch_data_event_sign(entry->cfe_filter->cf_crypto_state, so, cfil_info, data_req);
3790 	}
3791 
3792 	microuptime(&tv);
3793 	CFI_ADD_TIME_LOG(cfil_info, &tv, &cfil_info->cfi_first_event, data_req->cfd_msghdr.cfm_op);
3794 
3795 	/* Pass the message to the content filter */
3796 	error = ctl_enqueuembuf(entry->cfe_filter->cf_kcref,
3797 	    entry->cfe_filter->cf_kcunit,
3798 	    msg, CTL_DATA_EOR);
3799 	if (error != 0) {
3800 		CFIL_LOG(LOG_ERR, "ctl_enqueuembuf() failed: %d", error);
3801 		mbuf_freem(msg);
3802 		goto done;
3803 	}
3804 	entry->cfe_flags &= ~CFEF_FLOW_CONTROLLED;
3805 	OSIncrementAtomic(&cfil_stats.cfs_data_event_ok);
3806 
3807 	if (cfil_info->cfi_debug && cfil_log_data) {
3808 		CFIL_LOG(LOG_DEBUG, "CFIL: VERDICT ACTION: so %llx sockID %llu outgoing %d: mbuf %llx copyoffset %u copylen %u (%s)",
3809 		    (uint64_t)VM_KERNEL_ADDRPERM(so), cfil_info->cfi_sock_id, outgoing, (uint64_t)VM_KERNEL_ADDRPERM(data), copyoffset, copylen,
3810 		    data_req->cfd_flags & CFD_DATA_FLAG_IP_HEADER ? "IP HDR" : "NO IP HDR");
3811 	}
3812 
3813 done:
3814 	if (error == ENOBUFS) {
3815 		entry->cfe_flags |= CFEF_FLOW_CONTROLLED;
3816 		OSIncrementAtomic(
3817 			&cfil_stats.cfs_data_event_flow_control);
3818 
3819 		if (!cfil_rw_lock_shared_to_exclusive(&cfil_lck_rw)) {
3820 			cfil_rw_lock_exclusive(&cfil_lck_rw);
3821 		}
3822 
3823 		cfc->cf_flags |= CFF_FLOW_CONTROLLED;
3824 
3825 		cfil_rw_unlock_exclusive(&cfil_lck_rw);
3826 	} else {
3827 		if (error != 0) {
3828 			OSIncrementAtomic(&cfil_stats.cfs_data_event_fail);
3829 		}
3830 
3831 		cfil_rw_unlock_shared(&cfil_lck_rw);
3832 	}
3833 	return error;
3834 }
3835 
3836 /*
3837  * Process the queue of data waiting to be delivered to content filter
3838  */
3839 static int
cfil_data_service_ctl_q(struct socket * so,struct cfil_info * cfil_info,uint32_t kcunit,int outgoing)3840 cfil_data_service_ctl_q(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing)
3841 {
3842 	errno_t error = 0;
3843 	struct mbuf *data, *tmp = NULL;
3844 	unsigned int datalen = 0, copylen = 0, copyoffset = 0;
3845 	struct cfil_entry *entry;
3846 	struct cfe_buf *entrybuf;
3847 	uint64_t currentoffset = 0;
3848 
3849 	if (cfil_info == NULL) {
3850 		return 0;
3851 	}
3852 
3853 	CFIL_LOG(LOG_INFO, "so %llx kcunit %u outgoing %d",
3854 	    (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit, outgoing);
3855 
3856 	socket_lock_assert_owned(so);
3857 
3858 	entry = &cfil_info->cfi_entries[kcunit - 1];
3859 	if (outgoing) {
3860 		entrybuf = &entry->cfe_snd;
3861 	} else {
3862 		entrybuf = &entry->cfe_rcv;
3863 	}
3864 
3865 	/* Send attached message if not yet done */
3866 	if ((entry->cfe_flags & CFEF_SENT_SOCK_ATTACHED) == 0) {
3867 		error = cfil_dispatch_attach_event(so, cfil_info, CFI_ENTRY_KCUNIT(cfil_info, entry),
3868 		    cfil_info->cfi_dir);
3869 		if (error != 0) {
3870 			/* We can recover from flow control */
3871 			if (error == ENOBUFS || error == ENOMEM) {
3872 				error = 0;
3873 			}
3874 			goto done;
3875 		}
3876 	} else if ((entry->cfe_flags & CFEF_DATA_START) == 0) {
3877 		OSIncrementAtomic(&cfil_stats.cfs_ctl_q_not_started);
3878 		goto done;
3879 	}
3880 
3881 	if (cfil_info->cfi_debug && cfil_log_data) {
3882 		CFIL_LOG(LOG_DEBUG, "CFIL: SERVICE CTL-Q: pass_offset %llu peeked %llu peek_offset %llu",
3883 		    entrybuf->cfe_pass_offset,
3884 		    entrybuf->cfe_peeked,
3885 		    entrybuf->cfe_peek_offset);
3886 	}
3887 
3888 	/* Move all data that can pass */
3889 	while ((data = cfil_queue_first(&entrybuf->cfe_ctl_q)) != NULL &&
3890 	    entrybuf->cfe_ctl_q.q_start < entrybuf->cfe_pass_offset) {
3891 		datalen = cfil_data_length(data, NULL, NULL);
3892 		tmp = data;
3893 
3894 		if (entrybuf->cfe_ctl_q.q_start + datalen <=
3895 		    entrybuf->cfe_pass_offset) {
3896 			/*
3897 			 * The first mbuf can fully pass
3898 			 */
3899 			copylen = datalen;
3900 		} else {
3901 			/*
3902 			 * The first mbuf can partially pass
3903 			 */
3904 			copylen = (unsigned int)(entrybuf->cfe_pass_offset - entrybuf->cfe_ctl_q.q_start);
3905 		}
3906 		VERIFY(copylen <= datalen);
3907 
3908 		if (cfil_info->cfi_debug && cfil_log_data) {
3909 			CFIL_LOG(LOG_DEBUG,
3910 			    "CFIL: SERVICE CTL-Q PASSING: %llx first %llu peeked %llu pass %llu peek %llu"
3911 			    "datalen %u copylen %u",
3912 			    (uint64_t)VM_KERNEL_ADDRPERM(tmp),
3913 			    entrybuf->cfe_ctl_q.q_start,
3914 			    entrybuf->cfe_peeked,
3915 			    entrybuf->cfe_pass_offset,
3916 			    entrybuf->cfe_peek_offset,
3917 			    datalen, copylen);
3918 		}
3919 
3920 		/*
3921 		 * Data that passes has been peeked at explicitly or
3922 		 * implicitly
3923 		 */
3924 		if (entrybuf->cfe_ctl_q.q_start + copylen >
3925 		    entrybuf->cfe_peeked) {
3926 			entrybuf->cfe_peeked =
3927 			    entrybuf->cfe_ctl_q.q_start + copylen;
3928 		}
3929 		/*
3930 		 * Stop on partial pass
3931 		 */
3932 		if (copylen < datalen) {
3933 			break;
3934 		}
3935 
3936 		/* All good, move full data from ctl queue to pending queue */
3937 		cfil_queue_remove(&entrybuf->cfe_ctl_q, data, datalen);
3938 
3939 		cfil_queue_enqueue(&entrybuf->cfe_pending_q, data, datalen);
3940 		if (outgoing) {
3941 			OSAddAtomic64(datalen,
3942 			    &cfil_stats.cfs_pending_q_out_enqueued);
3943 		} else {
3944 			OSAddAtomic64(datalen,
3945 			    &cfil_stats.cfs_pending_q_in_enqueued);
3946 		}
3947 	}
3948 	CFIL_INFO_VERIFY(cfil_info);
3949 	if (tmp != NULL) {
3950 		CFIL_LOG(LOG_DEBUG,
3951 		    "%llx first %llu peeked %llu pass %llu peek %llu"
3952 		    "datalen %u copylen %u",
3953 		    (uint64_t)VM_KERNEL_ADDRPERM(tmp),
3954 		    entrybuf->cfe_ctl_q.q_start,
3955 		    entrybuf->cfe_peeked,
3956 		    entrybuf->cfe_pass_offset,
3957 		    entrybuf->cfe_peek_offset,
3958 		    datalen, copylen);
3959 	}
3960 	tmp = NULL;
3961 
3962 	/* Now deal with remaining data the filter wants to peek at */
3963 	for (data = cfil_queue_first(&entrybuf->cfe_ctl_q),
3964 	    currentoffset = entrybuf->cfe_ctl_q.q_start;
3965 	    data != NULL && currentoffset < entrybuf->cfe_peek_offset;
3966 	    data = cfil_queue_next(&entrybuf->cfe_ctl_q, data),
3967 	    currentoffset += datalen) {
3968 		datalen = cfil_data_length(data, NULL, NULL);
3969 		tmp = data;
3970 
3971 		/* We've already peeked at this mbuf */
3972 		if (currentoffset + datalen <= entrybuf->cfe_peeked) {
3973 			continue;
3974 		}
3975 		/*
3976 		 * The data in the first mbuf may have been
3977 		 * partially peeked at
3978 		 */
3979 		copyoffset = (unsigned int)(entrybuf->cfe_peeked - currentoffset);
3980 		VERIFY(copyoffset < datalen);
3981 		copylen = datalen - copyoffset;
3982 		VERIFY(copylen <= datalen);
3983 		/*
3984 		 * Do not copy more than needed
3985 		 */
3986 		if (currentoffset + copyoffset + copylen >
3987 		    entrybuf->cfe_peek_offset) {
3988 			copylen = (unsigned int)(entrybuf->cfe_peek_offset -
3989 			    (currentoffset + copyoffset));
3990 		}
3991 
3992 		if (cfil_info->cfi_debug && cfil_log_data) {
3993 			CFIL_LOG(LOG_DEBUG,
3994 			    "CFIL: SERVICE CTL-Q PEEKING: %llx current %llu peeked %llu pass %llu peek %llu "
3995 			    "datalen %u copylen %u copyoffset %u",
3996 			    (uint64_t)VM_KERNEL_ADDRPERM(tmp),
3997 			    currentoffset,
3998 			    entrybuf->cfe_peeked,
3999 			    entrybuf->cfe_pass_offset,
4000 			    entrybuf->cfe_peek_offset,
4001 			    datalen, copylen, copyoffset);
4002 		}
4003 
4004 		/*
4005 		 * Stop if there is nothing more to peek at
4006 		 */
4007 		if (copylen == 0) {
4008 			break;
4009 		}
4010 		/*
4011 		 * Let the filter get a peek at this span of data
4012 		 */
4013 		error = cfil_dispatch_data_event(so, cfil_info, kcunit,
4014 		    outgoing, data, copyoffset, copylen);
4015 		if (error != 0) {
4016 			/* On error, leave data in ctl_q */
4017 			break;
4018 		}
4019 		entrybuf->cfe_peeked += copylen;
4020 		if (outgoing) {
4021 			OSAddAtomic64(copylen,
4022 			    &cfil_stats.cfs_ctl_q_out_peeked);
4023 		} else {
4024 			OSAddAtomic64(copylen,
4025 			    &cfil_stats.cfs_ctl_q_in_peeked);
4026 		}
4027 
4028 		/* Stop when data could not be fully peeked at */
4029 		if (copylen + copyoffset < datalen) {
4030 			break;
4031 		}
4032 	}
4033 	CFIL_INFO_VERIFY(cfil_info);
4034 	if (tmp != NULL) {
4035 		CFIL_LOG(LOG_DEBUG,
4036 		    "%llx first %llu peeked %llu pass %llu peek %llu"
4037 		    "datalen %u copylen %u copyoffset %u",
4038 		    (uint64_t)VM_KERNEL_ADDRPERM(tmp),
4039 		    currentoffset,
4040 		    entrybuf->cfe_peeked,
4041 		    entrybuf->cfe_pass_offset,
4042 		    entrybuf->cfe_peek_offset,
4043 		    datalen, copylen, copyoffset);
4044 	}
4045 
4046 	/*
4047 	 * Process data that has passed the filter
4048 	 */
4049 	error = cfil_service_pending_queue(so, cfil_info, kcunit, outgoing);
4050 	if (error != 0) {
4051 		CFIL_LOG(LOG_ERR, "cfil_service_pending_queue() error %d",
4052 		    error);
4053 		goto done;
4054 	}
4055 
4056 	/*
4057 	 * Dispatch disconnect events that could not be sent
4058 	 */
4059 	if (cfil_info == NULL) {
4060 		goto done;
4061 	} else if (outgoing) {
4062 		if ((cfil_info->cfi_flags & CFIF_SHUT_WR) &&
4063 		    !(entry->cfe_flags & CFEF_SENT_DISCONNECT_OUT)) {
4064 			cfil_dispatch_disconnect_event(so, cfil_info, kcunit, 1);
4065 		}
4066 	} else {
4067 		if ((cfil_info->cfi_flags & CFIF_SHUT_RD) &&
4068 		    !(entry->cfe_flags & CFEF_SENT_DISCONNECT_IN)) {
4069 			cfil_dispatch_disconnect_event(so, cfil_info, kcunit, 0);
4070 		}
4071 	}
4072 
4073 done:
4074 	CFIL_LOG(LOG_DEBUG,
4075 	    "first %llu peeked %llu pass %llu peek %llu",
4076 	    entrybuf->cfe_ctl_q.q_start,
4077 	    entrybuf->cfe_peeked,
4078 	    entrybuf->cfe_pass_offset,
4079 	    entrybuf->cfe_peek_offset);
4080 
4081 	CFIL_INFO_VERIFY(cfil_info);
4082 	return error;
4083 }
4084 
4085 /*
4086  * cfil_data_filter()
4087  *
4088  * Process data for a content filter installed on a socket
4089  */
4090 int
cfil_data_filter(struct socket * so,struct cfil_info * cfil_info,uint32_t kcunit,int outgoing,struct mbuf * data,uint32_t datalen)4091 cfil_data_filter(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing,
4092     struct mbuf *data, uint32_t datalen)
4093 {
4094 	errno_t error = 0;
4095 	struct cfil_entry *entry;
4096 	struct cfe_buf *entrybuf;
4097 
4098 	CFIL_LOG(LOG_INFO, "so %llx kcunit %u outgoing %d",
4099 	    (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit, outgoing);
4100 
4101 	socket_lock_assert_owned(so);
4102 
4103 	entry = &cfil_info->cfi_entries[kcunit - 1];
4104 	if (outgoing) {
4105 		entrybuf = &entry->cfe_snd;
4106 	} else {
4107 		entrybuf = &entry->cfe_rcv;
4108 	}
4109 
4110 	/* Are we attached to the filter? */
4111 	if (entry->cfe_filter == NULL) {
4112 		error = 0;
4113 		goto done;
4114 	}
4115 
4116 	/* Dispatch to filters */
4117 	cfil_queue_enqueue(&entrybuf->cfe_ctl_q, data, datalen);
4118 	if (outgoing) {
4119 		OSAddAtomic64(datalen,
4120 		    &cfil_stats.cfs_ctl_q_out_enqueued);
4121 	} else {
4122 		OSAddAtomic64(datalen,
4123 		    &cfil_stats.cfs_ctl_q_in_enqueued);
4124 	}
4125 
4126 	error = cfil_data_service_ctl_q(so, cfil_info, kcunit, outgoing);
4127 	if (error != 0) {
4128 		CFIL_LOG(LOG_ERR, "cfil_data_service_ctl_q() error %d",
4129 		    error);
4130 	}
4131 	/*
4132 	 * We have to return EJUSTRETURN in all cases to avoid double free
4133 	 * by socket layer
4134 	 */
4135 	error = EJUSTRETURN;
4136 done:
4137 	CFIL_INFO_VERIFY(cfil_info);
4138 
4139 	CFIL_LOG(LOG_INFO, "return %d", error);
4140 	return error;
4141 }
4142 
4143 /*
4144  * cfil_service_inject_queue() re-inject data that passed the
4145  * content filters
4146  */
4147 static int
cfil_service_inject_queue(struct socket * so,struct cfil_info * cfil_info,int outgoing)4148 cfil_service_inject_queue(struct socket *so, struct cfil_info *cfil_info, int outgoing)
4149 {
4150 	mbuf_t data;
4151 	unsigned int datalen;
4152 	int mbcnt = 0;
4153 	int mbnum = 0;
4154 	errno_t error = 0;
4155 	struct cfi_buf *cfi_buf;
4156 	struct cfil_queue *inject_q;
4157 	int need_rwakeup = 0;
4158 	int count = 0;
4159 	struct inpcb *inp = NULL;
4160 	struct ip *ip = NULL;
4161 	unsigned int hlen;
4162 
4163 	if (cfil_info == NULL) {
4164 		return 0;
4165 	}
4166 
4167 	socket_lock_assert_owned(so);
4168 
4169 	if (so->so_state & SS_DEFUNCT) {
4170 		return 0;
4171 	}
4172 
4173 	if (outgoing) {
4174 		cfi_buf = &cfil_info->cfi_snd;
4175 		cfil_info->cfi_flags &= ~CFIF_RETRY_INJECT_OUT;
4176 	} else {
4177 		cfi_buf = &cfil_info->cfi_rcv;
4178 		cfil_info->cfi_flags &= ~CFIF_RETRY_INJECT_IN;
4179 	}
4180 	inject_q = &cfi_buf->cfi_inject_q;
4181 
4182 	if (cfil_queue_empty(inject_q)) {
4183 		return 0;
4184 	}
4185 
4186 	if (cfil_info->cfi_debug && cfil_log_data) {
4187 		CFIL_LOG(LOG_DEBUG, "CFIL: SERVICE INJECT-Q: <so %llx> outgoing %d queue len %llu",
4188 		    (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing, cfil_queue_len(inject_q));
4189 	}
4190 
4191 	while ((data = cfil_queue_first(inject_q)) != NULL) {
4192 		datalen = cfil_data_length(data, &mbcnt, &mbnum);
4193 
4194 		if (cfil_info->cfi_debug && cfil_log_data) {
4195 			CFIL_LOG(LOG_DEBUG, "CFIL: SERVICE INJECT-Q: <so %llx> data %llx datalen %u (mbcnt %u)",
4196 			    (uint64_t)VM_KERNEL_ADDRPERM(so), (uint64_t)VM_KERNEL_ADDRPERM(data), datalen, mbcnt);
4197 		}
4198 
4199 		/* Remove data from queue and adjust stats */
4200 		cfil_queue_remove(inject_q, data, datalen);
4201 		cfi_buf->cfi_pending_first += datalen;
4202 		cfi_buf->cfi_pending_mbcnt -= mbcnt;
4203 		cfi_buf->cfi_pending_mbnum -= mbnum;
4204 		cfil_info_buf_verify(cfi_buf);
4205 
4206 		if (outgoing) {
4207 			error = sosend_reinject(so, NULL, data, NULL, 0);
4208 			if (error != 0) {
4209 				cfil_info_log(LOG_ERR, cfil_info, "CFIL: Error: sosend_reinject() failed");
4210 				CFIL_LOG(LOG_ERR, "CFIL: sosend() failed %d", error);
4211 				break;
4212 			}
4213 			// At least one injection succeeded, need to wake up pending threads.
4214 			need_rwakeup = 1;
4215 		} else {
4216 			data->m_flags |= M_SKIPCFIL;
4217 
4218 			/*
4219 			 * NOTE: We currently only support TCP, UDP, ICMP,
4220 			 * ICMPv6 and RAWIP.  For MPTCP and message TCP we'll
4221 			 * need to call the appropriate sbappendxxx()
4222 			 * of fix sock_inject_data_in()
4223 			 */
4224 			if (NEED_DGRAM_FLOW_TRACKING(so)) {
4225 				if (OPTIONAL_IP_HEADER(so)) {
4226 					inp = sotoinpcb(so);
4227 					if (inp && (inp->inp_flags & INP_STRIPHDR)) {
4228 						mbuf_t data_start = cfil_data_start(data);
4229 						if (data_start != NULL && (data_start->m_flags & M_PKTHDR)) {
4230 							ip = mtod(data_start, struct ip *);
4231 							hlen = IP_VHL_HL(ip->ip_vhl) << 2;
4232 							data_start->m_len -= hlen;
4233 							data_start->m_pkthdr.len -= hlen;
4234 							data_start->m_data += hlen;
4235 						}
4236 					}
4237 				}
4238 
4239 				if (sbappendchain(&so->so_rcv, data, 0)) {
4240 					need_rwakeup = 1;
4241 				}
4242 			} else {
4243 				if (sbappendstream(&so->so_rcv, data)) {
4244 					need_rwakeup = 1;
4245 				}
4246 			}
4247 		}
4248 
4249 		if (outgoing) {
4250 			OSAddAtomic64(datalen,
4251 			    &cfil_stats.cfs_inject_q_out_passed);
4252 		} else {
4253 			OSAddAtomic64(datalen,
4254 			    &cfil_stats.cfs_inject_q_in_passed);
4255 		}
4256 
4257 		count++;
4258 	}
4259 
4260 	if (cfil_info->cfi_debug && cfil_log_data) {
4261 		CFIL_LOG(LOG_DEBUG, "CFIL: SERVICE INJECT-Q: <so %llx> injected %d",
4262 		    (uint64_t)VM_KERNEL_ADDRPERM(so), count);
4263 	}
4264 
4265 	/* A single wakeup is for several packets is more efficient */
4266 	if (need_rwakeup) {
4267 		if (outgoing == TRUE) {
4268 			sowwakeup(so);
4269 		} else {
4270 			sorwakeup(so);
4271 		}
4272 	}
4273 
4274 	if (error != 0 && cfil_info) {
4275 		if (error == ENOBUFS) {
4276 			OSIncrementAtomic(&cfil_stats.cfs_inject_q_nobufs);
4277 		}
4278 		if (error == ENOMEM) {
4279 			OSIncrementAtomic(&cfil_stats.cfs_inject_q_nomem);
4280 		}
4281 
4282 		if (outgoing) {
4283 			cfil_info->cfi_flags |= CFIF_RETRY_INJECT_OUT;
4284 			OSIncrementAtomic(&cfil_stats.cfs_inject_q_out_fail);
4285 		} else {
4286 			cfil_info->cfi_flags |= CFIF_RETRY_INJECT_IN;
4287 			OSIncrementAtomic(&cfil_stats.cfs_inject_q_in_fail);
4288 		}
4289 	}
4290 
4291 	/*
4292 	 * Notify
4293 	 */
4294 	if (cfil_info && (cfil_info->cfi_flags & CFIF_SHUT_WR)) {
4295 		cfil_sock_notify_shutdown(so, SHUT_WR);
4296 		if (cfil_sock_data_pending(&so->so_snd) == 0) {
4297 			soshutdownlock_final(so, SHUT_WR);
4298 		}
4299 	}
4300 	if (cfil_info && (cfil_info->cfi_flags & CFIF_CLOSE_WAIT)) {
4301 		if (cfil_filters_attached(so) == 0) {
4302 			CFIL_LOG(LOG_INFO, "so %llx waking",
4303 			    (uint64_t)VM_KERNEL_ADDRPERM(so));
4304 			wakeup((caddr_t)cfil_info);
4305 		}
4306 	}
4307 
4308 	CFIL_INFO_VERIFY(cfil_info);
4309 
4310 	return error;
4311 }
4312 
4313 static int
cfil_service_pending_queue(struct socket * so,struct cfil_info * cfil_info,uint32_t kcunit,int outgoing)4314 cfil_service_pending_queue(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing)
4315 {
4316 	uint64_t passlen, curlen;
4317 	mbuf_t data;
4318 	unsigned int datalen;
4319 	errno_t error = 0;
4320 	struct cfil_entry *entry;
4321 	struct cfe_buf *entrybuf;
4322 	struct cfil_queue *pending_q;
4323 	struct cfil_entry *iter_entry = NULL;
4324 
4325 	CFIL_LOG(LOG_INFO, "so %llx kcunit %u outgoing %d",
4326 	    (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit, outgoing);
4327 
4328 	socket_lock_assert_owned(so);
4329 
4330 	entry = &cfil_info->cfi_entries[kcunit - 1];
4331 	if (outgoing) {
4332 		entrybuf = &entry->cfe_snd;
4333 	} else {
4334 		entrybuf = &entry->cfe_rcv;
4335 	}
4336 
4337 	pending_q = &entrybuf->cfe_pending_q;
4338 
4339 	passlen = entrybuf->cfe_pass_offset - pending_q->q_start;
4340 
4341 	if (cfil_queue_empty(pending_q)) {
4342 		for (iter_entry = SLIST_NEXT(entry, cfe_order_link);
4343 		    iter_entry != NULL;
4344 		    iter_entry = SLIST_NEXT(iter_entry, cfe_order_link)) {
4345 			error = cfil_data_service_ctl_q(so, cfil_info, CFI_ENTRY_KCUNIT(cfil_info, iter_entry), outgoing);
4346 			/* 0 means passed so we can continue */
4347 			if (error != 0) {
4348 				break;
4349 			}
4350 		}
4351 		goto done;
4352 	}
4353 
4354 	/*
4355 	 * Locate the chunks of data that we can pass to the next filter
4356 	 * A data chunk must be on mbuf boundaries
4357 	 */
4358 	curlen = 0;
4359 	while ((data = cfil_queue_first(pending_q)) != NULL) {
4360 		datalen = cfil_data_length(data, NULL, NULL);
4361 
4362 		if (cfil_info->cfi_debug && cfil_log_data) {
4363 			CFIL_LOG(LOG_DEBUG,
4364 			    "CFIL: SERVICE PENDING-Q: data %llx datalen %u passlen %llu curlen %llu",
4365 			    (uint64_t)VM_KERNEL_ADDRPERM(data), datalen,
4366 			    passlen, curlen);
4367 		}
4368 
4369 		if (curlen + datalen > passlen) {
4370 			break;
4371 		}
4372 
4373 		cfil_queue_remove(pending_q, data, datalen);
4374 
4375 		curlen += datalen;
4376 
4377 		for (iter_entry = SLIST_NEXT(entry, cfe_order_link);
4378 		    iter_entry != NULL;
4379 		    iter_entry = SLIST_NEXT(iter_entry, cfe_order_link)) {
4380 			error = cfil_data_filter(so, cfil_info, CFI_ENTRY_KCUNIT(cfil_info, iter_entry), outgoing,
4381 			    data, datalen);
4382 			/* 0 means passed so we can continue */
4383 			if (error != 0) {
4384 				break;
4385 			}
4386 		}
4387 		/* When data has passed all filters, re-inject */
4388 		if (error == 0) {
4389 			if (outgoing) {
4390 				cfil_queue_enqueue(
4391 					&cfil_info->cfi_snd.cfi_inject_q,
4392 					data, datalen);
4393 				OSAddAtomic64(datalen,
4394 				    &cfil_stats.cfs_inject_q_out_enqueued);
4395 			} else {
4396 				cfil_queue_enqueue(
4397 					&cfil_info->cfi_rcv.cfi_inject_q,
4398 					data, datalen);
4399 				OSAddAtomic64(datalen,
4400 				    &cfil_stats.cfs_inject_q_in_enqueued);
4401 			}
4402 		}
4403 	}
4404 
4405 done:
4406 	CFIL_INFO_VERIFY(cfil_info);
4407 
4408 	return error;
4409 }
4410 
4411 int
cfil_update_data_offsets(struct socket * so,struct cfil_info * cfil_info,uint32_t kcunit,int outgoing,uint64_t pass_offset,uint64_t peek_offset)4412 cfil_update_data_offsets(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing,
4413     uint64_t pass_offset, uint64_t peek_offset)
4414 {
4415 	errno_t error = 0;
4416 	struct cfil_entry *entry = NULL;
4417 	struct cfe_buf *entrybuf;
4418 	int updated = 0;
4419 
4420 	CFIL_LOG(LOG_INFO, "pass %llu peek %llu", pass_offset, peek_offset);
4421 
4422 	socket_lock_assert_owned(so);
4423 
4424 	if (cfil_info == NULL) {
4425 		CFIL_LOG(LOG_ERR, "so %llx cfil detached",
4426 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
4427 		error = 0;
4428 		goto done;
4429 	} else if (cfil_info->cfi_flags & CFIF_DROP) {
4430 		CFIL_LOG(LOG_ERR, "so %llx drop set",
4431 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
4432 		error = EPIPE;
4433 		goto done;
4434 	}
4435 
4436 	entry = &cfil_info->cfi_entries[kcunit - 1];
4437 	if (outgoing) {
4438 		entrybuf = &entry->cfe_snd;
4439 	} else {
4440 		entrybuf = &entry->cfe_rcv;
4441 	}
4442 
4443 	/* Record updated offsets for this content filter */
4444 	if (pass_offset > entrybuf->cfe_pass_offset) {
4445 		entrybuf->cfe_pass_offset = pass_offset;
4446 
4447 		if (entrybuf->cfe_peek_offset < entrybuf->cfe_pass_offset) {
4448 			entrybuf->cfe_peek_offset = entrybuf->cfe_pass_offset;
4449 		}
4450 		updated = 1;
4451 	} else {
4452 		CFIL_LOG(LOG_INFO, "pass_offset %llu <= cfe_pass_offset %llu",
4453 		    pass_offset, entrybuf->cfe_pass_offset);
4454 	}
4455 	/* Filter does not want or need to see data that's allowed to pass */
4456 	if (peek_offset > entrybuf->cfe_pass_offset &&
4457 	    peek_offset > entrybuf->cfe_peek_offset) {
4458 		entrybuf->cfe_peek_offset = peek_offset;
4459 		updated = 1;
4460 	}
4461 	/* Nothing to do */
4462 	if (updated == 0) {
4463 		goto done;
4464 	}
4465 
4466 	/* Move data held in control queue to pending queue if needed */
4467 	error = cfil_data_service_ctl_q(so, cfil_info, kcunit, outgoing);
4468 	if (error != 0) {
4469 		CFIL_LOG(LOG_ERR, "cfil_data_service_ctl_q() error %d",
4470 		    error);
4471 		goto done;
4472 	}
4473 	error = EJUSTRETURN;
4474 
4475 done:
4476 	/*
4477 	 * The filter is effectively detached when pass all from both sides
4478 	 * or when the socket is closed and no more data is waiting
4479 	 * to be delivered to the filter
4480 	 */
4481 	if (entry != NULL &&
4482 	    ((entry->cfe_snd.cfe_pass_offset == CFM_MAX_OFFSET &&
4483 	    entry->cfe_rcv.cfe_pass_offset == CFM_MAX_OFFSET) ||
4484 	    ((cfil_info->cfi_flags & CFIF_CLOSE_WAIT) &&
4485 	    cfil_queue_empty(&entry->cfe_snd.cfe_ctl_q) &&
4486 	    cfil_queue_empty(&entry->cfe_rcv.cfe_ctl_q)))) {
4487 		entry->cfe_flags |= CFEF_CFIL_DETACHED;
4488 
4489 		if (cfil_info->cfi_debug) {
4490 			cfil_info_log(LOG_INFO, cfil_info, outgoing ?
4491 			    "CFIL: OUT - PASSED ALL - DETACH":
4492 			    "CFIL: IN - PASSED ALL - DETACH");
4493 		}
4494 
4495 		CFIL_LOG(LOG_INFO, "so %llx detached %u",
4496 		    (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit);
4497 		if ((cfil_info->cfi_flags & CFIF_CLOSE_WAIT) &&
4498 		    cfil_filters_attached(so) == 0) {
4499 			if (cfil_info->cfi_debug) {
4500 				cfil_info_log(LOG_INFO, cfil_info, "CFIL: WAKING");
4501 			}
4502 			CFIL_LOG(LOG_INFO, "so %llx waking",
4503 			    (uint64_t)VM_KERNEL_ADDRPERM(so));
4504 			wakeup((caddr_t)cfil_info);
4505 		}
4506 	}
4507 	CFIL_INFO_VERIFY(cfil_info);
4508 	CFIL_LOG(LOG_INFO, "return %d", error);
4509 	return error;
4510 }
4511 
4512 /*
4513  * Update pass offset for socket when no data is pending
4514  */
4515 static int
cfil_set_socket_pass_offset(struct socket * so,struct cfil_info * cfil_info,int outgoing)4516 cfil_set_socket_pass_offset(struct socket *so, struct cfil_info *cfil_info, int outgoing)
4517 {
4518 	struct cfi_buf *cfi_buf;
4519 	struct cfil_entry *entry;
4520 	struct cfe_buf *entrybuf;
4521 	uint32_t kcunit;
4522 	uint64_t pass_offset = 0;
4523 	boolean_t first = true;
4524 
4525 	if (cfil_info == NULL) {
4526 		return 0;
4527 	}
4528 
4529 	if (cfil_info->cfi_debug && cfil_log_data) {
4530 		CFIL_LOG(LOG_DEBUG, "so %llx outgoing %d",
4531 		    (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing);
4532 	}
4533 
4534 	socket_lock_assert_owned(so);
4535 
4536 	if (outgoing) {
4537 		cfi_buf = &cfil_info->cfi_snd;
4538 	} else {
4539 		cfi_buf = &cfil_info->cfi_rcv;
4540 	}
4541 
4542 	if (cfil_info->cfi_debug && cfil_log_data) {
4543 		CFIL_LOG(LOG_DEBUG, "CFIL: <so %llx, sockID %llu> outgoing %d cfi_pending_first %llu cfi_pending_last %llu",
4544 		    (uint64_t)VM_KERNEL_ADDRPERM(so), cfil_info->cfi_sock_id, outgoing,
4545 		    cfi_buf->cfi_pending_first, cfi_buf->cfi_pending_last);
4546 	}
4547 
4548 	if (cfi_buf->cfi_pending_last - cfi_buf->cfi_pending_first == 0) {
4549 		for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
4550 			entry = &cfil_info->cfi_entries[kcunit - 1];
4551 
4552 			/* Are we attached to a filter? */
4553 			if (entry->cfe_filter == NULL) {
4554 				continue;
4555 			}
4556 
4557 			if (outgoing) {
4558 				entrybuf = &entry->cfe_snd;
4559 			} else {
4560 				entrybuf = &entry->cfe_rcv;
4561 			}
4562 
4563 			// Keep track of the smallest pass_offset among filters.
4564 			if (first == true ||
4565 			    entrybuf->cfe_pass_offset < pass_offset) {
4566 				pass_offset = entrybuf->cfe_pass_offset;
4567 				first = false;
4568 			}
4569 		}
4570 		cfi_buf->cfi_pass_offset = pass_offset;
4571 	}
4572 
4573 	if (cfil_info->cfi_debug && cfil_log_data) {
4574 		CFIL_LOG(LOG_DEBUG, "CFIL: <so %llx, sockID %llu>, cfi_pass_offset %llu",
4575 		    (uint64_t)VM_KERNEL_ADDRPERM(so), cfil_info->cfi_sock_id, cfi_buf->cfi_pass_offset);
4576 	}
4577 
4578 	return 0;
4579 }
4580 
4581 int
cfil_action_data_pass(struct socket * so,struct cfil_info * cfil_info,uint32_t kcunit,int outgoing,uint64_t pass_offset,uint64_t peek_offset)4582 cfil_action_data_pass(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing,
4583     uint64_t pass_offset, uint64_t peek_offset)
4584 {
4585 	errno_t error = 0;
4586 
4587 	CFIL_LOG(LOG_INFO, "");
4588 
4589 	socket_lock_assert_owned(so);
4590 
4591 	error = cfil_acquire_sockbuf(so, cfil_info, outgoing);
4592 	if (error != 0) {
4593 		CFIL_LOG(LOG_INFO, "so %llx %s dropped",
4594 		    (uint64_t)VM_KERNEL_ADDRPERM(so),
4595 		    outgoing ? "out" : "in");
4596 		goto release;
4597 	}
4598 
4599 	error = cfil_update_data_offsets(so, cfil_info, kcunit, outgoing,
4600 	    pass_offset, peek_offset);
4601 
4602 	cfil_service_inject_queue(so, cfil_info, outgoing);
4603 
4604 	cfil_set_socket_pass_offset(so, cfil_info, outgoing);
4605 release:
4606 	CFIL_INFO_VERIFY(cfil_info);
4607 	cfil_release_sockbuf(so, outgoing);
4608 
4609 	return error;
4610 }
4611 
4612 
4613 static void
cfil_flush_queues(struct socket * so,struct cfil_info * cfil_info)4614 cfil_flush_queues(struct socket *so, struct cfil_info *cfil_info)
4615 {
4616 	struct cfil_entry *entry;
4617 	int kcunit;
4618 	uint64_t drained;
4619 
4620 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || cfil_info == NULL) {
4621 		goto done;
4622 	}
4623 
4624 	socket_lock_assert_owned(so);
4625 
4626 	/*
4627 	 * Flush the output queues and ignore errors as long as
4628 	 * we are attached
4629 	 */
4630 	(void) cfil_acquire_sockbuf(so, cfil_info, 1);
4631 	if (cfil_info != NULL) {
4632 		drained = 0;
4633 		for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
4634 			entry = &cfil_info->cfi_entries[kcunit - 1];
4635 
4636 			drained += cfil_queue_drain(&entry->cfe_snd.cfe_ctl_q);
4637 			drained += cfil_queue_drain(&entry->cfe_snd.cfe_pending_q);
4638 		}
4639 		drained += cfil_queue_drain(&cfil_info->cfi_snd.cfi_inject_q);
4640 
4641 		if (drained) {
4642 			if (cfil_info->cfi_flags & CFIF_DROP) {
4643 				OSIncrementAtomic(
4644 					&cfil_stats.cfs_flush_out_drop);
4645 			} else {
4646 				OSIncrementAtomic(
4647 					&cfil_stats.cfs_flush_out_close);
4648 			}
4649 		}
4650 	}
4651 	cfil_release_sockbuf(so, 1);
4652 
4653 	/*
4654 	 * Flush the input queues
4655 	 */
4656 	(void) cfil_acquire_sockbuf(so, cfil_info, 0);
4657 	if (cfil_info != NULL) {
4658 		drained = 0;
4659 		for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
4660 			entry = &cfil_info->cfi_entries[kcunit - 1];
4661 
4662 			drained += cfil_queue_drain(
4663 				&entry->cfe_rcv.cfe_ctl_q);
4664 			drained += cfil_queue_drain(
4665 				&entry->cfe_rcv.cfe_pending_q);
4666 		}
4667 		drained += cfil_queue_drain(&cfil_info->cfi_rcv.cfi_inject_q);
4668 
4669 		if (drained) {
4670 			if (cfil_info->cfi_flags & CFIF_DROP) {
4671 				OSIncrementAtomic(
4672 					&cfil_stats.cfs_flush_in_drop);
4673 			} else {
4674 				OSIncrementAtomic(
4675 					&cfil_stats.cfs_flush_in_close);
4676 			}
4677 		}
4678 	}
4679 	cfil_release_sockbuf(so, 0);
4680 done:
4681 	CFIL_INFO_VERIFY(cfil_info);
4682 }
4683 
4684 int
cfil_action_drop(struct socket * so,struct cfil_info * cfil_info,uint32_t kcunit)4685 cfil_action_drop(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit)
4686 {
4687 	errno_t error = 0;
4688 	struct cfil_entry *entry;
4689 	struct proc *p;
4690 
4691 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || cfil_info == NULL) {
4692 		goto done;
4693 	}
4694 
4695 	socket_lock_assert_owned(so);
4696 
4697 	entry = &cfil_info->cfi_entries[kcunit - 1];
4698 
4699 	/* Are we attached to the filter? */
4700 	if (entry->cfe_filter == NULL) {
4701 		goto done;
4702 	}
4703 
4704 	cfil_info->cfi_flags |= CFIF_DROP;
4705 
4706 	p = current_proc();
4707 
4708 	/*
4709 	 * Force the socket to be marked defunct
4710 	 * (forcing fixed along with rdar://19391339)
4711 	 */
4712 	if (so->so_flow_db == NULL) {
4713 		error = sosetdefunct(p, so,
4714 		    SHUTDOWN_SOCKET_LEVEL_CONTENT_FILTER | SHUTDOWN_SOCKET_LEVEL_DISCONNECT_ALL,
4715 		    FALSE);
4716 
4717 		/* Flush the socket buffer and disconnect */
4718 		if (error == 0) {
4719 			error = sodefunct(p, so,
4720 			    SHUTDOWN_SOCKET_LEVEL_CONTENT_FILTER | SHUTDOWN_SOCKET_LEVEL_DISCONNECT_ALL);
4721 		}
4722 	}
4723 
4724 	/* The filter is done, mark as detached */
4725 	entry->cfe_flags |= CFEF_CFIL_DETACHED;
4726 
4727 	if (cfil_info->cfi_debug) {
4728 		cfil_info_log(LOG_INFO, cfil_info, "CFIL: DROP - DETACH");
4729 	}
4730 
4731 	CFIL_LOG(LOG_INFO, "so %llx detached %u",
4732 	    (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit);
4733 
4734 	/* Pending data needs to go */
4735 	cfil_flush_queues(so, cfil_info);
4736 
4737 	if (cfil_info && (cfil_info->cfi_flags & CFIF_CLOSE_WAIT)) {
4738 		if (cfil_filters_attached(so) == 0) {
4739 			CFIL_LOG(LOG_INFO, "so %llx waking",
4740 			    (uint64_t)VM_KERNEL_ADDRPERM(so));
4741 			wakeup((caddr_t)cfil_info);
4742 		}
4743 	}
4744 done:
4745 	return error;
4746 }
4747 
4748 int
cfil_action_bless_client(uint32_t kcunit,struct cfil_msg_hdr * msghdr)4749 cfil_action_bless_client(uint32_t kcunit, struct cfil_msg_hdr *msghdr)
4750 {
4751 	errno_t error = 0;
4752 	struct cfil_info *cfil_info = NULL;
4753 
4754 	bool cfil_attached = false;
4755 	struct cfil_msg_bless_client *blessmsg = (struct cfil_msg_bless_client *)msghdr;
4756 
4757 	// Search and lock socket
4758 	struct socket *so = cfil_socket_from_client_uuid(blessmsg->cfb_client_uuid, &cfil_attached);
4759 	if (so == NULL) {
4760 		error = ENOENT;
4761 	} else {
4762 		// The client gets a pass automatically
4763 		cfil_info = (so->so_flow_db != NULL) ?
4764 		    soflow_db_get_feature_context(so->so_flow_db, msghdr->cfm_sock_id) : so->so_cfil;
4765 
4766 		if (cfil_attached) {
4767 			if (cfil_info != NULL && cfil_info->cfi_debug) {
4768 				cfil_info_log(LOG_INFO, cfil_info, "CFIL: VERDICT RECEIVED: BLESS");
4769 			}
4770 			cfil_sock_received_verdict(so);
4771 			(void)cfil_action_data_pass(so, cfil_info, kcunit, 1, CFM_MAX_OFFSET, CFM_MAX_OFFSET);
4772 			(void)cfil_action_data_pass(so, cfil_info, kcunit, 0, CFM_MAX_OFFSET, CFM_MAX_OFFSET);
4773 		} else {
4774 			so->so_flags1 |= SOF1_CONTENT_FILTER_SKIP;
4775 		}
4776 		socket_unlock(so, 1);
4777 	}
4778 
4779 	return error;
4780 }
4781 
4782 int
cfil_action_set_crypto_key(uint32_t kcunit,struct cfil_msg_hdr * msghdr)4783 cfil_action_set_crypto_key(uint32_t kcunit, struct cfil_msg_hdr *msghdr)
4784 {
4785 	struct content_filter *cfc = NULL;
4786 	cfil_crypto_state_t crypto_state = NULL;
4787 	struct cfil_msg_set_crypto_key *keymsg = (struct cfil_msg_set_crypto_key *)msghdr;
4788 
4789 	CFIL_LOG(LOG_NOTICE, "");
4790 
4791 	if (kcunit > MAX_CONTENT_FILTER) {
4792 		CFIL_LOG(LOG_ERR, "kcunit %u > MAX_CONTENT_FILTER (%d)",
4793 		    kcunit, MAX_CONTENT_FILTER);
4794 		return EINVAL;
4795 	}
4796 	crypto_state = cfil_crypto_init_client((uint8_t *)keymsg->crypto_key);
4797 	if (crypto_state == NULL) {
4798 		CFIL_LOG(LOG_ERR, "failed to initialize crypto state for unit %u)",
4799 		    kcunit);
4800 		return EINVAL;
4801 	}
4802 
4803 	cfil_rw_lock_exclusive(&cfil_lck_rw);
4804 
4805 	cfc = content_filters[kcunit - 1];
4806 	if (cfc->cf_kcunit != kcunit) {
4807 		CFIL_LOG(LOG_ERR, "bad unit info %u)",
4808 		    kcunit);
4809 		cfil_rw_unlock_exclusive(&cfil_lck_rw);
4810 		cfil_crypto_cleanup_state(crypto_state);
4811 		return EINVAL;
4812 	}
4813 	if (cfc->cf_crypto_state != NULL) {
4814 		cfil_crypto_cleanup_state(cfc->cf_crypto_state);
4815 		cfc->cf_crypto_state = NULL;
4816 	}
4817 	cfc->cf_crypto_state = crypto_state;
4818 
4819 	cfil_rw_unlock_exclusive(&cfil_lck_rw);
4820 	return 0;
4821 }
4822 
4823 static int
cfil_update_entry_offsets(struct socket * so,struct cfil_info * cfil_info,int outgoing,unsigned int datalen)4824 cfil_update_entry_offsets(struct socket *so, struct cfil_info *cfil_info, int outgoing, unsigned int datalen)
4825 {
4826 	struct cfil_entry *entry;
4827 	struct cfe_buf *entrybuf;
4828 	uint32_t kcunit;
4829 
4830 	CFIL_LOG(LOG_INFO, "so %llx outgoing %d datalen %u",
4831 	    (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing, datalen);
4832 
4833 	for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
4834 		entry = &cfil_info->cfi_entries[kcunit - 1];
4835 
4836 		/* Are we attached to the filter? */
4837 		if (entry->cfe_filter == NULL) {
4838 			continue;
4839 		}
4840 
4841 		if (outgoing) {
4842 			entrybuf = &entry->cfe_snd;
4843 		} else {
4844 			entrybuf = &entry->cfe_rcv;
4845 		}
4846 
4847 		entrybuf->cfe_ctl_q.q_start += datalen;
4848 		if (entrybuf->cfe_pass_offset < entrybuf->cfe_ctl_q.q_start) {
4849 			entrybuf->cfe_pass_offset = entrybuf->cfe_ctl_q.q_start;
4850 		}
4851 		entrybuf->cfe_peeked = entrybuf->cfe_ctl_q.q_start;
4852 		if (entrybuf->cfe_peek_offset < entrybuf->cfe_pass_offset) {
4853 			entrybuf->cfe_peek_offset = entrybuf->cfe_pass_offset;
4854 		}
4855 
4856 		entrybuf->cfe_ctl_q.q_end += datalen;
4857 
4858 		entrybuf->cfe_pending_q.q_start += datalen;
4859 		entrybuf->cfe_pending_q.q_end += datalen;
4860 	}
4861 	CFIL_INFO_VERIFY(cfil_info);
4862 	return 0;
4863 }
4864 
4865 int
cfil_data_common(struct socket * so,struct cfil_info * cfil_info,int outgoing,struct sockaddr * to,struct mbuf * data,struct mbuf * control,uint32_t flags)4866 cfil_data_common(struct socket *so, struct cfil_info *cfil_info, int outgoing, struct sockaddr *to,
4867     struct mbuf *data, struct mbuf *control, uint32_t flags)
4868 {
4869 #pragma unused(to, control, flags)
4870 	errno_t error = 0;
4871 	unsigned int datalen;
4872 	int mbcnt = 0;
4873 	int mbnum = 0;
4874 	int kcunit;
4875 	struct cfi_buf *cfi_buf;
4876 	struct mbuf *chain = NULL;
4877 
4878 	if (cfil_info == NULL) {
4879 		CFIL_LOG(LOG_ERR, "so %llx cfil detached",
4880 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
4881 		error = 0;
4882 		goto done;
4883 	} else if (cfil_info->cfi_flags & CFIF_DROP) {
4884 		CFIL_LOG(LOG_ERR, "so %llx drop set",
4885 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
4886 		error = EPIPE;
4887 		goto done;
4888 	}
4889 
4890 	datalen = cfil_data_length(data, &mbcnt, &mbnum);
4891 
4892 	if (datalen == 0) {
4893 		error = 0;
4894 		goto done;
4895 	}
4896 
4897 	if (outgoing) {
4898 		cfi_buf = &cfil_info->cfi_snd;
4899 		cfil_info->cfi_byte_outbound_count += datalen;
4900 	} else {
4901 		cfi_buf = &cfil_info->cfi_rcv;
4902 		cfil_info->cfi_byte_inbound_count += datalen;
4903 	}
4904 
4905 	cfi_buf->cfi_pending_last += datalen;
4906 	cfi_buf->cfi_pending_mbcnt += mbcnt;
4907 	cfi_buf->cfi_pending_mbnum += mbnum;
4908 
4909 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
4910 		if (cfi_buf->cfi_pending_mbnum > cfil_udp_gc_mbuf_num_max ||
4911 		    cfi_buf->cfi_pending_mbcnt > cfil_udp_gc_mbuf_cnt_max) {
4912 			cfi_buf->cfi_tail_drop_cnt++;
4913 			cfi_buf->cfi_pending_mbcnt -= mbcnt;
4914 			cfi_buf->cfi_pending_mbnum -= mbnum;
4915 			return EPIPE;
4916 		}
4917 	}
4918 
4919 	cfil_info_buf_verify(cfi_buf);
4920 
4921 	if (cfil_info->cfi_debug && cfil_log_data) {
4922 		CFIL_LOG(LOG_DEBUG, "CFIL: QUEUEING DATA: <so %llx> %s: data %llx len %u flags 0x%x nextpkt %llx - cfi_pending_last %llu cfi_pending_mbcnt %u   cfi_pass_offset %llu",
4923 		    (uint64_t)VM_KERNEL_ADDRPERM(so),
4924 		    outgoing ? "OUT" : "IN",
4925 		    (uint64_t)VM_KERNEL_ADDRPERM(data), datalen, data->m_flags,
4926 		    (uint64_t)VM_KERNEL_ADDRPERM(data->m_nextpkt),
4927 		    cfi_buf->cfi_pending_last,
4928 		    cfi_buf->cfi_pending_mbcnt,
4929 		    cfi_buf->cfi_pass_offset);
4930 	}
4931 
4932 	/* Fast path when below pass offset */
4933 	if (cfi_buf->cfi_pending_last <= cfi_buf->cfi_pass_offset) {
4934 		cfil_update_entry_offsets(so, cfil_info, outgoing, datalen);
4935 		if (cfil_info->cfi_debug && cfil_log_data) {
4936 			CFIL_LOG(LOG_DEBUG, "CFIL: QUEUEING DATA: FAST PATH");
4937 		}
4938 	} else {
4939 		struct cfil_entry *iter_entry;
4940 		SLIST_FOREACH(iter_entry, &cfil_info->cfi_ordered_entries, cfe_order_link) {
4941 			// Is cfil attached to this filter?
4942 			kcunit = CFI_ENTRY_KCUNIT(cfil_info, iter_entry);
4943 			if (IS_ENTRY_ATTACHED(cfil_info, kcunit)) {
4944 				if (NEED_DGRAM_FLOW_TRACKING(so) && chain == NULL) {
4945 					/* Datagrams only:
4946 					 * Chain addr (incoming only TDB), control (optional) and data into one chain.
4947 					 * This full chain will be reinjected into socket after recieving verdict.
4948 					 */
4949 					(void) cfil_dgram_save_socket_state(cfil_info, data);
4950 					chain = sbconcat_mbufs(NULL, outgoing ? NULL : to, data, control);
4951 					if (chain == NULL) {
4952 						return ENOBUFS;
4953 					}
4954 					data = chain;
4955 				}
4956 				error = cfil_data_filter(so, cfil_info, kcunit, outgoing, data,
4957 				    datalen);
4958 			}
4959 			/* 0 means passed so continue with next filter */
4960 			if (error != 0) {
4961 				break;
4962 			}
4963 		}
4964 	}
4965 
4966 	/* Move cursor if no filter claimed the data */
4967 	if (error == 0) {
4968 		cfi_buf->cfi_pending_first += datalen;
4969 		cfi_buf->cfi_pending_mbcnt -= mbcnt;
4970 		cfi_buf->cfi_pending_mbnum -= mbnum;
4971 		cfil_info_buf_verify(cfi_buf);
4972 	}
4973 done:
4974 	CFIL_INFO_VERIFY(cfil_info);
4975 
4976 	return error;
4977 }
4978 
4979 /*
4980  * Callback from socket layer sosendxxx()
4981  */
4982 int
cfil_sock_data_out(struct socket * so,struct sockaddr * to,struct mbuf * data,struct mbuf * control,uint32_t flags,struct soflow_hash_entry * flow_entry)4983 cfil_sock_data_out(struct socket *so, struct sockaddr  *to,
4984     struct mbuf *data, struct mbuf *control, uint32_t flags, struct soflow_hash_entry *flow_entry)
4985 {
4986 	int error = 0;
4987 	int new_filter_control_unit = 0;
4988 
4989 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
4990 		return cfil_sock_udp_handle_data(TRUE, so, NULL, to, data, control, flags, flow_entry);
4991 	}
4992 
4993 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) {
4994 		/* Drop pre-existing TCP sockets if filter is enabled now */
4995 		if (!DO_PRESERVE_CONNECTIONS && cfil_active_count > 0 && !SKIP_FILTER_FOR_TCP_SOCKET(so)) {
4996 			new_filter_control_unit = necp_socket_get_content_filter_control_unit(so);
4997 			if (new_filter_control_unit > 0) {
4998 				CFIL_LOG(LOG_NOTICE, "CFIL: TCP(OUT) <so %llx> - filter state changed - dropped pre-existing flow", (uint64_t)VM_KERNEL_ADDRPERM(so));
4999 				return EPIPE;
5000 			}
5001 		}
5002 		return 0;
5003 	}
5004 
5005 	/* Drop pre-existing TCP sockets when filter state changed */
5006 	new_filter_control_unit = necp_socket_get_content_filter_control_unit(so);
5007 	if (new_filter_control_unit > 0 && new_filter_control_unit != so->so_cfil->cfi_filter_control_unit && !SKIP_FILTER_FOR_TCP_SOCKET(so)) {
5008 		if (DO_PRESERVE_CONNECTIONS) {
5009 			so->so_cfil->cfi_filter_control_unit = new_filter_control_unit;
5010 		} else {
5011 			CFIL_LOG(LOG_NOTICE, "CFIL: TCP(OUT) <so %llx> - filter state changed - dropped pre-existing flow (old state 0x%x new state 0x%x)",
5012 			    (uint64_t)VM_KERNEL_ADDRPERM(so),
5013 			    so->so_cfil->cfi_filter_control_unit, new_filter_control_unit);
5014 			return EPIPE;
5015 		}
5016 	}
5017 
5018 	/*
5019 	 * Pass initial data for TFO.
5020 	 */
5021 	if (IS_INITIAL_TFO_DATA(so)) {
5022 		return 0;
5023 	}
5024 
5025 	socket_lock_assert_owned(so);
5026 
5027 	if (so->so_cfil->cfi_flags & CFIF_DROP) {
5028 		CFIL_LOG(LOG_ERR, "so %llx drop set",
5029 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
5030 		return EPIPE;
5031 	}
5032 	if (control != NULL) {
5033 		CFIL_LOG(LOG_ERR, "so %llx control",
5034 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
5035 		OSIncrementAtomic(&cfil_stats.cfs_data_out_control);
5036 	}
5037 	if ((flags & MSG_OOB)) {
5038 		CFIL_LOG(LOG_ERR, "so %llx MSG_OOB",
5039 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
5040 		OSIncrementAtomic(&cfil_stats.cfs_data_out_oob);
5041 	}
5042 	/*
5043 	 * Abort if socket is defunct.
5044 	 */
5045 	if (so->so_flags & SOF_DEFUNCT) {
5046 		return EPIPE;
5047 	}
5048 	if ((so->so_snd.sb_flags & SB_LOCK) == 0) {
5049 		panic("so %p SB_LOCK not set", so);
5050 	}
5051 
5052 	if (so->so_snd.sb_cfil_thread != NULL) {
5053 		panic("%s sb_cfil_thread %p not NULL", __func__,
5054 		    so->so_snd.sb_cfil_thread);
5055 	}
5056 
5057 	error = cfil_data_common(so, so->so_cfil, 1, to, data, control, flags);
5058 
5059 	return error;
5060 }
5061 
5062 /*
5063  * Callback from socket layer sbappendxxx()
5064  */
5065 int
cfil_sock_data_in(struct socket * so,struct sockaddr * from,struct mbuf * data,struct mbuf * control,uint32_t flags,struct soflow_hash_entry * flow_entry)5066 cfil_sock_data_in(struct socket *so, struct sockaddr *from,
5067     struct mbuf *data, struct mbuf *control, uint32_t flags, struct soflow_hash_entry *flow_entry)
5068 {
5069 	int error = 0;
5070 	int new_filter_control_unit = 0;
5071 
5072 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
5073 		return cfil_sock_udp_handle_data(FALSE, so, NULL, from, data, control, flags, flow_entry);
5074 	}
5075 
5076 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) {
5077 		/* Drop pre-existing TCP sockets if filter is enabled now */
5078 		if (!DO_PRESERVE_CONNECTIONS && cfil_active_count > 0 && !SKIP_FILTER_FOR_TCP_SOCKET(so)) {
5079 			new_filter_control_unit = necp_socket_get_content_filter_control_unit(so);
5080 			if (new_filter_control_unit > 0) {
5081 				CFIL_LOG(LOG_NOTICE, "CFIL: TCP(IN) <so %llx> - filter state changed - dropped pre-existing flow", (uint64_t)VM_KERNEL_ADDRPERM(so));
5082 				return EPIPE;
5083 			}
5084 		}
5085 		return 0;
5086 	}
5087 
5088 	/* Drop pre-existing TCP sockets when filter state changed */
5089 	new_filter_control_unit = necp_socket_get_content_filter_control_unit(so);
5090 	if (new_filter_control_unit > 0 && new_filter_control_unit != so->so_cfil->cfi_filter_control_unit && !SKIP_FILTER_FOR_TCP_SOCKET(so)) {
5091 		if (DO_PRESERVE_CONNECTIONS) {
5092 			so->so_cfil->cfi_filter_control_unit = new_filter_control_unit;
5093 		} else {
5094 			CFIL_LOG(LOG_NOTICE, "CFIL: TCP(IN) <so %llx> - filter state changed - dropped pre-existing flow (old state 0x%x new state 0x%x)",
5095 			    (uint64_t)VM_KERNEL_ADDRPERM(so),
5096 			    so->so_cfil->cfi_filter_control_unit, new_filter_control_unit);
5097 			return EPIPE;
5098 		}
5099 	}
5100 
5101 	/*
5102 	 * Pass initial data for TFO.
5103 	 */
5104 	if (IS_INITIAL_TFO_DATA(so)) {
5105 		return 0;
5106 	}
5107 
5108 	socket_lock_assert_owned(so);
5109 
5110 	if (so->so_cfil->cfi_flags & CFIF_DROP) {
5111 		CFIL_LOG(LOG_ERR, "so %llx drop set",
5112 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
5113 		return EPIPE;
5114 	}
5115 	if (control != NULL) {
5116 		CFIL_LOG(LOG_ERR, "so %llx control",
5117 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
5118 		OSIncrementAtomic(&cfil_stats.cfs_data_in_control);
5119 	}
5120 	if (data->m_type == MT_OOBDATA) {
5121 		CFIL_LOG(LOG_ERR, "so %llx MSG_OOB",
5122 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
5123 		OSIncrementAtomic(&cfil_stats.cfs_data_in_oob);
5124 	}
5125 	error = cfil_data_common(so, so->so_cfil, 0, from, data, control, flags);
5126 
5127 	return error;
5128 }
5129 
5130 /*
5131  * Callback from socket layer soshutdownxxx()
5132  *
5133  * We may delay the shutdown write if there's outgoing data in process.
5134  *
5135  * There is no point in delaying the shutdown read because the process
5136  * indicated that it does not want to read anymore data.
5137  */
5138 int
cfil_sock_shutdown(struct socket * so,int * how)5139 cfil_sock_shutdown(struct socket *so, int *how)
5140 {
5141 	int error = 0;
5142 
5143 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
5144 		return cfil_sock_udp_shutdown(so, how);
5145 	}
5146 
5147 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) {
5148 		goto done;
5149 	}
5150 
5151 	socket_lock_assert_owned(so);
5152 
5153 	CFIL_LOG(LOG_INFO, "so %llx how %d",
5154 	    (uint64_t)VM_KERNEL_ADDRPERM(so), *how);
5155 
5156 	/*
5157 	 * Check the state of the socket before the content filter
5158 	 */
5159 	if (*how != SHUT_WR && (so->so_state & SS_CANTRCVMORE) != 0) {
5160 		/* read already shut down */
5161 		error = ENOTCONN;
5162 		goto done;
5163 	}
5164 	if (*how != SHUT_RD && (so->so_state & SS_CANTSENDMORE) != 0) {
5165 		/* write already shut down */
5166 		error = ENOTCONN;
5167 		goto done;
5168 	}
5169 
5170 	if ((so->so_cfil->cfi_flags & CFIF_DROP) != 0) {
5171 		CFIL_LOG(LOG_ERR, "so %llx drop set",
5172 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
5173 		goto done;
5174 	}
5175 
5176 	/*
5177 	 * shutdown read: SHUT_RD or SHUT_RDWR
5178 	 */
5179 	if (*how != SHUT_WR) {
5180 		if (so->so_cfil->cfi_flags & CFIF_SHUT_RD) {
5181 			error = ENOTCONN;
5182 			goto done;
5183 		}
5184 		so->so_cfil->cfi_flags |= CFIF_SHUT_RD;
5185 		cfil_sock_notify_shutdown(so, SHUT_RD);
5186 	}
5187 	/*
5188 	 * shutdown write: SHUT_WR or SHUT_RDWR
5189 	 */
5190 	if (*how != SHUT_RD) {
5191 		if (so->so_cfil->cfi_flags & CFIF_SHUT_WR) {
5192 			error = ENOTCONN;
5193 			goto done;
5194 		}
5195 		so->so_cfil->cfi_flags |= CFIF_SHUT_WR;
5196 		cfil_sock_notify_shutdown(so, SHUT_WR);
5197 		/*
5198 		 * When outgoing data is pending, we delay the shutdown at the
5199 		 * protocol level until the content filters give the final
5200 		 * verdict on the pending data.
5201 		 */
5202 		if (cfil_sock_data_pending(&so->so_snd) != 0) {
5203 			/*
5204 			 * When shutting down the read and write sides at once
5205 			 * we can proceed to the final shutdown of the read
5206 			 * side. Otherwise, we just return.
5207 			 */
5208 			if (*how == SHUT_WR) {
5209 				error = EJUSTRETURN;
5210 			} else if (*how == SHUT_RDWR) {
5211 				*how = SHUT_RD;
5212 			}
5213 		}
5214 	}
5215 done:
5216 	return error;
5217 }
5218 
5219 /*
5220  * This is called when the socket is closed and there is no more
5221  * opportunity for filtering
5222  */
5223 void
cfil_sock_is_closed(struct socket * so)5224 cfil_sock_is_closed(struct socket *so)
5225 {
5226 	errno_t error = 0;
5227 	int kcunit;
5228 
5229 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
5230 		cfil_sock_udp_is_closed(so);
5231 		return;
5232 	}
5233 
5234 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) {
5235 		return;
5236 	}
5237 
5238 	CFIL_LOG(LOG_INFO, "so %llx", (uint64_t)VM_KERNEL_ADDRPERM(so));
5239 
5240 	socket_lock_assert_owned(so);
5241 
5242 	for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
5243 		/* Let the filters know of the closing */
5244 		error = cfil_dispatch_closed_event(so, so->so_cfil, kcunit);
5245 	}
5246 
5247 	/* Last chance to push passed data out */
5248 	error = cfil_acquire_sockbuf(so, so->so_cfil, 1);
5249 	if (error == 0) {
5250 		cfil_service_inject_queue(so, so->so_cfil, 1);
5251 	}
5252 	cfil_release_sockbuf(so, 1);
5253 
5254 	if (so->so_cfil != NULL) {
5255 		so->so_cfil->cfi_flags |= CFIF_SOCK_CLOSED;
5256 	}
5257 
5258 	/* Pending data needs to go */
5259 	cfil_flush_queues(so, so->so_cfil);
5260 
5261 	CFIL_INFO_VERIFY(so->so_cfil);
5262 }
5263 
5264 /*
5265  * This is called when the socket is disconnected so let the filters
5266  * know about the disconnection and that no more data will come
5267  *
5268  * The how parameter has the same values as soshutown()
5269  */
5270 void
cfil_sock_notify_shutdown(struct socket * so,int how)5271 cfil_sock_notify_shutdown(struct socket *so, int how)
5272 {
5273 	errno_t error = 0;
5274 	int kcunit;
5275 
5276 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
5277 		cfil_sock_udp_notify_shutdown(so, how, 0, 0);
5278 		return;
5279 	}
5280 
5281 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) {
5282 		return;
5283 	}
5284 
5285 	CFIL_LOG(LOG_INFO, "so %llx how %d",
5286 	    (uint64_t)VM_KERNEL_ADDRPERM(so), how);
5287 
5288 	socket_lock_assert_owned(so);
5289 
5290 	for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
5291 		/* Disconnect incoming side */
5292 		if (how != SHUT_WR) {
5293 			error = cfil_dispatch_disconnect_event(so, so->so_cfil, kcunit, 0);
5294 		}
5295 		/* Disconnect outgoing side */
5296 		if (how != SHUT_RD) {
5297 			error = cfil_dispatch_disconnect_event(so, so->so_cfil, kcunit, 1);
5298 		}
5299 	}
5300 }
5301 
5302 static int
cfil_filters_attached(struct socket * so)5303 cfil_filters_attached(struct socket *so)
5304 {
5305 	struct cfil_entry *entry;
5306 	uint32_t kcunit;
5307 	int attached = 0;
5308 
5309 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
5310 		return cfil_filters_udp_attached(so, FALSE);
5311 	}
5312 
5313 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) {
5314 		return 0;
5315 	}
5316 
5317 	socket_lock_assert_owned(so);
5318 
5319 	for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
5320 		entry = &so->so_cfil->cfi_entries[kcunit - 1];
5321 
5322 		/* Are we attached to the filter? */
5323 		if (entry->cfe_filter == NULL) {
5324 			continue;
5325 		}
5326 		if ((entry->cfe_flags & CFEF_SENT_SOCK_ATTACHED) == 0) {
5327 			continue;
5328 		}
5329 		if ((entry->cfe_flags & CFEF_CFIL_DETACHED) != 0) {
5330 			continue;
5331 		}
5332 		attached = 1;
5333 		break;
5334 	}
5335 
5336 	return attached;
5337 }
5338 
5339 /*
5340  * This is called when the socket is closed and we are waiting for
5341  * the filters to gives the final pass or drop
5342  */
5343 void
cfil_sock_close_wait(struct socket * so)5344 cfil_sock_close_wait(struct socket *so)
5345 {
5346 	lck_mtx_t *mutex_held;
5347 	struct timespec ts;
5348 	int error;
5349 
5350 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
5351 		cfil_sock_udp_close_wait(so);
5352 		return;
5353 	}
5354 
5355 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) {
5356 		return;
5357 	}
5358 
5359 	// This flow does not need to wait for close ack from user-space
5360 	if (IS_NO_CLOSE_WAIT(so->so_cfil)) {
5361 		if (so->so_cfil->cfi_debug) {
5362 			cfil_info_log(LOG_INFO, so->so_cfil, "CFIL: SKIP CLOSE WAIT");
5363 		}
5364 		return;
5365 	}
5366 
5367 	CFIL_LOG(LOG_INFO, "so %llx", (uint64_t)VM_KERNEL_ADDRPERM(so));
5368 
5369 	if (so->so_proto->pr_getlock != NULL) {
5370 		mutex_held = (*so->so_proto->pr_getlock)(so, PR_F_WILLUNLOCK);
5371 	} else {
5372 		mutex_held = so->so_proto->pr_domain->dom_mtx;
5373 	}
5374 	LCK_MTX_ASSERT(mutex_held, LCK_MTX_ASSERT_OWNED);
5375 
5376 	while (cfil_filters_attached(so)) {
5377 		/*
5378 		 * Notify the filters we are going away so they can detach
5379 		 */
5380 		cfil_sock_notify_shutdown(so, SHUT_RDWR);
5381 
5382 		/*
5383 		 * Make sure we need to wait after the filter are notified
5384 		 * of the disconnection
5385 		 */
5386 		if (cfil_filters_attached(so) == 0) {
5387 			break;
5388 		}
5389 
5390 		CFIL_LOG(LOG_INFO, "so %llx waiting",
5391 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
5392 
5393 		ts.tv_sec = cfil_close_wait_timeout / 1000;
5394 		ts.tv_nsec = (cfil_close_wait_timeout % 1000) *
5395 		    NSEC_PER_USEC * 1000;
5396 
5397 		OSIncrementAtomic(&cfil_stats.cfs_close_wait);
5398 		so->so_cfil->cfi_flags |= CFIF_CLOSE_WAIT;
5399 		error = msleep((caddr_t)so->so_cfil, mutex_held,
5400 		    PSOCK | PCATCH, "cfil_sock_close_wait", &ts);
5401 
5402 		// Woke up from sleep, validate if cfil_info is still valid
5403 		if (so->so_cfil == NULL) {
5404 			// cfil_info is not valid, do not continue
5405 			return;
5406 		}
5407 
5408 		so->so_cfil->cfi_flags &= ~CFIF_CLOSE_WAIT;
5409 
5410 		CFIL_LOG(LOG_NOTICE, "so %llx timed out %d",
5411 		    (uint64_t)VM_KERNEL_ADDRPERM(so), (error != 0));
5412 
5413 		/*
5414 		 * Force close in case of timeout
5415 		 */
5416 		if (error != 0) {
5417 			OSIncrementAtomic(&cfil_stats.cfs_close_wait_timeout);
5418 			break;
5419 		}
5420 	}
5421 }
5422 
5423 /*
5424  * Returns the size of the data held by the content filter by using
5425  */
5426 int32_t
cfil_sock_data_pending(struct sockbuf * sb)5427 cfil_sock_data_pending(struct sockbuf *sb)
5428 {
5429 	struct socket *so = sb->sb_so;
5430 	uint64_t pending = 0;
5431 
5432 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
5433 		return cfil_sock_udp_data_pending(sb, FALSE);
5434 	}
5435 
5436 	if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_cfil != NULL) {
5437 		struct cfi_buf *cfi_buf;
5438 
5439 		socket_lock_assert_owned(so);
5440 
5441 		if ((sb->sb_flags & SB_RECV) == 0) {
5442 			cfi_buf = &so->so_cfil->cfi_snd;
5443 		} else {
5444 			cfi_buf = &so->so_cfil->cfi_rcv;
5445 		}
5446 
5447 		pending = cfi_buf->cfi_pending_last -
5448 		    cfi_buf->cfi_pending_first;
5449 
5450 		/*
5451 		 * If we are limited by the "chars of mbufs used" roughly
5452 		 * adjust so we won't overcommit
5453 		 */
5454 		if (pending > (uint64_t)cfi_buf->cfi_pending_mbcnt) {
5455 			pending = cfi_buf->cfi_pending_mbcnt;
5456 		}
5457 	}
5458 
5459 	VERIFY(pending < INT32_MAX);
5460 
5461 	return (int32_t)(pending);
5462 }
5463 
5464 /*
5465  * Return the socket buffer space used by data being held by content filters
5466  * so processes won't clog the socket buffer
5467  */
5468 int32_t
cfil_sock_data_space(struct sockbuf * sb)5469 cfil_sock_data_space(struct sockbuf *sb)
5470 {
5471 	struct socket *so = sb->sb_so;
5472 	uint64_t pending = 0;
5473 
5474 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
5475 		return cfil_sock_udp_data_pending(sb, TRUE);
5476 	}
5477 
5478 	if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_cfil != NULL &&
5479 	    so->so_snd.sb_cfil_thread != current_thread()) {
5480 		struct cfi_buf *cfi_buf;
5481 
5482 		socket_lock_assert_owned(so);
5483 
5484 		if ((sb->sb_flags & SB_RECV) == 0) {
5485 			cfi_buf = &so->so_cfil->cfi_snd;
5486 		} else {
5487 			cfi_buf = &so->so_cfil->cfi_rcv;
5488 		}
5489 
5490 		pending = cfi_buf->cfi_pending_last -
5491 		    cfi_buf->cfi_pending_first;
5492 
5493 		/*
5494 		 * If we are limited by the "chars of mbufs used" roughly
5495 		 * adjust so we won't overcommit
5496 		 */
5497 		if ((uint64_t)cfi_buf->cfi_pending_mbcnt > pending) {
5498 			pending = cfi_buf->cfi_pending_mbcnt;
5499 		}
5500 	}
5501 
5502 	VERIFY(pending < INT32_MAX);
5503 
5504 	return (int32_t)(pending);
5505 }
5506 
5507 /*
5508  * A callback from the socket and protocol layer when data becomes
5509  * available in the socket buffer to give a chance for the content filter
5510  * to re-inject data that was held back
5511  */
5512 void
cfil_sock_buf_update(struct sockbuf * sb)5513 cfil_sock_buf_update(struct sockbuf *sb)
5514 {
5515 	int outgoing;
5516 	int error;
5517 	struct socket *so = sb->sb_so;
5518 
5519 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
5520 		cfil_sock_udp_buf_update(sb);
5521 		return;
5522 	}
5523 
5524 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) {
5525 		return;
5526 	}
5527 
5528 	if (!cfil_sbtrim) {
5529 		return;
5530 	}
5531 
5532 	socket_lock_assert_owned(so);
5533 
5534 	if ((sb->sb_flags & SB_RECV) == 0) {
5535 		if ((so->so_cfil->cfi_flags & CFIF_RETRY_INJECT_OUT) == 0) {
5536 			return;
5537 		}
5538 		outgoing = 1;
5539 		OSIncrementAtomic(&cfil_stats.cfs_inject_q_out_retry);
5540 	} else {
5541 		if ((so->so_cfil->cfi_flags & CFIF_RETRY_INJECT_IN) == 0) {
5542 			return;
5543 		}
5544 		outgoing = 0;
5545 		OSIncrementAtomic(&cfil_stats.cfs_inject_q_in_retry);
5546 	}
5547 
5548 	CFIL_LOG(LOG_NOTICE, "so %llx outgoing %d",
5549 	    (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing);
5550 
5551 	error = cfil_acquire_sockbuf(so, so->so_cfil, outgoing);
5552 	if (error == 0) {
5553 		cfil_service_inject_queue(so, so->so_cfil, outgoing);
5554 	}
5555 	cfil_release_sockbuf(so, outgoing);
5556 }
5557 
5558 int
sysctl_cfil_filter_list(struct sysctl_oid * oidp,void * arg1,int arg2,struct sysctl_req * req)5559 sysctl_cfil_filter_list(struct sysctl_oid *oidp, void *arg1, int arg2,
5560     struct sysctl_req *req)
5561 {
5562 #pragma unused(oidp, arg1, arg2)
5563 	int error = 0;
5564 	size_t len = 0;
5565 	u_int32_t i;
5566 
5567 	/* Read only  */
5568 	if (req->newptr != USER_ADDR_NULL) {
5569 		return EPERM;
5570 	}
5571 
5572 	cfil_rw_lock_shared(&cfil_lck_rw);
5573 
5574 	for (i = 0; i < MAX_CONTENT_FILTER; i++) {
5575 		struct cfil_filter_stat filter_stat;
5576 		struct content_filter *cfc = content_filters[i];
5577 
5578 		if (cfc == NULL) {
5579 			continue;
5580 		}
5581 
5582 		/* If just asking for the size */
5583 		if (req->oldptr == USER_ADDR_NULL) {
5584 			len += sizeof(struct cfil_filter_stat);
5585 			continue;
5586 		}
5587 
5588 		bzero(&filter_stat, sizeof(struct cfil_filter_stat));
5589 		filter_stat.cfs_len = sizeof(struct cfil_filter_stat);
5590 		filter_stat.cfs_filter_id = cfc->cf_kcunit;
5591 		filter_stat.cfs_flags = cfc->cf_flags;
5592 		filter_stat.cfs_sock_count = cfc->cf_sock_count;
5593 		filter_stat.cfs_necp_control_unit = cfc->cf_necp_control_unit;
5594 
5595 		error = SYSCTL_OUT(req, &filter_stat,
5596 		    sizeof(struct cfil_filter_stat));
5597 		if (error != 0) {
5598 			break;
5599 		}
5600 	}
5601 	/* If just asking for the size */
5602 	if (req->oldptr == USER_ADDR_NULL) {
5603 		req->oldidx = len;
5604 	}
5605 
5606 	cfil_rw_unlock_shared(&cfil_lck_rw);
5607 
5608 	if (cfil_log_level >= LOG_DEBUG) {
5609 		if (req->oldptr != USER_ADDR_NULL) {
5610 			for (i = 1; i <= MAX_CONTENT_FILTER; i++) {
5611 				cfil_filter_show(i);
5612 			}
5613 		}
5614 	}
5615 
5616 	return error;
5617 }
5618 
5619 static int
sysctl_cfil_sock_list(struct sysctl_oid * oidp,void * arg1,int arg2,struct sysctl_req * req)5620 sysctl_cfil_sock_list(struct sysctl_oid *oidp, void *arg1, int arg2,
5621     struct sysctl_req *req)
5622 {
5623 #pragma unused(oidp, arg1, arg2)
5624 	int error = 0;
5625 	u_int32_t i;
5626 	struct cfil_info *cfi;
5627 
5628 	/* Read only  */
5629 	if (req->newptr != USER_ADDR_NULL) {
5630 		return EPERM;
5631 	}
5632 
5633 	cfil_rw_lock_shared(&cfil_lck_rw);
5634 
5635 	/*
5636 	 * If just asking for the size,
5637 	 */
5638 	if (req->oldptr == USER_ADDR_NULL) {
5639 		req->oldidx = cfil_sock_attached_count *
5640 		    sizeof(struct cfil_sock_stat);
5641 		/* Bump the length in case new sockets gets attached */
5642 		req->oldidx += req->oldidx >> 3;
5643 		goto done;
5644 	}
5645 
5646 	TAILQ_FOREACH(cfi, &cfil_sock_head, cfi_link) {
5647 		struct cfil_entry *entry;
5648 		struct cfil_sock_stat stat;
5649 		struct socket *so = cfi->cfi_so;
5650 
5651 		bzero(&stat, sizeof(struct cfil_sock_stat));
5652 		stat.cfs_len = sizeof(struct cfil_sock_stat);
5653 		stat.cfs_sock_id = cfi->cfi_sock_id;
5654 		stat.cfs_flags = cfi->cfi_flags;
5655 
5656 		if (so != NULL && so->so_proto != NULL && so->so_proto->pr_domain != NULL) {
5657 			stat.cfs_pid = so->last_pid;
5658 			memcpy(stat.cfs_uuid, so->last_uuid,
5659 			    sizeof(uuid_t));
5660 			if (so->so_flags & SOF_DELEGATED) {
5661 				stat.cfs_e_pid = so->e_pid;
5662 				memcpy(stat.cfs_e_uuid, so->e_uuid,
5663 				    sizeof(uuid_t));
5664 			} else {
5665 				stat.cfs_e_pid = so->last_pid;
5666 				memcpy(stat.cfs_e_uuid, so->last_uuid,
5667 				    sizeof(uuid_t));
5668 			}
5669 
5670 			stat.cfs_sock_family = so->so_proto->pr_domain->dom_family;
5671 			stat.cfs_sock_type = so->so_proto->pr_type;
5672 			stat.cfs_sock_protocol = GET_SO_PROTO(so);
5673 		}
5674 
5675 		stat.cfs_snd.cbs_pending_first =
5676 		    cfi->cfi_snd.cfi_pending_first;
5677 		stat.cfs_snd.cbs_pending_last =
5678 		    cfi->cfi_snd.cfi_pending_last;
5679 		stat.cfs_snd.cbs_inject_q_len =
5680 		    cfil_queue_len(&cfi->cfi_snd.cfi_inject_q);
5681 		stat.cfs_snd.cbs_pass_offset =
5682 		    cfi->cfi_snd.cfi_pass_offset;
5683 
5684 		stat.cfs_rcv.cbs_pending_first =
5685 		    cfi->cfi_rcv.cfi_pending_first;
5686 		stat.cfs_rcv.cbs_pending_last =
5687 		    cfi->cfi_rcv.cfi_pending_last;
5688 		stat.cfs_rcv.cbs_inject_q_len =
5689 		    cfil_queue_len(&cfi->cfi_rcv.cfi_inject_q);
5690 		stat.cfs_rcv.cbs_pass_offset =
5691 		    cfi->cfi_rcv.cfi_pass_offset;
5692 
5693 		for (i = 0; i < MAX_CONTENT_FILTER; i++) {
5694 			struct cfil_entry_stat *estat;
5695 			struct cfe_buf *ebuf;
5696 			struct cfe_buf_stat *sbuf;
5697 
5698 			entry = &cfi->cfi_entries[i];
5699 
5700 			estat = &stat.ces_entries[i];
5701 
5702 			estat->ces_len = sizeof(struct cfil_entry_stat);
5703 			estat->ces_filter_id = entry->cfe_filter ?
5704 			    entry->cfe_filter->cf_kcunit : 0;
5705 			estat->ces_flags = entry->cfe_flags;
5706 			estat->ces_necp_control_unit =
5707 			    entry->cfe_necp_control_unit;
5708 
5709 			estat->ces_last_event.tv_sec =
5710 			    (int64_t)entry->cfe_last_event.tv_sec;
5711 			estat->ces_last_event.tv_usec =
5712 			    (int64_t)entry->cfe_last_event.tv_usec;
5713 
5714 			estat->ces_last_action.tv_sec =
5715 			    (int64_t)entry->cfe_last_action.tv_sec;
5716 			estat->ces_last_action.tv_usec =
5717 			    (int64_t)entry->cfe_last_action.tv_usec;
5718 
5719 			ebuf = &entry->cfe_snd;
5720 			sbuf = &estat->ces_snd;
5721 			sbuf->cbs_pending_first =
5722 			    cfil_queue_offset_first(&ebuf->cfe_pending_q);
5723 			sbuf->cbs_pending_last =
5724 			    cfil_queue_offset_last(&ebuf->cfe_pending_q);
5725 			sbuf->cbs_ctl_first =
5726 			    cfil_queue_offset_first(&ebuf->cfe_ctl_q);
5727 			sbuf->cbs_ctl_last =
5728 			    cfil_queue_offset_last(&ebuf->cfe_ctl_q);
5729 			sbuf->cbs_pass_offset =  ebuf->cfe_pass_offset;
5730 			sbuf->cbs_peek_offset =  ebuf->cfe_peek_offset;
5731 			sbuf->cbs_peeked =  ebuf->cfe_peeked;
5732 
5733 			ebuf = &entry->cfe_rcv;
5734 			sbuf = &estat->ces_rcv;
5735 			sbuf->cbs_pending_first =
5736 			    cfil_queue_offset_first(&ebuf->cfe_pending_q);
5737 			sbuf->cbs_pending_last =
5738 			    cfil_queue_offset_last(&ebuf->cfe_pending_q);
5739 			sbuf->cbs_ctl_first =
5740 			    cfil_queue_offset_first(&ebuf->cfe_ctl_q);
5741 			sbuf->cbs_ctl_last =
5742 			    cfil_queue_offset_last(&ebuf->cfe_ctl_q);
5743 			sbuf->cbs_pass_offset =  ebuf->cfe_pass_offset;
5744 			sbuf->cbs_peek_offset =  ebuf->cfe_peek_offset;
5745 			sbuf->cbs_peeked =  ebuf->cfe_peeked;
5746 		}
5747 		error = SYSCTL_OUT(req, &stat,
5748 		    sizeof(struct cfil_sock_stat));
5749 		if (error != 0) {
5750 			break;
5751 		}
5752 	}
5753 done:
5754 	cfil_rw_unlock_shared(&cfil_lck_rw);
5755 
5756 	if (cfil_log_level >= LOG_DEBUG) {
5757 		if (req->oldptr != USER_ADDR_NULL) {
5758 			cfil_info_show();
5759 		}
5760 	}
5761 
5762 	return error;
5763 }
5764 
5765 /*
5766  * UDP Socket Support
5767  */
5768 static void
cfil_hash_entry_log(int level,struct socket * so,struct soflow_hash_entry * entry,uint64_t sockId,const char * msg)5769 cfil_hash_entry_log(int level, struct socket *so, struct soflow_hash_entry *entry, uint64_t sockId, const char* msg)
5770 {
5771 	char local[MAX_IPv6_STR_LEN + 6];
5772 	char remote[MAX_IPv6_STR_LEN + 6];
5773 	const void  *addr;
5774 
5775 	// No sock or not UDP, no-op
5776 	if (so == NULL || entry == NULL) {
5777 		return;
5778 	}
5779 
5780 	local[0] = remote[0] = 0x0;
5781 
5782 	switch (entry->soflow_family) {
5783 	case AF_INET6:
5784 		addr = &entry->soflow_laddr.addr6;
5785 		inet_ntop(AF_INET6, addr, local, sizeof(local));
5786 		addr = &entry->soflow_faddr.addr6;
5787 		inet_ntop(AF_INET6, addr, remote, sizeof(local));
5788 		break;
5789 	case AF_INET:
5790 		addr = &entry->soflow_laddr.addr46.ia46_addr4.s_addr;
5791 		inet_ntop(AF_INET, addr, local, sizeof(local));
5792 		addr = &entry->soflow_faddr.addr46.ia46_addr4.s_addr;
5793 		inet_ntop(AF_INET, addr, remote, sizeof(local));
5794 		break;
5795 	default:
5796 		return;
5797 	}
5798 
5799 	CFIL_LOG(level, "<%s>: <%s(%d) so %llx cfil %p, entry %p, sockID %llu <%llu>> lport %d fport %d laddr %s faddr %s hash %X",
5800 	    msg,
5801 	    IS_UDP(so) ? "UDP" : "proto", GET_SO_PROTO(so),
5802 	    (uint64_t)VM_KERNEL_ADDRPERM(so), entry->soflow_feat_ctxt, entry, sockId, entry->soflow_feat_ctxt_id,
5803 	    ntohs(entry->soflow_lport), ntohs(entry->soflow_fport), local, remote,
5804 	    entry->soflow_flowhash);
5805 }
5806 
5807 static void
cfil_inp_log(int level,struct socket * so,const char * msg)5808 cfil_inp_log(int level, struct socket *so, const char* msg)
5809 {
5810 	struct inpcb *inp = NULL;
5811 	char local[MAX_IPv6_STR_LEN + 6];
5812 	char remote[MAX_IPv6_STR_LEN + 6];
5813 	const void  *addr;
5814 
5815 	if (so == NULL) {
5816 		return;
5817 	}
5818 
5819 	inp = sotoinpcb(so);
5820 	if (inp == NULL) {
5821 		return;
5822 	}
5823 
5824 	local[0] = remote[0] = 0x0;
5825 
5826 	if (inp->inp_vflag & INP_IPV6) {
5827 		addr = &inp->in6p_laddr.s6_addr32;
5828 		inet_ntop(AF_INET6, addr, local, sizeof(local));
5829 		addr = &inp->in6p_faddr.s6_addr32;
5830 		inet_ntop(AF_INET6, addr, remote, sizeof(local));
5831 	} else {
5832 		addr = &inp->inp_laddr.s_addr;
5833 		inet_ntop(AF_INET, addr, local, sizeof(local));
5834 		addr = &inp->inp_faddr.s_addr;
5835 		inet_ntop(AF_INET, addr, remote, sizeof(local));
5836 	}
5837 
5838 	if (so->so_cfil != NULL) {
5839 		CFIL_LOG(level, "<%s>: <%s so %llx cfil %p - flags 0x%x 0x%x, sockID %llu> lport %d fport %d laddr %s faddr %s",
5840 		    msg, IS_UDP(so) ? "UDP" : "TCP",
5841 		    (uint64_t)VM_KERNEL_ADDRPERM(so), so->so_cfil, inp->inp_flags, inp->inp_socket->so_flags, so->so_cfil->cfi_sock_id,
5842 		    ntohs(inp->inp_lport), ntohs(inp->inp_fport), local, remote);
5843 	} else {
5844 		CFIL_LOG(level, "<%s>: <%s so %llx - flags 0x%x 0x%x> lport %d fport %d laddr %s faddr %s",
5845 		    msg, IS_UDP(so) ? "UDP" : "TCP",
5846 		    (uint64_t)VM_KERNEL_ADDRPERM(so), inp->inp_flags, inp->inp_socket->so_flags,
5847 		    ntohs(inp->inp_lport), ntohs(inp->inp_fport), local, remote);
5848 	}
5849 }
5850 
5851 static void
cfil_info_log(int level,struct cfil_info * cfil_info,const char * msg)5852 cfil_info_log(int level, struct cfil_info *cfil_info, const char* msg)
5853 {
5854 	if (cfil_info == NULL) {
5855 		return;
5856 	}
5857 
5858 	if (cfil_info->cfi_hash_entry != NULL) {
5859 		cfil_hash_entry_log(level, cfil_info->cfi_so, cfil_info->cfi_hash_entry, cfil_info->cfi_sock_id, msg);
5860 	} else {
5861 		cfil_inp_log(level, cfil_info->cfi_so, msg);
5862 	}
5863 }
5864 
5865 static void
cfil_sock_udp_unlink_flow(struct socket * so,struct soflow_hash_entry * hash_entry,struct cfil_info * cfil_info)5866 cfil_sock_udp_unlink_flow(struct socket *so, struct soflow_hash_entry *hash_entry, struct cfil_info *cfil_info)
5867 {
5868 	if (so == NULL || hash_entry == NULL || cfil_info == NULL) {
5869 		return;
5870 	}
5871 
5872 	if (so->so_flags & SOF_CONTENT_FILTER) {
5873 		VERIFY(so->so_usecount > 0);
5874 		so->so_usecount--;
5875 	}
5876 
5877 	// Hold exclusive lock before clearing cfil_info hash entry link
5878 	cfil_rw_lock_exclusive(&cfil_lck_rw);
5879 
5880 	cfil_info->cfi_hash_entry = NULL;
5881 
5882 	if (cfil_info->cfi_debug) {
5883 		CFIL_LOG(LOG_INFO, "CFIL <%s>: <so %llx> - use count %d",
5884 		    IS_UDP(so) ? "UDP" : "TCP", (uint64_t)VM_KERNEL_ADDRPERM(so), so->so_usecount);
5885 	}
5886 
5887 	cfil_rw_unlock_exclusive(&cfil_lck_rw);
5888 }
5889 
5890 bool
check_port(struct sockaddr * addr,u_short port)5891 check_port(struct sockaddr *addr, u_short port)
5892 {
5893 	struct sockaddr_in *sin = NULL;
5894 	struct sockaddr_in6 *sin6 = NULL;
5895 
5896 	if (addr == NULL || port == 0) {
5897 		return FALSE;
5898 	}
5899 
5900 	switch (addr->sa_family) {
5901 	case AF_INET:
5902 		sin = satosin(addr);
5903 		if (sin->sin_len < sizeof(*sin)) {
5904 			return FALSE;
5905 		}
5906 		if (port == ntohs(sin->sin_port)) {
5907 			return TRUE;
5908 		}
5909 		break;
5910 	case AF_INET6:
5911 		sin6 = satosin6(addr);
5912 		if (sin6->sin6_len < sizeof(*sin6)) {
5913 			return FALSE;
5914 		}
5915 		if (port == ntohs(sin6->sin6_port)) {
5916 			return TRUE;
5917 		}
5918 		break;
5919 	default:
5920 		break;
5921 	}
5922 	return FALSE;
5923 }
5924 
5925 cfil_sock_id_t
cfil_sock_id_from_datagram_socket(struct socket * so,struct sockaddr * local,struct sockaddr * remote)5926 cfil_sock_id_from_datagram_socket(struct socket *so, struct sockaddr *local, struct sockaddr *remote)
5927 {
5928 	socket_lock_assert_owned(so);
5929 
5930 	if (so->so_flow_db == NULL) {
5931 		return CFIL_SOCK_ID_NONE;
5932 	}
5933 	return (cfil_sock_id_t)soflow_db_get_feature_context_id(so->so_flow_db, local, remote);
5934 }
5935 
5936 static struct cfil_info *
cfil_sock_udp_get_info(struct socket * so,uint32_t filter_control_unit,bool outgoing,struct soflow_hash_entry * hash_entry,struct sockaddr * local,struct sockaddr * remote)5937 cfil_sock_udp_get_info(struct socket *so, uint32_t filter_control_unit, bool outgoing, struct soflow_hash_entry *hash_entry,
5938     struct sockaddr *local, struct sockaddr *remote)
5939 {
5940 	int new_filter_control_unit = 0;
5941 	struct cfil_info *cfil_info = NULL;
5942 
5943 	errno_t error = 0;
5944 	socket_lock_assert_owned(so);
5945 
5946 	if (hash_entry == NULL || hash_entry->soflow_db == NULL) {
5947 		return NULL;
5948 	}
5949 
5950 	if (hash_entry->soflow_feat_ctxt != NULL && hash_entry->soflow_feat_ctxt_id != 0) {
5951 		/* Drop pre-existing UDP flow if filter state changed */
5952 		cfil_info = (struct cfil_info *) hash_entry->soflow_feat_ctxt;
5953 		new_filter_control_unit = necp_socket_get_content_filter_control_unit(so);
5954 		if (new_filter_control_unit > 0 &&
5955 		    new_filter_control_unit != cfil_info->cfi_filter_control_unit) {
5956 			if (DO_PRESERVE_CONNECTIONS) {
5957 				cfil_info->cfi_filter_control_unit = new_filter_control_unit;
5958 			} else {
5959 				CFIL_LOG(LOG_NOTICE, "CFIL: UDP(%s) <so %llx> - filter state changed - dropped pre-existing flow (old state 0x%x new state 0x%x)",
5960 				    outgoing ? "OUT" : "IN", (uint64_t)VM_KERNEL_ADDRPERM(so),
5961 				    cfil_info->cfi_filter_control_unit, new_filter_control_unit);
5962 				return NULL;
5963 			}
5964 		}
5965 		return cfil_info;
5966 	}
5967 
5968 	cfil_info = cfil_info_alloc(so, hash_entry);
5969 	if (cfil_info == NULL) {
5970 		CFIL_LOG(LOG_ERR, "CFIL: <so %llx> UDP failed to alloc cfil_info", (uint64_t)VM_KERNEL_ADDRPERM(so));
5971 		OSIncrementAtomic(&cfil_stats.cfs_sock_attach_no_mem);
5972 		return NULL;
5973 	}
5974 	cfil_info->cfi_filter_control_unit = filter_control_unit;
5975 	cfil_info->cfi_dir = outgoing ? CFS_CONNECTION_DIR_OUT : CFS_CONNECTION_DIR_IN;
5976 	cfil_info->cfi_debug = DEBUG_FLOW(sotoinpcb(so), so, local, remote);
5977 	if (cfil_info->cfi_debug) {
5978 		CFIL_LOG(LOG_INFO, "CFIL: <so %llx> UDP (outgoing %d) - debug flow with port %d", (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing, cfil_log_port);
5979 		CFIL_LOG(LOG_INFO, "CFIL: <so %llx> UDP so_gencnt %llx entry flowhash %x cfil %p sockID %llx",
5980 		    (uint64_t)VM_KERNEL_ADDRPERM(so), so->so_gencnt, hash_entry->soflow_flowhash, cfil_info, cfil_info->cfi_sock_id);
5981 	}
5982 
5983 	if (cfil_info_attach_unit(so, filter_control_unit, cfil_info) == 0) {
5984 		CFIL_INFO_FREE(cfil_info);
5985 		CFIL_LOG(LOG_ERR, "CFIL: <so %llx> UDP cfil_info_attach_unit(%u) failed",
5986 		    (uint64_t)VM_KERNEL_ADDRPERM(so), filter_control_unit);
5987 		OSIncrementAtomic(&cfil_stats.cfs_sock_attach_failed);
5988 		return NULL;
5989 	}
5990 
5991 	if (cfil_info->cfi_debug) {
5992 		CFIL_LOG(LOG_DEBUG, "CFIL: UDP <so %llx> filter_control_unit %u sockID %llu attached",
5993 		    (uint64_t)VM_KERNEL_ADDRPERM(so),
5994 		    filter_control_unit, cfil_info->cfi_sock_id);
5995 	}
5996 
5997 	so->so_flags |= SOF_CONTENT_FILTER;
5998 	OSIncrementAtomic(&cfil_stats.cfs_sock_attached);
5999 
6000 	/* Hold a reference on the socket for each flow */
6001 	so->so_usecount++;
6002 
6003 	/* link cfil_info to flow */
6004 	hash_entry->soflow_feat_ctxt = cfil_info;
6005 	hash_entry->soflow_feat_ctxt_id = cfil_info->cfi_sock_id;
6006 
6007 	if (cfil_info->cfi_debug) {
6008 		cfil_info_log(LOG_INFO, cfil_info, "CFIL: ADDED");
6009 	}
6010 
6011 	error = cfil_dispatch_attach_event(so, cfil_info, 0,
6012 	    outgoing ? CFS_CONNECTION_DIR_OUT : CFS_CONNECTION_DIR_IN);
6013 	/* We can recover from flow control or out of memory errors */
6014 	if (error != 0 && error != ENOBUFS && error != ENOMEM) {
6015 		CFIL_LOG(LOG_ERR, "CFIL: UDP <so %llx> cfil_dispatch_attach_event failed <error %d>",
6016 		    (uint64_t)VM_KERNEL_ADDRPERM(so), error);
6017 		return NULL;
6018 	}
6019 
6020 	CFIL_INFO_VERIFY(cfil_info);
6021 	return cfil_info;
6022 }
6023 
6024 errno_t
cfil_sock_udp_handle_data(bool outgoing,struct socket * so,struct sockaddr * local,struct sockaddr * remote,struct mbuf * data,struct mbuf * control,uint32_t flags,struct soflow_hash_entry * hash_entry)6025 cfil_sock_udp_handle_data(bool outgoing, struct socket *so,
6026     struct sockaddr *local, struct sockaddr *remote,
6027     struct mbuf *data, struct mbuf *control, uint32_t flags,
6028     struct soflow_hash_entry *hash_entry)
6029 {
6030 #pragma unused(outgoing, so, local, remote, data, control, flags)
6031 	errno_t error = 0;
6032 	uint32_t filter_control_unit;
6033 	struct cfil_info *cfil_info = NULL;
6034 
6035 	socket_lock_assert_owned(so);
6036 
6037 	if (cfil_active_count == 0) {
6038 		CFIL_LOG(LOG_DEBUG, "CFIL: UDP no active filter");
6039 		OSIncrementAtomic(&cfil_stats.cfs_sock_attach_in_vain);
6040 		return error;
6041 	}
6042 
6043 	// Socket has been blessed
6044 	if ((so->so_flags1 & SOF1_CONTENT_FILTER_SKIP) != 0) {
6045 		return error;
6046 	}
6047 
6048 	filter_control_unit = necp_socket_get_content_filter_control_unit(so);
6049 	if (filter_control_unit == 0) {
6050 		CFIL_LOG(LOG_DEBUG, "CFIL: UDP failed to get control unit");
6051 		return error;
6052 	}
6053 
6054 	if (filter_control_unit == NECP_FILTER_UNIT_NO_FILTER) {
6055 		return error;
6056 	}
6057 
6058 	if ((filter_control_unit & NECP_MASK_USERSPACE_ONLY) != 0) {
6059 		CFIL_LOG(LOG_DEBUG, "CFIL: UDP user space only");
6060 		OSIncrementAtomic(&cfil_stats.cfs_sock_userspace_only);
6061 		return error;
6062 	}
6063 
6064 	if (hash_entry == NULL) {
6065 		CFIL_LOG(LOG_ERR, "CFIL: <so %llx> NULL soflow_hash_entry", (uint64_t)VM_KERNEL_ADDRPERM(so));
6066 		return EPIPE;
6067 	}
6068 
6069 	if (hash_entry->soflow_db == NULL) {
6070 		CFIL_LOG(LOG_ERR, "CFIL: <so %llx> NULL soflow_hash_entry db", (uint64_t)VM_KERNEL_ADDRPERM(so));
6071 		return EPIPE;
6072 	}
6073 
6074 	cfil_info = cfil_sock_udp_get_info(so, filter_control_unit, outgoing, hash_entry, local, remote);
6075 	if (cfil_info == NULL) {
6076 		return EPIPE;
6077 	}
6078 	// Update last used timestamp, this is for flow Idle TO
6079 
6080 	if (cfil_info->cfi_debug) {
6081 		cfil_info_log(LOG_DEBUG, cfil_info, "CFIL: Got flow");
6082 	}
6083 
6084 	if (cfil_info->cfi_flags & CFIF_DROP) {
6085 		if (cfil_info->cfi_debug) {
6086 			cfil_info_log(LOG_INFO, cfil_info, "CFIL: UDP DROP");
6087 		}
6088 		return EPIPE;
6089 	}
6090 	if (control != NULL) {
6091 		OSIncrementAtomic(&cfil_stats.cfs_data_in_control);
6092 	}
6093 	if (data->m_type == MT_OOBDATA) {
6094 		CFIL_LOG(LOG_ERR, "so %llx MSG_OOB",
6095 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
6096 		OSIncrementAtomic(&cfil_stats.cfs_data_in_oob);
6097 	}
6098 
6099 	error = cfil_data_common(so, cfil_info, outgoing, remote, data, control, flags);
6100 
6101 	return error;
6102 }
6103 
6104 struct cfil_udp_attached_context {
6105 	bool need_wait;
6106 	lck_mtx_t *mutex_held;
6107 	int attached;
6108 };
6109 
6110 static bool
cfil_filters_udp_attached_per_flow(struct socket * so,struct soflow_hash_entry * hash_entry,void * context)6111 cfil_filters_udp_attached_per_flow(struct socket *so,
6112     struct soflow_hash_entry *hash_entry,
6113     void *context)
6114 {
6115 	struct cfil_udp_attached_context *apply_context = NULL;
6116 	struct cfil_info *cfil_info = NULL;
6117 	struct cfil_entry *entry = NULL;
6118 	uint64_t sock_flow_id = 0;
6119 	struct timespec ts;
6120 	errno_t error = 0;
6121 	int kcunit;
6122 
6123 	if (hash_entry->soflow_feat_ctxt == NULL || context == NULL) {
6124 		return true;
6125 	}
6126 
6127 	cfil_info = hash_entry->soflow_feat_ctxt;
6128 	apply_context = (struct cfil_udp_attached_context *)context;
6129 
6130 	for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
6131 		entry = &cfil_info->cfi_entries[kcunit - 1];
6132 
6133 		/* Are we attached to the filter? */
6134 		if (entry->cfe_filter == NULL) {
6135 			continue;
6136 		}
6137 
6138 		if ((entry->cfe_flags & CFEF_SENT_SOCK_ATTACHED) == 0) {
6139 			continue;
6140 		}
6141 		if ((entry->cfe_flags & CFEF_CFIL_DETACHED) != 0) {
6142 			continue;
6143 		}
6144 
6145 		if (apply_context->need_wait == TRUE) {
6146 			if (cfil_info->cfi_debug) {
6147 				cfil_info_log(LOG_INFO, cfil_info, "CFIL: UDP PER-FLOW WAIT FOR FLOW TO FINISH");
6148 			}
6149 
6150 			ts.tv_sec = cfil_close_wait_timeout / 1000;
6151 			ts.tv_nsec = (cfil_close_wait_timeout % 1000) * NSEC_PER_USEC * 1000;
6152 
6153 			OSIncrementAtomic(&cfil_stats.cfs_close_wait);
6154 			cfil_info->cfi_flags |= CFIF_CLOSE_WAIT;
6155 			sock_flow_id = cfil_info->cfi_sock_id;
6156 
6157 			error = msleep((caddr_t)cfil_info, apply_context->mutex_held,
6158 			    PSOCK | PCATCH, "cfil_filters_udp_attached_per_flow", &ts);
6159 
6160 			// Woke up from sleep, validate if cfil_info is still valid
6161 			if (so->so_flow_db == NULL ||
6162 			    (cfil_info != soflow_db_get_feature_context(so->so_flow_db, sock_flow_id))) {
6163 				// cfil_info is not valid, do not continue
6164 				return false;
6165 			}
6166 
6167 			cfil_info->cfi_flags &= ~CFIF_CLOSE_WAIT;
6168 
6169 			if (cfil_info->cfi_debug) {
6170 				cfil_info_log(LOG_INFO, cfil_info, "CFIL: UDP PER-FLOW WAIT FOR FLOW DONE");
6171 			}
6172 
6173 			/*
6174 			 * Force close in case of timeout
6175 			 */
6176 			if (error != 0) {
6177 				OSIncrementAtomic(&cfil_stats.cfs_close_wait_timeout);
6178 
6179 				if (cfil_info->cfi_debug) {
6180 					cfil_info_log(LOG_INFO, cfil_info, "CFIL: UDP PER-FLOW WAIT FOR FLOW TIMED OUT, FORCE DETACH");
6181 				}
6182 
6183 				entry->cfe_flags |= CFEF_CFIL_DETACHED;
6184 				return false;
6185 			}
6186 		}
6187 		apply_context->attached = 1;
6188 		return false;
6189 	}
6190 	return true;
6191 }
6192 
6193 /*
6194  * Go through all UDP flows for specified socket and returns TRUE if
6195  * any flow is still attached.  If need_wait is TRUE, wait on first
6196  * attached flow.
6197  */
6198 static int
cfil_filters_udp_attached(struct socket * so,bool need_wait)6199 cfil_filters_udp_attached(struct socket *so, bool need_wait)
6200 {
6201 	struct cfil_udp_attached_context apply_context = { 0 };
6202 	lck_mtx_t *mutex_held;
6203 
6204 	socket_lock_assert_owned(so);
6205 
6206 	if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_flow_db != NULL) {
6207 		if (so->so_proto->pr_getlock != NULL) {
6208 			mutex_held = (*so->so_proto->pr_getlock)(so, PR_F_WILLUNLOCK);
6209 		} else {
6210 			mutex_held = so->so_proto->pr_domain->dom_mtx;
6211 		}
6212 		LCK_MTX_ASSERT(mutex_held, LCK_MTX_ASSERT_OWNED);
6213 
6214 		apply_context.need_wait = need_wait;
6215 		apply_context.mutex_held = mutex_held;
6216 		soflow_db_apply(so->so_flow_db, cfil_filters_udp_attached_per_flow, (void *)&apply_context);
6217 	}
6218 
6219 	return apply_context.attached;
6220 }
6221 
6222 struct cfil_udp_data_pending_context {
6223 	struct sockbuf *sb;
6224 	uint64_t total_pending;
6225 };
6226 
6227 static bool
cfil_sock_udp_data_pending_per_flow(struct socket * so,struct soflow_hash_entry * hash_entry,void * context)6228 cfil_sock_udp_data_pending_per_flow(struct socket *so,
6229     struct soflow_hash_entry *hash_entry,
6230     void *context)
6231 {
6232 #pragma unused(so)
6233 	struct cfil_udp_data_pending_context *apply_context = NULL;
6234 	struct cfil_info *cfil_info = NULL;
6235 	struct cfi_buf *cfi_buf;
6236 
6237 	uint64_t pending = 0;
6238 
6239 	if (hash_entry->soflow_feat_ctxt == NULL || context == NULL) {
6240 		return true;
6241 	}
6242 
6243 	cfil_info = hash_entry->soflow_feat_ctxt;
6244 	apply_context = (struct cfil_udp_data_pending_context *)context;
6245 
6246 	if (apply_context->sb == NULL) {
6247 		return true;
6248 	}
6249 
6250 	if ((apply_context->sb->sb_flags & SB_RECV) == 0) {
6251 		cfi_buf = &cfil_info->cfi_snd;
6252 	} else {
6253 		cfi_buf = &cfil_info->cfi_rcv;
6254 	}
6255 
6256 	pending = cfi_buf->cfi_pending_last - cfi_buf->cfi_pending_first;
6257 	/*
6258 	 * If we are limited by the "chars of mbufs used" roughly
6259 	 * adjust so we won't overcommit
6260 	 */
6261 	if ((uint64_t)cfi_buf->cfi_pending_mbcnt > pending) {
6262 		pending = cfi_buf->cfi_pending_mbcnt;
6263 	}
6264 
6265 	apply_context->total_pending += pending;
6266 	return true;
6267 }
6268 
6269 int32_t
cfil_sock_udp_data_pending(struct sockbuf * sb,bool check_thread)6270 cfil_sock_udp_data_pending(struct sockbuf *sb, bool check_thread)
6271 {
6272 	struct cfil_udp_data_pending_context apply_context = { 0 };
6273 	struct socket *so = sb->sb_so;
6274 
6275 	socket_lock_assert_owned(so);
6276 
6277 	if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_flow_db != NULL &&
6278 	    (check_thread == FALSE || so->so_snd.sb_cfil_thread != current_thread())) {
6279 		apply_context.sb = sb;
6280 		soflow_db_apply(so->so_flow_db, cfil_sock_udp_data_pending_per_flow, (void *)&apply_context);
6281 
6282 		VERIFY(apply_context.total_pending < INT32_MAX);
6283 	}
6284 
6285 	return (int32_t)(apply_context.total_pending);
6286 }
6287 
6288 struct cfil_udp_notify_shutdown_context {
6289 	int how;
6290 	int drop_flag;
6291 	int shut_flag;
6292 	int done_count;
6293 };
6294 
6295 static bool
cfil_sock_udp_notify_shutdown_per_flow(struct socket * so,struct soflow_hash_entry * hash_entry,void * context)6296 cfil_sock_udp_notify_shutdown_per_flow(struct socket *so,
6297     struct soflow_hash_entry *hash_entry,
6298     void *context)
6299 {
6300 	struct cfil_udp_notify_shutdown_context *apply_context = NULL;
6301 	struct cfil_info *cfil_info = NULL;
6302 	errno_t error = 0;
6303 	int kcunit;
6304 
6305 	if (hash_entry->soflow_feat_ctxt == NULL || context == NULL) {
6306 		return true;
6307 	}
6308 
6309 	cfil_info = hash_entry->soflow_feat_ctxt;
6310 	apply_context = (struct cfil_udp_notify_shutdown_context *)context;
6311 
6312 	// This flow is marked as DROP
6313 	if (cfil_info->cfi_flags & apply_context->drop_flag) {
6314 		apply_context->done_count++;
6315 		return true;
6316 	}
6317 
6318 	// This flow has been shut already, skip
6319 	if (cfil_info->cfi_flags & apply_context->shut_flag) {
6320 		return true;
6321 	}
6322 	// Mark flow as shut
6323 	cfil_info->cfi_flags |= apply_context->shut_flag;
6324 	apply_context->done_count++;
6325 
6326 	for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
6327 		/* Disconnect incoming side */
6328 		if (apply_context->how != SHUT_WR) {
6329 			error = cfil_dispatch_disconnect_event(so, cfil_info, kcunit, 0);
6330 		}
6331 		/* Disconnect outgoing side */
6332 		if (apply_context->how != SHUT_RD) {
6333 			error = cfil_dispatch_disconnect_event(so, cfil_info, kcunit, 1);
6334 		}
6335 	}
6336 
6337 	if (cfil_info->cfi_debug) {
6338 		cfil_info_log(LOG_INFO, cfil_info, "CFIL: UDP PER-FLOW NOTIFY_SHUTDOWN");
6339 	}
6340 
6341 	return true;
6342 }
6343 
6344 int
cfil_sock_udp_notify_shutdown(struct socket * so,int how,int drop_flag,int shut_flag)6345 cfil_sock_udp_notify_shutdown(struct socket *so, int how, int drop_flag, int shut_flag)
6346 {
6347 	struct cfil_udp_notify_shutdown_context apply_context = { 0 };
6348 	errno_t error = 0;
6349 
6350 	socket_lock_assert_owned(so);
6351 
6352 	if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_flow_db != NULL) {
6353 		apply_context.how = how;
6354 		apply_context.drop_flag = drop_flag;
6355 		apply_context.shut_flag = shut_flag;
6356 
6357 		soflow_db_apply(so->so_flow_db, cfil_sock_udp_notify_shutdown_per_flow, (void *)&apply_context);
6358 	}
6359 
6360 	if (apply_context.done_count == 0) {
6361 		error = ENOTCONN;
6362 	}
6363 	return error;
6364 }
6365 
6366 int
cfil_sock_udp_shutdown(struct socket * so,int * how)6367 cfil_sock_udp_shutdown(struct socket *so, int *how)
6368 {
6369 	int error = 0;
6370 
6371 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || (so->so_flow_db == NULL)) {
6372 		goto done;
6373 	}
6374 
6375 	socket_lock_assert_owned(so);
6376 
6377 	CFIL_LOG(LOG_INFO, "so %llx how %d",
6378 	    (uint64_t)VM_KERNEL_ADDRPERM(so), *how);
6379 
6380 	/*
6381 	 * Check the state of the socket before the content filter
6382 	 */
6383 	if (*how != SHUT_WR && (so->so_state & SS_CANTRCVMORE) != 0) {
6384 		/* read already shut down */
6385 		error = ENOTCONN;
6386 		goto done;
6387 	}
6388 	if (*how != SHUT_RD && (so->so_state & SS_CANTSENDMORE) != 0) {
6389 		/* write already shut down */
6390 		error = ENOTCONN;
6391 		goto done;
6392 	}
6393 
6394 	/*
6395 	 * shutdown read: SHUT_RD or SHUT_RDWR
6396 	 */
6397 	if (*how != SHUT_WR) {
6398 		error = cfil_sock_udp_notify_shutdown(so, SHUT_RD, CFIF_DROP, CFIF_SHUT_RD);
6399 		if (error != 0) {
6400 			goto done;
6401 		}
6402 	}
6403 	/*
6404 	 * shutdown write: SHUT_WR or SHUT_RDWR
6405 	 */
6406 	if (*how != SHUT_RD) {
6407 		error = cfil_sock_udp_notify_shutdown(so, SHUT_WR, CFIF_DROP, CFIF_SHUT_WR);
6408 		if (error != 0) {
6409 			goto done;
6410 		}
6411 
6412 		/*
6413 		 * When outgoing data is pending, we delay the shutdown at the
6414 		 * protocol level until the content filters give the final
6415 		 * verdict on the pending data.
6416 		 */
6417 		if (cfil_sock_data_pending(&so->so_snd) != 0) {
6418 			/*
6419 			 * When shutting down the read and write sides at once
6420 			 * we can proceed to the final shutdown of the read
6421 			 * side. Otherwise, we just return.
6422 			 */
6423 			if (*how == SHUT_WR) {
6424 				error = EJUSTRETURN;
6425 			} else if (*how == SHUT_RDWR) {
6426 				*how = SHUT_RD;
6427 			}
6428 		}
6429 	}
6430 done:
6431 	return error;
6432 }
6433 
6434 void
cfil_sock_udp_close_wait(struct socket * so)6435 cfil_sock_udp_close_wait(struct socket *so)
6436 {
6437 	socket_lock_assert_owned(so);
6438 
6439 	while (cfil_filters_udp_attached(so, FALSE)) {
6440 		/*
6441 		 * Notify the filters we are going away so they can detach
6442 		 */
6443 		cfil_sock_udp_notify_shutdown(so, SHUT_RDWR, 0, 0);
6444 
6445 		/*
6446 		 * Make sure we need to wait after the filter are notified
6447 		 * of the disconnection
6448 		 */
6449 		if (cfil_filters_udp_attached(so, TRUE) == 0) {
6450 			break;
6451 		}
6452 	}
6453 }
6454 
6455 static bool
cfil_sock_udp_is_closed_per_flow(struct socket * so,struct soflow_hash_entry * hash_entry,void * context)6456 cfil_sock_udp_is_closed_per_flow(struct socket *so,
6457     struct soflow_hash_entry *hash_entry,
6458     void *context)
6459 {
6460 #pragma unused(context)
6461 	struct cfil_info *cfil_info = NULL;
6462 	errno_t error = 0;
6463 	int kcunit;
6464 
6465 	if (hash_entry->soflow_feat_ctxt == NULL) {
6466 		return true;
6467 	}
6468 
6469 	cfil_info = hash_entry->soflow_feat_ctxt;
6470 
6471 	for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
6472 		/* Let the filters know of the closing */
6473 		error = cfil_dispatch_closed_event(so, cfil_info, kcunit);
6474 	}
6475 
6476 	/* Last chance to push passed data out */
6477 	error = cfil_acquire_sockbuf(so, cfil_info, 1);
6478 	if (error == 0) {
6479 		cfil_service_inject_queue(so, cfil_info, 1);
6480 	}
6481 	cfil_release_sockbuf(so, 1);
6482 
6483 	cfil_info->cfi_flags |= CFIF_SOCK_CLOSED;
6484 
6485 	/* Pending data needs to go */
6486 	cfil_flush_queues(so, cfil_info);
6487 
6488 	CFIL_INFO_VERIFY(cfil_info);
6489 
6490 	if (cfil_info->cfi_debug) {
6491 		cfil_info_log(LOG_INFO, cfil_info, "CFIL: UDP PER-FLOW IS_CLOSED");
6492 	}
6493 
6494 	return true;
6495 }
6496 
6497 void
cfil_sock_udp_is_closed(struct socket * so)6498 cfil_sock_udp_is_closed(struct socket *so)
6499 {
6500 	socket_lock_assert_owned(so);
6501 
6502 	if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_flow_db != NULL) {
6503 		soflow_db_apply(so->so_flow_db, cfil_sock_udp_is_closed_per_flow, NULL);
6504 	}
6505 }
6506 
6507 static bool
cfil_sock_udp_buf_update_per_flow(struct socket * so,struct soflow_hash_entry * hash_entry,void * context)6508 cfil_sock_udp_buf_update_per_flow(struct socket *so,
6509     struct soflow_hash_entry *hash_entry,
6510     void *context)
6511 {
6512 	struct cfil_info *cfil_info = NULL;
6513 	struct sockbuf *sb = NULL;
6514 	errno_t error = 0;
6515 	int outgoing;
6516 
6517 	if (hash_entry->soflow_feat_ctxt == NULL || context == NULL) {
6518 		return true;
6519 	}
6520 
6521 	cfil_info = hash_entry->soflow_feat_ctxt;
6522 	sb = (struct sockbuf *) context;
6523 
6524 	if ((sb->sb_flags & SB_RECV) == 0) {
6525 		if ((cfil_info->cfi_flags & CFIF_RETRY_INJECT_OUT) == 0) {
6526 			return true;
6527 		}
6528 		outgoing = 1;
6529 		OSIncrementAtomic(&cfil_stats.cfs_inject_q_out_retry);
6530 	} else {
6531 		if ((cfil_info->cfi_flags & CFIF_RETRY_INJECT_IN) == 0) {
6532 			return true;
6533 		}
6534 		outgoing = 0;
6535 		OSIncrementAtomic(&cfil_stats.cfs_inject_q_in_retry);
6536 	}
6537 
6538 	CFIL_LOG(LOG_NOTICE, "so %llx outgoing %d",
6539 	    (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing);
6540 
6541 	error = cfil_acquire_sockbuf(so, cfil_info, outgoing);
6542 	if (error == 0) {
6543 		cfil_service_inject_queue(so, cfil_info, outgoing);
6544 	}
6545 	cfil_release_sockbuf(so, outgoing);
6546 	return true;
6547 }
6548 
6549 void
cfil_sock_udp_buf_update(struct sockbuf * sb)6550 cfil_sock_udp_buf_update(struct sockbuf *sb)
6551 {
6552 	struct socket *so = sb->sb_so;
6553 
6554 	socket_lock_assert_owned(so);
6555 
6556 	if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_flow_db != NULL) {
6557 		if (!cfil_sbtrim) {
6558 			return;
6559 		}
6560 		soflow_db_apply(so->so_flow_db, cfil_sock_udp_buf_update_per_flow, (void *)sb);
6561 	}
6562 }
6563 
6564 void
cfil_filter_show(u_int32_t kcunit)6565 cfil_filter_show(u_int32_t kcunit)
6566 {
6567 	struct content_filter *cfc = NULL;
6568 	struct cfil_entry *entry;
6569 	int count = 0;
6570 
6571 	if (kcunit > MAX_CONTENT_FILTER) {
6572 		return;
6573 	}
6574 
6575 	cfil_rw_lock_shared(&cfil_lck_rw);
6576 
6577 	if (content_filters[kcunit - 1] == NULL) {
6578 		cfil_rw_unlock_shared(&cfil_lck_rw);
6579 		return;
6580 	}
6581 	cfc = content_filters[kcunit - 1];
6582 
6583 	CFIL_LOG(LOG_DEBUG, "CFIL: FILTER SHOW: Filter <unit %d, entry count %d> flags <%lx>:",
6584 	    kcunit, cfc->cf_sock_count, (unsigned long)cfc->cf_flags);
6585 	if (cfc->cf_flags & CFF_DETACHING) {
6586 		CFIL_LOG(LOG_DEBUG, "CFIL: FILTER SHOW:-DETACHING");
6587 	}
6588 	if (cfc->cf_flags & CFF_ACTIVE) {
6589 		CFIL_LOG(LOG_DEBUG, "CFIL: FILTER SHOW:-ACTIVE");
6590 	}
6591 	if (cfc->cf_flags & CFF_FLOW_CONTROLLED) {
6592 		CFIL_LOG(LOG_DEBUG, "CFIL: FILTER SHOW:-FLOW CONTROLLED");
6593 	}
6594 
6595 	TAILQ_FOREACH(entry, &cfc->cf_sock_entries, cfe_link) {
6596 		if (entry->cfe_cfil_info && entry->cfe_cfil_info->cfi_so) {
6597 			struct cfil_info *cfil_info = entry->cfe_cfil_info;
6598 
6599 			count++;
6600 
6601 			if (entry->cfe_flags & CFEF_CFIL_DETACHED) {
6602 				cfil_info_log(LOG_DEBUG, cfil_info, "CFIL: FILTER SHOW:-DETACHED");
6603 			} else {
6604 				cfil_info_log(LOG_DEBUG, cfil_info, "CFIL: FILTER SHOW:-ATTACHED");
6605 			}
6606 		}
6607 	}
6608 
6609 	CFIL_LOG(LOG_DEBUG, "CFIL: FILTER SHOW:Filter - total entries shown: %d", count);
6610 
6611 	cfil_rw_unlock_shared(&cfil_lck_rw);
6612 }
6613 
6614 void
cfil_info_show(void)6615 cfil_info_show(void)
6616 {
6617 	struct cfil_info *cfil_info;
6618 	int count = 0;
6619 
6620 	cfil_rw_lock_shared(&cfil_lck_rw);
6621 
6622 	CFIL_LOG(LOG_DEBUG, "CFIL: INFO SHOW:count %d", cfil_sock_attached_count);
6623 
6624 	TAILQ_FOREACH(cfil_info, &cfil_sock_head, cfi_link) {
6625 		count++;
6626 
6627 		cfil_info_log(LOG_DEBUG, cfil_info, "CFIL: INFO SHOW");
6628 
6629 		if (cfil_info->cfi_flags & CFIF_DROP) {
6630 			CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - DROP");
6631 		}
6632 		if (cfil_info->cfi_flags & CFIF_CLOSE_WAIT) {
6633 			CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - CLOSE_WAIT");
6634 		}
6635 		if (cfil_info->cfi_flags & CFIF_SOCK_CLOSED) {
6636 			CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - SOCK_CLOSED");
6637 		}
6638 		if (cfil_info->cfi_flags & CFIF_RETRY_INJECT_IN) {
6639 			CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - RETRY_INJECT_IN");
6640 		}
6641 		if (cfil_info->cfi_flags & CFIF_RETRY_INJECT_OUT) {
6642 			CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - RETRY_INJECT_OUT");
6643 		}
6644 		if (cfil_info->cfi_flags & CFIF_SHUT_WR) {
6645 			CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - SHUT_WR");
6646 		}
6647 		if (cfil_info->cfi_flags & CFIF_SHUT_RD) {
6648 			CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - SHUT_RD");
6649 		}
6650 	}
6651 
6652 	CFIL_LOG(LOG_DEBUG, "CFIL: INFO SHOW:total cfil_info shown: %d", count);
6653 
6654 	cfil_rw_unlock_shared(&cfil_lck_rw);
6655 }
6656 
6657 bool
cfil_info_action_timed_out(struct cfil_info * cfil_info,int timeout)6658 cfil_info_action_timed_out(struct cfil_info *cfil_info, int timeout)
6659 {
6660 	struct cfil_entry *entry;
6661 	struct timeval current_tv;
6662 	struct timeval diff_time;
6663 
6664 	if (cfil_info == NULL) {
6665 		return false;
6666 	}
6667 
6668 	/*
6669 	 * If we have queued up more data than passed offset and we haven't received
6670 	 * an action from user space for a while (the user space filter might have crashed),
6671 	 * return action timed out.
6672 	 */
6673 	if (cfil_info->cfi_snd.cfi_pending_last > cfil_info->cfi_snd.cfi_pass_offset ||
6674 	    cfil_info->cfi_rcv.cfi_pending_last > cfil_info->cfi_rcv.cfi_pass_offset) {
6675 		microuptime(&current_tv);
6676 
6677 		for (int kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
6678 			entry = &cfil_info->cfi_entries[kcunit - 1];
6679 
6680 			if (entry->cfe_filter == NULL) {
6681 				continue;
6682 			}
6683 
6684 			if (cfil_info->cfi_snd.cfi_pending_last > entry->cfe_snd.cfe_pass_offset ||
6685 			    cfil_info->cfi_rcv.cfi_pending_last > entry->cfe_rcv.cfe_pass_offset) {
6686 				// haven't gotten an action from this filter, check timeout
6687 				timersub(&current_tv, &entry->cfe_last_action, &diff_time);
6688 				if (diff_time.tv_sec >= timeout) {
6689 					if (cfil_info->cfi_debug) {
6690 						cfil_info_log(LOG_INFO, cfil_info, "CFIL: flow ACTION timeout expired");
6691 					}
6692 					return true;
6693 				}
6694 			}
6695 		}
6696 	}
6697 	return false;
6698 }
6699 
6700 bool
cfil_info_buffer_threshold_exceeded(struct cfil_info * cfil_info)6701 cfil_info_buffer_threshold_exceeded(struct cfil_info *cfil_info)
6702 {
6703 	if (cfil_info == NULL) {
6704 		return false;
6705 	}
6706 
6707 	/*
6708 	 * Clean up flow if it exceeded queue thresholds
6709 	 */
6710 	if (cfil_info->cfi_snd.cfi_tail_drop_cnt ||
6711 	    cfil_info->cfi_rcv.cfi_tail_drop_cnt) {
6712 		if (cfil_info->cfi_debug) {
6713 			CFIL_LOG(LOG_INFO, "CFIL: queue threshold exceeded:mbuf max < count: %d bytes: %d > tail drop count < OUT: %d IN: %d > ",
6714 			    cfil_udp_gc_mbuf_num_max,
6715 			    cfil_udp_gc_mbuf_cnt_max,
6716 			    cfil_info->cfi_snd.cfi_tail_drop_cnt,
6717 			    cfil_info->cfi_rcv.cfi_tail_drop_cnt);
6718 			cfil_info_log(LOG_INFO, cfil_info, "CFIL: queue threshold exceeded");
6719 		}
6720 		return true;
6721 	}
6722 
6723 	return false;
6724 }
6725 
6726 static bool
cfil_dgram_gc_needed(struct socket * so,struct soflow_hash_entry * hash_entry,u_int64_t current_time)6727 cfil_dgram_gc_needed(struct socket *so, struct soflow_hash_entry *hash_entry, u_int64_t current_time)
6728 {
6729 #pragma unused(current_time)
6730 	struct cfil_info *cfil_info = NULL;
6731 
6732 	if (so == NULL || hash_entry == NULL || hash_entry->soflow_feat_ctxt == NULL) {
6733 		return false;
6734 	}
6735 	cfil_info = (struct cfil_info *) hash_entry->soflow_feat_ctxt;
6736 
6737 	cfil_rw_lock_shared(&cfil_lck_rw);
6738 
6739 	if (cfil_info_action_timed_out(cfil_info, UDP_FLOW_GC_ACTION_TO) ||
6740 	    cfil_info_buffer_threshold_exceeded(cfil_info)) {
6741 		if (cfil_info->cfi_debug) {
6742 			cfil_info_log(LOG_INFO, cfil_info, "CFIL: UDP PER-FLOW GC NEEDED");
6743 		}
6744 		cfil_rw_unlock_shared(&cfil_lck_rw);
6745 		return true;
6746 	}
6747 
6748 	cfil_rw_unlock_shared(&cfil_lck_rw);
6749 	return false;
6750 }
6751 
6752 static bool
cfil_dgram_gc_perform(struct socket * so,struct soflow_hash_entry * hash_entry)6753 cfil_dgram_gc_perform(struct socket *so, struct soflow_hash_entry *hash_entry)
6754 {
6755 	struct cfil_info *cfil_info = NULL;
6756 
6757 	if (so == NULL || hash_entry == NULL || hash_entry->soflow_feat_ctxt == NULL) {
6758 		return false;
6759 	}
6760 	cfil_info = (struct cfil_info *) hash_entry->soflow_feat_ctxt;
6761 
6762 	if (cfil_info->cfi_debug) {
6763 		cfil_info_log(LOG_INFO, cfil_info, "CFIL: UDP PER-FLOW GC PERFORM");
6764 	}
6765 
6766 	for (int kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
6767 		/* Let the filters know of the closing */
6768 		cfil_dispatch_closed_event(so, cfil_info, kcunit);
6769 	}
6770 	cfil_sock_udp_unlink_flow(so, hash_entry, cfil_info);
6771 	CFIL_INFO_FREE(cfil_info);
6772 	OSIncrementAtomic(&cfil_stats.cfs_sock_detached);
6773 	return true;
6774 }
6775 
6776 static bool
cfil_dgram_detach_entry(struct socket * so,struct soflow_hash_entry * hash_entry)6777 cfil_dgram_detach_entry(struct socket *so, struct soflow_hash_entry *hash_entry)
6778 {
6779 	struct cfil_info *cfil_info = NULL;
6780 
6781 	if (hash_entry == NULL || hash_entry->soflow_feat_ctxt == NULL) {
6782 		return true;
6783 	}
6784 	cfil_info = (struct cfil_info *) hash_entry->soflow_feat_ctxt;
6785 
6786 	if (cfil_info->cfi_debug) {
6787 		cfil_info_log(LOG_INFO, cfil_info, "CFIL: DGRAM DETACH ENTRY");
6788 	}
6789 
6790 	cfil_sock_udp_unlink_flow(so, hash_entry, cfil_info);
6791 	CFIL_INFO_FREE(cfil_info);
6792 	OSIncrementAtomic(&cfil_stats.cfs_sock_detached);
6793 
6794 	return true;
6795 }
6796 
6797 static bool
cfil_dgram_detach_db(struct socket * so,struct soflow_db * db)6798 cfil_dgram_detach_db(struct socket *so, struct soflow_db *db)
6799 {
6800 #pragma unused(db)
6801 	if (so && so->so_flags & SOF_CONTENT_FILTER) {
6802 		so->so_flags &= ~SOF_CONTENT_FILTER;
6803 		CFIL_LOG(LOG_DEBUG, "CFIL: DGRAM DETACH DB <so %llx>", (uint64_t)VM_KERNEL_ADDRPERM(so));
6804 	}
6805 	return true;
6806 }
6807 
6808 struct m_tag *
cfil_dgram_save_socket_state(struct cfil_info * cfil_info,struct mbuf * m)6809 cfil_dgram_save_socket_state(struct cfil_info *cfil_info, struct mbuf *m)
6810 {
6811 	struct m_tag *tag = NULL;
6812 	struct cfil_tag *ctag = NULL;
6813 	struct soflow_hash_entry *hash_entry = NULL;
6814 	struct inpcb *inp = NULL;
6815 
6816 	if (cfil_info == NULL || cfil_info->cfi_so == NULL ||
6817 	    cfil_info->cfi_hash_entry == NULL || m == NULL || !(m->m_flags & M_PKTHDR)) {
6818 		return NULL;
6819 	}
6820 
6821 	inp = sotoinpcb(cfil_info->cfi_so);
6822 
6823 	/* Allocate a tag */
6824 	tag = m_tag_create(KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_CFIL_UDP,
6825 	    sizeof(struct cfil_tag), M_DONTWAIT, m);
6826 
6827 	if (tag) {
6828 		ctag = (struct cfil_tag*)(tag + 1);
6829 		ctag->cfil_so_state_change_cnt = cfil_info->cfi_so->so_state_change_cnt;
6830 		ctag->cfil_so_options = cfil_info->cfi_so->so_options;
6831 		ctag->cfil_inp_flags = inp ? inp->inp_flags : 0;
6832 
6833 		hash_entry = cfil_info->cfi_hash_entry;
6834 		if (hash_entry->soflow_family == AF_INET6) {
6835 			fill_ip6_sockaddr_4_6(&ctag->cfil_faddr,
6836 			    &hash_entry->soflow_faddr.addr6,
6837 			    hash_entry->soflow_fport, hash_entry->soflow_faddr6_ifscope);
6838 		} else if (hash_entry->soflow_family == AF_INET) {
6839 			fill_ip_sockaddr_4_6(&ctag->cfil_faddr,
6840 			    hash_entry->soflow_faddr.addr46.ia46_addr4,
6841 			    hash_entry->soflow_fport);
6842 		}
6843 		m_tag_prepend(m, tag);
6844 		return tag;
6845 	}
6846 	return NULL;
6847 }
6848 
6849 struct m_tag *
cfil_dgram_get_socket_state(struct mbuf * m,uint32_t * state_change_cnt,uint32_t * options,struct sockaddr ** faddr,int * inp_flags)6850 cfil_dgram_get_socket_state(struct mbuf *m, uint32_t *state_change_cnt, uint32_t *options,
6851     struct sockaddr **faddr, int *inp_flags)
6852 {
6853 	struct m_tag *tag = NULL;
6854 	struct cfil_tag *ctag = NULL;
6855 
6856 	tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_CFIL_UDP, NULL);
6857 	if (tag) {
6858 		ctag = (struct cfil_tag *)(tag + 1);
6859 		if (state_change_cnt) {
6860 			*state_change_cnt = ctag->cfil_so_state_change_cnt;
6861 		}
6862 		if (options) {
6863 			*options = ctag->cfil_so_options;
6864 		}
6865 		if (faddr) {
6866 			*faddr = (struct sockaddr *) &ctag->cfil_faddr;
6867 		}
6868 		if (inp_flags) {
6869 			*inp_flags = ctag->cfil_inp_flags;
6870 		}
6871 
6872 		/*
6873 		 * Unlink tag and hand it over to caller.
6874 		 * Note that caller will be responsible to free it.
6875 		 */
6876 		m_tag_unlink(m, tag);
6877 		return tag;
6878 	}
6879 	return NULL;
6880 }
6881 
6882 boolean_t
cfil_dgram_peek_socket_state(struct mbuf * m,int * inp_flags)6883 cfil_dgram_peek_socket_state(struct mbuf *m, int *inp_flags)
6884 {
6885 	struct m_tag *tag = NULL;
6886 	struct cfil_tag *ctag = NULL;
6887 
6888 	tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_CFIL_UDP, NULL);
6889 	if (tag) {
6890 		ctag = (struct cfil_tag *)(tag + 1);
6891 		if (inp_flags) {
6892 			*inp_flags = ctag->cfil_inp_flags;
6893 		}
6894 		return true;
6895 	}
6896 	return false;
6897 }
6898 
6899 static int
cfil_dispatch_stats_event_locked(int kcunit,struct cfil_stats_report_buffer * buffer,uint32_t stats_count)6900 cfil_dispatch_stats_event_locked(int kcunit, struct cfil_stats_report_buffer *buffer, uint32_t stats_count)
6901 {
6902 	struct content_filter *cfc = NULL;
6903 	errno_t error = 0;
6904 	size_t msgsize = 0;
6905 
6906 	if (buffer == NULL || stats_count == 0) {
6907 		return error;
6908 	}
6909 
6910 	if (kcunit > MAX_CONTENT_FILTER) {
6911 		return error;
6912 	}
6913 
6914 	cfc = content_filters[kcunit - 1];
6915 	if (cfc == NULL) {
6916 		return error;
6917 	}
6918 
6919 	/* Would be wasteful to try */
6920 	if (cfc->cf_flags & CFF_FLOW_CONTROLLED) {
6921 		error = ENOBUFS;
6922 		goto done;
6923 	}
6924 
6925 	msgsize = sizeof(struct cfil_msg_stats_report) + (sizeof(struct cfil_msg_sock_stats) * stats_count);
6926 	buffer->msghdr.cfm_len = (uint32_t)msgsize;
6927 	buffer->msghdr.cfm_version = 1;
6928 	buffer->msghdr.cfm_type = CFM_TYPE_EVENT;
6929 	buffer->msghdr.cfm_op = CFM_OP_STATS;
6930 	buffer->msghdr.cfm_sock_id = 0;
6931 	buffer->count = stats_count;
6932 
6933 	if (cfil_log_stats) {
6934 		CFIL_LOG(LOG_DEBUG, "STATS (kcunit %d): msg size %lu - %lu %lu %lu",
6935 		    kcunit,
6936 		    (unsigned long)msgsize,
6937 		    (unsigned long)sizeof(struct cfil_msg_stats_report),
6938 		    (unsigned long)sizeof(struct cfil_msg_sock_stats),
6939 		    (unsigned long)stats_count);
6940 	}
6941 
6942 	error = ctl_enqueuedata(cfc->cf_kcref, cfc->cf_kcunit,
6943 	    buffer,
6944 	    msgsize,
6945 	    CTL_DATA_EOR);
6946 	if (error != 0) {
6947 		CFIL_LOG(LOG_ERR, "ctl_enqueuedata() failed:%d", error);
6948 		goto done;
6949 	}
6950 	OSIncrementAtomic(&cfil_stats.cfs_stats_event_ok);
6951 
6952 	if (cfil_log_stats) {
6953 		CFIL_LOG(LOG_DEBUG, "CFIL: STATS REPORT:send msg to %d", kcunit);
6954 	}
6955 done:
6956 
6957 	if (error == ENOBUFS) {
6958 		OSIncrementAtomic(
6959 			&cfil_stats.cfs_stats_event_flow_control);
6960 
6961 		if (!cfil_rw_lock_shared_to_exclusive(&cfil_lck_rw)) {
6962 			cfil_rw_lock_exclusive(&cfil_lck_rw);
6963 		}
6964 
6965 		cfc->cf_flags |= CFF_FLOW_CONTROLLED;
6966 
6967 		cfil_rw_lock_exclusive_to_shared(&cfil_lck_rw);
6968 	} else if (error != 0) {
6969 		OSIncrementAtomic(&cfil_stats.cfs_stats_event_fail);
6970 	}
6971 
6972 	return error;
6973 }
6974 
6975 static void
cfil_stats_report_thread_sleep(bool forever)6976 cfil_stats_report_thread_sleep(bool forever)
6977 {
6978 	if (cfil_log_stats) {
6979 		CFIL_LOG(LOG_DEBUG, "CFIL: STATS COLLECTION SLEEP");
6980 	}
6981 
6982 	if (forever) {
6983 		(void) assert_wait((event_t) &cfil_sock_attached_stats_count,
6984 		    THREAD_INTERRUPTIBLE);
6985 	} else {
6986 		uint64_t deadline = 0;
6987 		nanoseconds_to_absolutetime(CFIL_STATS_REPORT_RUN_INTERVAL_NSEC, &deadline);
6988 		clock_absolutetime_interval_to_deadline(deadline, &deadline);
6989 
6990 		(void) assert_wait_deadline(&cfil_sock_attached_stats_count,
6991 		    THREAD_INTERRUPTIBLE, deadline);
6992 	}
6993 }
6994 
6995 static void
cfil_stats_report_thread_func(void * v,wait_result_t w)6996 cfil_stats_report_thread_func(void *v, wait_result_t w)
6997 {
6998 #pragma unused(v, w)
6999 
7000 	ASSERT(cfil_stats_report_thread == current_thread());
7001 	thread_set_thread_name(current_thread(), "CFIL_STATS_REPORT");
7002 
7003 	// Kick off gc shortly
7004 	cfil_stats_report_thread_sleep(false);
7005 	thread_block_parameter((thread_continue_t) cfil_stats_report, NULL);
7006 	/* NOTREACHED */
7007 }
7008 
7009 static bool
cfil_stats_collect_flow_stats_for_filter(int kcunit,struct cfil_info * cfil_info,struct cfil_entry * entry,struct timeval current_tv)7010 cfil_stats_collect_flow_stats_for_filter(int kcunit,
7011     struct cfil_info *cfil_info,
7012     struct cfil_entry *entry,
7013     struct timeval current_tv)
7014 {
7015 	struct cfil_stats_report_buffer *buffer = NULL;
7016 	struct cfil_msg_sock_stats *flow_array = NULL;
7017 	struct cfil_msg_sock_stats *stats = NULL;
7018 	struct inpcb *inp = NULL;
7019 	struct timeval diff_time;
7020 	uint64_t diff_time_usecs;
7021 	int index = 0;
7022 
7023 	if (entry->cfe_stats_report_frequency == 0) {
7024 		return false;
7025 	}
7026 
7027 	buffer = global_cfil_stats_report_buffers[kcunit - 1];
7028 	if (buffer == NULL) {
7029 		CFIL_LOG(LOG_ERR, "CFIL: STATS: no buffer");
7030 		return false;
7031 	}
7032 
7033 	timersub(&current_tv, &entry->cfe_stats_report_ts, &diff_time);
7034 	diff_time_usecs = (diff_time.tv_sec * USEC_PER_SEC) + diff_time.tv_usec;
7035 
7036 	if (cfil_info->cfi_debug && cfil_log_stats) {
7037 		CFIL_LOG(LOG_DEBUG, "CFIL: STATS REPORT - elapsed time - ts %llu %llu cur ts %llu %llu diff %llu %llu(usecs %llu) @freq %llu usecs sockID %llu",
7038 		    (unsigned long long)entry->cfe_stats_report_ts.tv_sec,
7039 		    (unsigned long long)entry->cfe_stats_report_ts.tv_usec,
7040 		    (unsigned long long)current_tv.tv_sec,
7041 		    (unsigned long long)current_tv.tv_usec,
7042 		    (unsigned long long)diff_time.tv_sec,
7043 		    (unsigned long long)diff_time.tv_usec,
7044 		    (unsigned long long)diff_time_usecs,
7045 		    (unsigned long long)((entry->cfe_stats_report_frequency * NSEC_PER_MSEC) / NSEC_PER_USEC),
7046 		    cfil_info->cfi_sock_id);
7047 	}
7048 
7049 	// Compare elapsed time in usecs
7050 	if (diff_time_usecs >= (entry->cfe_stats_report_frequency * NSEC_PER_MSEC) / NSEC_PER_USEC) {
7051 		if (cfil_info->cfi_debug && cfil_log_stats) {
7052 			CFIL_LOG(LOG_DEBUG, "CFIL: STATS REPORT - in %llu reported %llu",
7053 			    cfil_info->cfi_byte_inbound_count,
7054 			    entry->cfe_byte_inbound_count_reported);
7055 			CFIL_LOG(LOG_DEBUG, "CFIL: STATS REPORT - out %llu reported %llu",
7056 			    cfil_info->cfi_byte_outbound_count,
7057 			    entry->cfe_byte_outbound_count_reported);
7058 		}
7059 		// Check if flow has new bytes that have not been reported
7060 		if (entry->cfe_byte_inbound_count_reported < cfil_info->cfi_byte_inbound_count ||
7061 		    entry->cfe_byte_outbound_count_reported < cfil_info->cfi_byte_outbound_count) {
7062 			flow_array = (struct cfil_msg_sock_stats *)&buffer->stats;
7063 			index = global_cfil_stats_counts[kcunit - 1];
7064 
7065 			stats = &flow_array[index];
7066 			stats->cfs_sock_id = cfil_info->cfi_sock_id;
7067 			stats->cfs_byte_inbound_count = cfil_info->cfi_byte_inbound_count;
7068 			stats->cfs_byte_outbound_count = cfil_info->cfi_byte_outbound_count;
7069 
7070 			if (entry->cfe_laddr_sent == false) {
7071 				/* cache it if necessary */
7072 				if (cfil_info->cfi_so_attach_laddr.sa.sa_len == 0) {
7073 					inp = cfil_info->cfi_so ? sotoinpcb(cfil_info->cfi_so) : NULL;
7074 					if (inp != NULL) {
7075 						boolean_t outgoing = (cfil_info->cfi_dir == CFS_CONNECTION_DIR_OUT);
7076 						union sockaddr_in_4_6 *src = outgoing ? &cfil_info->cfi_so_attach_laddr : NULL;
7077 						union sockaddr_in_4_6 *dst = outgoing ? NULL : &cfil_info->cfi_so_attach_laddr;
7078 						cfil_fill_event_msg_addresses(cfil_info->cfi_hash_entry, inp,
7079 						    src, dst, !IS_INP_V6(inp), outgoing);
7080 					}
7081 				}
7082 
7083 				if (cfil_info->cfi_so_attach_laddr.sa.sa_len != 0) {
7084 					stats->cfs_laddr.sin6 = cfil_info->cfi_so_attach_laddr.sin6;
7085 					entry->cfe_laddr_sent = true;
7086 				}
7087 			}
7088 
7089 			global_cfil_stats_counts[kcunit - 1]++;
7090 
7091 			entry->cfe_stats_report_ts = current_tv;
7092 			entry->cfe_byte_inbound_count_reported = cfil_info->cfi_byte_inbound_count;
7093 			entry->cfe_byte_outbound_count_reported = cfil_info->cfi_byte_outbound_count;
7094 			if (cfil_info->cfi_debug && cfil_log_stats) {
7095 				cfil_info_log(LOG_DEBUG, cfil_info, "CFIL: STATS COLLECTED");
7096 			}
7097 			CFI_ADD_TIME_LOG(cfil_info, &current_tv, &cfil_info->cfi_first_event, CFM_OP_STATS);
7098 			return true;
7099 		}
7100 	}
7101 	return false;
7102 }
7103 
7104 static void
cfil_stats_report(void * v,wait_result_t w)7105 cfil_stats_report(void *v, wait_result_t w)
7106 {
7107 #pragma unused(v, w)
7108 
7109 	struct cfil_info *cfil_info = NULL;
7110 	struct cfil_entry *entry = NULL;
7111 	struct timeval current_tv;
7112 	uint32_t flow_count = 0;
7113 	uint64_t saved_next_sock_id = 0; // Next sock id to be reported for next loop
7114 	bool flow_reported = false;
7115 
7116 	if (cfil_log_stats) {
7117 		CFIL_LOG(LOG_DEBUG, "CFIL: STATS COLLECTION RUNNING");
7118 	}
7119 
7120 	do {
7121 		// Collect all sock ids of flows that has new stats
7122 		cfil_rw_lock_shared(&cfil_lck_rw);
7123 
7124 		if (cfil_sock_attached_stats_count == 0) {
7125 			if (cfil_log_stats) {
7126 				CFIL_LOG(LOG_DEBUG, "CFIL: STATS: no flow");
7127 			}
7128 			cfil_rw_unlock_shared(&cfil_lck_rw);
7129 			goto go_sleep;
7130 		}
7131 
7132 		for (int kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
7133 			if (global_cfil_stats_report_buffers[kcunit - 1] != NULL) {
7134 				memset(global_cfil_stats_report_buffers[kcunit - 1], 0, sizeof(struct cfil_stats_report_buffer));
7135 			}
7136 			global_cfil_stats_counts[kcunit - 1] = 0;
7137 		}
7138 
7139 		microuptime(&current_tv);
7140 		flow_count = 0;
7141 
7142 		TAILQ_FOREACH(cfil_info, &cfil_sock_head_stats, cfi_link_stats) {
7143 			if (saved_next_sock_id != 0 &&
7144 			    saved_next_sock_id == cfil_info->cfi_sock_id) {
7145 				// Here is where we left off previously, start accumulating
7146 				saved_next_sock_id = 0;
7147 			}
7148 
7149 			if (saved_next_sock_id == 0) {
7150 				if (flow_count >= CFIL_STATS_REPORT_MAX_COUNT) {
7151 					// Examine a fixed number of flows each round.  Remember the current flow
7152 					// so we can start from here for next loop
7153 					saved_next_sock_id = cfil_info->cfi_sock_id;
7154 					break;
7155 				}
7156 
7157 				flow_reported = false;
7158 				for (int kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
7159 					entry = &cfil_info->cfi_entries[kcunit - 1];
7160 					if (entry->cfe_filter == NULL) {
7161 						if (cfil_info->cfi_debug && cfil_log_stats) {
7162 							CFIL_LOG(LOG_DEBUG, "CFIL: STATS REPORT - so %llx no filter",
7163 							    cfil_info->cfi_so ? (uint64_t)VM_KERNEL_ADDRPERM(cfil_info->cfi_so) : 0);
7164 						}
7165 						continue;
7166 					}
7167 
7168 					if ((entry->cfe_stats_report_frequency > 0) &&
7169 					    cfil_stats_collect_flow_stats_for_filter(kcunit, cfil_info, entry, current_tv) == true) {
7170 						flow_reported = true;
7171 					}
7172 				}
7173 				if (flow_reported == true) {
7174 					flow_count++;
7175 				}
7176 			}
7177 		}
7178 
7179 		if (flow_count > 0) {
7180 			if (cfil_log_stats) {
7181 				CFIL_LOG(LOG_DEBUG, "CFIL: STATS reporting for %d flows", flow_count);
7182 			}
7183 			for (int kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
7184 				if (global_cfil_stats_report_buffers[kcunit - 1] != NULL &&
7185 				    global_cfil_stats_counts[kcunit - 1] > 0) {
7186 					cfil_dispatch_stats_event_locked(kcunit,
7187 					    global_cfil_stats_report_buffers[kcunit - 1],
7188 					    global_cfil_stats_counts[kcunit - 1]);
7189 				}
7190 			}
7191 		} else {
7192 			cfil_rw_unlock_shared(&cfil_lck_rw);
7193 			goto go_sleep;
7194 		}
7195 
7196 		cfil_rw_unlock_shared(&cfil_lck_rw);
7197 
7198 		// Loop again if we haven't finished the whole cfil_info list
7199 	} while (saved_next_sock_id != 0);
7200 
7201 go_sleep:
7202 
7203 	// Sleep forever (until waken up) if no more flow to report
7204 	cfil_rw_lock_shared(&cfil_lck_rw);
7205 	cfil_stats_report_thread_sleep(cfil_sock_attached_stats_count == 0 ? true : false);
7206 	cfil_rw_unlock_shared(&cfil_lck_rw);
7207 	thread_block_parameter((thread_continue_t) cfil_stats_report, NULL);
7208 	/* NOTREACHED */
7209 }
7210