1#! /usr/bin/python -Es
2# Copyright (C) 2005-2013 Red Hat
3# see file 'COPYING' for use and warranty information
4#
5# semanage is a tool for managing SELinux configuration files
6#
7#    This program is free software; you can redistribute it and/or
8#    modify it under the terms of the GNU General Public License as
9#    published by the Free Software Foundation; either version 2 of
10#    the License, or (at your option) any later version.
11#
12#    This program is distributed in the hope that it will be useful,
13#    but WITHOUT ANY WARRANTY; without even the implied warranty of
14#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15#    GNU General Public License for more details.
16#
17#    You should have received a copy of the GNU General Public License
18#    along with this program; if not, write to the Free Software
19#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20#                                        02111-1307  USA
21#
22#
23
24import pwd, grp, string, selinux, tempfile, os, re, sys, stat, shutil
25from semanage import *;
26PROGNAME = "policycoreutils"
27import sepolicy
28from sepolicy import boolean_desc, boolean_category, gen_bool_dict
29gen_bool_dict()
30from IPy import IP
31
32import gettext
33gettext.bindtextdomain(PROGNAME, "/usr/share/locale")
34gettext.textdomain(PROGNAME)
35
36import gettext
37translation=gettext.translation(PROGNAME, localedir = "/usr/share/locale", fallback=True)
38_=translation.ugettext
39
40import syslog
41
42file_types = {}
43file_types[""] = SEMANAGE_FCONTEXT_ALL;
44file_types["all files"] = SEMANAGE_FCONTEXT_ALL;
45file_types["a"] = SEMANAGE_FCONTEXT_ALL;
46file_types["regular file"] = SEMANAGE_FCONTEXT_REG;
47file_types["--"] = SEMANAGE_FCONTEXT_REG;
48file_types["f"] = SEMANAGE_FCONTEXT_REG;
49file_types["-d"] = SEMANAGE_FCONTEXT_DIR;
50file_types["directory"] = SEMANAGE_FCONTEXT_DIR;
51file_types["d"] = SEMANAGE_FCONTEXT_DIR;
52file_types["-c"] = SEMANAGE_FCONTEXT_CHAR;
53file_types["character device"] = SEMANAGE_FCONTEXT_CHAR;
54file_types["c"] = SEMANAGE_FCONTEXT_CHAR;
55file_types["-b"] = SEMANAGE_FCONTEXT_BLOCK;
56file_types["block device"] = SEMANAGE_FCONTEXT_BLOCK;
57file_types["b"] = SEMANAGE_FCONTEXT_BLOCK;
58file_types["-s"] = SEMANAGE_FCONTEXT_SOCK;
59file_types["socket"] = SEMANAGE_FCONTEXT_SOCK;
60file_types["s"] = SEMANAGE_FCONTEXT_SOCK;
61file_types["-l"] = SEMANAGE_FCONTEXT_LINK;
62file_types["l"] = SEMANAGE_FCONTEXT_LINK;
63file_types["symbolic link"] = SEMANAGE_FCONTEXT_LINK;
64file_types["p"] = SEMANAGE_FCONTEXT_PIPE;
65file_types["-p"] = SEMANAGE_FCONTEXT_PIPE;
66file_types["named pipe"] = SEMANAGE_FCONTEXT_PIPE;
67
68file_type_str_to_option = { "all files": "a",
69                            "regular file":"f",
70                            "directory":"d",
71                            "character device":"c",
72                            "block device":"b",
73                            "socket file":"s",
74                            "symbolic link":"l",
75                            "named pipe":"p" }
76try:
77	import audit
78	class logger:
79		def __init__(self):
80			self.audit_fd = audit.audit_open()
81			self.log_list = []
82		def log(self, msg, name = "", sename = "", serole = "", serange = "", oldsename = "", oldserole = "", oldserange = ""):
83
84			sep = "-"
85			if sename != oldsename:
86				msg += sep + "sename"; sep = ","
87			if serole != oldserole:
88				msg += sep + "role"; sep = ","
89			if serange != oldserange:
90				msg += sep + "range"; sep = ","
91
92			self.log_list.append([self.audit_fd, audit.AUDIT_ROLE_ASSIGN, sys.argv[0], str(msg), name, 0, sename, serole, serange, oldsename, oldserole, oldserange, "", "", ""])
93
94		def log_remove(self, msg, name = "", sename = "", serole = "", serange = "", oldsename = "", oldserole = "", oldserange = ""):
95			self.log_list.append([self.audit_fd, audit.AUDIT_ROLE_REMOVE, sys.argv[0], str(msg), name, 0, sename, serole, serange, oldsename, oldserole, oldserange, "", "", ""])
96
97		def commit(self,success):
98			for l in self.log_list:
99				audit.audit_log_semanage_message(*(l + [success]))
100			self.log_list = []
101except:
102	class logger:
103		def __init__(self):
104			self.log_list=[]
105
106		def log(self, msg, name = "", sename = "", serole = "", serange = "", oldsename = "", oldserole = "", oldserange = ""):
107			message = " %s name=%s" % (msg, name)
108			if sename != "":
109				message += " sename=" + sename
110			if oldsename != "":
111				message += " oldsename=" + oldsename
112			if serole != "":
113				message += " role=" + serole
114			if oldserole != "":
115				message += " old_role=" + oldserole
116			if serange != "" and serange != None:
117				message += " MLSRange=" + serange
118			if oldserange != "" and oldserange != None:
119				message += " old_MLSRange=" + oldserange
120			self.log_list.append(message)
121
122		def log_remove(self, msg, name = "", sename = "", serole = "", serange = "", oldsename = "", oldserole = "", oldserange = ""):
123			self.log(msg, name, sename, serole, serange, oldsename, oldserole, oldserange)
124
125		def commit(self,success):
126			if success == 1:
127				message = "Successful: "
128			else:
129				message = "Failed: "
130			for l in self.log_list:
131				syslog.syslog(syslog.LOG_INFO, message + l)
132
133class nulllogger:
134	def log(self, msg, name = "", sename = "", serole = "", serange = "", oldsename = "", oldserole = "", oldserange = ""):
135		pass
136
137	def log_remove(self, msg, name = "", sename = "", serole = "", serange = "", oldsename = "", oldserole = "", oldserange = ""):
138		pass
139
140	def commit(self,success):
141		pass
142
143def validate_level(raw):
144	sensitivity = "s[0-9]*"
145	category = "c[0-9]*"
146	cat_range = category + "(\." + category +")?"
147	categories = cat_range + "(\," + cat_range + ")*"
148	reg = sensitivity + "(-" + sensitivity + ")?" + "(:" + categories + ")?"
149	return re.search("^" + reg +"$", raw)
150
151def translate(raw, prepend = 1):
152        filler = "a:b:c:"
153        if prepend == 1:
154		context = "%s%s" % (filler, raw)
155	else:
156		context = raw
157	(rc, trans) = selinux.selinux_raw_to_trans_context(context)
158	if rc != 0:
159		return raw
160	if prepend:
161		trans = trans[len(filler):]
162	if trans == "":
163		return raw
164	else:
165		return trans
166
167def untranslate(trans, prepend = 1):
168        filler = "a:b:c:"
169 	if prepend == 1:
170		context = "%s%s" % (filler, trans)
171	else:
172		context = trans
173
174	(rc, raw) = selinux.selinux_trans_to_raw_context(context)
175	if rc != 0:
176		return trans
177	if prepend:
178		raw = raw[len(filler):]
179	if raw == "":
180		return trans
181	else:
182		return raw
183
184class semanageRecords:
185        transaction = False
186        handle = None
187        store = None
188        def __init__(self, store):
189               global handle
190	       self.load = True
191               self.sh = self.get_handle(store)
192
193	       rc, localstore = selinux.selinux_getpolicytype()
194	       if store == "" or store == localstore:
195		       self.mylog = logger()
196	       else:
197		       self.mylog = nulllogger()
198
199	def set_reload(self, load):
200	       self.load = load
201
202        def get_handle(self, store):
203		global is_mls_enabled
204
205		if semanageRecords.handle:
206			return semanageRecords.handle
207
208		handle = semanage_handle_create()
209		if not handle:
210			raise ValueError(_("Could not create semanage handle"))
211
212		if not semanageRecords.transaction and store != "":
213			semanage_select_store(handle, store, SEMANAGE_CON_DIRECT);
214			semanageRecords.store = store
215
216		if not semanage_is_managed(handle):
217			semanage_handle_destroy(handle)
218			raise ValueError(_("SELinux policy is not managed or store cannot be accessed."))
219
220		rc = semanage_access_check(handle)
221		if rc < SEMANAGE_CAN_READ:
222			semanage_handle_destroy(handle)
223			raise ValueError(_("Cannot read policy store."))
224
225		rc = semanage_connect(handle)
226		if rc < 0:
227			semanage_handle_destroy(handle)
228			raise ValueError(_("Could not establish semanage connection"))
229
230		is_mls_enabled = semanage_mls_enabled(handle)
231		if is_mls_enabled < 0:
232			semanage_handle_destroy(handle)
233			raise ValueError(_("Could not test MLS enabled status"))
234
235		semanageRecords.handle = handle
236		return semanageRecords.handle
237
238        def deleteall(self):
239               raise ValueError(_("Not yet implemented"))
240
241        def start(self):
242               if semanageRecords.transaction:
243                      raise ValueError(_("Semanage transaction already in progress"))
244               self.begin()
245               semanageRecords.transaction = True
246
247        def begin(self):
248               if semanageRecords.transaction:
249                      return
250               rc = semanage_begin_transaction(self.sh)
251               if rc < 0:
252                      raise ValueError(_("Could not start semanage transaction"))
253        def customized(self):
254               raise ValueError(_("Not yet implemented"))
255
256        def commit(self):
257		if semanageRecords.transaction:
258			return
259
260		semanage_set_reload(self.sh, self.load)
261		rc = semanage_commit(self.sh)
262		if rc < 0:
263			self.mylog.commit(0)
264			raise ValueError(_("Could not commit semanage transaction"))
265		self.mylog.commit(1)
266
267        def finish(self):
268               if not semanageRecords.transaction:
269                      raise ValueError(_("Semanage transaction not in progress"))
270               semanageRecords.transaction = False
271               self.commit()
272
273class moduleRecords(semanageRecords):
274	def __init__(self, store):
275	       semanageRecords.__init__(self, store)
276
277	def get_all(self):
278               l = []
279               (rc, mlist, number) = semanage_module_list_all(self.sh)
280               if rc < 0:
281                      raise ValueError(_("Could not list SELinux modules"))
282
283               for i in range(number):
284                      mod = semanage_module_list_nth(mlist, i)
285
286                      rc, name = semanage_module_info_get_name(self.sh, mod)
287                      if rc < 0:
288                          raise ValueError(_("Could not get module name"))
289
290                      rc, enabled = semanage_module_info_get_enabled(self.sh, mod)
291                      if rc < 0:
292                          raise ValueError(_("Could not get module enabled"))
293
294                      rc, priority = semanage_module_info_get_priority(self.sh, mod)
295                      if rc < 0:
296                          raise ValueError(_("Could not get module priority"))
297
298                      rc, lang_ext = semanage_module_info_get_lang_ext(self.sh, mod)
299                      if rc < 0:
300                          raise ValueError(_("Could not get module lang_ext"))
301
302                      l.append((name, enabled, priority, lang_ext))
303
304               # sort the list so they are in name order, but with higher priorities coming first
305               l.sort(key = lambda t: t[3], reverse=True)
306               l.sort(key = lambda t: t[0])
307               return l
308
309        def customized(self):
310		all = self.get_all()
311		if len(all) == 0:
312			return
313                return map(lambda x: "-d %s" % x[0], filter(lambda t: t[1] == 0, all))
314
315	def list(self, heading = 1, locallist = 0):
316		all = self.get_all()
317		if len(all) == 0:
318			return
319
320		if heading:
321			print "\n%-25s %-9s %s\n" % (_("Module Name"), _("Priority"), _("Language"))
322                for t in all:
323                       if t[1] == 0:
324                              disabled = _("Disabled")
325                       else:
326                              if locallist:
327                                      continue
328                              disabled = ""
329                       print "%-25s %-9s %-5s %s" % (t[0], t[2], t[3], disabled)
330
331	def add(self, file, priority):
332               if not os.path.exists(file):
333                       raise ValueError(_("Module does not exists %s ") % file)
334
335               rc = semanage_set_default_priority(self.sh, priority)
336               if rc < 0:
337                       raise ValueError(_("Invalid priority %d (needs to be between 1 and 999)") % priority)
338
339               rc = semanage_module_install_file(self.sh, file);
340               if rc >= 0:
341                      self.commit()
342
343	def set_enabled(self, module, enable):
344               for m in module.split():
345                      rc, key = semanage_module_key_create(self.sh)
346                      if rc < 0:
347                              raise ValueError(_("Could not create module key"))
348
349                      rc = semanage_module_key_set_name(self.sh, key, m)
350                      if rc < 0:
351                              raise ValueError(_("Could not set module key name"))
352
353                      rc = semanage_module_set_enabled(self.sh, key, enable)
354                      if rc < 0:
355                              if enable:
356                                  raise ValueError(_("Could not enable module %s") % m)
357                              else:
358                                  raise ValueError(_("Could not disable module %s") % m)
359               self.commit()
360
361	def modify(self, file):
362               rc = semanage_module_update_file(self.sh, file);
363               if rc >= 0:
364                      self.commit()
365
366	def delete(self, module, priority):
367               rc = semanage_set_default_priority(self.sh, priority)
368               if rc < 0:
369                       raise ValueError(_("Invalid priority %d (needs to be between 1 and 999)") % priority)
370
371               for m in module.split():
372                      rc = semanage_module_remove(self.sh, m)
373                      if rc < 0 and rc != -2:
374                             raise ValueError(_("Could not remove module %s (remove failed)") % m)
375
376               self.commit()
377
378	def deleteall(self):
379                l = map(lambda x: x[0], filter(lambda t: t[1] == 0, self.get_all()))
380                for m in l:
381                        self.enable(m)
382
383class dontauditClass(semanageRecords):
384	def __init__(self, store):
385               semanageRecords.__init__(self, store)
386
387	def toggle(self, dontaudit):
388               if dontaudit not in [ "on", "off" ]:
389                      raise ValueError(_("dontaudit requires either 'on' or 'off'"))
390               self.begin()
391               rc = semanage_set_disable_dontaudit(self.sh, dontaudit == "off")
392               self.commit()
393
394class permissiveRecords(semanageRecords):
395	def __init__(self, store):
396               semanageRecords.__init__(self, store)
397
398	def get_all(self):
399               l = []
400               (rc, mlist, number) = semanage_module_list(self.sh)
401               if rc < 0:
402                      raise ValueError(_("Could not list SELinux modules"))
403
404               for i in range(number):
405                      mod = semanage_module_list_nth(mlist, i)
406                      name = semanage_module_get_name(mod)
407                      if name and name.startswith("permissive_"):
408                             l.append(name.split("permissive_")[1])
409               return l
410
411	def list(self, heading = 1, locallist = 0):
412		all = map(lambda y: y["name"], filter(lambda x: x["permissive"], sepolicy.info(sepolicy.TYPE)))
413		if len(all) == 0:
414			return
415
416		if heading:
417			print "\n%-25s\n" % (_("Builtin Permissive Types"))
418		customized = self.get_all()
419                for t in all:
420			if t not in customized:
421				print t
422
423		if len(customized) == 0:
424			return
425
426		if heading:
427			print "\n%-25s\n" % (_("Customized Permissive Types"))
428		for t in customized:
429			print t
430
431	def add(self, type):
432               import glob
433	       try:
434		       import sepolgen.module as module
435	       except ImportError:
436		       raise ValueError(_("The sepolgen python module is required to setup permissive domains.\nIn some distributions it is included in the policycoreutils-devel patckage.\n# yum install policycoreutils-devel\nOr similar for your distro."))
437
438               name = "permissive_%s" % type
439               modtxt = "(typepermissive %s)" % type
440
441               rc = semanage_module_install(self.sh, modtxt, len(modtxt), name, "cil");
442               if rc >= 0:
443                      self.commit()
444
445               if rc < 0:
446			raise ValueError(_("Could not set permissive domain %s (module installation failed)") % name)
447
448	def delete(self, name):
449               for n in name.split():
450                      rc = semanage_module_remove(self.sh, "permissive_%s" % n)
451                      if rc < 0:
452                             raise ValueError(_("Could not remove permissive domain %s (remove failed)") % name)
453
454               self.commit()
455
456	def deleteall(self):
457               l = self.get_all()
458               if len(l) > 0:
459                      all = " ".join(l)
460                      self.delete(all)
461
462class loginRecords(semanageRecords):
463	def __init__(self, store = ""):
464		semanageRecords.__init__(self, store)
465		self.oldsename  = None
466		self.oldserange = None
467		self.sename  = None
468		self.serange = None
469
470	def __add(self, name, sename, serange):
471		rec, self.oldsename, self.oldserange = selinux.getseuserbyname(name)
472		if sename == "":
473			sename = "user_u"
474
475		userrec = seluserRecords()
476		range, (rc, oldserole) = userrec.get(self.oldsename)
477		range, (rc, serole) = userrec.get(sename)
478
479		if is_mls_enabled == 1:
480			if serange != "":
481				serange = untranslate(serange)
482			else:
483                           serange = range
484
485		(rc, k) = semanage_seuser_key_create(self.sh, name)
486		if rc < 0:
487			raise ValueError(_("Could not create a key for %s") % name)
488
489		(rc, exists) = semanage_seuser_exists(self.sh, k)
490		if rc < 0:
491			raise ValueError(_("Could not check if login mapping for %s is defined") % name)
492		if exists:
493			raise ValueError(_("Login mapping for %s is already defined") % name)
494                if name[0] == '%':
495                       try:
496                              grp.getgrnam(name[1:])
497                       except:
498                              raise ValueError(_("Linux Group %s does not exist") % name[1:])
499                else:
500                       try:
501                              pwd.getpwnam(name)
502                       except:
503                              raise ValueError(_("Linux User %s does not exist") % name)
504
505                (rc, u) = semanage_seuser_create(self.sh)
506                if rc < 0:
507                       raise ValueError(_("Could not create login mapping for %s") % name)
508
509                rc = semanage_seuser_set_name(self.sh, u, name)
510                if rc < 0:
511                       raise ValueError(_("Could not set name for %s") % name)
512
513                if (is_mls_enabled == 1) and (serange != ""):
514                       rc = semanage_seuser_set_mlsrange(self.sh, u, serange)
515                       if rc < 0:
516                              raise ValueError(_("Could not set MLS range for %s") % name)
517
518                rc = semanage_seuser_set_sename(self.sh, u, sename)
519                if rc < 0:
520                       raise ValueError(_("Could not set SELinux user for %s") % name)
521
522                rc = semanage_seuser_modify_local(self.sh, k, u)
523                if rc < 0:
524                       raise ValueError(_("Could not add login mapping for %s") % name)
525
526		semanage_seuser_key_free(k)
527		semanage_seuser_free(u)
528		self.mylog.log("login", name, sename=sename, serange=serange, serole=",".join(serole), oldserole=",".join(oldserole), oldsename=self.oldsename, oldserange=self.oldserange);
529
530	def add(self, name, sename, serange):
531		try:
532			self.begin()
533			self.__add(name, sename, serange)
534			self.commit()
535		except ValueError, error:
536			self.mylog.commit(0)
537			raise error
538
539	def __modify(self, name, sename = "", serange = ""):
540		rec, self.oldsename, self.oldserange = selinux.getseuserbyname(name)
541		if sename == "" and serange == "":
542                      raise ValueError(_("Requires seuser or serange"))
543
544		userrec = seluserRecords()
545		range, (rc, oldserole) = userrec.get(self.oldsename)
546
547		if sename != "":
548			range, (rc, serole) = userrec.get(sename)
549		else:
550			serole=oldserole
551
552		if serange != "":
553			self.serange=serange
554		else:
555			self.serange=range
556
557		(rc, k) = semanage_seuser_key_create(self.sh, name)
558		if rc < 0:
559		       raise ValueError(_("Could not create a key for %s") % name)
560
561		(rc, exists) = semanage_seuser_exists(self.sh, k)
562		if rc < 0:
563			raise ValueError(_("Could not check if login mapping for %s is defined") % name)
564		if not exists:
565			raise ValueError(_("Login mapping for %s is not defined") % name)
566
567		(rc, u) = semanage_seuser_query(self.sh, k)
568		if rc < 0:
569			raise ValueError(_("Could not query seuser for %s") % name)
570
571		self.oldserange = semanage_seuser_get_mlsrange(u)
572		self.oldsename = semanage_seuser_get_sename(u)
573		if (is_mls_enabled == 1) and (serange != ""):
574			semanage_seuser_set_mlsrange(self.sh, u, untranslate(serange))
575
576		if sename != "":
577			semanage_seuser_set_sename(self.sh, u, sename)
578		else:
579			self.sename = self.oldsename
580
581		rc = semanage_seuser_modify_local(self.sh, k, u)
582		if rc < 0:
583			raise ValueError(_("Could not modify login mapping for %s") % name)
584
585		semanage_seuser_key_free(k)
586		semanage_seuser_free(u)
587		self.mylog.log("login", name,sename=self.sename,serange=self.serange, serole=",".join(serole), oldserole=",".join(oldserole), oldsename=self.oldsename, oldserange=self.oldserange);
588
589	def modify(self, name, sename = "", serange = ""):
590		try:
591                        self.begin()
592                        self.__modify(name, sename, serange)
593                        self.commit()
594		except ValueError, error:
595			self.mylog.commit(0)
596			raise error
597
598	def __delete(self, name):
599		rec, self.oldsename, self.oldserange = selinux.getseuserbyname(name)
600		userrec = seluserRecords()
601		range, (rc, oldserole) = userrec.get(self.oldsename)
602
603		(rc, k) = semanage_seuser_key_create(self.sh, name)
604		if rc < 0:
605			raise ValueError(_("Could not create a key for %s") % name)
606
607		(rc, exists) = semanage_seuser_exists(self.sh, k)
608		if rc < 0:
609			raise ValueError(_("Could not check if login mapping for %s is defined") % name)
610		if not exists:
611			raise ValueError(_("Login mapping for %s is not defined") % name)
612
613		(rc, exists) = semanage_seuser_exists_local(self.sh, k)
614		if rc < 0:
615			raise ValueError(_("Could not check if login mapping for %s is defined") % name)
616		if not exists:
617			raise ValueError(_("Login mapping for %s is defined in policy, cannot be deleted") % name)
618
619		rc = semanage_seuser_del_local(self.sh, k)
620		if rc < 0:
621			raise ValueError(_("Could not delete login mapping for %s") % name)
622
623		semanage_seuser_key_free(k)
624
625		rec, self.sename, self.serange = selinux.getseuserbyname("__default__")
626		range, (rc, serole) = userrec.get(self.sename)
627
628		self.mylog.log_remove("login", name, sename=self.sename, serange=self.serange, serole=",".join(serole), oldserole=",".join(oldserole), oldsename=self.oldsename, oldserange=self.oldserange);
629
630	def delete(self, name):
631		try:
632			self.begin()
633			self.__delete(name)
634			self.commit()
635
636		except ValueError, error:
637			self.mylog.commit(0)
638			raise error
639
640	def deleteall(self):
641		(rc, ulist) = semanage_seuser_list_local(self.sh)
642		if rc < 0:
643			raise ValueError(_("Could not list login mappings"))
644
645		try:
646			self.begin()
647			for u in ulist:
648				self.__delete(semanage_seuser_get_name(u))
649			self.commit()
650		except ValueError, error:
651			self.mylog.commit(0)
652			raise error
653
654	def get_all_logins(self):
655		ddict = {}
656		self.logins_path = selinux.selinux_policy_root() + "/logins"
657		for path,dirs,files in os.walk(self.logins_path):
658			if path == self.logins_path:
659				for name in files:
660					try:
661						fd = open(path + "/" + name)
662						rec = fd.read().rstrip().split(":")
663						fd.close()
664						ddict[name] = (rec[1], rec[2], rec[0])
665					except IndexError:
666						pass
667		return ddict
668
669	def get_all(self, locallist = 0):
670		ddict = {}
671                if locallist:
672                       (rc, self.ulist) = semanage_seuser_list_local(self.sh)
673                else:
674                       (rc, self.ulist) = semanage_seuser_list(self.sh)
675		if rc < 0:
676			raise ValueError(_("Could not list login mappings"))
677
678		for u in self.ulist:
679			name = semanage_seuser_get_name(u)
680			ddict[name] = (semanage_seuser_get_sename(u), semanage_seuser_get_mlsrange(u), "*")
681		return ddict
682
683        def customized(self):
684                l = []
685                ddict = self.get_all(True)
686                keys = ddict.keys()
687                keys.sort()
688                for k in keys:
689                       l.append("-a -s %s -r '%s' %s" % (ddict[k][0], ddict[k][1], k))
690                return l
691
692	def list(self,heading = 1, locallist = 0):
693		ddict = self.get_all(locallist)
694		ldict = self.get_all_logins()
695		lkeys = ldict.keys()
696		keys = ddict.keys()
697		if len(keys) == 0 and len(lkeys) == 0:
698			return
699		keys.sort()
700		lkeys.sort()
701
702		if is_mls_enabled == 1:
703			if heading:
704				print "\n%-20s %-20s %-20s %s\n" % (_("Login Name"), _("SELinux User"), _("MLS/MCS Range"), _("Service"))
705			for k in keys:
706				u = ddict[k]
707				print "%-20s %-20s %-20s %s" % (k, u[0], translate(u[1]), u[2])
708			if len(lkeys):
709				print "\nLocal customization in %s" % self.logins_path
710
711			for k in lkeys:
712				u = ldict[k]
713				print "%-20s %-20s %-20s %s" % (k, u[0], translate(u[1]), u[2])
714		else:
715			if heading:
716				print "\n%-25s %-25s\n" % (_("Login Name"), _("SELinux User"))
717			for k in keys:
718				print "%-25s %-25s" % (k, ddict[k][0])
719
720class seluserRecords(semanageRecords):
721	def __init__(self, store = ""):
722		semanageRecords.__init__(self, store)
723
724	def get(self, name):
725                (rc, k) = semanage_user_key_create(self.sh, name)
726                if rc < 0:
727                       raise ValueError(_("Could not create a key for %s") % name)
728                (rc, exists) = semanage_user_exists(self.sh, k)
729                if rc < 0:
730                       raise ValueError(_("Could not check if SELinux user %s is defined") % name)
731                (rc, u) = semanage_user_query(self.sh, k)
732                if rc < 0:
733                       raise ValueError(_("Could not query user for %s") % name)
734                serange = semanage_user_get_mlsrange(u)
735                serole = semanage_user_get_roles(self.sh,u)
736		semanage_user_key_free(k)
737		semanage_user_free(u)
738		return serange, serole
739
740	def __add(self, name, roles, selevel, serange, prefix):
741		if is_mls_enabled == 1:
742			if serange == "":
743				serange = "s0"
744			else:
745				serange = untranslate(serange)
746
747			if selevel == "":
748				selevel = "s0"
749			else:
750				selevel = untranslate(selevel)
751
752                if len(roles) < 1:
753                       raise ValueError(_("You must add at least one role for %s") % name)
754
755                (rc, k) = semanage_user_key_create(self.sh, name)
756                if rc < 0:
757                       raise ValueError(_("Could not create a key for %s") % name)
758
759                (rc, exists) = semanage_user_exists(self.sh, k)
760                if rc < 0:
761                       raise ValueError(_("Could not check if SELinux user %s is defined") % name)
762                if exists:
763                       raise ValueError(_("SELinux user %s is already defined") % name)
764
765                (rc, u) = semanage_user_create(self.sh)
766                if rc < 0:
767                       raise ValueError(_("Could not create SELinux user for %s") % name)
768
769                rc = semanage_user_set_name(self.sh, u, name)
770                if rc < 0:
771                       raise ValueError(_("Could not set name for %s") % name)
772
773                for r in roles:
774                       rc = semanage_user_add_role(self.sh, u, r)
775                       if rc < 0:
776                              raise ValueError(_("Could not add role %s for %s") % (r, name))
777
778                if is_mls_enabled == 1:
779                       rc = semanage_user_set_mlsrange(self.sh, u, serange)
780                       if rc < 0:
781                              raise ValueError(_("Could not set MLS range for %s") % name)
782
783                       rc = semanage_user_set_mlslevel(self.sh, u, selevel)
784                       if rc < 0:
785                              raise ValueError(_("Could not set MLS level for %s") % name)
786                rc = semanage_user_set_prefix(self.sh, u, prefix)
787                if rc < 0:
788                       raise ValueError(_("Could not add prefix %s for %s") % (r, prefix))
789                (rc, key) = semanage_user_key_extract(self.sh,u)
790                if rc < 0:
791                       raise ValueError(_("Could not extract key for %s") % name)
792
793                rc = semanage_user_modify_local(self.sh, k, u)
794                if rc < 0:
795                       raise ValueError(_("Could not add SELinux user %s") % name)
796
797                semanage_user_key_free(k)
798                semanage_user_free(u)
799		self.mylog.log("seuser", sename=name, serole=",".join(roles), serange=serange)
800
801	def add(self, name, roles, selevel, serange, prefix):
802		serole = " ".join(roles)
803		try:
804			self.begin()
805			self.__add( name, roles, selevel, serange, prefix)
806			self.commit()
807		except ValueError, error:
808			self.mylog.commit(0)
809			raise error
810
811        def __modify(self, name, roles = [], selevel = "", serange = "", prefix = ""):
812		oldserole = ""
813		oldserange = ""
814		newroles = string.join(roles, ' ');
815                if prefix == "" and len(roles) == 0  and serange == "" and selevel == "":
816                       if is_mls_enabled == 1:
817                              raise ValueError(_("Requires prefix, roles, level or range"))
818                       else:
819                              raise ValueError(_("Requires prefix or roles"))
820
821                (rc, k) = semanage_user_key_create(self.sh, name)
822                if rc < 0:
823                       raise ValueError(_("Could not create a key for %s") % name)
824
825                (rc, exists) = semanage_user_exists(self.sh, k)
826                if rc < 0:
827                       raise ValueError(_("Could not check if SELinux user %s is defined") % name)
828                if not exists:
829                       raise ValueError(_("SELinux user %s is not defined") % name)
830
831                (rc, u) = semanage_user_query(self.sh, k)
832                if rc < 0:
833                       raise ValueError(_("Could not query user for %s") % name)
834
835                oldserange = semanage_user_get_mlsrange(u)
836                (rc, rlist) = semanage_user_get_roles(self.sh, u)
837                if rc >= 0:
838                       oldserole = string.join(rlist, ' ');
839
840                if (is_mls_enabled == 1) and (serange != ""):
841                       semanage_user_set_mlsrange(self.sh, u, untranslate(serange))
842                if (is_mls_enabled == 1) and (selevel != ""):
843                       semanage_user_set_mlslevel(self.sh, u, untranslate(selevel))
844
845                if prefix != "":
846                       semanage_user_set_prefix(self.sh, u, prefix)
847
848                if len(roles) != 0:
849                       for r in rlist:
850                              if r not in roles:
851                                     semanage_user_del_role(u, r)
852                       for r in roles:
853                              if r not in rlist:
854                                     semanage_user_add_role(self.sh, u, r)
855
856                rc = semanage_user_modify_local(self.sh, k, u)
857                if rc < 0:
858                       raise ValueError(_("Could not modify SELinux user %s") % name)
859
860		semanage_user_key_free(k)
861		semanage_user_free(u)
862
863		role=",".join(newroles.split())
864		oldserole=",".join(oldserole.split())
865		self.mylog.log("seuser", sename=name, oldsename=name, serole=role, serange=serange, oldserole=oldserole, oldserange=oldserange)
866
867
868	def modify(self, name, roles = [], selevel = "", serange = "", prefix = ""):
869		try:
870                        self.begin()
871                        self.__modify(name, roles, selevel, serange, prefix)
872                        self.commit()
873		except ValueError, error:
874			self.mylog.commit(0)
875			raise error
876
877	def __delete(self, name):
878               (rc, k) = semanage_user_key_create(self.sh, name)
879               if rc < 0:
880                      raise ValueError(_("Could not create a key for %s") % name)
881
882               (rc, exists) = semanage_user_exists(self.sh, k)
883               if rc < 0:
884                      raise ValueError(_("Could not check if SELinux user %s is defined") % name)
885               if not exists:
886                      raise ValueError(_("SELinux user %s is not defined") % name)
887
888               (rc, exists) = semanage_user_exists_local(self.sh, k)
889               if rc < 0:
890                      raise ValueError(_("Could not check if SELinux user %s is defined") % name)
891               if not exists:
892                      raise ValueError(_("SELinux user %s is defined in policy, cannot be deleted") % name)
893
894	       (rc, u) = semanage_user_query(self.sh, k)
895	       if rc < 0:
896                       raise ValueError(_("Could not query user for %s") % name)
897	       oldserange = semanage_user_get_mlsrange(u)
898	       (rc, rlist) = semanage_user_get_roles(self.sh, u)
899	       oldserole = ",".join(rlist)
900
901               rc = semanage_user_del_local(self.sh, k)
902               if rc < 0:
903                      raise ValueError(_("Could not delete SELinux user %s") % name)
904
905               semanage_user_key_free(k)
906	       semanage_user_free(u)
907
908	       self.mylog.log_remove("seuser", oldsename=name, oldserange=oldserange, oldserole=oldserole)
909
910	def delete(self, name):
911		try:
912                        self.begin()
913                        self.__delete(name)
914                        self.commit()
915
916		except ValueError, error:
917			self.mylog.commit(0)
918			raise error
919
920	def deleteall(self):
921		(rc, ulist) = semanage_user_list_local(self.sh)
922		if rc < 0:
923			raise ValueError(_("Could not list login mappings"))
924
925		try:
926			self.begin()
927			for u in ulist:
928				self.__delete(semanage_user_get_name(u))
929			self.commit()
930		except ValueError, error:
931			self.mylog.commit(0)
932			raise error
933
934	def get_all(self, locallist = 0):
935		ddict = {}
936                if locallist:
937                       (rc, self.ulist) = semanage_user_list_local(self.sh)
938                else:
939                       (rc, self.ulist) = semanage_user_list(self.sh)
940		if rc < 0:
941			raise ValueError(_("Could not list SELinux users"))
942
943		for u in self.ulist:
944			name = semanage_user_get_name(u)
945			(rc, rlist) = semanage_user_get_roles(self.sh, u)
946			if rc < 0:
947				raise ValueError(_("Could not list roles for user %s") % name)
948
949			roles = string.join(rlist, ' ');
950			ddict[semanage_user_get_name(u)] = (semanage_user_get_prefix(u), semanage_user_get_mlslevel(u), semanage_user_get_mlsrange(u), roles)
951
952		return ddict
953
954        def customized(self):
955                l = []
956                ddict = self.get_all(True)
957                keys = ddict.keys()
958                keys.sort()
959                for k in keys:
960                       l.append("-a -L %s -r %s -R '%s' %s" % (ddict[k][1], ddict[k][2], ddict[k][3], k))
961                return l
962
963	def list(self, heading = 1, locallist = 0):
964		ddict = self.get_all(locallist)
965		keys = ddict.keys()
966		if len(keys) == 0:
967			return
968		keys.sort()
969
970		if is_mls_enabled == 1:
971			if heading:
972				print "\n%-15s %-10s %-10s %-30s" % ("", _("Labeling"), _("MLS/"), _("MLS/"))
973				print "%-15s %-10s %-10s %-30s %s\n" % (_("SELinux User"), _("Prefix"), _("MCS Level"), _("MCS Range"), _("SELinux Roles"))
974			for k in keys:
975				print "%-15s %-10s %-10s %-30s %s" % (k, ddict[k][0], translate(ddict[k][1]), translate(ddict[k][2]), ddict[k][3])
976		else:
977			if heading:
978				print "%-15s %s\n" % (_("SELinux User"), _("SELinux Roles"))
979			for k in keys:
980				print "%-15s %s" % (k, ddict[k][3])
981
982class portRecords(semanageRecords):
983	try:
984		valid_types =  sepolicy.info(sepolicy.ATTRIBUTE,"port_type")[0]["types"]
985	except RuntimeError:
986		valid_types = []
987
988	def __init__(self, store = ""):
989		semanageRecords.__init__(self, store)
990
991	def __genkey(self, port, proto):
992		if proto == "tcp":
993			proto_d = SEMANAGE_PROTO_TCP
994		else:
995			if proto == "udp":
996				proto_d = SEMANAGE_PROTO_UDP
997			else:
998				raise ValueError(_("Protocol udp or tcp is required"))
999		if port == "":
1000			raise ValueError(_("Port is required"))
1001
1002		ports = port.split("-")
1003		if len(ports) == 1:
1004			high = low = int(ports[0])
1005		else:
1006			low = int(ports[0])
1007			high = int(ports[1])
1008
1009		if high > 65535:
1010			raise ValueError(_("Invalid Port"))
1011
1012		(rc, k) = semanage_port_key_create(self.sh, low, high, proto_d)
1013		if rc < 0:
1014			raise ValueError(_("Could not create a key for %s/%s") % (proto, port))
1015		return ( k, proto_d, low, high )
1016
1017	def __add(self, port, proto, serange, type):
1018		if is_mls_enabled == 1:
1019			if serange == "":
1020				serange = "s0"
1021			else:
1022				serange = untranslate(serange)
1023
1024		if type == "":
1025			raise ValueError(_("Type is required"))
1026
1027		if type not in self.valid_types:
1028			raise ValueError(_("Type %s is invalid, must be a port type") % type)
1029
1030		( k, proto_d, low, high ) = self.__genkey(port, proto)
1031
1032		(rc, exists) = semanage_port_exists(self.sh, k)
1033		if rc < 0:
1034			raise ValueError(_("Could not check if port %s/%s is defined") % (proto, port))
1035		if exists:
1036			raise ValueError(_("Port %s/%s already defined") % (proto, port))
1037
1038		(rc, p) = semanage_port_create(self.sh)
1039		if rc < 0:
1040			raise ValueError(_("Could not create port for %s/%s") % (proto, port))
1041
1042		semanage_port_set_proto(p, proto_d)
1043		semanage_port_set_range(p, low, high)
1044		(rc, con) = semanage_context_create(self.sh)
1045		if rc < 0:
1046			raise ValueError(_("Could not create context for %s/%s") % (proto, port))
1047
1048		rc = semanage_context_set_user(self.sh, con, "system_u")
1049		if rc < 0:
1050			raise ValueError(_("Could not set user in port context for %s/%s") % (proto, port))
1051
1052		rc = semanage_context_set_role(self.sh, con, "object_r")
1053		if rc < 0:
1054			raise ValueError(_("Could not set role in port context for %s/%s") % (proto, port))
1055
1056		rc = semanage_context_set_type(self.sh, con, type)
1057		if rc < 0:
1058			raise ValueError(_("Could not set type in port context for %s/%s") % (proto, port))
1059
1060		if (is_mls_enabled == 1) and (serange != ""):
1061			rc = semanage_context_set_mls(self.sh, con, serange)
1062			if rc < 0:
1063				raise ValueError(_("Could not set mls fields in port context for %s/%s") % (proto, port))
1064
1065		rc = semanage_port_set_con(self.sh, p, con)
1066		if rc < 0:
1067			raise ValueError(_("Could not set port context for %s/%s") % (proto, port))
1068
1069		rc = semanage_port_modify_local(self.sh, k, p)
1070		if rc < 0:
1071			raise ValueError(_("Could not add port %s/%s") % (proto, port))
1072
1073		semanage_context_free(con)
1074		semanage_port_key_free(k)
1075		semanage_port_free(p)
1076
1077	def add(self, port, proto, serange, type):
1078                self.begin()
1079                self.__add(port, proto, serange, type)
1080                self.commit()
1081
1082	def __modify(self, port, proto, serange, setype):
1083		if serange == "" and setype == "":
1084			if is_mls_enabled == 1:
1085				raise ValueError(_("Requires setype or serange"))
1086			else:
1087				raise ValueError(_("Requires setype"))
1088
1089		if setype and setype not in self.valid_types:
1090			raise ValueError(_("Type %s is invalid, must be a port type") % setype)
1091
1092		( k, proto_d, low, high ) = self.__genkey(port, proto)
1093
1094		(rc, exists) = semanage_port_exists(self.sh, k)
1095		if rc < 0:
1096			raise ValueError(_("Could not check if port %s/%s is defined") % (proto, port))
1097		if not exists:
1098			raise ValueError(_("Port %s/%s is not defined") % (proto,port))
1099
1100		(rc, p) = semanage_port_query(self.sh, k)
1101		if rc < 0:
1102			raise ValueError(_("Could not query port %s/%s") % (proto, port))
1103
1104		con = semanage_port_get_con(p)
1105
1106		if (is_mls_enabled == 1) and (serange != ""):
1107			semanage_context_set_mls(self.sh, con, untranslate(serange))
1108		if setype != "":
1109			semanage_context_set_type(self.sh, con, setype)
1110
1111		rc = semanage_port_modify_local(self.sh, k, p)
1112		if rc < 0:
1113			raise ValueError(_("Could not modify port %s/%s") % (proto, port))
1114
1115		semanage_port_key_free(k)
1116		semanage_port_free(p)
1117
1118	def modify(self, port, proto, serange, setype):
1119                self.begin()
1120                self.__modify(port, proto, serange, setype)
1121                self.commit()
1122
1123	def deleteall(self):
1124		(rc, plist) = semanage_port_list_local(self.sh)
1125		if rc < 0:
1126			raise ValueError(_("Could not list the ports"))
1127
1128                self.begin()
1129
1130		for port in plist:
1131                       proto = semanage_port_get_proto(port)
1132                       proto_str = semanage_port_get_proto_str(proto)
1133                       low = semanage_port_get_low(port)
1134                       high = semanage_port_get_high(port)
1135                       port_str = "%s-%s" % (low, high)
1136                       ( k, proto_d, low, high ) = self.__genkey(port_str , proto_str)
1137                       if rc < 0:
1138                              raise ValueError(_("Could not create a key for %s") % port_str)
1139
1140                       rc = semanage_port_del_local(self.sh, k)
1141                       if rc < 0:
1142                              raise ValueError(_("Could not delete the port %s") % port_str)
1143                       semanage_port_key_free(k)
1144
1145                self.commit()
1146
1147	def __delete(self, port, proto):
1148		( k, proto_d, low, high ) = self.__genkey(port, proto)
1149		(rc, exists) = semanage_port_exists(self.sh, k)
1150		if rc < 0:
1151			raise ValueError(_("Could not check if port %s/%s is defined") % (proto, port))
1152		if not exists:
1153			raise ValueError(_("Port %s/%s is not defined") % (proto, port))
1154
1155		(rc, exists) = semanage_port_exists_local(self.sh, k)
1156		if rc < 0:
1157			raise ValueError(_("Could not check if port %s/%s is defined") % (proto, port))
1158		if not exists:
1159			raise ValueError(_("Port %s/%s is defined in policy, cannot be deleted") % (proto, port))
1160
1161		rc = semanage_port_del_local(self.sh, k)
1162		if rc < 0:
1163			raise ValueError(_("Could not delete port %s/%s") % (proto, port))
1164
1165		semanage_port_key_free(k)
1166
1167	def delete(self, port, proto):
1168                self.begin()
1169                self.__delete(port, proto)
1170                self.commit()
1171
1172	def get_all(self, locallist = 0):
1173		ddict = {}
1174                if locallist:
1175                       (rc, self.plist) = semanage_port_list_local(self.sh)
1176                else:
1177                       (rc, self.plist) = semanage_port_list(self.sh)
1178		if rc < 0:
1179			raise ValueError(_("Could not list ports"))
1180
1181		for port in self.plist:
1182			con = semanage_port_get_con(port)
1183			ctype = semanage_context_get_type(con)
1184			if ctype == "reserved_port_t":
1185				continue
1186			level = semanage_context_get_mls(con)
1187			proto = semanage_port_get_proto(port)
1188			proto_str = semanage_port_get_proto_str(proto)
1189			low = semanage_port_get_low(port)
1190			high = semanage_port_get_high(port)
1191			ddict[(low, high, proto_str)] = (ctype, level)
1192		return ddict
1193
1194	def get_all_by_type(self, locallist = 0):
1195		ddict = {}
1196                if locallist:
1197                       (rc, self.plist) = semanage_port_list_local(self.sh)
1198                else:
1199                       (rc, self.plist) = semanage_port_list(self.sh)
1200		if rc < 0:
1201			raise ValueError(_("Could not list ports"))
1202
1203		for port in self.plist:
1204			con = semanage_port_get_con(port)
1205			ctype = semanage_context_get_type(con)
1206			if ctype == "reserved_port_t":
1207				continue
1208			proto = semanage_port_get_proto(port)
1209			proto_str = semanage_port_get_proto_str(proto)
1210			low = semanage_port_get_low(port)
1211			high = semanage_port_get_high(port)
1212			if (ctype, proto_str) not in ddict.keys():
1213				ddict[(ctype,proto_str)] = []
1214			if low == high:
1215				ddict[(ctype,proto_str)].append("%d" % low)
1216			else:
1217				ddict[(ctype,proto_str)].append("%d-%d" % (low, high))
1218		return ddict
1219
1220        def customized(self):
1221                l = []
1222		ddict = self.get_all(True)
1223		keys = ddict.keys()
1224		keys.sort()
1225                for k in keys:
1226                       if k[0] == k[1]:
1227                              l.append("-a -t %s -p %s %s" % (ddict[k][0], k[2], k[0]))
1228                       else:
1229                              l.append("-a -t %s -p %s %s-%s" % (ddict[k][0], k[2], k[0], k[1]))
1230                return l
1231
1232	def list(self, heading = 1, locallist = 0):
1233		ddict = self.get_all_by_type(locallist)
1234		keys = ddict.keys()
1235		if len(keys) == 0:
1236			return
1237		keys.sort()
1238
1239		if heading:
1240			print "%-30s %-8s %s\n" % (_("SELinux Port Type"), _("Proto"), _("Port Number"))
1241		for i in keys:
1242			rec = "%-30s %-8s " % i
1243			rec += "%s" % ddict[i][0]
1244			for p in ddict[i][1:]:
1245				rec += ", %s" % p
1246			print rec
1247
1248class nodeRecords(semanageRecords):
1249       try:
1250	       valid_types =  sepolicy.info(sepolicy.ATTRIBUTE,"node_type")[0]["types"]
1251       except RuntimeError:
1252	       valid_types = []
1253
1254       def __init__(self, store = ""):
1255               semanageRecords.__init__(self,store)
1256               self.protocol = ["ipv4", "ipv6"]
1257
1258       def validate(self, addr, mask, protocol):
1259               newaddr=addr
1260               newmask=mask
1261               newprotocol=""
1262
1263               if addr == "":
1264                       raise ValueError(_("Node Address is required"))
1265
1266               # verify valid comination
1267               if len(mask) == 0 or mask[0] == "/":
1268                       i = IP(addr + mask)
1269                       newaddr = i.strNormal(0)
1270                       newmask = str(i.netmask())
1271                       if newmask == "0.0.0.0" and i.version() == 6:
1272                               newmask = "::"
1273
1274                       protocol = "ipv%d" % i.version()
1275
1276               try:
1277                      newprotocol = self.protocol.index(protocol)
1278               except:
1279                      raise ValueError(_("Unknown or missing protocol"))
1280
1281               return newaddr, newmask, newprotocol
1282
1283       def __add(self, addr, mask, proto, serange, ctype):
1284               addr, mask, proto = self.validate(addr, mask, proto)
1285
1286               if is_mls_enabled == 1:
1287                       if serange == "":
1288                               serange = "s0"
1289                       else:
1290                               serange = untranslate(serange)
1291
1292               if ctype == "":
1293                       raise ValueError(_("SELinux node type is required"))
1294
1295	       if ctype not in self.valid_types:
1296		       raise ValueError(_("Type %s is invalid, must be a node type") % ctype)
1297
1298               (rc, k) = semanage_node_key_create(self.sh, addr, mask, proto)
1299               if rc < 0:
1300                       raise ValueError(_("Could not create key for %s") % addr)
1301               if rc < 0:
1302                       raise ValueError(_("Could not check if addr %s is defined") % addr)
1303
1304               (rc, exists) = semanage_node_exists(self.sh, k)
1305               if exists:
1306                       raise ValueError(_("Addr %s already defined") % addr)
1307
1308               (rc, node) = semanage_node_create(self.sh)
1309               if rc < 0:
1310                       raise ValueError(_("Could not create addr for %s") % addr)
1311               semanage_node_set_proto(node, proto)
1312
1313               rc = semanage_node_set_addr(self.sh, node, proto, addr)
1314               (rc, con) = semanage_context_create(self.sh)
1315               if rc < 0:
1316                       raise ValueError(_("Could not create context for %s") % addr)
1317
1318               rc = semanage_node_set_mask(self.sh, node, proto, mask)
1319               if rc < 0:
1320                       raise ValueError(_("Could not set mask for %s") % addr)
1321
1322               rc = semanage_context_set_user(self.sh, con, "system_u")
1323               if rc < 0:
1324                       raise ValueError(_("Could not set user in addr context for %s") % addr)
1325
1326               rc = semanage_context_set_role(self.sh, con, "object_r")
1327               if rc < 0:
1328                       raise ValueError(_("Could not set role in addr context for %s") % addr)
1329
1330               rc = semanage_context_set_type(self.sh, con, ctype)
1331               if rc < 0:
1332                       raise ValueError(_("Could not set type in addr context for %s") % addr)
1333
1334               if (is_mls_enabled == 1) and (serange != ""):
1335                       rc = semanage_context_set_mls(self.sh, con, serange)
1336                       if rc < 0:
1337                               raise ValueError(_("Could not set mls fields in addr context for %s") % addr)
1338
1339               rc = semanage_node_set_con(self.sh, node, con)
1340               if rc < 0:
1341                       raise ValueError(_("Could not set addr context for %s") % addr)
1342
1343               rc = semanage_node_modify_local(self.sh, k, node)
1344               if rc < 0:
1345                       raise ValueError(_("Could not add addr %s") % addr)
1346
1347               semanage_context_free(con)
1348               semanage_node_key_free(k)
1349               semanage_node_free(node)
1350
1351       def add(self, addr, mask, proto, serange, ctype):
1352                self.begin()
1353                self.__add(addr, mask, proto, serange, ctype)
1354                self.commit()
1355
1356       def __modify(self, addr, mask, proto, serange, setype):
1357               addr, mask, proto = self.validate(addr, mask, proto)
1358
1359               if serange == "" and setype == "":
1360                       raise ValueError(_("Requires setype or serange"))
1361
1362	       if setype and setype not in self.valid_types:
1363		       raise ValueError(_("Type %s is invalid, must be a node type") % setype)
1364
1365               (rc, k) = semanage_node_key_create(self.sh, addr, mask, proto)
1366               if rc < 0:
1367                       raise ValueError(_("Could not create key for %s") % addr)
1368
1369               (rc, exists) = semanage_node_exists(self.sh, k)
1370               if rc < 0:
1371                       raise ValueError(_("Could not check if addr %s is defined") % addr)
1372               if not exists:
1373                       raise ValueError(_("Addr %s is not defined") % addr)
1374
1375               (rc, node) = semanage_node_query(self.sh, k)
1376               if rc < 0:
1377                       raise ValueError(_("Could not query addr %s") % addr)
1378
1379               con = semanage_node_get_con(node)
1380               if (is_mls_enabled == 1) and (serange != ""):
1381                       semanage_context_set_mls(self.sh, con, untranslate(serange))
1382               if setype != "":
1383                       semanage_context_set_type(self.sh, con, setype)
1384
1385               rc = semanage_node_modify_local(self.sh, k, node)
1386               if rc < 0:
1387                       raise ValueError(_("Could not modify addr %s") % addr)
1388
1389               semanage_node_key_free(k)
1390               semanage_node_free(node)
1391
1392       def modify(self, addr, mask, proto, serange, setype):
1393                self.begin()
1394                self.__modify(addr, mask, proto, serange, setype)
1395                self.commit()
1396
1397       def __delete(self, addr, mask, proto):
1398
1399               addr, mask, proto = self.validate(addr, mask, proto)
1400
1401               (rc, k) = semanage_node_key_create(self.sh, addr, mask, proto)
1402               if rc < 0:
1403                       raise ValueError(_("Could not create key for %s") % addr)
1404
1405               (rc, exists) = semanage_node_exists(self.sh, k)
1406               if rc < 0:
1407                       raise ValueError(_("Could not check if addr %s is defined") % addr)
1408               if not exists:
1409                       raise ValueError(_("Addr %s is not defined") % addr)
1410
1411               (rc, exists) = semanage_node_exists_local(self.sh, k)
1412               if rc < 0:
1413                       raise ValueError(_("Could not check if addr %s is defined") % addr)
1414               if not exists:
1415                       raise ValueError(_("Addr %s is defined in policy, cannot be deleted") % addr)
1416
1417               rc = semanage_node_del_local(self.sh, k)
1418               if rc < 0:
1419                       raise ValueError(_("Could not delete addr %s") % addr)
1420
1421               semanage_node_key_free(k)
1422
1423       def delete(self, addr, mask, proto):
1424              self.begin()
1425              self.__delete(addr, mask, proto)
1426              self.commit()
1427
1428       def deleteall(self):
1429              (rc, nlist) = semanage_node_list_local(self.sh)
1430              if rc < 0:
1431                     raise ValueError(_("Could not deleteall node mappings"))
1432
1433              self.begin()
1434              for node in nlist:
1435                     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)])
1436              self.commit()
1437
1438       def get_all(self, locallist = 0):
1439               ddict = {}
1440	       if locallist :
1441			(rc, self.ilist) = semanage_node_list_local(self.sh)
1442	       else:
1443	                (rc, self.ilist) = semanage_node_list(self.sh)
1444               if rc < 0:
1445                       raise ValueError(_("Could not list addrs"))
1446
1447               for node in self.ilist:
1448                       con = semanage_node_get_con(node)
1449                       addr = semanage_node_get_addr(self.sh, node)
1450                       mask = semanage_node_get_mask(self.sh, node)
1451                       proto = self.protocol[semanage_node_get_proto(node)]
1452                       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))
1453
1454               return ddict
1455
1456       def customized(self):
1457               l = []
1458               ddict = self.get_all(True)
1459               keys = ddict.keys()
1460               keys.sort()
1461               for k in keys:
1462                      l.append("-a -M %s -p %s -t %s %s" % (k[1], k[2],ddict[k][2], k[0]))
1463               return l
1464
1465       def list(self, heading = 1, locallist = 0):
1466               ddict = self.get_all(locallist)
1467               keys = ddict.keys()
1468	       if len(keys) == 0:
1469		       return
1470               keys.sort()
1471
1472               if heading:
1473                       print "%-18s %-18s %-5s %-5s\n" % ("IP Address", "Netmask", "Protocol", "Context")
1474               if is_mls_enabled:
1475			for k in keys:
1476				val = ''
1477				for fields in k:
1478					val = val + '\t' + str(fields)
1479                                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))
1480               else:
1481                       for k in keys:
1482                               print "%-18s %-18s %-5s %s:%s:%s " % (k[0],k[1],k[2],ddict[k][0], ddict[k][1],ddict[k][2])
1483
1484
1485class interfaceRecords(semanageRecords):
1486	def __init__(self, store = ""):
1487		semanageRecords.__init__(self, store)
1488
1489	def __add(self, interface, serange, ctype):
1490		if is_mls_enabled == 1:
1491			if serange == "":
1492				serange = "s0"
1493			else:
1494				serange = untranslate(serange)
1495
1496		if ctype == "":
1497			raise ValueError(_("SELinux Type is required"))
1498
1499		(rc, k) = semanage_iface_key_create(self.sh, interface)
1500		if rc < 0:
1501			raise ValueError(_("Could not create key for %s") % interface)
1502
1503		(rc, exists) = semanage_iface_exists(self.sh, k)
1504		if rc < 0:
1505			raise ValueError(_("Could not check if interface %s is defined") % interface)
1506		if exists:
1507			raise ValueError(_("Interface %s already defined") % interface)
1508
1509		(rc, iface) = semanage_iface_create(self.sh)
1510		if rc < 0:
1511			raise ValueError(_("Could not create interface for %s") % interface)
1512
1513		rc = semanage_iface_set_name(self.sh, iface, interface)
1514		(rc, con) = semanage_context_create(self.sh)
1515		if rc < 0:
1516			raise ValueError(_("Could not create context for %s") % interface)
1517
1518		rc = semanage_context_set_user(self.sh, con, "system_u")
1519		if rc < 0:
1520			raise ValueError(_("Could not set user in interface context for %s") % interface)
1521
1522		rc = semanage_context_set_role(self.sh, con, "object_r")
1523		if rc < 0:
1524			raise ValueError(_("Could not set role in interface context for %s") % interface)
1525
1526		rc = semanage_context_set_type(self.sh, con, ctype)
1527		if rc < 0:
1528			raise ValueError(_("Could not set type in interface context for %s") % interface)
1529
1530		if (is_mls_enabled == 1) and (serange != ""):
1531			rc = semanage_context_set_mls(self.sh, con, serange)
1532			if rc < 0:
1533				raise ValueError(_("Could not set mls fields in interface context for %s") % interface)
1534
1535		rc = semanage_iface_set_ifcon(self.sh, iface, con)
1536		if rc < 0:
1537			raise ValueError(_("Could not set interface context for %s") % interface)
1538
1539		rc = semanage_iface_set_msgcon(self.sh, iface, con)
1540		if rc < 0:
1541			raise ValueError(_("Could not set message context for %s") % interface)
1542
1543		rc = semanage_iface_modify_local(self.sh, k, iface)
1544		if rc < 0:
1545			raise ValueError(_("Could not add interface %s") % interface)
1546
1547		semanage_context_free(con)
1548		semanage_iface_key_free(k)
1549		semanage_iface_free(iface)
1550
1551	def add(self, interface, serange, ctype):
1552                self.begin()
1553                self.__add(interface, serange, ctype)
1554                self.commit()
1555
1556	def __modify(self, interface, serange, setype):
1557		if serange == "" and setype == "":
1558			raise ValueError(_("Requires setype or serange"))
1559
1560		(rc, k) = semanage_iface_key_create(self.sh, interface)
1561		if rc < 0:
1562			raise ValueError(_("Could not create key for %s") % interface)
1563
1564		(rc, exists) = semanage_iface_exists(self.sh, k)
1565		if rc < 0:
1566			raise ValueError(_("Could not check if interface %s is defined") % interface)
1567		if not exists:
1568			raise ValueError(_("Interface %s is not defined") % interface)
1569
1570		(rc, iface) = semanage_iface_query(self.sh, k)
1571		if rc < 0:
1572			raise ValueError(_("Could not query interface %s") % interface)
1573
1574		con = semanage_iface_get_ifcon(iface)
1575
1576		if (is_mls_enabled == 1) and (serange != ""):
1577			semanage_context_set_mls(self.sh, con, untranslate(serange))
1578		if setype != "":
1579			semanage_context_set_type(self.sh, con, setype)
1580
1581		rc = semanage_iface_modify_local(self.sh, k, iface)
1582		if rc < 0:
1583			raise ValueError(_("Could not modify interface %s") % interface)
1584
1585		semanage_iface_key_free(k)
1586		semanage_iface_free(iface)
1587
1588	def modify(self, interface, serange, setype):
1589                self.begin()
1590                self.__modify(interface, serange, setype)
1591                self.commit()
1592
1593	def __delete(self, interface):
1594		(rc, k) = semanage_iface_key_create(self.sh, interface)
1595		if rc < 0:
1596			raise ValueError(_("Could not create key for %s") % interface)
1597
1598		(rc, exists) = semanage_iface_exists(self.sh, k)
1599		if rc < 0:
1600			raise ValueError(_("Could not check if interface %s is defined") % interface)
1601		if not exists:
1602			raise ValueError(_("Interface %s is not defined") % interface)
1603
1604		(rc, exists) = semanage_iface_exists_local(self.sh, k)
1605		if rc < 0:
1606			raise ValueError(_("Could not check if interface %s is defined") % interface)
1607		if not exists:
1608			raise ValueError(_("Interface %s is defined in policy, cannot be deleted") % interface)
1609
1610		rc = semanage_iface_del_local(self.sh, k)
1611		if rc < 0:
1612			raise ValueError(_("Could not delete interface %s") % interface)
1613
1614		semanage_iface_key_free(k)
1615
1616	def delete(self, interface):
1617                self.begin()
1618                self.__delete(interface)
1619                self.commit()
1620
1621        def deleteall(self):
1622		(rc, ulist) = semanage_iface_list_local(self.sh)
1623		if rc < 0:
1624			raise ValueError(_("Could not delete all interface  mappings"))
1625
1626                self.begin()
1627		for i in ulist:
1628			self.__delete(semanage_iface_get_name(i))
1629                self.commit()
1630
1631	def get_all(self, locallist = 0):
1632		ddict = {}
1633                if locallist:
1634                       (rc, self.ilist) = semanage_iface_list_local(self.sh)
1635                else:
1636                       (rc, self.ilist) = semanage_iface_list(self.sh)
1637		if rc < 0:
1638			raise ValueError(_("Could not list interfaces"))
1639
1640		for interface in self.ilist:
1641			con = semanage_iface_get_ifcon(interface)
1642			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))
1643
1644		return ddict
1645
1646        def customized(self):
1647                l = []
1648                ddict = self.get_all(True)
1649                keys = ddict.keys()
1650                keys.sort()
1651                for k in keys:
1652                       l.append("-a -t %s %s" % (ddict[k][2], k))
1653                return l
1654
1655	def list(self, heading = 1, locallist = 0):
1656		ddict = self.get_all(locallist)
1657		keys = ddict.keys()
1658		if len(keys) == 0:
1659			return
1660		keys.sort()
1661
1662		if heading:
1663			print "%-30s %s\n" % (_("SELinux Interface"), _("Context"))
1664		if is_mls_enabled:
1665			for k in keys:
1666				print "%-30s %s:%s:%s:%s " % (k,ddict[k][0], ddict[k][1],ddict[k][2], translate(ddict[k][3], False))
1667		else:
1668			for k in keys:
1669				print "%-30s %s:%s:%s " % (k,ddict[k][0], ddict[k][1],ddict[k][2])
1670
1671class fcontextRecords(semanageRecords):
1672	try:
1673		valid_types =  sepolicy.info(sepolicy.ATTRIBUTE,"file_type")[0]["types"]
1674		valid_types +=  sepolicy.info(sepolicy.ATTRIBUTE,"device_node")[0]["types"]
1675                valid_types.append("<<none>>")
1676	except RuntimeError:
1677		valid_types = []
1678
1679	def __init__(self, store = ""):
1680		semanageRecords.__init__(self, store)
1681                self.equiv = {}
1682                self.equiv_dist = {}
1683                self.equal_ind = False
1684                try:
1685                       fd = open(selinux.selinux_file_context_subs_path(), "r")
1686                       for i in fd.readlines():
1687                              i = i.strip()
1688                              if len(i) == 0:
1689                                     continue
1690                              if i.startswith("#"):
1691                                     continue
1692                              target, substitute = i.split()
1693                              self.equiv[target] = substitute
1694                       fd.close()
1695                except IOError:
1696                       pass
1697                try:
1698                       fd = open(selinux.selinux_file_context_subs_dist_path(), "r")
1699                       for i in fd.readlines():
1700                              i = i.strip()
1701                              if len(i) == 0:
1702                                     continue
1703                              if i.startswith("#"):
1704                                     continue
1705                              target, substitute = i.split()
1706                              self.equiv_dist[target] = substitute
1707                       fd.close()
1708                except IOError:
1709                       pass
1710
1711        def commit(self):
1712                if self.equal_ind:
1713                       subs_file = selinux.selinux_file_context_subs_path()
1714                       tmpfile = "%s.tmp" % subs_file
1715                       fd = open(tmpfile, "w")
1716                       for target in self.equiv.keys():
1717                              fd.write("%s %s\n" % (target, self.equiv[target]))
1718                       fd.close()
1719                       try:
1720                              os.chmod(tmpfile, os.stat(subs_file)[stat.ST_MODE])
1721                       except:
1722                              pass
1723                       os.rename(tmpfile,subs_file)
1724                       self.equal_ind = False
1725		semanageRecords.commit(self)
1726
1727        def add_equal(self, target, substitute):
1728                self.begin()
1729                if target != "/" and target[-1] == "/":
1730                        raise ValueError(_("Target %s is not valid. Target is not allowed to end with '/'") % target )
1731
1732                if substitute != "/" and substitute[-1] == "/":
1733                       raise ValueError(_("Substiture %s is not valid. Substitute is not allowed to end with '/'") % substitute )
1734
1735                if target in self.equiv.keys():
1736                       raise ValueError(_("Equivalence class for %s already exists") % target)
1737                self.validate(target)
1738
1739		for fdict in (self.equiv, self.equiv_dist):
1740			for i in fdict:
1741				if i.startswith(target + "/"):
1742					raise ValueError(_("File spec %s conflicts with equivalency rule '%s %s'") % (target, i, fdict[i]))
1743
1744                self.equiv[target] = substitute
1745                self.equal_ind = True
1746                self.commit()
1747
1748        def modify_equal(self, target, substitute):
1749                self.begin()
1750                if target not in self.equiv.keys():
1751                       raise ValueError(_("Equivalence class for %s does not exists") % target)
1752                self.equiv[target] = substitute
1753                self.equal_ind = True
1754                self.commit()
1755
1756        def createcon(self, target, seuser = "system_u"):
1757                (rc, con) = semanage_context_create(self.sh)
1758                if rc < 0:
1759                       raise ValueError(_("Could not create context for %s") % target)
1760		if seuser == "":
1761			seuser = "system_u"
1762
1763                rc = semanage_context_set_user(self.sh, con, seuser)
1764                if rc < 0:
1765                       raise ValueError(_("Could not set user in file context for %s") % target)
1766
1767                rc = semanage_context_set_role(self.sh, con, "object_r")
1768                if rc < 0:
1769                       raise ValueError(_("Could not set role in file context for %s") % target)
1770
1771		if is_mls_enabled == 1:
1772                       rc = semanage_context_set_mls(self.sh, con, "s0")
1773                       if rc < 0:
1774                              raise ValueError(_("Could not set mls fields in file context for %s") % target)
1775
1776                return con
1777
1778        def validate(self, target):
1779               if target == "" or target.find("\n") >= 0:
1780                      raise ValueError(_("Invalid file specification"))
1781               if target.find(" ") != -1:
1782                      raise ValueError(_("File specification can not include spaces"))
1783	       for fdict in (self.equiv, self.equiv_dist):
1784		       for i in fdict:
1785			       if target.startswith(i+"/"):
1786				       t = re.sub(i, fdict[i], target)
1787				       raise ValueError(_("File spec %s conflicts with equivalency rule '%s %s'; Try adding '%s' instead") % (target, i, fdict[i], t))
1788
1789
1790	def __add(self, target, type, ftype = "", serange = "", seuser = "system_u"):
1791                self.validate(target)
1792
1793		if is_mls_enabled == 1:
1794                       serange = untranslate(serange)
1795
1796		if type == "":
1797			raise ValueError(_("SELinux Type is required"))
1798
1799		if type not in self.valid_types:
1800			raise ValueError(_("Type %s is invalid, must be a file or device type") % type)
1801
1802		(rc, k) = semanage_fcontext_key_create(self.sh, target, file_types[ftype])
1803		if rc < 0:
1804			raise ValueError(_("Could not create key for %s") % target)
1805
1806		(rc, exists) = semanage_fcontext_exists(self.sh, k)
1807		if rc < 0:
1808			raise ValueError(_("Could not check if file context for %s is defined") % target)
1809
1810		if not exists:
1811                       (rc, exists) = semanage_fcontext_exists_local(self.sh, k)
1812                       if rc < 0:
1813                              raise ValueError(_("Could not check if file context for %s is defined") % target)
1814
1815                if exists:
1816                       raise ValueError(_("File context for %s already defined") % target)
1817
1818		(rc, fcontext) = semanage_fcontext_create(self.sh)
1819		if rc < 0:
1820			raise ValueError(_("Could not create file context for %s") % target)
1821
1822		rc = semanage_fcontext_set_expr(self.sh, fcontext, target)
1823                if type != "<<none>>":
1824                       con = self.createcon(target, seuser)
1825
1826                       rc = semanage_context_set_type(self.sh, con, type)
1827                       if rc < 0:
1828                              raise ValueError(_("Could not set type in file context for %s") % target)
1829
1830                       if (is_mls_enabled == 1) and (serange != ""):
1831                              rc = semanage_context_set_mls(self.sh, con, serange)
1832                              if rc < 0:
1833                                     raise ValueError(_("Could not set mls fields in file context for %s") % target)
1834                       rc = semanage_fcontext_set_con(self.sh, fcontext, con)
1835                       if rc < 0:
1836                              raise ValueError(_("Could not set file context for %s") % target)
1837
1838		semanage_fcontext_set_type(fcontext, file_types[ftype])
1839
1840		rc = semanage_fcontext_modify_local(self.sh, k, fcontext)
1841		if rc < 0:
1842			raise ValueError(_("Could not add file context for %s") % target)
1843
1844                if type != "<<none>>":
1845                       semanage_context_free(con)
1846		semanage_fcontext_key_free(k)
1847		semanage_fcontext_free(fcontext)
1848
1849	def add(self, target, type, ftype = "", serange = "", seuser = "system_u"):
1850                self.begin()
1851                self.__add(target, type, ftype, serange, seuser)
1852                self.commit()
1853
1854	def __modify(self, target, setype, ftype, serange, seuser):
1855		if serange == "" and setype == "" and seuser == "":
1856			raise ValueError(_("Requires setype, serange or seuser"))
1857		if setype and setype not in self.valid_types:
1858			raise ValueError(_("Type %s is invalid, must be a port type") % setype)
1859
1860                self.validate(target)
1861
1862		(rc, k) = semanage_fcontext_key_create(self.sh, target, file_types[ftype])
1863		if rc < 0:
1864			raise ValueError(_("Could not create a key for %s") % target)
1865
1866		(rc, exists) = semanage_fcontext_exists(self.sh, k)
1867		if rc < 0:
1868			raise ValueError(_("Could not check if file context for %s is defined") % target)
1869		if not exists:
1870                       (rc, exists) = semanage_fcontext_exists_local(self.sh, k)
1871                       if not exists:
1872                              raise ValueError(_("File context for %s is not defined") % target)
1873
1874		(rc, fcontext) = semanage_fcontext_query_local(self.sh, k)
1875		if rc < 0:
1876                       (rc, fcontext) = semanage_fcontext_query(self.sh, k)
1877                       if rc < 0:
1878                              raise ValueError(_("Could not query file context for %s") % target)
1879
1880                if setype != "<<none>>":
1881                       con = semanage_fcontext_get_con(fcontext)
1882
1883                       if con == None:
1884                              con = self.createcon(target)
1885
1886                       if (is_mls_enabled == 1) and (serange != ""):
1887                              semanage_context_set_mls(self.sh, con, untranslate(serange))
1888                       if seuser != "":
1889                              semanage_context_set_user(self.sh, con, seuser)
1890
1891                       if setype != "":
1892                              semanage_context_set_type(self.sh, con, setype)
1893
1894                       rc = semanage_fcontext_set_con(self.sh, fcontext, con)
1895                       if rc < 0:
1896                              raise ValueError(_("Could not set file context for %s") % target)
1897                else:
1898                       rc = semanage_fcontext_set_con(self.sh, fcontext, None)
1899                       if rc < 0:
1900                              raise ValueError(_("Could not set file context for %s") % target)
1901
1902		rc = semanage_fcontext_modify_local(self.sh, k, fcontext)
1903		if rc < 0:
1904			raise ValueError(_("Could not modify file context for %s") % target)
1905
1906		semanage_fcontext_key_free(k)
1907		semanage_fcontext_free(fcontext)
1908
1909	def modify(self, target, setype, ftype, serange, seuser):
1910                self.begin()
1911                self.__modify(target, setype, ftype, serange, seuser)
1912                self.commit()
1913
1914	def deleteall(self):
1915		(rc, flist) = semanage_fcontext_list_local(self.sh)
1916		if rc < 0:
1917			raise ValueError(_("Could not list the file contexts"))
1918
1919                self.begin()
1920
1921		for fcontext in flist:
1922                       target = semanage_fcontext_get_expr(fcontext)
1923                       ftype = semanage_fcontext_get_type(fcontext)
1924                       ftype_str = semanage_fcontext_get_type_str(ftype)
1925                       (rc, k) = semanage_fcontext_key_create(self.sh, target, file_types[ftype_str])
1926                       if rc < 0:
1927                              raise ValueError(_("Could not create a key for %s") % target)
1928
1929                       rc = semanage_fcontext_del_local(self.sh, k)
1930                       if rc < 0:
1931                              raise ValueError(_("Could not delete the file context %s") % target)
1932                       semanage_fcontext_key_free(k)
1933
1934                self.equiv = {}
1935                self.equal_ind = True
1936                self.commit()
1937
1938	def __delete(self, target, ftype):
1939                if target in self.equiv.keys():
1940                       self.equiv.pop(target)
1941                       self.equal_ind = True
1942                       return
1943
1944		(rc,k) = semanage_fcontext_key_create(self.sh, target, file_types[ftype])
1945		if rc < 0:
1946			raise ValueError(_("Could not create a key for %s") % target)
1947
1948		(rc, exists) = semanage_fcontext_exists_local(self.sh, k)
1949		if rc < 0:
1950			raise ValueError(_("Could not check if file context for %s is defined") % target)
1951		if not exists:
1952			(rc, exists) = semanage_fcontext_exists(self.sh, k)
1953			if rc < 0:
1954				raise ValueError(_("Could not check if file context for %s is defined") % target)
1955			if exists:
1956				raise ValueError(_("File context for %s is defined in policy, cannot be deleted") % target)
1957			else:
1958				raise ValueError(_("File context for %s is not defined") % target)
1959
1960		rc = semanage_fcontext_del_local(self.sh, k)
1961		if rc < 0:
1962			raise ValueError(_("Could not delete file context for %s") % target)
1963
1964		semanage_fcontext_key_free(k)
1965
1966	def delete(self, target, ftype):
1967                self.begin()
1968                self.__delete( target, ftype)
1969                self.commit()
1970
1971	def get_all(self, locallist = 0):
1972                if locallist:
1973                       (rc, self.flist) = semanage_fcontext_list_local(self.sh)
1974                else:
1975                       (rc, self.flist) = semanage_fcontext_list(self.sh)
1976                       if rc < 0:
1977                              raise ValueError(_("Could not list file contexts"))
1978
1979                       (rc, fclocal) = semanage_fcontext_list_local(self.sh)
1980                       if rc < 0:
1981                              raise ValueError(_("Could not list local file contexts"))
1982
1983                       self.flist += fclocal
1984
1985                ddict = {}
1986		for fcontext in self.flist:
1987			expr = semanage_fcontext_get_expr(fcontext)
1988			ftype = semanage_fcontext_get_type(fcontext)
1989			ftype_str = semanage_fcontext_get_type_str(ftype)
1990			con = semanage_fcontext_get_con(fcontext)
1991			if con:
1992                               ddict[(expr, ftype_str)] = (semanage_context_get_user(con), semanage_context_get_role(con), semanage_context_get_type(con), semanage_context_get_mls(con))
1993			else:
1994				ddict[(expr, ftype_str)] = con
1995
1996		return ddict
1997
1998        def customized(self):
1999               l = []
2000               fcon_dict = self.get_all(True)
2001               keys = fcon_dict.keys()
2002               keys.sort()
2003               for k in keys:
2004                      if fcon_dict[k]:
2005                             l.append("-a -f %s -t %s '%s'" % (file_type_str_to_option[k[1]], fcon_dict[k][2], k[0]))
2006
2007	       if len(self.equiv):
2008                      for target in self.equiv.keys():
2009			     l.append("-a -e %s %s" % (self.equiv[target], target))
2010               return l
2011
2012	def list(self, heading = 1, locallist = 0 ):
2013		fcon_dict = self.get_all(locallist)
2014                keys = fcon_dict.keys()
2015		if len(keys) != 0:
2016			keys.sort()
2017			if heading:
2018				print "%-50s %-18s %s\n" % (_("SELinux fcontext"), _("type"), _("Context"))
2019			for k in keys:
2020				if fcon_dict[k]:
2021					if is_mls_enabled:
2022						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))
2023					else:
2024						print "%-50s %-18s %s:%s:%s " % (k[0], k[1], fcon_dict[k][0], fcon_dict[k][1],fcon_dict[k][2])
2025				else:
2026					print "%-50s %-18s <<None>>" % (k[0], k[1])
2027
2028		if len(self.equiv_dist):
2029		       if not locallist:
2030			       if heading:
2031				       print _("\nSELinux Distribution fcontext Equivalence \n")
2032			       for target in self.equiv_dist.keys():
2033				       print "%s = %s" % (target, self.equiv_dist[target])
2034		if len(self.equiv):
2035                       if heading:
2036                              print _("\nSELinux Local fcontext Equivalence \n")
2037
2038                       for target in self.equiv.keys():
2039                              print "%s = %s" % (target, self.equiv[target])
2040
2041class booleanRecords(semanageRecords):
2042	def __init__(self, store = ""):
2043		semanageRecords.__init__(self, store)
2044                self.dict = {}
2045                self.dict["TRUE"] = 1
2046                self.dict["FALSE"] = 0
2047                self.dict["ON"] = 1
2048                self.dict["OFF"] = 0
2049                self.dict["1"] = 1
2050                self.dict["0"] = 0
2051
2052		try:
2053			rc, self.current_booleans = selinux.security_get_boolean_names()
2054			rc, ptype = selinux.selinux_getpolicytype()
2055		except:
2056			self.current_booleans = []
2057			ptype = None
2058
2059		if self.store == None or self.store == ptype:
2060			self.modify_local = True
2061		else:
2062			self.modify_local = False
2063
2064	def __mod(self, name, value):
2065                name = selinux.selinux_boolean_sub(name)
2066
2067                (rc, k) = semanage_bool_key_create(self.sh, name)
2068                if rc < 0:
2069                       raise ValueError(_("Could not create a key for %s") % name)
2070                (rc, exists) = semanage_bool_exists(self.sh, k)
2071                if rc < 0:
2072                       raise ValueError(_("Could not check if boolean %s is defined") % name)
2073                if not exists:
2074                       raise ValueError(_("Boolean %s is not defined") % name)
2075
2076                (rc, b) = semanage_bool_query(self.sh, k)
2077                if rc < 0:
2078                       raise ValueError(_("Could not query file context %s") % name)
2079
2080                if value.upper() in self.dict:
2081                       semanage_bool_set_value(b, self.dict[value.upper()])
2082                else:
2083                       raise ValueError(_("You must specify one of the following values: %s") % ", ".join(self.dict.keys()) )
2084
2085		if self.modify_local and name in self.current_booleans:
2086			rc = semanage_bool_set_active(self.sh, k, b)
2087			if rc < 0:
2088				raise ValueError(_("Could not set active value of boolean %s") % name)
2089                rc = semanage_bool_modify_local(self.sh, k, b)
2090                if rc < 0:
2091                       raise ValueError(_("Could not modify boolean %s") % name)
2092		semanage_bool_key_free(k)
2093		semanage_bool_free(b)
2094
2095	def modify(self, name, value = None, use_file = False):
2096                self.begin()
2097                if use_file:
2098                       fd = open(name)
2099                       for b in fd.read().split("\n"):
2100                              b = b.strip()
2101                              if len(b) == 0:
2102                                     continue
2103
2104                              try:
2105                                     boolname, val = b.split("=")
2106                              except ValueError:
2107                                     raise ValueError(_("Bad format %s: Record %s" % ( name, b) ))
2108                              self.__mod(boolname.strip(), val.strip())
2109                       fd.close()
2110                else:
2111                       self.__mod(name, value)
2112
2113                self.commit()
2114
2115	def __delete(self, name):
2116                name = selinux.selinux_boolean_sub(name)
2117
2118                (rc, k) = semanage_bool_key_create(self.sh, name)
2119                if rc < 0:
2120                      raise ValueError(_("Could not create a key for %s") % name)
2121		(rc, exists) = semanage_bool_exists(self.sh, k)
2122		if rc < 0:
2123			raise ValueError(_("Could not check if boolean %s is defined") % name)
2124		if not exists:
2125			raise ValueError(_("Boolean %s is not defined") % name)
2126
2127		(rc, exists) = semanage_bool_exists_local(self.sh, k)
2128		if rc < 0:
2129			raise ValueError(_("Could not check if boolean %s is defined") % name)
2130		if not exists:
2131			raise ValueError(_("Boolean %s is defined in policy, cannot be deleted") % name)
2132
2133		rc = semanage_bool_del_local(self.sh, k)
2134		if rc < 0:
2135			raise ValueError(_("Could not delete boolean %s") % name)
2136
2137		semanage_bool_key_free(k)
2138
2139	def delete(self, name):
2140                self.begin()
2141                self.__delete(name)
2142                self.commit()
2143
2144	def deleteall(self):
2145		(rc, self.blist) = semanage_bool_list_local(self.sh)
2146		if rc < 0:
2147			raise ValueError(_("Could not list booleans"))
2148
2149                self.begin()
2150
2151		for boolean in self.blist:
2152                       name = semanage_bool_get_name(boolean)
2153                       self.__delete(name)
2154
2155                self.commit()
2156
2157	def get_all(self, locallist = 0):
2158		ddict = {}
2159                if locallist:
2160                       (rc, self.blist) = semanage_bool_list_local(self.sh)
2161                else:
2162                       (rc, self.blist) = semanage_bool_list(self.sh)
2163		if rc < 0:
2164			raise ValueError(_("Could not list booleans"))
2165
2166		for boolean in self.blist:
2167                       value = []
2168                       name = semanage_bool_get_name(boolean)
2169                       value.append(semanage_bool_get_value(boolean))
2170		       if self.modify_local and boolean in self.current_booleans:
2171			       value.append(selinux.security_get_boolean_pending(name))
2172			       value.append(selinux.security_get_boolean_active(name))
2173		       else:
2174			       value.append(value[0])
2175			       value.append(value[0])
2176                       ddict[name] = value
2177
2178		return ddict
2179
2180        def get_desc(self, name):
2181		name = selinux.selinux_boolean_sub(name)
2182		return boolean_desc(name)
2183
2184        def get_category(self, name):
2185		name = selinux.selinux_boolean_sub(name)
2186		return boolean_category(name)
2187
2188        def customized(self):
2189               l = []
2190               ddict = self.get_all(True)
2191               keys = ddict.keys()
2192               keys.sort()
2193               for k in keys:
2194                      if ddict[k]:
2195                             l.append("-m -%s %s" %  (ddict[k][2], k))
2196               return l
2197
2198	def list(self, heading = True, locallist = False, use_file = False):
2199                on_off = (_("off"), _("on"))
2200		if use_file:
2201                       ddict = self.get_all(locallist)
2202                       keys = ddict.keys()
2203                       for k in keys:
2204                              if ddict[k]:
2205                                     print "%s=%s" %  (k, ddict[k][2])
2206                       return
2207		ddict = self.get_all(locallist)
2208		keys = ddict.keys()
2209		if len(keys) == 0:
2210			return
2211
2212		if heading:
2213			print "%-30s %s  %s %s\n" % (_("SELinux boolean"),_("State"), _("Default"), _("Description"))
2214		for k in keys:
2215			if ddict[k]:
2216				print "%-30s (%-5s,%5s)  %s" %  (k, on_off[selinux.security_get_boolean_active(k)], on_off[ddict[k][2]], self.get_desc(k))
2217