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 inline uint64_t dc_sum_bytes(struct data_counters *counters,
273 enum ifs_tx_rx direction)
275 return counters->bpc[set][direction][IFS_TCP].bytes
276 + counters->bpc[set][direction][IFS_UDP].bytes
277 + counters->bpc[set][direction][IFS_PROTO_OTHER].bytes;
280 static inline uint64_t dc_sum_packets(struct data_counters *counters,
282 enum ifs_tx_rx direction)
284 return counters->bpc[set][direction][IFS_TCP].packets
285 + counters->bpc[set][direction][IFS_UDP].packets
286 + counters->bpc[set][direction][IFS_PROTO_OTHER].packets;
289 static struct tag_node *tag_node_tree_search(struct rb_root *root, tag_t tag)
291 struct rb_node *node = root->rb_node;
294 struct tag_node *data = rb_entry(node, struct tag_node, node);
296 RB_DEBUG("qtaguid: tag_node_tree_search(0x%llx): "
297 " node=%p data=%p\n", tag, node, data);
298 result = tag_compare(tag, data->tag);
299 RB_DEBUG("qtaguid: tag_node_tree_search(0x%llx): "
300 " data.tag=0x%llx (uid=%u) res=%d\n",
301 tag, data->tag, get_uid_from_tag(data->tag), result);
303 node = node->rb_left;
305 node = node->rb_right;
312 static void tag_node_tree_insert(struct tag_node *data, struct rb_root *root)
314 struct rb_node **new = &(root->rb_node), *parent = NULL;
316 /* Figure out where to put new node */
318 struct tag_node *this = rb_entry(*new, struct tag_node,
320 int result = tag_compare(data->tag, this->tag);
321 RB_DEBUG("qtaguid: %s(): tag=0x%llx"
322 " (uid=%u)\n", __func__,
324 get_uid_from_tag(this->tag));
327 new = &((*new)->rb_left);
329 new = &((*new)->rb_right);
334 /* Add new node and rebalance tree. */
335 rb_link_node(&data->node, parent, new);
336 rb_insert_color(&data->node, root);
339 static void tag_stat_tree_insert(struct tag_stat *data, struct rb_root *root)
341 tag_node_tree_insert(&data->tn, root);
344 static struct tag_stat *tag_stat_tree_search(struct rb_root *root, tag_t tag)
346 struct tag_node *node = tag_node_tree_search(root, tag);
349 return rb_entry(&node->node, struct tag_stat, tn.node);
352 static void tag_counter_set_tree_insert(struct tag_counter_set *data,
353 struct rb_root *root)
355 tag_node_tree_insert(&data->tn, root);
358 static struct tag_counter_set *tag_counter_set_tree_search(struct rb_root *root,
361 struct tag_node *node = tag_node_tree_search(root, tag);
364 return rb_entry(&node->node, struct tag_counter_set, tn.node);
368 static void tag_ref_tree_insert(struct tag_ref *data, struct rb_root *root)
370 tag_node_tree_insert(&data->tn, root);
373 static struct tag_ref *tag_ref_tree_search(struct rb_root *root, tag_t tag)
375 struct tag_node *node = tag_node_tree_search(root, tag);
378 return rb_entry(&node->node, struct tag_ref, tn.node);
381 static struct sock_tag *sock_tag_tree_search(struct rb_root *root,
382 const struct sock *sk)
384 struct rb_node *node = root->rb_node;
387 struct sock_tag *data = rb_entry(node, struct sock_tag,
390 node = node->rb_left;
391 else if (sk > data->sk)
392 node = node->rb_right;
399 static void sock_tag_tree_insert(struct sock_tag *data, struct rb_root *root)
401 struct rb_node **new = &(root->rb_node), *parent = NULL;
403 /* Figure out where to put new node */
405 struct sock_tag *this = rb_entry(*new, struct sock_tag,
408 if (data->sk < this->sk)
409 new = &((*new)->rb_left);
410 else if (data->sk > this->sk)
411 new = &((*new)->rb_right);
416 /* Add new node and rebalance tree. */
417 rb_link_node(&data->sock_node, parent, new);
418 rb_insert_color(&data->sock_node, root);
421 static void sock_tag_tree_erase(struct rb_root *st_to_free_tree)
423 struct rb_node *node;
424 struct sock_tag *st_entry;
426 node = rb_first(st_to_free_tree);
428 st_entry = rb_entry(node, struct sock_tag, sock_node);
429 node = rb_next(node);
430 CT_DEBUG("qtaguid: %s(): "
431 "erase st: sk=%p tag=0x%llx (uid=%u)\n", __func__,
434 get_uid_from_tag(st_entry->tag));
435 rb_erase(&st_entry->sock_node, st_to_free_tree);
436 sockfd_put(st_entry->socket);
441 static struct proc_qtu_data *proc_qtu_data_tree_search(struct rb_root *root,
444 struct rb_node *node = root->rb_node;
447 struct proc_qtu_data *data = rb_entry(node,
448 struct proc_qtu_data,
451 node = node->rb_left;
452 else if (pid > data->pid)
453 node = node->rb_right;
460 static void proc_qtu_data_tree_insert(struct proc_qtu_data *data,
461 struct rb_root *root)
463 struct rb_node **new = &(root->rb_node), *parent = NULL;
465 /* Figure out where to put new node */
467 struct proc_qtu_data *this = rb_entry(*new,
468 struct proc_qtu_data,
471 if (data->pid < this->pid)
472 new = &((*new)->rb_left);
473 else if (data->pid > this->pid)
474 new = &((*new)->rb_right);
479 /* Add new node and rebalance tree. */
480 rb_link_node(&data->node, parent, new);
481 rb_insert_color(&data->node, root);
484 static void uid_tag_data_tree_insert(struct uid_tag_data *data,
485 struct rb_root *root)
487 struct rb_node **new = &(root->rb_node), *parent = NULL;
489 /* Figure out where to put new node */
491 struct uid_tag_data *this = rb_entry(*new,
495 if (data->uid < this->uid)
496 new = &((*new)->rb_left);
497 else if (data->uid > this->uid)
498 new = &((*new)->rb_right);
503 /* Add new node and rebalance tree. */
504 rb_link_node(&data->node, parent, new);
505 rb_insert_color(&data->node, root);
508 static struct uid_tag_data *uid_tag_data_tree_search(struct rb_root *root,
511 struct rb_node *node = root->rb_node;
514 struct uid_tag_data *data = rb_entry(node,
518 node = node->rb_left;
519 else if (uid > data->uid)
520 node = node->rb_right;
528 * Allocates a new uid_tag_data struct if needed.
529 * Returns a pointer to the found or allocated uid_tag_data.
530 * Returns a PTR_ERR on failures, and lock is not held.
531 * If found is not NULL:
532 * sets *found to true if not allocated.
533 * sets *found to false if allocated.
535 struct uid_tag_data *get_uid_data(uid_t uid, bool *found_res)
537 struct uid_tag_data *utd_entry;
539 /* Look for top level uid_tag_data for the UID */
540 utd_entry = uid_tag_data_tree_search(&uid_tag_data_tree, uid);
541 DR_DEBUG("qtaguid: get_uid_data(%u) utd=%p\n", uid, utd_entry);
544 *found_res = utd_entry;
548 utd_entry = kzalloc(sizeof(*utd_entry), GFP_ATOMIC);
550 pr_err("qtaguid: get_uid_data(%u): "
551 "tag data alloc failed\n", uid);
552 return ERR_PTR(-ENOMEM);
555 utd_entry->uid = uid;
556 utd_entry->tag_ref_tree = RB_ROOT;
557 uid_tag_data_tree_insert(utd_entry, &uid_tag_data_tree);
558 DR_DEBUG("qtaguid: get_uid_data(%u) new utd=%p\n", uid, utd_entry);
562 /* Never returns NULL. Either PTR_ERR or a valid ptr. */
563 static struct tag_ref *new_tag_ref(tag_t new_tag,
564 struct uid_tag_data *utd_entry)
566 struct tag_ref *tr_entry;
569 if (utd_entry->num_active_tags + 1 > max_sock_tags) {
570 pr_info("qtaguid: new_tag_ref(0x%llx): "
571 "tag ref alloc quota exceeded. max=%d\n",
572 new_tag, max_sock_tags);
578 tr_entry = kzalloc(sizeof(*tr_entry), GFP_ATOMIC);
580 pr_err("qtaguid: new_tag_ref(0x%llx): "
581 "tag ref alloc failed\n",
586 tr_entry->tn.tag = new_tag;
587 /* tr_entry->num_sock_tags handled by caller */
588 utd_entry->num_active_tags++;
589 tag_ref_tree_insert(tr_entry, &utd_entry->tag_ref_tree);
590 DR_DEBUG("qtaguid: new_tag_ref(0x%llx): "
591 " inserted new tag ref %p\n",
599 static struct tag_ref *lookup_tag_ref(tag_t full_tag,
600 struct uid_tag_data **utd_res)
602 struct uid_tag_data *utd_entry;
603 struct tag_ref *tr_entry;
605 uid_t uid = get_uid_from_tag(full_tag);
607 DR_DEBUG("qtaguid: lookup_tag_ref(tag=0x%llx (uid=%u))\n",
610 utd_entry = get_uid_data(uid, &found_utd);
611 if (IS_ERR_OR_NULL(utd_entry)) {
613 *utd_res = utd_entry;
617 tr_entry = tag_ref_tree_search(&utd_entry->tag_ref_tree, full_tag);
619 *utd_res = utd_entry;
620 DR_DEBUG("qtaguid: lookup_tag_ref(0x%llx) utd_entry=%p tr_entry=%p\n",
621 full_tag, utd_entry, tr_entry);
625 /* Never returns NULL. Either PTR_ERR or a valid ptr. */
626 static struct tag_ref *get_tag_ref(tag_t full_tag,
627 struct uid_tag_data **utd_res)
629 struct uid_tag_data *utd_entry;
630 struct tag_ref *tr_entry;
632 DR_DEBUG("qtaguid: get_tag_ref(0x%llx)\n",
634 spin_lock_bh(&uid_tag_data_tree_lock);
635 tr_entry = lookup_tag_ref(full_tag, &utd_entry);
636 BUG_ON(IS_ERR_OR_NULL(utd_entry));
638 tr_entry = new_tag_ref(full_tag, utd_entry);
640 spin_unlock_bh(&uid_tag_data_tree_lock);
642 *utd_res = utd_entry;
643 DR_DEBUG("qtaguid: get_tag_ref(0x%llx) utd=%p tr=%p\n",
644 full_tag, utd_entry, tr_entry);
648 /* Checks and maybe frees the UID Tag Data entry */
649 static void put_utd_entry(struct uid_tag_data *utd_entry)
651 /* Are we done with the UID tag data entry? */
652 if (RB_EMPTY_ROOT(&utd_entry->tag_ref_tree) &&
653 !utd_entry->num_pqd) {
654 DR_DEBUG("qtaguid: %s(): "
655 "erase utd_entry=%p uid=%u "
656 "by pid=%u tgid=%u uid=%u\n", __func__,
657 utd_entry, utd_entry->uid,
658 current->pid, current->tgid, current_fsuid());
659 BUG_ON(utd_entry->num_active_tags);
660 rb_erase(&utd_entry->node, &uid_tag_data_tree);
663 DR_DEBUG("qtaguid: %s(): "
664 "utd_entry=%p still has %d tags %d proc_qtu_data\n",
665 __func__, utd_entry, utd_entry->num_active_tags,
667 BUG_ON(!(utd_entry->num_active_tags ||
668 utd_entry->num_pqd));
673 * If no sock_tags are using this tag_ref,
674 * decrements refcount of utd_entry, removes tr_entry
675 * from utd_entry->tag_ref_tree and frees.
677 static void free_tag_ref_from_utd_entry(struct tag_ref *tr_entry,
678 struct uid_tag_data *utd_entry)
680 DR_DEBUG("qtaguid: %s(): %p tag=0x%llx (uid=%u)\n", __func__,
681 tr_entry, tr_entry->tn.tag,
682 get_uid_from_tag(tr_entry->tn.tag));
683 if (!tr_entry->num_sock_tags) {
684 BUG_ON(!utd_entry->num_active_tags);
685 utd_entry->num_active_tags--;
686 rb_erase(&tr_entry->tn.node, &utd_entry->tag_ref_tree);
687 DR_DEBUG("qtaguid: %s(): erased %p\n", __func__, tr_entry);
692 static void put_tag_ref_tree(tag_t full_tag, struct uid_tag_data *utd_entry)
694 struct rb_node *node;
695 struct tag_ref *tr_entry;
698 DR_DEBUG("qtaguid: %s(tag=0x%llx (uid=%u))\n", __func__,
699 full_tag, get_uid_from_tag(full_tag));
700 acct_tag = get_atag_from_tag(full_tag);
701 node = rb_first(&utd_entry->tag_ref_tree);
703 tr_entry = rb_entry(node, struct tag_ref, tn.node);
704 node = rb_next(node);
705 if (!acct_tag || tr_entry->tn.tag == full_tag)
706 free_tag_ref_from_utd_entry(tr_entry, utd_entry);
710 static int read_proc_u64(char *page, char **start, off_t off,
711 int count, int *eof, void *data)
716 uint64_t *iface_entry = data;
721 value = *iface_entry;
722 p += sprintf(p, "%llu\n", value);
723 len = (p - page) - off;
724 *eof = (len <= count) ? 1 : 0;
729 static int read_proc_bool(char *page, char **start, off_t off,
730 int count, int *eof, void *data)
735 bool *bool_entry = data;
741 p += sprintf(p, "%u\n", value);
742 len = (p - page) - off;
743 *eof = (len <= count) ? 1 : 0;
748 static int get_active_counter_set(tag_t tag)
751 struct tag_counter_set *tcs;
753 MT_DEBUG("qtaguid: get_active_counter_set(tag=0x%llx)"
755 tag, get_uid_from_tag(tag));
756 /* For now we only handle UID tags for active sets */
757 tag = get_utag_from_tag(tag);
758 spin_lock_bh(&tag_counter_set_list_lock);
759 tcs = tag_counter_set_tree_search(&tag_counter_set_tree, tag);
761 active_set = tcs->active_set;
762 spin_unlock_bh(&tag_counter_set_list_lock);
767 * Find the entry for tracking the specified interface.
768 * Caller must hold iface_stat_list_lock
770 static struct iface_stat *get_iface_entry(const char *ifname)
772 struct iface_stat *iface_entry;
774 /* Find the entry for tracking the specified tag within the interface */
775 if (ifname == NULL) {
776 pr_info("qtaguid: iface_stat: get() NULL device name\n");
780 /* Iterate over interfaces */
781 list_for_each_entry(iface_entry, &iface_stat_list, list) {
782 if (!strcmp(ifname, iface_entry->ifname))
790 static int iface_stat_fmt_proc_read(char *page, char **num_items_returned,
791 off_t items_to_skip, int char_count,
792 int *eof, void *data)
797 int fmt = (int)data; /* The data is just 1 (old) or 2 (uses fmt) */
798 struct iface_stat *iface_entry;
799 struct rtnl_link_stats64 dev_stats, *stats;
800 struct rtnl_link_stats64 no_dev_stats = {0};
802 if (unlikely(module_passive)) {
807 CT_DEBUG("qtaguid:proc iface_stat_fmt "
808 "pid=%u tgid=%u uid=%u "
809 "page=%p *num_items_returned=%p off=%ld "
810 "char_count=%d *eof=%d\n",
811 current->pid, current->tgid, current_fsuid(),
812 page, *num_items_returned,
813 items_to_skip, char_count, *eof);
818 if (fmt == 2 && item_index++ >= items_to_skip) {
819 len = snprintf(outp, char_count,
821 "total_skb_rx_bytes total_skb_rx_packets "
822 "total_skb_tx_bytes total_skb_tx_packets\n"
824 if (len >= char_count) {
830 (*num_items_returned)++;
834 * This lock will prevent iface_stat_update() from changing active,
835 * and in turn prevent an interface from unregistering itself.
837 spin_lock_bh(&iface_stat_list_lock);
838 list_for_each_entry(iface_entry, &iface_stat_list, list) {
839 if (item_index++ < items_to_skip)
842 if (iface_entry->active) {
843 stats = dev_get_stats(iface_entry->net_dev,
846 stats = &no_dev_stats;
849 * If the meaning of the data changes, then update the fmtX
856 "%llu %llu %llu %llu "
857 "%llu %llu %llu %llu\n",
860 iface_entry->totals_via_dev[IFS_RX].bytes,
861 iface_entry->totals_via_dev[IFS_RX].packets,
862 iface_entry->totals_via_dev[IFS_TX].bytes,
863 iface_entry->totals_via_dev[IFS_TX].packets,
864 stats->rx_bytes, stats->rx_packets,
865 stats->tx_bytes, stats->tx_packets
871 "%llu %llu %llu %llu\n",
873 iface_entry->totals_via_skb[IFS_RX].bytes,
874 iface_entry->totals_via_skb[IFS_RX].packets,
875 iface_entry->totals_via_skb[IFS_TX].bytes,
876 iface_entry->totals_via_skb[IFS_TX].packets
879 if (len >= char_count) {
880 spin_unlock_bh(&iface_stat_list_lock);
886 (*num_items_returned)++;
888 spin_unlock_bh(&iface_stat_list_lock);
894 static void iface_create_proc_worker(struct work_struct *work)
896 struct proc_dir_entry *proc_entry;
897 struct iface_stat_work *isw = container_of(work, struct iface_stat_work,
899 struct iface_stat *new_iface = isw->iface_entry;
901 /* iface_entries are not deleted, so safe to manipulate. */
902 proc_entry = proc_mkdir(new_iface->ifname, iface_stat_procdir);
903 if (IS_ERR_OR_NULL(proc_entry)) {
904 pr_err("qtaguid: iface_stat: create_proc(): alloc failed.\n");
909 new_iface->proc_ptr = proc_entry;
911 create_proc_read_entry("tx_bytes", proc_iface_perms, proc_entry,
913 &new_iface->totals_via_dev[IFS_TX].bytes);
914 create_proc_read_entry("rx_bytes", proc_iface_perms, proc_entry,
916 &new_iface->totals_via_dev[IFS_RX].bytes);
917 create_proc_read_entry("tx_packets", proc_iface_perms, proc_entry,
919 &new_iface->totals_via_dev[IFS_TX].packets);
920 create_proc_read_entry("rx_packets", proc_iface_perms, proc_entry,
922 &new_iface->totals_via_dev[IFS_RX].packets);
923 create_proc_read_entry("active", proc_iface_perms, proc_entry,
924 read_proc_bool, &new_iface->active);
926 IF_DEBUG("qtaguid: iface_stat: create_proc(): done "
927 "entry=%p dev=%s\n", new_iface, new_iface->ifname);
932 * Will set the entry's active state, and
933 * update the net_dev accordingly also.
935 static void _iface_stat_set_active(struct iface_stat *entry,
936 struct net_device *net_dev,
940 entry->net_dev = net_dev;
941 entry->active = true;
942 IF_DEBUG("qtaguid: %s(%s): "
943 "enable tracking. rfcnt=%d\n", __func__,
945 __this_cpu_read(*net_dev->pcpu_refcnt));
947 entry->active = false;
948 entry->net_dev = NULL;
949 IF_DEBUG("qtaguid: %s(%s): "
950 "disable tracking. rfcnt=%d\n", __func__,
952 __this_cpu_read(*net_dev->pcpu_refcnt));
957 /* Caller must hold iface_stat_list_lock */
958 static struct iface_stat *iface_alloc(struct net_device *net_dev)
960 struct iface_stat *new_iface;
961 struct iface_stat_work *isw;
963 new_iface = kzalloc(sizeof(*new_iface), GFP_ATOMIC);
964 if (new_iface == NULL) {
965 pr_err("qtaguid: iface_stat: create(%s): "
966 "iface_stat alloc failed\n", net_dev->name);
969 new_iface->ifname = kstrdup(net_dev->name, GFP_ATOMIC);
970 if (new_iface->ifname == NULL) {
971 pr_err("qtaguid: iface_stat: create(%s): "
972 "ifname alloc failed\n", net_dev->name);
976 spin_lock_init(&new_iface->tag_stat_list_lock);
977 new_iface->tag_stat_tree = RB_ROOT;
978 _iface_stat_set_active(new_iface, net_dev, true);
981 * ipv6 notifier chains are atomic :(
982 * No create_proc_read_entry() for you!
984 isw = kmalloc(sizeof(*isw), GFP_ATOMIC);
986 pr_err("qtaguid: iface_stat: create(%s): "
987 "work alloc failed\n", new_iface->ifname);
988 _iface_stat_set_active(new_iface, net_dev, false);
989 kfree(new_iface->ifname);
993 isw->iface_entry = new_iface;
994 INIT_WORK(&isw->iface_work, iface_create_proc_worker);
995 schedule_work(&isw->iface_work);
996 list_add(&new_iface->list, &iface_stat_list);
1000 static void iface_check_stats_reset_and_adjust(struct net_device *net_dev,
1001 struct iface_stat *iface)
1003 struct rtnl_link_stats64 dev_stats, *stats;
1006 stats = dev_get_stats(net_dev, &dev_stats);
1007 /* No empty packets */
1009 (stats->rx_bytes < iface->last_known[IFS_RX].bytes)
1010 || (stats->tx_bytes < iface->last_known[IFS_TX].bytes);
1012 IF_DEBUG("qtaguid: %s(%s): iface=%p netdev=%p "
1013 "bytes rx/tx=%llu/%llu "
1014 "active=%d last_known=%d "
1015 "stats_rewound=%d\n", __func__,
1016 net_dev ? net_dev->name : "?",
1018 stats->rx_bytes, stats->tx_bytes,
1019 iface->active, iface->last_known_valid, stats_rewound);
1021 if (iface->active && iface->last_known_valid && stats_rewound) {
1022 pr_warn_once("qtaguid: iface_stat: %s(%s): "
1023 "iface reset its stats unexpectedly\n", __func__,
1026 iface->totals_via_dev[IFS_TX].bytes +=
1027 iface->last_known[IFS_TX].bytes;
1028 iface->totals_via_dev[IFS_TX].packets +=
1029 iface->last_known[IFS_TX].packets;
1030 iface->totals_via_dev[IFS_RX].bytes +=
1031 iface->last_known[IFS_RX].bytes;
1032 iface->totals_via_dev[IFS_RX].packets +=
1033 iface->last_known[IFS_RX].packets;
1034 iface->last_known_valid = false;
1035 IF_DEBUG("qtaguid: %s(%s): iface=%p "
1036 "used last known bytes rx/tx=%llu/%llu\n", __func__,
1037 iface->ifname, iface, iface->last_known[IFS_RX].bytes,
1038 iface->last_known[IFS_TX].bytes);
1043 * Create a new entry for tracking the specified interface.
1044 * Do nothing if the entry already exists.
1045 * Called when an interface is configured with a valid IP address.
1047 static void iface_stat_create(struct net_device *net_dev,
1048 struct in_ifaddr *ifa)
1050 struct in_device *in_dev = NULL;
1052 struct iface_stat *entry;
1054 struct iface_stat *new_iface;
1056 IF_DEBUG("qtaguid: iface_stat: create(%s): ifa=%p netdev=%p\n",
1057 net_dev ? net_dev->name : "?",
1060 pr_err("qtaguid: iface_stat: create(): no net dev\n");
1064 ifname = net_dev->name;
1066 in_dev = in_dev_get(net_dev);
1068 pr_err("qtaguid: iface_stat: create(%s): no inet dev\n",
1072 IF_DEBUG("qtaguid: iface_stat: create(%s): in_dev=%p\n",
1074 for (ifa = in_dev->ifa_list; ifa; ifa = ifa->ifa_next) {
1075 IF_DEBUG("qtaguid: iface_stat: create(%s): "
1076 "ifa=%p ifa_label=%s\n",
1078 ifa->ifa_label ? ifa->ifa_label : "(null)");
1079 if (ifa->ifa_label && !strcmp(ifname, ifa->ifa_label))
1085 IF_DEBUG("qtaguid: iface_stat: create(%s): no matching IP\n",
1089 ipaddr = ifa->ifa_local;
1091 spin_lock_bh(&iface_stat_list_lock);
1092 entry = get_iface_entry(ifname);
1093 if (entry != NULL) {
1094 bool activate = !ipv4_is_loopback(ipaddr);
1095 IF_DEBUG("qtaguid: iface_stat: create(%s): entry=%p\n",
1097 iface_check_stats_reset_and_adjust(net_dev, entry);
1098 _iface_stat_set_active(entry, net_dev, activate);
1099 IF_DEBUG("qtaguid: %s(%s): "
1100 "tracking now %d on ip=%pI4\n", __func__,
1101 entry->ifname, activate, &ipaddr);
1102 goto done_unlock_put;
1103 } else if (ipv4_is_loopback(ipaddr)) {
1104 IF_DEBUG("qtaguid: iface_stat: create(%s): "
1105 "ignore loopback dev. ip=%pI4\n", ifname, &ipaddr);
1106 goto done_unlock_put;
1109 new_iface = iface_alloc(net_dev);
1110 IF_DEBUG("qtaguid: iface_stat: create(%s): done "
1111 "entry=%p ip=%pI4\n", ifname, new_iface, &ipaddr);
1113 spin_unlock_bh(&iface_stat_list_lock);
1119 static void iface_stat_create_ipv6(struct net_device *net_dev,
1120 struct inet6_ifaddr *ifa)
1122 struct in_device *in_dev;
1124 struct iface_stat *entry;
1125 struct iface_stat *new_iface;
1128 IF_DEBUG("qtaguid: iface_stat: create6(): ifa=%p netdev=%p->name=%s\n",
1129 ifa, net_dev, net_dev ? net_dev->name : "");
1131 pr_err("qtaguid: iface_stat: create6(): no net dev!\n");
1134 ifname = net_dev->name;
1136 in_dev = in_dev_get(net_dev);
1138 pr_err("qtaguid: iface_stat: create6(%s): no inet dev\n",
1143 IF_DEBUG("qtaguid: iface_stat: create6(%s): in_dev=%p\n",
1147 IF_DEBUG("qtaguid: iface_stat: create6(%s): no matching IP\n",
1151 addr_type = ipv6_addr_type(&ifa->addr);
1153 spin_lock_bh(&iface_stat_list_lock);
1154 entry = get_iface_entry(ifname);
1155 if (entry != NULL) {
1156 bool activate = !(addr_type & IPV6_ADDR_LOOPBACK);
1157 IF_DEBUG("qtaguid: %s(%s): entry=%p\n", __func__,
1159 iface_check_stats_reset_and_adjust(net_dev, entry);
1160 _iface_stat_set_active(entry, net_dev, activate);
1161 IF_DEBUG("qtaguid: %s(%s): "
1162 "tracking now %d on ip=%pI6c\n", __func__,
1163 entry->ifname, activate, &ifa->addr);
1164 goto done_unlock_put;
1165 } else if (addr_type & IPV6_ADDR_LOOPBACK) {
1166 IF_DEBUG("qtaguid: %s(%s): "
1167 "ignore loopback dev. ip=%pI6c\n", __func__,
1168 ifname, &ifa->addr);
1169 goto done_unlock_put;
1172 new_iface = iface_alloc(net_dev);
1173 IF_DEBUG("qtaguid: iface_stat: create6(%s): done "
1174 "entry=%p ip=%pI6c\n", ifname, new_iface, &ifa->addr);
1177 spin_unlock_bh(&iface_stat_list_lock);
1182 static struct sock_tag *get_sock_stat_nl(const struct sock *sk)
1184 MT_DEBUG("qtaguid: get_sock_stat_nl(sk=%p)\n", sk);
1185 return sock_tag_tree_search(&sock_tag_tree, sk);
1188 static struct sock_tag *get_sock_stat(const struct sock *sk)
1190 struct sock_tag *sock_tag_entry;
1191 MT_DEBUG("qtaguid: get_sock_stat(sk=%p)\n", sk);
1194 spin_lock_bh(&sock_tag_list_lock);
1195 sock_tag_entry = get_sock_stat_nl(sk);
1196 spin_unlock_bh(&sock_tag_list_lock);
1197 return sock_tag_entry;
1200 static int ipx_proto(const struct sk_buff *skb,
1201 struct xt_action_param *par)
1203 int thoff = 0, tproto;
1205 switch (par->family) {
1207 tproto = ipv6_find_hdr(skb, &thoff, -1, NULL, NULL);
1209 MT_DEBUG("%s(): transport header not found in ipv6"
1210 " skb=%p\n", __func__, skb);
1213 tproto = ip_hdr(skb)->protocol;
1216 tproto = IPPROTO_RAW;
1222 data_counters_update(struct data_counters *dc, int set,
1223 enum ifs_tx_rx direction, int proto, int bytes)
1227 dc_add_byte_packets(dc, set, direction, IFS_TCP, bytes, 1);
1230 dc_add_byte_packets(dc, set, direction, IFS_UDP, bytes, 1);
1234 dc_add_byte_packets(dc, set, direction, IFS_PROTO_OTHER, bytes,
1241 * Update stats for the specified interface. Do nothing if the entry
1242 * does not exist (when a device was never configured with an IP address).
1243 * Called when an device is being unregistered.
1245 static void iface_stat_update(struct net_device *net_dev, bool stash_only)
1247 struct rtnl_link_stats64 dev_stats, *stats;
1248 struct iface_stat *entry;
1250 stats = dev_get_stats(net_dev, &dev_stats);
1251 spin_lock_bh(&iface_stat_list_lock);
1252 entry = get_iface_entry(net_dev->name);
1253 if (entry == NULL) {
1254 IF_DEBUG("qtaguid: iface_stat: update(%s): not tracked\n",
1256 spin_unlock_bh(&iface_stat_list_lock);
1260 IF_DEBUG("qtaguid: %s(%s): entry=%p\n", __func__,
1261 net_dev->name, entry);
1262 if (!entry->active) {
1263 IF_DEBUG("qtaguid: %s(%s): already disabled\n", __func__,
1265 spin_unlock_bh(&iface_stat_list_lock);
1270 entry->last_known[IFS_TX].bytes = stats->tx_bytes;
1271 entry->last_known[IFS_TX].packets = stats->tx_packets;
1272 entry->last_known[IFS_RX].bytes = stats->rx_bytes;
1273 entry->last_known[IFS_RX].packets = stats->rx_packets;
1274 entry->last_known_valid = true;
1275 IF_DEBUG("qtaguid: %s(%s): "
1276 "dev stats stashed rx/tx=%llu/%llu\n", __func__,
1277 net_dev->name, stats->rx_bytes, stats->tx_bytes);
1278 spin_unlock_bh(&iface_stat_list_lock);
1281 entry->totals_via_dev[IFS_TX].bytes += stats->tx_bytes;
1282 entry->totals_via_dev[IFS_TX].packets += stats->tx_packets;
1283 entry->totals_via_dev[IFS_RX].bytes += stats->rx_bytes;
1284 entry->totals_via_dev[IFS_RX].packets += stats->rx_packets;
1285 /* We don't need the last_known[] anymore */
1286 entry->last_known_valid = false;
1287 _iface_stat_set_active(entry, net_dev, false);
1288 IF_DEBUG("qtaguid: %s(%s): "
1289 "disable tracking. rx/tx=%llu/%llu\n", __func__,
1290 net_dev->name, stats->rx_bytes, stats->tx_bytes);
1291 spin_unlock_bh(&iface_stat_list_lock);
1295 * Update stats for the specified interface from the skb.
1296 * Do nothing if the entry
1297 * does not exist (when a device was never configured with an IP address).
1298 * Called on each sk.
1300 static void iface_stat_update_from_skb(const struct sk_buff *skb,
1301 struct xt_action_param *par)
1303 struct iface_stat *entry;
1304 const struct net_device *el_dev;
1305 enum ifs_tx_rx direction = par->in ? IFS_RX : IFS_TX;
1306 int bytes = skb->len;
1309 MT_DEBUG("qtaguid[%d]: no skb->dev\n", par->hooknum);
1310 el_dev = par->in ? : par->out;
1312 const struct net_device *other_dev;
1314 other_dev = par->in ? : par->out;
1315 if (el_dev != other_dev) {
1316 MT_DEBUG("qtaguid[%d]: skb->dev=%p %s vs "
1317 "par->(in/out)=%p %s\n",
1318 par->hooknum, el_dev, el_dev->name, other_dev,
1323 if (unlikely(!el_dev)) {
1324 pr_err("qtaguid[%d]: %s(): no par->in/out?!!\n",
1325 par->hooknum, __func__);
1327 } else if (unlikely(!el_dev->name)) {
1328 pr_err("qtaguid[%d]: %s(): no dev->name?!!\n",
1329 par->hooknum, __func__);
1332 int proto = ipx_proto(skb, par);
1333 MT_DEBUG("qtaguid[%d]: dev name=%s type=%d fam=%d proto=%d\n",
1334 par->hooknum, el_dev->name, el_dev->type,
1335 par->family, proto);
1338 spin_lock_bh(&iface_stat_list_lock);
1339 entry = get_iface_entry(el_dev->name);
1340 if (entry == NULL) {
1341 IF_DEBUG("qtaguid: iface_stat: %s(%s): not tracked\n",
1342 __func__, el_dev->name);
1343 spin_unlock_bh(&iface_stat_list_lock);
1347 IF_DEBUG("qtaguid: %s(%s): entry=%p\n", __func__,
1348 el_dev->name, entry);
1350 entry->totals_via_skb[direction].bytes += bytes;
1351 entry->totals_via_skb[direction].packets++;
1352 spin_unlock_bh(&iface_stat_list_lock);
1355 static void tag_stat_update(struct tag_stat *tag_entry,
1356 enum ifs_tx_rx direction, int proto, int bytes)
1359 active_set = get_active_counter_set(tag_entry->tn.tag);
1360 MT_DEBUG("qtaguid: tag_stat_update(tag=0x%llx (uid=%u) set=%d "
1361 "dir=%d proto=%d bytes=%d)\n",
1362 tag_entry->tn.tag, get_uid_from_tag(tag_entry->tn.tag),
1363 active_set, direction, proto, bytes);
1364 data_counters_update(&tag_entry->counters, active_set, direction,
1366 if (tag_entry->parent_counters)
1367 data_counters_update(tag_entry->parent_counters, active_set,
1368 direction, proto, bytes);
1372 * Create a new entry for tracking the specified {acct_tag,uid_tag} within
1374 * iface_entry->tag_stat_list_lock should be held.
1376 static struct tag_stat *create_if_tag_stat(struct iface_stat *iface_entry,
1379 struct tag_stat *new_tag_stat_entry = NULL;
1380 IF_DEBUG("qtaguid: iface_stat: %s(): ife=%p tag=0x%llx"
1381 " (uid=%u)\n", __func__,
1382 iface_entry, tag, get_uid_from_tag(tag));
1383 new_tag_stat_entry = kzalloc(sizeof(*new_tag_stat_entry), GFP_ATOMIC);
1384 if (!new_tag_stat_entry) {
1385 pr_err("qtaguid: iface_stat: tag stat alloc failed\n");
1388 new_tag_stat_entry->tn.tag = tag;
1389 tag_stat_tree_insert(new_tag_stat_entry, &iface_entry->tag_stat_tree);
1391 return new_tag_stat_entry;
1394 static void if_tag_stat_update(const char *ifname, uid_t uid,
1395 const struct sock *sk, enum ifs_tx_rx direction,
1396 int proto, int bytes)
1398 struct tag_stat *tag_stat_entry;
1399 tag_t tag, acct_tag;
1401 struct data_counters *uid_tag_counters;
1402 struct sock_tag *sock_tag_entry;
1403 struct iface_stat *iface_entry;
1404 struct tag_stat *new_tag_stat = NULL;
1405 MT_DEBUG("qtaguid: if_tag_stat_update(ifname=%s "
1406 "uid=%u sk=%p dir=%d proto=%d bytes=%d)\n",
1407 ifname, uid, sk, direction, proto, bytes);
1410 iface_entry = get_iface_entry(ifname);
1412 pr_err("qtaguid: iface_stat: stat_update() %s not found\n",
1416 /* It is ok to process data when an iface_entry is inactive */
1418 MT_DEBUG("qtaguid: iface_stat: stat_update() dev=%s entry=%p\n",
1419 ifname, iface_entry);
1422 * Look for a tagged sock.
1423 * It will have an acct_uid.
1425 sock_tag_entry = get_sock_stat(sk);
1426 if (sock_tag_entry) {
1427 tag = sock_tag_entry->tag;
1428 acct_tag = get_atag_from_tag(tag);
1429 uid_tag = get_utag_from_tag(tag);
1431 acct_tag = make_atag_from_value(0);
1432 tag = combine_atag_with_uid(acct_tag, uid);
1433 uid_tag = make_tag_from_uid(uid);
1435 MT_DEBUG("qtaguid: iface_stat: stat_update(): "
1436 " looking for tag=0x%llx (uid=%u) in ife=%p\n",
1437 tag, get_uid_from_tag(tag), iface_entry);
1438 /* Loop over tag list under this interface for {acct_tag,uid_tag} */
1439 spin_lock_bh(&iface_entry->tag_stat_list_lock);
1441 tag_stat_entry = tag_stat_tree_search(&iface_entry->tag_stat_tree,
1443 if (tag_stat_entry) {
1445 * Updating the {acct_tag, uid_tag} entry handles both stats:
1446 * {0, uid_tag} will also get updated.
1448 tag_stat_update(tag_stat_entry, direction, proto, bytes);
1449 spin_unlock_bh(&iface_entry->tag_stat_list_lock);
1453 /* Loop over tag list under this interface for {0,uid_tag} */
1454 tag_stat_entry = tag_stat_tree_search(&iface_entry->tag_stat_tree,
1456 if (!tag_stat_entry) {
1457 /* Here: the base uid_tag did not exist */
1459 * No parent counters. So
1460 * - No {0, uid_tag} stats and no {acc_tag, uid_tag} stats.
1462 new_tag_stat = create_if_tag_stat(iface_entry, uid_tag);
1465 uid_tag_counters = &new_tag_stat->counters;
1467 uid_tag_counters = &tag_stat_entry->counters;
1471 /* Create the child {acct_tag, uid_tag} and hook up parent. */
1472 new_tag_stat = create_if_tag_stat(iface_entry, tag);
1475 new_tag_stat->parent_counters = uid_tag_counters;
1478 * For new_tag_stat to be still NULL here would require:
1479 * {0, uid_tag} exists
1480 * and {acct_tag, uid_tag} doesn't exist
1481 * AND acct_tag == 0.
1482 * Impossible. This reassures us that new_tag_stat
1483 * below will always be assigned.
1485 BUG_ON(!new_tag_stat);
1487 tag_stat_update(new_tag_stat, direction, proto, bytes);
1489 spin_unlock_bh(&iface_entry->tag_stat_list_lock);
1492 static int iface_netdev_event_handler(struct notifier_block *nb,
1493 unsigned long event, void *ptr) {
1494 struct net_device *dev = ptr;
1496 if (unlikely(module_passive))
1499 IF_DEBUG("qtaguid: iface_stat: netdev_event(): "
1500 "ev=0x%lx/%s netdev=%p->name=%s\n",
1501 event, netdev_evt_str(event), dev, dev ? dev->name : "");
1505 iface_stat_create(dev, NULL);
1506 atomic64_inc(&qtu_events.iface_events);
1509 case NETDEV_UNREGISTER:
1510 iface_stat_update(dev, event == NETDEV_DOWN);
1511 atomic64_inc(&qtu_events.iface_events);
1517 static int iface_inet6addr_event_handler(struct notifier_block *nb,
1518 unsigned long event, void *ptr)
1520 struct inet6_ifaddr *ifa = ptr;
1521 struct net_device *dev;
1523 if (unlikely(module_passive))
1526 IF_DEBUG("qtaguid: iface_stat: inet6addr_event(): "
1527 "ev=0x%lx/%s ifa=%p\n",
1528 event, netdev_evt_str(event), ifa);
1532 BUG_ON(!ifa || !ifa->idev);
1533 dev = (struct net_device *)ifa->idev->dev;
1534 iface_stat_create_ipv6(dev, ifa);
1535 atomic64_inc(&qtu_events.iface_events);
1538 case NETDEV_UNREGISTER:
1539 BUG_ON(!ifa || !ifa->idev);
1540 dev = (struct net_device *)ifa->idev->dev;
1541 iface_stat_update(dev, event == NETDEV_DOWN);
1542 atomic64_inc(&qtu_events.iface_events);
1548 static int iface_inetaddr_event_handler(struct notifier_block *nb,
1549 unsigned long event, void *ptr)
1551 struct in_ifaddr *ifa = ptr;
1552 struct net_device *dev;
1554 if (unlikely(module_passive))
1557 IF_DEBUG("qtaguid: iface_stat: inetaddr_event(): "
1558 "ev=0x%lx/%s ifa=%p\n",
1559 event, netdev_evt_str(event), ifa);
1563 BUG_ON(!ifa || !ifa->ifa_dev);
1564 dev = ifa->ifa_dev->dev;
1565 iface_stat_create(dev, ifa);
1566 atomic64_inc(&qtu_events.iface_events);
1569 case NETDEV_UNREGISTER:
1570 BUG_ON(!ifa || !ifa->ifa_dev);
1571 dev = ifa->ifa_dev->dev;
1572 iface_stat_update(dev, event == NETDEV_DOWN);
1573 atomic64_inc(&qtu_events.iface_events);
1579 static struct notifier_block iface_netdev_notifier_blk = {
1580 .notifier_call = iface_netdev_event_handler,
1583 static struct notifier_block iface_inetaddr_notifier_blk = {
1584 .notifier_call = iface_inetaddr_event_handler,
1587 static struct notifier_block iface_inet6addr_notifier_blk = {
1588 .notifier_call = iface_inet6addr_event_handler,
1591 static int __init iface_stat_init(struct proc_dir_entry *parent_procdir)
1595 iface_stat_procdir = proc_mkdir(iface_stat_procdirname, parent_procdir);
1596 if (!iface_stat_procdir) {
1597 pr_err("qtaguid: iface_stat: init failed to create proc entry\n");
1602 iface_stat_all_procfile = create_proc_entry(iface_stat_all_procfilename,
1605 if (!iface_stat_all_procfile) {
1606 pr_err("qtaguid: iface_stat: init "
1607 " failed to create stat_old proc entry\n");
1611 iface_stat_all_procfile->read_proc = iface_stat_fmt_proc_read;
1612 iface_stat_all_procfile->data = (void *)1; /* fmt1 */
1614 iface_stat_fmt_procfile = create_proc_entry(iface_stat_fmt_procfilename,
1617 if (!iface_stat_fmt_procfile) {
1618 pr_err("qtaguid: iface_stat: init "
1619 " failed to create stat_all proc entry\n");
1621 goto err_zap_all_stats_entry;
1623 iface_stat_fmt_procfile->read_proc = iface_stat_fmt_proc_read;
1624 iface_stat_fmt_procfile->data = (void *)2; /* fmt2 */
1627 err = register_netdevice_notifier(&iface_netdev_notifier_blk);
1629 pr_err("qtaguid: iface_stat: init "
1630 "failed to register dev event handler\n");
1631 goto err_zap_all_stats_entries;
1633 err = register_inetaddr_notifier(&iface_inetaddr_notifier_blk);
1635 pr_err("qtaguid: iface_stat: init "
1636 "failed to register ipv4 dev event handler\n");
1640 err = register_inet6addr_notifier(&iface_inet6addr_notifier_blk);
1642 pr_err("qtaguid: iface_stat: init "
1643 "failed to register ipv6 dev event handler\n");
1644 goto err_unreg_ip4_addr;
1649 unregister_inetaddr_notifier(&iface_inetaddr_notifier_blk);
1651 unregister_netdevice_notifier(&iface_netdev_notifier_blk);
1652 err_zap_all_stats_entries:
1653 remove_proc_entry(iface_stat_fmt_procfilename, parent_procdir);
1654 err_zap_all_stats_entry:
1655 remove_proc_entry(iface_stat_all_procfilename, parent_procdir);
1657 remove_proc_entry(iface_stat_procdirname, parent_procdir);
1662 static struct sock *qtaguid_find_sk(const struct sk_buff *skb,
1663 struct xt_action_param *par)
1666 unsigned int hook_mask = (1 << par->hooknum);
1668 MT_DEBUG("qtaguid: find_sk(skb=%p) hooknum=%d family=%d\n", skb,
1669 par->hooknum, par->family);
1672 * Let's not abuse the the xt_socket_get*_sk(), or else it will
1673 * return garbage SKs.
1675 if (!(hook_mask & XT_SOCKET_SUPPORTED_HOOKS))
1678 switch (par->family) {
1680 sk = xt_socket_get6_sk(skb, par);
1683 sk = xt_socket_get4_sk(skb, par);
1690 * Seems to be issues on the file ptr for TCP_TIME_WAIT SKs.
1691 * http://kerneltrap.org/mailarchive/linux-netdev/2010/10/21/6287959
1692 * Not fixed in 3.0-r3 :(
1695 MT_DEBUG("qtaguid: %p->sk_proto=%u "
1696 "->sk_state=%d\n", sk, sk->sk_protocol, sk->sk_state);
1697 if (sk->sk_state == TCP_TIME_WAIT) {
1698 xt_socket_put_sk(sk);
1705 static void account_for_uid(const struct sk_buff *skb,
1706 const struct sock *alternate_sk, uid_t uid,
1707 struct xt_action_param *par)
1709 const struct net_device *el_dev;
1712 MT_DEBUG("qtaguid[%d]: no skb->dev\n", par->hooknum);
1713 el_dev = par->in ? : par->out;
1715 const struct net_device *other_dev;
1717 other_dev = par->in ? : par->out;
1718 if (el_dev != other_dev) {
1719 MT_DEBUG("qtaguid[%d]: skb->dev=%p %s vs "
1720 "par->(in/out)=%p %s\n",
1721 par->hooknum, el_dev, el_dev->name, other_dev,
1726 if (unlikely(!el_dev)) {
1727 pr_info("qtaguid[%d]: no par->in/out?!!\n", par->hooknum);
1728 } else if (unlikely(!el_dev->name)) {
1729 pr_info("qtaguid[%d]: no dev->name?!!\n", par->hooknum);
1731 int proto = ipx_proto(skb, par);
1732 MT_DEBUG("qtaguid[%d]: dev name=%s type=%d fam=%d proto=%d\n",
1733 par->hooknum, el_dev->name, el_dev->type,
1734 par->family, proto);
1736 if_tag_stat_update(el_dev->name, uid,
1737 skb->sk ? skb->sk : alternate_sk,
1738 par->in ? IFS_RX : IFS_TX,
1743 static bool qtaguid_mt(const struct sk_buff *skb, struct xt_action_param *par)
1745 const struct xt_qtaguid_match_info *info = par->matchinfo;
1746 const struct file *filp;
1747 bool got_sock = false;
1752 if (unlikely(module_passive))
1753 return (info->match ^ info->invert) == 0;
1755 MT_DEBUG("qtaguid[%d]: entered skb=%p par->in=%p/out=%p fam=%d\n",
1756 par->hooknum, skb, par->in, par->out, par->family);
1758 atomic64_inc(&qtu_events.match_calls);
1760 res = (info->match ^ info->invert) == 0;
1764 switch (par->hooknum) {
1765 case NF_INET_PRE_ROUTING:
1766 case NF_INET_POST_ROUTING:
1767 atomic64_inc(&qtu_events.match_calls_prepost);
1768 iface_stat_update_from_skb(skb, par);
1770 * We are done in pre/post. The skb will get processed
1773 res = (info->match ^ info->invert);
1776 /* default: Fall through and do UID releated work */
1782 * A missing sk->sk_socket happens when packets are in-flight
1783 * and the matching socket is already closed and gone.
1785 sk = qtaguid_find_sk(skb, par);
1787 * If we got the socket from the find_sk(), we will need to put
1788 * it back, as nf_tproxy_get_sock_v4() got it.
1792 atomic64_inc(&qtu_events.match_found_sk_in_ct);
1794 atomic64_inc(&qtu_events.match_found_no_sk_in_ct);
1796 atomic64_inc(&qtu_events.match_found_sk);
1798 MT_DEBUG("qtaguid[%d]: sk=%p got_sock=%d fam=%d proto=%d\n",
1799 par->hooknum, sk, got_sock, par->family, ipx_proto(skb, par));
1801 MT_DEBUG("qtaguid[%d]: sk=%p->sk_socket=%p->file=%p\n",
1802 par->hooknum, sk, sk->sk_socket,
1803 sk->sk_socket ? sk->sk_socket->file : (void *)-1LL);
1804 filp = sk->sk_socket ? sk->sk_socket->file : NULL;
1805 MT_DEBUG("qtaguid[%d]: filp...uid=%u\n",
1806 par->hooknum, filp ? filp->f_cred->fsuid : -1);
1809 if (sk == NULL || sk->sk_socket == NULL) {
1811 * Here, the qtaguid_find_sk() using connection tracking
1812 * couldn't find the owner, so for now we just count them
1813 * against the system.
1816 * TODO: unhack how to force just accounting.
1817 * For now we only do iface stats when the uid-owner is not
1820 if (!(info->match & XT_QTAGUID_UID))
1821 account_for_uid(skb, sk, 0, par);
1822 MT_DEBUG("qtaguid[%d]: leaving (sk?sk->sk_socket)=%p\n",
1824 sk ? sk->sk_socket : NULL);
1825 res = (info->match ^ info->invert) == 0;
1826 atomic64_inc(&qtu_events.match_no_sk);
1827 goto put_sock_ret_res;
1828 } else if (info->match & info->invert & XT_QTAGUID_SOCKET) {
1830 goto put_sock_ret_res;
1832 filp = sk->sk_socket->file;
1834 MT_DEBUG("qtaguid[%d]: leaving filp=NULL\n", par->hooknum);
1835 account_for_uid(skb, sk, 0, par);
1836 res = ((info->match ^ info->invert) &
1837 (XT_QTAGUID_UID | XT_QTAGUID_GID)) == 0;
1838 atomic64_inc(&qtu_events.match_no_sk_file);
1839 goto put_sock_ret_res;
1841 sock_uid = filp->f_cred->fsuid;
1843 * TODO: unhack how to force just accounting.
1844 * For now we only do iface stats when the uid-owner is not requested
1846 if (!(info->match & XT_QTAGUID_UID))
1847 account_for_uid(skb, sk, sock_uid, par);
1850 * The following two tests fail the match when:
1851 * id not in range AND no inverted condition requested
1852 * or id in range AND inverted condition requested
1853 * Thus (!a && b) || (a && !b) == a ^ b
1855 if (info->match & XT_QTAGUID_UID)
1856 if ((filp->f_cred->fsuid >= info->uid_min &&
1857 filp->f_cred->fsuid <= info->uid_max) ^
1858 !(info->invert & XT_QTAGUID_UID)) {
1859 MT_DEBUG("qtaguid[%d]: leaving uid not matching\n",
1862 goto put_sock_ret_res;
1864 if (info->match & XT_QTAGUID_GID)
1865 if ((filp->f_cred->fsgid >= info->gid_min &&
1866 filp->f_cred->fsgid <= info->gid_max) ^
1867 !(info->invert & XT_QTAGUID_GID)) {
1868 MT_DEBUG("qtaguid[%d]: leaving gid not matching\n",
1871 goto put_sock_ret_res;
1874 MT_DEBUG("qtaguid[%d]: leaving matched\n", par->hooknum);
1879 xt_socket_put_sk(sk);
1881 MT_DEBUG("qtaguid[%d]: left %d\n", par->hooknum, res);
1886 /* This function is not in xt_qtaguid_print.c because of locks visibility */
1887 static void prdebug_full_state(int indent_level, const char *fmt, ...)
1893 if (!unlikely(qtaguid_debug_mask & DDEBUG_MASK))
1896 fmt_buff = kasprintf(GFP_ATOMIC,
1897 "qtaguid: %s(): %s {\n", __func__, fmt);
1899 va_start(args, fmt);
1900 buff = kvasprintf(GFP_ATOMIC,
1903 pr_debug("%s", buff);
1908 spin_lock_bh(&sock_tag_list_lock);
1909 prdebug_sock_tag_tree(indent_level, &sock_tag_tree);
1910 spin_unlock_bh(&sock_tag_list_lock);
1912 spin_lock_bh(&sock_tag_list_lock);
1913 spin_lock_bh(&uid_tag_data_tree_lock);
1914 prdebug_uid_tag_data_tree(indent_level, &uid_tag_data_tree);
1915 prdebug_proc_qtu_data_tree(indent_level, &proc_qtu_data_tree);
1916 spin_unlock_bh(&uid_tag_data_tree_lock);
1917 spin_unlock_bh(&sock_tag_list_lock);
1919 spin_lock_bh(&iface_stat_list_lock);
1920 prdebug_iface_stat_list(indent_level, &iface_stat_list);
1921 spin_unlock_bh(&iface_stat_list_lock);
1923 pr_debug("qtaguid: %s(): }\n", __func__);
1926 static void prdebug_full_state(int indent_level, const char *fmt, ...) {}
1930 * Procfs reader to get all active socket tags using style "1)" as described in
1933 static int qtaguid_ctrl_proc_read(char *page, char **num_items_returned,
1934 off_t items_to_skip, int char_count, int *eof,
1940 struct rb_node *node;
1941 struct sock_tag *sock_tag_entry;
1943 int indent_level = 0;
1946 if (unlikely(module_passive)) {
1954 CT_DEBUG("qtaguid: proc ctrl pid=%u tgid=%u uid=%u "
1955 "page=%p off=%ld char_count=%d *eof=%d\n",
1956 current->pid, current->tgid, current_fsuid(),
1957 page, items_to_skip, char_count, *eof);
1959 spin_lock_bh(&sock_tag_list_lock);
1960 for (node = rb_first(&sock_tag_tree);
1962 node = rb_next(node)) {
1963 if (item_index++ < items_to_skip)
1965 sock_tag_entry = rb_entry(node, struct sock_tag, sock_node);
1966 uid = get_uid_from_tag(sock_tag_entry->tag);
1967 CT_DEBUG("qtaguid: proc_read(): sk=%p tag=0x%llx (uid=%u) "
1970 sock_tag_entry->tag,
1974 f_count = atomic_long_read(
1975 &sock_tag_entry->socket->file->f_count);
1976 len = snprintf(outp, char_count,
1977 "sock=%p tag=0x%llx (uid=%u) pid=%u "
1980 sock_tag_entry->tag, uid,
1981 sock_tag_entry->pid, f_count);
1982 if (len >= char_count) {
1983 spin_unlock_bh(&sock_tag_list_lock);
1989 (*num_items_returned)++;
1991 spin_unlock_bh(&sock_tag_list_lock);
1993 if (item_index++ >= items_to_skip) {
1994 len = snprintf(outp, char_count,
1995 "events: sockets_tagged=%llu "
1996 "sockets_untagged=%llu "
1997 "counter_set_changes=%llu "
1999 "iface_events=%llu "
2001 "match_calls_prepost=%llu "
2002 "match_found_sk=%llu "
2003 "match_found_sk_in_ct=%llu "
2004 "match_found_no_sk_in_ct=%llu "
2006 "match_no_sk_file=%llu\n",
2007 atomic64_read(&qtu_events.sockets_tagged),
2008 atomic64_read(&qtu_events.sockets_untagged),
2009 atomic64_read(&qtu_events.counter_set_changes),
2010 atomic64_read(&qtu_events.delete_cmds),
2011 atomic64_read(&qtu_events.iface_events),
2012 atomic64_read(&qtu_events.match_calls),
2013 atomic64_read(&qtu_events.match_calls_prepost),
2014 atomic64_read(&qtu_events.match_found_sk),
2015 atomic64_read(&qtu_events.match_found_sk_in_ct),
2017 &qtu_events.match_found_no_sk_in_ct),
2018 atomic64_read(&qtu_events.match_no_sk),
2019 atomic64_read(&qtu_events.match_no_sk_file));
2020 if (len >= char_count) {
2026 (*num_items_returned)++;
2029 /* Count the following as part of the last item_index */
2030 if (item_index > items_to_skip) {
2031 prdebug_full_state(indent_level, "proc ctrl");
2039 * Delete socket tags, and stat tags associated with a given
2040 * accouting tag and uid.
2042 static int ctrl_cmd_delete(const char *input)
2050 struct iface_stat *iface_entry;
2051 struct rb_node *node;
2052 struct sock_tag *st_entry;
2053 struct rb_root st_to_free_tree = RB_ROOT;
2054 struct tag_stat *ts_entry;
2055 struct tag_counter_set *tcs_entry;
2056 struct tag_ref *tr_entry;
2057 struct uid_tag_data *utd_entry;
2059 argc = sscanf(input, "%c %llu %u", &cmd, &acct_tag, &uid);
2060 CT_DEBUG("qtaguid: ctrl_delete(%s): argc=%d cmd=%c "
2061 "user_tag=0x%llx uid=%u\n", input, argc, cmd,
2067 if (!valid_atag(acct_tag)) {
2068 pr_info("qtaguid: ctrl_delete(%s): invalid tag\n", input);
2073 uid = current_fsuid();
2074 } else if (!can_impersonate_uid(uid)) {
2075 pr_info("qtaguid: ctrl_delete(%s): "
2076 "insufficient priv from pid=%u tgid=%u uid=%u\n",
2077 input, current->pid, current->tgid, current_fsuid());
2082 tag = combine_atag_with_uid(acct_tag, uid);
2083 CT_DEBUG("qtaguid: ctrl_delete(%s): "
2084 "looking for tag=0x%llx (uid=%u)\n",
2087 /* Delete socket tags */
2088 spin_lock_bh(&sock_tag_list_lock);
2089 node = rb_first(&sock_tag_tree);
2091 st_entry = rb_entry(node, struct sock_tag, sock_node);
2092 entry_uid = get_uid_from_tag(st_entry->tag);
2093 node = rb_next(node);
2094 if (entry_uid != uid)
2097 CT_DEBUG("qtaguid: ctrl_delete(%s): st tag=0x%llx (uid=%u)\n",
2098 input, st_entry->tag, entry_uid);
2100 if (!acct_tag || st_entry->tag == tag) {
2101 rb_erase(&st_entry->sock_node, &sock_tag_tree);
2102 /* Can't sockfd_put() within spinlock, do it later. */
2103 sock_tag_tree_insert(st_entry, &st_to_free_tree);
2104 tr_entry = lookup_tag_ref(st_entry->tag, NULL);
2105 BUG_ON(tr_entry->num_sock_tags <= 0);
2106 tr_entry->num_sock_tags--;
2108 * TODO: remove if, and start failing.
2109 * This is a hack to work around the fact that in some
2110 * places we have "if (IS_ERR_OR_NULL(pqd_entry))"
2111 * and are trying to work around apps
2112 * that didn't open the /dev/xt_qtaguid.
2114 if (st_entry->list.next && st_entry->list.prev)
2115 list_del(&st_entry->list);
2118 spin_unlock_bh(&sock_tag_list_lock);
2120 sock_tag_tree_erase(&st_to_free_tree);
2122 /* Delete tag counter-sets */
2123 spin_lock_bh(&tag_counter_set_list_lock);
2124 /* Counter sets are only on the uid tag, not full tag */
2125 tcs_entry = tag_counter_set_tree_search(&tag_counter_set_tree, tag);
2127 CT_DEBUG("qtaguid: ctrl_delete(%s): "
2128 "erase tcs: tag=0x%llx (uid=%u) set=%d\n",
2131 get_uid_from_tag(tcs_entry->tn.tag),
2132 tcs_entry->active_set);
2133 rb_erase(&tcs_entry->tn.node, &tag_counter_set_tree);
2136 spin_unlock_bh(&tag_counter_set_list_lock);
2139 * If acct_tag is 0, then all entries belonging to uid are
2142 spin_lock_bh(&iface_stat_list_lock);
2143 list_for_each_entry(iface_entry, &iface_stat_list, list) {
2144 spin_lock_bh(&iface_entry->tag_stat_list_lock);
2145 node = rb_first(&iface_entry->tag_stat_tree);
2147 ts_entry = rb_entry(node, struct tag_stat, tn.node);
2148 entry_uid = get_uid_from_tag(ts_entry->tn.tag);
2149 node = rb_next(node);
2151 CT_DEBUG("qtaguid: ctrl_delete(%s): "
2152 "ts tag=0x%llx (uid=%u)\n",
2153 input, ts_entry->tn.tag, entry_uid);
2155 if (entry_uid != uid)
2157 if (!acct_tag || ts_entry->tn.tag == tag) {
2158 CT_DEBUG("qtaguid: ctrl_delete(%s): "
2159 "erase ts: %s 0x%llx %u\n",
2160 input, iface_entry->ifname,
2161 get_atag_from_tag(ts_entry->tn.tag),
2163 rb_erase(&ts_entry->tn.node,
2164 &iface_entry->tag_stat_tree);
2168 spin_unlock_bh(&iface_entry->tag_stat_list_lock);
2170 spin_unlock_bh(&iface_stat_list_lock);
2172 /* Cleanup the uid_tag_data */
2173 spin_lock_bh(&uid_tag_data_tree_lock);
2174 node = rb_first(&uid_tag_data_tree);
2176 utd_entry = rb_entry(node, struct uid_tag_data, node);
2177 entry_uid = utd_entry->uid;
2178 node = rb_next(node);
2180 CT_DEBUG("qtaguid: ctrl_delete(%s): "
2184 if (entry_uid != uid)
2187 * Go over the tag_refs, and those that don't have
2188 * sock_tags using them are freed.
2190 put_tag_ref_tree(tag, utd_entry);
2191 put_utd_entry(utd_entry);
2193 spin_unlock_bh(&uid_tag_data_tree_lock);
2195 atomic64_inc(&qtu_events.delete_cmds);
2202 static int ctrl_cmd_counter_set(const char *input)
2208 struct tag_counter_set *tcs;
2211 argc = sscanf(input, "%c %d %u", &cmd, &counter_set, &uid);
2212 CT_DEBUG("qtaguid: ctrl_counterset(%s): argc=%d cmd=%c "
2213 "set=%d uid=%u\n", input, argc, cmd,
2219 if (counter_set < 0 || counter_set >= IFS_MAX_COUNTER_SETS) {
2220 pr_info("qtaguid: ctrl_counterset(%s): invalid counter_set range\n",
2225 if (!can_manipulate_uids()) {
2226 pr_info("qtaguid: ctrl_counterset(%s): "
2227 "insufficient priv from pid=%u tgid=%u uid=%u\n",
2228 input, current->pid, current->tgid, current_fsuid());
2233 tag = make_tag_from_uid(uid);
2234 spin_lock_bh(&tag_counter_set_list_lock);
2235 tcs = tag_counter_set_tree_search(&tag_counter_set_tree, tag);
2237 tcs = kzalloc(sizeof(*tcs), GFP_ATOMIC);
2239 spin_unlock_bh(&tag_counter_set_list_lock);
2240 pr_err("qtaguid: ctrl_counterset(%s): "
2241 "failed to alloc counter set\n",
2247 tag_counter_set_tree_insert(tcs, &tag_counter_set_tree);
2248 CT_DEBUG("qtaguid: ctrl_counterset(%s): added tcs tag=0x%llx "
2249 "(uid=%u) set=%d\n",
2250 input, tag, get_uid_from_tag(tag), counter_set);
2252 tcs->active_set = counter_set;
2253 spin_unlock_bh(&tag_counter_set_list_lock);
2254 atomic64_inc(&qtu_events.counter_set_changes);
2261 static int ctrl_cmd_tag(const char *input)
2266 tag_t acct_tag = make_atag_from_value(0);
2268 struct socket *el_socket;
2270 struct sock_tag *sock_tag_entry;
2271 struct tag_ref *tag_ref_entry;
2272 struct uid_tag_data *uid_tag_data_entry;
2273 struct proc_qtu_data *pqd_entry;
2275 /* Unassigned args will get defaulted later. */
2276 argc = sscanf(input, "%c %d %llu %u", &cmd, &sock_fd, &acct_tag, &uid);
2277 CT_DEBUG("qtaguid: ctrl_tag(%s): argc=%d cmd=%c sock_fd=%d "
2278 "acct_tag=0x%llx uid=%u\n", input, argc, cmd, sock_fd,
2284 el_socket = sockfd_lookup(sock_fd, &res); /* This locks the file */
2286 pr_info("qtaguid: ctrl_tag(%s): failed to lookup"
2287 " sock_fd=%d err=%d pid=%u tgid=%u uid=%u\n",
2288 input, sock_fd, res, current->pid, current->tgid,
2292 CT_DEBUG("qtaguid: ctrl_tag(%s): socket->...->f_count=%ld ->sk=%p\n",
2293 input, atomic_long_read(&el_socket->file->f_count),
2296 acct_tag = make_atag_from_value(0);
2297 } else if (!valid_atag(acct_tag)) {
2298 pr_info("qtaguid: ctrl_tag(%s): invalid tag\n", input);
2302 CT_DEBUG("qtaguid: ctrl_tag(%s): "
2303 "pid=%u tgid=%u uid=%u euid=%u fsuid=%u "
2304 "ctrl.gid=%u in_group()=%d in_egroup()=%d\n",
2305 input, current->pid, current->tgid, current_uid(),
2306 current_euid(), current_fsuid(),
2307 xt_qtaguid_ctrl_file->gid,
2308 in_group_p(xt_qtaguid_ctrl_file->gid),
2309 in_egroup_p(xt_qtaguid_ctrl_file->gid));
2311 uid = current_fsuid();
2312 } else if (!can_impersonate_uid(uid)) {
2313 pr_info("qtaguid: ctrl_tag(%s): "
2314 "insufficient priv from pid=%u tgid=%u uid=%u\n",
2315 input, current->pid, current->tgid, current_fsuid());
2319 full_tag = combine_atag_with_uid(acct_tag, uid);
2321 spin_lock_bh(&sock_tag_list_lock);
2322 sock_tag_entry = get_sock_stat_nl(el_socket->sk);
2323 tag_ref_entry = get_tag_ref(full_tag, &uid_tag_data_entry);
2324 if (IS_ERR(tag_ref_entry)) {
2325 res = PTR_ERR(tag_ref_entry);
2326 spin_unlock_bh(&sock_tag_list_lock);
2329 tag_ref_entry->num_sock_tags++;
2330 if (sock_tag_entry) {
2331 struct tag_ref *prev_tag_ref_entry;
2333 CT_DEBUG("qtaguid: ctrl_tag(%s): retag for sk=%p "
2334 "st@%p ...->f_count=%ld\n",
2335 input, el_socket->sk, sock_tag_entry,
2336 atomic_long_read(&el_socket->file->f_count));
2338 * This is a re-tagging, so release the sock_fd that was
2339 * locked at the time of the 1st tagging.
2340 * There is still the ref from this call's sockfd_lookup() so
2341 * it can be done within the spinlock.
2343 sockfd_put(sock_tag_entry->socket);
2344 prev_tag_ref_entry = lookup_tag_ref(sock_tag_entry->tag,
2345 &uid_tag_data_entry);
2346 BUG_ON(IS_ERR_OR_NULL(prev_tag_ref_entry));
2347 BUG_ON(prev_tag_ref_entry->num_sock_tags <= 0);
2348 prev_tag_ref_entry->num_sock_tags--;
2349 sock_tag_entry->tag = full_tag;
2351 CT_DEBUG("qtaguid: ctrl_tag(%s): newtag for sk=%p\n",
2352 input, el_socket->sk);
2353 sock_tag_entry = kzalloc(sizeof(*sock_tag_entry),
2355 if (!sock_tag_entry) {
2356 pr_err("qtaguid: ctrl_tag(%s): "
2357 "socket tag alloc failed\n",
2359 spin_unlock_bh(&sock_tag_list_lock);
2361 goto err_tag_unref_put;
2363 sock_tag_entry->sk = el_socket->sk;
2364 sock_tag_entry->socket = el_socket;
2365 sock_tag_entry->pid = current->tgid;
2366 sock_tag_entry->tag = combine_atag_with_uid(acct_tag,
2368 spin_lock_bh(&uid_tag_data_tree_lock);
2369 pqd_entry = proc_qtu_data_tree_search(
2370 &proc_qtu_data_tree, current->tgid);
2372 * TODO: remove if, and start failing.
2373 * At first, we want to catch user-space code that is not
2374 * opening the /dev/xt_qtaguid.
2376 if (IS_ERR_OR_NULL(pqd_entry))
2379 "User space forgot to open /dev/xt_qtaguid? "
2380 "pid=%u tgid=%u uid=%u\n", __func__,
2381 current->pid, current->tgid,
2384 list_add(&sock_tag_entry->list,
2385 &pqd_entry->sock_tag_list);
2386 spin_unlock_bh(&uid_tag_data_tree_lock);
2388 sock_tag_tree_insert(sock_tag_entry, &sock_tag_tree);
2389 atomic64_inc(&qtu_events.sockets_tagged);
2391 spin_unlock_bh(&sock_tag_list_lock);
2392 /* We keep the ref to the socket (file) until it is untagged */
2393 CT_DEBUG("qtaguid: ctrl_tag(%s): done st@%p ...->f_count=%ld\n",
2394 input, sock_tag_entry,
2395 atomic_long_read(&el_socket->file->f_count));
2399 BUG_ON(tag_ref_entry->num_sock_tags <= 0);
2400 tag_ref_entry->num_sock_tags--;
2401 free_tag_ref_from_utd_entry(tag_ref_entry, uid_tag_data_entry);
2403 CT_DEBUG("qtaguid: ctrl_tag(%s): done. ...->f_count=%ld\n",
2404 input, atomic_long_read(&el_socket->file->f_count) - 1);
2405 /* Release the sock_fd that was grabbed by sockfd_lookup(). */
2406 sockfd_put(el_socket);
2410 CT_DEBUG("qtaguid: ctrl_tag(%s): done.\n", input);
2414 static int ctrl_cmd_untag(const char *input)
2418 struct socket *el_socket;
2420 struct sock_tag *sock_tag_entry;
2421 struct tag_ref *tag_ref_entry;
2422 struct uid_tag_data *utd_entry;
2423 struct proc_qtu_data *pqd_entry;
2425 argc = sscanf(input, "%c %d", &cmd, &sock_fd);
2426 CT_DEBUG("qtaguid: ctrl_untag(%s): argc=%d cmd=%c sock_fd=%d\n",
2427 input, argc, cmd, sock_fd);
2432 el_socket = sockfd_lookup(sock_fd, &res); /* This locks the file */
2434 pr_info("qtaguid: ctrl_untag(%s): failed to lookup"
2435 " sock_fd=%d err=%d pid=%u tgid=%u uid=%u\n",
2436 input, sock_fd, res, current->pid, current->tgid,
2440 CT_DEBUG("qtaguid: ctrl_untag(%s): socket->...->f_count=%ld ->sk=%p\n",
2441 input, atomic_long_read(&el_socket->file->f_count),
2443 spin_lock_bh(&sock_tag_list_lock);
2444 sock_tag_entry = get_sock_stat_nl(el_socket->sk);
2445 if (!sock_tag_entry) {
2446 spin_unlock_bh(&sock_tag_list_lock);
2451 * The socket already belongs to the current process
2452 * so it can do whatever it wants to it.
2454 rb_erase(&sock_tag_entry->sock_node, &sock_tag_tree);
2456 tag_ref_entry = lookup_tag_ref(sock_tag_entry->tag, &utd_entry);
2457 BUG_ON(!tag_ref_entry);
2458 BUG_ON(tag_ref_entry->num_sock_tags <= 0);
2459 spin_lock_bh(&uid_tag_data_tree_lock);
2460 pqd_entry = proc_qtu_data_tree_search(
2461 &proc_qtu_data_tree, current->tgid);
2463 * TODO: remove if, and start failing.
2464 * At first, we want to catch user-space code that is not
2465 * opening the /dev/xt_qtaguid.
2467 if (IS_ERR_OR_NULL(pqd_entry))
2468 pr_warn_once("qtaguid: %s(): "
2469 "User space forgot to open /dev/xt_qtaguid? "
2470 "pid=%u tgid=%u uid=%u\n", __func__,
2471 current->pid, current->tgid, current_fsuid());
2473 list_del(&sock_tag_entry->list);
2474 spin_unlock_bh(&uid_tag_data_tree_lock);
2476 * We don't free tag_ref from the utd_entry here,
2477 * only during a cmd_delete().
2479 tag_ref_entry->num_sock_tags--;
2480 spin_unlock_bh(&sock_tag_list_lock);
2482 * Release the sock_fd that was grabbed at tag time,
2483 * and once more for the sockfd_lookup() here.
2485 sockfd_put(sock_tag_entry->socket);
2486 CT_DEBUG("qtaguid: ctrl_untag(%s): done. st@%p ...->f_count=%ld\n",
2487 input, sock_tag_entry,
2488 atomic_long_read(&el_socket->file->f_count) - 1);
2489 sockfd_put(el_socket);
2491 kfree(sock_tag_entry);
2492 atomic64_inc(&qtu_events.sockets_untagged);
2497 CT_DEBUG("qtaguid: ctrl_untag(%s): done. socket->...->f_count=%ld\n",
2498 input, atomic_long_read(&el_socket->file->f_count) - 1);
2499 /* Release the sock_fd that was grabbed by sockfd_lookup(). */
2500 sockfd_put(el_socket);
2504 CT_DEBUG("qtaguid: ctrl_untag(%s): done.\n", input);
2508 static int qtaguid_ctrl_parse(const char *input, int count)
2513 CT_DEBUG("qtaguid: ctrl(%s): pid=%u tgid=%u uid=%u\n",
2514 input, current->pid, current->tgid, current_fsuid());
2517 /* Collect params for commands */
2520 res = ctrl_cmd_delete(input);
2524 res = ctrl_cmd_counter_set(input);
2528 res = ctrl_cmd_tag(input);
2532 res = ctrl_cmd_untag(input);
2542 CT_DEBUG("qtaguid: ctrl(%s): res=%d\n", input, res);
2546 #define MAX_QTAGUID_CTRL_INPUT_LEN 255
2547 static int qtaguid_ctrl_proc_write(struct file *file, const char __user *buffer,
2548 unsigned long count, void *data)
2550 char input_buf[MAX_QTAGUID_CTRL_INPUT_LEN];
2552 if (unlikely(module_passive))
2555 if (count >= MAX_QTAGUID_CTRL_INPUT_LEN)
2558 if (copy_from_user(input_buf, buffer, count))
2561 input_buf[count] = '\0';
2562 return qtaguid_ctrl_parse(input_buf, count);
2565 struct proc_print_info {
2567 char **num_items_returned;
2568 struct iface_stat *iface_entry;
2569 struct tag_stat *ts_entry;
2575 static int pp_stats_line(struct proc_print_info *ppi, int cnt_set)
2578 struct data_counters *cnts;
2580 if (!ppi->item_index) {
2581 if (ppi->item_index++ < ppi->items_to_skip)
2583 len = snprintf(ppi->outp, ppi->char_count,
2584 "idx iface acct_tag_hex uid_tag_int cnt_set "
2585 "rx_bytes rx_packets "
2586 "tx_bytes tx_packets "
2587 "rx_tcp_bytes rx_tcp_packets "
2588 "rx_udp_bytes rx_udp_packets "
2589 "rx_other_bytes rx_other_packets "
2590 "tx_tcp_bytes tx_tcp_packets "
2591 "tx_udp_bytes tx_udp_packets "
2592 "tx_other_bytes tx_other_packets\n");
2594 tag_t tag = ppi->ts_entry->tn.tag;
2595 uid_t stat_uid = get_uid_from_tag(tag);
2596 /* Detailed tags are not available to everybody */
2597 if (get_atag_from_tag(tag)
2598 && !can_read_other_uid_stats(stat_uid)) {
2599 CT_DEBUG("qtaguid: stats line: "
2600 "%s 0x%llx %u: insufficient priv "
2601 "from pid=%u tgid=%u uid=%u stats.gid=%u\n",
2602 ppi->iface_entry->ifname,
2603 get_atag_from_tag(tag), stat_uid,
2604 current->pid, current->tgid, current_fsuid(),
2605 xt_qtaguid_stats_file->gid);
2608 if (ppi->item_index++ < ppi->items_to_skip)
2610 cnts = &ppi->ts_entry->counters;
2612 ppi->outp, ppi->char_count,
2613 "%d %s 0x%llx %u %u "
2623 ppi->iface_entry->ifname,
2624 get_atag_from_tag(tag),
2627 dc_sum_bytes(cnts, cnt_set, IFS_RX),
2628 dc_sum_packets(cnts, cnt_set, IFS_RX),
2629 dc_sum_bytes(cnts, cnt_set, IFS_TX),
2630 dc_sum_packets(cnts, cnt_set, IFS_TX),
2631 cnts->bpc[cnt_set][IFS_RX][IFS_TCP].bytes,
2632 cnts->bpc[cnt_set][IFS_RX][IFS_TCP].packets,
2633 cnts->bpc[cnt_set][IFS_RX][IFS_UDP].bytes,
2634 cnts->bpc[cnt_set][IFS_RX][IFS_UDP].packets,
2635 cnts->bpc[cnt_set][IFS_RX][IFS_PROTO_OTHER].bytes,
2636 cnts->bpc[cnt_set][IFS_RX][IFS_PROTO_OTHER].packets,
2637 cnts->bpc[cnt_set][IFS_TX][IFS_TCP].bytes,
2638 cnts->bpc[cnt_set][IFS_TX][IFS_TCP].packets,
2639 cnts->bpc[cnt_set][IFS_TX][IFS_UDP].bytes,
2640 cnts->bpc[cnt_set][IFS_TX][IFS_UDP].packets,
2641 cnts->bpc[cnt_set][IFS_TX][IFS_PROTO_OTHER].bytes,
2642 cnts->bpc[cnt_set][IFS_TX][IFS_PROTO_OTHER].packets);
2647 static bool pp_sets(struct proc_print_info *ppi)
2651 for (counter_set = 0; counter_set < IFS_MAX_COUNTER_SETS;
2653 len = pp_stats_line(ppi, counter_set);
2654 if (len >= ppi->char_count) {
2660 ppi->char_count -= len;
2661 (*ppi->num_items_returned)++;
2668 * Procfs reader to get all tag stats using style "1)" as described in
2670 * Groups all protocols tx/rx bytes.
2672 static int qtaguid_stats_proc_read(char *page, char **num_items_returned,
2673 off_t items_to_skip, int char_count, int *eof,
2676 struct proc_print_info ppi;
2681 ppi.char_count = char_count;
2682 ppi.num_items_returned = num_items_returned;
2683 ppi.items_to_skip = items_to_skip;
2685 if (unlikely(module_passive)) {
2686 len = pp_stats_line(&ppi, 0);
2687 /* The header should always be shorter than the buffer. */
2688 BUG_ON(len >= ppi.char_count);
2689 (*num_items_returned)++;
2694 CT_DEBUG("qtaguid:proc stats pid=%u tgid=%u uid=%u "
2695 "page=%p *num_items_returned=%p off=%ld "
2696 "char_count=%d *eof=%d\n",
2697 current->pid, current->tgid, current_fsuid(),
2698 page, *num_items_returned,
2699 items_to_skip, char_count, *eof);
2704 /* The idx is there to help debug when things go belly up. */
2705 len = pp_stats_line(&ppi, 0);
2706 /* Don't advance the outp unless the whole line was printed */
2707 if (len >= ppi.char_count) {
2709 return ppi.outp - page;
2713 ppi.char_count -= len;
2714 (*num_items_returned)++;
2717 spin_lock_bh(&iface_stat_list_lock);
2718 list_for_each_entry(ppi.iface_entry, &iface_stat_list, list) {
2719 struct rb_node *node;
2720 spin_lock_bh(&ppi.iface_entry->tag_stat_list_lock);
2721 for (node = rb_first(&ppi.iface_entry->tag_stat_tree);
2723 node = rb_next(node)) {
2724 ppi.ts_entry = rb_entry(node, struct tag_stat, tn.node);
2725 if (!pp_sets(&ppi)) {
2727 &ppi.iface_entry->tag_stat_list_lock);
2728 spin_unlock_bh(&iface_stat_list_lock);
2729 return ppi.outp - page;
2732 spin_unlock_bh(&ppi.iface_entry->tag_stat_list_lock);
2734 spin_unlock_bh(&iface_stat_list_lock);
2737 return ppi.outp - page;
2740 /*------------------------------------------*/
2741 static int qtudev_open(struct inode *inode, struct file *file)
2743 struct uid_tag_data *utd_entry;
2744 struct proc_qtu_data *pqd_entry;
2745 struct proc_qtu_data *new_pqd_entry;
2747 bool utd_entry_found;
2749 if (unlikely(qtu_proc_handling_passive))
2752 DR_DEBUG("qtaguid: qtudev_open(): pid=%u tgid=%u uid=%u\n",
2753 current->pid, current->tgid, current_fsuid());
2755 spin_lock_bh(&uid_tag_data_tree_lock);
2757 /* Look for existing uid data, or alloc one. */
2758 utd_entry = get_uid_data(current_fsuid(), &utd_entry_found);
2759 if (IS_ERR_OR_NULL(utd_entry)) {
2760 res = PTR_ERR(utd_entry);
2764 /* Look for existing PID based proc_data */
2765 pqd_entry = proc_qtu_data_tree_search(&proc_qtu_data_tree,
2768 pr_err("qtaguid: qtudev_open(): %u/%u %u "
2769 "%s already opened\n",
2770 current->pid, current->tgid, current_fsuid(),
2773 goto err_unlock_free_utd;
2776 new_pqd_entry = kzalloc(sizeof(*new_pqd_entry), GFP_ATOMIC);
2777 if (!new_pqd_entry) {
2778 pr_err("qtaguid: qtudev_open(): %u/%u %u: "
2779 "proc data alloc failed\n",
2780 current->pid, current->tgid, current_fsuid());
2782 goto err_unlock_free_utd;
2784 new_pqd_entry->pid = current->tgid;
2785 INIT_LIST_HEAD(&new_pqd_entry->sock_tag_list);
2786 new_pqd_entry->parent_tag_data = utd_entry;
2787 utd_entry->num_pqd++;
2789 proc_qtu_data_tree_insert(new_pqd_entry,
2790 &proc_qtu_data_tree);
2792 spin_unlock_bh(&uid_tag_data_tree_lock);
2793 DR_DEBUG("qtaguid: tracking data for uid=%u in pqd=%p\n",
2794 current_fsuid(), new_pqd_entry);
2795 file->private_data = new_pqd_entry;
2798 err_unlock_free_utd:
2799 if (!utd_entry_found) {
2800 rb_erase(&utd_entry->node, &uid_tag_data_tree);
2804 spin_unlock_bh(&uid_tag_data_tree_lock);
2808 static int qtudev_release(struct inode *inode, struct file *file)
2810 struct proc_qtu_data *pqd_entry = file->private_data;
2811 struct uid_tag_data *utd_entry = pqd_entry->parent_tag_data;
2812 struct sock_tag *st_entry;
2813 struct rb_root st_to_free_tree = RB_ROOT;
2814 struct list_head *entry, *next;
2817 if (unlikely(qtu_proc_handling_passive))
2821 * Do not trust the current->pid, it might just be a kworker cleaning
2822 * up after a dead proc.
2824 DR_DEBUG("qtaguid: qtudev_release(): "
2825 "pid=%u tgid=%u uid=%u "
2826 "pqd_entry=%p->pid=%u utd_entry=%p->active_tags=%d\n",
2827 current->pid, current->tgid, pqd_entry->parent_tag_data->uid,
2828 pqd_entry, pqd_entry->pid, utd_entry,
2829 utd_entry->num_active_tags);
2831 spin_lock_bh(&sock_tag_list_lock);
2832 spin_lock_bh(&uid_tag_data_tree_lock);
2834 list_for_each_safe(entry, next, &pqd_entry->sock_tag_list) {
2835 st_entry = list_entry(entry, struct sock_tag, list);
2836 DR_DEBUG("qtaguid: %s(): "
2837 "erase sock_tag=%p->sk=%p pid=%u tgid=%u uid=%u\n",
2839 st_entry, st_entry->sk,
2840 current->pid, current->tgid,
2841 pqd_entry->parent_tag_data->uid);
2843 utd_entry = uid_tag_data_tree_search(
2845 get_uid_from_tag(st_entry->tag));
2846 BUG_ON(IS_ERR_OR_NULL(utd_entry));
2847 DR_DEBUG("qtaguid: %s(): "
2848 "looking for tag=0x%llx in utd_entry=%p\n", __func__,
2849 st_entry->tag, utd_entry);
2850 tr = tag_ref_tree_search(&utd_entry->tag_ref_tree,
2853 BUG_ON(tr->num_sock_tags <= 0);
2854 tr->num_sock_tags--;
2855 free_tag_ref_from_utd_entry(tr, utd_entry);
2857 rb_erase(&st_entry->sock_node, &sock_tag_tree);
2858 list_del(&st_entry->list);
2859 /* Can't sockfd_put() within spinlock, do it later. */
2860 sock_tag_tree_insert(st_entry, &st_to_free_tree);
2863 * Try to free the utd_entry if no other proc_qtu_data is
2864 * using it (num_pqd is 0) and it doesn't have active tags
2865 * (num_active_tags is 0).
2867 put_utd_entry(utd_entry);
2870 rb_erase(&pqd_entry->node, &proc_qtu_data_tree);
2871 BUG_ON(pqd_entry->parent_tag_data->num_pqd < 1);
2872 pqd_entry->parent_tag_data->num_pqd--;
2873 put_utd_entry(pqd_entry->parent_tag_data);
2875 file->private_data = NULL;
2877 spin_unlock_bh(&uid_tag_data_tree_lock);
2878 spin_unlock_bh(&sock_tag_list_lock);
2881 sock_tag_tree_erase(&st_to_free_tree);
2883 prdebug_full_state(0, "%s(): pid=%u tgid=%u", __func__,
2884 current->pid, current->tgid);
2888 /*------------------------------------------*/
2889 static const struct file_operations qtudev_fops = {
2890 .owner = THIS_MODULE,
2891 .open = qtudev_open,
2892 .release = qtudev_release,
2895 static struct miscdevice qtu_device = {
2896 .minor = MISC_DYNAMIC_MINOR,
2897 .name = QTU_DEV_NAME,
2898 .fops = &qtudev_fops,
2899 /* How sad it doesn't allow for defaults: .mode = S_IRUGO | S_IWUSR */
2902 /*------------------------------------------*/
2903 static int __init qtaguid_proc_register(struct proc_dir_entry **res_procdir)
2906 *res_procdir = proc_mkdir(module_procdirname, init_net.proc_net);
2907 if (!*res_procdir) {
2908 pr_err("qtaguid: failed to create proc/.../xt_qtaguid\n");
2913 xt_qtaguid_ctrl_file = create_proc_entry("ctrl", proc_ctrl_perms,
2915 if (!xt_qtaguid_ctrl_file) {
2916 pr_err("qtaguid: failed to create xt_qtaguid/ctrl "
2921 xt_qtaguid_ctrl_file->read_proc = qtaguid_ctrl_proc_read;
2922 xt_qtaguid_ctrl_file->write_proc = qtaguid_ctrl_proc_write;
2924 xt_qtaguid_stats_file = create_proc_entry("stats", proc_stats_perms,
2926 if (!xt_qtaguid_stats_file) {
2927 pr_err("qtaguid: failed to create xt_qtaguid/stats "
2930 goto no_stats_entry;
2932 xt_qtaguid_stats_file->read_proc = qtaguid_stats_proc_read;
2934 * TODO: add support counter hacking
2935 * xt_qtaguid_stats_file->write_proc = qtaguid_stats_proc_write;
2940 remove_proc_entry("ctrl", *res_procdir);
2942 remove_proc_entry("xt_qtaguid", NULL);
2947 static struct xt_match qtaguid_mt_reg __read_mostly = {
2949 * This module masquerades as the "owner" module so that iptables
2950 * tools can deal with it.
2954 .family = NFPROTO_UNSPEC,
2955 .match = qtaguid_mt,
2956 .matchsize = sizeof(struct xt_qtaguid_match_info),
2960 static int __init qtaguid_mt_init(void)
2962 if (qtaguid_proc_register(&xt_qtaguid_procdir)
2963 || iface_stat_init(xt_qtaguid_procdir)
2964 || xt_register_match(&qtaguid_mt_reg)
2965 || misc_register(&qtu_device))
2971 * TODO: allow unloading of the module.
2972 * For now stats are permanent.
2973 * Kconfig forces'y/n' and never an 'm'.
2976 module_init(qtaguid_mt_init);
2977 MODULE_AUTHOR("jpa <jpa@google.com>");
2978 MODULE_DESCRIPTION("Xtables: socket owner+tag matching and associated stats");
2979 MODULE_LICENSE("GPL");
2980 MODULE_ALIAS("ipt_owner");
2981 MODULE_ALIAS("ip6t_owner");
2982 MODULE_ALIAS("ipt_qtaguid");
2983 MODULE_ALIAS("ip6t_qtaguid");