Access web using Powershell and Proxy - proxy

I can't seem to get access to a webpage using Powershell. I keep getting a "(407) Proxy Authentication Required". I've tried many things. I don't know what the proxy is or what kind of authentication it requires. The only thing I have access to is in IE it uses a script for configuring. I tried using some IPs from that, but no luck. Any ideas?
Here is one example of what I tried:
$wc = New-Object System.Net.WebClient
$wc.Headers.Add("User-Agent","Mozilla/4.0+")
$wc.Proxy = [System.Net.WebRequest]::DefaultWebProxy
$wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$wc.DownloadString("http://stackoverflow.com")

I had a similar issue and resolved it with just two lines of powershell:
$browser = New-Object System.Net.WebClient
$browser.Proxy.Credentials =[System.Net.CredentialCache]::DefaultNetworkCredentials

I haven't seen anyone doing something like this but there is a way to do this as a "global setting" in your Powershell script (I remember doing this in C# before for local dev builds).
[System.Net.WebRequest]::DefaultWebProxy = [System.Net.WebRequest]::GetSystemWebProxy()
[System.Net.WebRequest]::DefaultWebProxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
This way if you don't want to update all your WebClients with proxy details, you can just override the global setting (have to be done every time you run the script).
But this assumes that the current logged in Windows user is valid for the system-defined proxy server.
NOTE: I would say that this is only useful as a quick and dirty way to get a PS script working that wasn't proxy aware before (like Cake build).

If the proxy answers "407", "proxy authentication required", then the authentication is required:
$Username="Hugo"
$Password="abcdefgh"
$WebProxy = New-Object System.Net.WebProxy("http://webproxy:8080",$true)
$url="http://aaa.bbb.ccc.ddd/rss.xml"
$WebClient = New-Object net.webclient
$WebClient.Proxy=$webproxy
$WebClient.proxy.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
$path="C:\Users\hugo\xml\test.xml"
$WebClient.DownloadFile($url, $path)
Content now resides in "test.xml"

I know the question is specifically about Powershell 2.0, but I would like to share information on setting up a proxy server in Powershell Core (6+) because it's extremely hard to find elsewhere.
I agree with Dandré, that the best solution is to configure the default proxy server. I just had an issue with Powershell Core (7.1). I was trying exactly what Dandré suggests, but it didn't have any effect. After several hours of research and investigation, I have found out that Powershell Core is probably not using System.Net.WebRequest to make web requests anymore, but rather System.Net.Nett.HttpClient.
When I have configured the HttpClient's default proxy server, all web connections made by Powershell (Invoke-WebRequest, PowerShellGet's Find-Module, Install-Module, etc.) finally started to work.
Configure Default Proxy Server for Powershell Core
If you need to make the configuration permanent, just add the commands below to your Powershell profile.
Configure a specific default proxy server
[System.Net.Http.HttpClient]::DefaultProxy = New-Object System.Net.WebProxy('http://your-proxy')
If you need to set a specific port, add it to the proxy server URI: http://proxy:1234.
Configure credentials for authenticating proxy
In case it's an authenticating proxy, you need to set up the credentials to be used for proxy authentication. Use the following command to set the credentials of your domain account under which you're currently logged in to Windows:
[System.Net.Http.HttpClient]::DefaultProxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
If you need different credentials, you can use the Get-Credential cmdlet, but it's interactive so it's not an ideal solution to have in your Powershell profile. But I'm sure there're other ways.
[System.Net.Http.HttpClient]::DefaultProxy.Credentials = Get-Credential
Configure proxy server bypassing
If you just need to bypass the proxy server and use the direct connection, but Powershell is using the default system-wide proxy server, simply set the HttpClient's default proxy to null:
[System.Net.Http.HttpClient]::DefaultProxy = New-Object System.Net.WebProxy($null)
Add Proxy Configuration to Powershell Profile
To make the configuration permanent, simply add the commands you need to your Powershell profile. There're four of them (All users, all hosts; All users, current host; Current user, all hosts; Current user, current host), but I would use the "Current user, all hosts". To find out the location of a specific profile, use the $Profile variable with a profile name:
$Profile.CurrentUserAllHosts
It should print the path $Home\Documents\Powershell\profile.ps1.
If the profile doesn't exist yet, just create it and put the configuration there. It will be executed every time you execute a new Powershell Core (pwsh.exe) instance.
Configure Default Proxy using Environment Variable
An alternative solution is to use an environment variable. According to the documentation, HttpClient is actually using the following variables to initialize the default proxy if they're defined:
HTTP_PROXY for HTTP requests
HTTPS_PROXY for HTTPS requests
ALL_PROXY for both HTTP and HTTPS
NO_PROXY may contain a comma-separated list of hostnames excluded from proxying
An example usage:
ALL_PROXY='http://proxy:1234'
And if you need to pass credentials:
ALL_PROXY='http://username:password#proxy:1234'
This solution is supported by a wider range of applications, so if it's better or worse than the previous solution depends on what exactly you want to configure, just Powershell or also other applications.

