aboutsummaryrefslogtreecommitdiffstats
path: root/tools/python/xen/util/acmpolicy.py
blob: 5577193a762868a222457aa6e502a4bb296cf622 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
#============================================================================
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#============================================================================
# Copyright (C) 2006,2007 International Business Machines Corp.
# Author: Stefan Berger <stefanb@us.ibm.com>
#============================================================================

import os
import commands
import struct
import stat
import array
from xml.dom import minidom, Node
from xen.xend.XendLogging import log
from xen.util import security, xsconstants, bootloader, mkdir
from xen.util.xspolicy import XSPolicy
from xen.util.security import ACMError
from xen.xend.XendError import SecurityError

ACM_POLICIES_DIR = security.policy_dir_prefix + "/"

# Constants needed for generating a binary policy from its XML
# representation
ACM_POLICY_VERSION = 3  # Latest one
ACM_CHWALL_VERSION = 1

ACM_STE_VERSION = 1

ACM_MAGIC = 0x001debc;

ACM_NULL_POLICY = 0
ACM_CHINESE_WALL_POLICY = 1
ACM_SIMPLE_TYPE_ENFORCEMENT_POLICY = 2
ACM_POLICY_UNDEFINED = 15


ACM_SCHEMA_FILE = "/etc/xen/acm-security/policies/security_policy.xsd"

ACM_LABEL_UNLABELED = "__UNLABELED__"
ACM_LABEL_UNLABELED_DISPLAY = "unlabeled"

