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