Monday, September 9, 2024

Laravel with Mongodb

 Laravel version - 11.22.0

Php version - 8.3

Setup

  1. composer create-project laravel/laravel laraproject
  2. sudo pecl install mongodb
  3. Find php.in and modify it.
    1. phpinfo() or php -i will give location of php.ini
    2. Append the file to add at the bottom - extension="mongodb.so"
  4. composer require mongodb/laravel-mongodb
  5. modify the file 'config\database.php' to add the following

    'mongodb' => [
                'driver' => 'mongodb',
                'dsn' => env('DB_URI', 'mongodb://localhost:27017/db_name'),
                'database' => env('DB_DATABASE', 'db_name'),
            ],
  6. Set the default database connection name in config\database.php

    
        

Wednesday, January 13, 2021

Email attachment extraction linux

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
~

Tuesday, May 19, 2020

Extract last Word


#Function to split and parse out last word from a sentence in a cell.
#A1 = "This is the last word"
#Output = "word"

Function Laststr(str As String) As String
    LArray = Split(str, " ")
    lastindex = UBound(LArray)
    Laststr = LArray(lastindex)
End Function

Sunday, September 15, 2019

USB History part 3 [Offline Hive Analysis]


This post is about trying to get USB history information with timestamps from a registry snapshot in an offline state. In such a scenario it is possible to load the SYSTEM hive and parse the data under USBSTOR\..\..\Properties.

HKLM SYSTEM USBSTOR\..\..\Properties is the location in the registry that holds the keys containing USB last insertion and last removal timestamps as "last written time".
I could not figure out how to parse registry hives in PowerShell without loading them in the registry which, would make the "properties" inaccessible.

So I decided to do this in python. Use the first USB post to do this manually.

I have used the Regipy library for this along with Prettytable, lol. Please update the hive path in the script before running.
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()
    

    

And the output is coming soon...

References

https://github.com/mkorman90/regipy

Saturday, September 14, 2019

USB History Part 2 [Live Machine]

Get Last insert date of MSC Type USB Devices

Scope And Usage:

This script runs on a live machine.

On a live machine, without SYSTEM level access this is the maximum USB timestamp data we can fetch. I know we can also get first connect time but that is easy and is not part of this blog post.

It is not possible to get more USB data from USBSTOR properties with nt-authority\system privileges. If you have SYSTEM level privileges use the previous post to retrieve.

the below PowerShell script queries local HKLM hive to get only USB disk data logged under \\SYSTEM\ControlSet001\Enum\USB\. Only pen drives get logged here, so you will not see phone history.

So let us begin.....

The first portion of the script is only to create a function that will allow us to get the last write time of any key in the registry. The complete script can be found at [reference] and I did not create it, I am using it as is.
If you can import modules in powershell you can delete the function and import the script directly as a module.
#use import-module "path the script"

My part of the script is an implementation of the research paper published (reference), to query locations we can touch with god-level access on a live machine to get last connect data of USB devices.

A big shout out to the research team who published the article.
##############################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



References:
https://gallery.technet.microsoft.com/scriptcenter/Get-RegistryKeyLastWriteTim-63f4dd96
https://www.researchgate.net/publication/318514858_USB_Storage_Device_Forensics_for_Windows_10


Digging USB History


Automated tools


First, use any EDR tool if possible to fetch this data.
Second, if possible use USBDeview tool from Nirsoft (they have some amazing collection of tools)

List USB devices plugged in


PowerShell to Get USBstor list.
Get-ItemProperty -Path HKLM:SYSTEM\CurrentControlSet\Enum\USBSTOR\*\* | Select FriendlyName, PSChildName, ContainerID, ClassGUID

Also, fetch Get Mounted Device list. This PowerShell script fetches mounted USB data from the registry:
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
  }
}

Last Insertion\Removal of USB (time)


For all Registry locations Mentioned below get the Last Written time for the registry key. this can be fetched in 2 ways:
1. Manual Approach: export the registry key as a text file using Regedit.
2. Registry Snapshot: use any free tool to create a snapshot of registry and load registry snapshot using Access-data's free registry Viewer.

MSC type Devices


Last Insertion Timestamp from USBSTOR Key [ in Windows 10,  Windows 8]

HKLM\CurrentControlSet\Enum \USBSTOR\Disk&Ven_[VendorName]&Prod_[ProductName] &Rev_1.00\[SerialNo]\Properties\{83da6326-97a6-4088-9453-a 1923f573b29}\0066

Last Removal Timestamp from USBSTOR Key
HKLM\SYSTEM\CurrentControlSet \Enum\USBSTOR\Disk&Ven_[VendorName]&Prod_[Product Name]&Rev_1.00\[SerialNo]\Properties\{83da6326-97a6-4088- 9453-a1923f573b29}\0067

Last insertion time from System Hive under USB Key

HKLM\SYSTEM\CurrentControlSet \Enum\USB\VID_[VendorID]&PID_[ProductID]\[SerialNo]

From Event logs
Location: Microsoft/Windows/ DeviceSetupManager/Admin
EventID: 112
Description: Gives Timestamp of every time USB inserted into the system. It has no device specification information. To correlate this event with a device, ContainerID found from USBSTOR key is used. Here {ID} is ContainerID of device. 

