class Controller: """ Controlls the registry """ def __init__(self): self.registry = Registry() def main(self): """ starts everything """ self.register_books(self.registry) def register_books(self, registry): """ Registers books to the registry """ books = [Book("'The Wheel of time'", "Robert Jordan"), Book("'The painted man'", "Peter V. Brett"), Book("'The name of the wind'", "Patrick Rothfuss"), Book("'Off to Be the Wizard'", "Scott Meyer"), Book("'Half a King'", "Joe Abercrombie "), Book("'The Way of Shadows'", "Brent Weeks"), Book("'Fool's Assassin'", "Robin Hobb"), Book("'The Golem and the Jinni'", "Helene Wecker"), Book("'The Way of Kings'", "Brandon Sanderson"), Book("'1984'", "George Orwell"), Book("'The Count of Monte Cristo'", "Alexandre Dumas"), Book("'Brott och straff'", "Fyodor Dostoyevsky")] for book in books: registry.register_book(book) self.registry.print_books()
def saveBio(self, data): """ save biography data """ query = """ update patient.patient set surname='%(surname)s', first_names='%(first_names)s', birth_date='%(birth_date)s', gender='%(gender)s', nationalid='%(nationalid)s', nationality='%(nationality)s', note='%(note)s', callname='%(callname)s', language='%(language)s', occupation='%(occupation)s', marital_status='%(marital_status)s', dependants='%(dependants)s', ethnicity='%(ethnicity)s', employer='%(employer)s' where patient.file_number='%(file_number)d' """ % data # print query cursor = self.conn.cursor() cursor.execute(query) self.conn.commit() if self.lastSearchData: res = self.search(self.lastSearchData) Registry.get("SEARCH").presentResult()
def __init__(self, parent, ID): wx.Panel.__init__(self, parent, ID) Registry.add("SEARCH", self) # search searchBox = self.makeSearchBox() # normal result normalResultBox = self.makeNormalResultBox() # patient actions newBtn = wx.Button(self, wx.ID_NEW) self.Bind(wx.EVT_BUTTON, self.newEntry, newBtn) delBtn = wx.Button(self, wx.ID_DELETE) self.Bind(wx.EVT_BUTTON, self.deleteEntry, delBtn) btnBox = wx.BoxSizer(wx.HORIZONTAL) btnBox.Add(newBtn, 0, wx.ALIGN_CENTER|wx.ALL, 1) btnBox.Add(delBtn, 0, wx.ALIGN_CENTER|wx.ALL, 1) # panel sizer sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(searchBox, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) sizer.Add(normalResultBox, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) sizer.Add(btnBox, 0, wx.ALIGN_CENTER|wx.ALL, 3) self.SetSizer(sizer) self.SetAutoLayout(True) sizer.Fit(self) sizer.SetSizeHints(self) # reload last query self.__reloadLastQuery()
def __init__(self, parent, ID, name="", style=wx.TR_HAS_BUTTONS, size=wx.DefaultSize, registrykey=None): wx.TreeCtrl.__init__(self, parent, ID, name="", style=style, size=size) if registrykey: Registry.add(registrykey, self)
def __init__(self, parent, ID): wx.Panel.__init__(self, parent, ID) Registry.add("CLOCK", self) self.aclock = ac.AnalogClockWindow(self, -1, style=wx.SUNKEN_BORDER) self.aclock.SetTickSizes(h=5, m=2) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.aclock, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) self.SetSizer(sizer)
def __init__(self, parent, ID): wx.Panel.__init__(self, parent, ID) Registry.add("CONTACT", self) Result.addListener(self) self.grid = ContactGrid(self, -1) gridBox = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Contact List"), wx.HORIZONTAL) gridBox.Add(self.grid, 1, wx.GROW|wx.ALIGN_CENTER|wx.ALL, 3) self.physicalAddress = Address(self, "HOME_PHYSICAL", Colors.HOME) self.postalAddress = Address(self, "HOME_POSTAL", Colors.HOME) self.workPhysicalAddress = Address(self, "WORK_PHYSICAL", Colors.WORK) self.workPostalAdress = Address(self, "WORK_POSTAL", Colors.WORK) # register the widgets for later access self.addWidgets = {"HOME_PHYSICAL": self.physicalAddress, "HOME_POSTAL": self.postalAddress, "WORK_PHYSICAL": self.workPhysicalAddress, "WORK_POSTAL": self.workPostalAdress} agrid = wx.GridSizer(1, 2, 3, 3) agrid.AddMany([(self.physicalAddress, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3), (self.workPhysicalAddress, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3), (self.postalAddress, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3), (self.workPostalAdress, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3)]) #agrid.AddGrowableRow(0, 1) #agrid.AddGrowableRow(1, 1) #agrid.SetFlexibleDirection(wx.HORIZONTAL|wx.VERTICAL) # save saveBtn = wx.Button(self, wx.ID_SAVE) self.Bind(wx.EVT_BUTTON, self.__saveData, saveBtn) # new newBtn = wx.Button(self, wx.ID_NEW) self.Bind(wx.EVT_BUTTON, self.new, newBtn) btnBox = wx.BoxSizer(wx.HORIZONTAL) btnBox.Add(newBtn, 0, wx.ALIGN_CENTER|wx.ALL, 3) btnBox.Add(saveBtn, 0, wx.ALIGN_CENTER|wx.ALL, 3) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(gridBox, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) sizer.Add(agrid, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) sizer.Add(btnBox, 0, wx.ALIGN_CENTER|wx.ALL, 3) self.SetSizer(sizer)
def __init__(self, parent, ID, title): wx.Frame.__init__(self, parent, ID, title, wx.DefaultPosition, #size=(500, 600), style=wx.DEFAULT_FRAME_STYLE) Registry.add("APPFRAME", self) self.parent = parent self.splitter = wx.SplitterWindow(self, -1, style=wx.CLIP_CHILDREN| wx.SP_LIVE_UPDATE| wx.SP_3D) self.searchpanel = SearchPanel(self.splitter, -1) self.dataNB = DataNoteBook(self.splitter, -1) self.splitter.SplitVertically(self.searchpanel, self.dataNB) self.splitter.SetSashPosition(260, True) self.splitter.SetMinimumPaneSize(20) # application peripherals self.makeStatusBar() self.makeMenuBar() sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(self.searchpanel, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) sizer.Add(self.dataNB, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) self.SetSizer(sizer) self.SetAutoLayout(True) self.Fit() # self.SetSize(self.GetClientSize()) # self.SetSize((1000, 800)) self.Maximize(True) # event handler self.Bind(wx.EVT_CLOSE, CLEANUP.Quit) wx.EVT_SIZE(self, self.OnSize) self.Centre(wx.BOTH) self.SetIcon(self.__getIcon())
def __init__(self, parent, service=""): wx.Window.__init__(self, parent, -1, size=(20, -1)) Registry.addList("LEDS", self) self.service = service self.SetToolTip(wx.ToolTip(str(service))) self.defcolour = self.GetBackgroundColour() self.serviceColors = {'LOG':wx.GREEN, 'WATCH':wx.BLUE} self.serviceColor = self.serviceColors[self.service] font = wx.Font(FONTSIZE, wx.NORMAL, wx.NORMAL, wx.LIGHT) self.SetFont(font) EVT_LED(self, self.handleLEDEvt)
def __init__(self, parent, ID): wx.Panel.__init__(self, parent, ID) Registry.add("VISITS", self) Result.addListener(self) self.visits = {} self.file_number = None self.selected = None # visit list self.visitListCtrl = wx.ListBox(self, -1, size=(100, -1)) self.Bind(wx.EVT_LISTBOX, self.dateSelected, self.visitListCtrl) visitBox = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Visit List"), wx.HORIZONTAL) visitBox.Add(self.visitListCtrl, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # note self.note = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE) # self.Bind(wx.EVT_CHAR, self.OnKeyDown, self.note) wx.EVT_CHAR(self.note, self.OnKeyDown) self.noteLabel = wx.StaticBox(self, -1, "Visit Note") noteBox = wx.StaticBoxSizer(self.noteLabel, wx.HORIZONTAL) noteBox.Add(self.note, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) topBox = wx.BoxSizer(wx.HORIZONTAL) topBox.Add(visitBox, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) topBox.Add(noteBox, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # save saveBtn = wx.Button(self, wx.ID_SAVE) self.Bind(wx.EVT_BUTTON, self.__saveData, saveBtn) newBtn = wx.Button(self, wx.ID_NEW) self.Bind(wx.EVT_BUTTON, self.__new, newBtn) btnBox = wx.BoxSizer(wx.HORIZONTAL) btnBox.Add(newBtn, 0, wx.ALIGN_CENTER|wx.ALL, 3) btnBox.Add(saveBtn, 0, wx.ALIGN_CENTER|wx.ALL, 3) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(topBox, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) sizer.Add(btnBox, 0, wx.ALIGN_CENTER|wx.ALL, 3) self.SetSizer(sizer)
def getBar(self): """ get a reference to the status bar, it might not exist in the beginning """ if self.statusbar == None: try: self.statusbar = Registry.get('APPFRAME').GetStatusBar() return self.statusbar except AttributeError: return None else: return self.statusbar
def displayOKBox(txt,parent=None,hdr='Confirmation'): """ display an ok/cancel dialog box. return true if ok pressed, false otherwse. """ appframe = Registry.get('APPFRAME') if parent == None: parent = appframe dlg = ConfirmationDialog(parent,msg=txt) return dlg.ShowModal()
class Carrier(ftb.Ship.Ship): "A Ship subclass that carries a series of launchers carrying other ships/objects" def __init__(self, pShip): debug(__name__ + ", __init__") ftb.Ship.Ship.__init__(self, pShip) # TODO: change self.launchers to a Registry self.launchers = Registry() def AddLauncher(self, launcherName, launcher): debug(__name__ + ", AddLauncher") if launcherName != None and launcher != None: self.launchers.Register(launcher, launcherName) def GetLauncher(self, launcherName): debug(__name__ + ", GetLauncher") if launcherName != None and self.launchers.has_key(launcherName): return self.launchers.GetName(launcherName) def GetLaunchers(self): debug(__name__ + ", GetLaunchers") return self.launchers def GetNumLaunches(self, launchName): debug(__name__ + ", GetNumLaunches") "Iterates over all of a Carriers launchers and tallies up the number of a particular Launch aboard" retval = 0 if launchName != None: for launcherName in self.launchers._keyList: launcher = self.launchers[launcherName] retval = retval + launcher.GetNumLaunches(launchName) return retval def HasMoreLaunches(self, shuttle): debug(__name__ + ", HasMoreLaunches") return self.GetNumLaunches(shuttle) def GetLaunchType(self, launcherName): debug(__name__ + ", GetLaunchType") return self.launchers.GetName(launcherName).GetLaunchType() def NextLaunchType(self, launcherName): debug(__name__ + ", NextLaunchType") return self.launchers.GetName(launcherName).NextLaunchType() def LaunchShip(self, shuttle, launcherName): debug(__name__ + ", LaunchShip") return self.Launchers.GetName(launcherName).LaunchShip(shuttle) def LaunchShip(self, shuttle, launcherIndex): debug(__name__ + ", LaunchShip") return self.Launchers[launcherIndex].LaunchShip(shuttle)
def __init__(self, parent, ID): wx.StatusBar.__init__(self, parent, ID, style=wx.GA_SMOOTH) TimeRegistry.add('STATUSBAR', self) Registry.add("STATUSBAR", self) self.barrange = 0 self.barvalue = 0 # hart hartbmp = ART['24x24hart'] self.hartPic = wx.StaticBitmap(self, -1, hartbmp, size=(hartbmp.GetWidth(), hartbmp.GetHeight())) self.hartPic.Show(False) # the gauge self.gauge = wx.Gauge(self, -1, 0) self.gauge.SetBezelFace(3) self.gauge.SetShadowWidth(3) fieldlengths = [400, -1, 20, 20, 160, hartbmp.GetWidth() + 6] self.SetFieldsCount(len(fieldlengths)) self.SetStatusWidths(fieldlengths) self.write('Witkoppen Registry GUI Initialized ...') # network access flashers self.LOGLED = LEDWindow(self, service="LOG") self.WATCHLED = LEDWindow(self, service="WATCH") self.position() # position the various wigets on the bar EVT_GLOBAL_TIME(self, self.clockDisplay) EVT_STATUSBAR(self, self.OnBarMessage) wx.EVT_SIZE(self, self.OnSize)
def displayMessage(txt, parent=None, sw=1, hdr='Witkoppen, Attention'): """ bring something under user attention """ txt = str(txt) appframe = Registry.get('APPFRAME') if parent == None: parent = appframe if sw: if appframe: bar = appframe.GetStatusBar() if bar: bar.write(txt) dlg = MonologDialog(parent, txt, hdr) dlg.ShowModal()
def __init__(self, parent=None): QtGui.QWidget.__init__(self, None) self.parent = parent Registry().objects["config"] = Config() self.conf = Registry().objects["config"] self.ui = uic.loadUi(("./ui/configWindow.ui"), self) self.setWindowFlags(QtCore.Qt.CustomizeWindowHint | QtCore.Qt.WindowTitleHint) self.colorHelp.linkActivated.connect(self.open_browser) self.local = self.conf.config # flags first self.enableSound.setChecked(self.conf.config["enableSound"]) self.showOffline.setChecked(self.conf.config["showOffline"]) self.loadHistory.setChecked(self.conf.config["loadHistory"]) # input fields second self.contactsTimeout.setValue(self.conf.config["contactsTimeout"]) self.messagesTimeout.setValue(self.conf.config["messagesTimeout"]) self.historyCount.setValue(self.conf.config["historyCount"]) if isColor(self.conf.config["myColor"]): self.myColor.setText(self.conf.config["myColor"]) else: self.myColor.setText("000000") if isColor(self.conf.config["friendsColor"]): self.friendsColor.setText(self.conf.config["friendsColor"]) else: self.friendsColor.setText("000000") # finally, setting whether some widgets are active self.historyCount.setEnabled(self.loadHistory.isChecked()) self.apply.accepted.connect(self.save) self.apply.rejected.connect(self.close) self.enableSound.toggled.connect(self.enableSoundSave) self.showOffline.toggled.connect(self.showOfflineSave) self.loadHistory.toggled.connect(self.loadHistorySave) self.contactsTimeout.valueChanged.connect(self.contactsTimeoutSave) self.messagesTimeout.valueChanged.connect(self.messagesTimeoutSave) self.historyCount.valueChanged.connect(self.historyCountSave) self.myColor.textChanged.connect(self.myColorSave) self.friendsColor.textChanged.connect(self.friendsColorSave)
# print query try: cursor = self.conn.cursor() cursor.execute(query) self.conn.commit() except psycopg.IntegrityError, x: msg = "Failed to Add entry,\nFile Number %d already in use" % data['file_number'] from Dialogs.Utils import displayMessage displayMessage(msg) BARWRITER.write(msg) return if self.lastSearchData: res = self.search(self.lastSearchData) Registry.get("SEARCH").presentResult() BARWRITER.write("New Entry Added at %s" % time.ctime()) def deleteEntry(self, folderNo): """ delete the folder from the database""" query = """ delete from patient.contact where file_number='%(file_number)d'; delete from patient.visit where file_number='%(file_number)d'; delete from patient.patient where file_number='%(file_number)d'; """ % {"file_number":folderNo} cursor = self.conn.cursor() cursor.execute(query) self.conn.commit()
def __init__(self, parent, ID): wx.Panel.__init__(self, parent, ID) Registry.add("BIO", self) Result.addListener(self) modefont = wx.Font(16, wx.NORMAL , wx.BOLD, wx.NORMAL, False) self.modeLabel = wx.StaticText(self, -1, editstr, size=(600, -1)) self.modeLabel.SetFont(modefont) # folder number bigfont = wx.Font(22, wx.MODERN , wx.BOLD, wx.NORMAL, False) self.folderNumber = wx.TextCtrl(self, -1, "", size=(130, -1)) self.folderNumber.SetBackgroundColour(Colors.LIGHTBLUE) self.folderNumber.SetFont(bigfont) folderBox = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Folder Number"), wx.HORIZONTAL) folderBox.Add(self.folderNumber, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # name self.name = wx.TextCtrl(self, -1, "", size=(350, -1)) self.name.SetFont(bigfont) self.name.SetBackgroundColour(Colors.PURPLE) nameBox = wx.StaticBoxSizer(wx.StaticBox(self, -1, "First Names"), wx.HORIZONTAL) nameBox.Add(self.name, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # surname self.surname = wx.TextCtrl(self, -1, "", size=(250, -1)) self.surname.SetFont(bigfont) self.surname.SetBackgroundColour(Colors.PURPLE) surnameBox = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Surname"), wx.HORIZONTAL) surnameBox.Add(self.surname, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # callname self.callname = wx.TextCtrl(self, -1, "", size=(120, -1)) callnameBox = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Name"), wx.HORIZONTAL) callnameBox.Add(self.callname, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # add the names to the top ass well, they are written in large font topBox = wx.BoxSizer(wx.HORIZONTAL) topBox.Add(folderBox, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) topBox.Add(nameBox, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) topBox.Add(surnameBox, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # names # mainnameBox = wx.BoxSizer(wx.HORIZONTAL) # mainnameBox.Add(callnameBox, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # mainnameBox.Add(nameBox, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # mainnameBox.Add(surnameBox, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # birthdate #self.birthdate = wx.DatePickerCtrl(self, size=(120,-1), # style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY) self.birthdate = wx.TextCtrl(self, -1, "", size=(120, -1)) birthdayBox = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Birth Date"), wx.HORIZONTAL) birthdayBox.Add(self.birthdate, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # gender self.gender = wx.Choice(self, -1, choices=["Male", "Female", "Undefined"], size=(120, -1)) genderBox = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Gender"), wx.HORIZONTAL) genderBox.Add(self.gender, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # marital status self.marital_status = wx.Choice(self, -1, choices=["Single", "Married", "Divorced", "Widowed"], size=(120, -1)) maritalBox = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Marital Status"), wx.HORIZONTAL) maritalBox.Add(self.marital_status, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) bgBox = wx.BoxSizer(wx.HORIZONTAL) bgBox.Add(birthdayBox, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) bgBox.Add(genderBox, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) bgBox.Add(maritalBox, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # ID self.ID = wx.TextCtrl(self, -1, "", size=(200, -1)) IDBox = wx.StaticBoxSizer(wx.StaticBox(self, -1, "National ID"), wx.HORIZONTAL) IDBox.Add(self.ID, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # nationality self.nationality = wx.TextCtrl(self, -1, "") nationalBox = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Nationality"), wx.HORIZONTAL) nationalBox.Add(self.nationality, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # language self.language = wx.TextCtrl(self, -1, "", size=(200, -1)) languageBox = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Language"), wx.HORIZONTAL) languageBox.Add(self.language, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # race self.race = wx.TextCtrl(self, -1, "", size=(200, -1)) raceBox = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Ethnicity"), wx.HORIZONTAL) raceBox.Add(self.race, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # id allidBox = wx.BoxSizer(wx.HORIZONTAL) allidBox.Add(IDBox, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) allidBox.Add(nationalBox, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) allidBox.Add(languageBox, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) allidBox.Add(raceBox, 0, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # occupation self.occupation = wx.TextCtrl(self, -1, "", size=(300, -1)) occupationBox = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Occupation"), wx.HORIZONTAL) occupationBox.Add(self.occupation, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # employer self.employer = wx.TextCtrl(self, -1, "", size=(300, -1)) employerBox = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Employer"), wx.HORIZONTAL) employerBox.Add(self.employer, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) workBox = wx.BoxSizer(wx.HORIZONTAL) workBox.Add(occupationBox, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) workBox.Add(employerBox, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # dependants self.dependants = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE) self.dependants.SetBackgroundColour(Colors.INFOCOL) dependantBox = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Dependants, Only spouse and Children under 18"), wx.HORIZONTAL) dependantBox.Add(self.dependants, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # note self.note = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE) self.note.SetBackgroundColour(Colors.INFOCOL) noteBox = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Additional Notes"), wx.HORIZONTAL) noteBox.Add(self.note, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) depnoteBox = wx.BoxSizer(wx.HORIZONTAL) depnoteBox.Add(dependantBox, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) depnoteBox.Add(noteBox, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # synopsis self.synopsis = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE) synopsisBox = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Synopsis"), wx.HORIZONTAL) synopsisBox.Add(self.synopsis, 1, wx.ALIGN_CENTER|wx.GROW|wx.ALL, 3) # save saveBtn = wx.Button(self, wx.ID_SAVE) self.Bind(wx.EVT_BUTTON, self.__saveData, saveBtn) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.modeLabel, 0, wx.ALIGN_LEFT|wx.ALL, 3) sizer.Add(topBox, 0, wx.ALIGN_LEFT|wx.ALL, 3) sizer.Add(callnameBox, 0, wx.ALIGN_LEFT|wx.ALL, 3) sizer.Add(bgBox, 0, wx.ALIGN_LEFT|wx.ALL, 3) sizer.Add(allidBox, 0, wx.ALIGN_LEFT|wx.ALL, 3) sizer.Add(workBox, 0, wx.ALIGN_LEFT|wx.ALL, 3) sizer.Add(depnoteBox, 2, wx.ALIGN_LEFT|wx.GROW|wx.ALL, 3) sizer.Add(synopsisBox, 1, wx.ALIGN_LEFT|wx.GROW|wx.ALL, 3) sizer.Add(saveBtn, 0, wx.ALIGN_CENTER|wx.ALL, 3) self.SetSizer(sizer) self.widgetList = [ self.folderNumber, self.surname, self.name, self.birthdate, #self.gender, self.ID, self.nationality, self.note, self.callname, self.language, self.occupation, self.synopsis, self.dependants, self.race, self.employer ]
def samparse(samhive): results = OrderedDict() results['users'] = OrderedDict() #Ok this one is a bit more diffuclt. the data in here is in Binary data which means we need to unpack all of it. #The SAM file is structed like this #0000123F #F - Contains binary data #V - Contains binary data #0000234F #F - Contains binary data #V - Contains binary data #The subkeys that start with 0000 Correlate with each user on the computer while the F and V contain different data. #The 0000 can be striped off then you get a hex value which can be decoded to the user's RID #F contains type of account, and various account settings #V contains username, fullname, comment, password hashes and more #We have to individually parse both the F and V for every user. f_values = {} #Used to temp store F Data before we get V Value data #ACB Flags which tell us if the account is disabled/etc acb_flags = { 0x0001: "Account Disabled", 0x0002: "Home directory required", 0x0004: "Password not required", 0x0008: "Temporary duplicate account", 0x0010: "Normal user account", 0x0020: "MNS logon user account", 0x0040: "Interdomain trust account", 0x0080: "Workstation trust account", 0x0100: "Server trust account", 0x0200: "Password does not expire", 0x0400: "Account auto locked" } #Account Types types = { 0xbc: "Default Admin User", 0xd4: "Custom Limited Acct", 0xb0: "Default Guest Acct" } sam = Registry.Registry(samhive) #open the hive using python-registry usersRoot = sam.open("SAM\\Domains\\Account\\Users") for x in usersRoot.subkeys(): #We Use this to get the account name and timestamp if x.name() == "Names": for a in x.subkeys(): results['users'][ a.name()]['Account Created Date'] = a.timestamp().strftime( '%d %B %Y - %H:%M:%S') else: for a in x.values(): #F comes before V, and since we're using usernames, F will store in a temporary dict #F Comes in binary data aswell #For unpacking this is the formatting # x = padded null bytes (\00x) # L = Unsigned long (32bit) in little-endian # H = Unsigned short (16bit) in little-endian if a.name() == "F": b = struct.unpack( '<xxxxxxxxLLxxxxxxxxLLxxxxxxxxLLLxxxxHxxxxxxHHxxxxxxxxxxxx', a.value()) f_values[b[6]] = [] #Create a List and sort by RID f_values[b[6]].append(getTime(b[0], b[1])) #Last Login Date f_values[b[6]].append(getTime( b[2], b[3])) #This is password reset date f_values[b[6]].append(getTime(b[4], b[5])) #PWD Fail Date maybe? flags = [] for flag in acb_flags: #Compare the two hex values and check if one is contained in the other, if so save it if bool(flag & b[7]): flags.append(acb_flags[flag]) f_values[b[6]].append(flags) f_values[b[6]].append(b[8]) #Failed Login Count f_values[b[6]].append(b[9]) #Login Count #Parsing the "V" Value #the first 4 bytes of each entry refer to the location of the entry relative to offset #the second 4 bytes refer to the entry length, rounded up to the nearest multiple of 4 #for example the 4 bytes from 0x0c -> 0x10 contains the offset+0xcc(4) where the username is if a.name() == "V": data = a.value() #Unpacking The values, refrence here http://www.beginningtoseethelight.org/ntsecurity/index.htm #Get the account type, username, fullname, comment, driveletter, logon script, profile path, workstation's allowed, and LM and NT password hashes account_type = struct.unpack("<L", data[4:8])[0] username_ofst = struct.unpack("<L", data[12:16])[0] username_lngth = struct.unpack("<L", data[16:20])[0] fullname_ofst = struct.unpack("<L", data[24:28])[0] fullname_lngth = struct.unpack("<L", data[28:32])[0] comment_ofst = struct.unpack("<L", data[36:40])[0] comment_lngth = struct.unpack("<L", data[40:44])[0] driveletter_ofst = struct.unpack("<L", data[84:88])[0] driveletter_lngth = struct.unpack("<L", data[88:92])[0] logonscript_ofst = struct.unpack("<L", data[96:100])[0] logonscript_lngth = struct.unpack("<L", data[100:104])[0] profilepath_ofst = struct.unpack("<L", data[108:112])[0] profilepath_lngth = struct.unpack("<L", data[112:116])[0] workstations_ofst = struct.unpack("<L", data[120:124])[0] workstations_lngth = struct.unpack("<L", data[124:128])[0] # lmpwhash_ofset = struct.unpack("<L", data[156:160])[0] Can enable this, contains the NT and LM hashes # lmpwhash_lngth = struct.unpack("<L", data[160:164])[0] # ntpwhash_ofset = struct.unpack("<L", data[168:172])[0] # ntpwhash_lngth = struct.unpack("<L", data[172:176])[0] username = data[(username_ofst + 0xCC):(username_ofst + 0xCC + username_lngth)].replace( '\x00', '') results['users'][username] = OrderedDict() results['users'][username]['Full Name'] = data[( fullname_ofst + 0xCC):(fullname_ofst + 0xCC + fullname_lngth)] results['users'][username]['Comment'] = data[( comment_ofst + 0xCC):(comment_ofst + 0xCC + comment_lngth)] for acctype in types: if account_type == int(acctype): results['users'][username]['Account Type'] = types[ acctype] results['users'][username]['RID'] = str( int(x.name().strip("0000"), 16) ) #Since im converting hex to int, you need to tell python it's in base 16 results['users'][username]['Drive Letter'] = data[( driveletter_ofst + 0xCC):(driveletter_ofst + 0xCC + driveletter_lngth)] results['users'][username]['Profile Path'] = data[( profilepath_ofst + 0xCC):(profilepath_ofst + 0xCC + profilepath_lngth)] results['users'][username]['Logon Script'] = data[( logonscript_ofst + 0xCC):(logonscript_ofst + 0xCC + logonscript_lngth)] results['users'][username]['Workstations'] = data[( workstations_ofst + 0xCC):(workstations_ofst + 0xCC + workstations_lngth)] # results['users'][username]['LM Password Hash'] = data[(lmpwhash_ofset+0xCC):(lmpwhash_ofset+0xCC + lmpwhash_lngth)] # results['users'][username]['NT Password Hash'] = data[(ntpwhash_ofset+0xCC):(ntpwhash_ofset+0xCC + ntpwhash_lngth)] continue #Now we combine the two! for RID in f_values: for user in results['users']: if results['users'][user]['RID'] == str(RID): results['users'][user]['Last Login Date'] = f_values[RID][0] results['users'][user]['Password Reset Date'] = f_values[RID][ 1] results['users'][user]['Password Fail Date'] = f_values[RID][2] results['users'][user]['Account Flags'] = "" for user in results: if results[user]['RID'] == str(RID): results['users'][user]['Last Login Date'] = f_values[RID][0] results['users'][user]['Password Reset Date'] = f_values[RID][ 1] results['users'][user]['Password Fail Date'] = f_values[RID][2] results['users'][user]['Account Flags'] = "" for flag in f_values[RID][3]: results['users'][user]['Account Flags'] += (flag + " | ") results['users'][user]['Failed Login Count'] = f_values[RID][4] results['users'][user]['Login Count'] = f_values[RID][5] break results['groups'] = OrderedDict() #Now to parse the groups! groupsRoot = sam.open("SAM\\Domains\\Builtin\\Aliases") for x in groupsRoot.subkeys(): if x.name( )[: 5] == "00000": #We dont actually need the Names/Members keys here beacuse everything is in the "C" value #this is going to be the same as the V value, we have to unpack offsets/points to get the data we need #In the C key all offsets are started from 0x34 (this means we do offset+0x34) data = x.value("C").value() name_offst = struct.unpack("<L", data[16:20])[0] name_length = struct.unpack("<L", data[20:24])[0] comment_offst = struct.unpack("<L", data[28:32])[0] comment_lngth = struct.unpack("<L", data[32:36])[0] users_offset = struct.unpack("<L", data[40:44])[0] user_count = struct.unpack("<L", data[48:52])[0] groupname = data[(name_offst + 52):(name_offst + 52 + name_length)] results['groups'][groupname] = OrderedDict() results['groups'][groupname]['Group Description'] = data[( comment_offst + 52):(comment_offst + 52 + comment_lngth)] results['groups'][groupname]['Last Write'] = x.timestamp() results['groups'][groupname]['User Count'] = user_count results['groups'][groupname]['Members'] = '' try: newOffset = 0 for i in range(11, 0, -1): offset = int(users_offset + 52 + newOffset) tmp = struct.unpack("<L", data[offset:offset + 4])[0] if tmp == 257: if struct.unpack("<B", data[offset:offset + 1])[0] == 0: offset = offset + 1 results['groups'][groupname][ 'Members'] += binary_to_sid(data[offset:offset + 12]) #username = sid_to_username(binary_to_sid(data[offset:offset+12])) username = None if username != None: results['groups'][groupname][ 'Members'] += " -> " + username + "</br>" else: results['groups'][groupname]['Members'] += "\t\n" newOffset += 12 elif tmp == 1281: results['groups'][groupname][ 'Members'] += binary_to_sid(data[offset:offset + 28]) #username = sid_to_username(binary_to_sid(data[offset:offset+28])) username = None if username != None: results['groups'][groupname][ 'Members'] += " -> " + username + "</br>" else: results['groups'][groupname]['Members'] += "\n" newOffset += 28 except: if len(results['groups'][groupname]['Members']) == 0: results['groups'][groupname][ 'Members'] = 'No users in this group' else: continue return results
class Pinterest: def __init__(self, password='', proxies=None, username='', email='', cred_root='data'): self.email = email self.username = username self.password = password self.req_builder = RequestBuilder() self.bookmark_manager = BookmarkManager() self.http = requests.session() self.proxies = proxies data_path = os.path.join(cred_root, self.email) + os.sep if not os.path.isdir(data_path): os.makedirs(data_path) self.registry = Registry('{}registry.dat'.format(data_path)) cookies = self.registry.get(Registry.Key.COOKIES) if cookies is not None: self.http.cookies.update(cookies) def request(self, method, url, data=None, files=None, extra_headers=None): headers = CaseInsensitiveDict([ ('Referer', HOME_PAGE), ('X-Requested-With', 'XMLHttpRequest'), ('Accept', 'application/json'), ('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'), ('User-Agent', AGENT_STRING) ]) csrftoken = self.http.cookies.get('csrftoken') if csrftoken: headers.update([('X-CSRFToken', csrftoken)]) if extra_headers is not None: for h in extra_headers: headers.update([(h, extra_headers[h])]) response = self.http.request(method, url, data=data, headers=headers, files=files, proxies=self.proxies) response.raise_for_status() self.registry.update(Registry.Key.COOKIES, response.cookies) return response def get(self, url): return self.request('GET', url=url) def post(self, url, data=None, files=None, headers=None): return self.request('POST', url=url, data=data, files=files, extra_headers=headers) def login(self): self.get(HOME_PAGE) self.get(LOGIN_PAGE) options = {'username_or_email': self.email, 'password': self.password} data = self.req_builder.buildPost( options=options, source_url='/login/?referrer=home_page') return self.post(url=CREATE_USER_SESSION, data=data) def get_user_overview(self, username=None): if username is None: username = self.username options = { "isPrefetch": 'false', "username": username, "field_set_key": "profile" } url = self.req_builder.buildGet(url=USER_RESOURCE, options=options) result = self.get(url=url).json() return result['resource_response']['data'] def home_feed(self, page_size=100): next_bookmark = self.bookmark_manager.get_bookmark(primary='home_feed') if next_bookmark == '-end-': return [] options = { "bookmarks": [next_bookmark], "isPrefetch": False, "field_set_key": "hf_grid_partner", "in_nux": False, "prependPartner": True, "prependUserNews": False, "static_feed": False, "page_size": page_size } url = self.req_builder.buildGet(url=USER_HOME_FEED_RESOURCE, options=options) response = self.get(url=url).json() bookmark = '-end-' if 'bookmark' in response['resource_response']: bookmark = response['resource_response']['bookmark'] self.bookmark_manager.add_bookmark(primary='home_feed', bookmark=bookmark) return response['resource_response']['data'] def search(self, scope, query, page_size=250): next_bookmark = self.bookmark_manager.get_bookmark(primary='search', secondary=query) if next_bookmark == '-end-': return [] terms = query.split(' ') escaped_query = "%20".join(terms) term_meta_arr = [] for t in terms: term_meta_arr.append('term_meta[]=' + t) term_arg = "%7Ctyped&".join(term_meta_arr) source_url = '/search/{}/?q={}&rs=typed&{}%7Ctyped'.format( scope, escaped_query, term_arg) options = { "isPrefetch": False, "auto_correction_disabled": False, "query": query, "redux_normalize_feed": True, "rs": "typed", "scope": scope, "page_size": page_size, "bookmarks": [next_bookmark] } url = self.req_builder.buildGet(url=BASE_SEARCH_RESOURCE, options=options, source_url=source_url) resp = self.get(url=url).json() bookmark = resp['resource']['options']['bookmarks'][0] self.bookmark_manager.add_bookmark(primary='search', secondary=query, bookmark=bookmark) return resp['resource_response']['data']['results']
def getDefaultBrowserByUserName(self, userName): output = self.volumeInfo if "FAT" or "NTFS" in output.split(" ")[0]: os.chdir("%s/%s/" % (self.mountDir, output.split(" ")[2])) logger.info( "Loading every user info!") # TODO:It should be per user! try: os.chdir("Users/") except FileNotFoundError: logger.error("Couldn't find Users folder!") return None for userDir in os.listdir("."): if userName == userDir: if os.access( "{0}/AppData/Local/Microsoft/Windows/UsrClass.dat". format(userDir), os.F_OK | os.R_OK): registry = Registry.Registry( "{0}/NTUSER.DAT".format(userDir)) else: logger.warning("Couldn't find user registry on %s" % userDir) continue try: open1 = registry.open("http\\shell\\open\\command") except Registry.RegistryKeyNotFoundException: logger.error( "Couldn't find UsrClass http registry on user {0}". format(userDir)) continue logger.info("Now showing %s default http open info!" % userDir) logger.debug("Default HTTP open handler : {0}".format( open1.value("(default)").value())) try: open2 = registry.open("https\\shell\\open\\command") except Registry.RegistryKeyNotFoundException: logger.error( "Couldn't find UsrClass https registry on user {0}" .format(userDir)) continue logger.info("Now showing %s default http open info!" % userDir) logger.debug("Default HTTPS open handler : {0}".format( open2.value("(default)").value())) try: open3 = registry.open(".html") except Registry.RegistryKeyNotFoundException: logger.error( "Couldn't find UsrClass http registry on user {0}". format(userDir)) continue html_value = open3.value("(default)").value() try: open4 = registry.open(html_value) except Registry.RegistryKeyNotFoundException: logger.error( ".html association on user {0} may be broken!". format(userDir)) continue logger.info("Now showing %s default .html open info!" % userDir) logger.debug("Default .html open handler : {0}".format( open4.subkey("shell").subkey("open").subkey( "command").value("(default)").value()))
def __init__(self, ql, hive=None, config=None): self.ql = ql self.registry_config = None self.config = config # hive dir if hive: self.hive = hive else: self.hive = os.path.join(ql.rootfs, "Windows", "registry") ql.dprint("[+] Windows Registry PATH: %s" % self.hive) if not os.path.exists(self.hive): raise QlPrintException("Error: Registry files not found!") #return if ql.log_dir == None: ql.log_reg_dir = os.path.join(ql.rootfs, "qlog") else: ql.log_reg_dir = ql.log_dir self.config = os.path.join(ql.log_reg_dir, "registry", "registry_diff.json") if not os.path.exists(self.config): self.registry_config = {} try: os.makedirs(os.path.join(ql.log_reg_dir, "registry"), 0o755) except: pass else: # read config # use registry config first self.f_config = open(self.config, "rb") data = self.f_config.read() if data == b"": self.registry_config = {} self.f_config.close() else: try: self.registry_config = json.loads(data) except json.decoder.JSONDecodeError: raise QlErrorJsonDecode( "[!] Windows Registry JSON decode error") finally: self.f_config.close() # hkey local system self.hklm = {} try: self.hklm['SECURITY'] = Registry.Registry( os.path.join(self.hive, 'SECURITY')) self.hklm['SAM'] = Registry.Registry(os.path.join( self.hive, 'SAM')) self.hklm['SOFTWARE'] = Registry.Registry( os.path.join(self.hive, 'SOFTWARE')) self.hklm['SYSTEM'] = Registry.Registry( os.path.join(self.hive, 'SYSTEM')) # hkey current user self.hkcu = Registry.Registry(os.path.join(self.hive, 'NTUSER.DAT')) except FileNotFoundError: QlPrintException("WARNING: Registry files not found!") except Exception: QlPrintException("WARNING: Registry files format error")
def __init__(self, ql, hive=None, config=None): self.ql = ql rootfs = ql.rootfs self.registry_config = None # hive dir if hive: self.hive = hive else: if not ql.reg_dir: ql.reg_dir = "registry" self.hive = os.path.join(rootfs, ql.reg_dir) if not os.path.exists(self.hive): return # config path if config: self.config = config else: if not ql.reg_diff: ql.reg_diff = "config.json" self.config = os.path.join(rootfs, ql.reg_dir, ql.reg_diff) if not os.path.exists(self.config): self.registry_config = {} else: # read config # use registry config first self.f_config = open(self.config, "rb") data = self.f_config.read() if data == b"": self.registry_config = {} self.f_config.close() else: try: self.registry_config = json.loads(data) except json.decoder.JSONDecodeError: raise QlErrorJsonDecode( "Windows Registry JSON decode error") finally: self.f_config.close() # hkey local system self.hklm = {} try: self.hklm['SAM'] = Registry.Registry(os.path.join( self.hive, 'SAM')) self.hklm['SECURITY'] = Registry.Registry( os.path.join(self.hive, 'SECURITY')) self.hklm['SOFTWARE'] = Registry.Registry( os.path.join(self.hive, 'SOFTWARE')) self.hklm['SYSTEM'] = Registry.Registry( os.path.join(self.hive, 'SYSTEM')) # hkey current user self.hkcu = Registry.Registry(os.path.join(self.hive, 'NTUSER.DAT')) except FileNotFoundError: QlPrintException("WARNING: Registry files not found!") except Exception: QlPrintException("WARNING: Registry files format error")
def __init__(self, parent, ID): wx.Panel.__init__(self, parent, ID) Registry.add("ANC", self) Result.addListener(self)
def CurrentControlSet(self): select = Registry.Registry(self.hive).open("Select") current = select.value("Current").value() controlsetnum = "ControlSet00%d" % (current) return (controlsetnum)
def get_registry(pod): return Registry.Registry(pod)
def main(): #Definition der Argumente parser = argparse.ArgumentParser( description='Vergleich der Windows-Registrierungsdatenbank') parser.add_argument('--imageA', help='Dateipfad des ersten Festplattenabbildes', required=False) parser.add_argument('--imageB', help='Dateipfad des zweiten Festplattenabbildes', required=False) parser.add_argument('--outputDir', help='Dateipfad, in dem die Resultate der Vergleiche der einzelnen Dateien im ' 'CSV-Format abgelegt werden', required=True) parser.add_argument('--dirA', help='Verzeichnis, aus dem die Dateien gelesen werden', required=False) parser.add_argument('--dirB', help='Verzeichnis, aus dem die Dateien gelesen werden', required=False) args = vars(parser.parse_args()) if not args.get('imageA') and not args.get('dirA'): parser.error( u'Entweder --imageA bzw. --imageB oder --dirA bzw. --dirB müssen als Parameter ' u'angegeben werden.') if args.get('imageA') and not args.get('imageB'): parser.error(u'Es müssen beide Pfade zu den virtuellen Festplatten angegeben werden.') if args.get('dirA') and not args.get('dirB'): parser.error(u'Es müssen beide Pfade zu den Verzeichnissen angegeben werden.') imageA = args.get('imageA') imageB = args.get('imageB') outputDir = os.path.join(args.get('outputDir'), '', '') dirA = args.get('dirA') dirB = args.get('dirB') #Messen der benötigten Zeit startTime = time.time() if not dirA: dirA = TEMP_DIRECTORY_A dirB = TEMP_DIRECTORY_B g = guestfs.GuestFS(python_return_dict=True) extractFiles(g, imageA, dirA) extractFiles(g, imageB, dirB) g.close() else: dirA = os.path.join(dirA, '', '') dirB = os.path.join(dirB, '', '') for root, subFolders, fileList in os.walk(dirA): for file in fileList: files.add(file) for root, subFolders, fileList in os.walk(dirB): for file in fileList: files.add(file) if not os.path.exists(outputDir): os.makedirs(outputDir) for file in files: regA = Registry.Registry(dirA + file) regB = Registry.Registry(dirB + file) compare(regA, regB, file, outputDir) if not dirA: shutil.rmtree(TEMP_DIRECTORY_A) shutil.rmtree(TEMP_DIRECTORY_B) endTime = time.time() print u'Skript ausgeführt in {0}'.format( datetime.timedelta(seconds=round(endTime - startTime, 0)))
import argparse from Registry import Registry parser = argparse.ArgumentParser() parser.add_argument('-f', dest='inputfile') parser.add_argument('-o', dest='outfile') parser.add_argument('-n', dest='hostname') args = parser.parse_args() f = open(args.outfile, 'a') reg = Registry.Registry(args.inputfile) def rec(key, depth=0): for subkey in key.subkeys(): rec(subkey, depth + 0) for value in [ v for v in key.values() if v.value_type() == Registry.RegBin ]: shorten = value.value() #shorten = shorten.decode('utf-8') #sha1 = shorten[8:] shorten = shorten.decode('utf-16').rstrip('\x00') sha1 = shorten[4:] if value.name() == 'AeFileID': print("{},{},{}".format(key.timestamp(), sha1, args.hostname)) f.write("{},{},{}\n".format(key.timestamp(), sha1, args.hostname)) rec(reg.root())
def main(): if len(sys.argv) != 2: print(usage()) sys.exit(-1) registry = Registry.Registry(sys.argv[1]) select = registry.open("Select") current = select.value("Current").value() services = registry.open("ControlSet00%d\\Services" % (current)) print( 'TIME,NAME,START TYPE,SERVICE TYPE,DISPLAY NAME,IMAGE PATH,DLL,DESCRIPTION' ) for service in services.subkeys(): try: servicename = (service.name().replace(",", ";")) except: servicename = "-No_Service_Name-" try: timestamp = str(service.timestamp()) except: timestamp = "-No_Timestamp-" try: display_name = (service.value("DisplayName").value().replace( ",", ";")) except: display_name = "-No_Display_Name-" try: description = (service.value("Description").value().replace( ",", ";")) except: description = "-No_Description-" try: image_path = (service.value("ImagePath").value().replace(",", ";")) except: image_path = "-No_Image_Path-" try: dll = (service.subkey("Parameters").value( "ServiceDll").value().replace(",", ";")) except: dll = "-No_DLL-" try: start_type = service.value("Start").value() if str(start_type) == "0": start_type = "Start=Boot" if str(start_type) == "1": start_type = "Start=System" if str(start_type) == "2": start_type = "Start=AutoStart" if str(start_type) == "3": start_type = "Start=Manual" if str(start_type) == "4": start_type = "Start=Disabled" except: start_type = "Start=No_Info" try: svc_type = service.value("Type").value() if str(svc_type) == "1": svc_type = "Kernel_driver" if str(svc_type) == "2": svc_type = "File System_Driver" if str(svc_type) == "4": svc_type = "Adapter_Driver" if str(svc_type) == "8": svc_type = "File System_Driver" if str(svc_type) == "16": svc_type = "Own_Process" if str(svc_type) == "32": svc_type = "Share_Process" if str(svc_type) == "256": svc_type = "Interactive" if str(svc_type) == "272": svc_type = "Own_Process" if str(svc_type) == "288": svc_type = "Share_Process" except: svc_type = "-No_Service_Type-" print('%s, %s, %s, %s, %s, %s, %s, %s' % (timestamp, servicename, start_type, svc_type, display_name, image_path, dll, description))
def main(): parser = OptionParser() parser.add_option("-v", "--verbose", dest="verbose", help="verbose log output", default=False) parser.add_option("-l", "--label", dest="label", help="label of the agent", default=None) parser.add_option("--zk-quorum", dest=Constants.ZK_QUORUM, help="Zookeeper Quorum", default=None) parser.add_option("--zk-reg-path", dest=Constants.ZK_REG_PATH, help="Zookeeper Registry Path", default=None) parser.add_option("--debug", dest="debug", help="Agent debug hint", default="") (options, args) = parser.parse_args() if not Constants.AGENT_WORK_ROOT in os.environ and not 'PWD' in os.environ: parser.error("AGENT_WORK_ROOT environment variable or PWD must be set.") if Constants.AGENT_WORK_ROOT in os.environ: options.root_folder = os.environ[Constants.AGENT_WORK_ROOT] else: # some launch environments do not end up setting all environment variables options.root_folder = os.environ['PWD'] if not 'AGENT_LOG_ROOT' in os.environ: parser.error("AGENT_LOG_ROOT environment variable must be set.") options.log_folder = os.environ['AGENT_LOG_ROOT'] all_log_folders = [x.strip() for x in options.log_folder.split(',')] if len(all_log_folders) > 1: options.log_folder = all_log_folders[0] # If there are multiple log folder, separate by comma, pick one if not options.label: parser.error("label is required."); if not IS_WINDOWS: bind_signal_handlers() # Check for configuration file. agentConfig = AgentConfig(options.root_folder, options.log_folder, options.label) update_config_from_file(agentConfig) # update configurations if needed if options.zk_quorum: agentConfig.set(AgentConfig.SERVER_SECTION, Constants.ZK_QUORUM, options.zk_quorum) if options.zk_reg_path: agentConfig.set(AgentConfig.SERVER_SECTION, Constants.ZK_REG_PATH, options.zk_reg_path) if options.debug: agentConfig.set(AgentConfig.AGENT_SECTION, AgentConfig.APP_DBG_CMD, options.debug) logFile = posixpath.join(agentConfig.getResolvedPath(AgentConfig.LOG_DIR), logFileName) setup_logging(options.verbose, logFile) update_log_level(agentConfig, logFile) secDir = posixpath.join(agentConfig.getResolvedPath(AgentConfig.RUN_DIR), "security") logger.info("Security/Keys directory: " + secDir) agentConfig.set(AgentConfig.SECURITY_SECTION, "keysdir", secDir) perform_prestart_checks(agentConfig) ensure_folder_layout(agentConfig) # create security dir if necessary ensure_path_exists(secDir) write_pid() logger.info("Using AGENT_WORK_ROOT = " + options.root_folder) logger.info("Using AGENT_LOG_ROOT = " + options.log_folder) if len(all_log_folders) > 1: logger.info("Selected log folder from available: " + ",".join(all_log_folders)) # Extract the AM hostname and secured port from ZK registry zk_lookup_tries = 0 while zk_lookup_tries < Constants.MAX_AM_CONNECT_RETRIES: registry = Registry(options.zk_quorum, options.zk_reg_path) amHost, amUnsecuredPort, amSecuredPort = registry.readAMHostPort() tryConnect = True if not amHost or not amSecuredPort or not amUnsecuredPort: logger.info("Unable to extract AM host details from ZK, retrying ...") tryConnect = False time.sleep(NetUtil.CONNECT_SERVER_RETRY_INTERVAL_SEC) if tryConnect: if amHost: agentConfig.set(AgentConfig.SERVER_SECTION, "hostname", amHost) if amSecuredPort: agentConfig.set(AgentConfig.SERVER_SECTION, "secured_port", amSecuredPort) if amUnsecuredPort: agentConfig.set(AgentConfig.SERVER_SECTION, "port", amUnsecuredPort) server_url = SERVER_STATUS_URL.format( agentConfig.get(AgentConfig.SERVER_SECTION, 'hostname'), agentConfig.get(AgentConfig.SERVER_SECTION, 'port'), agentConfig.get(AgentConfig.SERVER_SECTION, 'check_path')) print("Connecting to the server at " + server_url + "...") logger.info('Connecting to the server at: ' + server_url) # Wait until server is reachable and continue to query ZK netutil = NetUtil() retries = netutil.try_to_connect(server_url, 3, logger) if retries < 3: break; pass pass zk_lookup_tries += 1 pass # Launch Controller communication global controller controller = Controller(agentConfig) controller.start() try: while controller.is_alive(): controller.join(timeout=1.0) except (KeyboardInterrupt, SystemExit): logger.info("... agent interrupted") pass
def main(): if os.path.basename(sys.argv[0]).lower() != "regrip.py": # Issue #5: allow selecting plugins based on argv[0] plugin_name = os.path.basename(sys.argv[0]) # Allow the symlink to be called reg_pluginname to reduce risk of collision if plugin_name.startswith("reg_"): plugin_name = plugin_name[len("reg_"):] else: plugin_name = None parser = argparse.ArgumentParser( description="Extract information from Windows Registry hives") parser.add_argument( "--system", "-y", help= "Path to the SYSTEM hive. Overrides --root and the REG_SYSTEM environment variable", type=str, default="") parser.add_argument( "--software", "-o", help= "Path to the SOFTWARE hive. Overrides --root and the REG_SOFTWARE environment variable", type=str, default="") parser.add_argument( "--sam", "-a", help= "Path to the SAM hive. Overrides --root and the REG_SAM environment variable", type=str, default="") parser.add_argument( "--ntuser", "-n", help= "Path to the NTUSER.DAT hive. Overrides the REG_NTUSER environment variable", type=str, default="") parser.add_argument( "--usrclass", "-u", help= "Path to the UsrClass.DAT hive. Overrides the REG_USRCLASS environment variable", type=str, default="") parser.add_argument( "--root", "-r", help= "Path to the C: folder. Overrides the REG_ROOT environment variable", type=str, default="") parser.add_argument( "--all-user-hives", help= "Work on all NTUSER.DAT and USRCLASS.DAT hives if required. Requires --root. Overrides --ntuser and --usrclass.", action="store_true") parser.add_argument("--verbose", "-v", help="Be more verbose", action="store_true") parser.add_argument("--bodyfile", "-b", help="Force output in Bodyfile format", action="store_true") parser.add_argument("--list", "-l", help="List available plugins", action="store_true") if not plugin_name: parser.add_argument("plugin_name", help="Name of the plugin to run", type=str) if "--list" in sys.argv or "-l" in sys.argv: list_plugins() return args = parser.parse_args() if not plugin_name: plugin_name = args.plugin_name if args.verbose: l.setLevel("DEBUG") plugin = load_plugin(plugin_name) if type(plugin.__REGHIVE__) == str: hive_names = [plugin.__REGHIVE__] else: hive_names = plugin.__REGHIVE__ for hive_name in hive_names: hive_paths = get_hive_paths(args, hive_name) if not hive_paths: print("[!] Hive not found:", hive_name, file=sys.stderr) continue for hive_path in hive_paths: if hive_path == "-": # Special case: read hive from stdin reg = Registry.Registry(sys.stdin.buffer) else: reg = Registry.Registry(hive_path) p = plugin(reg, l, hive_name, hive_path) results = p.run() if results: if hive_name == "NTUSER.DAT": p.info(f"User: {p.guess_username()}") for result in results: if args.bodyfile: p.display_machine(result) else: p.display_human(result)
def __init__(self, pShip): debug(__name__ + ", __init__") ftb.Ship.Ship.__init__(self, pShip) # TODO: change self.launchers to a Registry self.launchers = Registry()
def hive(): path = os.path.join(os.path.dirname(__file__), "reg_samples", "issue22.hive") return Registry.Registry(path)
def __init__(self, caching=0): self._reg_ag = Registry(StringType) # registry for aggregators self._reg_dag = Registry(StringType) # registry for disaggregators self.cache = {} # map (objId, aggregator) -> (timestamp, result_dict) self._caching = caching self._lock = Lock()
pass for subkey in reg.subkeys(): if debug: print("opening " + reg.path()) getOfflineEntries(subkey) if __name__ == '__main__': if debug: print("Starting RegLister") print("Minsize: " + str(minsize)) if computername: print("Computername: " + computername) if regfile: print("Filename: " + regfile) if regfile: if offline: if (debug or verbose): print("opening registry file " + regfile) try: reg = Registry.Registry(regfile).root() except FileNotFoundError: print("Error opening local registry file " + regfile) print("FileNotFoundError can indicate the file is in use and locked by the system") sys.exit() except: e = sys.exc_info()[0] print("Error opening local registry file " + regfile) print("Error message: " + str(e)) sys.exit() getOfflineEntries(reg) else: #Registry.Registry module was not imported, so offline analysis is not available print("Offline analysis requires the Registry.Registry module, part of python-registry.") print("This may be found at https://github.com/williballenthin/python-registry") print("Only live registry analysis is available without this module.")
def __init__(self, name, cost, modid): self.name = name self.modid = modid self.cost = cost self.Materials = Registry()
def __new__(meta, name, bases, class_dict): cls = type.__new__(meta, name, bases, class_dict) Registry.registerLutFormat(name, cls) return cls
primary_filepath = sys.argv[1] log1_filepath = sys.argv[2] log2_filepath = sys.argv[3] primary = StringIO() with open(primary_filepath, 'rb') as f: primary.write(f.read()) primary.seek(0) log1 = RegistryLog.RegistryLog(primary, log1_filepath) primary.seek(0) log2 = RegistryLog.RegistryLog(primary, log2_filepath) primary.seek(0) reg = Registry.Registry(primary) # Run the tests for the first time print_test_testAAAA_testBBBB(reg) print_test_fdenytsconnections(reg) r = reg._regf.recovery_required() if not (r.recover_header or r.recover_data): print('Recovery not required!') sys.exit(0) if not r.recover_header: print('Current hbins size: ' + str(reg._regf.hbins_size())) print('Header recovery: ' + str(r.recover_header)) print('Data recovery: ' + str(r.recover_data))
def getUsbVolumeName(self): partMgrAndDeviceName = self._getPartmgrAndDeviceSerial() temp_mountData = [] temp_result = [] result = [] output = self.volumeInfo try: for item in self._mountedDevice: temp_mountData.append(item['Value']) except (ValueError, TypeError): return None for a in range(len(temp_mountData)): for b in range(len(temp_mountData)): if temp_mountData[a] == temp_mountData[b] and a != b: temp_result.append("{0}={1}".format( self._mountedDevice[a]['Name'], self._mountedDevice[b]['Name'])) if "FAT" or "NTFS" in output.split(" ")[0]: os.chdir("%s/%s/" % (self.mountDir, output.split(" ")[2])) if os.access("Windows/System32/config/software", os.F_OK | os.R_OK): registry = Registry.Registry( "Windows/System32/config/software") elif os.access("Windows/System32/config/SOFTWARE", os.F_OK | os.R_OK): registry = Registry.Registry( "Windows/System32/config/SOFTWARE") else: logger.warning("Couldn't find SOFTWARE registry file!") return None open1 = registry.open("Microsoft\\Windows Search\\VolumeInfoCache") for item in temp_result: parts = item.split("=") if "DosDevices" in parts[0]: partitionId = parts[0][-2:] guid = parts[1].split("Volume")[1] if "DosDevices" in parts[1]: partitionId = parts[1][-2:] guid = parts[0].split("Volume")[0] try: tempResult = dict() Label = open1.subkey(partitionId).value( "VolumeLabel").value() for parts1 in partMgrAndDeviceName: try: print(parts1['DiskId']) index = parts1['DiskId'].index(guid) except ValueError: logger.critical(guid) continue serial = parts1['serials'][index] for lists in self._lastInserted: if serial in lists['DeviceName']: tempResult['DeviceName'] = lists['DeviceName'] tempResult['Label'] = Label result.append(tempResult) else: continue except Registry.RegistryKeyNotFoundException: continue logger.critical(result) return result
def windowsHandler(self): # For windows case, we read first CurrentVersion info from Registry import Registry reg = Registry.Registry('/mnt/Windows/System32/config/SOFTWARE') # ======== OS SECTION =============================================== cv_dict = {} for entry in reg.open( 'Microsoft\\Windows NT\\CurrentVersion').values(): cv_dict[entry.name()] = entry.value() if 'ProductName' in cv_dict: self.editNodeText('OSNAME', 'Microsoft ' + cv_dict['ProductName']) self.editNodeText('FULL_NAME', 'Microsoft ' + cv_dict['ProductName']) if 'CSDVersion' in cv_dict: self.editNodeText('OSCOMMENTS', cv_dict['CSDVersion']) self.editNodeText('SERVICE_PACK', cv_dict['CSDVersion'], 'OPERATINGSYSTEM') if 'CurrentVersion' in cv_dict and 'CurrentBuild' in cv_dict: self.editNodeText( 'OSVERSION', cv_dict['CurrentVersion'] + '.' + cv_dict['CurrentBuild']) self.editNodeText('KERNEL_VERSION', '6.1.7601') self.editNodeText('KERNEL_NAME', 'MSWin32') self.editNodeText('NAME', 'Windows', 'OPERATINGSYSTEM') self.editNodeText('PUBLISHER', 'Microsoft Corporation', 'OPERATINGSYSTEM') if 'BuildLabEx' in cv_dict and 'amd64' in cv_dict['BuildLabEx']: self.editNodeText('ARCH', '64-bit', 'OPERATINGSYSTEM') else: self.editNodeText('ARCH', '32-bit', 'OPERATINGSYSTEM') # ======== SOFTWARE SECTION ========================================= soft_keys = reg.open( 'Microsoft\\Windows\\CurrentVersion\\Uninstall').subkeys() soft_keys += reg.open( 'Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall' ).subkeys() for key in soft_keys: soft_dict = {} for entry in key.values(): try: soft_dict[entry.name()] = entry.value().encode( 'ascii', 'ignore') except: soft_dict[entry.name()] = entry.value() soft = {} soft['ARCH'] = 'x86_64' soft['FROM'] = 'registry' soft['GUID'] = key.name() if 'HelpLink' in soft_dict: soft['HELPLINK'] = soft_dict['HelpLink'] if 'DisplayName' in soft_dict: soft['NAME'] = soft_dict['DisplayName'] else: continue if 'Publisher' in soft_dict: soft['PUBLISHER'] = soft_dict['Publisher'] if 'UninstallString' in soft_dict: soft['UNINSTALL_STRING'] = soft_dict['UninstallString'] if 'DisplayVersion' in soft_dict: soft['VERSION'] = soft_dict['DisplayVersion'] if 'URLInfoAbout' in soft_dict: soft['URL_INFO_ABOUT'] = soft_dict['URLInfoAbout'] self.addSoftware(soft)
def extractUSB(hiveSystem): reg = Registry.Registry(hiveSystem) usbPath = r"ControlSet001\Enum\USB" try: usbKey = reg.open(usbPath) except Registry.RegistryKeyNotFoundException: print("Couldn't find USB key. Exiting...") usbFinalList = [] for i in usbKey.subkeys(): try: vIDpIDKey = i if vIDpIDKey.name()[0:8] != "ROOT_HUB": device = Usb(len(usbFinalList)) device.setVendorID(vIDpIDKey.name()[4:8]) device.setProductID(vIDpIDKey.name()[13:17]) for j in vIDpIDKey.subkeys(): try: serialNumberKey = j classSubclassProtocol = serialNumberKey.value( "CompatibleIDs").value() classSubclassProtocolSplit = classSubclassProtocol[ 0].split("_") descriptionSplit = serialNumberKey.value( "DeviceDesc").value().split(";") deviceMfgSplit = serialNumberKey.value( "Mfg").value().split(";") device.getSerialNumber().append(serialNumberKey.name()) device.getDescription().append(descriptionSplit[1]) if (len(classSubclassProtocolSplit) >= 3): device.getUsbClass().append( classSubclassProtocolSplit[1][0:2]) device.getUsbSubclass().append( classSubclassProtocolSplit[2][0:2]) device.getUsbProtocol().append( classSubclassProtocolSplit[3][0:2]) else: device.getUsbClass().append('None') device.getUsbSubclass().append('None') device.getUsbProtocol().append('None') if (len(deviceMfgSplit) >= 1): device.getDeviceMfg().append(deviceMfgSplit[1]) else: device.getDeviceMfg().append('None') try: device.getParentIdPrefix().append( serialNumberKey.value( "ParentIdPrefix").value()) except: print( "missingParentIdPrefix exception at (i,j) = (", i, ",", j, ") with serial number key:", device.getSerialNumber()[-1]) device.getParentIdPrefix().append('None') device.getServiceName().append( serialNumberKey.value("Service").value()) device.getCapabilities().append( serialNumberKey.value("Capabilities").value()) properties1Key = serialNumberKey.subkey( "Properties").subkey( "{540b947e-8b40-45bc-a8a2-6a0b894cbda2}") try: properties1_4Key = properties1Key.subkey("0004") device.getDeviceName().append((( properties1_4Key.value("").raw_data()).replace( b'\x00', b'')).decode('utf-8')) except: print("keyDoesNotExsist exception [", properties1Key.path(), "\\0004] \n \t at (i,j) = (", i, ",", j, ") \n \t with serial number key:", device.getSerialNumber()[-1]) device.getDeviceName().append('None') try: properties1_7Key = properties1Key.subkey("0007") device.getDeviceConfigurationId().append((( properties1_7Key.value("").raw_data()).replace( b'\x00', b'')).decode('utf-8')) except: print("keyDoesNotExsist exception [", properties1Key.path(), "\\0007] \n \t at (i,j) = (", i, ",", j, ") \n \t with serial number key:", device.getSerialNumber()[-1]) device.getDeviceConfigurationId().append('None') try: properties1_AKey = properties1Key.subkey("000A") device.getBiosDeviceName().append((( properties1_AKey.value("").raw_data()).replace( b'\x00', b'')).decode('utf-8')) except: print("keyDoesNotExsist exception [", properties1Key.path(), "\\000A] \n \t at (i,j) = (", i, ",", j, ") \n \t with serial number key:", device.getSerialNumber()[-1]) device.getBiosDeviceName().append('None') properties2Key = serialNumberKey.subkey( "Properties").subkey( "{a8b865dd-2e3d-4094-ad97-e593a70c75d6}") try: properties2_2Key = properties2Key.subkey("0002") stringDate = dateFromLittleEndian( properties2_2Key.value("").raw_data()) device.getDrAssemblyDate().append(stringDate) except: print("keyDoesNotExsist exception [", properties2Key.path(), "\\0002] \n \t at (i,j) = (", i, ",", j, ") \n \t with serial number key:", device.getSerialNumber()[-1]) device.getDrAssemblyDate().append('None') try: properties2_3Key = properties2Key.subkey("0003") device.getDrVersion().append((( properties2_3Key.value("").raw_data()).replace( b'\x00', b'')).decode('utf-8')) except: print("keyDoesNotExsist exception [", properties2Key.path(), "\\0003] \n \t at (i,j) = (", i, ",", j, ") \n \t with serial number key:", device.getSerialNumber()[-1]) device.getDrVersion().append('None') try: properties2_4Key = properties2Key.subkey("0004") device.getDrDescription().append((( properties2_4Key.value("").raw_data()).replace( b'\x00', b'')).decode('utf-8')) except: print("keyDoesNotExsist exception [", properties2Key.path(), "\\0004] \n \t at (i,j) = (", i, ",", j, ") \n \t with serial number key:", device.getSerialNumber()[-1]) device.getDrDescription().append('None') try: properties2_5Key = properties2Key.subkey("0005") device.getDrInfPath().append((( properties2_5Key.value("").raw_data()).replace( b'\x00', b'')).decode('utf-8')) except: print("keyDoesNotExsist exception [", properties2Key.path(), "\\0005] \n \t at (i,j) = (", i, ",", j, ") \n \t with serial number key:", device.getSerialNumber()[-1]) device.getDrInfPath().append('None') try: properties2_6Key = properties2Key.subkey("0006") device.getDrInfSection().append((( properties2_6Key.value("").raw_data()).replace( b'\x00', b'')).decode('utf-8')) except: print("keyDoesNotExsist exception [", properties2Key.path(), "\\0006] \n \t at (i,j) = (", i, ",", j, ") \n \t with serial number key:", device.getSerialNumber()[-1]) device.getDrInfSection().append('None') properties3Key = serialNumberKey.subkey( "Properties").subkey( "{83da6326-97a6-4088-9453-a1923f573b29}") try: properties3_64Key = properties3Key.subkey("0064") stringDate = dateFromLittleEndian( properties3_64Key.value("").raw_data()) device.getDeviceInstallDate().append(stringDate) except: print("keyDoesNotExsist exception [", properties3Key.path(), "\\0064] \n \t at (i,j) = (", i, ",", j, ") \n \t with serial number key:", device.getSerialNumber()[-1]) device.getDeviceInstallDate().append('None') try: properties3_65Key = properties3Key.subkey("0065") stringDate = dateFromLittleEndian( properties3_65Key.value("").raw_data()) device.getDeviceFirstInstallDate().append( stringDate) except: print("keyDoesNotExsist exception [", properties3Key.path(), "\\0065] \n \t at (i,j) = (", i, ",", j, ") \n \t with serial number key:", device.getSerialNumber()[-1]) device.getDeviceFirstInstallDate().append('None') try: properties3_66Key = properties3Key.subkey("0066") stringDate = dateFromLittleEndian( properties3_66Key.value("").raw_data()) device.getDeviceLastArrivalDate().append( stringDate) except: print("keyDoesNotExsist exception [", properties3Key.path(), "\\0066] \n \t at (i,j) = (", i, ",", j, ") \n \t with serial number key:", device.getSerialNumber()[-1]) device.getDeviceLastArrivalDate().append('None') try: properties3_67Key = properties3Key.subkey("0067") stringDate = dateFromLittleEndian( properties3_67Key.value("").raw_data()) device.getDeviceLastRemovalDate().append( stringDate) except: print("keyDoesNotExsist exception [", properties3Key.path(), "\\0067] \n \t at (i,j) = (", i, ",", j, ") \n \t with serial number key:", device.getSerialNumber()[-1]) device.getDeviceLastRemovalDate().append('None') except: print("assignment exception at (i,j) = (", i, ",", j, ") with serial number key:", device.getSerialNumber()[-1]) usbFinalList.append(device) except: print("exception at i = ", i) continue return usbFinalList
def __init__(self): self.registry = Registry()
def main(): # Parsing the Arguments parser = argparse.ArgumentParser() parser.add_argument( "-i", "--inputfile", dest="InputFile", help= 'Path to the Amcache Hive file. Syntax of command is Python Windows10_Amcache_Parser.py -i PathToAmcacheFile.hve -o /DirReport' ) parser.add_argument( "-o", "--outputdirectory", dest="OutputDir", help= "Dir path to Export your CSV reports. Syntax of command is Python Windows10_Amcache_Parser.py -i PathToAmcacheFile.hve -o /DirReport/" ) args = parser.parse_args() # Now running the command to extract the Hive file contents try: # Importing the Hive file reg = Registry.Registry(args.InputFile) # Getting the root key topLevel = reg.root() rootKey = topLevel.subkey('Root') ##################################################################### # Getting the list of applications installed # Grabbing the InventoryApplication Key inventoryApplications = rootKey.subkey('InventoryApplication') keyCount = inventoryApplications.subkeys_number() # Now parsing the subkeys from the InventoryApplication InventoryOfApplications = [] for i in range(keyCount): applicationKey = inventoryApplications.subkeys()[i] # Now parsing through all the values on this key numberOfValues = applicationKey.values_number() ApplicationEntry = {} for d in range(numberOfValues): value = applicationKey.values()[d] name = value.name() value = value.value() ApplicationEntry[name] = value # Now adding the timestamp of the program's first execution FirstTimeOfExecution = applicationKey.timestamp() ApplicationEntry[ 'TimeOfFirstExecution'] = FirstTimeOfExecution.isoformat() # Now adding the entry into the inventory of applications InventoryOfApplications.append(ApplicationEntry) ##################################################################### # Getting the list of files executed # InventoryApplicationFile is the key name inventoryApplications = rootKey.subkey('InventoryApplicationFile') keyCount = inventoryApplications.subkeys_number() # Now parsing the subkeys to get their values InventoryOfApplicationFiles = [] for i in range(keyCount): applicationKey = inventoryApplications.subkeys()[i] # Now parsing through all the values on this key numberOfValues = applicationKey.values_number() ApplicationEntry = {} for d in range(numberOfValues): value = applicationKey.values()[d] name = value.name() value = value.value() ApplicationEntry[name] = value # Now adding the timestamp of the program's first execution FirstTimeOfExecution = applicationKey.timestamp() ApplicationEntry[ 'TimeOfFirstExecution'] = FirstTimeOfExecution.isoformat() # Now adding the entry into the inventory of applications InventoryOfApplicationFiles.append(ApplicationEntry) ##################################################################### # Now extracting the lists to a report direcotry Outdir = args.OutputDir # Now exporting the results to several CSVs InventoryOfApplicationsCSV = [] ExportPath = Outdir + 'InventoryOfApplications.csv' Headers = [ 'StoreAppType', 'RegistryKeyPath', 'Source', 'RootDirPath', 'InstallDate', 'OSVersionAtInstallTime', 'MsiProductCode', 'ProgramInstanceId', 'MsiPackageCode', 'ProgramId', 'InboxModernApp', 'Type', 'BundleManifestPath', 'ManifestPath', 'Publisher', 'Language', 'UninstallString', 'Version', 'TimeOfFirstExecution', 'Name', 'PackageFullName', 'HiddenArp' ] InventoryOfApplicationsCSV.append(Headers) for i in InventoryOfApplications: sublist = list(i.values()) InventoryOfApplicationsCSV.append(sublist) # Exporting Report 1 with open(ExportPath, 'w') as f: wr = csv.writer(f, lineterminator='\n') for row in InventoryOfApplicationsCSV: wr.writerow(row) # Now exporting InventoryFile Results InventoryOfApplicationFilesCSV = [] ExportPath = Outdir + 'InventoryOfFiles.csv' Headers = [ 'IsOsComponent', 'Publisher', 'FileId', 'BinaryType', 'LowerCaseLongPath', 'LinkDate', 'Language', 'BinProductVersion', 'Version', 'ProgramId', 'ProductVersion', 'LongPathHash', 'IsPeFile', 'BinFileVersion', 'Name', 'TimeOfFirstExecution', 'Size', 'Usn', 'ProductName' ] InventoryOfApplicationFilesCSV.append(Headers) for i in InventoryOfApplicationFiles: sublist = list(i.values()) InventoryOfApplicationFilesCSV.append(sublist) # Exporting Report 2 with open(ExportPath, 'w') as f: wr = csv.writer(f, lineterminator='\n') for row in InventoryOfApplicationFilesCSV: wr.writerow(row) except: print( 'check your syntax....python /home/sansforensics/Desktop/Windows10_Amcache_Parser.py -i /home/sansforensics/Desktop/Amcache.hve -o /home/sansforensics/Desktop/amcacheTest/' )
def newEntry(self, evt): """ create a new patient""" panel = Registry.get('BIO') panel.addNew()
def answer1(data1): handle = Registry.Registry("/home/student/Public/registry/SOFTWARE") regkey = handle.open("Microsoft\\Windows NT\\CurrentVersion\\Winlogon") reg_value = regkey.value(data1) print(reg_value.value()) return reg_value.value()
def _registryFactory(self, name): from Registry import Registry return Registry(name)
def Parse_Amcache(path): total_files = getTotalFilesStartsWith(path, 'amcache_') print("Amcache Hive Count: {}".format(total_files)) counter = 0 for filename in TraversePath(path): fname = os.path.split(filename)[1] if fname.lower().startswith('amcache_'): #Get hostname from ECAT style Filename hostname = getHostnameFromFilename(fname) #entries = '' if g_debug: print('[+] Parsing file: {}'.format(filename)) try: r = Registry.Registry(filename) except: print('[!] Unable to open as Amcache Hive as Registry : {}'. format(filename)) else: try: ee = amcache.parse_execution_entries(r) except: print('[!] Unable to parse Amcache Hive : {}'.format( filename)) else: entries = [] TimelineEntry = namedtuple("TimelineEntry", ["timestamp", "type", "entry"]) #print ee for e in ee: for t in [ "source_key_timestamp", "created_timestamp", "modified_timestamp", "modified_timestamp2", "linker_timestamp" ]: ts = getattr(e, t) if ts == UNIX_TIMESTAMP_ZERO: continue if ts == WINDOWS_TIMESTAMP_ZERO: continue if ts == datetime.datetime.min: continue #print ts #print e #print type(e) #for i in e: #print i #print e.entry.path #print e.entry.sha1 entries.append(TimelineEntry(ts, t, e)) #print (hostname, ts, e.entry.path, e.entry.sha1) #write_line(hostname, e.timestamp, e.entry.path, e.entry.sha1) #entries.append(ts,e) #w = unicodecsv.writer(sys.stdout, delimiter="|", quotechar="\"",quoting=unicodecsv.QUOTE_MINIMAL, encoding="utf-8") #w.writerow(["timestamp", "timestamp_type", "path", "sha1"]) #for e in sorted(entries, key=lambda e: e.timestamp): #print e #print (hostname, [e.timestamp, e.entry.path, e.entry.sha1]) #line = hostname + e.timestamp, e.type, e.entry.path, e.entry.sha1 # w.writerow([e.timestamp, e.type, e.entry.path, e.entry.sha1]) for e in entries: #('Hostname,Time Stamp,Last Update,File Path,File Size,Shimcache Exec Flag,SHA1 Hash,Data Source\n') ts = e.timestamp #print type(ts) #print ts.strftime("%B %d, %Y") #timestamp = ts.strftime(DATE_ISO) line = "{},{},{},{},{},{},{},{}".format( hostname, ts.strftime(DATE_ISO), "", e.entry.path.replace(',', ''), "", "", e.entry.sha1, "amcache") #line = hostname + ts.strftime(DATE_ISO) + e.entry.path + e.entry.sha1 #if line.count(',') > 7: # temp = line.split(',') # end = line.count(',') # #print(temp[0] + ',' + temp[1] + ',' + temp[2] + ',' + "".join(temp[3:end-4]) + ',' + temp[end-3] + ',' + temp[end-2] + ',' + temp[end-1] + ',' + temp[end]) # line = temp[0] + ',' + temp[1] + ',' + temp[2] + ',' + "".join(temp[3:end-4]) + ',' + temp[end-3] + ',' + temp[end-2] + ',' + temp[end-1] + ',' + temp[end] # #print line write_line(line) counter += 1 print('{:.1%} Complete'.format( float(counter) / float(total_files)))
print "\nExtract Hive files\n" rootVol = os.environ['WINDIR'][:2] exportHIVE(rootVol) hive_file = ['./export/NTUSER.DAT', './export/UsrClass.dat'] shell_path = [ "Local Settings\\Software\\Microsoft\\Windows\\ShellNoRoam", "Local Settings\\Software\\Microsoft\\Windows\\Shell" ] result = [] for hive in hive_file: reg = Registry.Registry(hive) for sp in shell_path: try: shell_key = reg.open(sp) bagmru_key = shell_key.subkey("BagMRU") bags_key = shell_key.subkey("Bags") parse_shellbags(bagmru_key, bags_key, bagmru_key, "", "") except Registry.RegistryKeyNotFoundException: pass except Exception: print "[-] Error during parsing ", sp if os.path.isdir('./result') == False: os.mkdir('./result')
def getUsbStorLastInsteredTime(self): # # Get USB Info in several steps. # 1:get CurrentControlSet\Enum\USBSTOR\{Device Class Name}\{lists of serial number} # 2.get CurrentControlSet\Enum\USB\{VID_PID} and check setp1's serial number and get Device Parameters\SymbolicName 's value # 3.get CurrentControlSet\Control\DeviceClasses\{SymbolicName} and check if VID_PID are correct. # output = self.volumeInfo usb_serials = [ ] # [("Name":"Disk&dgrre","serials":["1234312",“12342134”]),.....] usb_vid_pid = [ ] # [('Name':"VID_0781&PID_5571","4C84654":"\??\USB#VID_0781&PID_5571#4C530012450531101593#{a5dcbf10-6530-11d2-901f-00c04fb951ed}")] final_result = [] try: bias = datetime.timedelta(hours=-self.bias) except TypeError: pass if "FAT" or "NTFS" in output.split(" ")[0]: os.chdir("%s/%s" % (self.mountDir, output.split(" ")[2])) if os.access("Windows/System32/config/system", os.F_OK | os.R_OK): registry = Registry.Registry("Windows/System32/config/system") elif os.access("Windows/System32/config/SYSTEM", os.F_OK | os.R_OK): registry = Registry.Registry("Windows/System32/config/SYSTEM") else: logger.warning("Couldn't find SYSTEM registry file!") return None select_current = registry.open("Select").value("Current").value() open1 = registry.open("ControlSet00%d\\Enum\\USBSTOR" % select_current) for usbstor_item in open1.subkeys(): tempResult = dict() tempResult['Name'] = usbstor_item.name() tempResult['serials'] = [] tempResult['DiskId'] = [] for device_class_name in usbstor_item.subkeys(): tempResult['serials'].append( device_class_name.name().split("&")[0]) tempResult['DiskId'].append( device_class_name.subkey("Device Parameters").subkey( "Partmgr").value("DiskId").value()) usb_serials.append(tempResult) logger.critical(usb_serials) open2 = registry.open("ControlSet00%d\\Enum\\USB" % select_current) for usb_item in open2.subkeys(): tempResult = dict() for temp in usb_serials: temp_serialList = temp['serials'] try: for temp_serial in temp_serialList: usb_item.find_key(temp_serial) tempResult['vid_pid_name'] = usb_item.name() tempResult[temp_serial] = \ usb_item.subkey(temp_serial).subkey("Device Parameters").value("SymbolicName") \ .value().split("#")[-1] except Registry.RegistryKeyNotFoundException: continue usb_vid_pid.append(tempResult) logger.critical(usb_vid_pid) open3 = registry.open("ControlSet00%d\\Control\\DeviceClasses" % select_current) # usb_vid_pid = [] # [('Name':"VID_0781&PID_5571","4C84654":"\??\USB#VID_0781&PID_5571#4C530012450531101593#{a5dcbf10-6530-11d2-901f-00c04fb951ed}")] # try: for usb_vid_pid_item in usb_vid_pid: temp_name_list = [] for a in range(1, len(list(usb_vid_pid_item.values()))): open4 = open3.subkey(list(usb_vid_pid_item.values())[a]) for open4_item in open4.subkeys(): for i in range(1, len(list(usb_vid_pid_item.keys()))): temp_final = dict() temp_name = "##?#USB#" + usb_vid_pid_item[ 'vid_pid_name'] + "#" + list( usb_vid_pid_item.keys())[i] + "#" + list( usb_vid_pid_item.values())[i] if temp_name in temp_name_list: continue temp_name_list.append(temp_name) final = open4.subkey(temp_name) temp_final['DeviceName'] = temp_name temp_final['LastTime'] = ( final.timestamp() + bias).strftime('%Y %m %d - %H:%M:%S') final_result.append(temp_final) # except Registry.RegistryKeyNotFoundException: # pass logger.critical(final_result) return final_result
def __init__(self, parent, ID, name="", style=wx.TAB_TRAVERSAL, registrykey="", size=wx.DefaultSize): wx.Panel.__init__(self, parent, ID, name="", style=style, size=size) if registrykey: Registry.add(registrykey, self)
class Launcher: "A proxy for a ship's subsystem capable of launching an object" # pSystem - The Hull System (targetable and destroyable) component of # our launcher # pProperty - The ObjectEmitterProperty for the launcher def __init__(self, pSystem, pProperty, pShip): # TODO: Ensure compatability with LaunchGroup self.pHullSystem = pSystem self.pOEPProperty = pProperty self.Complement = Registry() self.bClearToLaunch = 1 self.fLaunchInterval = 2.0 self.sLaunchType = None self.pShip = pShip def AddLaunchable( self, \ launchScriptName, \ aiModuleName, \ numberOfLaunch, \ commandable = 1): if (launchScriptName != None and numberOfLaunch >= 0): launchable = Launchable(aiModuleName, numberOfLaunch, commandable) self.Complement.Register(launchable, launchScriptName) def RemoveLaunchable(self, launchScriptName, numberOfLaunch): if launchScriptName != None and \ numberOfLaunch >= 0: for launchType in self.Complement: if launchType == launchScriptName: self.Complement.Remove(launchScriptName) def GetComplement(self): return self.Complement def GetNumLaunches(self, launch): "Returns the number of Launches remaining of the requested type" retval = 0 if (self.Complement._keyList.has_key(launch)): retval = self.Complement.GetName(launch).count return retval def HasMoreLaunches(self, launch): return self.GetNumLaunches(launch) def SetLaunchInterval(self, interval): self.fLaunchInterval = interval def SetClearToLaunch(self, clear): "Sets this Launcher's semaphore to allow a Launch to deply" self.bClearToLaunch = clear def GetLaunchType(self): "Get the current Launch type." if (self.sLaunchType == None): keys = self.Complement._keyList.keys() for type in keys: if (self.Complement.GetName(type) > 0): self.sLaunchType = type return self.sLaunchType def NextLaunchType(self): "Cycle to the next Launch type" retval = None if (self.sLaunchType == None): retval = self.GetLaunchType() else: keys = self.Complement._keyList.keys() startingIdx = keys.index(self.sLaunchType) index = startingIdx while (1): if (len(keys) - 1 == index): index = 0 elif (index < len(keys) - 1): index = index + 1 if (index == startingIdx): # we've cycled the whole dict. we're out of ships break elif (self.Complement[index] > 0): retval = keys[index] self.sLaunchType = retval return retval def LaunchShip(self): return self.LaunchShip(self.sLaunchType) def LaunchShip(self, launch, bTimer=None): "Decrement our count of this type of Launch and then launch an instance of this type of Launch" retval = 0 if self.bClearToLaunch == 1 and \ self.Complement._keyList.has_key( launch) and \ self.Complement.GetName( launch) > 0: self.bClearToLaunch = 0 launchable = self.Complement.GetName(launch) launchCount = launchable.count - 1 if (bTimer == None): bTimer = launchCount self.Complement.Register( Launchable( launchable.aiModuleName, \ launchCount), \ launch) LaunchAIShip( self.pShip, \ self.pOEPProperty, \ self.pHullSystem, \ launch, \ self.fLaunchInterval, \ launchable.aiModuleName, \ launchable.commandable, \ bTimer) retval = 1 return retval def Equals(self, other): retval = 0 if self.GetComplement() == other.GetComplement(): retval = 1 return retval
def run(self): db = Database() # https://github.com/williballenthin/python-registry file_id = self.request.POST['file_id'] key_request = urllib.unquote(self.request.POST['key']) reg_data = db.get_filebyid(file_id) reg = Registry.Registry(reg_data) if key_request == 'root': key = reg.root() else: try: key = reg.open(key_request) except Registry.RegistryKeyNotFoundException: # Check for values key = False if key: # Get the Parent try: parent_path = "\\".join( key.parent().path().strip("\\").split('\\')[1:]) print key.parent().path() except Registry.RegistryKeyHasNoParentException: parent_path = None json_response = {'parent_key': parent_path} # Get Sub Keys child_keys = [] for sub in self.reg_sub_keys(key): sub_path = "\\".join(sub.path().strip("\\").split('\\')[1:]) child_keys.append(sub_path) # Get Values key_values = [] for value in key.values(): val_name = value.name() val_type = value.value_type_str() val_value = value.value() # Replace Unicode Chars try: val_value = val_value.replace('\x00', ' ') except AttributeError: pass # Convert Bin to Hex chars if val_type == 'RegBin' and all(c in string.printable for c in val_value) == False: val_value = val_value.encode('hex') if val_type == 'RegNone' and all(c in string.printable for c in val_value) == False: val_value = val_value.encode('hex') # Assemble and send key_values.append([val_name, val_type, val_value]) # print val_type, val_value json_response['child_keys'] = child_keys json_response['key_values'] = key_values json_response = json.dumps(json_response) self.render_type = 'json' self.render_data = json_response self.render_javascript = open( os.path.join('extensions', self.extra_js), 'rb').read()
def open_file_as_reg(reg_file): file_size = reg_file.info.meta.size file_content = reg_file.read_random(0, file_size) file_like_obj = StringIO.StringIO(file_content) return Registry.Registry(file_like_obj)
class AggregatedStorage(Storage): """ Implementation of the AggregatedStorage proposal as described in http://plone.org/development/teams/developer/AggregatedStorage """ def __init__(self, caching=0): self._reg_ag = Registry(StringType) # registry for aggregators self._reg_dag = Registry(StringType) # registry for disaggregators self.cache = {} # map (objId, aggregator) -> (timestamp, result_dict) self._caching = caching self._lock = Lock() def __getstate__(self): """Override __getstate__ used for copy operations Required to fix the copy problem with the lock """ state = self.__dict__ state['_lock'] = None return state def __setstate__(self, state): """Override __setstate__ used for copy operations Required to fix the copy problem with the lock """ state['_lock'] = Lock() self.__dict__.update(state) def registerAggregator(self, fieldname, methodname): if self._reg_ag.get(fieldname): raise KeyError('Aggregator for field "%s" already registered' % fieldname) self._reg_ag.register(fieldname, methodname) def registerDisaggregator(self, fieldname, methodname): if self._reg_dag.get(fieldname): raise KeyError('Disaggregator for field "%s" already registered' % fieldname) self._reg_dag.register(fieldname, methodname) def get(self, name, instance, **kwargs): methodname = self._reg_ag.get(name) if not methodname: raise KeyError('No aggregator registered for field "%s"' % name) method = getattr(instance, methodname) if not method: raise KeyError('Aggregator "%s" for field "%s" not found' % (methodname, name)) result = method(name, instance, **kwargs) if not isinstance(result, DictType): raise TypeError('Result returned from an aggregator must be DictType') return result[name] if self._caching: cache_entry = self._cache_get(instance.getId(), methodname) else: cache_entry = None if cache_entry is None: method = getattr(instance, methodname) if not method: raise KeyError('Aggregator "%s" for field "%s" not found' % (methodname, name)) result = method(name, instance, **kwargs) if not isinstance(result, DictType): raise TypeError('Result returned from an aggregator must be DictType') if self._caching: self._cache_put(instance.getId(), methodname, result) if not result.has_key(name): raise KeyError('result dictionary returned from "%s"' ' does not contain an key for "%s"' % (methodname, name)) return result[name] else: return cache_entry[name] def set(self, name, instance, value, **kwargs): methodname = self._reg_dag.get(name) if not methodname: raise KeyError('No disaggregator registered for field "%s"' % name) method = getattr(instance, methodname) if not method: raise KeyError('Disaggregator "%s" for field "%s" not found' % (methodname, name)) if self._caching: self._cache_remove(instance.getId(), methodname) method(name, instance, value, **kwargs) def unset(self, name, instance, **kwargs): pass ###################################################################### # A very basic cache implementation to cache the result dictionaries # returned by the aggregators ###################################################################### def _cache_get(self, objId, methodname): """ retrieve the result dictionary for (objId, methodname) """ self._lock.acquire() entry = self.cache.get((objId, methodname)) if entry is None: self._lock.release() return None if time.time() - entry[0] > CACHE_TIMEOUT: del self.cache[(objId, methodname)] self._lock.release() return None self._lock.release() return entry[1] def _cache_put(self, objId, methodname, result): """ store (objId, methodname) : (current_time, result) in cache """ self._lock.acquire() self.cache[(objId, methodname)] = (time.time(), result) self._lock.release() def _cache_remove(self, objId, methodname): """ remove (objId, methodname) from cache """ self._lock.acquire() key = (objId, methodname) if self.cache.has_key(key): del self.cache[key] self._lock.release()
def network_settings(sys_reg, soft_reg): """ Network Settings """ nic_names = [] results_dict = {} nic_list = [] nics_dict = {} int_list = [] registry = Registry.Registry(soft_reg) key = registry.open("Microsoft\\Windows NT\\CurrentVersion\\NetworkCards") print(("=" * 51) + "\n[+] Network Adapters\n" + ("=" * 51)) # Populate the subkeys containing the NICs information for v in key.subkeys(): nic_list.append(v.name()) for nic in nic_list: k = registry.open("Microsoft\\Windows NT\\CurrentVersion\\NetworkCards\\%s" % nic) for v in k.values(): if v.name() == "Description": desc = v.value() nic_names.append(desc) if v.name() == "ServiceName": guid = v.value() nics_dict['Description'] = desc nics_dict['ServiceName'] = guid reg = Registry.Registry(sys_reg) key2 = reg.open("ControlSet00%s\\services\\Tcpip\\Parameters\\Interfaces" % control_set_check(sys_reg)) # Populate the subkeys containing the interfaces GUIDs for v in key2.subkeys(): int_list.append(v.name()) def guid_to_name(g): for k,v in nics_dict.items(): ''' k = ServiceName, Description v = GUID, Adapter name ''' if v == g: return nics_dict['Description'] # Grab the NICs info based on the above list for i in int_list: print("[-] Interface........: %s" % guid_to_name(i)) print("[-] GUID.............: %s" % i) key3 = reg.open("ControlSet00%s\\services\\Tcpip\\Parameters\\Interfaces\\%s" % (control_set_check(sys_reg), i)) for v in key3.values(): if v.name() == "Domain": results_dict['Domain'] = v.value() if v.name() == "IPAddress": # Sometimes the IP would end up in a list here so just doing a little check ip = v.value() results_dict['IPAddress'] = ip[0] if v.name() == "DhcpIPAddress": results_dict['DhcpIPAddress'] = v.value() if v.name() == "DhcpServer": results_dict['DhcpServer'] = v.value() if v.name() == "DhcpSubnetMask": results_dict['DhcpSubnetMask'] = v.value() # Just to avoid key errors and continue to do becuase not all will have these fields if not 'Domain' in results_dict: results_dict['Domain'] = "N/A" if not 'IPAddress' in results_dict: results_dict['IPAddress'] = "N/A" if not 'DhcpIPAddress' in results_dict: results_dict['DhcpIPAddress'] = "N/A" if not 'DhcpServer' in results_dict: results_dict['DhcpServer'] = "N/A" if not 'DhcpSubnetMask' in results_dict: results_dict['DhcpSubnetMask'] = "N/A" print("[-] Domain...........: %s" % results_dict['Domain']) print("[-] IP Address.......: %s" % results_dict['IPAddress']) print("[-] DHCP IP..........: %s" % results_dict['DhcpIPAddress']) print("[-] DHCP Server......: %s" % results_dict['DhcpServer']) print("[-] DHCP Subnet......: %s" % results_dict['DhcpSubnetMask']) print("\n" )
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function from __future__ import unicode_literals import sys from Registry import Registry def usage(): return " USAGE:\n\t%s <Windows Registry file> <Registry key path> <Registry Value>" % sys.argv[ 0] if __name__ == '__main__': if len(sys.argv) != 4: print(usage()) sys.exit(-1) registry = Registry.Registry(sys.argv[1]) key = registry.open(sys.argv[2]) if sys.argv[3] == "default": sys.argv[3] = "(default)" value = key.value(sys.argv[3]) sys.stdout.write(str(value.value()))
def registeredComponentsInCategory(category): global _registry return _registry.types.get(category) or [] def componentfactory(category, type): global _registry return _registry.getFactory(category, type) def componentinfo(category, type): global _registry return _registry.getInfo(category, type) def registercomponent(category, type, factory): global _registry _registry.register(category, type, factory) return from Registry import Registry _registry = Registry() del Registry # version __id__ = "$Id$" # End of file