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