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