• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright (C) 2005-2013 Red Hat
2# see file 'COPYING' for use and warranty information
3#
4# semanage is a tool for managing SELinux configuration files
5#
6#    This program is free software; you can redistribute it and/or
7#    modify it under the terms of the GNU General Public License as
8#    published by the Free Software Foundation; either version 2 of
9#    the License, or (at your option) any later version.
10#
11#    This program is distributed in the hope that it will be useful,
12#    but WITHOUT ANY WARRANTY; without even the implied warranty of
13#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14#    GNU General Public License for more details.
15#
16#    You should have received a copy of the GNU General Public License
17#    along with this program; if not, write to the Free Software
18#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19#                                        02111-1307  USA
20#
21#
22
23import pwd
24import grp
25import selinux
26import os
27import re
28import sys
29import stat
30import socket
31from semanage import *
32PROGNAME = "policycoreutils"
33import sepolicy
34import setools
35from IPy import IP
36
37try:
38    import gettext
39    kwargs = {}
40    if sys.version_info < (3,):
41        kwargs['unicode'] = True
42    gettext.install(PROGNAME,
43                    localedir="/usr/share/locale",
44                    codeset='utf-8',
45                    **kwargs)
46except:
47    try:
48        import builtins
49        builtins.__dict__['_'] = str
50    except ImportError:
51        import __builtin__
52        __builtin__.__dict__['_'] = unicode
53
54import syslog
55
56file_types = {}
57file_types[""] = SEMANAGE_FCONTEXT_ALL
58file_types["all files"] = SEMANAGE_FCONTEXT_ALL
59file_types["a"] = SEMANAGE_FCONTEXT_ALL
60file_types["regular file"] = SEMANAGE_FCONTEXT_REG
61file_types["--"] = SEMANAGE_FCONTEXT_REG
62file_types["f"] = SEMANAGE_FCONTEXT_REG
63file_types["-d"] = SEMANAGE_FCONTEXT_DIR
64file_types["directory"] = SEMANAGE_FCONTEXT_DIR
65file_types["d"] = SEMANAGE_FCONTEXT_DIR
66file_types["-c"] = SEMANAGE_FCONTEXT_CHAR
67file_types["character device"] = SEMANAGE_FCONTEXT_CHAR
68file_types["c"] = SEMANAGE_FCONTEXT_CHAR
69file_types["-b"] = SEMANAGE_FCONTEXT_BLOCK
70file_types["block device"] = SEMANAGE_FCONTEXT_BLOCK
71file_types["b"] = SEMANAGE_FCONTEXT_BLOCK
72file_types["-s"] = SEMANAGE_FCONTEXT_SOCK
73file_types["socket"] = SEMANAGE_FCONTEXT_SOCK
74file_types["s"] = SEMANAGE_FCONTEXT_SOCK
75file_types["-l"] = SEMANAGE_FCONTEXT_LINK
76file_types["l"] = SEMANAGE_FCONTEXT_LINK
77file_types["symbolic link"] = SEMANAGE_FCONTEXT_LINK
78file_types["p"] = SEMANAGE_FCONTEXT_PIPE
79file_types["-p"] = SEMANAGE_FCONTEXT_PIPE
80file_types["named pipe"] = SEMANAGE_FCONTEXT_PIPE
81
82file_type_str_to_option = {"all files": "a",
83                           "regular file": "f",
84                           "directory": "d",
85                           "character device": "c",
86                           "block device": "b",
87                           "socket": "s",
88                           "symbolic link": "l",
89                           "named pipe": "p"}
90
91ftype_to_audit = {"": "any",
92                  "a" : "any",
93                  "b": "block",
94                  "c": "char",
95                  "d": "dir",
96                  "f": "file",
97                  "l": "symlink",
98                  "p": "pipe",
99                  "s": "socket"}
100
101try:
102    import audit
103    #test if audit module is enabled
104    audit.audit_close(audit.audit_open())
105
106    class logger:
107
108        def __init__(self):
109            self.audit_fd = audit.audit_open()
110            self.log_list = []
111            self.log_change_list = []
112
113        def log(self, msg, name="", sename="", serole="", serange="", oldsename="", oldserole="", oldserange=""):
114
115            sep = "-"
116            if sename != oldsename:
117                msg += sep + "sename"
118                sep = ","
119            if serole != oldserole:
120                msg += sep + "role"
121                sep = ","
122            if serange != oldserange:
123                msg += sep + "range"
124                sep = ","
125
126            self.log_list.append([self.audit_fd, audit.AUDIT_ROLE_ASSIGN, sys.argv[0], str(msg), name, 0, sename, serole, serange, oldsename, oldserole, oldserange, "", "", ""])
127
128        def log_remove(self, msg, name="", sename="", serole="", serange="", oldsename="", oldserole="", oldserange=""):
129            self.log_list.append([self.audit_fd, audit.AUDIT_ROLE_REMOVE, sys.argv[0], str(msg), name, 0, sename, serole, serange, oldsename, oldserole, oldserange, "", "", ""])
130
131        def log_change(self, msg):
132            self.log_change_list.append([self.audit_fd, audit.AUDIT_USER_MAC_CONFIG_CHANGE, str(msg), "semanage", "", "", ""])
133
134        def commit(self, success):
135            for l in self.log_list:
136                audit.audit_log_semanage_message(*(l + [success]))
137            for l in self.log_change_list:
138                audit.audit_log_user_comm_message(*(l + [success]))
139
140            self.log_list = []
141            self.log_change_list = []
142except (OSError, ImportError):
143    class logger:
144
145        def __init__(self):
146            self.log_list = []
147
148        def log(self, msg, name="", sename="", serole="", serange="", oldsename="", oldserole="", oldserange=""):
149            message = " %s name=%s" % (msg, name)
150            if sename != "":
151                message += " sename=" + sename
152            if oldsename != "":
153                message += " oldsename=" + oldsename
154            if serole != "":
155                message += " role=" + serole
156            if oldserole != "":
157                message += " old_role=" + oldserole
158            if serange != "" and serange is not None:
159                message += " MLSRange=" + serange
160            if oldserange != "" and oldserange is not None:
161                message += " old_MLSRange=" + oldserange
162            self.log_list.append(message)
163
164        def log_remove(self, msg, name="", sename="", serole="", serange="", oldsename="", oldserole="", oldserange=""):
165            self.log(msg, name, sename, serole, serange, oldsename, oldserole, oldserange)
166
167        def log_change(self, msg):
168            self.log_list.append(" %s" % msg)
169
170        def commit(self, success):
171            if success == 1:
172                message = "Successful: "
173            else:
174                message = "Failed: "
175            for l in self.log_list:
176                syslog.syslog(syslog.LOG_INFO, message + l)
177
178
179class nulllogger:
180
181    def log(self, msg, name="", sename="", serole="", serange="", oldsename="", oldserole="", oldserange=""):
182        pass
183
184    def log_remove(self, msg, name="", sename="", serole="", serange="", oldsename="", oldserole="", oldserange=""):
185        pass
186
187    def log_change(self, msg):
188        pass
189
190    def commit(self, success):
191        pass
192
193
194def validate_level(raw):
195    sensitivity = "s[0-9]*"
196    category = "c[0-9]*"
197    cat_range = category + r"(\." + category + ")?"
198    categories = cat_range + r"(\," + cat_range + ")*"
199    reg = sensitivity + "(-" + sensitivity + ")?" + "(:" + categories + ")?"
200    return re.search("^" + reg + "$", raw)
201
202
203def translate(raw, prepend=1):
204    filler = "a:b:c:"
205    if prepend == 1:
206        context = "%s%s" % (filler, raw)
207    else:
208        context = raw
209    (rc, trans) = selinux.selinux_raw_to_trans_context(context)
210    if rc != 0:
211        return raw
212    if prepend:
213        trans = trans[len(filler):]
214    if trans == "":
215        return raw
216    else:
217        return trans
218
219
220def untranslate(trans, prepend=1):
221    filler = "a:b:c:"
222    if prepend == 1:
223        context = "%s%s" % (filler, trans)
224    else:
225        context = trans
226
227    (rc, raw) = selinux.selinux_trans_to_raw_context(context)
228    if rc != 0:
229        return trans
230    if prepend:
231        raw = raw[len(filler):]
232    if raw == "":
233        return trans
234    else:
235        return raw
236
237
238class semanageRecords:
239    transaction = False
240    handle = None
241    store = None
242    args = None
243
244    def __init__(self, args = None):
245        global handle
246        if args:
247            # legacy code - args was store originally
248            if type(args) == str:
249                self.store = args
250            else:
251                self.args = args
252        self.noreload = getattr(args, "noreload", False)
253        if not self.store:
254            self.store = getattr(args, "store", "")
255
256        self.sh = self.get_handle(self.store)
257
258        rc, localstore = selinux.selinux_getpolicytype()
259        if self.store == "" or self.store == localstore:
260            self.mylog = logger()
261        else:
262            sepolicy.load_store_policy(self.store)
263            selinux.selinux_set_policy_root("%s%s" % (selinux.selinux_path(), self.store))
264            self.mylog = nulllogger()
265
266    def set_reload(self, load):
267        self.noreload = not load
268
269    def get_handle(self, store):
270        global is_mls_enabled
271
272        if semanageRecords.handle:
273            return semanageRecords.handle
274
275        handle = semanage_handle_create()
276        if not handle:
277            raise ValueError(_("Could not create semanage handle"))
278
279        if not semanageRecords.transaction and store != "":
280            semanage_select_store(handle, store, SEMANAGE_CON_DIRECT)
281            semanageRecords.store = store
282
283        if not semanage_is_managed(handle):
284            semanage_handle_destroy(handle)
285            raise ValueError(_("SELinux policy is not managed or store cannot be accessed."))
286
287        rc = semanage_access_check(handle)
288        if rc < SEMANAGE_CAN_READ:
289            semanage_handle_destroy(handle)
290            raise ValueError(_("Cannot read policy store."))
291
292        rc = semanage_connect(handle)
293        if rc < 0:
294            semanage_handle_destroy(handle)
295            raise ValueError(_("Could not establish semanage connection"))
296
297        is_mls_enabled = semanage_mls_enabled(handle)
298        if is_mls_enabled < 0:
299            semanage_handle_destroy(handle)
300            raise ValueError(_("Could not test MLS enabled status"))
301
302        semanageRecords.handle = handle
303        return semanageRecords.handle
304
305    def deleteall(self):
306        raise ValueError(_("Not yet implemented"))
307
308    def start(self):
309        if semanageRecords.transaction:
310            raise ValueError(_("Semanage transaction already in progress"))
311        self.begin()
312        semanageRecords.transaction = True
313
314    def begin(self):
315        if semanageRecords.transaction:
316            return
317        rc = semanage_begin_transaction(self.sh)
318        if rc < 0:
319            raise ValueError(_("Could not start semanage transaction"))
320
321    def customized(self):
322        raise ValueError(_("Not yet implemented"))
323
324    def commit(self):
325        if semanageRecords.transaction:
326            return
327
328        if self.noreload:
329            semanage_set_reload(self.sh, 0)
330        rc = semanage_commit(self.sh)
331        if rc < 0:
332            self.mylog.commit(0)
333            raise ValueError(_("Could not commit semanage transaction"))
334        self.mylog.commit(1)
335
336    def finish(self):
337        if not semanageRecords.transaction:
338            raise ValueError(_("Semanage transaction not in progress"))
339        semanageRecords.transaction = False
340        self.commit()
341
342
343class moduleRecords(semanageRecords):
344
345    def __init__(self, args = None):
346        semanageRecords.__init__(self, args)
347
348    def get_all(self):
349        l = []
350        (rc, mlist, number) = semanage_module_list_all(self.sh)
351        if rc < 0:
352            raise ValueError(_("Could not list SELinux modules"))
353
354        for i in range(number):
355            mod = semanage_module_list_nth(mlist, i)
356
357            rc, name = semanage_module_info_get_name(self.sh, mod)
358            if rc < 0:
359                raise ValueError(_("Could not get module name"))
360
361            rc, enabled = semanage_module_info_get_enabled(self.sh, mod)
362            if rc < 0:
363                raise ValueError(_("Could not get module enabled"))
364
365            rc, priority = semanage_module_info_get_priority(self.sh, mod)
366            if rc < 0:
367                raise ValueError(_("Could not get module priority"))
368
369            rc, lang_ext = semanage_module_info_get_lang_ext(self.sh, mod)
370            if rc < 0:
371                raise ValueError(_("Could not get module lang_ext"))
372
373            l.append((name, enabled, priority, lang_ext))
374
375        # sort the list so they are in name order, but with higher priorities coming first
376        l.sort(key=lambda t: t[3], reverse=True)
377        l.sort(key=lambda t: t[0])
378        return l
379
380    def customized(self):
381        all = self.get_all()
382        if len(all) == 0:
383            return
384        return ["-d %s" % x[0] for x in [t for t in all if t[1] == 0]]
385
386    def list(self, heading=1, locallist=0):
387        all = self.get_all()
388        if len(all) == 0:
389            return
390
391        if heading:
392            print("\n%-25s %-9s %s\n" % (_("Module Name"), _("Priority"), _("Language")))
393        for t in all:
394            if t[1] == 0:
395                disabled = _("Disabled")
396            else:
397                if locallist:
398                    continue
399                disabled = ""
400            print("%-25s %-9s %-5s %s" % (t[0], t[2], t[3], disabled))
401
402    def add(self, file, priority):
403        if not os.path.exists(file):
404            raise ValueError(_("Module does not exist: %s ") % file)
405
406        rc = semanage_set_default_priority(self.sh, priority)
407        if rc < 0:
408            raise ValueError(_("Invalid priority %d (needs to be between 1 and 999)") % priority)
409
410        rc = semanage_module_install_file(self.sh, file)
411        if rc >= 0:
412            self.commit()
413
414    def set_enabled(self, module, enable):
415        for m in module.split():
416            rc, key = semanage_module_key_create(self.sh)
417            if rc < 0:
418                raise ValueError(_("Could not create module key"))
419
420            rc = semanage_module_key_set_name(self.sh, key, m)
421            if rc < 0:
422                raise ValueError(_("Could not set module key name"))
423
424            rc = semanage_module_set_enabled(self.sh, key, enable)
425            if rc < 0:
426                if enable:
427                    raise ValueError(_("Could not enable module %s") % m)
428                else:
429                    raise ValueError(_("Could not disable module %s") % m)
430        self.commit()
431
432    def delete(self, module, priority):
433        rc = semanage_set_default_priority(self.sh, priority)
434        if rc < 0:
435            raise ValueError(_("Invalid priority %d (needs to be between 1 and 999)") % priority)
436
437        for m in module.split():
438            rc = semanage_module_remove(self.sh, m)
439            if rc < 0 and rc != -2:
440                raise ValueError(_("Could not remove module %s (remove failed)") % m)
441
442        self.commit()
443
444    def deleteall(self):
445        l = [x[0] for x in [t for t in self.get_all() if t[1] == 0]]
446        for m in l:
447            self.set_enabled(m, True)
448
449
450class dontauditClass(semanageRecords):
451
452    def __init__(self, args = None):
453        semanageRecords.__init__(self, args)
454
455    def toggle(self, dontaudit):
456        if dontaudit not in ["on", "off"]:
457            raise ValueError(_("dontaudit requires either 'on' or 'off'"))
458        self.begin()
459        semanage_set_disable_dontaudit(self.sh, dontaudit == "off")
460        self.commit()
461
462
463class permissiveRecords(semanageRecords):
464
465    def __init__(self, args = None):
466        semanageRecords.__init__(self, args)
467
468    def get_all(self):
469        l = []
470        (rc, mlist, number) = semanage_module_list(self.sh)
471        if rc < 0:
472            raise ValueError(_("Could not list SELinux modules"))
473
474        for i in range(number):
475            mod = semanage_module_list_nth(mlist, i)
476            name = semanage_module_get_name(mod)
477            if name and name.startswith("permissive_"):
478                l.append(name.split("permissive_")[1])
479        return l
480
481    def list(self, heading=1, locallist=0):
482        all = [y["name"] for y in [x for x in sepolicy.info(sepolicy.TYPE) if x["permissive"]]]
483        if len(all) == 0:
484            return
485
486        if heading:
487            print("\n%-25s\n" % (_("Builtin Permissive Types")))
488        customized = self.get_all()
489        for t in all:
490            if t not in customized:
491                print(t)
492
493        if len(customized) == 0:
494            return
495
496        if heading:
497            print("\n%-25s\n" % (_("Customized Permissive Types")))
498        for t in customized:
499            print(t)
500
501    def add(self, type):
502        try:
503            import sepolgen.module as module
504        except ImportError:
505            raise ValueError(_("The sepolgen python module is required to setup permissive domains.\nIn some distributions it is included in the policycoreutils-devel package.\n# yum install policycoreutils-devel\nOr similar for your distro."))
506
507        name = "permissive_%s" % type
508        modtxt = "(typepermissive %s)" % type
509
510        rc = semanage_module_install(self.sh, modtxt, len(modtxt), name, "cil")
511        if rc >= 0:
512            self.commit()
513
514        if rc < 0:
515            raise ValueError(_("Could not set permissive domain %s (module installation failed)") % name)
516
517    def delete(self, name):
518        for n in name.split():
519            rc = semanage_module_remove(self.sh, "permissive_%s" % n)
520            if rc < 0:
521                raise ValueError(_("Could not remove permissive domain %s (remove failed)") % name)
522
523        self.commit()
524
525    def deleteall(self):
526        l = self.get_all()
527        if len(l) > 0:
528            all = " ".join(l)
529            self.delete(all)
530
531
532class loginRecords(semanageRecords):
533
534    def __init__(self, args = None):
535        semanageRecords.__init__(self, args)
536        self.oldsename = None
537        self.oldserange = None
538        self.sename = None
539        self.serange = None
540
541    def __add(self, name, sename, serange):
542        rec, self.oldsename, self.oldserange = selinux.getseuserbyname(name)
543        if sename == "":
544            sename = "user_u"
545
546        userrec = seluserRecords(self.args)
547        range, (rc, oldserole) = userrec.get(self.oldsename)
548        range, (rc, serole) = userrec.get(sename)
549
550        if is_mls_enabled == 1:
551            if serange != "":
552                serange = untranslate(serange)
553            else:
554                serange = range
555
556        (rc, k) = semanage_seuser_key_create(self.sh, name)
557        if rc < 0:
558            raise ValueError(_("Could not create a key for %s") % name)
559
560        (rc, exists) = semanage_seuser_exists(self.sh, k)
561        if rc < 0:
562            raise ValueError(_("Could not check if login mapping for %s is defined") % name)
563        if exists:
564            raise ValueError(_("Login mapping for %s is already defined") % name)
565        if name[0] == '%':
566            try:
567                grp.getgrnam(name[1:])
568            except:
569                raise ValueError(_("Linux Group %s does not exist") % name[1:])
570        else:
571            try:
572                pwd.getpwnam(name)
573            except:
574                raise ValueError(_("Linux User %s does not exist") % name)
575
576        (rc, u) = semanage_seuser_create(self.sh)
577        if rc < 0:
578            raise ValueError(_("Could not create login mapping for %s") % name)
579
580        rc = semanage_seuser_set_name(self.sh, u, name)
581        if rc < 0:
582            raise ValueError(_("Could not set name for %s") % name)
583
584        if (is_mls_enabled == 1) and (serange != ""):
585            rc = semanage_seuser_set_mlsrange(self.sh, u, serange)
586            if rc < 0:
587                raise ValueError(_("Could not set MLS range for %s") % name)
588
589        rc = semanage_seuser_set_sename(self.sh, u, sename)
590        if rc < 0:
591            raise ValueError(_("Could not set SELinux user for %s") % name)
592
593        rc = semanage_seuser_modify_local(self.sh, k, u)
594        if rc < 0:
595            raise ValueError(_("Could not add login mapping for %s") % name)
596
597        semanage_seuser_key_free(k)
598        semanage_seuser_free(u)
599
600    def add(self, name, sename, serange):
601        try:
602            self.begin()
603            self.__add(name, sename, serange)
604            self.commit()
605        except ValueError as error:
606            raise error
607
608    def __modify(self, name, sename="", serange=""):
609        rec, self.oldsename, self.oldserange = selinux.getseuserbyname(name)
610        if sename == "" and serange == "":
611            raise ValueError(_("Requires seuser or serange"))
612
613        userrec = seluserRecords(self.args)
614        range, (rc, oldserole) = userrec.get(self.oldsename)
615
616        if sename != "":
617            range, (rc, serole) = userrec.get(sename)
618        else:
619            serole = oldserole
620
621        if serange != "":
622            self.serange = serange
623        else:
624            self.serange = range
625
626        (rc, k) = semanage_seuser_key_create(self.sh, name)
627        if rc < 0:
628            raise ValueError(_("Could not create a key for %s") % name)
629
630        (rc, exists) = semanage_seuser_exists(self.sh, k)
631        if rc < 0:
632            raise ValueError(_("Could not check if login mapping for %s is defined") % name)
633        if not exists:
634            raise ValueError(_("Login mapping for %s is not defined") % name)
635
636        (rc, u) = semanage_seuser_query(self.sh, k)
637        if rc < 0:
638            raise ValueError(_("Could not query seuser for %s") % name)
639
640        self.oldserange = semanage_seuser_get_mlsrange(u)
641        self.oldsename = semanage_seuser_get_sename(u)
642        if (is_mls_enabled == 1) and (serange != ""):
643            semanage_seuser_set_mlsrange(self.sh, u, untranslate(serange))
644
645        if sename != "":
646            semanage_seuser_set_sename(self.sh, u, sename)
647            self.sename = sename
648        else:
649            self.sename = self.oldsename
650
651        rc = semanage_seuser_modify_local(self.sh, k, u)
652        if rc < 0:
653            raise ValueError(_("Could not modify login mapping for %s") % name)
654
655        semanage_seuser_key_free(k)
656        semanage_seuser_free(u)
657
658    def modify(self, name, sename="", serange=""):
659        try:
660            self.begin()
661            self.__modify(name, sename, serange)
662            self.commit()
663        except ValueError as error:
664            raise error
665
666    def __delete(self, name):
667        rec, self.oldsename, self.oldserange = selinux.getseuserbyname(name)
668        userrec = seluserRecords(self.args)
669        range, (rc, oldserole) = userrec.get(self.oldsename)
670
671        (rc, k) = semanage_seuser_key_create(self.sh, name)
672        if rc < 0:
673            raise ValueError(_("Could not create a key for %s") % name)
674
675        (rc, exists) = semanage_seuser_exists(self.sh, k)
676        if rc < 0:
677            raise ValueError(_("Could not check if login mapping for %s is defined") % name)
678        if not exists:
679            raise ValueError(_("Login mapping for %s is not defined") % name)
680
681        (rc, exists) = semanage_seuser_exists_local(self.sh, k)
682        if rc < 0:
683            raise ValueError(_("Could not check if login mapping for %s is defined") % name)
684        if not exists:
685            raise ValueError(_("Login mapping for %s is defined in policy, cannot be deleted") % name)
686
687        rc = semanage_seuser_del_local(self.sh, k)
688        if rc < 0:
689            raise ValueError(_("Could not delete login mapping for %s") % name)
690
691        semanage_seuser_key_free(k)
692
693        rec, self.sename, self.serange = selinux.getseuserbyname("__default__")
694        range, (rc, serole) = userrec.get(self.sename)
695
696    def delete(self, name):
697        try:
698            self.begin()
699            self.__delete(name)
700            self.commit()
701
702        except ValueError as error:
703            raise error
704
705    def deleteall(self):
706        (rc, ulist) = semanage_seuser_list_local(self.sh)
707        if rc < 0:
708            raise ValueError(_("Could not list login mappings"))
709
710        try:
711            self.begin()
712            for u in ulist:
713                self.__delete(semanage_seuser_get_name(u))
714            self.commit()
715        except ValueError as error:
716            raise error
717
718    def get_all_logins(self):
719        ddict = {}
720        self.logins_path = selinux.selinux_policy_root() + "/logins"
721        for path, dirs, files in os.walk(self.logins_path):
722            if path == self.logins_path:
723                for name in files:
724                    try:
725                        fd = open(path + "/" + name)
726                        rec = fd.read().rstrip().split(":")
727                        fd.close()
728                        ddict[name] = (rec[1], rec[2], rec[0])
729                    except IndexError:
730                        pass
731        return ddict
732
733    def get_all(self, locallist=0):
734        ddict = {}
735        if locallist:
736            (rc, self.ulist) = semanage_seuser_list_local(self.sh)
737        else:
738            (rc, self.ulist) = semanage_seuser_list(self.sh)
739        if rc < 0:
740            raise ValueError(_("Could not list login mappings"))
741
742        for u in self.ulist:
743            name = semanage_seuser_get_name(u)
744            ddict[name] = (semanage_seuser_get_sename(u), semanage_seuser_get_mlsrange(u), "*")
745        return ddict
746
747    def customized(self):
748        l = []
749        ddict = self.get_all(True)
750        for k in sorted(ddict.keys()):
751            if ddict[k][1]:
752                l.append("-a -s %s -r '%s' %s" % (ddict[k][0], ddict[k][1], k))
753            else:
754                l.append("-a -s %s %s" % (ddict[k][0], k))
755        return l
756
757    def list(self, heading=1, locallist=0):
758        ddict = self.get_all(locallist)
759        ldict = self.get_all_logins()
760        lkeys = sorted(ldict.keys())
761        keys = sorted(ddict.keys())
762        if len(keys) == 0 and len(lkeys) == 0:
763            return
764
765        if is_mls_enabled == 1:
766            if heading:
767                print("\n%-20s %-20s %-20s %s\n" % (_("Login Name"), _("SELinux User"), _("MLS/MCS Range"), _("Service")))
768            for k in keys:
769                u = ddict[k]
770                print("%-20s %-20s %-20s %s" % (k, u[0], translate(u[1]), u[2]))
771            if len(lkeys):
772                print("\nLocal customization in %s" % self.logins_path)
773
774            for k in lkeys:
775                u = ldict[k]
776                print("%-20s %-20s %-20s %s" % (k, u[0], translate(u[1]), u[2]))
777        else:
778            if heading:
779                print("\n%-25s %-25s\n" % (_("Login Name"), _("SELinux User")))
780            for k in keys:
781                print("%-25s %-25s" % (k, ddict[k][0]))
782
783
784class seluserRecords(semanageRecords):
785
786    def __init__(self, args = None):
787        semanageRecords.__init__(self, args)
788
789    def get(self, name):
790        (rc, k) = semanage_user_key_create(self.sh, name)
791        if rc < 0:
792            raise ValueError(_("Could not create a key for %s") % name)
793        (rc, exists) = semanage_user_exists(self.sh, k)
794        if rc < 0:
795            raise ValueError(_("Could not check if SELinux user %s is defined") % name)
796        (rc, u) = semanage_user_query(self.sh, k)
797        if rc < 0:
798            raise ValueError(_("Could not query user for %s") % name)
799        serange = semanage_user_get_mlsrange(u)
800        serole = semanage_user_get_roles(self.sh, u)
801        semanage_user_key_free(k)
802        semanage_user_free(u)
803        return serange, serole
804
805    def __add(self, name, roles, selevel, serange, prefix):
806        if is_mls_enabled == 1:
807            if serange == "":
808                serange = "s0"
809            else:
810                serange = untranslate(serange)
811
812            if selevel == "":
813                selevel = "s0"
814            else:
815                selevel = untranslate(selevel)
816
817        if len(roles) < 1:
818            raise ValueError(_("You must add at least one role for %s") % name)
819
820        (rc, k) = semanage_user_key_create(self.sh, name)
821        if rc < 0:
822            raise ValueError(_("Could not create a key for %s") % name)
823
824        (rc, exists) = semanage_user_exists(self.sh, k)
825        if rc < 0:
826            raise ValueError(_("Could not check if SELinux user %s is defined") % name)
827        if exists:
828            raise ValueError(_("SELinux user %s is already defined") % name)
829
830        (rc, u) = semanage_user_create(self.sh)
831        if rc < 0:
832            raise ValueError(_("Could not create SELinux user for %s") % name)
833
834        rc = semanage_user_set_name(self.sh, u, name)
835        if rc < 0:
836            raise ValueError(_("Could not set name for %s") % name)
837
838        for r in roles:
839            rc = semanage_user_add_role(self.sh, u, r)
840            if rc < 0:
841                raise ValueError(_("Could not add role %s for %s") % (r, name))
842
843        if is_mls_enabled == 1:
844            rc = semanage_user_set_mlsrange(self.sh, u, serange)
845            if rc < 0:
846                raise ValueError(_("Could not set MLS range for %s") % name)
847
848            rc = semanage_user_set_mlslevel(self.sh, u, selevel)
849            if rc < 0:
850                raise ValueError(_("Could not set MLS level for %s") % name)
851        rc = semanage_user_set_prefix(self.sh, u, prefix)
852        if rc < 0:
853            raise ValueError(_("Could not add prefix %s for %s") % (r, prefix))
854        (rc, key) = semanage_user_key_extract(self.sh, u)
855        if rc < 0:
856            raise ValueError(_("Could not extract key for %s") % name)
857
858        rc = semanage_user_modify_local(self.sh, k, u)
859        if rc < 0:
860            raise ValueError(_("Could not add SELinux user %s") % name)
861
862        semanage_user_key_free(k)
863        semanage_user_free(u)
864        self.mylog.log("seuser", sename=name, serole=",".join(roles), serange=serange)
865
866    def add(self, name, roles, selevel, serange, prefix):
867        try:
868            self.begin()
869            self.__add(name, roles, selevel, serange, prefix)
870            self.commit()
871        except ValueError as error:
872            self.mylog.commit(0)
873            raise error
874
875    def __modify(self, name, roles=[], selevel="", serange="", prefix=""):
876        oldserole = ""
877        oldserange = ""
878        newroles = " ".join(roles)
879        if prefix == "" and len(roles) == 0 and serange == "" and selevel == "":
880            if is_mls_enabled == 1:
881                raise ValueError(_("Requires prefix, roles, level or range"))
882            else:
883                raise ValueError(_("Requires prefix or roles"))
884
885        (rc, k) = semanage_user_key_create(self.sh, name)
886        if rc < 0:
887            raise ValueError(_("Could not create a key for %s") % name)
888
889        (rc, exists) = semanage_user_exists(self.sh, k)
890        if rc < 0:
891            raise ValueError(_("Could not check if SELinux user %s is defined") % name)
892        if not exists:
893            raise ValueError(_("SELinux user %s is not defined") % name)
894
895        (rc, u) = semanage_user_query(self.sh, k)
896        if rc < 0:
897            raise ValueError(_("Could not query user for %s") % name)
898
899        oldserange = semanage_user_get_mlsrange(u)
900        (rc, rlist) = semanage_user_get_roles(self.sh, u)
901        if rc >= 0:
902            oldserole = " ".join(rlist)
903
904        if (is_mls_enabled == 1) and (serange != ""):
905            semanage_user_set_mlsrange(self.sh, u, untranslate(serange))
906        if (is_mls_enabled == 1) and (selevel != ""):
907            semanage_user_set_mlslevel(self.sh, u, untranslate(selevel))
908
909        if prefix != "":
910            semanage_user_set_prefix(self.sh, u, prefix)
911
912        if len(roles) != 0:
913            for r in rlist:
914                if r not in roles:
915                    semanage_user_del_role(u, r)
916            for r in roles:
917                if r not in rlist:
918                    semanage_user_add_role(self.sh, u, r)
919
920        rc = semanage_user_modify_local(self.sh, k, u)
921        if rc < 0:
922            raise ValueError(_("Could not modify SELinux user %s") % name)
923
924        semanage_user_key_free(k)
925        semanage_user_free(u)
926
927        role = ",".join(newroles.split())
928        oldserole = ",".join(oldserole.split())
929        self.mylog.log("seuser", sename=name, oldsename=name, serole=role, serange=serange, oldserole=oldserole, oldserange=oldserange)
930
931    def modify(self, name, roles=[], selevel="", serange="", prefix=""):
932        try:
933            self.begin()
934            self.__modify(name, roles, selevel, serange, prefix)
935            self.commit()
936        except ValueError as error:
937            self.mylog.commit(0)
938            raise error
939
940    def __delete(self, name):
941        (rc, k) = semanage_user_key_create(self.sh, name)
942        if rc < 0:
943            raise ValueError(_("Could not create a key for %s") % name)
944
945        (rc, exists) = semanage_user_exists(self.sh, k)
946        if rc < 0:
947            raise ValueError(_("Could not check if SELinux user %s is defined") % name)
948        if not exists:
949            raise ValueError(_("SELinux user %s is not defined") % name)
950
951        (rc, exists) = semanage_user_exists_local(self.sh, k)
952        if rc < 0:
953            raise ValueError(_("Could not check if SELinux user %s is defined") % name)
954        if not exists:
955            raise ValueError(_("SELinux user %s is defined in policy, cannot be deleted") % name)
956
957        (rc, u) = semanage_user_query(self.sh, k)
958        if rc < 0:
959            raise ValueError(_("Could not query user for %s") % name)
960        oldserange = semanage_user_get_mlsrange(u)
961        (rc, rlist) = semanage_user_get_roles(self.sh, u)
962        oldserole = ",".join(rlist)
963
964        rc = semanage_user_del_local(self.sh, k)
965        if rc < 0:
966            raise ValueError(_("Could not delete SELinux user %s") % name)
967
968        semanage_user_key_free(k)
969        semanage_user_free(u)
970
971        self.mylog.log_remove("seuser", oldsename=name, oldserange=oldserange, oldserole=oldserole)
972
973    def delete(self, name):
974        try:
975            self.begin()
976            self.__delete(name)
977            self.commit()
978
979        except ValueError as error:
980            self.mylog.commit(0)
981            raise error
982
983    def deleteall(self):
984        (rc, ulist) = semanage_user_list_local(self.sh)
985        if rc < 0:
986            raise ValueError(_("Could not list login mappings"))
987
988        try:
989            self.begin()
990            for u in ulist:
991                self.__delete(semanage_user_get_name(u))
992            self.commit()
993        except ValueError as error:
994            self.mylog.commit(0)
995            raise error
996
997    def get_all(self, locallist=0):
998        ddict = {}
999        if locallist:
1000            (rc, self.ulist) = semanage_user_list_local(self.sh)
1001        else:
1002            (rc, self.ulist) = semanage_user_list(self.sh)
1003        if rc < 0:
1004            raise ValueError(_("Could not list SELinux users"))
1005
1006        for u in self.ulist:
1007            name = semanage_user_get_name(u)
1008            (rc, rlist) = semanage_user_get_roles(self.sh, u)
1009            if rc < 0:
1010                raise ValueError(_("Could not list roles for user %s") % name)
1011
1012            roles = " ".join(rlist)
1013            ddict[semanage_user_get_name(u)] = (semanage_user_get_prefix(u), semanage_user_get_mlslevel(u), semanage_user_get_mlsrange(u), roles)
1014
1015        return ddict
1016
1017    def customized(self):
1018        l = []
1019        ddict = self.get_all(True)
1020        for k in sorted(ddict.keys()):
1021            if ddict[k][1] or ddict[k][2]:
1022                l.append("-a -L %s -r %s -R '%s' %s" % (ddict[k][1], ddict[k][2], ddict[k][3], k))
1023            else:
1024                l.append("-a -R '%s' %s" % (ddict[k][3], k))
1025        return l
1026
1027    def list(self, heading=1, locallist=0):
1028        ddict = self.get_all(locallist)
1029        if len(ddict) == 0:
1030            return
1031        keys = sorted(ddict.keys())
1032
1033        if is_mls_enabled == 1:
1034            if heading:
1035                print("\n%-15s %-10s %-10s %-30s" % ("", _("Labeling"), _("MLS/"), _("MLS/")))
1036                print("%-15s %-10s %-10s %-30s %s\n" % (_("SELinux User"), _("Prefix"), _("MCS Level"), _("MCS Range"), _("SELinux Roles")))
1037            for k in keys:
1038                print("%-15s %-10s %-10s %-30s %s" % (k, ddict[k][0], translate(ddict[k][1]), translate(ddict[k][2]), ddict[k][3]))
1039        else:
1040            if heading:
1041                print("%-15s %s\n" % (_("SELinux User"), _("SELinux Roles")))
1042            for k in keys:
1043                print("%-15s %s" % (k, ddict[k][3]))
1044
1045
1046class portRecords(semanageRecords):
1047
1048    valid_types = []
1049
1050    def __init__(self, args = None):
1051        semanageRecords.__init__(self, args)
1052        try:
1053            self.valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "port_type"))[0]["types"])
1054        except RuntimeError:
1055            pass
1056
1057    def __genkey(self, port, proto):
1058        if proto == "tcp":
1059            proto_d = SEMANAGE_PROTO_TCP
1060        else:
1061            if proto == "udp":
1062                proto_d = SEMANAGE_PROTO_UDP
1063            else:
1064                raise ValueError(_("Protocol udp or tcp is required"))
1065        if port == "":
1066            raise ValueError(_("Port is required"))
1067
1068        ports = port.split("-")
1069        if len(ports) == 1:
1070            high = low = int(ports[0])
1071        else:
1072            low = int(ports[0])
1073            high = int(ports[1])
1074
1075        if high > 65535:
1076            raise ValueError(_("Invalid Port"))
1077
1078        (rc, k) = semanage_port_key_create(self.sh, low, high, proto_d)
1079        if rc < 0:
1080            raise ValueError(_("Could not create a key for %s/%s") % (proto, port))
1081        return (k, proto_d, low, high)
1082
1083    def __add(self, port, proto, serange, type):
1084        if is_mls_enabled == 1:
1085            if serange == "":
1086                serange = "s0"
1087            else:
1088                serange = untranslate(serange)
1089
1090        if type == "":
1091            raise ValueError(_("Type is required"))
1092
1093        type = sepolicy.get_real_type_name(type)
1094
1095        if type not in self.valid_types:
1096            raise ValueError(_("Type %s is invalid, must be a port type") % type)
1097
1098        (k, proto_d, low, high) = self.__genkey(port, proto)
1099
1100        (rc, exists) = semanage_port_exists(self.sh, k)
1101        if rc < 0:
1102            raise ValueError(_("Could not check if port %s/%s is defined") % (proto, port))
1103        if exists:
1104            raise ValueError(_("Port %s/%s already defined") % (proto, port))
1105
1106        (rc, p) = semanage_port_create(self.sh)
1107        if rc < 0:
1108            raise ValueError(_("Could not create port for %s/%s") % (proto, port))
1109
1110        semanage_port_set_proto(p, proto_d)
1111        semanage_port_set_range(p, low, high)
1112        (rc, con) = semanage_context_create(self.sh)
1113        if rc < 0:
1114            raise ValueError(_("Could not create context for %s/%s") % (proto, port))
1115
1116        rc = semanage_context_set_user(self.sh, con, "system_u")
1117        if rc < 0:
1118            raise ValueError(_("Could not set user in port context for %s/%s") % (proto, port))
1119
1120        rc = semanage_context_set_role(self.sh, con, "object_r")
1121        if rc < 0:
1122            raise ValueError(_("Could not set role in port context for %s/%s") % (proto, port))
1123
1124        rc = semanage_context_set_type(self.sh, con, type)
1125        if rc < 0:
1126            raise ValueError(_("Could not set type in port context for %s/%s") % (proto, port))
1127
1128        if (is_mls_enabled == 1) and (serange != ""):
1129            rc = semanage_context_set_mls(self.sh, con, serange)
1130            if rc < 0:
1131                raise ValueError(_("Could not set mls fields in port context for %s/%s") % (proto, port))
1132
1133        rc = semanage_port_set_con(self.sh, p, con)
1134        if rc < 0:
1135            raise ValueError(_("Could not set port context for %s/%s") % (proto, port))
1136
1137        rc = semanage_port_modify_local(self.sh, k, p)
1138        if rc < 0:
1139            raise ValueError(_("Could not add port %s/%s") % (proto, port))
1140
1141        semanage_context_free(con)
1142        semanage_port_key_free(k)
1143        semanage_port_free(p)
1144
1145        self.mylog.log_change("resrc=port op=add lport=%s proto=%s tcontext=%s:%s:%s:%s" % (port, socket.getprotobyname(proto), "system_u", "object_r", type, serange))
1146
1147    def add(self, port, proto, serange, type):
1148        self.begin()
1149        self.__add(port, proto, serange, type)
1150        self.commit()
1151
1152    def __modify(self, port, proto, serange, setype):
1153        if serange == "" and setype == "":
1154            if is_mls_enabled == 1:
1155                raise ValueError(_("Requires setype or serange"))
1156            else:
1157                raise ValueError(_("Requires setype"))
1158
1159        setype = sepolicy.get_real_type_name(setype)
1160        if setype and setype not in self.valid_types:
1161            raise ValueError(_("Type %s is invalid, must be a port type") % setype)
1162
1163        (k, proto_d, low, high) = self.__genkey(port, proto)
1164
1165        (rc, exists) = semanage_port_exists(self.sh, k)
1166        if rc < 0:
1167            raise ValueError(_("Could not check if port %s/%s is defined") % (proto, port))
1168        if not exists:
1169            raise ValueError(_("Port %s/%s is not defined") % (proto, port))
1170
1171        (rc, p) = semanage_port_query(self.sh, k)
1172        if rc < 0:
1173            raise ValueError(_("Could not query port %s/%s") % (proto, port))
1174
1175        con = semanage_port_get_con(p)
1176
1177        if is_mls_enabled == 1:
1178            if serange == "":
1179                serange = "s0"
1180            else:
1181                semanage_context_set_mls(self.sh, con, untranslate(serange))
1182        if setype != "":
1183            semanage_context_set_type(self.sh, con, setype)
1184
1185        rc = semanage_port_modify_local(self.sh, k, p)
1186        if rc < 0:
1187            raise ValueError(_("Could not modify port %s/%s") % (proto, port))
1188
1189        semanage_port_key_free(k)
1190        semanage_port_free(p)
1191
1192        self.mylog.log_change("resrc=port op=modify lport=%s proto=%s tcontext=%s:%s:%s:%s" % (port, socket.getprotobyname(proto), "system_u", "object_r", setype, serange))
1193
1194    def modify(self, port, proto, serange, setype):
1195        self.begin()
1196        self.__modify(port, proto, serange, setype)
1197        self.commit()
1198
1199    def deleteall(self):
1200        (rc, plist) = semanage_port_list_local(self.sh)
1201        if rc < 0:
1202            raise ValueError(_("Could not list the ports"))
1203
1204        self.begin()
1205
1206        for port in plist:
1207            proto = semanage_port_get_proto(port)
1208            proto_str = semanage_port_get_proto_str(proto)
1209            low = semanage_port_get_low(port)
1210            high = semanage_port_get_high(port)
1211            port_str = "%s-%s" % (low, high)
1212
1213            (k, proto_d, low, high) = self.__genkey(port_str, proto_str)
1214            if rc < 0:
1215                raise ValueError(_("Could not create a key for %s") % port_str)
1216
1217            rc = semanage_port_del_local(self.sh, k)
1218            if rc < 0:
1219                raise ValueError(_("Could not delete the port %s") % port_str)
1220            semanage_port_key_free(k)
1221
1222            if low == high:
1223                port_str = low
1224
1225            self.mylog.log_change("resrc=port op=delete lport=%s proto=%s" % (port_str, socket.getprotobyname(proto_str)))
1226
1227        self.commit()
1228
1229    def __delete(self, port, proto):
1230        (k, proto_d, low, high) = self.__genkey(port, proto)
1231        (rc, exists) = semanage_port_exists(self.sh, k)
1232        if rc < 0:
1233            raise ValueError(_("Could not check if port %s/%s is defined") % (proto, port))
1234        if not exists:
1235            raise ValueError(_("Port %s/%s is not defined") % (proto, port))
1236
1237        (rc, exists) = semanage_port_exists_local(self.sh, k)
1238        if rc < 0:
1239            raise ValueError(_("Could not check if port %s/%s is defined") % (proto, port))
1240        if not exists:
1241            raise ValueError(_("Port %s/%s is defined in policy, cannot be deleted") % (proto, port))
1242
1243        rc = semanage_port_del_local(self.sh, k)
1244        if rc < 0:
1245            raise ValueError(_("Could not delete port %s/%s") % (proto, port))
1246
1247        semanage_port_key_free(k)
1248
1249        self.mylog.log_change("resrc=port op=delete lport=%s proto=%s" % (port, socket.getprotobyname(proto)))
1250
1251    def delete(self, port, proto):
1252        self.begin()
1253        self.__delete(port, proto)
1254        self.commit()
1255
1256    def get_all(self, locallist=0):
1257        ddict = {}
1258        if locallist:
1259            (rc, self.plist) = semanage_port_list_local(self.sh)
1260        else:
1261            (rc, self.plist) = semanage_port_list(self.sh)
1262        if rc < 0:
1263            raise ValueError(_("Could not list ports"))
1264
1265        for port in self.plist:
1266            con = semanage_port_get_con(port)
1267            ctype = semanage_context_get_type(con)
1268            level = semanage_context_get_mls(con)
1269            proto = semanage_port_get_proto(port)
1270            proto_str = semanage_port_get_proto_str(proto)
1271            low = semanage_port_get_low(port)
1272            high = semanage_port_get_high(port)
1273            ddict[(low, high, proto_str)] = (ctype, level)
1274        return ddict
1275
1276    def get_all_by_type(self, locallist=0):
1277        ddict = {}
1278        if locallist:
1279            (rc, self.plist) = semanage_port_list_local(self.sh)
1280        else:
1281            (rc, self.plist) = semanage_port_list(self.sh)
1282        if rc < 0:
1283            raise ValueError(_("Could not list ports"))
1284
1285        for port in self.plist:
1286            con = semanage_port_get_con(port)
1287            ctype = semanage_context_get_type(con)
1288            proto = semanage_port_get_proto(port)
1289            proto_str = semanage_port_get_proto_str(proto)
1290            low = semanage_port_get_low(port)
1291            high = semanage_port_get_high(port)
1292            if (ctype, proto_str) not in ddict.keys():
1293                ddict[(ctype, proto_str)] = []
1294            if low == high:
1295                ddict[(ctype, proto_str)].append("%d" % low)
1296            else:
1297                ddict[(ctype, proto_str)].append("%d-%d" % (low, high))
1298        return ddict
1299
1300    def customized(self):
1301        l = []
1302        ddict = self.get_all(True)
1303        for k in sorted(ddict.keys()):
1304            port = k[0] if k[0] == k[1] else "%s-%s" % (k[0], k[1])
1305            if ddict[k][1]:
1306                l.append("-a -t %s -r '%s' -p %s %s" % (ddict[k][0], ddict[k][1], k[2], port))
1307            else:
1308                l.append("-a -t %s -p %s %s" % (ddict[k][0], k[2], port))
1309        return l
1310
1311    def list(self, heading=1, locallist=0):
1312        ddict = self.get_all_by_type(locallist)
1313        if len(ddict) == 0:
1314            return
1315        keys = sorted(ddict.keys())
1316
1317        if heading:
1318            print("%-30s %-8s %s\n" % (_("SELinux Port Type"), _("Proto"), _("Port Number")))
1319        for i in keys:
1320            rec = "%-30s %-8s " % i
1321            rec += "%s" % ddict[i][0]
1322            for p in ddict[i][1:]:
1323                rec += ", %s" % p
1324            print(rec)
1325
1326class ibpkeyRecords(semanageRecords):
1327
1328    valid_types = []
1329
1330    def __init__(self, args = None):
1331        semanageRecords.__init__(self, args)
1332        try:
1333            q = setools.TypeQuery(setools.SELinuxPolicy(sepolicy.get_store_policy(self.store)), attrs=["ibpkey_type"])
1334            self.valid_types = sorted(str(t) for t in q.results())
1335        except:
1336            pass
1337
1338    def __genkey(self, pkey, subnet_prefix):
1339        if subnet_prefix == "":
1340            raise ValueError(_("Subnet Prefix is required"))
1341
1342        pkeys = pkey.split("-")
1343        if len(pkeys) == 1:
1344            high = low = int(pkeys[0], 0)
1345        else:
1346            low = int(pkeys[0], 0)
1347            high = int(pkeys[1], 0)
1348
1349        if high > 65535:
1350            raise ValueError(_("Invalid Pkey"))
1351
1352        (rc, k) = semanage_ibpkey_key_create(self.sh, subnet_prefix, low, high)
1353        if rc < 0:
1354            raise ValueError(_("Could not create a key for %s/%s") % (subnet_prefix, pkey))
1355        return (k, subnet_prefix, low, high)
1356
1357    def __add(self, pkey, subnet_prefix, serange, type):
1358        if is_mls_enabled == 1:
1359            if serange == "":
1360                serange = "s0"
1361            else:
1362                serange = untranslate(serange)
1363
1364        if type == "":
1365            raise ValueError(_("Type is required"))
1366
1367        type = sepolicy.get_real_type_name(type)
1368
1369        if type not in self.valid_types:
1370            raise ValueError(_("Type %s is invalid, must be a ibpkey type") % type)
1371
1372        (k, subnet_prefix, low, high) = self.__genkey(pkey, subnet_prefix)
1373
1374        (rc, exists) = semanage_ibpkey_exists(self.sh, k)
1375        if rc < 0:
1376            raise ValueError(_("Could not check if ibpkey %s/%s is defined") % (subnet_prefix, pkey))
1377        if exists:
1378            raise ValueError(_("ibpkey %s/%s already defined") % (subnet_prefix, pkey))
1379
1380        (rc, p) = semanage_ibpkey_create(self.sh)
1381        if rc < 0:
1382            raise ValueError(_("Could not create ibpkey for %s/%s") % (subnet_prefix, pkey))
1383
1384        semanage_ibpkey_set_subnet_prefix(self.sh, p, subnet_prefix)
1385        semanage_ibpkey_set_range(p, low, high)
1386        (rc, con) = semanage_context_create(self.sh)
1387        if rc < 0:
1388            raise ValueError(_("Could not create context for %s/%s") % (subnet_prefix, pkey))
1389
1390        rc = semanage_context_set_user(self.sh, con, "system_u")
1391        if rc < 0:
1392            raise ValueError(_("Could not set user in ibpkey context for %s/%s") % (subnet_prefix, pkey))
1393
1394        rc = semanage_context_set_role(self.sh, con, "object_r")
1395        if rc < 0:
1396            raise ValueError(_("Could not set role in ibpkey context for %s/%s") % (subnet_prefix, pkey))
1397
1398        rc = semanage_context_set_type(self.sh, con, type)
1399        if rc < 0:
1400            raise ValueError(_("Could not set type in ibpkey context for %s/%s") % (subnet_prefix, pkey))
1401
1402        if (is_mls_enabled == 1) and (serange != ""):
1403            rc = semanage_context_set_mls(self.sh, con, serange)
1404            if rc < 0:
1405                raise ValueError(_("Could not set mls fields in ibpkey context for %s/%s") % (subnet_prefix, pkey))
1406
1407        rc = semanage_ibpkey_set_con(self.sh, p, con)
1408        if rc < 0:
1409            raise ValueError(_("Could not set ibpkey context for %s/%s") % (subnet_prefix, pkey))
1410
1411        rc = semanage_ibpkey_modify_local(self.sh, k, p)
1412        if rc < 0:
1413            raise ValueError(_("Could not add ibpkey %s/%s") % (subnet_prefix, pkey))
1414
1415        semanage_context_free(con)
1416        semanage_ibpkey_key_free(k)
1417        semanage_ibpkey_free(p)
1418
1419    def add(self, pkey, subnet_prefix, serange, type):
1420        self.begin()
1421        self.__add(pkey, subnet_prefix, serange, type)
1422        self.commit()
1423
1424    def __modify(self, pkey, subnet_prefix, serange, setype):
1425        if serange == "" and setype == "":
1426            if is_mls_enabled == 1:
1427                raise ValueError(_("Requires setype or serange"))
1428            else:
1429                raise ValueError(_("Requires setype"))
1430
1431        setype = sepolicy.get_real_type_name(setype)
1432
1433        if setype and setype not in self.valid_types:
1434            raise ValueError(_("Type %s is invalid, must be a ibpkey type") % setype)
1435
1436        (k, subnet_prefix, low, high) = self.__genkey(pkey, subnet_prefix)
1437
1438        (rc, exists) = semanage_ibpkey_exists(self.sh, k)
1439        if rc < 0:
1440            raise ValueError(_("Could not check if ibpkey %s/%s is defined") % (subnet_prefix, pkey))
1441        if not exists:
1442            raise ValueError(_("ibpkey %s/%s is not defined") % (subnet_prefix, pkey))
1443
1444        (rc, p) = semanage_ibpkey_query(self.sh, k)
1445        if rc < 0:
1446            raise ValueError(_("Could not query ibpkey %s/%s") % (subnet_prefix, pkey))
1447
1448        con = semanage_ibpkey_get_con(p)
1449
1450        if (is_mls_enabled == 1) and (serange != ""):
1451            semanage_context_set_mls(self.sh, con, untranslate(serange))
1452        if setype != "":
1453            semanage_context_set_type(self.sh, con, setype)
1454
1455        rc = semanage_ibpkey_modify_local(self.sh, k, p)
1456        if rc < 0:
1457            raise ValueError(_("Could not modify ibpkey %s/%s") % (subnet_prefix, pkey))
1458
1459        semanage_ibpkey_key_free(k)
1460        semanage_ibpkey_free(p)
1461
1462    def modify(self, pkey, subnet_prefix, serange, setype):
1463        self.begin()
1464        self.__modify(pkey, subnet_prefix, serange, setype)
1465        self.commit()
1466
1467    def deleteall(self):
1468        (rc, plist) = semanage_ibpkey_list_local(self.sh)
1469        if rc < 0:
1470            raise ValueError(_("Could not list the ibpkeys"))
1471
1472        self.begin()
1473
1474        for ibpkey in plist:
1475            (rc, subnet_prefix) = semanage_ibpkey_get_subnet_prefix(self.sh, ibpkey)
1476            low = semanage_ibpkey_get_low(ibpkey)
1477            high = semanage_ibpkey_get_high(ibpkey)
1478            pkey_str = "%s-%s" % (low, high)
1479            (k, subnet_prefix, low, high) = self.__genkey(pkey_str, subnet_prefix)
1480            if rc < 0:
1481                raise ValueError(_("Could not create a key for %s") % pkey_str)
1482
1483            rc = semanage_ibpkey_del_local(self.sh, k)
1484            if rc < 0:
1485                raise ValueError(_("Could not delete the ibpkey %s") % pkey_str)
1486            semanage_ibpkey_key_free(k)
1487
1488        self.commit()
1489
1490    def __delete(self, pkey, subnet_prefix):
1491        (k, subnet_prefix, low, high) = self.__genkey(pkey, subnet_prefix)
1492        (rc, exists) = semanage_ibpkey_exists(self.sh, k)
1493        if rc < 0:
1494            raise ValueError(_("Could not check if ibpkey %s/%s is defined") % (subnet_prefix, pkey))
1495        if not exists:
1496            raise ValueError(_("ibpkey %s/%s is not defined") % (subnet_prefix, pkey))
1497
1498        (rc, exists) = semanage_ibpkey_exists_local(self.sh, k)
1499        if rc < 0:
1500            raise ValueError(_("Could not check if ibpkey %s/%s is defined") % (subnet_prefix, pkey))
1501        if not exists:
1502            raise ValueError(_("ibpkey %s/%s is defined in policy, cannot be deleted") % (subnet_prefix, pkey))
1503
1504        rc = semanage_ibpkey_del_local(self.sh, k)
1505        if rc < 0:
1506            raise ValueError(_("Could not delete ibpkey %s/%s") % (subnet_prefix, pkey))
1507
1508        semanage_ibpkey_key_free(k)
1509
1510    def delete(self, pkey, subnet_prefix):
1511        self.begin()
1512        self.__delete(pkey, subnet_prefix)
1513        self.commit()
1514
1515    def get_all(self, locallist=0):
1516        ddict = {}
1517        if locallist:
1518            (rc, self.plist) = semanage_ibpkey_list_local(self.sh)
1519        else:
1520            (rc, self.plist) = semanage_ibpkey_list(self.sh)
1521        if rc < 0:
1522            raise ValueError(_("Could not list ibpkeys"))
1523
1524        for ibpkey in self.plist:
1525            con = semanage_ibpkey_get_con(ibpkey)
1526            ctype = semanage_context_get_type(con)
1527            if ctype == "reserved_ibpkey_t":
1528                continue
1529            level = semanage_context_get_mls(con)
1530            (rc, subnet_prefix) = semanage_ibpkey_get_subnet_prefix(self.sh, ibpkey)
1531            low = semanage_ibpkey_get_low(ibpkey)
1532            high = semanage_ibpkey_get_high(ibpkey)
1533            ddict[(low, high, subnet_prefix)] = (ctype, level)
1534        return ddict
1535
1536    def get_all_by_type(self, locallist=0):
1537        ddict = {}
1538        if locallist:
1539            (rc, self.plist) = semanage_ibpkey_list_local(self.sh)
1540        else:
1541            (rc, self.plist) = semanage_ibpkey_list(self.sh)
1542        if rc < 0:
1543            raise ValueError(_("Could not list ibpkeys"))
1544
1545        for ibpkey in self.plist:
1546            con = semanage_ibpkey_get_con(ibpkey)
1547            ctype = semanage_context_get_type(con)
1548            (rc, subnet_prefix) = semanage_ibpkey_get_subnet_prefix(self.sh, ibpkey)
1549            low = semanage_ibpkey_get_low(ibpkey)
1550            high = semanage_ibpkey_get_high(ibpkey)
1551            if (ctype, subnet_prefix) not in ddict.keys():
1552                ddict[(ctype, subnet_prefix)] = []
1553            if low == high:
1554                ddict[(ctype, subnet_prefix)].append("0x%x" % low)
1555            else:
1556                ddict[(ctype, subnet_prefix)].append("0x%x-0x%x" % (low, high))
1557        return ddict
1558
1559    def customized(self):
1560        l = []
1561        ddict = self.get_all(True)
1562
1563        for k in sorted(ddict.keys()):
1564            port = k[0] if k[0] == k[1] else "%s-%s" % (k[0], k[1])
1565            if ddict[k][1]:
1566                l.append("-a -t %s -r '%s' -x %s %s" % (ddict[k][0], ddict[k][1], k[2], port))
1567            else:
1568                l.append("-a -t %s -x %s %s" % (ddict[k][0], k[2], port))
1569        return l
1570
1571    def list(self, heading=1, locallist=0):
1572        ddict = self.get_all_by_type(locallist)
1573        keys = ddict.keys()
1574        if len(keys) == 0:
1575            return
1576
1577        if heading:
1578            print("%-30s %-18s %s\n" % (_("SELinux IB Pkey Type"), _("Subnet_Prefix"), _("Pkey Number")))
1579        for i in sorted(keys):
1580            rec = "%-30s %-18s " % i
1581            rec += "%s" % ddict[i][0]
1582            for p in ddict[i][1:]:
1583                rec += ", %s" % p
1584            print(rec)
1585
1586class ibendportRecords(semanageRecords):
1587
1588    valid_types = []
1589
1590    def __init__(self, args = None):
1591        semanageRecords.__init__(self, args)
1592        try:
1593            q = setools.TypeQuery(setools.SELinuxPolicy(sepolicy.get_store_policy(self.store)), attrs=["ibendport_type"])
1594            self.valid_types = set(str(t) for t in q.results())
1595        except:
1596            pass
1597
1598    def __genkey(self, ibendport, ibdev_name):
1599        if ibdev_name == "":
1600            raise ValueError(_("IB device name is required"))
1601
1602        port = int(ibendport)
1603
1604        if port > 255 or port < 1:
1605            raise ValueError(_("Invalid Port Number"))
1606
1607        (rc, k) = semanage_ibendport_key_create(self.sh, ibdev_name, port)
1608        if rc < 0:
1609            raise ValueError(_("Could not create a key for ibendport %s/%s") % (ibdev_name, ibendport))
1610        return (k, ibdev_name, port)
1611
1612    def __add(self, ibendport, ibdev_name, serange, type):
1613        if is_mls_enabled == 1:
1614            if serange == "":
1615                serange = "s0"
1616            else:
1617                serange = untranslate(serange)
1618
1619        if type == "":
1620            raise ValueError(_("Type is required"))
1621
1622        type = sepolicy.get_real_type_name(type)
1623
1624        if type not in self.valid_types:
1625            raise ValueError(_("Type %s is invalid, must be an ibendport type") % type)
1626        (k, ibendport, port) = self.__genkey(ibendport, ibdev_name)
1627
1628        (rc, exists) = semanage_ibendport_exists(self.sh, k)
1629        if rc < 0:
1630            raise ValueError(_("Could not check if ibendport %s/%s is defined") % (ibdev_name, port))
1631        if exists:
1632            raise ValueError(_("ibendport %s/%s already defined") % (ibdev_name, port))
1633
1634        (rc, p) = semanage_ibendport_create(self.sh)
1635        if rc < 0:
1636            raise ValueError(_("Could not create ibendport for %s/%s") % (ibdev_name, port))
1637
1638        semanage_ibendport_set_ibdev_name(self.sh, p, ibdev_name)
1639        semanage_ibendport_set_port(p, port)
1640        (rc, con) = semanage_context_create(self.sh)
1641        if rc < 0:
1642            raise ValueError(_("Could not create context for %s/%s") % (ibdev_name, port))
1643
1644        rc = semanage_context_set_user(self.sh, con, "system_u")
1645        if rc < 0:
1646            raise ValueError(_("Could not set user in ibendport context for %s/%s") % (ibdev_name, port))
1647
1648        rc = semanage_context_set_role(self.sh, con, "object_r")
1649        if rc < 0:
1650            raise ValueError(_("Could not set role in ibendport context for %s/%s") % (ibdev_name, port))
1651
1652        rc = semanage_context_set_type(self.sh, con, type)
1653        if rc < 0:
1654            raise ValueError(_("Could not set type in ibendport context for %s/%s") % (ibdev_name, port))
1655
1656        if (is_mls_enabled == 1) and (serange != ""):
1657            rc = semanage_context_set_mls(self.sh, con, serange)
1658            if rc < 0:
1659                raise ValueError(_("Could not set mls fields in ibendport context for %s/%s") % (ibdev_name, port))
1660
1661        rc = semanage_ibendport_set_con(self.sh, p, con)
1662        if rc < 0:
1663            raise ValueError(_("Could not set ibendport context for %s/%s") % (ibdev_name, port))
1664
1665        rc = semanage_ibendport_modify_local(self.sh, k, p)
1666        if rc < 0:
1667            raise ValueError(_("Could not add ibendport %s/%s") % (ibdev_name, port))
1668
1669        semanage_context_free(con)
1670        semanage_ibendport_key_free(k)
1671        semanage_ibendport_free(p)
1672
1673    def add(self, ibendport, ibdev_name, serange, type):
1674        self.begin()
1675        self.__add(ibendport, ibdev_name, serange, type)
1676        self.commit()
1677
1678    def __modify(self, ibendport, ibdev_name, serange, setype):
1679        if serange == "" and setype == "":
1680            if is_mls_enabled == 1:
1681                raise ValueError(_("Requires setype or serange"))
1682            else:
1683                raise ValueError(_("Requires setype"))
1684
1685        setype = sepolicy.get_real_type_name(setype)
1686
1687        if setype and setype not in self.valid_types:
1688            raise ValueError(_("Type %s is invalid, must be an ibendport type") % setype)
1689
1690        (k, ibdev_name, port) = self.__genkey(ibendport, ibdev_name)
1691
1692        (rc, exists) = semanage_ibendport_exists(self.sh, k)
1693        if rc < 0:
1694            raise ValueError(_("Could not check if ibendport %s/%s is defined") % (ibdev_name, ibendport))
1695        if not exists:
1696            raise ValueError(_("ibendport %s/%s is not defined") % (ibdev_name, ibendport))
1697
1698        (rc, p) = semanage_ibendport_query(self.sh, k)
1699        if rc < 0:
1700            raise ValueError(_("Could not query ibendport %s/%s") % (ibdev_name, ibendport))
1701
1702        con = semanage_ibendport_get_con(p)
1703
1704        if (is_mls_enabled == 1) and (serange != ""):
1705            semanage_context_set_mls(self.sh, con, untranslate(serange))
1706        if setype != "":
1707            semanage_context_set_type(self.sh, con, setype)
1708
1709        rc = semanage_ibendport_modify_local(self.sh, k, p)
1710        if rc < 0:
1711            raise ValueError(_("Could not modify ibendport %s/%s") % (ibdev_name, ibendport))
1712
1713        semanage_ibendport_key_free(k)
1714        semanage_ibendport_free(p)
1715
1716    def modify(self, ibendport, ibdev_name, serange, setype):
1717        self.begin()
1718        self.__modify(ibendport, ibdev_name, serange, setype)
1719        self.commit()
1720
1721    def deleteall(self):
1722        (rc, plist) = semanage_ibendport_list_local(self.sh)
1723        if rc < 0:
1724            raise ValueError(_("Could not list the ibendports"))
1725
1726        self.begin()
1727
1728        for ibendport in plist:
1729            (rc, ibdev_name) = semanage_ibendport_get_ibdev_name(self.sh, ibendport)
1730            port = semanage_ibendport_get_port(ibendport)
1731            (k, ibdev_name, port) = self.__genkey(str(port), ibdev_name)
1732            if rc < 0:
1733                raise ValueError(_("Could not create a key for %s/%d") % (ibdevname, port))
1734
1735            rc = semanage_ibendport_del_local(self.sh, k)
1736            if rc < 0:
1737                raise ValueError(_("Could not delete the ibendport %s/%d") % (ibdev_name, port))
1738            semanage_ibendport_key_free(k)
1739
1740        self.commit()
1741
1742    def __delete(self, ibendport, ibdev_name):
1743        (k, ibdev_name, port) = self.__genkey(ibendport, ibdev_name)
1744        (rc, exists) = semanage_ibendport_exists(self.sh, k)
1745        if rc < 0:
1746            raise ValueError(_("Could not check if ibendport %s/%s is defined") % (ibdev_name, ibendport))
1747        if not exists:
1748            raise ValueError(_("ibendport %s/%s is not defined") % (ibdev_name, ibendport))
1749
1750        (rc, exists) = semanage_ibendport_exists_local(self.sh, k)
1751        if rc < 0:
1752            raise ValueError(_("Could not check if ibendport %s/%s is defined") % (ibdev_name, ibendport))
1753        if not exists:
1754            raise ValueError(_("ibendport %s/%s is defined in policy, cannot be deleted") % (ibdev_name, ibendport))
1755
1756        rc = semanage_ibendport_del_local(self.sh, k)
1757        if rc < 0:
1758            raise ValueError(_("Could not delete ibendport %s/%s") % (ibdev_name, ibendport))
1759
1760        semanage_ibendport_key_free(k)
1761
1762    def delete(self, ibendport, ibdev_name):
1763        self.begin()
1764        self.__delete(ibendport, ibdev_name)
1765        self.commit()
1766
1767    def get_all(self, locallist=0):
1768        ddict = {}
1769        if locallist:
1770            (rc, self.plist) = semanage_ibendport_list_local(self.sh)
1771        else:
1772            (rc, self.plist) = semanage_ibendport_list(self.sh)
1773        if rc < 0:
1774            raise ValueError(_("Could not list ibendports"))
1775
1776        for ibendport in self.plist:
1777            con = semanage_ibendport_get_con(ibendport)
1778            ctype = semanage_context_get_type(con)
1779            if ctype == "reserved_ibendport_t":
1780                continue
1781            level = semanage_context_get_mls(con)
1782            (rc, ibdev_name) = semanage_ibendport_get_ibdev_name(self.sh, ibendport)
1783            port = semanage_ibendport_get_port(ibendport)
1784            ddict[(port, ibdev_name)] = (ctype, level)
1785        return ddict
1786
1787    def get_all_by_type(self, locallist=0):
1788        ddict = {}
1789        if locallist:
1790            (rc, self.plist) = semanage_ibendport_list_local(self.sh)
1791        else:
1792            (rc, self.plist) = semanage_ibendport_list(self.sh)
1793        if rc < 0:
1794            raise ValueError(_("Could not list ibendports"))
1795
1796        for ibendport in self.plist:
1797            con = semanage_ibendport_get_con(ibendport)
1798            ctype = semanage_context_get_type(con)
1799            (rc, ibdev_name) = semanage_ibendport_get_ibdev_name(self.sh, ibendport)
1800            port = semanage_ibendport_get_port(ibendport)
1801            if (ctype, ibdev_name) not in ddict.keys():
1802                ddict[(ctype, ibdev_name)] = []
1803            ddict[(ctype, ibdev_name)].append("0x%x" % port)
1804        return ddict
1805
1806    def customized(self):
1807        l = []
1808        ddict = self.get_all(True)
1809
1810        for k in sorted(ddict.keys()):
1811            if ddict[k][1]:
1812                l.append("-a -t %s -r '%s' -z %s %s" % (ddict[k][0], ddict[k][1], k[1], k[0]))
1813            else:
1814                l.append("-a -t %s -z %s %s" % (ddict[k][0], k[1], k[0]))
1815        return l
1816
1817    def list(self, heading=1, locallist=0):
1818        ddict = self.get_all_by_type(locallist)
1819        keys = ddict.keys()
1820        if len(keys) == 0:
1821            return
1822
1823        if heading:
1824            print("%-30s %-18s %s\n" % (_("SELinux IB End Port Type"), _("IB Device Name"), _("Port Number")))
1825        for i in sorted(keys):
1826            rec = "%-30s %-18s " % i
1827            rec += "%s" % ddict[i][0]
1828            for p in ddict[i][1:]:
1829                rec += ", %s" % p
1830            print(rec)
1831
1832class nodeRecords(semanageRecords):
1833
1834    valid_types = []
1835
1836    def __init__(self, args = None):
1837        semanageRecords.__init__(self, args)
1838        self.protocol = ["ipv4", "ipv6"]
1839        try:
1840            self.valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "node_type"))[0]["types"])
1841        except RuntimeError:
1842            pass
1843
1844    def validate(self, addr, mask, protocol):
1845        newaddr = addr
1846        newmask = mask
1847        newprotocol = ""
1848
1849        if addr == "":
1850            raise ValueError(_("Node Address is required"))
1851
1852        # verify valid comination
1853        if len(mask) == 0 or mask[0] == "/":
1854            i = IP(addr + mask)
1855            newaddr = i.strNormal(0)
1856            newmask = str(i.netmask())
1857            if newmask == "0.0.0.0" and i.version() == 6:
1858                newmask = "::"
1859
1860            protocol = "ipv%d" % i.version()
1861
1862        try:
1863            newprotocol = self.protocol.index(protocol)
1864        except:
1865            raise ValueError(_("Unknown or missing protocol"))
1866
1867        return newaddr, newmask, newprotocol
1868
1869    def __add(self, addr, mask, proto, serange, ctype):
1870        addr, mask, proto = self.validate(addr, mask, proto)
1871
1872        if is_mls_enabled == 1:
1873            if serange == "":
1874                serange = "s0"
1875            else:
1876                serange = untranslate(serange)
1877
1878        if ctype == "":
1879            raise ValueError(_("SELinux node type is required"))
1880
1881        ctype = sepolicy.get_real_type_name(ctype)
1882
1883        if ctype not in self.valid_types:
1884            raise ValueError(_("Type %s is invalid, must be a node type") % ctype)
1885
1886        (rc, k) = semanage_node_key_create(self.sh, addr, mask, proto)
1887        if rc < 0:
1888            raise ValueError(_("Could not create key for %s") % addr)
1889        if rc < 0:
1890            raise ValueError(_("Could not check if addr %s is defined") % addr)
1891
1892        (rc, exists) = semanage_node_exists(self.sh, k)
1893        if exists:
1894            raise ValueError(_("Addr %s already defined") % addr)
1895
1896        (rc, node) = semanage_node_create(self.sh)
1897        if rc < 0:
1898            raise ValueError(_("Could not create addr for %s") % addr)
1899        semanage_node_set_proto(node, proto)
1900
1901        rc = semanage_node_set_addr(self.sh, node, proto, addr)
1902        (rc, con) = semanage_context_create(self.sh)
1903        if rc < 0:
1904            raise ValueError(_("Could not create context for %s") % addr)
1905
1906        rc = semanage_node_set_mask(self.sh, node, proto, mask)
1907        if rc < 0:
1908            raise ValueError(_("Could not set mask for %s") % addr)
1909
1910        rc = semanage_context_set_user(self.sh, con, "system_u")
1911        if rc < 0:
1912            raise ValueError(_("Could not set user in addr context for %s") % addr)
1913
1914        rc = semanage_context_set_role(self.sh, con, "object_r")
1915        if rc < 0:
1916            raise ValueError(_("Could not set role in addr context for %s") % addr)
1917
1918        rc = semanage_context_set_type(self.sh, con, ctype)
1919        if rc < 0:
1920            raise ValueError(_("Could not set type in addr context for %s") % addr)
1921
1922        if (is_mls_enabled == 1) and (serange != ""):
1923            rc = semanage_context_set_mls(self.sh, con, serange)
1924            if rc < 0:
1925                raise ValueError(_("Could not set mls fields in addr context for %s") % addr)
1926
1927        rc = semanage_node_set_con(self.sh, node, con)
1928        if rc < 0:
1929            raise ValueError(_("Could not set addr context for %s") % addr)
1930
1931        rc = semanage_node_modify_local(self.sh, k, node)
1932        if rc < 0:
1933            raise ValueError(_("Could not add addr %s") % addr)
1934
1935        semanage_context_free(con)
1936        semanage_node_key_free(k)
1937        semanage_node_free(node)
1938
1939        self.mylog.log_change("resrc=node op=add laddr=%s netmask=%s proto=%s tcontext=%s:%s:%s:%s" % (addr, mask, socket.getprotobyname(self.protocol[proto]), "system_u", "object_r", ctype, serange))
1940
1941    def add(self, addr, mask, proto, serange, ctype):
1942        self.begin()
1943        self.__add(addr, mask, proto, serange, ctype)
1944        self.commit()
1945
1946    def __modify(self, addr, mask, proto, serange, setype):
1947        addr, mask, proto = self.validate(addr, mask, proto)
1948
1949        if serange == "" and setype == "":
1950            raise ValueError(_("Requires setype or serange"))
1951
1952        setype = sepolicy.get_real_type_name(setype)
1953
1954        if setype and setype not in self.valid_types:
1955            raise ValueError(_("Type %s is invalid, must be a node type") % setype)
1956
1957        (rc, k) = semanage_node_key_create(self.sh, addr, mask, proto)
1958        if rc < 0:
1959            raise ValueError(_("Could not create key for %s") % addr)
1960
1961        (rc, exists) = semanage_node_exists(self.sh, k)
1962        if rc < 0:
1963            raise ValueError(_("Could not check if addr %s is defined") % addr)
1964        if not exists:
1965            raise ValueError(_("Addr %s is not defined") % addr)
1966
1967        (rc, node) = semanage_node_query(self.sh, k)
1968        if rc < 0:
1969            raise ValueError(_("Could not query addr %s") % addr)
1970
1971        con = semanage_node_get_con(node)
1972        if (is_mls_enabled == 1) and (serange != ""):
1973            semanage_context_set_mls(self.sh, con, untranslate(serange))
1974        if setype != "":
1975            semanage_context_set_type(self.sh, con, setype)
1976
1977        rc = semanage_node_modify_local(self.sh, k, node)
1978        if rc < 0:
1979            raise ValueError(_("Could not modify addr %s") % addr)
1980
1981        semanage_node_key_free(k)
1982        semanage_node_free(node)
1983
1984        self.mylog.log_change("resrc=node op=modify laddr=%s netmask=%s proto=%s tcontext=%s:%s:%s:%s" % (addr, mask, socket.getprotobyname(self.protocol[proto]), "system_u", "object_r", setype, serange))
1985
1986    def modify(self, addr, mask, proto, serange, setype):
1987        self.begin()
1988        self.__modify(addr, mask, proto, serange, setype)
1989        self.commit()
1990
1991    def __delete(self, addr, mask, proto):
1992
1993        addr, mask, proto = self.validate(addr, mask, proto)
1994
1995        (rc, k) = semanage_node_key_create(self.sh, addr, mask, proto)
1996        if rc < 0:
1997            raise ValueError(_("Could not create key for %s") % addr)
1998
1999        (rc, exists) = semanage_node_exists(self.sh, k)
2000        if rc < 0:
2001            raise ValueError(_("Could not check if addr %s is defined") % addr)
2002        if not exists:
2003            raise ValueError(_("Addr %s is not defined") % addr)
2004
2005        (rc, exists) = semanage_node_exists_local(self.sh, k)
2006        if rc < 0:
2007            raise ValueError(_("Could not check if addr %s is defined") % addr)
2008        if not exists:
2009            raise ValueError(_("Addr %s is defined in policy, cannot be deleted") % addr)
2010
2011        rc = semanage_node_del_local(self.sh, k)
2012        if rc < 0:
2013            raise ValueError(_("Could not delete addr %s") % addr)
2014
2015        semanage_node_key_free(k)
2016
2017        self.mylog.log_change("resrc=node op=delete laddr=%s netmask=%s proto=%s" % (addr, mask, socket.getprotobyname(self.protocol[proto])))
2018
2019    def delete(self, addr, mask, proto):
2020        self.begin()
2021        self.__delete(addr, mask, proto)
2022        self.commit()
2023
2024    def deleteall(self):
2025        (rc, nlist) = semanage_node_list_local(self.sh)
2026        if rc < 0:
2027            raise ValueError(_("Could not deleteall node mappings"))
2028
2029        self.begin()
2030        for node in nlist:
2031            self.__delete(semanage_node_get_addr(self.sh, node)[1], semanage_node_get_mask(self.sh, node)[1], self.protocol[semanage_node_get_proto(node)])
2032        self.commit()
2033
2034    def get_all(self, locallist=0):
2035        ddict = {}
2036        if locallist:
2037            (rc, self.ilist) = semanage_node_list_local(self.sh)
2038        else:
2039            (rc, self.ilist) = semanage_node_list(self.sh)
2040        if rc < 0:
2041            raise ValueError(_("Could not list addrs"))
2042
2043        for node in self.ilist:
2044            con = semanage_node_get_con(node)
2045            addr = semanage_node_get_addr(self.sh, node)
2046            mask = semanage_node_get_mask(self.sh, node)
2047            proto = self.protocol[semanage_node_get_proto(node)]
2048            ddict[(addr[1], mask[1], proto)] = (semanage_context_get_user(con), semanage_context_get_role(con), semanage_context_get_type(con), semanage_context_get_mls(con))
2049
2050        return ddict
2051
2052    def customized(self):
2053        l = []
2054        ddict = self.get_all(True)
2055        for k in sorted(ddict.keys()):
2056            if ddict[k][3]:
2057                l.append("-a -M %s -p %s -t %s -r '%s' %s" % (k[1], k[2], ddict[k][2], ddict[k][3], k[0]))
2058            else:
2059                l.append("-a -M %s -p %s -t %s %s" % (k[1], k[2], ddict[k][2], k[0]))
2060        return l
2061
2062    def list(self, heading=1, locallist=0):
2063        ddict = self.get_all(locallist)
2064        if len(ddict) == 0:
2065            return
2066        keys = sorted(ddict.keys())
2067
2068        if heading:
2069            print("%-18s %-18s %-5s %-5s\n" % ("IP Address", "Netmask", "Protocol", "Context"))
2070        if is_mls_enabled:
2071            for k in keys:
2072                val = ''
2073                for fields in k:
2074                    val = val + '\t' + str(fields)
2075                print("%-18s %-18s %-5s %s:%s:%s:%s " % (k[0], k[1], k[2], ddict[k][0], ddict[k][1], ddict[k][2], translate(ddict[k][3], False)))
2076        else:
2077            for k in keys:
2078                print("%-18s %-18s %-5s %s:%s:%s " % (k[0], k[1], k[2], ddict[k][0], ddict[k][1], ddict[k][2]))
2079
2080
2081class interfaceRecords(semanageRecords):
2082
2083    def __init__(self, args = None):
2084        semanageRecords.__init__(self, args)
2085
2086    def __add(self, interface, serange, ctype):
2087        if is_mls_enabled == 1:
2088            if serange == "":
2089                serange = "s0"
2090            else:
2091                serange = untranslate(serange)
2092
2093        if ctype == "":
2094            raise ValueError(_("SELinux Type is required"))
2095
2096        (rc, k) = semanage_iface_key_create(self.sh, interface)
2097        if rc < 0:
2098            raise ValueError(_("Could not create key for %s") % interface)
2099
2100        (rc, exists) = semanage_iface_exists(self.sh, k)
2101        if rc < 0:
2102            raise ValueError(_("Could not check if interface %s is defined") % interface)
2103        if exists:
2104            raise ValueError(_("Interface %s already defined") % interface)
2105
2106        (rc, iface) = semanage_iface_create(self.sh)
2107        if rc < 0:
2108            raise ValueError(_("Could not create interface for %s") % interface)
2109
2110        rc = semanage_iface_set_name(self.sh, iface, interface)
2111        (rc, con) = semanage_context_create(self.sh)
2112        if rc < 0:
2113            raise ValueError(_("Could not create context for %s") % interface)
2114
2115        rc = semanage_context_set_user(self.sh, con, "system_u")
2116        if rc < 0:
2117            raise ValueError(_("Could not set user in interface context for %s") % interface)
2118
2119        rc = semanage_context_set_role(self.sh, con, "object_r")
2120        if rc < 0:
2121            raise ValueError(_("Could not set role in interface context for %s") % interface)
2122
2123        rc = semanage_context_set_type(self.sh, con, ctype)
2124        if rc < 0:
2125            raise ValueError(_("Could not set type in interface context for %s") % interface)
2126
2127        if (is_mls_enabled == 1) and (serange != ""):
2128            rc = semanage_context_set_mls(self.sh, con, serange)
2129            if rc < 0:
2130                raise ValueError(_("Could not set mls fields in interface context for %s") % interface)
2131
2132        rc = semanage_iface_set_ifcon(self.sh, iface, con)
2133        if rc < 0:
2134            raise ValueError(_("Could not set interface context for %s") % interface)
2135
2136        rc = semanage_iface_set_msgcon(self.sh, iface, con)
2137        if rc < 0:
2138            raise ValueError(_("Could not set message context for %s") % interface)
2139
2140        rc = semanage_iface_modify_local(self.sh, k, iface)
2141        if rc < 0:
2142            raise ValueError(_("Could not add interface %s") % interface)
2143
2144        semanage_context_free(con)
2145        semanage_iface_key_free(k)
2146        semanage_iface_free(iface)
2147
2148        self.mylog.log_change("resrc=interface op=add netif=%s tcontext=%s:%s:%s:%s" % (interface, "system_u", "object_r", ctype, serange))
2149
2150    def add(self, interface, serange, ctype):
2151        self.begin()
2152        self.__add(interface, serange, ctype)
2153        self.commit()
2154
2155    def __modify(self, interface, serange, setype):
2156        if serange == "" and setype == "":
2157            raise ValueError(_("Requires setype or serange"))
2158
2159        (rc, k) = semanage_iface_key_create(self.sh, interface)
2160        if rc < 0:
2161            raise ValueError(_("Could not create key for %s") % interface)
2162
2163        (rc, exists) = semanage_iface_exists(self.sh, k)
2164        if rc < 0:
2165            raise ValueError(_("Could not check if interface %s is defined") % interface)
2166        if not exists:
2167            raise ValueError(_("Interface %s is not defined") % interface)
2168
2169        (rc, iface) = semanage_iface_query(self.sh, k)
2170        if rc < 0:
2171            raise ValueError(_("Could not query interface %s") % interface)
2172
2173        con = semanage_iface_get_ifcon(iface)
2174
2175        if (is_mls_enabled == 1) and (serange != ""):
2176            semanage_context_set_mls(self.sh, con, untranslate(serange))
2177        if setype != "":
2178            semanage_context_set_type(self.sh, con, setype)
2179
2180        rc = semanage_iface_modify_local(self.sh, k, iface)
2181        if rc < 0:
2182            raise ValueError(_("Could not modify interface %s") % interface)
2183
2184        semanage_iface_key_free(k)
2185        semanage_iface_free(iface)
2186
2187        self.mylog.log_change("resrc=interface op=modify netif=%s tcontext=%s:%s:%s:%s" % (interface, "system_u", "object_r", setype, serange))
2188
2189    def modify(self, interface, serange, setype):
2190        self.begin()
2191        self.__modify(interface, serange, setype)
2192        self.commit()
2193
2194    def __delete(self, interface):
2195        (rc, k) = semanage_iface_key_create(self.sh, interface)
2196        if rc < 0:
2197            raise ValueError(_("Could not create key for %s") % interface)
2198
2199        (rc, exists) = semanage_iface_exists(self.sh, k)
2200        if rc < 0:
2201            raise ValueError(_("Could not check if interface %s is defined") % interface)
2202        if not exists:
2203            raise ValueError(_("Interface %s is not defined") % interface)
2204
2205        (rc, exists) = semanage_iface_exists_local(self.sh, k)
2206        if rc < 0:
2207            raise ValueError(_("Could not check if interface %s is defined") % interface)
2208        if not exists:
2209            raise ValueError(_("Interface %s is defined in policy, cannot be deleted") % interface)
2210
2211        rc = semanage_iface_del_local(self.sh, k)
2212        if rc < 0:
2213            raise ValueError(_("Could not delete interface %s") % interface)
2214
2215        semanage_iface_key_free(k)
2216
2217        self.mylog.log_change("resrc=interface op=delete netif=%s" % interface)
2218
2219    def delete(self, interface):
2220        self.begin()
2221        self.__delete(interface)
2222        self.commit()
2223
2224    def deleteall(self):
2225        (rc, ulist) = semanage_iface_list_local(self.sh)
2226        if rc < 0:
2227            raise ValueError(_("Could not delete all interface  mappings"))
2228
2229        self.begin()
2230        for i in ulist:
2231            self.__delete(semanage_iface_get_name(i))
2232        self.commit()
2233
2234    def get_all(self, locallist=0):
2235        ddict = {}
2236        if locallist:
2237            (rc, self.ilist) = semanage_iface_list_local(self.sh)
2238        else:
2239            (rc, self.ilist) = semanage_iface_list(self.sh)
2240        if rc < 0:
2241            raise ValueError(_("Could not list interfaces"))
2242
2243        for interface in self.ilist:
2244            con = semanage_iface_get_ifcon(interface)
2245            ddict[semanage_iface_get_name(interface)] = (semanage_context_get_user(con), semanage_context_get_role(con), semanage_context_get_type(con), semanage_context_get_mls(con))
2246
2247        return ddict
2248
2249    def customized(self):
2250        l = []
2251        ddict = self.get_all(True)
2252        for k in sorted(ddict.keys()):
2253            if ddict[k][3]:
2254                l.append("-a -t %s -r '%s' %s" % (ddict[k][2], ddict[k][3], k))
2255            else:
2256                l.append("-a -t %s %s" % (ddict[k][2], k))
2257        return l
2258
2259    def list(self, heading=1, locallist=0):
2260        ddict = self.get_all(locallist)
2261        if len(ddict) == 0:
2262            return
2263        keys = sorted(ddict.keys())
2264
2265        if heading:
2266            print("%-30s %s\n" % (_("SELinux Interface"), _("Context")))
2267        if is_mls_enabled:
2268            for k in keys:
2269                print("%-30s %s:%s:%s:%s " % (k, ddict[k][0], ddict[k][1], ddict[k][2], translate(ddict[k][3], False)))
2270        else:
2271            for k in keys:
2272                print("%-30s %s:%s:%s " % (k, ddict[k][0], ddict[k][1], ddict[k][2]))
2273
2274
2275class fcontextRecords(semanageRecords):
2276
2277    valid_types = []
2278
2279    def __init__(self, args = None):
2280        semanageRecords.__init__(self, args)
2281        try:
2282            self.valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "file_type"))[0]["types"])
2283            self.valid_types += list(list(sepolicy.info(sepolicy.ATTRIBUTE, "device_node"))[0]["types"])
2284        except RuntimeError:
2285            pass
2286
2287        self.equiv = {}
2288        self.equiv_dist = {}
2289        self.equal_ind = False
2290        try:
2291            fd = open(selinux.selinux_file_context_subs_path(), "r")
2292            for i in fd.readlines():
2293                i = i.strip()
2294                if len(i) == 0:
2295                    continue
2296                if i.startswith("#"):
2297                    continue
2298                target, substitute = i.split()
2299                self.equiv[target] = substitute
2300            fd.close()
2301        except IOError:
2302            pass
2303        try:
2304            fd = open(selinux.selinux_file_context_subs_dist_path(), "r")
2305            for i in fd.readlines():
2306                i = i.strip()
2307                if len(i) == 0:
2308                    continue
2309                if i.startswith("#"):
2310                    continue
2311                target, substitute = i.split()
2312                self.equiv_dist[target] = substitute
2313            fd.close()
2314        except IOError:
2315            pass
2316
2317    def commit(self):
2318        if self.equal_ind:
2319            subs_file = selinux.selinux_file_context_subs_path()
2320            tmpfile = "%s.tmp" % subs_file
2321            fd = open(tmpfile, "w")
2322            for target in self.equiv.keys():
2323                fd.write("%s %s\n" % (target, self.equiv[target]))
2324            fd.close()
2325            try:
2326                os.chmod(tmpfile, os.stat(subs_file)[stat.ST_MODE])
2327            except:
2328                pass
2329            os.rename(tmpfile, subs_file)
2330            self.equal_ind = False
2331        semanageRecords.commit(self)
2332
2333    def add_equal(self, target, substitute):
2334        self.begin()
2335        if target != "/" and target[-1] == "/":
2336            raise ValueError(_("Target %s is not valid. Target is not allowed to end with '/'") % target)
2337
2338        if substitute != "/" and substitute[-1] == "/":
2339            raise ValueError(_("Substitute %s is not valid. Substitute is not allowed to end with '/'") % substitute)
2340
2341        if target in self.equiv.keys():
2342            raise ValueError(_("Equivalence class for %s already exists") % target)
2343        self.validate(target)
2344
2345        for fdict in (self.equiv, self.equiv_dist):
2346            for i in fdict:
2347                if i.startswith(target + "/"):
2348                    raise ValueError(_("File spec %s conflicts with equivalency rule '%s %s'") % (target, i, fdict[i]))
2349
2350        self.mylog.log_change("resrc=fcontext op=add-equal %s %s" % (audit.audit_encode_nv_string("sglob", target, 0), audit.audit_encode_nv_string("tglob", substitute, 0)))
2351
2352        self.equiv[target] = substitute
2353        self.equal_ind = True
2354        self.commit()
2355
2356    def modify_equal(self, target, substitute):
2357        self.begin()
2358        if target not in self.equiv.keys():
2359            raise ValueError(_("Equivalence class for %s does not exist") % target)
2360        self.equiv[target] = substitute
2361        self.equal_ind = True
2362
2363        self.mylog.log_change("resrc=fcontext op=modify-equal %s %s" % (audit.audit_encode_nv_string("sglob", target, 0), audit.audit_encode_nv_string("tglob", substitute, 0)))
2364
2365        self.commit()
2366
2367    def createcon(self, target, seuser="system_u"):
2368        (rc, con) = semanage_context_create(self.sh)
2369        if rc < 0:
2370            raise ValueError(_("Could not create context for %s") % target)
2371        if seuser == "":
2372            seuser = "system_u"
2373
2374        rc = semanage_context_set_user(self.sh, con, seuser)
2375        if rc < 0:
2376            raise ValueError(_("Could not set user in file context for %s") % target)
2377
2378        rc = semanage_context_set_role(self.sh, con, "object_r")
2379        if rc < 0:
2380            raise ValueError(_("Could not set role in file context for %s") % target)
2381
2382        if is_mls_enabled == 1:
2383            rc = semanage_context_set_mls(self.sh, con, "s0")
2384            if rc < 0:
2385                raise ValueError(_("Could not set mls fields in file context for %s") % target)
2386
2387        return con
2388
2389    def validate(self, target):
2390        if target == "" or target.find("\n") >= 0:
2391            raise ValueError(_("Invalid file specification"))
2392        if target.find(" ") != -1:
2393            raise ValueError(_("File specification can not include spaces"))
2394        for fdict in (self.equiv, self.equiv_dist):
2395            for i in fdict:
2396                if target.startswith(i + "/"):
2397                    t = re.sub(i, fdict[i], target)
2398                    raise ValueError(_("File spec %s conflicts with equivalency rule '%s %s'; Try adding '%s' instead") % (target, i, fdict[i], t))
2399
2400    def __add(self, target, type, ftype="", serange="", seuser="system_u"):
2401        self.validate(target)
2402
2403        if is_mls_enabled == 1:
2404            serange = untranslate(serange)
2405
2406        if type == "":
2407            raise ValueError(_("SELinux Type is required"))
2408
2409        if type != "<<none>>":
2410            type = sepolicy.get_real_type_name(type)
2411            if type not in self.valid_types:
2412                raise ValueError(_("Type %s is invalid, must be a file or device type") % type)
2413
2414        (rc, k) = semanage_fcontext_key_create(self.sh, target, file_types[ftype])
2415        if rc < 0:
2416            raise ValueError(_("Could not create key for %s") % target)
2417
2418        (rc, exists) = semanage_fcontext_exists(self.sh, k)
2419        if rc < 0:
2420            raise ValueError(_("Could not check if file context for %s is defined") % target)
2421
2422        if not exists:
2423            (rc, exists) = semanage_fcontext_exists_local(self.sh, k)
2424            if rc < 0:
2425                raise ValueError(_("Could not check if file context for %s is defined") % target)
2426
2427        if exists:
2428            raise ValueError(_("File context for %s already defined") % target)
2429
2430        (rc, fcontext) = semanage_fcontext_create(self.sh)
2431        if rc < 0:
2432            raise ValueError(_("Could not create file context for %s") % target)
2433
2434        rc = semanage_fcontext_set_expr(self.sh, fcontext, target)
2435        if type != "<<none>>":
2436            con = self.createcon(target, seuser)
2437
2438            rc = semanage_context_set_type(self.sh, con, type)
2439            if rc < 0:
2440                raise ValueError(_("Could not set type in file context for %s") % target)
2441
2442            if (is_mls_enabled == 1) and (serange != ""):
2443                rc = semanage_context_set_mls(self.sh, con, serange)
2444                if rc < 0:
2445                    raise ValueError(_("Could not set mls fields in file context for %s") % target)
2446            rc = semanage_fcontext_set_con(self.sh, fcontext, con)
2447            if rc < 0:
2448                raise ValueError(_("Could not set file context for %s") % target)
2449
2450        semanage_fcontext_set_type(fcontext, file_types[ftype])
2451
2452        rc = semanage_fcontext_modify_local(self.sh, k, fcontext)
2453        if rc < 0:
2454            raise ValueError(_("Could not add file context for %s") % target)
2455
2456        if type != "<<none>>":
2457            semanage_context_free(con)
2458        semanage_fcontext_key_free(k)
2459        semanage_fcontext_free(fcontext)
2460
2461        if not seuser:
2462            seuser = "system_u"
2463
2464        self.mylog.log_change("resrc=fcontext op=add %s ftype=%s tcontext=%s:%s:%s:%s" % (audit.audit_encode_nv_string("tglob", target, 0), ftype_to_audit[ftype], seuser, "object_r", type, serange))
2465
2466    def add(self, target, type, ftype="", serange="", seuser="system_u"):
2467        self.begin()
2468        self.__add(target, type, ftype, serange, seuser)
2469        self.commit()
2470
2471    def __modify(self, target, setype, ftype, serange, seuser):
2472        if serange == "" and setype == "" and seuser == "":
2473            raise ValueError(_("Requires setype, serange or seuser"))
2474        if setype not in ["",  "<<none>>"]:
2475            setype = sepolicy.get_real_type_name(setype)
2476            if setype not in self.valid_types:
2477                raise ValueError(_("Type %s is invalid, must be a file or device type") % setype)
2478
2479        self.validate(target)
2480
2481        (rc, k) = semanage_fcontext_key_create(self.sh, target, file_types[ftype])
2482        if rc < 0:
2483            raise ValueError(_("Could not create a key for %s") % target)
2484
2485        (rc, exists) = semanage_fcontext_exists(self.sh, k)
2486        if rc < 0:
2487            raise ValueError(_("Could not check if file context for %s is defined") % target)
2488        if not exists:
2489            (rc, exists) = semanage_fcontext_exists_local(self.sh, k)
2490            if not exists:
2491                raise ValueError(_("File context for %s is not defined") % target)
2492
2493        try:
2494            (rc, fcontext) = semanage_fcontext_query_local(self.sh, k)
2495        except OSError:
2496            try:
2497                (rc, fcontext) = semanage_fcontext_query(self.sh, k)
2498            except OSError:
2499                raise ValueError(_("Could not query file context for %s") % target)
2500
2501        if setype != "<<none>>":
2502            con = semanage_fcontext_get_con(fcontext)
2503
2504            if con is None:
2505                con = self.createcon(target)
2506
2507            if (is_mls_enabled == 1) and (serange != ""):
2508                semanage_context_set_mls(self.sh, con, untranslate(serange))
2509            if seuser != "":
2510                semanage_context_set_user(self.sh, con, seuser)
2511
2512            if setype != "":
2513                semanage_context_set_type(self.sh, con, setype)
2514
2515            rc = semanage_fcontext_set_con(self.sh, fcontext, con)
2516            if rc < 0:
2517                raise ValueError(_("Could not set file context for %s") % target)
2518        else:
2519            rc = semanage_fcontext_set_con(self.sh, fcontext, None)
2520            if rc < 0:
2521                raise ValueError(_("Could not set file context for %s") % target)
2522
2523        rc = semanage_fcontext_modify_local(self.sh, k, fcontext)
2524        if rc < 0:
2525            raise ValueError(_("Could not modify file context for %s") % target)
2526
2527        semanage_fcontext_key_free(k)
2528        semanage_fcontext_free(fcontext)
2529
2530        if not seuser:
2531            seuser = "system_u"
2532
2533        self.mylog.log_change("resrc=fcontext op=modify %s ftype=%s tcontext=%s:%s:%s:%s" % (audit.audit_encode_nv_string("tglob", target, 0), ftype_to_audit[ftype], seuser, "object_r", setype, serange))
2534
2535    def modify(self, target, setype, ftype, serange, seuser):
2536        self.begin()
2537        self.__modify(target, setype, ftype, serange, seuser)
2538        self.commit()
2539
2540    def deleteall(self):
2541        (rc, flist) = semanage_fcontext_list_local(self.sh)
2542        if rc < 0:
2543            raise ValueError(_("Could not list the file contexts"))
2544
2545        self.begin()
2546
2547        for fcontext in flist:
2548            target = semanage_fcontext_get_expr(fcontext)
2549            ftype = semanage_fcontext_get_type(fcontext)
2550            ftype_str = semanage_fcontext_get_type_str(ftype)
2551            (rc, k) = semanage_fcontext_key_create(self.sh, target, file_types[ftype_str])
2552            if rc < 0:
2553                raise ValueError(_("Could not create a key for %s") % target)
2554
2555            rc = semanage_fcontext_del_local(self.sh, k)
2556            if rc < 0:
2557                raise ValueError(_("Could not delete the file context %s") % target)
2558            semanage_fcontext_key_free(k)
2559
2560            self.mylog.log_change("resrc=fcontext op=delete %s ftype=%s" % (audit.audit_encode_nv_string("tglob", target, 0), ftype_to_audit[file_type_str_to_option[ftype_str]]))
2561
2562        self.equiv = {}
2563        self.equal_ind = True
2564        self.commit()
2565
2566    def __delete(self, target, ftype):
2567        if target in self.equiv.keys():
2568            self.equiv.pop(target)
2569            self.equal_ind = True
2570
2571            self.mylog.log_change("resrc=fcontext op=delete-equal %s" % (audit.audit_encode_nv_string("tglob", target, 0)))
2572
2573            return
2574
2575        (rc, k) = semanage_fcontext_key_create(self.sh, target, file_types[ftype])
2576        if rc < 0:
2577            raise ValueError(_("Could not create a key for %s") % target)
2578
2579        (rc, exists) = semanage_fcontext_exists_local(self.sh, k)
2580        if rc < 0:
2581            raise ValueError(_("Could not check if file context for %s is defined") % target)
2582        if not exists:
2583            (rc, exists) = semanage_fcontext_exists(self.sh, k)
2584            if rc < 0:
2585                raise ValueError(_("Could not check if file context for %s is defined") % target)
2586            if exists:
2587                raise ValueError(_("File context for %s is defined in policy, cannot be deleted") % target)
2588            else:
2589                raise ValueError(_("File context for %s is not defined") % target)
2590
2591        rc = semanage_fcontext_del_local(self.sh, k)
2592        if rc < 0:
2593            raise ValueError(_("Could not delete file context for %s") % target)
2594
2595        semanage_fcontext_key_free(k)
2596
2597        self.mylog.log_change("resrc=fcontext op=delete %s ftype=%s" % (audit.audit_encode_nv_string("tglob", target, 0), ftype_to_audit[ftype]))
2598
2599    def delete(self, target, ftype):
2600        self.begin()
2601        self.__delete(target, ftype)
2602        self.commit()
2603
2604    def get_all(self, locallist=0):
2605        if locallist:
2606            (rc, self.flist) = semanage_fcontext_list_local(self.sh)
2607        else:
2608            (rc, self.flist) = semanage_fcontext_list(self.sh)
2609            if rc < 0:
2610                raise ValueError(_("Could not list file contexts"))
2611
2612            (rc, fchomedirs) = semanage_fcontext_list_homedirs(self.sh)
2613            if rc < 0:
2614                raise ValueError(_("Could not list file contexts for home directories"))
2615
2616            (rc, fclocal) = semanage_fcontext_list_local(self.sh)
2617            if rc < 0:
2618                raise ValueError(_("Could not list local file contexts"))
2619
2620            self.flist += fchomedirs
2621            self.flist += fclocal
2622
2623        ddict = {}
2624        for fcontext in self.flist:
2625            expr = semanage_fcontext_get_expr(fcontext)
2626            ftype = semanage_fcontext_get_type(fcontext)
2627            ftype_str = semanage_fcontext_get_type_str(ftype)
2628            con = semanage_fcontext_get_con(fcontext)
2629            if con:
2630                ddict[(expr, ftype_str)] = (semanage_context_get_user(con), semanage_context_get_role(con), semanage_context_get_type(con), semanage_context_get_mls(con))
2631            else:
2632                ddict[(expr, ftype_str)] = con
2633
2634        return ddict
2635
2636    def customized(self):
2637        l = []
2638        fcon_dict = self.get_all(True)
2639        for k in sorted(fcon_dict.keys()):
2640            if fcon_dict[k]:
2641                if fcon_dict[k][3]:
2642                    l.append("-a -f %s -t %s -r '%s' '%s'" % (file_type_str_to_option[k[1]], fcon_dict[k][2], fcon_dict[k][3], k[0]))
2643                else:
2644                    l.append("-a -f %s -t %s '%s'" % (file_type_str_to_option[k[1]], fcon_dict[k][2], k[0]))
2645
2646        if len(self.equiv):
2647            for target in self.equiv.keys():
2648                l.append("-a -e %s %s" % (self.equiv[target], target))
2649        return l
2650
2651    def list(self, heading=1, locallist=0):
2652        fcon_dict = self.get_all(locallist)
2653        if len(fcon_dict) != 0:
2654            if heading:
2655                print("%-50s %-18s %s\n" % (_("SELinux fcontext"), _("type"), _("Context")))
2656            for k in sorted(fcon_dict.keys()):
2657                if fcon_dict[k]:
2658                    if is_mls_enabled:
2659                        print("%-50s %-18s %s:%s:%s:%s " % (k[0], k[1], fcon_dict[k][0], fcon_dict[k][1], fcon_dict[k][2], translate(fcon_dict[k][3], False)))
2660                    else:
2661                        print("%-50s %-18s %s:%s:%s " % (k[0], k[1], fcon_dict[k][0], fcon_dict[k][1], fcon_dict[k][2]))
2662                else:
2663                    print("%-50s %-18s <<None>>" % (k[0], k[1]))
2664
2665        if len(self.equiv_dist):
2666            if not locallist:
2667                if heading:
2668                    print(_("\nSELinux Distribution fcontext Equivalence \n"))
2669                for target in self.equiv_dist.keys():
2670                    print("%s = %s" % (target, self.equiv_dist[target]))
2671        if len(self.equiv):
2672            if heading:
2673                print(_("\nSELinux Local fcontext Equivalence \n"))
2674
2675            for target in self.equiv.keys():
2676                print("%s = %s" % (target, self.equiv[target]))
2677
2678
2679class booleanRecords(semanageRecords):
2680
2681    def __init__(self, args = None):
2682        semanageRecords.__init__(self, args)
2683        self.dict = {}
2684        self.dict["TRUE"] = 1
2685        self.dict["FALSE"] = 0
2686        self.dict["ON"] = 1
2687        self.dict["OFF"] = 0
2688        self.dict["1"] = 1
2689        self.dict["0"] = 0
2690
2691        try:
2692            rc, self.current_booleans = selinux.security_get_boolean_names()
2693            rc, ptype = selinux.selinux_getpolicytype()
2694        except:
2695            self.current_booleans = []
2696            ptype = None
2697
2698        if self.store == "" or self.store == ptype:
2699            self.modify_local = True
2700        else:
2701            self.modify_local = False
2702
2703    def __mod(self, name, value):
2704        name = selinux.selinux_boolean_sub(name)
2705
2706        (rc, k) = semanage_bool_key_create(self.sh, name)
2707        if rc < 0:
2708            raise ValueError(_("Could not create a key for %s") % name)
2709        (rc, exists) = semanage_bool_exists(self.sh, k)
2710        if rc < 0:
2711            raise ValueError(_("Could not check if boolean %s is defined") % name)
2712        if not exists:
2713            raise ValueError(_("Boolean %s is not defined") % name)
2714
2715        (rc, b) = semanage_bool_query(self.sh, k)
2716        if rc < 0:
2717            raise ValueError(_("Could not query file context %s") % name)
2718
2719        if value.upper() in self.dict:
2720            semanage_bool_set_value(b, self.dict[value.upper()])
2721        else:
2722            raise ValueError(_("You must specify one of the following values: %s") % ", ".join(self.dict.keys()))
2723
2724        if self.modify_local and name in self.current_booleans:
2725            rc = semanage_bool_set_active(self.sh, k, b)
2726            if rc < 0:
2727                raise ValueError(_("Could not set active value of boolean %s") % name)
2728        rc = semanage_bool_modify_local(self.sh, k, b)
2729        if rc < 0:
2730            raise ValueError(_("Could not modify boolean %s") % name)
2731        semanage_bool_key_free(k)
2732        semanage_bool_free(b)
2733
2734    def modify(self, name, value=None, use_file=False):
2735        self.begin()
2736        if use_file:
2737            fd = open(name)
2738            for b in fd.read().split("\n"):
2739                b = b.strip()
2740                if len(b) == 0:
2741                    continue
2742
2743                try:
2744                    boolname, val = b.split("=")
2745                except ValueError:
2746                    raise ValueError(_("Bad format %s: Record %s" % (name, b)))
2747                self.__mod(boolname.strip(), val.strip())
2748            fd.close()
2749        else:
2750            self.__mod(name, value)
2751
2752        self.commit()
2753
2754    def __delete(self, name):
2755        name = selinux.selinux_boolean_sub(name)
2756
2757        (rc, k) = semanage_bool_key_create(self.sh, name)
2758        if rc < 0:
2759            raise ValueError(_("Could not create a key for %s") % name)
2760        (rc, exists) = semanage_bool_exists(self.sh, k)
2761        if rc < 0:
2762            raise ValueError(_("Could not check if boolean %s is defined") % name)
2763        if not exists:
2764            raise ValueError(_("Boolean %s is not defined") % name)
2765
2766        (rc, exists) = semanage_bool_exists_local(self.sh, k)
2767        if rc < 0:
2768            raise ValueError(_("Could not check if boolean %s is defined") % name)
2769        if not exists:
2770            raise ValueError(_("Boolean %s is defined in policy, cannot be deleted") % name)
2771
2772        rc = semanage_bool_del_local(self.sh, k)
2773        if rc < 0:
2774            raise ValueError(_("Could not delete boolean %s") % name)
2775
2776        semanage_bool_key_free(k)
2777
2778    def delete(self, name):
2779        self.begin()
2780        self.__delete(name)
2781        self.commit()
2782
2783    def deleteall(self):
2784        (rc, self.blist) = semanage_bool_list_local(self.sh)
2785        if rc < 0:
2786            raise ValueError(_("Could not list booleans"))
2787
2788        self.begin()
2789
2790        for boolean in self.blist:
2791            name = semanage_bool_get_name(boolean)
2792            self.__delete(name)
2793
2794        self.commit()
2795
2796    def get_all(self, locallist=0):
2797        ddict = {}
2798        if locallist:
2799            (rc, self.blist) = semanage_bool_list_local(self.sh)
2800        else:
2801            (rc, self.blist) = semanage_bool_list(self.sh)
2802        if rc < 0:
2803            raise ValueError(_("Could not list booleans"))
2804
2805        for boolean in self.blist:
2806            value = []
2807            name = semanage_bool_get_name(boolean)
2808            value.append(semanage_bool_get_value(boolean))
2809            if self.modify_local and name in self.current_booleans:
2810                value.append(selinux.security_get_boolean_pending(name))
2811                value.append(selinux.security_get_boolean_active(name))
2812            else:
2813                value.append(value[0])
2814                value.append(value[0])
2815            ddict[name] = value
2816
2817        return ddict
2818
2819    def get_desc(self, name):
2820        name = selinux.selinux_boolean_sub(name)
2821        return sepolicy.boolean_desc(name)
2822
2823    def get_category(self, name):
2824        name = selinux.selinux_boolean_sub(name)
2825        return sepolicy.boolean_category(name)
2826
2827    def customized(self):
2828        l = []
2829        ddict = self.get_all(True)
2830        for k in sorted(ddict.keys()):
2831            if ddict[k]:
2832                l.append("-m -%s %s" % (ddict[k][2], k))
2833        return l
2834
2835    def list(self, heading=True, locallist=False, use_file=False):
2836        on_off = (_("off"), _("on"))
2837        if use_file:
2838            ddict = self.get_all(locallist)
2839            for k in sorted(ddict.keys()):
2840                if ddict[k]:
2841                    print("%s=%s" % (k, ddict[k][2]))
2842            return
2843        ddict = self.get_all(locallist)
2844        if len(ddict) == 0:
2845            return
2846
2847        if heading:
2848            print("%-30s %s  %s %s\n" % (_("SELinux boolean"), _("State"), _("Default"), _("Description")))
2849        for k in sorted(ddict.keys()):
2850            if ddict[k]:
2851                print("%-30s (%-5s,%5s)  %s" % (k, on_off[ddict[k][2]], on_off[ddict[k][0]], self.get_desc(k)))
2852