class ACMPolicy(XSPolicy):
    """
     ACMPolicy class. Implements methods for getting information from
     the XML representation of the policy as well as compilation and
     loading of a policy into the HV.
    """

    def __init__(self, name=None, dom=None, ref=None, xml=None):
        if name:
            self.name = name
            try:
                self.dom = minidom.parse(self.path_from_policy_name(name))
            except Exception, e:
                raise SecurityError(-xsconstants.XSERR_XML_PROCESSING,
                                    str(e))
        elif dom:
            self.dom = dom
            self.name = self.get_name()
        elif xml:
            try:
                self.dom = minidom.parseString(xml)
            except Exception, e:
                raise SecurityError(-xsconstants.XSERR_XML_PROCESSING,
                                    str(e))
            self.name = self.get_name()
        rc = self.validate()
        if rc != xsconstants.XSERR_SUCCESS:
            raise SecurityError(rc)
        mkdir.parents(ACM_POLICIES_DIR, stat.S_IRWXU)
        if ref:
            from xen.xend.XendXSPolicy import XendACMPolicy
            self.xendacmpolicy = XendACMPolicy(self, {}, ref)
        else:
            self.xendacmpolicy = None
        XSPolicy.__init__(self, name=self.name, ref=ref)

    def get_dom(self):
        return self.dom

    def get_name(self):
        return self.policy_dom_get_hdr_item("PolicyName")

    def get_type(self):
        return xsconstants.XS_POLICY_ACM

    def get_type_name(self):
        return xsconstants.ACM_POLICY_ID

    def __str__(self):
        return self.get_name()


    def validate(self):
        """
            validate against the policy's schema Does not fail if the
            libxml2 python lib is not installed
        """
        rc = xsconstants.XSERR_SUCCESS
        try:
            import libxml2
        except Exception, e:
            log.warn("Libxml2 python-wrapper is not installed on the system.")
            return xsconstants.XSERR_SUCCESS
        try:
            parserctxt = libxml2.schemaNewParserCtxt(ACM_SCHEMA_FILE)
            schemaparser = parserctxt.schemaParse()
            valid = schemaparser.schemaNewValidCtxt()
            doc = libxml2.parseDoc(self.toxml())
            if doc.schemaValidateDoc(valid) != 0:
                rc = -xsconstants.XSERR_BAD_XML
        except Exception, e:
            log.warn("Problem with the schema: %s" % str(e))
            rc = -xsconstants.XSERR_GENERAL_FAILURE
        if rc != xsconstants.XSERR_SUCCESS:
            log.warn("XML did not validate against schema")
        if rc == xsconstants.XSERR_SUCCESS:
            rc = self.__validate_name_and_labels()
        return rc

    def __validate_name_and_labels(self):
        """ no ':' allowed in the policy name and the labels """
        if ':' in self.get_name():
            return -xsconstants.XSERR_BAD_POLICY_NAME
        for s in self.policy_get_resourcelabel_names():
            if ':' in s:
                return -xsconstants.XSERR_BAD_LABEL
        for s in self.policy_get_virtualmachinelabel_names():
            if ':' in s:
                return -xsconstants.XSERR_BAD_LABEL
        return xsconstants.XSERR_SUCCESS


    def update(self, xml_new):
        """
            Update the policy with the new XML. The hypervisor decides
            whether the new policy can be applied.
        """
        rc = -xsconstants.XSERR_XML_PROCESSING
        errors = ""
        acmpol_old = self
        try:
            acmpol_new = ACMPolicy(xml=xml_new)
        except Exception:
            return -xsconstants.XSERR_XML_PROCESSING, errors

        vmlabel_map = acmpol_new.policy_get_vmlabel_translation_map()
        # An update requires version information in the current
        # and new policy. The version number of the current policy
        # must be the same as what is in the FromPolicy/Version node
        # in the new one and the current policy's name must be the
        # same as in FromPolicy/PolicyName

        now_vers    = acmpol_old.policy_dom_get_hdr_item("Version")
        now_name    = acmpol_old.policy_dom_get_hdr_item("PolicyName")
        req_oldvers = acmpol_new.policy_dom_get_frompol_item("Version")
        req_oldname = acmpol_new.policy_dom_get_frompol_item("PolicyName")

        if now_vers == "" or \
           now_vers != req_oldvers or \
           now_name != req_oldname:
            log.info("Policy rejected: %s != %s or %s != %s" % \
                     (now_vers,req_oldvers,now_name,req_oldname))
            return -xsconstants.XSERR_VERSION_PREVENTS_UPDATE, errors

        if not self.isVersionUpdate(acmpol_new):
            log.info("Policy rejected since new version is not an update.")
            return -xsconstants.XSERR_VERSION_PREVENTS_UPDATE, errors

        if self.isloaded():
            newvmnames = \
                 acmpol_new.policy_get_virtualmachinelabel_names_sorted()
            oldvmnames = \
                 acmpol_old.policy_get_virtualmachinelabel_names_sorted()
            del_array = ""
            chg_array = ""
            for o in oldvmnames:
                if o not in newvmnames:
                    old_idx = oldvmnames.index(o) + 1 # for _NULL_LABEL_
                    if vmlabel_map.has_key(o):
                        #not a deletion, but a renaming
                        new = vmlabel_map[o]
                        new_idx = newvmnames.index(new) + 1 # for _NULL_LABEL_
                        chg_array += struct.pack("ii", old_idx, new_idx)
                    else:
                        del_array += struct.pack("i", old_idx)
            for v in newvmnames:
                if v in oldvmnames:
                    old_idx = oldvmnames.index(v) + 1 # for _NULL_LABEL_
                    new_idx = newvmnames.index(v) + 1 # for _NULL_LABEL_
                    if old_idx != new_idx:
                        chg_array += struct.pack("ii", old_idx, new_idx)

            # VM labels indicated in the 'from' attribute of a VM or
            # resource node but that did not exist in the old policy
            # are considered bad labels.
            bad_renamings = set(vmlabel_map.keys()) - set(oldvmnames)
            if len(bad_renamings) > 0:
                log.error("Bad VM label renamings: %s" %
                          list(bad_renamings))
                return -xsconstants.XSERR_BAD_LABEL, errors

            reslabel_map = acmpol_new.policy_get_reslabel_translation_map()
            oldresnames  = acmpol_old.policy_get_resourcelabel_names()
            bad_renamings = set(reslabel_map.keys()) - set(oldresnames)
            if len(bad_renamings) > 0:
                log.error("Bad resource label renamings: %s" %
                          list(bad_renamings))
                return -xsconstants.XSERR_BAD_LABEL, errors

            #Get binary and map from the new policy
            rc, map, bin_pol = acmpol_new.policy_create_map_and_bin()
            if rc != xsconstants.XSERR_SUCCESS:
                log.error("Could not build the map and binary policy.")
                return rc, errors

            #Need to do / check the following:
            # - relabel all resources where there is a 'from' field in
            #   the policy and mark those as unlabeled where the label
            #   does not appear in the new policy anymore
            # - relabel all VMs where there is a 'from' field in the
            #   policy and mark those as unlabeled where the label
            #   does not appear in the new policy anymore; no running
            #   or paused VM may be unlabeled through this
            # - check that under the new labeling conditions the VMs
            #   still have access to their resources as before. Unlabeled
            #   resources are inaccessible. If this check fails, the
            #   update failed.
            # - Attempt changes in the hypervisor; if this step fails,
            #   roll back the relabeling of resources and VMs
            # - Commit the relabeling of resources


            rc, errors = security.change_acm_policy(bin_pol,
                                        del_array, chg_array,
                                        vmlabel_map, reslabel_map,
                                        self, acmpol_new)

            if rc == 0:
                # Replace the old DOM with the new one and save it
                self.dom = acmpol_new.dom
                self.compile()
                log.info("ACM policy update was successful")
        else:
            #Not loaded in HV
            self.dom = acmpol_new.dom
            self.compile()
        return rc, errors

    def compareVersions(self, v1, v2):
        """
            Compare two policy versions given their tuples of major and
            minor.
            Return '0' if versions are equal, '>0' if v1 > v2 and
            '<' if v1 < v2
        """
        rc = v1[0] - v2[0]
        if rc == 0:
            rc = v1[1] - v2[1]
        return rc

    def getVersionTuple(self, item="Version"):
        v_str = self.policy_dom_get_hdr_item(item)
        return self.__convVersionToTuple(v_str)

    def get_version(self):
        return self.policy_dom_get_hdr_item("Version")

    def isVersionUpdate(self, polnew):
        if self.compareVersions(polnew.getVersionTuple(),
                                self.getVersionTuple()) > 0:
            return True
        return False

    def __convVersionToTuple(self, v_str):
        """ Convert a version string, formatted according to the scheme
            "%d.%d" into a tuple of (major, minor). Return (0,0) if the
            string is empty.
        """
        major = 0
        minor = 0
        if v_str != "":
            tmp = v_str.split(".")
            major = int(tmp[0])
            if len(tmp) > 1:
                minor = int(tmp[1])
        return (major, minor)


    def policy_path(self, name, prefix = ACM_POLICIES_DIR ):
        path = prefix + name.replace('.','/')
        _path = path.split("/")
        del _path[-1]
        mkdir.parents("/".join(_path), stat.S_IRWXU)
        return path

    def path_from_policy_name(self, name):
        return self.policy_path(name) + "-security_policy.xml"

    #
    # Functions interacting with the bootloader
    #
    def vmlabel_to_ssidref(self, vm_label):
        """ Convert a VMlabel into an ssidref given the current
            policy
            Return xsconstants.INVALID_SSIDREF if conversion failed.
        """
        ssidref = xsconstants.INVALID_SSIDREF
        names = self.policy_get_virtualmachinelabel_names_sorted()
        try:
            vmidx = names.index(vm_label) + 1 # for _NULL_LABEL_
            ssidref = (vmidx << 16) | vmidx
        except:
            pass
        return ssidref

    def set_vm_bootlabel(self, vm_label):
        parms="<>"
        if vm_label != "":
            ssidref = self.vmlabel_to_ssidref(vm_label)
            if ssidref == xsconstants.INVALID_SSIDREF:
                return -xsconstants.XSERR_BAD_LABEL
            parms = "0x%08x:%s:%s:%s" % \
                        (ssidref, xsconstants.ACM_POLICY_ID, \
                         self.get_name(),vm_label)
        else:
            ssidref = 0 #Identifier for removal
        try:
            def_title = bootloader.get_default_title()
            bootloader.set_kernel_attval(def_title, "ssidref", parms)
        except:
            return -xsconstants.XSERR_GENERAL_FAILURE
        return ssidref

    #
    # Utility functions related to the policy's files
    #
    def get_filename(self, postfix, prefix = ACM_POLICIES_DIR, dotted=False):
        """
           Create the filename for the policy. The prefix is prepended
           to the path. If dotted is True, then a policy name like
           'a.b.c' will remain as is, otherwise it will become 'a/b/c'
        """
        name = self.get_name()
        if name:
            p = name.split(".")
            path = ""
            if dotted == True:
                sep = "."
            else:
                sep = "/"
            if len(p) > 1:
                path = sep.join(p[0:len(p)-1])
            if prefix != "" or path != "":
                allpath = prefix + path + sep + p[-1] + postfix
            else:
                allpath = p[-1] + postfix
            return allpath
        return None

    def __readfile(self, name):
        cont = ""
        filename = self.get_filename(name)
        f = open(filename, "r")
        if f:
            cont = f.read()
            f.close()
        return cont

    def get_map(self):
        return self.__readfile(".map")

    def get_bin(self):
        return self.__readfile(".bin")

    #
    # DOM-related functions
    #

    def policy_dom_get(self, parent, key, createit=False):
        for node in parent.childNodes:
            if node.nodeType == Node.ELEMENT_NODE:
                if node.nodeName == key:
                    return node
        if createit:
            self.dom_create_node(parent, key)
            return self.policy_dom_get(parent, key)

    def dom_create_node(self, parent, newname, value=" "):
        xml = "<a><"+newname+">"+ value +"</"+newname+"></a>"
        frag = minidom.parseString(xml)
        frag.childNodes[0].nodeType = Node.DOCUMENT_FRAGMENT_NODE
        parent.appendChild(frag.childNodes[0])
        return frag.childNodes[0]

    def dom_get_node(self, path, createit=False):
        node = None
        parts = path.split("/")
        doc = self.get_dom()
        if len(parts) > 0:
            node = self.policy_dom_get(doc.documentElement, parts[0])
            if node:
                i = 1
                while i < len(parts):
                    _node = self.policy_dom_get(node, parts[i], createit)
                    if not _node:
                        if not createit:
                            break
                        else:
                            self.dom_create_node(node, parts[i])
                            _node = self.policy_dom_get(node, parts[i])
                    node = _node
                    i += 1
        return node

    #
    # Header-related functions
    #
    def policy_dom_get_header_subnode(self, nodename):
        node = self.dom_get_node("PolicyHeader/%s" % nodename)
        return node

    def policy_dom_get_hdr_item(self, name, default=""):
        node = self.policy_dom_get_header_subnode(name)
        if node and len(node.childNodes) > 0:
            return node.childNodes[0].nodeValue
        return default

    def policy_dom_get_frompol_item(self, name, default="", createit=False):
        node = self.dom_get_node("PolicyHeader/FromPolicy",createit)
        if node:
            node = self.policy_dom_get(node, name, createit)
            if node and len(node.childNodes) > 0:
                return node.childNodes[0].nodeValue
        return default

    def get_header_fields_map(self):
        header = {
          'policyname'   : self.policy_dom_get_hdr_item("PolicyName"),
          'policyurl'    : self.policy_dom_get_hdr_item("PolicyUrl"),
          'reference'    : self.policy_dom_get_hdr_item("Reference"),
          'date'         : self.policy_dom_get_hdr_item("Date"),
          'namespaceurl' : self.policy_dom_get_hdr_item("NameSpaceUrl"),
          'version'      : self.policy_dom_get_hdr_item("Version")
        }
        return header

    def set_frompolicy_name(self, name):
        """ For tools to adapt the header of the policy """
        node = self.dom_get_node("PolicyHeader/FromPolicy/PolicyName",
                                 createit=True)
        node.childNodes[0].nodeValue = name

    def set_frompolicy_version(self, version):
        """ For tools to adapt the header of the policy """
        node = self.dom_get_node("PolicyHeader/FromPolicy/Version",
                                 createit=True)
        node.childNodes[0].nodeValue = version

    def set_policy_name(self, name):
        """ For tools to adapt the header of the policy """
        node = self.dom_get_node("PolicyHeader/PolicyName")
        node.childNodes[0].nodeValue = name

    def set_policy_version(self, version):
        """ For tools to adapt the header of the policy """
        node = self.dom_get_node("PolicyHeader/Version")
        node.childNodes[0].nodeValue = version

    def update_frompolicy(self, curpol):
        self.set_frompolicy_name(curpol.policy_dom_get_hdr_item("PolicyName"))
        version = curpol.policy_dom_get_hdr_item("Version")
        self.set_frompolicy_version(version)
        (maj, min) = self.__convVersionToTuple(version)
        self.set_policy_version("%s.%s" % (maj, min+1))

    #
    # Get all types that are part of a node
    #

    def policy_get_types(self, node):
        strings = []
        i = 0
        while i < len(node.childNodes):
            if node.childNodes[i].nodeName == "Type" and \
               len(node.childNodes[i].childNodes) > 0:
                strings.append(node.childNodes[i].childNodes[0].nodeValue)
            i += 1
        return strings

    #
    # Simple Type Enforcement-related functions
    #

    def policy_get_stetypes_node(self):
        node = self.dom_get_node("SimpleTypeEnforcement/SimpleTypeEnforcementTypes")
        return node

    def policy_get_stetypes_types(self):
        strings = []
        node = self.policy_get_stetypes_node()
        if node:
            strings = self.policy_get_types(node)
        return strings

    #
    # Chinese Wall Type-related functions
    #

    def policy_get_chwall_types(self):
        strings = []
        node = self.dom_get_node("ChineseWall/ChineseWallTypes")
        if node:
            strings = self.policy_get_types(node)
        return strings

    def policy_get_chwall_cfses(self):
        cfs = []
        node = self.dom_get_node("ChineseWall/ConflictSets")
        if node:
            i = 0
            while i < len(node.childNodes):
                _cfs = {}
                if node.childNodes[i].nodeName == "Conflict":
                    _cfs['name']  = node.childNodes[i].getAttribute('name')
                    _cfs['chws'] = self.policy_get_types(node.childNodes[i])
                    cfs.append(_cfs)
                i += 1
        return cfs

    def policy_get_chwall_cfses_names_sorted(self):
        """
           Return the list of all conflict set names in alphabetical
           order.
        """
        cfs_names = []
        node = self.dom_get_node("ChineseWall/ConflictSets")
        if node:
            i = 0
            while i < len(node.childNodes):
                if node.childNodes[i].nodeName == "Conflict":
                    n  = node.childNodes[i].getAttribute('name')
                    #it better have a name!
                    if n:
                        cfs_names.append(n)
                i += 1
        cfs_names.sort()
        return cfs_names

    #
    # Subject Label-related functions
    #

    def policy_get_bootstrap_vmlabel(self):
        node = self.dom_get_node("SecurityLabelTemplate/SubjectLabels")
        if node:
            vmlabel = node.getAttribute("bootstrap")
        return vmlabel

    # Get the names of all virtual machine labels; returns an array
    def policy_get_virtualmachinelabel_names(self):
        strings = []
        node = self.dom_get_node("SecurityLabelTemplate/SubjectLabels")
        if node:
            i = 0
            while i < len(node.childNodes):
                if node.childNodes[i].nodeName == "VirtualMachineLabel":
                    name = self.policy_dom_get(node.childNodes[i], "Name")
                    if len(name.childNodes) > 0:
                        strings.append(name.childNodes[0].nodeValue)
                i += 1
        return strings

    def policy_sort_virtualmachinelabel_names(self, vmnames):
        bootstrap = self.policy_get_bootstrap_vmlabel()
        if bootstrap not in vmnames:
            raise SecurityError(-xsconstants.XSERR_POLICY_INCONSISTENT)
        vmnames.remove(bootstrap)
        vmnames.sort()
        vmnames.insert(0, bootstrap)
        return vmnames

    def policy_get_virtualmachinelabel_names_sorted(self):
        """ Get a sorted list of VMlabel names. The bootstrap VM's
            label will be the first one in that list, followed
            by an alphabetically sorted list of VM label names """
        vmnames = self.policy_get_virtualmachinelabel_names()
        return self.policy_sort_virtualmachinelabel_names(vmnames)

    def policy_get_virtualmachinelabels(self):
        """ Get a list of all virtual machine labels in this policy """
        res = []
        node = self.dom_get_node("SecurityLabelTemplate/SubjectLabels")
        if node:
            i = 0
            while i < len(node.childNodes):
                if node.childNodes[i].nodeName == "VirtualMachineLabel":
                    name = self.policy_dom_get(node.childNodes[i], "Name")
                    if len(name.childNodes) > 0:
                        _res = {}
                        _res['type'] = xsconstants.ACM_LABEL_VM
                        _res['name'] = name.childNodes[0].nodeValue
                        stes = self.policy_dom_get(node.childNodes[i],
                                                 "SimpleTypeEnforcementTypes")
                        if stes:
                           _res['stes'] = self.policy_get_types(stes)
                        else:
                            _res['stes'] = []
                        chws = self.policy_dom_get(node.childNodes[i],
                                                   "ChineseWallTypes")
                        if chws:
                            _res['chws'] = self.policy_get_types(chws)
                        else:
                            _res['chws'] = []
                        res.append(_res)
                i += 1
        return res

    def policy_get_stes_of_vmlabel(self, vmlabel):
        """ Get a list of all STEs of a given VMlabel """
        return self.__policy_get_stes_of_labeltype(vmlabel,
                                        "/SubjectLabels", "VirtualMachineLabel")

    def policy_get_stes_of_resource(self, reslabel):
        """ Get a list of all resources of a given VMlabel """
        return self.__policy_get_stes_of_labeltype(reslabel,
                                        "/ObjectLabels", "ResourceLabel")

    def __policy_get_stes_of_labeltype(self, label, path, labeltype):
        node = self.dom_get_node("SecurityLabelTemplate" + path)
        if node:
            i = 0
            while i < len(node.childNodes):
                if node.childNodes[i].nodeName == labeltype:
                    name = self.policy_dom_get(node.childNodes[i], "Name")
                    if len(name.childNodes) > 0 and \
                       name.childNodes[0].nodeValue == label:
                        stes = self.policy_dom_get(node.childNodes[i],
                                            "SimpleTypeEnforcementTypes")
                        if not stes:
                            return []
                        return self.policy_get_types(stes)
                i += 1
        return []

    def policy_check_vmlabel_against_reslabels(self, vmlabel, resources):
        """
           Check whether the given vmlabel is compatible with the given
           resource labels. Do this by getting all the STEs of the
           vmlabel and the STEs of the resources. Any STE type of the
           VM label must match an STE type of the resource.
        """
        vm_stes = self.policy_get_stes_of_vmlabel(vmlabel)
        if len(vm_stes) == 0:
            return False
        for res in resources:
            res_stes = self.policy_get_stes_of_resource(res)
            if len(res_stes) == 0 or \
               len( set(res_stes).intersection( set(vm_stes) ) ) == 0:
                return False
        return True

    def __policy_get_label_translation_map(self, path, labeltype):
        res = {}
        node = self.dom_get_node("SecurityLabelTemplate/" + path)
        if node:
            i = 0
            while i < len(node.childNodes):
                if node.childNodes[i].nodeName == labeltype:
                    name = self.policy_dom_get(node.childNodes[i], "Name")
                    from_name = name.getAttribute("from")
                    if from_name and len(name.childNodes) > 0:
                        res.update({from_name : name.childNodes[0].nodeValue})
                i += 1
        return res

    def policy_get_vmlabel_translation_map(self):
        """
            Get a dictionary of virtual machine mappings from their
            old VMlabel name to the new VMlabel name.
        """
        return self.__policy_get_label_translation_map("SubjectLabels",
                                                       "VirtualMachineLabel")

    def policy_get_reslabel_translation_map(self):
        """
            Get a dictionary of resource mappings from their
            old resource label name to the new resource label name.
        """
        return self.__policy_get_label_translation_map("ObjectLabels",
                                                       "ResourceLabel")

    #
    # Object Label-related functions
    #
    def policy_get_resourcelabel_names(self):
        """
            Get the names of all resource labels in an array but
            only those that actually have types
        """
        strings = []
        node = self.dom_get_node("SecurityLabelTemplate/ObjectLabels")
        if node:
            i = 0
            while i < len(node.childNodes):
                if node.childNodes[i].nodeName == "ResourceLabel":
                    name = self.policy_dom_get(node.childNodes[i], "Name")
                    stes = self.policy_dom_get(node.childNodes[i],
                                          "SimpleTypeEnforcementTypes")
                    if stes and len(name.childNodes) > 0:
                        strings.append(name.childNodes[0].nodeValue)
                i += 1
        return strings

    def policy_get_resourcelabels(self):
        """
           Get all information about all resource labels of this policy.
        """
        res = []
        node = self.dom_get_node("SecurityLabelTemplate/ObjectLabels")
        if node:
            i = 0
            while i < len(node.childNodes):
                if node.childNodes[i].nodeName == "ResourceLabel":
                    name = self.policy_dom_get(node.childNodes[i], "Name")
                    if len(name.childNodes) > 0:
                        _res = {}
                        _res['type'] = xsconstants.ACM_LABEL_RES
                        _res['name'] = name.childNodes[0].nodeValue
                        stes = self.policy_dom_get(node.childNodes[i],
                                                   "SimpleTypeEnforcementTypes")
                        if stes:
                            _res['stes'] = self.policy_get_types(stes)
                        else:
                            _res['stes'] = []
                        _res['chws'] = []
                        res.append(_res)
                i += 1
        return res


    def policy_find_reslabels_with_stetype(self, stetype):
        """
           Find those resource labels that hold a given STE type.
        """
        res = []
        reslabels = self.policy_get_resourcelabels()
        for resl in reslabels:
            if stetype in resl['stes']:
                res.append(resl['name'])
        return res


    def toxml(self):
        dom = self.get_dom()
        if dom:
            return dom.toxml()
        return None

    def save(self):
        ### Save the XML policy into a file ###
        rc = -xsconstants.XSERR_FILE_ERROR
        name = self.get_name()
        if name:
            path = self.path_from_policy_name(name)
            if path:
                f = open(path, 'w')
                if f:
                    f.write(self.toxml())
                    f.close()
                    rc = 0
        return rc

    def __write_to_file(self, suffix, data):
        #write the data into a file with the given suffix
        f = open(self.get_filename(suffix),"w")
        if f:
            try:
                try:
                    f.write(data)
                except Exception, e:
                    log.error("Error writing file: %s" % str(e))
                    return -xsconstants.XSERR_FILE_ERROR
            finally:
                f.close()
        else:
            return -xsconstants.XSERR_FILE_ERROR
        return xsconstants.XSERR_SUCCESS


    def compile(self):
        rc = self.save()
        if rc == 0:
            rc, mapfile, bin_pol = self.policy_create_map_and_bin()

            if rc == 0:
                rc = self.__write_to_file(".map", mapfile)
                if rc != 0:
                    log.error("Error writing map file")

            if rc == 0:
                rc = self.__write_to_file(".bin", bin_pol)
                if rc != 0:
                    log.error("Error writing binary policy file")
        return rc

    def loadintohv(self):
        """
            load this policy into the hypervisor
            if successful,the policy's flags will indicate that the
            policy is the one loaded into the hypervisor
        """
        if not self.isloaded():
            (ret, output) = commands.getstatusoutput(
                                   security.xensec_tool +
                                   " loadpolicy " +
                                   self.get_filename(".bin"))
            if ret != 0:
                return -xsconstants.XSERR_POLICY_LOAD_FAILED
        return xsconstants.XSERR_SUCCESS

    def isloaded(self):
        """
            Determine whether this policy is the active one.
        """
        security.refresh_security_policy()
        if self.get_name() == security.active_policy:
            return True
        return False

    def destroy(self):
        """
            Destroy the policy including its binary, mapping and
            XML files.
            This only works if the policy is not the one that's loaded
        """
        if self.isloaded():
            return -xsconstants.XSERR_POLICY_LOADED
        files = [ self.get_filename(".map",""),
                  self.get_filename(".bin",""),
                  self.path_from_policy_name(self.get_name())]
        for f in files:
            try:
                os.unlink(f)
            except:
                pass
        if self.xendacmpolicy:
            self.xendacmpolicy.destroy()
        XSPolicy.destroy(self)
        return xsconstants.XSERR_SUCCESS

    def policy_get_domain_label(self, domid):
        """
           Given a domain's ID, retrieve the label it has using
           its ssidref for reverse calculation.
        """
        try:
            mgmt_dom = security.get_ssid(domid)
        except:
            return ""
        return self.policy_get_domain_label_by_ssidref(int(mgmt_dom[3]))

    def policy_get_domain_label_by_ssidref(self, ssidref):
        """ Given an ssidref, find the corresponding VM label """
        chwall_ref = ssidref & 0xffff
        try:
            allvmtypes = self.policy_get_virtualmachinelabel_names_sorted()
        except:
            return None
        return allvmtypes[chwall_ref-1] # skip _NULL_LABEL_

    def policy_get_domain_label_formatted(self, domid):
        label = self.policy_get_domain_label(domid)
        if label == "":
            return ""
        return "%s:%s:%s" % (xsconstants.ACM_POLICY_ID, self.get_name(), label)

    def policy_get_domain_label_by_ssidref_formatted(self, ssidref):
        label = self.policy_get_domain_label_by_ssidref(ssidref)
        if label == "":
            return ""
        return "%s:%s:%s" % (xsconstants.ACM_POLICY_ID, self.get_name(), label)

    def policy_create_map_and_bin(self):
        """
            Create the policy's map and binary files -- compile the policy.
        """
        def roundup8(len):
            return ((len + 7) & ~7)

        rc = xsconstants.XSERR_SUCCESS
        mapfile = ""
        primpolcode = ACM_POLICY_UNDEFINED
        secpolcode  = ACM_POLICY_UNDEFINED
        unknown_ste = set()
        unknown_chw = set()

        rc = self.validate()
        if rc:
            return rc, "", ""

        stes = self.policy_get_stetypes_types()
        if stes:
            stes.sort()

        chws = self.policy_get_chwall_types()
        if chws:
            chws.sort()

        vms = self.policy_get_virtualmachinelabels()
        bootstrap = self.policy_get_bootstrap_vmlabel()

        vmlabels = self.policy_get_virtualmachinelabel_names_sorted()
        if bootstrap not in vmlabels:
            log.error("Bootstrap label '%s' not found among VM labels '%s'." \
                      % (bootstrap, vmlabels))
            return -xsconstants.XSERR_POLICY_INCONSISTENT, "", ""

        vms_with_chws = []
        chws_by_vm = { ACM_LABEL_UNLABELED : [] }
        for v in vms:
            if v.has_key("chws"):
                vms_with_chws.append(v["name"])
                chws_by_vm[v["name"]] = v["chws"]


        if bootstrap in vms_with_chws:
            vms_with_chws.remove(bootstrap)
            vms_with_chws.sort()
            vms_with_chws.insert(0, bootstrap)
        else:
            vms_with_chws.sort()

        if ACM_LABEL_UNLABELED in vms_with_chws:
            vms_with_chws.remove(ACM_LABEL_UNLABELED) ; # @1

        vms_with_stes = []
        stes_by_vm = { ACM_LABEL_UNLABELED : [] }
        for v in vms:
            if v.has_key("stes"):
                vms_with_stes.append(v["name"])
                stes_by_vm[v["name"]] = v["stes"]

        if bootstrap in vms_with_stes:
            vms_with_stes.remove(bootstrap)
            vms_with_stes.sort()
            vms_with_stes.insert(0, bootstrap)
        else:
            vms_with_stes.sort()

        if ACM_LABEL_UNLABELED in vms_with_stes:
            vms_with_stes.remove(ACM_LABEL_UNLABELED) ; # @2

        resnames = self.policy_get_resourcelabel_names()
        resnames.sort()
        stes_by_res = {}
        res = self.policy_get_resourcelabels()
        for r in res:
            if r.has_key("stes"):
                stes_by_res[r["name"]] = r["stes"]

        if ACM_LABEL_UNLABELED in resnames:
            resnames.remove(ACM_LABEL_UNLABELED)

        max_chw_ssids = 1 + len(vms_with_chws)
        max_chw_types = 1 + len(vms_with_chws)
        max_ste_ssids = 1 + len(vms_with_stes) + len(resnames)
        max_ste_types = 1 + len(vms_with_stes) + len(resnames)

        mapfile  = "POLICYREFERENCENAME    %s\n" % self.get_name()
        mapfile += "MAGIC                  %08x\n" % ACM_MAGIC
        mapfile += "POLICFILE              %s\n" % \
            self.path_from_policy_name(self.get_name())
        mapfile += "BINARYFILE             %s\n" % self.get_filename(".bin")
        mapfile += "MAX-CHWALL-TYPES       %08x\n" % len(chws)
        mapfile += "MAX-CHWALL-SSIDS       %08x\n" % max_chw_ssids
        mapfile += "MAX-CHWALL-LABELS      %08x\n" % max_chw_ssids
        mapfile += "MAX-STE-TYPES          %08x\n" % len(stes)
        mapfile += "MAX-STE-SSIDS          %08x\n" % max_ste_ssids
        mapfile += "MAX-STE-LABELS         %08x\n" % max_ste_ssids
        mapfile += "\n"

        if chws:
            mapfile += \
                 "PRIMARY                CHWALL\n"
            primpolcode = ACM_CHINESE_WALL_POLICY
            if stes:
                mapfile += \
                     "SECONDARY              STE\n"
            else:
                mapfile += \
                     "SECONDARY             NULL\n"
            secpolcode = ACM_SIMPLE_TYPE_ENFORCEMENT_POLICY
        else:
            if stes:
                mapfile += \
                     "PRIMARY                STE\n"
                primpolcode = ACM_SIMPLE_TYPE_ENFORCEMENT_POLICY
            mapfile += \
                     "SECONDARY             NULL\n"

        mapfile += "\n"

        if len(vms_with_chws) > 0:
            mapfile += \
                 "LABEL->SSID ANY CHWALL __NULL_LABEL__       %x\n" % 0
            i = 0
            for v in vms_with_chws:
                mapfile += \
                 "LABEL->SSID VM  CHWALL %-20s %x\n" % \
                  (v, i+1)
                i += 1
            mapfile += "\n"

        if len(vms_with_stes) > 0 or len(resnames) > 0:
            mapfile += \
                 "LABEL->SSID ANY STE    __NULL_LABEL__       %08x\n" % 0
            i = 0
            for v in vms_with_stes:
                mapfile += \
                 "LABEL->SSID VM  STE    %-20s %x\n" % (v, i+1)
                i += 1
            j = 0
            for r in resnames:
                mapfile += \
                 "LABEL->SSID RES STE    %-20s %x\n" % (r, j+i+1)
                j += 1
            mapfile += "\n"

        if vms_with_chws:
            mapfile += \
                 "SSID->TYPE CHWALL      %08x\n" % 0
            i = 1
            for v in vms_with_chws:
                mapfile += \
                 "SSID->TYPE CHWALL      %08x" % i
                for c in chws_by_vm[v]:
                    mapfile += " %s" % c
                mapfile += "\n"
                i += 1
            mapfile += "\n"

        if len(vms_with_stes) > 0 or len(resnames) > 0:
            mapfile += \
                 "SSID->TYPE STE         %08x\n" % 0
            i = 1
            for v in vms_with_stes:
                mapfile += \
                 "SSID->TYPE STE         %08x" % i
                for s in stes_by_vm[v]:
                    mapfile += " %s" % s
                mapfile += "\n"
                i += 1

            for r in resnames:
                mapfile += \
                 "SSID->TYPE STE         %08x" % i
                for s in stes_by_res[r]:
                    mapfile += " %s" % s
                mapfile += "\n"
                i += 1
            mapfile += "\n"

        if chws:
            i = 0
            while i < len(chws):
                mapfile += \
                 "TYPE CHWALL            %-20s %d\n" % (chws[i], i)
                i += 1
            mapfile += "\n"
        if stes:
            i = 0
            while i < len(stes):
                mapfile += \
                 "TYPE STE               %-20s %d\n" % (stes[i], i)
                i += 1
            mapfile += "\n"

        mapfile += "\n"

        # Build header with policy name
        length = roundup8(4 + len(self.get_name()) + 1)
        polname = self.get_name();
        pr_bin = struct.pack("!i", len(polname)+1)
        pr_bin += polname;
        while len(pr_bin) < length:
             pr_bin += "\x00"

        # Build chinese wall part
        vms_with_chws.insert(0, ACM_LABEL_UNLABELED)

        cfses_names = self.policy_get_chwall_cfses_names_sorted()
        cfses = self.policy_get_chwall_cfses()

        chwformat = "!iiiiiiiii"
        max_chw_cfs = len(cfses)
        chw_ssid_offset = struct.calcsize(chwformat)
        chw_confset_offset = chw_ssid_offset + \
                             2 * len(chws) * max_chw_types
        chw_running_types_offset = 0
        chw_conf_agg_offset = 0

        chw_bin = struct.pack(chwformat,
                              ACM_CHWALL_VERSION,
                              ACM_CHINESE_WALL_POLICY,
                              len(chws),
                              max_chw_ssids,
                              max_chw_cfs,
                              chw_ssid_offset,
                              chw_confset_offset,
                              chw_running_types_offset,
                              chw_conf_agg_offset)
        chw_bin_body = ""

        # VMs that are listed and their chinese walls
        for v in vms_with_chws:
            for c in chws:
                unknown_chw |= (set(chws_by_vm[v]) - set(chws))
                if c in chws_by_vm[v]:
                    chw_bin_body += struct.pack("!h",1)
                else:
                    chw_bin_body += struct.pack("!h",0)

        # Conflict sets -- they need to be processed in alphabetical order
        for cn in cfses_names:
            if cn == "" or cn is None:
                return -xsconstants.XSERR_BAD_CONFLICTSET, "", ""
            i = 0
            while i < len(cfses):
                if cfses[i]['name'] == cn:
                    conf = cfses[i]['chws']
                    break
                i += 1
            for c in chws:
                if c in conf:
                    chw_bin_body += struct.pack("!h",1)
                else:
                    chw_bin_body += struct.pack("!h",0)
            del cfses[i]

        if len(cfses) != 0:
            return -xsconstants.XSERR_BAD_CONFLICTSET, "", ""

        chw_bin += chw_bin_body

        while len(chw_bin) < roundup8(len(chw_bin)):
            chw_bin += "\x00"

        # Build STE part
        vms_with_stes.insert(0, ACM_LABEL_UNLABELED) # Took out in @2

        steformat="!iiiii"
        ste_bin = struct.pack(steformat,
                              ACM_STE_VERSION,
                              ACM_SIMPLE_TYPE_ENFORCEMENT_POLICY,
                              len(stes),
                              max_ste_types,
                              struct.calcsize(steformat))
        ste_bin_body = ""
        if stes:
            # VMs that are listed and their STE types
            for v in vms_with_stes:
                unknown_ste |= (set(stes_by_vm[v]) - set(stes))
                for s in stes:
                    if s in stes_by_vm[v]:
                        ste_bin_body += struct.pack("!h",1)
                    else:
                        ste_bin_body += struct.pack("!h",0)
            for r in resnames:
                unknown_ste |= (set(stes_by_res[r]) - set(stes))
                for s in stes:
                    if s in stes_by_res[r]:
                        ste_bin_body += struct.pack("!h",1)
                    else:
                        ste_bin_body += struct.pack("!h",0)

        ste_bin += ste_bin_body;

        while len(ste_bin) < roundup8(len(ste_bin)):
            ste_bin += "\x00"

        #Write binary header:
        headerformat="!iiiiiiiiii"
        totallen_bin = struct.calcsize(headerformat) + \
                       len(pr_bin) + len(chw_bin) + len(ste_bin)
        polref_offset = struct.calcsize(headerformat)
        primpoloffset = polref_offset + len(pr_bin)
        if primpolcode == ACM_CHINESE_WALL_POLICY:
            secpoloffset = primpoloffset + len(chw_bin)
        elif primpolcode == ACM_SIMPLE_TYPE_ENFORCEMENT_POLICY:
            secpoloffset = primpoloffset + len(ste_bin)
        else:
            secpoloffset = primpoloffset

        (major, minor) = self.getVersionTuple()
        hdr_bin = struct.pack(headerformat,
                              ACM_POLICY_VERSION,
                              ACM_MAGIC,
                              totallen_bin,
                              polref_offset,
                              primpolcode,
                              primpoloffset,
                              secpolcode,
                              secpoloffset,
                              major, minor)

        all_bin = array.array('B')
        for s in [ hdr_bin, pr_bin, chw_bin, ste_bin ]:
            for c in s:
                all_bin.append(ord(c))

        log.info("Compiled policy: rc = %s" % hex(rc))
        if len(unknown_ste) > 0:
            log.info("The following STEs in VM/res labels were unknown:" \
                     " %s" % list(unknown_ste))
        if len(unknown_chw) > 0:
            log.info("The following Ch. Wall types in labels were unknown:" \
                     " %s" % list(unknown_chw))
        return rc, mapfile, all_bin.tostring()