def get(self, slug): """ GET request of /configs/view query param: 'module_name' get the config of the module given by module_name """ if self.current_user: if slug == "view": module = self.get_argument( "module_name", None) # TODO handle input of wrong module name config_path = get_config_path(module) config = load_config(config_path) self.write({ 'type': 'view_config', 'module': module, 'config': config }) else: self.set_status(401) self.write({ "status": 401, "reason": "no_token", "redirect_suggestions": ["/login"] })
def ftp_upload(self, uploadlist=None, message=True): ftp1 = self.ftp_config msg = "" OK = True ftp = ftp_connect(ftp1["server"], ftp1["login"], ftp1["pass"]) if ftp is None: msg += _("No FTP connexion") return if uploadlist is None: uploadlist = ["./idefix.json"] for file1 in uploadlist: ret = ftp_send(ftp, get_config_path(file1)) if ret == True: msg += file1 + _(" sent\n") else: msg += ret OK = False ftp.close() if OK: title = "Upload OK" else: title = "ERRORS in upload" print(msg) if message: showwarning(title, msg, 1)
def requires_password(configname): if not configname: configname = get_config_path('confix.cfg') parser = ConfigParser(interpolation=None, default_section='__DEFAULT') parser.read(configname) if parser.has_section('__options'): return 'password' in parser['__options'] return False
def ftp_send(ftp, filepath, directory=None, dest_name=None): if directory: ftp.cwd(directory) # change into subdirectory if not dest_name: dest_name = os.path.split(filepath)[1] if os.path.isfile(get_config_path(filepath)): with open(get_config_path(filepath), 'rb') as f1: # file to send ftp.storbinary('STOR ' + dest_name, f1) # send the file else: message = filepath + " not found" print(message) return message # print( ftp.retrlines('LIST')) if directory: ftp.cwd('..') # return to house directory return True
def test_decrypt_config(configname, password): if not configname: configname = get_config_path('confix.cfg') parser = ConfigParser(interpolation=None, default_section='__DEFAULT') parser.read(configname) if parser.has_section('__options'): return decrypt_password(parser['__options'].get('password'), password) == password return True
def build_files(self, widget): # launched by the GO button f1 = open(get_config_path("idefix.json"), "w", newline="\n") config2 = self.rebuild_config() self.active_config_text = json.dumps( config2, indent=3 ) # update the copy in memory of the config, used to detect changes and remind the user to save. f1.write(self.active_config_text) f1.close() if not self.load_locale: # send the files by FTP. Load_locale is the development mode, where files are read and written only on the local disk self.ftp_upload()
def import_network(self, data, auto_data=None): ftp1 = self.controller.ftp_config ftp = ftp_connect(ftp1["server"], ftp1["login"], ftp1["pass"]) tmp_file = get_config_path('tmp_idefix2_conf.json') with open(tmp_file, 'w', newline="\n") as f: f.write(data) ftp_send(ftp, filepath=tmp_file, dest_name="idefix2_conf.json") os.unlink(tmp_file) if auto_data: # Optionally restore idefix_auto.conf if it was provided tmp_file = get_config_path('tmp_idefix_auto.conf') with open(tmp_file, 'w') as f: f.write(auto_data) ftp_send(ftp, filepath=tmp_file, dest_name="idefix_auto.conf") os.unlink(tmp_file) command_f = io.BytesIO() command_f.write(bytes("restore_config", "utf-8")) command_f.seek(0) # send command ftp.storlines('STOR trigger', command_f) ftp.close()
def run(self, configpath=None, offline=False, to_json=False): """Export the configuration either as a zip file if to_json=False or as a json file if to_json=True""" if not configpath: dialog = Gtk.FileChooserDialog( _("Export Config"), self.arw['window1'], Gtk.FileChooserAction.SAVE, (_("Export"), Gtk.ResponseType.ACCEPT), ) file_filter = Gtk.FileFilter() if to_json: file_filter.add_pattern('*.json') else: file_filter.add_pattern('*.zip') dialog.set_filter(file_filter) response = dialog.run() if response == Gtk.ResponseType.ACCEPT: configpath = dialog.get_filename() dialog.destroy() config2 = self.controller.rebuild_config() config2_str = json.dumps(config2, indent=3) if to_json: f1 = open(configpath, "w", newline="\n") f1.write(config2_str) f1.close() else: zf = zipfile.ZipFile(os.path.splitext(configpath)[0] + ".zip", 'w') try: x = Information.get_infos(self, "get_conf") conf_list = json.loads(x) zf.writestr("idefix2_conf.json", conf_list["idefix2_conf.json"]) if "idefix_auto.conf" in conf_list: zf.writestr("idefix_auto.conf", conf_list["idefix_auto.conf"]) except TypeError: if offline: print("No connection, skipping idefix2_conf.json") else: alert(_("Cannot retrieve network configuration from Idefix")) return zf.writestr("idefix.json", config2_str) zf.write(get_config_path('confix.cfg'), 'confix.cfg') zf.close() alert(_("Configuration saved"))
def __init__(self, arw, controller, filename=None, password=DEFAULT_KEY): self.arw = arw self.controller = controller self.password = password if not filename: filename = get_config_path('confix.cfg') self.filename = filename self.window = self.arw['profiles_window'] self.profiles_store = self.arw['profiles_store'] self.arw['profile_context_menu'].attach_to_widget( self.arw['profiles_tree']) mode_iter = self.arw['profile_mode_store'].get_iter_first() while mode_iter: self.mode_iters[self.arw['profile_mode_store'].get_value( mode_iter, 0)] = mode_iter mode_iter = self.arw['profile_mode_store'].iter_next(mode_iter) self.config = get_config(self.filename, self.password) self.config_found = os.path.exists(self.filename)
def post(self, slug): """ POST request of /configs/update query param: 'module_name' http body: json changes the config of the module given by module_name to the json in the http body """ if self.current_user: if slug == "update": module = self.get_argument( "module_name", None) # TODO handle input of wrong module name config_path = get_config_path(module) new_config = tornado.escape.json_decode(self.request.body) write_config(config_path, new_config) else: self.set_status(401) self.write({ "status": 401, "reason": "no_token", "redirect_suggestions": ["/login"] })
def get(self, slug): """ GET request of /execution/[slug] slug can eiter be: start, stop start: query param: 'module_name' start a module stop: query param: 'module_name' stop a module """ if self.current_user: data = {} if slug == "start": module_to_start = self.get_argument("module_name", None) if module_to_start not in servers: spec = importlib.util.find_spec( ".main", MODULE_PACKAGE + module_to_start) module = importlib.util.module_from_spec(spec) sys.modules[module_to_start] = module spec.loader.exec_module(module) # starting the module application # TODO consider ssl (or use global ssl certs from platform?) # TODO maybe wrap in try/except to suggest succes to user (for now just returns True) module_config = get_config_path(module_to_start) module.apply_config( module_config) # function implemented by module module_config_path = get_config_path(module_to_start) with open(module_config_path) as json_file: module_config = json.load(json_file) module.apply_config( module_config) # function implemented by module module_app = module.make_app( ) # function implemented by module module_server = tornado.httpserver.HTTPServer( module_app, no_keep_alive=True ) # need no-keep-alive to be able to stop server port = determine_free_port() servers[module_to_start] = { "server": module_server, "port": port } # set services if hasattr(module, 'get_services') and callable( getattr(module, 'get_services')): ii = module.get_services() server_services[module_to_start] = { "port": port, "service": ii } else: server_services[module_to_start] = { "port": port, "service": {} } module_server.listen(port) self.write({ 'type': 'starting_response', 'module': module_to_start, 'success': True, 'port': port }) else: print( "module already running, starting denied. stop module first" ) self.write({ 'type': 'starting_response', 'module': module_to_start, 'port': servers[module_to_start]['port'], 'success': False, 'reason': 'already_running' }) elif slug == "stop": module_to_stop = self.get_argument("module_name", None) shutdown_module(module_to_stop) elif slug == "running": # show running things, and its config for i in server_services: print(i) data['server_services'] = server_services self.render('templates/exe.html', data=data) else: self.set_status(401) self.write({ "status": 401, "reason": "no_token", "redirect_suggestions": ["/login"] })
def __init__(self, screen, new_score=-1, endless=False, online=False): self.screen = screen if not endless: self.title = util.bigfont.render("Story Mode", True, (0, 0, 0)) elif not online: self.title = util.bigfont.render("Endless Mode", True, (0, 0, 0)) else: self.title = util.bigfont.render("Endless Online", True, (0, 0, 0)) if not Highscores.sky: Highscores.sky = util.load_image("taivas") Highscores.sky = pygame.transform.scale( Highscores.sky, (SCREEN_WIDTH, SCREEN_HEIGHT)) self.inputting = False self.input_score = -1 self.scores = [] self.done = False self.endless = endless if online: if not self.online_init(): self.done = True print("Could not get online highscores!") return self.pathname = util.get_config_path() if not endless: self.filename = self.pathname + "/scores" else: self.filename = self.pathname + "/endless_scores" try: if not os.path.exists(self.pathname): os.mkdir(self.pathname) except: print("Can't make directory " + self.pathname) self.done = True return if not os.path.exists(self.filename): #print "Creating dummy high scores" self.dummy_scores() else: try: f = codecs.open(self.filename, "r", "utf_8") i = 0 name, score = "", 0 for line in f: if i % 2 == 0: name = line.strip() else: try: score = int(line) except: print("Corrupt high score file.") self.dummy_scores() break self.scores.append((name, score)) i += 1 except: self.dummy_scores() print("Can't open file " + self.filename + " or file corrupt") if len(self.scores) < 10: print("Corrupt high score file.") self.dummy_scores() # The online highscore is always submitted if endless and new_score != -1: self.submit_score(Variables.name, new_score) if new_score > self.scores[9][1]: #print "It's a new high score!" #self.inputting = True for i in range(10): if self.scores[i][1] < new_score: self.input_score = i for j in range(9 - i): self.scores[9 - j] = self.scores[8 - j] self.scores[i] = [Variables.name, new_score] break self.write_scores()
def __init__(self, screen, new_score = -1, endless = False, online = False): self.screen = screen if not endless: self.title = util.bigfont.render("Story Mode", True, (0,0,0)) elif not online: self.title = util.bigfont.render("Endless Mode", True, (0,0,0)) else: self.title = util.bigfont.render("Endless Online", True, (0,0,0)) if not Highscores.sky: Highscores.sky = util.load_image("taivas") Highscores.sky = pygame.transform.scale(Highscores.sky, (SCREEN_WIDTH, SCREEN_HEIGHT)) self.inputting = False self.input_score = -1 self.scores = [] self.done = False self.endless = endless if online: if not self.online_init(): self.done = True print "Could not get online highscores!" return self.pathname = util.get_config_path() if not endless: self.filename = self.pathname + "/scores" else: self.filename = self.pathname + "/endless_scores" try: if not os.path.exists(self.pathname): os.mkdir(self.pathname) except: print "Can't make directory " + self.pathname self.done = True return if not os.path.exists(self.filename): #print "Creating dummy high scores" self.dummy_scores() else: try: f = codecs.open(self.filename, "r", "utf_8") i = 0 name, score = "", 0 for line in f: if i % 2 == 0: name = line.strip() else: try: score = int(line) except: print "Corrupt high score file." self.dummy_scores() break self.scores.append((name, score)) i += 1 except: self.dummy_scores() print "Can't open file " + self.filename + " or file corrupt" if len(self.scores) < 10: print "Corrupt high score file." self.dummy_scores() # The online highscore is always submitted if endless and new_score != -1: self.submit_score(Variables.name, new_score) if new_score > self.scores[9][1]: #print "It's a new high score!" #self.inputting = True for i in xrange(10): if self.scores[i][1] < new_score: self.input_score = i for j in xrange(9 - i): self.scores[9 - j] = self.scores[8 - j] self.scores[i] = [Variables.name, new_score] break self.write_scores()
def __init__(self, configname, config_password): # self.ftp_config = ftp_config # When set to true, the configuration is loaded and written from and to local files (development mode) self.load_locale = False self.mem_text = "" self.mem_time = 0 self.block_signals = False # Load the glade file self.widgets = gtk.Builder() self.widgets.set_translation_domain("confix") self.widgets.add_from_file('./confix.glade') # create an array of all objects with their name as key ar_widgets = self.widgets.get_objects() self.arw = {} for z in ar_widgets: try: name = gtk.Buildable.get_name(z) self.arw[name] = z z.name = name except: pass # Assistant self.widgets2 = gtk.Builder() self.widgets2.set_translation_domain("confix") self.widgets2.add_from_file('./assistant.glade') # create an array of all objects with their name as key ar_widgets = self.widgets2.get_objects() self.arw2 = {} for z in ar_widgets: try: name = gtk.Buildable.get_name(z) self.arw2[name] = z z.name = name except: pass self.import_json = ImportJsonDialog(self.arw, self) # self.import_json_from_idefix = ImportJsonFromIdefix(self.arw, self) # self.import_json_from_ftp = ImportJsonFromFTP(self.arw, self) self.restore_dialog = RestoreDialog(self.arw, self) self.export_json = ExportJsonDialog(self.arw, self) self.offline = False self.arw["program_title"].set_text("Confix - Version " + version) window1 = self.arw["window1"] window1.show_all() window1.set_title(_("Confix")) window1.connect("destroy", self.destroy) self.groups_manager = GroupManager(self.arw, self) if not future: for widget in ["scrolledwindow2", "toolbar3", "paned3", "box2"]: # interface prévue pour le firewall self.arw[widget].hide() self.arw["firewall_disabled"].show() else: self.arw["firewall_disabled"].hide() # images for buttons image = Gtk.Image() image.set_from_file("./data/toggle_all.png") self.all_button = image image2 = Gtk.Image() image2.set_from_file("./data/toggle_list.png") self.list_button = image2 image3 = Gtk.Image() image3.set_from_file("./data/toggle_allow.png") self.allow_button = image3 image4 = Gtk.Image() image4.set_from_file("./data/toggle_deny.png") self.deny_button = image4 image5 = Gtk.Image() image5.set_from_file("./data/toggle_all.png") self.all2_button = image5 image6 = Gtk.Image() image6.set_from_file("./data/toggle_list.png") self.list2_button = image6 # self.arw["button1"].set_image(self.blue_button) # self.arw["button1"].set_always_show_image(True) if config_password: kargs = {'password': config_password} else: kargs = {} self.profiles = ConfigProfile(self.arw, self, **kargs) # à garder $$ self.ftp_config = self.idefix_config['conf'][active_config] # set check boxes in menu self.block_signals = True self.arw['menu_autoload_check'].set_active( self.profiles.config['__options'].get('auto_load', 0) == '1') self.block_signals = False # get the style from the css file and apply it css_provider = Gtk.CssProvider() css_provider.load_from_path('./data/confix.css') screen = Gdk.Screen.get_default() style_context = Gtk.StyleContext() style_context.add_provider_for_screen(screen, css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER) # autoconnect signals for self functions self.filter_rules = FilterRules(self.arw, self) self.proxy_group = ProxyGroup(self.arw, self) self.firewall = Firewall(self.arw, self) self.users = Users(self.arw, self) self.assistant = Assistant(self.arw, self.arw2, self) self.information = Information(self.arw, self) self.idefix2_config = Idefix2Config(self.arw, self) self.users_store = self.users.users_store self.filter_store = self.filter_rules.filter_store self.proxy_rules_store = self.filter_rules.proxy_rules_store self.groups_store = self.proxy_group.groups_store self.firewall_store = self.firewall.firewall_store self.signal_handler = SignalHandler([ self, self.filter_rules, self.proxy_group, self.firewall, self.users, self.profiles, self.assistant, self.information, self.information.services, self.idefix2_config ]) self.widgets.connect_signals(self.signal_handler) self.widgets2.connect_signals(self.signal_handler) # autosave textview buffers when typing (see also drag and drop below) # and when drag is received for textView in [ "maclist", "rule_dest", "filter_#comments", "firewall_ports", "firewall_users", "firewall_comments" ]: self.arw[textView].connect("key-release-event", self.update_tv) self.arw[textView].connect("drag-data-received", self.on_drag_data_received) self.config = OrderedDict() while Gtk.events_pending(): Gtk.main_iteration() # load configuration if configname == "": # No connexion profile chosen self.ftp_config = None else: self.ftp_config = self.profiles.config[configname] ftp = self.open_connexion_profile() self.arw["configname"].set_text(configname) if self.load_locale: # development environment self.arw['loading_window'].hide() if os.path.isfile(get_config_path("dev/idefix.json")): data_str = open(get_config_path("dev/idefix.json"), "r").read() try: self.config = json.loads(data_str, object_pairs_hook=OrderedDict) self.update() except: alert( "Unable to load configuration. Please import another one." ) for category in [ "firewall", "rules", "proxy-rules", "ports-rules", "ports", "groups" ]: if category not in self.config: self.config[category] = OrderedDict() if "users" not in self.config: self.config["users"] = OrderedDict() if not future: # delete from config["firewall"] the generated lines todel = [] for key in self.config["firewall"]: if key[0:2] == "__": todel.append(key) for key in todel: del self.config["firewall"][key] # chooser # create a special store with users who have an Internet access # 0 - Name # 1 - Unused # 2 - Unused # 3 - True if sub user, False is user # 4 - True if category, False is user self.chooser_users_store = gtk.TreeStore(str, str, bool, bool) tvcolumn = gtk.TreeViewColumn(_('Groups Drag and Drop'), Gtk.CellRendererText(), text=0) self.arw["chooser"].append_column(tvcolumn) self.arw["chooser"].get_selection() self.proxy_group.set_group_store('proxy') # sel.set_mode(Gtk.SelectionMode.MULTIPLE) tvcolumn = gtk.TreeViewColumn(_('Users Drag and Drop'), Gtk.CellRendererText(), text=0) self.arw["chooser1"].append_column(tvcolumn) self.arw["chooser1"].get_selection() self.arw["chooser1"].set_model(self.chooser_users_store) # sel.set_mode(Gtk.SelectionMode.MULTIPLE) tvcolumn = gtk.TreeViewColumn(_('Firewall'), Gtk.CellRendererText(), text=0) self.arw["chooser2"].append_column(tvcolumn) # sel.set_mode(Gtk.SelectionMode.MULTIPLE) self.arw["chooser2"].get_selection() self.empty_store = EMPTY_STORE for chooser in ["chooser", "chooser1", "chooser2"]: self.arw[chooser].enable_model_drag_source( Gdk.ModifierType.BUTTON1_MASK, [], DRAG_ACTION) self.arw[chooser].drag_source_add_text_targets() self.arw[chooser].connect("drag-data-get", self.chooser_drag_data_get) # drop for TextView # see above, the line : self.arw["proxy_group"].connect("drag-data-received", self.on_drag_data_received) # icons for users list self.maclist = self.users.create_maclist() self.users.populate_users() self.filter_rules.populate_rules() self.populate_ports() self.populate_groups() self.populate_users_chooser() self.firewall.populate_firewall() self.set_check_boxes() self.set_colors() self.profiles.list_configuration_profiles() self.assistant.disable_simulated_user( ) # In case the previous user has not disabled simulation before shutting down # Assistants # manage requests uses the model of the first tab self.arw2["manage_request_tree"].set_model(self.users.users_store) self.tvcolumn = gtk.TreeViewColumn(_('Users'), self.users.cell, text=0) self.arw2["manage_request_tree"].append_column(self.tvcolumn) if not self.profiles.config_found: self.assistant.show_assistant_first() # user defined options checkbox_config = self.profiles.config['__options'].get( 'checkbox_config', 0) == '1' if checkbox_config: self.filter_rules.set_gui('check') filter_tab = self.profiles.config['__options'].get('filter_tab', 0) == '1' if filter_tab: self.arw['notebook3'].set_current_page(1) password_option = self.profiles.config['__options'].get('password') if password_option: self.arw['option_password_check'].set_active(True) self.arw['option_password_entry'].set_text(config_password) developper_menu = self.profiles.config['__options'].get( 'developper_menu', 0) == '1' if developper_menu is False: self.arw['developper_menu'].set_sensitive(False) self.arw['developper_menu'].set_visible(False) advanced_filter = self.profiles.config['__options'].get( 'advanced_filter', 0) == '1' self.arw['filter_rules_box'].set_visible(advanced_filter) auto_load = self.profiles.config['__options'].get('auto_load', 0) == '1' if auto_load: last_config = self.profiles.config['__options'].get('last_config') if last_config: configname = last_config if configname: self.ftp_config = self.profiles.config[configname] if self.open_connexion_profile(configname): self.arw["configname"].set_text(configname)