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