def do_socialize(self, hours): """Go out with friends. Please supply a number of hours, as in 'socialize 2' """ if "HOSPITAL_ACTIVITIES" in self.character.disease_stage: print("\tYou're not allowed outside yet") return if self.character.display_energy() < 20: print("\tYou can't summon the energy to face people right now. How about a quiet night in?") return if random.random() < self.character.disease_stage.get("SOCIALIZE_FAILURE", 0): print("\tYou get too anxious thinking about people right now. How about a quiet night in?") return if hours > 6: print("\tNone of your friends are free for more than 6 hours") hours = 6 elif random.random() < self.character.disease_stage.get("FOCUS_CHANCE", 0): print("\tYou lose track of time and stay out for 6 hours") hours = 6 effect = random.choice(self.character.disease_stage["SOCIALIZING_EFFECTS"]) if effect == "DRUNK": print("\tYou have a drink, and then another and another and another. You black out") if random.random() < ALCOHOL_POISONING_CHANCE: print("\tYou get severe alcohol poisoning") self.character.dead = True return True print("\tLater your friends, freaked out, tell you you thought you were a character from the last book you read") elif effect == "INAPPROPRIATE": print("\tYou start making more and more inappropriate jokes. Some people laugh riotously, but an old friend looks disgusted") elif effect == "PROMISCUOUS": print("\tYou hook up with someone you just met") messages = self.character.socialize(hours) messages.append("You hang out with friends. You spend $" + str(10 * hours)) for message in messages: print("\t" + message)
def update(self): if not self.permission_path: messages.append('Netopeer DBus configuration file location not specified.', 'error') return(False) xpath_user = self.dbus_ctxt.xpathEval('/busconfig/policy[@user and allow/@own = \'org.liberouter.netopeer.server\']/@user') if xpath_user: xpath_user[0].setContent(self.user) xpath_group = self.dbus_ctxt.xpathEval('/busconfig/policy[@group and allow/@send_destination = \'org.liberouter.netopeer.server\' and allow/@receive_sender = \'org.liberouter.netopeer.server\']/@group') if xpath_group: xpath_group[0].setContent(self.group) self.dbus_doc.saveFormatFile(self.permission_path, 1) if self.service_path: if self.service_content.find('User='******'User=.*$', 'User='******'\nUser='******'w') service.write(self.service_content) service.close() return(True)
def update(self): if not self.modules: return(True) # check netopeer config content modules_node = self.netopeer_ctxt.xpathEval('/d:datastores/d:startup/n:netopeer/n:modules') if not modules_node: netopeer_node = self.netopeer_ctxt.xpathEval('/d:datastores/d:startup/n:netopeer') if not netopeer_node: startup_node = self.netopeer_ctxt.xpathEval('/d:datastores/d:startup') if not startup_node: messages.append('Invalid content of the Netopeer startup datastore', 'error') return(False) netopeer_node = startup_node[0].newChild(None, 'netopeer', None) netopeer_node.newNs('urn:cesnet:tmc:netopeer:1.0', None) else: netopeer_node = netopeer_node[0] modules_node = netopeer_node.newChild(netopeer_node.ns(), 'modules', None) else: modules_node = modules_node[0] for module in self.modules: xml_module = self.netopeer_ctxt.xpathEval('/d:datastores/d:startup/n:netopeer/n:modules/n:module[n:name=\'{s}\']/n:enabled'.format(s=module.name)) if not xml_module: # create it new_module = modules_node.newChild(modules_node.ns(), 'module', None) new_module.newChild(new_module.ns(), 'name', module.name) new_module.newChild(new_module.ns(), 'enabled', 'true' if module.enabled else 'false') else: # set it according to the current value xml_module[0].setContent('true' if module.enabled else 'false') self.netopeer_doc.saveFormatFile(self.netopeer_path, 1) return(True)
def print_status(self): messages = [] hunger_time = MEAL_INTERVAL if "HUNGER_DELAY" in self.character.disease_stage: hunger_time += self.character.disease_stage["HUNGER_DELAY"] if self.character.last_meal > hunger_time: messages.append("You feel hungry") if self.character.last_sleep > SLEEP_INTERVAL: messages.append("You feel sleepy") if self.character.last_exercise > EXERCISE_INTERVAL: messages.append("You feel lethargic") if self.character.last_social > SOCIAL_INTERVAL: messages.append("You feel lonely") if self.character.last_cleaned > CLEANING_INTERVAL: messages.append("Your house is a mess") for message in messages: print("\t" + message) print() mood = self.character.display_mood() energy = self.character.display_energy() day = (self.character.hours_played // 24) + 1 hour = self.character.hours_played % 24 print("Day: " + str(day) + " Hour: " + str(hour) + " Mood: " + str(mood) + " Energy: " + str(energy) + " Money: $" + str(self.character.money) + " Food: " + str(self.character.groceries) + " meals")
def add_hours(self, hours): messages = [] #if we crossed a day boundary if (self.hours_played // 24) < ((self.hours_played + hours) // 24): self.hours_gamed = 0 self.hours_socialized = 0 self.hours_read = 0 self.hours_watched = 0 self.called_parents = False self.called_friend = False self.last_exercise += 1 self.last_social += 1 self.last_cleaned += 1 self.disease_days += 1 if self.disease_days >= self.disease_stage["LENGTH"]: if "NEXT_STAGE" not in self.disease_stage: self.dead = True messages.append("You have committed suicide") return messages messages.extend(self.change_stage(self.disease_stage["NEXT_STAGE"])) if ((self.hours_played + hours) // 24) % 7 == 0: self.money -= RENT messages.append("Rent and bills due. $" + str(RENT) + " deducted") self.last_meal += hours self.last_sleep += hours self.hours_played += hours if "EFFECT" in self.disease_stage and random.random() < stages.SIDE_EFFECT_FREQ: messages.append(self.disease_stage["EFFECT"]["MESSAGE"]) if random.random() < self.disease_stage["THOUGHT_FREQ"] * hours: messages.append(random.choice(self.disease_stage["THOUGHTS"])) if self.last_meal > 24 * 7: messages.append("You have starved to death") self.dead = True return messages
def get(self): if self.netopeer_path: if not os.path.exists(self.netopeer_path) or os.path.getsize(self.netopeer_path) == 0: datastore = open(self.netopeer_path, 'w') datastore.write('<?xml version="1.0" encoding="UTF-8"?>\n<datastores xmlns="urn:cesnet:tmc:datastores:file">\n <running lock=""/>\n <startup lock=""/>\n <candidate modified="false" lock=""/>\n</datastores>') datastore.close() self.netopeer_doc = libxml2.parseFile(self.netopeer_path) self.netopeer_ctxt = self.netopeer_doc.xpathNewContext() self.netopeer_ctxt.xpathRegisterNs('d', 'urn:cesnet:tmc:datastores:file') self.netopeer_ctxt.xpathRegisterNs('n', 'urn:cesnet:tmc:netopeer:1.0') client_key_paths = self.netopeer_ctxt.xpathEval("/d:datastores/d:startup/n:netopeer/n:ssh/n:client-auth-keys/n:client-auth-key/n:path") if len(client_key_paths) > 0: for key_path in client_key_paths: key_username_nodes = self.netopeer_ctxt.xpathEval("/d:datastores/d:startup/n:netopeer/n:ssh/n:client-auth-keys/n:client-auth-key[n:path='{s}']/n:username".format(s=key_path.content)) if len(key_username_nodes) == 0: messages.append('An authorized client SSH key configuration is invalid.', 'warning') else: self.client_keys[key_path.content] = key_username_nodes[0].content if 4+len(key_username_nodes[0].content)+len(key_path.content) > self.linewidth: self.linewidth = 4+len(key_username_nodes[0].content)+len(key_path.content) self.new_client_keys = copy.copy(self.client_keys) return True
def get_stunnel_config(self): if not self.stunnelpath: return ((None, None)) try: file = open(self.stunnelpath, 'r') except OSError: return ((None, None)) text = file.read() file.close() i = text.find('\ncert = ') if i == -1: messages.append( 'stunnel config file does not define any server certificate', 'error') return ((None, None)) i += 8 certpath = text[i:text.find('\n', i)] i = text.find('\nkey = ') if i == -1: keypath = None else: i += 7 keypath = text[i:text.find('\n', i)] return ((certpath, keypath))
def get(self): if not self.permission_path: messages.append('Netopeer DBus configuration file location not specified.', 'error') return(False) try: self.dbus_doc = libxml2.parseFile(self.permission_path) except: messages.append('Unable to parse DBus configuration file', 'error') return(False) self.dbus_ctxt = self.dbus_doc.xpathNewContext() xpath_user = self.dbus_ctxt.xpathEval('/busconfig/policy[@user and allow/@own = \'org.liberouter.netopeer.server\']/@user') if xpath_user: self.user = xpath_user[0].get_content() if len(self.user) >= self.linewidth: self.linewidth = len(self.user) + 3 xpath_group = self.dbus_ctxt.xpathEval('/busconfig/policy[@group and allow/@send_destination = \'org.liberouter.netopeer.server\' and allow/@receive_sender = \'org.liberouter.netopeer.server\']/@group') if xpath_group: self.group = xpath_group[0].get_content() if len(self.group) >= self.linewidth: self.linewidth = len(self.group) + 3 if self.service_path: service = open(self.service_path, 'r') self.service_content = service.read() service.close() return(True)
def handle(self, stdscr, window, height, width, key): if key == curses.KEY_UP and ((not self.show_cert and self.selected > -2) or (self.show_cert and self.selected > 0)): self.selected = self.selected-1 elif key == curses.KEY_DOWN and self.selected < len(self.certs)-1: self.selected = self.selected+1 elif key == ord('\n'): if self.selected == -2: window.addstr(1, 0, ' '*(width-2)) path = self.get_editable(1, 0, stdscr, window, self.certspath, curses.color_pair(1), True) if path == '' or path == self.certspath: return(True) self.certspath = path self.certspath_toedit = True self.get() elif self.selected == -1: window.erase() window.addstr('Absolute path: ') path = self.get_editable(0, 15, stdscr, window, '', curses.color_pair(1) | curses.A_REVERSE, True) if path == '': return(True) try: cert = M2Crypto.X509.load_cert(path) except (IOError, M2Crypto.X509.X509Error): messages.append('\"' + path + '\" not a valid certificate', 'error') return(True) prefix = '' if cert.check_ca() and os.path.basename(path)[:3] != 'ca_': prefix = 'ca_' if not cert.check_ca() and os.path.basename(path)[:3] != 'cl_': prefix = 'cl_' if os.path.exists(os.path.join(self.certspath, prefix + os.path.basename(path))): messages.append('Certificate \"' + os.path.basename(path)[:-4] + '\" already in the CA directory', 'error') return(True) cert = self.parse_cert(path, prefix) if cert: self.certs.append(cert) self.certs.sort() self.certs_toadd.append((path, prefix)) else: self.show_cert = not self.show_cert elif key == curses.KEY_DC and self.selected > -1: self.certs_toremove.append(os.path.join(self.certspath, self.certs[self.selected][0]) + '.pem') del self.certs[self.selected] self.selected -= 1; elif key == curses.KEY_NPAGE and self.selected != len(self.certs)-1: if self.selected < 0: self.selected += height-3 else: self.selected += height-2 if self.selected > len(self.certs)-1: self.selected = len(self.certs)-1 elif key == curses.KEY_PPAGE and self.selected != -2: self.selected -= height-2 if self.selected < -2: self.selected = -2 else: curses.flash() return(True)
def update(self): changes = False try: while len(self.crls_toremove) > 0: os.remove(self.crls_toremove.pop()) changes = True except OSError, e: messages.append('Could not remove \"' + self.crls[self.selected][0] + '\": ' + e.strerror + '\n', 'error')
def handle(self, stdscr, window, height, width, key): if key == curses.KEY_UP and ((not self.show_crl and self.selected > -2) or (self.show_crl and self.selected > 0)): self.selected = self.selected - 1 elif key == curses.KEY_DOWN and self.selected < len(self.crls) - 1: self.selected = self.selected + 1 elif key == ord('\n'): if self.selected == -2: window.addstr(1, 0, ' ' * (width - 2)) path = self.get_editable(1, 0, stdscr, window, self.crlpath, curses.color_pair(1), True) if path == '' or path == self.crlpath: return (True) self.crlpath = path self.crlpath_toedit = True self.get() elif self.selected == -1: window.erase() window.addstr('Absolute path: ') path = self.get_editable( 0, 15, stdscr, window, '', curses.color_pair(1) | curses.A_REVERSE, True) if path == '': return (True) if os.path.exists( os.path.join(self.crlpath, os.path.basename(path))): messages.append( 'CRL \"' + os.path.basename(path)[:-4] + '\" already in the CRL directory', 'error') return (True) crl = self.parse_crl(path) if crl: self.crls.append(crl) self.crls.sort() self.crls_toadd.append(path) else: self.show_crl = not self.show_crl elif key == curses.KEY_DC and self.selected > -1: self.crls_toremove.append( os.path.join(self.crlpath, self.crls[self.selected][0]) + '.pem') del self.crls[self.selected] self.selected -= 1 elif key == curses.KEY_NPAGE and self.selected != len(self.crls) - 1: if self.selected < 0: self.selected += height - 3 else: self.selected += height - 2 if self.selected > len(self.crls) - 1: self.selected = len(self.crls) - 1 elif key == curses.KEY_PPAGE and self.selected != -2: self.selected -= height - 2 if self.selected < -2: self.selected = -2 else: curses.flash() return (True)
def update(self): changes = False try: while len(self.certs_toremove) > 0: os.remove(self.certs_toremove.pop()) changes = True except OSError, e: messages.append( 'Could not remove \"' + self.certs[self.selected][0] + '\": ' + e.strerror + '\n', 'error')
def find(self): self.stunnelpath = config.paths['cfgdir'] + '/stunnel_config' if not os.path.isfile(self.stunnelpath): messages.append('netopeer stunnel config file not found', 'error') self.stunnelpath = None return(False) self.crlpath = self.get_stunnel_config() if self.crlpath == None: return(False) return(True)
def find(self): self.stunnelpath = config.paths['cfgdir'] + '/stunnel_config' if not os.path.isfile(self.stunnelpath): messages.append('netopeer stunnel config file not found', 'error') self.stunnelpath = None return (False) self.certspath = self.get_stunnel_config() if self.certspath == None: return (False) return (True)
def find(self): for path in list(set([config.paths['bindir']] + (os.environ['PATH'].split(os.pathsep)))): if not self.server_path and os.path.exists(os.path.join(path,'netopeer-server')): self.server_path = os.path.join(path,'netopeer-server') if os.path.exists(config.paths['modulesdir']): self.modules_path = config.paths['modulesdir'] else: messages.append('Netopeer modules directory not found. No module can be configured.', 'error') return(True)
def do_read(self, hours): """Read a book. Please supply a number of hours, as in 'read 4' """ if random.random() < self.character.disease_stage.get("LEISURE_FAILURE", 0): print("\tYou try to read but the words swim on the page") return if hours > 4: hours = 4 print("\tAfter 4 hours you lose interest") messages = self.character.read(hours) messages.append("You read a book") for message in messages: print("\t" + message)
def do_game(self, hours): """Play video games. Please supply a number of hours, as in 'game 1' """ if hours > 8: print("\tAfter 8 hours you lose interest") hours = 8 elif random.random() < self.character.disease_stage.get("FOCUS_CHANCE", 0): print("\tYou get in the zone and loose track of time. You game for 8 hours") hours = 8 messages = self.character.game(hours) messages.append("You play on your computer. Your mood is now " + str(self.character.display_mood())) for message in messages: print("\t" + message)
def find(self): for path in list(set([config.paths['bindir']] + (os.environ['PATH'].split(os.pathsep)))): if not self.server_path and os.path.exists(os.path.join(path,'netopeer-server')): self.server_path = os.path.join(path,'netopeer-server') if not self.agent_path and os.path.exists(os.path.join(path,'netopeer-agent')): self.agent_path = os.path.join(path,'netopeer-agent') if os.path.exists(config.paths['modulesdir']): self.modules_path = config.paths['modulesdir'] else: messages.append('Netopeer modules directory not found. No module can be configured.', 'error') return(True)
def handle(self, stdscr, window, height, width, key): if key == curses.KEY_UP and ((not self.show_crl and self.selected > -2) or (self.show_crl and self.selected > 0)): self.selected = self.selected-1 elif key == curses.KEY_DOWN and self.selected < len(self.crls)-1: self.selected = self.selected+1 elif key == ord('\n'): if self.selected == -2: window.addstr(1, 0, ' '*(width-2)) path = self.get_editable(1, 0, stdscr, window, self.crlpath, curses.color_pair(1), True) if path == '' or path == self.crlpath: return(True) self.crlpath = path self.crlpath_toedit = True self.get() elif self.selected == -1: window.erase() window.addstr('Absolute path: ') path = self.get_editable(0, 15, stdscr, window, '', curses.color_pair(1) | curses.A_REVERSE, True) if path == '': return(True) if os.path.exists(os.path.join(self.crlpath, os.path.basename(path))): messages.append('CRL \"' + os.path.basename(path)[:-4] + '\" already in the CRL directory', 'error') return(True) crl = self.parse_crl(path) if crl: self.crls.append(crl) self.crls.sort() self.crls_toadd.append(path) else: self.show_crl = not self.show_crl elif key == curses.KEY_DC and self.selected > -1: self.crls_toremove.append(os.path.join(self.crlpath, self.crls[self.selected][0]) + '.pem') del self.crls[self.selected] self.selected -= 1; elif key == curses.KEY_NPAGE and self.selected != len(self.crls)-1: if self.selected < 0: self.selected += height-3 else: self.selected += height-2 if self.selected > len(self.crls)-1: self.selected = len(self.crls)-1 elif key == curses.KEY_PPAGE and self.selected != -2: self.selected -= height-2 if self.selected < -2: self.selected = -2 else: curses.flash() return(True)
def do_clean(self, arg): """Clean your house""" if "HOSPITAL_ACTIVITIES" in self.character.disease_stage: print("\tYou're not at home right now") return if random.random() < self.character.disease_stage.get("WORK_FAILURE", 0): print("\tYou can't be bothered to clean anything right now") return if self.character.display_energy() < 20: print("\tYou're too tired to face cleaning right now") return messages = self.character.clean() messages.append("You clean your house") for message in messages: print("\t" + message)
def do_exercise(self, arg): """Go for a run""" if "HOSPITAL_ACTIVITIES" in self.character.disease_stage: print("\tYou're not allowed outside yet") return if self.character.hours_played % 24 in self.character.disease_stage.get("MEAL_TIMES", []): print("\tA nurse stops you to tell you it is meal time") return if self.character.display_energy() < 20: print("\tContemplating a run makes you feel exhausted. Maybe tomorrow...") return messages = self.character.exercise() messages.append("You go for a run") for message in messages: print("\t" + message)
def find(self): if len(config.paths['dbusconfdir']) and os.path.exists(os.path.join(config.paths['dbusconfdir'],'org.liberouter.netopeer.conf')): self.permission_path = os.path.join(config.paths['dbusconfdir'],'org.liberouter.netopeer.conf') else: messages.append('Netopeer DBus configuration file not found.', 'error') return(False) if len(config.paths['dbusservices']) and os.path.exists(os.path.join(config.paths['dbusservices'],'org.liberouter.netopeer.server.service')): self.service_path = os.path.join(config.paths['dbusservices'],'org.liberouter.netopeer.server.service') elif os.path.exists('/usr/share/dbus-1/system-services/org.liberouter.netopeer.server.service'): self.service_path = '/usr/share/dbus-1/system-services/org.liberouter.netopeer.server.service' else: messages.append('Netopeer DBus service autostart file not installed.', 'note') return(True)
def do_eat(self, arg): """Eat a meal""" if self.character.hours_played % 24 not in self.character.disease_stage.get("MEAL_TIMES", range(24)): print("\tIt is not meal time yet") return if (self.character.last_meal < 4 or random.random() < self.character.disease_stage.get("EAT_FAILURE", 0)): print("\tYou don't feel like eating right now") return if self.character.groceries < 1: print("\tYou are out of food. Try 'shop' to get more") return messages = self.character.eat() messages.append("You eat a meal") for message in messages: print("\t" + message)
def parse_cert(self, path, prefix=''): try: cert = M2Crypto.X509.load_cert(path) except (IOError, M2Crypto.X509.X509Error): cert = None if not cert: messages.append('Could not parse certificate \"' + path + '\"', 'warning') return None # learn the longest items subject = cert.get_subject() subj_line_len = 0 if subject.C and len(subject.C) > subj_line_len: subj_line_len = len(subject.C) if subject.ST and len(subject.ST) > subj_line_len: subj_line_len = len(subject.ST) if subject.L and len(subject.L) > subj_line_len: subj_line_len = len(subject.L) if subject.O and len(subject.O) > subj_line_len: subj_line_len = len(subject.O) if subject.OU and len(subject.OU) > subj_line_len: subj_line_len = len(subject.OU) if subject.CN and len(subject.CN) > subj_line_len: subj_line_len = len(subject.CN) if subject.emailAddress and len(subject.emailAddress) > subj_line_len: subj_line_len = len(subject.emailAddress) issuer = cert.get_subject() iss_line_len = 0 if issuer.C and len(issuer.C) > iss_line_len: iss_line_len = len(issuer.C) if issuer.ST and len(issuer.ST) > iss_line_len: iss_line_len = len(issuer.ST) if issuer.L and len(issuer.L) > iss_line_len: iss_line_len = len(issuer.L) if issuer.O and len(issuer.O) > iss_line_len: iss_line_len = len(issuer.O) if issuer.OU and len(issuer.OU) > iss_line_len: iss_line_len = len(issuer.OU) if issuer.CN and len(issuer.CN) > iss_line_len: iss_line_len = len(issuer.CN) if issuer.emailAddress and len(issuer.emailAddress) > iss_line_len: iss_line_len = len(issuer.emailAddress) return ((prefix + os.path.basename(path)[:-4], cert, subj_line_len, iss_line_len))
def download_species_byOrder(bird_family, bird_order, bird_species, tax_code): # initate web driver ebird_url = f'https://ebird.org/species/{tax_code}' chromeDriver = 'C:\\Users\\jmentore\\Documents\\Selenium Chrome Driver\\chromedriver.exe' driver = webdriver.Chrome(executable_path=chromeDriver) driver.get(ebird_url) driver.maximize_window() time.sleep(3) # Clicks the view all link view_all = driver.find_element( By.XPATH, '/html/body/div/div[7]/div/div/div[2]/div[1]/a') time.sleep(5) view_all.click() ids = driver.find_elements_by_tag_name('img') sci_name = bird_species family = bird_family order = bird_order ebird_counter = 0 file_ext = '.jpg' show_more = driver.find_element_by_id('show_more') while show_more.is_displayed(): try: for ii in ids: download_link = ii.get_attribute('src') r = requests.get(download_link) img = Image.open(BytesIO(r.content)) ebird_counter = ebird_counter + 1 img.save( f'{family}/{order}/{sci_name}/{sci_name}-{ebird_counter}{file_ext}' ) time.sleep(5) print(download_link) time.sleep(5) driver.find_element_by_xpath('//*[@id="show_more"]').click() except Exception as e: messages.append(e) time.sleep(1) if not show_more.is_displayed(): print(f'Total url extracted: {ebird_counter}') driver.quit()
def parse_cert(self, path, prefix = ''): try: cert = M2Crypto.X509.load_cert(path) except (IOError, M2Crypto.X509.X509Error): cert = None if not cert: messages.append('Could not parse certificate \"' + path + '\"', 'warning') return None # learn the longest items subject = cert.get_subject() subj_line_len = 0 if subject.C and len(subject.C) > subj_line_len: subj_line_len = len(subject.C) if subject.ST and len(subject.ST) > subj_line_len: subj_line_len = len(subject.ST) if subject.L and len(subject.L) > subj_line_len: subj_line_len = len(subject.L) if subject.O and len(subject.O) > subj_line_len: subj_line_len = len(subject.O) if subject.OU and len(subject.OU) > subj_line_len: subj_line_len = len(subject.OU) if subject.CN and len(subject.CN) > subj_line_len: subj_line_len = len(subject.CN) if subject.emailAddress and len(subject.emailAddress) > subj_line_len: subj_line_len = len(subject.emailAddress) issuer = cert.get_subject() iss_line_len = 0 if issuer.C and len(issuer.C) > iss_line_len: iss_line_len = len(issuer.C) if issuer.ST and len(issuer.ST) > iss_line_len: iss_line_len = len(issuer.ST) if issuer.L and len(issuer.L) > iss_line_len: iss_line_len = len(issuer.L) if issuer.O and len(issuer.O) > iss_line_len: iss_line_len = len(issuer.O) if issuer.OU and len(issuer.OU) > iss_line_len: iss_line_len = len(issuer.OU) if issuer.CN and len(issuer.CN) > iss_line_len: iss_line_len = len(issuer.CN) if issuer.emailAddress and len(issuer.emailAddress) > iss_line_len: iss_line_len = len(issuer.emailAddress) return((prefix + os.path.basename(path)[:-4], cert, subj_line_len, iss_line_len))
def _parse_msg_data(self) -> List[Tuple[int, bytes]]: messages: List[Tuple[int, bytes]] = [] msg_length = None while True: total_length = len(self._msg_data) if total_length < 4: return messages else: msg_length = int.from_bytes(self._msg_data[:4], byteorder="big") if total_length < 4 + msg_length: return messages else: messages.append( (msg_length, self._msg_data[4:4 + msg_length])) self._msg_data = self._msg_data[4 + msg_length:] logger.debug("Parsed message of length {} from {}".format( msg_length, self._stream))
def get_stunnel_config(self): if not self.stunnelpath: return(None) try: file = open(self.stunnelpath, 'r') except IOError: return(None) text = file.read() file.close() i = text.find('\nCRLpath = ') if i == -1: messages.append('stunnel config file does not define any CRL directory', 'error') return(None) i += 11 crlpath = text[i : text.find('\n', i)] return(crlpath)
def do_watch(self, arg): """Watch tv or a movie for a number of hours, as in 'watch movie 4' """ args = arg.split() if len(args) < 2: print("\tPlease pick tv or movie and give a number of hours, as in 'watch movie 4'") return if args[0] != "tv" and args[0] != "movie": print("\tYou can watch tv or movies, as in 'watch movie 4'") return messages = self.watch(args[1]) if messages is None: return article = "" if args[0] == "movie": article = "a " messages.append("You watch " + article + args[0]) for message in messages: print("\t" + message)
def do_sleep(self, hours): """Sleep to get your energy back. Please supply a number of hours, as in 'sleep 8' """ if "SLEEP_CAP" in self.character.disease_stage: if hours > self.character.disease_stage["SLEEP_CAP"]: print("\tYou can't sleep. You wake up early feeling fully rested") hours = self.character.disease_stage["SLEEP_CAP"] if hours > 12: print("\tAfter 12 hours you wake up.") hours = 12 messages = self.character.sleep(hours) messages.append("You sleep for " + str(hours) + " hours. Your energy is now " + str(self.character.display_energy())) if "WAKEUP_DELAY" in self.character.disease_stage: hour_str = " hours" if self.character.disease_stage["WAKEUP_DELAY"] == 1: hour_str = " hour" messages.append("You stay in bed for " + str(self.character.disease_stage["WAKEUP_DELAY"]) + hour_str) messages.extend(self.character.add_hours(self.character.disease_stage["WAKEUP_DELAY"])) for message in messages: print("\t" + message)
def get(self): if self.netopeer_path: if not os.path.exists(self.netopeer_path) or os.path.getsize( self.netopeer_path) == 0: datastore = open(self.netopeer_path, 'w') datastore.write( '<?xml version="1.0" encoding="UTF-8"?>\n<datastores xmlns="urn:cesnet:tmc:datastores:file">\n <running lock=""/>\n <startup lock=""/>\n <candidate modified="false" lock=""/>\n</datastores>' ) datastore.close() self.netopeer_doc = libxml2.parseFile(self.netopeer_path) self.netopeer_ctxt = self.netopeer_doc.xpathNewContext() self.netopeer_ctxt.xpathRegisterNs( 'd', 'urn:cesnet:tmc:datastores:file') self.netopeer_ctxt.xpathRegisterNs('n', 'urn:cesnet:tmc:netopeer:1.0') client_key_paths = self.netopeer_ctxt.xpathEval( "/d:datastores/d:startup/n:netopeer/n:ssh/n:client-auth-keys/n:client-auth-key/n:path" ) if len(client_key_paths) > 0: for key_path in client_key_paths: key_username_nodes = self.netopeer_ctxt.xpathEval( "/d:datastores/d:startup/n:netopeer/n:ssh/n:client-auth-keys/n:client-auth-key[n:path='{s}']/n:username" .format(s=key_path.content)) if len(key_username_nodes) == 0: messages.append( 'An authorized client SSH key configuration is invalid.', 'warning') else: self.client_keys[ key_path.content] = key_username_nodes[0].content if 4 + len(key_username_nodes[0].content) + len( key_path.content) > self.linewidth: self.linewidth = 4 + len( key_username_nodes[0].content) + len( key_path.content) self.new_client_keys = copy.copy(self.client_keys) return True
def get_stunnel_config(self): if not self.stunnelpath: return (None) try: file = open(self.stunnelpath, 'r') except IOError: return (None) text = file.read() file.close() i = text.find('\nCApath = ') if i == -1: messages.append( 'stunnel config file does not define any trusted CA directory', 'error') return (None) i += 10 certspath = text[i:text.find('\n', i)] return (certspath)
def do_shop(self, arg): """Buy more groceries""" if "HOSPITAL_ACTIVITIES" in self.character.disease_stage: print("\tYou're not allowed outside yet") return if self.character.hours_played % 24 in self.character.disease_stage.get("MEAL_TIMES", []): print("\tA nurse stops you to tell you it is meal time") return if self.character.display_energy() < 10: print("\tYou're too tired to haul home food. There must be something in the fridge...") return if self.character.hours_played % 24 < 8 or self.character.hours_played % 24 > 22: print("\tThe grocery store is closed right now.") return if self.character.groceries > 21: print("\tYour fridge is too full for more groceries") else: messages = self.character.shopping() messages.append("You buy another week of groceries") for message in messages: print("\t" + message)
def change_stage(self, stage): messages = [] if "TIME_WARP" in self.disease_stage and stage == self.disease_stage["NEXT_STAGE"]: month_str = " months pass " if self.disease_stage["TIME_WARP"] == 1: month_str = " month passes " messages.append(str(self.disease_stage["TIME_WARP"]) + month_str + "this way") self.last_exercise = 7 self.last_social = 7 self.last_cleaned = 7 self.hours_gamed = 0 self.hours_socialized = 0 self.hours_read = 0 self.hours_watched = 0 self.called_parents = False self.called_friend = False self.hours_played += (24 * 30 * self.disease_stage["TIME_WARP"]) if "EXIT_MESSAGE" in self.disease_stage: messages.append(self.disease_stage["EXIT_MESSAGE"]) self.disease_stage = stage #reset mood and energy based on new disease caps self.energy += 0 self.mood += 0 self.disease_days = 0 messages.append(self.disease_stage["INTRO_MESSAGE"]) return messages
def do_work(self, hours): """Work to gain money. Please supply a number of hours, as in 'work 4' """ if "HOSPITAL_ACTIVITIES" in self.character.disease_stage: print("\tYour doctor doesn't want you to work while you're in the hospital") return if random.random() < self.character.disease_stage.get("WORK_FAILURE", 0): print("\tYou sit down to work but end up playing video games instead") self.do_game(hours) return if self.character.display_energy() < 20: print("\tYou try to work but your eyes can't focus on the screen.") return if hours > 8: print("\tAfter 8 hours your mind starts to wander...") hours = 8 elif random.random() < self.character.disease_stage.get("FOCUS_CHANCE", 0): print("\tYou get in the zone and loose track of time. You work for 8 hours") hours = 8 messages = self.character.work(hours) messages.append("You go to your computer and work. You gain $" + str(10 * hours)) for message in messages: print("\t" + message)
def parse_crl(self, path): try: crl = M2Crypto.X509.load_crl(path) except (IOError, M2Crypto.X509.X509Error): crl = None if not crl: messages.append('Could not parse CRL \"' + path + '\"', 'warning') return None # learn the longest items and create the crl structure text = crl.as_text() # find issuer and get the string i = text.find('Issuer: ') if i == -1: messages.append('Could not parse CRL \"' + path + '\"', 'warning') return None issuer = text[i+8 : text.find('\n', i)] items = issuer.split('/') C, ST, L, O, OU, CN, EA = None, None, None, None, None, None, None for item in items: if item[:2] == 'C=': C = item[2:] if item[:3] == 'ST=': ST = item[3:] if item[:2] == 'L=': L = item[2:] if item[:2] == 'O=': O = item[2:] if item[:3] == 'OU=': OU = item[3:] if item[:3] == 'CN=': CN = item[3:] if item[:13] == 'emailAddress=': EA = item[13:] i = text.find('Last Update: ') if i == -1: messages.append('Could not parse CRL \"' + path + '\"', 'warning') return None VF = text[i+13 : text.find('\n', i)] i = text.find('Next Update: ') if i == -1: messages.append('Could not parse CRL \"' + path + '\"', 'warning') return None VT = text[i+13 : text.find('\n', i)] return((os.path.basename(path)[:-4], C, ST, L, O, OU, CN, EA, VF, VT))
def parse_crl(self, path): try: crl = M2Crypto.X509.load_crl(path) except (IOError, M2Crypto.X509.X509Error): crl = None if not crl: messages.append('Could not parse CRL \"' + path + '\"', 'warning') return None # learn the longest items and create the crl structure text = crl.as_text() # find issuer and get the string i = text.find('Issuer: ') if i == -1: messages.append('Could not parse CRL \"' + path + '\"', 'warning') return None issuer = text[i + 8:text.find('\n', i)] items = issuer.split('/') C, ST, L, O, OU, CN, EA = None, None, None, None, None, None, None for item in items: if item[:2] == 'C=': C = item[2:] if item[:3] == 'ST=': ST = item[3:] if item[:2] == 'L=': L = item[2:] if item[:2] == 'O=': O = item[2:] if item[:3] == 'OU=': OU = item[3:] if item[:3] == 'CN=': CN = item[3:] if item[:13] == 'emailAddress=': EA = item[13:] i = text.find('Last Update: ') if i == -1: messages.append('Could not parse CRL \"' + path + '\"', 'warning') return None VF = text[i + 13:text.find('\n', i)] i = text.find('Next Update: ') if i == -1: messages.append('Could not parse CRL \"' + path + '\"', 'warning') return None VT = text[i + 13:text.find('\n', i)] return ((os.path.basename(path)[:-4], C, ST, L, O, OU, CN, EA, VF, VT))
def post_safe(url, params): done = False tries_left = 3 messages = [] while tries_left and not done: tries_left -= 1 try: response = requests.post(url, data=params) done = True except Exception as e: messages.append(e) time.sleep(1) if not done: output = "%s\n" % (datetime.now().strftime('%Y-%m-%d %H:%M'), ) output += "requests() failed 3 times:\n" for m in messages: output += m + "\n" print(output) return done
def find(self): for path in list( set([config.paths['bindir']] + (os.environ['PATH'].split(os.pathsep)))): if not self.server_path and os.path.exists( os.path.join(path, 'netopeer-server')): self.server_path = os.path.join(path, 'netopeer-server') try: p = subprocess.Popen([self.server_path, '-V'], stdout=subprocess.PIPE) version_line = p.communicate()[0].split(os.linesep)[0] ver_idx = string.find(version_line, 'version ') if ver_idx > -1: self.server_version = version_line[ver_idx + 8:] except: pass if os.path.exists(config.paths['modulesdir']): self.modules_path = config.paths['modulesdir'] else: messages.append( 'Netopeer modules directory not found. No module can be configured.', 'error') return (True)
def find(self): if os.path.exists(config.paths['cfgdir']): self.certpath = config.paths['cfgdir'] + '/stunnel' if not os.path.isdir(self.certpath): messages.append( 'stunnel directory does not exist, creating it', 'warning') if not os.mkdir(self.certspath, 0700): messages.append('stunnel directory could not be created', 'error') self.certspath = None self.stunnelpath = config.paths['cfgdir'] + '/stunnel_config' if not os.path.isfile(self.stunnelpath): messages.append('netopeer stunnel config file not found', 'error') self.stunnelpath = None
def paint(self, window, focus, height, width): tools = [] if not self.show_cert: if self.selected == -3 or self.selected == -2: if self.selected == -3: tools.append(('ENTER', 'show')) if (self.selected == -3 and self.server_cert != None) or ( self.selected == -2 and self.server_key != None): tools.append(('DEL', 'remove')) tools.append(('INS', 'replace')) elif self.selected == -1: tools.append(('ENTER', 'add cert')) else: tools.append(('ENTER', 'show')) tools.append(('DEL', 'remove')) tools.append(('PGUP, PGDOWN', 'scrolling')) if self.selected < height - 8: cert_index = 0 else: cert_index = ((self.selected + 6) / (height - 2)) * (height - 2) - 6 if cert_index == 0: cert_count = height - 7 if self.server_cert == None: if 28 > self.linewidth: self.linewidth = 28 self.maddstrln( window, width, 'Server certificate (not set)' + ' ' * (self.linewidth - 28), curses.color_pair(0) | curses.A_REVERSE if focus and self.selected == -3 else 0) else: self.maddstrln( window, width, 'Server certificate' + ' ' * (self.linewidth - 18), curses.color_pair(0) | curses.A_REVERSE if focus and self.selected == -3 else 0) if self.server_key == None: if 20 > self.linewidth: self.linewidth = 20 self.maddstrln( window, width, 'Server key (not set)' + ' ' * (self.linewidth - 20), curses.color_pair(0) | curses.A_REVERSE if focus and self.selected == -2 else 0) else: self.maddstrln( window, width, 'Server key (' + self.server_key_type + ')' + ' ' * ((self.linewidth - 13) - len(self.server_key_type)), curses.color_pair(0) | curses.A_REVERSE if focus and self.selected == -2 else 0) self.maddstrln(window, width, '') self.maddstrln(window, width, 'Trusted CA certificates:') self.maddstrln( window, width, 'Add a certificate', curses.color_pair(0) | curses.A_REVERSE if focus and self.selected == -1 else 0, self.linewidth) self.maddstrln(window, width, '') else: cert_count = height - 2 try: i = 0 while cert_index + i < len(self.ca_certs) and i < cert_count: self.maddstrln( window, width, 'CA cert {d}'.format(d=cert_index + i), curses.color_pair(0) | curses.A_REVERSE if focus and self.selected == cert_index + i else 0, self.linewidth) i += 1 if len(self.ca_certs) == 0: self.maddstrln(window, width, 'None') except curses.error: pass else: tools.append(('ENTER', 'hide')) tools.append(('DEL', 'remove')) if self.selected == -3: cert = self.server_cert[0] else: cert = self.ca_certs[self.selected][0] subject = cert.get_subject() issuer = cert.get_issuer() valid = cert.get_not_after() if height > 22: try: if self.selected == -3: window.addstr('Server cert\n\n') else: window.addstr( 'CA cert {d}\n\n'.format(d=self.selected)) window.addstr('Subject\n') window.addstr('C: ' + str(subject.C) + '\n') window.addstr('ST: ' + str(subject.ST) + '\n') window.addstr('L: ' + str(subject.L) + '\n') window.addstr('O: ' + str(subject.O) + '\n') window.addstr('OU: ' + str(subject.OU) + '\n') window.addstr('CN: ' + str(subject.CN) + '\n') window.addstr('EA: ' + str(subject.emailAddress) + '\n') window.addstr('\nIssuer\n') window.addstr('C: ' + str(issuer.C) + '\n') window.addstr('ST: ' + str(issuer.ST) + '\n') window.addstr('L: ' + str(issuer.L) + '\n') window.addstr('O: ' + str(issuer.O) + '\n') window.addstr('OU: ' + str(issuer.OU) + '\n') window.addstr('CN: ' + str(issuer.CN) + '\n') window.addstr('EA: ' + str(issuer.emailAddress) + '\n') window.addstr('\nValid: ' + str(valid) + '\n') except curses.error: pass else: # cert name width (or) valid width (or) subject longest line + issuer longest line if width - 2 < 34 or width - 2 < 4 + self.ca_certs[ self.selected][1] + 1 + 4 + self.ca_certs[ self.selected][2] + 1: self.show_cert = False tools.pop() tools.append(('ENTER', 'show')) messages.append('Cannot show cert, terminal too small', 'warning') self.paint(window, focus, height, width) else: try: if self.selected == -3: window.addstr('Server cert\n\n') else: window.addstr( 'CA cert {d}\n\n'.format(d=self.selected)) msg = 'Subject' window.addstr( msg + ' ' * (5 + self.ca_certs[self.selected][1] - len(msg)) + 'Issuer\n') msg = 'C: ' + str(subject.C) msg2 = 'C: ' + str(issuer.C) window.addstr( msg + ' ' * (5 + self.ca_certs[self.selected][1] - len(msg)) + msg2 + '\n') msg = 'ST: ' + str(subject.ST) msg2 = 'ST: ' + str(issuer.ST) window.addstr( msg + ' ' * (5 + self.ca_certs[self.selected][1] - len(msg)) + msg2 + '\n') msg = 'L: ' + str(subject.L) msg2 = 'L: ' + str(issuer.L) window.addstr( msg + ' ' * (5 + self.ca_certs[self.selected][1] - len(msg)) + msg2 + '\n') msg = 'O: ' + str(subject.O) msg2 = 'O: ' + str(issuer.O) window.addstr( msg + ' ' * (5 + self.ca_certs[self.selected][1] - len(msg)) + msg2 + '\n') msg = 'OU: ' + str(subject.OU) msg2 = 'OU: ' + str(issuer.OU) window.addstr( msg + ' ' * (5 + self.ca_certs[self.selected][1] - len(msg)) + msg2 + '\n') msg = 'CN: ' + str(subject.CN) msg2 = 'CN: ' + str(issuer.CN) window.addstr( msg + ' ' * (5 + self.ca_certs[self.selected][1] - len(msg)) + msg2 + '\n') msg = 'EA: ' + str(subject.emailAddress) msg2 = 'EA: ' + str(issuer.emailAddress) window.addstr( msg + ' ' * (5 + self.ca_certs[self.selected][1] - len(msg)) + msg2 + '\n') window.addstr('\nValid: ' + str(valid) + '\n') except curses.error: pass return tools
def get(self): if self.netopeer_path: if not os.path.exists(self.netopeer_path) or os.path.getsize( self.netopeer_path) == 0: datastore = open(self.netopeer_path, 'w') datastore.write( '<?xml version="1.0" encoding="UTF-8"?>\n<datastores xmlns="urn:cesnet:tmc:datastores:file">\n <running lock=""/>\n <startup lock=""/>\n <candidate modified="false" lock=""/>\n</datastores>' ) datastore.close() self.netopeer_doc = libxml2.parseFile(self.netopeer_path) self.netopeer_ctxt = self.netopeer_doc.xpathNewContext() self.netopeer_ctxt.xpathRegisterNs( 'd', 'urn:cesnet:tmc:datastores:file') self.netopeer_ctxt.xpathRegisterNs('n', 'urn:cesnet:tmc:netopeer:1.0') # server certificate self.server_cert = None server_cert_nodes = self.netopeer_ctxt.xpathEval( '/d:datastores/d:startup/n:netopeer/n:tls/n:server-cert') if len(server_cert_nodes) > 0: if len(server_cert_nodes) > 1: messages.append( 'More "server-cert" nodes found, using the first', 'warning') server_cert_node = server_cert_nodes[0] cert = self.parse_cert(server_cert_node.content) if cert == None: messages.append('Could not parse the server certificate', 'warning') else: self.server_cert = cert # server key self.server_key = None self.server_key_type = None server_key_nodes = self.netopeer_ctxt.xpathEval( '/d:datastores/d:startup/n:netopeer/n:tls/n:server-key') if len(server_key_nodes) > 0: if len(server_key_nodes) > 1: messages.append( 'More "server-key" nodes found, using the first', 'warning') server_key_data_nodes = self.netopeer_ctxt.xpathEval( '/d:datastores/d:startup/n:netopeer/n:tls/n:server-key/n:key-data' ) server_key_type_nodes = self.netopeer_ctxt.xpathEval( '/d:datastores/d:startup/n:netopeer/n:tls/n:server-key/n:key-type' ) if len(server_key_data_nodes) > 0 or len( server_key_type_nodes) > 0: key_error = False if len(server_key_data_nodes) == 0: messages.append('"key-data" node is missing', 'warning') key_error = True if len(server_key_type_nodes) == 0: messages.append('"key-type" node is missing', 'warning') key_error = True if not key_error: if len(server_key_data_nodes) > 1: messages.append( 'More "key-data" nodes found, using the first', 'warning') if len(server_key_type_nodes) > 1: messages.append( 'More "key-type" nodes found, using the first', 'warning') key_type = server_key_type_nodes[0].content if key_type != 'RSA' and key_type != 'DSA': messages.append( '"key-type" is unsupported (' + key_type + ')', 'warning') else: try: if key_type == 'RSA': key = M2Crypto.RSA.load_key_string( '-----BEGIN RSA PRIVATE KEY-----\n' + server_key_data_nodes[0].content + '\n-----END RSA PRIVATE KEY-----') else: key_bio = M2Crypto.BIO.MemoryBuffer( '-----BEGIN DSA PRIVATE KEY-----\n' + server_key_data_nodes[0].content + '\n-----END DSA PRIVATE KEY-----') key = M2Crypto.DSA.load_key_bio(key_bio) except (M2Crypto.RSA.RSAError, M2Crypto.DSA.DSAError): key = None if key == None: messages.append( 'Could not parse the server private key', 'error') else: self.server_key = key self.server_key_type = key_type # trusted CA certs self.ca_certs = [] ca_cert_nodes = self.netopeer_ctxt.xpathEval( '/d:datastores/d:startup/n:netopeer/n:tls/n:trusted-ca-certs/n:trusted-ca-cert' ) for ca_cert_node in ca_cert_nodes: cert = self.parse_cert(ca_cert_node.content) if cert == None: messages.append('Could not parse a CA certificate', 'warning') continue self.ca_certs.append(cert) self.ca_certs.sort() return True
def handle(self, stdscr, window, height, width, key): if key == ord('\n'): selected = 0 while True: try: window.erase() window.addstr( 'Single file (PEM)\n', curses.color_pair(0) | curses.A_REVERSE if selected == 0 else 0) window.addstr( 'Two files (CRT and KEY)', curses.color_pair(0) | curses.A_REVERSE if selected == 1 else 0) window.refresh() except curses.error: pass key = stdscr.getch() if key == ord('\n'): break elif key == curses.KEY_DOWN and selected == 0: selected = 1 elif key == curses.KEY_UP and selected == 1: selected = 0 elif key == curses.KEY_LEFT: return (True) else: curses.flash() window.erase() certpath = None keypath = None if selected == 0: window.addstr('PEM absolute path: ') certpath = self.get_editable( 0, 19, stdscr, window, '', curses.color_pair(1) | curses.A_REVERSE, True) if certpath == '': return (True) pem = self.parse_cert(certpath) if not pem: messages.append( 'Certificate \"' + certpath + '\" inaccessible or not valid', 'error') return (True) self.stunnel_certpath = certpath self.stunnel_keypath = None self.crt = None self.pem = pem self.pem_toreplace = certpath else: window.addstr('CRT absolute path: ') certpath = self.get_editable( 0, 19, stdscr, window, '', curses.color_pair(1) | curses.A_REVERSE, True) if certpath == '': return (True) crt = self.parse_cert(certpath) if not crt: messages.append( 'Certificate \"' + certpath + '\" inaccessible or not valid', 'error') return (True) window.erase() window.addstr('KEY absolute path: ') keypath = self.get_editable( 0, 19, stdscr, window, '', curses.color_pair(1) | curses.A_REVERSE, True) if keypath == '': return (True) if not os.path.isfile(keypath): messages.append( 'Private key \"' + keypath + '\" inaccessible', 'error') return (True) self.stunnel_certpath = certpath self.stunnel_keypath = keypath self.crt = crt self.pem = None self.crt_toreplace = certpath self.key_toreplace = keypath else: curses.flash() return (True)
def update(self): if self.pem_toreplace: pempath = os.path.join(self.certpath, 'server.pem') if os.path.isfile(pempath): try: os.remove(pempath) except OSError as e: messages.append( 'Could not remove \"' + pempath + '\": ' + e.strerror + '\n', 'error') try: shutil.copyfile(self.pem_toreplace, pempath) except Error: messages.append( 'Could not copy \"' + self.pem_toreplace + '\": src and dest are the same', 'error') return (False) except IOError as e: messages.append( 'Could not copy \"' + self.pem_toreplace + '\": ' + e.strerror + '\n', 'error') return (False) if self.crt_toreplace and self.key_toreplace: crtpath = os.path.join(self.certpath, 'server.crt') if os.path.isfile(crtpath): try: os.remove(crtpath) except OSError as e: messages.append( 'Could not remove \"' + crtpath + '\": ' + e.strerror + '\n', 'error') try: shutil.copyfile(self.crt_toreplace, crtpath) except Error: messages.append( 'Could not copy \"' + self.crt_toreplace + '\": src and dest are the same', 'error') return (False) except IOError as e: messages.append( 'Could not copy \"' + self.crt_toreplace + '\": ' + e.strerror + '\n', 'error') return (False) keypath = os.path.join(self.certpath, 'server.key') if os.path.isfile(keypath): try: os.remove(keypath) except OSError as e: messages.append( 'Could not remove \"' + keypath + '\": ' + e.strerror + '\n', 'error') try: shutil.copyfile(self.key_toreplace, keypath) except Error: messages.append( 'Could not copy \"' + self.key_toreplace + '\": src and dest are the same', 'error') return (False) except IOError as e: messages.append( 'Could not copy \"' + self.key_toreplace + '\": ' + e.strerror + '\n', 'error') return (False) changes = False if self.pem_toreplace: self.set_stunnel_config(pempath, None) self.pem_toreplace = None changes = True elif self.crt_toreplace and self.key_toreplace: self.set_stunnel_config(crtpath, keypath) self.crt_toreplace = None self.key_toreplace = None changes = True if changes: stunnel_pidpath = config.paths['cfgdir'] + '/stunnel/stunnel.pid' if os.path.exists(stunnel_pidpath): try: pidfile = open(stunnel_pidpath, 'r') stunnelpid = int(pidfile.read()) os.kill(stunnelpid, signal.SIGHUP) except (ValueError, IOError, OSError): messages.append( 'netopeer stunnel pid file found, but could not force config reload, changes may not take effect before stunnel restart', 'error') return self.get()
if os.path.exists(config.paths['cfgdir']): self.certpath = config.paths['cfgdir'] + '/stunnel' if not os.path.isdir(self.certpath): messages.append( 'stunnel directory does not exist, creating it', 'warning') if not os.mkdir(self.certspath, 0700): messages.append('stunnel directory could not be created', 'error') self.certspath = None self.stunnelpath = config.paths['cfgdir'] + '/stunnel_config' if not os.path.isfile(self.stunnelpath): messages.append('netopeer stunnel config file not found', 'error') self.stunnelpath = None else: messages.append('netopeer stunnel directory not found', 'error') return (True) def parse_cert(self, path): try: cert = M2Crypto.X509.load_cert(path) except (IOError, M2Crypto.X509.X509Error): cert = None if not cert: return None # learn the longest items subject = cert.get_subject() subj_line_len = 0 if subject.C and len(subject.C) > subj_line_len: subj_line_len = len(subject.C)
def handle(self, stdscr, window, height, width, key): if key == curses.KEY_UP and ( (not self.show_cert and self.selected > -2) or (self.show_cert and self.selected > 0)): self.selected = self.selected - 1 elif key == curses.KEY_DOWN and self.selected < len(self.certs) - 1: self.selected = self.selected + 1 elif key == ord('\n'): if self.selected == -2: window.addstr(1, 0, ' ' * (width - 2)) path = self.get_editable(1, 0, stdscr, window, self.certspath, curses.color_pair(1), True) if path == '' or path == self.certspath: return (True) self.certspath = path self.certspath_toedit = True self.get() elif self.selected == -1: window.erase() window.addstr('Absolute path: ') path = self.get_editable( 0, 15, stdscr, window, '', curses.color_pair(1) | curses.A_REVERSE, True) if path == '': return (True) try: cert = M2Crypto.X509.load_cert(path) except (IOError, M2Crypto.X509.X509Error): messages.append('\"' + path + '\" not a valid certificate', 'error') return (True) prefix = '' if cert.check_ca() and os.path.basename(path)[:3] != 'ca_': prefix = 'ca_' if not cert.check_ca() and os.path.basename(path)[:3] != 'cl_': prefix = 'cl_' if os.path.exists( os.path.join(self.certspath, prefix + os.path.basename(path))): messages.append( 'Certificate \"' + os.path.basename(path)[:-4] + '\" already in the CA directory', 'error') return (True) cert = self.parse_cert(path, prefix) if cert: self.certs.append(cert) self.certs.sort() self.certs_toadd.append((path, prefix)) else: self.show_cert = not self.show_cert elif key == curses.KEY_DC and self.selected > -1: self.certs_toremove.append( os.path.join(self.certspath, self.certs[self.selected][0]) + '.pem') del self.certs[self.selected] self.selected -= 1 elif key == curses.KEY_NPAGE and self.selected != len(self.certs) - 1: if self.selected < 0: self.selected += height - 3 else: self.selected += height - 2 if self.selected > len(self.certs) - 1: self.selected = len(self.certs) - 1 elif key == curses.KEY_PPAGE and self.selected != -2: self.selected -= height - 2 if self.selected < -2: self.selected = -2 else: curses.flash() return (True)
def find(self): libxml2.keepBlanksDefault(0) if not os.path.exists(config.paths['modulesdir']): messages.append('Netopeer modules directory not found.', 'error') return False module_path = os.path.join(config.paths['modulesdir'], 'Netopeer.xml') if not os.path.isfile(module_path): messages_append('Netopeer module configuration not found', 'error') return False module_doc = libxml2.parseFile(module_path) module_ctxt = module_doc.xpathNewContext() xpath_repo_type = module_ctxt.xpathEval('/device/repo/type') if not xpath_repo_type: messages.append('Module Netopeer is not valid, repo type is not specified', 'error') return False elif len(xpath_repo_type) != 1: messages.append('Module Netopeer is not valid, there are multiple repo types specified', 'error') return False elif xpath_repo_type[0].get_content() != 'file': messages.append('Module Netopeer is not valid, the repository is not a file', 'error') return False xpath_repo_path = module_ctxt.xpathEval('/device/repo/path') if not xpath_repo_path: messages.append('Module Netopeer is not valid, repo path is not specified', 'error') return False elif len(xpath_repo_path) != 1: messages.append('Module Netopeer is not valid, there are multiple repo paths specified', 'error') return False self.netopeer_path = xpath_repo_path[0].get_content() return True
def call(self, recipient): messages = self.add_hours(1) if recipient in CALL_DICT["parents"]: if not self.called_parents: self.mood += 5 self.called_parents = True if self.display_mood() < 20: messages.append("Your parents notice how rough you're feeling and are worried") elif self.display_mood() < 50: messages.append("Your parents notice you're feeling down and try to cheer you up") elif self.display_mood() > 150: messages.append("Your parents can barely understand you. They are seriously worried about you") else: messages.append("You have a lovely chat with your parents") if self.money < 0: self.money = 0 messages.append("Your parents bail you out of your debt. You feel guilty") elif recipient in CALL_DICT["friend"]: if not self.called_friend: self.mood += 5 self.called_friend = True if self.display_mood() < 20: messages.append("Your friend notices how rough you're feeling and is worried") elif self.display_mood() < 50: messages.append("Your friend notices you're not very happy and tries to cheer you up") elif self.display_mood() > 150: messages.append("You seriously freak out your friend, who can barely get a word in edgewise") else: messages.append("You have a lovely chat with a friend") elif recipient in CALL_DICT["hospital"]: if "HOSPITAL_MESSAGE" in self.disease_stage: messages.append(self.disease_stage["HOSPTIAL_MESSAGE"]) else: messages.append("You are turned away. Try 'call doctor'") if "HOSPTIAL_STAGE" in self.disease_stage: messages.extend(self.change_stage(self.disease_stage["HOSPTIAL_STAGE"])) elif recipient in CALL_DICT["doctor"]: if "DOCTOR_MESSAGE" in self.disease_stage: messages.append(self.disease_stage["DOCTOR_MESSAGE"]) else: messages.append("You seem to be in fine health") if "DOCTOR_STAGE" in self.disease_stage: messages.extend(self.change_stage(self.disease_stage["DOCTOR_STAGE"])) elif recipient in CALL_DICT["helpline"]: messages.append("The helpline details resources available to you. Try 'call psychologist', 'call doctor', or 'call hospital'") elif recipient in CALL_DICT["psychologist"]: if "PSYCHOLOGIST_MESSAGE" in self.disease_stage: messages.append(self.disease_stage["PSYCHOLOGIST_MESSAGE"]) else: messages.append("They psychologist patiently listens to your problems") if "PSYCHOLOGIST_STAGE" in self.disease_stage: messages.extend(self.change_stage(self.disease_stage["PSYCHOLOGIST_STAGE"])) return messages
class nc_cacerts(ncmodule.ncmodule): name = 'CA Certificates' stunnelpath = None certspath = None certspath_toedit = False certs = [] line_len = len('Add a certificate') show_cert = False certs_toremove = [] certs_toadd = [] # curses selected = -2 def find(self): self.stunnelpath = config.paths['cfgdir'] + '/stunnel_config' if not os.path.isfile(self.stunnelpath): messages.append('netopeer stunnel config file not found', 'error') self.stunnelpath = None return (False) self.certspath = self.get_stunnel_config() if self.certspath == None: return (False) return (True) def parse_cert(self, path, prefix=''): try: cert = M2Crypto.X509.load_cert(path) except (IOError, M2Crypto.X509.X509Error): cert = None if not cert: messages.append('Could not parse certificate \"' + path + '\"', 'warning') return None # learn the longest items subject = cert.get_subject() subj_line_len = 0 if subject.C and len(subject.C) > subj_line_len: subj_line_len = len(subject.C) if subject.ST and len(subject.ST) > subj_line_len: subj_line_len = len(subject.ST) if subject.L and len(subject.L) > subj_line_len: subj_line_len = len(subject.L) if subject.O and len(subject.O) > subj_line_len: subj_line_len = len(subject.O) if subject.OU and len(subject.OU) > subj_line_len: subj_line_len = len(subject.OU) if subject.CN and len(subject.CN) > subj_line_len: subj_line_len = len(subject.CN) if subject.emailAddress and len(subject.emailAddress) > subj_line_len: subj_line_len = len(subject.emailAddress) issuer = cert.get_subject() iss_line_len = 0 if issuer.C and len(issuer.C) > iss_line_len: iss_line_len = len(issuer.C) if issuer.ST and len(issuer.ST) > iss_line_len: iss_line_len = len(issuer.ST) if issuer.L and len(issuer.L) > iss_line_len: iss_line_len = len(issuer.L) if issuer.O and len(issuer.O) > iss_line_len: iss_line_len = len(issuer.O) if issuer.OU and len(issuer.OU) > iss_line_len: iss_line_len = len(issuer.OU) if issuer.CN and len(issuer.CN) > iss_line_len: iss_line_len = len(issuer.CN) if issuer.emailAddress and len(issuer.emailAddress) > iss_line_len: iss_line_len = len(issuer.emailAddress) return ((prefix + os.path.basename(path)[:-4], cert, subj_line_len, iss_line_len)) def set_stunnel_config(self, new_certspath): if not self.stunnelpath: return (False) try: file = open(self.stunnelpath, 'r') except IOError: return (False) text = file.read() file.close() if text[:9] == 'CAPath = ': starti = 9 endi = text.find('\n', starti) else: starti = text.find('\nCApath = ') if starti > -1: starti += 10 endi = text.find('\n', starti) try: file = open(self.stunnelpath, 'w') except IOError: return (False) if starti > -1: file.write(text[:starti]) file.write(new_certspath) file.write(text[endi:]) else: file.write('CApath = ' + new_certspath + '\n') file.write(text) file.close() return (True) def get_stunnel_config(self): if not self.stunnelpath: return (None) try: file = open(self.stunnelpath, 'r') except IOError: return (None) text = file.read() file.close() i = text.find('\nCApath = ') if i == -1: messages.append( 'stunnel config file does not define any trusted CA directory', 'error') return (None) i += 10 certspath = text[i:text.find('\n', i)] return (certspath) def get(self): self.certs = [] self.line_len = len('Add a certificate') if self.certspath == None or not os.path.isdir(self.certspath): return (False) if len(self.certspath) > self.line_len: self.line_len = len(self.certspath) for path in os.listdir(self.certspath): if len(path) < 8 or path[-4:] != '.pem' or ( path[:3] != 'ca_' and path[:3] != 'cl_') or os.path.isdir( os.path.join(self.certspath, path)): continue cert = self.parse_cert(os.path.join(self.certspath, path)) if cert: if len(cert[0]) > self.line_len: self.line_len = len(cert[0]) self.certs.append(cert) self.certs.sort() return (True) def update(self): changes = False try: while len(self.certs_toremove) > 0: os.remove(self.certs_toremove.pop()) changes = True except OSError, e: messages.append( 'Could not remove \"' + self.certs[self.selected][0] + '\": ' + e.strerror + '\n', 'error') try: while len(self.certs_toadd) > 0: (path, prefix) = self.certs_toadd.pop() shutil.copyfile( path, os.path.join(self.certspath, prefix + os.path.basename(path)[:-4] + '.pem')) changes = True except IOError as e: messages.append( 'Could not add \"' + path + '\": ' + e.strerror + '\n', 'error') if changes: # rehash cert dir and tell stunnel to reload it if not os.path.exists(config.paths['crehash']): messages.append( 'Could not rehash the CA directory with \"' + config.paths['crehash'] + '\", left inconsistent', 'error') return (False) try: FNULL = open(os.devnull, 'w') subprocess.check_call( [config.paths['crehash'], self.certspath], stdin=FNULL, stdout=FNULL, stderr=FNULL, shell=False) FNULL.close() except subprocess.CalledProcessError: messages.append( 'c_rehash failed, the CA directory left inconsistent', 'error') return (False) stunnel_pidpath = config.paths['cfgdir'] + '/stunnel/stunnel.pid' if os.path.exists(stunnel_pidpath): try: pidfile = open(stunnel_pidpath, 'r') stunnelpid = int(pidfile.read()) os.kill(stunnelpid, signal.SIGHUP) except (ValueError, IOError, OSError): messages.append( 'netopeer stunnel pid file found, but could not force config reload, changes may not take effect before stunnel restart', 'error') if self.certspath_toedit: if not self.set_stunnel_config(self.certspath): messages.append( 'Could not write the new stunnel trusted CA dir into config file', 'error') return (False) self.certspath_toedit = False return (True)
def handle(self, stdscr, window, height, width, key): if key == curses.KEY_UP and self.selected > 0: self.selected = self.selected-1 elif key == curses.KEY_DOWN and self.selected < len(self.new_client_keys): self.selected = self.selected+1 elif key == curses.KEY_DC and self.selected > 0: if self.selected == len(self.new_client_keys): self.selected = self.selected-1 selected_key_path = sorted(self.new_client_keys.keys())[self.selected-1] del self.new_client_keys[selected_key_path] elif key == ord('\n'): if self.selected == 0: window.addstr(1, 0, 'Path: '+' '*(self.linewidth-6)) key_path = self.get_editable(1, 6, stdscr, window, '', curses.color_pair(1) | curses.A_REVERSE, True) if key_path == '': return True if not os.path.isfile(key_path): messages.append('"'+key_path+'" is not a file', 'error') return True try: key_file = open(key_path, 'r') except IOError as e: messages.append('File "'+key_path+'" open: '+e.strerror, 'error') key_data = key_file.read() key_file.close() if string.find(key_data, ' PRIVATE KEY-----\n') > -1: messages.append('"'+key_path+'" is a private key', 'error') return True if key_path in self.new_client_keys: messages.append('The key is already in the configuration', 'error') return True window.addstr(2, 0, 'Username: '******' '*(len(key_path)-4)) key_username = self.get_editable(2, 10, stdscr, window, '', curses.color_pair(1) | curses.A_REVERSE, False) if key_username == '': return True self.new_client_keys[key_path] = key_username if 4+len(key_path)+len(key_username) > self.linewidth: self.linewidth = 4+len(key_path)+len(key_username) elif self.selected > 0: window.addstr(1, 0, 'Path: '+' '*(self.linewidth-5)) selected_key_path = sorted(self.new_client_keys.keys())[self.selected-1] key_path = self.get_editable(1, 6, stdscr, window, selected_key_path, curses.color_pair(1), True) if key_path == '': return True if key_path != selected_key_path: if not os.path.isfile(key_path): messages.append('"'+key_path+'" is not a file', 'error') return True try: key_file = open(key_path, 'r') except IOError as e: messages.append('File "'+key_path+'" open: '+e.strerror, 'error') key_data = key_file.read() key_file.close() if string.find(key_data, ' PRIVATE KEY-----\n') > -1: messages.append('"'+key_path+'" is a private key', 'error') return True self.new_client_keys[key_path] = self.new_client_keys[selected_key_path] del self.new_client_keys[selected_key_path] window.addstr(2, 0, 'Username: '******' '*(len(key_path)-4)) key_username = self.get_editable(2, 10, stdscr, window, self.new_client_keys[key_path], curses.color_pair(1), False) if key_username == '': return True if key_username != self.new_client_keys[key_path]: self.new_client_keys[key_path] = key_username if 4+len(key_path)+len(key_username) > self.linewidth: self.linewidth = 4+len(key_path)+len(key_username) else: curses.flash() return True
def postcmd(self, stop, line): if self.character.dead: print() print("You have died. Game over") return True if not stop and not line.startswith("help") and not line.startswith("?") and not self.bad_command: if random.random() < self.character.disease_stage.get("LOSS_OF_CONTROL_CHANCE", 0): print("\tYou lose control for about 8 hours") messages = self.character.add_hours(8) activity = random.choice(self.character.disease_stage["ACTIVITIES"]) if activity == "SHOPPING": messages.append("You go shopping and spend all of your money on home furnishings") self.character.money -= 500 elif activity == "DRIVING": messages.append("You rent a car and go for a drive. You find yourself driving much too fast") if random.random() < SPEEDING_RISK: messages.append("You get into a terrible car accident. You and the other driver are both killed") messages.append("Game over") self.character.dead = True return True elif activity == "ART": messages.append("You start creating a gorgeous calligraphy project") elif activity == "MUSIC": messages.append("You find yourself thinking in rhymes and start writing songs") for message in messages: print('\t' + message) self.print_status() print() self.bad_command = False return stop
def find(self): libxml2.keepBlanksDefault(0) if not os.path.exists(config.paths['modulesdir']): messages.append('Netopeer modules directory not found.', 'error') return False module_path = os.path.join(config.paths['modulesdir'], 'Netopeer.xml') if not os.path.isfile(module_path): messages_append('Netopeer module configuration not found', 'error') return False module_doc = libxml2.parseFile(module_path) module_ctxt = module_doc.xpathNewContext() xpath_repo_type = module_ctxt.xpathEval('/device/repo/type') if not xpath_repo_type: messages.append( 'Module Netopeer is not valid, repo type is not specified', 'error') return False elif len(xpath_repo_type) != 1: messages.append( 'Module Netopeer is not valid, there are multiple repo types specified', 'error') return False elif xpath_repo_type[0].get_content() != 'file': messages.append( 'Module Netopeer is not valid, the repository is not a file', 'error') return False xpath_repo_path = module_ctxt.xpathEval('/device/repo/path') if not xpath_repo_path: messages.append( 'Module Netopeer is not valid, repo path is not specified', 'error') return False elif len(xpath_repo_path) != 1: messages.append( 'Module Netopeer is not valid, there are multiple repo paths specified', 'error') return False self.netopeer_path = xpath_repo_path[0].get_content() return True
def handle(self, stdscr, window, height, width, key): if key == curses.KEY_UP and ( (not self.show_cert and self.selected > -3) or (self.show_cert and self.selected > 0)): self.selected = self.selected - 1 elif key == curses.KEY_DOWN and self.selected < len( self.ca_certs) - 1 and (not self.show_cert or self.selected > -1): self.selected = self.selected + 1 elif key == ord('\n'): if self.selected == -1: window.addstr(4, 0, 'Absolute path: ' + ' ' * (self.linewidth - 15)) path = self.get_editable( 4, 15, stdscr, window, '', curses.color_pair(1) | curses.A_REVERSE, True) if path == '': return True try: cert = self.parse_cert(path) except (IOError, M2Crypto.X509.X509Error): cert = None if cert == None: messages.append( '\"' + path + '\" is not a valid certificate', 'error') return True if not cert[0].check_ca(): messages.append( 'Certificate \"' + os.path.basename(path) + '\" not a CA certificate', 'error') return True for old_cert in self.ca_certs: if cert[0].get_fingerprint( ) == old_cert[0].get_fingerprint(): messages.append( 'Certificate \"' + os.path.basename(path) + '\" already trusted', 'error') return True self.ca_certs.append(cert) self.ca_certs.sort() self.ca_certs_change = True elif (self.selected == -3 and self.server_cert != None) or self.selected > -1: self.show_cert = not self.show_cert else: curses.flash() elif key == curses.KEY_DC: if self.selected == -3 and self.server_cert != None: self.server_cert = None self.server_cert_change = True if self.show_cert: self.show_cert = False elif self.selected == -2 and self.server_key != None: self.server_key = None self.server_key_type = None self.server_key_change = True elif self.selected > -1: del self.ca_certs[self.selected] self.ca_certs_change = True self.selected -= 1 if self.show_cert and self.selected == -1: self.show_cert = False else: curses.flash() elif key == curses.KEY_IC and self.selected < -1 and not self.show_cert: if self.selected == -3: window.addstr(0, 0, 'Absolute path: ' + ' ' * (self.linewidth - 15)) path = self.get_editable( 0, 15, stdscr, window, '', curses.color_pair(1) | curses.A_REVERSE, True) if path == '': return True try: cert = self.parse_cert(path) except (IOError, M2Crypto.X509.X509Error): cert = None if cert == None: messages.append( '"' + path + '" is not a valid certificate', 'error') return True if cert[0].check_ca(): messages.append( 'Certificate \"' + os.path.basename(path) + '\" is a CA certificate', 'error') return True self.server_cert = cert self.server_cert_change = True elif self.selected == -2: window.addstr(1, 0, 'Absolute path: ' + ' ' * (self.linewidth - 15)) path = self.get_editable( 1, 15, stdscr, window, '', curses.color_pair(1) | curses.A_REVERSE, True) if path == '': return True key_type = None try: key_file = open(path, 'r') except IOError as e: messages.append('File "' + path + '" open: ' + e.strerror, 'error') return True key_data = key_file.read() key_file.close() if string.find(key_data, '-----BEGIN RSA PRIVATE KEY-----\n') > -1: key_type = 'RSA' elif string.find(key_data, '-----BEGIN DSA PRIVATE KEY-----\n') > -1: key_type = 'DSA' else: messages.append('"' + path + '" is in an unknown format', 'error') return True try: if key_type == 'RSA': key = M2Crypto.RSA.load_key(path) else: key = M2Crypto.DSA.load_key(path) except (M2Crypto.RSA.RSAError, M2Crypto.DSA.DSAError): key = None if key == None: messages.append( '"' + path + '" is not a valid private key', 'error') self.server_key = key self.server_key_type = key_type self.server_key_change = True elif key == curses.KEY_NPAGE and not self.show_cert and self.selected != len( self.ca_certs) - 1: if self.selected == -3 or self.selected == -2: self.selected += height - 5 elif self.selected == -1: self.selected += height - 3 else: self.selected += height - 2 if self.selected > len(self.ca_certs) - 1: self.selected = len(self.ca_certs) - 1 elif key == curses.KEY_PPAGE and not self.show_cert and self.selected != -3: if self.selected == height - 8 or self.selected == height - 7: self.selected -= height - 5 elif self.selected == height - 6: self.selected = -2 elif self.selected == height - 4 or self.selected == height - 5: self.selected = -1 else: self.selected -= height - 2 if self.selected < -3: self.selected = -3 else: curses.flash() return True
def set_stunnel_config(self, certpath, keypath): if not self.stunnelpath or not certpath: return (None) try: conf = open(self.stunnelpath, 'r') except OSError: return (None) text = conf.read() conf.close() startcert = text.find('\ncert = ') if startcert == -1: messages.append( 'Corrupted stunnel config file: no certificate specified', 'error') return (None) startcert += 8 endcert = text.find('\n', startcert) startkey = text.find('\nkey = ') if keypath: if startkey == -1: startkey = text.find('\n;key = ') if startkey != -1: key_commented = True else: startkey += 6 key_commented = False if startkey != -1: startkey += 1 endkey = text.find('\n', startkey) try: conf = open(self.stunnelpath, 'w') except OSError: return (None) conf.write(text[:startcert]) conf.write(certpath) if not keypath: if startkey == -1: conf.write(text[endcert:]) else: conf.write(text[endcert:startkey]) conf.write(';') conf.write(text[startkey:]) else: if startkey == -1: conf.write('\nkey = ') conf.write(keypath) conf.write(text[endcert:]) else: if key_commented: conf.write(text[endcert:startkey]) conf.write('key = ') conf.write(keypath) conf.write(text[endkey:]) else: conf.write(text[endcert:startkey]) conf.write(keypath) conf.write(text[endkey:]) conf.close()
def paint(self, window, focus, height, width): tools = [('PGUP, PGDOWN', 'scrolling'), ('DEL', 'remove')] if not self.show_cert: tools.append(('ENTER', 'show')) if self.selected < height - 7: cert_index = 0 else: cert_index = ((self.selected + 5) / (height - 2)) * (height - 2) - 5 if cert_index == 0: cert_count = height - 7 self.maddstrln(window, width, 'Trusted CA/client certificates in:') self.maddstrln( window, width, self.certspath, curses.color_pair(0) | curses.A_UNDERLINE | (curses.A_REVERSE if focus and self.selected == -2 else 0), self.line_len) self.maddstrln(window, width, '') self.maddstrln( window, width, 'Add a certificate', curses.color_pair(0) | curses.A_REVERSE if focus and self.selected == -1 else 0, self.line_len) self.maddstrln(window, width, '') else: cert_count = height - 2 try: i = 0 while cert_index + i < len(self.certs) and i < cert_count: self.maddstrln( window, width, self.certs[cert_index + i][0], curses.color_pair(0) | curses.A_REVERSE if focus and self.selected == cert_index + i else 0, self.line_len) i += 1 if len(self.certs) == 0: self.maddstrln(window, width, 'None') except curses.error: pass else: tools.append(('ENTER', 'hide')) cert = self.certs[self.selected][1] subject = cert.get_subject() issuer = cert.get_issuer() valid = cert.get_not_after() if height > 22: try: window.addstr(self.certs[self.selected][0] + '\n\n') window.addstr('Subject\n') window.addstr('C: ' + str(subject.C) + '\n') window.addstr('ST: ' + str(subject.ST) + '\n') window.addstr('L: ' + str(subject.L) + '\n') window.addstr('O: ' + str(subject.O) + '\n') window.addstr('OU: ' + str(subject.OU) + '\n') window.addstr('CN: ' + str(subject.CN) + '\n') window.addstr('EA: ' + str(subject.emailAddress) + '\n') window.addstr('\nIssuer\n') window.addstr('C: ' + str(issuer.C) + '\n') window.addstr('ST: ' + str(issuer.ST) + '\n') window.addstr('L: ' + str(issuer.L) + '\n') window.addstr('O: ' + str(issuer.O) + '\n') window.addstr('OU: ' + str(issuer.OU) + '\n') window.addstr('CN: ' + str(issuer.CN) + '\n') window.addstr('EA: ' + str(issuer.emailAddress) + '\n') window.addstr('\nValid: ' + str(valid) + '\n') except curses.error: pass else: # cert name width (or) valid width (or) subject longest line + issuer longest line if width-2 < len(self.certs[self.selected][0])+1 or width-2 < 34 or\ width-2 < 4 + self.certs[self.selected][2] + 1 + 4 + self.certs[self.selected][3] + 1: self.show_cert = False tools.pop() tools.append(('ENTER', 'show')) messages.append('Cannot show cert, terminal too small', 'warning') self.paint(window, focus, height, width) else: try: window.addstr(self.certs[self.selected][0] + '\n\n') msg = 'Subject' window.addstr( msg + ' ' * (5 + self.certs[self.selected][2] - len(msg)) + 'Issuer\n') msg = 'C: ' + str(subject.C) msg2 = 'C: ' + str(issuer.C) window.addstr( msg + ' ' * (5 + self.certs[self.selected][2] - len(msg)) + msg2 + '\n') msg = 'ST: ' + str(subject.ST) msg2 = 'ST: ' + str(issuer.ST) window.addstr( msg + ' ' * (5 + self.certs[self.selected][2] - len(msg)) + msg2 + '\n') msg = 'L: ' + str(subject.L) msg2 = 'L: ' + str(issuer.L) window.addstr( msg + ' ' * (5 + self.certs[self.selected][2] - len(msg)) + msg2 + '\n') msg = 'O: ' + str(subject.O) msg2 = 'O: ' + str(issuer.O) window.addstr( msg + ' ' * (5 + self.certs[self.selected][2] - len(msg)) + msg2 + '\n') msg = 'OU: ' + str(subject.OU) msg2 = 'OU: ' + str(issuer.OU) window.addstr( msg + ' ' * (5 + self.certs[self.selected][2] - len(msg)) + msg2 + '\n') msg = 'CN: ' + str(subject.CN) msg2 = 'CN: ' + str(issuer.CN) window.addstr( msg + ' ' * (5 + self.certs[self.selected][2] - len(msg)) + msg2 + '\n') msg = 'EA: ' + str(subject.emailAddress) msg2 = 'EA: ' + str(issuer.emailAddress) window.addstr( msg + ' ' * (5 + self.certs[self.selected][2] - len(msg)) + msg2 + '\n') window.addstr('\nValid: ' + str(valid) + '\n') except curses.error: pass return (tools)
def get(self): if self.modules_path: for module_conf in os.listdir(self.modules_path): if os.path.isfile(os.path.join(self.modules_path, module_conf)): module_valid = True # get module name, everything before last dot module_name = module_conf.rsplit('.', 1)[0] module_doc = libxml2.parseFile(os.path.join(self.modules_path, module_conf)) module_ctxt = module_doc.xpathNewContext() xpath_mainyin = module_ctxt.xpathEval('/device/data-models/model-main/path') if not xpath_mainyin: messages.append('Module {s} is not valid, main model path is missing'.format(s=module_name), 'warning') continue elif len(xpath_mainyin) != 1: messages.append('Module {s} is not valid, there are multiple main models'.format(s=module_name), 'warning') continue elif not os.path.exists(xpath_mainyin[0].get_content()): messages.append('Module {s} is not valid, main model file does not exist'.format(s=module_name), 'warning') continue xpath_maintransapi = module_ctxt.xpathEval('/device/data-models/model-main/transapi') if xpath_maintransapi and len(xpath_maintransapi) != 1: messages.append('Module {s} is not valid, there are multiple main transapi modules'.format(s=module_name), 'warning') continue elif xpath_maintransapi and not os.path.exists(xpath_maintransapi[0].get_content()): messages.append('Module {s} is not valid, main model transapi file does not exist'.format(s=module_name), 'warning') continue xpath_repo_type = module_ctxt.xpathEval('/device/repo/type') if not xpath_repo_type: messages.append('Module {s} is not valid, repo type is not specified'.format(s=module_name), 'warning') continue elif len(xpath_repo_type) != 1: messages.append('Module {s} is not valid, there are multiple repo types specified'.format(s=module_name), 'warning') continue elif xpath_repo_type[0].get_content() == 'file': xpath_repo_path = module_ctxt.xpathEval('/device/repo/path') if not xpath_repo_path: messages.append('Module {s} is not valid, repo path is not specified'.format(s=module_name), 'warning') continue elif len(xpath_repo_path) != 1: messages.append('Module {s} is not valid, there are multiple repo paths specified'.format(s=module_name), 'warning') continue # it is not necessary to test that the datastore exists if module_name == 'Netopeer': self.netopeer_path = xpath_repo_path[0].get_content() xpath_augmentyin = module_ctxt.xpathEval('/device/data-models/model/path') for yin in xpath_augmentyin: if not os.path.exists(yin.get_content()): messages.append('Module {s} is not valid, main model transapi file does not exist'.format(s=module_name), 'warning') module_valid = False break # do not allow manipulation with an internal or invalid modules if module_valid and not (module_name == 'Netopeer' or module_name == 'NETCONF-server'): self.modules.append(netopeer_module(module_name)) if self.selected < 0: self.selected = 0 if len(module_name) > self.modules_maxlen: self.modules_maxlen = len(module_name) if self.netopeer_path: if not os.path.exists(self.netopeer_path) or os.path.getsize(self.netopeer_path) == 0: datastore = open(self.netopeer_path, 'w') datastore.write('<?xml version="1.0" encoding="UTF-8"?>\n<datastores xmlns="urn:cesnet:tmc:datastores:file">\n <running lock=""/>\n <startup lock=""/>\n <candidate modified="false" lock=""/>\n</datastores>') datastore.close() self.netopeer_doc = libxml2.parseFile(self.netopeer_path) self.netopeer_ctxt = self.netopeer_doc.xpathNewContext() self.netopeer_ctxt.xpathRegisterNs('d', 'urn:cesnet:tmc:datastores:file') self.netopeer_ctxt.xpathRegisterNs('n', 'urn:cesnet:tmc:netopeer:1.0') netopeer_allowed_modules = self.netopeer_ctxt.xpathEval("/d:datastores/d:startup/n:netopeer/n:modules/n:module[n:enabled=\'true\']/n:name") netopeer_forbidden_modules = self.netopeer_ctxt.xpathEval("/d:datastores/d:startup/n:netopeer/n:modules/n:module[n:enabled=\'false\']/n:name") for module_name in map(libxml2.xmlNode.get_content,netopeer_allowed_modules): if module_name in map(getattr, self.modules, ['name']*len(self.modules)): for module in self.modules: if module_name == module.name: module.enable() break else: missing_module = self.netopeer_ctxt.xpathEval('/d:datastores/d:startup/n:netopeer/n:modules/n:module[n:name = \'{s}\']/n:enabled'.format(s=module_name)) missing_module[0].setContent('false') messages.append('Module {s} is not installed. Disabling in netopeer configuration.'.format(s=module_name), 'warning') for module_name in map(libxml2.xmlNode.get_content, netopeer_forbidden_modules): if module_name in map(getattr, self.modules, ['name']*len(self.modules)): for module in self.modules: if module_name == module.name: module.disable() break else: messages.append('Module {s} not installed. Skipping in netopeer configuration.'.format(s=module_name), 'warning') else: messages.append('Netopeer module not found, unable to manage modules', 'error') self.selected = -1 self.modules = [] return(True)