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