xref: /xnu-8020.101.4/bsd/net/content_filter.c (revision e7776783b89a353188416a9a346c6cdb4928faad)
1 /*
2  * Copyright (c) 2013-2021 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 			sin6->sin6_scope_id = ntohs(sin6->sin6_addr.s6_addr16[1]);
3514 			sin6->sin6_addr.s6_addr16[1] = 0;
3515 		}
3516 	}
3517 }
3518 
3519 static void
fill_ip_sockaddr_4_6(union sockaddr_in_4_6 * sin46,struct in_addr ip,u_int16_t port)3520 fill_ip_sockaddr_4_6(union sockaddr_in_4_6 *sin46,
3521     struct in_addr ip, u_int16_t port)
3522 {
3523 	if (sin46 == NULL) {
3524 		return;
3525 	}
3526 
3527 	struct sockaddr_in *sin = &sin46->sin;
3528 
3529 	sin->sin_family = AF_INET;
3530 	sin->sin_len = sizeof(*sin);
3531 	sin->sin_port = port;
3532 	sin->sin_addr.s_addr = ip.s_addr;
3533 }
3534 
3535 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)3536 cfil_get_flow_address_v6(struct soflow_hash_entry *entry, struct inpcb *inp,
3537     struct in6_addr **laddr, struct in6_addr **faddr,
3538     u_int16_t *lport, u_int16_t *fport)
3539 {
3540 	if (entry != NULL) {
3541 		*laddr = &entry->soflow_laddr.addr6;
3542 		*faddr = &entry->soflow_faddr.addr6;
3543 		*lport = entry->soflow_lport;
3544 		*fport = entry->soflow_fport;
3545 	} else {
3546 		*laddr = &inp->in6p_laddr;
3547 		*faddr = &inp->in6p_faddr;
3548 		*lport = inp->inp_lport;
3549 		*fport = inp->inp_fport;
3550 	}
3551 }
3552 
3553 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)3554 cfil_get_flow_address(struct soflow_hash_entry *entry, struct inpcb *inp,
3555     struct in_addr *laddr, struct in_addr *faddr,
3556     u_int16_t *lport, u_int16_t *fport)
3557 {
3558 	if (entry != NULL) {
3559 		*laddr = entry->soflow_laddr.addr46.ia46_addr4;
3560 		*faddr = entry->soflow_faddr.addr46.ia46_addr4;
3561 		*lport = entry->soflow_lport;
3562 		*fport = entry->soflow_fport;
3563 	} else {
3564 		*laddr = inp->inp_laddr;
3565 		*faddr = inp->inp_faddr;
3566 		*lport = inp->inp_lport;
3567 		*fport = inp->inp_fport;
3568 	}
3569 }
3570 
3571 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)3572 cfil_dispatch_data_event(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing,
3573     struct mbuf *data, unsigned int copyoffset, unsigned int copylen)
3574 {
3575 	errno_t error = 0;
3576 	struct mbuf *copy = NULL;
3577 	struct mbuf *msg = NULL;
3578 	unsigned int one = 1;
3579 	struct cfil_msg_data_event *data_req;
3580 	size_t hdrsize;
3581 	struct inpcb *inp = (struct inpcb *)so->so_pcb;
3582 	struct cfil_entry *entry;
3583 	struct cfe_buf *entrybuf;
3584 	struct content_filter *cfc;
3585 	struct timeval tv;
3586 	int inp_flags = 0;
3587 
3588 	cfil_rw_lock_shared(&cfil_lck_rw);
3589 
3590 	entry = &cfil_info->cfi_entries[kcunit - 1];
3591 	if (outgoing) {
3592 		entrybuf = &entry->cfe_snd;
3593 	} else {
3594 		entrybuf = &entry->cfe_rcv;
3595 	}
3596 
3597 	cfc = entry->cfe_filter;
3598 	if (cfc == NULL) {
3599 		goto done;
3600 	}
3601 
3602 	data = cfil_data_start(data);
3603 	if (data == NULL) {
3604 		CFIL_LOG(LOG_ERR, "No data start");
3605 		goto done;
3606 	}
3607 
3608 	CFIL_LOG(LOG_INFO, "so %llx kcunit %u outgoing %d",
3609 	    (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit, outgoing);
3610 
3611 	socket_lock_assert_owned(so);
3612 
3613 	/* Would be wasteful to try */
3614 	if (cfc->cf_flags & CFF_FLOW_CONTROLLED) {
3615 		error = ENOBUFS;
3616 		goto done;
3617 	}
3618 
3619 	/* Make a copy of the data to pass to kernel control socket */
3620 	copy = m_copym_mode(data, copyoffset, copylen, M_DONTWAIT,
3621 	    M_COPYM_NOOP_HDR);
3622 	if (copy == NULL) {
3623 		CFIL_LOG(LOG_ERR, "m_copym_mode() failed");
3624 		error = ENOMEM;
3625 		goto done;
3626 	}
3627 
3628 	/* We need an mbuf packet for the message header */
3629 	hdrsize = sizeof(struct cfil_msg_data_event);
3630 	error = mbuf_allocpacket(MBUF_DONTWAIT, hdrsize, &one, &msg);
3631 	if (error != 0) {
3632 		CFIL_LOG(LOG_ERR, "mbuf_allocpacket() failed");
3633 		m_freem(copy);
3634 		/*
3635 		 * ENOBUFS is to indicate flow control
3636 		 */
3637 		error = ENOMEM;
3638 		goto done;
3639 	}
3640 	mbuf_setlen(msg, hdrsize);
3641 	mbuf_pkthdr_setlen(msg, hdrsize + copylen);
3642 	msg->m_next = copy;
3643 	data_req = (struct cfil_msg_data_event *)mbuf_data(msg);
3644 	bzero(data_req, hdrsize);
3645 	data_req->cfd_msghdr.cfm_len = (uint32_t)hdrsize + copylen;
3646 	data_req->cfd_msghdr.cfm_version = 1;
3647 	data_req->cfd_msghdr.cfm_type = CFM_TYPE_EVENT;
3648 	data_req->cfd_msghdr.cfm_op =
3649 	    outgoing ? CFM_OP_DATA_OUT : CFM_OP_DATA_IN;
3650 	data_req->cfd_msghdr.cfm_sock_id =
3651 	    entry->cfe_cfil_info->cfi_sock_id;
3652 	data_req->cfd_start_offset = entrybuf->cfe_peeked;
3653 	data_req->cfd_end_offset = entrybuf->cfe_peeked + copylen;
3654 
3655 	data_req->cfd_flags = 0;
3656 	if (OPTIONAL_IP_HEADER(so)) {
3657 		/*
3658 		 * For non-UDP/TCP traffic, indicate to filters if optional
3659 		 * IP header is present:
3660 		 *      outgoing - indicate according to INP_HDRINCL flag
3661 		 *      incoming - For IPv4 only, stripping of IP header is
3662 		 *                 optional.  But for CFIL, we delay stripping
3663 		 *                 at rip_input.  So CFIL always expects IP
3664 		 *                 frames. IP header will be stripped according
3665 		 *                 to INP_STRIPHDR flag later at reinjection.
3666 		 */
3667 		if ((!outgoing && !IS_INP_V6(inp)) ||
3668 		    (outgoing && cfil_dgram_peek_socket_state(data, &inp_flags) && (inp_flags & INP_HDRINCL))) {
3669 			data_req->cfd_flags |= CFD_DATA_FLAG_IP_HEADER;
3670 		}
3671 	}
3672 
3673 	/*
3674 	 * Copy address/port into event msg.
3675 	 * For non connected sockets need to copy addresses from passed
3676 	 * parameters
3677 	 */
3678 	cfil_fill_event_msg_addresses(cfil_info->cfi_hash_entry, inp,
3679 	    &data_req->cfc_src, &data_req->cfc_dst,
3680 	    !IS_INP_V6(inp), outgoing);
3681 
3682 	if (cfil_info->cfi_debug && cfil_log_data) {
3683 		cfil_info_log(LOG_DEBUG, cfil_info, "CFIL: SENDING DATA UP");
3684 	}
3685 
3686 	if (cfil_info->cfi_isSignatureLatest == false) {
3687 		cfil_dispatch_data_event_sign(entry->cfe_filter->cf_crypto_state, so, cfil_info, data_req);
3688 	}
3689 
3690 	microuptime(&tv);
3691 	CFI_ADD_TIME_LOG(cfil_info, &tv, &cfil_info->cfi_first_event, data_req->cfd_msghdr.cfm_op);
3692 
3693 	/* Pass the message to the content filter */
3694 	error = ctl_enqueuembuf(entry->cfe_filter->cf_kcref,
3695 	    entry->cfe_filter->cf_kcunit,
3696 	    msg, CTL_DATA_EOR);
3697 	if (error != 0) {
3698 		CFIL_LOG(LOG_ERR, "ctl_enqueuembuf() failed: %d", error);
3699 		mbuf_freem(msg);
3700 		goto done;
3701 	}
3702 	entry->cfe_flags &= ~CFEF_FLOW_CONTROLLED;
3703 	OSIncrementAtomic(&cfil_stats.cfs_data_event_ok);
3704 
3705 	if (cfil_info->cfi_debug && cfil_log_data) {
3706 		CFIL_LOG(LOG_DEBUG, "CFIL: VERDICT ACTION: so %llx sockID %llu outgoing %d: mbuf %llx copyoffset %u copylen %u (%s)",
3707 		    (uint64_t)VM_KERNEL_ADDRPERM(so), cfil_info->cfi_sock_id, outgoing, (uint64_t)VM_KERNEL_ADDRPERM(data), copyoffset, copylen,
3708 		    data_req->cfd_flags & CFD_DATA_FLAG_IP_HEADER ? "IP HDR" : "NO IP HDR");
3709 	}
3710 
3711 done:
3712 	if (error == ENOBUFS) {
3713 		entry->cfe_flags |= CFEF_FLOW_CONTROLLED;
3714 		OSIncrementAtomic(
3715 			&cfil_stats.cfs_data_event_flow_control);
3716 
3717 		if (!cfil_rw_lock_shared_to_exclusive(&cfil_lck_rw)) {
3718 			cfil_rw_lock_exclusive(&cfil_lck_rw);
3719 		}
3720 
3721 		cfc->cf_flags |= CFF_FLOW_CONTROLLED;
3722 
3723 		cfil_rw_unlock_exclusive(&cfil_lck_rw);
3724 	} else {
3725 		if (error != 0) {
3726 			OSIncrementAtomic(&cfil_stats.cfs_data_event_fail);
3727 		}
3728 
3729 		cfil_rw_unlock_shared(&cfil_lck_rw);
3730 	}
3731 	return error;
3732 }
3733 
3734 /*
3735  * Process the queue of data waiting to be delivered to content filter
3736  */
3737 static int
cfil_data_service_ctl_q(struct socket * so,struct cfil_info * cfil_info,uint32_t kcunit,int outgoing)3738 cfil_data_service_ctl_q(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing)
3739 {
3740 	errno_t error = 0;
3741 	struct mbuf *data, *tmp = NULL;
3742 	unsigned int datalen = 0, copylen = 0, copyoffset = 0;
3743 	struct cfil_entry *entry;
3744 	struct cfe_buf *entrybuf;
3745 	uint64_t currentoffset = 0;
3746 
3747 	if (cfil_info == NULL) {
3748 		return 0;
3749 	}
3750 
3751 	CFIL_LOG(LOG_INFO, "so %llx kcunit %u outgoing %d",
3752 	    (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit, outgoing);
3753 
3754 	socket_lock_assert_owned(so);
3755 
3756 	entry = &cfil_info->cfi_entries[kcunit - 1];
3757 	if (outgoing) {
3758 		entrybuf = &entry->cfe_snd;
3759 	} else {
3760 		entrybuf = &entry->cfe_rcv;
3761 	}
3762 
3763 	/* Send attached message if not yet done */
3764 	if ((entry->cfe_flags & CFEF_SENT_SOCK_ATTACHED) == 0) {
3765 		error = cfil_dispatch_attach_event(so, cfil_info, CFI_ENTRY_KCUNIT(cfil_info, entry),
3766 		    cfil_info->cfi_dir);
3767 		if (error != 0) {
3768 			/* We can recover from flow control */
3769 			if (error == ENOBUFS || error == ENOMEM) {
3770 				error = 0;
3771 			}
3772 			goto done;
3773 		}
3774 	} else if ((entry->cfe_flags & CFEF_DATA_START) == 0) {
3775 		OSIncrementAtomic(&cfil_stats.cfs_ctl_q_not_started);
3776 		goto done;
3777 	}
3778 
3779 	if (cfil_info->cfi_debug && cfil_log_data) {
3780 		CFIL_LOG(LOG_DEBUG, "CFIL: SERVICE CTL-Q: pass_offset %llu peeked %llu peek_offset %llu",
3781 		    entrybuf->cfe_pass_offset,
3782 		    entrybuf->cfe_peeked,
3783 		    entrybuf->cfe_peek_offset);
3784 	}
3785 
3786 	/* Move all data that can pass */
3787 	while ((data = cfil_queue_first(&entrybuf->cfe_ctl_q)) != NULL &&
3788 	    entrybuf->cfe_ctl_q.q_start < entrybuf->cfe_pass_offset) {
3789 		datalen = cfil_data_length(data, NULL, NULL);
3790 		tmp = data;
3791 
3792 		if (entrybuf->cfe_ctl_q.q_start + datalen <=
3793 		    entrybuf->cfe_pass_offset) {
3794 			/*
3795 			 * The first mbuf can fully pass
3796 			 */
3797 			copylen = datalen;
3798 		} else {
3799 			/*
3800 			 * The first mbuf can partially pass
3801 			 */
3802 			copylen = (unsigned int)(entrybuf->cfe_pass_offset - entrybuf->cfe_ctl_q.q_start);
3803 		}
3804 		VERIFY(copylen <= datalen);
3805 
3806 		if (cfil_info->cfi_debug && cfil_log_data) {
3807 			CFIL_LOG(LOG_DEBUG,
3808 			    "CFIL: SERVICE CTL-Q PASSING: %llx first %llu peeked %llu pass %llu peek %llu"
3809 			    "datalen %u copylen %u",
3810 			    (uint64_t)VM_KERNEL_ADDRPERM(tmp),
3811 			    entrybuf->cfe_ctl_q.q_start,
3812 			    entrybuf->cfe_peeked,
3813 			    entrybuf->cfe_pass_offset,
3814 			    entrybuf->cfe_peek_offset,
3815 			    datalen, copylen);
3816 		}
3817 
3818 		/*
3819 		 * Data that passes has been peeked at explicitly or
3820 		 * implicitly
3821 		 */
3822 		if (entrybuf->cfe_ctl_q.q_start + copylen >
3823 		    entrybuf->cfe_peeked) {
3824 			entrybuf->cfe_peeked =
3825 			    entrybuf->cfe_ctl_q.q_start + copylen;
3826 		}
3827 		/*
3828 		 * Stop on partial pass
3829 		 */
3830 		if (copylen < datalen) {
3831 			break;
3832 		}
3833 
3834 		/* All good, move full data from ctl queue to pending queue */
3835 		cfil_queue_remove(&entrybuf->cfe_ctl_q, data, datalen);
3836 
3837 		cfil_queue_enqueue(&entrybuf->cfe_pending_q, data, datalen);
3838 		if (outgoing) {
3839 			OSAddAtomic64(datalen,
3840 			    &cfil_stats.cfs_pending_q_out_enqueued);
3841 		} else {
3842 			OSAddAtomic64(datalen,
3843 			    &cfil_stats.cfs_pending_q_in_enqueued);
3844 		}
3845 	}
3846 	CFIL_INFO_VERIFY(cfil_info);
3847 	if (tmp != NULL) {
3848 		CFIL_LOG(LOG_DEBUG,
3849 		    "%llx first %llu peeked %llu pass %llu peek %llu"
3850 		    "datalen %u copylen %u",
3851 		    (uint64_t)VM_KERNEL_ADDRPERM(tmp),
3852 		    entrybuf->cfe_ctl_q.q_start,
3853 		    entrybuf->cfe_peeked,
3854 		    entrybuf->cfe_pass_offset,
3855 		    entrybuf->cfe_peek_offset,
3856 		    datalen, copylen);
3857 	}
3858 	tmp = NULL;
3859 
3860 	/* Now deal with remaining data the filter wants to peek at */
3861 	for (data = cfil_queue_first(&entrybuf->cfe_ctl_q),
3862 	    currentoffset = entrybuf->cfe_ctl_q.q_start;
3863 	    data != NULL && currentoffset < entrybuf->cfe_peek_offset;
3864 	    data = cfil_queue_next(&entrybuf->cfe_ctl_q, data),
3865 	    currentoffset += datalen) {
3866 		datalen = cfil_data_length(data, NULL, NULL);
3867 		tmp = data;
3868 
3869 		/* We've already peeked at this mbuf */
3870 		if (currentoffset + datalen <= entrybuf->cfe_peeked) {
3871 			continue;
3872 		}
3873 		/*
3874 		 * The data in the first mbuf may have been
3875 		 * partially peeked at
3876 		 */
3877 		copyoffset = (unsigned int)(entrybuf->cfe_peeked - currentoffset);
3878 		VERIFY(copyoffset < datalen);
3879 		copylen = datalen - copyoffset;
3880 		VERIFY(copylen <= datalen);
3881 		/*
3882 		 * Do not copy more than needed
3883 		 */
3884 		if (currentoffset + copyoffset + copylen >
3885 		    entrybuf->cfe_peek_offset) {
3886 			copylen = (unsigned int)(entrybuf->cfe_peek_offset -
3887 			    (currentoffset + copyoffset));
3888 		}
3889 
3890 		if (cfil_info->cfi_debug && cfil_log_data) {
3891 			CFIL_LOG(LOG_DEBUG,
3892 			    "CFIL: SERVICE CTL-Q PEEKING: %llx current %llu peeked %llu pass %llu peek %llu "
3893 			    "datalen %u copylen %u copyoffset %u",
3894 			    (uint64_t)VM_KERNEL_ADDRPERM(tmp),
3895 			    currentoffset,
3896 			    entrybuf->cfe_peeked,
3897 			    entrybuf->cfe_pass_offset,
3898 			    entrybuf->cfe_peek_offset,
3899 			    datalen, copylen, copyoffset);
3900 		}
3901 
3902 		/*
3903 		 * Stop if there is nothing more to peek at
3904 		 */
3905 		if (copylen == 0) {
3906 			break;
3907 		}
3908 		/*
3909 		 * Let the filter get a peek at this span of data
3910 		 */
3911 		error = cfil_dispatch_data_event(so, cfil_info, kcunit,
3912 		    outgoing, data, copyoffset, copylen);
3913 		if (error != 0) {
3914 			/* On error, leave data in ctl_q */
3915 			break;
3916 		}
3917 		entrybuf->cfe_peeked += copylen;
3918 		if (outgoing) {
3919 			OSAddAtomic64(copylen,
3920 			    &cfil_stats.cfs_ctl_q_out_peeked);
3921 		} else {
3922 			OSAddAtomic64(copylen,
3923 			    &cfil_stats.cfs_ctl_q_in_peeked);
3924 		}
3925 
3926 		/* Stop when data could not be fully peeked at */
3927 		if (copylen + copyoffset < datalen) {
3928 			break;
3929 		}
3930 	}
3931 	CFIL_INFO_VERIFY(cfil_info);
3932 	if (tmp != NULL) {
3933 		CFIL_LOG(LOG_DEBUG,
3934 		    "%llx first %llu peeked %llu pass %llu peek %llu"
3935 		    "datalen %u copylen %u copyoffset %u",
3936 		    (uint64_t)VM_KERNEL_ADDRPERM(tmp),
3937 		    currentoffset,
3938 		    entrybuf->cfe_peeked,
3939 		    entrybuf->cfe_pass_offset,
3940 		    entrybuf->cfe_peek_offset,
3941 		    datalen, copylen, copyoffset);
3942 	}
3943 
3944 	/*
3945 	 * Process data that has passed the filter
3946 	 */
3947 	error = cfil_service_pending_queue(so, cfil_info, kcunit, outgoing);
3948 	if (error != 0) {
3949 		CFIL_LOG(LOG_ERR, "cfil_service_pending_queue() error %d",
3950 		    error);
3951 		goto done;
3952 	}
3953 
3954 	/*
3955 	 * Dispatch disconnect events that could not be sent
3956 	 */
3957 	if (cfil_info == NULL) {
3958 		goto done;
3959 	} else if (outgoing) {
3960 		if ((cfil_info->cfi_flags & CFIF_SHUT_WR) &&
3961 		    !(entry->cfe_flags & CFEF_SENT_DISCONNECT_OUT)) {
3962 			cfil_dispatch_disconnect_event(so, cfil_info, kcunit, 1);
3963 		}
3964 	} else {
3965 		if ((cfil_info->cfi_flags & CFIF_SHUT_RD) &&
3966 		    !(entry->cfe_flags & CFEF_SENT_DISCONNECT_IN)) {
3967 			cfil_dispatch_disconnect_event(so, cfil_info, kcunit, 0);
3968 		}
3969 	}
3970 
3971 done:
3972 	CFIL_LOG(LOG_DEBUG,
3973 	    "first %llu peeked %llu pass %llu peek %llu",
3974 	    entrybuf->cfe_ctl_q.q_start,
3975 	    entrybuf->cfe_peeked,
3976 	    entrybuf->cfe_pass_offset,
3977 	    entrybuf->cfe_peek_offset);
3978 
3979 	CFIL_INFO_VERIFY(cfil_info);
3980 	return error;
3981 }
3982 
3983 /*
3984  * cfil_data_filter()
3985  *
3986  * Process data for a content filter installed on a socket
3987  */
3988 int
cfil_data_filter(struct socket * so,struct cfil_info * cfil_info,uint32_t kcunit,int outgoing,struct mbuf * data,uint32_t datalen)3989 cfil_data_filter(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing,
3990     struct mbuf *data, uint32_t datalen)
3991 {
3992 	errno_t error = 0;
3993 	struct cfil_entry *entry;
3994 	struct cfe_buf *entrybuf;
3995 
3996 	CFIL_LOG(LOG_INFO, "so %llx kcunit %u outgoing %d",
3997 	    (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit, outgoing);
3998 
3999 	socket_lock_assert_owned(so);
4000 
4001 	entry = &cfil_info->cfi_entries[kcunit - 1];
4002 	if (outgoing) {
4003 		entrybuf = &entry->cfe_snd;
4004 	} else {
4005 		entrybuf = &entry->cfe_rcv;
4006 	}
4007 
4008 	/* Are we attached to the filter? */
4009 	if (entry->cfe_filter == NULL) {
4010 		error = 0;
4011 		goto done;
4012 	}
4013 
4014 	/* Dispatch to filters */
4015 	cfil_queue_enqueue(&entrybuf->cfe_ctl_q, data, datalen);
4016 	if (outgoing) {
4017 		OSAddAtomic64(datalen,
4018 		    &cfil_stats.cfs_ctl_q_out_enqueued);
4019 	} else {
4020 		OSAddAtomic64(datalen,
4021 		    &cfil_stats.cfs_ctl_q_in_enqueued);
4022 	}
4023 
4024 	error = cfil_data_service_ctl_q(so, cfil_info, kcunit, outgoing);
4025 	if (error != 0) {
4026 		CFIL_LOG(LOG_ERR, "cfil_data_service_ctl_q() error %d",
4027 		    error);
4028 	}
4029 	/*
4030 	 * We have to return EJUSTRETURN in all cases to avoid double free
4031 	 * by socket layer
4032 	 */
4033 	error = EJUSTRETURN;
4034 done:
4035 	CFIL_INFO_VERIFY(cfil_info);
4036 
4037 	CFIL_LOG(LOG_INFO, "return %d", error);
4038 	return error;
4039 }
4040 
4041 /*
4042  * cfil_service_inject_queue() re-inject data that passed the
4043  * content filters
4044  */
4045 static int
cfil_service_inject_queue(struct socket * so,struct cfil_info * cfil_info,int outgoing)4046 cfil_service_inject_queue(struct socket *so, struct cfil_info *cfil_info, int outgoing)
4047 {
4048 	mbuf_t data;
4049 	unsigned int datalen;
4050 	int mbcnt = 0;
4051 	int mbnum = 0;
4052 	errno_t error = 0;
4053 	struct cfi_buf *cfi_buf;
4054 	struct cfil_queue *inject_q;
4055 	int need_rwakeup = 0;
4056 	int count = 0;
4057 	struct inpcb *inp = NULL;
4058 	struct ip *ip = NULL;
4059 	unsigned int hlen;
4060 
4061 	if (cfil_info == NULL) {
4062 		return 0;
4063 	}
4064 
4065 	socket_lock_assert_owned(so);
4066 
4067 	if (so->so_state & SS_DEFUNCT) {
4068 		return 0;
4069 	}
4070 
4071 	if (outgoing) {
4072 		cfi_buf = &cfil_info->cfi_snd;
4073 		cfil_info->cfi_flags &= ~CFIF_RETRY_INJECT_OUT;
4074 	} else {
4075 		cfi_buf = &cfil_info->cfi_rcv;
4076 		cfil_info->cfi_flags &= ~CFIF_RETRY_INJECT_IN;
4077 	}
4078 	inject_q = &cfi_buf->cfi_inject_q;
4079 
4080 	if (cfil_queue_empty(inject_q)) {
4081 		return 0;
4082 	}
4083 
4084 	if (cfil_info->cfi_debug && cfil_log_data) {
4085 		CFIL_LOG(LOG_DEBUG, "CFIL: SERVICE INJECT-Q: <so %llx> outgoing %d queue len %llu",
4086 		    (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing, cfil_queue_len(inject_q));
4087 	}
4088 
4089 	while ((data = cfil_queue_first(inject_q)) != NULL) {
4090 		datalen = cfil_data_length(data, &mbcnt, &mbnum);
4091 
4092 		if (cfil_info->cfi_debug && cfil_log_data) {
4093 			CFIL_LOG(LOG_DEBUG, "CFIL: SERVICE INJECT-Q: <so %llx> data %llx datalen %u (mbcnt %u)",
4094 			    (uint64_t)VM_KERNEL_ADDRPERM(so), (uint64_t)VM_KERNEL_ADDRPERM(data), datalen, mbcnt);
4095 		}
4096 
4097 		/* Remove data from queue and adjust stats */
4098 		cfil_queue_remove(inject_q, data, datalen);
4099 		cfi_buf->cfi_pending_first += datalen;
4100 		cfi_buf->cfi_pending_mbcnt -= mbcnt;
4101 		cfi_buf->cfi_pending_mbnum -= mbnum;
4102 		cfil_info_buf_verify(cfi_buf);
4103 
4104 		if (outgoing) {
4105 			error = sosend_reinject(so, NULL, data, NULL, 0);
4106 			if (error != 0) {
4107 				cfil_info_log(LOG_ERR, cfil_info, "CFIL: Error: sosend_reinject() failed");
4108 				CFIL_LOG(LOG_ERR, "CFIL: sosend() failed %d", error);
4109 				break;
4110 			}
4111 			// At least one injection succeeded, need to wake up pending threads.
4112 			need_rwakeup = 1;
4113 		} else {
4114 			data->m_flags |= M_SKIPCFIL;
4115 
4116 			/*
4117 			 * NOTE: We currently only support TCP, UDP, ICMP,
4118 			 * ICMPv6 and RAWIP.  For MPTCP and message TCP we'll
4119 			 * need to call the appropriate sbappendxxx()
4120 			 * of fix sock_inject_data_in()
4121 			 */
4122 			if (NEED_DGRAM_FLOW_TRACKING(so)) {
4123 				if (OPTIONAL_IP_HEADER(so)) {
4124 					inp = sotoinpcb(so);
4125 					if (inp && (inp->inp_flags & INP_STRIPHDR)) {
4126 						mbuf_t data_start = cfil_data_start(data);
4127 						if (data_start != NULL && (data_start->m_flags & M_PKTHDR)) {
4128 							ip = mtod(data_start, struct ip *);
4129 							hlen = IP_VHL_HL(ip->ip_vhl) << 2;
4130 							data_start->m_len -= hlen;
4131 							data_start->m_pkthdr.len -= hlen;
4132 							data_start->m_data += hlen;
4133 						}
4134 					}
4135 				}
4136 
4137 				if (sbappendchain(&so->so_rcv, data, 0)) {
4138 					need_rwakeup = 1;
4139 				}
4140 			} else {
4141 				if (sbappendstream(&so->so_rcv, data)) {
4142 					need_rwakeup = 1;
4143 				}
4144 			}
4145 		}
4146 
4147 		if (outgoing) {
4148 			OSAddAtomic64(datalen,
4149 			    &cfil_stats.cfs_inject_q_out_passed);
4150 		} else {
4151 			OSAddAtomic64(datalen,
4152 			    &cfil_stats.cfs_inject_q_in_passed);
4153 		}
4154 
4155 		count++;
4156 	}
4157 
4158 	if (cfil_info->cfi_debug && cfil_log_data) {
4159 		CFIL_LOG(LOG_DEBUG, "CFIL: SERVICE INJECT-Q: <so %llx> injected %d",
4160 		    (uint64_t)VM_KERNEL_ADDRPERM(so), count);
4161 	}
4162 
4163 	/* A single wakeup is for several packets is more efficient */
4164 	if (need_rwakeup) {
4165 		if (outgoing == TRUE) {
4166 			sowwakeup(so);
4167 		} else {
4168 			sorwakeup(so);
4169 		}
4170 	}
4171 
4172 	if (error != 0 && cfil_info) {
4173 		if (error == ENOBUFS) {
4174 			OSIncrementAtomic(&cfil_stats.cfs_inject_q_nobufs);
4175 		}
4176 		if (error == ENOMEM) {
4177 			OSIncrementAtomic(&cfil_stats.cfs_inject_q_nomem);
4178 		}
4179 
4180 		if (outgoing) {
4181 			cfil_info->cfi_flags |= CFIF_RETRY_INJECT_OUT;
4182 			OSIncrementAtomic(&cfil_stats.cfs_inject_q_out_fail);
4183 		} else {
4184 			cfil_info->cfi_flags |= CFIF_RETRY_INJECT_IN;
4185 			OSIncrementAtomic(&cfil_stats.cfs_inject_q_in_fail);
4186 		}
4187 	}
4188 
4189 	/*
4190 	 * Notify
4191 	 */
4192 	if (cfil_info && (cfil_info->cfi_flags & CFIF_SHUT_WR)) {
4193 		cfil_sock_notify_shutdown(so, SHUT_WR);
4194 		if (cfil_sock_data_pending(&so->so_snd) == 0) {
4195 			soshutdownlock_final(so, SHUT_WR);
4196 		}
4197 	}
4198 	if (cfil_info && (cfil_info->cfi_flags & CFIF_CLOSE_WAIT)) {
4199 		if (cfil_filters_attached(so) == 0) {
4200 			CFIL_LOG(LOG_INFO, "so %llx waking",
4201 			    (uint64_t)VM_KERNEL_ADDRPERM(so));
4202 			wakeup((caddr_t)cfil_info);
4203 		}
4204 	}
4205 
4206 	CFIL_INFO_VERIFY(cfil_info);
4207 
4208 	return error;
4209 }
4210 
4211 static int
cfil_service_pending_queue(struct socket * so,struct cfil_info * cfil_info,uint32_t kcunit,int outgoing)4212 cfil_service_pending_queue(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing)
4213 {
4214 	uint64_t passlen, curlen;
4215 	mbuf_t data;
4216 	unsigned int datalen;
4217 	errno_t error = 0;
4218 	struct cfil_entry *entry;
4219 	struct cfe_buf *entrybuf;
4220 	struct cfil_queue *pending_q;
4221 	struct cfil_entry *iter_entry = NULL;
4222 
4223 	CFIL_LOG(LOG_INFO, "so %llx kcunit %u outgoing %d",
4224 	    (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit, outgoing);
4225 
4226 	socket_lock_assert_owned(so);
4227 
4228 	entry = &cfil_info->cfi_entries[kcunit - 1];
4229 	if (outgoing) {
4230 		entrybuf = &entry->cfe_snd;
4231 	} else {
4232 		entrybuf = &entry->cfe_rcv;
4233 	}
4234 
4235 	pending_q = &entrybuf->cfe_pending_q;
4236 
4237 	passlen = entrybuf->cfe_pass_offset - pending_q->q_start;
4238 
4239 	if (cfil_queue_empty(pending_q)) {
4240 		for (iter_entry = SLIST_NEXT(entry, cfe_order_link);
4241 		    iter_entry != NULL;
4242 		    iter_entry = SLIST_NEXT(iter_entry, cfe_order_link)) {
4243 			error = cfil_data_service_ctl_q(so, cfil_info, CFI_ENTRY_KCUNIT(cfil_info, iter_entry), outgoing);
4244 			/* 0 means passed so we can continue */
4245 			if (error != 0) {
4246 				break;
4247 			}
4248 		}
4249 		goto done;
4250 	}
4251 
4252 	/*
4253 	 * Locate the chunks of data that we can pass to the next filter
4254 	 * A data chunk must be on mbuf boundaries
4255 	 */
4256 	curlen = 0;
4257 	while ((data = cfil_queue_first(pending_q)) != NULL) {
4258 		datalen = cfil_data_length(data, NULL, NULL);
4259 
4260 		if (cfil_info->cfi_debug && cfil_log_data) {
4261 			CFIL_LOG(LOG_DEBUG,
4262 			    "CFIL: SERVICE PENDING-Q: data %llx datalen %u passlen %llu curlen %llu",
4263 			    (uint64_t)VM_KERNEL_ADDRPERM(data), datalen,
4264 			    passlen, curlen);
4265 		}
4266 
4267 		if (curlen + datalen > passlen) {
4268 			break;
4269 		}
4270 
4271 		cfil_queue_remove(pending_q, data, datalen);
4272 
4273 		curlen += datalen;
4274 
4275 		for (iter_entry = SLIST_NEXT(entry, cfe_order_link);
4276 		    iter_entry != NULL;
4277 		    iter_entry = SLIST_NEXT(iter_entry, cfe_order_link)) {
4278 			error = cfil_data_filter(so, cfil_info, CFI_ENTRY_KCUNIT(cfil_info, iter_entry), outgoing,
4279 			    data, datalen);
4280 			/* 0 means passed so we can continue */
4281 			if (error != 0) {
4282 				break;
4283 			}
4284 		}
4285 		/* When data has passed all filters, re-inject */
4286 		if (error == 0) {
4287 			if (outgoing) {
4288 				cfil_queue_enqueue(
4289 					&cfil_info->cfi_snd.cfi_inject_q,
4290 					data, datalen);
4291 				OSAddAtomic64(datalen,
4292 				    &cfil_stats.cfs_inject_q_out_enqueued);
4293 			} else {
4294 				cfil_queue_enqueue(
4295 					&cfil_info->cfi_rcv.cfi_inject_q,
4296 					data, datalen);
4297 				OSAddAtomic64(datalen,
4298 				    &cfil_stats.cfs_inject_q_in_enqueued);
4299 			}
4300 		}
4301 	}
4302 
4303 done:
4304 	CFIL_INFO_VERIFY(cfil_info);
4305 
4306 	return error;
4307 }
4308 
4309 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)4310 cfil_update_data_offsets(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing,
4311     uint64_t pass_offset, uint64_t peek_offset)
4312 {
4313 	errno_t error = 0;
4314 	struct cfil_entry *entry = NULL;
4315 	struct cfe_buf *entrybuf;
4316 	int updated = 0;
4317 
4318 	CFIL_LOG(LOG_INFO, "pass %llu peek %llu", pass_offset, peek_offset);
4319 
4320 	socket_lock_assert_owned(so);
4321 
4322 	if (cfil_info == NULL) {
4323 		CFIL_LOG(LOG_ERR, "so %llx cfil detached",
4324 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
4325 		error = 0;
4326 		goto done;
4327 	} else if (cfil_info->cfi_flags & CFIF_DROP) {
4328 		CFIL_LOG(LOG_ERR, "so %llx drop set",
4329 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
4330 		error = EPIPE;
4331 		goto done;
4332 	}
4333 
4334 	entry = &cfil_info->cfi_entries[kcunit - 1];
4335 	if (outgoing) {
4336 		entrybuf = &entry->cfe_snd;
4337 	} else {
4338 		entrybuf = &entry->cfe_rcv;
4339 	}
4340 
4341 	/* Record updated offsets for this content filter */
4342 	if (pass_offset > entrybuf->cfe_pass_offset) {
4343 		entrybuf->cfe_pass_offset = pass_offset;
4344 
4345 		if (entrybuf->cfe_peek_offset < entrybuf->cfe_pass_offset) {
4346 			entrybuf->cfe_peek_offset = entrybuf->cfe_pass_offset;
4347 		}
4348 		updated = 1;
4349 	} else {
4350 		CFIL_LOG(LOG_INFO, "pass_offset %llu <= cfe_pass_offset %llu",
4351 		    pass_offset, entrybuf->cfe_pass_offset);
4352 	}
4353 	/* Filter does not want or need to see data that's allowed to pass */
4354 	if (peek_offset > entrybuf->cfe_pass_offset &&
4355 	    peek_offset > entrybuf->cfe_peek_offset) {
4356 		entrybuf->cfe_peek_offset = peek_offset;
4357 		updated = 1;
4358 	}
4359 	/* Nothing to do */
4360 	if (updated == 0) {
4361 		goto done;
4362 	}
4363 
4364 	/* Move data held in control queue to pending queue if needed */
4365 	error = cfil_data_service_ctl_q(so, cfil_info, kcunit, outgoing);
4366 	if (error != 0) {
4367 		CFIL_LOG(LOG_ERR, "cfil_data_service_ctl_q() error %d",
4368 		    error);
4369 		goto done;
4370 	}
4371 	error = EJUSTRETURN;
4372 
4373 done:
4374 	/*
4375 	 * The filter is effectively detached when pass all from both sides
4376 	 * or when the socket is closed and no more data is waiting
4377 	 * to be delivered to the filter
4378 	 */
4379 	if (entry != NULL &&
4380 	    ((entry->cfe_snd.cfe_pass_offset == CFM_MAX_OFFSET &&
4381 	    entry->cfe_rcv.cfe_pass_offset == CFM_MAX_OFFSET) ||
4382 	    ((cfil_info->cfi_flags & CFIF_CLOSE_WAIT) &&
4383 	    cfil_queue_empty(&entry->cfe_snd.cfe_ctl_q) &&
4384 	    cfil_queue_empty(&entry->cfe_rcv.cfe_ctl_q)))) {
4385 		entry->cfe_flags |= CFEF_CFIL_DETACHED;
4386 
4387 		if (cfil_info->cfi_debug) {
4388 			cfil_info_log(LOG_INFO, cfil_info, outgoing ?
4389 			    "CFIL: OUT - PASSED ALL - DETACH":
4390 			    "CFIL: IN - PASSED ALL - DETACH");
4391 		}
4392 
4393 		CFIL_LOG(LOG_INFO, "so %llx detached %u",
4394 		    (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit);
4395 		if ((cfil_info->cfi_flags & CFIF_CLOSE_WAIT) &&
4396 		    cfil_filters_attached(so) == 0) {
4397 			if (cfil_info->cfi_debug) {
4398 				cfil_info_log(LOG_INFO, cfil_info, "CFIL: WAKING");
4399 			}
4400 			CFIL_LOG(LOG_INFO, "so %llx waking",
4401 			    (uint64_t)VM_KERNEL_ADDRPERM(so));
4402 			wakeup((caddr_t)cfil_info);
4403 		}
4404 	}
4405 	CFIL_INFO_VERIFY(cfil_info);
4406 	CFIL_LOG(LOG_INFO, "return %d", error);
4407 	return error;
4408 }
4409 
4410 /*
4411  * Update pass offset for socket when no data is pending
4412  */
4413 static int
cfil_set_socket_pass_offset(struct socket * so,struct cfil_info * cfil_info,int outgoing)4414 cfil_set_socket_pass_offset(struct socket *so, struct cfil_info *cfil_info, int outgoing)
4415 {
4416 	struct cfi_buf *cfi_buf;
4417 	struct cfil_entry *entry;
4418 	struct cfe_buf *entrybuf;
4419 	uint32_t kcunit;
4420 	uint64_t pass_offset = 0;
4421 	boolean_t first = true;
4422 
4423 	if (cfil_info == NULL) {
4424 		return 0;
4425 	}
4426 
4427 	if (cfil_info->cfi_debug && cfil_log_data) {
4428 		CFIL_LOG(LOG_DEBUG, "so %llx outgoing %d",
4429 		    (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing);
4430 	}
4431 
4432 	socket_lock_assert_owned(so);
4433 
4434 	if (outgoing) {
4435 		cfi_buf = &cfil_info->cfi_snd;
4436 	} else {
4437 		cfi_buf = &cfil_info->cfi_rcv;
4438 	}
4439 
4440 	if (cfil_info->cfi_debug && cfil_log_data) {
4441 		CFIL_LOG(LOG_DEBUG, "CFIL: <so %llx, sockID %llu> outgoing %d cfi_pending_first %llu cfi_pending_last %llu",
4442 		    (uint64_t)VM_KERNEL_ADDRPERM(so), cfil_info->cfi_sock_id, outgoing,
4443 		    cfi_buf->cfi_pending_first, cfi_buf->cfi_pending_last);
4444 	}
4445 
4446 	if (cfi_buf->cfi_pending_last - cfi_buf->cfi_pending_first == 0) {
4447 		for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
4448 			entry = &cfil_info->cfi_entries[kcunit - 1];
4449 
4450 			/* Are we attached to a filter? */
4451 			if (entry->cfe_filter == NULL) {
4452 				continue;
4453 			}
4454 
4455 			if (outgoing) {
4456 				entrybuf = &entry->cfe_snd;
4457 			} else {
4458 				entrybuf = &entry->cfe_rcv;
4459 			}
4460 
4461 			// Keep track of the smallest pass_offset among filters.
4462 			if (first == true ||
4463 			    entrybuf->cfe_pass_offset < pass_offset) {
4464 				pass_offset = entrybuf->cfe_pass_offset;
4465 				first = false;
4466 			}
4467 		}
4468 		cfi_buf->cfi_pass_offset = pass_offset;
4469 	}
4470 
4471 	if (cfil_info->cfi_debug && cfil_log_data) {
4472 		CFIL_LOG(LOG_DEBUG, "CFIL: <so %llx, sockID %llu>, cfi_pass_offset %llu",
4473 		    (uint64_t)VM_KERNEL_ADDRPERM(so), cfil_info->cfi_sock_id, cfi_buf->cfi_pass_offset);
4474 	}
4475 
4476 	return 0;
4477 }
4478 
4479 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)4480 cfil_action_data_pass(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit, int outgoing,
4481     uint64_t pass_offset, uint64_t peek_offset)
4482 {
4483 	errno_t error = 0;
4484 
4485 	CFIL_LOG(LOG_INFO, "");
4486 
4487 	socket_lock_assert_owned(so);
4488 
4489 	error = cfil_acquire_sockbuf(so, cfil_info, outgoing);
4490 	if (error != 0) {
4491 		CFIL_LOG(LOG_INFO, "so %llx %s dropped",
4492 		    (uint64_t)VM_KERNEL_ADDRPERM(so),
4493 		    outgoing ? "out" : "in");
4494 		goto release;
4495 	}
4496 
4497 	error = cfil_update_data_offsets(so, cfil_info, kcunit, outgoing,
4498 	    pass_offset, peek_offset);
4499 
4500 	cfil_service_inject_queue(so, cfil_info, outgoing);
4501 
4502 	cfil_set_socket_pass_offset(so, cfil_info, outgoing);
4503 release:
4504 	CFIL_INFO_VERIFY(cfil_info);
4505 	cfil_release_sockbuf(so, outgoing);
4506 
4507 	return error;
4508 }
4509 
4510 
4511 static void
cfil_flush_queues(struct socket * so,struct cfil_info * cfil_info)4512 cfil_flush_queues(struct socket *so, struct cfil_info *cfil_info)
4513 {
4514 	struct cfil_entry *entry;
4515 	int kcunit;
4516 	uint64_t drained;
4517 
4518 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || cfil_info == NULL) {
4519 		goto done;
4520 	}
4521 
4522 	socket_lock_assert_owned(so);
4523 
4524 	/*
4525 	 * Flush the output queues and ignore errors as long as
4526 	 * we are attached
4527 	 */
4528 	(void) cfil_acquire_sockbuf(so, cfil_info, 1);
4529 	if (cfil_info != NULL) {
4530 		drained = 0;
4531 		for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
4532 			entry = &cfil_info->cfi_entries[kcunit - 1];
4533 
4534 			drained += cfil_queue_drain(&entry->cfe_snd.cfe_ctl_q);
4535 			drained += cfil_queue_drain(&entry->cfe_snd.cfe_pending_q);
4536 		}
4537 		drained += cfil_queue_drain(&cfil_info->cfi_snd.cfi_inject_q);
4538 
4539 		if (drained) {
4540 			if (cfil_info->cfi_flags & CFIF_DROP) {
4541 				OSIncrementAtomic(
4542 					&cfil_stats.cfs_flush_out_drop);
4543 			} else {
4544 				OSIncrementAtomic(
4545 					&cfil_stats.cfs_flush_out_close);
4546 			}
4547 		}
4548 	}
4549 	cfil_release_sockbuf(so, 1);
4550 
4551 	/*
4552 	 * Flush the input queues
4553 	 */
4554 	(void) cfil_acquire_sockbuf(so, cfil_info, 0);
4555 	if (cfil_info != NULL) {
4556 		drained = 0;
4557 		for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
4558 			entry = &cfil_info->cfi_entries[kcunit - 1];
4559 
4560 			drained += cfil_queue_drain(
4561 				&entry->cfe_rcv.cfe_ctl_q);
4562 			drained += cfil_queue_drain(
4563 				&entry->cfe_rcv.cfe_pending_q);
4564 		}
4565 		drained += cfil_queue_drain(&cfil_info->cfi_rcv.cfi_inject_q);
4566 
4567 		if (drained) {
4568 			if (cfil_info->cfi_flags & CFIF_DROP) {
4569 				OSIncrementAtomic(
4570 					&cfil_stats.cfs_flush_in_drop);
4571 			} else {
4572 				OSIncrementAtomic(
4573 					&cfil_stats.cfs_flush_in_close);
4574 			}
4575 		}
4576 	}
4577 	cfil_release_sockbuf(so, 0);
4578 done:
4579 	CFIL_INFO_VERIFY(cfil_info);
4580 }
4581 
4582 int
cfil_action_drop(struct socket * so,struct cfil_info * cfil_info,uint32_t kcunit)4583 cfil_action_drop(struct socket *so, struct cfil_info *cfil_info, uint32_t kcunit)
4584 {
4585 	errno_t error = 0;
4586 	struct cfil_entry *entry;
4587 	struct proc *p;
4588 
4589 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || cfil_info == NULL) {
4590 		goto done;
4591 	}
4592 
4593 	socket_lock_assert_owned(so);
4594 
4595 	entry = &cfil_info->cfi_entries[kcunit - 1];
4596 
4597 	/* Are we attached to the filter? */
4598 	if (entry->cfe_filter == NULL) {
4599 		goto done;
4600 	}
4601 
4602 	cfil_info->cfi_flags |= CFIF_DROP;
4603 
4604 	p = current_proc();
4605 
4606 	/*
4607 	 * Force the socket to be marked defunct
4608 	 * (forcing fixed along with rdar://19391339)
4609 	 */
4610 	if (so->so_flow_db == NULL) {
4611 		error = sosetdefunct(p, so,
4612 		    SHUTDOWN_SOCKET_LEVEL_CONTENT_FILTER | SHUTDOWN_SOCKET_LEVEL_DISCONNECT_ALL,
4613 		    FALSE);
4614 
4615 		/* Flush the socket buffer and disconnect */
4616 		if (error == 0) {
4617 			error = sodefunct(p, so,
4618 			    SHUTDOWN_SOCKET_LEVEL_CONTENT_FILTER | SHUTDOWN_SOCKET_LEVEL_DISCONNECT_ALL);
4619 		}
4620 	}
4621 
4622 	/* The filter is done, mark as detached */
4623 	entry->cfe_flags |= CFEF_CFIL_DETACHED;
4624 
4625 	if (cfil_info->cfi_debug) {
4626 		cfil_info_log(LOG_INFO, cfil_info, "CFIL: DROP - DETACH");
4627 	}
4628 
4629 	CFIL_LOG(LOG_INFO, "so %llx detached %u",
4630 	    (uint64_t)VM_KERNEL_ADDRPERM(so), kcunit);
4631 
4632 	/* Pending data needs to go */
4633 	cfil_flush_queues(so, cfil_info);
4634 
4635 	if (cfil_info && (cfil_info->cfi_flags & CFIF_CLOSE_WAIT)) {
4636 		if (cfil_filters_attached(so) == 0) {
4637 			CFIL_LOG(LOG_INFO, "so %llx waking",
4638 			    (uint64_t)VM_KERNEL_ADDRPERM(so));
4639 			wakeup((caddr_t)cfil_info);
4640 		}
4641 	}
4642 done:
4643 	return error;
4644 }
4645 
4646 int
cfil_action_bless_client(uint32_t kcunit,struct cfil_msg_hdr * msghdr)4647 cfil_action_bless_client(uint32_t kcunit, struct cfil_msg_hdr *msghdr)
4648 {
4649 	errno_t error = 0;
4650 	struct cfil_info *cfil_info = NULL;
4651 
4652 	bool cfil_attached = false;
4653 	struct cfil_msg_bless_client *blessmsg = (struct cfil_msg_bless_client *)msghdr;
4654 
4655 	// Search and lock socket
4656 	struct socket *so = cfil_socket_from_client_uuid(blessmsg->cfb_client_uuid, &cfil_attached);
4657 	if (so == NULL) {
4658 		error = ENOENT;
4659 	} else {
4660 		// The client gets a pass automatically
4661 		cfil_info = (so->so_flow_db != NULL) ?
4662 		    soflow_db_get_feature_context(so->so_flow_db, msghdr->cfm_sock_id) : so->so_cfil;
4663 
4664 		if (cfil_attached) {
4665 			if (cfil_info != NULL && cfil_info->cfi_debug) {
4666 				cfil_info_log(LOG_INFO, cfil_info, "CFIL: VERDICT RECEIVED: BLESS");
4667 			}
4668 			cfil_sock_received_verdict(so);
4669 			(void)cfil_action_data_pass(so, cfil_info, kcunit, 1, CFM_MAX_OFFSET, CFM_MAX_OFFSET);
4670 			(void)cfil_action_data_pass(so, cfil_info, kcunit, 0, CFM_MAX_OFFSET, CFM_MAX_OFFSET);
4671 		} else {
4672 			so->so_flags1 |= SOF1_CONTENT_FILTER_SKIP;
4673 		}
4674 		socket_unlock(so, 1);
4675 	}
4676 
4677 	return error;
4678 }
4679 
4680 int
cfil_action_set_crypto_key(uint32_t kcunit,struct cfil_msg_hdr * msghdr)4681 cfil_action_set_crypto_key(uint32_t kcunit, struct cfil_msg_hdr *msghdr)
4682 {
4683 	struct content_filter *cfc = NULL;
4684 	cfil_crypto_state_t crypto_state = NULL;
4685 	struct cfil_msg_set_crypto_key *keymsg = (struct cfil_msg_set_crypto_key *)msghdr;
4686 
4687 	CFIL_LOG(LOG_NOTICE, "");
4688 
4689 	if (kcunit > MAX_CONTENT_FILTER) {
4690 		CFIL_LOG(LOG_ERR, "kcunit %u > MAX_CONTENT_FILTER (%d)",
4691 		    kcunit, MAX_CONTENT_FILTER);
4692 		return EINVAL;
4693 	}
4694 	crypto_state = cfil_crypto_init_client((uint8_t *)keymsg->crypto_key);
4695 	if (crypto_state == NULL) {
4696 		CFIL_LOG(LOG_ERR, "failed to initialize crypto state for unit %u)",
4697 		    kcunit);
4698 		return EINVAL;
4699 	}
4700 
4701 	cfil_rw_lock_exclusive(&cfil_lck_rw);
4702 
4703 	cfc = content_filters[kcunit - 1];
4704 	if (cfc->cf_kcunit != kcunit) {
4705 		CFIL_LOG(LOG_ERR, "bad unit info %u)",
4706 		    kcunit);
4707 		cfil_rw_unlock_exclusive(&cfil_lck_rw);
4708 		cfil_crypto_cleanup_state(crypto_state);
4709 		return EINVAL;
4710 	}
4711 	if (cfc->cf_crypto_state != NULL) {
4712 		cfil_crypto_cleanup_state(cfc->cf_crypto_state);
4713 		cfc->cf_crypto_state = NULL;
4714 	}
4715 	cfc->cf_crypto_state = crypto_state;
4716 
4717 	cfil_rw_unlock_exclusive(&cfil_lck_rw);
4718 	return 0;
4719 }
4720 
4721 static int
cfil_update_entry_offsets(struct socket * so,struct cfil_info * cfil_info,int outgoing,unsigned int datalen)4722 cfil_update_entry_offsets(struct socket *so, struct cfil_info *cfil_info, int outgoing, unsigned int datalen)
4723 {
4724 	struct cfil_entry *entry;
4725 	struct cfe_buf *entrybuf;
4726 	uint32_t kcunit;
4727 
4728 	CFIL_LOG(LOG_INFO, "so %llx outgoing %d datalen %u",
4729 	    (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing, datalen);
4730 
4731 	for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
4732 		entry = &cfil_info->cfi_entries[kcunit - 1];
4733 
4734 		/* Are we attached to the filter? */
4735 		if (entry->cfe_filter == NULL) {
4736 			continue;
4737 		}
4738 
4739 		if (outgoing) {
4740 			entrybuf = &entry->cfe_snd;
4741 		} else {
4742 			entrybuf = &entry->cfe_rcv;
4743 		}
4744 
4745 		entrybuf->cfe_ctl_q.q_start += datalen;
4746 		if (entrybuf->cfe_pass_offset < entrybuf->cfe_ctl_q.q_start) {
4747 			entrybuf->cfe_pass_offset = entrybuf->cfe_ctl_q.q_start;
4748 		}
4749 		entrybuf->cfe_peeked = entrybuf->cfe_ctl_q.q_start;
4750 		if (entrybuf->cfe_peek_offset < entrybuf->cfe_pass_offset) {
4751 			entrybuf->cfe_peek_offset = entrybuf->cfe_pass_offset;
4752 		}
4753 
4754 		entrybuf->cfe_ctl_q.q_end += datalen;
4755 
4756 		entrybuf->cfe_pending_q.q_start += datalen;
4757 		entrybuf->cfe_pending_q.q_end += datalen;
4758 	}
4759 	CFIL_INFO_VERIFY(cfil_info);
4760 	return 0;
4761 }
4762 
4763 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)4764 cfil_data_common(struct socket *so, struct cfil_info *cfil_info, int outgoing, struct sockaddr *to,
4765     struct mbuf *data, struct mbuf *control, uint32_t flags)
4766 {
4767 #pragma unused(to, control, flags)
4768 	errno_t error = 0;
4769 	unsigned int datalen;
4770 	int mbcnt = 0;
4771 	int mbnum = 0;
4772 	int kcunit;
4773 	struct cfi_buf *cfi_buf;
4774 	struct mbuf *chain = NULL;
4775 
4776 	if (cfil_info == NULL) {
4777 		CFIL_LOG(LOG_ERR, "so %llx cfil detached",
4778 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
4779 		error = 0;
4780 		goto done;
4781 	} else if (cfil_info->cfi_flags & CFIF_DROP) {
4782 		CFIL_LOG(LOG_ERR, "so %llx drop set",
4783 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
4784 		error = EPIPE;
4785 		goto done;
4786 	}
4787 
4788 	datalen = cfil_data_length(data, &mbcnt, &mbnum);
4789 
4790 	if (datalen == 0) {
4791 		error = 0;
4792 		goto done;
4793 	}
4794 
4795 	if (outgoing) {
4796 		cfi_buf = &cfil_info->cfi_snd;
4797 		cfil_info->cfi_byte_outbound_count += datalen;
4798 	} else {
4799 		cfi_buf = &cfil_info->cfi_rcv;
4800 		cfil_info->cfi_byte_inbound_count += datalen;
4801 	}
4802 
4803 	cfi_buf->cfi_pending_last += datalen;
4804 	cfi_buf->cfi_pending_mbcnt += mbcnt;
4805 	cfi_buf->cfi_pending_mbnum += mbnum;
4806 
4807 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
4808 		if (cfi_buf->cfi_pending_mbnum > cfil_udp_gc_mbuf_num_max ||
4809 		    cfi_buf->cfi_pending_mbcnt > cfil_udp_gc_mbuf_cnt_max) {
4810 			cfi_buf->cfi_tail_drop_cnt++;
4811 			cfi_buf->cfi_pending_mbcnt -= mbcnt;
4812 			cfi_buf->cfi_pending_mbnum -= mbnum;
4813 			return EPIPE;
4814 		}
4815 	}
4816 
4817 	cfil_info_buf_verify(cfi_buf);
4818 
4819 	if (cfil_info->cfi_debug && cfil_log_data) {
4820 		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",
4821 		    (uint64_t)VM_KERNEL_ADDRPERM(so),
4822 		    outgoing ? "OUT" : "IN",
4823 		    (uint64_t)VM_KERNEL_ADDRPERM(data), datalen, data->m_flags,
4824 		    (uint64_t)VM_KERNEL_ADDRPERM(data->m_nextpkt),
4825 		    cfi_buf->cfi_pending_last,
4826 		    cfi_buf->cfi_pending_mbcnt,
4827 		    cfi_buf->cfi_pass_offset);
4828 	}
4829 
4830 	/* Fast path when below pass offset */
4831 	if (cfi_buf->cfi_pending_last <= cfi_buf->cfi_pass_offset) {
4832 		cfil_update_entry_offsets(so, cfil_info, outgoing, datalen);
4833 		if (cfil_info->cfi_debug && cfil_log_data) {
4834 			CFIL_LOG(LOG_DEBUG, "CFIL: QUEUEING DATA: FAST PATH");
4835 		}
4836 	} else {
4837 		struct cfil_entry *iter_entry;
4838 		SLIST_FOREACH(iter_entry, &cfil_info->cfi_ordered_entries, cfe_order_link) {
4839 			// Is cfil attached to this filter?
4840 			kcunit = CFI_ENTRY_KCUNIT(cfil_info, iter_entry);
4841 			if (IS_ENTRY_ATTACHED(cfil_info, kcunit)) {
4842 				if (NEED_DGRAM_FLOW_TRACKING(so) && chain == NULL) {
4843 					/* Datagrams only:
4844 					 * Chain addr (incoming only TDB), control (optional) and data into one chain.
4845 					 * This full chain will be reinjected into socket after recieving verdict.
4846 					 */
4847 					(void) cfil_dgram_save_socket_state(cfil_info, data);
4848 					chain = sbconcat_mbufs(NULL, outgoing ? NULL : to, data, control);
4849 					if (chain == NULL) {
4850 						return ENOBUFS;
4851 					}
4852 					data = chain;
4853 				}
4854 				error = cfil_data_filter(so, cfil_info, kcunit, outgoing, data,
4855 				    datalen);
4856 			}
4857 			/* 0 means passed so continue with next filter */
4858 			if (error != 0) {
4859 				break;
4860 			}
4861 		}
4862 	}
4863 
4864 	/* Move cursor if no filter claimed the data */
4865 	if (error == 0) {
4866 		cfi_buf->cfi_pending_first += datalen;
4867 		cfi_buf->cfi_pending_mbcnt -= mbcnt;
4868 		cfi_buf->cfi_pending_mbnum -= mbnum;
4869 		cfil_info_buf_verify(cfi_buf);
4870 	}
4871 done:
4872 	CFIL_INFO_VERIFY(cfil_info);
4873 
4874 	return error;
4875 }
4876 
4877 /*
4878  * Callback from socket layer sosendxxx()
4879  */
4880 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)4881 cfil_sock_data_out(struct socket *so, struct sockaddr  *to,
4882     struct mbuf *data, struct mbuf *control, uint32_t flags, struct soflow_hash_entry *flow_entry)
4883 {
4884 	int error = 0;
4885 	int new_filter_control_unit = 0;
4886 
4887 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
4888 		return cfil_sock_udp_handle_data(TRUE, so, NULL, to, data, control, flags, flow_entry);
4889 	}
4890 
4891 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) {
4892 		/* Drop pre-existing TCP sockets if filter is enabled now */
4893 		if (!DO_PRESERVE_CONNECTIONS && cfil_active_count > 0 && !SKIP_FILTER_FOR_TCP_SOCKET(so)) {
4894 			new_filter_control_unit = necp_socket_get_content_filter_control_unit(so);
4895 			if (new_filter_control_unit > 0) {
4896 				CFIL_LOG(LOG_NOTICE, "CFIL: TCP(OUT) <so %llx> - filter state changed - dropped pre-existing flow", (uint64_t)VM_KERNEL_ADDRPERM(so));
4897 				return EPIPE;
4898 			}
4899 		}
4900 		return 0;
4901 	}
4902 
4903 	/* Drop pre-existing TCP sockets when filter state changed */
4904 	new_filter_control_unit = necp_socket_get_content_filter_control_unit(so);
4905 	if (new_filter_control_unit > 0 && new_filter_control_unit != so->so_cfil->cfi_filter_control_unit && !SKIP_FILTER_FOR_TCP_SOCKET(so)) {
4906 		if (DO_PRESERVE_CONNECTIONS) {
4907 			so->so_cfil->cfi_filter_control_unit = new_filter_control_unit;
4908 		} else {
4909 			CFIL_LOG(LOG_NOTICE, "CFIL: TCP(OUT) <so %llx> - filter state changed - dropped pre-existing flow (old state 0x%x new state 0x%x)",
4910 			    (uint64_t)VM_KERNEL_ADDRPERM(so),
4911 			    so->so_cfil->cfi_filter_control_unit, new_filter_control_unit);
4912 			return EPIPE;
4913 		}
4914 	}
4915 
4916 	/*
4917 	 * Pass initial data for TFO.
4918 	 */
4919 	if (IS_INITIAL_TFO_DATA(so)) {
4920 		return 0;
4921 	}
4922 
4923 	socket_lock_assert_owned(so);
4924 
4925 	if (so->so_cfil->cfi_flags & CFIF_DROP) {
4926 		CFIL_LOG(LOG_ERR, "so %llx drop set",
4927 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
4928 		return EPIPE;
4929 	}
4930 	if (control != NULL) {
4931 		CFIL_LOG(LOG_ERR, "so %llx control",
4932 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
4933 		OSIncrementAtomic(&cfil_stats.cfs_data_out_control);
4934 	}
4935 	if ((flags & MSG_OOB)) {
4936 		CFIL_LOG(LOG_ERR, "so %llx MSG_OOB",
4937 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
4938 		OSIncrementAtomic(&cfil_stats.cfs_data_out_oob);
4939 	}
4940 	if ((so->so_snd.sb_flags & SB_LOCK) == 0) {
4941 		panic("so %p SB_LOCK not set", so);
4942 	}
4943 
4944 	if (so->so_snd.sb_cfil_thread != NULL) {
4945 		panic("%s sb_cfil_thread %p not NULL", __func__,
4946 		    so->so_snd.sb_cfil_thread);
4947 	}
4948 
4949 	error = cfil_data_common(so, so->so_cfil, 1, to, data, control, flags);
4950 
4951 	return error;
4952 }
4953 
4954 /*
4955  * Callback from socket layer sbappendxxx()
4956  */
4957 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)4958 cfil_sock_data_in(struct socket *so, struct sockaddr *from,
4959     struct mbuf *data, struct mbuf *control, uint32_t flags, struct soflow_hash_entry *flow_entry)
4960 {
4961 	int error = 0;
4962 	int new_filter_control_unit = 0;
4963 
4964 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
4965 		return cfil_sock_udp_handle_data(FALSE, so, NULL, from, data, control, flags, flow_entry);
4966 	}
4967 
4968 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) {
4969 		/* Drop pre-existing TCP sockets if filter is enabled now */
4970 		if (!DO_PRESERVE_CONNECTIONS && cfil_active_count > 0 && !SKIP_FILTER_FOR_TCP_SOCKET(so)) {
4971 			new_filter_control_unit = necp_socket_get_content_filter_control_unit(so);
4972 			if (new_filter_control_unit > 0) {
4973 				CFIL_LOG(LOG_NOTICE, "CFIL: TCP(IN) <so %llx> - filter state changed - dropped pre-existing flow", (uint64_t)VM_KERNEL_ADDRPERM(so));
4974 				return EPIPE;
4975 			}
4976 		}
4977 		return 0;
4978 	}
4979 
4980 	/* Drop pre-existing TCP sockets when filter state changed */
4981 	new_filter_control_unit = necp_socket_get_content_filter_control_unit(so);
4982 	if (new_filter_control_unit > 0 && new_filter_control_unit != so->so_cfil->cfi_filter_control_unit && !SKIP_FILTER_FOR_TCP_SOCKET(so)) {
4983 		if (DO_PRESERVE_CONNECTIONS) {
4984 			so->so_cfil->cfi_filter_control_unit = new_filter_control_unit;
4985 		} else {
4986 			CFIL_LOG(LOG_NOTICE, "CFIL: TCP(IN) <so %llx> - filter state changed - dropped pre-existing flow (old state 0x%x new state 0x%x)",
4987 			    (uint64_t)VM_KERNEL_ADDRPERM(so),
4988 			    so->so_cfil->cfi_filter_control_unit, new_filter_control_unit);
4989 			return EPIPE;
4990 		}
4991 	}
4992 
4993 	/*
4994 	 * Pass initial data for TFO.
4995 	 */
4996 	if (IS_INITIAL_TFO_DATA(so)) {
4997 		return 0;
4998 	}
4999 
5000 	socket_lock_assert_owned(so);
5001 
5002 	if (so->so_cfil->cfi_flags & CFIF_DROP) {
5003 		CFIL_LOG(LOG_ERR, "so %llx drop set",
5004 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
5005 		return EPIPE;
5006 	}
5007 	if (control != NULL) {
5008 		CFIL_LOG(LOG_ERR, "so %llx control",
5009 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
5010 		OSIncrementAtomic(&cfil_stats.cfs_data_in_control);
5011 	}
5012 	if (data->m_type == MT_OOBDATA) {
5013 		CFIL_LOG(LOG_ERR, "so %llx MSG_OOB",
5014 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
5015 		OSIncrementAtomic(&cfil_stats.cfs_data_in_oob);
5016 	}
5017 	error = cfil_data_common(so, so->so_cfil, 0, from, data, control, flags);
5018 
5019 	return error;
5020 }
5021 
5022 /*
5023  * Callback from socket layer soshutdownxxx()
5024  *
5025  * We may delay the shutdown write if there's outgoing data in process.
5026  *
5027  * There is no point in delaying the shutdown read because the process
5028  * indicated that it does not want to read anymore data.
5029  */
5030 int
cfil_sock_shutdown(struct socket * so,int * how)5031 cfil_sock_shutdown(struct socket *so, int *how)
5032 {
5033 	int error = 0;
5034 
5035 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
5036 		return cfil_sock_udp_shutdown(so, how);
5037 	}
5038 
5039 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) {
5040 		goto done;
5041 	}
5042 
5043 	socket_lock_assert_owned(so);
5044 
5045 	CFIL_LOG(LOG_INFO, "so %llx how %d",
5046 	    (uint64_t)VM_KERNEL_ADDRPERM(so), *how);
5047 
5048 	/*
5049 	 * Check the state of the socket before the content filter
5050 	 */
5051 	if (*how != SHUT_WR && (so->so_state & SS_CANTRCVMORE) != 0) {
5052 		/* read already shut down */
5053 		error = ENOTCONN;
5054 		goto done;
5055 	}
5056 	if (*how != SHUT_RD && (so->so_state & SS_CANTSENDMORE) != 0) {
5057 		/* write already shut down */
5058 		error = ENOTCONN;
5059 		goto done;
5060 	}
5061 
5062 	if ((so->so_cfil->cfi_flags & CFIF_DROP) != 0) {
5063 		CFIL_LOG(LOG_ERR, "so %llx drop set",
5064 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
5065 		goto done;
5066 	}
5067 
5068 	/*
5069 	 * shutdown read: SHUT_RD or SHUT_RDWR
5070 	 */
5071 	if (*how != SHUT_WR) {
5072 		if (so->so_cfil->cfi_flags & CFIF_SHUT_RD) {
5073 			error = ENOTCONN;
5074 			goto done;
5075 		}
5076 		so->so_cfil->cfi_flags |= CFIF_SHUT_RD;
5077 		cfil_sock_notify_shutdown(so, SHUT_RD);
5078 	}
5079 	/*
5080 	 * shutdown write: SHUT_WR or SHUT_RDWR
5081 	 */
5082 	if (*how != SHUT_RD) {
5083 		if (so->so_cfil->cfi_flags & CFIF_SHUT_WR) {
5084 			error = ENOTCONN;
5085 			goto done;
5086 		}
5087 		so->so_cfil->cfi_flags |= CFIF_SHUT_WR;
5088 		cfil_sock_notify_shutdown(so, SHUT_WR);
5089 		/*
5090 		 * When outgoing data is pending, we delay the shutdown at the
5091 		 * protocol level until the content filters give the final
5092 		 * verdict on the pending data.
5093 		 */
5094 		if (cfil_sock_data_pending(&so->so_snd) != 0) {
5095 			/*
5096 			 * When shutting down the read and write sides at once
5097 			 * we can proceed to the final shutdown of the read
5098 			 * side. Otherwise, we just return.
5099 			 */
5100 			if (*how == SHUT_WR) {
5101 				error = EJUSTRETURN;
5102 			} else if (*how == SHUT_RDWR) {
5103 				*how = SHUT_RD;
5104 			}
5105 		}
5106 	}
5107 done:
5108 	return error;
5109 }
5110 
5111 /*
5112  * This is called when the socket is closed and there is no more
5113  * opportunity for filtering
5114  */
5115 void
cfil_sock_is_closed(struct socket * so)5116 cfil_sock_is_closed(struct socket *so)
5117 {
5118 	errno_t error = 0;
5119 	int kcunit;
5120 
5121 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
5122 		cfil_sock_udp_is_closed(so);
5123 		return;
5124 	}
5125 
5126 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) {
5127 		return;
5128 	}
5129 
5130 	CFIL_LOG(LOG_INFO, "so %llx", (uint64_t)VM_KERNEL_ADDRPERM(so));
5131 
5132 	socket_lock_assert_owned(so);
5133 
5134 	for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
5135 		/* Let the filters know of the closing */
5136 		error = cfil_dispatch_closed_event(so, so->so_cfil, kcunit);
5137 	}
5138 
5139 	/* Last chance to push passed data out */
5140 	error = cfil_acquire_sockbuf(so, so->so_cfil, 1);
5141 	if (error == 0) {
5142 		cfil_service_inject_queue(so, so->so_cfil, 1);
5143 	}
5144 	cfil_release_sockbuf(so, 1);
5145 
5146 	so->so_cfil->cfi_flags |= CFIF_SOCK_CLOSED;
5147 
5148 	/* Pending data needs to go */
5149 	cfil_flush_queues(so, so->so_cfil);
5150 
5151 	CFIL_INFO_VERIFY(so->so_cfil);
5152 }
5153 
5154 /*
5155  * This is called when the socket is disconnected so let the filters
5156  * know about the disconnection and that no more data will come
5157  *
5158  * The how parameter has the same values as soshutown()
5159  */
5160 void
cfil_sock_notify_shutdown(struct socket * so,int how)5161 cfil_sock_notify_shutdown(struct socket *so, int how)
5162 {
5163 	errno_t error = 0;
5164 	int kcunit;
5165 
5166 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
5167 		cfil_sock_udp_notify_shutdown(so, how, 0, 0);
5168 		return;
5169 	}
5170 
5171 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) {
5172 		return;
5173 	}
5174 
5175 	CFIL_LOG(LOG_INFO, "so %llx how %d",
5176 	    (uint64_t)VM_KERNEL_ADDRPERM(so), how);
5177 
5178 	socket_lock_assert_owned(so);
5179 
5180 	for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
5181 		/* Disconnect incoming side */
5182 		if (how != SHUT_WR) {
5183 			error = cfil_dispatch_disconnect_event(so, so->so_cfil, kcunit, 0);
5184 		}
5185 		/* Disconnect outgoing side */
5186 		if (how != SHUT_RD) {
5187 			error = cfil_dispatch_disconnect_event(so, so->so_cfil, kcunit, 1);
5188 		}
5189 	}
5190 }
5191 
5192 static int
cfil_filters_attached(struct socket * so)5193 cfil_filters_attached(struct socket *so)
5194 {
5195 	struct cfil_entry *entry;
5196 	uint32_t kcunit;
5197 	int attached = 0;
5198 
5199 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
5200 		return cfil_filters_udp_attached(so, FALSE);
5201 	}
5202 
5203 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) {
5204 		return 0;
5205 	}
5206 
5207 	socket_lock_assert_owned(so);
5208 
5209 	for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
5210 		entry = &so->so_cfil->cfi_entries[kcunit - 1];
5211 
5212 		/* Are we attached to the filter? */
5213 		if (entry->cfe_filter == NULL) {
5214 			continue;
5215 		}
5216 		if ((entry->cfe_flags & CFEF_SENT_SOCK_ATTACHED) == 0) {
5217 			continue;
5218 		}
5219 		if ((entry->cfe_flags & CFEF_CFIL_DETACHED) != 0) {
5220 			continue;
5221 		}
5222 		attached = 1;
5223 		break;
5224 	}
5225 
5226 	return attached;
5227 }
5228 
5229 /*
5230  * This is called when the socket is closed and we are waiting for
5231  * the filters to gives the final pass or drop
5232  */
5233 void
cfil_sock_close_wait(struct socket * so)5234 cfil_sock_close_wait(struct socket *so)
5235 {
5236 	lck_mtx_t *mutex_held;
5237 	struct timespec ts;
5238 	int error;
5239 
5240 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
5241 		cfil_sock_udp_close_wait(so);
5242 		return;
5243 	}
5244 
5245 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) {
5246 		return;
5247 	}
5248 
5249 	// This flow does not need to wait for close ack from user-space
5250 	if (IS_NO_CLOSE_WAIT(so->so_cfil)) {
5251 		if (so->so_cfil->cfi_debug) {
5252 			cfil_info_log(LOG_INFO, so->so_cfil, "CFIL: SKIP CLOSE WAIT");
5253 		}
5254 		return;
5255 	}
5256 
5257 	CFIL_LOG(LOG_INFO, "so %llx", (uint64_t)VM_KERNEL_ADDRPERM(so));
5258 
5259 	if (so->so_proto->pr_getlock != NULL) {
5260 		mutex_held = (*so->so_proto->pr_getlock)(so, PR_F_WILLUNLOCK);
5261 	} else {
5262 		mutex_held = so->so_proto->pr_domain->dom_mtx;
5263 	}
5264 	LCK_MTX_ASSERT(mutex_held, LCK_MTX_ASSERT_OWNED);
5265 
5266 	while (cfil_filters_attached(so)) {
5267 		/*
5268 		 * Notify the filters we are going away so they can detach
5269 		 */
5270 		cfil_sock_notify_shutdown(so, SHUT_RDWR);
5271 
5272 		/*
5273 		 * Make sure we need to wait after the filter are notified
5274 		 * of the disconnection
5275 		 */
5276 		if (cfil_filters_attached(so) == 0) {
5277 			break;
5278 		}
5279 
5280 		CFIL_LOG(LOG_INFO, "so %llx waiting",
5281 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
5282 
5283 		ts.tv_sec = cfil_close_wait_timeout / 1000;
5284 		ts.tv_nsec = (cfil_close_wait_timeout % 1000) *
5285 		    NSEC_PER_USEC * 1000;
5286 
5287 		OSIncrementAtomic(&cfil_stats.cfs_close_wait);
5288 		so->so_cfil->cfi_flags |= CFIF_CLOSE_WAIT;
5289 		error = msleep((caddr_t)so->so_cfil, mutex_held,
5290 		    PSOCK | PCATCH, "cfil_sock_close_wait", &ts);
5291 		so->so_cfil->cfi_flags &= ~CFIF_CLOSE_WAIT;
5292 
5293 		CFIL_LOG(LOG_NOTICE, "so %llx timed out %d",
5294 		    (uint64_t)VM_KERNEL_ADDRPERM(so), (error != 0));
5295 
5296 		/*
5297 		 * Force close in case of timeout
5298 		 */
5299 		if (error != 0) {
5300 			OSIncrementAtomic(&cfil_stats.cfs_close_wait_timeout);
5301 			break;
5302 		}
5303 	}
5304 }
5305 
5306 /*
5307  * Returns the size of the data held by the content filter by using
5308  */
5309 int32_t
cfil_sock_data_pending(struct sockbuf * sb)5310 cfil_sock_data_pending(struct sockbuf *sb)
5311 {
5312 	struct socket *so = sb->sb_so;
5313 	uint64_t pending = 0;
5314 
5315 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
5316 		return cfil_sock_udp_data_pending(sb, FALSE);
5317 	}
5318 
5319 	if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_cfil != NULL) {
5320 		struct cfi_buf *cfi_buf;
5321 
5322 		socket_lock_assert_owned(so);
5323 
5324 		if ((sb->sb_flags & SB_RECV) == 0) {
5325 			cfi_buf = &so->so_cfil->cfi_snd;
5326 		} else {
5327 			cfi_buf = &so->so_cfil->cfi_rcv;
5328 		}
5329 
5330 		pending = cfi_buf->cfi_pending_last -
5331 		    cfi_buf->cfi_pending_first;
5332 
5333 		/*
5334 		 * If we are limited by the "chars of mbufs used" roughly
5335 		 * adjust so we won't overcommit
5336 		 */
5337 		if (pending > (uint64_t)cfi_buf->cfi_pending_mbcnt) {
5338 			pending = cfi_buf->cfi_pending_mbcnt;
5339 		}
5340 	}
5341 
5342 	VERIFY(pending < INT32_MAX);
5343 
5344 	return (int32_t)(pending);
5345 }
5346 
5347 /*
5348  * Return the socket buffer space used by data being held by content filters
5349  * so processes won't clog the socket buffer
5350  */
5351 int32_t
cfil_sock_data_space(struct sockbuf * sb)5352 cfil_sock_data_space(struct sockbuf *sb)
5353 {
5354 	struct socket *so = sb->sb_so;
5355 	uint64_t pending = 0;
5356 
5357 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
5358 		return cfil_sock_udp_data_pending(sb, TRUE);
5359 	}
5360 
5361 	if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_cfil != NULL &&
5362 	    so->so_snd.sb_cfil_thread != current_thread()) {
5363 		struct cfi_buf *cfi_buf;
5364 
5365 		socket_lock_assert_owned(so);
5366 
5367 		if ((sb->sb_flags & SB_RECV) == 0) {
5368 			cfi_buf = &so->so_cfil->cfi_snd;
5369 		} else {
5370 			cfi_buf = &so->so_cfil->cfi_rcv;
5371 		}
5372 
5373 		pending = cfi_buf->cfi_pending_last -
5374 		    cfi_buf->cfi_pending_first;
5375 
5376 		/*
5377 		 * If we are limited by the "chars of mbufs used" roughly
5378 		 * adjust so we won't overcommit
5379 		 */
5380 		if ((uint64_t)cfi_buf->cfi_pending_mbcnt > pending) {
5381 			pending = cfi_buf->cfi_pending_mbcnt;
5382 		}
5383 	}
5384 
5385 	VERIFY(pending < INT32_MAX);
5386 
5387 	return (int32_t)(pending);
5388 }
5389 
5390 /*
5391  * A callback from the socket and protocol layer when data becomes
5392  * available in the socket buffer to give a chance for the content filter
5393  * to re-inject data that was held back
5394  */
5395 void
cfil_sock_buf_update(struct sockbuf * sb)5396 cfil_sock_buf_update(struct sockbuf *sb)
5397 {
5398 	int outgoing;
5399 	int error;
5400 	struct socket *so = sb->sb_so;
5401 
5402 	if (NEED_DGRAM_FLOW_TRACKING(so)) {
5403 		cfil_sock_udp_buf_update(sb);
5404 		return;
5405 	}
5406 
5407 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || so->so_cfil == NULL) {
5408 		return;
5409 	}
5410 
5411 	if (!cfil_sbtrim) {
5412 		return;
5413 	}
5414 
5415 	socket_lock_assert_owned(so);
5416 
5417 	if ((sb->sb_flags & SB_RECV) == 0) {
5418 		if ((so->so_cfil->cfi_flags & CFIF_RETRY_INJECT_OUT) == 0) {
5419 			return;
5420 		}
5421 		outgoing = 1;
5422 		OSIncrementAtomic(&cfil_stats.cfs_inject_q_out_retry);
5423 	} else {
5424 		if ((so->so_cfil->cfi_flags & CFIF_RETRY_INJECT_IN) == 0) {
5425 			return;
5426 		}
5427 		outgoing = 0;
5428 		OSIncrementAtomic(&cfil_stats.cfs_inject_q_in_retry);
5429 	}
5430 
5431 	CFIL_LOG(LOG_NOTICE, "so %llx outgoing %d",
5432 	    (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing);
5433 
5434 	error = cfil_acquire_sockbuf(so, so->so_cfil, outgoing);
5435 	if (error == 0) {
5436 		cfil_service_inject_queue(so, so->so_cfil, outgoing);
5437 	}
5438 	cfil_release_sockbuf(so, outgoing);
5439 }
5440 
5441 int
sysctl_cfil_filter_list(struct sysctl_oid * oidp,void * arg1,int arg2,struct sysctl_req * req)5442 sysctl_cfil_filter_list(struct sysctl_oid *oidp, void *arg1, int arg2,
5443     struct sysctl_req *req)
5444 {
5445 #pragma unused(oidp, arg1, arg2)
5446 	int error = 0;
5447 	size_t len = 0;
5448 	u_int32_t i;
5449 
5450 	/* Read only  */
5451 	if (req->newptr != USER_ADDR_NULL) {
5452 		return EPERM;
5453 	}
5454 
5455 	cfil_rw_lock_shared(&cfil_lck_rw);
5456 
5457 	for (i = 0; i < MAX_CONTENT_FILTER; i++) {
5458 		struct cfil_filter_stat filter_stat;
5459 		struct content_filter *cfc = content_filters[i];
5460 
5461 		if (cfc == NULL) {
5462 			continue;
5463 		}
5464 
5465 		/* If just asking for the size */
5466 		if (req->oldptr == USER_ADDR_NULL) {
5467 			len += sizeof(struct cfil_filter_stat);
5468 			continue;
5469 		}
5470 
5471 		bzero(&filter_stat, sizeof(struct cfil_filter_stat));
5472 		filter_stat.cfs_len = sizeof(struct cfil_filter_stat);
5473 		filter_stat.cfs_filter_id = cfc->cf_kcunit;
5474 		filter_stat.cfs_flags = cfc->cf_flags;
5475 		filter_stat.cfs_sock_count = cfc->cf_sock_count;
5476 		filter_stat.cfs_necp_control_unit = cfc->cf_necp_control_unit;
5477 
5478 		error = SYSCTL_OUT(req, &filter_stat,
5479 		    sizeof(struct cfil_filter_stat));
5480 		if (error != 0) {
5481 			break;
5482 		}
5483 	}
5484 	/* If just asking for the size */
5485 	if (req->oldptr == USER_ADDR_NULL) {
5486 		req->oldidx = len;
5487 	}
5488 
5489 	cfil_rw_unlock_shared(&cfil_lck_rw);
5490 
5491 	if (cfil_log_level >= LOG_DEBUG) {
5492 		if (req->oldptr != USER_ADDR_NULL) {
5493 			for (i = 1; i <= MAX_CONTENT_FILTER; i++) {
5494 				cfil_filter_show(i);
5495 			}
5496 		}
5497 	}
5498 
5499 	return error;
5500 }
5501 
5502 static int
sysctl_cfil_sock_list(struct sysctl_oid * oidp,void * arg1,int arg2,struct sysctl_req * req)5503 sysctl_cfil_sock_list(struct sysctl_oid *oidp, void *arg1, int arg2,
5504     struct sysctl_req *req)
5505 {
5506 #pragma unused(oidp, arg1, arg2)
5507 	int error = 0;
5508 	u_int32_t i;
5509 	struct cfil_info *cfi;
5510 
5511 	/* Read only  */
5512 	if (req->newptr != USER_ADDR_NULL) {
5513 		return EPERM;
5514 	}
5515 
5516 	cfil_rw_lock_shared(&cfil_lck_rw);
5517 
5518 	/*
5519 	 * If just asking for the size,
5520 	 */
5521 	if (req->oldptr == USER_ADDR_NULL) {
5522 		req->oldidx = cfil_sock_attached_count *
5523 		    sizeof(struct cfil_sock_stat);
5524 		/* Bump the length in case new sockets gets attached */
5525 		req->oldidx += req->oldidx >> 3;
5526 		goto done;
5527 	}
5528 
5529 	TAILQ_FOREACH(cfi, &cfil_sock_head, cfi_link) {
5530 		struct cfil_entry *entry;
5531 		struct cfil_sock_stat stat;
5532 		struct socket *so = cfi->cfi_so;
5533 
5534 		bzero(&stat, sizeof(struct cfil_sock_stat));
5535 		stat.cfs_len = sizeof(struct cfil_sock_stat);
5536 		stat.cfs_sock_id = cfi->cfi_sock_id;
5537 		stat.cfs_flags = cfi->cfi_flags;
5538 
5539 		if (so != NULL) {
5540 			stat.cfs_pid = so->last_pid;
5541 			memcpy(stat.cfs_uuid, so->last_uuid,
5542 			    sizeof(uuid_t));
5543 			if (so->so_flags & SOF_DELEGATED) {
5544 				stat.cfs_e_pid = so->e_pid;
5545 				memcpy(stat.cfs_e_uuid, so->e_uuid,
5546 				    sizeof(uuid_t));
5547 			} else {
5548 				stat.cfs_e_pid = so->last_pid;
5549 				memcpy(stat.cfs_e_uuid, so->last_uuid,
5550 				    sizeof(uuid_t));
5551 			}
5552 
5553 			stat.cfs_sock_family = so->so_proto->pr_domain->dom_family;
5554 			stat.cfs_sock_type = so->so_proto->pr_type;
5555 			stat.cfs_sock_protocol = so->so_proto->pr_protocol;
5556 		}
5557 
5558 		stat.cfs_snd.cbs_pending_first =
5559 		    cfi->cfi_snd.cfi_pending_first;
5560 		stat.cfs_snd.cbs_pending_last =
5561 		    cfi->cfi_snd.cfi_pending_last;
5562 		stat.cfs_snd.cbs_inject_q_len =
5563 		    cfil_queue_len(&cfi->cfi_snd.cfi_inject_q);
5564 		stat.cfs_snd.cbs_pass_offset =
5565 		    cfi->cfi_snd.cfi_pass_offset;
5566 
5567 		stat.cfs_rcv.cbs_pending_first =
5568 		    cfi->cfi_rcv.cfi_pending_first;
5569 		stat.cfs_rcv.cbs_pending_last =
5570 		    cfi->cfi_rcv.cfi_pending_last;
5571 		stat.cfs_rcv.cbs_inject_q_len =
5572 		    cfil_queue_len(&cfi->cfi_rcv.cfi_inject_q);
5573 		stat.cfs_rcv.cbs_pass_offset =
5574 		    cfi->cfi_rcv.cfi_pass_offset;
5575 
5576 		for (i = 0; i < MAX_CONTENT_FILTER; i++) {
5577 			struct cfil_entry_stat *estat;
5578 			struct cfe_buf *ebuf;
5579 			struct cfe_buf_stat *sbuf;
5580 
5581 			entry = &cfi->cfi_entries[i];
5582 
5583 			estat = &stat.ces_entries[i];
5584 
5585 			estat->ces_len = sizeof(struct cfil_entry_stat);
5586 			estat->ces_filter_id = entry->cfe_filter ?
5587 			    entry->cfe_filter->cf_kcunit : 0;
5588 			estat->ces_flags = entry->cfe_flags;
5589 			estat->ces_necp_control_unit =
5590 			    entry->cfe_necp_control_unit;
5591 
5592 			estat->ces_last_event.tv_sec =
5593 			    (int64_t)entry->cfe_last_event.tv_sec;
5594 			estat->ces_last_event.tv_usec =
5595 			    (int64_t)entry->cfe_last_event.tv_usec;
5596 
5597 			estat->ces_last_action.tv_sec =
5598 			    (int64_t)entry->cfe_last_action.tv_sec;
5599 			estat->ces_last_action.tv_usec =
5600 			    (int64_t)entry->cfe_last_action.tv_usec;
5601 
5602 			ebuf = &entry->cfe_snd;
5603 			sbuf = &estat->ces_snd;
5604 			sbuf->cbs_pending_first =
5605 			    cfil_queue_offset_first(&ebuf->cfe_pending_q);
5606 			sbuf->cbs_pending_last =
5607 			    cfil_queue_offset_last(&ebuf->cfe_pending_q);
5608 			sbuf->cbs_ctl_first =
5609 			    cfil_queue_offset_first(&ebuf->cfe_ctl_q);
5610 			sbuf->cbs_ctl_last =
5611 			    cfil_queue_offset_last(&ebuf->cfe_ctl_q);
5612 			sbuf->cbs_pass_offset =  ebuf->cfe_pass_offset;
5613 			sbuf->cbs_peek_offset =  ebuf->cfe_peek_offset;
5614 			sbuf->cbs_peeked =  ebuf->cfe_peeked;
5615 
5616 			ebuf = &entry->cfe_rcv;
5617 			sbuf = &estat->ces_rcv;
5618 			sbuf->cbs_pending_first =
5619 			    cfil_queue_offset_first(&ebuf->cfe_pending_q);
5620 			sbuf->cbs_pending_last =
5621 			    cfil_queue_offset_last(&ebuf->cfe_pending_q);
5622 			sbuf->cbs_ctl_first =
5623 			    cfil_queue_offset_first(&ebuf->cfe_ctl_q);
5624 			sbuf->cbs_ctl_last =
5625 			    cfil_queue_offset_last(&ebuf->cfe_ctl_q);
5626 			sbuf->cbs_pass_offset =  ebuf->cfe_pass_offset;
5627 			sbuf->cbs_peek_offset =  ebuf->cfe_peek_offset;
5628 			sbuf->cbs_peeked =  ebuf->cfe_peeked;
5629 		}
5630 		error = SYSCTL_OUT(req, &stat,
5631 		    sizeof(struct cfil_sock_stat));
5632 		if (error != 0) {
5633 			break;
5634 		}
5635 	}
5636 done:
5637 	cfil_rw_unlock_shared(&cfil_lck_rw);
5638 
5639 	if (cfil_log_level >= LOG_DEBUG) {
5640 		if (req->oldptr != USER_ADDR_NULL) {
5641 			cfil_info_show();
5642 		}
5643 	}
5644 
5645 	return error;
5646 }
5647 
5648 /*
5649  * UDP Socket Support
5650  */
5651 static void
cfil_hash_entry_log(int level,struct socket * so,struct soflow_hash_entry * entry,uint64_t sockId,const char * msg)5652 cfil_hash_entry_log(int level, struct socket *so, struct soflow_hash_entry *entry, uint64_t sockId, const char* msg)
5653 {
5654 	char local[MAX_IPv6_STR_LEN + 6];
5655 	char remote[MAX_IPv6_STR_LEN + 6];
5656 	const void  *addr;
5657 
5658 	// No sock or not UDP, no-op
5659 	if (so == NULL || entry == NULL) {
5660 		return;
5661 	}
5662 
5663 	local[0] = remote[0] = 0x0;
5664 
5665 	switch (entry->soflow_family) {
5666 	case AF_INET6:
5667 		addr = &entry->soflow_laddr.addr6;
5668 		inet_ntop(AF_INET6, addr, local, sizeof(local));
5669 		addr = &entry->soflow_faddr.addr6;
5670 		inet_ntop(AF_INET6, addr, remote, sizeof(local));
5671 		break;
5672 	case AF_INET:
5673 		addr = &entry->soflow_laddr.addr46.ia46_addr4.s_addr;
5674 		inet_ntop(AF_INET, addr, local, sizeof(local));
5675 		addr = &entry->soflow_faddr.addr46.ia46_addr4.s_addr;
5676 		inet_ntop(AF_INET, addr, remote, sizeof(local));
5677 		break;
5678 	default:
5679 		return;
5680 	}
5681 
5682 	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",
5683 	    msg,
5684 	    IS_UDP(so) ? "UDP" : "proto", GET_SO_PROTO(so),
5685 	    (uint64_t)VM_KERNEL_ADDRPERM(so), entry->soflow_feat_ctxt, entry, sockId, entry->soflow_feat_ctxt_id,
5686 	    ntohs(entry->soflow_lport), ntohs(entry->soflow_fport), local, remote,
5687 	    entry->soflow_flowhash);
5688 }
5689 
5690 static void
cfil_inp_log(int level,struct socket * so,const char * msg)5691 cfil_inp_log(int level, struct socket *so, const char* msg)
5692 {
5693 	struct inpcb *inp = NULL;
5694 	char local[MAX_IPv6_STR_LEN + 6];
5695 	char remote[MAX_IPv6_STR_LEN + 6];
5696 	const void  *addr;
5697 
5698 	if (so == NULL) {
5699 		return;
5700 	}
5701 
5702 	inp = sotoinpcb(so);
5703 	if (inp == NULL) {
5704 		return;
5705 	}
5706 
5707 	local[0] = remote[0] = 0x0;
5708 
5709 	if (inp->inp_vflag & INP_IPV6) {
5710 		addr = &inp->in6p_laddr.s6_addr32;
5711 		inet_ntop(AF_INET6, addr, local, sizeof(local));
5712 		addr = &inp->in6p_faddr.s6_addr32;
5713 		inet_ntop(AF_INET6, addr, remote, sizeof(local));
5714 	} else {
5715 		addr = &inp->inp_laddr.s_addr;
5716 		inet_ntop(AF_INET, addr, local, sizeof(local));
5717 		addr = &inp->inp_faddr.s_addr;
5718 		inet_ntop(AF_INET, addr, remote, sizeof(local));
5719 	}
5720 
5721 	if (so->so_cfil != NULL) {
5722 		CFIL_LOG(level, "<%s>: <%s so %llx cfil %p - flags 0x%x 0x%x, sockID %llu> lport %d fport %d laddr %s faddr %s",
5723 		    msg, IS_UDP(so) ? "UDP" : "TCP",
5724 		    (uint64_t)VM_KERNEL_ADDRPERM(so), so->so_cfil, inp->inp_flags, inp->inp_socket->so_flags, so->so_cfil->cfi_sock_id,
5725 		    ntohs(inp->inp_lport), ntohs(inp->inp_fport), local, remote);
5726 	} else {
5727 		CFIL_LOG(level, "<%s>: <%s so %llx - flags 0x%x 0x%x> lport %d fport %d laddr %s faddr %s",
5728 		    msg, IS_UDP(so) ? "UDP" : "TCP",
5729 		    (uint64_t)VM_KERNEL_ADDRPERM(so), inp->inp_flags, inp->inp_socket->so_flags,
5730 		    ntohs(inp->inp_lport), ntohs(inp->inp_fport), local, remote);
5731 	}
5732 }
5733 
5734 static void
cfil_info_log(int level,struct cfil_info * cfil_info,const char * msg)5735 cfil_info_log(int level, struct cfil_info *cfil_info, const char* msg)
5736 {
5737 	if (cfil_info == NULL) {
5738 		return;
5739 	}
5740 
5741 	if (cfil_info->cfi_hash_entry != NULL) {
5742 		cfil_hash_entry_log(level, cfil_info->cfi_so, cfil_info->cfi_hash_entry, cfil_info->cfi_sock_id, msg);
5743 	} else {
5744 		cfil_inp_log(level, cfil_info->cfi_so, msg);
5745 	}
5746 }
5747 
5748 static void
cfil_sock_udp_unlink_flow(struct socket * so,struct soflow_hash_entry * hash_entry,struct cfil_info * cfil_info)5749 cfil_sock_udp_unlink_flow(struct socket *so, struct soflow_hash_entry *hash_entry, struct cfil_info *cfil_info)
5750 {
5751 	if (so == NULL || hash_entry == NULL || cfil_info == NULL) {
5752 		return;
5753 	}
5754 
5755 	if (so->so_flags & SOF_CONTENT_FILTER) {
5756 		VERIFY(so->so_usecount > 0);
5757 		so->so_usecount--;
5758 	}
5759 
5760 	// Hold exclusive lock before clearing cfil_info hash entry link
5761 	cfil_rw_lock_exclusive(&cfil_lck_rw);
5762 
5763 	cfil_info->cfi_hash_entry = NULL;
5764 
5765 	if (cfil_info->cfi_debug) {
5766 		CFIL_LOG(LOG_INFO, "CFIL <%s>: <so %llx> - use count %d",
5767 		    IS_UDP(so) ? "UDP" : "TCP", (uint64_t)VM_KERNEL_ADDRPERM(so), so->so_usecount);
5768 	}
5769 
5770 	cfil_rw_unlock_exclusive(&cfil_lck_rw);
5771 }
5772 
5773 bool
check_port(struct sockaddr * addr,u_short port)5774 check_port(struct sockaddr *addr, u_short port)
5775 {
5776 	struct sockaddr_in *sin = NULL;
5777 	struct sockaddr_in6 *sin6 = NULL;
5778 
5779 	if (addr == NULL || port == 0) {
5780 		return FALSE;
5781 	}
5782 
5783 	switch (addr->sa_family) {
5784 	case AF_INET:
5785 		sin = satosin(addr);
5786 		if (sin->sin_len != sizeof(*sin)) {
5787 			return FALSE;
5788 		}
5789 		if (port == ntohs(sin->sin_port)) {
5790 			return TRUE;
5791 		}
5792 		break;
5793 	case AF_INET6:
5794 		sin6 = satosin6(addr);
5795 		if (sin6->sin6_len != sizeof(*sin6)) {
5796 			return FALSE;
5797 		}
5798 		if (port == ntohs(sin6->sin6_port)) {
5799 			return TRUE;
5800 		}
5801 		break;
5802 	default:
5803 		break;
5804 	}
5805 	return FALSE;
5806 }
5807 
5808 cfil_sock_id_t
cfil_sock_id_from_datagram_socket(struct socket * so,struct sockaddr * local,struct sockaddr * remote)5809 cfil_sock_id_from_datagram_socket(struct socket *so, struct sockaddr *local, struct sockaddr *remote)
5810 {
5811 	socket_lock_assert_owned(so);
5812 
5813 	if (so->so_flow_db == NULL) {
5814 		return CFIL_SOCK_ID_NONE;
5815 	}
5816 	return (cfil_sock_id_t)soflow_db_get_feature_context_id(so->so_flow_db, local, remote);
5817 }
5818 
5819 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)5820 cfil_sock_udp_get_info(struct socket *so, uint32_t filter_control_unit, bool outgoing, struct soflow_hash_entry *hash_entry,
5821     struct sockaddr *local, struct sockaddr *remote)
5822 {
5823 	int new_filter_control_unit = 0;
5824 	struct cfil_info *cfil_info = NULL;
5825 
5826 	errno_t error = 0;
5827 	socket_lock_assert_owned(so);
5828 
5829 	if (hash_entry == NULL || hash_entry->soflow_db == NULL) {
5830 		return NULL;
5831 	}
5832 
5833 	if (hash_entry->soflow_feat_ctxt != NULL && hash_entry->soflow_feat_ctxt_id != 0) {
5834 		/* Drop pre-existing UDP flow if filter state changed */
5835 		cfil_info = (struct cfil_info *) hash_entry->soflow_feat_ctxt;
5836 		new_filter_control_unit = necp_socket_get_content_filter_control_unit(so);
5837 		if (new_filter_control_unit > 0 &&
5838 		    new_filter_control_unit != cfil_info->cfi_filter_control_unit) {
5839 			if (DO_PRESERVE_CONNECTIONS) {
5840 				cfil_info->cfi_filter_control_unit = new_filter_control_unit;
5841 			} else {
5842 				CFIL_LOG(LOG_NOTICE, "CFIL: UDP(%s) <so %llx> - filter state changed - dropped pre-existing flow (old state 0x%x new state 0x%x)",
5843 				    outgoing ? "OUT" : "IN", (uint64_t)VM_KERNEL_ADDRPERM(so),
5844 				    cfil_info->cfi_filter_control_unit, new_filter_control_unit);
5845 				return NULL;
5846 			}
5847 		}
5848 		return cfil_info;
5849 	}
5850 
5851 	cfil_info = cfil_info_alloc(so, hash_entry);
5852 	if (cfil_info == NULL) {
5853 		CFIL_LOG(LOG_ERR, "CFIL: UDP failed to alloc cfil_info");
5854 		OSIncrementAtomic(&cfil_stats.cfs_sock_attach_no_mem);
5855 		return NULL;
5856 	}
5857 	cfil_info->cfi_filter_control_unit = filter_control_unit;
5858 	cfil_info->cfi_dir = outgoing ? CFS_CONNECTION_DIR_OUT : CFS_CONNECTION_DIR_IN;
5859 	cfil_info->cfi_debug = DEBUG_FLOW(sotoinpcb(so), so, local, remote);
5860 	if (cfil_info->cfi_debug) {
5861 		CFIL_LOG(LOG_INFO, "CFIL: UDP (outgoing %d) - debug flow with port %d", outgoing, cfil_log_port);
5862 		CFIL_LOG(LOG_INFO, "CFIL: UDP so_gencnt %llx entry flowhash %x cfil %p sockID %llx",
5863 		    so->so_gencnt, hash_entry->soflow_flowhash, cfil_info, cfil_info->cfi_sock_id);
5864 	}
5865 
5866 	if (cfil_info_attach_unit(so, filter_control_unit, cfil_info) == 0) {
5867 		CFIL_INFO_FREE(cfil_info);
5868 		CFIL_LOG(LOG_ERR, "CFIL: UDP cfil_info_attach_unit(%u) failed",
5869 		    filter_control_unit);
5870 		OSIncrementAtomic(&cfil_stats.cfs_sock_attach_failed);
5871 		return NULL;
5872 	}
5873 
5874 	if (cfil_info->cfi_debug) {
5875 		CFIL_LOG(LOG_DEBUG, "CFIL: UDP <so %llx> filter_control_unit %u sockID %llu attached",
5876 		    (uint64_t)VM_KERNEL_ADDRPERM(so),
5877 		    filter_control_unit, cfil_info->cfi_sock_id);
5878 	}
5879 
5880 	so->so_flags |= SOF_CONTENT_FILTER;
5881 	OSIncrementAtomic(&cfil_stats.cfs_sock_attached);
5882 
5883 	/* Hold a reference on the socket for each flow */
5884 	so->so_usecount++;
5885 
5886 	/* link cfil_info to flow */
5887 	hash_entry->soflow_feat_ctxt = cfil_info;
5888 	hash_entry->soflow_feat_ctxt_id = cfil_info->cfi_sock_id;
5889 
5890 	if (cfil_info->cfi_debug) {
5891 		cfil_info_log(LOG_INFO, cfil_info, "CFIL: ADDED");
5892 	}
5893 
5894 	error = cfil_dispatch_attach_event(so, cfil_info, 0,
5895 	    outgoing ? CFS_CONNECTION_DIR_OUT : CFS_CONNECTION_DIR_IN);
5896 	/* We can recover from flow control or out of memory errors */
5897 	if (error != 0 && error != ENOBUFS && error != ENOMEM) {
5898 		return NULL;
5899 	}
5900 
5901 	CFIL_INFO_VERIFY(cfil_info);
5902 	return cfil_info;
5903 }
5904 
5905 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)5906 cfil_sock_udp_handle_data(bool outgoing, struct socket *so,
5907     struct sockaddr *local, struct sockaddr *remote,
5908     struct mbuf *data, struct mbuf *control, uint32_t flags,
5909     struct soflow_hash_entry *hash_entry)
5910 {
5911 #pragma unused(outgoing, so, local, remote, data, control, flags)
5912 	errno_t error = 0;
5913 	uint32_t filter_control_unit;
5914 	struct cfil_info *cfil_info = NULL;
5915 
5916 	socket_lock_assert_owned(so);
5917 
5918 	if (cfil_active_count == 0) {
5919 		CFIL_LOG(LOG_DEBUG, "CFIL: UDP no active filter");
5920 		OSIncrementAtomic(&cfil_stats.cfs_sock_attach_in_vain);
5921 		return error;
5922 	}
5923 
5924 	// Socket has been blessed
5925 	if ((so->so_flags1 & SOF1_CONTENT_FILTER_SKIP) != 0) {
5926 		return error;
5927 	}
5928 
5929 	filter_control_unit = necp_socket_get_content_filter_control_unit(so);
5930 	if (filter_control_unit == 0) {
5931 		CFIL_LOG(LOG_DEBUG, "CFIL: UDP failed to get control unit");
5932 		return error;
5933 	}
5934 
5935 	if (filter_control_unit == NECP_FILTER_UNIT_NO_FILTER) {
5936 		return error;
5937 	}
5938 
5939 	if ((filter_control_unit & NECP_MASK_USERSPACE_ONLY) != 0) {
5940 		CFIL_LOG(LOG_DEBUG, "CFIL: UDP user space only");
5941 		OSIncrementAtomic(&cfil_stats.cfs_sock_userspace_only);
5942 		return error;
5943 	}
5944 
5945 	cfil_info = cfil_sock_udp_get_info(so, filter_control_unit, outgoing, hash_entry, local, remote);
5946 	if (cfil_info == NULL) {
5947 		CFIL_LOG(LOG_ERR, "CFIL: <so %llx> Falied to get UDP cfil_info", (uint64_t)VM_KERNEL_ADDRPERM(so));
5948 		return EPIPE;
5949 	}
5950 	// Update last used timestamp, this is for flow Idle TO
5951 
5952 	if (cfil_info->cfi_debug) {
5953 		cfil_info_log(LOG_DEBUG, cfil_info, "CFIL: Got flow");
5954 	}
5955 
5956 	if (cfil_info->cfi_flags & CFIF_DROP) {
5957 		if (cfil_info->cfi_debug) {
5958 			cfil_info_log(LOG_INFO, cfil_info, "CFIL: UDP DROP");
5959 		}
5960 		return EPIPE;
5961 	}
5962 	if (control != NULL) {
5963 		OSIncrementAtomic(&cfil_stats.cfs_data_in_control);
5964 	}
5965 	if (data->m_type == MT_OOBDATA) {
5966 		CFIL_LOG(LOG_ERR, "so %llx MSG_OOB",
5967 		    (uint64_t)VM_KERNEL_ADDRPERM(so));
5968 		OSIncrementAtomic(&cfil_stats.cfs_data_in_oob);
5969 	}
5970 
5971 	error = cfil_data_common(so, cfil_info, outgoing, remote, data, control, flags);
5972 
5973 	return error;
5974 }
5975 
5976 struct cfil_udp_attached_context {
5977 	bool need_wait;
5978 	lck_mtx_t *mutex_held;
5979 	int attached;
5980 };
5981 
5982 static bool
cfil_filters_udp_attached_per_flow(struct socket * so,struct soflow_hash_entry * hash_entry,void * context)5983 cfil_filters_udp_attached_per_flow(struct socket *so,
5984     struct soflow_hash_entry *hash_entry,
5985     void *context)
5986 {
5987 	struct cfil_udp_attached_context *apply_context = NULL;
5988 	struct cfil_info *cfil_info = NULL;
5989 	struct cfil_entry *entry = NULL;
5990 	uint64_t sock_flow_id = 0;
5991 	struct timespec ts;
5992 	errno_t error = 0;
5993 	int kcunit;
5994 
5995 	if (hash_entry->soflow_feat_ctxt == NULL || context == NULL) {
5996 		return true;
5997 	}
5998 
5999 	cfil_info = hash_entry->soflow_feat_ctxt;
6000 	apply_context = (struct cfil_udp_attached_context *)context;
6001 
6002 	for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
6003 		entry = &cfil_info->cfi_entries[kcunit - 1];
6004 
6005 		/* Are we attached to the filter? */
6006 		if (entry->cfe_filter == NULL) {
6007 			continue;
6008 		}
6009 
6010 		if ((entry->cfe_flags & CFEF_SENT_SOCK_ATTACHED) == 0) {
6011 			continue;
6012 		}
6013 		if ((entry->cfe_flags & CFEF_CFIL_DETACHED) != 0) {
6014 			continue;
6015 		}
6016 
6017 		apply_context->attached = 1;
6018 
6019 		if (apply_context->need_wait == TRUE) {
6020 			if (cfil_info->cfi_debug) {
6021 				cfil_info_log(LOG_INFO, cfil_info, "CFIL: UDP PER-FLOW WAIT FOR FLOW TO FINISH");
6022 			}
6023 
6024 			ts.tv_sec = cfil_close_wait_timeout / 1000;
6025 			ts.tv_nsec = (cfil_close_wait_timeout % 1000) * NSEC_PER_USEC * 1000;
6026 
6027 			OSIncrementAtomic(&cfil_stats.cfs_close_wait);
6028 			cfil_info->cfi_flags |= CFIF_CLOSE_WAIT;
6029 			sock_flow_id = cfil_info->cfi_sock_id;
6030 
6031 			error = msleep((caddr_t)cfil_info, apply_context->mutex_held,
6032 			    PSOCK | PCATCH, "cfil_filters_udp_attached_per_flow", &ts);
6033 
6034 			// Woke up from sleep, validate if cfil_info is still valid
6035 			if (so->so_flow_db == NULL ||
6036 			    (cfil_info != soflow_db_get_feature_context(so->so_flow_db, sock_flow_id))) {
6037 				// cfil_info is not valid, do not continue
6038 				return false;
6039 			}
6040 
6041 			cfil_info->cfi_flags &= ~CFIF_CLOSE_WAIT;
6042 
6043 			if (cfil_info->cfi_debug) {
6044 				cfil_info_log(LOG_INFO, cfil_info, "CFIL: UDP PER-FLOW WAIT FOR FLOW DONE");
6045 			}
6046 
6047 			/*
6048 			 * Force close in case of timeout
6049 			 */
6050 			if (error != 0) {
6051 				OSIncrementAtomic(&cfil_stats.cfs_close_wait_timeout);
6052 
6053 				if (cfil_info->cfi_debug) {
6054 					cfil_info_log(LOG_INFO, cfil_info, "CFIL: UDP PER-FLOW WAIT FOR FLOW TIMED OUT, FORCE DETACH");
6055 				}
6056 
6057 				entry->cfe_flags |= CFEF_CFIL_DETACHED;
6058 			}
6059 		}
6060 		return false;
6061 	}
6062 	return true;
6063 }
6064 
6065 /*
6066  * Go through all UDP flows for specified socket and returns TRUE if
6067  * any flow is still attached.  If need_wait is TRUE, wait on first
6068  * attached flow.
6069  */
6070 static int
cfil_filters_udp_attached(struct socket * so,bool need_wait)6071 cfil_filters_udp_attached(struct socket *so, bool need_wait)
6072 {
6073 	struct cfil_udp_attached_context apply_context = { 0 };
6074 	lck_mtx_t *mutex_held;
6075 
6076 	socket_lock_assert_owned(so);
6077 
6078 	if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_flow_db != NULL) {
6079 		if (so->so_proto->pr_getlock != NULL) {
6080 			mutex_held = (*so->so_proto->pr_getlock)(so, PR_F_WILLUNLOCK);
6081 		} else {
6082 			mutex_held = so->so_proto->pr_domain->dom_mtx;
6083 		}
6084 		LCK_MTX_ASSERT(mutex_held, LCK_MTX_ASSERT_OWNED);
6085 
6086 		apply_context.need_wait = need_wait;
6087 		apply_context.mutex_held = mutex_held;
6088 		soflow_db_apply(so->so_flow_db, cfil_filters_udp_attached_per_flow, (void *)&apply_context);
6089 	}
6090 
6091 	return apply_context.attached;
6092 }
6093 
6094 struct cfil_udp_data_pending_context {
6095 	struct sockbuf *sb;
6096 	uint64_t total_pending;
6097 };
6098 
6099 static bool
cfil_sock_udp_data_pending_per_flow(struct socket * so,struct soflow_hash_entry * hash_entry,void * context)6100 cfil_sock_udp_data_pending_per_flow(struct socket *so,
6101     struct soflow_hash_entry *hash_entry,
6102     void *context)
6103 {
6104 #pragma unused(so)
6105 	struct cfil_udp_data_pending_context *apply_context = NULL;
6106 	struct cfil_info *cfil_info = NULL;
6107 	struct cfi_buf *cfi_buf;
6108 
6109 	uint64_t pending = 0;
6110 
6111 	if (hash_entry->soflow_feat_ctxt == NULL || context == NULL) {
6112 		return true;
6113 	}
6114 
6115 	cfil_info = hash_entry->soflow_feat_ctxt;
6116 	apply_context = (struct cfil_udp_data_pending_context *)context;
6117 
6118 	if (apply_context->sb == NULL) {
6119 		return true;
6120 	}
6121 
6122 	if ((apply_context->sb->sb_flags & SB_RECV) == 0) {
6123 		cfi_buf = &cfil_info->cfi_snd;
6124 	} else {
6125 		cfi_buf = &cfil_info->cfi_rcv;
6126 	}
6127 
6128 	pending = cfi_buf->cfi_pending_last - cfi_buf->cfi_pending_first;
6129 	/*
6130 	 * If we are limited by the "chars of mbufs used" roughly
6131 	 * adjust so we won't overcommit
6132 	 */
6133 	if ((uint64_t)cfi_buf->cfi_pending_mbcnt > pending) {
6134 		pending = cfi_buf->cfi_pending_mbcnt;
6135 	}
6136 
6137 	apply_context->total_pending += pending;
6138 	return true;
6139 }
6140 
6141 int32_t
cfil_sock_udp_data_pending(struct sockbuf * sb,bool check_thread)6142 cfil_sock_udp_data_pending(struct sockbuf *sb, bool check_thread)
6143 {
6144 	struct cfil_udp_data_pending_context apply_context = { 0 };
6145 	struct socket *so = sb->sb_so;
6146 
6147 	socket_lock_assert_owned(so);
6148 
6149 	if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_flow_db != NULL &&
6150 	    (check_thread == FALSE || so->so_snd.sb_cfil_thread != current_thread())) {
6151 		apply_context.sb = sb;
6152 		soflow_db_apply(so->so_flow_db, cfil_sock_udp_data_pending_per_flow, (void *)&apply_context);
6153 
6154 		VERIFY(apply_context.total_pending < INT32_MAX);
6155 	}
6156 
6157 	return (int32_t)(apply_context.total_pending);
6158 }
6159 
6160 struct cfil_udp_notify_shutdown_context {
6161 	int how;
6162 	int drop_flag;
6163 	int shut_flag;
6164 	int done_count;
6165 };
6166 
6167 static bool
cfil_sock_udp_notify_shutdown_per_flow(struct socket * so,struct soflow_hash_entry * hash_entry,void * context)6168 cfil_sock_udp_notify_shutdown_per_flow(struct socket *so,
6169     struct soflow_hash_entry *hash_entry,
6170     void *context)
6171 {
6172 	struct cfil_udp_notify_shutdown_context *apply_context = NULL;
6173 	struct cfil_info *cfil_info = NULL;
6174 	errno_t error = 0;
6175 	int kcunit;
6176 
6177 	if (hash_entry->soflow_feat_ctxt == NULL || context == NULL) {
6178 		return true;
6179 	}
6180 
6181 	cfil_info = hash_entry->soflow_feat_ctxt;
6182 	apply_context = (struct cfil_udp_notify_shutdown_context *)context;
6183 
6184 	// This flow is marked as DROP
6185 	if (cfil_info->cfi_flags & apply_context->drop_flag) {
6186 		apply_context->done_count++;
6187 		return true;
6188 	}
6189 
6190 	// This flow has been shut already, skip
6191 	if (cfil_info->cfi_flags & apply_context->shut_flag) {
6192 		return true;
6193 	}
6194 	// Mark flow as shut
6195 	cfil_info->cfi_flags |= apply_context->shut_flag;
6196 	apply_context->done_count++;
6197 
6198 	for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
6199 		/* Disconnect incoming side */
6200 		if (apply_context->how != SHUT_WR) {
6201 			error = cfil_dispatch_disconnect_event(so, cfil_info, kcunit, 0);
6202 		}
6203 		/* Disconnect outgoing side */
6204 		if (apply_context->how != SHUT_RD) {
6205 			error = cfil_dispatch_disconnect_event(so, cfil_info, kcunit, 1);
6206 		}
6207 	}
6208 
6209 	if (cfil_info->cfi_debug) {
6210 		cfil_info_log(LOG_INFO, cfil_info, "CFIL: UDP PER-FLOW NOTIFY_SHUTDOWN");
6211 	}
6212 
6213 	return true;
6214 }
6215 
6216 int
cfil_sock_udp_notify_shutdown(struct socket * so,int how,int drop_flag,int shut_flag)6217 cfil_sock_udp_notify_shutdown(struct socket *so, int how, int drop_flag, int shut_flag)
6218 {
6219 	struct cfil_udp_notify_shutdown_context apply_context = { 0 };
6220 	errno_t error = 0;
6221 
6222 	socket_lock_assert_owned(so);
6223 
6224 	if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_flow_db != NULL) {
6225 		apply_context.how = how;
6226 		apply_context.drop_flag = drop_flag;
6227 		apply_context.shut_flag = shut_flag;
6228 
6229 		soflow_db_apply(so->so_flow_db, cfil_sock_udp_notify_shutdown_per_flow, (void *)&apply_context);
6230 	}
6231 
6232 	if (apply_context.done_count == 0) {
6233 		error = ENOTCONN;
6234 	}
6235 	return error;
6236 }
6237 
6238 int
cfil_sock_udp_shutdown(struct socket * so,int * how)6239 cfil_sock_udp_shutdown(struct socket *so, int *how)
6240 {
6241 	int error = 0;
6242 
6243 	if ((so->so_flags & SOF_CONTENT_FILTER) == 0 || (so->so_flow_db == NULL)) {
6244 		goto done;
6245 	}
6246 
6247 	socket_lock_assert_owned(so);
6248 
6249 	CFIL_LOG(LOG_INFO, "so %llx how %d",
6250 	    (uint64_t)VM_KERNEL_ADDRPERM(so), *how);
6251 
6252 	/*
6253 	 * Check the state of the socket before the content filter
6254 	 */
6255 	if (*how != SHUT_WR && (so->so_state & SS_CANTRCVMORE) != 0) {
6256 		/* read already shut down */
6257 		error = ENOTCONN;
6258 		goto done;
6259 	}
6260 	if (*how != SHUT_RD && (so->so_state & SS_CANTSENDMORE) != 0) {
6261 		/* write already shut down */
6262 		error = ENOTCONN;
6263 		goto done;
6264 	}
6265 
6266 	/*
6267 	 * shutdown read: SHUT_RD or SHUT_RDWR
6268 	 */
6269 	if (*how != SHUT_WR) {
6270 		error = cfil_sock_udp_notify_shutdown(so, SHUT_RD, CFIF_DROP, CFIF_SHUT_RD);
6271 		if (error != 0) {
6272 			goto done;
6273 		}
6274 	}
6275 	/*
6276 	 * shutdown write: SHUT_WR or SHUT_RDWR
6277 	 */
6278 	if (*how != SHUT_RD) {
6279 		error = cfil_sock_udp_notify_shutdown(so, SHUT_WR, CFIF_DROP, CFIF_SHUT_WR);
6280 		if (error != 0) {
6281 			goto done;
6282 		}
6283 
6284 		/*
6285 		 * When outgoing data is pending, we delay the shutdown at the
6286 		 * protocol level until the content filters give the final
6287 		 * verdict on the pending data.
6288 		 */
6289 		if (cfil_sock_data_pending(&so->so_snd) != 0) {
6290 			/*
6291 			 * When shutting down the read and write sides at once
6292 			 * we can proceed to the final shutdown of the read
6293 			 * side. Otherwise, we just return.
6294 			 */
6295 			if (*how == SHUT_WR) {
6296 				error = EJUSTRETURN;
6297 			} else if (*how == SHUT_RDWR) {
6298 				*how = SHUT_RD;
6299 			}
6300 		}
6301 	}
6302 done:
6303 	return error;
6304 }
6305 
6306 void
cfil_sock_udp_close_wait(struct socket * so)6307 cfil_sock_udp_close_wait(struct socket *so)
6308 {
6309 	socket_lock_assert_owned(so);
6310 
6311 	while (cfil_filters_udp_attached(so, FALSE)) {
6312 		/*
6313 		 * Notify the filters we are going away so they can detach
6314 		 */
6315 		cfil_sock_udp_notify_shutdown(so, SHUT_RDWR, 0, 0);
6316 
6317 		/*
6318 		 * Make sure we need to wait after the filter are notified
6319 		 * of the disconnection
6320 		 */
6321 		if (cfil_filters_udp_attached(so, TRUE) == 0) {
6322 			break;
6323 		}
6324 	}
6325 }
6326 
6327 static bool
cfil_sock_udp_is_closed_per_flow(struct socket * so,struct soflow_hash_entry * hash_entry,void * context)6328 cfil_sock_udp_is_closed_per_flow(struct socket *so,
6329     struct soflow_hash_entry *hash_entry,
6330     void *context)
6331 {
6332 #pragma unused(context)
6333 	struct cfil_info *cfil_info = NULL;
6334 	errno_t error = 0;
6335 	int kcunit;
6336 
6337 	if (hash_entry->soflow_feat_ctxt == NULL) {
6338 		return true;
6339 	}
6340 
6341 	cfil_info = hash_entry->soflow_feat_ctxt;
6342 
6343 	for (kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
6344 		/* Let the filters know of the closing */
6345 		error = cfil_dispatch_closed_event(so, cfil_info, kcunit);
6346 	}
6347 
6348 	/* Last chance to push passed data out */
6349 	error = cfil_acquire_sockbuf(so, cfil_info, 1);
6350 	if (error == 0) {
6351 		cfil_service_inject_queue(so, cfil_info, 1);
6352 	}
6353 	cfil_release_sockbuf(so, 1);
6354 
6355 	cfil_info->cfi_flags |= CFIF_SOCK_CLOSED;
6356 
6357 	/* Pending data needs to go */
6358 	cfil_flush_queues(so, cfil_info);
6359 
6360 	CFIL_INFO_VERIFY(cfil_info);
6361 
6362 	if (cfil_info->cfi_debug) {
6363 		cfil_info_log(LOG_INFO, cfil_info, "CFIL: UDP PER-FLOW IS_CLOSED");
6364 	}
6365 
6366 	return true;
6367 }
6368 
6369 void
cfil_sock_udp_is_closed(struct socket * so)6370 cfil_sock_udp_is_closed(struct socket *so)
6371 {
6372 	socket_lock_assert_owned(so);
6373 
6374 	if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_flow_db != NULL) {
6375 		soflow_db_apply(so->so_flow_db, cfil_sock_udp_is_closed_per_flow, NULL);
6376 	}
6377 }
6378 
6379 static bool
cfil_sock_udp_buf_update_per_flow(struct socket * so,struct soflow_hash_entry * hash_entry,void * context)6380 cfil_sock_udp_buf_update_per_flow(struct socket *so,
6381     struct soflow_hash_entry *hash_entry,
6382     void *context)
6383 {
6384 	struct cfil_info *cfil_info = NULL;
6385 	struct sockbuf *sb = NULL;
6386 	errno_t error = 0;
6387 	int outgoing;
6388 
6389 	if (hash_entry->soflow_feat_ctxt == NULL || context == NULL) {
6390 		return true;
6391 	}
6392 
6393 	cfil_info = hash_entry->soflow_feat_ctxt;
6394 	sb = (struct sockbuf *) context;
6395 
6396 	if ((sb->sb_flags & SB_RECV) == 0) {
6397 		if ((cfil_info->cfi_flags & CFIF_RETRY_INJECT_OUT) == 0) {
6398 			return true;
6399 		}
6400 		outgoing = 1;
6401 		OSIncrementAtomic(&cfil_stats.cfs_inject_q_out_retry);
6402 	} else {
6403 		if ((cfil_info->cfi_flags & CFIF_RETRY_INJECT_IN) == 0) {
6404 			return true;
6405 		}
6406 		outgoing = 0;
6407 		OSIncrementAtomic(&cfil_stats.cfs_inject_q_in_retry);
6408 	}
6409 
6410 	CFIL_LOG(LOG_NOTICE, "so %llx outgoing %d",
6411 	    (uint64_t)VM_KERNEL_ADDRPERM(so), outgoing);
6412 
6413 	error = cfil_acquire_sockbuf(so, cfil_info, outgoing);
6414 	if (error == 0) {
6415 		cfil_service_inject_queue(so, cfil_info, outgoing);
6416 	}
6417 	cfil_release_sockbuf(so, outgoing);
6418 	return true;
6419 }
6420 
6421 void
cfil_sock_udp_buf_update(struct sockbuf * sb)6422 cfil_sock_udp_buf_update(struct sockbuf *sb)
6423 {
6424 	struct socket *so = sb->sb_so;
6425 
6426 	socket_lock_assert_owned(so);
6427 
6428 	if ((so->so_flags & SOF_CONTENT_FILTER) != 0 && so->so_flow_db != NULL) {
6429 		if (!cfil_sbtrim) {
6430 			return;
6431 		}
6432 		soflow_db_apply(so->so_flow_db, cfil_sock_udp_buf_update_per_flow, (void *)sb);
6433 	}
6434 }
6435 
6436 void
cfil_filter_show(u_int32_t kcunit)6437 cfil_filter_show(u_int32_t kcunit)
6438 {
6439 	struct content_filter *cfc = NULL;
6440 	struct cfil_entry *entry;
6441 	int count = 0;
6442 
6443 	if (kcunit > MAX_CONTENT_FILTER) {
6444 		return;
6445 	}
6446 
6447 	cfil_rw_lock_shared(&cfil_lck_rw);
6448 
6449 	if (content_filters[kcunit - 1] == NULL) {
6450 		cfil_rw_unlock_shared(&cfil_lck_rw);
6451 		return;
6452 	}
6453 	cfc = content_filters[kcunit - 1];
6454 
6455 	CFIL_LOG(LOG_DEBUG, "CFIL: FILTER SHOW: Filter <unit %d, entry count %d> flags <%lx>:",
6456 	    kcunit, cfc->cf_sock_count, (unsigned long)cfc->cf_flags);
6457 	if (cfc->cf_flags & CFF_DETACHING) {
6458 		CFIL_LOG(LOG_DEBUG, "CFIL: FILTER SHOW:-DETACHING");
6459 	}
6460 	if (cfc->cf_flags & CFF_ACTIVE) {
6461 		CFIL_LOG(LOG_DEBUG, "CFIL: FILTER SHOW:-ACTIVE");
6462 	}
6463 	if (cfc->cf_flags & CFF_FLOW_CONTROLLED) {
6464 		CFIL_LOG(LOG_DEBUG, "CFIL: FILTER SHOW:-FLOW CONTROLLED");
6465 	}
6466 
6467 	TAILQ_FOREACH(entry, &cfc->cf_sock_entries, cfe_link) {
6468 		if (entry->cfe_cfil_info && entry->cfe_cfil_info->cfi_so) {
6469 			struct cfil_info *cfil_info = entry->cfe_cfil_info;
6470 
6471 			count++;
6472 
6473 			if (entry->cfe_flags & CFEF_CFIL_DETACHED) {
6474 				cfil_info_log(LOG_DEBUG, cfil_info, "CFIL: FILTER SHOW:-DETACHED");
6475 			} else {
6476 				cfil_info_log(LOG_DEBUG, cfil_info, "CFIL: FILTER SHOW:-ATTACHED");
6477 			}
6478 		}
6479 	}
6480 
6481 	CFIL_LOG(LOG_DEBUG, "CFIL: FILTER SHOW:Filter - total entries shown: %d", count);
6482 
6483 	cfil_rw_unlock_shared(&cfil_lck_rw);
6484 }
6485 
6486 void
cfil_info_show(void)6487 cfil_info_show(void)
6488 {
6489 	struct cfil_info *cfil_info;
6490 	int count = 0;
6491 
6492 	cfil_rw_lock_shared(&cfil_lck_rw);
6493 
6494 	CFIL_LOG(LOG_DEBUG, "CFIL: INFO SHOW:count %d", cfil_sock_attached_count);
6495 
6496 	TAILQ_FOREACH(cfil_info, &cfil_sock_head, cfi_link) {
6497 		count++;
6498 
6499 		cfil_info_log(LOG_DEBUG, cfil_info, "CFIL: INFO SHOW");
6500 
6501 		if (cfil_info->cfi_flags & CFIF_DROP) {
6502 			CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - DROP");
6503 		}
6504 		if (cfil_info->cfi_flags & CFIF_CLOSE_WAIT) {
6505 			CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - CLOSE_WAIT");
6506 		}
6507 		if (cfil_info->cfi_flags & CFIF_SOCK_CLOSED) {
6508 			CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - SOCK_CLOSED");
6509 		}
6510 		if (cfil_info->cfi_flags & CFIF_RETRY_INJECT_IN) {
6511 			CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - RETRY_INJECT_IN");
6512 		}
6513 		if (cfil_info->cfi_flags & CFIF_RETRY_INJECT_OUT) {
6514 			CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - RETRY_INJECT_OUT");
6515 		}
6516 		if (cfil_info->cfi_flags & CFIF_SHUT_WR) {
6517 			CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - SHUT_WR");
6518 		}
6519 		if (cfil_info->cfi_flags & CFIF_SHUT_RD) {
6520 			CFIL_LOG(LOG_DEBUG, "CFIL: INFO FLAG - SHUT_RD");
6521 		}
6522 	}
6523 
6524 	CFIL_LOG(LOG_DEBUG, "CFIL: INFO SHOW:total cfil_info shown: %d", count);
6525 
6526 	cfil_rw_unlock_shared(&cfil_lck_rw);
6527 }
6528 
6529 bool
cfil_info_action_timed_out(struct cfil_info * cfil_info,int timeout)6530 cfil_info_action_timed_out(struct cfil_info *cfil_info, int timeout)
6531 {
6532 	struct cfil_entry *entry;
6533 	struct timeval current_tv;
6534 	struct timeval diff_time;
6535 
6536 	if (cfil_info == NULL) {
6537 		return false;
6538 	}
6539 
6540 	/*
6541 	 * If we have queued up more data than passed offset and we haven't received
6542 	 * an action from user space for a while (the user space filter might have crashed),
6543 	 * return action timed out.
6544 	 */
6545 	if (cfil_info->cfi_snd.cfi_pending_last > cfil_info->cfi_snd.cfi_pass_offset ||
6546 	    cfil_info->cfi_rcv.cfi_pending_last > cfil_info->cfi_rcv.cfi_pass_offset) {
6547 		microuptime(&current_tv);
6548 
6549 		for (int kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
6550 			entry = &cfil_info->cfi_entries[kcunit - 1];
6551 
6552 			if (entry->cfe_filter == NULL) {
6553 				continue;
6554 			}
6555 
6556 			if (cfil_info->cfi_snd.cfi_pending_last > entry->cfe_snd.cfe_pass_offset ||
6557 			    cfil_info->cfi_rcv.cfi_pending_last > entry->cfe_rcv.cfe_pass_offset) {
6558 				// haven't gotten an action from this filter, check timeout
6559 				timersub(&current_tv, &entry->cfe_last_action, &diff_time);
6560 				if (diff_time.tv_sec >= timeout) {
6561 					if (cfil_info->cfi_debug) {
6562 						cfil_info_log(LOG_INFO, cfil_info, "CFIL: flow ACTION timeout expired");
6563 					}
6564 					return true;
6565 				}
6566 			}
6567 		}
6568 	}
6569 	return false;
6570 }
6571 
6572 bool
cfil_info_buffer_threshold_exceeded(struct cfil_info * cfil_info)6573 cfil_info_buffer_threshold_exceeded(struct cfil_info *cfil_info)
6574 {
6575 	if (cfil_info == NULL) {
6576 		return false;
6577 	}
6578 
6579 	/*
6580 	 * Clean up flow if it exceeded queue thresholds
6581 	 */
6582 	if (cfil_info->cfi_snd.cfi_tail_drop_cnt ||
6583 	    cfil_info->cfi_rcv.cfi_tail_drop_cnt) {
6584 		if (cfil_info->cfi_debug) {
6585 			CFIL_LOG(LOG_INFO, "CFIL: queue threshold exceeded:mbuf max < count: %d bytes: %d > tail drop count < OUT: %d IN: %d > ",
6586 			    cfil_udp_gc_mbuf_num_max,
6587 			    cfil_udp_gc_mbuf_cnt_max,
6588 			    cfil_info->cfi_snd.cfi_tail_drop_cnt,
6589 			    cfil_info->cfi_rcv.cfi_tail_drop_cnt);
6590 			cfil_info_log(LOG_INFO, cfil_info, "CFIL: queue threshold exceeded");
6591 		}
6592 		return true;
6593 	}
6594 
6595 	return false;
6596 }
6597 
6598 static bool
cfil_dgram_gc_needed(struct socket * so,struct soflow_hash_entry * hash_entry,u_int64_t current_time)6599 cfil_dgram_gc_needed(struct socket *so, struct soflow_hash_entry *hash_entry, u_int64_t current_time)
6600 {
6601 #pragma unused(current_time)
6602 	struct cfil_info *cfil_info = NULL;
6603 
6604 	if (so == NULL || hash_entry == NULL || hash_entry->soflow_feat_ctxt == NULL) {
6605 		return false;
6606 	}
6607 	cfil_info = (struct cfil_info *) hash_entry->soflow_feat_ctxt;
6608 
6609 	cfil_rw_lock_shared(&cfil_lck_rw);
6610 
6611 	if (cfil_info_action_timed_out(cfil_info, UDP_FLOW_GC_ACTION_TO) ||
6612 	    cfil_info_buffer_threshold_exceeded(cfil_info)) {
6613 		if (cfil_info->cfi_debug) {
6614 			cfil_info_log(LOG_INFO, cfil_info, "CFIL: UDP PER-FLOW GC NEEDED");
6615 		}
6616 		cfil_rw_unlock_shared(&cfil_lck_rw);
6617 		return true;
6618 	}
6619 
6620 	cfil_rw_unlock_shared(&cfil_lck_rw);
6621 	return false;
6622 }
6623 
6624 static bool
cfil_dgram_gc_perform(struct socket * so,struct soflow_hash_entry * hash_entry)6625 cfil_dgram_gc_perform(struct socket *so, struct soflow_hash_entry *hash_entry)
6626 {
6627 	struct cfil_info *cfil_info = NULL;
6628 
6629 	if (so == NULL || hash_entry == NULL || hash_entry->soflow_feat_ctxt == NULL) {
6630 		return false;
6631 	}
6632 	cfil_info = (struct cfil_info *) hash_entry->soflow_feat_ctxt;
6633 
6634 	if (cfil_info->cfi_debug) {
6635 		cfil_info_log(LOG_INFO, cfil_info, "CFIL: UDP PER-FLOW GC PERFORM");
6636 	}
6637 
6638 	for (int kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
6639 		/* Let the filters know of the closing */
6640 		cfil_dispatch_closed_event(so, cfil_info, kcunit);
6641 	}
6642 	cfil_sock_udp_unlink_flow(so, hash_entry, cfil_info);
6643 	CFIL_INFO_FREE(cfil_info);
6644 	OSIncrementAtomic(&cfil_stats.cfs_sock_detached);
6645 	return true;
6646 }
6647 
6648 static bool
cfil_dgram_detach_entry(struct socket * so,struct soflow_hash_entry * hash_entry)6649 cfil_dgram_detach_entry(struct socket *so, struct soflow_hash_entry *hash_entry)
6650 {
6651 	struct cfil_info *cfil_info = NULL;
6652 
6653 	if (hash_entry == NULL || hash_entry->soflow_feat_ctxt == NULL) {
6654 		return true;
6655 	}
6656 	cfil_info = (struct cfil_info *) hash_entry->soflow_feat_ctxt;
6657 
6658 	if (cfil_info->cfi_debug) {
6659 		cfil_info_log(LOG_INFO, cfil_info, "CFIL: DGRAM DETACH ENTRY");
6660 	}
6661 
6662 	cfil_sock_udp_unlink_flow(so, hash_entry, cfil_info);
6663 	CFIL_INFO_FREE(cfil_info);
6664 	OSIncrementAtomic(&cfil_stats.cfs_sock_detached);
6665 
6666 	return true;
6667 }
6668 
6669 static bool
cfil_dgram_detach_db(struct socket * so,struct soflow_db * db)6670 cfil_dgram_detach_db(struct socket *so, struct soflow_db *db)
6671 {
6672 #pragma unused(db)
6673 	if (so && so->so_flags & SOF_CONTENT_FILTER) {
6674 		so->so_flags &= ~SOF_CONTENT_FILTER;
6675 		CFIL_LOG(LOG_DEBUG, "CFIL: DGRAM DETACH DB <so %llx>", (uint64_t)VM_KERNEL_ADDRPERM(so));
6676 	}
6677 	return true;
6678 }
6679 
6680 struct m_tag *
cfil_dgram_save_socket_state(struct cfil_info * cfil_info,struct mbuf * m)6681 cfil_dgram_save_socket_state(struct cfil_info *cfil_info, struct mbuf *m)
6682 {
6683 	struct m_tag *tag = NULL;
6684 	struct cfil_tag *ctag = NULL;
6685 	struct soflow_hash_entry *hash_entry = NULL;
6686 	struct inpcb *inp = NULL;
6687 
6688 	if (cfil_info == NULL || cfil_info->cfi_so == NULL ||
6689 	    cfil_info->cfi_hash_entry == NULL || m == NULL || !(m->m_flags & M_PKTHDR)) {
6690 		return NULL;
6691 	}
6692 
6693 	inp = sotoinpcb(cfil_info->cfi_so);
6694 
6695 	/* Allocate a tag */
6696 	tag = m_tag_create(KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_CFIL_UDP,
6697 	    sizeof(struct cfil_tag), M_DONTWAIT, m);
6698 
6699 	if (tag) {
6700 		ctag = (struct cfil_tag*)(tag + 1);
6701 		ctag->cfil_so_state_change_cnt = cfil_info->cfi_so->so_state_change_cnt;
6702 		ctag->cfil_so_options = cfil_info->cfi_so->so_options;
6703 		ctag->cfil_inp_flags = inp ? inp->inp_flags : 0;
6704 
6705 		hash_entry = cfil_info->cfi_hash_entry;
6706 		if (hash_entry->soflow_family == AF_INET6) {
6707 			fill_ip6_sockaddr_4_6(&ctag->cfil_faddr,
6708 			    &hash_entry->soflow_faddr.addr6,
6709 			    hash_entry->soflow_fport, hash_entry->soflow_faddr6_ifscope);
6710 		} else if (hash_entry->soflow_family == AF_INET) {
6711 			fill_ip_sockaddr_4_6(&ctag->cfil_faddr,
6712 			    hash_entry->soflow_faddr.addr46.ia46_addr4,
6713 			    hash_entry->soflow_fport);
6714 		}
6715 		m_tag_prepend(m, tag);
6716 		return tag;
6717 	}
6718 	return NULL;
6719 }
6720 
6721 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)6722 cfil_dgram_get_socket_state(struct mbuf *m, uint32_t *state_change_cnt, uint32_t *options,
6723     struct sockaddr **faddr, int *inp_flags)
6724 {
6725 	struct m_tag *tag = NULL;
6726 	struct cfil_tag *ctag = NULL;
6727 
6728 	tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_CFIL_UDP, NULL);
6729 	if (tag) {
6730 		ctag = (struct cfil_tag *)(tag + 1);
6731 		if (state_change_cnt) {
6732 			*state_change_cnt = ctag->cfil_so_state_change_cnt;
6733 		}
6734 		if (options) {
6735 			*options = ctag->cfil_so_options;
6736 		}
6737 		if (faddr) {
6738 			*faddr = (struct sockaddr *) &ctag->cfil_faddr;
6739 		}
6740 		if (inp_flags) {
6741 			*inp_flags = ctag->cfil_inp_flags;
6742 		}
6743 
6744 		/*
6745 		 * Unlink tag and hand it over to caller.
6746 		 * Note that caller will be responsible to free it.
6747 		 */
6748 		m_tag_unlink(m, tag);
6749 		return tag;
6750 	}
6751 	return NULL;
6752 }
6753 
6754 boolean_t
cfil_dgram_peek_socket_state(struct mbuf * m,int * inp_flags)6755 cfil_dgram_peek_socket_state(struct mbuf *m, int *inp_flags)
6756 {
6757 	struct m_tag *tag = NULL;
6758 	struct cfil_tag *ctag = NULL;
6759 
6760 	tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_CFIL_UDP, NULL);
6761 	if (tag) {
6762 		ctag = (struct cfil_tag *)(tag + 1);
6763 		if (inp_flags) {
6764 			*inp_flags = ctag->cfil_inp_flags;
6765 		}
6766 		return true;
6767 	}
6768 	return false;
6769 }
6770 
6771 static int
cfil_dispatch_stats_event_locked(int kcunit,struct cfil_stats_report_buffer * buffer,uint32_t stats_count)6772 cfil_dispatch_stats_event_locked(int kcunit, struct cfil_stats_report_buffer *buffer, uint32_t stats_count)
6773 {
6774 	struct content_filter *cfc = NULL;
6775 	errno_t error = 0;
6776 	size_t msgsize = 0;
6777 
6778 	if (buffer == NULL || stats_count == 0) {
6779 		return error;
6780 	}
6781 
6782 	if (kcunit > MAX_CONTENT_FILTER) {
6783 		return error;
6784 	}
6785 
6786 	cfc = content_filters[kcunit - 1];
6787 	if (cfc == NULL) {
6788 		return error;
6789 	}
6790 
6791 	/* Would be wasteful to try */
6792 	if (cfc->cf_flags & CFF_FLOW_CONTROLLED) {
6793 		error = ENOBUFS;
6794 		goto done;
6795 	}
6796 
6797 	msgsize = sizeof(struct cfil_msg_stats_report) + (sizeof(struct cfil_msg_sock_stats) * stats_count);
6798 	buffer->msghdr.cfm_len = (uint32_t)msgsize;
6799 	buffer->msghdr.cfm_version = 1;
6800 	buffer->msghdr.cfm_type = CFM_TYPE_EVENT;
6801 	buffer->msghdr.cfm_op = CFM_OP_STATS;
6802 	buffer->msghdr.cfm_sock_id = 0;
6803 	buffer->count = stats_count;
6804 
6805 	if (cfil_log_stats) {
6806 		CFIL_LOG(LOG_DEBUG, "STATS (kcunit %d): msg size %lu - %lu %lu %lu",
6807 		    kcunit,
6808 		    (unsigned long)msgsize,
6809 		    (unsigned long)sizeof(struct cfil_msg_stats_report),
6810 		    (unsigned long)sizeof(struct cfil_msg_sock_stats),
6811 		    (unsigned long)stats_count);
6812 	}
6813 
6814 	error = ctl_enqueuedata(cfc->cf_kcref, cfc->cf_kcunit,
6815 	    buffer,
6816 	    msgsize,
6817 	    CTL_DATA_EOR);
6818 	if (error != 0) {
6819 		CFIL_LOG(LOG_ERR, "ctl_enqueuedata() failed:%d", error);
6820 		goto done;
6821 	}
6822 	OSIncrementAtomic(&cfil_stats.cfs_stats_event_ok);
6823 
6824 	if (cfil_log_stats) {
6825 		CFIL_LOG(LOG_DEBUG, "CFIL: STATS REPORT:send msg to %d", kcunit);
6826 	}
6827 done:
6828 
6829 	if (error == ENOBUFS) {
6830 		OSIncrementAtomic(
6831 			&cfil_stats.cfs_stats_event_flow_control);
6832 
6833 		if (!cfil_rw_lock_shared_to_exclusive(&cfil_lck_rw)) {
6834 			cfil_rw_lock_exclusive(&cfil_lck_rw);
6835 		}
6836 
6837 		cfc->cf_flags |= CFF_FLOW_CONTROLLED;
6838 
6839 		cfil_rw_lock_exclusive_to_shared(&cfil_lck_rw);
6840 	} else if (error != 0) {
6841 		OSIncrementAtomic(&cfil_stats.cfs_stats_event_fail);
6842 	}
6843 
6844 	return error;
6845 }
6846 
6847 static void
cfil_stats_report_thread_sleep(bool forever)6848 cfil_stats_report_thread_sleep(bool forever)
6849 {
6850 	if (cfil_log_stats) {
6851 		CFIL_LOG(LOG_DEBUG, "CFIL: STATS COLLECTION SLEEP");
6852 	}
6853 
6854 	if (forever) {
6855 		(void) assert_wait((event_t) &cfil_sock_attached_stats_count,
6856 		    THREAD_INTERRUPTIBLE);
6857 	} else {
6858 		uint64_t deadline = 0;
6859 		nanoseconds_to_absolutetime(CFIL_STATS_REPORT_RUN_INTERVAL_NSEC, &deadline);
6860 		clock_absolutetime_interval_to_deadline(deadline, &deadline);
6861 
6862 		(void) assert_wait_deadline(&cfil_sock_attached_stats_count,
6863 		    THREAD_INTERRUPTIBLE, deadline);
6864 	}
6865 }
6866 
6867 static void
cfil_stats_report_thread_func(void * v,wait_result_t w)6868 cfil_stats_report_thread_func(void *v, wait_result_t w)
6869 {
6870 #pragma unused(v, w)
6871 
6872 	ASSERT(cfil_stats_report_thread == current_thread());
6873 	thread_set_thread_name(current_thread(), "CFIL_STATS_REPORT");
6874 
6875 	// Kick off gc shortly
6876 	cfil_stats_report_thread_sleep(false);
6877 	thread_block_parameter((thread_continue_t) cfil_stats_report, NULL);
6878 	/* NOTREACHED */
6879 }
6880 
6881 static bool
cfil_stats_collect_flow_stats_for_filter(int kcunit,struct cfil_info * cfil_info,struct cfil_entry * entry,struct timeval current_tv)6882 cfil_stats_collect_flow_stats_for_filter(int kcunit,
6883     struct cfil_info *cfil_info,
6884     struct cfil_entry *entry,
6885     struct timeval current_tv)
6886 {
6887 	struct cfil_stats_report_buffer *buffer = NULL;
6888 	struct cfil_msg_sock_stats *flow_array = NULL;
6889 	struct cfil_msg_sock_stats *stats = NULL;
6890 	struct inpcb *inp = NULL;
6891 	struct timeval diff_time;
6892 	uint64_t diff_time_usecs;
6893 	int index = 0;
6894 
6895 	if (entry->cfe_stats_report_frequency == 0) {
6896 		return false;
6897 	}
6898 
6899 	buffer = global_cfil_stats_report_buffers[kcunit - 1];
6900 	if (buffer == NULL) {
6901 		CFIL_LOG(LOG_ERR, "CFIL: STATS: no buffer");
6902 		return false;
6903 	}
6904 
6905 	timersub(&current_tv, &entry->cfe_stats_report_ts, &diff_time);
6906 	diff_time_usecs = (diff_time.tv_sec * USEC_PER_SEC) + diff_time.tv_usec;
6907 
6908 	if (cfil_info->cfi_debug && cfil_log_stats) {
6909 		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",
6910 		    (unsigned long long)entry->cfe_stats_report_ts.tv_sec,
6911 		    (unsigned long long)entry->cfe_stats_report_ts.tv_usec,
6912 		    (unsigned long long)current_tv.tv_sec,
6913 		    (unsigned long long)current_tv.tv_usec,
6914 		    (unsigned long long)diff_time.tv_sec,
6915 		    (unsigned long long)diff_time.tv_usec,
6916 		    (unsigned long long)diff_time_usecs,
6917 		    (unsigned long long)((entry->cfe_stats_report_frequency * NSEC_PER_MSEC) / NSEC_PER_USEC),
6918 		    cfil_info->cfi_sock_id);
6919 	}
6920 
6921 	// Compare elapsed time in usecs
6922 	if (diff_time_usecs >= (entry->cfe_stats_report_frequency * NSEC_PER_MSEC) / NSEC_PER_USEC) {
6923 		if (cfil_info->cfi_debug && cfil_log_stats) {
6924 			CFIL_LOG(LOG_DEBUG, "CFIL: STATS REPORT - in %llu reported %llu",
6925 			    cfil_info->cfi_byte_inbound_count,
6926 			    entry->cfe_byte_inbound_count_reported);
6927 			CFIL_LOG(LOG_DEBUG, "CFIL: STATS REPORT - out %llu reported %llu",
6928 			    cfil_info->cfi_byte_outbound_count,
6929 			    entry->cfe_byte_outbound_count_reported);
6930 		}
6931 		// Check if flow has new bytes that have not been reported
6932 		if (entry->cfe_byte_inbound_count_reported < cfil_info->cfi_byte_inbound_count ||
6933 		    entry->cfe_byte_outbound_count_reported < cfil_info->cfi_byte_outbound_count) {
6934 			flow_array = (struct cfil_msg_sock_stats *)&buffer->stats;
6935 			index = global_cfil_stats_counts[kcunit - 1];
6936 
6937 			stats = &flow_array[index];
6938 			stats->cfs_sock_id = cfil_info->cfi_sock_id;
6939 			stats->cfs_byte_inbound_count = cfil_info->cfi_byte_inbound_count;
6940 			stats->cfs_byte_outbound_count = cfil_info->cfi_byte_outbound_count;
6941 
6942 			if (entry->cfe_laddr_sent == false) {
6943 				/* cache it if necessary */
6944 				if (cfil_info->cfi_so_attach_laddr.sa.sa_len == 0) {
6945 					inp = cfil_info->cfi_so ? sotoinpcb(cfil_info->cfi_so) : NULL;
6946 					if (inp != NULL) {
6947 						boolean_t outgoing = (cfil_info->cfi_dir == CFS_CONNECTION_DIR_OUT);
6948 						union sockaddr_in_4_6 *src = outgoing ? &cfil_info->cfi_so_attach_laddr : NULL;
6949 						union sockaddr_in_4_6 *dst = outgoing ? NULL : &cfil_info->cfi_so_attach_laddr;
6950 						cfil_fill_event_msg_addresses(cfil_info->cfi_hash_entry, inp,
6951 						    src, dst, !IS_INP_V6(inp), outgoing);
6952 					}
6953 				}
6954 
6955 				if (cfil_info->cfi_so_attach_laddr.sa.sa_len != 0) {
6956 					stats->cfs_laddr.sin6 = cfil_info->cfi_so_attach_laddr.sin6;
6957 					entry->cfe_laddr_sent = true;
6958 				}
6959 			}
6960 
6961 			global_cfil_stats_counts[kcunit - 1]++;
6962 
6963 			entry->cfe_stats_report_ts = current_tv;
6964 			entry->cfe_byte_inbound_count_reported = cfil_info->cfi_byte_inbound_count;
6965 			entry->cfe_byte_outbound_count_reported = cfil_info->cfi_byte_outbound_count;
6966 			if (cfil_info->cfi_debug && cfil_log_stats) {
6967 				cfil_info_log(LOG_DEBUG, cfil_info, "CFIL: STATS COLLECTED");
6968 			}
6969 			CFI_ADD_TIME_LOG(cfil_info, &current_tv, &cfil_info->cfi_first_event, CFM_OP_STATS);
6970 			return true;
6971 		}
6972 	}
6973 	return false;
6974 }
6975 
6976 static void
cfil_stats_report(void * v,wait_result_t w)6977 cfil_stats_report(void *v, wait_result_t w)
6978 {
6979 #pragma unused(v, w)
6980 
6981 	struct cfil_info *cfil_info = NULL;
6982 	struct cfil_entry *entry = NULL;
6983 	struct timeval current_tv;
6984 	uint32_t flow_count = 0;
6985 	uint64_t saved_next_sock_id = 0; // Next sock id to be reported for next loop
6986 	bool flow_reported = false;
6987 
6988 	if (cfil_log_stats) {
6989 		CFIL_LOG(LOG_DEBUG, "CFIL: STATS COLLECTION RUNNING");
6990 	}
6991 
6992 	do {
6993 		// Collect all sock ids of flows that has new stats
6994 		cfil_rw_lock_shared(&cfil_lck_rw);
6995 
6996 		if (cfil_sock_attached_stats_count == 0) {
6997 			if (cfil_log_stats) {
6998 				CFIL_LOG(LOG_DEBUG, "CFIL: STATS: no flow");
6999 			}
7000 			cfil_rw_unlock_shared(&cfil_lck_rw);
7001 			goto go_sleep;
7002 		}
7003 
7004 		for (int kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
7005 			if (global_cfil_stats_report_buffers[kcunit - 1] != NULL) {
7006 				memset(global_cfil_stats_report_buffers[kcunit - 1], 0, sizeof(struct cfil_stats_report_buffer));
7007 			}
7008 			global_cfil_stats_counts[kcunit - 1] = 0;
7009 		}
7010 
7011 		microuptime(&current_tv);
7012 		flow_count = 0;
7013 
7014 		TAILQ_FOREACH(cfil_info, &cfil_sock_head_stats, cfi_link_stats) {
7015 			if (saved_next_sock_id != 0 &&
7016 			    saved_next_sock_id == cfil_info->cfi_sock_id) {
7017 				// Here is where we left off previously, start accumulating
7018 				saved_next_sock_id = 0;
7019 			}
7020 
7021 			if (saved_next_sock_id == 0) {
7022 				if (flow_count >= CFIL_STATS_REPORT_MAX_COUNT) {
7023 					// Examine a fixed number of flows each round.  Remember the current flow
7024 					// so we can start from here for next loop
7025 					saved_next_sock_id = cfil_info->cfi_sock_id;
7026 					break;
7027 				}
7028 
7029 				flow_reported = false;
7030 				for (int kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
7031 					entry = &cfil_info->cfi_entries[kcunit - 1];
7032 					if (entry->cfe_filter == NULL) {
7033 						if (cfil_info->cfi_debug && cfil_log_stats) {
7034 							CFIL_LOG(LOG_DEBUG, "CFIL: STATS REPORT - so %llx no filter",
7035 							    cfil_info->cfi_so ? (uint64_t)VM_KERNEL_ADDRPERM(cfil_info->cfi_so) : 0);
7036 						}
7037 						continue;
7038 					}
7039 
7040 					if ((entry->cfe_stats_report_frequency > 0) &&
7041 					    cfil_stats_collect_flow_stats_for_filter(kcunit, cfil_info, entry, current_tv) == true) {
7042 						flow_reported = true;
7043 					}
7044 				}
7045 				if (flow_reported == true) {
7046 					flow_count++;
7047 				}
7048 			}
7049 		}
7050 
7051 		if (flow_count > 0) {
7052 			if (cfil_log_stats) {
7053 				CFIL_LOG(LOG_DEBUG, "CFIL: STATS reporting for %d flows", flow_count);
7054 			}
7055 			for (int kcunit = 1; kcunit <= MAX_CONTENT_FILTER; kcunit++) {
7056 				if (global_cfil_stats_report_buffers[kcunit - 1] != NULL &&
7057 				    global_cfil_stats_counts[kcunit - 1] > 0) {
7058 					cfil_dispatch_stats_event_locked(kcunit,
7059 					    global_cfil_stats_report_buffers[kcunit - 1],
7060 					    global_cfil_stats_counts[kcunit - 1]);
7061 				}
7062 			}
7063 		} else {
7064 			cfil_rw_unlock_shared(&cfil_lck_rw);
7065 			goto go_sleep;
7066 		}
7067 
7068 		cfil_rw_unlock_shared(&cfil_lck_rw);
7069 
7070 		// Loop again if we haven't finished the whole cfil_info list
7071 	} while (saved_next_sock_id != 0);
7072 
7073 go_sleep:
7074 
7075 	// Sleep forever (until waken up) if no more flow to report
7076 	cfil_rw_lock_shared(&cfil_lck_rw);
7077 	cfil_stats_report_thread_sleep(cfil_sock_attached_stats_count == 0 ? true : false);
7078 	cfil_rw_unlock_shared(&cfil_lck_rw);
7079 	thread_block_parameter((thread_continue_t) cfil_stats_report, NULL);
7080 	/* NOTREACHED */
7081 }
7082