If the email is a msg file:
sudo apt install ripmime ripmime -i email.eml |
If the email is an eml file:
sudo apt install mpack munpack sample.eml |
sudo apt install ripmime ripmime -i email.eml |
sudo apt install mpack munpack sample.eml |
from datetime import datetime, timedelta
from regipy.registry import RegistryHive #pip install regipy
from prettytable import PrettyTable #pip install PrettyTable
WIN32_EPOCH = datetime(1601, 1, 1)
def dt_from_win32_ts(timestamp):
return WIN32_EPOCH + timedelta(microseconds=timestamp // 10)
#upadate location of offline saved hive
reg = RegistryHive ('C:\\path\\to\\hive')
def get_disk_id():
diskid=[]
for disk_id in reg.get_key('SYSTEM\\ControlSet001\\Enum\\USBSTOR').iter_subkeys():
diskid.append(disk_id.name)
return diskid
def get_serial_id(diskid):
serialid=[]
for ser in reg.get_key('SYSTEM\\ControlSet001\\Enum\\USBSTOR\\'+diskid).iter_subkeys():
serialid.append(ser.name)
return serialid
def get_last_insert_id(diskid,serialid):
last_inser_time=''
for ser in reg.get_key('SYSTEM\\ControlSet001\\Enum\\USBSTOR\\'+diskid+'\\'+serialid+"\\Properties\\{83da6326-97a6-4088-9453-a1923f573b29}").iter_subkeys():
if ('0066' in ser.name):
ts=ser.header.last_modified
dt = dt_from_win32_ts(ts)
utc_time =dt.strftime('%Y-%m-%dT%H:%M:%S.%f')
last_inser_time= utc_time
return last_inser_time
def get_last_removal_id(diskid,serialid):
last_remove_time=''
for ser in reg.get_key('SYSTEM\\ControlSet001\\Enum\\USBSTOR\\'+diskid+'\\'+serialid+"\\Properties\\{83da6326-97a6-4088-9453-a1923f573b29}").iter_subkeys():
if ('0067' in ser.name):
ts=ser.header.last_modified
dt = dt_from_win32_ts(ts)
utc_time =dt.strftime('%Y-%m-%dT%H:%M:%S.%f')
last_remove_time= utc_time
return last_remove_time
def get_first_insert_id(diskid,serialid):
first_insert_time=''
for ser in reg.get_key('SYSTEM\\ControlSet001\\Enum\\USBSTOR\\'+diskid+'\\'+serialid+"\\Properties\\{83da6326-97a6-4088-9453-a1923f573b29}").iter_subkeys():
if ('0003' in ser.name):
ts=ser.header.last_modified
dt = dt_from_win32_ts(ts)
utc_time =dt.strftime('%Y-%m-%dT%H:%M:%S.%f')
first_insert_time= utc_time
return first_insert_time
def get_easy_name(diskid,serialid):
easy_name=''
t= (reg.get_key('SYSTEM\\ControlSet001\\Enum\\USBSTOR\\'+diskid+'\\'+serialid).get_values(as_json=True))
for jt in t:
if ("FriendlyName" in jt.name):
easy_name= jt.value
return easy_name
def get_usb_history():
x = PrettyTable()
x.field_names = ['easy_name', 'SerialID','Last_Insert_Time','Last_Remove_Time','First_insert_time','InstanceID']
for diskid in get_disk_id():
for serialid in get_serial_id(diskid):
lit=get_last_insert_id(diskid,serialid) #last insert time of usb in utc
lrt=get_last_removal_id(diskid,serialid) #last removal time of usb in utc
fit=get_first_insert_id(diskid,serialid) #first insert time of usb in utc
easy_name=get_easy_name(diskid,serialid)
x.add_row([easy_name,serialid.rsplit("&",1)[0],lit,lrt,fit,diskid])
print(x)
get_usb_history()
##############################Part 1 ######################################
#Output of script in: C:\Windows\temp\usbdata.csv
#source: https://gallery.technet.microsoft.com/scriptcenter/Get-RegistryKeyLastWriteTim-63f4dd96
Function Get-RegistryKeyTimestamp {
<#
.SYNOPSIS
Retrieves the registry key timestamp from a local or remote system.
.DESCRIPTION
Retrieves the registry key timestamp from a local or remote system.
.PARAMETER RegistryKey
Registry key object that can be passed into function.
.PARAMETER SubKey
The subkey path to view timestamp.
.PARAMETER RegistryHive
The registry hive that you will connect to.
Accepted Values:
ClassesRoot
CurrentUser
LocalMachine
Users
PerformanceData
CurrentConfig
DynData
.NOTES
Name: Get-RegistryKeyTimestamp
Author: Boe Prox
Version History:
1.0 -- Boe Prox 17 Dec 2014
-Initial Build
.EXAMPLE
$RegistryKey = Get-Item "HKLM:\System\CurrentControlSet\Control\Lsa"
$RegistryKey | Get-RegistryKeyTimestamp | Format-List
FullName : HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa
Name : Lsa
LastWriteTime : 12/16/2014 10:16:35 PM
Description
-----------
Displays the lastwritetime timestamp for the Lsa registry key.
.EXAMPLE
Get-RegistryKeyTimestamp -Computername Server1 -RegistryHive LocalMachine -SubKey 'System\CurrentControlSet\Control\Lsa' |
Format-List
FullName : HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa
Name : Lsa
LastWriteTime : 12/17/2014 6:46:08 AM
Description
-----------
Displays the lastwritetime timestamp for the Lsa registry key of the remote system.
.INPUTS
System.String
Microsoft.Win32.RegistryKey
.OUTPUTS
Microsoft.Registry.Timestamp
#>
[OutputType('Microsoft.Registry.Timestamp')]
[cmdletbinding(
DefaultParameterSetName = 'ByValue'
)]
Param (
[parameter(ValueFromPipeline=$True, ParameterSetName='ByValue')]
[Microsoft.Win32.RegistryKey]$RegistryKey,
[parameter(ParameterSetName='ByPath')]
[string]$SubKey,
[parameter(ParameterSetName='ByPath')]
[Microsoft.Win32.RegistryHive]$RegistryHive,
[parameter(ParameterSetName='ByPath')]
[string]$Computername
)
Begin {
#region Create Win32 API Object
Try {
[void][advapi32]
} Catch {
#region Module Builder
$Domain = [AppDomain]::CurrentDomain
$DynAssembly = New-Object System.Reflection.AssemblyName('RegAssembly')
$AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run) # Only run in memory
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('RegistryTimeStampModule', $False)
#endregion Module Builder
#region DllImport
$TypeBuilder = $ModuleBuilder.DefineType('advapi32', 'Public, Class')
#region RegQueryInfoKey Method
$PInvokeMethod = $TypeBuilder.DefineMethod(
'RegQueryInfoKey', #Method Name
[Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
[IntPtr], #Method Return Type
[Type[]] @(
[Microsoft.Win32.SafeHandles.SafeRegistryHandle], #Registry Handle
[System.Text.StringBuilder], #Class Name
[UInt32 ].MakeByRefType(), #Class Length
[UInt32], #Reserved
[UInt32 ].MakeByRefType(), #Subkey Count
[UInt32 ].MakeByRefType(), #Max Subkey Name Length
[UInt32 ].MakeByRefType(), #Max Class Length
[UInt32 ].MakeByRefType(), #Value Count
[UInt32 ].MakeByRefType(), #Max Value Name Length
[UInt32 ].MakeByRefType(), #Max Value Name Length
[UInt32 ].MakeByRefType(), #Security Descriptor Size
[long].MakeByRefType() #LastWriteTime
) #Method Parameters
)
$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
[Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
[Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
)
$FieldValueArray = [Object[]] @(
'RegQueryInfoKey', #CASE SENSITIVE!!
$True
)
$SetLastErrorCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
$DllImportConstructor,
@('advapi32.dll'),
$FieldArray,
$FieldValueArray
)
$PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
#endregion RegQueryInfoKey Method
[void]$TypeBuilder.CreateType()
#endregion DllImport
}
#endregion Create Win32 API object
}
Process {
#region Constant Variables
$ClassLength = 255
[long]$TimeStamp = $null
#endregion Constant Variables
#region Registry Key Data
If ($PSCmdlet.ParameterSetName -eq 'ByPath') {
#Get registry key data
$RegistryKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($RegistryHive, $Computername).OpenSubKey($SubKey)
If ($RegistryKey -isnot [Microsoft.Win32.RegistryKey]) {
Throw "Cannot open or locate $SubKey on $Computername"
}
}
$ClassName = New-Object System.Text.StringBuilder $RegistryKey.Name
$RegistryHandle = $RegistryKey.Handle
#endregion Registry Key Data
#region Retrieve timestamp
$Return = [advapi32]::RegQueryInfoKey(
$RegistryHandle,
$ClassName,
[ref]$ClassLength,
$Null,
[ref]$Null,
[ref]$Null,
[ref]$Null,
[ref]$Null,
[ref]$Null,
[ref]$Null,
[ref]$Null,
[ref]$TimeStamp
)
Switch ($Return) {
0 {
#Convert High/Low date to DateTime Object
$LastWriteTime = (Get-Date $TimeStamp).AddYears(1600)
#Return object
$Object = [pscustomobject]@{
FullName = $RegistryKey.Name
Name = $RegistryKey.Name -replace '.*\\(.*)','$1'
LastWriteTime = $LastWriteTime
}
#$Object.pstypenames.insert(0,'Microsoft.Registry.Timestamp')
$Object
}
122 {
Throw "ERROR_INSUFFICIENT_BUFFER (0x7a)"
}
Default {
Throw "Error ($return) occurred"
}
}
#endregion Retrieve timestamp
}
}
#####################################Part 2#####################################
$usbstor =Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Enum\USBSTOR\*\*' # get all usb serial id foldername from usbstor, eg, 061719-24143&0
function list_msc_devices{
$usbstor =Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Enum\USBSTOR\*\*'
$output=@()
foreach ($x in $usbstor){
$instance_name=$x.PSParentPath.Split("\")[-1]
$serial=''
if($x.PSChildName -match '&0$'){
$serial=$x.PSChildName.Substring(0,$x.PSChildName.Length-2)} # this is the usb serial ID
else {$serial=$x.PSChildName}
$friendlyname=$x.FriendlyName
$output += New-Object -TypeName psobject -Property @{Name=$friendlyname;Serial=$serial;instance=$instance_name}
}
return $output
}
#SYSTEM\CurrentControlSet\Enum\USB\VID_090C&PID_1000\061719-24143
#Get-RegistryKeyTimestamp -RegistryHive LocalMachine -SubKey $subkey_last
function add_Last_in{
$lastin=@()
$output=list_msc_devices
$serial = list_msc_devices | select -Property Serial
foreach($o in $output){
$ss= $o.Serial.tostring()
$path='HKLM:\SYSTEM\ControlSet001\Enum\USB\*\'+ $ss #find usb serial ID under "USB" not (USBstor)
$u=Get-ItemProperty -Path $path #fetch path to grab enclosing folder name
foreach($usbpath in $u)
{
$path =$usbpath.PSPath.Split(":")[2]
if ($path -ne $null)
{
$instanceid=$path.Split("\")[-2] #this is the instanceid, also the folder name under which lies serial id,eg VID_0781&PID_5567
$subkey_last="SYSTEM\ControlSet001\Enum\USB\"+$instanceid+"\" +$ss
$last_time=Get-RegistryKeyTimestamp -RegistryHive LocalMachine -SubKey $subkey_last
#$last_time.LastWriteTime.ToString()
$o | Add-Member -MemberType NoteProperty "Last_In" -Value $last_time.LastWriteTime.ToString()
$lastin+=$o
}
}
}
return $lastin
}
#ControlSet001\Control\DeviceClasses\{53f56307-b6bf-11d0-94f2-00a0c91efb8b}\##?#USBSTOR#Instance_name#Serial_ID&0#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}
function add_First_in{
$first_in=@()
$inputobject=add_Last_in
foreach ($row in $inputobject)
{
$keypath='SYSTEM\ControlSet001\Control\DeviceClasses\{53f56307-b6bf-11d0-94f2-00a0c91efb8b}\##?#USBSTOR#'+$row.instance+"#"+$row.Serial +"&0#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}"
$last_time=(Get-RegistryKeyTimestamp -RegistryHive LocalMachine -SubKey $keypath.ToString()).LastWriteTime.ToString()
$row | Add-Member -MemberType NoteProperty "First_In" -Value $last_time
$first_in+=$row
}
return $first_in
}
Function get_msc_usb{
$usb=add_First_in
$usb | select -Property Name,First_In,Last_In,Serial | Export-Csv "C:\Windows\Temp\usbdata.csv"
}
get_msc_usb
Get-ItemProperty -Path HKLM:SYSTEM\CurrentControlSet\Enum\USBSTOR\*\* | Select FriendlyName, PSChildName, ContainerID, ClassGUID
Write-Output "Data from mounted devides at HKLM:\SYSTEM\MountedDevices\"
Write-Output "Good Only at parsing USB device data there, Other data might not get parsed properly "
$RegKey=(Get-ItemProperty -Path "HKLM:\SYSTEM\MountedDevices\")
$RegKey.PSObject.Properties | ForEach-Object {
If($_.Name -like '\*'){
$out = new-object psobject
$val=[System.Text.Encoding]::Unicode.GetString($_.Value)
If($val -match "&"){
$serial =$val.Split("#")[2]
$Type=$val.Split("&")[0].Split("#")[1]
$vendor= $val.Split("&")[1].Split("_")[1]
$prod=$val.Split("&")[2].Substring($val.Split("&")[2].IndexOf("_")+1)
$out | add-member noteproperty Serial $serial
$out | add-member noteproperty Type $Type
$out | add-member noteproperty vendor $vendor
$out | add-member noteproperty Product $prod
write-output $out}
}
}
Raw results for the above script.$RegKey=(Get-ItemProperty -Path "HKLM:\SYSTEM\MountedDevices\")
$RegKey.PSObject.Properties | ForEach-Object {
If($_.Name -like '\*'){
$val=[System.Text.Encoding]::Unicode.GetString($_.Value)
Write-output $_.Name '=' $val
}
}
Get-WmiObject -Class Win32_Product | Select-Object Name, Version, Vendor, InstallDate,IdentifyingNumber |Format-Table -AutoSize
Get-WmiObject Win32Reg_AddRemovePrograms | Select-Object DisplayName, Version, Publisher, InstallDate |Format-Table -AutoSize
Now we turn to the registry where installed software information is stored but in parts in various locations. hence we need to look at 3 locations to get the complete picture.Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*'| Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |Format-Table -AutoSize
Get-ItemProperty "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |Format-Table -AutoSize
Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*" | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |Format-Table -AutoSize
get-eventlog -logname system | where-object {$_.eventid -eq 6005 -or $_.eventid -eq 6006 -or $_.eventid -eq 1074 -or $_.eventid -eq 1076 -or $_.eventid -eq 6008}
$logs = get-eventlog system -source Microsoft-Windows-Winlogon
$res = @()
ForEach ($log in $logs) {
if($log.instanceid -eq 7001)
{$type = "Logon"}
Elseif ($log.instanceid -eq 7002){$type="Logoff"}
Else {Continue}
$res += New-Object PSObject -Property @{Time = $log.TimeWritten; "Event" = $type; User =(gp "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$($(New-Object System.Security.Principal.SecurityIdentifier $Log.ReplacementStrings[1]))")."ProfileImagePath".split("\")[-1]}
}
$res | Select-Object -Property Time,Event,User
$Events = Get-WinEvent -LogName Security -FilterXPath "*[System[EventID=4624] and EventData[Data[@Name='TargetUserName'] and Data = 'administrator']]"
Get-TimeZone | select Standardname
# Parse out the event message data
ForEach ($Event in $Events) {
# Convert the event to XML
$eventXML = [xml]$Event.ToXml()
# Iterate through each one of the XML message properties
For ($i=0; $i -lt $eventXML.Event.EventData.Data.Count; $i++) {
# Append these as object properties
Add-Member -InputObject $Event -MemberType NoteProperty -Force -Name $eventXML.Event.EventData.Data[$i].name -Value $eventXML.Event.EventData.Data[$i].'#text'
}
}
# View the results with your favorite output method
#$Events | Select-Object * | Out-GridView
$Events| Select-Object -Property TimeCreated,Targetusername,logontype,processname | Format-Table
$Events = Get-WinEvent -LogName Security -FilterXPath "*[System[EventID=4798 and TimeCreated[timediff(@SystemTime) <= 86400000]] and EventData[Data[@Name='SubjectUserName'] != '$(hostname)$'] and EventData[Data[@Name='TargetUserName'] and Data = 'administrator']]"
Get-TimeZone | select Standardname
# Parse out the event message data
ForEach ($Event in $Events) {
# Convert the event to XML
$eventXML = [xml]$Event.ToXml()
# Iterate through each one of the XML message properties
For ($i=0; $i -lt $eventXML.Event.EventData.Data.Count; $i++) {
# Append these as object properties
#$eventXML.Event.EventData.Data[$i].name
#$eventXML.Event.EventData.Data[$i].'#text'
Add-Member -InputObject $Event -MemberType NoteProperty -Force -Name $eventXML.Event.EventData.Data[$i].name -Value $eventXML.Event.EventData.Data[$i].'#text'
}
}
# View the results with your favorite output method
#$Events | Select-Object * | Out-GridView
$Events| Select-Object -Property TimeCreated,Targetusername,SubjectUserName,callerprocessname,keywordsdisplaynames | Format-Table