1#!/usr/bin/python -Es
2#
3# Copyright (C) 2013 Red Hat
4# see file 'COPYING' for use and warranty information
5#
6# selinux gui is a tool for the examining and modifying SELinux policy
7#
8#    This program is free software; you can redistribute it and/or
9#    modify it under the terms of the GNU General Public License as
10#    published by the Free Software Foundation; either version 2 of
11#    the License, or (at your option) any later version.
12#
13#    This program is distributed in the hope that it will be useful,
14#    but WITHOUT ANY WARRANTY; without even the implied warranty of
15#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16#    GNU General Public License for more details.
17#
18#    You should have received a copy of the GNU General Public License
19#    along with this program; if not, write to the Free Software
20#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
21#                                        02111-1307  USA
22#
23#    author: Ryan Hallisey rhallisey@redhat.com
24#    author: Dan Walsh dwalsh@redhat.com
25#    author: Miroslav Grepl mgrepl@redhat.com
26#
27#
28
29from gi.repository import Gtk
30from gi.repository import Gdk
31from gi.repository import GLib
32from sepolicy.sedbus import SELinuxDBus
33import sys
34import sepolicy
35import selinux
36from selinux import DISABLED, PERMISSIVE, ENFORCING
37import sepolicy.network
38import sepolicy.manpage
39import dbus
40import time
41import os, re
42import gettext
43import unicodedata
44
45PROGNAME="policycoreutils"
46gettext.bindtextdomain(PROGNAME, "/usr/share/locale")
47gettext.textdomain(PROGNAME)
48try:
49    gettext.install(PROGNAME,
50                    localedir="/usr/share/locale",
51                    unicode=False,
52                    codeset = 'utf-8')
53except IOError:
54    import __builtin__
55    __builtin__.__dict__['_'] = unicode
56
57reverse_file_type_str = {}
58for f in sepolicy.file_type_str:
59    reverse_file_type_str[sepolicy.file_type_str[f]] = f
60
61enabled=[_("No"), _("Yes")]
62action=[_("Disable"), _("Enable")]
63def compare(a, b):
64    return cmp(a.lower(),b.lower())
65
66import distutils.sysconfig
67ADVANCED_LABEL = ( _("Advanced >>"), _("Advanced <<") )
68ADVANCED_SEARCH_LABEL = ( _("Advanced Search >>"), _("Advanced Search <<") )
69OUTBOUND_PAGE = 0
70INBOUND_PAGE = 1
71
72TRANSITIONS_FROM_PAGE=0
73TRANSITIONS_TO_PAGE=1
74TRANSITIONS_FILE_PAGE=2
75
76EXE_PAGE = 0
77WRITABLE_PAGE = 1
78APP_PAGE = 2
79
80BOOLEANS_PAGE=0
81FILES_PAGE=1
82NETWORK_PAGE=2
83TRANSITIONS_PAGE=3
84LOGIN_PAGE=4
85USER_PAGE=5
86LOCKDOWN_PAGE=6
87SYSTEM_PAGE=7
88FILE_EQUIV_PAGE=8
89START_PAGE=9
90
91keys = ["boolean", "fcontext", "fcontext-equiv", "port", "login", "user", "module", "node", "interface" ]
92
93DISABLED_TEXT = _("""<small>
94To change from Disabled to Enforcing mode
95- Change the system mode from Disabled to Permissive
96- Reboot, so that the system can relabel
97- Once the system is working as planned
98  * Change the system mode to Enforcing</small>
99""")
100
101class SELinuxGui():
102
103    def __init__( self , app = None, test = False):
104        self.finish_init = False
105        self.opage = START_PAGE
106        self.dbus = SELinuxDBus()
107        try:
108            customized = self.dbus.customized()
109        except dbus.exceptions.DBusException, e:
110            print e
111            self.quit()
112
113        sepolicy_domains = sepolicy.get_all_domains()
114        sepolicy_domains.sort(compare)
115        if app and app not in sepolicy_domains:
116            self.error(_("%s is not a valid domain" % app))
117            self.quit()
118
119        self.init_cur()
120        self.application = app
121        self.filter_txt = ""
122        builder = Gtk.Builder() # BUILDER OBJ
123        self.code_path = distutils.sysconfig.get_python_lib(plat_specific = True) + "/sepolicy/"
124        glade_file = self.code_path + "sepolicy.glade"
125        builder.add_from_file(glade_file)
126        self.outer_notebook = builder.get_object("outer_notebook")
127        self.window = builder.get_object("SELinux_window")
128        self.main_selection_window = builder.get_object("Main_selection_menu")
129        self.main_advanced_label = builder.get_object("main_advanced_label")
130        self.popup = 0
131        self.applications_selection_button = builder.get_object("applications_selection_button")
132        self.revert_button = builder.get_object("Revert_button")
133        self.busy_cursor = Gdk.Cursor(Gdk.CursorType.WATCH)
134        self.ready_cursor = Gdk.Cursor(Gdk.CursorType.LEFT_PTR)
135        self.initialtype = selinux.selinux_getpolicytype()[1]
136        self.current_popup = None
137        self.import_export = None
138        self.clear_entry = True
139        self.files_add = False
140        self.network_add = False
141
142        self.all_list = []
143        self.installed_list = []
144        self.previously_modified = {}
145
146        # file dialog
147        self.file_dialog = builder.get_object("add_path_dialog")
148        # Error check ***************************************
149        self.error_check_window = builder.get_object("error_check_window")
150        self.error_check_label = builder.get_object("error_check_label")
151        self.invalid_entry = False
152        # Advanced search window ****************************
153        self.advanced_search_window = builder.get_object("advanced_search_window")
154        self.advanced_search_liststore = builder.get_object("Advanced_search_liststore")
155        self.advanced_search_liststore.set_sort_column_id(0, Gtk.SortType.ASCENDING)
156        self.advanced_search_filter = builder.get_object("advanced_filter")
157        self.advanced_search_filter.set_visible_func(self.filter_the_data)
158        self.advanced_filter_entry = builder.get_object("advanced_filter_entry")
159        self.advanced_search_treeview = builder.get_object("advanced_search_treeview")
160        self.advanced_search = False
161
162        # Login Items **************************************
163        self.login_label = builder.get_object("Login_label")
164        self.login_seuser_combobox = builder.get_object("login_seuser_combobox")
165        self.login_seuser_combolist = builder.get_object("login_seuser_liststore")
166        self.login_name_entry = builder.get_object("login_name_entry")
167        self.login_mls_label = builder.get_object("login_mls_label")
168        self.login_mls_entry = builder.get_object("login_mls_entry")
169        self.login_radio_button = builder.get_object("Login_button")
170        self.login_treeview = builder.get_object("login_treeview")
171        self.login_liststore = builder.get_object("login_liststore")
172        self.login_liststore.set_sort_column_id(0, Gtk.SortType.ASCENDING)
173        self.login_filter = builder.get_object("login_filter")
174        self.login_filter.set_visible_func(self.filter_the_data)
175        self.login_popup_window = builder.get_object("login_popup_window")
176        self.login_delete_liststore = builder.get_object("login_delete_liststore")
177        self.login_delete_window = builder.get_object("login_delete_window")
178
179        # Users Items **************************************
180        self.user_popup_window = builder.get_object("user_popup_window")
181        self.user_radio_button = builder.get_object("User_button")
182        self.user_liststore = builder.get_object("user_liststore")
183        self.user_liststore.set_sort_column_id(0, Gtk.SortType.ASCENDING)
184        self.user_filter = builder.get_object("user_filter")
185        self.user_filter.set_visible_func(self.filter_the_data)
186        self.user_treeview = builder.get_object("user_treeview")
187        self.user_roles_combobox = builder.get_object("user_roles_combobox")
188        self.user_roles_combolist = builder.get_object("user_roles_liststore")
189        self.user_label = builder.get_object("User_label")
190        self.user_name_entry = builder.get_object("user_name_entry")
191        self.user_mls_label = builder.get_object("user_mls_label")
192        self.user_mls_level_entry = builder.get_object("user_mls_level_entry")
193        self.user_mls_entry = builder.get_object("user_mls_entry")
194        self.user_combobox = builder.get_object("selinux_user_combobox")
195        self.user_delete_liststore = builder.get_object("user_delete_liststore")
196        self.user_delete_window = builder.get_object("user_delete_window")
197
198        # File Equiv Items **************************************
199        self.file_equiv_label = builder.get_object("file_equiv_label")
200        self.file_equiv_source_entry = builder.get_object("file_equiv_source_entry")
201        self.file_equiv_dest_entry = builder.get_object("file_equiv_dest_entry")
202        self.file_equiv_radio_button = builder.get_object("file_equiv_button")
203        self.file_equiv_treeview = builder.get_object("file_equiv_treeview")
204        self.file_equiv_liststore = builder.get_object("file_equiv_liststore")
205        self.file_equiv_liststore.set_sort_column_id(0, Gtk.SortType.ASCENDING)
206        self.file_equiv_popup_window = builder.get_object("file_equiv_popup_window")
207        self.file_equiv_treefilter = builder.get_object("file_equiv_filter")
208        self.file_equiv_treefilter.set_visible_func(self.filter_the_data)
209        self.file_equiv_delete_liststore = builder.get_object("file_equiv_delete_liststore")
210        self.file_equiv_delete_window = builder.get_object("file_equiv_delete_window")
211
212        # System Items **************************************
213        self.app_system_button = builder.get_object("app_system_button")
214        self.system_radio_button = builder.get_object("System_button")
215        self.lockdown_radio_button = builder.get_object("Lockdown_button")
216        self.systems_box = builder.get_object("Systems_box")
217        self.relabel_button = builder.get_object("Relabel_button")
218        self.relabel_button_no = builder.get_object("Relabel_button_no")
219        self.advanced_system = builder.get_object("advanced_system")
220        self.outer_notebook_frame = builder.get_object("outer_notebook_frame")
221        self.system_policy_label = builder.get_object("system_policy_type_label")
222        # Browse Items **************************************
223        self.select_button_browse = builder.get_object("select_button_browse")
224        self.cancel_button_browse = builder.get_object("cancel_button_browse")
225        # More types window items ***************************
226        self.moreTypes_window_files = builder.get_object("moreTypes_window_files")
227        self.more_types_files_liststore = builder.get_object("more_types_file_liststore")
228        self.moreTypes_treeview = builder.get_object("moreTypes_treeview_files")
229        # System policy type ********************************
230        self.system_policy_type_liststore = builder.get_object("system_policy_type_liststore")
231        self.system_policy_type_combobox = builder.get_object("system_policy_type_combobox")
232        self.policy_list = []
233        if self.populate_system_policy() < 2:
234            self.advanced_system.set_visible(False)
235            self.system_policy_label.set_visible(False)
236            self.system_policy_type_combobox.set_visible(False)
237
238        self.enforcing_button_default = builder.get_object("Enforcing_button_default")
239        self.permissive_button_default = builder.get_object("Permissive_button_default")
240        self.disabled_button_default = builder.get_object("Disabled_button_default")
241        self.initialize_system_default_mode()
242
243        # Lockdown Window *********************************
244        self.enable_unconfined_button = builder.get_object("enable_unconfined")
245        self.disable_unconfined_button = builder.get_object("disable_unconfined")
246        self.enable_permissive_button = builder.get_object("enable_permissive")
247        self.disable_permissive_button = builder.get_object("disable_permissive")
248        self.enable_ptrace_button = builder.get_object("enable_ptrace")
249        self.disable_ptrace_button = builder.get_object("disable_ptrace")
250
251        # Help Window *********************************
252        self.help_window = builder.get_object("help_window")
253        self.help_text = builder.get_object("help_textv")
254        self.info_text = builder.get_object("info_text")
255        self.help_image = builder.get_object("help_image")
256        self.forward_button = builder.get_object("forward_button")
257        self.back_button = builder.get_object("back_button")
258        # Update menu items *********************************
259        self.update_window = builder.get_object("update_window")
260        self.update_treeview = builder.get_object("update_treeview")
261        self.update_treestore = builder.get_object("Update_treestore")
262        self.apply_button = builder.get_object("apply_button")
263        self.update_button = builder.get_object("Update_button")
264        # Add button objects ********************************
265        self.add_button = builder.get_object("Add_button")
266        self.delete_button = builder.get_object("Delete_button")
267
268        self.files_path_entry = builder.get_object("files_path_entry")
269        self.network_ports_entry = builder.get_object("network_ports_entry")
270        self.files_popup_window = builder.get_object("files_popup_window")
271        self.network_popup_window = builder.get_object("network_popup_window")
272
273        self.popup_network_label = builder.get_object("Network_label")
274        self.popup_files_label = builder.get_object("files_label")
275
276        self.recursive_path_toggle = builder.get_object("make_path_recursive")
277        self.files_type_combolist = builder.get_object("files_type_combo_store")
278        self.files_class_combolist = builder.get_object("files_class_combo_store")
279        self.files_type_combobox = builder.get_object("files_type_combobox")
280        self.files_class_combobox = builder.get_object("files_class_combobox")
281        self.files_mls_label = builder.get_object("files_mls_label")
282        self.files_mls_entry = builder.get_object("files_mls_entry")
283        self.advanced_text_files = builder.get_object("Advanced_text_files")
284        self.files_cancel_button = builder.get_object("cancel_delete_files")
285
286        self.network_tcp_button = builder.get_object("tcp_button")
287        self.network_udp_button = builder.get_object("udp_button")
288        self.network_port_type_combolist = builder.get_object("network_type_combo_store")
289        self.network_port_type_combobox = builder.get_object("network_type_combobox")
290        self.network_mls_label = builder.get_object("network_mls_label")
291        self.network_mls_entry = builder.get_object("network_mls_entry")
292        self.advanced_text_network = builder.get_object("Advanced_text_network")
293        self.network_cancel_button = builder.get_object("cancel_network_delete")
294
295        # Add button objects ********************************
296
297        # Modify items **************************************
298        self.show_mislabeled_files_only = builder.get_object("Show_mislabeled_files")
299        self.mislabeled_files_label = builder.get_object("mislabeled_files_label")
300        self.warning_files = builder.get_object("warning_files")
301        self.modify_button = builder.get_object("Modify_button")
302        self.modify_button.set_sensitive(False)
303        # Modify items **************************************
304
305        # Fix label *****************************************
306        self.fix_label_window = builder.get_object("fix_label_window")
307        self.fixlabel_label = builder.get_object("fixlabel_label")
308        self.fix_label_cancel = builder.get_object("fix_label_cancel")
309        # Fix label *****************************************
310
311        # Delete items **************************************
312        self.files_delete_window = builder.get_object("files_delete_window")
313        self.files_delete_treeview = builder.get_object("files_delete_treeview")
314        self.files_delete_liststore = builder.get_object("files_delete_liststore")
315        self.network_delete_window = builder.get_object("network_delete_window")
316        self.network_delete_treeview = builder.get_object("network_delete_treeview")
317        self.network_delete_liststore =builder.get_object("network_delete_liststore")
318        # Delete items **************************************
319
320        # Progress bar **************************************
321        self.progress_bar = builder.get_object("progress_bar")
322        # Progress bar **************************************
323
324        # executable_files items ****************************
325        self.executable_files_treeview = builder.get_object("Executable_files_treeview")                  # Get the executable files tree view
326        self.executable_files_filter= builder.get_object("executable_files_filter")
327        self.executable_files_filter.set_visible_func(self.filter_the_data)
328        self.executable_files_tab = builder.get_object("Executable_files_tab")
329        self.executable_files_tab_tooltip_txt = self.executable_files_tab.get_tooltip_text()
330        self.executable_files_liststore = builder.get_object("executable_files_treestore")
331        self.executable_files_liststore.set_sort_column_id(0, Gtk.SortType.ASCENDING)
332
333        self.files_radio_button = builder.get_object("files_button")
334        self.files_button_tooltip_txt = self.files_radio_button.get_tooltip_text()
335        # executable_files items ****************************
336
337        # writable files items ******************************
338        self.writable_files_treeview = builder.get_object("Writable_files_treeview")           # Get the Writable files tree view
339        self.writable_files_liststore = builder.get_object("writable_files_treestore")         # Contains the tree with File Path, SELinux File Label, Class
340        self.writable_files_liststore.set_sort_column_id(0, Gtk.SortType.ASCENDING)
341        self.writable_files_filter = builder.get_object("writable_files_filter")
342        self.writable_files_filter.set_visible_func(self.filter_the_data)
343        self.writable_files_tab = builder.get_object("Writable_files_tab")
344        self.writable_files_tab_tooltip_txt = self.writable_files_tab.get_tooltip_text()
345        # writable files items ******************************
346
347        # Application File Types ****************************
348        self.application_files_treeview = builder.get_object("Application_files_treeview")                    # Get the Application files tree view
349        self.application_files_filter = builder.get_object("application_files_filter")         # Contains the tree with File Path, Description, Class
350        self.application_files_filter.set_visible_func(self.filter_the_data)
351        self.application_files_tab = builder.get_object("Application_files_tab")
352        self.application_files_tab_tooltip_txt = self.writable_files_tab.get_tooltip_text()
353        self.application_files_liststore = builder.get_object("application_files_treestore")
354        self.application_files_liststore.set_sort_column_id(0, Gtk.SortType.ASCENDING)
355        self.application_files_tab = builder.get_object("Application_files_tab")
356        self.application_files_tab_tooltip_txt = self.application_files_tab.get_tooltip_text()
357        # Application File Type *****************************
358
359        # network items *************************************
360        self.network_radio_button = builder.get_object("network_button")
361        self.network_button_tooltip_txt = self.network_radio_button.get_tooltip_text()
362
363        self.network_out_treeview = builder.get_object("outbound_treeview")
364        self.network_out_liststore = builder.get_object("network_out_liststore")
365        self.network_out_liststore.set_sort_column_id(0, Gtk.SortType.ASCENDING)
366        self.network_out_filter =  builder.get_object("network_out_filter")
367        self.network_out_filter.set_visible_func(self.filter_the_data)
368        self.network_out_tab = builder.get_object("network_out_tab")
369        self.network_out_tab_tooltip_txt = self.network_out_tab.get_tooltip_text()
370
371        self.network_in_treeview = builder.get_object("inbound_treeview")
372        self.network_in_liststore = builder.get_object("network_in_liststore")
373        self.network_in_liststore.set_sort_column_id(0, Gtk.SortType.ASCENDING)
374        self.network_in_filter =  builder.get_object("network_in_filter")
375        self.network_in_filter.set_visible_func(self.filter_the_data)
376        self.network_in_tab = builder.get_object("network_in_tab")
377        self.network_in_tab_tooltip_txt = self.network_in_tab.get_tooltip_text()
378        # network items *************************************
379
380        # boolean items ************************************
381        self.boolean_treeview = builder.get_object("Boolean_treeview")         # Get the booleans tree list
382        self.boolean_liststore = builder.get_object("boolean_liststore")
383        self.boolean_liststore.set_sort_column_id(2, Gtk.SortType.ASCENDING)
384        self.boolean_filter = builder.get_object("boolean_filter")
385        self.boolean_filter.set_visible_func(self.filter_the_data)
386
387        self.boolean_more_detail_window = builder.get_object("booleans_more_detail_window")
388        self.boolean_more_detail_treeview = builder.get_object("booleans_more_detail_treeview")
389        self.boolean_more_detail_tree_data_set = builder.get_object("booleans_more_detail_liststore")
390        self.boolean_radio_button = builder.get_object("Booleans_button")
391        self.active_button = self.boolean_radio_button
392        self.boolean_button_tooltip_txt = self.boolean_radio_button.get_tooltip_text()
393        # boolean items ************************************
394
395        # transitions items ************************************
396        self.transitions_into_treeview = builder.get_object("transitions_into_treeview")         # Get the transitions tree list Enabled, source, Executable File
397        self.transitions_into_liststore = builder.get_object("transitions_into_liststore")   # Contains the tree with
398        self.transitions_into_liststore.set_sort_column_id(1, Gtk.SortType.ASCENDING)
399        self.transitions_into_filter = builder.get_object("transitions_into_filter")
400        self.transitions_into_filter.set_visible_func(self.filter_the_data)
401        self.transitions_into_tab = builder.get_object("Transitions_into_tab")
402        self.transitions_into_tab_tooltip_txt = self.transitions_into_tab.get_tooltip_text()
403
404        self.transitions_radio_button = builder.get_object("Transitions_button")
405        self.transitions_button_tooltip_txt = self.transitions_radio_button.get_tooltip_text()
406
407        self.transitions_from_treeview = builder.get_object("transitions_from_treeview")         # Get the transitions tree list
408        self.transitions_from_treestore = builder.get_object("transitions_from_treestore")       # Contains the tree with Enabled, Executable File Type, Transtype
409        self.transitions_from_treestore.set_sort_column_id(2, Gtk.SortType.ASCENDING)
410        self.transitions_from_filter = builder.get_object("transitions_from_filter")
411        self.transitions_from_filter.set_visible_func(self.filter_the_data)
412        self.transitions_from_tab = builder.get_object("Transitions_from_tab")
413        self.transitions_from_tab_tooltip_txt = self.transitions_from_tab.get_tooltip_text()
414
415        self.transitions_file_treeview = builder.get_object("file_transitions_treeview")         # Get the transitions tree list
416        self.transitions_file_liststore = builder.get_object("file_transitions_liststore")       # Contains the tree with Enabled, Executable File Type, Transtype
417        self.transitions_file_liststore.set_sort_column_id(0, Gtk.SortType.ASCENDING)
418        self.transitions_file_filter = builder.get_object("file_transitions_filter")
419        self.transitions_file_filter.set_visible_func(self.filter_the_data)
420        self.transitions_file_tab = builder.get_object("file_transitions")
421        self.transitions_file_tab_tooltip_txt = self.transitions_from_tab.get_tooltip_text()
422        # transitions items ************************************
423
424        # Combobox and Entry items **************************
425        self.combobox_menu = builder.get_object("combobox_org")                    # This is the combobox box object, aka the arrow next to the entry text bar
426        self.combobox_menu_model = builder.get_object("application_liststore")
427        self.completion_entry = builder.get_object("completion_entry")        #self.combobox_menu.get_child()
428        self.completion_entry_model = builder.get_object("application_liststore")
429        self.entrycompletion_obj = builder.get_object("entrycompletion_obj")
430        #self.entrycompletion_obj = Gtk.EntryCompletion()
431        self.entrycompletion_obj.set_model(self.completion_entry_model)
432        self.entrycompletion_obj.set_minimum_key_length(0)
433        self.entrycompletion_obj.set_text_column(0)
434        self.entrycompletion_obj.set_match_func(self.match_func, None)
435        self.completion_entry.set_completion(self.entrycompletion_obj)
436        self.completion_entry.set_icon_from_stock(0, Gtk.STOCK_FIND)
437        # Combobox and Entry items **************************
438
439        # Modify buttons ************************************
440        self.show_modified_only = builder.get_object("Show_modified_only_toggle")
441        # Modify button *************************************
442
443        # status bar *****************************************
444        self.current_status_label = builder.get_object("Enforcing_label")
445        self.current_status_enforcing = builder.get_object("Enforcing_button")
446        self.current_status_permissive = builder.get_object("Permissive_button")
447        self.status_bar = builder.get_object("status_bar")
448        self.context_id = self.status_bar.get_context_id("SELinux status")
449
450        # filters *********************************************
451        self.filter_entry = builder.get_object("filter_entry")
452        self.filter_box = builder.get_object("filter_box")
453        self.add_modify_delete_box = builder.get_object("add_modify_delete_box")
454        # Get_model() sets the tree model filter to be the parent of the tree model (tree model has all the data in it)
455
456        # Toggle button ****************************************
457        self.cell = builder.get_object("activate")
458        self.del_cell_files = builder.get_object("files_toggle_delete")
459        self.del_cell_files.connect("toggled", self.on_toggle_update, self.files_delete_liststore)
460        self.del_cell_files_equiv = builder.get_object("file_equiv_toggle_delete1")
461        self.del_cell_files_equiv.connect("toggled", self.on_toggle_update, self.file_equiv_delete_liststore)
462        self.del_cell_user = builder.get_object("user_toggle_delete")
463        self.del_cell_user.connect("toggled", self.on_toggle_update, self.user_delete_liststore)
464        self.del_cell_login = builder.get_object("login_toggle_delete")
465        self.del_cell_login.connect("toggled", self.on_toggle_update, self.login_delete_liststore)
466        self.del_cell_network = builder.get_object("network_toggle_delete")
467        self.del_cell_network.connect("toggled", self.on_toggle_update, self.network_delete_liststore)
468        self.update_cell = builder.get_object("toggle_update")
469        # Notebook items ***************************************
470        self.outer_notebook = builder.get_object("outer_notebook")
471        self.inner_notebook_files = builder.get_object("files_inner_notebook")
472        self.inner_notebook_network = builder.get_object("network_inner_notebook")
473        self.inner_notebook_transitions = builder.get_object("transitions_inner_notebook")
474        # logind gui ***************************************
475        loading_gui = builder.get_object("loading_gui")
476
477        self.update_cell.connect("toggled", self.on_toggle_update, self.update_treestore)
478        self.all_entries = []
479
480        # Need to connect button on code because the tree view model is a treeviewsort
481        self.cell.connect("toggled", self.on_toggle, self.boolean_liststore)
482
483        self.loading = 1
484        path = None
485        if test:
486            domains = [ "httpd_t", "abrt_t" ]
487            if app and app not in domains:
488                domains.append(app)
489        else:
490            domains = sepolicy_domains
491            loading_gui.show()
492        length = len(domains)
493        for domain in domains:
494            # After the user selects a path in the drop down menu call
495            # get_init_entrypoint_target(entrypoint) to get the transtype
496            # which will give you the application
497            self.combo_box_initialize(domain, None)
498            self.advanced_search_initialize(domain)
499            self.all_list.append(domain)
500            self.percentage = float(float(self.loading)/float(length))
501            self.progress_bar.set_fraction(self.percentage)
502            self.progress_bar.set_pulse_step(self.percentage)
503            self.idle_func()
504
505            entrypoint = sepolicy.get_init_entrypoint(domain)
506            if entrypoint:
507                path = sepolicy.find_entrypoint_path(entrypoint)
508                if path:
509                    self.combo_box_initialize(path, None)
510                    # Adds all files entrypoint paths that exists on disc
511                    # into the combobox
512                    self.advanced_search_initialize(path)
513                    self.installed_list.append(path)
514
515            self.loading += 1
516        loading_gui.hide()
517
518        dic = {
519               "on_combo_button_clicked" : self.open_combo_menu,
520               "on_disable_ptrace_toggled" : self.on_disable_ptrace,
521               "on_SELinux_window_configure_event" : self.hide_combo_menu,
522               "on_entrycompletion_obj_match_selected" : self.set_application_label,
523               "on_filter_changed" : self.get_filter_data,
524               "on_save_changes_file_equiv_clicked" : self.update_to_file_equiv,
525               "on_save_changes_login_clicked" : self.update_to_login,
526               "on_save_changes_user_clicked" : self.update_to_user,
527               "on_save_changes_files_clicked" : self.update_to_files,
528               "on_save_changes_network_clicked" : self.update_to_network,
529               "on_Advanced_text_files_button_press_event" : self.reveal_advanced,
530               "item_in_tree_selected" : self.cursor_changed,
531               "on_Application_file_types_treeview_configure_event" : self.resize_wrap,
532               "on_save_delete_clicked" : self.on_save_delete_clicked,
533               "on_moreTypes_treeview_files_row_activated" : self.populate_type_combo,
534               "on_retry_button_files_clicked" : self.invalid_entry_retry,
535               "on_make_path_recursive_toggled" : self.recursive_path,
536               "on_files_path_entry_button_press_event" : self.highlight_entry_text,
537               "on_files_path_entry_changed" : self.autofill_add_files_entry,
538               "on_select_type_files_clicked" : self.select_type_more,
539               "on_choose_file" : self.on_browse_select,
540               "on_Enforcing_button_toggled" : self.set_enforce,
541               "on_confirmation_close" : self.confirmation_close,
542               "on_column_clicked" : self.column_clicked,
543               "on_tab_switch" : self.clear_filters,
544
545               "on_file_equiv_button_clicked" : self.show_file_equiv_page,
546               "on_app/system_button_clicked" : self.system_interface,
547               "on_app/users_button_clicked" : self.users_interface,
548               "on_main_advanced_label_button_press_event": self.advanced_label_main,
549
550               "on_Show_mislabeled_files_toggled" : self.show_mislabeled_files,
551               "on_Browse_button_files_clicked" : self.browse_for_files,
552               "on_cancel_popup_clicked" : self.close_popup,
553               "on_treeview_cursor_changed" : self.cursor_changed,
554               "on_login_seuser_combobox_changed"  : self.login_seuser_combobox_change,
555               "on_user_roles_combobox_changed":self.user_roles_combobox_change,
556
557               "on_cancel_button_browse_clicked" : self.close_config_window,
558               "on_apply_button_clicked" : self.apply_changes_button_press,
559               "on_Revert_button_clicked" : self.update_or_revert_changes,
560               "on_Update_button_clicked" : self.update_or_revert_changes,
561               "on_advanced_filter_entry_changed" : self.get_advanced_filter_data,
562               "on_advanced_search_treeview_row_activated" : self.advanced_item_selected,
563               "on_Select_advanced_search_clicked" : self.advanced_item_button_push,
564               "on_All_advanced_button_toggled" : self.advanced_radio_select,
565               "on_Installed_advanced_button_toggled" : self.advanced_radio_select,
566               "on_info_button_button_press_event" : self.on_help_button,
567               "on_back_button_clicked" : self.on_help_back_clicked,
568               "on_forward_button_clicked" : self.on_help_forward_clicked,
569               "on_Boolean_treeview_columns_changed" : self.resize_columns,
570               "on_completion_entry_changed" : self.application_selected,
571               "on_Add_button_clicked" : self.add_button_clicked,
572               "on_Delete_button_clicked" : self.delete_button_clicked,
573               "on_Modify_button_clicked" : self.modify_button_clicked,
574               "on_Show_modified_only_toggled" : self.on_show_modified_only,
575               "on_cancel_button_config_clicked" : self.close_config_window,
576               "on_Import_button_clicked" : self.import_config_show,
577               "on_Export_button_clicked" : self.export_config_show,
578               "on_enable_unconfined_toggled": self.unconfined_toggle,
579               "on_enable_permissive_toggled": self.permissive_toggle,
580               "on_system_policy_type_combobox_changed" : self.change_default_policy,
581               "on_Enforcing_button_default_toggled" : self.change_default_mode,
582               "on_Permissive_button_default_toggled" : self.change_default_mode,
583               "on_Disabled_button_default_toggled" : self.change_default_mode,
584
585               "on_Relabel_button_toggled_cb": self.relabel_on_reboot,
586               "on_advanced_system_button_press_event" : self.reveal_advanced_system,
587               "on_files_type_combobox_changed" : self.show_more_types,
588               "on_filter_row_changed" : self.filter_the_data,
589               "on_button_toggled" : self.tab_change,
590               "gtk_main_quit": self.closewindow
591               }
592
593        self.previously_modified_initialize(customized)
594        builder.connect_signals(dic)
595        self.window.show()                # Show the gui to the screen
596        GLib.timeout_add_seconds(5,self.selinux_status)
597        self.selinux_status()
598        self.lockdown_inited = False
599        self.add_modify_delete_box.hide()
600        self.filter_box.hide()
601        if self.status == DISABLED:
602            self.show_system_page()
603        else:
604            if self.application:
605                self.applications_selection_button.set_label(self.application)
606                self.completion_entry.set_text(self.application)
607                self.show_applications_page()
608                self.tab_change()
609            else:
610                self.clearbuttons()
611                self.outer_notebook.set_current_page(START_PAGE)
612
613        self.reinit()
614        self.finish_init = True
615        Gtk.main()
616
617    def init_cur(self):
618        self.cur_dict = {}
619        for k in keys:
620            self.cur_dict[k] = {}
621
622    def remove_cur(self,ctr):
623        i = 0
624        for k in self.cur_dict:
625            for j in self.cur_dict[k]:
626                if i == ctr:
627                    del(self.cur_dict[k][j])
628                    return
629                i += 1
630
631    def selinux_status(self):
632        try:
633            self.status = selinux.security_getenforce()
634        except OSError:
635            self.status = DISABLED
636        if self.status == DISABLED:
637            self.current_status_label.set_sensitive(False)
638            self.current_status_enforcing.set_sensitive(False)
639            self.current_status_permissive.set_sensitive(False)
640            self.enforcing_button_default.set_sensitive(False)
641            self.status_bar.push(self.context_id,  _("System Status: Disabled"))
642            self.info_text.set_label(DISABLED_TEXT)
643        else:
644            self.set_enforce_text(self.status)
645        if os.path.exists('/.autorelabel'):
646            self.relabel_button.set_active(True)
647        else:
648            self.relabel_button_no.set_active(True)
649
650        policytype = selinux.selinux_getpolicytype()[1]
651
652        mode = selinux.selinux_getenforcemode()[1]
653        if mode == ENFORCING:
654            self.enforcing_button_default.set_active(True)
655        if mode == PERMISSIVE:
656            self.permissive_button_default.set_active(True)
657        if mode == DISABLED:
658            self.disabled_button_default.set_active(True)
659
660        return True
661
662    def lockdown_init(self):
663        if self.lockdown_inited:
664            return
665        self.wait_mouse()
666        self.lockdown_inited = True
667        self.disable_ptrace_button.set_active(selinux.security_get_boolean_active("deny_ptrace"))
668        self.module_dict = {}
669        for m in self.dbus.semodule_list().split("\n"):
670            mod = m.split()
671            if len(mod) < 2:
672                continue
673            self.module_dict[mod[0]] = { "version": mod[1], "Disabled" : (len(mod) > 2) }
674
675        self.enable_unconfined_button.set_active(not self.module_dict["unconfined"]["Disabled"])
676        self.enable_permissive_button.set_active(not self.module_dict["permissivedomains"]["Disabled"])
677        self.ready_mouse()
678
679    def column_clicked(self, treeview, treepath, treecol, *args):
680        iter = self.get_selected_iter()
681        if not iter:
682            return
683
684        if self.opage == BOOLEANS_PAGE:
685            if treecol.get_name() == "more_detail_col":
686                self.display_more_detail(self.window, treepath)
687
688        if self.opage == FILES_PAGE:
689            visible = self.liststore.get_value(iter, 3)
690            # If visible is true then fix mislabeled will be visible
691            if treecol.get_name() == "restorecon_col" and visible:
692                self.fix_mislabeled(self.liststore.get_value(iter, 0))
693
694        if self.opage == TRANSITIONS_PAGE:
695            bool_name = self.liststore.get_value(iter, 1)
696            if bool_name:
697                self.boolean_radio_button.clicked()
698                self.filter_entry.set_text(bool_name)
699
700    def idle_func(self):
701        while Gtk.events_pending():
702            Gtk.main_iteration()
703
704    def match_func(self, completion, key_string, iter, func_data):
705        try:
706            if self.combobox_menu_model.get_value(iter, 0).find(key_string) != -1:
707                return True
708            return False
709        except AttributeError:
710            pass
711
712    def help_show_page(self):
713        self.back_button.set_sensitive(self.help_page != 0)
714        self.forward_button.set_sensitive(self.help_page < (len(self.help_list) - 1))
715        try:
716            fd = open("%shelp/%s.txt" % (self.code_path, self.help_list[self.help_page]), "r")
717            buf = fd.read()
718            fd.close()
719        except IOError:
720            buf = ""
721        help_text = self.help_text.get_buffer()
722        help_text.set_text(buf % { "APP": self.application })
723        self.help_text.set_buffer(help_text)
724        self.help_image.set_from_file("%shelp/%s.png" % (self.code_path, self.help_list[self.help_page]))
725        self.show_popup(self.help_window)
726
727    def on_help_back_clicked(self, *args):
728        self.help_page -= 1
729        self.help_show_page()
730
731    def on_help_forward_clicked(self, *args):
732        self.help_page += 1
733        self.help_show_page()
734
735    def on_help_button(self, *args):
736        self.help_page = 0
737        self.help_list = []
738        if self.opage == START_PAGE:
739            self.help_window.set_title(_("Help: Start Page"))
740            self.help_list = [ "start"]
741
742        if self.opage == BOOLEANS_PAGE:
743            self.help_window.set_title(_("Help: Booleans Page"))
744            self.help_list = [ "booleans", "booleans_toggled", "booleans_more", "booleans_more_show"]
745
746        if self.opage == FILES_PAGE:
747            ipage = self.inner_notebook_files.get_current_page()
748            if ipage == EXE_PAGE:
749                self.help_window.set_title(_("Help: Executable Files Page"))
750                self.help_list = [ "files_exec" ]
751            if ipage == WRITABLE_PAGE:
752                self.help_window.set_title(_("Help: Writable Files Page"))
753                self.help_list = [ "files_write" ]
754            if ipage == APP_PAGE:
755                self.help_window.set_title(_("Help: Application Types Page"))
756                self.help_list = [ "files_app" ]
757        if self.opage == NETWORK_PAGE:
758            ipage = self.inner_notebook_network.get_current_page()
759            if ipage == OUTBOUND_PAGE:
760                self.help_window.set_title(_("Help: Outbound Network Connections Page"))
761                self.help_list = [ "ports_outbound" ]
762            if ipage == INBOUND_PAGE:
763                self.help_window.set_title(_("Help: Inbound Network Connections Page"))
764                self.help_list = [ "ports_inbound" ]
765
766        if self.opage == TRANSITIONS_PAGE:
767            ipage = self.inner_notebook_transitions.get_current_page()
768            if ipage == TRANSITIONS_FROM_PAGE:
769                self.help_window.set_title(_("Help: Transition from application Page"))
770                self.help_list = [ "transition_from", "transition_from_boolean", "transition_from_boolean_1", "transition_from_boolean_2"]
771            if ipage == TRANSITIONS_TO_PAGE:
772                self.help_window.set_title(_("Help: Transition into application Page"))
773                self.help_list = [ "transition_to" ]
774            if ipage == TRANSITIONS_FILE_PAGE:
775                self.help_window.set_title(_("Help: Transition application file Page"))
776                self.help_list = [ "transition_file" ]
777
778        if self.opage == SYSTEM_PAGE:
779                self.help_window.set_title(_("Help: Systems Page"))
780                self.help_list = [ "system", "system_boot_mode", "system_current_mode", "system_export", "system_policy_type", "system_relabel" ]
781
782        if self.opage == LOCKDOWN_PAGE:
783                self.help_window.set_title(_("Help: Lockdown Page"))
784                self.help_list = [ "lockdown", "lockdown_unconfined", "lockdown_permissive", "lockdown_ptrace" ]
785
786        if self.opage == LOGIN_PAGE:
787                self.help_window.set_title(_("Help: Login Page"))
788                self.help_list = [ "login", "login_default" ]
789
790        if self.opage == USER_PAGE:
791                self.help_window.set_title(_("Help: SELinux User Page"))
792                self.help_list = [ "users" ]
793
794        if self.opage == FILE_EQUIV_PAGE:
795                self.help_window.set_title(_("Help: File Equivalence Page"))
796                self.help_list = [ "file_equiv"]
797        return self.help_show_page()
798
799    def open_combo_menu(self, *args):
800        if self.popup == 0:
801            self.popup = 1
802            location = self.window.get_position()
803            self.main_selection_window.move(location[0]+2, location[1]+65)
804            self.main_selection_window.show()
805        else:
806            self.main_selection_window.hide()
807            self.popup = 0
808
809    def hide_combo_menu(self, *args):
810        self.main_selection_window.hide()
811        self.popup = 0
812
813    def set_application_label(self, *args):
814        self.set_application_label = True
815
816    def resize_wrap(self, *args):
817        print args
818
819    def initialize_system_default_mode(self):
820        self.enforce_mode = selinux.selinux_getenforcemode()[1]
821        if self.enforce_mode == ENFORCING:
822            self.enforce_button = self.enforcing_button_default
823        if self.enforce_mode == PERMISSIVE:
824            self.enforce_button = self.permissive_button_default
825        if self.enforce_mode == DISABLED:
826            self.enforce_button = self.disabled_button_default
827
828    def populate_system_policy(self):
829        selinux_path = selinux.selinux_path()
830        types = map(lambda x: x[1], filter(lambda x: x[0]==selinux_path, os.walk(selinux_path)))[0]
831        types.sort()
832        ctr = 0
833        for item in types:
834            iter = self.system_policy_type_liststore.append()
835            self.system_policy_type_liststore.set_value(iter, 0, item)
836            if item == self.initialtype:
837                self.system_policy_type_combobox.set_active(ctr)
838                self.typeHistory = ctr
839            ctr += 1
840        return ctr
841
842    def filter_the_data(self, list, iter, *args):
843        # When there is no txt in the box show all items in the tree
844        if self.filter_txt == "":
845            return True
846        try:
847            for x in range(0,list.get_n_columns()):
848                try:
849                    val = list.get_value(iter, x)
850                    if val == True or val == False or val == None:
851                        continue
852                    # Returns true if filter_txt exists within the val
853                    if(val.find(self.filter_txt) != -1 or val.lower().find(self.filter_txt) != -1) :
854                        return True
855                except AttributeError, TypeError:
856                    pass
857        except: #ValueError:
858            pass
859        return False
860
861    def net_update(self, app, netd, protocol, direction, model):
862        for k in netd.keys():
863            for t,ports in netd[k]:
864                pkey = (",".join(ports), protocol)
865                if pkey in self.cur_dict["port"]:
866                    if self.cur_dict["port"][pkey]["action"] == "-d":
867                        continue
868                    if t != self.cur_dict["port"][pkey]["type"]:
869                        continue
870                self.network_initial_data_insert(model, ", ".join(ports), t, protocol)
871
872    def file_equiv_initialize(self):
873        self.wait_mouse()
874        edict = sepolicy.get_file_equiv()
875        self.file_equiv_liststore.clear()
876        for f in edict:
877            iter = self.file_equiv_liststore.append()
878            if edict[f]["modify"]:
879                name = self.markup(f)
880                equiv = self.markup(edict[f]["equiv"])
881            else:
882                name = f
883                equiv = edict[f]["equiv"]
884
885            self.file_equiv_liststore.set_value(iter, 0, name)
886            self.file_equiv_liststore.set_value(iter, 1, equiv)
887            self.file_equiv_liststore.set_value(iter, 2, edict[f]["modify"])
888        self.ready_mouse()
889
890    def user_initialize(self):
891        self.wait_mouse()
892        self.user_liststore.clear()
893        for u in sepolicy.get_selinux_users():
894            iter = self.user_liststore.append()
895            self.user_liststore.set_value(iter, 0, str(u["name"]))
896            roles = u["roles"]
897            if "object_r" in roles:
898                roles.remove("object_r")
899            self.user_liststore.set_value(iter, 1, ", ".join(roles))
900            self.user_liststore.set_value(iter, 2, u["level"])
901            self.user_liststore.set_value(iter, 3, u["range"])
902            self.user_liststore.set_value(iter, 4, True)
903        self.ready_mouse()
904
905    def login_initialize(self):
906        self.wait_mouse()
907        self.login_liststore.clear()
908        for u in sepolicy.get_login_mappings():
909            iter = self.login_liststore.append()
910            self.login_liststore.set_value(iter, 0, u["name"])
911            self.login_liststore.set_value(iter, 1, u["seuser"])
912            self.login_liststore.set_value(iter, 2, u["mls"])
913            self.login_liststore.set_value(iter, 3, True)
914        self.ready_mouse()
915
916    def network_initialize(self, app):
917        netd = sepolicy.network.get_network_connect(app, "tcp", "name_connect")
918        self.net_update(app, netd, "tcp", OUTBOUND_PAGE, self.network_out_liststore)
919        netd = sepolicy.network.get_network_connect(app, "tcp", "name_bind")
920        self.net_update(app, netd, "tcp", INBOUND_PAGE, self.network_in_liststore)
921        netd = sepolicy.network.get_network_connect(app, "udp", "name_bind")
922        self.net_update(app, netd, "udp", INBOUND_PAGE, self.network_in_liststore)
923
924    def network_initial_data_insert(self, model, ports, portType, protocol):
925        iter = model.append()
926        model.set_value(iter, 0, ports)
927        model.set_value(iter, 1, protocol)
928        model.set_value(iter, 2, portType)
929        model.set_value(iter, 4, True)
930
931    def combo_set_active_text(self, combobox, val):
932        ctr = 0
933        liststore = combobox.get_model()
934        for i in liststore:
935            if i[0] == val:
936                combobox.set_active(ctr)
937                return
938            ctr += 1
939
940        niter = liststore.get_iter(ctr-1)
941        if liststore.get_value(niter, 0) == _("More..."):
942            iter = liststore.insert_before(niter)
943            ctr = ctr - 1
944        else:
945            iter = liststore.append()
946        liststore.set_value(iter, 0, val)
947        combobox.set_active(ctr)
948
949    def combo_get_active_text(self, combobox):
950        liststore = combobox.get_model()
951        index = combobox.get_active()
952        if index < 0:
953            return None
954        iter = liststore.get_iter(index)
955        return liststore.get_value(iter, 0)
956
957    def combo_box_initialize(self, val, desc):
958        if val == None:
959            return
960        iter = self.combobox_menu_model.append()
961        for f in val:
962            self.combobox_menu_model.set_value(iter, 0, val)
963
964    def select_type_more(self, *args):
965        app = self.moreTypes_treeview.get_selection()
966        iter = app.get_selected()[1]
967        if iter == None:
968            return
969        app = self.more_types_files_liststore.get_value(iter, 0)
970        self.combo_set_active_text(self.files_type_combobox, app)
971        self.closewindow(self.moreTypes_window_files)
972
973    def advanced_item_button_push(self, *args):
974        row = self.advanced_search_treeview.get_selection()
975        model, iter = row.get_selected()
976        iter = model.convert_iter_to_child_iter(iter)
977        iter = self.advanced_search_filter.convert_iter_to_child_iter(iter)
978        app = self.advanced_search_liststore.get_value(iter, 1)
979        if app == None:
980            return
981        self.advanced_filter_entry.set_text('')
982        self.advanced_search_window.hide()
983        self.reveal_advanced(self.main_advanced_label)
984        self.completion_entry.set_text(app)
985        self.application_selected()
986
987    def advanced_item_selected(self, treeview, path, *args):
988        iter = self.advanced_search_filter.get_iter(path)
989        iter = self.advanced_search_filter.convert_iter_to_child_iter(iter)
990        app = self.advanced_search_liststore.get_value(iter, 1)
991        self.advanced_filter_entry.set_text('')
992        self.advanced_search_window.hide()
993        self.reveal_advanced(self.main_advanced_label)
994        self.completion_entry.set_text(app)
995        self.application_selected()
996
997    def find_application(self, app):
998        if app and len(app) > 0:
999            for items in self.combobox_menu_model:
1000                if app == items[0]:
1001                    return True
1002        return False
1003
1004    def application_selected(self, *args):
1005        self.show_mislabeled_files_only.set_visible(False)
1006        self.mislabeled_files_label.set_visible(False)
1007        self.warning_files.set_visible(False)
1008        self.filter_entry.set_text('')
1009
1010        app = self.completion_entry.get_text()
1011        if not self.find_application(app):
1012            return
1013        self.show_applications_page()
1014        self.add_button.set_sensitive(True)
1015        self.delete_button.set_sensitive(True)
1016        # Clear the tree to prepare for a new selection otherwise
1017        self.executable_files_liststore.clear()
1018        # data will pile up everytime the user selects a new item from the drop down menu
1019        self.network_in_liststore.clear()
1020        self.network_out_liststore.clear()
1021        self.boolean_liststore.clear()
1022        self.transitions_into_liststore.clear()
1023        self.transitions_from_treestore.clear()
1024        self.application_files_liststore.clear()
1025        self.writable_files_liststore.clear()
1026        self.transitions_file_liststore.clear()
1027
1028        try:
1029            if app[0] == '/':
1030                app = sepolicy.get_init_transtype(app)
1031                if not app:
1032                    return
1033                self.application = app
1034        except IndexError:
1035            pass
1036
1037        self.wait_mouse()
1038        self.previously_modified_initialize(self.dbus.customized())
1039        self.reinit()
1040        self.boolean_initialize(app)
1041        self.mislabeled_files = False
1042        self.executable_files_initialize(app)
1043        self.network_initialize(app)
1044        self.writable_files_initialize(app)
1045        self.transitions_into_initialize(app)
1046        self.transitions_from_initialize(app)
1047        self.application_files_initialize(app)
1048        self.transitions_files_initialize(app)
1049
1050        self.executable_files_tab.set_tooltip_text(_("File path used to enter the '%s' domain." % app))
1051        self.writable_files_tab.set_tooltip_text(_("Files to which the '%s' domain can write." % app))
1052        self.network_out_tab.set_tooltip_text(_("Network Ports to which the '%s' is allowed to connect." % app))
1053        self.network_in_tab.set_tooltip_text(_("Network Ports to which the '%s' is allowed to listen." % app))
1054        self.application_files_tab.set_tooltip_text(_("File Types defined for the '%s'." % app))
1055        self.boolean_radio_button.set_tooltip_text(_("Display boolean information that can be used to modify the policy for the '%s'." % app))
1056        self.files_radio_button.set_tooltip_text(_("Display file type information that can be used by the '%s'." % app))
1057        self.network_radio_button.set_tooltip_text(_("Display network ports to which the '%s' can connect or listen to." % app))
1058        self.transitions_into_tab.set_label(_("Application Transitions Into '%s'" % app))
1059        self.transitions_from_tab.set_label(_("Application Transitions From '%s'" % app))
1060        self.transitions_file_tab.set_label(_("File Transitions From '%s'" % app))
1061        self.transitions_into_tab.set_tooltip_text(_("Executables which will transition to the '%s', when executing a selected domains entrypoint.") % app)
1062        self.transitions_from_tab.set_tooltip_text(_("Executables which will transition to a different domain, when the '%s' executes them.") % app)
1063        self.transitions_file_tab.set_tooltip_text(_("Files by '%s' will transitions to a different label." % app))
1064        self.transitions_radio_button.set_tooltip_text(_("Display applications that can transition into or out of the '%s'." % app))
1065
1066        self.application = app
1067        self.applications_selection_button.set_label(self.application)
1068        self.ready_mouse()
1069
1070    def reinit(self):
1071        sepolicy.reinit()
1072        self.fcdict=sepolicy.get_fcdict()
1073        self.local_file_paths = sepolicy.get_local_file_paths()
1074
1075    def previously_modified_initialize(self, buf):
1076        self.cust_dict = {}
1077        for i in buf.split("\n"):
1078            rec = i.split()
1079            if len(rec) == 0:
1080                continue
1081            if rec[1] == "-D":
1082                continue
1083            if rec[0] not in self.cust_dict:
1084                self.cust_dict[rec[0]] = {}
1085            if rec[0] == "boolean":
1086                self.cust_dict["boolean"][rec[-1]] = { "active": rec[2] == "-1" }
1087            if rec[0] == "login":
1088                self.cust_dict["login"][rec[-1]] = { "seuser": rec[3], "range": rec[5] }
1089            if rec[0] == "interface":
1090                self.cust_dict["interface"][rec[-1]] = { "type": rec[3] }
1091            if rec[0] == "user":
1092                self.cust_dict["user"][rec[-1]] = { "level": "s0", "range": rec[3], "role": rec[5] }
1093            if rec[0] == "port":
1094                self.cust_dict["port"][(rec[-1], rec[-2] )] = { "type": rec[3] }
1095            if rec[0] == "node":
1096                self.cust_dict["node"][rec[-1]] = { "mask": rec[3], "protocol":rec[5], "type": rec[7] }
1097            if rec[0] == "fcontext":
1098                if rec[2] == "-e":
1099                    if "fcontext-equiv" not in self.cust_dict:
1100                        self.cust_dict["fcontext-equiv"] = {}
1101                    self.cust_dict["fcontext-equiv"][(rec[-1])] = { "equiv": rec[3] }
1102                else:
1103                    self.cust_dict["fcontext"][(rec[-1],rec[3])] = { "type": rec[5] }
1104            if rec[0] == "module":
1105                self.cust_dict["module"][rec[-1]] = { "enabled": rec[2] != "-d" }
1106
1107        if "module" not in self.cust_dict:
1108            return
1109        for semodule, button in [ ("unconfined", self.disable_unconfined_button), ("permissivedomains", self.disable_permissive_button) ]:
1110            if semodule in self.cust_dict["module"]:
1111                button.set_active(self.cust_dict["module"][semodule]["enabled"])
1112
1113        for i in keys:
1114            if i not in self.cust_dict:
1115                self.cust_dict.update({i:{}})
1116
1117    def executable_files_initialize(self, application):
1118        self.entrypoints = sepolicy.get_entrypoints(application)
1119        for exe in self.entrypoints.keys():
1120            if len(self.entrypoints[exe]) == 0:
1121                continue
1122            file_class = self.entrypoints[exe][1]
1123            for path in self.entrypoints[exe][0]:
1124                if (path, file_class) in self.cur_dict["fcontext"]:
1125                    if self.cur_dict["fcontext"][(path, file_class)]["action"] == "-d":
1126                        continue
1127                    if exe != self.cur_dict["fcontext"][(path, file_class)]["type"]:
1128                        continue
1129                self.files_initial_data_insert(self.executable_files_liststore, path, exe, file_class)
1130
1131    def mislabeled(self, path):
1132        try:
1133            con = selinux.matchpathcon(path,0)[1]
1134            cur = selinux.getfilecon(path)[1]
1135            return con != cur
1136        except OSError:
1137            return False
1138
1139    def set_mislabeled(self, tree, path, iter, niter):
1140        if not self.mislabeled(path):
1141            return
1142        con = selinux.matchpathcon(path,0)[1]
1143        cur = selinux.getfilecon(path)[1]
1144        self.mislabeled_files=True
1145        # Set visibility of label
1146        tree.set_value(niter, 3, True)
1147        # Has a mislabel
1148        tree.set_value(iter, 4, True)
1149        tree.set_value(niter, 4, True)
1150        tree.set_value(iter, 5, con.split(":")[2])
1151        tree.set_value(iter, 6, cur.split(":")[2])
1152
1153    def writable_files_initialize(self, application):
1154        # Traversing the dictionary data struct
1155        self.writable_files = sepolicy.get_writable_files(application)
1156        for write in self.writable_files.keys():
1157            if len(self.writable_files[write]) < 2:
1158                self.files_initial_data_insert(self.writable_files_liststore, None, write, _("all files"))
1159                continue
1160            file_class = self.writable_files[write][1]
1161            for path in self.writable_files[write][0]:
1162                if (path,file_class) in self.cur_dict["fcontext"]:
1163                    if self.cur_dict["fcontext"][(path,file_class) ]["action"] == "-d":
1164                        continue
1165                    if write != self.cur_dict["fcontext"][(path, file_class)]["type"]:
1166                        continue
1167                self.files_initial_data_insert(self.writable_files_liststore, path, write, file_class)
1168
1169    def files_initial_data_insert(self, liststore, path, seLinux_label, file_class):
1170        iter = liststore.append(None)
1171        if path == None:
1172            path = _("MISSING FILE PATH")
1173            modify = False
1174        else:
1175            modify = (path,file_class) in self.local_file_paths
1176            for p in sepolicy.find_file(path):
1177                niter = liststore.append(iter)
1178                liststore.set_value(niter, 0, p)
1179                self.set_mislabeled(liststore, p, iter, niter)
1180            if modify:
1181                path = self.markup(path)
1182                file_class = self.markup(selinux_label)
1183                file_class = self.markup(file_class)
1184        liststore.set_value(iter, 0, path)
1185        liststore.set_value(iter, 1, seLinux_label)
1186        liststore.set_value(iter, 2, file_class)
1187        liststore.set_value(iter, 7, modify)
1188
1189    def markup(self, f):
1190        return "<b>%s</b>" % f
1191
1192    def unmarkup(self, f):
1193        if f:
1194            return re.sub("</b>$","", re.sub("^<b>","", f))
1195        return None
1196
1197    def application_files_initialize(self, application):
1198        self.file_types = sepolicy.get_file_types(application)
1199        for app in self.file_types.keys():
1200            if len(self.file_types[app]) == 0:
1201                continue
1202            file_class = self.file_types[app][1]
1203            for path in self.file_types[app][0]:
1204                desc = sepolicy.get_description(app, markup = self.markup)
1205                if (path, file_class) in self.cur_dict["fcontext"]:
1206                    if self.cur_dict["fcontext"][(path, file_class)]["action"] == "-d":
1207                        continue
1208                    if app != self.cur_dict["fcontext"][(path, file_class)]["type"]:
1209                        continue
1210                self.files_initial_data_insert(self.application_files_liststore, path, desc, file_class)
1211
1212    def modified(self):
1213        i = 0
1214        for k in self.cur_dict:
1215            if len(self.cur_dict[k]) > 0:
1216                return True
1217        return False
1218
1219    def boolean_initialize(self, application):
1220        for blist in sepolicy.get_bools(application):
1221            for b, active in blist:
1222                if b in self.cur_dict["boolean"]:
1223                    active = self.cur_dict["boolean"][b]['active']
1224                desc = sepolicy.boolean_desc(b)
1225                self.boolean_initial_data_insert(b, desc , active)
1226
1227    def boolean_initial_data_insert(self, val, desc, active):
1228        # Insert data from data source into tree
1229        iter = self.boolean_liststore.append()
1230        self.boolean_liststore.set_value(iter, 0, active)
1231        self.boolean_liststore.set_value(iter, 1, desc)
1232        self.boolean_liststore.set_value(iter, 2, val)
1233        self.boolean_liststore.set_value(iter, 3, _('More...'))
1234
1235    def transitions_into_initialize(self, application):
1236        for x in sepolicy.get_transitions_into(application):
1237            active = None
1238            executable = None
1239            source = None
1240            if "boolean" in x:
1241                active = x["boolean"]
1242            if "target" in x:
1243                executable = x["target"]
1244            if "source" in x:
1245                source = x["source"]
1246            self.transitions_into_initial_data_insert(active, executable, source)
1247
1248    def transitions_into_initial_data_insert(self, active, executable, source):
1249        iter = self.transitions_into_liststore.append()
1250        if active != None:
1251            self.transitions_into_liststore.set_value(iter, 0, enabled[active[0][1]])         # active[0][1] is either T or F (enabled is all the way at the top)
1252        else:
1253            self.transitions_into_liststore.set_value(iter, 0, "Default")
1254
1255        self.transitions_into_liststore.set_value(iter, 2, executable)
1256        self.transitions_into_liststore.set_value(iter, 1, source)
1257
1258    def transitions_from_initialize(self, application):
1259        for x in sepolicy.get_transitions(application):
1260            active = None
1261            executable = None
1262            transtype = None
1263            if "boolean" in x:
1264                active = x["boolean"]
1265            if "target" in x:
1266                executable_type = x["target"]
1267            if "transtype" in x:
1268                transtype = x["transtype"]
1269            self.transitions_from_initial_data_insert(active, executable_type, transtype)
1270            try:
1271                for executable in self.fcdict[executable_type]["regex"]:
1272                    self.transitions_from_initial_data_insert(active, executable, transtype)
1273            except KeyError:
1274                pass
1275
1276    def transitions_from_initial_data_insert(self, active, executable, transtype):
1277        iter = self.transitions_from_treestore.append(None)
1278        if active == None:
1279            self.transitions_from_treestore.set_value(iter, 0, "Default")
1280            self.transitions_from_treestore.set_value(iter, 5, False)
1281        else:
1282            niter = self.transitions_from_treestore.append(iter)
1283            # active[0][1] is either T or F (enabled is all the way at the top)
1284            self.transitions_from_treestore.set_value(iter, 0, enabled[active[0][1]])
1285            markup = '<span foreground="blue"><u>%s</u></span>'
1286            if active[0][1]:
1287                self.transitions_from_treestore.set_value(niter, 2, (_("To disable this transition, go to the " + markup % _("Boolean section."))))
1288            else:
1289                self.transitions_from_treestore.set_value(niter, 2, (_("To enable this transition, go to the " + markup % _("Boolean section."))))
1290
1291            # active[0][0] is the Bool Name
1292            self.transitions_from_treestore.set_value(niter, 1, active[0][0])
1293            self.transitions_from_treestore.set_value(niter, 5, True)
1294
1295        self.transitions_from_treestore.set_value(iter, 2, executable)
1296        self.transitions_from_treestore.set_value(iter, 3, transtype)
1297
1298    def transitions_files_initialize(self, application):
1299        for i in sepolicy.get_file_transitions(application):
1300            if 'filename' in i:
1301                filename = i['filename']
1302            else:
1303                filename = None
1304            self.transitions_files_inital_data_insert(i['target'], i['class'], i['transtype'], filename)
1305
1306    def transitions_files_inital_data_insert(self, path, tclass, dest, name):
1307        iter = self.transitions_file_liststore.append()
1308        self.transitions_file_liststore.set_value(iter, 0, path)
1309        self.transitions_file_liststore.set_value(iter, 1, tclass)
1310        self.transitions_file_liststore.set_value(iter, 2, dest)
1311        if name == None:
1312            name = '*'
1313        self.transitions_file_liststore.set_value(iter, 3, name)
1314
1315    def tab_change(self, *args):
1316        self.clear_filters()
1317        self.treeview = None
1318        self.treesort = None
1319        self.treefilter = None
1320        self.liststore = None
1321        self.modify_button.set_sensitive(False)
1322        self.add_modify_delete_box.hide()
1323        self.show_modified_only.set_visible(False)
1324        self.show_mislabeled_files_only.set_visible(False)
1325        self.mislabeled_files_label.set_visible(False)
1326        self.warning_files.set_visible(False)
1327
1328        if self.boolean_radio_button.get_active():
1329            self.outer_notebook.set_current_page(BOOLEANS_PAGE)
1330            self.treeview = self.boolean_treeview
1331            self.show_modified_only.set_visible(True)
1332
1333        if self.files_radio_button.get_active():
1334            self.show_popup(self.add_modify_delete_box)
1335            self.show_modified_only.set_visible(True)
1336            self.show_mislabeled_files_only.set_visible(self.mislabeled_files)
1337            self.mislabeled_files_label.set_visible(self.mislabeled_files)
1338            self.warning_files.set_visible(self.mislabeled_files)
1339            self.outer_notebook.set_current_page(FILES_PAGE)
1340            if args[0] == self.inner_notebook_files:
1341                ipage = args[2]
1342            else:
1343                ipage = self.inner_notebook_files.get_current_page()
1344            if ipage == EXE_PAGE:
1345                self.treeview = self.executable_files_treeview
1346                category = _("executable")
1347            elif ipage == WRITABLE_PAGE:
1348                self.treeview = self.writable_files_treeview
1349                category = _("writable")
1350            elif ipage == APP_PAGE:
1351                self.treeview = self.application_files_treeview
1352                category = _("application")
1353            self.add_button.set_tooltip_text(_("Add new %(TYPE)s file path for '%(DOMAIN)s' domains.") % { "TYPE": category, "DOMAIN": self.application})
1354            self.delete_button.set_tooltip_text(_("Delete %(TYPE)s file paths for '%(DOMAIN)s' domain.") % { "TYPE": category, "DOMAIN": self.application})
1355            self.modify_button.set_tooltip_text(_("Modify %(TYPE)s file path for '%(DOMAIN)s' domain. Only bolded items in the list can be selected, this indicates they were modified previously.") % { "TYPE": category, "DOMAIN": self.application})
1356
1357        if self.network_radio_button.get_active():
1358            self.add_modify_delete_box.show()
1359            self.show_modified_only.set_visible(True)
1360            self.outer_notebook.set_current_page(NETWORK_PAGE)
1361            if args[0] == self.inner_notebook_network:
1362                ipage = args[2]
1363            else:
1364                ipage = self.inner_notebook_network.get_current_page()
1365            if ipage == OUTBOUND_PAGE:
1366                self.treeview = self.network_out_treeview
1367                category = _("connect")
1368            if ipage == INBOUND_PAGE:
1369                self.treeview = self.network_in_treeview
1370                category = _("listen for inbound connections")
1371
1372            self.add_button.set_tooltip_text(_("Add new port definition to which the '%(APP)s' domain is allowed to %s.") % {"APP": self.application, "PERM": category})
1373            self.delete_button.set_tooltip_text(_("Delete modified port definitions to which the '%(APP)s' domain is allowed to %s.") % {"APP": self.application, "PERM": category})
1374            self.modify_button.set_tooltip_text(_("Modify port definitions to which the '%(APP)s' domain is allowed to %(PERM)s.") % {"APP": self.application, "PERM": category})
1375
1376        if self.transitions_radio_button.get_active():
1377            self.outer_notebook.set_current_page(TRANSITIONS_PAGE)
1378            if args[0] == self.inner_notebook_transitions:
1379                ipage = args[2]
1380            else:
1381                ipage = self.inner_notebook_transitions.get_current_page()
1382            if ipage == TRANSITIONS_FROM_PAGE:
1383                self.treeview = self.transitions_from_treeview
1384            if ipage == TRANSITIONS_TO_PAGE:
1385                self.treeview = self.transitions_into_treeview
1386            if ipage == TRANSITIONS_FILE_PAGE:
1387                self.treeview = self.transitions_file_treeview
1388
1389        if self.system_radio_button.get_active():
1390            self.outer_notebook.set_current_page(SYSTEM_PAGE)
1391            self.filter_box.hide()
1392
1393        if self.lockdown_radio_button.get_active():
1394            self.lockdown_init()
1395            self.outer_notebook.set_current_page(LOCKDOWN_PAGE)
1396            self.filter_box.hide()
1397
1398        if self.user_radio_button.get_active():
1399            self.outer_notebook.set_current_page(USER_PAGE)
1400            self.add_modify_delete_box.show()
1401            self.show_modified_only.set_visible(True)
1402            self.treeview = self.user_treeview
1403            self.add_button.set_tooltip_text(_("Add new SELinux User/Role definition."))
1404            self.delete_button.set_tooltip_text(_("Delete modified SELinux User/Role definitions."))
1405            self.modify_button.set_tooltip_text(_("Modify selected modified SELinux User/Role definitions."))
1406
1407        if self.login_radio_button.get_active():
1408            self.outer_notebook.set_current_page(LOGIN_PAGE)
1409            self.add_modify_delete_box.show()
1410            self.show_modified_only.set_visible(True)
1411            self.treeview = self.login_treeview
1412            self.add_button.set_tooltip_text(_("Add new Login Mapping definition."))
1413            self.delete_button.set_tooltip_text(_("Delete modified Login Mapping definitions."))
1414            self.modify_button.set_tooltip_text(_("Modify selected modified Login Mapping definitions."))
1415
1416        if self.file_equiv_radio_button.get_active():
1417            self.outer_notebook.set_current_page(FILE_EQUIV_PAGE)
1418            self.add_modify_delete_box.show()
1419            self.show_modified_only.set_visible(True)
1420            self.treeview = self.file_equiv_treeview
1421            self.add_button.set_tooltip_text(_("Add new File Equivalence definition."))
1422            self.delete_button.set_tooltip_text(_("Delete modified File Equivalence definitions."))
1423            self.modify_button.set_tooltip_text(_("Modify selected modified File Equivalence definitions. Only bolded items in the list can be selected, this indicates they were modified previously."))
1424
1425        self.opage = self.outer_notebook.get_current_page()
1426        if self.treeview:
1427            self.filter_box.show()
1428            self.treesort = self.treeview.get_model()
1429            self.treefilter = self.treesort.get_model()
1430            self.liststore = self.treefilter.get_model()
1431            for x in range(0,self.liststore.get_n_columns()):
1432                col = self.treeview.get_column(x)
1433                if col:
1434                    cell = col.get_cells()[0]
1435                    if isinstance(cell,Gtk.CellRendererText):
1436                        self.liststore.set_sort_func(x, self.stripsort, None)
1437            self.treeview.get_selection().unselect_all()
1438        self.modify_button.set_sensitive(False)
1439
1440    def stripsort(self, model, row1, row2, user_data):
1441        sort_column, _ = model.get_sort_column_id()
1442        val1 = self.unmarkup(model.get_value(row1, sort_column))
1443        val2 = self.unmarkup(model.get_value(row2, sort_column))
1444        return cmp(val1,val2)
1445
1446    def display_more_detail(self, windows, path):
1447        it = self.boolean_filter.get_iter(path)
1448        it = self.boolean_filter.convert_iter_to_child_iter(it)
1449
1450        self.boolean_more_detail_tree_data_set.clear()
1451        self.boolean_more_detail_window.set_title(_("Boolean %s Allow Rules") % self.boolean_liststore.get_value(it, 2))
1452        blist = sepolicy.get_boolean_rules(self.application,self.boolean_liststore.get_value(it, 2));
1453        for b in blist:
1454            self.display_more_detail_init(b["source"], b["target"], b["class"], b["permlist"])
1455        self.show_popup(self.boolean_more_detail_window)
1456
1457    def display_more_detail_init(self, source, target, class_type, permission):
1458        iter = self.boolean_more_detail_tree_data_set.append()
1459        self.boolean_more_detail_tree_data_set.set_value(iter, 0, "allow %s %s:%s { %s };" % (source, target, class_type, " ".join(permission)))
1460
1461    def add_button_clicked(self, *args):
1462        self.modify = False
1463        if self.opage == NETWORK_PAGE:
1464            self.popup_network_label.set_text((_("Add Network Port for %s.  Ports will be created when update is applied."))% self.application)
1465            self.network_popup_window.set_title((_("Add Network Port for %s"))% self.application)
1466            self.init_network_dialog(args)
1467            return
1468
1469        if self.opage == FILES_PAGE:
1470            self.popup_files_label.set_text((_("Add File Labeling for %s. File labels will be created when update is applied."))% self.application)
1471            self.files_popup_window.set_title((_("Add File Labeling for %s"))% self.application)
1472            self.init_files_dialog(args)
1473            ipage = self.inner_notebook_files.get_current_page()
1474            if ipage == EXE_PAGE:
1475                self.files_path_entry.set_text("ex: /usr/sbin/Foobar")
1476            else:
1477                self.files_path_entry.set_text("ex: /var/lib/Foobar")
1478            self.clear_entry = True
1479
1480        if self.opage == LOGIN_PAGE:
1481            self.login_label.set_text((_("Add Login Mapping. User Mapping will be created when Update is applied.")))
1482            self.login_popup_window.set_title(_("Add Login Mapping"))
1483            self.login_init_dialog(args)
1484            self.clear_entry = True
1485
1486        if self.opage == USER_PAGE:
1487            self.user_label.set_text((_("Add SELinux User Role. SELinux user roles will be created when update is applied.")))
1488            self.user_popup_window.set_title(_("Add SELinux Users"))
1489            self.user_init_dialog(args)
1490            self.clear_entry = True
1491
1492        if self.opage == FILE_EQUIV_PAGE:
1493            self.file_equiv_source_entry.set_text("")
1494            self.file_equiv_dest_entry.set_text("")
1495            self.file_equiv_label.set_text((_("Add File Equivalency Mapping. Mapping will be created when update is applied.")))
1496            self.file_equiv_popup_window.set_title(_("Add SELinux File Equivalency"))
1497            self.clear_entry = True
1498            self.show_popup(self.file_equiv_popup_window)
1499
1500        self.new_updates()
1501
1502    def show_popup(self, window):
1503        self.current_popup = window
1504        window.show()
1505
1506    def close_popup(self, *args):
1507        self.current_popup.hide()
1508        self.window.set_sensitive(True)
1509        return True
1510
1511    def modify_button_clicked(self, *args):
1512        iter = None
1513        if self.treeview:
1514            iter = self.get_selected_iter()
1515            if not iter:
1516                self.modify_button.set_sensitive(False)
1517                return
1518        self.modify = True
1519        if self.opage == NETWORK_PAGE:
1520            self.modify_button_network_clicked(args)
1521
1522        if self.opage == FILES_PAGE:
1523            self.popup_files_label.set_text((_("Modify File Labeling for %s. File labels will be created when update is applied."))% self.application)
1524            self.files_popup_window.set_title((_("Add File Labeling for %s"))% self.application)
1525            self.delete_old_item = None
1526            self.init_files_dialog(args)
1527            self.modify = True
1528            operation = "Modify"
1529            mls = 1
1530            ipage = self.inner_notebook_files.get_current_page()
1531
1532            if ipage == EXE_PAGE:
1533                iter = self.executable_files_filter.convert_iter_to_child_iter(iter)
1534                self.delete_old_item = iter
1535                path = self.executable_files_liststore.get_value(iter, 0)
1536                self.files_path_entry.set_text(path)
1537                ftype = self.executable_files_liststore.get_value(iter, 1)
1538                if type != None:
1539                    self.combo_set_active_text(self.files_type_combobox, ftype)
1540                tclass = self.executable_files_liststore.get_value(iter, 2)
1541                if tclass != None:
1542                    self.combo_set_active_text(self.files_class_combobox, tclass)
1543
1544            if ipage == WRITABLE_PAGE:
1545                iter = self.writable_files_filter.convert_iter_to_child_iter(iter)
1546                self.delete_old_item = iter
1547                path = self.writable_files_liststore.get_value(iter, 0)
1548                self.files_path_entry.set_text(path)
1549                type = self.writable_files_liststore.get_value(iter, 1)
1550                if type != None:
1551                    self.combo_set_active_text(self.files_type_combobox, type)
1552                tclass = self.writable_files_liststore.get_value(iter, 2)
1553                if tclass != None:
1554                    self.combo_set_active_text(self.files_class_combobox, tclass)
1555
1556            if ipage == APP_PAGE:
1557                iter = self.application_files_filter.convert_iter_to_child_iter(iter)
1558                self.delete_old_item = iter
1559                path = self.application_files_liststore.get_value(iter, 0)
1560                self.files_path_entry.set_text(path)
1561                try:
1562                    get_type = self.application_files_liststore.get_value(iter, 1)
1563                    get_type = get_type.split("<b>")[1].split("</b>")
1564                except AttributeError:
1565                    pass
1566                type = self.application_files_liststore.get_value(iter, 2)
1567                if type != None:
1568                    self.combo_set_active_text(self.files_type_combobox, type)
1569                tclass = get_type[0]
1570                if tclass != None:
1571                    self.combo_set_active_text(self.files_class_combobox, tclass)
1572
1573        if self.opage == USER_PAGE:
1574            self.user_init_dialog(args)
1575            self.user_name_entry.set_text(self.user_liststore.get_value(iter,0))
1576            self.user_mls_level_entry.set_text(self.user_liststore.get_value(iter,2))
1577            self.user_mls_entry.set_text(self.user_liststore.get_value(iter,3))
1578            self.combo_set_active_text(self.user_roles_combobox, self.user_liststore.get_value(iter,1))
1579            self.user_label.set_text((_("Modify SELinux User Role. SELinux user roles will be modified when update is applied.")))
1580            self.user_popup_window.set_title(_("Modify SELinux Users"))
1581            self.show_popup(self.user_popup_window)
1582
1583        if self.opage == LOGIN_PAGE:
1584            self.login_init_dialog(args)
1585            self.login_name_entry.set_text(self.login_liststore.get_value(iter,0))
1586            self.login_mls_entry.set_text(self.login_liststore.get_value(iter,2))
1587            self.combo_set_active_text(self.login_seuser_combobox, self.login_liststore.get_value(iter,1))
1588            self.login_label.set_text((_("Modify Login Mapping. Login Mapping will be modified when Update is applied.")))
1589            self.login_popup_window.set_title(_("Modify Login Mapping"))
1590            self.show_popup(self.login_popup_window)
1591
1592        if self.opage == FILE_EQUIV_PAGE:
1593            self.file_equiv_source_entry.set_text(self.file_equiv_liststore.get_value(iter,0))
1594            self.file_equiv_dest_entry.set_text(self.file_equiv_liststore.get_value(iter,1))
1595            self.file_equiv_label.set_text((_("Modify File Equivalency Mapping. Mapping will be created when update is applied.")))
1596            self.file_equiv_popup_window.set_title(_("Modify SELinux File Equivalency"))
1597            self.clear_entry = True
1598            self.show_popup(self.file_equiv_popup_window)
1599
1600    def populate_type_combo(self, tree, loc, *args):
1601        iter = self.more_types_files_liststore.get_iter(loc)
1602        ftype = self.more_types_files_liststore.get_value(iter, 0)
1603        self.combo_set_active_text(self.files_type_combobox, ftype)
1604        self.show_popup(self.files_popup_window)
1605        self.moreTypes_window_files.hide()
1606
1607    def strip_domain(self, domain):
1608        if domain == None:
1609            return
1610        if domain.endswith("_script_t"):
1611            split_char="_script_t"
1612        else:
1613            split_char="_t"
1614        return domain.split(split_char)[0]
1615
1616    def exclude_type(self, type, exclude_list):
1617        for e in exclude_list:
1618            if type.startswith(e):
1619                return True
1620        return False
1621
1622    def init_files_dialog(self, *args):
1623        exclude_list = []
1624        self.files_class_combobox.set_sensitive(True)
1625        self.show_popup(self.files_popup_window)
1626        ipage = self.inner_notebook_files.get_current_page()
1627        self.files_type_combolist.clear()
1628        self.files_class_combolist.clear()
1629        compare = self.strip_domain(self.application)
1630        for d in self.completion_entry_model:
1631            if d[0].startswith(compare) and d[0] != self.application and not d[0].startswith("httpd_sys"):
1632                exclude_list.append(self.strip_domain(d[0]))
1633
1634        self.more_types_files_liststore.clear()
1635        try:
1636            for files in sepolicy.file_type_str:
1637                iter = self.files_class_combolist.append()
1638                self.files_class_combolist.set_value(iter, 0, sepolicy.file_type_str[files])
1639
1640            if ipage == EXE_PAGE and self.entrypoints != None:
1641                for exe in self.entrypoints.keys():
1642                    if exe.startswith(compare):
1643                        iter = self.files_type_combolist.append()
1644                        self.files_type_combolist.set_value(iter, 0, exe)
1645                    iter = self.more_types_files_liststore.append()
1646                    self.more_types_files_liststore.set_value(iter, 0, exe)
1647                self.files_class_combobox.set_active(4)
1648                self.files_class_combobox.set_sensitive(False)
1649
1650            elif ipage == WRITABLE_PAGE and self.writable_files != None:
1651                for write in self.writable_files.keys():
1652                    if write.startswith(compare) and not self.exclude_type(write, exclude_list) and write in self.file_types:
1653                        iter = self.files_type_combolist.append()
1654                        self.files_type_combolist.set_value(iter, 0, write)
1655                    iter = self.more_types_files_liststore.append()
1656                    self.more_types_files_liststore.set_value(iter, 0, write)
1657                self.files_class_combobox.set_active(0)
1658            elif ipage == APP_PAGE and self.file_types != None:
1659                for app in sepolicy.get_all_file_types():
1660                    if app.startswith(compare):
1661                        if app.startswith(compare) and not self.exclude_type(app, exclude_list):
1662                            iter = self.files_type_combolist.append()
1663                            self.files_type_combolist.set_value(iter, 0, app)
1664                        iter = self.more_types_files_liststore.append()
1665                        self.more_types_files_liststore.set_value(iter, 0, app)
1666                self.files_class_combobox.set_active(0)
1667        except AttributeError:
1668            print "error"
1669            pass
1670        self.files_type_combobox.set_active(0)
1671        self.files_mls_entry.set_text("s0")
1672        iter = self.files_type_combolist.append()
1673        self.files_type_combolist.set_value(iter, 0, _('More...'))
1674
1675    def modify_button_network_clicked(self, *args):
1676        iter = self.get_selected_iter()
1677        if not iter:
1678            self.modify_button.set_sensitive(False)
1679            return
1680
1681        self.popup_network_label.set_text((_("Modify Network Port for %s.  Ports will be created when update is applied."))% self.application)
1682        self.network_popup_window.set_title((_("Modify Network Port for %s"))% self.application)
1683        self.delete_old_item = None
1684        self.init_network_dialog(args)
1685        operation = "Modify"
1686        mls = 1
1687        self.modify = True
1688        iter = self.get_selected_iter()
1689        port = self.liststore.get_value(iter, 0)
1690        self.network_ports_entry.set_text(port)
1691        protocol = self.liststore.get_value(iter, 1)
1692        if protocol == "tcp":
1693            self.network_tcp_button.set_active(True)
1694        elif protocol == "udp":
1695            self.network_udp_button.set_active(True)
1696        type = self.liststore.get_value(iter, 2)
1697        if type != None:
1698            self.combo_set_active_text(self.network_port_type_combobox, type)
1699        self.delete_old_item = iter
1700
1701    def init_network_dialog(self, *args):
1702        self.show_popup(self.network_popup_window)
1703        ipage = self.inner_notebook_network.get_current_page()
1704        self.network_port_type_combolist.clear()
1705        self.network_ports_entry.set_text("")
1706
1707        try:
1708            if ipage == OUTBOUND_PAGE:
1709                netd = sepolicy.network.get_network_connect(self.application, "tcp", "name_connect")
1710            elif ipage == INBOUND_PAGE:
1711                netd = sepolicy.network.get_network_connect(self.application, "tcp", "name_bind")
1712                netd += sepolicy.network.get_network_connect(self.application, "udp", "name_bind")
1713
1714            port_types = []
1715            for k in netd.keys():
1716                for t,ports in netd[k]:
1717                    if t not in port_types + ["port_t", "unreserved_port_t"]:
1718                        if t.endswith("_type"):
1719                            continue
1720
1721                        port_types.append(t)
1722
1723            port_types.sort()
1724            short_domain = self.strip_domain(self.application)
1725            if short_domain[-1] == "d":
1726                short_domain = short_domain[:-1]
1727            short_domain = short_domain + "_"
1728            ctr = 0
1729            found = 0
1730            for t in port_types:
1731                if t.startswith(short_domain):
1732                    found = ctr
1733                iter = self.network_port_type_combolist.append()
1734                self.network_port_type_combolist.set_value(iter, 0, t)
1735                ctr += 1
1736            self.network_port_type_combobox.set_active(found)
1737
1738        except AttributeError:
1739            pass
1740
1741        self.network_tcp_button.set_active(True)
1742        self.network_mls_entry.set_text("s0")
1743
1744    def login_seuser_combobox_change(self, combo, *args):
1745        seuser = self.combo_get_active_text(combo)
1746        if self.login_mls_entry.get_text() == "":
1747            for u in sepolicy.get_selinux_users():
1748                if seuser == u['name']:
1749                    self.login_mls_entry.set_text(u['range'])
1750
1751    def user_roles_combobox_change(self, combo, *args):
1752        serole = self.combo_get_active_text(combo)
1753        if self.user_mls_entry.get_text() == "":
1754            for u in sepolicy.get_all_roles():
1755                if serole == u['name']:
1756                    self.user_mls_entry.set_text(u['range'])
1757
1758    def get_selected_iter(self):
1759        iter = None
1760        if not self.treeview:
1761            return None
1762        row = self.treeview.get_selection()
1763        if not row:
1764            return None
1765        treesort, iter = row.get_selected()
1766        if iter:
1767            iter = treesort.convert_iter_to_child_iter(iter)
1768            if iter:
1769                iter = self.treefilter.convert_iter_to_child_iter(iter)
1770        return iter
1771
1772    def cursor_changed(self, *args):
1773        self.modify_button.set_sensitive(False)
1774        iter = self.get_selected_iter()
1775        if iter == None:
1776            self.modify_button.set_sensitive(False)
1777            return
1778        if not self.liststore[iter] or not self.liststore[iter][-1]:
1779            return
1780        self.modify_button.set_sensitive(self.liststore[iter][-1])
1781
1782    def login_init_dialog(self, *args):
1783        self.show_popup(self.login_popup_window)
1784        self.login_seuser_combolist.clear()
1785        users = sepolicy.get_all_users()
1786        users.sort()
1787        for u in users:
1788            iter = self.login_seuser_combolist.append()
1789            self.login_seuser_combolist.set_value(iter, 0, str(u))
1790        self.login_name_entry.set_text("")
1791        self.login_mls_entry.set_text("")
1792
1793    def user_init_dialog(self, *args):
1794        self.show_popup(self.user_popup_window)
1795        self.user_roles_combolist.clear()
1796        roles = sepolicy.get_all_roles()
1797        roles.sort()
1798        for r in roles:
1799            iter = self.user_roles_combolist.append()
1800            self.user_roles_combolist.set_value(iter, 0, str(r))
1801        self.user_name_entry.set_text("")
1802        self.user_mls_entry.set_text("")
1803
1804    def on_disable_ptrace(self, checkbutton):
1805        if self.finish_init:
1806            update_buffer = "boolean -m -%d deny_ptrace" % checkbutton.get_active()
1807            self.wait_mouse()
1808            try:
1809                self.dbus.semanage(update_buffer)
1810            except dbus.exceptions.DBusException, e:
1811                self.error(e)
1812            self.ready_mouse()
1813
1814    def on_show_modified_only(self, checkbutton):
1815        length = self.liststore.get_n_columns()
1816        def dup_row(row):
1817            l = []
1818            for i in range(0,length):
1819                l.append(row[i])
1820            return l
1821
1822        append_list = []
1823        if self.opage == BOOLEANS_PAGE:
1824            if not checkbutton.get_active():
1825                return self.boolean_initialize(self.application)
1826
1827            for row in self.liststore:
1828                if row[2] in self.cust_dict["boolean"]:
1829                    append_list.append(dup_row(row))
1830
1831        if self.opage == FILES_PAGE:
1832            ipage = self.inner_notebook_files.get_current_page()
1833            if not checkbutton.get_active():
1834                if ipage == EXE_PAGE:
1835                    return self.executable_files_initialize(self.application)
1836                if ipage == WRITABLE_PAGE:
1837                    return self.writable_files_initialize(self.application)
1838                if ipage == APP_PAGE:
1839                    return self.application_files_initialize(self.application)
1840            for row in self.liststore:
1841                if (row[0],row[2]) in self.cust_dict["fcontext"]:
1842                    append_list.append(row)
1843
1844        if self.opage == NETWORK_PAGE:
1845            if not checkbutton.get_active():
1846                return self.network_initialize(self.application)
1847            for row in self.liststore:
1848                if (row[0], row[1]) in self.cust_dict["port"]:
1849                    append_list.append(dup_row(row))
1850
1851        if self.opage == FILE_EQUIV_PAGE:
1852            if not checkbutton.get_active() == True:
1853                return self.file_equiv_initialize()
1854
1855            for row in self.liststore:
1856                if row[0] in self.cust_dict["fcontext-equiv"]:
1857                    append_list.append(dup_row(row))
1858
1859        if self.opage == USER_PAGE:
1860            if not checkbutton.get_active():
1861                return self.user_initialize()
1862
1863            for row in self.liststore:
1864                if row[0] in self.cust_dict["user"]:
1865                    append_list.append(dup_row(row))
1866
1867        if self.opage == LOGIN_PAGE:
1868            if not checkbutton.get_active() == True:
1869                return self.login_initialize()
1870
1871            for row in self.liststore:
1872                if row[0] in self.cust_dict["login"]:
1873                    append_list.append(dup_row(row))
1874
1875        self.liststore.clear()
1876        for row in append_list:
1877            iter = self.liststore.append()
1878            for i in range(0,length):
1879                self.liststore.set_value(iter, i, row[i])
1880
1881    def init_modified_files_liststore(self, tree, app, ipage, operation, path, fclass, ftype):
1882        iter = tree.append(None)
1883        tree.set_value(iter, 0, path)
1884        tree.set_value(iter, 1, ftype)
1885        tree.set_value(iter, 2, fclass)
1886
1887    def restore_to_default(self, *args):
1888        print "restore to defualt clicked..."
1889
1890    def invalid_entry_retry(self, *args):
1891        self.closewindow(self.error_check_window)
1892        self.files_popup_window.set_sensitive(True)
1893        self.network_popup_window.set_sensitive(True)
1894
1895    def error_check_files(self, insert_txt):
1896        if len(insert_txt) == 0 or insert_txt[0] != '/':
1897            self.error_check_window.show()
1898            self.files_popup_window.set_sensitive(False)
1899            self.network_popup_window.set_sensitive(False)
1900            self.error_check_label.set_text((_("The entry '%s' is not a valid path.  Paths must begin with a '/'.")) % insert_txt)
1901            return True
1902        return False
1903
1904    def error_check_network(self, port):
1905        try:
1906            pnum = int(port)
1907            if pnum < 1 or pnum > 65536:
1908                raise ValueError
1909        except ValueError:
1910            self.error_check_window.show()
1911            self.files_popup_window.set_sensitive(False)
1912            self.network_popup_window.set_sensitive(False)
1913            self.error_check_label.set_text((_("Port number must be between 1 and 65536")))
1914            return True
1915        return False
1916
1917    def show_more_types(self, *args):
1918        if self.finish_init:
1919            if self.combo_get_active_text(self.files_type_combobox) == _('More...'):
1920                self.files_popup_window.hide()
1921                self.moreTypes_window_files.show()
1922
1923    def update_to_login(self, *args):
1924        self.close_popup()
1925        seuser = self.combo_get_active_text(self.login_seuser_combobox)
1926        mls_range = self.login_mls_entry.get_text()
1927        name = self.login_name_entry.get_text()
1928        if self.modify:
1929            iter = self.get_selected_iter()
1930            oldname = self.login_liststore.get_value(iter,0)
1931            oldseuser = self.login_liststore.get_value(iter,1)
1932            oldrange = self.login_liststore.get_value(iter,2)
1933            self.liststore.set_value(iter,0,oldname)
1934            self.liststore.set_value(iter,1,oldseuser)
1935            self.liststore.set_value(iter,2,oldrange)
1936            self.cur_dict["login"][name] = { "action": "-m", "range": mls_range, "seuser": seuser, "oldrange": oldrange, "oldseuser": oldseuser, "oldname": oldname }
1937        else:
1938            iter = self.liststore.append(None)
1939            self.cur_dict["login"][name] = { "action": "-a", "range": mls_range, "seuser": seuser }
1940
1941        self.liststore.set_value(iter,0,name)
1942        self.liststore.set_value(iter,1,seuser)
1943        self.liststore.set_value(iter,2, mls_range)
1944
1945        self.new_updates()
1946
1947    def update_to_user(self, *args):
1948        self.close_popup()
1949        roles = self.combo_get_active_text(self.user_roles_combobox)
1950        level = self.user_mls_level_entry.get_text()
1951        mls_range = self.user_mls_entry.get_text()
1952        name = self.user_name_entry.get_text()
1953        if self.modify:
1954            iter = self.get_selected_iter()
1955            oldname = self.user_liststore.get_value(iter,0)
1956            oldroles = self.user_liststore.get_value(iter,1)
1957            oldlevel = self.user_liststore.get_value(iter,1)
1958            oldrange = self.user_liststore.get_value(iter,3)
1959            self.liststore.set_value(iter,0,oldname)
1960            self.liststore.set_value(iter,1,oldroles)
1961            self.liststore.set_value(iter,2,oldlevel)
1962            self.liststore.set_value(iter,3,oldrange)
1963            self.cur_dict["user"][name] = { "action": "-m", "range": mls_range, "level": level, "role":roles, "oldrange": oldrange, "oldlevel": oldlevel, "oldroles": oldroles, "oldname": oldname }
1964        else:
1965            iter = self.liststore.append(None)
1966            self.cur_dict["user"][name] = { "action": "-a", "range": mls_range, "level": level, "role": roles}
1967
1968        self.liststore.set_value(iter, 0, name)
1969        self.liststore.set_value(iter, 1, roles)
1970        self.liststore.set_value(iter, 2, level)
1971        self.liststore.set_value(iter, 3, mls_range)
1972
1973        self.new_updates()
1974
1975    def update_to_file_equiv(self, *args):
1976        self.close_popup()
1977        dest = self.file_equiv_dest_entry.get_text()
1978        src = self.file_equiv_source_entry.get_text()
1979        if self.modify:
1980            iter = self.get_selected_iter()
1981            olddest = self.unmarkup(self.liststore.set_value(iter,0))
1982            oldsrc = self.unmarkup(self.liststore.set_value(iter,1))
1983            self.cur_dict["fcontext-equiv"][dest] = { "action": "-m", "src": src, "oldsrc": oldsrc, "olddest": olddest }
1984        else:
1985            iter = self.liststore.append(None)
1986            self.cur_dict["fcontext-equiv"][dest] = { "action": "-a", "src": src }
1987        self.liststore.set_value(iter,0,self.markup(dest))
1988        self.liststore.set_value(iter,1,self.markup(src))
1989
1990    def update_to_files(self, *args):
1991        self.close_popup()
1992        self.files_add = True
1993        # Insert Function will be used in the future
1994        path = self.files_path_entry.get_text()
1995        if self.error_check_files(path):
1996            return
1997
1998        setype = self.combo_get_active_text(self.files_type_combobox)
1999        mls = self.files_mls_entry.get_text()
2000        tclass = self.combo_get_active_text(self.files_class_combobox)
2001
2002        if self.modify:
2003            iter = self.get_selected_iter()
2004            oldpath = self.unmark(self.liststore.get_value(iter, 0))
2005            setype = self.unmark(self.liststore.set_value(iter, 1))
2006            oldtclass = self.liststore.get_value(iter, 2)
2007            self.cur_dict["fcontext"][(path, tclass)] = { "action": "-m", "type": setype, "oldtype": oldsetype, "oldmls": oldmls, "oldclass": oldclass }
2008        else:
2009            iter = self.liststore.append(None)
2010            self.cur_dict["fcontext"][(path, tclass)] = { "action": "-a", "type": setype }
2011        self.liststore.set_value(iter, 0, self.markup(path))
2012        self.liststore.set_value(iter, 1, self.markup(setype))
2013        self.liststore.set_value(iter, 2, self.markup(tclass))
2014
2015        self.files_add = False
2016        self.recursive_path_toggle.set_active(False)
2017        self.new_updates()
2018
2019    def update_to_network(self, *args):
2020        self.network_add = True
2021        ports = self.network_ports_entry.get_text()
2022        if self.error_check_network(ports):
2023            return
2024        if self.network_tcp_button.get_active():
2025            protocol = "tcp"
2026        else:
2027            protocol = "udp"
2028
2029        setype = self.combo_get_active_text(self.network_port_type_combobox)
2030        mls = self.network_mls_entry.get_text()
2031
2032        if self.modify:
2033            iter = self.get_selected_iter()
2034            oldports = self.unmark(self.liststore.get_value(iter, 0))
2035            oldprotocol = self.unmark(self.liststore.get_value(iter, 1))
2036            oldsetype = self.unmark(self.liststore.set_value(iter, 2))
2037            self.cur_dict["port"][(ports, protocol)] = { "action": "-m", "type": setype, "mls": mls, "oldtype": oldsetype, "oldmls": oldmls, "oldprotocol": oldprotocol, "oldports": oldports }
2038        else:
2039            iter = self.liststore.append(None)
2040            self.cur_dict["port"][(ports, protocol)] = { "action": "-a", "type": setype, "mls": mls}
2041        self.liststore.set_value(iter, 0, ports)
2042        self.liststore.set_value(iter, 1, protocol)
2043        self.liststore.set_value(iter, 2, setype)
2044
2045        self.network_add = False
2046        self.network_popup_window.hide()
2047        self.window.set_sensitive(True)
2048        self.new_updates()
2049
2050    def delete_button_clicked(self, *args):
2051        operation = "Add"
2052        self.window.set_sensitive(False)
2053        if self.opage == NETWORK_PAGE:
2054            self.network_delete_liststore.clear()
2055            port_dict = self.cust_dict["port"]
2056            for ports,protocol in port_dict:
2057                setype = port_dict[(ports, protocol)]["type"]
2058                iter = self.network_delete_liststore.append()
2059                self.network_delete_liststore.set_value(iter, 1, ports)
2060                self.network_delete_liststore.set_value(iter, 2, protocol)
2061                self.network_delete_liststore.set_value(iter, 3, setype)
2062            self.show_popup(self.network_delete_window)
2063            return
2064
2065        if self.opage == FILES_PAGE:
2066            self.files_delete_liststore.clear()
2067            fcontext_dict = self.cust_dict["fcontext"]
2068            for path,tclass in fcontext_dict:
2069                setype = fcontext_dict[(path, tclass)]["type"]
2070                iter = self.files_delete_liststore.append()
2071                self.files_delete_liststore.set_value(iter, 1, path)
2072                self.files_delete_liststore.set_value(iter, 2, setype)
2073                self.files_delete_liststore.set_value(iter, 3, sepolicy.file_type_str[tclass])
2074            self.show_popup(self.files_delete_window)
2075            return
2076
2077        if self.opage == USER_PAGE:
2078            self.user_delete_liststore.clear()
2079            user_dict = self.cust_dict["user"]
2080            for user in user_dict:
2081                roles = user_dict[user]["role"]
2082                mls = user_dict[user]["range"]
2083                level = user_dict[user]["level"]
2084                iter = self.user_delete_liststore.append()
2085                self.user_delete_liststore.set_value(iter, 1, user)
2086                self.user_delete_liststore.set_value(iter, 2, roles)
2087                self.user_delete_liststore.set_value(iter, 3, level)
2088                self.user_delete_liststore.set_value(iter, 4, mls)
2089            self.show_popup(self.user_delete_window)
2090            return
2091
2092        if self.opage == LOGIN_PAGE:
2093            self.login_delete_liststore.clear()
2094            login_dict = self.cust_dict["login"]
2095            for login in login_dict:
2096                seuser = login_dict[login]["seuser"]
2097                mls = login_dict[login]["range"]
2098                iter = self.login_delete_liststore.append()
2099                self.login_delete_liststore.set_value(iter, 1, seuser)
2100                self.login_delete_liststore.set_value(iter, 2, login)
2101                self.login_delete_liststore.set_value(iter, 3, mls)
2102            self.show_popup(self.login_delete_window)
2103            return
2104
2105        if self.opage == FILE_EQUIV_PAGE:
2106            self.file_equiv_delete_liststore.clear()
2107            for items in self.file_equiv_liststore:
2108                if items[2]:
2109                    iter = self.file_equiv_delete_liststore.append()
2110                    self.file_equiv_delete_liststore.set_value(iter, 1, self.unmarkup(items[0]))
2111                    self.file_equiv_delete_liststore.set_value(iter, 2, self.unmarkup(items[1]))
2112            self.show_popup(self.file_equiv_delete_window)
2113            return
2114
2115    def on_save_delete_clicked(self, *args):
2116        self.close_popup()
2117        if self.opage == NETWORK_PAGE:
2118            for delete in self.network_delete_liststore:
2119                if delete[0]:
2120                    self.cur_dict["port"][(delete[1], delete[2])] = { "action": "-d", "type": delete[3] }
2121        if self.opage == FILES_PAGE:
2122            for delete in self.files_delete_liststore:
2123                if delete[0]:
2124                    self.cur_dict["fcontext"][(delete[1], reverse_file_type_str[delete[3]])] = { "action": "-d", "type": delete[2] }
2125        if self.opage == USER_PAGE:
2126            for delete in self.user_delete_liststore:
2127                if delete[0]:
2128                    self.cur_dict["user"][delete[1]] = { "action": "-d" , "role": delete[2], "range": delete[4] }
2129        if self.opage == LOGIN_PAGE:
2130            for delete in self.login_delete_liststore:
2131                if delete[0]:
2132                    self.cur_dict["login"][delete[2]] = { "action": "-d", "login":delete[2], "seuser":delete[1], "range":delete[3] }
2133        if self.opage == FILE_EQUIV_PAGE:
2134            for delete in self.file_equiv_delete_liststore:
2135                if delete[0]:
2136                    self.cur_dict["fcontext-equiv"][delete[1]] = { "action": "-d", "src" : delete[2] }
2137        self.new_updates()
2138
2139    def on_save_delete_file_equiv_clicked(self, *args):
2140        for delete in self.files_delete_liststore:
2141            print delete[0], delete[1], delete[2],
2142
2143    def on_toggle_update(self, cell, path, model):
2144        model[path][0] = not model[path][0]
2145
2146    def ipage_delete(self, liststore, key):
2147        ctr = 0
2148        for items in liststore:
2149            if items[0] == key[0] and items[2] == key[1]:
2150                iter = liststore.get_iter(ctr)
2151                liststore.remove(iter)
2152                return
2153            ctr+=1
2154
2155    def on_toggle(self, cell, path, model):
2156        if not path:
2157            return
2158        iter = self.boolean_filter.get_iter(path)
2159        iter = self.boolean_filter.convert_iter_to_child_iter(iter)
2160        name = model.get_value(iter, 2)
2161        model.set_value(iter, 0, not model.get_value(iter, 0))
2162        active = model.get_value(iter, 0)
2163        if name in self.cur_dict["boolean"]:
2164            del(self.cur_dict["boolean"][name])
2165        else:
2166            self.cur_dict["boolean"][name] = {"active":active}
2167        self.new_updates()
2168
2169    def get_advanced_filter_data(self, entry, *args):
2170        self.filter_txt = entry.get_text()
2171        self.advanced_search_filter.refilter()
2172
2173    def get_filter_data(self, windows, *args):
2174        #search for desired item
2175        # The txt that the use rinputs into the filter is stored in filter_txt
2176        self.filter_txt = windows.get_text()
2177        self.treefilter.refilter()
2178
2179    def update_gui(self, *args):
2180        self.update = True
2181        self.update_treestore.clear()
2182        for bools in self.cur_dict["boolean"]:
2183            operation = self.cur_dict["boolean"][bools]["action"]
2184            iter = self.update_treestore.append(None)
2185            self.update_treestore.set_value(iter, 0, True)
2186            self.update_treestore.set_value(iter, 1,  sepolicy.boolean_desc(bools))
2187            self.update_treestore.set_value(iter, 2, action[self.cur_dict["boolean"][bools]['active']])
2188            self.update_treestore.set_value(iter, 3, True)
2189            niter = self.update_treestore.append(iter)
2190            self.update_treestore.set_value(niter, 1, (_("SELinux name: %s"))% bools)
2191            self.update_treestore.set_value(niter, 3, False)
2192
2193        for path,tclass in self.cur_dict["fcontext"]:
2194            operation = self.cur_dict["fcontext"][(path,tclass)]["action"]
2195            setype = self.cur_dict["fcontext"][(path,tclass)]["type"]
2196            iter = self.update_treestore.append(None)
2197            self.update_treestore.set_value(iter, 0, True)
2198            self.update_treestore.set_value(iter, 2, operation)
2199            self.update_treestore.set_value(iter, 0, True)
2200            if operation == "-a":
2201                self.update_treestore.set_value(iter, 1, (_("Add file labeling for %s"))% self.application)
2202            if operation == "-d":
2203                self.update_treestore.set_value(iter, 1, (_("Delete file labeling for %s"))% self.application)
2204            if operation == "-m":
2205                self.update_treestore.set_value(iter, 1, (_("Modify file labeling for %s"))% self.application)
2206
2207            niter = self.update_treestore.append(iter)
2208            self.update_treestore.set_value(niter, 3, False)
2209            self.update_treestore.set_value(niter, 1, (_("File path: %s"))% path)
2210            niter = self.update_treestore.append(iter)
2211            self.update_treestore.set_value(niter, 3, False)
2212            self.update_treestore.set_value(niter, 1, (_("File class: %s"))% sepolicy.file_type_str[tclass])
2213            niter = self.update_treestore.append(iter)
2214            self.update_treestore.set_value(niter, 3, False)
2215            self.update_treestore.set_value(niter, 1, (_("SELinux file type: %s"))% setype)
2216
2217        for port,protocol in self.cur_dict["port"]:
2218            operation = self.cur_dict["port"][(port,protocol)]["action"]
2219            iter = self.update_treestore.append(None)
2220            self.update_treestore.set_value(iter, 0, True)
2221            self.update_treestore.set_value(iter, 2, operation)
2222            self.update_treestore.set_value(iter, 3, True)
2223            if operation == "-a":
2224                self.update_treestore.set_value(iter, 1, (_("Add ports for %s"))% self.application)
2225            if operation == "-d":
2226                self.update_treestore.set_value(iter, 1, (_("Delete ports for %s"))% self.application)
2227            if operation == "-m":
2228                self.update_treestore.set_value(iter, 1, (_("Modify ports for %s"))% self.application)
2229
2230            niter = self.update_treestore.append(iter)
2231            self.update_treestore.set_value(niter, 1, (_("Network ports: %s"))% port)
2232            self.update_treestore.set_value(niter, 3, False)
2233            niter = self.update_treestore.append(iter)
2234            self.update_treestore.set_value(niter, 1, (_("Network protocol: %s"))% protocol)
2235            self.update_treestore.set_value(niter, 3, False)
2236            setype = self.cur_dict["port"][(port, protocol)]["type"]
2237            niter = self.update_treestore.append(iter)
2238            self.update_treestore.set_value(niter, 3, False)
2239            self.update_treestore.set_value(niter, 1, (_("SELinux file type: %s"))% setype)
2240
2241        for user in self.cur_dict["user"]:
2242            operation = self.cur_dict["user"][user]["action"]
2243            iter = self.update_treestore.append(None)
2244            self.update_treestore.set_value(iter, 0, True)
2245            self.update_treestore.set_value(iter, 2, operation)
2246            self.update_treestore.set_value(iter, 0, True)
2247            if operation == "-a":
2248                self.update_treestore.set_value(iter, 1, _("Add user"))
2249            if operation == "-d":
2250                self.update_treestore.set_value(iter, 1, _("Delete user"))
2251            if operation == "-m":
2252                self.update_treestore.set_value(iter, 1, _("Modify user"))
2253
2254            niter = self.update_treestore.append(iter)
2255            self.update_treestore.set_value(niter, 1, (_("SELinux User : %s"))% user)
2256            self.update_treestore.set_value(niter, 3, False)
2257            niter = self.update_treestore.append(iter)
2258            self.update_treestore.set_value(niter, 3, False)
2259            roles = self.cur_dict["user"][user]["role"]
2260            self.update_treestore.set_value(niter, 1, (_("Roles: %s")) % roles)
2261            mls = self.cur_dict["user"][user]["range"]
2262            niter = self.update_treestore.append(iter)
2263            self.update_treestore.set_value(niter, 3, False)
2264            self.update_treestore.set_value(niter, 1, _("MLS/MCS Range: %s") % mls)
2265
2266        for login in self.cur_dict["login"]:
2267            operation = self.cur_dict["login"][login]["action"]
2268            iter = self.update_treestore.append(None)
2269            self.update_treestore.set_value(iter, 0, True)
2270            self.update_treestore.set_value(iter, 2, operation)
2271            self.update_treestore.set_value(iter, 0, True)
2272            if operation == "-a":
2273                self.update_treestore.set_value(iter, 1, _("Add login mapping"))
2274            if operation == "-d":
2275                self.update_treestore.set_value(iter, 1, _("Delete login mapping"))
2276            if operation == "-m":
2277                self.update_treestore.set_value(iter, 1, _("Modify login mapping"))
2278
2279            niter = self.update_treestore.append(iter)
2280            self.update_treestore.set_value(niter, 3, False)
2281            self.update_treestore.set_value(niter, 1, (_("Login Name : %s"))% login)
2282            niter = self.update_treestore.append(iter)
2283            self.update_treestore.set_value(niter, 3, False)
2284            seuser = self.cur_dict["login"][login]["seuser"]
2285            self.update_treestore.set_value(niter, 1, (_("SELinux User: %s")) % seuser)
2286            mls = self.cur_dict["login"][login]["range"]
2287            niter = self.update_treestore.append(iter)
2288            self.update_treestore.set_value(niter, 3, False)
2289            self.update_treestore.set_value(niter, 1, _("MLS/MCS Range: %s") % mls)
2290
2291        for path in self.cur_dict["fcontext-equiv"]:
2292            operation = self.cur_dict["fcontext-equiv"][path]["action"]
2293            iter = self.update_treestore.append(None)
2294            self.update_treestore.set_value(iter, 0, True)
2295            self.update_treestore.set_value(iter, 2, operation)
2296            self.update_treestore.set_value(iter, 0, True)
2297            if operation == "-a":
2298                self.update_treestore.set_value(iter, 1, (_("Add file equiv labeling.")))
2299            if operation == "-d":
2300                self.update_treestore.set_value(iter, 1, (_("Delete file equiv labeling.")))
2301            if operation == "-m":
2302                self.update_treestore.set_value(iter, 1, (_("Modify file equiv labeling.")))
2303
2304            niter = self.update_treestore.append(iter)
2305            self.update_treestore.set_value(niter, 3, False)
2306            self.update_treestore.set_value(niter, 1, (_("File path : %s"))% path)
2307            niter = self.update_treestore.append(iter)
2308            self.update_treestore.set_value(niter, 3, False)
2309            src = self.cur_dict["fcontext-equiv"][path]["src"]
2310            self.update_treestore.set_value(niter, 1, (_("Equivalence: %s")) % src)
2311
2312        self.show_popup(self.update_window)
2313
2314    def set_active_application_button(self):
2315        if self.boolean_radio_button.get_active():
2316            self.active_button = self.boolean_radio_button
2317        if self.files_radio_button.get_active():
2318            self.active_button = self.files_radio_button
2319        if self.transitions_radio_button.get_active():
2320            self.active_button = self.transitions_radio_button
2321        if self.network_radio_button.get_active():
2322            self.active_button = self.network_radio_button
2323
2324    def clearbuttons(self, clear=True):
2325        self.main_selection_window.hide()
2326        self.boolean_radio_button.set_visible(False)
2327        self.files_radio_button.set_visible(False)
2328        self.network_radio_button.set_visible(False)
2329        self.transitions_radio_button.set_visible(False)
2330        self.system_radio_button.set_visible(False)
2331        self.lockdown_radio_button.set_visible(False)
2332        self.user_radio_button.set_visible(False)
2333        self.login_radio_button.set_visible(False)
2334        if clear:
2335            self.completion_entry.set_text("")
2336
2337    def show_system_page(self):
2338        self.clearbuttons()
2339        self.system_radio_button.set_visible(True)
2340        self.lockdown_radio_button.set_visible(True)
2341        self.applications_selection_button.set_label(_("System"))
2342        self.system_radio_button.set_active(True)
2343        self.tab_change()
2344        self.idle_func()
2345
2346    def show_file_equiv_page(self, *args):
2347        self.clearbuttons()
2348        self.file_equiv_initialize()
2349        self.file_equiv_radio_button.set_active(True)
2350        self.applications_selection_button.set_label(_("File Equivalence"))
2351        self.tab_change()
2352        self.idle_func()
2353        self.add_button.set_sensitive(True)
2354        self.delete_button.set_sensitive(True)
2355
2356    def show_users_page(self):
2357        self.clearbuttons()
2358        self.login_radio_button.set_visible(True)
2359        self.user_radio_button.set_visible(True)
2360        self.applications_selection_button.set_label(_("Users"))
2361        self.login_radio_button.set_active(True)
2362        self.tab_change()
2363        self.user_initialize()
2364        self.login_initialize()
2365        self.idle_func()
2366        self.add_button.set_sensitive(True)
2367        self.delete_button.set_sensitive(True)
2368
2369    def show_applications_page(self):
2370        self.clearbuttons(False)
2371        self.boolean_radio_button.set_visible(True)
2372        self.files_radio_button.set_visible(True)
2373        self.network_radio_button.set_visible(True)
2374        self.transitions_radio_button.set_visible(True)
2375        self.boolean_radio_button.set_active(True)
2376        self.tab_change()
2377        self.idle_func()
2378
2379    def system_interface(self, *args):
2380        self.show_system_page()
2381
2382    def users_interface(self, *args):
2383        self.show_users_page()
2384
2385    def show_mislabeled_files(self, checkbutton, *args):
2386        iterlist = []
2387        ctr = 0
2388        ipage = self.inner_notebook_files.get_current_page()
2389        if checkbutton.get_active() == True:
2390            for items in self.liststore:
2391                iter = self.treesort.get_iter(ctr)
2392                iter = self.treesort.convert_iter_to_child_iter(iter)
2393                iter = self.treefilter.convert_iter_to_child_iter(iter)
2394                if iter != None:
2395                    if self.liststore.get_value(iter, 4) == False:
2396                        iterlist.append(iter)
2397                    ctr +=1
2398            for iters in iterlist:
2399                self.liststore.remove(iters)
2400
2401        elif self.application != None:
2402            self.liststore.clear()
2403            if ipage == EXE_PAGE:
2404                self.executable_files_initialize(self.application)
2405            elif ipage == WRITABLE_PAGE:
2406                self.writable_files_initialize(self.application)
2407            elif ipage == APP_PAGE:
2408                self.application_files_initialize(self.application)
2409
2410    def fix_mislabeled(self, path):
2411        cur = selinux.getfilecon(path)[1].split(":")[2]
2412        con = selinux.matchpathcon(path,0)[1].split(":")[2]
2413        if self.verify(_("Run restorecon on %(PATH)s to change its type from %(CUR_CONTEXT)s to the default %(DEF_CONTEXT)s?") % {"PATH":path, "CUR_CONTEXT": cur, "DEF_CONTEXT": con}, title="restorecon dialog") == Gtk.ResponseType.YES:
2414            self.dbus.restorecon(path)
2415            self.application_selected()
2416
2417    def new_updates(self, *args):
2418        self.update_button.set_sensitive(self.modified())
2419        self.revert_button.set_sensitive(self.modified())
2420
2421    def update_or_revert_changes(self, button, *args):
2422        self.update_gui()
2423        self.update = (button.get_label() == _("Update"))
2424        if self.update:
2425            self.update_window.set_title(_("Update Changes"))
2426        else:
2427            self.update_window.set_title(_("Revert Changes"))
2428
2429    def apply_changes_button_press(self, *args):
2430        self.close_popup()
2431        if self.update:
2432            self.update_the_system()
2433        else:
2434            self.revert_data()
2435        self.finish_init = False
2436        self.previously_modified_initialize(self.dbus.customized())
2437        self.finish_init = True
2438        self.clear_filters()
2439        self.application_selected()
2440        self.new_updates()
2441        self.update_treestore.clear()
2442
2443    def update_the_system(self, *args):
2444        self.close_popup()
2445        update_buffer = self.format_update()
2446        self.wait_mouse()
2447        try:
2448            self.dbus.semanage(update_buffer)
2449        except dbus.exceptions.DBusException, e:
2450            print e
2451        self.ready_mouse()
2452        self.init_cur()
2453
2454    def ipage_value_lookup(self, lookup):
2455        ipage_values = {"Executable Files": 0, "Writable Files": 1, "Application File Type": 2, "Inbound": 1, "Outbound": 0}
2456        for value in ipage_values:
2457            if value == lookup:
2458                return ipage_values[value]
2459        return "Booleans"
2460
2461    def get_attributes_update(self, attribute):
2462        attribute = attribute.split(": ")[1]
2463        bool_id = attribute.split(": ")[0]
2464        if bool_id == "SELinux name":
2465            self.bool_revert = attribute
2466        else:
2467            return attribute
2468
2469    def format_update(self):
2470        self.revert_data()
2471        update_buffer = ""
2472        for k in self.cur_dict:
2473            if k in "boolean":
2474                for b in self.cur_dict[k]:
2475                    update_buffer += "boolean -m -%d %s\n" % (self.cur_dict[k][b]["active"], b)
2476            if k in "login":
2477                for l in self.cur_dict[k]:
2478                    if self.cur_dict[k][l]["action"] == "-d":
2479                        update_buffer += "login -d %s\n" % l
2480                    else:
2481                        update_buffer += "login %s -s %s -r %s %s\n" % (self.cur_dict[k][l]["action"], self.cur_dict[k][l]["seuser"], self.cur_dict[k][l]["range"], l)
2482            if k in "user":
2483                for u in self.cur_dict[k]:
2484                    if self.cur_dict[k][u]["action"] == "-d":
2485                        update_buffer += "user -d %s\n" % u
2486                    else:
2487                        update_buffer += "user %s -L %s -r %s -R %s %s\n" % (self.cur_dict[k][u]["action"], self.cur_dict[k][u]["level"], self.cur_dict[k][u]["range"], self.cur_dict[k][u]["role"], u)
2488
2489            if k in "fcontext-equiv":
2490                for f in self.cur_dict[k]:
2491                    if self.cur_dict[k][f]["action"] == "-d":
2492                        update_buffer += "fcontext -d %s\n" % f
2493                    else:
2494                        update_buffer += "fcontext %s -e %s %s\n" % (self.cur_dict[k][f]["action"], self.cur_dict[k][f]["src"], f)
2495
2496            if k in "fcontext":
2497                for f in self.cur_dict[k]:
2498                    if self.cur_dict[k][f]["action"] == "-d":
2499                        update_buffer += "fcontext -d %s\n" % f
2500                    else:
2501                        update_buffer += "fcontext %s -t %s -f %s %s\n" % (self.cur_dict[k][f]["action"], self.cur_dict[k][f]["type"], self.cur_dict[k][f]["class"], f)
2502
2503            if k in "port":
2504                for port, protocol in self.cur_dict[k]:
2505                    if self.cur_dict[k][(port, protocol)]["action"] == "-d":
2506                        update_buffer += "port -d -p %s %s\n" % (protocol, port)
2507                    else:
2508                        update_buffer += "port %s -t %s -p %s %s\n" % (self.cur_dict[k][f]["action"], self.cur_dict[k][f]["type"], procotol, port)
2509
2510        return update_buffer
2511
2512    def revert_data(self):
2513        ctr = 0
2514        remove_list=[]
2515        update_buffer =  ""
2516        for items in self.update_treestore:
2517            if not self.update_treestore[ctr][0]:
2518                remove_list.append(ctr)
2519            ctr += 1
2520        remove_list.reverse()
2521        for ctr in remove_list:
2522            self.remove_cur(ctr)
2523
2524    def reveal_advanced_system(self, label, *args):
2525        advanced = label.get_text() == ADVANCED_LABEL[0]
2526        if advanced:
2527            label.set_text(ADVANCED_LABEL[1])
2528        else:
2529            label.set_text(ADVANCED_LABEL[0])
2530        self.system_policy_label.set_visible(advanced)
2531        self.system_policy_type_combobox.set_visible(advanced)
2532
2533    def reveal_advanced(self, label, *args):
2534        advanced = label.get_text() == ADVANCED_LABEL[0]
2535        if advanced:
2536            label.set_text(ADVANCED_LABEL[1])
2537        else:
2538            label.set_text(ADVANCED_LABEL[0])
2539        self.files_mls_label.set_visible(advanced)
2540        self.files_mls_entry.set_visible(advanced)
2541        self.network_mls_label.set_visible(advanced)
2542        self.network_mls_entry.set_visible(advanced)
2543
2544    def advanced_search_initialize(self, path):
2545        try:
2546            if path[0] == '/':
2547                domain = sepolicy.get_init_transtype(path)
2548            else:
2549                domain = path
2550        except IndexError:
2551            return
2552        except OSError:
2553            return
2554        iter = self.advanced_search_liststore.append()
2555        self.advanced_search_liststore.set_value(iter, 0, path)
2556        self.advanced_search_liststore.set_value(iter, 1, domain)
2557        user_types = sepolicy.get_user_types()
2558        if domain in user_types + ['initrc_t']:
2559            return
2560
2561        entrypoints = sepolicy.get_entrypoints(domain)
2562        # From entry_point = 0 to the number of keys in the dic
2563        for exe in entrypoints:
2564            if len(entrypoints[exe]):
2565                file_class  = entrypoints[exe][1]
2566                for path in entrypoints[exe][0]:
2567                    iter = self.advanced_search_liststore.append()
2568                    self.advanced_search_liststore.set_value(iter, 1, domain)
2569                    self.advanced_search_liststore.set_value(iter, 0, path)
2570
2571    def advanced_label_main(self, label, *args):
2572        if label.get_text() == ADVANCED_SEARCH_LABEL[1]:
2573            label.set_text(ADVANCED_SEARCH_LABEL[0])
2574            self.close_popup()
2575        else:
2576            label.set_text(ADVANCED_SEARCH_LABEL[1])
2577            self.show_popup(self.advanced_search_window)
2578
2579    def advanced_radio_select(self, button):
2580        label = ""
2581        if button.get_active():
2582            label = button.get_label()
2583        if label == '':
2584            return
2585        self.advanced_search_liststore.clear()
2586        if label == "All":
2587            for items in self.all_list:
2588                self.advanced_search_initialize(items)
2589                self.idle_func()
2590
2591        elif label == "Installed":
2592            if self.installed_list == []:
2593                return
2594            for items in self.installed_list:
2595                self.advanced_search_initialize(items)
2596                self.idle_func()
2597
2598    def set_enforce_text(self, value):
2599        if value:
2600           self.status_bar.push(self.context_id, _("System Status: Enforcing"))
2601        else:
2602            self.status_bar.push(self.context_id, _("System Status: Permissive"))
2603        self.current_status_permissive.set_active(True)
2604
2605    def set_enforce(self, button):
2606        self.dbus.setenforce(button.get_active())
2607        self.set_enforce_text(button.get_active())
2608
2609    def on_browse_select(self, *args):
2610        filename = self.file_dialog.get_filename()
2611        if filename == None:
2612            return
2613        self.clear_entry = False
2614        self.file_dialog.hide()
2615        self.files_path_entry.set_text(filename)
2616        if self.import_export == 'Import':
2617            self.import_config(filename)
2618        elif self.import_export == 'Export':
2619            self.export_config(filename)
2620
2621    def recursive_path(self, *args):
2622        path = self.files_path_entry.get_text()
2623        if self.recursive_path_toggle.get_active():
2624            if not path.endswith("(/.*)?"):
2625                self.files_path_entry.set_text(path+"(/.*)?")
2626        elif path.endswith("(/.*)?"):
2627            path = path.split("(/.*)?")[0]
2628            self.files_path_entry.set_text(path)
2629
2630    def highlight_entry_text(self, entry_obj, *args):
2631        txt = entry_obj.get_text()
2632        if self.clear_entry:
2633            entry_obj.set_text('')
2634            self.clear_entry = False
2635
2636    def autofill_add_files_entry(self, entry):
2637        text = entry.get_text()
2638        if text == '':
2639            return
2640        if text.endswith("(/.*)?"):
2641            self.recursive_path_toggle.set_active(True)
2642        for d in sepolicy.DEFAULT_DIRS:
2643            if text.startswith(d):
2644                for t in self.files_type_combolist:
2645                    if t[0].endswith(sepolicy.DEFAULT_DIRS[d]):
2646                        self.combo_set_active_text(self.files_type_combobox, t[0])
2647
2648    def resize_columns(self, *args):
2649        self.boolean_column_1 = self.boolean_treeview.get_col(1)
2650        width = self.boolean_column_1.get_width()
2651        renderer = self.boolean_column_1.get_cell_renderers()
2652
2653    def browse_for_files(self, *args):
2654        self.file_dialog.show()
2655
2656    def close_config_window(self, *args):
2657        self.file_dialog.hide()
2658
2659    def change_default_policy(self, *args):
2660        if self.typeHistory == self.system_policy_type_combobox.get_active():
2661            return
2662
2663        if self.verify(_("Changing the policy type will cause a relabel of the entire file system on the next boot. Relabeling takes a long time depending on the size of the file system.  Do you wish to continue?")) == Gtk.ResponseType.NO:
2664            self.system_policy_type_combobox.set_active(self.typeHistory)
2665            return None
2666
2667        self.dbus.change_default_policy(self.combo_get_active_text(self.system_policy_type_combobox))
2668        self.dbus.relabel_on_boot(True)
2669        self.typeHistory = self.system_policy_type_combobox.get_active()
2670
2671    def change_default_mode(self, button):
2672        if not self.finish_init:
2673            return
2674        self.enabled_changed(button)
2675        if button.get_active():
2676            self.dbus.change_default_mode(button.get_label().lower())
2677
2678    def import_config_show(self, *args):
2679        self.file_dialog.set_action(Gtk.FileChooserAction.OPEN)
2680        self.file_dialog.set_title("Import Configuration")
2681        self.file_dialog.show()
2682        #self.file_dialog.set_uri('/tmp')
2683        self.import_export = 'Import'
2684
2685    def export_config_show(self, *args):
2686        self.file_dialog.set_action(Gtk.FileChooserAction.SAVE)
2687        self.file_dialog.set_title("Export Configuration")
2688        self.file_dialog.show()
2689        self.import_export = 'Export'
2690
2691    def export_config(self, filename):
2692        self.wait_mouse()
2693        buf = self.dbus.customized()
2694        fd = open(filename, 'w')
2695        fd.write(buf)
2696        fd.close()
2697        self.ready_mouse()
2698
2699    def import_config(self, filename):
2700        fd = open(filename, "r")
2701        buf = fd.read()
2702        fd.close()
2703        self.wait_mouse()
2704        try:
2705            self.dbus.semanage(buf)
2706        except OSError:
2707            pass
2708        self.ready_mouse()
2709
2710    def init_dictionary(self, dic, app, ipage, operation, p, q, ftype, mls, changed, old):
2711        if (app, ipage, operation) not in dic:
2712                    dic[app, ipage, operation] = {}
2713        if (p, q) not in dic[app, ipage, operation]:
2714                    dic[app, ipage, operation][p, q] = {'type': ftype, 'mls': mls, 'changed': changed, 'old': old}
2715
2716    def translate_bool(self, b):
2717        b = b.split('-')[1]
2718        if b == '0':
2719            return False
2720        if b == '1':
2721            return True
2722
2723    def relabel_on_reboot(self, *args):
2724        active = self.relabel_button.get_active()
2725        exists = os.path.exists("/.autorelabel")
2726
2727        if active and exists:
2728            return
2729        if not active and not exists:
2730            return
2731        try:
2732            self.dbus.relabel_on_boot(active)
2733        except dbus.exceptions.DBusException, e:
2734            self.error(e)
2735
2736    def closewindow(self, window, *args):
2737        window.hide()
2738        self.recursive_path_toggle.set_active(False)
2739        self.window.set_sensitive(True)
2740        if self.moreTypes_window_files == window:
2741            self.show_popup(self.files_popup_window)
2742            if self.combo_get_active_text(self.files_type_combobox) == _('More...'):
2743                self.files_type_combobox.set_active(0)
2744        if self.error_check_window == window:
2745            if self.files_add:
2746                self.show_popup(self.files_popup_window)
2747            elif self.network_add:
2748                self.show_popup(self.network_popup_window)
2749        if self.files_mls_label.get_visible() or self.network_mls_label.get_visible():
2750            self.advanced_text_files.set_visible(True)
2751            self.files_mls_label.set_visible(False)
2752            self.files_mls_entry.set_visible(False)
2753            self.advanced_text_network.set_visible(True)
2754            self.network_mls_label.set_visible(False)
2755            self.network_mls_entry.set_visible(False)
2756        if self.main_advanced_label.get_text() == ADVANCED_SEARCH_LABEL[1]:
2757            self.main_advanced_label.set_text(ADVANCED_SEARCH_LABEL[0])
2758        return True
2759
2760    def wait_mouse(self):
2761        self.window.get_window().set_cursor(self.busy_cursor)
2762        self.idle_func()
2763
2764    def ready_mouse(self):
2765        self.window.get_window().set_cursor(self.ready_cursor)
2766        self.idle_func()
2767
2768    def verify(self, message, title="" ):
2769        dlg = Gtk.MessageDialog(None, 0, Gtk.MessageType.INFO,
2770                                Gtk.ButtonsType.YES_NO,
2771                                message)
2772        dlg.set_title(title)
2773        dlg.set_position(Gtk.WindowPosition.MOUSE)
2774        dlg.show_all()
2775        rc = dlg.run()
2776        dlg.destroy()
2777        return rc
2778
2779    def error(self, message):
2780        dlg = Gtk.MessageDialog(None, 0, Gtk.MessageType.ERROR,
2781                                Gtk.ButtonsType.CLOSE,
2782                                message)
2783        dlg.set_position(Gtk.WindowPosition.MOUSE)
2784        dlg.show_all()
2785        dlg.run()
2786        dlg.destroy()
2787
2788    def enabled_changed(self, radio):
2789        if not radio.get_active():
2790            return
2791        label = radio.get_label()
2792        if label == 'Disabled' and self.enforce_mode != DISABLED:
2793            if self.verify(_("Changing to SELinux disabled requires a reboot.  It is not recommended.  If you later decide to turn SELinux back on, the system will be required to relabel.  If you just want to see if SELinux is causing a problem on your system, you can go to permissive mode which will only log errors and not enforce SELinux policy.  Permissive mode does not require a reboot.  Do you wish to continue?")) == Gtk.ResponseType.NO:
2794                self.enforce_button.set_active(True)
2795
2796        if label != 'Disabled' and self.enforce_mode == DISABLED:
2797            if self.verify(_("Changing to SELinux enabled will cause a relabel of the entire file system on the next boot. Relabeling takes a long time depending on the size of the file system.  Do you wish to continue?")) == Gtk.ResponseType.NO:
2798                self.enforce_button.set_active(True)
2799        self.enforce_button = radio
2800
2801    def clear_filters(self, *args):
2802        self.filter_entry.set_text('')
2803        self.show_modified_only.set_active(False)
2804
2805    def unconfined_toggle(self, *args):
2806        if not self.finish_init:
2807            return
2808        self.wait_mouse()
2809        if self.enable_unconfined_button.get_active():
2810            self.dbus.semanage("module -e unconfined")
2811        else:
2812            self.dbus.semanage("module -d unconfined")
2813        self.ready_mouse()
2814
2815    def permissive_toggle(self, *args):
2816        if not self.finish_init:
2817            return
2818        self.wait_mouse()
2819        if self.enable_permissive_button.get_active():
2820            self.dbus.semanage("module -e permissivedomains")
2821        else:
2822            self.dbus.semanage("module -d permissivedomains")
2823        self.ready_mouse()
2824
2825    def confirmation_close(self, button, *args):
2826        if len(self.update_treestore) > 0:
2827            if self.verify(_("You are attempting to close the application without applying your changes.\n    *    To apply changes you have made during this session, click No and click Update.\n    *    To leave the application without applying your changes, click Yes.  All changes that you have made during this session will be lost."), _("Loss of data Dialog")) == Gtk.ResponseType.NO:
2828                return True
2829        self.quit()
2830
2831    def quit(self, *args):
2832        sys.exit(0)
2833
2834if __name__ == '__main__':
2835    start = SELinuxGui()
2836