Important Device classes locations for USB 

HKLM\SYSTEM\CurrentControlSet\Control\DeviceClasses, are:
• 53f56307-b6bf-11d0-94f2-00a0c91efb8b
• 53f5630d-b6bf-11d0-94f2-00a0c91efb8b 

MTP and PTP type Devices


Last Insertion Timestamp from USB Key [Windows 10, Windows 8]
HKLM\SYSTEM\CurrentControlSet\Enum\USBSTOR\VID_[VendorID]&PID_[ProductID]\[SerialNo]\Properties\{83da6326-97a6-4088-9453 a1923f573b29}\0066.

 Last Removal Timestamp from USB Key

 HKLM\SYSTEM\CurrentControlSet\Enum\USBSTOR\VID_[VendorID]&PID_[ProductID]\[SerialNo]\Properties\{83da6326-97a6-4088-9453 a1923f573b29}\0067

From Event Logs

Location: Microsoft\Windows\ WPDMTPClassDriver\Operational
EventID: 1000, 1001, 1003
Description: Last insertion timestamp of MTP- and PTP-enabled USB devices. It does not have an identification feature of a device. To chain events, we need to link Execution ProcessID and ThreadID

Location: Microsoft\Windows\ WPDMTPClassDriver\Operational
Event ID:1002
Description: Operational Last removal timestamp of MTP- and PTP-enabled USB devices. It does not have an identification feature of a device. To chain events, we need to link Execution ProcessID and ThreadID.

References

https://www.researchgate.net/publication/318514858_USB_Storage_Device_Forensics_for_Windows_10
https://www.forensicswiki.org/wiki/USB

Installed Software Powershell

First the easy ways, but it might give all of the installed software.
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.

HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\ HKLM:\SOFTWARE\Wow6432node\Microsoft\Windows\CurrentVersion\Uninstall\
HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ 
Below mentioned are Powershell commands to retrieve installed software. Please run one at a time:
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

Thursday, September 12, 2019

Startup, Logon And Run as Admin Powershell

Get system start and stop information.

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}

1074 is Logged when an app (ex: Windows Update) causes the system to restart, or when a user initiates a restart or shutdown.
6006 is Logged as a clean shutdown. It gives the message "The Event log service was stopped.
6005 when the system was last turned on. It gives the message "The Event log service was started."
6008 unexpected shutdown


Account Logon Logoff info [fetch account info locally from registry] 

$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

event id 7001 is Logon, event id 7002 is Logoff (default username is not trusted hence, ReplacementStrings is used to get actual user SID, then map it to registry to get logon name.)

Time restrictions

get-eventlog system -source Microsoft-Windows-Winlogon -After (Get-Date).AddDays(-7);


Run as administrator Event History [Windows 10]

Event ID - 4776

Message: The computer attempted to validate the credentials for an account.
Logon Account: administrator

Event ID - 4648 [also use XML view]
Message: A logon was attempted using explicit credentials.
Keywords: Audit Success
Account Whose Credentials Were Used:
Account Name: Administrator
Process Information:
Process Name: C:\Windows\System32\consent.exe
Network Information:
Network Address: ::1


Event ID - 4624 [also use XML view]
Message: 
An account was successfully logged on.
Logon Information:

Logon Type: 2
New Logon:
Security ID: Hostname\Administrator
Account Name: Administrator      XML,[TargetUserName]

Process Information:
Process ID: 0x2f00
Process Name: C:\Windows\System32\consent.exe XML [ProcessName]


Event ID - 4798 [also use XML view]
Message: 
A user's local group membership was enumerated.
Subject:
Security ID: Domain\user_requesting_run_as_admin
Account Name: user_requesting_run_as_admin
Account Domain: Domain

User:
Security ID: hostname\Administrator
Account Name: Administrator

Process Information:
Process Name: C:\Windows\explorer.exe

Script to get 4624 logon event as 'administrator', ensure service is consent.exe. The script is taken from the blog post below in references
 $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

The script below is to check who enumerated 'administrator' account and when using which process. This is user enumeration, not authentication.
Looks for data in last 24 hours and where user != hostname$
$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


Reference


https://www.codetwo.com/admins-blog/how-to-check-event-logs-with-powershell-get-eventlog/ 
https://blogs.technet.microsoft.com/ashleymcglone/2013/08/28/powershell-get-winevent-xml-madness-getting-details-from-event-logs/

Thursday, August 15, 2019

Linux Bypasses

#How to read a file without cat or string in Linux?

1. fold [filename]
2. tar c [filename/directory]
3. iconv [filename]
4. shuf [filename]
5. lzop -v -c [filename]
6. more, less, head, tail
7.python, Perl

#Execute files which might be restricted


1. setpriv --nnp [executable]
2. install [../executable] /tmp
2.a run-parts tmp [free of all other binaries]
3. /lib/ld-linux.so [1-2] [FULL PATH of executable]
The binary does not need to "chmod +x", mean you can chmod executable again if needed

#Scan for executable containing functions


1. scanelf
1.a scanelf -s chmod -R / (looks for executable containing chmod from "/" recursively)


Friday, August 9, 2019