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