1

I'm trying to get a session cookie using PowerShell and InternetExplorer.Application but nothing seems to work.

There is no $ie.Document.cookie variable. The session cookie is not available to JavaScript(because it is http-only)

# Create an ie com object
$ie = New-Object -ComObject "InternetExplorer.Application" 
$ie.visible = $true; 
$ie.navigate2("https://www.example.com/login");
# Wait for the page to load 
while ($ie.Busy -eq $true) { Start-Sleep -Milliseconds 1000; }
#Add login details 
$ie.Document.getElementById("username").value = "user"; 
$ie.Document.getElementById("password").value = "1234";
$ie.Document.getElementsByName("login_button")[0].Click();
while($ie.Busy -eq $true) { Start-Sleep -Milliseconds 1000; }
$div = $ie.Document.getElementsByTagName('div')[0];
$ie.navigate("javascript: window.location=document.cookie.match(new RegExp('(^| )csrf_token=([^;]+)'))[2]");
while($ie.Busy -eq $true) { Start-Sleep -Milliseconds 1000; }
$csrf = $ie.LocationUrl.Substring(32);
echo $csrf;
#Stop-Process -Name iexplore
$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession

$cookie = New-Object System.Net.Cookie     
$cookie.Name = "user_name"
$cookie.Value = "user"
$cookie.Domain = "www.example.com"
$session.Cookies.Add($cookie);

$cookie = New-Object System.Net.Cookie     
$cookie.Name = "user_session_id"
$cookie.Value = "What I need"
$cookie.Domain = "www.example.com"
$session.Cookies.Add($cookie);

Invoke-WebRequest -URI "https://www.example.com/demo/my_file&csrf_token=$csrf" -WebSession $session -OutFile 'finally.zip';
echo 'Done!';

Note that the only way I found to get the csrf is to use javascript to get the value to the url, but I can't do it with the user_session_id because it is marked as http_only.

ShadowBeast
  • 97
  • 1
  • 1
  • 6

1 Answers1

4

Take a look at these options to incorporate into what you already have.

First, get the cookies

$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession

Get-Content .\cookie.txt | 
foreach {
$line = $_ -split '/' | select -First 1

$tokens=$line.Split("`t").TrimEnd()

    $c = @{
        name=$tokens[0]
        value=$tokens[1]
        domain=$tokens[2]
    }

    $cookie = New-Object System.Net.Cookie
    $cookie.Name=$c.name
    $cookie.Value=$c.Value
    $cookie.Domain=$c.domain

    $session.Cookies.Add($cookie)
}

Getting Cookies using PowerShell

Here are two straightforward ways to get website cookies within PowerShell.

$url = "https://www.linkedin.com" 
$webrequest = Invoke-WebRequest -Uri $url -SessionVariable websession 
$cookies = $websession.Cookies.GetCookies($url) 


# Here, you can output all of $cookies, or you can go through them one by one. 

foreach ($cookie in $cookies) { 
     # You can get cookie specifics, or just use $cookie 
     # This gets each cookie's name and value 
     Write-Host "$($cookie.name) = $($cookie.value)" 
}
postanote
  • 12,933
  • 2
  • 10
  • 19