2 * Kernel iptables module to track stats for packets based on user tags.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 2 as
8 * published by the Free Software Foundation.
12 * There are run-time debug flags enabled via the debug_mask module param, or
13 * via the DEFAULT_DEBUG_MASK. See xt_qtaguid_internal.h.
17 #include <linux/file.h>
18 #include <linux/inetdevice.h>
19 #include <linux/module.h>
20 #include <linux/netfilter/x_tables.h>
21 #include <linux/netfilter/xt_qtaguid.h>
22 #include <linux/skbuff.h>
23 #include <linux/workqueue.h>
24 #include <net/addrconf.h>
29 #if defined(CONFIG_IP6_NF_IPTABLES) || defined(CONFIG_IP6_NF_IPTABLES_MODULE)
30 #include <linux/netfilter_ipv6/ip6_tables.h>
33 #include <linux/netfilter/xt_socket.h>
34 #include "xt_qtaguid_internal.h"
35 #include "xt_qtaguid_print.h"
38 * We only use the xt_socket funcs within a similar context to avoid unexpected
41 #define XT_SOCKET_SUPPORTED_HOOKS \
42 ((1 << NF_INET_PRE_ROUTING) | (1 << NF_INET_LOCAL_IN))
45 static const char *module_procdirname = "xt_qtaguid";
46 static struct proc_dir_entry *xt_qtaguid_procdir;
48 static unsigned int proc_iface_perms = S_IRUGO;
49 module_param_named(iface_perms, proc_iface_perms, uint, S_IRUGO | S_IWUSR);
51 static struct proc_dir_entry *xt_qtaguid_stats_file;
52 static unsigned int proc_stats_perms = S_IRUGO;
53 module_param_named(stats_perms, proc_stats_perms, uint, S_IRUGO | S_IWUSR);
55 static struct proc_dir_entry *xt_qtaguid_ctrl_file;
57 /* Everybody can write. But proc_ctrl_write_limited is true by default which
58 * limits what can be controlled. See the can_*() functions.
60 static unsigned int proc_ctrl_perms = S_IRUGO | S_IWUGO;
61 module_param_named(ctrl_perms, proc_ctrl_perms, uint, S_IRUGO | S_IWUSR);
63 /* Limited by default, so the gid of the ctrl and stats proc entries
64 * will limit what can be done. See the can_*() functions.
66 static bool proc_stats_readall_limited = true;
67 static bool proc_ctrl_write_limited = true;
69 module_param_named(stats_readall_limited, proc_stats_readall_limited, bool,
71 module_param_named(ctrl_write_limited, proc_ctrl_write_limited, bool,
75 * Limit the number of active tags (via socket tags) for a given UID.
76 * Multiple processes could share the UID.
78 static int max_sock_tags = DEFAULT_MAX_SOCK_TAGS;
79 module_param(max_sock_tags, int, S_IRUGO | S_IWUSR);
82 * After the kernel has initiallized this module, it is still possible
84 * Setting passive to Y:
85 * - the iface stats handling will not act on notifications.
86 * - iptables matches will never match.
87 * - ctrl commands silently succeed.
88 * - stats are always empty.
89 * This is mostly usefull when a bug is suspected.
91 static bool module_passive;
92 module_param_named(passive, module_passive, bool, S_IRUGO | S_IWUSR);
95 * Control how qtaguid data is tracked per proc/uid.
96 * Setting tag_tracking_passive to Y:
97 * - don't create proc specific structs to track tags
98 * - don't check that active tag stats exceed some limits.
99 * - don't clean up socket tags on process exits.
100 * This is mostly usefull when a bug is suspected.
102 static bool qtu_proc_handling_passive;
103 module_param_named(tag_tracking_passive, qtu_proc_handling_passive, bool,
106 #define QTU_DEV_NAME "xt_qtaguid"
108 uint qtaguid_debug_mask = DEFAULT_DEBUG_MASK;
109 module_param_named(debug_mask, qtaguid_debug_mask, uint, S_IRUGO | S_IWUSR);
111 /*---------------------------------------------------------------------------*/
112 static const char *iface_stat_procdirname = "iface_stat";
113 static struct proc_dir_entry *iface_stat_procdir;
115 * The iface_stat_all* will go away once userspace gets use to the new fields
116 * that have a format line.
118 static const char *iface_stat_all_procfilename = "iface_stat_all";
119 static struct proc_dir_entry *iface_stat_all_procfile;
120 static const char *iface_stat_fmt_procfilename = "iface_stat_fmt";
121 static struct proc_dir_entry *iface_stat_fmt_procfile;
127 * iface_stat_list_lock
130 * uid_tag_data_tree_lock
131 * tag_counter_set_list_lock
132 * Notice how sock_tag_list_lock is held sometimes when uid_tag_data_tree_lock
135 * Call tree with all lock holders as of 2012-04-27:
137 * iface_stat_fmt_proc_read()
138 * iface_stat_list_lock
139 * (struct iface_stat)
141 * qtaguid_ctrl_proc_read()
144 * (struct proc_qtu_data->sock_tag_list)
145 * prdebug_full_state()
148 * uid_tag_data_tree_lock
149 * (uid_tag_data_tree)
150 * (proc_qtu_data_tree)
151 * iface_stat_list_lock
153 * qtaguid_stats_proc_read()
154 * iface_stat_list_lock
155 * struct iface_stat->tag_stat_list_lock
158 * uid_tag_data_tree_lock
161 * sock_tag_data_list_lock
162 * uid_tag_data_tree_lock
163 * prdebug_full_state()
165 * uid_tag_data_tree_lock
166 * iface_stat_list_lock
168 * iface_netdev_event_handler()
169 * iface_stat_create()
170 * iface_stat_list_lock
171 * iface_stat_update()
172 * iface_stat_list_lock
174 * iface_inetaddr_event_handler()
175 * iface_stat_create()
176 * iface_stat_list_lock
177 * iface_stat_update()
178 * iface_stat_list_lock
180 * iface_inet6addr_event_handler()
181 * iface_stat_create_ipv6()
182 * iface_stat_list_lock
183 * iface_stat_update()
184 * iface_stat_list_lock
188 * if_tag_stat_update()
191 * struct iface_stat->tag_stat_list_lock
193 * get_active_counter_set()
194 * tag_counter_set_list_lock
196 * get_active_counter_set()
197 * tag_counter_set_list_lock
200 * qtaguid_ctrl_parse()
203 * tag_counter_set_list_lock
204 * iface_stat_list_lock
205 * struct iface_stat->tag_stat_list_lock
206 * uid_tag_data_tree_lock
207 * ctrl_cmd_counter_set()
208 * tag_counter_set_list_lock
213 * uid_tag_data_tree_lock
214 * (uid_tag_data_tree)
215 * uid_tag_data_tree_lock
216 * (proc_qtu_data_tree)
219 * uid_tag_data_tree_lock
222 static LIST_HEAD(iface_stat_list);
223 static DEFINE_SPINLOCK(iface_stat_list_lock);
225 static struct rb_root sock_tag_tree = RB_ROOT;
226 static DEFINE_SPINLOCK(sock_tag_list_lock);
228 static struct rb_root tag_counter_set_tree = RB_ROOT;
229 static DEFINE_SPINLOCK(tag_counter_set_list_lock);
231 static struct rb_root uid_tag_data_tree = RB_ROOT;
232 static DEFINE_SPINLOCK(uid_tag_data_tree_lock);
234 static struct rb_root proc_qtu_data_tree = RB_ROOT;
235 /* No proc_qtu_data_tree_lock; use uid_tag_data_tree_lock */
237 static struct qtaguid_event_counts qtu_events;
238 /*----------------------------------------------*/
239 static bool can_manipulate_uids(void)
242 return in_egroup_p(xt_qtaguid_ctrl_file->gid)
243 || unlikely(!current_fsuid()) || unlikely(!proc_ctrl_write_limited)
244 || unlikely(current_fsuid() == xt_qtaguid_ctrl_file->uid);
247 static bool can_impersonate_uid(uid_t uid)
249 return uid == current_fsuid() || can_manipulate_uids();
252 static bool can_read_other_uid_stats(uid_t uid)
255 return in_egroup_p(xt_qtaguid_stats_file->gid)
256 || unlikely(!current_fsuid()) || uid == current_fsuid()
257 || unlikely(!proc_stats_readall_limited)
258 || unlikely(current_fsuid() == xt_qtaguid_ctrl_file->uid);
261 static inline void dc_add_byte_packets(struct data_counters *counters, int set,
262 enum ifs_tx_rx direction,
263 enum ifs_proto ifs_proto,
267 counters->bpc[set][direction][ifs_proto].bytes += bytes;
268 counters->bpc[set][direction][ifs_proto].packets += packets;
271 static struct tag_node *tag_node_tree_search(struct rb_root *root, tag_t tag)
273 struct rb_node *node = root->rb_node;
276 struct tag_node *data = rb_entry(node, struct tag_node, node);
278 RB_DEBUG("qtaguid: tag_node_tree_search(0x%llx): "
279 " node=%p data=%p\n", tag, node, data);
280 result = tag_compare(tag, data->tag);
281 RB_DEBUG("qtaguid: tag_node_tree_search(0x%llx): "
282 " data.tag=0x%llx (uid=%u) res=%d\n",
283 tag, data->tag, get_uid_from_tag(data->tag), result);
285 node = node->rb_left;
287 node = node->rb_right;
294 static void tag_node_tree_insert(struct tag_node *data, struct rb_root *root)
296 struct rb_node **new = &(root->rb_node), *parent = NULL;
298 /* Figure out where to put new node */
300 struct tag_node *this = rb_entry(*new, struct tag_node,
302 int result = tag_compare(data->tag, this->tag);
303 RB_DEBUG("qtaguid: %s(): tag=0x%llx"
304 " (uid=%u)\n", __func__,
306 get_uid_from_tag(this->tag));
309 new = &((*new)->rb_left);
311 new = &((*new)->rb_right);
316 /* Add new node and rebalance tree. */
317 rb_link_node(&data->node, parent, new);
318 rb_insert_color(&data->node, root);
321 static void tag_stat_tree_insert(struct tag_stat *data, struct rb_root *root)
323 tag_node_tree_insert(&data->tn, root);
326 static struct tag_stat *tag_stat_tree_search(struct rb_root *root, tag_t tag)
328 struct tag_node *node = tag_node_tree_search(root, tag);
331 return rb_entry(&node->node, struct tag_stat, tn.node);
334 static void tag_counter_set_tree_insert(struct tag_counter_set *data,
335 struct rb_root *root)
337 tag_node_tree_insert(&data->tn, root);
340 static struct tag_counter_set *tag_counter_set_tree_search(struct rb_root *root,
343 struct tag_node *node = tag_node_tree_search(root, tag);
346 return rb_entry(&node->node, struct tag_counter_set, tn.node);
350 static void tag_ref_tree_insert(struct tag_ref *data, struct rb_root *root)
352 tag_node_tree_insert(&data->tn, root);
355 static struct tag_ref *tag_ref_tree_search(struct rb_root *root, tag_t tag)
357 struct tag_node *node = tag_node_tree_search(root, tag);
360 return rb_entry(&node->node, struct tag_ref, tn.node);
363 static struct sock_tag *sock_tag_tree_search(struct rb_root *root,
364 const struct sock *sk)
366 struct rb_node *node = root->rb_node;
369 struct sock_tag *data = rb_entry(node, struct sock_tag,
372 node = node->rb_left;
373 else if (sk > data->sk)
374 node = node->rb_right;
381 static void sock_tag_tree_insert(struct sock_tag *data, struct rb_root *root)
383 struct rb_node **new = &(root->rb_node), *parent = NULL;
385 /* Figure out where to put new node */
387 struct sock_tag *this = rb_entry(*new, struct sock_tag,
390 if (data->sk < this->sk)
391 new = &((*new)->rb_left);
392 else if (data->sk > this->sk)
393 new = &((*new)->rb_right);
398 /* Add new node and rebalance tree. */
399 rb_link_node(&data->sock_node, parent, new);
400 rb_insert_color(&data->sock_node, root);
403 static void sock_tag_tree_erase(struct rb_root *st_to_free_tree)
405 struct rb_node *node;
406 struct sock_tag *st_entry;
408 node = rb_first(st_to_free_tree);
410 st_entry = rb_entry(node, struct sock_tag, sock_node);
411 node = rb_next(node);
412 CT_DEBUG("qtaguid: %s(): "
413 "erase st: sk=%p tag=0x%llx (uid=%u)\n", __func__,
416 get_uid_from_tag(st_entry->tag));
417 rb_erase(&st_entry->sock_node, st_to_free_tree);
418 sockfd_put(st_entry->socket);
423 static struct proc_qtu_data *proc_qtu_data_tree_search(struct rb_root *root,
426 struct rb_node *node = root->rb_node;
429 struct proc_qtu_data *data = rb_entry(node,
430 struct proc_qtu_data,
433 node = node->rb_left;
434 else if (pid > data->pid)
435 node = node->rb_right;
442 static void proc_qtu_data_tree_insert(struct proc_qtu_data *data,
443 struct rb_root *root)
445 struct rb_node **new = &(root->rb_node), *parent = NULL;
447 /* Figure out where to put new node */
449 struct proc_qtu_data *this = rb_entry(*new,
450 struct proc_qtu_data,
453 if (data->pid < this->pid)
454 new = &((*new)->rb_left);
455 else if (data->pid > this->pid)
456 new = &((*new)->rb_right);
461 /* Add new node and rebalance tree. */
462 rb_link_node(&data->node, parent, new);
463 rb_insert_color(&data->node, root);
466 static void uid_tag_data_tree_insert(struct uid_tag_data *data,
467 struct rb_root *root)
469 struct rb_node **new = &(root->rb_node), *parent = NULL;
471 /* Figure out where to put new node */
473 struct uid_tag_data *this = rb_entry(*new,
477 if (data->uid < this->uid)
478 new = &((*new)->rb_left);
479 else if (data->uid > this->uid)
480 new = &((*new)->rb_right);
485 /* Add new node and rebalance tree. */
486 rb_link_node(&data->node, parent, new);
487 rb_insert_color(&data->node, root);
490 static struct uid_tag_data *uid_tag_data_tree_search(struct rb_root *root,
493 struct rb_node *node = root->rb_node;
496 struct uid_tag_data *data = rb_entry(node,
500 node = node->rb_left;
501 else if (uid > data->uid)
502 node = node->rb_right;
510 * Allocates a new uid_tag_data struct if needed.
511 * Returns a pointer to the found or allocated uid_tag_data.
512 * Returns a PTR_ERR on failures, and lock is not held.
513 * If found is not NULL:
514 * sets *found to true if not allocated.
515 * sets *found to false if allocated.
517 struct uid_tag_data *get_uid_data(uid_t uid, bool *found_res)
519 struct uid_tag_data *utd_entry;
521 /* Look for top level uid_tag_data for the UID */
522 utd_entry = uid_tag_data_tree_search(&uid_tag_data_tree, uid);
523 DR_DEBUG("qtaguid: get_uid_data(%u) utd=%p\n", uid, utd_entry);
526 *found_res = utd_entry;
530 utd_entry = kzalloc(sizeof(*utd_entry), GFP_ATOMIC);
532 pr_err("qtaguid: get_uid_data(%u): "
533 "tag data alloc failed\n", uid);
534 return ERR_PTR(-ENOMEM);
537 utd_entry->uid = uid;
538 utd_entry->tag_ref_tree = RB_ROOT;
539 uid_tag_data_tree_insert(utd_entry, &uid_tag_data_tree);
540 DR_DEBUG("qtaguid: get_uid_data(%u) new utd=%p\n", uid, utd_entry);
544 /* Never returns NULL. Either PTR_ERR or a valid ptr. */
545 static struct tag_ref *new_tag_ref(tag_t new_tag,
546 struct uid_tag_data *utd_entry)
548 struct tag_ref *tr_entry;
551 if (utd_entry->num_active_tags + 1 > max_sock_tags) {
552 pr_info("qtaguid: new_tag_ref(0x%llx): "
553 "tag ref alloc quota exceeded. max=%d\n",
554 new_tag, max_sock_tags);
560 tr_entry = kzalloc(sizeof(*tr_entry), GFP_ATOMIC);
562 pr_err("qtaguid: new_tag_ref(0x%llx): "
563 "tag ref alloc failed\n",
568 tr_entry->tn.tag = new_tag;
569 /* tr_entry->num_sock_tags handled by caller */
570 utd_entry->num_active_tags++;
571 tag_ref_tree_insert(tr_entry, &utd_entry->tag_ref_tree);
572 DR_DEBUG("qtaguid: new_tag_ref(0x%llx): "
573 " inserted new tag ref %p\n",
581 static struct tag_ref *lookup_tag_ref(tag_t full_tag,
582 struct uid_tag_data **utd_res)
584 struct uid_tag_data *utd_entry;
585 struct tag_ref *tr_entry;
587 uid_t uid = get_uid_from_tag(full_tag);
589 DR_DEBUG("qtaguid: lookup_tag_ref(tag=0x%llx (uid=%u))\n",
592 utd_entry = get_uid_data(uid, &found_utd);
593 if (IS_ERR_OR_NULL(utd_entry)) {
595 *utd_res = utd_entry;
599 tr_entry = tag_ref_tree_search(&utd_entry->tag_ref_tree, full_tag);
601 *utd_res = utd_entry;
602 DR_DEBUG("qtaguid: lookup_tag_ref(0x%llx) utd_entry=%p tr_entry=%p\n",
603 full_tag, utd_entry, tr_entry);
607 /* Never returns NULL. Either PTR_ERR or a valid ptr. */
608 static struct tag_ref *get_tag_ref(tag_t full_tag,
609 struct uid_tag_data **utd_res)
611 struct uid_tag_data *utd_entry;
612 struct tag_ref *tr_entry;
614 DR_DEBUG("qtaguid: get_tag_ref(0x%llx)\n",
616 spin_lock_bh(&uid_tag_data_tree_lock);
617 tr_entry = lookup_tag_ref(full_tag, &utd_entry);
618 BUG_ON(IS_ERR_OR_NULL(utd_entry));
620 tr_entry = new_tag_ref(full_tag, utd_entry);
622 spin_unlock_bh(&uid_tag_data_tree_lock);
624 *utd_res = utd_entry;
625 DR_DEBUG("qtaguid: get_tag_ref(0x%llx) utd=%p tr=%p\n",
626 full_tag, utd_entry, tr_entry);
630 /* Checks and maybe frees the UID Tag Data entry */
631 static void put_utd_entry(struct uid_tag_data *utd_entry)
633 /* Are we done with the UID tag data entry? */
634 if (RB_EMPTY_ROOT(&utd_entry->tag_ref_tree) &&
635 !utd_entry->num_pqd) {
636 DR_DEBUG("qtaguid: %s(): "
637 "erase utd_entry=%p uid=%u "
638 "by pid=%u tgid=%u uid=%u\n", __func__,
639 utd_entry, utd_entry->uid,
640 current->pid, current->tgid, current_fsuid());
641 BUG_ON(utd_entry->num_active_tags);
642 rb_erase(&utd_entry->node, &uid_tag_data_tree);
645 DR_DEBUG("qtaguid: %s(): "
646 "utd_entry=%p still has %d tags %d proc_qtu_data\n",
647 __func__, utd_entry, utd_entry->num_active_tags,
649 BUG_ON(!(utd_entry->num_active_tags ||
650 utd_entry->num_pqd));
655 * If no sock_tags are using this tag_ref,
656 * decrements refcount of utd_entry, removes tr_entry
657 * from utd_entry->tag_ref_tree and frees.
659 static void free_tag_ref_from_utd_entry(struct tag_ref *tr_entry,
660 struct uid_tag_data *utd_entry)
662 DR_DEBUG("qtaguid: %s(): %p tag=0x%llx (uid=%u)\n", __func__,
663 tr_entry, tr_entry->tn.tag,
664 get_uid_from_tag(tr_entry->tn.tag));
665 if (!tr_entry->num_sock_tags) {
666 BUG_ON(!utd_entry->num_active_tags);
667 utd_entry->num_active_tags--;
668 rb_erase(&tr_entry->tn.node, &utd_entry->tag_ref_tree);
669 DR_DEBUG("qtaguid: %s(): erased %p\n", __func__, tr_entry);
674 static void put_tag_ref_tree(tag_t full_tag, struct uid_tag_data *utd_entry)
676 struct rb_node *node;
677 struct tag_ref *tr_entry;
680 DR_DEBUG("qtaguid: %s(tag=0x%llx (uid=%u))\n", __func__,
681 full_tag, get_uid_from_tag(full_tag));
682 acct_tag = get_atag_from_tag(full_tag);
683 node = rb_first(&utd_entry->tag_ref_tree);
685 tr_entry = rb_entry(node, struct tag_ref, tn.node);
686 node = rb_next(node);
687 if (!acct_tag || tr_entry->tn.tag == full_tag)
688 free_tag_ref_from_utd_entry(tr_entry, utd_entry);
692 static int read_proc_u64(char *page, char **start, off_t off,
693 int count, int *eof, void *data)
698 uint64_t *iface_entry = data;
703 value = *iface_entry;
704 p += sprintf(p, "%llu\n", value);
705 len = (p - page) - off;
706 *eof = (len <= count) ? 1 : 0;
711 static int read_proc_bool(char *page, char **start, off_t off,
712 int count, int *eof, void *data)
717 bool *bool_entry = data;
723 p += sprintf(p, "%u\n", value);
724 len = (p - page) - off;
725 *eof = (len <= count) ? 1 : 0;
730 static int get_active_counter_set(tag_t tag)
733 struct tag_counter_set *tcs;
735 MT_DEBUG("qtaguid: get_active_counter_set(tag=0x%llx)"
737 tag, get_uid_from_tag(tag));
738 /* For now we only handle UID tags for active sets */
739 tag = get_utag_from_tag(tag);
740 spin_lock_bh(&tag_counter_set_list_lock);
741 tcs = tag_counter_set_tree_search(&tag_counter_set_tree, tag);
743 active_set = tcs->active_set;
744 spin_unlock_bh(&tag_counter_set_list_lock);
749 * Find the entry for tracking the specified interface.
750 * Caller must hold iface_stat_list_lock
752 static struct iface_stat *get_iface_entry(const char *ifname)
754 struct iface_stat *iface_entry;
756 /* Find the entry for tracking the specified tag within the interface */
757 if (ifname == NULL) {
758 pr_info("qtaguid: iface_stat: get() NULL device name\n");
762 /* Iterate over interfaces */
763 list_for_each_entry(iface_entry, &iface_stat_list, list) {
764 if (!strcmp(ifname, iface_entry->ifname))
772 /* This is for fmt2 only */
773 static int pp_iface_stat_line(bool header, char *outp,
774 int char_count, struct iface_stat *iface_entry)
778 len = snprintf(outp, char_count,
780 "total_skb_rx_bytes total_skb_rx_packets "
781 "total_skb_tx_bytes total_skb_tx_packets "
782 "rx_tcp_bytes rx_tcp_packets "
783 "rx_udp_bytes rx_udp_packets "
784 "rx_other_bytes rx_other_packets "
785 "tx_tcp_bytes tx_tcp_packets "
786 "tx_udp_bytes tx_udp_packets "
787 "tx_other_bytes tx_other_packets\n"
790 struct data_counters *cnts;
791 int cnt_set = 0; /* We only use one set for the device */
792 cnts = &iface_entry->totals_via_skb;
796 "%llu %llu %llu %llu %llu %llu %llu %llu "
797 "%llu %llu %llu %llu %llu %llu %llu %llu\n",
799 dc_sum_bytes(cnts, cnt_set, IFS_RX),
800 dc_sum_packets(cnts, cnt_set, IFS_RX),
801 dc_sum_bytes(cnts, cnt_set, IFS_TX),
802 dc_sum_packets(cnts, cnt_set, IFS_TX),
803 cnts->bpc[cnt_set][IFS_RX][IFS_TCP].bytes,
804 cnts->bpc[cnt_set][IFS_RX][IFS_TCP].packets,
805 cnts->bpc[cnt_set][IFS_RX][IFS_UDP].bytes,
806 cnts->bpc[cnt_set][IFS_RX][IFS_UDP].packets,
807 cnts->bpc[cnt_set][IFS_RX][IFS_PROTO_OTHER].bytes,
808 cnts->bpc[cnt_set][IFS_RX][IFS_PROTO_OTHER].packets,
809 cnts->bpc[cnt_set][IFS_TX][IFS_TCP].bytes,
810 cnts->bpc[cnt_set][IFS_TX][IFS_TCP].packets,
811 cnts->bpc[cnt_set][IFS_TX][IFS_UDP].bytes,
812 cnts->bpc[cnt_set][IFS_TX][IFS_UDP].packets,
813 cnts->bpc[cnt_set][IFS_TX][IFS_PROTO_OTHER].bytes,
814 cnts->bpc[cnt_set][IFS_TX][IFS_PROTO_OTHER].packets);
819 static int iface_stat_fmt_proc_read(char *page, char **num_items_returned,
820 off_t items_to_skip, int char_count,
821 int *eof, void *data)
826 int fmt = (int)data; /* The data is just 1 (old) or 2 (uses fmt) */
827 struct iface_stat *iface_entry;
828 struct rtnl_link_stats64 dev_stats, *stats;
829 struct rtnl_link_stats64 no_dev_stats = {0};
831 if (unlikely(module_passive)) {
836 CT_DEBUG("qtaguid:proc iface_stat_fmt "
837 "pid=%u tgid=%u uid=%u "
838 "page=%p *num_items_returned=%p off=%ld "
839 "char_count=%d *eof=%d\n",
840 current->pid, current->tgid, current_fsuid(),
841 page, *num_items_returned,
842 items_to_skip, char_count, *eof);
847 if (fmt == 2 && item_index++ >= items_to_skip) {
848 len = pp_iface_stat_line(true, outp, char_count, NULL);
849 if (len >= char_count) {
855 (*num_items_returned)++;
859 * This lock will prevent iface_stat_update() from changing active,
860 * and in turn prevent an interface from unregistering itself.
862 spin_lock_bh(&iface_stat_list_lock);
863 list_for_each_entry(iface_entry, &iface_stat_list, list) {
864 if (item_index++ < items_to_skip)
867 if (iface_entry->active) {
868 stats = dev_get_stats(iface_entry->net_dev,
871 stats = &no_dev_stats;
874 * If the meaning of the data changes, then update the fmtX
881 "%llu %llu %llu %llu "
882 "%llu %llu %llu %llu\n",
885 iface_entry->totals_via_dev[IFS_RX].bytes,
886 iface_entry->totals_via_dev[IFS_RX].packets,
887 iface_entry->totals_via_dev[IFS_TX].bytes,
888 iface_entry->totals_via_dev[IFS_TX].packets,
889 stats->rx_bytes, stats->rx_packets,
890 stats->tx_bytes, stats->tx_packets
893 len = pp_iface_stat_line(false, outp, char_count,
896 if (len >= char_count) {
897 spin_unlock_bh(&iface_stat_list_lock);
903 (*num_items_returned)++;
905 spin_unlock_bh(&iface_stat_list_lock);
911 static void iface_create_proc_worker(struct work_struct *work)
913 struct proc_dir_entry *proc_entry;
914 struct iface_stat_work *isw = container_of(work, struct iface_stat_work,
916 struct iface_stat *new_iface = isw->iface_entry;
918 /* iface_entries are not deleted, so safe to manipulate. */
919 proc_entry = proc_mkdir(new_iface->ifname, iface_stat_procdir);
920 if (IS_ERR_OR_NULL(proc_entry)) {
921 pr_err("qtaguid: iface_stat: create_proc(): alloc failed.\n");
926 new_iface->proc_ptr = proc_entry;
928 create_proc_read_entry("tx_bytes", proc_iface_perms, proc_entry,
930 &new_iface->totals_via_dev[IFS_TX].bytes);
931 create_proc_read_entry("rx_bytes", proc_iface_perms, proc_entry,
933 &new_iface->totals_via_dev[IFS_RX].bytes);
934 create_proc_read_entry("tx_packets", proc_iface_perms, proc_entry,
936 &new_iface->totals_via_dev[IFS_TX].packets);
937 create_proc_read_entry("rx_packets", proc_iface_perms, proc_entry,
939 &new_iface->totals_via_dev[IFS_RX].packets);
940 create_proc_read_entry("active", proc_iface_perms, proc_entry,
941 read_proc_bool, &new_iface->active);
943 IF_DEBUG("qtaguid: iface_stat: create_proc(): done "
944 "entry=%p dev=%s\n", new_iface, new_iface->ifname);
949 * Will set the entry's active state, and
950 * update the net_dev accordingly also.
952 static void _iface_stat_set_active(struct iface_stat *entry,
953 struct net_device *net_dev,
957 entry->net_dev = net_dev;
958 entry->active = true;
959 IF_DEBUG("qtaguid: %s(%s): "
960 "enable tracking. rfcnt=%d\n", __func__,
962 __this_cpu_read(*net_dev->pcpu_refcnt));
964 entry->active = false;
965 entry->net_dev = NULL;
966 IF_DEBUG("qtaguid: %s(%s): "
967 "disable tracking. rfcnt=%d\n", __func__,
969 __this_cpu_read(*net_dev->pcpu_refcnt));
974 /* Caller must hold iface_stat_list_lock */
975 static struct iface_stat *iface_alloc(struct net_device *net_dev)
977 struct iface_stat *new_iface;
978 struct iface_stat_work *isw;
980 new_iface = kzalloc(sizeof(*new_iface), GFP_ATOMIC);
981 if (new_iface == NULL) {
982 pr_err("qtaguid: iface_stat: create(%s): "
983 "iface_stat alloc failed\n", net_dev->name);
986 new_iface->ifname = kstrdup(net_dev->name, GFP_ATOMIC);
987 if (new_iface->ifname == NULL) {
988 pr_err("qtaguid: iface_stat: create(%s): "
989 "ifname alloc failed\n", net_dev->name);
993 spin_lock_init(&new_iface->tag_stat_list_lock);
994 new_iface->tag_stat_tree = RB_ROOT;
995 _iface_stat_set_active(new_iface, net_dev, true);
998 * ipv6 notifier chains are atomic :(
999 * No create_proc_read_entry() for you!
1001 isw = kmalloc(sizeof(*isw), GFP_ATOMIC);
1003 pr_err("qtaguid: iface_stat: create(%s): "
1004 "work alloc failed\n", new_iface->ifname);
1005 _iface_stat_set_active(new_iface, net_dev, false);
1006 kfree(new_iface->ifname);
1010 isw->iface_entry = new_iface;
1011 INIT_WORK(&isw->iface_work, iface_create_proc_worker);
1012 schedule_work(&isw->iface_work);
1013 list_add(&new_iface->list, &iface_stat_list);
1017 static void iface_check_stats_reset_and_adjust(struct net_device *net_dev,
1018 struct iface_stat *iface)
1020 struct rtnl_link_stats64 dev_stats, *stats;
1023 stats = dev_get_stats(net_dev, &dev_stats);
1024 /* No empty packets */
1026 (stats->rx_bytes < iface->last_known[IFS_RX].bytes)
1027 || (stats->tx_bytes < iface->last_known[IFS_TX].bytes);
1029 IF_DEBUG("qtaguid: %s(%s): iface=%p netdev=%p "
1030 "bytes rx/tx=%llu/%llu "
1031 "active=%d last_known=%d "
1032 "stats_rewound=%d\n", __func__,
1033 net_dev ? net_dev->name : "?",
1035 stats->rx_bytes, stats->tx_bytes,
1036 iface->active, iface->last_known_valid, stats_rewound);
1038 if (iface->active && iface->last_known_valid && stats_rewound) {
1039 pr_warn_once("qtaguid: iface_stat: %s(%s): "
1040 "iface reset its stats unexpectedly\n", __func__,
1043 iface->totals_via_dev[IFS_TX].bytes +=
1044 iface->last_known[IFS_TX].bytes;
1045 iface->totals_via_dev[IFS_TX].packets +=
1046 iface->last_known[IFS_TX].packets;
1047 iface->totals_via_dev[IFS_RX].bytes +=
1048 iface->last_known[IFS_RX].bytes;
1049 iface->totals_via_dev[IFS_RX].packets +=
1050 iface->last_known[IFS_RX].packets;
1051 iface->last_known_valid = false;
1052 IF_DEBUG("qtaguid: %s(%s): iface=%p "
1053 "used last known bytes rx/tx=%llu/%llu\n", __func__,
1054 iface->ifname, iface, iface->last_known[IFS_RX].bytes,
1055 iface->last_known[IFS_TX].bytes);
1060 * Create a new entry for tracking the specified interface.
1061 * Do nothing if the entry already exists.
1062 * Called when an interface is configured with a valid IP address.
1064 static void iface_stat_create(struct net_device *net_dev,
1065 struct in_ifaddr *ifa)
1067 struct in_device *in_dev = NULL;
1069 struct iface_stat *entry;
1071 struct iface_stat *new_iface;
1073 IF_DEBUG("qtaguid: iface_stat: create(%s): ifa=%p netdev=%p\n",
1074 net_dev ? net_dev->name : "?",
1077 pr_err("qtaguid: iface_stat: create(): no net dev\n");
1081 ifname = net_dev->name;
1083 in_dev = in_dev_get(net_dev);
1085 pr_err("qtaguid: iface_stat: create(%s): no inet dev\n",
1089 IF_DEBUG("qtaguid: iface_stat: create(%s): in_dev=%p\n",
1091 for (ifa = in_dev->ifa_list; ifa; ifa = ifa->ifa_next) {
1092 IF_DEBUG("qtaguid: iface_stat: create(%s): "
1093 "ifa=%p ifa_label=%s\n",
1095 ifa->ifa_label ? ifa->ifa_label : "(null)");
1096 if (ifa->ifa_label && !strcmp(ifname, ifa->ifa_label))
1102 IF_DEBUG("qtaguid: iface_stat: create(%s): no matching IP\n",
1106 ipaddr = ifa->ifa_local;
1108 spin_lock_bh(&iface_stat_list_lock);
1109 entry = get_iface_entry(ifname);
1110 if (entry != NULL) {
1111 IF_DEBUG("qtaguid: iface_stat: create(%s): entry=%p\n",
1113 iface_check_stats_reset_and_adjust(net_dev, entry);
1114 _iface_stat_set_active(entry, net_dev, true);
1115 IF_DEBUG("qtaguid: %s(%s): "
1116 "tracking now %d on ip=%pI4\n", __func__,
1117 entry->ifname, true, &ipaddr);
1118 goto done_unlock_put;
1121 new_iface = iface_alloc(net_dev);
1122 IF_DEBUG("qtaguid: iface_stat: create(%s): done "
1123 "entry=%p ip=%pI4\n", ifname, new_iface, &ipaddr);
1125 spin_unlock_bh(&iface_stat_list_lock);
1131 static void iface_stat_create_ipv6(struct net_device *net_dev,
1132 struct inet6_ifaddr *ifa)
1134 struct in_device *in_dev;
1136 struct iface_stat *entry;
1137 struct iface_stat *new_iface;
1140 IF_DEBUG("qtaguid: iface_stat: create6(): ifa=%p netdev=%p->name=%s\n",
1141 ifa, net_dev, net_dev ? net_dev->name : "");
1143 pr_err("qtaguid: iface_stat: create6(): no net dev!\n");
1146 ifname = net_dev->name;
1148 in_dev = in_dev_get(net_dev);
1150 pr_err("qtaguid: iface_stat: create6(%s): no inet dev\n",
1155 IF_DEBUG("qtaguid: iface_stat: create6(%s): in_dev=%p\n",
1159 IF_DEBUG("qtaguid: iface_stat: create6(%s): no matching IP\n",
1163 addr_type = ipv6_addr_type(&ifa->addr);
1165 spin_lock_bh(&iface_stat_list_lock);
1166 entry = get_iface_entry(ifname);
1167 if (entry != NULL) {
1168 IF_DEBUG("qtaguid: %s(%s): entry=%p\n", __func__,
1170 iface_check_stats_reset_and_adjust(net_dev, entry);
1171 _iface_stat_set_active(entry, net_dev, true);
1172 IF_DEBUG("qtaguid: %s(%s): "
1173 "tracking now %d on ip=%pI6c\n", __func__,
1174 entry->ifname, true, &ifa->addr);
1175 goto done_unlock_put;
1178 new_iface = iface_alloc(net_dev);
1179 IF_DEBUG("qtaguid: iface_stat: create6(%s): done "
1180 "entry=%p ip=%pI6c\n", ifname, new_iface, &ifa->addr);
1183 spin_unlock_bh(&iface_stat_list_lock);
1188 static struct sock_tag *get_sock_stat_nl(const struct sock *sk)
1190 MT_DEBUG("qtaguid: get_sock_stat_nl(sk=%p)\n", sk);
1191 return sock_tag_tree_search(&sock_tag_tree, sk);
1194 static struct sock_tag *get_sock_stat(const struct sock *sk)
1196 struct sock_tag *sock_tag_entry;
1197 MT_DEBUG("qtaguid: get_sock_stat(sk=%p)\n", sk);
1200 spin_lock_bh(&sock_tag_list_lock);
1201 sock_tag_entry = get_sock_stat_nl(sk);
1202 spin_unlock_bh(&sock_tag_list_lock);
1203 return sock_tag_entry;
1206 static int ipx_proto(const struct sk_buff *skb,
1207 struct xt_action_param *par)
1209 int thoff = 0, tproto;
1211 switch (par->family) {
1213 tproto = ipv6_find_hdr(skb, &thoff, -1, NULL, NULL);
1215 MT_DEBUG("%s(): transport header not found in ipv6"
1216 " skb=%p\n", __func__, skb);
1219 tproto = ip_hdr(skb)->protocol;
1222 tproto = IPPROTO_RAW;
1228 data_counters_update(struct data_counters *dc, int set,
1229 enum ifs_tx_rx direction, int proto, int bytes)
1233 dc_add_byte_packets(dc, set, direction, IFS_TCP, bytes, 1);
1236 dc_add_byte_packets(dc, set, direction, IFS_UDP, bytes, 1);
1240 dc_add_byte_packets(dc, set, direction, IFS_PROTO_OTHER, bytes,
1247 * Update stats for the specified interface. Do nothing if the entry
1248 * does not exist (when a device was never configured with an IP address).
1249 * Called when an device is being unregistered.
1251 static void iface_stat_update(struct net_device *net_dev, bool stash_only)
1253 struct rtnl_link_stats64 dev_stats, *stats;
1254 struct iface_stat *entry;
1256 stats = dev_get_stats(net_dev, &dev_stats);
1257 spin_lock_bh(&iface_stat_list_lock);
1258 entry = get_iface_entry(net_dev->name);
1259 if (entry == NULL) {
1260 IF_DEBUG("qtaguid: iface_stat: update(%s): not tracked\n",
1262 spin_unlock_bh(&iface_stat_list_lock);
1266 IF_DEBUG("qtaguid: %s(%s): entry=%p\n", __func__,
1267 net_dev->name, entry);
1268 if (!entry->active) {
1269 IF_DEBUG("qtaguid: %s(%s): already disabled\n", __func__,
1271 spin_unlock_bh(&iface_stat_list_lock);
1276 entry->last_known[IFS_TX].bytes = stats->tx_bytes;
1277 entry->last_known[IFS_TX].packets = stats->tx_packets;
1278 entry->last_known[IFS_RX].bytes = stats->rx_bytes;
1279 entry->last_known[IFS_RX].packets = stats->rx_packets;
1280 entry->last_known_valid = true;
1281 IF_DEBUG("qtaguid: %s(%s): "
1282 "dev stats stashed rx/tx=%llu/%llu\n", __func__,
1283 net_dev->name, stats->rx_bytes, stats->tx_bytes);
1284 spin_unlock_bh(&iface_stat_list_lock);
1287 entry->totals_via_dev[IFS_TX].bytes += stats->tx_bytes;
1288 entry->totals_via_dev[IFS_TX].packets += stats->tx_packets;
1289 entry->totals_via_dev[IFS_RX].bytes += stats->rx_bytes;
1290 entry->totals_via_dev[IFS_RX].packets += stats->rx_packets;
1291 /* We don't need the last_known[] anymore */
1292 entry->last_known_valid = false;
1293 _iface_stat_set_active(entry, net_dev, false);
1294 IF_DEBUG("qtaguid: %s(%s): "
1295 "disable tracking. rx/tx=%llu/%llu\n", __func__,
1296 net_dev->name, stats->rx_bytes, stats->tx_bytes);
1297 spin_unlock_bh(&iface_stat_list_lock);
1301 * Update stats for the specified interface from the skb.
1302 * Do nothing if the entry
1303 * does not exist (when a device was never configured with an IP address).
1304 * Called on each sk.
1306 static void iface_stat_update_from_skb(const struct sk_buff *skb,
1307 struct xt_action_param *par)
1309 struct iface_stat *entry;
1310 const struct net_device *el_dev;
1311 enum ifs_tx_rx direction = par->in ? IFS_RX : IFS_TX;
1312 int bytes = skb->len;
1316 MT_DEBUG("qtaguid[%d]: no skb->dev\n", par->hooknum);
1317 el_dev = par->in ? : par->out;
1319 const struct net_device *other_dev;
1321 other_dev = par->in ? : par->out;
1322 if (el_dev != other_dev) {
1323 MT_DEBUG("qtaguid[%d]: skb->dev=%p %s vs "
1324 "par->(in/out)=%p %s\n",
1325 par->hooknum, el_dev, el_dev->name, other_dev,
1330 if (unlikely(!el_dev)) {
1331 pr_err("qtaguid[%d]: %s(): no par->in/out?!!\n",
1332 par->hooknum, __func__);
1334 } else if (unlikely(!el_dev->name)) {
1335 pr_err("qtaguid[%d]: %s(): no dev->name?!!\n",
1336 par->hooknum, __func__);
1339 proto = ipx_proto(skb, par);
1340 MT_DEBUG("qtaguid[%d]: dev name=%s type=%d fam=%d proto=%d\n",
1341 par->hooknum, el_dev->name, el_dev->type,
1342 par->family, proto);
1345 spin_lock_bh(&iface_stat_list_lock);
1346 entry = get_iface_entry(el_dev->name);
1347 if (entry == NULL) {
1348 IF_DEBUG("qtaguid: iface_stat: %s(%s): not tracked\n",
1349 __func__, el_dev->name);
1350 spin_unlock_bh(&iface_stat_list_lock);
1354 IF_DEBUG("qtaguid: %s(%s): entry=%p\n", __func__,
1355 el_dev->name, entry);
1357 data_counters_update(&entry->totals_via_skb, 0, direction, proto,
1359 spin_unlock_bh(&iface_stat_list_lock);
1362 static void tag_stat_update(struct tag_stat *tag_entry,
1363 enum ifs_tx_rx direction, int proto, int bytes)
1366 active_set = get_active_counter_set(tag_entry->tn.tag);
1367 MT_DEBUG("qtaguid: tag_stat_update(tag=0x%llx (uid=%u) set=%d "
1368 "dir=%d proto=%d bytes=%d)\n",
1369 tag_entry->tn.tag, get_uid_from_tag(tag_entry->tn.tag),
1370 active_set, direction, proto, bytes);
1371 data_counters_update(&tag_entry->counters, active_set, direction,
1373 if (tag_entry->parent_counters)
1374 data_counters_update(tag_entry->parent_counters, active_set,
1375 direction, proto, bytes);
1379 * Create a new entry for tracking the specified {acct_tag,uid_tag} within
1381 * iface_entry->tag_stat_list_lock should be held.
1383 static struct tag_stat *create_if_tag_stat(struct iface_stat *iface_entry,
1386 struct tag_stat *new_tag_stat_entry = NULL;
1387 IF_DEBUG("qtaguid: iface_stat: %s(): ife=%p tag=0x%llx"
1388 " (uid=%u)\n", __func__,
1389 iface_entry, tag, get_uid_from_tag(tag));
1390 new_tag_stat_entry = kzalloc(sizeof(*new_tag_stat_entry), GFP_ATOMIC);
1391 if (!new_tag_stat_entry) {
1392 pr_err("qtaguid: iface_stat: tag stat alloc failed\n");
1395 new_tag_stat_entry->tn.tag = tag;
1396 tag_stat_tree_insert(new_tag_stat_entry, &iface_entry->tag_stat_tree);
1398 return new_tag_stat_entry;
1401 static void if_tag_stat_update(const char *ifname, uid_t uid,
1402 const struct sock *sk, enum ifs_tx_rx direction,
1403 int proto, int bytes)
1405 struct tag_stat *tag_stat_entry;
1406 tag_t tag, acct_tag;
1408 struct data_counters *uid_tag_counters;
1409 struct sock_tag *sock_tag_entry;
1410 struct iface_stat *iface_entry;
1411 struct tag_stat *new_tag_stat = NULL;
1412 MT_DEBUG("qtaguid: if_tag_stat_update(ifname=%s "
1413 "uid=%u sk=%p dir=%d proto=%d bytes=%d)\n",
1414 ifname, uid, sk, direction, proto, bytes);
1417 iface_entry = get_iface_entry(ifname);
1419 pr_err("qtaguid: iface_stat: stat_update() %s not found\n",
1423 /* It is ok to process data when an iface_entry is inactive */
1425 MT_DEBUG("qtaguid: iface_stat: stat_update() dev=%s entry=%p\n",
1426 ifname, iface_entry);
1429 * Look for a tagged sock.
1430 * It will have an acct_uid.
1432 sock_tag_entry = get_sock_stat(sk);
1433 if (sock_tag_entry) {
1434 tag = sock_tag_entry->tag;
1435 acct_tag = get_atag_from_tag(tag);
1436 uid_tag = get_utag_from_tag(tag);
1438 acct_tag = make_atag_from_value(0);
1439 tag = combine_atag_with_uid(acct_tag, uid);
1440 uid_tag = make_tag_from_uid(uid);
1442 MT_DEBUG("qtaguid: iface_stat: stat_update(): "
1443 " looking for tag=0x%llx (uid=%u) in ife=%p\n",
1444 tag, get_uid_from_tag(tag), iface_entry);
1445 /* Loop over tag list under this interface for {acct_tag,uid_tag} */
1446 spin_lock_bh(&iface_entry->tag_stat_list_lock);
1448 tag_stat_entry = tag_stat_tree_search(&iface_entry->tag_stat_tree,
1450 if (tag_stat_entry) {
1452 * Updating the {acct_tag, uid_tag} entry handles both stats:
1453 * {0, uid_tag} will also get updated.
1455 tag_stat_update(tag_stat_entry, direction, proto, bytes);
1456 spin_unlock_bh(&iface_entry->tag_stat_list_lock);
1460 /* Loop over tag list under this interface for {0,uid_tag} */
1461 tag_stat_entry = tag_stat_tree_search(&iface_entry->tag_stat_tree,
1463 if (!tag_stat_entry) {
1464 /* Here: the base uid_tag did not exist */
1466 * No parent counters. So
1467 * - No {0, uid_tag} stats and no {acc_tag, uid_tag} stats.
1469 new_tag_stat = create_if_tag_stat(iface_entry, uid_tag);
1472 uid_tag_counters = &new_tag_stat->counters;
1474 uid_tag_counters = &tag_stat_entry->counters;
1478 /* Create the child {acct_tag, uid_tag} and hook up parent. */
1479 new_tag_stat = create_if_tag_stat(iface_entry, tag);
1482 new_tag_stat->parent_counters = uid_tag_counters;
1485 * For new_tag_stat to be still NULL here would require:
1486 * {0, uid_tag} exists
1487 * and {acct_tag, uid_tag} doesn't exist
1488 * AND acct_tag == 0.
1489 * Impossible. This reassures us that new_tag_stat
1490 * below will always be assigned.
1492 BUG_ON(!new_tag_stat);
1494 tag_stat_update(new_tag_stat, direction, proto, bytes);
1496 spin_unlock_bh(&iface_entry->tag_stat_list_lock);
1499 static int iface_netdev_event_handler(struct notifier_block *nb,
1500 unsigned long event, void *ptr) {
1501 struct net_device *dev = ptr;
1503 if (unlikely(module_passive))
1506 IF_DEBUG("qtaguid: iface_stat: netdev_event(): "
1507 "ev=0x%lx/%s netdev=%p->name=%s\n",
1508 event, netdev_evt_str(event), dev, dev ? dev->name : "");
1512 iface_stat_create(dev, NULL);
1513 atomic64_inc(&qtu_events.iface_events);
1516 case NETDEV_UNREGISTER:
1517 iface_stat_update(dev, event == NETDEV_DOWN);
1518 atomic64_inc(&qtu_events.iface_events);
1524 static int iface_inet6addr_event_handler(struct notifier_block *nb,
1525 unsigned long event, void *ptr)
1527 struct inet6_ifaddr *ifa = ptr;
1528 struct net_device *dev;
1530 if (unlikely(module_passive))
1533 IF_DEBUG("qtaguid: iface_stat: inet6addr_event(): "
1534 "ev=0x%lx/%s ifa=%p\n",
1535 event, netdev_evt_str(event), ifa);
1539 BUG_ON(!ifa || !ifa->idev);
1540 dev = (struct net_device *)ifa->idev->dev;
1541 iface_stat_create_ipv6(dev, ifa);
1542 atomic64_inc(&qtu_events.iface_events);
1545 case NETDEV_UNREGISTER:
1546 BUG_ON(!ifa || !ifa->idev);
1547 dev = (struct net_device *)ifa->idev->dev;
1548 iface_stat_update(dev, event == NETDEV_DOWN);
1549 atomic64_inc(&qtu_events.iface_events);
1555 static int iface_inetaddr_event_handler(struct notifier_block *nb,
1556 unsigned long event, void *ptr)
1558 struct in_ifaddr *ifa = ptr;
1559 struct net_device *dev;
1561 if (unlikely(module_passive))
1564 IF_DEBUG("qtaguid: iface_stat: inetaddr_event(): "
1565 "ev=0x%lx/%s ifa=%p\n",
1566 event, netdev_evt_str(event), ifa);
1570 BUG_ON(!ifa || !ifa->ifa_dev);
1571 dev = ifa->ifa_dev->dev;
1572 iface_stat_create(dev, ifa);
1573 atomic64_inc(&qtu_events.iface_events);
1576 case NETDEV_UNREGISTER:
1577 BUG_ON(!ifa || !ifa->ifa_dev);
1578 dev = ifa->ifa_dev->dev;
1579 iface_stat_update(dev, event == NETDEV_DOWN);
1580 atomic64_inc(&qtu_events.iface_events);
1586 static struct notifier_block iface_netdev_notifier_blk = {
1587 .notifier_call = iface_netdev_event_handler,
1590 static struct notifier_block iface_inetaddr_notifier_blk = {
1591 .notifier_call = iface_inetaddr_event_handler,
1594 static struct notifier_block iface_inet6addr_notifier_blk = {
1595 .notifier_call = iface_inet6addr_event_handler,
1598 static int __init iface_stat_init(struct proc_dir_entry *parent_procdir)
1602 iface_stat_procdir = proc_mkdir(iface_stat_procdirname, parent_procdir);
1603 if (!iface_stat_procdir) {
1604 pr_err("qtaguid: iface_stat: init failed to create proc entry\n");
1609 iface_stat_all_procfile = create_proc_entry(iface_stat_all_procfilename,
1612 if (!iface_stat_all_procfile) {
1613 pr_err("qtaguid: iface_stat: init "
1614 " failed to create stat_old proc entry\n");
1618 iface_stat_all_procfile->read_proc = iface_stat_fmt_proc_read;
1619 iface_stat_all_procfile->data = (void *)1; /* fmt1 */
1621 iface_stat_fmt_procfile = create_proc_entry(iface_stat_fmt_procfilename,
1624 if (!iface_stat_fmt_procfile) {
1625 pr_err("qtaguid: iface_stat: init "
1626 " failed to create stat_all proc entry\n");
1628 goto err_zap_all_stats_entry;
1630 iface_stat_fmt_procfile->read_proc = iface_stat_fmt_proc_read;
1631 iface_stat_fmt_procfile->data = (void *)2; /* fmt2 */
1634 err = register_netdevice_notifier(&iface_netdev_notifier_blk);
1636 pr_err("qtaguid: iface_stat: init "
1637 "failed to register dev event handler\n");
1638 goto err_zap_all_stats_entries;
1640 err = register_inetaddr_notifier(&iface_inetaddr_notifier_blk);
1642 pr_err("qtaguid: iface_stat: init "
1643 "failed to register ipv4 dev event handler\n");
1647 err = register_inet6addr_notifier(&iface_inet6addr_notifier_blk);
1649 pr_err("qtaguid: iface_stat: init "
1650 "failed to register ipv6 dev event handler\n");
1651 goto err_unreg_ip4_addr;
1656 unregister_inetaddr_notifier(&iface_inetaddr_notifier_blk);
1658 unregister_netdevice_notifier(&iface_netdev_notifier_blk);
1659 err_zap_all_stats_entries:
1660 remove_proc_entry(iface_stat_fmt_procfilename, parent_procdir);
1661 err_zap_all_stats_entry:
1662 remove_proc_entry(iface_stat_all_procfilename, parent_procdir);
1664 remove_proc_entry(iface_stat_procdirname, parent_procdir);
1669 static struct sock *qtaguid_find_sk(const struct sk_buff *skb,
1670 struct xt_action_param *par)
1673 unsigned int hook_mask = (1 << par->hooknum);
1675 MT_DEBUG("qtaguid: find_sk(skb=%p) hooknum=%d family=%d\n", skb,
1676 par->hooknum, par->family);
1679 * Let's not abuse the the xt_socket_get*_sk(), or else it will
1680 * return garbage SKs.
1682 if (!(hook_mask & XT_SOCKET_SUPPORTED_HOOKS))
1685 switch (par->family) {
1687 sk = xt_socket_get6_sk(skb, par);
1690 sk = xt_socket_get4_sk(skb, par);
1697 * Seems to be issues on the file ptr for TCP_TIME_WAIT SKs.
1698 * http://kerneltrap.org/mailarchive/linux-netdev/2010/10/21/6287959
1699 * Not fixed in 3.0-r3 :(
1702 MT_DEBUG("qtaguid: %p->sk_proto=%u "
1703 "->sk_state=%d\n", sk, sk->sk_protocol, sk->sk_state);
1704 if (sk->sk_state == TCP_TIME_WAIT) {
1705 xt_socket_put_sk(sk);
1712 static void account_for_uid(const struct sk_buff *skb,
1713 const struct sock *alternate_sk, uid_t uid,
1714 struct xt_action_param *par)
1716 const struct net_device *el_dev;
1719 MT_DEBUG("qtaguid[%d]: no skb->dev\n", par->hooknum);
1720 el_dev = par->in ? : par->out;
1722 const struct net_device *other_dev;
1724 other_dev = par->in ? : par->out;
1725 if (el_dev != other_dev) {
1726 MT_DEBUG("qtaguid[%d]: skb->dev=%p %s vs "
1727 "par->(in/out)=%p %s\n",
1728 par->hooknum, el_dev, el_dev->name, other_dev,
1733 if (unlikely(!el_dev)) {
1734 pr_info("qtaguid[%d]: no par->in/out?!!\n", par->hooknum);
1735 } else if (unlikely(!el_dev->name)) {
1736 pr_info("qtaguid[%d]: no dev->name?!!\n", par->hooknum);
1738 int proto = ipx_proto(skb, par);
1739 MT_DEBUG("qtaguid[%d]: dev name=%s type=%d fam=%d proto=%d\n",
1740 par->hooknum, el_dev->name, el_dev->type,
1741 par->family, proto);
1743 if_tag_stat_update(el_dev->name, uid,
1744 skb->sk ? skb->sk : alternate_sk,
1745 par->in ? IFS_RX : IFS_TX,
1750 static bool qtaguid_mt(const struct sk_buff *skb, struct xt_action_param *par)
1752 const struct xt_qtaguid_match_info *info = par->matchinfo;
1753 const struct file *filp;
1754 bool got_sock = false;
1759 if (unlikely(module_passive))
1760 return (info->match ^ info->invert) == 0;
1762 MT_DEBUG("qtaguid[%d]: entered skb=%p par->in=%p/out=%p fam=%d\n",
1763 par->hooknum, skb, par->in, par->out, par->family);
1765 atomic64_inc(&qtu_events.match_calls);
1767 res = (info->match ^ info->invert) == 0;
1771 switch (par->hooknum) {
1772 case NF_INET_PRE_ROUTING:
1773 case NF_INET_POST_ROUTING:
1774 atomic64_inc(&qtu_events.match_calls_prepost);
1775 iface_stat_update_from_skb(skb, par);
1777 * We are done in pre/post. The skb will get processed
1780 res = (info->match ^ info->invert);
1783 /* default: Fall through and do UID releated work */
1789 * A missing sk->sk_socket happens when packets are in-flight
1790 * and the matching socket is already closed and gone.
1792 sk = qtaguid_find_sk(skb, par);
1794 * If we got the socket from the find_sk(), we will need to put
1795 * it back, as nf_tproxy_get_sock_v4() got it.
1799 atomic64_inc(&qtu_events.match_found_sk_in_ct);
1801 atomic64_inc(&qtu_events.match_found_no_sk_in_ct);
1803 atomic64_inc(&qtu_events.match_found_sk);
1805 MT_DEBUG("qtaguid[%d]: sk=%p got_sock=%d fam=%d proto=%d\n",
1806 par->hooknum, sk, got_sock, par->family, ipx_proto(skb, par));
1808 MT_DEBUG("qtaguid[%d]: sk=%p->sk_socket=%p->file=%p\n",
1809 par->hooknum, sk, sk->sk_socket,
1810 sk->sk_socket ? sk->sk_socket->file : (void *)-1LL);
1811 filp = sk->sk_socket ? sk->sk_socket->file : NULL;
1812 MT_DEBUG("qtaguid[%d]: filp...uid=%u\n",
1813 par->hooknum, filp ? filp->f_cred->fsuid : -1);
1816 if (sk == NULL || sk->sk_socket == NULL) {
1818 * Here, the qtaguid_find_sk() using connection tracking
1819 * couldn't find the owner, so for now we just count them
1820 * against the system.
1823 * TODO: unhack how to force just accounting.
1824 * For now we only do iface stats when the uid-owner is not
1827 if (!(info->match & XT_QTAGUID_UID))
1828 account_for_uid(skb, sk, 0, par);
1829 MT_DEBUG("qtaguid[%d]: leaving (sk?sk->sk_socket)=%p\n",
1831 sk ? sk->sk_socket : NULL);
1832 res = (info->match ^ info->invert) == 0;
1833 atomic64_inc(&qtu_events.match_no_sk);
1834 goto put_sock_ret_res;
1835 } else if (info->match & info->invert & XT_QTAGUID_SOCKET) {
1837 goto put_sock_ret_res;
1839 filp = sk->sk_socket->file;
1841 MT_DEBUG("qtaguid[%d]: leaving filp=NULL\n", par->hooknum);
1842 account_for_uid(skb, sk, 0, par);
1843 res = ((info->match ^ info->invert) &
1844 (XT_QTAGUID_UID | XT_QTAGUID_GID)) == 0;
1845 atomic64_inc(&qtu_events.match_no_sk_file);
1846 goto put_sock_ret_res;
1848 sock_uid = filp->f_cred->fsuid;
1850 * TODO: unhack how to force just accounting.
1851 * For now we only do iface stats when the uid-owner is not requested
1853 if (!(info->match & XT_QTAGUID_UID))
1854 account_for_uid(skb, sk, sock_uid, par);
1857 * The following two tests fail the match when:
1858 * id not in range AND no inverted condition requested
1859 * or id in range AND inverted condition requested
1860 * Thus (!a && b) || (a && !b) == a ^ b
1862 if (info->match & XT_QTAGUID_UID)
1863 if ((filp->f_cred->fsuid >= info->uid_min &&
1864 filp->f_cred->fsuid <= info->uid_max) ^
1865 !(info->invert & XT_QTAGUID_UID)) {
1866 MT_DEBUG("qtaguid[%d]: leaving uid not matching\n",
1869 goto put_sock_ret_res;
1871 if (info->match & XT_QTAGUID_GID)
1872 if ((filp->f_cred->fsgid >= info->gid_min &&
1873 filp->f_cred->fsgid <= info->gid_max) ^
1874 !(info->invert & XT_QTAGUID_GID)) {
1875 MT_DEBUG("qtaguid[%d]: leaving gid not matching\n",
1878 goto put_sock_ret_res;
1881 MT_DEBUG("qtaguid[%d]: leaving matched\n", par->hooknum);
1886 xt_socket_put_sk(sk);
1888 MT_DEBUG("qtaguid[%d]: left %d\n", par->hooknum, res);
1893 /* This function is not in xt_qtaguid_print.c because of locks visibility */
1894 static void prdebug_full_state(int indent_level, const char *fmt, ...)
1900 if (!unlikely(qtaguid_debug_mask & DDEBUG_MASK))
1903 fmt_buff = kasprintf(GFP_ATOMIC,
1904 "qtaguid: %s(): %s {\n", __func__, fmt);
1906 va_start(args, fmt);
1907 buff = kvasprintf(GFP_ATOMIC,
1910 pr_debug("%s", buff);
1915 spin_lock_bh(&sock_tag_list_lock);
1916 prdebug_sock_tag_tree(indent_level, &sock_tag_tree);
1917 spin_unlock_bh(&sock_tag_list_lock);
1919 spin_lock_bh(&sock_tag_list_lock);
1920 spin_lock_bh(&uid_tag_data_tree_lock);
1921 prdebug_uid_tag_data_tree(indent_level, &uid_tag_data_tree);
1922 prdebug_proc_qtu_data_tree(indent_level, &proc_qtu_data_tree);
1923 spin_unlock_bh(&uid_tag_data_tree_lock);
1924 spin_unlock_bh(&sock_tag_list_lock);
1926 spin_lock_bh(&iface_stat_list_lock);
1927 prdebug_iface_stat_list(indent_level, &iface_stat_list);
1928 spin_unlock_bh(&iface_stat_list_lock);
1930 pr_debug("qtaguid: %s(): }\n", __func__);
1933 static void prdebug_full_state(int indent_level, const char *fmt, ...) {}
1937 * Procfs reader to get all active socket tags using style "1)" as described in
1940 static int qtaguid_ctrl_proc_read(char *page, char **num_items_returned,
1941 off_t items_to_skip, int char_count, int *eof,
1947 struct rb_node *node;
1948 struct sock_tag *sock_tag_entry;
1950 int indent_level = 0;
1953 if (unlikely(module_passive)) {
1961 CT_DEBUG("qtaguid: proc ctrl pid=%u tgid=%u uid=%u "
1962 "page=%p off=%ld char_count=%d *eof=%d\n",
1963 current->pid, current->tgid, current_fsuid(),
1964 page, items_to_skip, char_count, *eof);
1966 spin_lock_bh(&sock_tag_list_lock);
1967 for (node = rb_first(&sock_tag_tree);
1969 node = rb_next(node)) {
1970 if (item_index++ < items_to_skip)
1972 sock_tag_entry = rb_entry(node, struct sock_tag, sock_node);
1973 uid = get_uid_from_tag(sock_tag_entry->tag);
1974 CT_DEBUG("qtaguid: proc_read(): sk=%p tag=0x%llx (uid=%u) "
1977 sock_tag_entry->tag,
1981 f_count = atomic_long_read(
1982 &sock_tag_entry->socket->file->f_count);
1983 len = snprintf(outp, char_count,
1984 "sock=%p tag=0x%llx (uid=%u) pid=%u "
1987 sock_tag_entry->tag, uid,
1988 sock_tag_entry->pid, f_count);
1989 if (len >= char_count) {
1990 spin_unlock_bh(&sock_tag_list_lock);
1996 (*num_items_returned)++;
1998 spin_unlock_bh(&sock_tag_list_lock);
2000 if (item_index++ >= items_to_skip) {
2001 len = snprintf(outp, char_count,
2002 "events: sockets_tagged=%llu "
2003 "sockets_untagged=%llu "
2004 "counter_set_changes=%llu "
2006 "iface_events=%llu "
2008 "match_calls_prepost=%llu "
2009 "match_found_sk=%llu "
2010 "match_found_sk_in_ct=%llu "
2011 "match_found_no_sk_in_ct=%llu "
2013 "match_no_sk_file=%llu\n",
2014 atomic64_read(&qtu_events.sockets_tagged),
2015 atomic64_read(&qtu_events.sockets_untagged),
2016 atomic64_read(&qtu_events.counter_set_changes),
2017 atomic64_read(&qtu_events.delete_cmds),
2018 atomic64_read(&qtu_events.iface_events),
2019 atomic64_read(&qtu_events.match_calls),
2020 atomic64_read(&qtu_events.match_calls_prepost),
2021 atomic64_read(&qtu_events.match_found_sk),
2022 atomic64_read(&qtu_events.match_found_sk_in_ct),
2024 &qtu_events.match_found_no_sk_in_ct),
2025 atomic64_read(&qtu_events.match_no_sk),
2026 atomic64_read(&qtu_events.match_no_sk_file));
2027 if (len >= char_count) {
2033 (*num_items_returned)++;
2036 /* Count the following as part of the last item_index */
2037 if (item_index > items_to_skip) {
2038 prdebug_full_state(indent_level, "proc ctrl");
2046 * Delete socket tags, and stat tags associated with a given
2047 * accouting tag and uid.
2049 static int ctrl_cmd_delete(const char *input)
2057 struct iface_stat *iface_entry;
2058 struct rb_node *node;
2059 struct sock_tag *st_entry;
2060 struct rb_root st_to_free_tree = RB_ROOT;
2061 struct tag_stat *ts_entry;
2062 struct tag_counter_set *tcs_entry;
2063 struct tag_ref *tr_entry;
2064 struct uid_tag_data *utd_entry;
2066 argc = sscanf(input, "%c %llu %u", &cmd, &acct_tag, &uid);
2067 CT_DEBUG("qtaguid: ctrl_delete(%s): argc=%d cmd=%c "
2068 "user_tag=0x%llx uid=%u\n", input, argc, cmd,
2074 if (!valid_atag(acct_tag)) {
2075 pr_info("qtaguid: ctrl_delete(%s): invalid tag\n", input);
2080 uid = current_fsuid();
2081 } else if (!can_impersonate_uid(uid)) {
2082 pr_info("qtaguid: ctrl_delete(%s): "
2083 "insufficient priv from pid=%u tgid=%u uid=%u\n",
2084 input, current->pid, current->tgid, current_fsuid());
2089 tag = combine_atag_with_uid(acct_tag, uid);
2090 CT_DEBUG("qtaguid: ctrl_delete(%s): "
2091 "looking for tag=0x%llx (uid=%u)\n",
2094 /* Delete socket tags */
2095 spin_lock_bh(&sock_tag_list_lock);
2096 node = rb_first(&sock_tag_tree);
2098 st_entry = rb_entry(node, struct sock_tag, sock_node);
2099 entry_uid = get_uid_from_tag(st_entry->tag);
2100 node = rb_next(node);
2101 if (entry_uid != uid)
2104 CT_DEBUG("qtaguid: ctrl_delete(%s): st tag=0x%llx (uid=%u)\n",
2105 input, st_entry->tag, entry_uid);
2107 if (!acct_tag || st_entry->tag == tag) {
2108 rb_erase(&st_entry->sock_node, &sock_tag_tree);
2109 /* Can't sockfd_put() within spinlock, do it later. */
2110 sock_tag_tree_insert(st_entry, &st_to_free_tree);
2111 tr_entry = lookup_tag_ref(st_entry->tag, NULL);
2112 BUG_ON(tr_entry->num_sock_tags <= 0);
2113 tr_entry->num_sock_tags--;
2115 * TODO: remove if, and start failing.
2116 * This is a hack to work around the fact that in some
2117 * places we have "if (IS_ERR_OR_NULL(pqd_entry))"
2118 * and are trying to work around apps
2119 * that didn't open the /dev/xt_qtaguid.
2121 if (st_entry->list.next && st_entry->list.prev)
2122 list_del(&st_entry->list);
2125 spin_unlock_bh(&sock_tag_list_lock);
2127 sock_tag_tree_erase(&st_to_free_tree);
2129 /* Delete tag counter-sets */
2130 spin_lock_bh(&tag_counter_set_list_lock);
2131 /* Counter sets are only on the uid tag, not full tag */
2132 tcs_entry = tag_counter_set_tree_search(&tag_counter_set_tree, tag);
2134 CT_DEBUG("qtaguid: ctrl_delete(%s): "
2135 "erase tcs: tag=0x%llx (uid=%u) set=%d\n",
2138 get_uid_from_tag(tcs_entry->tn.tag),
2139 tcs_entry->active_set);
2140 rb_erase(&tcs_entry->tn.node, &tag_counter_set_tree);
2143 spin_unlock_bh(&tag_counter_set_list_lock);
2146 * If acct_tag is 0, then all entries belonging to uid are
2149 spin_lock_bh(&iface_stat_list_lock);
2150 list_for_each_entry(iface_entry, &iface_stat_list, list) {
2151 spin_lock_bh(&iface_entry->tag_stat_list_lock);
2152 node = rb_first(&iface_entry->tag_stat_tree);
2154 ts_entry = rb_entry(node, struct tag_stat, tn.node);
2155 entry_uid = get_uid_from_tag(ts_entry->tn.tag);
2156 node = rb_next(node);
2158 CT_DEBUG("qtaguid: ctrl_delete(%s): "
2159 "ts tag=0x%llx (uid=%u)\n",
2160 input, ts_entry->tn.tag, entry_uid);
2162 if (entry_uid != uid)
2164 if (!acct_tag || ts_entry->tn.tag == tag) {
2165 CT_DEBUG("qtaguid: ctrl_delete(%s): "
2166 "erase ts: %s 0x%llx %u\n",
2167 input, iface_entry->ifname,
2168 get_atag_from_tag(ts_entry->tn.tag),
2170 rb_erase(&ts_entry->tn.node,
2171 &iface_entry->tag_stat_tree);
2175 spin_unlock_bh(&iface_entry->tag_stat_list_lock);
2177 spin_unlock_bh(&iface_stat_list_lock);
2179 /* Cleanup the uid_tag_data */
2180 spin_lock_bh(&uid_tag_data_tree_lock);
2181 node = rb_first(&uid_tag_data_tree);
2183 utd_entry = rb_entry(node, struct uid_tag_data, node);
2184 entry_uid = utd_entry->uid;
2185 node = rb_next(node);
2187 CT_DEBUG("qtaguid: ctrl_delete(%s): "
2191 if (entry_uid != uid)
2194 * Go over the tag_refs, and those that don't have
2195 * sock_tags using them are freed.
2197 put_tag_ref_tree(tag, utd_entry);
2198 put_utd_entry(utd_entry);
2200 spin_unlock_bh(&uid_tag_data_tree_lock);
2202 atomic64_inc(&qtu_events.delete_cmds);
2209 static int ctrl_cmd_counter_set(const char *input)
2215 struct tag_counter_set *tcs;
2218 argc = sscanf(input, "%c %d %u", &cmd, &counter_set, &uid);
2219 CT_DEBUG("qtaguid: ctrl_counterset(%s): argc=%d cmd=%c "
2220 "set=%d uid=%u\n", input, argc, cmd,
2226 if (counter_set < 0 || counter_set >= IFS_MAX_COUNTER_SETS) {
2227 pr_info("qtaguid: ctrl_counterset(%s): invalid counter_set range\n",
2232 if (!can_manipulate_uids()) {
2233 pr_info("qtaguid: ctrl_counterset(%s): "
2234 "insufficient priv from pid=%u tgid=%u uid=%u\n",
2235 input, current->pid, current->tgid, current_fsuid());
2240 tag = make_tag_from_uid(uid);
2241 spin_lock_bh(&tag_counter_set_list_lock);
2242 tcs = tag_counter_set_tree_search(&tag_counter_set_tree, tag);
2244 tcs = kzalloc(sizeof(*tcs), GFP_ATOMIC);
2246 spin_unlock_bh(&tag_counter_set_list_lock);
2247 pr_err("qtaguid: ctrl_counterset(%s): "
2248 "failed to alloc counter set\n",
2254 tag_counter_set_tree_insert(tcs, &tag_counter_set_tree);
2255 CT_DEBUG("qtaguid: ctrl_counterset(%s): added tcs tag=0x%llx "
2256 "(uid=%u) set=%d\n",
2257 input, tag, get_uid_from_tag(tag), counter_set);
2259 tcs->active_set = counter_set;
2260 spin_unlock_bh(&tag_counter_set_list_lock);
2261 atomic64_inc(&qtu_events.counter_set_changes);
2268 static int ctrl_cmd_tag(const char *input)
2273 tag_t acct_tag = make_atag_from_value(0);
2275 struct socket *el_socket;
2277 struct sock_tag *sock_tag_entry;
2278 struct tag_ref *tag_ref_entry;
2279 struct uid_tag_data *uid_tag_data_entry;
2280 struct proc_qtu_data *pqd_entry;
2282 /* Unassigned args will get defaulted later. */
2283 argc = sscanf(input, "%c %d %llu %u", &cmd, &sock_fd, &acct_tag, &uid);
2284 CT_DEBUG("qtaguid: ctrl_tag(%s): argc=%d cmd=%c sock_fd=%d "
2285 "acct_tag=0x%llx uid=%u\n", input, argc, cmd, sock_fd,
2291 el_socket = sockfd_lookup(sock_fd, &res); /* This locks the file */
2293 pr_info("qtaguid: ctrl_tag(%s): failed to lookup"
2294 " sock_fd=%d err=%d pid=%u tgid=%u uid=%u\n",
2295 input, sock_fd, res, current->pid, current->tgid,
2299 CT_DEBUG("qtaguid: ctrl_tag(%s): socket->...->f_count=%ld ->sk=%p\n",
2300 input, atomic_long_read(&el_socket->file->f_count),
2303 acct_tag = make_atag_from_value(0);
2304 } else if (!valid_atag(acct_tag)) {
2305 pr_info("qtaguid: ctrl_tag(%s): invalid tag\n", input);
2309 CT_DEBUG("qtaguid: ctrl_tag(%s): "
2310 "pid=%u tgid=%u uid=%u euid=%u fsuid=%u "
2311 "ctrl.gid=%u in_group()=%d in_egroup()=%d\n",
2312 input, current->pid, current->tgid, current_uid(),
2313 current_euid(), current_fsuid(),
2314 xt_qtaguid_ctrl_file->gid,
2315 in_group_p(xt_qtaguid_ctrl_file->gid),
2316 in_egroup_p(xt_qtaguid_ctrl_file->gid));
2318 uid = current_fsuid();
2319 } else if (!can_impersonate_uid(uid)) {
2320 pr_info("qtaguid: ctrl_tag(%s): "
2321 "insufficient priv from pid=%u tgid=%u uid=%u\n",
2322 input, current->pid, current->tgid, current_fsuid());
2326 full_tag = combine_atag_with_uid(acct_tag, uid);
2328 spin_lock_bh(&sock_tag_list_lock);
2329 sock_tag_entry = get_sock_stat_nl(el_socket->sk);
2330 tag_ref_entry = get_tag_ref(full_tag, &uid_tag_data_entry);
2331 if (IS_ERR(tag_ref_entry)) {
2332 res = PTR_ERR(tag_ref_entry);
2333 spin_unlock_bh(&sock_tag_list_lock);
2336 tag_ref_entry->num_sock_tags++;
2337 if (sock_tag_entry) {
2338 struct tag_ref *prev_tag_ref_entry;
2340 CT_DEBUG("qtaguid: ctrl_tag(%s): retag for sk=%p "
2341 "st@%p ...->f_count=%ld\n",
2342 input, el_socket->sk, sock_tag_entry,
2343 atomic_long_read(&el_socket->file->f_count));
2345 * This is a re-tagging, so release the sock_fd that was
2346 * locked at the time of the 1st tagging.
2347 * There is still the ref from this call's sockfd_lookup() so
2348 * it can be done within the spinlock.
2350 sockfd_put(sock_tag_entry->socket);
2351 prev_tag_ref_entry = lookup_tag_ref(sock_tag_entry->tag,
2352 &uid_tag_data_entry);
2353 BUG_ON(IS_ERR_OR_NULL(prev_tag_ref_entry));
2354 BUG_ON(prev_tag_ref_entry->num_sock_tags <= 0);
2355 prev_tag_ref_entry->num_sock_tags--;
2356 sock_tag_entry->tag = full_tag;
2358 CT_DEBUG("qtaguid: ctrl_tag(%s): newtag for sk=%p\n",
2359 input, el_socket->sk);
2360 sock_tag_entry = kzalloc(sizeof(*sock_tag_entry),
2362 if (!sock_tag_entry) {
2363 pr_err("qtaguid: ctrl_tag(%s): "
2364 "socket tag alloc failed\n",
2366 spin_unlock_bh(&sock_tag_list_lock);
2368 goto err_tag_unref_put;
2370 sock_tag_entry->sk = el_socket->sk;
2371 sock_tag_entry->socket = el_socket;
2372 sock_tag_entry->pid = current->tgid;
2373 sock_tag_entry->tag = combine_atag_with_uid(acct_tag,
2375 spin_lock_bh(&uid_tag_data_tree_lock);
2376 pqd_entry = proc_qtu_data_tree_search(
2377 &proc_qtu_data_tree, current->tgid);
2379 * TODO: remove if, and start failing.
2380 * At first, we want to catch user-space code that is not
2381 * opening the /dev/xt_qtaguid.
2383 if (IS_ERR_OR_NULL(pqd_entry))
2386 "User space forgot to open /dev/xt_qtaguid? "
2387 "pid=%u tgid=%u uid=%u\n", __func__,
2388 current->pid, current->tgid,
2391 list_add(&sock_tag_entry->list,
2392 &pqd_entry->sock_tag_list);
2393 spin_unlock_bh(&uid_tag_data_tree_lock);
2395 sock_tag_tree_insert(sock_tag_entry, &sock_tag_tree);
2396 atomic64_inc(&qtu_events.sockets_tagged);
2398 spin_unlock_bh(&sock_tag_list_lock);
2399 /* We keep the ref to the socket (file) until it is untagged */
2400 CT_DEBUG("qtaguid: ctrl_tag(%s): done st@%p ...->f_count=%ld\n",
2401 input, sock_tag_entry,
2402 atomic_long_read(&el_socket->file->f_count));
2406 BUG_ON(tag_ref_entry->num_sock_tags <= 0);
2407 tag_ref_entry->num_sock_tags--;
2408 free_tag_ref_from_utd_entry(tag_ref_entry, uid_tag_data_entry);
2410 CT_DEBUG("qtaguid: ctrl_tag(%s): done. ...->f_count=%ld\n",
2411 input, atomic_long_read(&el_socket->file->f_count) - 1);
2412 /* Release the sock_fd that was grabbed by sockfd_lookup(). */
2413 sockfd_put(el_socket);
2417 CT_DEBUG("qtaguid: ctrl_tag(%s): done.\n", input);
2421 static int ctrl_cmd_untag(const char *input)
2425 struct socket *el_socket;
2427 struct sock_tag *sock_tag_entry;
2428 struct tag_ref *tag_ref_entry;
2429 struct uid_tag_data *utd_entry;
2430 struct proc_qtu_data *pqd_entry;
2432 argc = sscanf(input, "%c %d", &cmd, &sock_fd);
2433 CT_DEBUG("qtaguid: ctrl_untag(%s): argc=%d cmd=%c sock_fd=%d\n",
2434 input, argc, cmd, sock_fd);
2439 el_socket = sockfd_lookup(sock_fd, &res); /* This locks the file */
2441 pr_info("qtaguid: ctrl_untag(%s): failed to lookup"
2442 " sock_fd=%d err=%d pid=%u tgid=%u uid=%u\n",
2443 input, sock_fd, res, current->pid, current->tgid,
2447 CT_DEBUG("qtaguid: ctrl_untag(%s): socket->...->f_count=%ld ->sk=%p\n",
2448 input, atomic_long_read(&el_socket->file->f_count),
2450 spin_lock_bh(&sock_tag_list_lock);
2451 sock_tag_entry = get_sock_stat_nl(el_socket->sk);
2452 if (!sock_tag_entry) {
2453 spin_unlock_bh(&sock_tag_list_lock);
2458 * The socket already belongs to the current process
2459 * so it can do whatever it wants to it.
2461 rb_erase(&sock_tag_entry->sock_node, &sock_tag_tree);
2463 tag_ref_entry = lookup_tag_ref(sock_tag_entry->tag, &utd_entry);
2464 BUG_ON(!tag_ref_entry);
2465 BUG_ON(tag_ref_entry->num_sock_tags <= 0);
2466 spin_lock_bh(&uid_tag_data_tree_lock);
2467 pqd_entry = proc_qtu_data_tree_search(
2468 &proc_qtu_data_tree, current->tgid);
2470 * TODO: remove if, and start failing.
2471 * At first, we want to catch user-space code that is not
2472 * opening the /dev/xt_qtaguid.
2474 if (IS_ERR_OR_NULL(pqd_entry))
2475 pr_warn_once("qtaguid: %s(): "
2476 "User space forgot to open /dev/xt_qtaguid? "
2477 "pid=%u tgid=%u uid=%u\n", __func__,
2478 current->pid, current->tgid, current_fsuid());
2480 list_del(&sock_tag_entry->list);
2481 spin_unlock_bh(&uid_tag_data_tree_lock);
2483 * We don't free tag_ref from the utd_entry here,
2484 * only during a cmd_delete().
2486 tag_ref_entry->num_sock_tags--;
2487 spin_unlock_bh(&sock_tag_list_lock);
2489 * Release the sock_fd that was grabbed at tag time,
2490 * and once more for the sockfd_lookup() here.
2492 sockfd_put(sock_tag_entry->socket);
2493 CT_DEBUG("qtaguid: ctrl_untag(%s): done. st@%p ...->f_count=%ld\n",
2494 input, sock_tag_entry,
2495 atomic_long_read(&el_socket->file->f_count) - 1);
2496 sockfd_put(el_socket);
2498 kfree(sock_tag_entry);
2499 atomic64_inc(&qtu_events.sockets_untagged);
2504 CT_DEBUG("qtaguid: ctrl_untag(%s): done. socket->...->f_count=%ld\n",
2505 input, atomic_long_read(&el_socket->file->f_count) - 1);
2506 /* Release the sock_fd that was grabbed by sockfd_lookup(). */
2507 sockfd_put(el_socket);
2511 CT_DEBUG("qtaguid: ctrl_untag(%s): done.\n", input);
2515 static int qtaguid_ctrl_parse(const char *input, int count)
2520 CT_DEBUG("qtaguid: ctrl(%s): pid=%u tgid=%u uid=%u\n",
2521 input, current->pid, current->tgid, current_fsuid());
2524 /* Collect params for commands */
2527 res = ctrl_cmd_delete(input);
2531 res = ctrl_cmd_counter_set(input);
2535 res = ctrl_cmd_tag(input);
2539 res = ctrl_cmd_untag(input);
2549 CT_DEBUG("qtaguid: ctrl(%s): res=%d\n", input, res);
2553 #define MAX_QTAGUID_CTRL_INPUT_LEN 255
2554 static int qtaguid_ctrl_proc_write(struct file *file, const char __user *buffer,
2555 unsigned long count, void *data)
2557 char input_buf[MAX_QTAGUID_CTRL_INPUT_LEN];
2559 if (unlikely(module_passive))
2562 if (count >= MAX_QTAGUID_CTRL_INPUT_LEN)
2565 if (copy_from_user(input_buf, buffer, count))
2568 input_buf[count] = '\0';
2569 return qtaguid_ctrl_parse(input_buf, count);
2572 struct proc_print_info {
2574 char **num_items_returned;
2575 struct iface_stat *iface_entry;
2576 struct tag_stat *ts_entry;
2582 static int pp_stats_line(struct proc_print_info *ppi, int cnt_set)
2585 struct data_counters *cnts;
2587 if (!ppi->item_index) {
2588 if (ppi->item_index++ < ppi->items_to_skip)
2590 len = snprintf(ppi->outp, ppi->char_count,
2591 "idx iface acct_tag_hex uid_tag_int cnt_set "
2592 "rx_bytes rx_packets "
2593 "tx_bytes tx_packets "
2594 "rx_tcp_bytes rx_tcp_packets "
2595 "rx_udp_bytes rx_udp_packets "
2596 "rx_other_bytes rx_other_packets "
2597 "tx_tcp_bytes tx_tcp_packets "
2598 "tx_udp_bytes tx_udp_packets "
2599 "tx_other_bytes tx_other_packets\n");
2601 tag_t tag = ppi->ts_entry->tn.tag;
2602 uid_t stat_uid = get_uid_from_tag(tag);
2603 /* Detailed tags are not available to everybody */
2604 if (get_atag_from_tag(tag)
2605 && !can_read_other_uid_stats(stat_uid)) {
2606 CT_DEBUG("qtaguid: stats line: "
2607 "%s 0x%llx %u: insufficient priv "
2608 "from pid=%u tgid=%u uid=%u stats.gid=%u\n",
2609 ppi->iface_entry->ifname,
2610 get_atag_from_tag(tag), stat_uid,
2611 current->pid, current->tgid, current_fsuid(),
2612 xt_qtaguid_stats_file->gid);
2615 if (ppi->item_index++ < ppi->items_to_skip)
2617 cnts = &ppi->ts_entry->counters;
2619 ppi->outp, ppi->char_count,
2620 "%d %s 0x%llx %u %u "
2630 ppi->iface_entry->ifname,
2631 get_atag_from_tag(tag),
2634 dc_sum_bytes(cnts, cnt_set, IFS_RX),
2635 dc_sum_packets(cnts, cnt_set, IFS_RX),
2636 dc_sum_bytes(cnts, cnt_set, IFS_TX),
2637 dc_sum_packets(cnts, cnt_set, IFS_TX),
2638 cnts->bpc[cnt_set][IFS_RX][IFS_TCP].bytes,
2639 cnts->bpc[cnt_set][IFS_RX][IFS_TCP].packets,
2640 cnts->bpc[cnt_set][IFS_RX][IFS_UDP].bytes,
2641 cnts->bpc[cnt_set][IFS_RX][IFS_UDP].packets,
2642 cnts->bpc[cnt_set][IFS_RX][IFS_PROTO_OTHER].bytes,
2643 cnts->bpc[cnt_set][IFS_RX][IFS_PROTO_OTHER].packets,
2644 cnts->bpc[cnt_set][IFS_TX][IFS_TCP].bytes,
2645 cnts->bpc[cnt_set][IFS_TX][IFS_TCP].packets,
2646 cnts->bpc[cnt_set][IFS_TX][IFS_UDP].bytes,
2647 cnts->bpc[cnt_set][IFS_TX][IFS_UDP].packets,
2648 cnts->bpc[cnt_set][IFS_TX][IFS_PROTO_OTHER].bytes,
2649 cnts->bpc[cnt_set][IFS_TX][IFS_PROTO_OTHER].packets);
2654 static bool pp_sets(struct proc_print_info *ppi)
2658 for (counter_set = 0; counter_set < IFS_MAX_COUNTER_SETS;
2660 len = pp_stats_line(ppi, counter_set);
2661 if (len >= ppi->char_count) {
2667 ppi->char_count -= len;
2668 (*ppi->num_items_returned)++;
2675 * Procfs reader to get all tag stats using style "1)" as described in
2677 * Groups all protocols tx/rx bytes.
2679 static int qtaguid_stats_proc_read(char *page, char **num_items_returned,
2680 off_t items_to_skip, int char_count, int *eof,
2683 struct proc_print_info ppi;
2688 ppi.char_count = char_count;
2689 ppi.num_items_returned = num_items_returned;
2690 ppi.items_to_skip = items_to_skip;
2692 if (unlikely(module_passive)) {
2693 len = pp_stats_line(&ppi, 0);
2694 /* The header should always be shorter than the buffer. */
2695 BUG_ON(len >= ppi.char_count);
2696 (*num_items_returned)++;
2701 CT_DEBUG("qtaguid:proc stats pid=%u tgid=%u uid=%u "
2702 "page=%p *num_items_returned=%p off=%ld "
2703 "char_count=%d *eof=%d\n",
2704 current->pid, current->tgid, current_fsuid(),
2705 page, *num_items_returned,
2706 items_to_skip, char_count, *eof);
2711 /* The idx is there to help debug when things go belly up. */
2712 len = pp_stats_line(&ppi, 0);
2713 /* Don't advance the outp unless the whole line was printed */
2714 if (len >= ppi.char_count) {
2716 return ppi.outp - page;
2720 ppi.char_count -= len;
2721 (*num_items_returned)++;
2724 spin_lock_bh(&iface_stat_list_lock);
2725 list_for_each_entry(ppi.iface_entry, &iface_stat_list, list) {
2726 struct rb_node *node;
2727 spin_lock_bh(&ppi.iface_entry->tag_stat_list_lock);
2728 for (node = rb_first(&ppi.iface_entry->tag_stat_tree);
2730 node = rb_next(node)) {
2731 ppi.ts_entry = rb_entry(node, struct tag_stat, tn.node);
2732 if (!pp_sets(&ppi)) {
2734 &ppi.iface_entry->tag_stat_list_lock);
2735 spin_unlock_bh(&iface_stat_list_lock);
2736 return ppi.outp - page;
2739 spin_unlock_bh(&ppi.iface_entry->tag_stat_list_lock);
2741 spin_unlock_bh(&iface_stat_list_lock);
2744 return ppi.outp - page;
2747 /*------------------------------------------*/
2748 static int qtudev_open(struct inode *inode, struct file *file)
2750 struct uid_tag_data *utd_entry;
2751 struct proc_qtu_data *pqd_entry;
2752 struct proc_qtu_data *new_pqd_entry;
2754 bool utd_entry_found;
2756 if (unlikely(qtu_proc_handling_passive))
2759 DR_DEBUG("qtaguid: qtudev_open(): pid=%u tgid=%u uid=%u\n",
2760 current->pid, current->tgid, current_fsuid());
2762 spin_lock_bh(&uid_tag_data_tree_lock);
2764 /* Look for existing uid data, or alloc one. */
2765 utd_entry = get_uid_data(current_fsuid(), &utd_entry_found);
2766 if (IS_ERR_OR_NULL(utd_entry)) {
2767 res = PTR_ERR(utd_entry);
2771 /* Look for existing PID based proc_data */
2772 pqd_entry = proc_qtu_data_tree_search(&proc_qtu_data_tree,
2775 pr_err("qtaguid: qtudev_open(): %u/%u %u "
2776 "%s already opened\n",
2777 current->pid, current->tgid, current_fsuid(),
2780 goto err_unlock_free_utd;
2783 new_pqd_entry = kzalloc(sizeof(*new_pqd_entry), GFP_ATOMIC);
2784 if (!new_pqd_entry) {
2785 pr_err("qtaguid: qtudev_open(): %u/%u %u: "
2786 "proc data alloc failed\n",
2787 current->pid, current->tgid, current_fsuid());
2789 goto err_unlock_free_utd;
2791 new_pqd_entry->pid = current->tgid;
2792 INIT_LIST_HEAD(&new_pqd_entry->sock_tag_list);
2793 new_pqd_entry->parent_tag_data = utd_entry;
2794 utd_entry->num_pqd++;
2796 proc_qtu_data_tree_insert(new_pqd_entry,
2797 &proc_qtu_data_tree);
2799 spin_unlock_bh(&uid_tag_data_tree_lock);
2800 DR_DEBUG("qtaguid: tracking data for uid=%u in pqd=%p\n",
2801 current_fsuid(), new_pqd_entry);
2802 file->private_data = new_pqd_entry;
2805 err_unlock_free_utd:
2806 if (!utd_entry_found) {
2807 rb_erase(&utd_entry->node, &uid_tag_data_tree);
2811 spin_unlock_bh(&uid_tag_data_tree_lock);
2815 static int qtudev_release(struct inode *inode, struct file *file)
2817 struct proc_qtu_data *pqd_entry = file->private_data;
2818 struct uid_tag_data *utd_entry = pqd_entry->parent_tag_data;
2819 struct sock_tag *st_entry;
2820 struct rb_root st_to_free_tree = RB_ROOT;
2821 struct list_head *entry, *next;
2824 if (unlikely(qtu_proc_handling_passive))
2828 * Do not trust the current->pid, it might just be a kworker cleaning
2829 * up after a dead proc.
2831 DR_DEBUG("qtaguid: qtudev_release(): "
2832 "pid=%u tgid=%u uid=%u "
2833 "pqd_entry=%p->pid=%u utd_entry=%p->active_tags=%d\n",
2834 current->pid, current->tgid, pqd_entry->parent_tag_data->uid,
2835 pqd_entry, pqd_entry->pid, utd_entry,
2836 utd_entry->num_active_tags);
2838 spin_lock_bh(&sock_tag_list_lock);
2839 spin_lock_bh(&uid_tag_data_tree_lock);
2841 list_for_each_safe(entry, next, &pqd_entry->sock_tag_list) {
2842 st_entry = list_entry(entry, struct sock_tag, list);
2843 DR_DEBUG("qtaguid: %s(): "
2844 "erase sock_tag=%p->sk=%p pid=%u tgid=%u uid=%u\n",
2846 st_entry, st_entry->sk,
2847 current->pid, current->tgid,
2848 pqd_entry->parent_tag_data->uid);
2850 utd_entry = uid_tag_data_tree_search(
2852 get_uid_from_tag(st_entry->tag));
2853 BUG_ON(IS_ERR_OR_NULL(utd_entry));
2854 DR_DEBUG("qtaguid: %s(): "
2855 "looking for tag=0x%llx in utd_entry=%p\n", __func__,
2856 st_entry->tag, utd_entry);
2857 tr = tag_ref_tree_search(&utd_entry->tag_ref_tree,
2860 BUG_ON(tr->num_sock_tags <= 0);
2861 tr->num_sock_tags--;
2862 free_tag_ref_from_utd_entry(tr, utd_entry);
2864 rb_erase(&st_entry->sock_node, &sock_tag_tree);
2865 list_del(&st_entry->list);
2866 /* Can't sockfd_put() within spinlock, do it later. */
2867 sock_tag_tree_insert(st_entry, &st_to_free_tree);
2870 * Try to free the utd_entry if no other proc_qtu_data is
2871 * using it (num_pqd is 0) and it doesn't have active tags
2872 * (num_active_tags is 0).
2874 put_utd_entry(utd_entry);
2877 rb_erase(&pqd_entry->node, &proc_qtu_data_tree);
2878 BUG_ON(pqd_entry->parent_tag_data->num_pqd < 1);
2879 pqd_entry->parent_tag_data->num_pqd--;
2880 put_utd_entry(pqd_entry->parent_tag_data);
2882 file->private_data = NULL;
2884 spin_unlock_bh(&uid_tag_data_tree_lock);
2885 spin_unlock_bh(&sock_tag_list_lock);
2888 sock_tag_tree_erase(&st_to_free_tree);
2890 prdebug_full_state(0, "%s(): pid=%u tgid=%u", __func__,
2891 current->pid, current->tgid);
2895 /*------------------------------------------*/
2896 static const struct file_operations qtudev_fops = {
2897 .owner = THIS_MODULE,
2898 .open = qtudev_open,
2899 .release = qtudev_release,
2902 static struct miscdevice qtu_device = {
2903 .minor = MISC_DYNAMIC_MINOR,
2904 .name = QTU_DEV_NAME,
2905 .fops = &qtudev_fops,
2906 /* How sad it doesn't allow for defaults: .mode = S_IRUGO | S_IWUSR */
2909 /*------------------------------------------*/
2910 static int __init qtaguid_proc_register(struct proc_dir_entry **res_procdir)
2913 *res_procdir = proc_mkdir(module_procdirname, init_net.proc_net);
2914 if (!*res_procdir) {
2915 pr_err("qtaguid: failed to create proc/.../xt_qtaguid\n");
2920 xt_qtaguid_ctrl_file = create_proc_entry("ctrl", proc_ctrl_perms,
2922 if (!xt_qtaguid_ctrl_file) {
2923 pr_err("qtaguid: failed to create xt_qtaguid/ctrl "
2928 xt_qtaguid_ctrl_file->read_proc = qtaguid_ctrl_proc_read;
2929 xt_qtaguid_ctrl_file->write_proc = qtaguid_ctrl_proc_write;
2931 xt_qtaguid_stats_file = create_proc_entry("stats", proc_stats_perms,
2933 if (!xt_qtaguid_stats_file) {
2934 pr_err("qtaguid: failed to create xt_qtaguid/stats "
2937 goto no_stats_entry;
2939 xt_qtaguid_stats_file->read_proc = qtaguid_stats_proc_read;
2941 * TODO: add support counter hacking
2942 * xt_qtaguid_stats_file->write_proc = qtaguid_stats_proc_write;
2947 remove_proc_entry("ctrl", *res_procdir);
2949 remove_proc_entry("xt_qtaguid", NULL);
2954 static struct xt_match qtaguid_mt_reg __read_mostly = {
2956 * This module masquerades as the "owner" module so that iptables
2957 * tools can deal with it.
2961 .family = NFPROTO_UNSPEC,
2962 .match = qtaguid_mt,
2963 .matchsize = sizeof(struct xt_qtaguid_match_info),
2967 static int __init qtaguid_mt_init(void)
2969 if (qtaguid_proc_register(&xt_qtaguid_procdir)
2970 || iface_stat_init(xt_qtaguid_procdir)
2971 || xt_register_match(&qtaguid_mt_reg)
2972 || misc_register(&qtu_device))
2978 * TODO: allow unloading of the module.
2979 * For now stats are permanent.
2980 * Kconfig forces'y/n' and never an 'm'.
2983 module_init(qtaguid_mt_init);
2984 MODULE_AUTHOR("jpa <jpa@google.com>");
2985 MODULE_DESCRIPTION("Xtables: socket owner+tag matching and associated stats");
2986 MODULE_LICENSE("GPL");
2987 MODULE_ALIAS("ipt_owner");
2988 MODULE_ALIAS("ip6t_owner");
2989 MODULE_ALIAS("ipt_qtaguid");
2990 MODULE_ALIAS("ip6t_qtaguid");