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