-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathvmops
More file actions
executable file
·1645 lines (1399 loc) · 61.1 KB
/
vmops
File metadata and controls
executable file
·1645 lines (1399 loc) · 61.1 KB
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
#!/usr/bin/env python3
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# Version @VERSION@
#
# A plugin for executing script needed by vmops cloud
import os, sys, time
import XenAPIPlugin
if os.path.exists("/opt/xensource/sm"):
sys.path.extend(["/opt/xensource/sm/", "/usr/local/sbin/", "/sbin/"])
if os.path.exists("/usr/lib/xcp/sm"):
sys.path.extend(["/usr/lib/xcp/sm/", "/usr/local/sbin/", "/sbin/"])
import base64
import socket
import stat
import tempfile
import util
import subprocess
import zlib
import cloudstack_pluginlib as lib
import logging
from util import CommandException
lib.setup_logging("/var/log/cloud/cloud.log")
def echo(fn):
def wrapped(*v, **k):
name = fn.__name__
#command string is logged in SMlog, so method enter/exit logging into SMlog will help for debugging
util.SMlog("#### CLOUD enter %s ####" % name )
res = fn(*v, **k)
util.SMlog("#### CLOUD exit %s ####" % name )
return res
return wrapped
@echo
def add_to_VCPUs_params_live(session, args):
key = args['key']
value = args['value']
vmname = args['vmname']
try:
cmd = ["bash", "/opt/cloud/bin/add_to_vcpus_params_live.sh", vmname, key, value]
txt = util.pread2(cmd)
except:
return 'false'
return 'true'
@echo
def setup_iscsi(session, args):
uuid=args['uuid']
try:
cmd = ["bash", "/opt/cloud/bin/setup_iscsi.sh", uuid]
txt = util.pread2(cmd)
except:
txt = ''
return txt
@echo
def preparemigration(session, args):
uuid = args['uuid']
try:
cmd = ["/opt/cloud/bin/make_migratable.sh", uuid]
util.pread2(cmd)
txt = 'success'
except:
logging.debug("Catch prepare migration exception" )
txt = ''
return txt
@echo
def setIptables(session, args):
try:
cmd = ["/bin/bash", "/opt/cloud/bin/setupxenserver.sh"]
txt = util.pread2(cmd)
txt = 'success'
except:
logging.debug(" setIptables execution failed " )
txt = ''
return txt
@echo
def pingdomr(session, args):
host = args['host']
port = args['port']
socket.setdefaulttimeout(3)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((host,int(port)))
txt = 'success'
except:
txt = ''
s.close()
return txt
@echo
def kill_copy_process(session, args):
namelabel = args['namelabel']
try:
cmd = ["bash", "/opt/cloud/bin/kill_copy_process.sh", namelabel]
txt = util.pread2(cmd)
except:
txt = 'false'
return txt
@echo
def pingxenserver(session, args):
txt = 'success'
return txt
def pingtest(session, args):
sargs = args['args']
cmd = sargs.split(' ')
cmd.insert(0, "/opt/cloud/bin/pingtest.sh")
cmd.insert(0, "/bin/bash")
try:
txt = util.pread2(cmd)
txt = 'success'
except:
logging.debug(" pingtest failed " )
txt = ''
return txt
@echo
def setLinkLocalIP(session, args):
brName = args['brName']
try:
cmd = ["ip", "route", "del", "169.254.0.0/16"]
txt = util.pread2(cmd)
except:
txt = ''
try:
cmd = ["ifconfig", brName, "169.254.0.1", "netmask", "255.255.0.0"]
txt = util.pread2(cmd)
except:
try:
cmd = ['cat', '/etc/xensource/network.conf']
result = util.pread2(cmd)
except:
return 'can not cat network.conf'
if result.lower().strip() == "bridge":
try:
cmd = ["brctl", "addbr", brName]
txt = util.pread2(cmd)
except:
pass
else:
try:
cmd = ["ovs-vsctl", "add-br", brName]
txt = util.pread2(cmd)
except:
pass
try:
cmd = ["ifconfig", brName, "169.254.0.1", "netmask", "255.255.0.0"]
txt = util.pread2(cmd)
except:
pass
try:
cmd = ["ip", "route", "add", "169.254.0.0/16", "dev", brName, "src", "169.254.0.1"]
txt = util.pread2(cmd)
except:
txt = ''
txt = 'success'
return txt
@echo
def createFile(session, args):
file_path = args['filepath']
file_contents = args['filecontents']
try:
f = open(file_path, "w")
f.write(file_contents)
f.close()
txt = 'success'
except:
logging.debug(" failed to create HA proxy cfg file ")
txt = ''
return txt
@echo
def secureCopyToHost(session, args):
host_filepath = args['hostfilepath']
src_ip = args['srcip']
src_filepath = args['srcfilepath']
src_target = "root@" + src_ip + ":" + src_filepath
# Make any directories as needed
if not os.path.isdir(host_filepath):
try:
os.makedirs(host_filepath)
except OSError as e:
if not os.path.isdir(host_filepath):
errMsg = "OSError while creating " + host_filepath + " with errno: " + str(e.errno) + " and strerr: " + e.strerror
logging.debug(errMsg)
return "fail# Cannot create the directory to copy file to " + host_filepath
# Copy file to created directory
txt=""
try:
txt = util.pread2(['scp','-P','3922','-q','-o','StrictHostKeyChecking=no','-i','/root/.ssh/id_rsa.cloud', src_target, host_filepath])
util.pread2(['chmod', 'a+r', os.path.join(host_filepath, os.path.basename(src_filepath))])
txt = 'success#' + txt
except:
logging.error("failed to scp source target " + src_target + " to host at file path " + host_filepath)
txt = 'fail#' + txt
return txt
@echo
def createFileInDomr(session, args):
src_filepath = args['srcfilepath']
dst_path = args['dstfilepath']
domrip = args['domrip']
cleanup = 'true' if 'cleanup' not in args else args['cleanup']
txt=""
try:
target = "root@" + domrip + ":" + dst_path
txt = util.pread2(['scp','-P','3922','-q','-o','StrictHostKeyChecking=no','-i','/root/.ssh/id_rsa.cloud',src_filepath, target])
if cleanup == 'true' or not cleanup:
util.pread2(['rm',src_filepath])
txt = 'succ#' + txt
except:
logging.debug("failed to copy file " + src_filepath + " from host to VR with ip " + domrip)
txt = 'fail#' + txt
return txt
@echo
def runPatchScriptInDomr(session, args):
domrip = args['domrip']
txt=""
try:
target = "root@" + domrip
txt = util.pread2(['ssh','-p','3922','-i','/root/.ssh/id_rsa.cloud', target, "/bin/bash","/var/cache/cloud/patch-sysvms.sh"])
txt = 'succ#' + txt
except:
logging.debug("failed to run patch script in systemVM with IP: " + domrip)
txt = 'fail#' + txt
return txt
@echo
def deleteFile(session, args):
file_path = args["filepath"]
try:
if os.path.isfile(file_path):
os.remove(file_path)
txt = 'success'
except:
logging.debug(" failed to remove HA proxy cfg file ")
txt = ''
return txt
#using all the iptables chain names length to 24 because cleanup_rules groups the vm chain excluding -def,-eg
#to avoid multiple iptables chains for single vm, there using length 24
def chain_name(vm_name):
if vm_name.startswith('i-') or vm_name.startswith('r-'):
if vm_name.endswith('untagged'):
return '-'.join(vm_name.split('-')[:-1])
if len(vm_name) > 25:
vm_name = vm_name[0:24]
return vm_name
def chain_name_def(vm_name):
#iptables chain length max is 29 chars
if len(vm_name) > 25:
vm_name = vm_name[0:24]
if vm_name.startswith('i-'):
if vm_name.endswith('untagged'):
return '-'.join(vm_name.split('-')[:-1]) + "-def"
return vm_name + "-def"
if len(vm_name) > 28:
vm_name = vm_name[0:27]
return vm_name
def egress_chain_name(vm_name):
#iptables chain length max is 29 chars
name = chain_name(vm_name)
name = name+"-eg"
return name
#chain name length is 14 because it has protocol and ports appends
def chain_name_ipset(vm_name):
if vm_name.startswith('i-') or vm_name.startswith('r-'):
if vm_name.endswith('untagged'):
return ''.join(vm_name.split('')[:-1])
if len(vm_name) > 14:
vm_name = vm_name[0:13]
return vm_name
def egress_chain_name_ipset(vm_name):
name = chain_name_ipset(vm_name) + "-e"
return name
def ingress_chain_name_ipset(vm_name):
name = chain_name_ipset(vm_name)
return name
@echo
def can_bridge_firewall(session, args):
try:
util.pread2(['ebtables', '-V'])
util.pread2(['ipset', '-V'])
cmd = ['cat', '/etc/xensource/network.conf']
result = util.pread2(cmd)
if result.lower().strip() != "bridge":
return 'false'
except:
return 'false'
try:
util.pread2(['iptables', '-N', 'BRIDGE-FIREWALL'])
util.pread2(['iptables', '-I', 'BRIDGE-FIREWALL', '-m', 'state', '--state', 'RELATED,ESTABLISHED', '-j', 'ACCEPT'])
util.pread2(['iptables', '-A', 'BRIDGE-FIREWALL', '-m', 'physdev', '--physdev-is-bridged', '-p', 'udp', '--dport', '67', '--sport', '68', '-j', 'ACCEPT'])
util.pread2(['iptables', '-A', 'BRIDGE-FIREWALL', '-m', 'physdev', '--physdev-is-bridged', '-p', 'udp', '--dport', '68', '--sport', '67', '-j', 'ACCEPT'])
util.pread2(['iptables', '-D', 'FORWARD', '-j', 'RH-Firewall-1-INPUT'])
except:
logging.debug('Chain BRIDGE-FIREWALL already exists')
try:
util.pread2(['iptables', '-N', 'BRIDGE-DEFAULT-FIREWALL'])
util.pread2(['iptables', '-A', 'BRIDGE-DEFAULT-FIREWALL', '-m', 'state', '--state', 'RELATED,ESTABLISHED', '-j', 'ACCEPT'])
util.pread2(['iptables', '-A', 'BRIDGE-DEFAULT-FIREWALL', '-m', 'physdev', '--physdev-is-bridged', '-p', 'udp', '--dport', '67', '--sport', '68', '-j', 'ACCEPT'])
util.pread2(['iptables', '-A', 'BRIDGE-DEFAULT-FIREWALL', '-m', 'physdev', '--physdev-is-bridged', '-p', 'udp', '--dport', '68', '--sport', '67', '-j', 'ACCEPT'])
util.pread2(['iptables', '-I', 'BRIDGE-FIREWALL', '-j', 'BRIDGE-DEFAULT-FIREWALL'])
util.pread2(['iptables', '-D', 'BRIDGE-FIREWALL', '-m', 'state', '--state', 'RELATED,ESTABLISHED', '-j', 'ACCEPT'])
util.pread2(['iptables', '-D', 'BRIDGE-FIREWALL', '-m', 'physdev', '--physdev-is-bridged', '-p', 'udp', '--dport', '67', '--sport', '68', '-j', 'ACCEPT'])
util.pread2(['iptables', '-D', 'BRIDGE-FIREWALL', '-m', 'physdev', '--physdev-is-bridged', '-p', 'udp', '--dport', '68', '--sport', '67', '-j', 'ACCEPT'])
except:
logging.debug('Chain BRIDGE-DEFAULT-FIREWALL already exists')
result = 'true'
try:
util.pread2(['/bin/bash', '-c', 'iptables -n -L FORWARD | grep BRIDGE-FIREWALL'])
except:
try:
util.pread2(['iptables', '-I', 'FORWARD', '-m', 'physdev', '--physdev-is-bridged', '-j', 'BRIDGE-FIREWALL'])
util.pread2(['iptables', '-A', 'FORWARD', '-j', 'DROP'])
except:
return 'false'
default_ebtables_rules()
allow_egress_traffic(session)
if not os.path.exists('/var/run/cloud'):
os.makedirs('/var/run/cloud')
if not os.path.exists('/var/cache/cloud'):
os.makedirs('/var/cache/cloud')
#get_ipset_keyword()
cleanup_rules_for_dead_vms(session)
cleanup_rules(session, args)
return result
@echo
def default_ebtables_rules():
try:
util.pread2(['ebtables', '-N', 'DEFAULT_EBTABLES'])
util.pread2(['ebtables', '-A', 'FORWARD', '-j' 'DEFAULT_EBTABLES'])
util.pread2(['ebtables', '-A', 'DEFAULT_EBTABLES', '-p', 'IPv4', '--ip-dst', '255.255.255.255', '--ip-proto', 'udp', '--ip-dport', '67', '-j', 'ACCEPT'])
util.pread2(['ebtables', '-A', 'DEFAULT_EBTABLES', '-p', 'IPv4', '--ip-dst', '255.255.255.255', '--ip-proto', 'udp', '--ip-dport', '68', '-j', 'ACCEPT'])
util.pread2(['ebtables', '-A', 'DEFAULT_EBTABLES', '-p', 'ARP', '--arp-op', 'Request', '-j', 'ACCEPT'])
util.pread2(['ebtables', '-A', 'DEFAULT_EBTABLES', '-p', 'ARP', '--arp-op', 'Reply', '-j', 'ACCEPT'])
# deny mac broadcast and multicast
util.pread2(['ebtables', '-A', 'DEFAULT_EBTABLES', '-p', 'IPv4', '-d', 'Broadcast', '-j', 'DROP'])
util.pread2(['ebtables', '-A', 'DEFAULT_EBTABLES', '-p', 'IPv4', '-d', 'Multicast', '-j', 'DROP'])
# deny ip broadcast and multicast
util.pread2(['ebtables', '-A', 'DEFAULT_EBTABLES', '-p', 'IPv4', '--ip-dst', '255.255.255.255', '-j', 'DROP'])
util.pread2(['ebtables', '-A', 'DEFAULT_EBTABLES', '-p', 'IPv4', '--ip-dst', '224.0.0.0/4', '-j', 'DROP'])
util.pread2(['ebtables', '-A', 'DEFAULT_EBTABLES', '-p', 'IPv4', '-j', 'RETURN'])
# deny ipv6
util.pread2(['ebtables', '-A', 'DEFAULT_EBTABLES', '-p', 'IPv6', '-j', 'DROP'])
# deny vlan
util.pread2(['ebtables', '-A', 'DEFAULT_EBTABLES', '-p', '802_1Q', '-j', 'DROP'])
# deny all others (e.g., 802.1d, CDP)
util.pread2(['ebtables', '-A', 'DEFAULT_EBTABLES', '-j', 'DROP'])
except:
logging.debug('Chain DEFAULT_EBTABLES already exists')
@echo
def allow_egress_traffic(session):
devs = []
for pif in session.xenapi.PIF.get_all():
pif_rec = session.xenapi.PIF.get_record(pif)
dev = pif_rec.get('device')
devs.append(dev + "+")
for d in devs:
try:
util.pread2(['/bin/bash', '-c', "iptables -n -L FORWARD | grep '%s '" % d])
except:
try:
util.pread2(['iptables', '-I', 'FORWARD', '2', '-m', 'physdev', '--physdev-is-bridged', '--physdev-out', d, '-j', 'ACCEPT'])
except:
logging.debug("Failed to add FORWARD rule through to %s" % d)
return 'false'
return 'true'
def getIpsetType():
try:
out = util.pread2(['/bin/bash', '-c', "ipset -v | awk '{print $5}'"])
out.replace(".","")
if int(out) < 6:
return 'iptreemap'
else:
return 'nethash'
except:
return 'iptreemap'
def ipset(ipsetname, proto, start, end, cidrs):
type = getIpsetType()
try:
util.pread2(['ipset', '-N', ipsetname, type])
except:
logging.debug("ipset chain already exists: " + ipsetname)
result = True
ipsettmp = ''.join(''.join(ipsetname.split('-')).split('_')) + str(int(time.time()) % 1000)
try:
util.pread2(['ipset', '-N', ipsettmp, type])
except:
logging.debug("Failed to create temp ipset, reusing old name= " + ipsettmp)
try:
util.pread2(['ipset', '-F', ipsettmp])
except:
logging.debug("Failed to clear old temp ipset name=" + ipsettmp)
return False
try:
for cidr in cidrs:
try:
util.pread2(['ipset', '-A', ipsettmp, cidr])
except CommandException as cex:
logging.debug("ipset cidr add failed due to: " + str(cex.reason))
if cex.reason.rfind('already in set') == -1:
raise
except:
logging.debug("Failed to program ipset " + ipsetname)
util.pread2(['ipset', '-F', ipsettmp])
util.pread2(['ipset', '-X', ipsettmp])
return False
try:
util.pread2(['ipset', '-W', ipsettmp, ipsetname])
except:
logging.debug("Failed to swap ipset, trying to delete and swap ipset: " + ipsetname)
# the old ipset entry could be of iphash type, try to delete and recreate
try:
util.pread2(['ipset', '-X', ipsetname])
util.pread2(['ipset', '-N', ipsetname, type])
util.pread2(['ipset', '-W', ipsettmp, ipsetname])
except:
logging.debug("Failed to swap ipset " + ipsetname)
result = False
logging.debug("Succeeded in re-initializing and swapping ipset")
try:
util.pread2(['ipset', '-F', ipsettmp])
util.pread2(['ipset', '-X', ipsettmp])
except:
# if the temporary name clashes next time we'll just reuse it
logging.debug("Failed to delete temp ipset " + ipsettmp)
return result
@echo
def destroy_network_rules_for_vm(session, args):
vm_name = args.pop('vmName')
vmchain = chain_name(vm_name)
vmchain_egress = egress_chain_name(vm_name)
vmchain_default = chain_name_def(vm_name)
delete_rules_for_vm_in_bridge_firewall_chain(vm_name)
if vm_name.startswith('i-') or vm_name.startswith('r-') or vm_name.startswith('l-'):
try:
util.pread2(['iptables', '-F', vmchain_default])
util.pread2(['iptables', '-X', vmchain_default])
except:
logging.debug("Ignoring failure to delete chain " + vmchain_default)
destroy_ebtables_rules(vmchain)
destroy_arptables_rules(vmchain)
try:
util.pread2(['iptables', '-F', vmchain])
util.pread2(['iptables', '-X', vmchain])
except:
logging.debug("Ignoring failure to delete ingress chain " + vmchain)
try:
util.pread2(['iptables', '-F', vmchain_egress])
util.pread2(['iptables', '-X', vmchain_egress])
except:
logging.debug("Ignoring failure to delete egress chain " + vmchain_egress)
remove_rule_log_for_vm(vm_name)
remove_secip_log_for_vm(vm_name)
if 1 in [ vm_name.startswith(c) for c in ['r-', 's-', 'v-', 'l-'] ]:
return 'true'
try:
setscmd = "ipset --save | grep '%s' | grep -e '^-N' -e '^create' | awk '{print $2}'" % vmchain
ipset_names = filter(None, util.pread2(['/bin/bash', '-c', setscmd]).split('\n'))
for ipset_name in ipset_names:
if not ipset_name:
continue
util.pread2(['ipset', '-F', ipset_name])
util.pread2(['ipset', '-X', ipset_name])
except:
logging.debug("Failed to destroy ipsets for %" % vm_name)
return 'true'
@echo
def destroy_ebtables_rules(vm_chain):
delcmd = "ebtables-save | grep '%s' | sed 's/-A/-D/'" % vm_chain
delcmds = util.pread2(['/bin/bash', '-c', delcmd]).split('\n')
for cmd in filter(None, delcmds):
try:
dc = 'ebtables ' + cmd
util.pread2(filter(None, dc.split(' ')))
except:
logging.debug("Ignoring failure to delete ebtables rules for vm " + vm_chain)
try:
util.pread2(['ebtables', '-F', vm_chain])
util.pread2(['ebtables', '-X', vm_chain])
except:
logging.debug("Ignoring failure to delete ebtables chain for vm " + vm_chain)
@echo
def destroy_arptables_rules(vm_chain):
delcmd = "arptables -vL FORWARD | grep '%s' | sed 's/-i any//' | sed 's/-o any//' | awk '{print $1,$2,$3,$4}' " % vm_chain
delcmds = util.pread2(['/bin/bash', '-c', delcmd]).split('\n')
for cmd in filter(None, delcmds):
try:
dc = 'arptables -D FORWARD ' + cmd
util.pread2(filter(None, dc.split(' ')))
except:
logging.debug("Ignoring failure to delete arptables rules for vm " + vm_chain)
try:
util.pread2(['arptables', '-F', vm_chain])
util.pread2(['arptables', '-X', vm_chain])
except:
logging.debug("Ignoring failure to delete arptables chain for vm " + vm_chain)
@echo
def default_ebtables_antispoof_rules(vm_chain, vifs, vm_ip, vm_mac):
if vm_mac == 'ff:ff:ff:ff:ff:ff':
logging.debug("Ignoring since mac address is not valid")
return 'true'
try:
util.pread2(['ebtables', '-N', vm_chain])
except:
try:
util.pread2(['ebtables', '-F', vm_chain])
except:
logging.debug("Failed to create ebtables antispoof chain, skipping")
return 'true'
# note all rules for packets into the bridge (-i) precede all output rules (-o)
# always start after the first rule in the FORWARD chain that jumps to DEFAULT_EBTABLES chain
try:
for vif in vifs:
util.pread2(['ebtables', '-I', 'FORWARD', '2', '-i', vif, '-j', vm_chain])
util.pread2(['ebtables', '-A', 'FORWARD', '-o', vif, '-j', vm_chain])
except:
logging.debug("Failed to program default ebtables FORWARD rules for %s" % vm_chain)
return 'false'
try:
for vif in vifs:
# only allow source mac that belongs to the vm
try:
util.pread2(['ebtables', '-t', 'nat', '-I', 'PREROUTING', '-i', vif, '-s', '!' , vm_mac, '-j', 'DROP'])
except:
util.pread2(['ebtables', '-A', vm_chain, '-i', vif, '-s', '!', vm_mac, '-j', 'DROP'])
# do not allow fake dhcp responses
util.pread2(['ebtables', '-A', vm_chain, '-i', vif, '-p', 'IPv4', '--ip-proto', 'udp', '--ip-dport', '68', '-j', 'DROP'])
# do not allow snooping of dhcp requests
util.pread2(['ebtables', '-A', vm_chain, '-o', vif, '-p', 'IPv4', '--ip-proto', 'udp', '--ip-dport', '67', '-j', 'DROP'])
except:
logging.debug("Failed to program default ebtables antispoof rules for %s" % vm_chain)
return 'false'
return 'true'
@echo
def default_arp_antispoof(vm_chain, vifs, vm_ip, vm_mac):
if vm_mac == 'ff:ff:ff:ff:ff:ff':
logging.debug("Ignoring since mac address is not valid")
return 'true'
try:
util.pread2(['arptables', '-N', vm_chain])
except:
try:
util.pread2(['arptables', '-F', vm_chain])
except:
logging.debug("Failed to create arptables rule, skipping")
return 'true'
# note all rules for packets into the bridge (-i) precede all output rules (-o)
try:
for vif in vifs:
util.pread2(['arptables', '-I', 'FORWARD', '-i', vif, '-j', vm_chain])
util.pread2(['arptables', '-A', 'FORWARD', '-o', vif, '-j', vm_chain])
except:
logging.debug("Failed to program default arptables rules in FORWARD chain vm=" + vm_chain)
return 'false'
try:
for vif in vifs:
#accept arp replies into the bridge as long as the source mac and ips match the vm
util.pread2(['arptables', '-A', vm_chain, '-i', vif, '--opcode', 'Reply', '--source-mac', vm_mac, '--source-ip', vm_ip, '-j', 'ACCEPT'])
#accept any arp requests from this vm. In the future this can be restricted to deny attacks on hosts
#also important to restrict source ip and src mac in these requests as they can be used to update arp tables on destination
util.pread2(['arptables', '-A', vm_chain, '-i', vif, '--opcode', 'Request', '--source-mac', vm_mac, '--source-ip', vm_ip, '-j', 'RETURN'])
#accept any arp requests to this vm as long as the request is for this vm's ip
util.pread2(['arptables', '-A', vm_chain, '-o', vif, '--opcode', 'Request', '--destination-ip', vm_ip, '-j', 'ACCEPT'])
#accept any arp replies to this vm as long as the mac and ip matches
util.pread2(['arptables', '-A', vm_chain, '-o', vif, '--opcode', 'Reply', '--destination-mac', vm_mac, '--destination-ip', vm_ip, '-j', 'ACCEPT'])
util.pread2(['arptables', '-A', vm_chain, '-j', 'DROP'])
except:
logging.debug("Failed to program default arptables rules")
return 'false'
return 'true'
@echo
def network_rules_vmSecondaryIp(session, args):
vm_name = args.pop('vmName')
vm_mac = args.pop('vmMac')
ip_secondary = args.pop('vmSecIp')
action = args.pop('action')
logging.debug("vmMac = "+ vm_mac)
logging.debug("vmName = "+ vm_name)
#action = "-A"
logging.debug("action = "+ action)
try:
vm = session.xenapi.VM.get_by_name_label(vm_name)
if len(vm) != 1:
return 'false'
vm_rec = session.xenapi.VM.get_record(vm[0])
vm_vifs = vm_rec.get('VIFs')
vifnums = [session.xenapi.VIF.get_record(vif).get('device') for vif in vm_vifs]
domid = vm_rec.get('domid')
except:
logging.debug("### Failed to get domid or vif list for vm ##" + vm_name)
return 'false'
if domid == '-1':
logging.debug("### Failed to get domid for vm (-1): " + vm_name)
return 'false'
vifs = ["vif" + domid + "." + v for v in vifnums]
#vm_name = '-'.join(vm_name.split('-')[:-1])
vmchain = chain_name(vm_name)
add_to_ipset(vmchain, [ip_secondary], action)
#add arptables rules for the secondary ip
arp_rules_vmip(vmchain, vifs, [ip_secondary], vm_mac, action)
return 'true'
@echo
def default_network_rules_systemvm(session, args):
try:
util.pread2(['/bin/bash', '-c', 'iptables -n -L FORWARD | grep BRIDGE-FIREWALL'])
except:
can_bridge_firewall(session, args)
vm_name = args.pop('vmName')
try:
vm = session.xenapi.VM.get_by_name_label(vm_name)
if len(vm) != 1:
return 'false'
vm_rec = session.xenapi.VM.get_record(vm[0])
vm_vifs = vm_rec.get('VIFs')
vifnums = [session.xenapi.VIF.get_record(vif).get('device') for vif in vm_vifs]
domid = vm_rec.get('domid')
except:
logging.debug("### Failed to get domid or vif list for vm ##" + vm_name)
return 'false'
if domid == '-1':
logging.debug("### Failed to get domid for vm (-1): " + vm_name)
return 'false'
vifs = ["vif" + domid + "." + v for v in vifnums]
#vm_name = '-'.join(vm_name.split('-')[:-1])
vmchain = chain_name(vm_name)
delete_rules_for_vm_in_bridge_firewall_chain(vm_name)
try:
util.pread2(['iptables', '-N', vmchain])
except:
util.pread2(['iptables', '-F', vmchain])
for vif in vifs:
try:
util.pread2(['iptables', '-A', 'BRIDGE-FIREWALL', '-m', 'physdev', '--physdev-is-bridged', '--physdev-out', vif, '-j', vmchain])
util.pread2(['iptables', '-I', 'BRIDGE-FIREWALL', '2', '-m', 'physdev', '--physdev-is-bridged', '--physdev-in', vif, '-j', vmchain])
util.pread2(['iptables', '-I', vmchain, '-m', 'physdev', '--physdev-is-bridged', '--physdev-in', vif, '-j', 'RETURN'])
except:
logging.debug("Failed to program default rules")
return 'false'
util.pread2(['iptables', '-A', vmchain, '-j', 'ACCEPT'])
if write_rule_log_for_vm(vm_name, '-1', '_ignore_', domid, '_initial_', '-1') == False:
logging.debug("Failed to log default network rules for systemvm, ignoring")
return 'true'
@echo
def create_ipset_forvm (ipsetname):
result = True
type = getIpsetType()
try:
logging.debug("Creating ipset chain .... " + ipsetname)
util.pread2(['ipset', '-F', ipsetname])
util.pread2(['ipset', '-X', ipsetname])
util.pread2(['ipset', '-N', ipsetname, type])
except:
logging.debug("ipset chain not exists creating.... " + ipsetname)
util.pread2(['ipset', '-N', ipsetname, type])
return result
@echo
def add_to_ipset(ipsetname, ips, action):
result = True
for ip in ips:
try:
logging.debug("vm ip " + ip)
util.pread2(['ipset', action, ipsetname, ip])
except:
logging.debug("vm ip already in ip set" + ip)
continue
return result
@echo
def arp_rules_vmip (vm_chain, vifs, ips, vm_mac, action):
try:
if action == "-A":
action = "-I"
for vif in vifs:
for vm_ip in ips:
#accept any arp requests to this vm as long as the request is for this vm's ip
util.pread2(['arptables', action, vm_chain, '-o', vif, '--opcode', 'Request', '--destination-ip', vm_ip, '-j', 'ACCEPT'])
#accept any arp replies to this vm as long as the mac and ip matches
util.pread2(['arptables', action, vm_chain, '-o', vif, '--opcode', 'Reply', '--destination-mac', vm_mac, '--destination-ip', vm_ip, '-j', 'ACCEPT'])
#accept arp replies into the bridge as long as the source mac and ips match the vm
util.pread2(['arptables', action, vm_chain, '-i', vif, '--opcode', 'Reply', '--source-mac', vm_mac, '--source-ip', vm_ip, '-j', 'ACCEPT'])
#accept any arp requests from this vm. In the future this can be restricted to deny attacks on hosts
#also important to restrict source ip and src mac in these requests as they can be used to update arp tables on destination
util.pread2(['arptables', action, vm_chain, '-i', vif, '--opcode', 'Request', '--source-mac', vm_mac, '--source-ip', vm_ip, '-j', 'RETURN'])
except:
logging.debug("Failed to program arptables rules for ip")
return 'false'
return 'true'
@echo
def default_network_rules(session, args):
vm_name = args.pop('vmName')
vm_ip = args.pop('vmIP')
vm_id = args.pop('vmID')
vm_mac = args.pop('vmMAC')
sec_ips = args.pop("secIps")
action = "-A"
try:
vm = session.xenapi.VM.get_by_name_label(vm_name)
if len(vm) != 1:
logging.debug("### Failed to get record for vm " + vm_name)
return 'false'
vm_rec = session.xenapi.VM.get_record(vm[0])
domid = vm_rec.get('domid')
except:
logging.debug("### Failed to get domid for vm " + vm_name)
return 'false'
if domid == '-1':
logging.debug("### Failed to get domid for vm (-1): " + vm_name)
return 'false'
vif = "vif" + domid + ".0"
tap = "tap" + domid + ".0"
vifs = [vif]
try:
util.pread2(['ifconfig', tap])
vifs.append(tap)
except:
pass
delete_rules_for_vm_in_bridge_firewall_chain(vm_name)
vmchain = chain_name(vm_name)
vmchain_egress = egress_chain_name(vm_name)
vmchain_default = chain_name_def(vm_name)
destroy_ebtables_rules(vmchain)
try:
util.pread2(['iptables', '-N', vmchain])
except:
util.pread2(['iptables', '-F', vmchain])
try:
util.pread2(['iptables', '-N', vmchain_egress])
except:
util.pread2(['iptables', '-F', vmchain_egress])
try:
util.pread2(['iptables', '-N', vmchain_default])
except:
util.pread2(['iptables', '-F', vmchain_default])
vmipset = vm_name
if len(vmipset) > 28:
vmipset = vmipset[0:27]
#create ipset and add vm ips to that ip set
if create_ipset_forvm(vmipset) == False:
logging.debug(" failed to create ipset for rule " + str(tokens))
return 'false'
#add primary nic ip to ipset
if add_to_ipset(vmipset, [vm_ip], action ) == False:
logging.debug(" failed to add vm " + vm_ip + " ip to set ")
return 'false'
#add secondary nic ips to ipset
secIpSet = "1"
ips = sec_ips.split(';')
ips.pop()
if ips[0] == "0":
secIpSet = "0";
if secIpSet == "1":
logging.debug("Adding ipset for secondary ips")
add_to_ipset(vmipset, ips, action)
if write_secip_log_for_vm(vm_name, sec_ips, vm_id) == False:
logging.debug("Failed to log default network rules, ignoring")
keyword = '--' + get_ipset_keyword()
try:
for v in vifs:
util.pread2(['iptables', '-A', 'BRIDGE-FIREWALL', '-m', 'physdev', '--physdev-is-bridged', '--physdev-out', v, '-j', vmchain_default])
util.pread2(['iptables', '-I', 'BRIDGE-FIREWALL', '2', '-m', 'physdev', '--physdev-is-bridged', '--physdev-in', v, '-j', vmchain_default])
#don't let vm spoof its ip address
for v in vifs:
#util.pread2(['iptables', '-A', vmchain_default, '-m', 'physdev', '--physdev-is-bridged', '--physdev-in', v, '--source', vm_ip,'-p', 'udp', '--dport', '53', '-j', 'RETURN'])
util.pread2(['iptables', '-A', vmchain_default, '-m', 'physdev', '--physdev-is-bridged', '--physdev-in', v, '-m', 'set', keyword, vmipset, 'src', '-p', 'udp', '--dport', '53', '-j', 'RETURN'])
util.pread2(['iptables', '-A', vmchain_default, '-m', 'physdev', '--physdev-is-bridged', '--physdev-in', v, '-m', 'set', '!', keyword, vmipset, 'src', '-j', 'DROP'])
util.pread2(['iptables', '-A', vmchain_default, '-m', 'physdev', '--physdev-is-bridged', '--physdev-out', v, '-m', 'set', '!', keyword, vmipset, 'dst', '-j', 'DROP'])
util.pread2(['iptables', '-A', vmchain_default, '-m', 'physdev', '--physdev-is-bridged', '--physdev-in', v, '-m', 'set', keyword, vmipset, 'src', '-j', vmchain_egress])
util.pread2(['iptables', '-A', vmchain_default, '-m', 'physdev', '--physdev-is-bridged', '--physdev-out', v, '-j', vmchain])
except:
logging.debug("Failed to program default rules for vm " + vm_name)
return 'false'
default_arp_antispoof(vmchain, vifs, vm_ip, vm_mac)
#add default arp rules for secondary ips;
if secIpSet == "1":
logging.debug("Adding arp rules for sec ip")
arp_rules_vmip(vmchain, vifs, ips, vm_mac, action)
default_ebtables_antispoof_rules(vmchain, vifs, vm_ip, vm_mac)
if write_rule_log_for_vm(vm_name, vm_id, vm_ip, domid, '_initial_', '-1', vm_mac) == False:
logging.debug("Failed to log default network rules, ignoring")
logging.debug("Programmed default rules for vm " + vm_name)
return 'true'
@echo
def check_domid_changed(session, vmName):
curr_domid = '-1'
try:
vm = session.xenapi.VM.get_by_name_label(vmName)
if len(vm) != 1:
logging.debug("### Could not get record for vm ## " + vmName)
else:
vm_rec = session.xenapi.VM.get_record(vm[0])
curr_domid = vm_rec.get('domid')
except:
logging.debug("### Failed to get domid for vm ## " + vmName)
logfilename = "/var/run/cloud/" + vmName +".log"
if not os.path.exists(logfilename):
return ['-1', curr_domid]
lines = (line.rstrip() for line in open(logfilename))
[_vmName,_vmID,_vmIP,old_domid,_signature,_seqno, _vmMac] = ['_', '-1', '_', '-1', '_', '-1', 'ff:ff:ff:ff:ff:ff']
for line in lines:
try:
[_vmName,_vmID,_vmIP,old_domid,_signature,_seqno,_vmMac] = line.split(',')
except ValueError as v:
[_vmName,_vmID,_vmIP,old_domid,_signature,_seqno] = line.split(',')
break
return [curr_domid, old_domid]
@echo
def delete_rules_for_vm_in_bridge_firewall_chain(vmName):
vm_name = vmName
vmchain = chain_name_def(vm_name)
delcmd = "iptables-save | grep '\-A BRIDGE-FIREWALL' | grep '%s' | sed 's/-A/-D/'" % vmchain
delcmds = util.pread2(['/bin/bash', '-c', delcmd]).split('\n')
for cmd in filter(None, delcmds):
try:
dc = 'iptables ' + cmd
util.pread2(filter(None, dc.split(' ')))
except:
logging.debug("Ignoring failure to delete rules for vm " + vmName)
@echo
def network_rules_for_rebooted_vm(session, vmName):
vm_name = vmName
[curr_domid, old_domid] = check_domid_changed(session, vm_name)
if curr_domid == old_domid:
return True
if old_domid == '-1':
return True
if curr_domid == '-1':
return True
logging.debug("Found a rebooted VM -- reprogramming rules for " + vm_name)
delete_rules_for_vm_in_bridge_firewall_chain(vm_name)
if 1 in [ vm_name.startswith(c) for c in ['r-', 's-', 'v-', 'l-'] ]:
default_network_rules_systemvm(session, {"vmName":vm_name})
return True
vif = "vif" + curr_domid + ".0"
tap = "tap" + curr_domid + ".0"
vifs = [vif]
try:
util.pread2(['ifconfig', tap])
vifs.append(tap)
except:
pass
vmchain = chain_name(vm_name)
vmchain_default = chain_name_def(vm_name)
for v in vifs:
util.pread2(['iptables', '-A', 'BRIDGE-FIREWALL', '-m', 'physdev', '--physdev-is-bridged', '--physdev-out', v, '-j', vmchain_default])
util.pread2(['iptables', '-I', 'BRIDGE-FIREWALL', '2', '-m', 'physdev', '--physdev-is-bridged', '--physdev-in', v, '-j', vmchain_default])
#change antispoof rule in vmchain
try:
delcmd = "iptables-save | grep '\-A " + vmchain_default + "' | grep physdev-in | sed 's/!--set/! --set/' | sed 's/-A/-D/'"
delcmd2 = "iptables-save | grep '\-A " + vmchain_default + "' | grep physdev-out | sed 's/!--set/! --set/'| sed 's/-A/-D/'"
inscmd = "iptables-save | grep '\-A " + vmchain_default + "' | grep physdev-in | grep vif | sed -r 's/vif[0-9]+.0/" + vif + "/' | sed 's/!--set/! --set/'"
inscmd2 = "iptables-save| grep '\-A " + vmchain_default + "' | grep physdev-in | grep tap | sed -r 's/tap[0-9]+.0/" + tap + "/' | sed 's/!--set/! --set/'"