battery: sec_battery: export {CURRENT/VOLTAGE}_MAX to sysfs
[GitHub/LineageOS/android_kernel_samsung_universal7580.git] / drivers / net / tun.c
1 /*
2 * TUN - Universal TUN/TAP device driver.
3 * Copyright (C) 1999-2002 Maxim Krasnyansky <maxk@qualcomm.com>
4 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * $Id: tun.c,v 1.15 2002/03/01 02:44:24 maxk Exp $
17 */
18
19 /*
20 * Changes:
21 *
22 * Mike Kershaw <dragorn@kismetwireless.net> 2005/08/14
23 * Add TUNSETLINK ioctl to set the link encapsulation
24 *
25 * Mark Smith <markzzzsmith@yahoo.com.au>
26 * Use eth_random_addr() for tap MAC address.
27 *
28 * Harald Roelle <harald.roelle@ifi.lmu.de> 2004/04/20
29 * Fixes in packet dropping, queue length setting and queue wakeup.
30 * Increased default tx queue length.
31 * Added ethtool API.
32 * Minor cleanups
33 *
34 * Daniel Podlejski <underley@underley.eu.org>
35 * Modifications for 2.3.99-pre5 kernel.
36 */
37 /*
38 * Changes:
39 * KwnagHyun Kim <kh0304.kim@samsung.com> 2015/07/08
40 * Baesung Park <baesung.park@samsung.com> 2015/07/08
41 * Vignesh Saravanaperumal <vignesh1.s@samsung.com> 2015/07/08
42 * Add codes to share UID/PID information
43 *
44 */
45
46 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
47
48 #define DRV_NAME "tun"
49 #define DRV_VERSION "1.6"
50 #define DRV_DESCRIPTION "Universal TUN/TAP device driver"
51 #define DRV_COPYRIGHT "(C) 1999-2004 Max Krasnyansky <maxk@qualcomm.com>"
52
53 #include <linux/module.h>
54 #include <linux/errno.h>
55 #include <linux/kernel.h>
56 #include <linux/major.h>
57 #include <linux/slab.h>
58 #include <linux/poll.h>
59 #include <linux/fcntl.h>
60 #include <linux/init.h>
61 #include <linux/skbuff.h>
62 #include <linux/netdevice.h>
63 #include <linux/etherdevice.h>
64 #include <linux/miscdevice.h>
65 #include <linux/ethtool.h>
66 #include <linux/rtnetlink.h>
67 #include <linux/compat.h>
68 #include <linux/if.h>
69 #include <linux/if_arp.h>
70 #include <linux/if_ether.h>
71 #include <linux/if_tun.h>
72 #include <linux/crc32.h>
73 #include <linux/nsproxy.h>
74 #include <linux/virtio_net.h>
75 #include <linux/rcupdate.h>
76 #include <net/net_namespace.h>
77 #include <net/netns/generic.h>
78 #include <net/rtnetlink.h>
79 #include <net/sock.h>
80 // ------------- START of KNOX_VPN ------------------//
81 #include <linux/types.h>
82 #include <linux/udp.h>
83 #include <linux/tcp.h>
84 #include <linux/ip.h>
85 #include <net/ip.h>
86
87 #define META_MARK_BASE_LOWER 100
88 #define META_MARK_BASE_UPPER 500
89 // ------------- END of KNOX_VPN -------------------//
90
91 #include <asm/uaccess.h>
92
93 /* Uncomment to enable debugging */
94 /* #define TUN_DEBUG 1 */
95
96 #ifdef TUN_DEBUG
97 static int debug;
98
99 #define tun_debug(level, tun, fmt, args...) \
100 do { \
101 if (tun->debug) \
102 netdev_printk(level, tun->dev, fmt, ##args); \
103 } while (0)
104 #define DBG1(level, fmt, args...) \
105 do { \
106 if (debug == 2) \
107 printk(level fmt, ##args); \
108 } while (0)
109 #else
110 #define tun_debug(level, tun, fmt, args...) \
111 do { \
112 if (0) \
113 netdev_printk(level, tun->dev, fmt, ##args); \
114 } while (0)
115 #define DBG1(level, fmt, args...) \
116 do { \
117 if (0) \
118 printk(level fmt, ##args); \
119 } while (0)
120 #endif
121
122 // ------------- START of KNOX_VPN ------------------//
123 /* The KNOX framework marks packets intended to a VPN client for special processing differently.
124 * The marked packets hit special IP table rules and are routed back to user space using the TUN driver
125 * for policy based treatment by the VPN client.
126 * Some VPN clients can make more intelligent decisions based on the UID/PID information.
127 * For such clients, we mark packets to be in the range >= META_MARK_BASE_LOWER and < META_MARK_BASE_UPPER.
128 * When such packets are seen, we update the IP headers to carry UID/PID information
129 * in the IP options - all other packets are ignored.
130 * Also, see the comments above the individual steps taken in the code for details
131 */
132
133 /* Metadata header structure */
134
135 struct knox_meta_param {
136 uid_t uid;
137 pid_t pid;
138 };
139
140 #define TUN_META_HDR_SZ sizeof(struct knox_meta_param)
141 #define TUN_META_MARK_OFFSET offsetof(struct knox_meta_param, uid)
142 // ------------- END of KNOX_VPN -------------------//
143
144 #define GOODCOPY_LEN 128
145
146 #define FLT_EXACT_COUNT 8
147 struct tap_filter {
148 unsigned int count; /* Number of addrs. Zero means disabled */
149 u32 mask[2]; /* Mask of the hashed addrs */
150 unsigned char addr[FLT_EXACT_COUNT][ETH_ALEN];
151 };
152
153 /* DEFAULT_MAX_NUM_RSS_QUEUES were choosed to let the rx/tx queues allocated for
154 * the netdevice to be fit in one page. So we can make sure the success of
155 * memory allocation. TODO: increase the limit. */
156 #define MAX_TAP_QUEUES DEFAULT_MAX_NUM_RSS_QUEUES
157 #define MAX_TAP_FLOWS 4096
158
159 #define TUN_FLOW_EXPIRE (3 * HZ)
160
161 /* A tun_file connects an open character device to a tuntap netdevice. It
162 * also contains all socket related strctures (except sock_fprog and tap_filter)
163 * to serve as one transmit queue for tuntap device. The sock_fprog and
164 * tap_filter were kept in tun_struct since they were used for filtering for the
165 * netdevice not for a specific queue (at least I didn't see the requirement for
166 * this).
167 *
168 * RCU usage:
169 * The tun_file and tun_struct are loosely coupled, the pointer from one to the
170 * other can only be read while rcu_read_lock or rtnl_lock is held.
171 */
172 struct tun_file {
173 struct sock sk;
174 struct socket socket;
175 struct socket_wq wq;
176 struct tun_struct __rcu *tun;
177 struct net *net;
178 struct fasync_struct *fasync;
179 /* only used for fasnyc */
180 unsigned int flags;
181 u16 queue_index;
182 struct list_head next;
183 struct tun_struct *detached;
184 };
185
186 struct tun_flow_entry {
187 struct hlist_node hash_link;
188 struct rcu_head rcu;
189 struct tun_struct *tun;
190
191 u32 rxhash;
192 int queue_index;
193 unsigned long updated;
194 };
195
196 #define TUN_NUM_FLOW_ENTRIES 1024
197
198 /* Since the socket were moved to tun_file, to preserve the behavior of persist
199 * device, socket filter, sndbuf and vnet header size were restore when the
200 * file were attached to a persist device.
201 */
202 struct tun_struct {
203 struct tun_file __rcu *tfiles[MAX_TAP_QUEUES];
204 unsigned int numqueues;
205 unsigned int flags;
206 kuid_t owner;
207 kgid_t group;
208
209 struct net_device *dev;
210 netdev_features_t set_features;
211 #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
212 NETIF_F_TSO6|NETIF_F_UFO)
213
214 int vnet_hdr_sz;
215 int sndbuf;
216 struct tap_filter txflt;
217 struct sock_fprog fprog;
218 /* protected by rtnl lock */
219 bool filter_attached;
220 #ifdef TUN_DEBUG
221 int debug;
222 #endif
223 spinlock_t lock;
224 struct hlist_head flows[TUN_NUM_FLOW_ENTRIES];
225 struct timer_list flow_gc_timer;
226 unsigned long ageing_time;
227 unsigned int numdisabled;
228 struct list_head disabled;
229 void *security;
230 u32 flow_count;
231 };
232
233 static inline u32 tun_hashfn(u32 rxhash)
234 {
235 return rxhash & 0x3ff;
236 }
237
238 static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash)
239 {
240 struct tun_flow_entry *e;
241
242 hlist_for_each_entry_rcu(e, head, hash_link) {
243 if (e->rxhash == rxhash)
244 return e;
245 }
246 return NULL;
247 }
248
249 static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun,
250 struct hlist_head *head,
251 u32 rxhash, u16 queue_index)
252 {
253 struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC);
254
255 if (e) {
256 tun_debug(KERN_INFO, tun, "create flow: hash %u index %u\n",
257 rxhash, queue_index);
258 e->updated = jiffies;
259 e->rxhash = rxhash;
260 e->queue_index = queue_index;
261 e->tun = tun;
262 hlist_add_head_rcu(&e->hash_link, head);
263 ++tun->flow_count;
264 }
265 return e;
266 }
267
268 static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e)
269 {
270 tun_debug(KERN_INFO, tun, "delete flow: hash %u index %u\n",
271 e->rxhash, e->queue_index);
272 hlist_del_rcu(&e->hash_link);
273 kfree_rcu(e, rcu);
274 --tun->flow_count;
275 }
276
277 static void tun_flow_flush(struct tun_struct *tun)
278 {
279 int i;
280
281 spin_lock_bh(&tun->lock);
282 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
283 struct tun_flow_entry *e;
284 struct hlist_node *n;
285
286 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link)
287 tun_flow_delete(tun, e);
288 }
289 spin_unlock_bh(&tun->lock);
290 }
291
292 static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index)
293 {
294 int i;
295
296 spin_lock_bh(&tun->lock);
297 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
298 struct tun_flow_entry *e;
299 struct hlist_node *n;
300
301 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
302 if (e->queue_index == queue_index)
303 tun_flow_delete(tun, e);
304 }
305 }
306 spin_unlock_bh(&tun->lock);
307 }
308
309 static void tun_flow_cleanup(unsigned long data)
310 {
311 struct tun_struct *tun = (struct tun_struct *)data;
312 unsigned long delay = tun->ageing_time;
313 unsigned long next_timer = jiffies + delay;
314 unsigned long count = 0;
315 int i;
316
317 tun_debug(KERN_INFO, tun, "tun_flow_cleanup\n");
318
319 spin_lock_bh(&tun->lock);
320 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
321 struct tun_flow_entry *e;
322 struct hlist_node *n;
323
324 hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
325 unsigned long this_timer;
326 count++;
327 this_timer = e->updated + delay;
328 if (time_before_eq(this_timer, jiffies))
329 tun_flow_delete(tun, e);
330 else if (time_before(this_timer, next_timer))
331 next_timer = this_timer;
332 }
333 }
334
335 if (count)
336 mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer));
337 spin_unlock_bh(&tun->lock);
338 }
339
340 static void tun_flow_update(struct tun_struct *tun, u32 rxhash,
341 struct tun_file *tfile)
342 {
343 struct hlist_head *head;
344 struct tun_flow_entry *e;
345 unsigned long delay = tun->ageing_time;
346 u16 queue_index = tfile->queue_index;
347
348 if (!rxhash)
349 return;
350 else
351 head = &tun->flows[tun_hashfn(rxhash)];
352
353 rcu_read_lock();
354
355 /* We may get a very small possibility of OOO during switching, not
356 * worth to optimize.*/
357 if (tun->numqueues == 1 || tfile->detached)
358 goto unlock;
359
360 e = tun_flow_find(head, rxhash);
361 if (likely(e)) {
362 /* TODO: keep queueing to old queue until it's empty? */
363 e->queue_index = queue_index;
364 e->updated = jiffies;
365 } else {
366 spin_lock_bh(&tun->lock);
367 if (!tun_flow_find(head, rxhash) &&
368 tun->flow_count < MAX_TAP_FLOWS)
369 tun_flow_create(tun, head, rxhash, queue_index);
370
371 if (!timer_pending(&tun->flow_gc_timer))
372 mod_timer(&tun->flow_gc_timer,
373 round_jiffies_up(jiffies + delay));
374 spin_unlock_bh(&tun->lock);
375 }
376
377 unlock:
378 rcu_read_unlock();
379 }
380
381 /* We try to identify a flow through its rxhash first. The reason that
382 * we do not check rxq no. is becuase some cards(e.g 82599), chooses
383 * the rxq based on the txq where the last packet of the flow comes. As
384 * the userspace application move between processors, we may get a
385 * different rxq no. here. If we could not get rxhash, then we would
386 * hope the rxq no. may help here.
387 */
388 static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb)
389 {
390 struct tun_struct *tun = netdev_priv(dev);
391 struct tun_flow_entry *e;
392 u32 txq = 0;
393 u32 numqueues = 0;
394
395 rcu_read_lock();
396 numqueues = ACCESS_ONCE(tun->numqueues);
397
398 txq = skb_get_rxhash(skb);
399 if (txq) {
400 e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq);
401 if (e)
402 txq = e->queue_index;
403 else
404 /* use multiply and shift instead of expensive divide */
405 txq = ((u64)txq * numqueues) >> 32;
406 } else if (likely(skb_rx_queue_recorded(skb))) {
407 txq = skb_get_rx_queue(skb);
408 while (unlikely(txq >= numqueues))
409 txq -= numqueues;
410 }
411
412 rcu_read_unlock();
413 return txq;
414 }
415
416 static inline bool tun_not_capable(struct tun_struct *tun)
417 {
418 const struct cred *cred = current_cred();
419 struct net *net = dev_net(tun->dev);
420
421 return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) ||
422 (gid_valid(tun->group) && !in_egroup_p(tun->group))) &&
423 !ns_capable(net->user_ns, CAP_NET_ADMIN);
424 }
425
426 static void tun_set_real_num_queues(struct tun_struct *tun)
427 {
428 netif_set_real_num_tx_queues(tun->dev, tun->numqueues);
429 netif_set_real_num_rx_queues(tun->dev, tun->numqueues);
430 }
431
432 static void tun_disable_queue(struct tun_struct *tun, struct tun_file *tfile)
433 {
434 tfile->detached = tun;
435 list_add_tail(&tfile->next, &tun->disabled);
436 ++tun->numdisabled;
437 }
438
439 static struct tun_struct *tun_enable_queue(struct tun_file *tfile)
440 {
441 struct tun_struct *tun = tfile->detached;
442
443 tfile->detached = NULL;
444 list_del_init(&tfile->next);
445 --tun->numdisabled;
446 return tun;
447 }
448
449 static void __tun_detach(struct tun_file *tfile, bool clean)
450 {
451 struct tun_file *ntfile;
452 struct tun_struct *tun;
453
454 tun = rtnl_dereference(tfile->tun);
455
456 if (tun && !tfile->detached) {
457 u16 index = tfile->queue_index;
458 BUG_ON(index >= tun->numqueues);
459
460 rcu_assign_pointer(tun->tfiles[index],
461 tun->tfiles[tun->numqueues - 1]);
462 ntfile = rtnl_dereference(tun->tfiles[index]);
463 ntfile->queue_index = index;
464
465 --tun->numqueues;
466 if (clean) {
467 rcu_assign_pointer(tfile->tun, NULL);
468 sock_put(&tfile->sk);
469 } else
470 tun_disable_queue(tun, tfile);
471
472 synchronize_net();
473 tun_flow_delete_by_queue(tun, tun->numqueues + 1);
474 /* Drop read queue */
475 skb_queue_purge(&tfile->sk.sk_receive_queue);
476 tun_set_real_num_queues(tun);
477 } else if (tfile->detached && clean) {
478 tun = tun_enable_queue(tfile);
479 sock_put(&tfile->sk);
480 }
481
482 if (clean) {
483 if (tun && tun->numqueues == 0 && tun->numdisabled == 0) {
484 netif_carrier_off(tun->dev);
485
486 if (!(tun->flags & TUN_PERSIST) &&
487 tun->dev->reg_state == NETREG_REGISTERED)
488 unregister_netdevice(tun->dev);
489 }
490
491 BUG_ON(!test_bit(SOCK_EXTERNALLY_ALLOCATED,
492 &tfile->socket.flags));
493 sk_release_kernel(&tfile->sk);
494 }
495 }
496
497 static void tun_detach(struct tun_file *tfile, bool clean)
498 {
499 rtnl_lock();
500 __tun_detach(tfile, clean);
501 rtnl_unlock();
502 }
503
504 static void tun_detach_all(struct net_device *dev)
505 {
506 struct tun_struct *tun = netdev_priv(dev);
507 struct tun_file *tfile, *tmp;
508 int i, n = tun->numqueues;
509
510 for (i = 0; i < n; i++) {
511 tfile = rtnl_dereference(tun->tfiles[i]);
512 BUG_ON(!tfile);
513 wake_up_all(&tfile->wq.wait);
514 rcu_assign_pointer(tfile->tun, NULL);
515 --tun->numqueues;
516 }
517 list_for_each_entry(tfile, &tun->disabled, next) {
518 wake_up_all(&tfile->wq.wait);
519 rcu_assign_pointer(tfile->tun, NULL);
520 }
521 BUG_ON(tun->numqueues != 0);
522
523 synchronize_net();
524 for (i = 0; i < n; i++) {
525 tfile = rtnl_dereference(tun->tfiles[i]);
526 /* Drop read queue */
527 skb_queue_purge(&tfile->sk.sk_receive_queue);
528 sock_put(&tfile->sk);
529 }
530 list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) {
531 tun_enable_queue(tfile);
532 skb_queue_purge(&tfile->sk.sk_receive_queue);
533 sock_put(&tfile->sk);
534 }
535 BUG_ON(tun->numdisabled != 0);
536
537 if (tun->flags & TUN_PERSIST)
538 module_put(THIS_MODULE);
539 }
540
541 static int tun_attach(struct tun_struct *tun, struct file *file)
542 {
543 struct tun_file *tfile = file->private_data;
544 int err;
545
546 err = security_tun_dev_attach(tfile->socket.sk, tun->security);
547 if (err < 0)
548 goto out;
549
550 err = -EINVAL;
551 if (rtnl_dereference(tfile->tun) && !tfile->detached)
552 goto out;
553
554 err = -EBUSY;
555 if (!(tun->flags & TUN_TAP_MQ) && tun->numqueues == 1)
556 goto out;
557
558 err = -E2BIG;
559 if (!tfile->detached &&
560 tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES)
561 goto out;
562
563 err = 0;
564
565 /* Re-attach the filter to presist device */
566 if (tun->filter_attached == true) {
567 err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
568 if (!err)
569 goto out;
570 }
571 tfile->queue_index = tun->numqueues;
572 rcu_assign_pointer(tfile->tun, tun);
573 rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile);
574 tun->numqueues++;
575
576 if (tfile->detached)
577 tun_enable_queue(tfile);
578 else
579 sock_hold(&tfile->sk);
580
581 tun_set_real_num_queues(tun);
582
583 /* device is allowed to go away first, so no need to hold extra
584 * refcnt.
585 */
586
587 out:
588 return err;
589 }
590
591 static struct tun_struct *__tun_get(struct tun_file *tfile)
592 {
593 struct tun_struct *tun;
594
595 rcu_read_lock();
596 tun = rcu_dereference(tfile->tun);
597 if (tun)
598 dev_hold(tun->dev);
599 rcu_read_unlock();
600
601 return tun;
602 }
603
604 static struct tun_struct *tun_get(struct file *file)
605 {
606 return __tun_get(file->private_data);
607 }
608
609 static void tun_put(struct tun_struct *tun)
610 {
611 dev_put(tun->dev);
612 }
613
614 /* TAP filtering */
615 static void addr_hash_set(u32 *mask, const u8 *addr)
616 {
617 int n = ether_crc(ETH_ALEN, addr) >> 26;
618 mask[n >> 5] |= (1 << (n & 31));
619 }
620
621 static unsigned int addr_hash_test(const u32 *mask, const u8 *addr)
622 {
623 int n = ether_crc(ETH_ALEN, addr) >> 26;
624 return mask[n >> 5] & (1 << (n & 31));
625 }
626
627 static int update_filter(struct tap_filter *filter, void __user *arg)
628 {
629 struct { u8 u[ETH_ALEN]; } *addr;
630 struct tun_filter uf;
631 int err, alen, n, nexact;
632
633 if (copy_from_user(&uf, arg, sizeof(uf)))
634 return -EFAULT;
635
636 if (!uf.count) {
637 /* Disabled */
638 filter->count = 0;
639 return 0;
640 }
641
642 alen = ETH_ALEN * uf.count;
643 addr = kmalloc(alen, GFP_KERNEL);
644 if (!addr)
645 return -ENOMEM;
646
647 if (copy_from_user(addr, arg + sizeof(uf), alen)) {
648 err = -EFAULT;
649 goto done;
650 }
651
652 /* The filter is updated without holding any locks. Which is
653 * perfectly safe. We disable it first and in the worst
654 * case we'll accept a few undesired packets. */
655 filter->count = 0;
656 wmb();
657
658 /* Use first set of addresses as an exact filter */
659 for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
660 memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
661
662 nexact = n;
663
664 /* Remaining multicast addresses are hashed,
665 * unicast will leave the filter disabled. */
666 memset(filter->mask, 0, sizeof(filter->mask));
667 for (; n < uf.count; n++) {
668 if (!is_multicast_ether_addr(addr[n].u)) {
669 err = 0; /* no filter */
670 goto done;
671 }
672 addr_hash_set(filter->mask, addr[n].u);
673 }
674
675 /* For ALLMULTI just set the mask to all ones.
676 * This overrides the mask populated above. */
677 if ((uf.flags & TUN_FLT_ALLMULTI))
678 memset(filter->mask, ~0, sizeof(filter->mask));
679
680 /* Now enable the filter */
681 wmb();
682 filter->count = nexact;
683
684 /* Return the number of exact filters */
685 err = nexact;
686
687 done:
688 kfree(addr);
689 return err;
690 }
691
692 /* Returns: 0 - drop, !=0 - accept */
693 static int run_filter(struct tap_filter *filter, const struct sk_buff *skb)
694 {
695 /* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
696 * at this point. */
697 struct ethhdr *eh = (struct ethhdr *) skb->data;
698 int i;
699
700 /* Exact match */
701 for (i = 0; i < filter->count; i++)
702 if (ether_addr_equal(eh->h_dest, filter->addr[i]))
703 return 1;
704
705 /* Inexact match (multicast only) */
706 if (is_multicast_ether_addr(eh->h_dest))
707 return addr_hash_test(filter->mask, eh->h_dest);
708
709 return 0;
710 }
711
712 /*
713 * Checks whether the packet is accepted or not.
714 * Returns: 0 - drop, !=0 - accept
715 */
716 static int check_filter(struct tap_filter *filter, const struct sk_buff *skb)
717 {
718 if (!filter->count)
719 return 1;
720
721 return run_filter(filter, skb);
722 }
723
724 /* Network device part of the driver */
725
726 static const struct ethtool_ops tun_ethtool_ops;
727
728 /* Net device detach from fd. */
729 static void tun_net_uninit(struct net_device *dev)
730 {
731 tun_detach_all(dev);
732 }
733
734 /* Net device open. */
735 static int tun_net_open(struct net_device *dev)
736 {
737 netif_tx_start_all_queues(dev);
738 return 0;
739 }
740
741 /* Net device close. */
742 static int tun_net_close(struct net_device *dev)
743 {
744 netif_tx_stop_all_queues(dev);
745 return 0;
746 }
747
748 /* Net device start xmit */
749 static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)
750 {
751 struct tun_struct *tun = netdev_priv(dev);
752 int txq = skb->queue_mapping;
753 struct tun_file *tfile;
754
755 rcu_read_lock();
756 tfile = rcu_dereference(tun->tfiles[txq]);
757
758 /* Drop packet if interface is not attached */
759 if (txq >= tun->numqueues)
760 goto drop;
761
762 tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len);
763
764 BUG_ON(!tfile);
765
766 /* Drop if the filter does not like it.
767 * This is a noop if the filter is disabled.
768 * Filter can be enabled only for the TAP devices. */
769 if (!check_filter(&tun->txflt, skb))
770 goto drop;
771
772 if (tfile->socket.sk->sk_filter &&
773 sk_filter(tfile->socket.sk, skb))
774 goto drop;
775
776 /* Limit the number of packets queued by dividing txq length with the
777 * number of queues.
778 */
779 if (skb_queue_len(&tfile->socket.sk->sk_receive_queue)
780 >= dev->tx_queue_len / tun->numqueues)
781 goto drop;
782
783 /* Orphan the skb - required as we might hang on to it
784 * for indefinite time. */
785 if (unlikely(skb_orphan_frags(skb, GFP_ATOMIC)))
786 goto drop;
787 skb_orphan(skb);
788
789 nf_reset(skb);
790
791 /* Enqueue packet */
792 skb_queue_tail(&tfile->socket.sk->sk_receive_queue, skb);
793
794 /* Notify and wake up reader process */
795 if (tfile->flags & TUN_FASYNC)
796 kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
797 wake_up_interruptible_poll(&tfile->wq.wait, POLLIN |
798 POLLRDNORM | POLLRDBAND);
799
800 rcu_read_unlock();
801 return NETDEV_TX_OK;
802
803 drop:
804 dev->stats.tx_dropped++;
805 skb_tx_error(skb);
806 kfree_skb(skb);
807 rcu_read_unlock();
808 return NETDEV_TX_OK;
809 }
810
811 static void tun_net_mclist(struct net_device *dev)
812 {
813 /*
814 * This callback is supposed to deal with mc filter in
815 * _rx_ path and has nothing to do with the _tx_ path.
816 * In rx path we always accept everything userspace gives us.
817 */
818 }
819
820 #define MIN_MTU 68
821 #define MAX_MTU 65535
822
823 static int
824 tun_net_change_mtu(struct net_device *dev, int new_mtu)
825 {
826 if (new_mtu < MIN_MTU || new_mtu + dev->hard_header_len > MAX_MTU)
827 return -EINVAL;
828 dev->mtu = new_mtu;
829 return 0;
830 }
831
832 static netdev_features_t tun_net_fix_features(struct net_device *dev,
833 netdev_features_t features)
834 {
835 struct tun_struct *tun = netdev_priv(dev);
836
837 return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
838 }
839 #ifdef CONFIG_NET_POLL_CONTROLLER
840 static void tun_poll_controller(struct net_device *dev)
841 {
842 /*
843 * Tun only receives frames when:
844 * 1) the char device endpoint gets data from user space
845 * 2) the tun socket gets a sendmsg call from user space
846 * Since both of those are syncronous operations, we are guaranteed
847 * never to have pending data when we poll for it
848 * so theres nothing to do here but return.
849 * We need this though so netpoll recognizes us as an interface that
850 * supports polling, which enables bridge devices in virt setups to
851 * still use netconsole
852 */
853 return;
854 }
855 #endif
856 static const struct net_device_ops tun_netdev_ops = {
857 .ndo_uninit = tun_net_uninit,
858 .ndo_open = tun_net_open,
859 .ndo_stop = tun_net_close,
860 .ndo_start_xmit = tun_net_xmit,
861 .ndo_change_mtu = tun_net_change_mtu,
862 .ndo_fix_features = tun_net_fix_features,
863 .ndo_select_queue = tun_select_queue,
864 #ifdef CONFIG_NET_POLL_CONTROLLER
865 .ndo_poll_controller = tun_poll_controller,
866 #endif
867 };
868
869 static const struct net_device_ops tap_netdev_ops = {
870 .ndo_uninit = tun_net_uninit,
871 .ndo_open = tun_net_open,
872 .ndo_stop = tun_net_close,
873 .ndo_start_xmit = tun_net_xmit,
874 .ndo_change_mtu = tun_net_change_mtu,
875 .ndo_fix_features = tun_net_fix_features,
876 .ndo_set_rx_mode = tun_net_mclist,
877 .ndo_set_mac_address = eth_mac_addr,
878 .ndo_validate_addr = eth_validate_addr,
879 .ndo_select_queue = tun_select_queue,
880 #ifdef CONFIG_NET_POLL_CONTROLLER
881 .ndo_poll_controller = tun_poll_controller,
882 #endif
883 };
884
885 static int tun_flow_init(struct tun_struct *tun)
886 {
887 int i;
888
889 for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++)
890 INIT_HLIST_HEAD(&tun->flows[i]);
891
892 tun->ageing_time = TUN_FLOW_EXPIRE;
893 setup_timer(&tun->flow_gc_timer, tun_flow_cleanup, (unsigned long)tun);
894 mod_timer(&tun->flow_gc_timer,
895 round_jiffies_up(jiffies + tun->ageing_time));
896
897 return 0;
898 }
899
900 static void tun_flow_uninit(struct tun_struct *tun)
901 {
902 del_timer_sync(&tun->flow_gc_timer);
903 tun_flow_flush(tun);
904 }
905
906 /* Initialize net device. */
907 static void tun_net_init(struct net_device *dev)
908 {
909 struct tun_struct *tun = netdev_priv(dev);
910
911 switch (tun->flags & TUN_TYPE_MASK) {
912 case TUN_TUN_DEV:
913 dev->netdev_ops = &tun_netdev_ops;
914
915 /* Point-to-Point TUN Device */
916 dev->hard_header_len = 0;
917 dev->addr_len = 0;
918 dev->mtu = 1500;
919
920 /* Zero header length */
921 dev->type = ARPHRD_NONE;
922 dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
923 dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */
924 break;
925
926 case TUN_TAP_DEV:
927 dev->netdev_ops = &tap_netdev_ops;
928 /* Ethernet TAP Device */
929 ether_setup(dev);
930 dev->priv_flags &= ~IFF_TX_SKB_SHARING;
931 dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
932
933 eth_hw_addr_random(dev);
934
935 dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */
936 break;
937 }
938 }
939
940 /* Character device part */
941
942 /* Poll */
943 static unsigned int tun_chr_poll(struct file *file, poll_table *wait)
944 {
945 struct tun_file *tfile = file->private_data;
946 struct tun_struct *tun = __tun_get(tfile);
947 struct sock *sk;
948 unsigned int mask = 0;
949
950 if (!tun)
951 return POLLERR;
952
953 sk = tfile->socket.sk;
954
955 tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
956
957 poll_wait(file, &tfile->wq.wait, wait);
958
959 if (!skb_queue_empty(&sk->sk_receive_queue))
960 mask |= POLLIN | POLLRDNORM;
961
962 if (sock_writeable(sk) ||
963 (!test_and_set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
964 sock_writeable(sk)))
965 mask |= POLLOUT | POLLWRNORM;
966
967 if (tun->dev->reg_state != NETREG_REGISTERED)
968 mask = POLLERR;
969
970 tun_put(tun);
971 return mask;
972 }
973
974 /* prepad is the amount to reserve at front. len is length after that.
975 * linear is a hint as to how much to copy (usually headers). */
976 static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
977 size_t prepad, size_t len,
978 size_t linear, int noblock)
979 {
980 struct sock *sk = tfile->socket.sk;
981 struct sk_buff *skb;
982 int err;
983
984 /* Under a page? Don't bother with paged skb. */
985 if (prepad + len < PAGE_SIZE || !linear)
986 linear = len;
987
988 skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
989 &err);
990 if (!skb)
991 return ERR_PTR(err);
992
993 skb_reserve(skb, prepad);
994 skb_put(skb, linear);
995 skb->data_len = len - linear;
996 skb->len += len - linear;
997
998 return skb;
999 }
1000
1001 /* set skb frags from iovec, this can move to core network code for reuse */
1002 static int zerocopy_sg_from_iovec(struct sk_buff *skb, const struct iovec *from,
1003 int offset, size_t count)
1004 {
1005 int len = iov_length(from, count) - offset;
1006 int copy = skb_headlen(skb);
1007 int size, offset1 = 0;
1008 int i = 0;
1009
1010 /* Skip over from offset */
1011 while (count && (offset >= from->iov_len)) {
1012 offset -= from->iov_len;
1013 ++from;
1014 --count;
1015 }
1016
1017 /* copy up to skb headlen */
1018 while (count && (copy > 0)) {
1019 size = min_t(unsigned int, copy, from->iov_len - offset);
1020 if (copy_from_user(skb->data + offset1, from->iov_base + offset,
1021 size))
1022 return -EFAULT;
1023 if (copy > size) {
1024 ++from;
1025 --count;
1026 offset = 0;
1027 } else
1028 offset += size;
1029 copy -= size;
1030 offset1 += size;
1031 }
1032
1033 if (len == offset1)
1034 return 0;
1035
1036 while (count--) {
1037 struct page *page[MAX_SKB_FRAGS];
1038 int num_pages;
1039 unsigned long base;
1040 unsigned long truesize;
1041
1042 len = from->iov_len - offset;
1043 if (!len) {
1044 offset = 0;
1045 ++from;
1046 continue;
1047 }
1048 base = (unsigned long)from->iov_base + offset;
1049 size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT;
1050 if (i + size > MAX_SKB_FRAGS)
1051 return -EMSGSIZE;
1052 num_pages = get_user_pages_fast(base, size, 0, &page[i]);
1053 if (num_pages != size) {
1054 int j;
1055
1056 for (j = 0; j < num_pages; j++)
1057 put_page(page[i + j]);
1058 return -EFAULT;
1059 }
1060 truesize = size * PAGE_SIZE;
1061 skb->data_len += len;
1062 skb->len += len;
1063 skb->truesize += truesize;
1064 atomic_add(truesize, &skb->sk->sk_wmem_alloc);
1065 while (len) {
1066 int off = base & ~PAGE_MASK;
1067 int size = min_t(int, len, PAGE_SIZE - off);
1068 __skb_fill_page_desc(skb, i, page[i], off, size);
1069 skb_shinfo(skb)->nr_frags++;
1070 /* increase sk_wmem_alloc */
1071 base += size;
1072 len -= size;
1073 i++;
1074 }
1075 offset = 0;
1076 ++from;
1077 }
1078 return 0;
1079 }
1080
1081 static unsigned long iov_pages(const struct iovec *iv, int offset,
1082 unsigned long nr_segs)
1083 {
1084 unsigned long seg, base;
1085 int pages = 0, len, size;
1086
1087 while (nr_segs && (offset >= iv->iov_len)) {
1088 offset -= iv->iov_len;
1089 ++iv;
1090 --nr_segs;
1091 }
1092
1093 for (seg = 0; seg < nr_segs; seg++) {
1094 base = (unsigned long)iv[seg].iov_base + offset;
1095 len = iv[seg].iov_len - offset;
1096 size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT;
1097 pages += size;
1098 offset = 0;
1099 }
1100
1101 return pages;
1102 }
1103
1104 /* Get packet from user space buffer */
1105 static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
1106 void *msg_control, const struct iovec *iv,
1107 size_t total_len, size_t count, int noblock)
1108 {
1109 struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
1110 struct sk_buff *skb;
1111 size_t len = total_len, align = NET_SKB_PAD, linear;
1112 struct virtio_net_hdr gso = { 0 };
1113 int good_linear;
1114 int offset = 0;
1115 int copylen;
1116 bool zerocopy = false;
1117 int err;
1118 u32 rxhash;
1119
1120 if (!(tun->flags & TUN_NO_PI)) {
1121 if (len < sizeof(pi))
1122 return -EINVAL;
1123 len -= sizeof(pi);
1124
1125 if (memcpy_fromiovecend((void *)&pi, iv, 0, sizeof(pi)))
1126 return -EFAULT;
1127 offset += sizeof(pi);
1128 }
1129
1130 if (tun->flags & TUN_VNET_HDR) {
1131 int vnet_hdr_sz = ACCESS_ONCE(tun->vnet_hdr_sz);
1132
1133 if (len < vnet_hdr_sz)
1134 return -EINVAL;
1135 len -= vnet_hdr_sz;
1136
1137 if (memcpy_fromiovecend((void *)&gso, iv, offset, sizeof(gso)))
1138 return -EFAULT;
1139
1140 if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
1141 gso.csum_start + gso.csum_offset + 2 > gso.hdr_len)
1142 gso.hdr_len = gso.csum_start + gso.csum_offset + 2;
1143
1144 if (gso.hdr_len > len)
1145 return -EINVAL;
1146 offset += vnet_hdr_sz;
1147 }
1148
1149 if ((tun->flags & TUN_TYPE_MASK) == TUN_TAP_DEV) {
1150 align += NET_IP_ALIGN;
1151 if (unlikely(len < ETH_HLEN ||
1152 (gso.hdr_len && gso.hdr_len < ETH_HLEN)))
1153 return -EINVAL;
1154 }
1155
1156 good_linear = SKB_MAX_HEAD(align);
1157
1158 if (msg_control) {
1159 /* There are 256 bytes to be copied in skb, so there is
1160 * enough room for skb expand head in case it is used.
1161 * The rest of the buffer is mapped from userspace.
1162 */
1163 copylen = gso.hdr_len ? gso.hdr_len : GOODCOPY_LEN;
1164 if (copylen > good_linear)
1165 copylen = good_linear;
1166 linear = copylen;
1167 if (iov_pages(iv, offset + copylen, count) <= MAX_SKB_FRAGS)
1168 zerocopy = true;
1169 }
1170
1171 if (!zerocopy) {
1172 copylen = len;
1173 if (gso.hdr_len > good_linear)
1174 linear = good_linear;
1175 else
1176 linear = gso.hdr_len;
1177 }
1178
1179 skb = tun_alloc_skb(tfile, align, copylen, linear, noblock);
1180 if (IS_ERR(skb)) {
1181 if (PTR_ERR(skb) != -EAGAIN)
1182 tun->dev->stats.rx_dropped++;
1183 return PTR_ERR(skb);
1184 }
1185
1186 if (zerocopy)
1187 err = zerocopy_sg_from_iovec(skb, iv, offset, count);
1188 else {
1189 err = skb_copy_datagram_from_iovec(skb, 0, iv, offset, len);
1190 if (!err && msg_control) {
1191 struct ubuf_info *uarg = msg_control;
1192 uarg->callback(uarg, false);
1193 }
1194 }
1195
1196 if (err) {
1197 tun->dev->stats.rx_dropped++;
1198 kfree_skb(skb);
1199 return -EFAULT;
1200 }
1201
1202 if (gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
1203 if (!skb_partial_csum_set(skb, gso.csum_start,
1204 gso.csum_offset)) {
1205 tun->dev->stats.rx_frame_errors++;
1206 kfree_skb(skb);
1207 return -EINVAL;
1208 }
1209 }
1210
1211 switch (tun->flags & TUN_TYPE_MASK) {
1212 case TUN_TUN_DEV:
1213 if (tun->flags & TUN_NO_PI) {
1214 switch (skb->data[0] & 0xf0) {
1215 case 0x40:
1216 pi.proto = htons(ETH_P_IP);
1217 break;
1218 case 0x60:
1219 pi.proto = htons(ETH_P_IPV6);
1220 break;
1221 default:
1222 tun->dev->stats.rx_dropped++;
1223 kfree_skb(skb);
1224 return -EINVAL;
1225 }
1226 }
1227
1228 skb_reset_mac_header(skb);
1229 skb->protocol = pi.proto;
1230 skb->dev = tun->dev;
1231 break;
1232 case TUN_TAP_DEV:
1233 skb->protocol = eth_type_trans(skb, tun->dev);
1234 break;
1235 }
1236
1237 if (gso.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
1238 pr_debug("GSO!\n");
1239 switch (gso.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
1240 case VIRTIO_NET_HDR_GSO_TCPV4:
1241 skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
1242 break;
1243 case VIRTIO_NET_HDR_GSO_TCPV6:
1244 skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6;
1245 break;
1246 case VIRTIO_NET_HDR_GSO_UDP:
1247 skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
1248 break;
1249 default:
1250 tun->dev->stats.rx_frame_errors++;
1251 kfree_skb(skb);
1252 return -EINVAL;
1253 }
1254
1255 if (gso.gso_type & VIRTIO_NET_HDR_GSO_ECN)
1256 skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;
1257
1258 skb_shinfo(skb)->gso_size = gso.gso_size;
1259 if (skb_shinfo(skb)->gso_size == 0) {
1260 tun->dev->stats.rx_frame_errors++;
1261 kfree_skb(skb);
1262 return -EINVAL;
1263 }
1264
1265 /* Header must be checked, and gso_segs computed. */
1266 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
1267 skb_shinfo(skb)->gso_segs = 0;
1268 }
1269
1270 /* copy skb_ubuf_info for callback when skb has no error */
1271 if (zerocopy) {
1272 skb_shinfo(skb)->destructor_arg = msg_control;
1273 skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
1274 skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
1275 }
1276
1277 skb_reset_network_header(skb);
1278 skb_probe_transport_header(skb, 0);
1279
1280 rxhash = skb_get_rxhash(skb);
1281 netif_rx_ni(skb);
1282
1283 tun->dev->stats.rx_packets++;
1284 tun->dev->stats.rx_bytes += len;
1285
1286 tun_flow_update(tun, rxhash, tfile);
1287 return total_len;
1288 }
1289
1290 static ssize_t tun_chr_aio_write(struct kiocb *iocb, const struct iovec *iv,
1291 unsigned long count, loff_t pos)
1292 {
1293 struct file *file = iocb->ki_filp;
1294 struct tun_struct *tun = tun_get(file);
1295 struct tun_file *tfile = file->private_data;
1296 ssize_t result;
1297
1298 if (!tun)
1299 return -EBADFD;
1300
1301 tun_debug(KERN_INFO, tun, "tun_chr_write %ld\n", count);
1302
1303 result = tun_get_user(tun, tfile, NULL, iv, iov_length(iv, count),
1304 count, file->f_flags & O_NONBLOCK);
1305
1306 tun_put(tun);
1307 return result;
1308 }
1309
1310 // ------------- START of KNOX_VPN ------------------//
1311
1312 /* KNOX VPN packets have extra bytes because they carry meta information by default
1313 * Such packets have sizeof(struct tun_meta_header) extra bytes in the IP options
1314 * This automatically reflects in the IP header length (IHL)
1315 */
1316 static int knoxvpn_process_uidpid(struct tun_struct *tun, struct sk_buff *skb,
1317 const struct iovec *iv, int *len, ssize_t * total)
1318 {
1319 struct skb_shared_info *knox_shinfo = NULL;
1320 struct knox_meta_param metalocal = { 0, 0 };
1321
1322 if (skb != NULL)
1323 knox_shinfo = skb_shinfo(skb);
1324 else {
1325 #ifdef TUN_DEBUG
1326 pr_err("KNOX: NULL SKB in knoxvpn_process_uidpid");
1327 #endif
1328 return 0;
1329 }
1330
1331 if (knox_shinfo == NULL) {
1332 #ifdef TUN_DEBUG
1333 pr_err("KNOX: knox_shinfo value is null");
1334 #endif
1335 return 0;
1336 }
1337
1338 if (knox_shinfo->knox_mark >= META_MARK_BASE_LOWER && knox_shinfo->knox_mark <= META_MARK_BASE_UPPER) {
1339 metalocal.uid = knox_shinfo->uid;
1340 metalocal.pid = knox_shinfo->pid;
1341 }
1342
1343 if (knox_shinfo != NULL) {
1344 knox_shinfo->uid = knox_shinfo->pid = 0;
1345 knox_shinfo->knox_mark = 0;
1346 }
1347
1348 if (tun->flags & TUN_META_HDR) {
1349 #ifdef TUN_DEBUG
1350 pr_err("KNOX: Appending uid: %d and pid: %d", metalocal.uid,
1351 metalocal.pid);
1352 #endif
1353 if (unlikely
1354 (memcpy_toiovecend
1355 (iv, (void *)&metalocal, (*total),
1356 sizeof(struct knox_meta_param)))) {
1357 #ifdef TUN_DEBUG
1358 pr_err("KNOX: Failed to copy buffer to userspace");
1359 #endif
1360 return -1;
1361 }
1362 (*total) += TUN_META_HDR_SZ;
1363 }
1364
1365 return 0;
1366
1367 }
1368
1369 // ------------- END of KNOX_VPN ------------------//
1370
1371 /* Put packet to the user space buffer */
1372 static ssize_t tun_put_user(struct tun_struct *tun,
1373 struct tun_file *tfile,
1374 struct sk_buff *skb,
1375 const struct iovec *iv, int len)
1376 {
1377 struct tun_pi pi = { 0, skb->protocol };
1378 ssize_t total = 0;
1379 int vnet_hdr_sz = 0;
1380
1381 if (tun->flags & TUN_VNET_HDR)
1382 vnet_hdr_sz = ACCESS_ONCE(tun->vnet_hdr_sz);
1383
1384 if (!(tun->flags & TUN_NO_PI)) {
1385 if ((len -= sizeof(pi)) < 0)
1386 return -EINVAL;
1387
1388 if (len < skb->len + vnet_hdr_sz) {
1389 /* Packet will be striped */
1390 pi.flags |= TUN_PKT_STRIP;
1391 }
1392
1393 if (memcpy_toiovecend(iv, (void *) &pi, 0, sizeof(pi)))
1394 return -EFAULT;
1395 total += sizeof(pi);
1396 }
1397
1398 if (vnet_hdr_sz) {
1399 struct virtio_net_hdr gso = { 0 }; /* no info leak */
1400 if ((len -= vnet_hdr_sz) < 0)
1401 return -EINVAL;
1402
1403 if (skb_is_gso(skb)) {
1404 struct skb_shared_info *sinfo = skb_shinfo(skb);
1405
1406 /* This is a hint as to how much should be linear. */
1407 gso.hdr_len = skb_headlen(skb);
1408 gso.gso_size = sinfo->gso_size;
1409 if (sinfo->gso_type & SKB_GSO_TCPV4)
1410 gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
1411 else if (sinfo->gso_type & SKB_GSO_TCPV6)
1412 gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
1413 else if (sinfo->gso_type & SKB_GSO_UDP)
1414 gso.gso_type = VIRTIO_NET_HDR_GSO_UDP;
1415 else {
1416 pr_err("unexpected GSO type: "
1417 "0x%x, gso_size %d, hdr_len %d\n",
1418 sinfo->gso_type, gso.gso_size,
1419 gso.hdr_len);
1420 print_hex_dump(KERN_ERR, "tun: ",
1421 DUMP_PREFIX_NONE,
1422 16, 1, skb->head,
1423 min((int)gso.hdr_len, 64), true);
1424 WARN_ON_ONCE(1);
1425 return -EINVAL;
1426 }
1427 if (sinfo->gso_type & SKB_GSO_TCP_ECN)
1428 gso.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
1429 } else
1430 gso.gso_type = VIRTIO_NET_HDR_GSO_NONE;
1431
1432 if (skb->ip_summed == CHECKSUM_PARTIAL) {
1433 gso.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
1434 gso.csum_start = skb_checksum_start_offset(skb);
1435 gso.csum_offset = skb->csum_offset;
1436 } else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
1437 gso.flags = VIRTIO_NET_HDR_F_DATA_VALID;
1438 } /* else everything is zero */
1439
1440 if (unlikely(memcpy_toiovecend(iv, (void *)&gso, total,
1441 sizeof(gso))))
1442 return -EFAULT;
1443 total += vnet_hdr_sz;
1444 }
1445
1446 // ------------- START of KNOX_VPN ------------------//
1447 if (knoxvpn_process_uidpid(tun, skb, iv, &len, &total) < 0) {
1448 return -EINVAL;
1449 }
1450 // ------------- END of KNOX_VPN ------------------//
1451
1452 len = min_t(int, skb->len, len);
1453
1454 skb_copy_datagram_const_iovec(skb, 0, iv, total, len);
1455 total += skb->len;
1456
1457 tun->dev->stats.tx_packets++;
1458 tun->dev->stats.tx_bytes += len;
1459
1460 return total;
1461 }
1462
1463 static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
1464 struct kiocb *iocb, const struct iovec *iv,
1465 ssize_t len, int noblock)
1466 {
1467 DECLARE_WAITQUEUE(wait, current);
1468 struct sk_buff *skb;
1469 ssize_t ret = 0;
1470
1471 tun_debug(KERN_INFO, tun, "tun_do_read\n");
1472
1473 if (unlikely(!noblock))
1474 add_wait_queue(&tfile->wq.wait, &wait);
1475 while (len) {
1476 current->state = TASK_INTERRUPTIBLE;
1477
1478 /* Read frames from the queue */
1479 if (!(skb = skb_dequeue(&tfile->socket.sk->sk_receive_queue))) {
1480 if (noblock) {
1481 ret = -EAGAIN;
1482 break;
1483 }
1484 if (signal_pending(current)) {
1485 ret = -ERESTARTSYS;
1486 break;
1487 }
1488 if (tun->dev->reg_state != NETREG_REGISTERED) {
1489 ret = -EIO;
1490 break;
1491 }
1492
1493 /* Nothing to read, let's sleep */
1494 schedule();
1495 continue;
1496 }
1497
1498 ret = tun_put_user(tun, tfile, skb, iv, len);
1499 kfree_skb(skb);
1500 break;
1501 }
1502
1503 current->state = TASK_RUNNING;
1504 if (unlikely(!noblock))
1505 remove_wait_queue(&tfile->wq.wait, &wait);
1506
1507 return ret;
1508 }
1509
1510 static ssize_t tun_chr_aio_read(struct kiocb *iocb, const struct iovec *iv,
1511 unsigned long count, loff_t pos)
1512 {
1513 struct file *file = iocb->ki_filp;
1514 struct tun_file *tfile = file->private_data;
1515 struct tun_struct *tun = __tun_get(tfile);
1516 ssize_t len, ret;
1517
1518 if (!tun)
1519 return -EBADFD;
1520 len = iov_length(iv, count);
1521 if (len < 0) {
1522 ret = -EINVAL;
1523 goto out;
1524 }
1525
1526 ret = tun_do_read(tun, tfile, iocb, iv, len,
1527 file->f_flags & O_NONBLOCK);
1528 ret = min_t(ssize_t, ret, len);
1529 if (ret > 0)
1530 iocb->ki_pos = ret;
1531 out:
1532 tun_put(tun);
1533 return ret;
1534 }
1535
1536 static void tun_free_netdev(struct net_device *dev)
1537 {
1538 struct tun_struct *tun = netdev_priv(dev);
1539
1540 BUG_ON(!(list_empty(&tun->disabled)));
1541 tun_flow_uninit(tun);
1542 security_tun_dev_free_security(tun->security);
1543 free_netdev(dev);
1544 }
1545
1546 static void tun_setup(struct net_device *dev)
1547 {
1548 struct tun_struct *tun = netdev_priv(dev);
1549
1550 tun->owner = INVALID_UID;
1551 tun->group = INVALID_GID;
1552
1553 dev->ethtool_ops = &tun_ethtool_ops;
1554 dev->destructor = tun_free_netdev;
1555 }
1556
1557 /* Trivial set of netlink ops to allow deleting tun or tap
1558 * device with netlink.
1559 */
1560 static int tun_validate(struct nlattr *tb[], struct nlattr *data[])
1561 {
1562 return -EINVAL;
1563 }
1564
1565 static struct rtnl_link_ops tun_link_ops __read_mostly = {
1566 .kind = DRV_NAME,
1567 .priv_size = sizeof(struct tun_struct),
1568 .setup = tun_setup,
1569 .validate = tun_validate,
1570 };
1571
1572 static void tun_sock_write_space(struct sock *sk)
1573 {
1574 struct tun_file *tfile;
1575 wait_queue_head_t *wqueue;
1576
1577 if (!sock_writeable(sk))
1578 return;
1579
1580 if (!test_and_clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags))
1581 return;
1582
1583 wqueue = sk_sleep(sk);
1584 if (wqueue && waitqueue_active(wqueue))
1585 wake_up_interruptible_sync_poll(wqueue, POLLOUT |
1586 POLLWRNORM | POLLWRBAND);
1587
1588 tfile = container_of(sk, struct tun_file, sk);
1589 kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
1590 }
1591
1592 static int tun_sendmsg(struct kiocb *iocb, struct socket *sock,
1593 struct msghdr *m, size_t total_len)
1594 {
1595 int ret;
1596 struct tun_file *tfile = container_of(sock, struct tun_file, socket);
1597 struct tun_struct *tun = __tun_get(tfile);
1598
1599 if (!tun)
1600 return -EBADFD;
1601 ret = tun_get_user(tun, tfile, m->msg_control, m->msg_iov, total_len,
1602 m->msg_iovlen, m->msg_flags & MSG_DONTWAIT);
1603 tun_put(tun);
1604 return ret;
1605 }
1606
1607
1608 static int tun_recvmsg(struct kiocb *iocb, struct socket *sock,
1609 struct msghdr *m, size_t total_len,
1610 int flags)
1611 {
1612 struct tun_file *tfile = container_of(sock, struct tun_file, socket);
1613 struct tun_struct *tun = __tun_get(tfile);
1614 int ret;
1615
1616 if (!tun)
1617 return -EBADFD;
1618
1619 if (flags & ~(MSG_DONTWAIT|MSG_TRUNC)) {
1620 ret = -EINVAL;
1621 goto out;
1622 }
1623 ret = tun_do_read(tun, tfile, iocb, m->msg_iov, total_len,
1624 flags & MSG_DONTWAIT);
1625 if (ret > total_len) {
1626 m->msg_flags |= MSG_TRUNC;
1627 ret = flags & MSG_TRUNC ? ret : total_len;
1628 }
1629 out:
1630 tun_put(tun);
1631 return ret;
1632 }
1633
1634 static int tun_release(struct socket *sock)
1635 {
1636 if (sock->sk)
1637 sock_put(sock->sk);
1638 return 0;
1639 }
1640
1641 /* Ops structure to mimic raw sockets with tun */
1642 static const struct proto_ops tun_socket_ops = {
1643 .sendmsg = tun_sendmsg,
1644 .recvmsg = tun_recvmsg,
1645 .release = tun_release,
1646 };
1647
1648 static struct proto tun_proto = {
1649 .name = "tun",
1650 .owner = THIS_MODULE,
1651 .obj_size = sizeof(struct tun_file),
1652 };
1653
1654 static int tun_flags(struct tun_struct *tun)
1655 {
1656 int flags = 0;
1657
1658 // ------------- START of KNOX_VPN ------------------//
1659 /* Checks if meta header is enabled so that
1660 * packets will be prepended with meta data(UID/PID)
1661 */
1662 if (tun->flags & TUN_META_HDR) {
1663 flags |= IFF_META_HDR;
1664 }
1665 // ------------- END of KNOX_VPN -------------------//
1666
1667 if (tun->flags & TUN_TUN_DEV)
1668 flags |= IFF_TUN;
1669 else
1670 flags |= IFF_TAP;
1671
1672 if (tun->flags & TUN_NO_PI)
1673 flags |= IFF_NO_PI;
1674
1675 /* This flag has no real effect. We track the value for backwards
1676 * compatibility.
1677 */
1678 if (tun->flags & TUN_ONE_QUEUE)
1679 flags |= IFF_ONE_QUEUE;
1680
1681 if (tun->flags & TUN_VNET_HDR)
1682 flags |= IFF_VNET_HDR;
1683
1684 if (tun->flags & TUN_TAP_MQ)
1685 flags |= IFF_MULTI_QUEUE;
1686
1687 return flags;
1688 }
1689
1690 static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr,
1691 char *buf)
1692 {
1693 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1694 return sprintf(buf, "0x%x\n", tun_flags(tun));
1695 }
1696
1697 static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr,
1698 char *buf)
1699 {
1700 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1701 return uid_valid(tun->owner)?
1702 sprintf(buf, "%u\n",
1703 from_kuid_munged(current_user_ns(), tun->owner)):
1704 sprintf(buf, "-1\n");
1705 }
1706
1707 static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr,
1708 char *buf)
1709 {
1710 struct tun_struct *tun = netdev_priv(to_net_dev(dev));
1711 return gid_valid(tun->group) ?
1712 sprintf(buf, "%u\n",
1713 from_kgid_munged(current_user_ns(), tun->group)):
1714 sprintf(buf, "-1\n");
1715 }
1716
1717 static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
1718 static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
1719 static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
1720
1721 static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
1722 {
1723 struct tun_struct *tun;
1724 struct tun_file *tfile = file->private_data;
1725 struct net_device *dev;
1726 int err;
1727
1728 if (tfile->detached)
1729 return -EINVAL;
1730
1731 dev = __dev_get_by_name(net, ifr->ifr_name);
1732 if (dev) {
1733 if (ifr->ifr_flags & IFF_TUN_EXCL)
1734 return -EBUSY;
1735 if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
1736 tun = netdev_priv(dev);
1737 else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
1738 tun = netdev_priv(dev);
1739 else
1740 return -EINVAL;
1741
1742 if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
1743 !!(tun->flags & TUN_TAP_MQ))
1744 return -EINVAL;
1745
1746 if (tun_not_capable(tun))
1747 return -EPERM;
1748 err = security_tun_dev_open(tun->security);
1749 if (err < 0)
1750 return err;
1751
1752 err = tun_attach(tun, file);
1753 if (err < 0)
1754 return err;
1755
1756 if (tun->flags & TUN_TAP_MQ &&
1757 (tun->numqueues + tun->numdisabled > 1)) {
1758 /* One or more queue has already been attached, no need
1759 * to initialize the device again.
1760 */
1761 return 0;
1762 }
1763 }
1764 else {
1765 char *name;
1766 unsigned long flags = 0;
1767 int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
1768 MAX_TAP_QUEUES : 1;
1769
1770 if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
1771 return -EPERM;
1772 err = security_tun_dev_create();
1773 if (err < 0)
1774 return err;
1775
1776 /* Set dev type */
1777 if (ifr->ifr_flags & IFF_TUN) {
1778 /* TUN device */
1779 flags |= TUN_TUN_DEV;
1780 name = "tun%d";
1781 } else if (ifr->ifr_flags & IFF_TAP) {
1782 /* TAP device */
1783 flags |= TUN_TAP_DEV;
1784 name = "tap%d";
1785 } else
1786 return -EINVAL;
1787
1788 if (*ifr->ifr_name)
1789 name = ifr->ifr_name;
1790
1791 dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
1792 tun_setup, queues, queues);
1793
1794 if (!dev)
1795 return -ENOMEM;
1796
1797 dev_net_set(dev, net);
1798 dev->rtnl_link_ops = &tun_link_ops;
1799
1800 tun = netdev_priv(dev);
1801 tun->dev = dev;
1802 tun->flags = flags;
1803 tun->txflt.count = 0;
1804 tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
1805
1806 tun->filter_attached = false;
1807 tun->sndbuf = tfile->socket.sk->sk_sndbuf;
1808
1809 spin_lock_init(&tun->lock);
1810
1811 err = security_tun_dev_alloc_security(&tun->security);
1812 if (err < 0)
1813 goto err_free_dev;
1814
1815 tun_net_init(dev);
1816
1817 err = tun_flow_init(tun);
1818 if (err < 0)
1819 goto err_free_dev;
1820
1821 dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
1822 TUN_USER_FEATURES;
1823 dev->features = dev->hw_features;
1824 dev->vlan_features = dev->features;
1825
1826 INIT_LIST_HEAD(&tun->disabled);
1827 err = tun_attach(tun, file);
1828 if (err < 0)
1829 goto err_free_flow;
1830
1831 err = register_netdevice(tun->dev);
1832 if (err < 0)
1833 goto err_detach;
1834
1835 if (device_create_file(&tun->dev->dev, &dev_attr_tun_flags) ||
1836 device_create_file(&tun->dev->dev, &dev_attr_owner) ||
1837 device_create_file(&tun->dev->dev, &dev_attr_group))
1838 pr_err("Failed to create tun sysfs files\n");
1839 }
1840
1841 netif_carrier_on(tun->dev);
1842
1843 tun_debug(KERN_INFO, tun, "tun_set_iff\n");
1844
1845 // ------------- START of KNOX_VPN ------------------//
1846 if (ifr->ifr_flags & IFF_META_HDR) {
1847 tun->flags |= TUN_META_HDR;
1848 } else {
1849 tun->flags &= ~TUN_META_HDR;
1850 }
1851 // ------------- END of KNOX_VPN -------------------//
1852
1853 if (ifr->ifr_flags & IFF_NO_PI)
1854 tun->flags |= TUN_NO_PI;
1855 else
1856 tun->flags &= ~TUN_NO_PI;
1857
1858 /* This flag has no real effect. We track the value for backwards
1859 * compatibility.
1860 */
1861 if (ifr->ifr_flags & IFF_ONE_QUEUE)
1862 tun->flags |= TUN_ONE_QUEUE;
1863 else
1864 tun->flags &= ~TUN_ONE_QUEUE;
1865
1866 if (ifr->ifr_flags & IFF_VNET_HDR)
1867 tun->flags |= TUN_VNET_HDR;
1868 else
1869 tun->flags &= ~TUN_VNET_HDR;
1870
1871 if (ifr->ifr_flags & IFF_MULTI_QUEUE)
1872 tun->flags |= TUN_TAP_MQ;
1873 else
1874 tun->flags &= ~TUN_TAP_MQ;
1875
1876 /* Make sure persistent devices do not get stuck in
1877 * xoff state.
1878 */
1879 if (netif_running(tun->dev))
1880 netif_tx_wake_all_queues(tun->dev);
1881
1882 strcpy(ifr->ifr_name, tun->dev->name);
1883 return 0;
1884
1885 err_detach:
1886 tun_detach_all(dev);
1887 err_free_flow:
1888 tun_flow_uninit(tun);
1889 security_tun_dev_free_security(tun->security);
1890 err_free_dev:
1891 free_netdev(dev);
1892 return err;
1893 }
1894
1895 static void tun_get_iff(struct net *net, struct tun_struct *tun,
1896 struct ifreq *ifr)
1897 {
1898 tun_debug(KERN_INFO, tun, "tun_get_iff\n");
1899
1900 strcpy(ifr->ifr_name, tun->dev->name);
1901
1902 ifr->ifr_flags = tun_flags(tun);
1903
1904 }
1905
1906 /* This is like a cut-down ethtool ops, except done via tun fd so no
1907 * privs required. */
1908 static int set_offload(struct tun_struct *tun, unsigned long arg)
1909 {
1910 netdev_features_t features = 0;
1911
1912 if (arg & TUN_F_CSUM) {
1913 features |= NETIF_F_HW_CSUM;
1914 arg &= ~TUN_F_CSUM;
1915
1916 if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
1917 if (arg & TUN_F_TSO_ECN) {
1918 features |= NETIF_F_TSO_ECN;
1919 arg &= ~TUN_F_TSO_ECN;
1920 }
1921 if (arg & TUN_F_TSO4)
1922 features |= NETIF_F_TSO;
1923 if (arg & TUN_F_TSO6)
1924 features |= NETIF_F_TSO6;
1925 arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
1926 }
1927
1928 if (arg & TUN_F_UFO) {
1929 features |= NETIF_F_UFO;
1930 arg &= ~TUN_F_UFO;
1931 }
1932 }
1933
1934 /* This gives the user a way to test for new features in future by
1935 * trying to set them. */
1936 if (arg)
1937 return -EINVAL;
1938
1939 tun->set_features = features;
1940 netdev_update_features(tun->dev);
1941
1942 return 0;
1943 }
1944
1945 static void tun_detach_filter(struct tun_struct *tun, int n)
1946 {
1947 int i;
1948 struct tun_file *tfile;
1949
1950 for (i = 0; i < n; i++) {
1951 tfile = rtnl_dereference(tun->tfiles[i]);
1952 sk_detach_filter(tfile->socket.sk);
1953 }
1954
1955 tun->filter_attached = false;
1956 }
1957
1958 static int tun_attach_filter(struct tun_struct *tun)
1959 {
1960 int i, ret = 0;
1961 struct tun_file *tfile;
1962
1963 for (i = 0; i < tun->numqueues; i++) {
1964 tfile = rtnl_dereference(tun->tfiles[i]);
1965 ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
1966 if (ret) {
1967 tun_detach_filter(tun, i);
1968 return ret;
1969 }
1970 }
1971
1972 tun->filter_attached = true;
1973 return ret;
1974 }
1975
1976 static void tun_set_sndbuf(struct tun_struct *tun)
1977 {
1978 struct tun_file *tfile;
1979 int i;
1980
1981 for (i = 0; i < tun->numqueues; i++) {
1982 tfile = rtnl_dereference(tun->tfiles[i]);
1983 tfile->socket.sk->sk_sndbuf = tun->sndbuf;
1984 }
1985 }
1986
1987 static int tun_set_queue(struct file *file, struct ifreq *ifr)
1988 {
1989 struct tun_file *tfile = file->private_data;
1990 struct tun_struct *tun;
1991 int ret = 0;
1992
1993 rtnl_lock();
1994
1995 if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
1996 tun = tfile->detached;
1997 if (!tun) {
1998 ret = -EINVAL;
1999 goto unlock;
2000 }
2001 ret = security_tun_dev_attach_queue(tun->security);
2002 if (ret < 0)
2003 goto unlock;
2004 ret = tun_attach(tun, file);
2005 } else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
2006 tun = rtnl_dereference(tfile->tun);
2007 if (!tun || !(tun->flags & TUN_TAP_MQ) || tfile->detached)
2008 ret = -EINVAL;
2009 else
2010 __tun_detach(tfile, false);
2011 } else
2012 ret = -EINVAL;
2013
2014 unlock:
2015 rtnl_unlock();
2016 return ret;
2017 }
2018
2019 static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
2020 unsigned long arg, int ifreq_len)
2021 {
2022 struct tun_file *tfile = file->private_data;
2023 struct tun_struct *tun;
2024 void __user* argp = (void __user*)arg;
2025 struct ifreq ifr;
2026 kuid_t owner;
2027 kgid_t group;
2028 int sndbuf;
2029 int vnet_hdr_sz;
2030 int ret;
2031 // ------------- START of KNOX_VPN ------------------//
2032 int knox_flag = 0;
2033 int tun_meta_param;
2034 int tun_meta_value;
2035 // ------------- END of KNOX_VPN -------------------//
2036
2037 #ifdef CONFIG_ANDROID_PARANOID_NETWORK
2038 if (cmd != TUNGETIFF && !capable(CAP_NET_ADMIN)) {
2039 return -EPERM;
2040 }
2041 #endif
2042
2043 if (cmd == TUNSETIFF || cmd == TUNSETQUEUE || _IOC_TYPE(cmd) == 0x89) {
2044 if (copy_from_user(&ifr, argp, ifreq_len))
2045 return -EFAULT;
2046 } else {
2047 memset(&ifr, 0, sizeof(ifr));
2048 }
2049 if (cmd == TUNGETFEATURES) {
2050 /* Currently this just means: "what IFF flags are valid?".
2051 * This is needed because we never checked for invalid flags on
2052 * TUNSETIFF. */
2053 // ------------- START of KNOX_VPN ------------------//
2054 knox_flag |= IFF_META_HDR;
2055 return put_user(IFF_TUN | IFF_TAP | IFF_NO_PI | IFF_ONE_QUEUE |
2056 IFF_VNET_HDR | IFF_MULTI_QUEUE | knox_flag,
2057 (unsigned int __user*)argp);
2058 // ------------- END of KNOX_VPN -------------------//
2059 } else if (cmd == TUNSETQUEUE)
2060 return tun_set_queue(file, &ifr);
2061
2062 ret = 0;
2063 rtnl_lock();
2064
2065 tun = __tun_get(tfile);
2066 if (cmd == TUNSETIFF && !tun) {
2067 ifr.ifr_name[IFNAMSIZ-1] = '\0';
2068
2069 ret = tun_set_iff(tfile->net, file, &ifr);
2070
2071 if (ret)
2072 goto unlock;
2073
2074 if (copy_to_user(argp, &ifr, ifreq_len))
2075 ret = -EFAULT;
2076 goto unlock;
2077 }
2078
2079 ret = -EBADFD;
2080 if (!tun)
2081 goto unlock;
2082
2083 tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
2084
2085 ret = 0;
2086 switch (cmd) {
2087 case TUNGETIFF:
2088 tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
2089
2090 if (copy_to_user(argp, &ifr, ifreq_len))
2091 ret = -EFAULT;
2092 break;
2093
2094 case TUNSETNOCSUM:
2095 /* Disable/Enable checksum */
2096
2097 /* [unimplemented] */
2098 tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
2099 arg ? "disabled" : "enabled");
2100 break;
2101
2102 case TUNSETPERSIST:
2103 /* Disable/Enable persist mode. Keep an extra reference to the
2104 * module to prevent the module being unprobed.
2105 */
2106 if (arg && !(tun->flags & TUN_PERSIST)) {
2107 tun->flags |= TUN_PERSIST;
2108 __module_get(THIS_MODULE);
2109 }
2110 if (!arg && (tun->flags & TUN_PERSIST)) {
2111 tun->flags &= ~TUN_PERSIST;
2112 module_put(THIS_MODULE);
2113 }
2114
2115 tun_debug(KERN_INFO, tun, "persist %s\n",
2116 arg ? "enabled" : "disabled");
2117 break;
2118
2119 case TUNSETOWNER:
2120 /* Set owner of the device */
2121 owner = make_kuid(current_user_ns(), arg);
2122 if (!uid_valid(owner)) {
2123 ret = -EINVAL;
2124 break;
2125 }
2126 tun->owner = owner;
2127 tun_debug(KERN_INFO, tun, "owner set to %u\n",
2128 from_kuid(&init_user_ns, tun->owner));
2129 break;
2130
2131 case TUNSETGROUP:
2132 /* Set group of the device */
2133 group = make_kgid(current_user_ns(), arg);
2134 if (!gid_valid(group)) {
2135 ret = -EINVAL;
2136 break;
2137 }
2138 tun->group = group;
2139 tun_debug(KERN_INFO, tun, "group set to %u\n",
2140 from_kgid(&init_user_ns, tun->group));
2141 break;
2142
2143 case TUNSETLINK:
2144 /* Only allow setting the type when the interface is down */
2145 if (tun->dev->flags & IFF_UP) {
2146 tun_debug(KERN_INFO, tun,
2147 "Linktype set failed because interface is up\n");
2148 ret = -EBUSY;
2149 } else {
2150 tun->dev->type = (int) arg;
2151 tun_debug(KERN_INFO, tun, "linktype set to %d\n",
2152 tun->dev->type);
2153 ret = 0;
2154 }
2155 break;
2156
2157 #ifdef TUN_DEBUG
2158 case TUNSETDEBUG:
2159 tun->debug = arg;
2160 break;
2161 #endif
2162 case TUNSETOFFLOAD:
2163 ret = set_offload(tun, arg);
2164 break;
2165
2166 case TUNSETTXFILTER:
2167 /* Can be set only for TAPs */
2168 ret = -EINVAL;
2169 if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
2170 break;
2171 ret = update_filter(&tun->txflt, (void __user *)arg);
2172 break;
2173
2174 case SIOCGIFHWADDR:
2175 /* Get hw address */
2176 memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
2177 ifr.ifr_hwaddr.sa_family = tun->dev->type;
2178 if (copy_to_user(argp, &ifr, ifreq_len))
2179 ret = -EFAULT;
2180 break;
2181
2182 case SIOCSIFHWADDR:
2183 /* Set hw address */
2184 tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
2185 ifr.ifr_hwaddr.sa_data);
2186
2187 ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
2188 break;
2189
2190 case TUNGETSNDBUF:
2191 sndbuf = tfile->socket.sk->sk_sndbuf;
2192 if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
2193 ret = -EFAULT;
2194 break;
2195
2196 case TUNSETSNDBUF:
2197 if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
2198 ret = -EFAULT;
2199 break;
2200 }
2201
2202 tun->sndbuf = sndbuf;
2203 tun_set_sndbuf(tun);
2204 break;
2205
2206 case TUNGETVNETHDRSZ:
2207 vnet_hdr_sz = tun->vnet_hdr_sz;
2208 if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
2209 ret = -EFAULT;
2210 break;
2211
2212 case TUNSETVNETHDRSZ:
2213 if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
2214 ret = -EFAULT;
2215 break;
2216 }
2217 if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
2218 ret = -EINVAL;
2219 break;
2220 }
2221
2222 tun->vnet_hdr_sz = vnet_hdr_sz;
2223 break;
2224 // ------------- START of KNOX_VPN ------------------//
2225 case TUNGETMETAPARAM:
2226
2227 if (copy_from_user(&tun_meta_param, argp,
2228 sizeof(tun_meta_param))) {
2229 ret = -EFAULT;
2230 break;
2231 }
2232
2233 ret = 0;
2234 switch (tun_meta_param) {
2235 case TUN_GET_META_HDR_SZ:
2236 tun_meta_value = TUN_META_HDR_SZ;
2237 break;
2238
2239 case TUN_GET_META_MARK_OFFSET:
2240 tun_meta_value = TUN_META_MARK_OFFSET;
2241 break;
2242
2243 default:
2244 ret = -EINVAL;
2245 break;
2246 }
2247
2248 if (!ret) {
2249 if (copy_to_user(argp, &tun_meta_value,
2250 sizeof(tun_meta_value)))
2251 ret = -EFAULT;
2252 }
2253 break;
2254 // ------------- END of KNOX_VPN -------------------//
2255 case TUNATTACHFILTER:
2256 /* Can be set only for TAPs */
2257 ret = -EINVAL;
2258 if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
2259 break;
2260 ret = -EFAULT;
2261 if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
2262 break;
2263
2264 ret = tun_attach_filter(tun);
2265 break;
2266
2267 case TUNDETACHFILTER:
2268 /* Can be set only for TAPs */
2269 ret = -EINVAL;
2270 if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
2271 break;
2272 ret = 0;
2273 tun_detach_filter(tun, tun->numqueues);
2274 break;
2275
2276 default:
2277 ret = -EINVAL;
2278 break;
2279 }
2280
2281 unlock:
2282 rtnl_unlock();
2283 if (tun)
2284 tun_put(tun);
2285 return ret;
2286 }
2287
2288 static long tun_chr_ioctl(struct file *file,
2289 unsigned int cmd, unsigned long arg)
2290 {
2291 return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
2292 }
2293
2294 #ifdef CONFIG_COMPAT
2295 static long tun_chr_compat_ioctl(struct file *file,
2296 unsigned int cmd, unsigned long arg)
2297 {
2298 switch (cmd) {
2299 case TUNSETIFF:
2300 case TUNGETIFF:
2301 case TUNSETTXFILTER:
2302 case TUNGETSNDBUF:
2303 case TUNSETSNDBUF:
2304 case SIOCGIFHWADDR:
2305 case SIOCSIFHWADDR:
2306 arg = (unsigned long)compat_ptr(arg);
2307 break;
2308 default:
2309 arg = (compat_ulong_t)arg;
2310 break;
2311 }
2312
2313 /*
2314 * compat_ifreq is shorter than ifreq, so we must not access beyond
2315 * the end of that structure. All fields that are used in this
2316 * driver are compatible though, we don't need to convert the
2317 * contents.
2318 */
2319 return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
2320 }
2321 #endif /* CONFIG_COMPAT */
2322
2323 static int tun_chr_fasync(int fd, struct file *file, int on)
2324 {
2325 struct tun_file *tfile = file->private_data;
2326 int ret;
2327
2328 if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
2329 goto out;
2330
2331 if (on) {
2332 ret = __f_setown(file, task_pid(current), PIDTYPE_PID, 0);
2333 if (ret)
2334 goto out;
2335 tfile->flags |= TUN_FASYNC;
2336 } else
2337 tfile->flags &= ~TUN_FASYNC;
2338 ret = 0;
2339 out:
2340 return ret;
2341 }
2342
2343 static int tun_chr_open(struct inode *inode, struct file * file)
2344 {
2345 struct tun_file *tfile;
2346
2347 DBG1(KERN_INFO, "tunX: tun_chr_open\n");
2348
2349 tfile = (struct tun_file *)sk_alloc(&init_net, AF_UNSPEC, GFP_KERNEL,
2350 &tun_proto);
2351 if (!tfile)
2352 return -ENOMEM;
2353 rcu_assign_pointer(tfile->tun, NULL);
2354 tfile->net = get_net(current->nsproxy->net_ns);
2355 tfile->flags = 0;
2356
2357 rcu_assign_pointer(tfile->socket.wq, &tfile->wq);
2358 init_waitqueue_head(&tfile->wq.wait);
2359
2360 tfile->socket.file = file;
2361 tfile->socket.ops = &tun_socket_ops;
2362
2363 sock_init_data(&tfile->socket, &tfile->sk);
2364 sk_change_net(&tfile->sk, tfile->net);
2365
2366 tfile->sk.sk_write_space = tun_sock_write_space;
2367 tfile->sk.sk_sndbuf = INT_MAX;
2368
2369 file->private_data = tfile;
2370 set_bit(SOCK_EXTERNALLY_ALLOCATED, &tfile->socket.flags);
2371 INIT_LIST_HEAD(&tfile->next);
2372
2373 sock_set_flag(&tfile->sk, SOCK_ZEROCOPY);
2374
2375 return 0;
2376 }
2377
2378 static int tun_chr_close(struct inode *inode, struct file *file)
2379 {
2380 struct tun_file *tfile = file->private_data;
2381 struct net *net = tfile->net;
2382
2383 tun_detach(tfile, true);
2384 put_net(net);
2385
2386 return 0;
2387 }
2388
2389 static const struct file_operations tun_fops = {
2390 .owner = THIS_MODULE,
2391 .llseek = no_llseek,
2392 .read = do_sync_read,
2393 .aio_read = tun_chr_aio_read,
2394 .write = do_sync_write,
2395 .aio_write = tun_chr_aio_write,
2396 .poll = tun_chr_poll,
2397 .unlocked_ioctl = tun_chr_ioctl,
2398 #ifdef CONFIG_COMPAT
2399 .compat_ioctl = tun_chr_compat_ioctl,
2400 #endif
2401 .open = tun_chr_open,
2402 .release = tun_chr_close,
2403 .fasync = tun_chr_fasync
2404 };
2405
2406 static struct miscdevice tun_miscdev = {
2407 .minor = TUN_MINOR,
2408 .name = "tun",
2409 .nodename = "net/tun",
2410 .fops = &tun_fops,
2411 };
2412
2413 /* ethtool interface */
2414
2415 static int tun_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
2416 {
2417 cmd->supported = 0;
2418 cmd->advertising = 0;
2419 ethtool_cmd_speed_set(cmd, SPEED_10);
2420 cmd->duplex = DUPLEX_FULL;
2421 cmd->port = PORT_TP;
2422 cmd->phy_address = 0;
2423 cmd->transceiver = XCVR_INTERNAL;
2424 cmd->autoneg = AUTONEG_DISABLE;
2425 cmd->maxtxpkt = 0;
2426 cmd->maxrxpkt = 0;
2427 return 0;
2428 }
2429
2430 static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
2431 {
2432 struct tun_struct *tun = netdev_priv(dev);
2433
2434 strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
2435 strlcpy(info->version, DRV_VERSION, sizeof(info->version));
2436
2437 switch (tun->flags & TUN_TYPE_MASK) {
2438 case TUN_TUN_DEV:
2439 strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
2440 break;
2441 case TUN_TAP_DEV:
2442 strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
2443 break;
2444 }
2445 }
2446
2447 static u32 tun_get_msglevel(struct net_device *dev)
2448 {
2449 #ifdef TUN_DEBUG
2450 struct tun_struct *tun = netdev_priv(dev);
2451 return tun->debug;
2452 #else
2453 return -EOPNOTSUPP;
2454 #endif
2455 }
2456
2457 static void tun_set_msglevel(struct net_device *dev, u32 value)
2458 {
2459 #ifdef TUN_DEBUG
2460 struct tun_struct *tun = netdev_priv(dev);
2461 tun->debug = value;
2462 #endif
2463 }
2464
2465 static const struct ethtool_ops tun_ethtool_ops = {
2466 .get_settings = tun_get_settings,
2467 .get_drvinfo = tun_get_drvinfo,
2468 .get_msglevel = tun_get_msglevel,
2469 .set_msglevel = tun_set_msglevel,
2470 .get_link = ethtool_op_get_link,
2471 };
2472
2473
2474 static int __init tun_init(void)
2475 {
2476 int ret = 0;
2477
2478 pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
2479 pr_info("%s\n", DRV_COPYRIGHT);
2480
2481 ret = rtnl_link_register(&tun_link_ops);
2482 if (ret) {
2483 pr_err("Can't register link_ops\n");
2484 goto err_linkops;
2485 }
2486
2487 ret = misc_register(&tun_miscdev);
2488 if (ret) {
2489 pr_err("Can't register misc device %d\n", TUN_MINOR);
2490 goto err_misc;
2491 }
2492 return 0;
2493 err_misc:
2494 rtnl_link_unregister(&tun_link_ops);
2495 err_linkops:
2496 return ret;
2497 }
2498
2499 static void tun_cleanup(void)
2500 {
2501 misc_deregister(&tun_miscdev);
2502 rtnl_link_unregister(&tun_link_ops);
2503 }
2504
2505 /* Get an underlying socket object from tun file. Returns error unless file is
2506 * attached to a device. The returned object works like a packet socket, it
2507 * can be used for sock_sendmsg/sock_recvmsg. The caller is responsible for
2508 * holding a reference to the file for as long as the socket is in use. */
2509 struct socket *tun_get_socket(struct file *file)
2510 {
2511 struct tun_file *tfile;
2512 if (file->f_op != &tun_fops)
2513 return ERR_PTR(-EINVAL);
2514 tfile = file->private_data;
2515 if (!tfile)
2516 return ERR_PTR(-EBADFD);
2517 return &tfile->socket;
2518 }
2519 EXPORT_SYMBOL_GPL(tun_get_socket);
2520
2521 module_init(tun_init);
2522 module_exit(tun_cleanup);
2523 MODULE_DESCRIPTION(DRV_DESCRIPTION);
2524 MODULE_AUTHOR(DRV_COPYRIGHT);
2525 MODULE_LICENSE("GPL");
2526 MODULE_ALIAS_MISCDEV(TUN_MINOR);
2527 MODULE_ALIAS("devname:net/tun");