If you use the following you'll receive a prompt to enter your credentials:
$client.Credentials = Get-Credential

I solved this with just three lines:
$proxy='http://username:password#IP:PORT'
$ENV:HTTP_PROXY=$proxy
$ENV:HTTPS_PROXY=$proxy

If you know the script - just download it, open with Notepad and find IP and port of your proxy server. As for authentication - most probably your windows credentials are used, so in theory you should be able to keep it empty, unless there's something suspicious in the script.

try adding cache credentials....
$domain = 'ChDom'
$Client = new-object System.Net.WebClient
$cc = New-object System.Net.CredentialCache
$urlObj = New-object System.Uri($url)
#these variables must be plaintext strings
$creds = New-object System.Net.NetworkCredential($Username,$Password)
#your auth might be different than mine
$cc.add($urlobj,"NTLM",$creds)
$client.Credentials = $cc
$Client.Downloadfile($url, C:\Temp\TestPage.html)

Option 1 - Setting Proxy Authentication via Code.
Another Authenticated Proxy Example With Credentials
# 1). Set your http proxy address and port
$proxy = New-Object System.Net.WebProxy("http://p.weshare.net:80",$true)
# 2). Set your http proxy credentials
$proxy.Credentials = New-Object System.Net.NetworkCredential("username", "password")
# 3). Set the global proxy
[System.Net.WebRequest]::DefaultWebProxy = $proxy
# 4). sets a value that indicates whether to bypass the proxy server for local addresses.
[System.Net.WebRequest]::DefaultWebProxy.BypassProxyOnLocal = $true
# 5). Call Invoke-WebRequest without -Proxy Tag ( as it pulls it from what you defined )
$reposnseText = Invoke-WebRequest https://www.oracle.com
Just wrapping it as a Function
Function Set-My-Proxy
{
param($proxy,$username,$password)
$proxy = New-Object System.Net.WebProxy($proxy,$true)
$proxy.Credentials = New-Object System.Net.NetworkCredential($username, $password)
[System.Net.WebRequest]::DefaultWebProxy = $proxy
[System.Net.WebRequest]::DefaultWebProxy.BypassProxyOnLocal = $true
}
Call the Function
Set-My-Proxy 'http://p.weshare.net:80' 'username' 'password'
Option 2 - Setting Proxy Authentication via Another Proxy
Credits & Limitations of solution
Install local proxy, e.g : squid for windows
After installing, open squid.conf file ( right mouse click on squid icon on task bar -> Open Squid Configuration
Put the following code
please provide authenticated proxy ip only ( in our example : 10.1.2.3 - not domain one )
http_access allow all
http_port 3128
coredump_dir /var/spool/squid3
refresh_pattern ^ftp: 1440 20% 10080
refresh_pattern ^gopher: 1440 0% 1440
refresh_pattern -i (/cgi-bin/|\?) 0 0% 0
refresh_pattern (Release|Packages(.gz)*)$ 0 20% 2880
refresh_pattern . 0 20% 4320
cache_peer 10.1.2.3 parent 80 0 no-query default login=my_username:my_password
never_direct allow all
access_log none
cache_log none
Restart Squid Service
You now may call your local proxy, which will forward request to authenticated proxy and response back
Invoke-WebRequest -Uri 'https://stackoverflow.com/' -Proxy 'http://127.0.0.1:3128'

Related

PS script to copy data to external file share location

Scenario:
Site to Site VPN is configured with my network and with a remote Data centre and there is no AD Trust
On a daily basis, I need to copy the data from my server folder to remote file share location
For example:
Platform: Windows 2008
Server folder : D:\Data
Remote file share location: \1.2.3.4\Data
For remote file share location, they have different domain (for example username: xyz\user1)
How can I have a script where the data generated in our server folder (D:\Data) can be replicated to remote file share location using their credentials on a daily basis?
I'm confused with the step where how I can pass the 3rd party credentials to copy the data to their location as AD Trust is not configured.
Thanks in Advance.
You can use something like $cred = Get-Credential to create a variable that will store the credential in a PSCredential object.
Then when you call on it later you can just use $cred instead of signing in.
This will cause the script to prompt for domain credentials each time the script is run, and then use those when moving the files. I have used a simple cmdlet below and separated out the credential variable for readability.
Get-CimInstance Win32_DiskDrive -ComputerName Server01 -Credential $cred

unable to ping any sites in command line/powershell windows 7

Does windows command line requires any proxy setting to ping websites?
I can access all websites in my browser but when I try to ping the same from commandline or powershell I get "Request timed out" error. How to resolve this error?
In IE browser I've set a automatic proxy detection script as the network is company LAN. Tried most of solutions provided in web without any luck.
Due to this I am unable to run the chef commands to install gems and receiving error Unable to download data from https://rubygems.org/ - Errno::ETIMEDOUT:
A connection attempt failed because the connected party did not properly respon
d after a period of time, or established connection failed because connected hos
t has failed to respond. - connect(2) for "api.rubygems.org" port 443 (https://a
pi.rubygems.org/specs.4.8.gz)
Getting a ping reply or HTTP response are two entirely different things. That is, any server can honor either of those just as well as it pleases. In addition, there might be proxies and firewalls on the route that change the results. Even if a server is willing to reply on ping, corporate firewall might block it.
You might have some success with setting Chef's proxy settings via environment variables, as per documentation. As how to find out the proxy settings, ask your network admin. If that doesn't work, retrieve the proxy settings from IE's registry key. In case of link rot, here's the function:
function Get-InternetProxy {
<#
.SYNOPSIS
Determine the internet proxy address
.DESCRIPTION
This function allows you to determine the the internet proxy address used by your computer
.EXAMPLE
Get-InternetProxy
.Notes
Author : Antoine DELRUE
WebSite: http://obilan.be
#>
$proxies = (Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings').proxyServer
if ($proxies) {
if ($proxies -ilike "*=*") {
$proxies -replace "=","://" -split(';') | Select-Object -First 1
} else {
"http://" + $proxies
}
}
}

enable ssl connection filezilla throught powershell v3.0

By using power shell script, I am able to connect my ftp server via normal session. but not able to connect via secure session.
Whenever i try to connect via ssl its shows error "Requires SSL ". Can any one tell me the parameter to used for power shell.
Ftp server : IIS
Assuming you're using System.Net.FtpWebRequest, set the EnableSsl property to true:
$ftp = [System.Net.FtpWebRequest]::Create("ftp://ftp.example.com")
$ftp.EnableSsl = $true

Get windows proxy username/password

I have an access to a preconfigured Windows XP 32-bit workstation.
It's under firewall and to get outside it uses http proxy server.
To get proxy settings I need host, port, username and password.
http: // username : password # server : port
I'm able to find the proxy url and port (from PAC - automatic config file),
but I don't know how to get username/password. Is there a way to read it somehow? At least username? I might get the admin rights.
Do you know any tool that can help?
I only found these MS docs about some methods to get proxy config connection, but I don't know how to determinate what's the provided credentials:
WinHttpGetIEProxyConfigForCurrentUser function
WINHTTP_CURRENT_USER_IE_PROXY_CONFIG structure
WinHttpGetProxyForUrl function
I've also found this lib, but it's rather for parsing PAC:
http://code.google.com/p/pacparser/
In windows you cannot get password.
To get connect throw a proxy you have to use SSPI, check libcurl, you can get a connected socket throw proxy, build it with enable-sspi and openssl.
Iterating on Fernando Sanchez's answer and Robert's comment, you need to authenticate via SSPI. In my case I've connected using NTLM using this link
With curl using ntlm :
curl.exe --proxy <proxy_name>:<proxy_port> --proxy-ntlm -U : https://www.google.com
Also to partially answer your question the -U : means from curl man page :
If you use a Windows SSPI-enabled curl binary and do either Negotiate
or NTLM authentication then you can tell curl to select the user name
and password from your environment by specifying a single colon with
this option: "-U :".
You can get the proxy name and port from the windows registry (regedit). Quote from Robert's comment:
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet
Settings]
It can be present either in a manual way using REG_SZ ProxyServer or using an autoconfiguration script using REG_SZ AutoConfigURL = https://<configuration_url>
If the curl command above fails with Failure when receiving data from the peer maybe you have a curl release without NTLM, SSPI or OpenSSL. Try with the latest curl release

How to fill in proxy information in cntlm config file?

Cntlm is an NTLM / NTLM Session Response / NTLMv2 authenticating HTTP proxy intended to help you break free from the chains of Microsoft proprietary world.
I have my proxy URL in the following format:
http://user:passwords#my_proxy_server.com:80
And I have to provide this information to cntlm. Its config file cntlm.ini has following structure and parameters:
Username
Domain
Password
Proxy
I am not sure, how to break up my original proxy property to fill these four options?
Update your user, domain, and proxy information in cntlm.ini, then test your proxy with this command (run in your Cntlm installation folder):
cntlm -c cntlm.ini -I -M http://google.ro
It will ask for your password, and hopefully print your required authentication information, which must be saved in your cntlm.ini
Sample cntlm.ini:
Username user
Domain domain
# provide actual value if autodetection fails
# Workstation pc-name
Proxy my_proxy_server.com:80
NoProxy 127.0.0.*, 192.168.*
Listen 127.0.0.1:54321
Listen 192.168.1.42:8080
Gateway no
SOCKS5Proxy 5000
# provide socks auth info if you want it
# SOCKS5User socks-user:socks-password
# printed authentication info from the previous step
Auth NTLMv2
PassNTLMv2 98D6986BCFA9886E41698C1686B58A09
Note: on linux the config file is cntlm.conf
The solution takes two steps!
First, complete the user, domain, and proxy fields in cntlm.ini. The username and domain should probably be whatever you use to log in to Windows at your office, eg.
Username employee1730
Domain corporate
Proxy proxy.infosys.corp:8080
Then test cntlm with a command such as
cntlm.exe -c cntlm.ini -I -M http://www.bbc.co.uk
It will ask for your password (again whatever you use to log in to Windows_). Hopefully it will print 'http 200 ok' somewhere, and print your some cryptic tokens authentication information. Now add these to cntlm.ini, eg:
Auth NTLM
PassNT A2A7104B1CE00000000000000007E1E1
PassLM C66000000000000000000000008060C8
Finally, set the http_proxy environment variable in Windows (assuming you didn't change with the Listen field which by default is set to 3128) to the following
http://localhost:3128
Without any configuration, you can simply issue the following command (modifying myusername and mydomain with your own information):
cntlm -u myusername -d mydomain -H
or
cntlm -u myusername#mydomain -H
It will ask you the password of myusername and will give you the following output:
PassLM 1AD35398BE6565DDB5C4EF70C0593492
PassNT 77B9081511704EE852F94227CF48A793
PassNTLMv2 A8FC9092D566461E6BEA971931EF1AEC # Only for user 'myusername', domain 'mydomain'
Then create the file cntlm.ini (or cntlm.conf on Linux using default path) with the following content (replacing your myusername, mydomain and A8FC9092D566461E6BEA971931EF1AEC with your information and the result of the previous command):
Username myusername
Domain mydomain
Proxy my_proxy_server.com:80
NoProxy 127.0.0.*, 192.168.*
Listen 127.0.0.1:5865
Gateway yes
SOCKS5Proxy 5866
Auth NTLMv2
PassNTLMv2 A8FC9092D566461E6BEA971931EF1AEC
Then you will have a local open proxy on local port 5865 and another one understanding SOCKS5 protocol at local port 5866.
Here is a guide on how to use cntlm
What is cntlm?
cntlm is an NTLM/NTLMv2 authenticating HTTP proxy
It takes the address of your proxy and opens a listening socket, forwarding each request to the parent proxy
Why cntlm?
Using cntlm we make it possible to run tools like choro, pip3, apt-get from a command line
pip3 install requests
choco install git
The main advantage of cntlm is password protection.
With cntlm you can use password hashes.
So NO PLAINTEXT PASSWORD in %HTTP_PROXY% and %HTTPS_PROXY% environment variables
Install cntlm
You can get the latest cntlm release from sourceforge
Note! Username and domain
My username is zezulinsky
My domain is local
When I run commands I use zezulinsky#local
Place your username when you run commands
Generate password hash
Run a command
cntlm -u zezulinsky#local -H
Enter your password:
Password:
As a result you are getting hashed password:
PassLM AB7D42F42QQQQ407552C4BCA4AEBFB11
PassNT PE78D847E35FA7FA59710D1231AAAF99
PassNTLMv2 46738B2E607F9093296AA4C319C3A259
Verify your generated hash is valid
Run a command
cntlm -u zezulinsky#local -M http://google.com
Enter your password
Password:
The result output
Config profile 1/4... OK (HTTP code: 301)
----------------------------[ Profile 0 ]------
Auth NTLMv2
PassNTLMv2 46738B2E607F9093296AA4C319C3A259
------------------------------------------------
Note! check that PassNTLMv2 hash is the same
The resulting hash is the same for both commands
PassNTLMv2 46738B2E607F9093296AA4C319C3A259
Change configuration file
Place generated hashes into the cntlm.ini configuration file
C:\Program Files (x86)\Cntlm\cntlm.ini
Here is how your cntlm.ini should look like
Username zezulinsky
Domain local
PassLM AB7D42F42QQQQ407552C4BCA4AEBFB11
PassNT PE78D847E35FA7FA59710D1231AAAF99
PassNTLMv2 46738B2E607F9093296AA4C319C3A259
Proxy PROXYSERVER:8080
NoProxy localhost, 127.0.0.*
Listen 3128
Note! newline at the end of cntlm.ini
It is important to add a newline at the end of the cntlm.ini configuration file
Set your environment variables
HTTPS_PROXY=http://localhost:3128
HTTP_PROXY=http://localhost:3128
Check that your cntlm works
Stop all the processes named cntlm.exe with process explorer
Run the command
cntlm -u zezulinsky#local -H
The output looks like
cygwin warning:
MS-DOS style path detected: C:\Program Files (x86)\Cntlm\cntlm.ini
Preferred POSIX equivalent is: /Cntlm/cntlm.ini
CYGWIN environment variable option "nodosfilewarning" turns off this warning.
Consult the user's guide for more details about POSIX paths:
http://cygwin.com/cygwin-ug-net/using.html#using-pathnames
section: local, Username = 'zezulinsky'
section: local, Domain = 'local'
section: local, PassLM = 'AB7D42F42QQQQ407552C4BCA4AEBFB11'
section: local, PassNT = 'PE78D847E35FA7FA59710D1231AAAF99'
section: local, PassNTLMv2 = '46738B2E607F9093296AA4C319C3A259'
section: local, Proxy = 'PROXYSERVER:8080'
section: local, NoProxy = 'localhost, 10.*, 127.0.0.*
section: local, Listen = '3128'
Default config file opened successfully
cntlm: Proxy listening on 127.0.0.1:3128
Adding no-proxy for: 'localhost'
Adding no-proxy for: '10.*'
Adding no-proxy for: '127.0.0.*'
cntlm: Workstation name used: MYWORKSTATION
cntlm: Using following NTLM hashes: NTLMv2(1) NT(0) LM(0)
cntlm: PID 1234: Cntlm ready, staying in the foreground
Open a new cmd and run a command:
pip3 install requests
You should have requests python package installed
Restart your machine
Congrats, now you have cntlm installed and configured
Just to add , if you are performing a "pip" operation , you might need to add and additional "--proxy=localhost:port_number"
e.g pip install --proxy=localhost:3128 matplotlib
Visit this link to see full details.
Once you generated the file, and changed your password, you can run as below,
cntlm -H
Username will be the same. it will ask for password, give it, then copy the PassNTLMv2, edit the cntlm.ini, then just run the following
cntlm -v
Thank you Sasha Zezulinsky.
In windows:
I used
SET HTTPS_PROXY=http://localhost:3128
When it was set to
SET HTTPS_PROXY=http://127.0.0.1:3128, it never worked.
Below posts are also very helpful.
How to use pip on windows behind an authenticating proxy
For me just using cntlm -H wasn't generating the right hash, but it does with the command below providing the user name.
If you need to generate a new password hash for cntlm, because you have change it or you've been forced to update it, you can just type the below command and update your cntlm.conf configuration file with the output:
$ cntlm -u test -H
Password:
PassLM D2AABAF8828482D5552C4BCA4AEBFB11
PassNT 83AC305A1582F064C469755F04AE5C0A
PassNTLMv2 4B80D9370D353EE006D714E39715A5CB # Only for user 'test', domain ''

Resources