-
Notifications
You must be signed in to change notification settings - Fork 0
/
filter.c
1542 lines (1359 loc) · 51.4 KB
/
filter.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*********************************************************
* Copyright (C) 2006 VMware, Inc. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation version 2 and no later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*********************************************************/
#include "driver-config.h"
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/version.h>
#include <linux/socket.h>
#include <linux/if_ether.h>
#include <linux/in.h>
#include <linux/ip.h>
#include "compat_skbuff.h"
#include <linux/mutex.h>
#include <linux/netdevice.h>
/*
* All this makes sense only if NETFILTER support is configured in our kernel.
*/
#ifdef CONFIG_NETFILTER
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/poll.h>
#include "vnetFilter.h"
#include "vnetFilterInt.h"
#include "vnetInt.h"
#include "vmnetInt.h"
// VNet_FilterLogPacket.action for dropped packets
#define VNET_FILTER_ACTION_DRP (1)
#define VNET_FILTER_ACTION_DRP_SHORT (2)
#define VNET_FILTER_ACTION_DRP_MATCH (3)
#define VNET_FILTER_ACTION_DRP_DEFAULT (4)
// VNet_FilterLogPacket.action for forwarded packets
#define VNET_FILTER_ACTION_FWD (1<<8 | 1)
#define VNET_FILTER_ACTION_FWD_LOOP (1<<8 | 5)
#define VNET_FILTER_ACTION_FWD_MATCH (1<<8 | 6)
#define VNET_FILTER_ACTION_FWD_DEFAULT (1<<8 | 7)
/* netfilter hooks for filtering. */
static nf_hookfn VNetFilterHookFn;
static struct nf_hook_ops vmnet_nf_ops[] = {
{ .hook = VNetFilterHookFn,
.owner = THIS_MODULE,
.pf = PF_INET,
.hooknum = VMW_NF_INET_LOCAL_IN,
.priority = NF_IP_PRI_FILTER - 1, },
{ .hook = VNetFilterHookFn,
.owner = THIS_MODULE,
.pf = PF_INET,
.hooknum = VMW_NF_INET_POST_ROUTING,
.priority = NF_IP_PRI_FILTER - 1, }
};
/* track if we actually set a callback in IP's filter driver */
static Bool installedFilterCallback = FALSE;
/* rules to use for filtering */
RuleSet *ruleSetHead = NULL; /* linked list of all rules */
int32 numRuleSets = 0; /* number of rule sets in ruleSetHead's linked list */
RuleSet *activeRule = NULL; /* actual rule set for filter callback to use */
/* locks to protect against concurrent accesses. */
static DEFINE_MUTEX(filterIoctlMutex); /* serialize ioctl()s from user space. */
/*
* user/netfilter hook concurrency lock.
* This spinlock doesn't scale well if/when in the future the netfilter
* callbacks can be concurrently executing on multiple threads on multiple
* CPUs, so we should revisit locking for allowing for that in the future.
*/
static DEFINE_SPINLOCK(activeRuleLock);
/*
* Logging.
*
* All logging for development build uses LOG(2, (KERN_INFO ...)) because the default
* log level is set to 1 (vnetInt.h). All ACE logging, i.e. policy driven logging, uses
* printk(KERN_INFO ...).
*/
static uint32 logLevel = VNET_FILTER_LOGLEVEL_NORMAL; /* the current log level */
static void LogPacket(uint16 action, void *header, void *data,
uint32 length, Bool drop);
static int InsertHostFilterCallback(void);
static void RemoveHostFilterCallback(void);
static RuleSet *FindRuleSetById(uint32 id, RuleSet ***prevPtr);
static int CreateRuleSet(uint32 id, uint32 defaultAction);
static void DeleteRule(Rule *rule);
static int DeleteRuleSet(uint32 id);
static int ChangeRuleSet(uint32 id, Bool enable, Bool disable, uint32 action);
static int AddIPv4Rule(uint32 id, VNet_AddIPv4Rule *rule,
VNet_IPv4Address *addressList,
VNet_IPv4Port *portList);
/*
*----------------------------------------------------------------------
*
* DropPacket --
*
* Function is used to record information regarding a packet
* being dropped.
*
* Results:
* void
*
* Side effects:
* Might store information regarding the packet.
*
*----------------------------------------------------------------------
*/
static INLINE void
DropPacket(uint16 action, // IN: reason code
void *header, // IN: packet header
void *data, // IN: packet data
uint32 length) // IN: packet length
{
LogPacket(action, header, data, length, TRUE);
}
/*
*----------------------------------------------------------------------
*
* ForwardPacket --
*
* Function is used to record information regarding a packet
* being forwarded.
*
* Results:
* void
*
* Side effects:
* Might store information regarding the packet.
*
*----------------------------------------------------------------------
*/
static INLINE void
ForwardPacket(uint16 action, // IN: reason code
void *header, // IN: packet header
void *data, // IN: packet data
uint32 length) // IN: packet length
{
#ifdef DBG
LogPacket(action, header, data, length, FALSE);
#endif
}
/*
*----------------------------------------------------------------------
*
* VNetFilterHookFn --
*
* Function is registered as a callback function with the host's
* IP stack. This function can be used to filter on specified protocols
* IP addresses, and/or local and remote ports. It makes use of the Linux
* netfilter infrastructure, by inserting this function in netfilter at a
* priority 1 higher than iptables, so that we don't have to worry about
* any existing iptables based firewall rules on the Linux hosts.
*
* Results:
* NF_ACCEPT or NF_DROP.
*
* Side effects:
* None besides those described above.
*
*----------------------------------------------------------------------
*/
#define DEBUG_HOST_FILTER 0
#if DEBUG_HOST_FILTER
#define HostFilterPrint(a) printk a
#else
#define HostFilterPrint(a)
#endif
static unsigned int
VNetFilterHookFn(unsigned int hooknum, // IN:
#ifdef VMW_NFHOOK_USES_SKB
struct sk_buff *skb, // IN:
#else
struct sk_buff **pskb, // IN:
#endif
const struct net_device *in, // IN:
const struct net_device *out, // IN:
int (*okfn)(struct sk_buff *)) // IN:
{
#ifndef VMW_NFHOOK_USES_SKB
struct sk_buff *skb = *pskb;
#endif
struct iphdr *ip;
uint32 remoteAddr;
uint16 localPort;
uint16 remotePort;
uint8 *packet;
uint8 *packetHeader;
int packetLength;
RuleSet *currRuleSet;
Bool blockByDefault;
Bool transmit; /* TRUE if transmitting, FALSE is receiving */
Rule *currRule;
unsigned int verdict = NF_ACCEPT;
unsigned long flags;
/* Early checks to see we should even care. */
if (skb->protocol != htons(ETH_P_IP)) {
return verdict;
}
spin_lock_irqsave(&activeRuleLock, flags);
currRuleSet = activeRule;
// ASSERT(currRuleSet);
/*
* Function uses a local copy of ruleSetHead so that we're
* not adversely affected by any rule changes that might occur
* while this function is running.
*/
blockByDefault = currRuleSet->action == VNET_FILTER_RULE_BLOCK;
/* When the host transmits, hooknum is VMW_NF_INET_POST_ROUTING. */
/* When the host receives, hooknum is VMW_NF_INET_LOCAL_IN. */
transmit = (hooknum == VMW_NF_INET_POST_ROUTING);
packetHeader = compat_skb_network_header(skb);
ip = (struct iphdr*)packetHeader;
if (transmit) {
/* skb all set up for us. */
packet = compat_skb_transport_header(skb);
} else {
/* skb hasn't had a chance to be processed by TCP yet. */
packet = compat_skb_network_header(skb) + (ip->ihl << 2);
}
HostFilterPrint(("PacketFilter: IP ver %d ihl %d tos %d len %d id %d\n"
" offset %d ttl %d proto %d xsum %d\n"
" src 0x%08x dest 0x%08x %s\n",
ip->version, ip->ihl, ip->tos, ip->tot_len, ip->id,
ip->frag_off, ip->ttl, ip->protocol, ip->check,
ip->saddr, ip->daddr, transmit ? "OUTGOING":"INCOMING"));
/*
* For incoming packets, there should be a skb->dev associated with it, with
* a populated L2 address length.
*/
if (skb->dev && skb->dev->hard_header_len) {
packetLength = skb->len - skb->dev->hard_header_len - (ip->ihl << 2);
} else {
/*
* In certain cases, compat_skb_mac_header() has been observed to be NULL. Don't
* know why, but in such cases, this calculation will lead to a negative
* packetLength, and the packet to be dropped.
*/
packetLength = skb->len -
(compat_skb_network_header(skb) - compat_skb_mac_header(skb)) -
(ip->ihl << 2);
}
if (packetLength < 0) {
HostFilterPrint(("PacketFilter: ill formed packet for IPv4\n"));
HostFilterPrint(("skb: len %d h.raw %p nh.raw %p mac.raw %p, packetLength %d\n",
skb->len, compat_skb_transport_header(skb),
compat_skb_network_header(skb),
compat_skb_mac_header(skb), packetLength));
verdict = NF_DROP;
DropPacket(VNET_FILTER_ACTION_DRP_SHORT, packetHeader, packet, 0);
goto out_unlock;
}
remoteAddr = transmit ? ip->daddr : ip->saddr;
/* always allow 127/8. */
if ((remoteAddr & 0xff) == 127) {
HostFilterPrint(("PacketFilter: allowing %s loopback 0x%08x\n",
transmit ? "outgoing" : "incoming",
remoteAddr));
ForwardPacket(VNET_FILTER_ACTION_FWD_LOOP,
packetHeader, packet, packetLength);
goto out_unlock;
}
/* If we're dealing with TCP or UDP, then extract the port information */
if (ip->protocol == IPPROTO_TCP || ip->protocol == IPPROTO_UDP) {
uint16 srcPort, dstPort; /* used to extract port information from packet */
if (packetLength < 4) {
HostFilterPrint(("PacketFilter: payload too short for "
"TCP or UDP: %d\n", packetLength));
verdict = NF_DROP;
DropPacket(VNET_FILTER_ACTION_DRP_SHORT,
packetHeader, packet, packetLength);
goto out_unlock;
}
/* Retrieve UDP/TCP port info */
srcPort = *((uint16*)&packet[0]);
dstPort = *((uint16*)&packet[2]);
if (transmit) { /* transmit */
localPort = ntohs(srcPort);
remotePort = ntohs(dstPort);
} else { /* receive */
localPort = ntohs(dstPort);
remotePort = ntohs(srcPort);
}
HostFilterPrint(("PacketFilter: got local port %d remote port %d\n",
localPort, remotePort));
} else {
/* these mostly exist to silence compiler warning about uninit variables */
localPort = 0;
remotePort = 0;
}
currRule = currRuleSet->list;
/* traverse all the rules in the rule set */
while (currRule != NULL) {
uint32 i;
Bool matchedAddress;
/* if direction doesn't match rule, then skip */
if ((currRule->direction == VNET_FILTER_DIRECTION_IN && transmit) ||
(currRule->direction == VNET_FILTER_DIRECTION_OUT && !transmit)) {
HostFilterPrint(("PacketFilter: didn't match direction\n"));
/* wrong direction */
goto skipRule;
}
/*
* Check if the packet's address matches the rule. If the list is empty
* then this means we don't care about address and it's considered a match.
*/
matchedAddress = (currRule->addressListLen == 0); /* empty list means don't care */
for (i = 0; i < currRule->addressListLen; ++i) {
if ((remoteAddr & currRule->addressList[i].ipv4Mask) ==
currRule->addressList[i].ipv4Addr) {
matchedAddress = TRUE;
HostFilterPrint(("PacketFilter: rule matched ip addr %u: "
"0x%08x == 0x%08x\n", i, remoteAddr,
currRule->addressList[i].ipv4Addr));
break;
} else {
HostFilterPrint(("PacketFilter: rule not match ip addr %u: "
"0x%08x != 0x%08x\n", i, remoteAddr,
currRule->addressList[i].ipv4Addr));
}
}
if (!matchedAddress) {
HostFilterPrint(("PacketFilter: rule didn't match ip addr 0x%08x\n",
remoteAddr));
/* ip addr doesn't match */
goto skipRule;
}
/*
* Check the protocol. ~0 (0xffff) means we don't care about the
* protocol and it's considered a match.
*/
if (currRule->proto != 0xffff && currRule->proto != ip->protocol) {
HostFilterPrint(("PacketFilter: didn't match protocol: %u != %u\n",
ip->protocol, currRule->proto));
/* protocol doesn't match */
goto skipRule;
}
/*
* If the protocol is TCP or UDP then check the port list. If the list is empty
* then this means we don't care about ports and it's considered a match.
*/
if (currRule->proto == IPPROTO_TCP || currRule->proto == IPPROTO_UDP) {
/* An empty list means the rule don't care about port numbers*/
Bool matchedPort = (currRule->portListLen == 0);
for (i = 0; i < currRule->portListLen; ++i) {
RulePort *portRule = currRule->portList + i;
Bool matchedLocal, matchedRemote; /* improves readability */
/*
* It's presumed that if portRule->localPortLow == ~0 then
* portRule->localPortHigh == ~0. Similiar story for the
* remote ports.
*/
matchedLocal = (localPort >= portRule->localPortLow &&
localPort <= portRule->localPortHigh) ||
portRule->localPortLow == ~0;
matchedRemote = (remotePort >= portRule->remotePortLow &&
remotePort <= portRule->remotePortHigh) ||
portRule->remotePortLow == ~0;
if (matchedLocal && matchedRemote) {
HostFilterPrint(("PacketFilter: matched rule's "
"port element %u\n", i));
matchedPort = TRUE;
break;
}
HostFilterPrint(("PacketFilter: didn't match rule's "
"port element %u\n", i));
HostFilterPrint(("-- local %4u not in range [%4u, %4u] or \n",
localPort, portRule->localPortLow,
portRule->localPortHigh));
HostFilterPrint(("-- remote %4u not in range [%4u, %4u]\n",
remotePort, portRule->remotePortLow,
portRule->remotePortHigh));
}
if (!matchedPort) {
HostFilterPrint(("PacketFilter: rule didn't match port "
"(local %u remote %u)\n", localPort, remotePort));
/* port doesn't match */
goto skipRule;
}
}
/* rule matches so follow orders */
if (currRule->action == VNET_FILTER_RULE_ALLOW) {
HostFilterPrint(("PacketFilter: found match, forwarding\n"));
ForwardPacket(VNET_FILTER_ACTION_FWD_MATCH,
packetHeader, packet, packetLength);
goto out_unlock;
} else {
HostFilterPrint(("PacketFilter: found match, dropping\n"));
verdict = NF_DROP;
DropPacket(VNET_FILTER_ACTION_DRP_MATCH,
packetHeader, packet, packetLength);
goto out_unlock;
}
skipRule:
currRule = currRule->next;
}
/* Forward or drop packet based on the default rule */
HostFilterPrint(("PacketFilter: Didn't find match for %s "
"%u.%u.%u.%u, %s packet\n",
transmit ? "outgoing" : "incoming",
remoteAddr & 0xff, (remoteAddr >> 8) & 0xff,
(remoteAddr >> 16) & 0xff, (remoteAddr >> 24) & 0xff,
blockByDefault ? "drop" : "forward"));
if (blockByDefault) {
verdict = NF_DROP;
DropPacket(VNET_FILTER_ACTION_DRP_DEFAULT,
packetHeader, packet, packetLength);
} else {
ForwardPacket(VNET_FILTER_ACTION_FWD_DEFAULT,
packetHeader, packet, packetLength);
}
out_unlock:
spin_unlock_irqrestore(&activeRuleLock, flags);
return verdict;
}
/*
*----------------------------------------------------------------------
*
* InsertHostFilterCallback --
*
* Function registers a hook in the host's IP stack.
*
* Results:
* 0 on success (or if hook already installed),
* errno on failure.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static int
InsertHostFilterCallback(void)
{
uint32 i;
int retval = 0;
LOG(2, (KERN_INFO "vnet filter inserting callback\n"));
if (installedFilterCallback) {
LOG(2, (KERN_INFO "vnet filter callback already registered\n"));
goto end;
}
/* Register netfilter hooks. */
for (i = 0; i < ARRAY_SIZE(vmnet_nf_ops); i++) {
if ((retval = nf_register_hook(&vmnet_nf_ops[i])) >= 0) {
continue;
}
/* Encountered an error, back out. */
LOG(2, (KERN_INFO "vnet filter failed to register callback %d: %d\n",
i, retval));
while (i--) {
nf_unregister_hook(&vmnet_nf_ops[i]);
}
goto end;
}
installedFilterCallback = TRUE;
LOG(2, (KERN_INFO "Successfully set packet filter function\n"));
end:
return retval;
}
/*
*----------------------------------------------------------------------
*
* RemoveHostFilterCallback --
*
* Function deregisters a hook in the host's IP stack.
*
* Results:
* void
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static void
RemoveHostFilterCallback(void)
{
int i;
LOG(2, (KERN_INFO "vnet filter removing callback\n"));
if (installedFilterCallback) {
LOG(2, (KERN_INFO "filter callback was installed: removing filter\n"));
for (i = ARRAY_SIZE(vmnet_nf_ops) - 1; i >= 0; i--) {
nf_unregister_hook(&vmnet_nf_ops[i]);
}
installedFilterCallback = FALSE;
}
LOG(2, (KERN_INFO "vnet filter remove callback done\n"));
}
/*
*----------------------------------------------------------------------
*
* FindRuleSetById --
*
* Function is given an ID for a rule set, and returns a
* pointer to the ruleset with that ID. The function can
* optionally report what pointer is pointing to this item
* (suitable for removing the item from the linked list -- the
* result might be the prior item's next pointer, or the head).
*
* Results:
* NULL if rule set not found, otherwise pointer to rule set.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static RuleSet *
FindRuleSetById(uint32 id, // IN: id to locate
RuleSet ***prevPtr) // OUT: pointer to the ->next pointer
// (or head) that points to the
// returned item (optional)
{
RuleSet *curr;
RuleSet **prev = NULL;
// ASSERT(id != 0);
curr = ruleSetHead;
prev = &ruleSetHead;
while (curr != NULL) {
if (curr->id == id) {
LOG(2, (KERN_INFO "Found id %u at %p\n", id, curr));
if (prevPtr != NULL) {
*prevPtr = prev;
}
return curr;
}
prev = &curr->next;
curr = curr->next;
}
LOG(2, (KERN_INFO "Didn't find ruleset with id %u\n", id));
/* won't overwrite *prevPtr with NULL */
return NULL;
}
/*
*----------------------------------------------------------------------
*
* CreateRuleSet --
*
* Function creates a new rule set with a specified ID and
* default action. Call will fail if failed to alloc memory,
* or if ID is already in use, or if maximum number of
* rule sets have already been created.
*
* Results:
* Returns 0 on success, and otherwise returns errno.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static int
CreateRuleSet(uint32 id, // IN: requested ID for new rule set
uint32 defaultAction) // IN: default action for rule set
{
RuleSet *newRuleSet;
RuleSet *curr;
/* check if too many rule sets already exist */
if (numRuleSets >= MAX_RULE_SETS) {
LOG(2, (KERN_INFO "filter already has all rules (%u of %u) allocated\n",
numRuleSets, MAX_RULE_SETS));
return -EOVERFLOW;
}
/* check if ID is already in use */
curr = FindRuleSetById(id, NULL);
if (curr != NULL) {
LOG(2, (KERN_INFO "filter already has id %u\n", id));
return -EEXIST;
}
/* allocate and init new rule set */
newRuleSet = kmalloc(sizeof *newRuleSet, GFP_USER);
if (newRuleSet == NULL) {
LOG(2, (KERN_INFO "filter mem alloc failed\n"));
return -ENOMEM;
}
memset(newRuleSet, 0, sizeof *newRuleSet);
newRuleSet->next = ruleSetHead;
newRuleSet->id = id;
newRuleSet->enabled = FALSE;
newRuleSet->action = (uint16)defaultAction;
newRuleSet->list = NULL;
newRuleSet->numRules = 0;
newRuleSet->tail = &newRuleSet->list;
/* add new rule set to head of linked list */
numRuleSets++;
ruleSetHead = newRuleSet;
LOG(2, (KERN_INFO "filter created ruleset with id %u\n", id));
return 0;
}
/*
*----------------------------------------------------------------------
*
* DeleteRule --
*
* Function frees the memory in a Rule object. This function
* frees the arrays in the Rule, but not an elements that
* are chained on the linked-list via 'next'.
*
* Results:
* None.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static void
DeleteRule(Rule *rule) // IN: Rule to delete.
{
// ASSERT(rule);
if (!rule) {
return;
}
if (rule->addressList) {
kfree(rule->addressList);
rule->addressList = NULL;
}
if (rule->portList) {
kfree(rule->portList);
rule->portList = NULL;
}
kfree(rule);
}
/*
*----------------------------------------------------------------------
*
* DeleteRuleSet --
*
* Function deletes a rule set with a specified ID. Call will fail
* if ID not found or if the current rule set is being used for
* filtering.
*
* Results:
* Returns 0 on success, errno on failure.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static int
DeleteRuleSet(uint32 id) // IN: ID of new rule set to delete
{
RuleSet **prev = NULL;
RuleSet *curr;
Rule *currRule;
/* locate the ruleset with the specified ID */
curr = FindRuleSetById(id, &prev);
if (curr == NULL) {
LOG(2, (KERN_INFO "filter did not find id %u to delete\n", id));
return -ESRCH;
}
LOG(2, (KERN_INFO "found id %u\n", id));
/* check if in use */
if (curr->enabled) {
LOG(2, (KERN_INFO "Can't delete id %u since enabled\n", id));
return -EBUSY;
}
/* remove item from linked list */
*prev = curr->next;
/* free rules in rule set */
currRule = curr->list;
curr->list = NULL; /* help mitigate any bugs or races */
while (currRule) {
Rule *temp = currRule->next;
currRule->next = NULL; /* help mitigate any bugs or races */
DeleteRule(currRule);
currRule = temp;
}
kfree(curr);
numRuleSets--;
// ASSERT(numRuleSets >= 0);
return 0;
}
/*
*----------------------------------------------------------------------
*
* ChangeRuleSet --
*
* This function is used to specify which rule set is to be used
* for filtering (or stop using for filtering). If another
* rule set is currently used for filtering then the specified
* rule set will replace it. This funciton can also be used to
* change the default action for any rule set, but this option
* should not be used when disabling a rule set.
*
* Call will fail if ID can't be found, or when attempting to
* disable a rule set that's not enabled.
*
* Results:
* Returns 0 on success, errno on failure.
*
* Side effects:
* May add/remove filter callback.
*
*----------------------------------------------------------------------
*/
static int
ChangeRuleSet(uint32 id, // IN: requested ID of rule set
Bool enable, // IN: TRUE says start using this rule for filtering
Bool disable, // IN: TRUE says stop using this rule for filtering
uint32 action) // IN: default action for rule set
{
RuleSet *curr;
int retval;
unsigned long flags;
// ASSERT(!enable || !disable); /* at most one can be set */
LOG(2, (KERN_INFO "changeruleset %d enable %d disable %d action %x\n", id,
enable, disable, action));
/* locate the specified rule set */
curr = FindRuleSetById(id, NULL);
if (curr == NULL) {
LOG(2, (KERN_INFO "vnet filter can't find ruleset: %u\n", id));
return -ESRCH;
}
if (enable) {
RuleSet *oldActive;
if (action != VNET_FILTER_RULE_NO_CHANGE) {
LOG(2, (KERN_INFO "vnet filter changing default action "
"of active rule set: %u (id %u)\n", action, id));
curr->action = (uint16)action;
}
/* enable new rule */
curr->enabled = TRUE;
/* Grab activeRule spinlock. */
spin_lock_irqsave(&activeRuleLock, flags);
LOG(2, (KERN_INFO "changing active rule from "
"%p (%u) to %p (%u)\n", activeRule,
activeRule ? activeRule->id : 0,
curr, curr->id));
/* make rule active */
oldActive = activeRule;
activeRule = curr;
/* Safe to release activeRule spinlock now. */
spin_unlock_irqrestore(&activeRuleLock, flags);
/*
* Mark old rule as not enabled, except if it's the same
* as the newly enabled rule set.
*/
if (oldActive == NULL) {
// 1) activate (no current active)
LOG(2, (KERN_INFO "No prior rule was active\n"));
} else if (oldActive == curr) {
// 2) activate (current active, and same as this one)
LOG(2, (KERN_INFO "Activated rule that was already active\n"));
} else { /* oldActive != NULL && oldActive != curr */
// 3) activate (current active, and different than this one)
LOG(2, (KERN_INFO "Deactivating old rule: %p (id %u)\n",
oldActive, oldActive->id));
oldActive->enabled = FALSE;
}
if ((retval = InsertHostFilterCallback()) != 0) {
LOG(2, (KERN_INFO "Failed to insert filter in IP\n"));
}
} else if (disable) {
if (!curr->enabled) {
// 4) deactive (but not currently active)
LOG(2, (KERN_INFO "vnet filter tried to deactive a "
"non-active rule: %u\n", id));
if (activeRule) {
// ASSERT(activeRule != curr);
LOG(2, (KERN_INFO "-- current active is %p (id %u)\n",
activeRule, activeRule->id));
} else {
LOG(2, (KERN_INFO "-- no rule is currently active\n"));
}
/* in this case we'll also not change the default action */
return -EINVAL;
}
// 5) deactive (and currently active)
LOG(2, (KERN_INFO "vnet filter deactivating %p (id %u)\n",
curr, id));
RemoveHostFilterCallback();
// ASSERT(activeRule == curr);
/* Grab activeRule spinlock. */
spin_lock_irqsave(&activeRuleLock, flags);
activeRule = NULL;
/* Safe to release activeRule spinlock now. */
spin_unlock_irqrestore(&activeRuleLock, flags);
curr->enabled = FALSE;
if (action != VNET_FILTER_RULE_NO_CHANGE) {
LOG(2, (KERN_INFO "vnet filter changing default action: "
"%u (id %u)\n", action, id));
curr->action = (uint16)action;
}
retval = 0;
} else { /* !enable && !disable */
if (action == VNET_FILTER_RULE_NO_CHANGE) {
// 6) no activate change (and default not changed)
LOG(2, (KERN_INFO "vnet filter got nothing to change\n"));
retval = 0;
}
// 7) no activate change (but default action changed)
curr->action = (uint16)action;
LOG(2, (KERN_INFO "vnet filter changed action: %u\n", action));
retval = 0;
}
return retval;
}
/*
*----------------------------------------------------------------------
*
* AddIPv4Rule --
*
* Function is used to add an IPv4 rule to a rule set.
* Call will fail if failed to alloc memory, or if specified
* ID was not found. The actual rule is not sanity checked,
* as it's presumed the caller did this.
*
* Results:
* Returns 0 on success, errno on failure.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static int
AddIPv4Rule(uint32 id, // IN: requested ID of rule set
VNet_AddIPv4Rule *rule, // IN: rule to add
VNet_IPv4Address *addressList, // IN: list of addresses
VNet_IPv4Port *portList) // IN: list of ports
{
Rule *newRule;
RuleSet *curr;
// ASSERT(rule && addressList && portList);
/* locate the rule set with the specified ID */
curr = FindRuleSetById(id, NULL);
if (curr == NULL) {
LOG(2, (KERN_INFO "vnet filter can't find ruleset: %u\n", id));
return -ESRCH;
}
/* make sure that we don't have too many rules already */
if (curr->numRules >= MAX_RULES_PER_SET) {
LOG(2, (KERN_INFO "vnet filter has too many rules in ruleset: %u >= %u\n",
curr->numRules, MAX_RULES_PER_SET));
return -EOVERFLOW;
}
/* allocate and init rule */
newRule = kmalloc(sizeof *newRule, GFP_USER);
if (newRule == NULL) {
LOG(2, (KERN_INFO "vnet filter mem alloc failed for rule\n"));
return -ENOMEM;
}
memset(newRule, 0, sizeof *newRule);
newRule->action = (uint16)rule->action;
newRule->direction = (uint16)rule->direction;
newRule->proto = (uint16)rule->proto;
// ASSERT(rule->addressListLen <= 255); /* double-check for data truncation */
newRule->addressListLen = (uint8)rule->addressListLen;
if (newRule->addressListLen == 1 &&
addressList[0].ipv4RemoteAddr == 0 &&
addressList[0].ipv4RemoteMask == 0) {
newRule->addressListLen = 0;
LOG(2, (KERN_INFO "vnet filter address has single don't care rule\n"));
}
// ASSERT(rule->portListLen <= 255); /* double-check for data truncation */
newRule->portListLen = (uint8)rule->portListLen;
if (newRule->portListLen == 1 &&
portList[0].localPortLow == ~0 &&
portList[0].localPortHigh == ~0 &&
portList[0].remotePortLow == ~0 &&
portList[0].remotePortHigh == ~0) {