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